issue_id
int64 2.03k
426k
| title
stringlengths 9
251
| body
stringlengths 1
32.8k
⌀ | status
stringclasses 6
values | after_fix_sha
stringlengths 7
7
| project_name
stringclasses 6
values | repo_url
stringclasses 6
values | repo_name
stringclasses 6
values | language
stringclasses 1
value | issue_url
null | before_fix_sha
null | pull_url
null | commit_datetime
timestamp[us, tz=UTC] | report_datetime
timestamp[us, tz=UTC] | updated_file
stringlengths 2
187
| file_content
stringlengths 0
368k
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
130,722 |
Bug 130722 poincut references in percflow instantiation model aspects can not be resolved
|
Take these two aspects and this litte class: // source1 package test1; import test.Test; public aspect PointcutProvider { public pointcut test(): execution(* Test.*(..)); } // source2 package test; import test1.PointcutProvider; public aspect PointcutConsumer percflow(flow()) { // compiler issues the following line with // can not find pointcut test on test.PointcutConsumer pointcut mytest(): PointcutProvider.test(); // this also does not work with the same error message pointcut mytest(): test1.PointcutProvider.test(); pointcut flow(): mytest(); } // source3 package test; public class Test { public void foo() { } } Changing the consumer aspect to singleton instantiation model works.
|
resolved fixed
|
b166a7e
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-05-16T15:43:08Z | 2006-03-07T11:13:20Z |
weaver/testsrc/org/aspectj/weaver/bcel/NonstaticWeaveTestCase.java
|
/* *******************************************************************
* Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC).
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* PARC initial implementation
* ******************************************************************/
package org.aspectj.weaver.bcel;
import java.io.IOException;
import org.aspectj.weaver.*;
import org.aspectj.weaver.ShadowMunger;
import org.aspectj.weaver.patterns.*;
public class NonstaticWeaveTestCase extends WeaveTestCase {
{
regenerate = false;
}
public NonstaticWeaveTestCase(String name) {
super(name);
}
public void testBefore() throws IOException {
String s = "before(): get(* *.*) -> void Aspect.ajc_before()";
PerClause per = new PerSingleton();
per = per.concretize(world.resolve("Aspect"));
ShadowMunger myMunger = this.makeConcreteAdvice(s, 0, per);
weaveTest(getStandardTargets(), "NonStaticBefore", myMunger);
}
public void testBeforeCflow() throws IOException {
String s = "before(): get(* *.*) -> void Aspect.ajc_before()";
PerClause per = new PatternParser("percflow(execution(void main(..)))").maybeParsePerClause();
per.resolve(new TestScope(new String[0], new String[0], world));
ResolvedType onAspect = world.resolve("Aspect");
CrosscuttingMembers xcut = new CrosscuttingMembers(onAspect);
onAspect.crosscuttingMembers = xcut;
per = per.concretize(onAspect);
ShadowMunger myMunger = this.makeConcreteAdvice(s, 0, per);
xcut.addConcreteShadowMunger(myMunger);
weaveTest(getStandardTargets(), "CflowNonStaticBefore", xcut.getShadowMungers());
}
public void testBeforePerThis() throws IOException {
String s = "before(): call(* println(..)) -> void Aspect.ajc_before()";
PerClause per = new PatternParser("pertarget(call(* println(..)))").maybeParsePerClause();
per.resolve(new TestScope(new String[0], new String[0], world));
ResolvedType onAspect = world.resolve("Aspect");
CrosscuttingMembers xcut = new CrosscuttingMembers(onAspect);
onAspect.crosscuttingMembers = xcut;
per = per.concretize(onAspect);
ShadowMunger myMunger = this.makeConcreteAdvice(s, 0, per);
xcut.addConcreteShadowMunger(myMunger);
// List mungers = new ArrayList();
// mungers.add(myMunger);
// mungers.addAll(onAspect.getExtraConcreteShadowMungers());
weaveTest(getStandardTargets(), "PerThisNonStaticBefore", xcut.getShadowMungers());
}
}
|
130,722 |
Bug 130722 poincut references in percflow instantiation model aspects can not be resolved
|
Take these two aspects and this litte class: // source1 package test1; import test.Test; public aspect PointcutProvider { public pointcut test(): execution(* Test.*(..)); } // source2 package test; import test1.PointcutProvider; public aspect PointcutConsumer percflow(flow()) { // compiler issues the following line with // can not find pointcut test on test.PointcutConsumer pointcut mytest(): PointcutProvider.test(); // this also does not work with the same error message pointcut mytest(): test1.PointcutProvider.test(); pointcut flow(): mytest(); } // source3 package test; public class Test { public void foo() { } } Changing the consumer aspect to singleton instantiation model works.
|
resolved fixed
|
b166a7e
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-05-16T15:43:08Z | 2006-03-07T11:13:20Z |
weaver/testsrc/org/aspectj/weaver/bcel/PointcutResidueTestCase.java
|
/* *******************************************************************
* Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC).
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* PARC initial implementation
* ******************************************************************/
package org.aspectj.weaver.bcel;
import java.io.*;
import java.lang.reflect.Modifier;
import java.util.*;
import org.aspectj.weaver.*;
import org.aspectj.weaver.patterns.*;
import org.aspectj.weaver.patterns.SimpleScope;
public class PointcutResidueTestCase extends WeaveTestCase {
{
regenerate = false;
}
public PointcutResidueTestCase(String name) {
super(name);
}
String[] none = new String[0];
// -----
// ----
public void testArgResidue1() throws IOException {
checkMultiArgWeave(
"StringResidue1",
"call(* *(java.lang.Object, java.lang.Object)) && args(java.lang.String, java.lang.String)");
}
public void testArgResidue2() throws IOException {
checkMultiArgWeave(
"StringResidue2",
"call(* *(java.lang.Object, java.lang.Object)) && args(.., java.lang.String)");
}
public void testArgResidue3() throws IOException {
checkMultiArgWeave(
"StringResidue3",
"call(* *(java.lang.Object, java.lang.Object)) && args(java.lang.String, ..)");
}
// BETAX this is a beta feature.
// public void testArgResidue4() throws IOException {
// checkMultiArgWeave(
// "StringResidue4",
// "call(* *(java.lang.Object, java.lang.Object)) && args(.., java.lang.String, ..)");
// }
public void testMultiArgState() throws IOException {
checkWeave(
"StateResidue",
"MultiArgHelloWorld",
"call(* *(java.lang.Object, java.lang.Object)) && args(s, ..)",
new String[] { "java.lang.String" },
new String[] { "s" });
checkWeave(
"StateResidue",
"MultiArgHelloWorld",
"call(* *(java.lang.Object, java.lang.Object)) && args(s, *)",
new String[] { "java.lang.String" },
new String[] { "s" });
}
public void testAdd() throws IOException {
checkDynamicWeave("AddResidue", "call(public * add(..)) && target(java.util.ArrayList)");
checkDynamicWeave("AddResidue", "call(public * add(..)) && (target(java.util.ArrayList) || target(java.lang.String))");
checkDynamicWeave("AddResidue", "call(public * add(..)) && this(java.io.Serializable) && target(java.util.ArrayList) && !this(java.lang.Integer)");
}
public void testNot() throws IOException {
checkDynamicWeave("AddNotResidue", "call(public * add(..)) && !target(java.util.ArrayList)");
checkDynamicWeave("AddNotResidue", "call(public * add(..)) && !(target(java.util.ArrayList) || target(java.lang.String)) ");
checkDynamicWeave("AddNotResidue", "call(public * add(..)) && target(java.lang.Object) && !target(java.util.ArrayList)");
}
public void testState() throws IOException {
checkWeave(
"AddStateResidue",
"DynamicHelloWorld",
"call(public * add(..)) && target(list)",
new String[] { "java.util.ArrayList" },
new String[] { "list" });
checkWeave(
"AddStateResidue",
"DynamicHelloWorld",
"target(foo) && !target(java.lang.Integer) && call(public * add(..))",
new String[] { "java.util.ArrayList" },
new String[] { "foo" });
checkDynamicWeave(
"AddResidue",
"call(public * add(..)) && (target(java.util.ArrayList) || target(java.lang.String))");
checkDynamicWeave(
"AddResidue",
"call(public * add(..)) && this(java.io.Serializable) && target(java.util.ArrayList) && !this(java.lang.Integer)");
}
public void testNoResidueArgs() throws IOException {
checkDynamicWeave("NoResidue", "call(public * add(..)) && args(java.lang.Object)");
checkDynamicWeave("NoResidue", "call(public * add(..)) && args(*)");
checkDynamicWeave("NoResidue", "call(public * add(..))");
}
// ---- cflow tests
public void testCflowState() throws IOException {
checkWeave(
"CflowStateResidue",
"DynamicHelloWorld",
"cflow(call(public * add(..)) && target(list)) && execution(public void main(..))",
new String[] { "java.util.ArrayList" },
new String[] { "list" });
// checkWeave(
// "CflowStateResidue",
// "DynamicHelloWorld",
// "cflow(call(public * add(..)) && target(list)) && this(obj) && execution(public void doit(..))",
// new String[] { "java.lang.Object", "java.util.ArrayList" },
// new String[] { "obj", "list" });
// checkWeave(
// "AddStateResidue",
// "DynamicHelloWorld",
// "target(foo) && !target(java.lang.Integer) && call(public * add(..))",
// new String[] { "java.util.ArrayList" },
// new String[] { "foo" });
// checkDynamicWeave(
// "AddResidue",
// "call(public * add(..)) && (target(java.util.ArrayList) || target(java.lang.String))");
// checkDynamicWeave(
// "AddResidue",
// "call(public * add(..)) && this(java.io.Serializable) && target(java.util.ArrayList) && !this(java.lang.Integer)");
}
// ----
private void checkDynamicWeave(String label, String pointcutSource) throws IOException {
checkWeave(label, "DynamicHelloWorld", pointcutSource, new String[0], new String[0]);
}
private void checkMultiArgWeave(String label, String pointcutSource) throws IOException {
checkWeave(label, "MultiArgHelloWorld", pointcutSource, new String[0], new String[0]);
}
private void checkWeave(
String label,
String filename,
String pointcutSource,
String[] formalTypes,
String[] formalNames)
throws IOException
{
final Pointcut sp = Pointcut.fromString(pointcutSource);
final Pointcut rp =
sp.resolve(
new SimpleScope(
world,
SimpleScope.makeFormalBindings(UnresolvedType.forNames(formalTypes),
formalNames)
));
ShadowMunger pp =
new BcelAdvice(
AdviceKind.Before,
rp,
MemberImpl.method(
UnresolvedType.forName("Aspect"),
Modifier.STATIC,
"ajc_before_0",
MemberImpl.typesToSignature(
ResolvedType.VOID,
UnresolvedType.forNames(formalTypes),false)),
0, -1, -1, null, null);
ResolvedType inAspect = world.resolve("Aspect");
CrosscuttingMembers xcut = new CrosscuttingMembers(inAspect);
inAspect.crosscuttingMembers = xcut;
ShadowMunger cp = pp.concretize(inAspect, world, null);
xcut.addConcreteShadowMunger(cp);
//System.out.println("extras: " + inAspect.getExtraConcreteShadowMungers());
// List advice = new ArrayList();
// advice.add(cp);
// advice.addAll(inAspect.getExtraConcreteShadowMungers());
weaveTest(new String[] { filename }, label, xcut.getShadowMungers());
checkSerialize(rp);
}
public void weaveTest(String name, String outName, ShadowMunger planner) throws IOException {
List l = new ArrayList(1);
l.add(planner);
weaveTest(name, outName, l);
}
public void checkSerialize(Pointcut p) throws IOException {
ByteArrayOutputStream bo = new ByteArrayOutputStream();
DataOutputStream out = new DataOutputStream(bo);
p.write(out);
out.close();
ByteArrayInputStream bi = new ByteArrayInputStream(bo.toByteArray());
VersionedDataInputStream in = new VersionedDataInputStream(bi);
Pointcut newP = Pointcut.read(in, null);
assertEquals("write/read", p, newP);
}
}
|
130,722 |
Bug 130722 poincut references in percflow instantiation model aspects can not be resolved
|
Take these two aspects and this litte class: // source1 package test1; import test.Test; public aspect PointcutProvider { public pointcut test(): execution(* Test.*(..)); } // source2 package test; import test1.PointcutProvider; public aspect PointcutConsumer percflow(flow()) { // compiler issues the following line with // can not find pointcut test on test.PointcutConsumer pointcut mytest(): PointcutProvider.test(); // this also does not work with the same error message pointcut mytest(): test1.PointcutProvider.test(); pointcut flow(): mytest(); } // source3 package test; public class Test { public void foo() { } } Changing the consumer aspect to singleton instantiation model works.
|
resolved fixed
|
b166a7e
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-05-16T15:43:08Z | 2006-03-07T11:13:20Z |
weaver/testsrc/org/aspectj/weaver/bcel/WeaveOrderTestCase.java
|
/* *******************************************************************
* Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC).
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* PARC initial implementation
* ******************************************************************/
package org.aspectj.weaver.bcel;
import org.aspectj.weaver.patterns.*;
import org.aspectj.weaver.*;
/**.
*/
public class WeaveOrderTestCase extends WeaveTestCase {
{
regenerate = false;
}
public WeaveOrderTestCase(String name) {
super(name);
}
public void testLexicalOrder() {
Advice a1 =
makeConcreteAdvice(AdviceKind.Before, UnresolvedType.OBJECT, UnresolvedType.OBJECT, 1);
Advice a2 =
makeConcreteAdvice(AdviceKind.Before, UnresolvedType.OBJECT, UnresolvedType.THROWABLE, 2);
assertEquals(-1, a2.compareTo(a1));
assertEquals(+1, a1.compareTo(a2));
}
public void testLexicalOrderWithAfter() {
Advice a1 =
makeConcreteAdvice(AdviceKind.Before, UnresolvedType.OBJECT, UnresolvedType.OBJECT, 1);
Advice a2 =
makeConcreteAdvice(AdviceKind.After, UnresolvedType.OBJECT, UnresolvedType.THROWABLE, 2);
assertEquals(+1, a2.compareTo(a1));
assertEquals(-1, a1.compareTo(a2));
a1 =
makeConcreteAdvice(AdviceKind.After, UnresolvedType.OBJECT, UnresolvedType.OBJECT, 1);
a2 =
makeConcreteAdvice(AdviceKind.After, UnresolvedType.OBJECT, UnresolvedType.THROWABLE, 2);
assertEquals(+1, a2.compareTo(a1));
assertEquals(-1, a1.compareTo(a2));
}
public void testSubtypes() {
Advice a1 =
makeConcreteAdvice(AdviceKind.Before, UnresolvedType.OBJECT, UnresolvedType.OBJECT, 1);
Advice a2 =
makeConcreteAdvice(AdviceKind.Before, UnresolvedType.THROWABLE, UnresolvedType.OBJECT, 1);
Advice a3 =
makeConcreteAdvice(AdviceKind.Before, UnresolvedType.forName("java.lang.String"), UnresolvedType.OBJECT, 1);
assertEquals(+1, a2.compareTo(a1));
assertEquals(-1, a1.compareTo(a2));
assertEquals(+1, a3.compareTo(a1));
assertEquals(-1, a1.compareTo(a3));
assertEquals(0, a3.compareTo(a2));
assertEquals(0, a2.compareTo(a3));
}
public void testDominates() {
Declare dom =
new PatternParser("declare precedence: java.lang.String, java.lang.Throwable").parseDeclare();
//??? concretize dom
ResolvedType aType = world.resolve("Aspect");
CrosscuttingMembers xcut = new CrosscuttingMembers(aType);
aType.crosscuttingMembers = xcut;
xcut.addDeclare(dom);
world.getCrosscuttingMembersSet().addFixedCrosscuttingMembers(aType);
Advice a1 =
makeConcreteAdvice(AdviceKind.Before, UnresolvedType.OBJECT, UnresolvedType.OBJECT, 1);
Advice a2 =
makeConcreteAdvice(AdviceKind.Before, UnresolvedType.OBJECT, UnresolvedType.THROWABLE, 2);
Advice a3 =
makeConcreteAdvice(AdviceKind.Before, UnresolvedType.OBJECT, UnresolvedType.forName("java.lang.String"), 2);
assertEquals(-1, a2.compareTo(a1));
assertEquals(+1, a1.compareTo(a2));
assertEquals(-1, a3.compareTo(a1));
assertEquals(+1, a1.compareTo(a3));
assertEquals(+1, a3.compareTo(a2));
assertEquals(-1, a2.compareTo(a3));
}
public void testDominatesHarder() {
Declare dom =
new PatternParser("declare precedence: *, java.lang.String, java.lang.Throwable").parseDeclare();
//??? concretize dom
ResolvedType aType = world.resolve("Aspect");
CrosscuttingMembers xcut = new CrosscuttingMembers(aType);
aType.crosscuttingMembers = xcut;
xcut.addDeclare(dom);
world.getCrosscuttingMembersSet().addFixedCrosscuttingMembers(aType);
Advice a1 =
makeConcreteAdvice(AdviceKind.Before, UnresolvedType.OBJECT, UnresolvedType.OBJECT, 2);
Advice a2 =
makeConcreteAdvice(AdviceKind.Before, UnresolvedType.OBJECT, UnresolvedType.THROWABLE, 1);
Advice a3 =
makeConcreteAdvice(AdviceKind.Before, UnresolvedType.OBJECT, UnresolvedType.forName("java.lang.String"), 1);
assertEquals(-1, a2.compareTo(a1));
assertEquals(+1, a1.compareTo(a2));
assertEquals(-1, a3.compareTo(a1));
assertEquals(+1, a1.compareTo(a3));
assertEquals(+1, a3.compareTo(a2));
assertEquals(-1, a2.compareTo(a3));
}
private Advice makeConcreteAdvice(AdviceKind kind, UnresolvedType declaringAspect,
UnresolvedType concreteAspect, int lexicalPosition)
{
Advice a1 = new BcelAdvice(kind, makeResolvedPointcut("this(*)"),
MemberImpl.method(declaringAspect, 0, "foo", "()V"),
0, lexicalPosition, lexicalPosition, null, null);
a1 = (Advice)a1.concretize(concreteAspect.resolve(world), world, null);
return a1;
}
}
|
141,956 |
Bug 141956 Null Pointer Exception when trying to skip Parent Mungers.
|
I don't know much about the internal workings of aspectJ but this bug keeps popping up so I went through the trouble of checking of trying to debug it so that I could hopefully provide enough information to get it fixed. This happens while using eclipse AJDT. It never happens if I fully do a clean before rebuild. It only seems to happen when doing incrmental builds (using the project->build automatically setting). The error happens in the iterator that recursively builds a list of methods to return for matching. The error is triggered here: // we need to know if it is an interface from Parent kind munger // as those are used for @AJ ITD and we precisely want to skip those boolean shouldSkip = false; for (int j = 0; j < rtx.interTypeMungers.size(); j++) { ConcreteTypeMunger munger = (ConcreteTypeMunger) rtx.interTypeMungers.get(j); if (munger.getMunger().getKind() == ResolvedTypeMunger.Parent) { shouldSkip = true; break; } } munger.getMunger() returns null because the munger instance is a BcelPerClauseAspectAdder. My naive fix would be to check munger.getMunger() == null or check munger.getKind(). I'm assuming that BcelPerClausAspectAdder is one that should be skipped since it is related to @AJ ??? Again, I don't know very much about the internal architecture of the weaver magic so I hope this is enough information. I would appreciate it if someone who knows more of the internals could speculate as to why this bug would never pop up on a clean build but only on incremental builds? Also it's not on all incremental builds and I haven't been able to isolate what kind of changes or compiles it triggers this, although it seems that once I got the exception once, I keep getting it on every build until I do a clean. java.lang.NullPointerException at org.aspectj.weaver.ResolvedType.addAndRecurse(ResolvedType.java:288) at org.aspectj.weaver.ResolvedType.getMethodsWithoutIterator(ResolvedType.java:257) at org.aspectj.weaver.ResolvedType.lookupResolvedMember(ResolvedType.java:378) at org.aspectj.weaver.JoinPointSignatureIterator.findSignaturesFromSupertypes(JoinPointSignatureIterator.java:178) at org.aspectj.weaver.JoinPointSignatureIterator.hasNext(JoinPointSignatureIterator.java:69) at org.aspectj.weaver.patterns.SignaturePattern.matches(SignaturePattern.java:287) at org.aspectj.weaver.patterns.KindedPointcut.matchInternal(KindedPointcut.java:103) at org.aspectj.weaver.patterns.Pointcut.match(Pointcut.java:144) at org.aspectj.weaver.patterns.AndPointcut.matchInternal(AndPointcut.java:51) at org.aspectj.weaver.patterns.Pointcut.match(Pointcut.java:144) at org.aspectj.weaver.ShadowMunger.match(ShadowMunger.java:64) at org.aspectj.weaver.Advice.match(Advice.java:109) at org.aspectj.weaver.bcel.BcelAdvice.match(BcelAdvice.java:104) at org.aspectj.weaver.bcel.BcelClassWeaver.match(BcelClassWeaver.java:2210) at org.aspectj.weaver.bcel.BcelClassWeaver.match(BcelClassWeaver.java:1752) at org.aspectj.weaver.bcel.BcelClassWeaver.weave(BcelClassWeaver.java:479) at org.aspectj.weaver.bcel.BcelClassWeaver.weave(BcelClassWeaver.java:109) at org.aspectj.weaver.bcel.BcelWeaver.weave(BcelWeaver.java:1574) at org.aspectj.weaver.bcel.BcelWeaver.weaveWithoutDump(BcelWeaver.java:1525) at org.aspectj.weaver.bcel.BcelWeaver.weaveAndNotify(BcelWeaver.java:1305) at org.aspectj.weaver.bcel.BcelWeaver.weave(BcelWeaver.java:1127) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.weave(AjCompilerAdapter.java:321) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.afterCompiling(AjCompilerAdapter.java:192) at org.aspectj.ajdt.internal.compiler.CompilerAdapter.ajc$afterReturning$org_aspectj_ajdt_internal_compiler_CompilerAdapter$2$f9cc9ca0(CompilerAdapter.aj:70) at org.aspectj.org.eclipse.jdt.internal.compiler.Compiler.compile(Compiler.java:367) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.performCompilation(AjBuildManager.java:862) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.doBuild(AjBuildManager.java:269) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.incrementalBuild(AjBuildManager.java:168) at org.aspectj.ajde.internal.CompilerAdapter.compile(CompilerAdapter.java:117) at org.aspectj.ajde.internal.AspectJBuildManager$CompilerThread.run(AspectJBuildManager.java:191)
|
resolved fixed
|
5f6a6b1
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-05-17T11:38:39Z | 2006-05-16T09:00:00Z |
org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/compiler/lookup/EclipseFactory.java
|
/* *******************************************************************
* Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC).
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* PARC initial implementation
* Mik Kersten 2004-07-26 extended to allow overloading of
* hierarchy builder
* ******************************************************************/
package org.aspectj.ajdt.internal.compiler.lookup;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.aspectj.ajdt.internal.compiler.ast.AspectDeclaration;
import org.aspectj.ajdt.internal.compiler.ast.AstUtil;
import org.aspectj.ajdt.internal.core.builder.AjBuildManager;
import org.aspectj.bridge.ISourceLocation;
import org.aspectj.bridge.IMessage.Kind;
import org.aspectj.org.eclipse.jdt.core.compiler.CharOperation;
import org.aspectj.org.eclipse.jdt.internal.compiler.ast.ASTNode;
import org.aspectj.org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration;
import org.aspectj.org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration;
import org.aspectj.org.eclipse.jdt.internal.compiler.ast.EmptyStatement;
import org.aspectj.org.eclipse.jdt.internal.compiler.ast.TypeDeclaration;
import org.aspectj.org.eclipse.jdt.internal.compiler.ast.Wildcard;
import org.aspectj.org.eclipse.jdt.internal.compiler.impl.Constant;
import org.aspectj.org.eclipse.jdt.internal.compiler.impl.ReferenceContext;
import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.ArrayBinding;
import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.BaseTypes;
import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.Binding;
import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.FieldBinding;
import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.LocalTypeBinding;
import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.LookupEnvironment;
import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.MethodBinding;
import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.ParameterizedTypeBinding;
import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.RawTypeBinding;
import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.ReferenceBinding;
import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.Scope;
import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.SourceTypeBinding;
import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.TypeBinding;
import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.TypeVariableBinding;
import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.WildcardBinding;
import org.aspectj.weaver.BoundedReferenceType;
import org.aspectj.weaver.ConcreteTypeMunger;
import org.aspectj.weaver.IHasPosition;
import org.aspectj.weaver.Member;
import org.aspectj.weaver.NewFieldTypeMunger;
import org.aspectj.weaver.NewMethodTypeMunger;
import org.aspectj.weaver.ReferenceType;
import org.aspectj.weaver.ResolvedMember;
import org.aspectj.weaver.ResolvedMemberImpl;
import org.aspectj.weaver.ResolvedType;
import org.aspectj.weaver.Shadow;
import org.aspectj.weaver.TypeFactory;
import org.aspectj.weaver.TypeVariable;
import org.aspectj.weaver.TypeVariableDeclaringElement;
import org.aspectj.weaver.TypeVariableReference;
import org.aspectj.weaver.UnresolvedType;
import org.aspectj.weaver.UnresolvedTypeVariableReferenceType;
import org.aspectj.weaver.World;
import org.aspectj.weaver.UnresolvedType.TypeKind;
/**
* @author Jim Hugunin
*/
public class EclipseFactory {
public static boolean DEBUG = false;
private AjBuildManager buildManager;
private LookupEnvironment lookupEnvironment;
private boolean xSerializableAspects;
private World world;
public Collection finishedTypeMungers = null;
// We can get clashes if we don't treat raw types differently - we end up looking
// up a raw and getting the generic type (pr115788)
private Map/*UnresolvedType, TypeBinding*/ typexToBinding = new HashMap();
private Map/*UnresolvedType, TypeBinding*/ rawTypeXToBinding = new HashMap();
//XXX currently unused
// private Map/*TypeBinding, ResolvedType*/ bindingToResolvedTypeX = new HashMap();
public static EclipseFactory fromLookupEnvironment(LookupEnvironment env) {
AjLookupEnvironment aenv = (AjLookupEnvironment)env;
return aenv.factory;
}
public static EclipseFactory fromScopeLookupEnvironment(Scope scope) {
return fromLookupEnvironment(AstUtil.getCompilationUnitScope(scope).environment);
}
public EclipseFactory(LookupEnvironment lookupEnvironment,AjBuildManager buildManager) {
this.lookupEnvironment = lookupEnvironment;
this.buildManager = buildManager;
this.world = buildManager.getWorld();
this.xSerializableAspects = buildManager.buildConfig.isXserializableAspects();
}
public EclipseFactory(LookupEnvironment lookupEnvironment, World world, boolean xSer) {
this.lookupEnvironment = lookupEnvironment;
this.world = world;
this.xSerializableAspects = xSer;
this.buildManager = null;
}
public World getWorld() {
return world;
}
public void showMessage(
Kind kind,
String message,
ISourceLocation loc1,
ISourceLocation loc2)
{
getWorld().showMessage(kind, message, loc1, loc2);
}
public ResolvedType fromEclipse(ReferenceBinding binding) {
if (binding == null) return ResolvedType.MISSING;
//??? this seems terribly inefficient
//System.err.println("resolving: " + binding.getClass() + ", name = " + getName(binding));
ResolvedType ret = getWorld().resolve(fromBinding(binding));
//System.err.println(" got: " + ret);
return ret;
}
public ResolvedType fromTypeBindingToRTX(TypeBinding tb) {
if (tb == null) return ResolvedType.MISSING;
ResolvedType ret = getWorld().resolve(fromBinding(tb));
return ret;
}
public ResolvedType[] fromEclipse(ReferenceBinding[] bindings) {
if (bindings == null) {
return ResolvedType.NONE;
}
int len = bindings.length;
ResolvedType[] ret = new ResolvedType[len];
for (int i=0; i < len; i++) {
ret[i] = fromEclipse(bindings[i]);
}
return ret;
}
public static String getName(TypeBinding binding) {
if (binding instanceof TypeVariableBinding) {
// The first bound may be null - so default to object?
TypeVariableBinding tvb = (TypeVariableBinding)binding;
if (tvb.firstBound!=null) {
return getName(tvb.firstBound);
} else {
return getName(tvb.superclass);
}
}
if (binding instanceof ReferenceBinding) {
return new String(
CharOperation.concatWith(((ReferenceBinding)binding).compoundName, '.'));
}
String packageName = new String(binding.qualifiedPackageName());
String className = new String(binding.qualifiedSourceName()).replace('.', '$');
if (packageName.length() > 0) {
className = packageName + "." + className;
}
//XXX doesn't handle arrays correctly (or primitives?)
return new String(className);
}
/**
* Some generics notes:
*
* Andy 6-May-05
* We were having trouble with parameterized types in a couple of places - due to TypeVariableBindings. When we
* see a TypeVariableBinding now we default to either the firstBound if it is specified or java.lang.Object. Not
* sure when/if this gets us unstuck? It does mean we forget that it is a type variable when going back
* the other way from the UnresolvedType and that would seem a bad thing - but I've yet to see the reason we need to
* remember the type variable.
* Adrian 10-July-05
* When we forget it's a type variable we come unstuck when getting the declared members of a parameterized
* type - since we don't know it's a type variable we can't replace it with the type parameter.
*/
//??? going back and forth between strings and bindings is a waste of cycles
public UnresolvedType fromBinding(TypeBinding binding) {
if (binding instanceof HelperInterfaceBinding) {
return ((HelperInterfaceBinding) binding).getTypeX();
}
if (binding == null || binding.qualifiedSourceName() == null) {
return ResolvedType.MISSING;
}
// first piece of generics support!
if (binding instanceof TypeVariableBinding) {
TypeVariableBinding tb = (TypeVariableBinding) binding;
UnresolvedTypeVariableReferenceType utvrt = (UnresolvedTypeVariableReferenceType) fromTypeVariableBinding(tb);
return utvrt;
}
// handle arrays since the component type may need special treatment too...
if (binding instanceof ArrayBinding) {
ArrayBinding aBinding = (ArrayBinding) binding;
UnresolvedType componentType = fromBinding(aBinding.leafComponentType);
return UnresolvedType.makeArray(componentType, aBinding.dimensions);
}
if (binding instanceof WildcardBinding) {
WildcardBinding eWB = (WildcardBinding) binding;
UnresolvedType theType = TypeFactory.createTypeFromSignature(CharOperation.charToString(eWB.genericTypeSignature()));
// Repair the bound
// e.g. If the bound for the wildcard is a typevariable, e.g. '? extends E' then
// the type variable in the unresolvedtype will be correct only in name. In that
// case let's set it correctly based on the one in the eclipse WildcardBinding
UnresolvedType theBound = null;
if (eWB.bound instanceof TypeVariableBinding) {
theBound = fromTypeVariableBinding((TypeVariableBinding)eWB.bound);
} else {
theBound = fromBinding(eWB.bound);
}
if (theType.isGenericWildcard() && theType.isSuper()) theType.setLowerBound(theBound);
if (theType.isGenericWildcard() && theType.isExtends()) theType.setUpperBound(theBound);
return theType;
}
if (binding instanceof ParameterizedTypeBinding) {
if (binding instanceof RawTypeBinding) {
// special case where no parameters are specified!
return UnresolvedType.forRawTypeName(getName(binding));
}
ParameterizedTypeBinding ptb = (ParameterizedTypeBinding) binding;
UnresolvedType[] arguments = null;
if (ptb.arguments!=null) { // null can mean this is an inner type of a Parameterized Type with no bounds of its own (pr100227)
arguments = new UnresolvedType[ptb.arguments.length];
for (int i = 0; i < arguments.length; i++) {
arguments[i] = fromBinding(ptb.arguments[i]);
}
}
String baseTypeSignature = null;
ResolvedType baseType = getWorld().resolve(UnresolvedType.forName(getName(binding)),true);
if (!baseType.isMissing()) {
// can legitimately be missing if a bound refers to a type we haven't added to the world yet...
if (!baseType.isGenericType() && arguments!=null) baseType = baseType.getGenericType();
baseTypeSignature = baseType.getErasureSignature();
} else {
baseTypeSignature = UnresolvedType.forName(getName(binding)).getSignature();
}
// Create an unresolved parameterized type. We can't create a resolved one as the
// act of resolution here may cause recursion problems since the parameters may
// be type variables that we haven't fixed up yet.
if (arguments==null) arguments=new UnresolvedType[0];
String parameterizedSig = ResolvedType.PARAMETERIZED_TYPE_IDENTIFIER+CharOperation.charToString(binding.genericTypeSignature()).substring(1);
return TypeFactory.createUnresolvedParameterizedType(parameterizedSig,baseTypeSignature,arguments);
}
// Convert the source type binding for a generic type into a generic UnresolvedType
// notice we can easily determine the type variables from the eclipse object
// and we can recover the generic signature from it too - so we pass those
// to the forGenericType() method.
if (binding.isGenericType() &&
!binding.isParameterizedType() &&
!binding.isRawType()) {
TypeVariableBinding[] tvbs = binding.typeVariables();
TypeVariable[] tVars = new TypeVariable[tvbs.length];
for (int i = 0; i < tvbs.length; i++) {
TypeVariableBinding eclipseV = tvbs[i];
tVars[i] = ((TypeVariableReference)fromTypeVariableBinding(eclipseV)).getTypeVariable();
}
//TODO asc generics - temporary guard....
if (!(binding instanceof SourceTypeBinding))
throw new RuntimeException("Cant get the generic sig for "+binding.debugName());
return UnresolvedType.forGenericType(getName(binding),tVars,
CharOperation.charToString(((SourceTypeBinding)binding).genericSignature()));
}
// LocalTypeBinding have a name $Local$, we can get the real name by using the signature....
if (binding instanceof LocalTypeBinding) {
LocalTypeBinding ltb = (LocalTypeBinding) binding;
if (ltb.constantPoolName() != null && ltb.constantPoolName().length > 0) {
return UnresolvedType.forSignature(new String(binding.signature()));
} else {
// we're reporting a problem and don't have a resolved name for an
// anonymous local type yet, report the issue on the enclosing type
return UnresolvedType.forSignature(new String(ltb.enclosingType.signature()));
}
}
return UnresolvedType.forName(getName(binding));
}
/**
* Some type variables refer to themselves recursively, this enables us to avoid
* recursion problems.
*/
private static Map typeVariableBindingsInProgress = new HashMap();
/**
* Convert from the eclipse form of type variable (TypeVariableBinding) to the AspectJ
* form (TypeVariable).
*/
private UnresolvedType fromTypeVariableBinding(TypeVariableBinding aTypeVariableBinding) {
// first, check for recursive call to this method for the same tvBinding
if (typeVariableBindingsInProgress.containsKey(aTypeVariableBinding)) {
return (UnresolvedType) typeVariableBindingsInProgress.get(aTypeVariableBinding);
}
// Check if its a type variable binding that we need to recover to an alias...
if (typeVariablesForAliasRecovery!=null) {
String aliasname = (String)typeVariablesForAliasRecovery.get(aTypeVariableBinding);
if (aliasname!=null) {
UnresolvedTypeVariableReferenceType ret = new UnresolvedTypeVariableReferenceType();
ret.setTypeVariable(new TypeVariable(aliasname));
return ret;
}
}
if (typeVariablesForThisMember.containsKey(new String(aTypeVariableBinding.sourceName))) {
return (UnresolvedType)typeVariablesForThisMember.get(new String(aTypeVariableBinding.sourceName));
}
// Create the UnresolvedTypeVariableReferenceType for the type variable
String name = CharOperation.charToString(aTypeVariableBinding.sourceName());
UnresolvedTypeVariableReferenceType ret = new UnresolvedTypeVariableReferenceType();
typeVariableBindingsInProgress.put(aTypeVariableBinding,ret);
TypeVariable tv = new TypeVariable(name);
ret.setTypeVariable(tv);
// Dont set any bounds here, you'll get in a recursive mess
// TODO -- what about lower bounds??
UnresolvedType superclassType = fromBinding(aTypeVariableBinding.superclass());
UnresolvedType[] superinterfaces = new UnresolvedType[aTypeVariableBinding.superInterfaces.length];
for (int i = 0; i < superinterfaces.length; i++) {
superinterfaces[i] = fromBinding(aTypeVariableBinding.superInterfaces[i]);
}
tv.setUpperBound(superclassType);
tv.setAdditionalInterfaceBounds(superinterfaces);
tv.setRank(aTypeVariableBinding.rank);
if (aTypeVariableBinding.declaringElement instanceof MethodBinding) {
tv.setDeclaringElementKind(TypeVariable.METHOD);
// tv.setDeclaringElement(fromBinding((MethodBinding)aTypeVariableBinding.declaringElement);
} else {
tv.setDeclaringElementKind(TypeVariable.TYPE);
// // tv.setDeclaringElement(fromBinding(aTypeVariableBinding.declaringElement));
}
if (aTypeVariableBinding.declaringElement instanceof MethodBinding)
typeVariablesForThisMember.put(new String(aTypeVariableBinding.sourceName),ret);
typeVariableBindingsInProgress.remove(aTypeVariableBinding);
return ret;
}
public UnresolvedType[] fromBindings(TypeBinding[] bindings) {
if (bindings == null) return UnresolvedType.NONE;
int len = bindings.length;
UnresolvedType[] ret = new UnresolvedType[len];
for (int i=0; i<len; i++) {
ret[i] = fromBinding(bindings[i]);
}
return ret;
}
public static ASTNode astForLocation(IHasPosition location) {
return new EmptyStatement(location.getStart(), location.getEnd());
}
public Collection getDeclareParents() {
return getWorld().getDeclareParents();
}
public Collection getDeclareAnnotationOnTypes() {
return getWorld().getDeclareAnnotationOnTypes();
}
public Collection getDeclareAnnotationOnFields() {
return getWorld().getDeclareAnnotationOnFields();
}
public Collection getDeclareAnnotationOnMethods() {
return getWorld().getDeclareAnnotationOnMethods();
}
public boolean areTypeMungersFinished() {
return finishedTypeMungers != null;
}
public void finishTypeMungers() {
// make sure that type mungers are
Collection ret = new ArrayList();
Collection baseTypeMungers = getWorld().getCrosscuttingMembersSet().getTypeMungers();
// XXX by Andy: why do we mix up the mungers here? it means later we know about two sets
// and the late ones are a subset of the complete set? (see pr114436)
baseTypeMungers.addAll(getWorld().getCrosscuttingMembersSet().getLateTypeMungers());
for (Iterator i = baseTypeMungers.iterator(); i.hasNext(); ) {
ConcreteTypeMunger munger = (ConcreteTypeMunger) i.next();
EclipseTypeMunger etm = makeEclipseTypeMunger(munger);
if (etm != null) ret.add(etm);
}
finishedTypeMungers = ret;
}
public EclipseTypeMunger makeEclipseTypeMunger(ConcreteTypeMunger concrete) {
//System.err.println("make munger: " + concrete);
//!!! can't do this if we want incremental to work right
//if (concrete instanceof EclipseTypeMunger) return (EclipseTypeMunger)concrete;
//System.err.println(" was not eclipse");
if (concrete.getMunger() != null && EclipseTypeMunger.supportsKind(concrete.getMunger().getKind())) {
AbstractMethodDeclaration method = null;
if (concrete instanceof EclipseTypeMunger) {
method = ((EclipseTypeMunger)concrete).getSourceMethod();
}
EclipseTypeMunger ret =
new EclipseTypeMunger(this, concrete.getMunger(), concrete.getAspectType(), method);
if (ret.getSourceLocation() == null) {
ret.setSourceLocation(concrete.getSourceLocation());
}
return ret;
} else {
return null;
}
}
public Collection getTypeMungers() {
//??? assert finishedTypeMungers != null
return finishedTypeMungers;
}
public ResolvedMember makeResolvedMember(MethodBinding binding) {
return makeResolvedMember(binding, binding.declaringClass);
}
public ResolvedMember makeResolvedMember(MethodBinding binding, Shadow.Kind shadowKind) {
Member.Kind memberKind = binding.isConstructor() ? Member.CONSTRUCTOR : Member.METHOD;
if (shadowKind == Shadow.AdviceExecution) memberKind = Member.ADVICE;
return makeResolvedMember(binding,binding.declaringClass,memberKind);
}
/**
* Conversion from a methodbinding (eclipse) to a resolvedmember (aspectj) is now done
* in the scope of some type variables. Before converting the parts of a methodbinding
* (params, return type) we store the type variables in this structure, then should any
* component of the method binding refer to them, we grab them from the map.
*/
private Map typeVariablesForThisMember = new HashMap();
/**
* This is a map from typevariablebindings (eclipsey things) to the names the user
* originally specified in their ITD. For example if the target is 'interface I<N extends Number> {}'
* and the ITD was 'public void I<X>.m(List<X> lxs) {}' then this map would contain a pointer
* from the eclipse type 'N extends Number' to the letter 'X'.
*/
private Map typeVariablesForAliasRecovery;
/**
* Construct a resolvedmember from a methodbinding. The supplied map tells us about any
* typevariablebindings that replaced typevariables whilst the compiler was resolving types -
* this only happens if it is a generic itd that shares type variables with its target type.
*/
public ResolvedMember makeResolvedMemberForITD(MethodBinding binding,TypeBinding declaringType,
Map /*TypeVariableBinding > original alias name*/ recoveryAliases) {
ResolvedMember result = null;
try {
typeVariablesForAliasRecovery = recoveryAliases;
result = makeResolvedMember(binding,declaringType);
} finally {
typeVariablesForAliasRecovery = null;
}
return result;
}
public ResolvedMember makeResolvedMember(MethodBinding binding, TypeBinding declaringType) {
return makeResolvedMember(binding,declaringType,
binding.isConstructor() ? Member.CONSTRUCTOR : Member.METHOD);
}
public ResolvedMember makeResolvedMember(MethodBinding binding, TypeBinding declaringType, Member.Kind memberKind) {
//System.err.println("member for: " + binding + ", " + new String(binding.declaringClass.sourceName));
// Convert the type variables and store them
UnresolvedType[] ajTypeRefs = null;
typeVariablesForThisMember.clear();
// This is the set of type variables available whilst building the resolved member...
if (binding.typeVariables!=null) {
ajTypeRefs = new UnresolvedType[binding.typeVariables.length];
for (int i = 0; i < binding.typeVariables.length; i++) {
ajTypeRefs[i] = fromBinding(binding.typeVariables[i]);
typeVariablesForThisMember.put(new String(binding.typeVariables[i].sourceName),/*new Integer(binding.typeVariables[i].rank),*/ajTypeRefs[i]);
}
}
// AMC these next two lines shouldn't be needed once we sort out generic types properly in the world map
ResolvedType realDeclaringType = world.resolve(fromBinding(declaringType));
if (realDeclaringType.isRawType()) realDeclaringType = realDeclaringType.getGenericType();
ResolvedMemberImpl ret = new ResolvedMemberImpl(
memberKind,
realDeclaringType,
binding.modifiers,
fromBinding(binding.returnType),
new String(binding.selector),
fromBindings(binding.parameters),
fromBindings(binding.thrownExceptions)
);
if (binding.isVarargs()) {
ret.setVarargsMethod();
}
if (ajTypeRefs!=null) {
TypeVariable[] tVars = new TypeVariable[ajTypeRefs.length];
for (int i=0;i<ajTypeRefs.length;i++) {
tVars[i]=((TypeVariableReference)ajTypeRefs[i]).getTypeVariable();
}
ret.setTypeVariables(tVars);
}
typeVariablesForThisMember.clear();
ret.resolve(world);
return ret;
}
public ResolvedMember makeResolvedMember(FieldBinding binding) {
return makeResolvedMember(binding, binding.declaringClass);
}
public ResolvedMember makeResolvedMember(FieldBinding binding, TypeBinding receiverType) {
// AMC these next two lines shouldn't be needed once we sort out generic types properly in the world map
ResolvedType realDeclaringType = world.resolve(fromBinding(receiverType));
if (realDeclaringType.isRawType()) realDeclaringType = realDeclaringType.getGenericType();
return new ResolvedMemberImpl(
Member.FIELD,
realDeclaringType,
binding.modifiers,
world.resolve(fromBinding(binding.type)),
new String(binding.name),
UnresolvedType.NONE);
}
public TypeBinding makeTypeBinding(UnresolvedType typeX) {
TypeBinding ret = null;
// looking up type variables can get us into trouble
if (!typeX.isTypeVariableReference()) {
if (typeX.isRawType()) {
ret = (TypeBinding)rawTypeXToBinding.get(typeX);
} else {
ret = (TypeBinding)typexToBinding.get(typeX);
}
}
if (ret == null) {
ret = makeTypeBinding1(typeX);
if (!(typeX instanceof BoundedReferenceType) &&
!(typeX instanceof UnresolvedTypeVariableReferenceType)
) {
if (typeX.isRawType()) {
rawTypeXToBinding.put(typeX,ret);
} else {
typexToBinding.put(typeX, ret);
}
}
}
if (ret == null) {
System.out.println("can't find: " + typeX);
}
return ret;
}
// When converting a parameterized type from our world to the eclipse world, these get set so that
// resolution of the type parameters may known in what context it is occurring (pr114744)
private ReferenceBinding baseTypeForParameterizedType;
private int indexOfTypeParameterBeingConverted;
private TypeBinding makeTypeBinding1(UnresolvedType typeX) {
if (typeX.isPrimitiveType()) {
if (typeX == ResolvedType.BOOLEAN) return BaseTypes.BooleanBinding;
if (typeX == ResolvedType.BYTE) return BaseTypes.ByteBinding;
if (typeX == ResolvedType.CHAR) return BaseTypes.CharBinding;
if (typeX == ResolvedType.DOUBLE) return BaseTypes.DoubleBinding;
if (typeX == ResolvedType.FLOAT) return BaseTypes.FloatBinding;
if (typeX == ResolvedType.INT) return BaseTypes.IntBinding;
if (typeX == ResolvedType.LONG) return BaseTypes.LongBinding;
if (typeX == ResolvedType.SHORT) return BaseTypes.ShortBinding;
if (typeX == ResolvedType.VOID) return BaseTypes.VoidBinding;
throw new RuntimeException("weird primitive type " + typeX);
} else if (typeX.isArray()) {
int dim = 0;
while (typeX.isArray()) {
dim++;
typeX = typeX.getComponentType();
}
return lookupEnvironment.createArrayType(makeTypeBinding(typeX), dim);
} else if (typeX.isParameterizedType()) {
// Converting back to a binding from a UnresolvedType
UnresolvedType[] typeParameters = typeX.getTypeParameters();
ReferenceBinding baseTypeBinding = lookupBinding(typeX.getBaseName());
TypeBinding[] argumentBindings = new TypeBinding[typeParameters.length];
baseTypeForParameterizedType = baseTypeBinding;
for (int i = 0; i < argumentBindings.length; i++) {
indexOfTypeParameterBeingConverted = i;
argumentBindings[i] = makeTypeBinding(typeParameters[i]);
}
indexOfTypeParameterBeingConverted = 0;
baseTypeForParameterizedType = null;
ParameterizedTypeBinding ptb =
lookupEnvironment.createParameterizedType(baseTypeBinding,argumentBindings,baseTypeBinding.enclosingType());
return ptb;
} else if (typeX.isTypeVariableReference()) {
// return makeTypeVariableBinding((TypeVariableReference)typeX);
return makeTypeVariableBindingFromAJTypeVariable(((TypeVariableReference)typeX).getTypeVariable());
} else if (typeX.isRawType()) {
ReferenceBinding baseTypeBinding = lookupBinding(typeX.getBaseName());
RawTypeBinding rtb = lookupEnvironment.createRawType(baseTypeBinding,baseTypeBinding.enclosingType());
return rtb;
} else if (typeX.isGenericWildcard()) {
// translate from boundedreferencetype to WildcardBinding
BoundedReferenceType brt = (BoundedReferenceType)typeX;
// Work out 'kind' for the WildcardBinding
int boundkind = Wildcard.UNBOUND;
TypeBinding bound = null;
if (brt.isExtends()) {
boundkind = Wildcard.EXTENDS;
bound = makeTypeBinding(brt.getUpperBound());
} else if (brt.isSuper()) {
boundkind = Wildcard.SUPER;
bound = makeTypeBinding(brt.getLowerBound());
}
TypeBinding[] otherBounds = null;
if (brt.getAdditionalBounds()!=null && brt.getAdditionalBounds().length!=0) otherBounds = makeTypeBindings(brt.getAdditionalBounds());
WildcardBinding wb = lookupEnvironment.createWildcard(baseTypeForParameterizedType,indexOfTypeParameterBeingConverted,bound,otherBounds,boundkind);
return wb;
} else {
return lookupBinding(typeX.getName());
}
}
private ReferenceBinding lookupBinding(String sname) {
char[][] name = CharOperation.splitOn('.', sname.toCharArray());
ReferenceBinding rb = lookupEnvironment.getType(name);
return rb;
}
public TypeBinding[] makeTypeBindings(UnresolvedType[] types) {
int len = types.length;
TypeBinding[] ret = new TypeBinding[len];
for (int i = 0; i < len; i++) {
ret[i] = makeTypeBinding(types[i]);
}
return ret;
}
// just like the code above except it returns an array of ReferenceBindings
private ReferenceBinding[] makeReferenceBindings(UnresolvedType[] types) {
int len = types.length;
ReferenceBinding[] ret = new ReferenceBinding[len];
for (int i = 0; i < len; i++) {
ret[i] = (ReferenceBinding)makeTypeBinding(types[i]);
}
return ret;
}
// field related
public FieldBinding makeFieldBinding(NewFieldTypeMunger nftm) {
return internalMakeFieldBinding(nftm.getSignature(),nftm.getTypeVariableAliases());
}
/**
* Convert a resolvedmember into an eclipse field binding
*/
public FieldBinding makeFieldBinding(ResolvedMember member,List aliases) {
return internalMakeFieldBinding(member,aliases);
}
/**
* Convert a resolvedmember into an eclipse field binding
*/
public FieldBinding makeFieldBinding(ResolvedMember member) {
return internalMakeFieldBinding(member,null);
}
/**
* Take a normal AJ member and convert it into an eclipse fieldBinding.
* Taking into account any aliases that it may include due to being
* a generic itd. Any aliases are put into the typeVariableToBinding
* map so that they will be substituted as appropriate in the returned
* fieldbinding.
*/
public FieldBinding internalMakeFieldBinding(ResolvedMember member,List aliases) {
typeVariableToTypeBinding.clear();
TypeVariableBinding[] tvbs = null;
ReferenceBinding declaringType = (ReferenceBinding)makeTypeBinding(member.getDeclaringType());
// If there are aliases, place them in the map
if (aliases!=null && aliases.size()>0) {
int i =0;
for (Iterator iter = aliases.iterator(); iter.hasNext();) {
String element = (String) iter.next();
typeVariableToTypeBinding.put(element,declaringType.typeVariables()[i++]);
}
}
currentType = declaringType;
FieldBinding fb = new FieldBinding(member.getName().toCharArray(),
makeTypeBinding(member.getReturnType()),
member.getModifiers(),
currentType,
Constant.NotAConstant);
typeVariableToTypeBinding.clear();
currentType = null;
return fb;
}
private ReferenceBinding currentType = null;
// method binding related
public MethodBinding makeMethodBinding(NewMethodTypeMunger nmtm) {
return internalMakeMethodBinding(nmtm.getSignature(),nmtm.getTypeVariableAliases());
}
/**
* Convert a resolvedmember into an eclipse method binding.
*/
public MethodBinding makeMethodBinding(ResolvedMember member,List aliases) {
return internalMakeMethodBinding(member,aliases);
}
/**
* Creates a method binding for a resolvedmember taking into account type variable aliases -
* this variant can take an aliasTargetType and should be used when the alias target type
* cannot be retrieved from the resolvedmember.
*/
public MethodBinding makeMethodBinding(ResolvedMember member,List aliases,UnresolvedType aliasTargetType) {
return internalMakeMethodBinding(member,aliases,aliasTargetType);
}
/**
* Convert a resolvedmember into an eclipse method binding.
*/
public MethodBinding makeMethodBinding(ResolvedMember member) {
return internalMakeMethodBinding(member,null); // there are no aliases
}
public MethodBinding internalMakeMethodBinding(ResolvedMember member,List aliases) {
return internalMakeMethodBinding(member,aliases,member.getDeclaringType());
}
/**
* Take a normal AJ member and convert it into an eclipse methodBinding.
* Taking into account any aliases that it may include due to being a
* generic ITD. Any aliases are put into the typeVariableToBinding
* map so that they will be substituted as appropriate in the returned
* methodbinding
*/
public MethodBinding internalMakeMethodBinding(ResolvedMember member,List aliases,UnresolvedType aliasTargetType) {
typeVariableToTypeBinding.clear();
TypeVariableBinding[] tvbs = null;
if (member.getTypeVariables()!=null) {
if (member.getTypeVariables().length==0) {
tvbs = MethodBinding.NoTypeVariables;
} else {
tvbs = makeTypeVariableBindingsFromAJTypeVariables(member.getTypeVariables());
// QQQ do we need to bother fixing up the declaring element here?
}
}
ReferenceBinding declaringType = (ReferenceBinding)makeTypeBinding(member.getDeclaringType());
// If there are aliases, place them in the map
if (aliases!=null && aliases.size()!=0) {
int i=0;
ReferenceBinding aliasTarget = (ReferenceBinding)makeTypeBinding(aliasTargetType);
for (Iterator iter = aliases.iterator(); iter.hasNext();) {
String element = (String) iter.next();
typeVariableToTypeBinding.put(element,aliasTarget.typeVariables()[i++]);
}
}
currentType = declaringType;
MethodBinding mb = new MethodBinding(member.getModifiers(),
member.getName().toCharArray(),
makeTypeBinding(member.getReturnType()),
makeTypeBindings(member.getParameterTypes()),
makeReferenceBindings(member.getExceptions()),
declaringType);
if (tvbs!=null) mb.typeVariables = tvbs;
typeVariableToTypeBinding.clear();
currentType = null;
return mb;
}
/**
* Convert a bunch of type variables in one go, from AspectJ form to Eclipse form.
*/
// private TypeVariableBinding[] makeTypeVariableBindings(UnresolvedType[] typeVariables) {
// int len = typeVariables.length;
// TypeVariableBinding[] ret = new TypeVariableBinding[len];
// for (int i = 0; i < len; i++) {
// ret[i] = makeTypeVariableBinding((TypeVariableReference)typeVariables[i]);
// }
// return ret;
// }
private TypeVariableBinding[] makeTypeVariableBindingsFromAJTypeVariables(TypeVariable[] typeVariables) {
int len = typeVariables.length;
TypeVariableBinding[] ret = new TypeVariableBinding[len];
for (int i = 0; i < len; i++) {
ret[i] = makeTypeVariableBindingFromAJTypeVariable(typeVariables[i]);
}
return ret;
}
// only accessed through private methods in this class. Ensures all type variables we encounter
// map back to the same type binding - this is important later when Eclipse code is processing
// a methodbinding trying to come up with possible bindings for the type variables.
// key is currently the name of the type variable...is that ok?
private Map typeVariableToTypeBinding = new HashMap();
/**
* Converts from an TypeVariableReference to a TypeVariableBinding. A TypeVariableReference
* in AspectJ world holds a TypeVariable and it is this type variable that is converted
* to the TypeVariableBinding.
*/
private TypeVariableBinding makeTypeVariableBinding(TypeVariableReference tvReference) {
TypeVariable tv = tvReference.getTypeVariable();
TypeVariableBinding tvBinding = (TypeVariableBinding)typeVariableToTypeBinding.get(tv.getName());
if (currentType!=null) {
TypeVariableBinding tvb = currentType.getTypeVariable(tv.getName().toCharArray());
if (tvb!=null) return tvb;
}
if (tvBinding==null) {
Binding declaringElement = null;
// this will cause an infinite loop or NPE... not required yet luckily.
// if (tVar.getDeclaringElement() instanceof Member) {
// declaringElement = makeMethodBinding((ResolvedMember)tVar.getDeclaringElement());
// } else {
// declaringElement = makeTypeBinding((UnresolvedType)tVar.getDeclaringElement());
// }
tvBinding = new TypeVariableBinding(tv.getName().toCharArray(),declaringElement,tv.getRank());
typeVariableToTypeBinding.put(tv.getName(),tvBinding);
tvBinding.superclass=(ReferenceBinding)makeTypeBinding(tv.getUpperBound());
tvBinding.firstBound=(ReferenceBinding)makeTypeBinding(tv.getFirstBound());
if (tv.getAdditionalInterfaceBounds()==null) {
tvBinding.superInterfaces=TypeVariableBinding.NoSuperInterfaces;
} else {
TypeBinding tbs[] = makeTypeBindings(tv.getAdditionalInterfaceBounds());
ReferenceBinding[] rbs= new ReferenceBinding[tbs.length];
for (int i = 0; i < tbs.length; i++) {
rbs[i] = (ReferenceBinding)tbs[i];
}
tvBinding.superInterfaces=rbs;
}
}
return tvBinding;
}
private TypeVariableBinding makeTypeVariableBindingFromAJTypeVariable(TypeVariable tv) {
TypeVariableBinding tvBinding = (TypeVariableBinding)typeVariableToTypeBinding.get(tv.getName());
if (currentType!=null) {
TypeVariableBinding tvb = currentType.getTypeVariable(tv.getName().toCharArray());
if (tvb!=null) return tvb;
}
if (tvBinding==null) {
Binding declaringElement = null;
// this will cause an infinite loop or NPE... not required yet luckily.
// if (tVar.getDeclaringElement() instanceof Member) {
// declaringElement = makeMethodBinding((ResolvedMember)tVar.getDeclaringElement());
// } else {
// declaringElement = makeTypeBinding((UnresolvedType)tVar.getDeclaringElement());
// }
tvBinding = new TypeVariableBinding(tv.getName().toCharArray(),declaringElement,tv.getRank());
typeVariableToTypeBinding.put(tv.getName(),tvBinding);
tvBinding.superclass=(ReferenceBinding)makeTypeBinding(tv.getUpperBound());
tvBinding.firstBound=(ReferenceBinding)makeTypeBinding(tv.getFirstBound());
if (tv.getAdditionalInterfaceBounds()==null) {
tvBinding.superInterfaces=TypeVariableBinding.NoSuperInterfaces;
} else {
TypeBinding tbs[] = makeTypeBindings(tv.getAdditionalInterfaceBounds());
ReferenceBinding[] rbs= new ReferenceBinding[tbs.length];
for (int i = 0; i < tbs.length; i++) {
rbs[i] = (ReferenceBinding)tbs[i];
}
tvBinding.superInterfaces=rbs;
}
}
return tvBinding;
}
public MethodBinding makeMethodBindingForCall(Member member) {
return new MethodBinding(member.getCallsiteModifiers(),
member.getName().toCharArray(),
makeTypeBinding(member.getReturnType()),
makeTypeBindings(member.getParameterTypes()),
new ReferenceBinding[0],
(ReferenceBinding)makeTypeBinding(member.getDeclaringType()));
}
public void finishedCompilationUnit(CompilationUnitDeclaration unit) {
if ((buildManager != null) && buildManager.doGenerateModel()) {
AjBuildManager.getAsmHierarchyBuilder().buildStructureForCompilationUnit(unit, buildManager.getStructureModel(), buildManager.buildConfig);
}
}
public void addTypeBinding(TypeBinding binding) {
typexToBinding.put(fromBinding(binding), binding);
}
public void addTypeBindingAndStoreInWorld(TypeBinding binding) {
UnresolvedType ut = fromBinding(binding);
typexToBinding.put(ut, binding);
world.lookupOrCreateName(ut);
}
public Shadow makeShadow(ASTNode location, ReferenceContext context) {
return EclipseShadow.makeShadow(this, location, context);
}
public Shadow makeShadow(ReferenceContext context) {
return EclipseShadow.makeShadow(this, (ASTNode) context, context);
}
public void addSourceTypeBinding(SourceTypeBinding binding, CompilationUnitDeclaration unit) {
TypeDeclaration decl = binding.scope.referenceContext;
// Deal with the raw/basic type to give us an entry in the world type map
UnresolvedType simpleTx = null;
if (binding.isGenericType()) {
simpleTx = UnresolvedType.forRawTypeName(getName(binding));
} else if (binding.isLocalType()) {
LocalTypeBinding ltb = (LocalTypeBinding) binding;
if (ltb.constantPoolName() != null && ltb.constantPoolName().length > 0) {
simpleTx = UnresolvedType.forSignature(new String(binding.signature()));
} else {
simpleTx = UnresolvedType.forName(getName(binding));
}
}else {
simpleTx = UnresolvedType.forName(getName(binding));
}
ReferenceType name = getWorld().lookupOrCreateName(simpleTx);
// A type can change from simple > generic > simple across a set of compiles. We need
// to ensure the entry in the typemap is promoted and demoted correctly. The call
// to setGenericType() below promotes a simple to a raw. This call demotes it back
// to simple
// pr125405
if (!binding.isRawType() && !binding.isGenericType() && name.getTypekind()==TypeKind.RAW) {
name.demoteToSimpleType();
}
EclipseSourceType t = new EclipseSourceType(name, this, binding, decl, unit);
// For generics, go a bit further - build a typex for the generic type
// give it the same delegate and link it to the raw type
if (binding.isGenericType()) {
UnresolvedType complexTx = fromBinding(binding); // fully aware of any generics info
ResolvedType cName = world.resolve(complexTx,true);
ReferenceType complexName = null;
if (!cName.isMissing()) {
complexName = (ReferenceType) cName;
complexName = (ReferenceType) complexName.getGenericType();
if (complexName == null) complexName = new ReferenceType(complexTx,world);
} else {
complexName = new ReferenceType(complexTx,world);
}
name.setGenericType(complexName);
complexName.setDelegate(t);
}
name.setDelegate(t);
if (decl instanceof AspectDeclaration) {
((AspectDeclaration)decl).typeX = name;
((AspectDeclaration)decl).concreteName = t;
}
ReferenceBinding[] memberTypes = binding.memberTypes;
for (int i = 0, length = memberTypes.length; i < length; i++) {
addSourceTypeBinding((SourceTypeBinding) memberTypes[i], unit);
}
}
// XXX this doesn't feel like it belongs here, but it breaks a hard dependency on
// exposing AjBuildManager (needed by AspectDeclaration).
public boolean isXSerializableAspects() {
return xSerializableAspects;
}
public ResolvedMember fromBinding(MethodBinding binding) {
return new ResolvedMemberImpl(Member.METHOD,fromBinding(binding.declaringClass),binding.modifiers,
fromBinding(binding.returnType),CharOperation.charToString(binding.selector),fromBindings(binding.parameters));
}
public TypeVariableDeclaringElement fromBinding(Binding declaringElement) {
if (declaringElement instanceof TypeBinding) {
return fromBinding(((TypeBinding)declaringElement));
} else {
return fromBinding((MethodBinding)declaringElement);
}
}
public void cleanup() {
this.typexToBinding.clear();
this.rawTypeXToBinding.clear();
this.finishedTypeMungers = null;
}
}
|
141,956 |
Bug 141956 Null Pointer Exception when trying to skip Parent Mungers.
|
I don't know much about the internal workings of aspectJ but this bug keeps popping up so I went through the trouble of checking of trying to debug it so that I could hopefully provide enough information to get it fixed. This happens while using eclipse AJDT. It never happens if I fully do a clean before rebuild. It only seems to happen when doing incrmental builds (using the project->build automatically setting). The error happens in the iterator that recursively builds a list of methods to return for matching. The error is triggered here: // we need to know if it is an interface from Parent kind munger // as those are used for @AJ ITD and we precisely want to skip those boolean shouldSkip = false; for (int j = 0; j < rtx.interTypeMungers.size(); j++) { ConcreteTypeMunger munger = (ConcreteTypeMunger) rtx.interTypeMungers.get(j); if (munger.getMunger().getKind() == ResolvedTypeMunger.Parent) { shouldSkip = true; break; } } munger.getMunger() returns null because the munger instance is a BcelPerClauseAspectAdder. My naive fix would be to check munger.getMunger() == null or check munger.getKind(). I'm assuming that BcelPerClausAspectAdder is one that should be skipped since it is related to @AJ ??? Again, I don't know very much about the internal architecture of the weaver magic so I hope this is enough information. I would appreciate it if someone who knows more of the internals could speculate as to why this bug would never pop up on a clean build but only on incremental builds? Also it's not on all incremental builds and I haven't been able to isolate what kind of changes or compiles it triggers this, although it seems that once I got the exception once, I keep getting it on every build until I do a clean. java.lang.NullPointerException at org.aspectj.weaver.ResolvedType.addAndRecurse(ResolvedType.java:288) at org.aspectj.weaver.ResolvedType.getMethodsWithoutIterator(ResolvedType.java:257) at org.aspectj.weaver.ResolvedType.lookupResolvedMember(ResolvedType.java:378) at org.aspectj.weaver.JoinPointSignatureIterator.findSignaturesFromSupertypes(JoinPointSignatureIterator.java:178) at org.aspectj.weaver.JoinPointSignatureIterator.hasNext(JoinPointSignatureIterator.java:69) at org.aspectj.weaver.patterns.SignaturePattern.matches(SignaturePattern.java:287) at org.aspectj.weaver.patterns.KindedPointcut.matchInternal(KindedPointcut.java:103) at org.aspectj.weaver.patterns.Pointcut.match(Pointcut.java:144) at org.aspectj.weaver.patterns.AndPointcut.matchInternal(AndPointcut.java:51) at org.aspectj.weaver.patterns.Pointcut.match(Pointcut.java:144) at org.aspectj.weaver.ShadowMunger.match(ShadowMunger.java:64) at org.aspectj.weaver.Advice.match(Advice.java:109) at org.aspectj.weaver.bcel.BcelAdvice.match(BcelAdvice.java:104) at org.aspectj.weaver.bcel.BcelClassWeaver.match(BcelClassWeaver.java:2210) at org.aspectj.weaver.bcel.BcelClassWeaver.match(BcelClassWeaver.java:1752) at org.aspectj.weaver.bcel.BcelClassWeaver.weave(BcelClassWeaver.java:479) at org.aspectj.weaver.bcel.BcelClassWeaver.weave(BcelClassWeaver.java:109) at org.aspectj.weaver.bcel.BcelWeaver.weave(BcelWeaver.java:1574) at org.aspectj.weaver.bcel.BcelWeaver.weaveWithoutDump(BcelWeaver.java:1525) at org.aspectj.weaver.bcel.BcelWeaver.weaveAndNotify(BcelWeaver.java:1305) at org.aspectj.weaver.bcel.BcelWeaver.weave(BcelWeaver.java:1127) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.weave(AjCompilerAdapter.java:321) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.afterCompiling(AjCompilerAdapter.java:192) at org.aspectj.ajdt.internal.compiler.CompilerAdapter.ajc$afterReturning$org_aspectj_ajdt_internal_compiler_CompilerAdapter$2$f9cc9ca0(CompilerAdapter.aj:70) at org.aspectj.org.eclipse.jdt.internal.compiler.Compiler.compile(Compiler.java:367) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.performCompilation(AjBuildManager.java:862) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.doBuild(AjBuildManager.java:269) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.incrementalBuild(AjBuildManager.java:168) at org.aspectj.ajde.internal.CompilerAdapter.compile(CompilerAdapter.java:117) at org.aspectj.ajde.internal.AspectJBuildManager$CompilerThread.run(AspectJBuildManager.java:191)
|
resolved fixed
|
5f6a6b1
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-05-17T11:38:39Z | 2006-05-16T09:00:00Z |
tests/multiIncremental/PR141956/base/A.java
| |
141,956 |
Bug 141956 Null Pointer Exception when trying to skip Parent Mungers.
|
I don't know much about the internal workings of aspectJ but this bug keeps popping up so I went through the trouble of checking of trying to debug it so that I could hopefully provide enough information to get it fixed. This happens while using eclipse AJDT. It never happens if I fully do a clean before rebuild. It only seems to happen when doing incrmental builds (using the project->build automatically setting). The error happens in the iterator that recursively builds a list of methods to return for matching. The error is triggered here: // we need to know if it is an interface from Parent kind munger // as those are used for @AJ ITD and we precisely want to skip those boolean shouldSkip = false; for (int j = 0; j < rtx.interTypeMungers.size(); j++) { ConcreteTypeMunger munger = (ConcreteTypeMunger) rtx.interTypeMungers.get(j); if (munger.getMunger().getKind() == ResolvedTypeMunger.Parent) { shouldSkip = true; break; } } munger.getMunger() returns null because the munger instance is a BcelPerClauseAspectAdder. My naive fix would be to check munger.getMunger() == null or check munger.getKind(). I'm assuming that BcelPerClausAspectAdder is one that should be skipped since it is related to @AJ ??? Again, I don't know very much about the internal architecture of the weaver magic so I hope this is enough information. I would appreciate it if someone who knows more of the internals could speculate as to why this bug would never pop up on a clean build but only on incremental builds? Also it's not on all incremental builds and I haven't been able to isolate what kind of changes or compiles it triggers this, although it seems that once I got the exception once, I keep getting it on every build until I do a clean. java.lang.NullPointerException at org.aspectj.weaver.ResolvedType.addAndRecurse(ResolvedType.java:288) at org.aspectj.weaver.ResolvedType.getMethodsWithoutIterator(ResolvedType.java:257) at org.aspectj.weaver.ResolvedType.lookupResolvedMember(ResolvedType.java:378) at org.aspectj.weaver.JoinPointSignatureIterator.findSignaturesFromSupertypes(JoinPointSignatureIterator.java:178) at org.aspectj.weaver.JoinPointSignatureIterator.hasNext(JoinPointSignatureIterator.java:69) at org.aspectj.weaver.patterns.SignaturePattern.matches(SignaturePattern.java:287) at org.aspectj.weaver.patterns.KindedPointcut.matchInternal(KindedPointcut.java:103) at org.aspectj.weaver.patterns.Pointcut.match(Pointcut.java:144) at org.aspectj.weaver.patterns.AndPointcut.matchInternal(AndPointcut.java:51) at org.aspectj.weaver.patterns.Pointcut.match(Pointcut.java:144) at org.aspectj.weaver.ShadowMunger.match(ShadowMunger.java:64) at org.aspectj.weaver.Advice.match(Advice.java:109) at org.aspectj.weaver.bcel.BcelAdvice.match(BcelAdvice.java:104) at org.aspectj.weaver.bcel.BcelClassWeaver.match(BcelClassWeaver.java:2210) at org.aspectj.weaver.bcel.BcelClassWeaver.match(BcelClassWeaver.java:1752) at org.aspectj.weaver.bcel.BcelClassWeaver.weave(BcelClassWeaver.java:479) at org.aspectj.weaver.bcel.BcelClassWeaver.weave(BcelClassWeaver.java:109) at org.aspectj.weaver.bcel.BcelWeaver.weave(BcelWeaver.java:1574) at org.aspectj.weaver.bcel.BcelWeaver.weaveWithoutDump(BcelWeaver.java:1525) at org.aspectj.weaver.bcel.BcelWeaver.weaveAndNotify(BcelWeaver.java:1305) at org.aspectj.weaver.bcel.BcelWeaver.weave(BcelWeaver.java:1127) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.weave(AjCompilerAdapter.java:321) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.afterCompiling(AjCompilerAdapter.java:192) at org.aspectj.ajdt.internal.compiler.CompilerAdapter.ajc$afterReturning$org_aspectj_ajdt_internal_compiler_CompilerAdapter$2$f9cc9ca0(CompilerAdapter.aj:70) at org.aspectj.org.eclipse.jdt.internal.compiler.Compiler.compile(Compiler.java:367) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.performCompilation(AjBuildManager.java:862) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.doBuild(AjBuildManager.java:269) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.incrementalBuild(AjBuildManager.java:168) at org.aspectj.ajde.internal.CompilerAdapter.compile(CompilerAdapter.java:117) at org.aspectj.ajde.internal.AspectJBuildManager$CompilerThread.run(AspectJBuildManager.java:191)
|
resolved fixed
|
5f6a6b1
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-05-17T11:38:39Z | 2006-05-16T09:00:00Z |
tests/multiIncremental/PR141956/base/C.java
| |
141,956 |
Bug 141956 Null Pointer Exception when trying to skip Parent Mungers.
|
I don't know much about the internal workings of aspectJ but this bug keeps popping up so I went through the trouble of checking of trying to debug it so that I could hopefully provide enough information to get it fixed. This happens while using eclipse AJDT. It never happens if I fully do a clean before rebuild. It only seems to happen when doing incrmental builds (using the project->build automatically setting). The error happens in the iterator that recursively builds a list of methods to return for matching. The error is triggered here: // we need to know if it is an interface from Parent kind munger // as those are used for @AJ ITD and we precisely want to skip those boolean shouldSkip = false; for (int j = 0; j < rtx.interTypeMungers.size(); j++) { ConcreteTypeMunger munger = (ConcreteTypeMunger) rtx.interTypeMungers.get(j); if (munger.getMunger().getKind() == ResolvedTypeMunger.Parent) { shouldSkip = true; break; } } munger.getMunger() returns null because the munger instance is a BcelPerClauseAspectAdder. My naive fix would be to check munger.getMunger() == null or check munger.getKind(). I'm assuming that BcelPerClausAspectAdder is one that should be skipped since it is related to @AJ ??? Again, I don't know very much about the internal architecture of the weaver magic so I hope this is enough information. I would appreciate it if someone who knows more of the internals could speculate as to why this bug would never pop up on a clean build but only on incremental builds? Also it's not on all incremental builds and I haven't been able to isolate what kind of changes or compiles it triggers this, although it seems that once I got the exception once, I keep getting it on every build until I do a clean. java.lang.NullPointerException at org.aspectj.weaver.ResolvedType.addAndRecurse(ResolvedType.java:288) at org.aspectj.weaver.ResolvedType.getMethodsWithoutIterator(ResolvedType.java:257) at org.aspectj.weaver.ResolvedType.lookupResolvedMember(ResolvedType.java:378) at org.aspectj.weaver.JoinPointSignatureIterator.findSignaturesFromSupertypes(JoinPointSignatureIterator.java:178) at org.aspectj.weaver.JoinPointSignatureIterator.hasNext(JoinPointSignatureIterator.java:69) at org.aspectj.weaver.patterns.SignaturePattern.matches(SignaturePattern.java:287) at org.aspectj.weaver.patterns.KindedPointcut.matchInternal(KindedPointcut.java:103) at org.aspectj.weaver.patterns.Pointcut.match(Pointcut.java:144) at org.aspectj.weaver.patterns.AndPointcut.matchInternal(AndPointcut.java:51) at org.aspectj.weaver.patterns.Pointcut.match(Pointcut.java:144) at org.aspectj.weaver.ShadowMunger.match(ShadowMunger.java:64) at org.aspectj.weaver.Advice.match(Advice.java:109) at org.aspectj.weaver.bcel.BcelAdvice.match(BcelAdvice.java:104) at org.aspectj.weaver.bcel.BcelClassWeaver.match(BcelClassWeaver.java:2210) at org.aspectj.weaver.bcel.BcelClassWeaver.match(BcelClassWeaver.java:1752) at org.aspectj.weaver.bcel.BcelClassWeaver.weave(BcelClassWeaver.java:479) at org.aspectj.weaver.bcel.BcelClassWeaver.weave(BcelClassWeaver.java:109) at org.aspectj.weaver.bcel.BcelWeaver.weave(BcelWeaver.java:1574) at org.aspectj.weaver.bcel.BcelWeaver.weaveWithoutDump(BcelWeaver.java:1525) at org.aspectj.weaver.bcel.BcelWeaver.weaveAndNotify(BcelWeaver.java:1305) at org.aspectj.weaver.bcel.BcelWeaver.weave(BcelWeaver.java:1127) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.weave(AjCompilerAdapter.java:321) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.afterCompiling(AjCompilerAdapter.java:192) at org.aspectj.ajdt.internal.compiler.CompilerAdapter.ajc$afterReturning$org_aspectj_ajdt_internal_compiler_CompilerAdapter$2$f9cc9ca0(CompilerAdapter.aj:70) at org.aspectj.org.eclipse.jdt.internal.compiler.Compiler.compile(Compiler.java:367) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.performCompilation(AjBuildManager.java:862) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.doBuild(AjBuildManager.java:269) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.incrementalBuild(AjBuildManager.java:168) at org.aspectj.ajde.internal.CompilerAdapter.compile(CompilerAdapter.java:117) at org.aspectj.ajde.internal.AspectJBuildManager$CompilerThread.run(AspectJBuildManager.java:191)
|
resolved fixed
|
5f6a6b1
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-05-17T11:38:39Z | 2006-05-16T09:00:00Z |
tests/multiIncremental/PR141956/inc1/C.java
| |
141,956 |
Bug 141956 Null Pointer Exception when trying to skip Parent Mungers.
|
I don't know much about the internal workings of aspectJ but this bug keeps popping up so I went through the trouble of checking of trying to debug it so that I could hopefully provide enough information to get it fixed. This happens while using eclipse AJDT. It never happens if I fully do a clean before rebuild. It only seems to happen when doing incrmental builds (using the project->build automatically setting). The error happens in the iterator that recursively builds a list of methods to return for matching. The error is triggered here: // we need to know if it is an interface from Parent kind munger // as those are used for @AJ ITD and we precisely want to skip those boolean shouldSkip = false; for (int j = 0; j < rtx.interTypeMungers.size(); j++) { ConcreteTypeMunger munger = (ConcreteTypeMunger) rtx.interTypeMungers.get(j); if (munger.getMunger().getKind() == ResolvedTypeMunger.Parent) { shouldSkip = true; break; } } munger.getMunger() returns null because the munger instance is a BcelPerClauseAspectAdder. My naive fix would be to check munger.getMunger() == null or check munger.getKind(). I'm assuming that BcelPerClausAspectAdder is one that should be skipped since it is related to @AJ ??? Again, I don't know very much about the internal architecture of the weaver magic so I hope this is enough information. I would appreciate it if someone who knows more of the internals could speculate as to why this bug would never pop up on a clean build but only on incremental builds? Also it's not on all incremental builds and I haven't been able to isolate what kind of changes or compiles it triggers this, although it seems that once I got the exception once, I keep getting it on every build until I do a clean. java.lang.NullPointerException at org.aspectj.weaver.ResolvedType.addAndRecurse(ResolvedType.java:288) at org.aspectj.weaver.ResolvedType.getMethodsWithoutIterator(ResolvedType.java:257) at org.aspectj.weaver.ResolvedType.lookupResolvedMember(ResolvedType.java:378) at org.aspectj.weaver.JoinPointSignatureIterator.findSignaturesFromSupertypes(JoinPointSignatureIterator.java:178) at org.aspectj.weaver.JoinPointSignatureIterator.hasNext(JoinPointSignatureIterator.java:69) at org.aspectj.weaver.patterns.SignaturePattern.matches(SignaturePattern.java:287) at org.aspectj.weaver.patterns.KindedPointcut.matchInternal(KindedPointcut.java:103) at org.aspectj.weaver.patterns.Pointcut.match(Pointcut.java:144) at org.aspectj.weaver.patterns.AndPointcut.matchInternal(AndPointcut.java:51) at org.aspectj.weaver.patterns.Pointcut.match(Pointcut.java:144) at org.aspectj.weaver.ShadowMunger.match(ShadowMunger.java:64) at org.aspectj.weaver.Advice.match(Advice.java:109) at org.aspectj.weaver.bcel.BcelAdvice.match(BcelAdvice.java:104) at org.aspectj.weaver.bcel.BcelClassWeaver.match(BcelClassWeaver.java:2210) at org.aspectj.weaver.bcel.BcelClassWeaver.match(BcelClassWeaver.java:1752) at org.aspectj.weaver.bcel.BcelClassWeaver.weave(BcelClassWeaver.java:479) at org.aspectj.weaver.bcel.BcelClassWeaver.weave(BcelClassWeaver.java:109) at org.aspectj.weaver.bcel.BcelWeaver.weave(BcelWeaver.java:1574) at org.aspectj.weaver.bcel.BcelWeaver.weaveWithoutDump(BcelWeaver.java:1525) at org.aspectj.weaver.bcel.BcelWeaver.weaveAndNotify(BcelWeaver.java:1305) at org.aspectj.weaver.bcel.BcelWeaver.weave(BcelWeaver.java:1127) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.weave(AjCompilerAdapter.java:321) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.afterCompiling(AjCompilerAdapter.java:192) at org.aspectj.ajdt.internal.compiler.CompilerAdapter.ajc$afterReturning$org_aspectj_ajdt_internal_compiler_CompilerAdapter$2$f9cc9ca0(CompilerAdapter.aj:70) at org.aspectj.org.eclipse.jdt.internal.compiler.Compiler.compile(Compiler.java:367) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.performCompilation(AjBuildManager.java:862) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.doBuild(AjBuildManager.java:269) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.incrementalBuild(AjBuildManager.java:168) at org.aspectj.ajde.internal.CompilerAdapter.compile(CompilerAdapter.java:117) at org.aspectj.ajde.internal.AspectJBuildManager$CompilerThread.run(AspectJBuildManager.java:191)
|
resolved fixed
|
5f6a6b1
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-05-17T11:38:39Z | 2006-05-16T09:00:00Z |
tests/src/org/aspectj/systemtest/incremental/tools/MultiProjectIncrementalTests.java
|
/* *******************************************************************
* Copyright (c) 2005 Contributors.
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Eclipse Public License v1.0
* which accompanies this distribution and is available at
* http://eclipse.org/legal/epl-v10.html
*
* Contributors:
* Andy Clement initial implementation
* ******************************************************************/
package org.aspectj.systemtest.incremental.tools;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import org.aspectj.ajdt.internal.core.builder.AjState;
import org.aspectj.ajdt.internal.core.builder.AsmHierarchyBuilder;
import org.aspectj.ajdt.internal.core.builder.IncrementalStateManager;
import org.aspectj.asm.AsmManager;
import org.aspectj.asm.IProgramElement;
import org.aspectj.asm.IRelationship;
import org.aspectj.asm.IRelationshipMap;
import org.aspectj.asm.internal.Relationship;
import org.aspectj.bridge.IMessage;
import org.aspectj.testing.util.FileUtil;
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 AjdeInteractionTestbed {
public static boolean VERBOSE = false;
protected void setUp() throws Exception {
super.setUp();
AjdeInteractionTestbed.VERBOSE = VERBOSE;
AjState.FORCE_INCREMENTAL_DURING_TESTING = true;
}
protected void tearDown() throws Exception {
super.tearDown();
AjState.FORCE_INCREMENTAL_DURING_TESTING = false;
}
/*
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 {
AsmHierarchyBuilder.shouldAddUsesPointcut=false;
configureBuildStructureModel(true);
initialiseProject("P4");
build("P4");
dumpAJDEStructureModel("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();
dumpAJDEStructureModel("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("pack","C",true));
// This will be the line 7 entry in A.java
IProgramElement advice = findAdvice(checkForNode("pack","A",true));
IRelationshipMap asmRelMap = AsmManager.getDefault().getRelationshipMap();
assertEquals("There should be two relationships in the relationship map",
2,asmRelMap.getEntries().size());
for (Iterator iter = asmRelMap.getEntries().iterator(); iter.hasNext();) {
String sourceOfRelationship = (String) iter.next();
IProgramElement ipe = AsmManager.getDefault().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 relationships = asmRelMap.get(ipe);
assertNotNull("expected " + ipe.getName() +" to have some " +
"relationships",relationships);
for (Iterator iterator = relationships.iterator(); iterator.hasNext();) {
Relationship rel = (Relationship) iterator.next();
List targets = rel.getTargets();
for (Iterator iterator2 = targets.iterator(); iterator2.hasNext();) {
String t = (String) iterator2.next();
IProgramElement link = AsmManager.getDefault().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 {
AsmHierarchyBuilder.shouldAddUsesPointcut=true;
configureBuildStructureModel(false);
}
}
// Compile a single simple project
public void testTheBasics() {
initialiseProject("P1");
build("P1"); // This first build will be batch
build("P1");
checkWasntFullBuild();
checkCompileWeaveCount(0,0);
}
// source code doesnt matter, we are checking invalid path handling
public void testInvalidAspectpath_pr121395() {
initialiseProject("P1");
File f = new File("foo.jar");
Set s = new HashSet();
s.add(f);
configureAspectPath(s);
build("P1"); // This first build will be batch
checkForError("invalid aspectpath entry");
}
// Make simple changes to a project, adding a class
public void testSimpleChanges() {
initialiseProject("P1");
build("P1"); // This first build will be batch
alter("P1","inc1"); // adds a single class
build("P1");
checkCompileWeaveCount(1,-1);
build("P1");
checkCompileWeaveCount(0,-1);
}
// Make simple changes to a project, adding a class and an aspect
public void testAddingAnAspect() {
initialiseProject("P1");
build("P1"); // build 1, weave 1
alter("P1","inc1"); // adds a class
alter("P1","inc2"); // adds an aspect
build("P1"); // build 1,
long timeTakenForFullBuildAndWeave = getTimeTakenForBuild();
checkWasFullBuild(); // it *will* be a full build under the new
// "back-to-the-source strategy
checkCompileWeaveCount(5,3); // we compile X and A (the delta) find out that
// an aspect has changed, go back to the source
// and compile X,A,C, then weave them all.
build("P1");
long timeTakenForSimpleIncBuild = getTimeTakenForBuild();
// I don't think this test will have timing issues as the times should be *RADICALLY* different
// On my config, first build time is 2093ms and the second is 30ms
assertTrue("Should not take longer for the trivial incremental build! first="+timeTakenForFullBuildAndWeave+
"ms second="+timeTakenForSimpleIncBuild+"ms",
timeTakenForSimpleIncBuild<timeTakenForFullBuildAndWeave);
}
public void testBuildingTwoProjectsInTurns() {
configureBuildStructureModel(true);
initialiseProject("P1");
initialiseProject("P2");
build("P1");
build("P2");
build("P1");
checkWasntFullBuild();
build("P2");
checkWasntFullBuild();
}
/**
* In order for this next test to run, I had to move the weaver/world pair we keep in the
* AjBuildManager instance down into the state object - this makes perfect sense - otherwise
* when reusing the state for another project we'd not be switching to the right weaver/world
* for that project.
*/
public void testBuildingTwoProjectsMakingSmallChanges() {
configureBuildStructureModel(true);
initialiseProject("P1");
initialiseProject("P2");
build("P1");
build("P2");
build("P1");
checkWasntFullBuild();
build("P2");
checkWasntFullBuild();
alter("P1","inc1"); // adds a class
alter("P1","inc2"); // adds an aspect
build("P1");
checkWasFullBuild(); // adding an aspect makes us go back to the source
}
public void testPr134371() {
initialiseProject("PR134371");
build("PR134371");
alter("PR134371","inc1");
build("PR134371");
assertTrue("There should be no exceptions handled:\n"+MyErrorHandler.getErrorMessages(),
MyErrorHandler.getErrorMessages().isEmpty());
}
/**
* Setup up two simple projects and build them in turn - check the
* structure model is right after each build
*/
public void testBuildingTwoProjectsAndVerifyingModel() {
configureBuildStructureModel(true);
initialiseProject("P1");
initialiseProject("P2");
build("P1");
checkForNode("pkg","C",true);
build("P2");
checkForNode("pkg","C",false);
build("P1");
checkForNode("pkg","C",true);
build("P2");
checkForNode("pkg","C",false);
}
// Setup up two simple projects and build them in turn - check the
// structure model is right after each build
public void testBuildingTwoProjectsAndVerifyingStuff() {
configureBuildStructureModel(true);
initialiseProject("P1");
initialiseProject("P2");
build("P1");
checkForNode("pkg","C",true);
build("P2");
checkForNode("pkg","C",false);
build("P1");
checkForNode("pkg","C",true);
build("P2");
checkForNode("pkg","C",false);
}
/**
* Complex. Here we are testing that a state object records structural changes since
* the last full build correctly. We build a simple project from scratch - this will
* be a full build and so the structural changes since last build count should be 0.
* We then alter a class, adding a new method and check structural changes is 1.
*/
public void testStateManagement1() {
File binDirectoryForP1 = new File(getFile("P1","bin"));
initialiseProject("P1");
build("P1"); // full build
AjState ajs = IncrementalStateManager.findStateManagingOutputLocation(binDirectoryForP1);
assertTrue("There should be a state object for project P1",ajs!=null);
assertTrue("Should be no structural changes as it was a full build but found: "+
ajs.getNumberOfStructuralChangesSinceLastFullBuild(),
ajs.getNumberOfStructuralChangesSinceLastFullBuild()==0);
alter("P1","inc3"); // adds a method to the class C.java
build("P1");
checkWasntFullBuild();
ajs = IncrementalStateManager.findStateManagingOutputLocation(new File(getFile("P1","bin")));
assertTrue("There should be state for project P1",ajs!=null);
checkWasntFullBuild();
assertTrue("Should be one structural changes as it was a full build but found: "+
ajs.getNumberOfStructuralChangesSinceLastFullBuild(),
ajs.getNumberOfStructuralChangesSinceLastFullBuild()==1);
}
/**
* Complex. Here we are testing that a state object records structural changes since
* the last full build correctly. We build a simple project from scratch - this will
* be a full build and so the structural changes since last build count should be 0.
* We then alter a class, changing body of a method, not the structure and
* check struc changes is still 0.
*/
public void testStateManagement2() {
File binDirectoryForP1 = new File(getFile("P1","bin"));
initialiseProject("P1");
alter("P1","inc3"); // need this change in here so 'inc4' can be applied without making
// it a structural change
build("P1"); // full build
AjState ajs = IncrementalStateManager.findStateManagingOutputLocation(binDirectoryForP1);
assertTrue("There should be state for project P1",ajs!=null);
assertTrue("Should be no struc changes as its a full build: "+
ajs.getNumberOfStructuralChangesSinceLastFullBuild(),
ajs.getNumberOfStructuralChangesSinceLastFullBuild()==0);
alter("P1","inc4"); // changes body of main() method but does *not* change the structure of C.java
build("P1");
checkWasntFullBuild();
ajs = IncrementalStateManager.findStateManagingOutputLocation(new File(getFile("P1","bin")));
assertTrue("There should be state for project P1",ajs!=null);
checkWasntFullBuild();
assertTrue("Shouldn't be any structural changes but there were "+
ajs.getNumberOfStructuralChangesSinceLastFullBuild(),
ajs.getNumberOfStructuralChangesSinceLastFullBuild()==0);
}
/**
* 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
checkWasFullBuild();
alter("P1","inc4");
build("P1");
build("P2"); // build sees a change but works out its not structural
checkWasntFullBuild();
}
public void testPr85132() {
initialiseProject("PR85132");
build("PR85132");
alter("PR85132","inc1");
build("PR85132");
}
// parameterization of generic aspects
public void testPr125405() {
initialiseProject("PR125405");
build("PR125405");
checkCompileWeaveCount(1,1);
alter("PR125405","inc1");
build("PR125405");
// "only abstract aspects can have type parameters"
checkForError("only abstract aspects can have type parameters");
alter("PR125405","inc2");
build("PR125405");
checkCompileWeaveCount(1,1);
assertTrue("Should be no errors, but got "+MyTaskListManager.getErrorMessages(),MyTaskListManager.getErrorMessages().size()==0);
}
public void testPr128618() {
initialiseProject("PR128618_1");
initialiseProject("PR128618_2");
configureNewProjectDependency("PR128618_2","PR128618_1");
assertTrue("there should be no warning messages before we start",
MyTaskListManager.getWarningMessages().isEmpty());
build("PR128618_1");
build("PR128618_2");
List warnings = MyTaskListManager.getWarningMessages();
assertTrue("Should be one warning, but there are #"+warnings.size(),warnings.size()==1);
IMessage msg = (IMessage)(MyTaskListManager.getWarningMessages().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 = (IMessage)(MyTaskListManager.getWarningMessages().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");
}
public void testPr119570() {
initialiseProject("PR119570");
build("PR119570");
assertTrue("Should be no errors, but got "+MyTaskListManager.getErrorMessages(),MyTaskListManager.getErrorMessages().size()==0);
}
public void testPr119570_2() {
initialiseProject("PR119570_2");
build("PR119570_2");
List l = MyTaskListManager.getWarningMessages();
assertTrue("Should be no warnings, but got "+l,l.size()==0);
}
// If you fiddle with the compiler options - you must manually reset the options at the end of the test
public void testPr117209() {
try {
initialiseProject("pr117209");
configureNonStandardCompileOptions("-proceedOnError");
build("pr117209");
checkCompileWeaveCount(6,6);
} finally {
MyBuildOptionsAdapter.reset();
}
}
public void testPr114875() {
initialiseProject("pr114875");
build("pr114875");
alter("pr114875","inc1");
build("pr114875");
checkWasFullBuild();
alter("pr114875","inc2");
build("pr114875");
checkWasFullBuild(); // back to the source for an aspect change
}
public void testPr117882() {
// AjdeInteractionTestbed.VERBOSE=true;
// AjdeInteractionTestbed.configureBuildStructureModel(true);
initialiseProject("PR117882");
build("PR117882");
checkWasFullBuild();
alter("PR117882","inc1");
build("PR117882");
checkWasFullBuild(); // back to the source for an aspect
// AjdeInteractionTestbed.VERBOSE=false;
// AjdeInteractionTestbed.configureBuildStructureModel(false);
}
public void testPr117882_2() {
// AjdeInteractionTestbed.VERBOSE=true;
// AjdeInteractionTestbed.configureBuildStructureModel(true);
initialiseProject("PR117882_2");
build("PR117882_2");
checkWasFullBuild();
alter("PR117882_2","inc1");
build("PR117882_2");
checkWasFullBuild(); // back to the source...
//checkCompileWeaveCount(1,4);
//fullBuild("PR117882_2");
//checkWasFullBuild();
// AjdeInteractionTestbed.VERBOSE=false;
// AjdeInteractionTestbed.configureBuildStructureModel(false);
}
public void testPr115251() {
//AjdeInteractionTestbed.VERBOSE=true;
initialiseProject("PR115251");
build("PR115251");
checkWasFullBuild();
alter("PR115251","inc1");
build("PR115251");
checkWasFullBuild(); // back to the source
}
// public void testPr124399() {
// AjdeInteractionTestbed.VERBOSE=true;
// configureBuildStructureModel(true);
// initialiseProject("PR124399");
// build("PR124399");
// checkWasFullBuild();
// alter("PR124399","inc1");
// build("PR124399");
// checkWasntFullBuild();
// }
public void testPr121384() {
// AjdeInteractionTestbed.VERBOSE=true;
// AsmManager.setReporting("c:/foo.txt",true,true,true,false);
MyBuildOptionsAdapter.setNonStandardOptions("-showWeaveInfo");
configureBuildStructureModel(true);
initialiseProject("pr121384");
build("pr121384");
checkWasFullBuild();
alter("pr121384","inc1");
build("pr121384");
checkWasntFullBuild();
}
/* public void testPr111779() {
super.VERBOSE=true;
initialiseProject("PR111779");
build("PR111779");
alter("PR111779","inc1");
build("PR111779");
}
*/
public void testPr93310_1() {
initialiseProject("PR93310_1");
build("PR93310_1");
checkWasFullBuild();
String fileC2 = getWorkingDir().getAbsolutePath() + File.separatorChar + "PR93310_1" + File.separatorChar + "src" + File.separatorChar + "pack" + File.separatorChar + "C2.java";
(new File(fileC2)).delete();
alter("PR93310_1","inc1");
build("PR93310_1");
checkWasFullBuild();
int l = AjdeInteractionTestbed.MyStateListener.detectedDeletions.size();
assertTrue("Expected one deleted file to be noticed, but detected: "+l,l==1);
String name = (String)AjdeInteractionTestbed.MyStateListener.detectedDeletions.get(0);
assertTrue("Should end with C2.java but is "+name,name.endsWith("C2.java"));
}
public void testPr93310_2() {
initialiseProject("PR93310_2");
build("PR93310_2");
checkWasFullBuild();
String fileC2 = getWorkingDir().getAbsolutePath() + File.separatorChar + "PR93310_2" + File.separatorChar + "src" + File.separatorChar + "pack" + File.separatorChar + "C2.java";
(new File(fileC2)).delete();
alter("PR93310_2","inc1");
build("PR93310_2");
checkWasFullBuild();
int l = AjdeInteractionTestbed.MyStateListener.detectedDeletions.size();
assertTrue("Expected one deleted file to be noticed, but detected: "+l,l==1);
String name = (String)AjdeInteractionTestbed.MyStateListener.detectedDeletions.get(0);
assertTrue("Should end with C2.java but is "+name,name.endsWith("C2.java"));
}
// Stage1: Compile two files, pack.A and pack.A1 - A1 sets a protected field in A.
// Stage2: make the field private in class A > gives compile error
// Stage3: Add a new aspect whilst there is a compile error !
public void testPr113531() {
initialiseProject("PR113531");
build("PR113531");
assertFalse("build should have compiled ok",
MyTaskListManager.hasErrorMessages());
alter("PR113531","inc1");
build("PR113531");
assertEquals("error message should be 'foo cannot be resolved' ",
"foo cannot be resolved",
((IMessage)MyTaskListManager.getErrorMessages().get(0))
.getMessage());
alter("PR113531","inc2");
build("PR113531");
assertTrue("There should be no exceptions handled:\n"+MyErrorHandler.getErrorMessages(),
MyErrorHandler.getErrorMessages().isEmpty());
assertEquals("error message should be 'foo cannot be resolved' ",
"foo cannot be resolved",
((IMessage)MyTaskListManager.getErrorMessages().get(0))
.getMessage());
}
// Stage 1: Compile the 4 files, pack.A2 extends pack.A1 (aspects) where
// A2 uses a protected field in A1 and pack.C2 extends pack.C1 (classes)
// where C2 uses a protected field in C1
// Stage 2: make the field private in class C1 ==> compile errors in C2
// Stage 3: make the field private in aspect A1 whilst there's the compile
// error.
// There shouldn't be a BCExcpetion saying can't find delegate for pack.C2
public void testPr119882() {
initialiseProject("PR119882");
build("PR119882");
assertFalse("build should have compiled ok",MyTaskListManager.hasErrorMessages());
alter("PR119882","inc1");
build("PR119882");
//fullBuild("PR119882");
List errors = MyTaskListManager.getErrorMessages();
assertTrue("Should be at least one error, but got none",errors.size()==1);
assertEquals("error message should be 'i cannot be resolved' ",
"i cannot be resolved",
((IMessage)errors.get(0))
.getMessage());
alter("PR119882","inc2");
build("PR119882");
assertTrue("There should be no exceptions handled:\n"+MyErrorHandler.getErrorMessages(),
MyErrorHandler.getErrorMessages().isEmpty());
assertEquals("error message should be 'i cannot be resolved' ",
"i cannot be resolved",
((IMessage)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
}
public void testPr128655() {
configureNonStandardCompileOptions("-showWeaveInfo");
initialiseProject("pr128655");
build("pr128655");
List firstBuildMessages = MyTaskListManager.getWeavingMessages();
assertTrue("Should be at least one message about the dec @type, but there were none",firstBuildMessages.size()>0);
alter("pr128655","inc1");
build("pr128655");
checkWasntFullBuild(); // back to the source
List secondBuildMessages = MyTaskListManager.getWeavingMessages();
// check they are the same
for (int i = 0; i < firstBuildMessages.size(); i++) {
IMessage m1 = (IMessage)firstBuildMessages.get(i);
IMessage m2 = (IMessage)secondBuildMessages.get(i);
if (!m1.toString().equals(m2.toString())) {
System.err.println("Message during first build was: "+m1);
System.err.println("Message during second build was: "+m1);
fail("The two messages should be the same, but are not: \n"+m1+"!="+m2);
}
}
}
// Similar to above, but now the annotation is in the default package
public void testPr128655_2() {
configureNonStandardCompileOptions("-showWeaveInfo");
initialiseProject("pr128655_2");
build("pr128655_2");
List firstBuildMessages = MyTaskListManager.getWeavingMessages();
assertTrue("Should be at least one message about the dec @type, but there were none",firstBuildMessages.size()>0);
alter("pr128655_2","inc1");
build("pr128655_2");
checkWasntFullBuild(); // back to the source
List secondBuildMessages = MyTaskListManager.getWeavingMessages();
// check they are the same
for (int i = 0; i < firstBuildMessages.size(); i++) {
IMessage m1 = (IMessage)firstBuildMessages.get(i);
IMessage m2 = (IMessage)secondBuildMessages.get(i);
if (!m1.toString().equals(m2.toString())) {
System.err.println("Message during first build was: "+m1);
System.err.println("Message during second build was: "+m1);
fail("The two messages should be the same, but are not: \n"+m1+"!="+m2);
}
}
}
// test for comment #31 - NPE
public void testPr129163() {
configureBuildStructureModel(true);
initialiseProject("PR129613");
build("PR129613");
alter("PR129613","inc1");
build("PR129613");
assertTrue("There should be no exceptions handled:\n"+MyErrorHandler.getErrorMessages(),
MyErrorHandler.getErrorMessages().isEmpty());
assertEquals("warning message should be 'no match for this type name: File [Xlint:invalidAbsoluteTypeName]' ",
"no match for this type name: File [Xlint:invalidAbsoluteTypeName]",
((IMessage)MyTaskListManager.getWarningMessages().get(0))
.getMessage());
configureBuildStructureModel(false);
}
// 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
configureBuildStructureModel(true);
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
configureBuildStructureModel(false);
}
// 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() {
configureBuildStructureModel(true);
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
configureBuildStructureModel(false);
}
public void testPr133117() {
configureNonStandardCompileOptions("-Xlint:warning");
initialiseProject("PR133117");
build("PR133117");
assertTrue("There should only be one xlint warning message reported:\n"
+MyTaskListManager.getWarningMessages(),
MyTaskListManager.getWarningMessages().size()==1);
alter("PR133117","inc1");
build("PR133117");
List warnings = MyTaskListManager.getWarningMessages();
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() {
configureNonStandardCompileOptions("-outxml");
initialiseProject("PR131505");
build("PR131505");
checkWasFullBuild();
// aop.xml file shouldn't contain any aspects
checkXMLAspectCount("PR131505","",0);
// add a new aspect A which should be included in the aop.xml file
alter("PR131505","inc1");
build("PR131505");
checkWasFullBuild();
checkXMLAspectCount("PR131505","",1);
checkXMLAspectCount("PR131505","A",1);
// 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);
checkXMLAspectCount("PR131505","A",1);
// 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);
checkXMLAspectCount("PR131505","A1",1);
checkXMLAspectCount("PR131505","A",1);
// 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);
checkXMLAspectCount("PR131505","A1",0);
checkXMLAspectCount("PR131505","A",1);
// 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);
checkXMLAspectCount("PR131505","A",1);
checkXMLAspectCount("PR131505","pkg.A",1);
}
public void testPr136585() {
initialiseProject("PR136585");
build("PR136585");
alter("PR136585","inc1");
build("PR136585");
assertTrue("There should be no errors reported:\n"+MyTaskListManager.getErrorMessages(),
MyTaskListManager.getErrorMessages().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"+MyTaskListManager.getErrorMessages(),
MyTaskListManager.getErrorMessages().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"+MyTaskListManager.getErrorMessages(),
MyTaskListManager.getErrorMessages().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 testPr134541() {
initialiseProject("PR134541");
build("PR134541");
assertEquals("[Xlint:adviceDidNotMatch] should be associated with line 5",5,
((IMessage)MyTaskListManager.getWarningMessages().get(0)).getSourceLocation().getLine());
alter("PR134541","inc1");
build("PR134541");
if (World.compareLocations)
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,
((IMessage)MyTaskListManager.getWarningMessages().get(0)).getSourceLocation().getLine());
}
// 134471 related tests perform incremental compilation and verify features of the structure model post compile
public void testPr134471_IncrementalCompilationAndModelUpdates() {
try {
AsmHierarchyBuilder.shouldAddUsesPointcut=false;
configureBuildStructureModel(true);
configureNonStandardCompileOptions("-showWeaveInfo -emacssym");
// Step1. Build the code, simple advice from aspect A onto class C
initialiseProject("PR134471");
build("PR134471");
// Step2. Quick check that the advice points to something...
IProgramElement nodeForTypeA = checkForNode("pkg","A",true);
IProgramElement nodeForAdvice = findAdvice(nodeForTypeA);
List relatedElements = getRelatedElements(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(findCode(checkForNode("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");
// Step5. Quick check that the advice points to something...
nodeForTypeA = checkForNode("pkg","A",true);
nodeForAdvice = findAdvice(nodeForTypeA);
relatedElements = getRelatedElements(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(findCode(checkForNode("pkg","C",true)));
line = programElement.getSourceLocation().getLine();
assertTrue("advice should be at line 7 - but is at line "+line,line==7);
} finally {
AsmHierarchyBuilder.shouldAddUsesPointcut=true;
}
}
// now the advice moves down a few lines - hopefully the model will notice... see discussion in 134471
public void testPr134471_MovingAdvice() {
configureBuildStructureModel(true);
configureNonStandardCompileOptions("-showWeaveInfo -emacssym");
// Step1. build the project
initialiseProject("PR134471_2");
build("PR134471_2");
// Step2. confirm advice is from correct location
IProgramElement programElement = getFirstRelatedElement(findCode(checkForNode("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");
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(findCode(checkForNode("pkg","C",true)));
line = programElement.getSourceLocation().getLine();
assertTrue("advice should be at line 11 - but is at line "+line,line==11);
}
public void testAddingAndRemovingDecwWithStructureModel() {
configureBuildStructureModel(true);
initialiseProject("P3");
build("P3");
alter("P3","inc1");
build("P3");
assertTrue("There should be no exceptions handled:\n"+MyErrorHandler.getErrorMessages(),
MyErrorHandler.getErrorMessages().isEmpty());
alter("P3","inc2");
build("P3");
assertTrue("There should be no exceptions handled:\n"+MyErrorHandler.getErrorMessages(),
MyErrorHandler.getErrorMessages().isEmpty());
configureBuildStructureModel(false);
}
// 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 {
AsmHierarchyBuilder.shouldAddUsesPointcut=false;
configureBuildStructureModel(true);
configureNonStandardCompileOptions("-showWeaveInfo -emacssym");
// Step1. build the project
initialiseProject("PR134471");
build("PR134471");
// Step2. confirm advice is from correct location
IProgramElement programElement = getFirstRelatedElement(findCode(checkForNode("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");
// Step4. Quick check that the advice points to something...
IProgramElement nodeForTypeA = checkForNode("pkg","A",true);
IProgramElement nodeForAdvice = findAdvice(nodeForTypeA);
List relatedElements = getRelatedElements(nodeForAdvice,1);
// Step5. No change to the file C but it should still be advised afterwards
alter("PR134471","inc2");
build("PR134471");
checkWasntFullBuild();
// Step6. confirm advice is from correct location
programElement = getFirstRelatedElement(findCode(checkForNode("pkg","C",true)));
line = programElement.getSourceLocation().getLine();
assertTrue("advice should be at line 7 - but is at line "+line,line==7);
} finally {
AsmHierarchyBuilder.shouldAddUsesPointcut=true;
}
}
// similar to previous test but with 'declare warning' as well as advice
public void testPr134471_IncrementallyRecompilingAspectContainingDeclare() {
configureBuildStructureModel(true);
configureNonStandardCompileOptions("-showWeaveInfo -emacssym");
// Step1. build the project
initialiseProject("PR134471_3");
build("PR134471_3");
checkWasFullBuild();
// Step2. confirm declare warning is from correct location, decw matches line 7 in pkg.C
IProgramElement programElement = getFirstRelatedElement(findCode(checkForNode("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(findCode(checkForNode("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");
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(findCode(checkForNode("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();
// Step7. confirm declare warning is from correct location, decw (now at line 12) in pkg.A matches line 7 in pkg.C
programElement = getFirstRelatedElement(findCode(checkForNode("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() {
configureBuildStructureModel(true);
configureNonStandardCompileOptions("-showWeaveInfo -emacssym");
// Step1. build the project
initialiseProject("PR134471_3");
build("PR134471_3");
checkWasFullBuild();
// Step2. confirm declare warning is from correct location, decw matches line 7 in pkg.C
IProgramElement programElement = getFirstRelatedElement(findCode(checkForNode("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(findCode(checkForNode("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");
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(findCode(checkForNode("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();
// Step7. confirm declare warning is from correct location, decw (now at line 12) in pkg.A matches line 7 in pkg.C
programElement = getFirstRelatedElement(findCode(checkForNode("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(findCode(checkForNode("pkg","C",true),7));
line = programElement.getSourceLocation().getLine();
assertTrue("declare warning should be at line 12 - but is at line "+line,line==12);
}
// --- 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/*IProgramElement*/ getRelatedElements(IProgramElement programElement,int expected) {
List relatedElements = getRelatedElements(programElement);
StringBuffer debugString = new StringBuffer();
if (relatedElements!=null) {
for (Iterator iter = relatedElements.iterator(); iter.hasNext();) {
String element = (String) iter.next();
debugString.append(AsmManager.getDefault().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(IProgramElement programElement) {
List rels = getRelatedElements(programElement,1);
return AsmManager.getDefault().getHierarchy().findElementForHandle((String)rels.get(0));
}
private List/*IProgramElement*/ getRelatedElements(IProgramElement advice) {
List output = null;
IRelationshipMap map = AsmManager.getDefault().getRelationshipMap();
List/*IRelationship*/ rels = (List)map.get(advice);
if (rels==null) fail("Did not find any related elements!");
for (Iterator iter = rels.iterator(); iter.hasNext();) {
IRelationship element = (IRelationship) iter.next();
List/*String*/ targets = element.getTargets();
if (output==null) output = new ArrayList();
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 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
// ---------------------------------------------------------------------------------------------------
/**
* Check we compiled/wove the right number of files, passing '-1' indicates you don't care about
* that number.
*/
private void checkCompileWeaveCount(int expCompile,int expWoven) {
if (expCompile!=-1 && getCompiledFiles().size()!=expCompile)
fail("Expected compilation of "+expCompile+" files but compiled "+getCompiledFiles().size()+
"\n"+printCompiledAndWovenFiles());
if (expWoven!=-1 && getWovenClasses().size()!=expWoven)
fail("Expected weaving of "+expWoven+" files but wove "+getWovenClasses().size()+
"\n"+printCompiledAndWovenFiles());
}
private void checkWasntFullBuild() {
assertTrue("Shouldn't have been a full (batch) build",!wasFullBuild());
}
private void checkWasFullBuild() {
assertTrue("Should have been a full (batch) build",wasFullBuild());
}
private IProgramElement checkForNode(String packageName,String typeName,boolean shouldBeFound) {
IProgramElement ipe = AsmManager.getDefault().getHierarchy().findElementForType(packageName,typeName);
if (shouldBeFound) {
if (ipe==null) printModel();
assertTrue("Should have been able to find '"+packageName+"."+typeName+"' in the asm",ipe!=null);
} else {
if (ipe!=null) printModel();
assertTrue("Should have NOT been able to find '"+packageName+"."+typeName+"' in the asm",ipe==null);
}
return ipe;
}
private void printModel() {
try {
AsmManager.dumptree(AsmManager.getDefault().getHierarchy().getRoot(),0);
} catch (IOException e) {
e.printStackTrace();
}
}
public void build(String projectName) {
constructUpToDateLstFile(projectName,"build.lst");
build(projectName,"build.lst");
if (AjdeInteractionTestbed.VERBOSE) printBuildReport();
}
public void fullBuild(String projectName) {
constructUpToDateLstFile(projectName,"build.lst");
fullBuild(projectName,"build.lst");
if (AjdeInteractionTestbed.VERBOSE) printBuildReport();
}
private void constructUpToDateLstFile(String pname,String configname) {
File projectBase = new File(sandboxDir,pname);
File toConstruct = new File(projectBase,configname);
List filesForCompilation = new ArrayList();
collectUpFiles(projectBase,projectBase,filesForCompilation);
try {
FileOutputStream fos = new FileOutputStream(toConstruct);
DataOutputStream dos = new DataOutputStream(fos);
for (Iterator iter = filesForCompilation.iterator(); iter.hasNext();) {
String file = (String) iter.next();
dos.writeBytes(file+"\n");
}
dos.close();
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
public void checkForError(String anError) {
List messages = MyTaskListManager.getErrorMessages();
for (Iterator iter = messages.iterator(); iter.hasNext();) {
IMessage element = (IMessage) iter.next();
if (element.getMessage().indexOf(anError)!=-1) return;
}
fail("Didn't find the error message:\n'"+anError+"'.\nErrors that occurred:\n"+MyTaskListManager.getErrorMessages());
}
private void collectUpFiles(File location,File base,List collectionPoint) {
String contents[] = location.list();
if (contents==null) return;
for (int i = 0; i < contents.length; i++) {
String string = contents[i];
File f = new File(location,string);
if (f.isDirectory()) {
collectUpFiles(f,base,collectionPoint);
} else if (f.isFile() && (f.getName().endsWith(".aj") || f.getName().endsWith(".java"))) {
String fileFound;
try {
fileFound = f.getCanonicalPath();
String toRemove = base.getCanonicalPath();
if (!fileFound.startsWith(toRemove)) throw new RuntimeException("eh? "+fileFound+" "+toRemove);
collectionPoint.add(fileFound.substring(toRemove.length()+1));//+1 captures extra separator
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
/**
* Fill in the working directory with the project base files,
* from the 'base' folder.
*/
protected void initialiseProject(String p) {
File projectSrc=new File(testdataSrcDir+File.separatorChar+p+File.separatorChar+"base");
File destination=new File(getWorkingDir(),p);
if (!destination.exists()) {destination.mkdir();}
copy(projectSrc,destination);//,false);
}
/*
* Applies an overlay onto the project being tested - copying
* the contents of the specified overlay directory.
*/
private void alter(String projectName,String overlayDirectory) {
File projectSrc =new File(testdataSrcDir+File.separatorChar+projectName+
File.separatorChar+overlayDirectory);
File destination=new File(getWorkingDir(),projectName);
copy(projectSrc,destination);
}
/**
* Copy the contents of some directory to another location - the
* copy is recursive.
*/
private void copy(File from, File to) {
String contents[] = from.list();
if (contents==null) return;
for (int i = 0; i < contents.length; i++) {
String string = contents[i];
File f = new File(from,string);
File t = new File(to,string);
if (f.isDirectory() && !f.getName().startsWith("inc")) {
t.mkdir();
copy(f,t);
} else if (f.isFile()) {
StringBuffer sb = new StringBuffer();
//if (VERBOSE) System.err.println("Copying "+f+" to "+t);
FileUtil.copyFile(f,t,sb);
if (sb.length()!=0) { System.err.println(sb.toString());}
}
}
}
private static void log(String msg) {
if (VERBOSE) System.out.println(msg);
}
/**
* Count the number of times a specified aspectName appears in the default
* aop.xml file and compare with the expected number of occurrences. If just
* want to count the number of aspects mentioned within the file then
* pass "" for the aspectName, otherwise, specify the name of the
* aspect interested in.
*/
private void checkXMLAspectCount(String projectName, String aspectName, int expectedOccurrences) {
int aspectCount = 0;
File aopXML = new File(getWorkingDir().getAbsolutePath()
+ File.separatorChar + projectName + File.separatorChar
+ "bin" + File.separatorChar + "META-INF" + File.separatorChar + "aop.xml");
if (!aopXML.exists()) {
fail("Expected file " + aopXML.getAbsolutePath() + " to exist but it doesn't");
}
try {
BufferedReader reader = new BufferedReader(new FileReader(aopXML));
String line = reader.readLine();
while (line != null) {
if (aspectName.equals("") && line.indexOf("aspect name=\"") != -1) {
aspectCount++;
} else if (line.indexOf("aspect name=\""+aspectName+"\"") != -1) {
aspectCount++;
}
line = reader.readLine();
}
reader.close();
} catch (IOException ie) {
ie.printStackTrace();
}
if (aspectCount != expectedOccurrences) {
fail("Expected aspect " + aspectName + " to appear " + expectedOccurrences + " times" +
" in the aop.xml file but found " + aspectCount + " occurrences");
}
}
private void dumpAJDEStructureModel(String prefix) {
System.out.println("======================================");//$NON-NLS-1$
System.out.println("start of AJDE structure model:"+prefix); //$NON-NLS-1$
IRelationshipMap asmRelMap = AsmManager.getDefault().getRelationshipMap();
for (Iterator iter = asmRelMap.getEntries().iterator(); iter.hasNext();) {
String sourceOfRelationship = (String) iter.next();
IProgramElement ipe = AsmManager.getDefault().getHierarchy()
.findElementForHandle(sourceOfRelationship);
System.err.println("Examining source relationship handle: "+sourceOfRelationship);
List relationships = asmRelMap.get(ipe);
if (relationships != null) {
for (Iterator iterator = relationships.iterator(); iterator.hasNext();) {
Relationship rel = (Relationship) iterator.next();
List targets = rel.getTargets();
for (Iterator iterator2 = targets.iterator(); iterator2.hasNext();) {
String t = (String) iterator2.next();
IProgramElement link = AsmManager.getDefault().getHierarchy().findElementForHandle(t);
System.out.println(""); //$NON-NLS-1$
System.out.println(" sourceOfRelationship " + sourceOfRelationship); //$NON-NLS-1$
System.out.println(" relationship " + rel.getName()); //$NON-NLS-1$
System.out.println(" target " + link.getName()); //$NON-NLS-1$
}
}
}
}
System.out.println("End of AJDE structure model"); //$NON-NLS-1$
System.out.println("======================================");//$NON-NLS-1$
}
}
|
141,956 |
Bug 141956 Null Pointer Exception when trying to skip Parent Mungers.
|
I don't know much about the internal workings of aspectJ but this bug keeps popping up so I went through the trouble of checking of trying to debug it so that I could hopefully provide enough information to get it fixed. This happens while using eclipse AJDT. It never happens if I fully do a clean before rebuild. It only seems to happen when doing incrmental builds (using the project->build automatically setting). The error happens in the iterator that recursively builds a list of methods to return for matching. The error is triggered here: // we need to know if it is an interface from Parent kind munger // as those are used for @AJ ITD and we precisely want to skip those boolean shouldSkip = false; for (int j = 0; j < rtx.interTypeMungers.size(); j++) { ConcreteTypeMunger munger = (ConcreteTypeMunger) rtx.interTypeMungers.get(j); if (munger.getMunger().getKind() == ResolvedTypeMunger.Parent) { shouldSkip = true; break; } } munger.getMunger() returns null because the munger instance is a BcelPerClauseAspectAdder. My naive fix would be to check munger.getMunger() == null or check munger.getKind(). I'm assuming that BcelPerClausAspectAdder is one that should be skipped since it is related to @AJ ??? Again, I don't know very much about the internal architecture of the weaver magic so I hope this is enough information. I would appreciate it if someone who knows more of the internals could speculate as to why this bug would never pop up on a clean build but only on incremental builds? Also it's not on all incremental builds and I haven't been able to isolate what kind of changes or compiles it triggers this, although it seems that once I got the exception once, I keep getting it on every build until I do a clean. java.lang.NullPointerException at org.aspectj.weaver.ResolvedType.addAndRecurse(ResolvedType.java:288) at org.aspectj.weaver.ResolvedType.getMethodsWithoutIterator(ResolvedType.java:257) at org.aspectj.weaver.ResolvedType.lookupResolvedMember(ResolvedType.java:378) at org.aspectj.weaver.JoinPointSignatureIterator.findSignaturesFromSupertypes(JoinPointSignatureIterator.java:178) at org.aspectj.weaver.JoinPointSignatureIterator.hasNext(JoinPointSignatureIterator.java:69) at org.aspectj.weaver.patterns.SignaturePattern.matches(SignaturePattern.java:287) at org.aspectj.weaver.patterns.KindedPointcut.matchInternal(KindedPointcut.java:103) at org.aspectj.weaver.patterns.Pointcut.match(Pointcut.java:144) at org.aspectj.weaver.patterns.AndPointcut.matchInternal(AndPointcut.java:51) at org.aspectj.weaver.patterns.Pointcut.match(Pointcut.java:144) at org.aspectj.weaver.ShadowMunger.match(ShadowMunger.java:64) at org.aspectj.weaver.Advice.match(Advice.java:109) at org.aspectj.weaver.bcel.BcelAdvice.match(BcelAdvice.java:104) at org.aspectj.weaver.bcel.BcelClassWeaver.match(BcelClassWeaver.java:2210) at org.aspectj.weaver.bcel.BcelClassWeaver.match(BcelClassWeaver.java:1752) at org.aspectj.weaver.bcel.BcelClassWeaver.weave(BcelClassWeaver.java:479) at org.aspectj.weaver.bcel.BcelClassWeaver.weave(BcelClassWeaver.java:109) at org.aspectj.weaver.bcel.BcelWeaver.weave(BcelWeaver.java:1574) at org.aspectj.weaver.bcel.BcelWeaver.weaveWithoutDump(BcelWeaver.java:1525) at org.aspectj.weaver.bcel.BcelWeaver.weaveAndNotify(BcelWeaver.java:1305) at org.aspectj.weaver.bcel.BcelWeaver.weave(BcelWeaver.java:1127) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.weave(AjCompilerAdapter.java:321) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.afterCompiling(AjCompilerAdapter.java:192) at org.aspectj.ajdt.internal.compiler.CompilerAdapter.ajc$afterReturning$org_aspectj_ajdt_internal_compiler_CompilerAdapter$2$f9cc9ca0(CompilerAdapter.aj:70) at org.aspectj.org.eclipse.jdt.internal.compiler.Compiler.compile(Compiler.java:367) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.performCompilation(AjBuildManager.java:862) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.doBuild(AjBuildManager.java:269) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.incrementalBuild(AjBuildManager.java:168) at org.aspectj.ajde.internal.CompilerAdapter.compile(CompilerAdapter.java:117) at org.aspectj.ajde.internal.AspectJBuildManager$CompilerThread.run(AspectJBuildManager.java:191)
|
resolved fixed
|
5f6a6b1
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-05-17T11:38:39Z | 2006-05-16T09:00:00Z |
weaver/src/org/aspectj/weaver/ResolvedType.java
|
/* *******************************************************************
* Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC).
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* PARC initial implementation
* Alexandre Vasseur @AspectJ ITDs
* ******************************************************************/
package org.aspectj.weaver;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.aspectj.bridge.IMessage;
import org.aspectj.bridge.ISourceLocation;
import org.aspectj.bridge.Message;
import org.aspectj.bridge.MessageUtil;
import org.aspectj.util.FuzzyBoolean;
import org.aspectj.weaver.patterns.Declare;
import org.aspectj.weaver.patterns.PerClause;
public abstract class ResolvedType extends UnresolvedType implements AnnotatedElement {
private static final ResolvedType[] EMPTY_RESOLVED_TYPE_ARRAY = new ResolvedType[0];
public static final String PARAMETERIZED_TYPE_IDENTIFIER = "P";
private ResolvedType[] resolvedTypeParams;
protected World world;
protected ResolvedType(String signature, World world) {
super(signature);
this.world = world;
}
protected ResolvedType(String signature, String signatureErasure, World world) {
super(signature,signatureErasure);
this.world = world;
}
// ---- things that don't require a world
/**
* Returns an iterator through ResolvedType objects representing all the direct
* supertypes of this type. That is, through the superclass, if any, and
* all declared interfaces.
*/
public final Iterator getDirectSupertypes() {
Iterator ifacesIterator = Iterators.array(getDeclaredInterfaces());
ResolvedType superclass = getSuperclass();
if (superclass == null) {
return ifacesIterator;
} else {
return Iterators.snoc(ifacesIterator, superclass);
}
}
public abstract ResolvedMember[] getDeclaredFields();
public abstract ResolvedMember[] getDeclaredMethods();
public abstract ResolvedType[] getDeclaredInterfaces();
public abstract ResolvedMember[] getDeclaredPointcuts();
/**
* Returns a ResolvedType object representing the superclass of this type, or null.
* If this represents a java.lang.Object, a primitive type, or void, this
* method returns null.
*/
public abstract ResolvedType getSuperclass();
/**
* Returns the modifiers for this type.
* <p/>
* See {@link Class#getModifiers()} for a description
* of the weirdness of this methods on primitives and arrays.
*
* @param world the {@link World} in which the lookup is made.
* @return an int representing the modifiers for this type
* @see java.lang.reflect.Modifier
*/
public abstract int getModifiers();
// return true if this resolved type couldn't be found (but we know it's name maybe)
public boolean isMissing() {
return false;
}
// 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 final UnresolvedType getSuperclass(World world) {
return getSuperclass();
}
// This set contains pairs of types whose signatures are concatenated
// together, this means with a fast lookup we can tell if two types
// are equivalent.
static Set validBoxing = new HashSet();
static {
validBoxing.add("Ljava/lang/Byte;B");
validBoxing.add("Ljava/lang/Character;C");
validBoxing.add("Ljava/lang/Double;D");
validBoxing.add("Ljava/lang/Float;F");
validBoxing.add("Ljava/lang/Integer;I");
validBoxing.add("Ljava/lang/Long;J");
validBoxing.add("Ljava/lang/Short;S");
validBoxing.add("Ljava/lang/Boolean;Z");
validBoxing.add("BLjava/lang/Byte;");
validBoxing.add("CLjava/lang/Character;");
validBoxing.add("DLjava/lang/Double;");
validBoxing.add("FLjava/lang/Float;");
validBoxing.add("ILjava/lang/Integer;");
validBoxing.add("JLjava/lang/Long;");
validBoxing.add("SLjava/lang/Short;");
validBoxing.add("ZLjava/lang/Boolean;");
}
// utilities
public ResolvedType getResolvedComponentType() {
return null;
}
public World getWorld() {
return world;
}
// ---- things from object
public final boolean equals(Object other) {
if (other instanceof ResolvedType) {
return this == other;
} else {
return super.equals(other);
}
}
// ---- difficult things
/**
* returns an iterator through all of the fields of this type, in order
* for checking from JVM spec 2ed 5.4.3.2. This means that the order is
* <p/>
* <ul><li> fields from current class </li>
* <li> recur into direct superinterfaces </li>
* <li> recur into superclass </li>
* </ul>
* <p/>
* We keep a hashSet of interfaces that we've visited so we don't spiral
* out into 2^n land.
*/
public Iterator getFields() {
final Iterators.Filter dupFilter = Iterators.dupFilter();
Iterators.Getter typeGetter = new Iterators.Getter() {
public Iterator get(Object o) {
return
dupFilter.filter(
((ResolvedType)o).getDirectSupertypes());
}
};
Iterators.Getter fieldGetter = new Iterators.Getter() {
public Iterator get(Object o) {
return Iterators.array(((ResolvedType)o).getDeclaredFields());
}
};
return
Iterators.mapOver(
Iterators.recur(this, typeGetter),
fieldGetter);
}
/**
* returns an iterator through all of the methods of this type, in order
* for checking from JVM spec 2ed 5.4.3.3. This means that the order is
* <p/>
* <ul><li> methods from current class </li>
* <li> recur into superclass, all the way up, not touching interfaces </li>
* <li> recur into all superinterfaces, in some unspecified order </li>
* </ul>
* <p/>
* We keep a hashSet of interfaces that we've visited so we don't spiral
* out into 2^n land.
* NOTE: Take a look at the javadoc on getMethodsWithoutIterator() to see if
* you are sensitive to a quirk in getMethods()
*/
public Iterator getMethods() {
final Iterators.Filter dupFilter = Iterators.dupFilter();
Iterators.Getter ifaceGetter = new Iterators.Getter() {
public Iterator get(Object o) {
return
dupFilter.filter(
Iterators.array(((ResolvedType)o).getDeclaredInterfaces())
);
}
};
Iterators.Getter methodGetter = new Iterators.Getter() {
public Iterator get(Object o) {
return Iterators.array(((ResolvedType)o).getDeclaredMethods());
}
};
return
Iterators.mapOver(
Iterators.append(
new Iterator() {
ResolvedType curr = ResolvedType.this;
public boolean hasNext() {
return curr != null;
}
public Object next() {
ResolvedType ret = curr;
curr = curr.getSuperclass();
return ret;
}
public void remove() {
throw new UnsupportedOperationException();
}
},
Iterators.recur(this, ifaceGetter)),
methodGetter);
}
/**
* Return a list of methods, first those declared on this class, then those declared on the superclass (recurse) and then those declared
* on the superinterfaces. The getMethods() call above doesn't quite work the same as it will (through the iterator) return methods
* declared on *this* class twice, once at the start and once at the end - I couldn't debug that problem, so created this alternative.
*/
public List getMethodsWithoutIterator(boolean includeITDs, boolean allowMissing) {
List methods = new ArrayList();
Set knowninterfaces = new HashSet();
addAndRecurse(knowninterfaces,methods,this,includeITDs,allowMissing);
return methods;
}
private void addAndRecurse(Set knowninterfaces,List collector, ResolvedType rtx, boolean includeITDs, boolean allowMissing) {
collector.addAll(Arrays.asList(rtx.getDeclaredMethods())); // Add the methods declared on this type
// now add all the inter-typed members too
if (includeITDs && rtx.interTypeMungers != null) {
for (Iterator i = interTypeMungers.iterator(); i.hasNext();) {
ConcreteTypeMunger tm = (ConcreteTypeMunger) i.next();
ResolvedMember rm = tm.getSignature();
if (rm != null) { // new parent type munger can have null signature...
collector.add(tm.getSignature());
}
}
}
if (!rtx.equals(ResolvedType.OBJECT)) {
ResolvedType superType = rtx.getSuperclass();
if (superType != null && !superType.isMissing()) {
addAndRecurse(knowninterfaces,collector,superType,includeITDs,allowMissing); // Recurse if we aren't at the top
}
}
ResolvedType[] interfaces = rtx.getDeclaredInterfaces(); // Go through the interfaces on the way back down
for (int i = 0; i < interfaces.length; i++) {
ResolvedType iface = interfaces[i];
// we need to know if it is an interface from Parent kind munger
// as those are used for @AJ ITD and we precisely want to skip those
boolean shouldSkip = false;
for (int j = 0; j < rtx.interTypeMungers.size(); j++) {
ConcreteTypeMunger munger = (ConcreteTypeMunger) rtx.interTypeMungers.get(j);
if (munger.getMunger().getKind() == ResolvedTypeMunger.Parent) {
shouldSkip = true;
break;
}
}
if (!shouldSkip && !knowninterfaces.contains(iface)) { // Dont do interfaces more than once
knowninterfaces.add(iface);
if (allowMissing && iface.isMissing()) {
if (iface instanceof MissingResolvedTypeWithKnownSignature) {
((MissingResolvedTypeWithKnownSignature)iface).raiseWarningOnMissingInterfaceWhilstFindingMethods();
}
} else {
addAndRecurse(knowninterfaces,collector,iface,includeITDs,allowMissing);
}
}
}
}
public ResolvedType[] getResolvedTypeParameters() {
if (resolvedTypeParams == null) {
resolvedTypeParams = world.resolve(typeParameters);
}
return resolvedTypeParams;
}
/**
* described in JVM spec 2ed 5.4.3.2
*/
public ResolvedMember lookupField(Member m) {
return lookupMember(m, getFields());
}
/**
* described in JVM spec 2ed 5.4.3.3.
* Doesnt check ITDs.
*/
public ResolvedMember lookupMethod(Member m) {
return lookupMember(m, getMethods());
}
public ResolvedMember lookupMethodInITDs(Member m) {
if (interTypeMungers != null) {
for (Iterator i = interTypeMungers.iterator(); i.hasNext();) {
ConcreteTypeMunger tm = (ConcreteTypeMunger) i.next();
if (matches(tm.getSignature(), m)) {
return tm.getSignature();
}
}
}
return null;
}
/**
* return null if not found
*/
private ResolvedMember lookupMember(Member m, Iterator i) {
while (i.hasNext()) {
ResolvedMember f = (ResolvedMember) i.next();
if (matches(f, m)) return f;
if (f.hasBackingGenericMember() && m.getName().equals(f.getName())) { // might be worth checking the method behind the parameterized method (see pr137496)
if (matches(f.getBackingGenericMember(),m)) return f;
}
}
return null; //ResolvedMember.Missing;
//throw new BCException("can't find " + m);
}
/**
* return null if not found
*/
private ResolvedMember lookupMember(Member m, ResolvedMember[] a) {
for (int i = 0; i < a.length; i++) {
ResolvedMember f = a[i];
if (matches(f, m)) return f;
}
return null;
}
/**
* Looks for the first member in the hierarchy matching aMember. This method
* differs from lookupMember(Member) in that it takes into account parameters
* which are type variables - which clearly an unresolved Member cannot do since
* it does not know anything about type variables.
*/
public ResolvedMember lookupResolvedMember(ResolvedMember aMember,boolean allowMissing) {
Iterator toSearch = null;
ResolvedMember found = null;
if ((aMember.getKind() == Member.METHOD) || (aMember.getKind() == Member.CONSTRUCTOR)) {
toSearch = getMethodsWithoutIterator(true,allowMissing).iterator();
} else {
if (aMember.getKind() != Member.FIELD)
throw new IllegalStateException("I didn't know you would look for members of kind " + aMember.getKind());
toSearch = getFields();
}
while(toSearch.hasNext()) {
ResolvedMemberImpl candidate = (ResolvedMemberImpl) toSearch.next();
if (candidate.matches(aMember)) {
found = candidate;
break;
}
}
return found;
}
public static boolean matches(Member m1, Member m2) {
if (m1 == null) return m2 == null;
if (m2 == null) return false;
// Check the names
boolean equalNames = m1.getName().equals(m2.getName());
if (!equalNames) return false;
// Check the signatures
boolean equalSignatures = m1.getSignature().equals(m2.getSignature());
if (equalSignatures) return true;
// If they aren't the same, we need to allow for covariance ... where one sig might be ()LCar; and
// the subsig might be ()LFastCar; - where FastCar is a subclass of Car
boolean equalCovariantSignatures = m1.getParameterSignature().equals(m2.getParameterSignature());
if (equalCovariantSignatures) return true;
return false;
}
public static boolean conflictingSignature(Member m1, Member m2) {
if (m1 == null || m2 == null) return false;
if (!m1.getName().equals(m2.getName())) {
return false;
}
if (m1.getKind() != m2.getKind()) {
return false;
}
if (m1.getKind() == Member.FIELD) {
return m1.getDeclaringType().equals(m2.getDeclaringType());
} else if (m1.getKind() == Member.POINTCUT) {
return true;
}
UnresolvedType[] p1 = m1.getParameterTypes();
UnresolvedType[] p2 = m2.getParameterTypes();
int n = p1.length;
if (n != p2.length) return false;
for (int i=0; i < n; i++) {
if (!p1[i].equals(p2[i])) return false;
}
return true;
}
/**
* returns an iterator through all of the pointcuts of this type, in order
* for checking from JVM spec 2ed 5.4.3.2 (as for fields). This means that the order is
* <p/>
* <ul><li> pointcuts from current class </li>
* <li> recur into direct superinterfaces </li>
* <li> recur into superclass </li>
* </ul>
* <p/>
* We keep a hashSet of interfaces that we've visited so we don't spiral
* out into 2^n land.
*/
public Iterator getPointcuts() {
final Iterators.Filter dupFilter = Iterators.dupFilter();
// same order as fields
Iterators.Getter typeGetter = new Iterators.Getter() {
public Iterator get(Object o) {
return
dupFilter.filter(
((ResolvedType)o).getDirectSupertypes());
}
};
Iterators.Getter pointcutGetter = new Iterators.Getter() {
public Iterator get(Object o) {
//System.err.println("getting for " + o);
return Iterators.array(((ResolvedType)o).getDeclaredPointcuts());
}
};
return
Iterators.mapOver(
Iterators.recur(this, typeGetter),
pointcutGetter);
}
public ResolvedPointcutDefinition findPointcut(String name) {
//System.err.println("looking for pointcuts " + this);
for (Iterator i = getPointcuts(); i.hasNext(); ) {
ResolvedPointcutDefinition f = (ResolvedPointcutDefinition) i.next();
//System.err.println(f);
if (name.equals(f.getName())) {
return f;
}
}
// 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);
crosscuttingMembers.setPerClause(getPerClause());
crosscuttingMembers.addShadowMungers(collectShadowMungers());
crosscuttingMembers.addTypeMungers(getTypeMungers());
//FIXME AV - skip but needed ?? or ?? crosscuttingMembers.addLateTypeMungers(getLateTypeMungers());
crosscuttingMembers.addDeclares(collectDeclares(!this.doesNotExposeShadowMungers()));
crosscuttingMembers.addPrivilegedAccesses(getPrivilegedAccesses());
//System.err.println("collected cc members: " + this + ", " + collectDeclares());
return crosscuttingMembers;
}
public final Collection collectDeclares(boolean includeAdviceLike) {
if (! this.isAspect() ) return Collections.EMPTY_LIST;
ArrayList ret = new ArrayList();
//if (this.isAbstract()) {
// for (Iterator i = getDeclares().iterator(); i.hasNext();) {
// Declare dec = (Declare) i.next();
// if (!dec.isAdviceLike()) ret.add(dec);
// }
//
// if (!includeAdviceLike) return ret;
if (!this.isAbstract()) {
//ret.addAll(getDeclares());
final Iterators.Filter dupFilter = Iterators.dupFilter();
Iterators.Getter typeGetter = new Iterators.Getter() {
public Iterator get(Object o) {
return
dupFilter.filter(
((ResolvedType)o).getDirectSupertypes());
}
};
Iterator typeIterator = Iterators.recur(this, typeGetter);
while (typeIterator.hasNext()) {
ResolvedType ty = (ResolvedType) typeIterator.next();
//System.out.println("super: " + ty + ", " + );
for (Iterator i = ty.getDeclares().iterator(); i.hasNext();) {
Declare dec = (Declare) i.next();
if (dec.isAdviceLike()) {
if (includeAdviceLike) ret.add(dec);
} else {
ret.add(dec);
}
}
}
}
return ret;
}
private final Collection collectShadowMungers() {
if (! this.isAspect() || this.isAbstract() || this.doesNotExposeShadowMungers()) return Collections.EMPTY_LIST;
ArrayList acc = new ArrayList();
final Iterators.Filter dupFilter = Iterators.dupFilter();
Iterators.Getter typeGetter = new Iterators.Getter() {
public Iterator get(Object o) {
return
dupFilter.filter(
((ResolvedType)o).getDirectSupertypes());
}
};
Iterator typeIterator = Iterators.recur(this, typeGetter);
while (typeIterator.hasNext()) {
ResolvedType ty = (ResolvedType) typeIterator.next();
acc.addAll(ty.getDeclaredShadowMungers());
}
return acc;
}
protected boolean doesNotExposeShadowMungers() {
return false;
}
public PerClause getPerClause() {
return null;
}
protected Collection getDeclares() {
return Collections.EMPTY_LIST;
}
protected Collection getTypeMungers() {
return Collections.EMPTY_LIST;
}
protected Collection getPrivilegedAccesses() {
return Collections.EMPTY_LIST;
}
// ---- useful things
public final boolean isInterface() {
return Modifier.isInterface(getModifiers());
}
public final boolean isAbstract() {
return Modifier.isAbstract(getModifiers());
}
public boolean isClass() {
return false;
}
public boolean isAspect() {
return false;
}
public boolean isAnnotationStyleAspect() {
return false;
}
/**
* Note: Only overridden by Name subtype.
*/
public boolean isEnum() {
return false;
}
/**
* Note: Only overridden by Name subtype.
*/
public boolean isAnnotation() {
return false;
}
public boolean isAnonymous() {
return false;
}
public boolean isNested() {
return false;
}
/**
* Note: Only overridden by Name subtype
*/
public void addAnnotation(AnnotationX annotationX) {
throw new RuntimeException("ResolvedType.addAnnotation() should never be called");
}
/**
* Note: Only overridden by Name subtype
*/
public AnnotationX[] getAnnotations() {
throw new RuntimeException("ResolvedType.getAnnotations() should never be called");
}
/**
* Note: Only overridden by ReferenceType subtype
*/
public boolean canAnnotationTargetType() {
return false;
}
/**
* Note: Only overridden by ReferenceType subtype
*/
public AnnotationTargetKind[] getAnnotationTargetKinds() {
return null;
}
/**
* Note: Only overridden by Name subtype.
*/
public boolean isAnnotationWithRuntimeRetention() {
return false;
}
public boolean isSynthetic() {
return signature.indexOf("$ajc") != -1;
}
public final boolean isFinal() {
return Modifier.isFinal(getModifiers());
}
protected Map /*Type variable name -> UnresolvedType*/ getMemberParameterizationMap() {
if (!isParameterizedType()) return Collections.EMPTY_MAP;
TypeVariable[] tvs = getGenericType().getTypeVariables();
Map parameterizationMap = new HashMap();
for (int i = 0; i < tvs.length; i++) {
parameterizationMap.put(tvs[i].getName(), typeParameters[i]);
}
return parameterizationMap;
}
public Collection getDeclaredAdvice() {
List l = new ArrayList();
ResolvedMember[] methods = getDeclaredMethods();
if (isParameterizedType()) methods = getGenericType().getDeclaredMethods();
Map typeVariableMap = 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] = (UnresolvedType) typeVariableMap.get(tvrt.getTypeVariable().getName());
} else {
newPTypes[j] = ptypes[j];
}
} else {
newPTypes[j] = ptypes[j];
}
}
advice.setBindingParameterTypes(newPTypes);
}
}
munger.setDeclaringType(this);
l.add(munger);
}
}
return l;
}
public Collection getDeclaredShadowMungers() {
Collection c = getDeclaredAdvice();
return c;
}
// ---- only for testing!
public ResolvedMember[] getDeclaredJavaFields() {
return filterInJavaVisible(getDeclaredFields());
}
public ResolvedMember[] getDeclaredJavaMethods() {
return filterInJavaVisible(getDeclaredMethods());
}
public ShadowMunger[] getDeclaredShadowMungersArray() {
List l = (List) getDeclaredShadowMungers();
return (ShadowMunger[]) l.toArray(new ShadowMunger[l.size()]);
}
private ResolvedMember[] filterInJavaVisible(ResolvedMember[] ms) {
List l = new ArrayList();
for (int i=0, len = ms.length; i < len; i++) {
if (! ms[i].isAjSynthetic() && ms[i].getAssociatedShadowMunger() == null) {
l.add(ms[i]);
}
}
return (ResolvedMember[]) l.toArray(new ResolvedMember[l.size()]);
}
public abstract ISourceContext getSourceContext();
// ---- fields
public static final ResolvedType[] NONE = new ResolvedType[0];
public static final Primitive BYTE = new Primitive("B", 1, 0);
public static final Primitive CHAR = new Primitive("C", 1, 1);
public static final Primitive DOUBLE = new Primitive("D", 2, 2);
public static final Primitive FLOAT = new Primitive("F", 1, 3);
public static final Primitive INT = new Primitive("I", 1, 4);
public static final Primitive LONG = new Primitive("J", 2, 5);
public static final Primitive SHORT = new Primitive("S", 1, 6);
public static final Primitive VOID = new Primitive("V", 0, 8);
public static final Primitive BOOLEAN = new Primitive("Z", 1, 7);
public static final Missing MISSING = new Missing();
/** Reset the static state in the primitive types */
public static void resetPrimitives() {
BYTE.world=null;
CHAR.world=null;
DOUBLE.world=null;
FLOAT.world=null;
INT.world=null;
LONG.world=null;
SHORT.world=null;
VOID.world=null;
BOOLEAN.world=null;
}
// ---- types
public static ResolvedType makeArray(ResolvedType type, int dim) {
if (dim == 0) return type;
ResolvedType array = new Array("[" + type.getSignature(),"["+type.getErasureSignature(),type.getWorld(),type);
return makeArray(array,dim-1);
}
static class Array extends ResolvedType {
ResolvedType componentType;
// Sometimes the erasure is different, eg. [TT; and [Ljava/lang/Object;
Array(String sig, String erasureSig,World world, ResolvedType componentType) {
super(sig,erasureSig, world);
this.componentType = componentType;
}
public final ResolvedMember[] getDeclaredFields() {
return ResolvedMember.NONE;
}
public final ResolvedMember[] getDeclaredMethods() {
// ??? should this return clone? Probably not...
// If it ever does, here is the code:
// ResolvedMember cloneMethod =
// new ResolvedMember(Member.METHOD,this,Modifier.PUBLIC,UnresolvedType.OBJECT,"clone",new UnresolvedType[]{});
// return new ResolvedMember[]{cloneMethod};
return ResolvedMember.NONE;
}
public final ResolvedType[] getDeclaredInterfaces() {
return
new ResolvedType[] {
world.getCoreType(CLONEABLE),
world.getCoreType(SERIALIZABLE)
};
}
public final ResolvedMember[] getDeclaredPointcuts() {
return ResolvedMember.NONE;
}
public boolean hasAnnotation(UnresolvedType ofType) {
return false;
}
public final ResolvedType getSuperclass() {
return world.getCoreType(OBJECT);
}
public final boolean isAssignableFrom(ResolvedType o) {
if (! o.isArray()) return false;
if (o.getComponentType().isPrimitiveType()) {
return o.equals(this);
} else {
return getComponentType().resolve(world).isAssignableFrom(o.getComponentType().resolve(world));
}
}
public boolean isAssignableFrom(ResolvedType o, boolean allowMissing) {
return isAssignableFrom(o);
}
public final boolean isCoerceableFrom(ResolvedType o) {
if (o.equals(UnresolvedType.OBJECT) ||
o.equals(UnresolvedType.SERIALIZABLE) ||
o.equals(UnresolvedType.CLONEABLE)) {
return true;
}
if (! o.isArray()) return false;
if (o.getComponentType().isPrimitiveType()) {
return o.equals(this);
} else {
return getComponentType().resolve(world).isCoerceableFrom(o.getComponentType().resolve(world));
}
}
public final int getModifiers() {
int mask = Modifier.PUBLIC | Modifier.PRIVATE | Modifier.PROTECTED;
return (componentType.getModifiers() & mask) | Modifier.FINAL;
}
public UnresolvedType getComponentType() {
return componentType;
}
public ResolvedType getResolvedComponentType() {
return componentType;
}
public ISourceContext getSourceContext() {
return getResolvedComponentType().getSourceContext();
}
}
static class Primitive extends ResolvedType {
private int size;
private int index;
Primitive(String signature, int size, int index) {
super(signature, null);
this.size = size;
this.index = index;
this.typeKind=TypeKind.PRIMITIVE;
}
public final int getSize() {
return size;
}
public final int getModifiers() {
return Modifier.PUBLIC | Modifier.FINAL;
}
public final boolean isPrimitiveType() {
return true;
}
public boolean hasAnnotation(UnresolvedType ofType) {
return false;
}
public final boolean isAssignableFrom(ResolvedType other) {
if (!other.isPrimitiveType()) {
if (!world.isInJava5Mode()) return false;
return validBoxing.contains(this.getSignature()+other.getSignature());
}
return assignTable[((Primitive)other).index][index];
}
public final boolean isAssignableFrom(ResolvedType other, boolean allowMissing) {
return isAssignableFrom(other);
}
public final boolean isCoerceableFrom(ResolvedType other) {
if (this == other) return true;
if (! other.isPrimitiveType()) return false;
if (index > 6 || ((Primitive)other).index > 6) return false;
return true;
}
public ResolvedType resolve(World world) {
this.world = world;
return super.resolve(world);
}
public final boolean needsNoConversionFrom(ResolvedType other) {
if (! other.isPrimitiveType()) return false;
return noConvertTable[((Primitive)other).index][index];
}
private static final boolean[][] assignTable =
{// to: B C D F I J S V Z from
{ true , true , true , true , true , true , true , false, false }, // B
{ false, true , true , true , true , true , false, false, false }, // C
{ false, false, true , false, false, false, false, false, false }, // D
{ false, false, true , true , false, false, false, false, false }, // F
{ false, false, true , true , true , true , false, false, false }, // I
{ false, false, true , true , false, true , false, false, false }, // J
{ false, false, true , true , true , true , true , false, false }, // S
{ false, false, false, false, false, false, false, true , false }, // V
{ false, false, false, false, false, false, false, false, true }, // Z
};
private static final boolean[][] noConvertTable =
{// to: B C D F I J S V Z from
{ true , true , false, false, true , false, true , false, false }, // B
{ false, true , false, false, true , false, false, false, false }, // C
{ false, false, true , false, false, false, false, false, false }, // D
{ false, false, false, true , false, false, false, false, false }, // F
{ false, false, false, false, true , false, false, false, false }, // I
{ false, false, false, false, false, true , false, false, false }, // J
{ false, false, false, false, true , false, true , false, false }, // S
{ false, false, false, false, false, false, false, true , false }, // V
{ false, false, false, false, false, false, false, false, true }, // Z
};
// ----
public final ResolvedMember[] getDeclaredFields() {
return ResolvedMember.NONE;
}
public final ResolvedMember[] getDeclaredMethods() {
return ResolvedMember.NONE;
}
public final ResolvedType[] getDeclaredInterfaces() {
return ResolvedType.NONE;
}
public final ResolvedMember[] getDeclaredPointcuts() {
return ResolvedMember.NONE;
}
public final ResolvedType getSuperclass() {
return null;
}
public ISourceContext getSourceContext() {
return null;
}
}
static class Missing extends ResolvedType {
Missing() {
super(MISSING_NAME, null);
}
// public final String toString() {
// return "<missing>";
// }
public final String getName() {
return MISSING_NAME;
}
public final boolean isMissing() {
return true;
}
public boolean hasAnnotation(UnresolvedType ofType) {
return false;
}
public final ResolvedMember[] getDeclaredFields() {
return ResolvedMember.NONE;
}
public final ResolvedMember[] getDeclaredMethods() {
return ResolvedMember.NONE;
}
public final ResolvedType[] getDeclaredInterfaces() {
return ResolvedType.NONE;
}
public final ResolvedMember[] getDeclaredPointcuts() {
return ResolvedMember.NONE;
}
public final ResolvedType getSuperclass() {
return null;
}
public final int getModifiers() {
return 0;
}
public final boolean isAssignableFrom(ResolvedType other) {
return false;
}
public final boolean isAssignableFrom(ResolvedType other, boolean allowMissing) {
return false;
}
public final boolean isCoerceableFrom(ResolvedType other) {
return false;
}
public boolean needsNoConversionFrom(ResolvedType other) {
return false;
}
public ISourceContext getSourceContext() {
return null;
}
}
/**
* Look up a member, takes into account any ITDs on this type.
* return null if not found
*/
public ResolvedMember lookupMemberNoSupers(Member member) {
ResolvedMember ret = lookupDirectlyDeclaredMemberNoSupers(member);
if (ret == null && interTypeMungers != null) {
for (Iterator i = interTypeMungers.iterator(); i.hasNext();) {
ConcreteTypeMunger tm = (ConcreteTypeMunger) i.next();
if (matches(tm.getSignature(), member)) {
return tm.getSignature();
}
}
}
return ret;
}
public ResolvedMember lookupMemberWithSupersAndITDs(Member member) {
ResolvedMember ret = lookupMemberNoSupers(member);
if (ret != null) return ret;
ResolvedType supert = getSuperclass();
if (supert != null) {
ret = supert.lookupMemberNoSupers(member);
}
return ret;
}
/**
* as lookupMemberNoSupers, but does not include ITDs
*
* @param member
* @return
*/
public ResolvedMember lookupDirectlyDeclaredMemberNoSupers(Member member) {
ResolvedMember ret;
if (member.getKind() == Member.FIELD) {
ret = lookupMember(member, getDeclaredFields());
} else {
// assert member.getKind() == Member.METHOD || member.getKind() == Member.CONSTRUCTOR
ret = lookupMember(member, getDeclaredMethods());
}
return ret;
}
/**
* This lookup has specialized behaviour - a null result tells the
* EclipseTypeMunger that it should make a default implementation of a
* method on this type.
*
* @param member
* @return
*/
public ResolvedMember lookupMemberIncludingITDsOnInterfaces(Member member) {
return lookupMemberIncludingITDsOnInterfaces(member, this);
}
private ResolvedMember lookupMemberIncludingITDsOnInterfaces(Member member, ResolvedType onType) {
ResolvedMember ret = onType.lookupMemberNoSupers(member);
if (ret != null) {
return ret;
} else {
ResolvedType superType = onType.getSuperclass();
if (superType != null) {
ret = lookupMemberIncludingITDsOnInterfaces(member,superType);
}
if (ret == null) {
// try interfaces then, but only ITDs now...
ResolvedType[] superInterfaces = onType.getDeclaredInterfaces();
for (int i = 0; i < superInterfaces.length; i++) {
ret = superInterfaces[i].lookupMethodInITDs(member);
if (ret != null) return ret;
}
}
}
return ret;
}
protected List interTypeMungers = new ArrayList(0);
public List getInterTypeMungers() {
return interTypeMungers;
}
public List getInterTypeParentMungers() {
List l = new ArrayList();
for (Iterator iter = interTypeMungers.iterator(); iter.hasNext();) {
ConcreteTypeMunger element = (ConcreteTypeMunger) iter.next();
if (element.getMunger() instanceof NewParentTypeMunger) l.add(element);
}
return l;
}
/**
* ??? This method is O(N*M) where N = number of methods and M is number of
* inter-type declarations in my super
*/
public List getInterTypeMungersIncludingSupers() {
ArrayList ret = new ArrayList();
collectInterTypeMungers(ret);
return ret;
}
public List getInterTypeParentMungersIncludingSupers() {
ArrayList ret = new ArrayList();
collectInterTypeParentMungers(ret);
return ret;
}
private void collectInterTypeParentMungers(List collector) {
for (Iterator iter = getDirectSupertypes(); iter.hasNext();) {
ResolvedType superType = (ResolvedType) iter.next();
superType.collectInterTypeParentMungers(collector);
}
collector.addAll(getInterTypeParentMungers());
}
protected void collectInterTypeMungers(List collector) {
for (Iterator iter = getDirectSupertypes(); iter.hasNext();) {
ResolvedType superType = (ResolvedType) iter.next();
superType.collectInterTypeMungers(collector);
}
outer:
for (Iterator iter1 = collector.iterator(); iter1.hasNext();) {
ConcreteTypeMunger superMunger = (ConcreteTypeMunger) iter1.next();
if ( superMunger.getSignature() == null) continue;
if ( !superMunger.getSignature().isAbstract()) continue;
for (Iterator iter = getInterTypeMungers().iterator(); iter.hasNext();) {
ConcreteTypeMunger myMunger = (ConcreteTypeMunger) iter.next();
if (conflictingSignature(myMunger.getSignature(), superMunger.getSignature())) {
iter1.remove();
continue outer;
}
}
if (!superMunger.getSignature().isPublic()) continue;
for (Iterator iter = getMethods(); iter.hasNext(); ) {
ResolvedMember method = (ResolvedMember)iter.next();
if (conflictingSignature(method, superMunger.getSignature())) {
iter1.remove();
continue outer;
}
}
}
collector.addAll(getInterTypeMungers());
}
/**
* Check:
* 1) That we don't have any abstract type mungers unless this type is abstract.
* 2) That an abstract ITDM on an interface is declared public. (Compiler limitation) (PR70794)
*/
public void checkInterTypeMungers() {
if (isAbstract()) return;
boolean itdProblem = false;
for (Iterator iter = getInterTypeMungersIncludingSupers().iterator(); iter.hasNext();) {
ConcreteTypeMunger munger = (ConcreteTypeMunger) iter.next();
itdProblem = checkAbstractDeclaration(munger) || itdProblem; // Rule 2
}
if (itdProblem) return; // If the rules above are broken, return right now
for (Iterator iter = getInterTypeMungersIncludingSupers().iterator(); iter.hasNext();) {
ConcreteTypeMunger munger = (ConcreteTypeMunger) iter.next();
if (munger.getSignature() != null && munger.getSignature().isAbstract()) { // Rule 1
if (munger.getMunger().getKind() == ResolvedTypeMunger.MethodDelegate) {
;//ignore for @AJ ITD as munger.getSignature() is the interface method hence abstract
} else {
world.getMessageHandler().handleMessage(
new Message("must implement abstract inter-type declaration: " + munger.getSignature(),
"", IMessage.ERROR, getSourceLocation(), null,
new ISourceLocation[] { getMungerLocation(munger) }));
}
}
}
}
/**
* See PR70794. This method checks that if an abstract inter-type method declaration is made on
* an interface then it must also be public.
* This is a compiler limitation that could be made to work in the future (if someone
* provides a worthwhile usecase)
*
* @return indicates if the munger failed the check
*/
private boolean checkAbstractDeclaration(ConcreteTypeMunger munger) {
if (munger.getMunger()!=null && (munger.getMunger() instanceof NewMethodTypeMunger)) {
ResolvedMember itdMember = munger.getSignature();
ResolvedType onType = itdMember.getDeclaringType().resolve(world);
if (onType.isInterface() && itdMember.isAbstract() && !itdMember.isPublic()) {
world.getMessageHandler().handleMessage(
new Message(WeaverMessages.format(WeaverMessages.ITD_ABSTRACT_MUST_BE_PUBLIC_ON_INTERFACE,munger.getSignature(),onType),"",
Message.ERROR,getSourceLocation(),null,
new ISourceLocation[]{getMungerLocation(munger)})
);
return true;
}
}
return false;
}
/**
* Get a source location for the munger.
* Until intertype mungers remember where they came from, the source location
* for the munger itself is null. In these cases use the
* source location for the aspect containing the ITD.
*/
private ISourceLocation getMungerLocation(ConcreteTypeMunger munger) {
ISourceLocation sloc = munger.getSourceLocation();
if (sloc == null) {
sloc = munger.getAspectType().getSourceLocation();
}
return sloc;
}
/**
* Returns a ResolvedType object representing the declaring type of this type, or
* null if this type does not represent a non-package-level-type.
* <p/>
* <strong>Warning</strong>: This is guaranteed to work for all member types.
* For anonymous/local types, the only guarantee is given in JLS 13.1, where
* it guarantees that if you call getDeclaringType() repeatedly, you will eventually
* get the top-level class, but it does not say anything about classes in between.
*
* @return the declaring UnresolvedType object, or null.
*/
public ResolvedType getDeclaringType() {
if (isArray()) return null;
String name = getName();
int lastDollar = name.lastIndexOf('$');
while (lastDollar >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);
}
}
public static boolean hasBridgeModifier(int modifiers) {
return (modifiers & Constants.ACC_BRIDGE)!=0;
}
private static boolean samePackage(
ResolvedType targetType,
ResolvedType fromType) {
String p1 = targetType.getPackageName();
String p2 = fromType.getPackageName();
if (p1 == null) return p2 == null;
if (p2 == null) return false;
return p1.equals(p2);
}
/**
* Checks if the generic type for 'this' and the generic type for 'other' are the same -
* it can be passed raw or parameterized versions and will just compare the underlying
* generic type.
*/
private boolean genericTypeEquals(ResolvedType other) {
ResolvedType rt = other;
if (rt.isParameterizedType() || rt.isRawType()) rt.getGenericType();
if (( (isParameterizedType() || isRawType()) && getGenericType().equals(rt)) ||
(this.equals(other))) return true;
return false;
}
/**
* Look up the actual occurence of a particular type in the hierarchy for
* 'this' type. The input is going to be a generic type, and the caller
* wants to know if it was used in its RAW or a PARAMETERIZED form in this
* hierarchy.
*
* returns null if it can't be found.
*/
public ResolvedType discoverActualOccurrenceOfTypeInHierarchy(ResolvedType lookingFor) {
if (!lookingFor.isGenericType())
throw new BCException("assertion failed: method should only be called with generic type, but "+lookingFor+" is "+lookingFor.typeKind);
if (this.equals(ResolvedType.OBJECT)) return null;
if (genericTypeEquals(lookingFor)) return this;
ResolvedType superT = getSuperclass();
if (superT.genericTypeEquals(lookingFor)) return superT;
ResolvedType[] superIs = getDeclaredInterfaces();
for (int i = 0; i < superIs.length; i++) {
ResolvedType superI = superIs[i];
if (superI.genericTypeEquals(lookingFor)) return superI;
ResolvedType checkTheSuperI = superI.discoverActualOccurrenceOfTypeInHierarchy(lookingFor);
if (checkTheSuperI!=null) return checkTheSuperI;
}
return superT.discoverActualOccurrenceOfTypeInHierarchy(lookingFor);
}
/**
* Called for all type mungers but only does something if they share type variables
* with a generic type which they target. When this happens this routine will check
* for the target type in the target hierarchy and 'bind' any type parameters as
* appropriate. For example, for the ITD "List<T> I<T>.x" against a type like this:
* "class A implements I<String>" this routine will return a parameterized form of
* the ITD "List<String> I.x"
*/
public ConcreteTypeMunger fillInAnyTypeParameters(ConcreteTypeMunger munger) {
boolean debug = false;
ResolvedMember member = munger.getSignature();
if (munger.isTargetTypeParameterized()) {
if (debug) System.err.println("Processing attempted parameterization of "+munger+" targetting type "+this);
if (debug) System.err.println(" This type is "+this+" ("+typeKind+")");
// need to tailor this munger instance for the particular target...
if (debug) System.err.println(" Signature that needs parameterizing: "+member);
// Retrieve the generic type
ResolvedType onType = world.resolve(member.getDeclaringType()).getGenericType();
member.resolve(world); // Ensure all parts of the member are resolved
if (debug) System.err.println(" Actual target ontype: "+onType+" ("+onType.typeKind+")");
// quickly find the targettype in the type hierarchy for this type (it will be either RAW or PARAMETERIZED)
ResolvedType actualTarget = discoverActualOccurrenceOfTypeInHierarchy(onType);
if (actualTarget==null)
throw new BCException("assertion failed: asked "+this+" for occurrence of "+onType+" in its hierarchy??");
// only bind the tvars if its a parameterized type or the raw type (in which case they collapse to bounds) - don't do it for generic types ;)
if (!actualTarget.isGenericType()) {
if (debug) System.err.println("Occurrence in "+this+" is actually "+actualTarget+" ("+actualTarget.typeKind+")");
// parameterize the signature
// ResolvedMember newOne = member.parameterizedWith(actualTarget.getTypeParameters(),onType,actualTarget.isParameterizedType());
}
//if (!actualTarget.isRawType())
munger = munger.parameterizedFor(actualTarget);
if (debug) System.err.println("New sig: "+munger.getSignature());
if (debug) System.err.println("=====================================");
}
return munger;
}
public void addInterTypeMunger(ConcreteTypeMunger munger) {
ResolvedMember sig = munger.getSignature();
if (sig == null || munger.getMunger() == null ||
munger.getMunger().getKind() == ResolvedTypeMunger.PrivilegedAccess)
{
interTypeMungers.add(munger);
return;
}
ConcreteTypeMunger originalMunger = munger;
// we will use the 'parameterized' ITD for all the comparisons but we say the original
// one passed in actually matched as it will be added to the intertype member finder
// for the target type. It is possible we only want to do this if a generic type
// is discovered and the tvar is collapsed to a bound?
munger = fillInAnyTypeParameters(munger);
sig = munger.getSignature(); // possibly changed when type parms filled in
//System.err.println("add: " + munger + " to " + this.getClassName() + " with " + interTypeMungers);
if (sig.getKind() == Member.METHOD) {
if (!compareToExistingMembers(munger, getMethodsWithoutIterator(false,true) /*getMethods()*/)) return;
if (this.isInterface()) {
if (!compareToExistingMembers(munger,
Arrays.asList(world.getCoreType(OBJECT).getDeclaredMethods()).iterator())) return;
}
} else if (sig.getKind() == Member.FIELD) {
if (!compareToExistingMembers(munger, Arrays.asList(getDeclaredFields()).iterator())) return;
} else {
if (!compareToExistingMembers(munger, Arrays.asList(getDeclaredMethods()).iterator())) return;
}
// now compare to existingMungers
for (Iterator i = interTypeMungers.iterator(); i.hasNext(); ) {
ConcreteTypeMunger existingMunger = (ConcreteTypeMunger)i.next();
if (conflictingSignature(existingMunger.getSignature(), munger.getSignature())) {
//System.err.println("match " + munger + " with " + existingMunger);
if (isVisible(munger.getSignature().getModifiers(),
munger.getAspectType(), existingMunger.getAspectType()))
{
//System.err.println(" is visible");
int c = compareMemberPrecedence(sig, existingMunger.getSignature());
if (c == 0) {
c = getWorld().compareByPrecedenceAndHierarchy(munger.getAspectType(), existingMunger.getAspectType());
}
//System.err.println(" compare: " + c);
if (c < 0) {
// the existing munger dominates the new munger
checkLegalOverride(munger.getSignature(), existingMunger.getSignature());
return;
} else if (c > 0) {
// the new munger dominates the existing one
checkLegalOverride(existingMunger.getSignature(), munger.getSignature());
i.remove();
break;
} else {
interTypeConflictError(munger, existingMunger);
interTypeConflictError(existingMunger, munger);
return;
}
}
}
}
//System.err.println("adding: " + munger + " to " + this);
// we are adding the parameterized form of the ITD to the list of
// mungers. Within it, the munger knows the original declared
// signature for the ITD so it can be retrieved.
interTypeMungers.add(munger);
}
private boolean compareToExistingMembers(ConcreteTypeMunger munger, List existingMembersList) {
return compareToExistingMembers(munger,existingMembersList.iterator());
}
//??? returning too soon
private boolean compareToExistingMembers(ConcreteTypeMunger munger, Iterator existingMembers) {
ResolvedMember sig = munger.getSignature();
while (existingMembers.hasNext()) {
ResolvedMember existingMember = (ResolvedMember)existingMembers.next();
// don't worry about clashing with bridge methods
if (existingMember.isBridgeMethod()) continue;
//System.err.println("Comparing munger: "+sig+" with member "+existingMember);
if (conflictingSignature(existingMember, munger.getSignature())) {
//System.err.println("conflict: existingMember=" + existingMember + " typeMunger=" + munger);
//System.err.println(munger.getSourceLocation() + ", " + munger.getSignature() + ", " + munger.getSignature().getSourceLocation());
if (isVisible(existingMember.getModifiers(), this, munger.getAspectType())) {
int c = compareMemberPrecedence(sig, existingMember);
//System.err.println(" c: " + c);
if (c < 0) {
// existingMember dominates munger
checkLegalOverride(munger.getSignature(), existingMember);
return false;
} else if (c > 0) {
// munger dominates existingMember
checkLegalOverride(existingMember, munger.getSignature());
//interTypeMungers.add(munger);
//??? might need list of these overridden abstracts
continue;
} else {
// bridge methods can differ solely in return type.
// FIXME this whole method seems very hokey - unaware of covariance/varargs/bridging - it
// could do with a rewrite !
boolean sameReturnTypes = (existingMember.getReturnType().equals(sig.getReturnType()));
if (sameReturnTypes)
getWorld().getMessageHandler().handleMessage(
MessageUtil.error(WeaverMessages.format(WeaverMessages.ITD_MEMBER_CONFLICT,munger.getAspectType().getName(),
existingMember),
munger.getSourceLocation())
);
}
} else if (isDuplicateMemberWithinTargetType(existingMember,this,sig)) {
getWorld().getMessageHandler().handleMessage(
MessageUtil.error(WeaverMessages.format(WeaverMessages.ITD_MEMBER_CONFLICT,munger.getAspectType().getName(),
existingMember),
munger.getSourceLocation())
);
;
}
//return;
}
}
return true;
}
// we know that the member signature matches, but that the member in the target type is not visible to the aspect.
// this may still be disallowed if it would result in two members within the same declaring type with the same
// signature AND more than one of them is concrete AND they are both visible within the target type.
private boolean isDuplicateMemberWithinTargetType(ResolvedMember existingMember, ResolvedType targetType,ResolvedMember itdMember) {
if ( (existingMember.isAbstract() || itdMember.isAbstract())) return false;
UnresolvedType declaringType = existingMember.getDeclaringType();
if (!targetType.equals(declaringType)) return false;
// now have to test that itdMember is visible from targetType
if (itdMember.isPrivate()) return false;
if (itdMember.isPublic()) return true;
// must be in same package to be visible then...
if (!targetType.getPackageName().equals(itdMember.getDeclaringType().getPackageName())) return false;
// trying to put two members with the same signature into the exact same type..., and both visible in that type.
return true;
}
/**
* @return true if the override is legal
* note: calling showMessage with two locations issues TWO messages, not ONE message
* with an additional source location.
*/
public boolean checkLegalOverride(ResolvedMember parent, ResolvedMember child) {
//System.err.println("check: " + child.getDeclaringType() + " overrides " + parent.getDeclaringType());
if (Modifier.isFinal(parent.getModifiers())) {
world.showMessage(Message.ERROR,
WeaverMessages.format(WeaverMessages.CANT_OVERRIDE_FINAL_MEMBER,parent),
child.getSourceLocation(),null);
return false;
}
boolean incompatibleReturnTypes = false;
// In 1.5 mode, allow for covariance on return type
if (world.isInJava5Mode() && parent.getKind()==Member.METHOD) {
// Look at the generic types when doing this comparison
ResolvedType rtParentReturnType = parent.getGenericReturnType().resolve(world);
ResolvedType rtChildReturnType = child.getGenericReturnType().resolve(world);
incompatibleReturnTypes = !rtParentReturnType.isAssignableFrom(rtChildReturnType);
if (incompatibleReturnTypes) {
incompatibleReturnTypes = !rtParentReturnType.isAssignableFrom(rtChildReturnType);
}
} else {
incompatibleReturnTypes =!parent.getReturnType().equals(child.getReturnType());
}
if (incompatibleReturnTypes) {
world.showMessage(IMessage.ERROR,
WeaverMessages.format(WeaverMessages.ITD_RETURN_TYPE_MISMATCH,parent,child),
child.getSourceLocation(), parent.getSourceLocation());
return false;
}
if (parent.getKind() == Member.POINTCUT) {
UnresolvedType[] pTypes = parent.getParameterTypes();
UnresolvedType[] cTypes = child.getParameterTypes();
if (!Arrays.equals(pTypes, cTypes)) {
world.showMessage(IMessage.ERROR,
WeaverMessages.format(WeaverMessages.ITD_PARAM_TYPE_MISMATCH,parent,child),
child.getSourceLocation(), parent.getSourceLocation());
return false;
}
}
//System.err.println("check: " + child.getModifiers() + " more visible " + parent.getModifiers());
if (isMoreVisible(parent.getModifiers(), child.getModifiers())) {
world.showMessage(IMessage.ERROR,
WeaverMessages.format(WeaverMessages.ITD_VISIBILITY_REDUCTION,parent,child),
child.getSourceLocation(), parent.getSourceLocation());
return false;
}
// check declared exceptions
ResolvedType[] childExceptions = world.resolve(child.getExceptions());
ResolvedType[] parentExceptions = world.resolve(parent.getExceptions());
ResolvedType runtimeException = world.resolve("java.lang.RuntimeException");
ResolvedType error = world.resolve("java.lang.Error");
outer:
for (int i = 0, leni = childExceptions.length; i < leni; i++) {
//System.err.println("checking: " + childExceptions[i]);
if (runtimeException.isAssignableFrom(childExceptions[i])) continue;
if (error.isAssignableFrom(childExceptions[i])) continue;
for (int j = 0, lenj = parentExceptions.length; j < lenj; j++) {
if (parentExceptions[j].isAssignableFrom(childExceptions[i])) continue outer;
}
// this message is now better handled my MethodVerifier in JDT core.
// world.showMessage(IMessage.ERROR,
// WeaverMessages.format(WeaverMessages.ITD_DOESNT_THROW,childExceptions[i].getName()),
// child.getSourceLocation(), null);
return false;
}
if (parent.isStatic() && !child.isStatic()) {
world.showMessage(IMessage.ERROR,
WeaverMessages.format(WeaverMessages.ITD_OVERRIDDEN_STATIC,child,parent),
child.getSourceLocation(),null);
return false;
} else if (child.isStatic() && !parent.isStatic()) {
world.showMessage(IMessage.ERROR,
WeaverMessages.format(WeaverMessages.ITD_OVERIDDING_STATIC,child,parent),
child.getSourceLocation(),null);
return false;
}
return true;
}
private int compareMemberPrecedence(ResolvedMember m1, ResolvedMember m2) {
//if (!m1.getReturnType().equals(m2.getReturnType())) return 0;
// need to allow for the special case of 'clone' - which is like abstract but is
// not marked abstract. The code below this next line seems to make assumptions
// about what will have gotten through the compiler based on the normal
// java rules. clone goes against these...
if (m2.isProtected() && m2.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;
//System.err.println("conflict at " + m2.getSourceLocation());
getWorld().showMessage(IMessage.ERROR,
WeaverMessages.format(WeaverMessages.ITD_CONFLICT,m1.getAspectType().getName(),
m2.getSignature(),m2.getAspectType().getName()),
m2.getSourceLocation(), getSourceLocation());
}
public ResolvedMember lookupSyntheticMember(Member member) {
//??? horribly inefficient
//for (Iterator i =
//System.err.println("lookup " + member + " in " + interTypeMungers);
for (Iterator i = interTypeMungers.iterator(); i.hasNext(); ) {
ConcreteTypeMunger m = (ConcreteTypeMunger)i.next();
ResolvedMember ret = m.getMatchingSyntheticMember(member);
if (ret != null) {
//System.err.println(" found: " + ret);
return ret;
}
}
// 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,
ResolvedType.VOID,"<init>",world.resolve(member.getParameterTypes()));
return ret;
}
}
// if (this.getSuperclass() != ResolvedType.OBJECT && this.getSuperclass() != null) {
// return getSuperclass().lookupSyntheticMember(member);
// }
return null;
}
public void clearInterTypeMungers() {
if (isRawType()) getGenericType().clearInterTypeMungers();
interTypeMungers = new ArrayList();
}
public boolean isTopmostImplementor(ResolvedType interfaceType) {
if (isInterface()) return false;
if (!interfaceType.isAssignableFrom(this,true)) return false;
// check that I'm truly the topmost implementor
if (this.getSuperclass().isMissing()) return true; // we don't know anything about supertype, and it can't be exposed to weaver
if (interfaceType.isAssignableFrom(this.getSuperclass(),true)) {
return false;
}
return true;
}
public ResolvedType getTopmostImplementor(ResolvedType interfaceType) {
if (isInterface()) return null;
if (!interfaceType.isAssignableFrom(this)) return null;
// Check if my super class is an implementor?
ResolvedType higherType = this.getSuperclass().getTopmostImplementor(interfaceType);
if (higherType!=null) return higherType;
return this;
}
private ResolvedType findHigher(ResolvedType other) {
if (this == other) return this;
for(Iterator i = other.getDirectSupertypes(); i.hasNext(); ) {
ResolvedType rtx = (ResolvedType)i.next();
boolean b = this.isAssignableFrom(rtx);
if (b) return rtx;
}
return null;
}
public List getExposedPointcuts() {
List ret = new ArrayList();
if (getSuperclass() != null) ret.addAll(getSuperclass().getExposedPointcuts());
for (Iterator i = Arrays.asList(getDeclaredInterfaces()).iterator(); i.hasNext(); ) {
ResolvedType t = (ResolvedType)i.next();
addPointcutsResolvingConflicts(ret, Arrays.asList(t.getDeclaredPointcuts()), false);
}
addPointcutsResolvingConflicts(ret, Arrays.asList(getDeclaredPointcuts()), true);
for (Iterator i = ret.iterator(); i.hasNext(); ) {
ResolvedPointcutDefinition inherited = (ResolvedPointcutDefinition)i.next();
// System.err.println("looking at: " + inherited + " in " + this);
// System.err.println(" " + inherited.isAbstract() + " in " + this.isAbstract());
if (inherited.isAbstract()) {
if (!this.isAbstract()) {
getWorld().showMessage(IMessage.ERROR,
WeaverMessages.format(WeaverMessages.POINCUT_NOT_CONCRETE,inherited,this.getName()),
inherited.getSourceLocation(), this.getSourceLocation());
}
}
}
return ret;
}
private void addPointcutsResolvingConflicts(List acc, List added, boolean isOverriding) {
for (Iterator i = added.iterator(); i.hasNext();) {
ResolvedPointcutDefinition toAdd =
(ResolvedPointcutDefinition) i.next();
//System.err.println("adding: " + toAdd);
for (Iterator j = acc.iterator(); j.hasNext();) {
ResolvedPointcutDefinition existing =
(ResolvedPointcutDefinition) j.next();
if (existing == toAdd) continue;
if (!isVisible(existing.getModifiers(),
existing.getDeclaringType().resolve(getWorld()),
this)) {
continue;
}
if (conflictingSignature(existing, toAdd)) {
if (isOverriding) {
checkLegalOverride(existing, toAdd);
j.remove();
} else {
getWorld().showMessage(
IMessage.ERROR,
WeaverMessages.format(WeaverMessages.CONFLICTING_INHERITED_POINTCUTS,this.getName() + toAdd.getSignature()),
existing.getSourceLocation(),
toAdd.getSourceLocation());
j.remove();
}
}
}
acc.add(toAdd);
}
}
public ISourceLocation getSourceLocation() {
return null;
}
public boolean isExposedToWeaver() {
return false;
}
public WeaverStateInfo getWeaverState() {
return null;
}
/**
* Overridden by ReferenceType to return a sensible answer for parameterized and raw types.
*
* @return
*/
public ResolvedType getGenericType() {
if (!(isParameterizedType() || isRawType()))
throw new BCException("The type "+getBaseName()+" is not parameterized or raw - it has no generic type");
return null;
}
/**
* overriden by ReferenceType to return the gsig for a generic type
* @return
*/
public String getGenericSignature() {
return "";
}
public ResolvedType parameterizedWith(UnresolvedType[] typeParameters) {
if (!(isGenericType() || isParameterizedType())) return this;
return TypeFactory.createParameterizedType(this.getGenericType(), typeParameters, getWorld());
}
/**
* Iff I am a parameterized type, and any of my parameters are type variable
* references, return a version with those type parameters replaced in accordance
* with the passed bindings.
*/
public UnresolvedType parameterize(Map typeBindings) {
if (!isParameterizedType()) throw new IllegalStateException("Can't parameterize a type that is not a parameterized type");
boolean workToDo = false;
for (int i = 0; i < typeParameters.length; i++) {
if (typeParameters[i].isTypeVariableReference()) {
workToDo = true;
}
}
if (!workToDo) {
return this;
} else {
UnresolvedType[] newTypeParams = new UnresolvedType[typeParameters.length];
for (int i = 0; i < newTypeParams.length; i++) {
newTypeParams[i] = typeParameters[i];
if (newTypeParams[i].isTypeVariableReference()) {
TypeVariableReferenceType tvrt = (TypeVariableReferenceType) newTypeParams[i];
UnresolvedType binding = (UnresolvedType) typeBindings.get(tvrt.getTypeVariable().getName());
if (binding != null) newTypeParams[i] = binding;
}
}
return TypeFactory.createParameterizedType(getGenericType(), newTypeParams, getWorld());
}
}
public boolean hasParameterizedSuperType() {
getParameterizedSuperTypes();
return parameterizedSuperTypes.length > 0;
}
public boolean hasGenericSuperType() {
ResolvedType[] superTypes = getDeclaredInterfaces();
for (int i = 0; i < superTypes.length; i++) {
if (superTypes[i].isGenericType()) return true;
}
return false;
}
private ResolvedType[] parameterizedSuperTypes = null;
/**
* Similar to the above method, but accumulates the super types
*
* @return
*/
public ResolvedType[] getParameterizedSuperTypes() {
if (parameterizedSuperTypes != null) return parameterizedSuperTypes;
List accumulatedTypes = new ArrayList();
accumulateParameterizedSuperTypes(this,accumulatedTypes);
ResolvedType[] ret = new ResolvedType[accumulatedTypes.size()];
parameterizedSuperTypes = (ResolvedType[]) accumulatedTypes.toArray(ret);
return parameterizedSuperTypes;
}
private void accumulateParameterizedSuperTypes(ResolvedType forType, List parameterizedTypeList) {
if (forType.isParameterizedType()) {
parameterizedTypeList.add(forType);
}
if (forType.getSuperclass() != null) {
accumulateParameterizedSuperTypes(forType.getSuperclass(), parameterizedTypeList);
}
ResolvedType[] interfaces = forType.getDeclaredInterfaces();
for (int i = 0; i < interfaces.length; i++) {
accumulateParameterizedSuperTypes(interfaces[i], parameterizedTypeList);
}
}
/**
* Types may have pointcuts just as they have methods and fields.
*/
public ResolvedPointcutDefinition findPointcut(String name, World world) {
throw new UnsupportedOperationException("Not yet implemenented");
}
/**
* @return true if assignable to java.lang.Exception
*/
public boolean isException() {
return (world.getCoreType(UnresolvedType.JAVA_LANG_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);
}
/**
* Implemented by ReferenceTypes
*/
public String getSignatureForAttribute() {
throw new RuntimeException("Cannot ask this type "+this+" for a generic sig attribute");
}
private FuzzyBoolean parameterizedWithAMemberTypeVariable = FuzzyBoolean.MAYBE;
/**
* return true if the parameterization of this type includes a member type variable. Member
* type variables occur in generic methods/ctors.
*/
public boolean isParameterizedWithAMemberTypeVariable() {
// MAYBE means we haven't worked it out yet...
if (parameterizedWithAMemberTypeVariable==FuzzyBoolean.MAYBE) {
// if there are no type parameters then we cant be...
if (typeParameters==null || typeParameters.length==0) {
parameterizedWithAMemberTypeVariable = FuzzyBoolean.NO;
return false;
}
for (int i = 0; i < typeParameters.length; i++) {
UnresolvedType aType = (ResolvedType)typeParameters[i];
if (aType.isTypeVariableReference() &&
// assume the worst - if its definetly not a type declared one, it could be anything
((TypeVariableReference)aType).getTypeVariable().getDeclaringElementKind()!=TypeVariable.TYPE) {
parameterizedWithAMemberTypeVariable = FuzzyBoolean.YES;
return true;
}
if (aType.isParameterizedType()) {
boolean b = aType.isParameterizedWithAMemberTypeVariable();
if (b) {
parameterizedWithAMemberTypeVariable = FuzzyBoolean.YES;
return true;
}
}
if (aType.isGenericWildcard()) {
if (aType.isExtends()) {
boolean b = false;
UnresolvedType upperBound = aType.getUpperBound();
if (upperBound.isParameterizedType()) {
b = upperBound.isParameterizedWithAMemberTypeVariable();
} else if (upperBound.isTypeVariableReference() && ((TypeVariableReference)upperBound).getTypeVariable().getDeclaringElementKind()==TypeVariable.METHOD) {
b = true;
}
if (b) {
parameterizedWithAMemberTypeVariable = FuzzyBoolean.YES;
return true;
}
// FIXME asc need to check additional interface bounds
}
if (aType.isSuper()) {
boolean b = false;
UnresolvedType lowerBound = aType.getLowerBound();
if (lowerBound.isParameterizedType()) {
b = lowerBound.isParameterizedWithAMemberTypeVariable();
} else if (lowerBound.isTypeVariableReference() && ((TypeVariableReference)lowerBound).getTypeVariable().getDeclaringElementKind()==TypeVariable.METHOD) {
b = true;
}
if (b) {
parameterizedWithAMemberTypeVariable = FuzzyBoolean.YES;
return true;
}
}
}
}
parameterizedWithAMemberTypeVariable=FuzzyBoolean.NO;
}
return parameterizedWithAMemberTypeVariable.alwaysTrue();
}
protected boolean ajMembersNeedParameterization() {
if (isParameterizedType()) return true;
if (getSuperclass() != null) return getSuperclass().ajMembersNeedParameterization();
return false;
}
protected Map getAjMemberParameterizationMap() {
Map myMap = getMemberParameterizationMap();
if (myMap.size() == 0) {
// might extend a parameterized aspect that we also need to consider...
if (getSuperclass() != null) return getSuperclass().getAjMemberParameterizationMap();
}
return myMap;
}
}
|
138,223 |
Bug 138223 Compiler crash on two binding @xxx pcds in one compound expression
|
junit.framework.AssertionFailedError: test "Double at annotation matching (no binding)" failed test "Double at annotation matching (no binding)" failed Unexpected warning messages: warning at before() : transactionalOperation() { ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ /private/tmp/ajcSandbox/ajcTest18924.tmp/DoubleAnnotationMatching.aj:20:0::0 advice defined in DoubleAnnotationMatching has not been applied [Xlint:adviceDidNotMatch] Unexpected fail messages: abort trouble in: class Foo extends java.lang.Object: void <init>(): ALOAD_0 // LFoo; this (line 26) INVOKESPECIAL java.lang.Object.<init> ()V constructor-execution(void Foo.<init>()) | RETURN constructor-execution(void Foo.<init>()) end void <init>() public void foo() org.aspectj.weaver.MethodDeclarationLineNumber: 28:533 : method-execution(void Foo.foo()) | RETURN (line 28) method-execution(void Foo.foo()) end public void foo() public void bar() org.aspectj.weaver.MethodDeclarationLineNumber: 30:563 : method-execution(void Foo.bar()) | RETURN (line 30) method-execution(void Foo.bar()) end public void bar() end class Foo -- (BCException) Impossible! annotation=[Tx] shadow=[method-execution(void Foo.foo()) at /private/tmp/ajcSandbox/ajcTest18924.tmp/DoubleAnnotationMatching.aj:28::533] pointcut is at [/private/tmp/ajcSandbox/ajcTest18924.tmp/DoubleAnnotationMatching.aj:15::316] when implementing on shadow method-execution(void Foo.foo()) when weaving type Foo when weaving classes when weaving when batch building BuildConfig[null] #Files=1 Impossible! annotation=[Tx] shadow=[method-execution(void Foo.foo()) at /private/tmp/ajcSandbox/ajcTest18924.tmp/DoubleAnnotationMatching.aj:28::533] pointcut is at [/private/tmp/ajcSandbox/ajcTest18924.tmp/DoubleAnnotationMatching.aj:15::316] when implementing on shadow method-execution(void Foo.foo()) when weaving type Foo when weaving classes when weaving when batch building BuildConfig[null] #Files=1 org.aspectj.weaver.BCException: Impossible! annotation=[Tx] shadow=[method-execution(void Foo.foo()) at /private/tmp/ajcSandbox/ajcTest18924.tmp/DoubleAnnotationMatching.aj:28::533] pointcut is at [/private/tmp/ajcSandbox/ajcTest18924.tmp/DoubleAnnotationMatching.aj:15::316] when implementing on shadow method-execution(void Foo.foo()) when weaving type Foo when weaving classes when weaving when batch building BuildConfig[null] #Files=1 at org.aspectj.weaver.patterns.AnnotationPointcut.findResidueInternal(AnnotationPointcut.java:201) at org.aspectj.weaver.patterns.Pointcut.findResidue(Pointcut.java:267) at org.aspectj.weaver.patterns.AndPointcut.findResidueInternal(AndPointcut.java:93) at org.aspectj.weaver.patterns.Pointcut.findResidue(Pointcut.java:267) at org.aspectj.weaver.patterns.AndPointcut.findResidueInternal(AndPointcut.java:93) at org.aspectj.weaver.patterns.Pointcut.findResidue(Pointcut.java:267) at org.aspectj.weaver.patterns.IfPointcut.findResidueInternal(IfPointcut.java:173) at org.aspectj.weaver.patterns.Pointcut.findResidue(Pointcut.java:267) at org.aspectj.weaver.patterns.AndPointcut.findResidueInternal(AndPointcut.java:93) at org.aspectj.weaver.patterns.Pointcut.findResidue(Pointcut.java:267) at org.aspectj.weaver.patterns.AndPointcut.findResidueInternal(AndPointcut.java:93) at org.aspectj.weaver.patterns.Pointcut.findResidue(Pointcut.java:267) at org.aspectj.weaver.patterns.OrPointcut.findResidueInternal(OrPointcut.java:96) at org.aspectj.weaver.patterns.Pointcut.findResidue(Pointcut.java:267) at org.aspectj.weaver.bcel.BcelAdvice.specializeOn(BcelAdvice.java:132) at org.aspectj.weaver.bcel.BcelShadow.prepareForMungers(BcelShadow.java:325) at org.aspectj.weaver.Shadow.implement(Shadow.java:455) at org.aspectj.weaver.bcel.BcelClassWeaver.implement(BcelClassWeaver.java:2236) at org.aspectj.weaver.bcel.BcelClassWeaver.weave(BcelClassWeaver.java:491) at org.aspectj.weaver.bcel.BcelClassWeaver.weave(BcelClassWeaver.java:109) at org.aspectj.weaver.bcel.BcelWeaver.weave(BcelWeaver.java:1560) at org.aspectj.weaver.bcel.BcelWeaver.weaveWithoutDump(BcelWeaver.java:1511) at org.aspectj.weaver.bcel.BcelWeaver.weaveAndNotify(BcelWeaver.java:1291) at org.aspectj.weaver.bcel.BcelWeaver.weave(BcelWeaver.java:1113) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.weave(AjCompilerAdapter.java:311) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.afterCompiling(AjCompilerAdapter.java:183) at org.aspectj.ajdt.internal.compiler.CompilerAdapter.ajc$afterReturning$org_aspectj_ajdt_internal_compiler_CompilerAdapter$2$f9cc9ca0(CompilerAdapter.aj:70) at org.aspectj.org.eclipse.jdt.internal.compiler.Compiler.compile(Compiler.java:367) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.performCompilation(AjBuildManager.java:862) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.doBuild(AjBuildManager.java:242) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.batchBuild(AjBuildManager.java:161) at org.aspectj.ajdt.ajc.AjdtCommand.doCommand(AjdtCommand.java:114) at org.aspectj.ajdt.ajc.AjdtCommand.runCommand(AjdtCommand.java:60) at org.aspectj.tools.ajc.Main.run(Main.java:367) at org.aspectj.tools.ajc.Main.runMain(Main.java:246) at org.aspectj.tools.ajc.Ajc.compile(Ajc.java:199) at org.aspectj.tools.ajc.Ajc.compile(Ajc.java:163) at org.aspectj.tools.ajc.AjcTestCase.ajc(AjcTestCase.java:510) at org.aspectj.testing.CompileSpec.execute(CompileSpec.java:53) at org.aspectj.testing.AjcTest.runTest(AjcTest.java:68) at org.aspectj.testing.XMLBasedAjcTestCase.runTest(XMLBasedAjcTestCase.java:111) at org.aspectj.systemtest.ajc152.Ajc152Tests.testDoubleAnnotationMatching_pr138221(Ajc152Tests.java:37) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:585) at junit.framework.TestCase.runTest(TestCase.java:154) at junit.framework.TestCase.runBare(TestCase.java:127) at junit.framework.TestResult$1.protect(TestResult.java:106) at junit.framework.TestResult.runProtected(TestResult.java:124) at junit.framework.TestResult.run(TestResult.java:109) at junit.framework.TestCase.run(TestCase.java:118) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:478) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:344) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:196) command was: ajc -classpath /Users/adrian/projects/aspectjdev/lib/test/aspectjrt.jar:../testing-client/bin:../runtime/bin:../aspectj5rt/bin:../lib/junit/junit.jar:../bridge/bin:../loadtime/bin:../weaver/bin:../weaver5/bin:../aj-build/jars/bridge.jar:../aj-build/jars/util.jar:../aj-build/jars/loadtime.jar:../aj-build/jars/weaver.jar:../aj-build/jars/weaver5.jar:../aj-build/jars/asm.jar:../lib/test/testing-client.jar:../lib/test/aspectjrt.jar:/tmp/ajcSandbox/ajcTest18924.tmp -1.5 /tmp/ajcSandbox/ajcTest18924.tmp/DoubleAnnotationMatching.aj -d /tmp/ajcSandbox/ajcTest18924.tmp at junit.framework.Assert.fail(Assert.java:47) at org.aspectj.tools.ajc.AjcTestCase.assertMessages(AjcTestCase.java:452) at org.aspectj.testing.CompileSpec.execute(CompileSpec.java:56) at org.aspectj.testing.AjcTest.runTest(AjcTest.java:68) at org.aspectj.testing.XMLBasedAjcTestCase.runTest(XMLBasedAjcTestCase.java:111) at org.aspectj.systemtest.ajc152.Ajc152Tests.testDoubleAnnotationMatching_pr138221(Ajc152Tests.java:37) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:585) at junit.framework.TestCase.runTest(TestCase.java:154) at junit.framework.TestCase.runBare(TestCase.java:127) at junit.framework.TestResult$1.protect(TestResult.java:106) at junit.framework.TestResult.runProtected(TestResult.java:124) at junit.framework.TestResult.run(TestResult.java:109) at junit.framework.TestCase.run(TestCase.java:118) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:478) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:344) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:196)
|
resolved fixed
|
6b2d9ae
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-05-17T15:48:34Z | 2006-04-24T17:33:20Z |
tests/src/org/aspectj/systemtest/ajc152/Ajc152Tests.java
|
/*******************************************************************************
* Copyright (c) 2006 IBM
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* Andy Clement - initial API and implementation
*******************************************************************************/
package org.aspectj.systemtest.ajc152;
import java.io.File;
import junit.framework.Test;
import org.aspectj.testing.XMLBasedAjcTestCase;
public class Ajc152Tests extends org.aspectj.testing.XMLBasedAjcTestCase {
//public void testMisbehavingDeclareAnnotation_pr135865() { runTest("misbehaving declare annotation");}
//public void testMisbehavingDeclareAnnotation_pr135865_2() { runTest("misbehaving declare annotation - 2");}
public void testCompletelyBrokenAopConcretization_pr142165_1() { runTest("broken concretization");}
public void testCompletelyBrokenAopConcretization_pr142165_2() { runTest("broken concretization - 2");}
public void testCompletelyBrokenAopConcretization_pr142165_3() { runTest("broken concretization - 3");}
public void testVerifyErrorLTW_pr135068() { runTest("ltw verifyerror");}
public void testVerifyErrorLTW_pr135068_2() { runTest("ltw verifyerror - 2");}
public void testVerifyErrorLTW_pr135068_3() { runTest("ltw verifyerror - 3");}
public void testVerifyErrorLTW_pr135068_4() { runTest("ltw verifyerror - 4");}
public void testVerifyErrorForComplexCflow_pr136026() { runTest("verifyerror");}
public void testVerifyErrorForComplexCflow_pr136026_2() { runTest("verifyerror - 2");}
public void testAnnotationsAndGenericsBCException_pr129704() { runTest("annotations and generics leading to BCException");}
public void testMethodTooBigAfterWeaving_pr138384() { runTest("method too big"); }
public void testNotAtWithincode_pr138158_1() { runTest("not at withincode - 1");}
public void testNotAtWithincode_pr138158_2() { runTest("not at withincode - 2");}
public void testNotAtWithincode_pr138158_3() { runTest("not at within - 3");}
// public void testComplexGenericDecl_pr137568() { runTest("complicated generics declaration");}
public void testNpeOnDup_pr138143() { runTest("npe on duplicate method with ataj");}
public void testPointcutsAndGenerics_pr137496_1() { runTest("pointcuts and generics - B");}
public void testPointcutsAndGenerics_pr137496_2() { runTest("pointcuts and generics - D");}
public void testPointcutsAndGenerics_pr137496_3() { runTest("pointcuts and generics - E");}
public void testPointcutsAndGenerics_pr137496_4() { runTest("pointcuts and generics - F");}
public void testPointcutsAndGenerics_pr137496_5() { runTest("pointcuts and generics - G");}
public void testPointcutsAndGenerics_pr137496_6() { runTest("pointcuts and generics - H");}
public void testAspectLibrariesAndASM_pr135001() { runTest("aspect libraries and asm");}
public void testStackOverflow_pr136258() { runTest("stack overflow");}
public void testIncorrectOverridesEvaluation13() { runTest("incorrect overrides evaluation - 1.3"); }
public void testIncorrectOverridesEvaluation15() { runTest("incorrect overrides evaluation - 1.5"); }
public void testAtWithinCodeBug_pr138798() { runTest("atWithinCodeBug"); }
// known failures, uncomment when working.
public void testReferencePCutInDeclareWarning_pr138215() { runTest("Reference pointcut fails inside @DeclareWarning");}
public void testReferencePCutInPerClause_pr138219() { runTest("Can't use a FQ Reference pointcut in any pointcut expression referenced by a per-clause");}
public void testReferencePCutInPerClause_pr130722() { runTest("FQ Reference pointcut from perclause ref pc"); }
// public void testDoubleAnnotationMatching_pr138223() { runTest("Double at annotation matching (no binding)");}
public void testSuperCallsInAtAspectJAdvice_pr139749() { runTest("Super calls in @AspectJ advice");}
public void testNoClassCastExceptionWithPerThis_pr138286() { runTest("No ClassCastException with perThis");}
// this next one reported as a bug by Rob Harrop, but I can't reproduce the failure yet...
//public void testAtAspectWithReferencePCPerClause_pr138220() { runTest("@Aspect with reference pointcut in perclause");}
public void testJarChecking_pr137235_1() { runTest("directory with .jar extension: source and outjar"); }
public void testJarChecking_pr137235_2() { runTest("directory with .jar extension"); }
public void testMakePreMethodNPE_pr136393() { runTest("NPE in makePreMethod");}
/////////////////////////////////////////
public static Test suite() {
return XMLBasedAjcTestCase.loadSuite(Ajc152Tests.class);
}
protected File getSpecFile() {
return new File("../tests/src/org/aspectj/systemtest/ajc152/ajc152.xml");
}
}
|
138,223 |
Bug 138223 Compiler crash on two binding @xxx pcds in one compound expression
|
junit.framework.AssertionFailedError: test "Double at annotation matching (no binding)" failed test "Double at annotation matching (no binding)" failed Unexpected warning messages: warning at before() : transactionalOperation() { ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ /private/tmp/ajcSandbox/ajcTest18924.tmp/DoubleAnnotationMatching.aj:20:0::0 advice defined in DoubleAnnotationMatching has not been applied [Xlint:adviceDidNotMatch] Unexpected fail messages: abort trouble in: class Foo extends java.lang.Object: void <init>(): ALOAD_0 // LFoo; this (line 26) INVOKESPECIAL java.lang.Object.<init> ()V constructor-execution(void Foo.<init>()) | RETURN constructor-execution(void Foo.<init>()) end void <init>() public void foo() org.aspectj.weaver.MethodDeclarationLineNumber: 28:533 : method-execution(void Foo.foo()) | RETURN (line 28) method-execution(void Foo.foo()) end public void foo() public void bar() org.aspectj.weaver.MethodDeclarationLineNumber: 30:563 : method-execution(void Foo.bar()) | RETURN (line 30) method-execution(void Foo.bar()) end public void bar() end class Foo -- (BCException) Impossible! annotation=[Tx] shadow=[method-execution(void Foo.foo()) at /private/tmp/ajcSandbox/ajcTest18924.tmp/DoubleAnnotationMatching.aj:28::533] pointcut is at [/private/tmp/ajcSandbox/ajcTest18924.tmp/DoubleAnnotationMatching.aj:15::316] when implementing on shadow method-execution(void Foo.foo()) when weaving type Foo when weaving classes when weaving when batch building BuildConfig[null] #Files=1 Impossible! annotation=[Tx] shadow=[method-execution(void Foo.foo()) at /private/tmp/ajcSandbox/ajcTest18924.tmp/DoubleAnnotationMatching.aj:28::533] pointcut is at [/private/tmp/ajcSandbox/ajcTest18924.tmp/DoubleAnnotationMatching.aj:15::316] when implementing on shadow method-execution(void Foo.foo()) when weaving type Foo when weaving classes when weaving when batch building BuildConfig[null] #Files=1 org.aspectj.weaver.BCException: Impossible! annotation=[Tx] shadow=[method-execution(void Foo.foo()) at /private/tmp/ajcSandbox/ajcTest18924.tmp/DoubleAnnotationMatching.aj:28::533] pointcut is at [/private/tmp/ajcSandbox/ajcTest18924.tmp/DoubleAnnotationMatching.aj:15::316] when implementing on shadow method-execution(void Foo.foo()) when weaving type Foo when weaving classes when weaving when batch building BuildConfig[null] #Files=1 at org.aspectj.weaver.patterns.AnnotationPointcut.findResidueInternal(AnnotationPointcut.java:201) at org.aspectj.weaver.patterns.Pointcut.findResidue(Pointcut.java:267) at org.aspectj.weaver.patterns.AndPointcut.findResidueInternal(AndPointcut.java:93) at org.aspectj.weaver.patterns.Pointcut.findResidue(Pointcut.java:267) at org.aspectj.weaver.patterns.AndPointcut.findResidueInternal(AndPointcut.java:93) at org.aspectj.weaver.patterns.Pointcut.findResidue(Pointcut.java:267) at org.aspectj.weaver.patterns.IfPointcut.findResidueInternal(IfPointcut.java:173) at org.aspectj.weaver.patterns.Pointcut.findResidue(Pointcut.java:267) at org.aspectj.weaver.patterns.AndPointcut.findResidueInternal(AndPointcut.java:93) at org.aspectj.weaver.patterns.Pointcut.findResidue(Pointcut.java:267) at org.aspectj.weaver.patterns.AndPointcut.findResidueInternal(AndPointcut.java:93) at org.aspectj.weaver.patterns.Pointcut.findResidue(Pointcut.java:267) at org.aspectj.weaver.patterns.OrPointcut.findResidueInternal(OrPointcut.java:96) at org.aspectj.weaver.patterns.Pointcut.findResidue(Pointcut.java:267) at org.aspectj.weaver.bcel.BcelAdvice.specializeOn(BcelAdvice.java:132) at org.aspectj.weaver.bcel.BcelShadow.prepareForMungers(BcelShadow.java:325) at org.aspectj.weaver.Shadow.implement(Shadow.java:455) at org.aspectj.weaver.bcel.BcelClassWeaver.implement(BcelClassWeaver.java:2236) at org.aspectj.weaver.bcel.BcelClassWeaver.weave(BcelClassWeaver.java:491) at org.aspectj.weaver.bcel.BcelClassWeaver.weave(BcelClassWeaver.java:109) at org.aspectj.weaver.bcel.BcelWeaver.weave(BcelWeaver.java:1560) at org.aspectj.weaver.bcel.BcelWeaver.weaveWithoutDump(BcelWeaver.java:1511) at org.aspectj.weaver.bcel.BcelWeaver.weaveAndNotify(BcelWeaver.java:1291) at org.aspectj.weaver.bcel.BcelWeaver.weave(BcelWeaver.java:1113) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.weave(AjCompilerAdapter.java:311) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.afterCompiling(AjCompilerAdapter.java:183) at org.aspectj.ajdt.internal.compiler.CompilerAdapter.ajc$afterReturning$org_aspectj_ajdt_internal_compiler_CompilerAdapter$2$f9cc9ca0(CompilerAdapter.aj:70) at org.aspectj.org.eclipse.jdt.internal.compiler.Compiler.compile(Compiler.java:367) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.performCompilation(AjBuildManager.java:862) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.doBuild(AjBuildManager.java:242) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.batchBuild(AjBuildManager.java:161) at org.aspectj.ajdt.ajc.AjdtCommand.doCommand(AjdtCommand.java:114) at org.aspectj.ajdt.ajc.AjdtCommand.runCommand(AjdtCommand.java:60) at org.aspectj.tools.ajc.Main.run(Main.java:367) at org.aspectj.tools.ajc.Main.runMain(Main.java:246) at org.aspectj.tools.ajc.Ajc.compile(Ajc.java:199) at org.aspectj.tools.ajc.Ajc.compile(Ajc.java:163) at org.aspectj.tools.ajc.AjcTestCase.ajc(AjcTestCase.java:510) at org.aspectj.testing.CompileSpec.execute(CompileSpec.java:53) at org.aspectj.testing.AjcTest.runTest(AjcTest.java:68) at org.aspectj.testing.XMLBasedAjcTestCase.runTest(XMLBasedAjcTestCase.java:111) at org.aspectj.systemtest.ajc152.Ajc152Tests.testDoubleAnnotationMatching_pr138221(Ajc152Tests.java:37) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:585) at junit.framework.TestCase.runTest(TestCase.java:154) at junit.framework.TestCase.runBare(TestCase.java:127) at junit.framework.TestResult$1.protect(TestResult.java:106) at junit.framework.TestResult.runProtected(TestResult.java:124) at junit.framework.TestResult.run(TestResult.java:109) at junit.framework.TestCase.run(TestCase.java:118) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:478) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:344) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:196) command was: ajc -classpath /Users/adrian/projects/aspectjdev/lib/test/aspectjrt.jar:../testing-client/bin:../runtime/bin:../aspectj5rt/bin:../lib/junit/junit.jar:../bridge/bin:../loadtime/bin:../weaver/bin:../weaver5/bin:../aj-build/jars/bridge.jar:../aj-build/jars/util.jar:../aj-build/jars/loadtime.jar:../aj-build/jars/weaver.jar:../aj-build/jars/weaver5.jar:../aj-build/jars/asm.jar:../lib/test/testing-client.jar:../lib/test/aspectjrt.jar:/tmp/ajcSandbox/ajcTest18924.tmp -1.5 /tmp/ajcSandbox/ajcTest18924.tmp/DoubleAnnotationMatching.aj -d /tmp/ajcSandbox/ajcTest18924.tmp at junit.framework.Assert.fail(Assert.java:47) at org.aspectj.tools.ajc.AjcTestCase.assertMessages(AjcTestCase.java:452) at org.aspectj.testing.CompileSpec.execute(CompileSpec.java:56) at org.aspectj.testing.AjcTest.runTest(AjcTest.java:68) at org.aspectj.testing.XMLBasedAjcTestCase.runTest(XMLBasedAjcTestCase.java:111) at org.aspectj.systemtest.ajc152.Ajc152Tests.testDoubleAnnotationMatching_pr138221(Ajc152Tests.java:37) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:585) at junit.framework.TestCase.runTest(TestCase.java:154) at junit.framework.TestCase.runBare(TestCase.java:127) at junit.framework.TestResult$1.protect(TestResult.java:106) at junit.framework.TestResult.runProtected(TestResult.java:124) at junit.framework.TestResult.run(TestResult.java:109) at junit.framework.TestCase.run(TestCase.java:118) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:478) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:344) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:196)
|
resolved fixed
|
6b2d9ae
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-05-17T15:48:34Z | 2006-04-24T17:33:20Z |
weaver/src/org/aspectj/weaver/patterns/AnnotationPointcut.java
|
/* *******************************************************************
* Copyright (c) 2004 IBM Corporation.
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* ******************************************************************/
package org.aspectj.weaver.patterns;
import java.io.DataOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.aspectj.bridge.MessageUtil;
import org.aspectj.util.FuzzyBoolean;
import org.aspectj.weaver.AjcMemberMaker;
import org.aspectj.weaver.AnnotatedElement;
import org.aspectj.weaver.BCException;
import org.aspectj.weaver.ISourceContext;
import org.aspectj.weaver.IntMap;
import org.aspectj.weaver.Member;
import org.aspectj.weaver.NameMangler;
import org.aspectj.weaver.NewFieldTypeMunger;
import org.aspectj.weaver.ResolvedMember;
import org.aspectj.weaver.ResolvedType;
import org.aspectj.weaver.Shadow;
import org.aspectj.weaver.ShadowMunger;
import org.aspectj.weaver.UnresolvedType;
import org.aspectj.weaver.VersionedDataInputStream;
import org.aspectj.weaver.WeaverMessages;
import org.aspectj.weaver.ast.Literal;
import org.aspectj.weaver.ast.Test;
import org.aspectj.weaver.ast.Var;
import org.aspectj.weaver.bcel.BcelTypeMunger;
/**
* @annotation(@Foo) or @annotation(foo)
*
* Matches any join point where the subject of the join point has an
* annotation matching the annotationTypePattern:
*
* Join Point Kind Subject
* ================================
* method call the target method
* method execution the method
* constructor call the constructor
* constructor execution the constructor
* get the target field
* set the target field
* adviceexecution the advice
* initialization the constructor
* preinitialization the constructor
* staticinitialization the type being initialized
* handler the declared type of the handled exception
*/
public class AnnotationPointcut extends NameBindingPointcut {
private ExactAnnotationTypePattern annotationTypePattern;
private ShadowMunger munger = null; // only set after concretization
private String declarationText;
public AnnotationPointcut(ExactAnnotationTypePattern type) {
super();
this.annotationTypePattern = type;
this.pointcutKind = Pointcut.ANNOTATION;
buildDeclarationText();
}
public AnnotationPointcut(ExactAnnotationTypePattern type, ShadowMunger munger) {
this(type);
this.munger = munger;
buildDeclarationText();
}
public ExactAnnotationTypePattern getAnnotationTypePattern() {
return annotationTypePattern;
}
public int couldMatchKinds() {
return Shadow.ALL_SHADOW_KINDS_BITS;
}
public Pointcut parameterizeWith(Map typeVariableMap) {
AnnotationPointcut ret = new AnnotationPointcut((ExactAnnotationTypePattern)annotationTypePattern.parameterizeWith(typeVariableMap));
ret.copyLocationFrom(this);
return ret;
}
/* (non-Javadoc)
* @see org.aspectj.weaver.patterns.Pointcut#fastMatch(org.aspectj.weaver.patterns.FastMatchInfo)
*/
public FuzzyBoolean fastMatch(FastMatchInfo info) {
if (info.getKind() == Shadow.StaticInitialization) {
return annotationTypePattern.fastMatches(info.getType());
} else {
return FuzzyBoolean.MAYBE;
}
}
/* (non-Javadoc)
* @see org.aspectj.weaver.patterns.Pointcut#match(org.aspectj.weaver.Shadow)
*/
protected FuzzyBoolean matchInternal(Shadow shadow) {
AnnotatedElement toMatchAgainst = null;
Member member = shadow.getSignature();
ResolvedMember rMember = member.resolve(shadow.getIWorld());
if (rMember == null) {
if (member.getName().startsWith(NameMangler.PREFIX)) {
return FuzzyBoolean.NO;
}
shadow.getIWorld().getLint().unresolvableMember.signal(member.toString(), getSourceLocation());
return FuzzyBoolean.NO;
}
Shadow.Kind kind = shadow.getKind();
if (kind == Shadow.StaticInitialization) {
toMatchAgainst = rMember.getDeclaringType().resolve(shadow.getIWorld());
} else if ( (kind == Shadow.ExceptionHandler)) {
toMatchAgainst = rMember.getParameterTypes()[0].resolve(shadow.getIWorld());
} else {
toMatchAgainst = rMember;
// FIXME asc I'd like to get rid of this bit of logic altogether, shame ITD fields don't have an effective sig attribute
// FIXME asc perf cache the result of discovering the member that contains the real annotations
if (rMember.isAnnotatedElsewhere()) {
if (kind==Shadow.FieldGet || kind==Shadow.FieldSet) {
List mungers = rMember.getDeclaringType().resolve(shadow.getIWorld()).getInterTypeMungers(); // FIXME asc should include supers with getInterTypeMungersIncludingSupers?
for (Iterator iter = mungers.iterator(); iter.hasNext();) {
BcelTypeMunger typeMunger = (BcelTypeMunger) iter.next();
if (typeMunger.getMunger() instanceof NewFieldTypeMunger) {
ResolvedMember fakerm = typeMunger.getSignature();
if (fakerm.equals(member)) {
ResolvedMember ajcMethod = AjcMemberMaker.interFieldInitializer(fakerm,typeMunger.getAspectType());
ResolvedMember rmm = findMethod(typeMunger.getAspectType(),ajcMethod);
toMatchAgainst = rmm;
}
}
}
}
}
}
annotationTypePattern.resolve(shadow.getIWorld());
return annotationTypePattern.matches(toMatchAgainst);
}
private ResolvedMember findMethod(ResolvedType aspectType, ResolvedMember ajcMethod) {
ResolvedMember decMethods[] = aspectType.getDeclaredMethods();
for (int i = 0; i < decMethods.length; i++) {
ResolvedMember member = decMethods[i];
if (member.equals(ajcMethod)) return member;
}
return null;
}
/* (non-Javadoc)
* @see org.aspectj.weaver.patterns.Pointcut#resolveBindings(org.aspectj.weaver.patterns.IScope, org.aspectj.weaver.patterns.Bindings)
*/
protected void resolveBindings(IScope scope, Bindings bindings) {
if (!scope.getWorld().isInJava5Mode()) {
scope.message(MessageUtil.error(WeaverMessages.format(WeaverMessages.ATANNOTATION_ONLY_SUPPORTED_AT_JAVA5_LEVEL),
getSourceLocation()));
return;
}
annotationTypePattern = (ExactAnnotationTypePattern) annotationTypePattern.resolveBindings(scope,bindings,true);
// must be either a Var, or an annotation type pattern
}
/* (non-Javadoc)
* @see org.aspectj.weaver.patterns.Pointcut#concretize1(org.aspectj.weaver.ResolvedType, org.aspectj.weaver.IntMap)
*/
protected Pointcut concretize1(ResolvedType inAspect, ResolvedType declaringType, IntMap bindings) {
ExactAnnotationTypePattern newType = (ExactAnnotationTypePattern) annotationTypePattern.remapAdviceFormals(bindings);
Pointcut ret = new AnnotationPointcut(newType, bindings.getEnclosingAdvice());
ret.copyLocationFrom(this);
return ret;
}
/* (non-Javadoc)
* @see org.aspectj.weaver.patterns.Pointcut#findResidue(org.aspectj.weaver.Shadow, org.aspectj.weaver.patterns.ExposedState)
*/
protected Test findResidueInternal(Shadow shadow, ExposedState state) {
if (annotationTypePattern instanceof BindingAnnotationTypePattern) {
BindingAnnotationTypePattern btp = (BindingAnnotationTypePattern)annotationTypePattern;
UnresolvedType annotationType = btp.getAnnotationType();
Var var = shadow.getKindedAnnotationVar(annotationType);
// This should not happen, we shouldn't have gotten this far
// if we weren't going to find the annotation
if (var == null) throw new BCException("Impossible! annotation=["+annotationType+
"] shadow=["+shadow+" at "+shadow.getSourceLocation()+
"] pointcut is at ["+getSourceLocation()+"]");//return Literal.FALSE;
state.set(btp.getFormalIndex(),var);
}
if (matchInternal(shadow).alwaysTrue())
return Literal.TRUE;
else
return Literal.FALSE;
}
/* (non-Javadoc)
* @see org.aspectj.weaver.patterns.NameBindingPointcut#getBindingAnnotationTypePatterns()
*/
public List getBindingAnnotationTypePatterns() {
if (annotationTypePattern instanceof BindingAnnotationTypePattern) {
List l = new ArrayList();
l.add(annotationTypePattern);
return l;
} else return Collections.EMPTY_LIST;
}
/* (non-Javadoc)
* @see org.aspectj.weaver.patterns.NameBindingPointcut#getBindingTypePatterns()
*/
public List getBindingTypePatterns() {
return Collections.EMPTY_LIST;
}
/* (non-Javadoc)
* @see org.aspectj.weaver.patterns.PatternNode#write(java.io.DataOutputStream)
*/
public void write(DataOutputStream s) throws IOException {
s.writeByte(Pointcut.ANNOTATION);
annotationTypePattern.write(s);
writeLocation(s);
}
public static Pointcut read(VersionedDataInputStream s, ISourceContext context) throws IOException {
AnnotationTypePattern type = AnnotationTypePattern.read(s, context);
AnnotationPointcut ret = new AnnotationPointcut((ExactAnnotationTypePattern)type);
ret.readLocation(context, s);
return ret;
}
public boolean equals(Object other) {
if (!(other instanceof AnnotationPointcut)) return false;
AnnotationPointcut o = (AnnotationPointcut)other;
return o.annotationTypePattern.equals(this.annotationTypePattern);
}
public int hashCode() {
int result = 17;
result = 37*result + annotationTypePattern.hashCode();
return result;
}
public void buildDeclarationText() {
StringBuffer buf = new StringBuffer();
buf.append("@annotation(");
String annPatt = annotationTypePattern.toString();
buf.append(annPatt.startsWith("@") ? annPatt.substring(1) : annPatt);
buf.append(")");
this.declarationText = buf.toString();
}
public String toString() {
return this.declarationText;
}
public Object accept(PatternNodeVisitor visitor, Object data) {
return visitor.visit(this, data);
}
}
|
142,466 |
Bug 142466 [ltw] Fail at runtime if abstract methods are not implemented in a hierarchy that finishes with an XML aspect
|
see pr125480 - copying the test for that will be a good basis for a test for this bug. We don't check that when defining a concrete aspect there are no unimplemented abstract methods in the aspect we are concretizing.
|
resolved fixed
|
69e24e9
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-05-23T07:55:53Z | 2006-05-18T11:00:00Z |
loadtime/src/org/aspectj/weaver/loadtime/ConcreteAspectCodeGen.java
|
/*******************************************************************************
* Copyright (c) 2005 Contributors.
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Eclipse Public License v1.0
* which accompanies this distribution and is available at
* http://eclipse.org/legal/epl-v10.html
*
* Contributors:
* Alexandre Vasseur initial implementation
*******************************************************************************/
package org.aspectj.weaver.loadtime;
import org.aspectj.apache.bcel.Constants;
import org.aspectj.apache.bcel.classfile.JavaClass;
import org.aspectj.apache.bcel.generic.InstructionConstants;
import org.aspectj.apache.bcel.generic.InstructionList;
import org.aspectj.apache.bcel.generic.ObjectType;
import org.aspectj.apache.bcel.generic.Type;
import org.aspectj.apache.bcel.generic.annotation.AnnotationGen;
import org.aspectj.apache.bcel.generic.annotation.ElementNameValuePairGen;
import org.aspectj.apache.bcel.generic.annotation.ElementValueGen;
import org.aspectj.apache.bcel.generic.annotation.SimpleElementValueGen;
import org.aspectj.bridge.IMessage;
import org.aspectj.bridge.Message;
import org.aspectj.weaver.AnnotationX;
import org.aspectj.weaver.ResolvedMember;
import org.aspectj.weaver.ResolvedType;
import org.aspectj.weaver.UnresolvedType;
import org.aspectj.weaver.World;
import org.aspectj.weaver.bcel.BcelPerClauseAspectAdder;
import org.aspectj.weaver.bcel.BcelWorld;
import org.aspectj.weaver.bcel.LazyClassGen;
import org.aspectj.weaver.bcel.LazyMethodGen;
import org.aspectj.weaver.loadtime.definition.Definition;
import org.aspectj.weaver.patterns.PerClause;
import org.aspectj.weaver.patterns.PerSingleton;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
/**
* Generates bytecode for concrete-aspect
* <p/>
* The concrete aspect is @AspectJ code generated. As it is build during aop.xml definitions registration
* we perform the type munging for perclause ie aspectOf artifact directly, instead of waiting for it
* to go thru the weaver (that we are in the middle of configuring).
*
* @author <a href="mailto:alex AT gnilux DOT com">Alexandre Vasseur</a>
*/
public class ConcreteAspectCodeGen {
private final static String[] EMPTY_STRINGS = new String[0];
private final static Type[] EMPTY_TYPES = new Type[0];
/**
* Concrete aspect definition we build for
*/
private final Definition.ConcreteAspect m_concreteAspect;
/**
* World for which we build for
*/
private final World m_world;
/**
* Set to true when all is checks are verified
*/
private boolean m_isValid = false;
/**
* The parent aspect, not concretized
*/
private ResolvedType m_parent;
/**
* Aspect perClause, used for direct munging of aspectOf artifacts
*/
private PerClause m_perClause;
/**
* Create a new compiler for a concrete aspect
*
* @param concreteAspect
* @param world
*/
ConcreteAspectCodeGen(Definition.ConcreteAspect concreteAspect, World world) {
m_concreteAspect = concreteAspect;
m_world = world;
}
/**
* Checks that concrete aspect is valid
*
* @return true if ok, false otherwise
*/
public boolean validate() {
if (!(m_world instanceof BcelWorld)) {
reportError("Internal error: world must be of type BcelWorld");
return false;
}
// name must be undefined so far
ResolvedType current = m_world.resolve(m_concreteAspect.name, true);
if (!current.isMissing()) {
reportError("Attempt to concretize but choosen aspect name already defined: " + stringify());
return false;
}
// it can happen that extends is null, for precedence only declaration
if (m_concreteAspect.extend == null && m_concreteAspect.precedence != null) {
if (m_concreteAspect.pointcuts.isEmpty()) {
m_isValid = true;
m_perClause = new PerSingleton();
m_parent = null;
return true;// no need to checks more in that special case
} else {
reportError("Attempt to use nested pointcuts without extends clause: "+stringify());
return false;
}
}
m_parent = m_world.resolve(m_concreteAspect.extend, true);
// handle inner classes
if (m_parent.isMissing()) {
// fallback on inner class lookup mechanism
String fixedName = m_concreteAspect.extend;
int hasDot = fixedName.lastIndexOf('.');
while (hasDot > 0) {
char[] fixedNameChars = fixedName.toCharArray();
fixedNameChars[hasDot] = '$';
fixedName = new String(fixedNameChars);
hasDot = fixedName.lastIndexOf('.');
m_parent = m_world.resolve(UnresolvedType.forName(fixedName), true);
if (!m_parent.isMissing()) {
break;
}
}
}
if (m_parent.isMissing()) {
reportError("Cannot find m_parent aspect for: " + stringify());
return false;
}
// extends must be abstract
if (!m_parent.isAbstract()) {
reportError("Attempt to concretize a non-abstract aspect: " + stringify());
return false;
}
// m_parent must be aspect
if (!m_parent.isAspect()) {
reportError("Attempt to concretize a non aspect: " + stringify());
return false;
}
// must have all abstractions defined
List elligibleAbstractions = new ArrayList();
Iterator methods = m_parent.getMethods();
while (methods.hasNext()) {
ResolvedMember method = (ResolvedMember) methods.next();
if (method.isAbstract()) {
if ("()V".equals(method.getSignature())) {
String n = method.getName();
if (n.startsWith("ajc$pointcut")) { // Allow for the abstract pointcut being from a code style aspect compiled with -1.5 (see test for 128744)
n = n.substring(14);
n = n.substring(0,n.indexOf("$"));
elligibleAbstractions.add(n);
} else {
// Only interested in abstract methods that take no parameters and are marked @Pointcut
if (hasPointcutAnnotation(method))
elligibleAbstractions.add(method.getName());
}
} else {
reportError("Abstract method '" + method.getName() + "' cannot be concretized as a pointcut (illegal signature, must have no arguments, must return void): " + stringify());
return false;
}
}
}
List pointcutNames = new ArrayList();
for (Iterator it = m_concreteAspect.pointcuts.iterator(); it.hasNext();) {
Definition.Pointcut abstractPc = (Definition.Pointcut) it.next();
pointcutNames.add(abstractPc.name);
}
for (Iterator it = elligibleAbstractions.iterator(); it.hasNext();) {
String elligiblePc = (String) it.next();
if (!pointcutNames.contains(elligiblePc)) {
reportError("Abstract pointcut '" + elligiblePc + "' not configured: " + stringify());
return false;
}
}
m_perClause = m_parent.getPerClause();
m_isValid = true;
return m_isValid;
}
/**
* Rebuild the XML snip that defines this concrete aspect, for log error purpose
*
* @return string repr.
*/
private String stringify() {
StringBuffer sb = new StringBuffer("<concrete-aspect name='");
sb.append(m_concreteAspect.name);
sb.append("' extends='");
sb.append(m_concreteAspect.extend);
sb.append("'/> in aop.xml");
return sb.toString();
}
private boolean hasPointcutAnnotation(ResolvedMember member) {
AnnotationX[] as = member.getAnnotations();
if (as==null || as.length==0) return false;
for (int i = 0; i < as.length; i++) {
if (as[i].getTypeSignature().equals("Lorg/aspectj/lang/annotation/Pointcut;")) {
return true;
}
}
return false;
}
/**
* Build the bytecode for the concrete aspect
*
* @return concrete aspect bytecode
*/
public byte[] getBytes() {
if (!m_isValid) {
throw new RuntimeException("Must validate first");
}
//TODO AV - abstract away from BCEL...
// @Aspect //inherit clause from m_parent
// @DeclarePrecedence("....") // if any
// public class xxxName [extends xxxExtends] {
// [@Pointcut(xxxExpression-n)
// public void xxxName-n() {}]
// }
// @Aspect public class ...
LazyClassGen cg = new LazyClassGen(
m_concreteAspect.name.replace('.', '/'),
(m_parent==null)?"java/lang/Object":m_parent.getName().replace('.', '/'),
null,//TODO AV - we could point to the aop.xml that defines it and use JSR-45
Modifier.PUBLIC + Constants.ACC_SUPER,
EMPTY_STRINGS,
m_world
);
AnnotationGen ag = new AnnotationGen(
new ObjectType("org/aspectj/lang/annotation/Aspect"),
Collections.EMPTY_LIST,
true,
cg.getConstantPoolGen()
);
cg.addAnnotation(ag.getAnnotation());
if (m_concreteAspect.precedence != null) {
SimpleElementValueGen svg = new SimpleElementValueGen(
ElementValueGen.STRING,
cg.getConstantPoolGen(),
m_concreteAspect.precedence
);
List elems = new ArrayList();
elems.add(new ElementNameValuePairGen("value", svg, cg.getConstantPoolGen()));
AnnotationGen agprec = new AnnotationGen(
new ObjectType("org/aspectj/lang/annotation/DeclarePrecedence"),
elems,
true,
cg.getConstantPoolGen()
);
cg.addAnnotation(agprec.getAnnotation());
}
// default constructor
LazyMethodGen init = new LazyMethodGen(
Modifier.PUBLIC,
Type.VOID,
"<init>",
EMPTY_TYPES,
EMPTY_STRINGS,
cg
);
InstructionList cbody = init.getBody();
cbody.append(InstructionConstants.ALOAD_0);
cbody.append(cg.getFactory().createInvoke(
(m_parent==null)?"java/lang/Object":m_parent.getName().replace('.', '/'),
"<init>",
Type.VOID,
EMPTY_TYPES,
Constants.INVOKESPECIAL
));
cbody.append(InstructionConstants.RETURN);
cg.addMethodGen(init);
for (Iterator it = m_concreteAspect.pointcuts.iterator(); it.hasNext();) {
Definition.Pointcut abstractPc = (Definition.Pointcut) it.next();
LazyMethodGen mg = new LazyMethodGen(
Modifier.PUBLIC,//TODO AV - respect visibility instead of opening up?
Type.VOID,
abstractPc.name,
EMPTY_TYPES,
EMPTY_STRINGS,
cg
);
SimpleElementValueGen svg = new SimpleElementValueGen(
ElementValueGen.STRING,
cg.getConstantPoolGen(),
abstractPc.expression
);
List elems = new ArrayList();
elems.add(new ElementNameValuePairGen("value", svg, cg.getConstantPoolGen()));
AnnotationGen mag = new AnnotationGen(
new ObjectType("org/aspectj/lang/annotation/Pointcut"),
elems,
true,
cg.getConstantPoolGen()
);
AnnotationX max = new AnnotationX(mag.getAnnotation(), m_world);
mg.addAnnotation(max);
InstructionList body = mg.getBody();
body.append(InstructionConstants.RETURN);
cg.addMethodGen(mg);
}
// handle the perClause
BcelPerClauseAspectAdder perClauseMunger = new BcelPerClauseAspectAdder(
ResolvedType.forName(m_concreteAspect.name).resolve(m_world),
m_perClause.getKind()
);
perClauseMunger.forceMunge(cg, false);
//TODO AV - unsafe cast
// register the fresh new class into the world repository as it does not exist on the classpath anywhere
JavaClass jc = cg.getJavaClass((BcelWorld) m_world);
((BcelWorld) m_world).addSourceObjectType(jc);
return jc.getBytes();
}
/**
* Error reporting
*
* @param message
*/
private void reportError(String message) {
m_world.getMessageHandler().handleMessage(new Message(message, IMessage.ERROR, null, null));
}
}
|
142,466 |
Bug 142466 [ltw] Fail at runtime if abstract methods are not implemented in a hierarchy that finishes with an XML aspect
|
see pr125480 - copying the test for that will be a good basis for a test for this bug. We don't check that when defining a concrete aspect there are no unimplemented abstract methods in the aspect we are concretizing.
|
resolved fixed
|
69e24e9
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-05-23T07:55:53Z | 2006-05-18T11:00:00Z |
tests/bugs152/pr142466/AtAspectTestConcreteMethods.java
| |
142,466 |
Bug 142466 [ltw] Fail at runtime if abstract methods are not implemented in a hierarchy that finishes with an XML aspect
|
see pr125480 - copying the test for that will be a good basis for a test for this bug. We don't check that when defining a concrete aspect there are no unimplemented abstract methods in the aspect we are concretizing.
|
resolved fixed
|
69e24e9
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-05-23T07:55:53Z | 2006-05-18T11:00:00Z |
tests/bugs152/pr142466/HelloWorld.java
| |
142,466 |
Bug 142466 [ltw] Fail at runtime if abstract methods are not implemented in a hierarchy that finishes with an XML aspect
|
see pr125480 - copying the test for that will be a good basis for a test for this bug. We don't check that when defining a concrete aspect there are no unimplemented abstract methods in the aspect we are concretizing.
|
resolved fixed
|
69e24e9
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-05-23T07:55:53Z | 2006-05-18T11:00:00Z |
tests/bugs152/pr142466/case2/AtAspectTestConcreteMethods.java
| |
142,466 |
Bug 142466 [ltw] Fail at runtime if abstract methods are not implemented in a hierarchy that finishes with an XML aspect
|
see pr125480 - copying the test for that will be a good basis for a test for this bug. We don't check that when defining a concrete aspect there are no unimplemented abstract methods in the aspect we are concretizing.
|
resolved fixed
|
69e24e9
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-05-23T07:55:53Z | 2006-05-18T11:00:00Z |
tests/bugs152/pr142466/case2/HelloWorld.java
| |
142,466 |
Bug 142466 [ltw] Fail at runtime if abstract methods are not implemented in a hierarchy that finishes with an XML aspect
|
see pr125480 - copying the test for that will be a good basis for a test for this bug. We don't check that when defining a concrete aspect there are no unimplemented abstract methods in the aspect we are concretizing.
|
resolved fixed
|
69e24e9
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-05-23T07:55:53Z | 2006-05-18T11:00:00Z |
tests/src/org/aspectj/systemtest/ajc152/Ajc152Tests.java
|
/*******************************************************************************
* Copyright (c) 2006 IBM
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* Andy Clement - initial API and implementation
*******************************************************************************/
package org.aspectj.systemtest.ajc152;
import java.io.File;
import junit.framework.Test;
import org.aspectj.testing.XMLBasedAjcTestCase;
public class Ajc152Tests extends org.aspectj.testing.XMLBasedAjcTestCase {
public void testComplexGenericDecl_pr137568() { runTest("complicated generics declaration");}
public void testItdOnInnerTypeOfGenericType_pr132349() { runTest("ITD on inner type of generic type");}
public void testItdOnInnerTypeOfGenericType_pr132349_2() { runTest("ITD on inner type of generic type - 2");}
public void testItdOnInnerTypeOfGenericType_pr132349_3() { runTest("ITD on inner type of generic type - 3");}
// public void testCovarianceAndDecp_pr128443_1() { runTest("covariance and decp - 1"); }
public void testLTWGeneratedAspectAbstractMethod_pr125480() { runTest("aop.xml aspect inheriting abstract method ");}
public void testLTWGeneratedAspectAbstractMethod_pr125480_2() { runTest("aop.xml aspect inheriting abstract method - code style");}
//public void testSuperITDExplosion_pr134425() { runTest("super ITDs");}
//public void testMisbehavingDeclareAnnotation_pr135865() { runTest("misbehaving declare annotation");}
//public void testMisbehavingDeclareAnnotation_pr135865_2() { runTest("misbehaving declare annotation - 2");}
public void testCompletelyBrokenAopConcretization_pr142165_1() { runTest("broken concretization");}
public void testCompletelyBrokenAopConcretization_pr142165_2() { runTest("broken concretization - 2");}
public void testCompletelyBrokenAopConcretization_pr142165_3() { runTest("broken concretization - 3");}
public void testVerifyErrorLTW_pr135068() { runTest("ltw verifyerror");}
public void testVerifyErrorLTW_pr135068_2() { runTest("ltw verifyerror - 2");}
public void testVerifyErrorLTW_pr135068_3() { runTest("ltw verifyerror - 3");}
public void testVerifyErrorLTW_pr135068_4() { runTest("ltw verifyerror - 4");}
public void testVerifyErrorForComplexCflow_pr136026() { runTest("verifyerror");}
public void testVerifyErrorForComplexCflow_pr136026_2() { runTest("verifyerror - 2");}
public void testAnnotationsAndGenericsBCException_pr129704() { runTest("annotations and generics leading to BCException");}
public void testMethodTooBigAfterWeaving_pr138384() { runTest("method too big"); }
public void testNotAtWithincode_pr138158_1() { runTest("not at withincode - 1");}
public void testNotAtWithincode_pr138158_2() { runTest("not at withincode - 2");}
public void testNotAtWithincode_pr138158_3() { runTest("not at within - 3");}
public void testNpeOnDup_pr138143() { runTest("npe on duplicate method with ataj");}
public void testPointcutsAndGenerics_pr137496_1() { runTest("pointcuts and generics - B");}
public void testPointcutsAndGenerics_pr137496_2() { runTest("pointcuts and generics - D");}
public void testPointcutsAndGenerics_pr137496_3() { runTest("pointcuts and generics - E");}
public void testPointcutsAndGenerics_pr137496_4() { runTest("pointcuts and generics - F");}
public void testPointcutsAndGenerics_pr137496_5() { runTest("pointcuts and generics - G");}
public void testPointcutsAndGenerics_pr137496_6() { runTest("pointcuts and generics - H");}
public void testAspectLibrariesAndASM_pr135001() { runTest("aspect libraries and asm");}
public void testStackOverflow_pr136258() { runTest("stack overflow");}
public void testIncorrectOverridesEvaluation13() { runTest("incorrect overrides evaluation - 1.3"); }
public void testIncorrectOverridesEvaluation15() { runTest("incorrect overrides evaluation - 1.5"); }
public void testAtWithinCodeBug_pr138798() { runTest("atWithinCodeBug"); }
public void testReferencePCutInDeclareWarning_pr138215() { runTest("Reference pointcut fails inside @DeclareWarning");}
public void testReferencePCutInPerClause_pr138219() { runTest("Can't use a FQ Reference pointcut in any pointcut expression referenced by a per-clause");}
public void testReferencePCutInPerClause_pr130722() { runTest("FQ Reference pointcut from perclause ref pc"); }
public void testDoubleAnnotationMatching_pr138223() { runTest("Double at annotation matching (no binding)");}
public void testSuperCallsInAtAspectJAdvice_pr139749() { runTest("Super calls in @AspectJ advice");}
public void testNoClassCastExceptionWithPerThis_pr138286() { runTest("No ClassCastException with perThis");}
// this next one reported as a bug by Rob Harrop, but I can't reproduce the failure yet...
//public void testAtAspectWithReferencePCPerClause_pr138220() { runTest("@Aspect with reference pointcut in perclause");}
public void testJarChecking_pr137235_1() { runTest("directory with .jar extension: source and outjar"); }
public void testJarChecking_pr137235_2() { runTest("directory with .jar extension"); }
public void testMakePreMethodNPE_pr136393() { runTest("NPE in makePreMethod");}
// tests that can't be included for some reason
// Not valid whilst the ajc compiler forces debug on (ignores -g:none) - it will be green but is invalid, trust me
// public void testLongWindedMessages_pr129408() { runTest("long winded ataj messages");}
/////////////////////////////////////////
public static Test suite() {
return XMLBasedAjcTestCase.loadSuite(Ajc152Tests.class);
}
protected File getSpecFile() {
return new File("../tests/src/org/aspectj/systemtest/ajc152/ajc152.xml");
}
}
|
143,930 |
Bug 143930 create constructor ipe in same was as method ipes
| null |
resolved fixed
|
26a8a86
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-05-30T09:59:53Z | 2006-05-26T10:40:00Z |
ajdoc/testsrc/org/aspectj/tools/ajdoc/CoverageTestCase.java
|
/* *******************************************************************
* Copyright (c) 2003 Contributors.
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* Mik Kersten initial implementation
* ******************************************************************/
package org.aspectj.tools.ajdoc;
import java.io.File;
import java.util.List;
/**
* A long way to go until full coverage, but this is the place to add more.
*
* @author Mik Kersten
*/
public class CoverageTestCase extends AjdocTestCase {
protected File file0,file1,aspect1,file2,file3,file4,file5,file6,file7,file8,file9,file10;
protected void setUp() throws Exception {
super.setUp();
initialiseProject("coverage");
createFiles();
}
public void testOptions() {
String[] args = {
"-private",
"-encoding",
"EUCJIS",
"-docencoding",
"EUCJIS",
"-charset",
"UTF-8",
"-classpath",
AjdocTests.ASPECTJRT_PATH.getPath(),
"-d",
getAbsolutePathOutdir(),
file0.getAbsolutePath(),
};
org.aspectj.tools.ajdoc.Main.main(args);
assertTrue(true);
}
/**
* Test the "-public" argument
*/
public void testCoveragePublicMode() throws Exception {
File[] files = {file3,file9};
runAjdoc("public","1.4",files);
// have passed the "public" modifier as well as
// one public and one package visible class. There
// should only be ajdoc for the public class
File htmlFile = new File(getAbsolutePathOutdir() + "/foo/PkgVisibleClass.html");
assertFalse("ajdoc for PkgVisibleClass shouldn't exist because passed" +
" the 'public' flag to ajdoc",htmlFile.exists());
htmlFile = new File(getAbsolutePathOutdir() + "/foo/PlainJava.html");
if (htmlFile == null || !htmlFile.exists()) {
fail("couldn't find " + htmlFile.getAbsolutePath()
+ " - were there compilation errors?");
}
// check there's no private fields within the file, that
// the file contains the getI() method but doesn't contain
// the private ClassBar, Bazz and Jazz classes.
String[] strings = { "private", "getI()","ClassBar", "Bazz", "Jazz"};
List missing = AjdocOutputChecker.getMissingStringsInFile(htmlFile,strings);
assertEquals("There should be 4 missing strings",4,missing.size());
assertTrue(htmlFile.getName() + " should not contain the private modifier",missing.contains("private"));
assertTrue(htmlFile.getName() + " should not contain the private ClassBar class",missing.contains("ClassBar"));
assertTrue(htmlFile.getName() + " should not contain the private Bazz class",missing.contains("Bazz"));
assertTrue(htmlFile.getName() + " should not contain the private Jazz class",missing.contains("Jazz"));
}
/**
* Test that the ajdoc for an aspect has the title "Aspect"
*/
public void testAJdocHasAspectTitle() throws Exception {
File[] files = {new File(getAbsoluteProjectDir() + "/pkg/A.aj")};
runAjdoc("private","1.4",files);
File htmlFile = new File(getAbsolutePathOutdir() + "/pkg/A.html");
if (htmlFile == null || !htmlFile.exists()) {
fail("couldn't find " + htmlFile.getAbsolutePath()+ " - were there compilation errors?");
}
assertTrue(htmlFile.getAbsolutePath() + " should have Aspect A as it's title",
AjdocOutputChecker.containsString(htmlFile,"Aspect A"));
}
/**
* Test that the ajdoc for a class has the title "Class"
*/
public void testAJdocHasClassTitle() throws Exception {
File[] files = {new File(getAbsoluteProjectDir() + "/pkg/C.java")};
runAjdoc("private","1.4",files);
File htmlFile = new File(getAbsolutePathOutdir() + "/pkg/C.html");
if (htmlFile == null || !htmlFile.exists()) {
fail("couldn't find " + htmlFile.getAbsolutePath()+ " - were there compilation errors?");
}
assertTrue(htmlFile.getAbsolutePath() + " should have Class C as it's title",
AjdocOutputChecker.containsString(htmlFile,"Class C"));
}
/**
* Test that the ajdoc for an inner aspect is entitled "Aspect" rather
* than "Class", but that the enclosing class is still "Class"
*/
public void testInnerAspect() throws Exception {
File[] files = {file1, file2};
runAjdoc("private","1.4",files);
File htmlFile = new File(getAbsolutePathOutdir() + "/foo/ClassA.InnerAspect.html");
if (htmlFile == null || !htmlFile.exists()) {
fail("couldn't find " + htmlFile.getAbsolutePath()
+ " - were there compilation errors?");
}
// ensure that the file is entitled "Aspect ClassA.InnerAspect" rather
// than "Class ClassA.InnerAspect"
String[] strings = { "Aspect ClassA.InnerAspect",
"<PRE>static aspect <B>ClassA.InnerAspect</B><DT>extends java.lang.Object</DL>",
"Class ClassA.InnerAspect",
"<PRE>static class <B>ClassA.InnerAspect</B><DT>extends java.lang.Object</DL>"};
List missing = AjdocOutputChecker.getMissingStringsInFile(htmlFile,strings);
assertEquals("There should be 2 missing strings",2,missing.size());
assertTrue(htmlFile.getName() + " should not have Class as it's title",missing.contains("Class ClassA.InnerAspect"));
assertTrue(htmlFile.getName() + " should not have class in its subtitle",missing.contains("<PRE>static class <B>ClassA.InnerAspect</B><DT>extends java.lang.Object</DL>"));
// get the html file for the enclosing class
File htmlFileClass = new File(getAbsolutePathOutdir() + "/foo/ClassA.html");
if (htmlFileClass == null || !htmlFileClass.exists()) {
fail("couldn't find " + htmlFileClass.getAbsolutePath()
+ " - were there compilation errors?");
}
// ensure that the file is entitled "Class ClassA" and
// has not been changed to "Aspect ClassA"
String[] classStrings = { "Class ClassA</H2>",
"public abstract class <B>ClassA</B><DT>extends java.lang.Object<DT>",
"Aspect ClassA</H2>",
"public abstract aspect <B>ClassA</B><DT>extends java.lang.Object<DT>"};
List classMissing = AjdocOutputChecker.getMissingStringsInFile(htmlFileClass,classStrings);
assertEquals("There should be 2 missing strings",2,classMissing.size());
assertTrue(htmlFileClass.getName() + " should not have Aspect as it's title",classMissing.contains("Aspect ClassA</H2>"));
assertTrue(htmlFileClass.getName() + " should not have aspect in its subtitle",classMissing.contains("public abstract aspect <B>ClassA</B><DT>extends java.lang.Object<DT>"));
}
/**
* Test that all the different types of advice appear
* with the named pointcut in it's description
*/
public void testAdviceNamingCoverage() throws Exception {
File[] files = {file4};
runAjdoc("private","1.4",files);
File htmlFile = new File(getAbsolutePathOutdir() + "/foo/AdviceNamingCoverage.html");
if (htmlFile == null || !htmlFile.exists()) {
fail("couldn't find " + htmlFile.getAbsolutePath()
+ " - were there compilation errors?");
}
String[] strings = {
"after(): named..",
"afterReturning(int,int): namedWithArgs..",
"afterThrowing(): named..",
"before(): named..",
"around(int): namedWithOneArg..",
"before(int):",
"before(int): named()..",
"before():"};
List missing = AjdocOutputChecker.getMissingStringsInSection(
htmlFile, strings,"ADVICE DETAIL SUMMARY");
assertTrue(htmlFile.getName() + " should contain all advice in the Advice Detail section",missing.isEmpty());
missing = AjdocOutputChecker.getMissingStringsInSection(
htmlFile,strings,"ADVICE SUMMARY");
assertTrue(htmlFile.getName() + " should contain all advice in the Advice Summary section",missing.isEmpty());
}
/**
* Test that all the advises relationships appear in the
* Advice Detail and Advice Summary sections and that
* the links are correct
*/
public void testAdvisesRelationshipCoverage() throws Exception {
File[] files = {file4};
runAjdoc("private","1.4",files);
File htmlFile = new File(getAbsolutePathOutdir() + "/foo/AdvisesRelationshipCoverage.html");
if (htmlFile == null || !htmlFile.exists()) {
fail("couldn't find " + htmlFile.getAbsolutePath() + " - were there compilation errors?");
}
String[] strings = {
"before(): methodExecutionP..",
"HREF=\"../foo/Point.html#setX(int)\"",
"before(): constructorExecutionP..",
"HREF=\"../foo/Point.html#Point()\"",
"before(): callMethodP..",
"HREF=\"../foo/Point.html#changeX(int)\"",
"before(): callConstructorP..",
"HREF=\"../foo/Point.html#doIt()\"",
"before(): getP..",
"HREF=\"../foo/Point.html#getX()\"",
"before(): setP..",
"HREF=\"../foo/Point.html\"><tt>foo.Point</tt></A>, <A HREF=\"../foo/Point.html#Point()\"><tt>foo.Point.Point()</tt></A>, <A HREF=\"../foo/Point.html#setX(int)\"",
"before(): initializationP..",
"HREF=\"../foo/Point.html#Point()\"",
"before(): staticinitializationP..",
"HREF=\"../foo/Point.html\"",
"before(): handlerP..",
"HREF=\"../foo/Point.html#doIt()\""
};
for (int i = 0; i < strings.length - 1; i = i+2) {
boolean b = AjdocOutputChecker.detailSectionContainsRel(
htmlFile,"ADVICE DETAIL SUMMARY",strings[i],
HtmlDecorator.HtmlRelationshipKind.ADVISES,
strings[i+1]);
assertTrue(strings[i] + " should advise " + strings[i+1] +
" in the Advice Detail section", b);
}
for (int i = 0; i < strings.length - 1; i = i+2) {
boolean b = AjdocOutputChecker.summarySectionContainsRel(
htmlFile,"ADVICE SUMMARY",strings[i],
HtmlDecorator.HtmlRelationshipKind.ADVISES,
strings[i+1]);
assertTrue(strings[i] + " should advise " + strings[i+1] +
" in the Advice Summary section", b);
}
}
/**
* Test that the advised by relationship appears in the ajdoc when the
* advice is associated with a method execution pointcut
*/
public void testAdvisedByMethodExecution() throws Exception {
File[] files = {file4};
runAjdoc("private","1.4",files);
File htmlFile = new File(getAbsolutePathOutdir() + "/foo/Point.html");
if (htmlFile == null || !htmlFile.exists()) {
fail("couldn't find " + htmlFile.getAbsolutePath() + " - were there compilation errors?");
}
String[] strings = {
"setX(int)",
"HREF=\"../foo/AdvisesRelationshipCoverage.html#before(): methodExecutionP..\""};
boolean b = AjdocOutputChecker.detailSectionContainsRel(
htmlFile,"=== METHOD DETAIL",
strings[0],
HtmlDecorator.HtmlRelationshipKind.ADVISED_BY,
strings[1]);
assertTrue("the Method Detail should have " + strings[0]+" advised by " + strings[1],b);
b = AjdocOutputChecker.summarySectionContainsRel(
htmlFile,"=== METHOD SUMMARY",
strings[0],
HtmlDecorator.HtmlRelationshipKind.ADVISED_BY,
strings[1]);
assertTrue("the Method Summary should have " + strings[0]+" advised by " + strings[1],b);
}
/**
* Test that the advised by relationship appears in the ajdoc when the
* advice is associated with a constructor execution pointcut
*/
public void testAdvisedByConstructorExecution() throws Exception {
File[] files = {file4};
runAjdoc("private","1.4",files);
File htmlFile = new File(getAbsolutePathOutdir() + "/foo/Point.html");
if (htmlFile == null || !htmlFile.exists()) {
fail("couldn't find " + htmlFile.getAbsolutePath() + " - were there compilation errors?");
}
String[] strings = {
"Point()",
"HREF=\"../foo/AdvisesRelationshipCoverage.html#before(): constructorExecutionP..\""};
boolean b = AjdocOutputChecker.detailSectionContainsRel(
htmlFile,"=== CONSTRUCTOR DETAIL",
strings[0],
HtmlDecorator.HtmlRelationshipKind.ADVISED_BY,
strings[1]);
assertTrue("the Constructor Detail should have " + strings[0]+" advised by " + strings[1],b);
b = AjdocOutputChecker.summarySectionContainsRel(
htmlFile,"=== CONSTRUCTOR SUMMARY",
strings[0],
HtmlDecorator.HtmlRelationshipKind.ADVISED_BY,
strings[1]);
assertTrue("the Constructor Summary should have " + strings[0]+" advised by " + strings[1],b);
}
/**
* Test that the advised by relationship appears in the ajdoc when the
* advice is associated with a method call pointcut
*/
public void testAdvisedByMethodCall() throws Exception {
File[] files = {file4};
runAjdoc("private","1.4",files);
File htmlFile = new File(getAbsolutePathOutdir() + "/foo/Point.html");
if (htmlFile == null || !htmlFile.exists()) {
fail("couldn't find " + htmlFile.getAbsolutePath() + " - were there compilation errors?");
}
String[] strings = {
"changeX(int)",
"HREF=\"../foo/AdvisesRelationshipCoverage.html#before(): callMethodP..\""};
boolean b = AjdocOutputChecker.detailSectionContainsRel(
htmlFile,"=== METHOD DETAIL",
strings[0],
HtmlDecorator.HtmlRelationshipKind.ADVISED_BY,
strings[1]);
assertTrue("the Method Detail should have " + strings[0]+" advised by " + strings[1],b);
b = AjdocOutputChecker.summarySectionContainsRel(
htmlFile,"=== METHOD SUMMARY",
strings[0],
HtmlDecorator.HtmlRelationshipKind.ADVISED_BY,
strings[1]);
assertTrue("the Method Summary should have " + strings[0]+" advised by " + strings[1],b);
}
/**
* Test that the advised by relationship appears in the ajdoc when the
* advice is associated with a constructor call pointcut
*/
public void testAdvisedByConstructorCall() throws Exception {
File[] files = {file4};
runAjdoc("private","1.4",files);
File htmlFile = new File(getAbsolutePathOutdir() + "/foo/Point.html");
if (htmlFile == null || !htmlFile.exists()) {
fail("couldn't find " + htmlFile.getAbsolutePath() + " - were there compilation errors?");
}
String[] strings = {
"doIt()",
"HREF=\"../foo/AdvisesRelationshipCoverage.html#before(): callConstructorP..\""};
boolean b = AjdocOutputChecker.detailSectionContainsRel(
htmlFile,"=== METHOD DETAIL",
strings[0],
HtmlDecorator.HtmlRelationshipKind.ADVISED_BY,
strings[1]);
assertTrue("the Method Detail should have " + strings[0]+" advised by " + strings[1],b);
b = AjdocOutputChecker.summarySectionContainsRel(
htmlFile,"=== METHOD SUMMARY",
strings[0],
HtmlDecorator.HtmlRelationshipKind.ADVISED_BY,
strings[1]);
assertTrue("the Method Summary should have " + strings[0]+" advised by " + strings[1],b);
}
/**
* Test that the advised by relationship appears in the ajdoc when the
* advice is associated with a get pointcut
*/
public void testAdvisedByGet() throws Exception {
File[] files = {file4};
runAjdoc("private","1.4",files);
File htmlFile = new File(getAbsolutePathOutdir() + "/foo/Point.html");
if (htmlFile == null || !htmlFile.exists()) {
fail("couldn't find " + htmlFile.getAbsolutePath() + " - were there compilation errors?");
}
String[] strings = {
"getX()",
"HREF=\"../foo/AdvisesRelationshipCoverage.html#before(): getP..\""};
boolean b = AjdocOutputChecker.detailSectionContainsRel(
htmlFile,"=== METHOD DETAIL",
strings[0],
HtmlDecorator.HtmlRelationshipKind.ADVISED_BY,
strings[1]);
assertTrue("the Method Detail should have " + strings[0]+" advised by " + strings[1],b);
b = AjdocOutputChecker.summarySectionContainsRel(
htmlFile,"=== METHOD SUMMARY",
strings[0],
HtmlDecorator.HtmlRelationshipKind.ADVISED_BY,
strings[1]);
assertTrue("the Method Summary should have " + strings[0]+" advised by " + strings[1],b);
}
/**
* Test that the advised by relationship appears in the ajdoc when the
* advice is associated with a set pointcut
*/
public void testAdvisedBySet() throws Exception {
File[] files = {file4};
runAjdoc("private","1.4",files);
File htmlFile = new File(getAbsolutePathOutdir() + "/foo/Point.html");
if (htmlFile == null || !htmlFile.exists()) {
fail("couldn't find " + htmlFile.getAbsolutePath() + " - were there compilation errors?");
}
String href = "HREF=\"../foo/AdvisesRelationshipCoverage.html#before(): setP..\"";
boolean b = AjdocOutputChecker.detailSectionContainsRel(
htmlFile,"=== METHOD DETAIL",
"setX(int)",
HtmlDecorator.HtmlRelationshipKind.ADVISED_BY,
href);
assertTrue("the Method Detail should have setX(int) advised by " + href,b);
b = AjdocOutputChecker.summarySectionContainsRel(
htmlFile,"=== METHOD SUMMARY",
"setX(int)",
HtmlDecorator.HtmlRelationshipKind.ADVISED_BY,
href);
assertTrue("the Method Summary should have setX(int) advised by " + href,b);
b = AjdocOutputChecker.detailSectionContainsRel(
htmlFile,"=== CONSTRUCTOR DETAIL",
"Point()",
HtmlDecorator.HtmlRelationshipKind.ADVISED_BY,
href);
assertTrue("the Constructor Detail should have advised by " + href,b);
b = AjdocOutputChecker.summarySectionContainsRel(
htmlFile,"=== CONSTRUCTOR SUMMARY",
"Point()",
HtmlDecorator.HtmlRelationshipKind.ADVISED_BY,
href);
assertTrue("the Constructor Summary should have advised by " + href,b);
b = AjdocOutputChecker.classDataSectionContainsRel(
htmlFile,
HtmlDecorator.HtmlRelationshipKind.ADVISED_BY,
href);
assertTrue("The class data section should have 'advised by " + href + "'",b);
}
/**
* Test that the advised by relationship appears in the ajdoc when the
* advice is associated with an initialization pointcut
*/
public void testAdvisedByInitialization() throws Exception {
File[] files = {file4};
runAjdoc("private","1.4",files);
File htmlFile = new File(getAbsolutePathOutdir() + "/foo/Point.html");
if (htmlFile == null || !htmlFile.exists()) {
fail("couldn't find " + htmlFile.getAbsolutePath() + " - were there compilation errors?");
}
String[] strings = {
"Point()",
"HREF=\"../foo/AdvisesRelationshipCoverage.html#before(): initializationP..\""};
boolean b = AjdocOutputChecker.detailSectionContainsRel(
htmlFile,"=== CONSTRUCTOR DETAIL",strings[0],
HtmlDecorator.HtmlRelationshipKind.ADVISED_BY,
strings[1]);
assertTrue("the Method Detail should have 'setX(int) advised by ... before()'",b);
b = AjdocOutputChecker.summarySectionContainsRel(
htmlFile,"=== CONSTRUCTOR SUMMARY",strings[0],
HtmlDecorator.HtmlRelationshipKind.ADVISED_BY,
strings[1]);
assertTrue("the Method Summary should have 'setX(int) advised by ... before()'",b);
}
/**
* Test that the advised by relationship appears in the ajdoc when the
* advice is associated with a staticinitialization pointcut
*/
public void testAdvisedByStaticInitialization() throws Exception {
File[] files = {file4};
runAjdoc("private","1.4",files);
File htmlFile = new File(getAbsolutePathOutdir() + "/foo/Point.html");
if (htmlFile == null || !htmlFile.exists()) {
fail("couldn't find " + htmlFile.getAbsolutePath() + " - were there compilation errors?");
}
String href = "HREF=\"../foo/AdvisesRelationshipCoverage.html#before(): staticinitializationP..\"";
boolean b = AjdocOutputChecker.classDataSectionContainsRel(
htmlFile,
HtmlDecorator.HtmlRelationshipKind.ADVISED_BY,
href);
assertTrue("The class data section should have 'advised by " + href + "'",b);
}
/**
* Test that the advised by relationship appears in the ajdoc when the
* advice is associated with a handler pointcut
*/
public void testAdvisedByHandler() throws Exception {
File[] files = {file4};
runAjdoc("private","1.4",files);
File htmlFile = new File(getAbsolutePathOutdir() + "/foo/Point.html");
if (htmlFile == null || !htmlFile.exists()) {
fail("couldn't find " + htmlFile.getAbsolutePath() + " - were there compilation errors?");
}
String[] strings = {
"doIt()",
"HREF=\"../foo/AdvisesRelationshipCoverage.html#before(): handlerP..\""};
boolean b = AjdocOutputChecker.detailSectionContainsRel(
htmlFile,"=== METHOD DETAIL",
strings[0],
HtmlDecorator.HtmlRelationshipKind.ADVISED_BY,
strings[1]);
assertTrue("the Method Detail should have " + strings[0]+" advised by " + strings[1],b);
b = AjdocOutputChecker.summarySectionContainsRel(
htmlFile,"=== METHOD SUMMARY",
strings[0],
HtmlDecorator.HtmlRelationshipKind.ADVISED_BY,
strings[1]);
assertTrue("the Method Summary should have " + strings[0]+" advised by " + strings[1],b);
}
/**
* Test that if have two before advice blocks from the same
* aspect affect the same method, then both appear in the ajdoc
*/
public void testTwoBeforeAdvice() throws Exception {
File[] files = {new File(getAbsoluteProjectDir() + "/pkg/A2.aj")};
runAjdoc("private","1.4",files);
File htmlFile = new File(getAbsolutePathOutdir() + "/pkg/C2.html");
if (htmlFile == null || !htmlFile.exists()) {
fail("couldn't find " + htmlFile.getAbsolutePath() + " - were there compilation errors?");
}
String[] strings = {
"amethod()",
"HREF=\"../pkg/A2.html#before(): p..\"",
"HREF=\"../pkg/A2.html#before(): p2..\""};
boolean b = AjdocOutputChecker.detailSectionContainsRel(
htmlFile,"=== METHOD DETAIL",
strings[0],
HtmlDecorator.HtmlRelationshipKind.ADVISED_BY,
strings[1]);
assertTrue("the Method Detail should have " + strings[0]+" advised by " + strings[1],b);
b = AjdocOutputChecker.summarySectionContainsRel(
htmlFile,"=== METHOD SUMMARY",
strings[0],
HtmlDecorator.HtmlRelationshipKind.ADVISED_BY,
strings[1]);
assertTrue("the Method Summary should have " + strings[0]+" advised by " + strings[1],b);
b = AjdocOutputChecker.detailSectionContainsRel(
htmlFile,"=== METHOD DETAIL",
strings[0],
HtmlDecorator.HtmlRelationshipKind.ADVISED_BY,
strings[2]);
assertTrue("the Method Detail should have " + strings[0]+" advised by " + strings[2],b);
b = AjdocOutputChecker.summarySectionContainsRel(
htmlFile,"=== METHOD SUMMARY",
strings[0],
HtmlDecorator.HtmlRelationshipKind.ADVISED_BY,
strings[2]);
assertTrue("the Method Summary should have " + strings[0]+" advised by " + strings[2],b);
}
/**
* Test that there are no spurious "advised by" entries
* against the aspect in the ajdoc
*/
public void testNoSpuriousAdvisedByRels() throws Exception {
File[] files = {file4};
runAjdoc("private","1.4",files);
File htmlFile = new File(getAbsolutePathOutdir() + "/foo/AdvisesRelationshipCoverage.html");
if (htmlFile == null || !htmlFile.exists()) {
fail("couldn't find " + htmlFile.getAbsolutePath() + " - were there compilation errors?");
}
String href = "foo.Point.setX(int)";
boolean b = AjdocOutputChecker.classDataSectionContainsRel(
htmlFile,
HtmlDecorator.HtmlRelationshipKind.ADVISED_BY,
href);
assertFalse("The class data section should not have 'advised by " + href + "'",b);
}
public void testCoverage() {
File[] files = {aspect1,file0,file1,file2,file3,file4,file5,file6,
file7,file8,file9,file10};
runAjdoc("private","1.4",files);
}
/**
* Test that nested aspects appear with "aspect" in their title
* when the ajdoc file is written slightly differently (when it's
* written for this apsect, it's different than for testInnerAspect())
*/
public void testNestedAspect() throws Exception {
File[] files = {file9};
runAjdoc("private","1.4",files);
File htmlFile = new File(getAbsolutePathOutdir() + "/PkgVisibleClass.NestedAspect.html");
if (htmlFile == null || !htmlFile.exists()) {
fail("couldn't find " + htmlFile.getAbsolutePath()
+ " - were there compilation errors?");
}
// ensure that the file is entitled "Aspect PkgVisibleClass.NestedAspect" rather
// than "Class PkgVisibleClass.NestedAspect"
String[] strings = { "Aspect PkgVisibleClass.NestedAspect",
"<PRE>static aspect <B>PkgVisibleClass.NestedAspect</B><DT>extends java.lang.Object</DL>",
"Class PkgVisibleClass.NestedAspect",
"<PRE>static class <B>PkgVisibleClass.NestedAspect</B><DT>extends java.lang.Object</DL>"};
List missing = AjdocOutputChecker.getMissingStringsInFile(htmlFile,strings);
assertEquals("There should be 2 missing strings",2,missing.size());
assertTrue(htmlFile.getName() + " should not have Class as it's title",missing.contains("Class PkgVisibleClass.NestedAspect"));
assertTrue(htmlFile.getName() + " should not have class in its subtitle",missing.contains("<PRE>static class <B>PkgVisibleClass.NestedAspect</B><DT>extends java.lang.Object</DL>"));
// get the html file for the enclosing class
File htmlFileClass = new File(getAbsolutePathOutdir() + "/PkgVisibleClass.html");
if (htmlFileClass == null || !htmlFileClass.exists()) {
fail("couldn't find " + htmlFileClass.getAbsolutePath()
+ " - were there compilation errors?");
}
// ensure that the file is entitled "Class PkgVisibleClass" and
// has not been changed to "Aspect PkgVisibleClass"
String[] classStrings = { "Class PkgVisibleClass</H2>",
"class <B>PkgVisibleClass</B><DT>extends java.lang.Object</DL>",
"Aspect PkgVisibleClass</H2>",
"aspect <B>PkgVisibleClass</B><DT>extends java.lang.Object<DT>"};
List classMissing = AjdocOutputChecker.getMissingStringsInFile(htmlFileClass,classStrings);
assertEquals("There should be 2 missing strings",2,classMissing.size());
assertTrue(htmlFileClass.getName() + " should not have Aspect as it's title",classMissing.contains("Aspect PkgVisibleClass</H2>"));
assertTrue(htmlFileClass.getName() + " should not have aspect in its subtitle",classMissing.contains("aspect <B>PkgVisibleClass</B><DT>extends java.lang.Object<DT>"));
}
/**
* Test that in the case when you have a nested aspect whose
* name is part of the enclosing class, for example a class called
* ClassWithNestedAspect has nested aspect called NestedAspect,
* that the titles for the ajdoc are correct.
*/
public void testNestedAspectWithSimilarName() throws Exception {
File[] files = {new File(getAbsoluteProjectDir() + "/pkg/ClassWithNestedAspect.java")};
runAjdoc("private","1.4",files);
File htmlFile = new File(getAbsolutePathOutdir() + "/pkg/ClassWithNestedAspect.NestedAspect.html");
if (htmlFile == null || !htmlFile.exists()) {
fail("couldn't find " + htmlFile.getAbsolutePath()
+ " - were there compilation errors?");
}
// ensure that the file is entitled "Aspect ClassWithNestedAspect.NestedAspect"
// rather than "Class ClassWithNestedAspect.NestedAspect"
String[] strings = { "Aspect ClassWithNestedAspect.NestedAspect",
"<PRE>static aspect <B>ClassWithNestedAspect.NestedAspect</B><DT>extends java.lang.Object</DL>",
"Class ClassWithNestedAspect.NestedAspect",
"<PRE>static class <B>ClassWithNestedAspect.NestedAspect</B><DT>extends java.lang.Object</DL>"};
List missing = AjdocOutputChecker.getMissingStringsInFile(htmlFile,strings);
assertEquals("There should be 2 missing strings",2,missing.size());
assertTrue(htmlFile.getName() + " should not have Class as it's title",missing.contains("Class ClassWithNestedAspect.NestedAspect"));
assertTrue(htmlFile.getName() + " should not have class in its subtitle",missing.contains("<PRE>static class <B>ClassWithNestedAspect.NestedAspect</B><DT>extends java.lang.Object</DL>"));
// get the html file for the enclosing class
File htmlFileClass = new File(getAbsolutePathOutdir() + "/pkg/ClassWithNestedAspect.html");
if (htmlFileClass == null || !htmlFileClass.exists()) {
fail("couldn't find " + htmlFileClass.getAbsolutePath()
+ " - were there compilation errors?");
}
// ensure that the file is entitled "Class ClassWithNestedAspect" and
// has not been changed to "Aspect ClassWithNestedAspect"
String[] classStrings = { "Class ClassWithNestedAspect</H2>",
"public class <B>ClassWithNestedAspect</B><DT>extends java.lang.Object</DL>",
"Aspect ClassWithNestedAspect</H2>",
"public aspect <B>ClassWithNestedAspect</B><DT>extends java.lang.Object</DL>"};
List classMissing = AjdocOutputChecker.getMissingStringsInFile(htmlFileClass,classStrings);
assertEquals("There should be 2 missing strings",2,classMissing.size());
assertTrue(htmlFileClass.getName() + " should not have Aspect as it's title",
classMissing.contains("Aspect ClassWithNestedAspect</H2>"));
assertTrue(htmlFileClass.getName() + " should not have aspect in its subtitle",
classMissing.contains("public aspect <B>ClassWithNestedAspect</B><DT>extends java.lang.Object</DL>"));
}
/**
* Test that everythings being decorated correctly within the ajdoc
* for the aspect when the aspect is a nested aspect
*/
public void testAdviceInNestedAspect() throws Exception {
File[] files = {new File(getAbsoluteProjectDir() + "/pkg/ClassWithNestedAspect.java")};
runAjdoc("private","1.4",files);
File htmlFile = new File(getAbsolutePathOutdir() + "/pkg/ClassWithNestedAspect.NestedAspect.html");
if (htmlFile == null || !htmlFile.exists()) {
fail("couldn't find " + htmlFile.getAbsolutePath()
+ " - were there compilation errors?");
}
boolean b = AjdocOutputChecker.detailSectionContainsRel(
htmlFile,"ADVICE DETAIL SUMMARY",
"before(): p..",
HtmlDecorator.HtmlRelationshipKind.ADVISES,
"HREF=\"../pkg/ClassWithNestedAspect.html#amethod()\"");
assertTrue("Should have 'before(): p.. advises HREF=\"../pkg/ClassWithNestedAspect.html#amethod()\"" +
"' in the Advice Detail section", b);
b = AjdocOutputChecker.summarySectionContainsRel(
htmlFile,"ADVICE SUMMARY",
"before(): p..",
HtmlDecorator.HtmlRelationshipKind.ADVISES,
"HREF=\"../pkg/ClassWithNestedAspect.html#amethod()\"");
assertTrue("Should have 'before(): p.. advises HREF=\"../pkg/ClassWithNestedAspect.html#amethod()\"" +
"' in the Advice Summary section", b);
}
/**
* Test that everythings being decorated correctly within the ajdoc
* for the advised class when the aspect is a nested aspect
*/
public void testAdvisedByInNestedAspect() throws Exception {
File[] files = {new File(getAbsoluteProjectDir() + "/pkg/ClassWithNestedAspect.java")};
runAjdoc("private","1.4",files);
File htmlFile = new File(getAbsolutePathOutdir() + "/pkg/ClassWithNestedAspect.html");
if (htmlFile == null || !htmlFile.exists()) {
fail("couldn't find " + htmlFile.getAbsolutePath()
+ " - were there compilation errors?");
}
boolean b = AjdocOutputChecker.containsString(htmlFile,"POINTCUT SUMMARY ");
assertFalse(htmlFile.getName() + " should not contain a pointcut summary section",b);
b = AjdocOutputChecker.containsString(htmlFile,"ADVICE SUMMARY ");
assertFalse(htmlFile.getName() + " should not contain an adivce summary section",b);
b = AjdocOutputChecker.containsString(htmlFile,"POINTCUT DETAIL ");
assertFalse(htmlFile.getName() + " should not contain a pointcut detail section",b);
b = AjdocOutputChecker.containsString(htmlFile,"ADVICE DETAIL ");
assertFalse(htmlFile.getName() + " should not contain an advice detail section",b);
b = AjdocOutputChecker.detailSectionContainsRel(
htmlFile,"=== METHOD DETAIL",
"amethod()",
HtmlDecorator.HtmlRelationshipKind.ADVISED_BY,
"HREF=\"../pkg/ClassWithNestedAspect.NestedAspect.html#before(): p..\"");
assertTrue("Should have 'amethod() advised by " +
"HREF=\"../pkg/ClassWithNestedAspect.NestedAspect.html#before(): p..\"" +
"' in the Method Detail section", b);
b = AjdocOutputChecker.detailSectionContainsRel(
htmlFile,"=== METHOD DETAIL",
"amethod()",
HtmlDecorator.HtmlRelationshipKind.ADVISED_BY,
"pkg.ClassWithNestedAspect.NestedAspect.NestedAspect.before(): p..");
assertFalse("Should not have the label " +
"pkg.ClassWithNestedAspect.NestedAspect.NestedAspect.before(): p.." +
" in the Method Detail section", b);
b = AjdocOutputChecker.summarySectionContainsRel(
htmlFile,"=== METHOD SUMMARY",
"amethod()",
HtmlDecorator.HtmlRelationshipKind.ADVISED_BY,
"HREF=\"../pkg/ClassWithNestedAspect.NestedAspect.html#before(): p..\"");
assertTrue("Should have 'amethod() advised by " +
"HREF=\"../pkg/ClassWithNestedAspect.NestedAspect.html#before(): p..\"" +
"' in the Method Summary section", b);
b = AjdocOutputChecker.detailSectionContainsRel(
htmlFile,"=== METHOD SUMMARY",
"amethod()",
HtmlDecorator.HtmlRelationshipKind.ADVISED_BY,
"pkg.ClassWithNestedAspect.NestedAspect.NestedAspect.before(): p..");
assertFalse("Should not have the label " +
"pkg.ClassWithNestedAspect.NestedAspect.NestedAspect.before(): p.." +
" in the Method Summary section", b);
}
private void createFiles() {
file0 = new File(getAbsoluteProjectDir() + "/InDefaultPackage.java");
file1 = new File(getAbsoluteProjectDir() + "/foo/ClassA.java");
aspect1 = new File(getAbsoluteProjectDir() + "/foo/UseThisAspectForLinkCheck.aj");
file2 = new File(getAbsoluteProjectDir() + "/foo/InterfaceI.java");
file3 = new File(getAbsoluteProjectDir() + "/foo/PlainJava.java");
file4 = new File(getAbsoluteProjectDir() + "/foo/ModelCoverage.java");
file5 = new File(getAbsoluteProjectDir() + "/fluffy/Fluffy.java");
file6 = new File(getAbsoluteProjectDir() + "/fluffy/bunny/Bunny.java");
file7 = new File(getAbsoluteProjectDir() + "/fluffy/bunny/rocks/Rocks.java");
file8 = new File(getAbsoluteProjectDir() + "/fluffy/bunny/rocks/UseThisAspectForLinkCheckToo.java");
file9 = new File(getAbsoluteProjectDir() + "/foo/PkgVisibleClass.java");
file10 = new File(getAbsoluteProjectDir() + "/foo/NoMembers.java");
}
// public void testPlainJava() {
// String[] args = { "-d",
// getAbsolutePathOutdir(),
// file3.getAbsolutePath() };
// org.aspectj.tools.ajdoc.Main.main(args);
// }
}
|
143,930 |
Bug 143930 create constructor ipe in same was as method ipes
| null |
resolved fixed
|
26a8a86
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-05-30T09:59:53Z | 2006-05-26T10:40:00Z |
org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/core/builder/AsmElementFormatter.java
|
/* *******************************************************************
* Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC).
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* PARC initial implementation
* Alexandre Vasseur support for @AJ style
* ******************************************************************/
package org.aspectj.ajdt.internal.core.builder;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.aspectj.ajdt.internal.compiler.ast.AdviceDeclaration;
import org.aspectj.ajdt.internal.compiler.ast.DeclareDeclaration;
import org.aspectj.ajdt.internal.compiler.ast.InterTypeConstructorDeclaration;
import org.aspectj.ajdt.internal.compiler.ast.InterTypeDeclaration;
import org.aspectj.ajdt.internal.compiler.ast.InterTypeFieldDeclaration;
import org.aspectj.ajdt.internal.compiler.ast.InterTypeMethodDeclaration;
import org.aspectj.ajdt.internal.compiler.ast.PointcutDeclaration;
import org.aspectj.ajdt.internal.compiler.lookup.AjLookupEnvironment;
import org.aspectj.asm.IProgramElement;
import org.aspectj.weaver.AdviceKind;
import org.aspectj.weaver.ResolvedType;
import org.aspectj.weaver.UnresolvedType;
import org.aspectj.weaver.patterns.AndPointcut;
import org.aspectj.weaver.patterns.DeclareAnnotation;
import org.aspectj.weaver.patterns.DeclareErrorOrWarning;
import org.aspectj.weaver.patterns.DeclareParents;
import org.aspectj.weaver.patterns.DeclarePrecedence;
import org.aspectj.weaver.patterns.DeclareSoft;
import org.aspectj.weaver.patterns.OrPointcut;
import org.aspectj.weaver.patterns.ReferencePointcut;
import org.aspectj.weaver.patterns.TypePattern;
import org.aspectj.weaver.patterns.TypePatternList;
import org.aspectj.org.eclipse.jdt.core.compiler.CharOperation;
import org.aspectj.org.eclipse.jdt.internal.compiler.ast.Argument;
import org.aspectj.org.eclipse.jdt.internal.compiler.ast.MethodDeclaration;
import org.aspectj.org.eclipse.jdt.internal.compiler.ast.Annotation;
import org.aspectj.org.eclipse.jdt.internal.compiler.ast.TypeReference;
import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.TypeBinding;
/**
* @author Mik Kersten
*/
public class AsmElementFormatter {
public static final String UNDEFINED="<undefined>";
public static final String DECLARE_PRECEDENCE = "precedence";
public static final String DECLARE_SOFT = "soft";
public static final String DECLARE_PARENTS = "parents";
public static final String DECLARE_WARNING = "warning";
public static final String DECLARE_ERROR = "error";
public static final String DECLARE_UNKNONWN = "<unknown declare>";
public static final String POINTCUT_ABSTRACT = "<abstract pointcut>";
public static final String POINTCUT_ANONYMOUS = "<anonymous pointcut>";
public static final String DOUBLE_DOTS = "..";
public static final int MAX_MESSAGE_LENGTH = 18;
public static final String DEC_LABEL = "declare";
public void genLabelAndKind(MethodDeclaration methodDeclaration, IProgramElement node) {
if (methodDeclaration instanceof AdviceDeclaration) {
AdviceDeclaration ad = (AdviceDeclaration)methodDeclaration;
node.setKind(IProgramElement.Kind.ADVICE);
if (ad.kind == AdviceKind.Around) {
node.setCorrespondingType(ad.returnType.toString()); //returnTypeToString(0));
}
StringBuffer details = new StringBuffer();
if (ad.pointcutDesignator != null) {
if (ad.pointcutDesignator.getPointcut() instanceof ReferencePointcut) {
ReferencePointcut rp = (ReferencePointcut)ad.pointcutDesignator.getPointcut();
details.append(rp.name).append("..");
} else if (ad.pointcutDesignator.getPointcut() instanceof AndPointcut) {
AndPointcut ap = (AndPointcut)ad.pointcutDesignator.getPointcut();
if (ap.getLeft() instanceof ReferencePointcut) {
details.append(ap.getLeft().toString()).append(DOUBLE_DOTS);
} else {
details.append(POINTCUT_ANONYMOUS).append(DOUBLE_DOTS);
}
} else if (ad.pointcutDesignator.getPointcut() instanceof OrPointcut) {
OrPointcut op = (OrPointcut)ad.pointcutDesignator.getPointcut();
if (op.getLeft() instanceof ReferencePointcut) {
details.append(op.getLeft().toString()).append(DOUBLE_DOTS);
} else {
details.append(POINTCUT_ANONYMOUS).append(DOUBLE_DOTS);
}
} else {
details.append(POINTCUT_ANONYMOUS);
}
} else {
details.append(POINTCUT_ABSTRACT);
}
node.setName(ad.kind.toString());
//if (details.length()!=0)
node.setDetails(details.toString());
setParameters(methodDeclaration, node);
} else if (methodDeclaration instanceof PointcutDeclaration) {
PointcutDeclaration pd = (PointcutDeclaration)methodDeclaration;
node.setKind(IProgramElement.Kind.POINTCUT);
node.setName(translatePointcutName(new String(methodDeclaration.selector)));
setParameters(methodDeclaration, node);
} else if (methodDeclaration instanceof DeclareDeclaration) {
DeclareDeclaration declare = (DeclareDeclaration)methodDeclaration;
String name = DEC_LABEL + " ";
if (declare.declareDecl instanceof DeclareErrorOrWarning) {
DeclareErrorOrWarning deow = (DeclareErrorOrWarning)declare.declareDecl;
if (deow.isError()) {
node.setKind( IProgramElement.Kind.DECLARE_ERROR);
name += DECLARE_ERROR;
} else {
node.setKind( IProgramElement.Kind.DECLARE_WARNING);
name += DECLARE_WARNING;
}
node.setName(name) ;
node.setDetails("\"" + genDeclareMessage(deow.getMessage()) + "\"");
} else if (declare.declareDecl instanceof DeclareParents) {
node.setKind( IProgramElement.Kind.DECLARE_PARENTS);
DeclareParents dp = (DeclareParents)declare.declareDecl;
node.setName(name + DECLARE_PARENTS);
String kindOfDP = null;
StringBuffer details = new StringBuffer("");
TypePattern[] newParents = dp.getParents().getTypePatterns();
for (int i = 0; i < newParents.length; i++) {
TypePattern tp = newParents[i];
UnresolvedType tx = tp.getExactType();
if (kindOfDP == null) {
kindOfDP = "implements ";
try {
ResolvedType rtx = tx.resolve(((AjLookupEnvironment)declare.scope.environment()).factory.getWorld());
if (!rtx.isInterface()) kindOfDP = "extends ";
} catch (Throwable t) {
// What can go wrong???? who knows!
}
}
String typename= tp.toString();
if (typename.lastIndexOf(".")!=-1) {
typename=typename.substring(typename.lastIndexOf(".")+1);
}
details.append(typename);
if ((i+1)<newParents.length) details.append(",");
}
node.setDetails(kindOfDP+details.toString());
} else if (declare.declareDecl instanceof DeclareSoft) {
node.setKind( IProgramElement.Kind.DECLARE_SOFT);
DeclareSoft ds = (DeclareSoft)declare.declareDecl;
node.setName(name + DECLARE_SOFT);
node.setDetails(genTypePatternLabel(ds.getException()));
} else if (declare.declareDecl instanceof DeclarePrecedence) {
node.setKind( IProgramElement.Kind.DECLARE_PRECEDENCE);
DeclarePrecedence ds = (DeclarePrecedence)declare.declareDecl;
node.setName(name + DECLARE_PRECEDENCE);
node.setDetails(genPrecedenceListLabel(ds.getPatterns()));
} else if (declare.declareDecl instanceof DeclareAnnotation) {
DeclareAnnotation deca = (DeclareAnnotation)declare.declareDecl;
String thekind = deca.getKind().toString();
node.setName(name+"@"+thekind.substring(3));
if (deca.getKind()==DeclareAnnotation.AT_CONSTRUCTOR) {
node.setKind(IProgramElement.Kind.DECLARE_ANNOTATION_AT_CONSTRUCTOR);
} else if (deca.getKind()==DeclareAnnotation.AT_FIELD) {
node.setKind(IProgramElement.Kind.DECLARE_ANNOTATION_AT_FIELD);
} else if (deca.getKind()==DeclareAnnotation.AT_METHOD) {
node.setKind(IProgramElement.Kind.DECLARE_ANNOTATION_AT_METHOD);
} else if (deca.getKind()==DeclareAnnotation.AT_TYPE) {
node.setKind(IProgramElement.Kind.DECLARE_ANNOTATION_AT_TYPE);
}
node.setDetails(genDecaLabel(deca));
} else {
node.setKind(IProgramElement.Kind.ERROR);
node.setName(DECLARE_UNKNONWN);
}
} else if (methodDeclaration instanceof InterTypeDeclaration) {
InterTypeDeclaration itd = (InterTypeDeclaration)methodDeclaration;
String name = itd.getOnType().toString() + "." + new String(itd.getDeclaredSelector());
if (methodDeclaration instanceof InterTypeFieldDeclaration) {
node.setKind(IProgramElement.Kind.INTER_TYPE_FIELD);
node.setName(name);
} else if (methodDeclaration instanceof InterTypeMethodDeclaration) {
node.setKind(IProgramElement.Kind.INTER_TYPE_METHOD);
node.setName(name);
} else if (methodDeclaration instanceof InterTypeConstructorDeclaration) {
node.setKind(IProgramElement.Kind.INTER_TYPE_CONSTRUCTOR);
// StringBuffer argumentsSignature = new StringBuffer("fubar");
// argumentsSignature.append("(");
// if (methodDeclaration.arguments!=null && methodDeclaration.arguments.length>1) {
//
// for (int i = 1;i<methodDeclaration.arguments.length;i++) {
// argumentsSignature.append(methodDeclaration.arguments[i]);
// if (i+1<methodDeclaration.arguments.length) argumentsSignature.append(",");
// }
// }
// argumentsSignature.append(")");
// InterTypeConstructorDeclaration itcd = (InterTypeConstructorDeclaration)methodDeclaration;
node.setName(itd.getOnType().toString() + "." + itd.getOnType().toString()/*+argumentsSignature.toString()*/);
} else {
node.setKind(IProgramElement.Kind.ERROR);
node.setName(name);
}
node.setCorrespondingType(itd.returnType.toString());
if (node.getKind() != IProgramElement.Kind.INTER_TYPE_FIELD) {
setParameters(methodDeclaration, node);
}
} else {
if (methodDeclaration.isConstructor()) {
node.setKind(IProgramElement.Kind.CONSTRUCTOR);
} else {
node.setKind(IProgramElement.Kind.METHOD);
//TODO AV - could speed up if we could dig only for @Aspect declaring types (or aspect if mixed style allowed)
//??? how to : node.getParent().getKind().equals(IProgramElement.Kind.ASPECT)) {
if (true && methodDeclaration!=null && methodDeclaration.annotations != null && methodDeclaration.scope!=null) {
for (int i = 0; i < methodDeclaration.annotations.length; i++) {
//Note: AV: implicit single advice type support here (should be enforced somewhere as well (APT etc))
Annotation annotation = methodDeclaration.annotations[i];
String annotationSig = new String(annotation.type.getTypeBindingPublic(methodDeclaration.scope).signature());
if (annotationSig!=null && annotationSig.charAt(1)=='o') {
if ("Lorg/aspectj/lang/annotation/Pointcut;".equals(annotationSig)) {
node.setKind(IProgramElement.Kind.POINTCUT);
break;
} else if ("Lorg/aspectj/lang/annotation/Before;".equals(annotationSig)
|| "Lorg/aspectj/lang/annotation/After;".equals(annotationSig)
|| "Lorg/aspectj/lang/annotation/AfterReturning;".equals(annotationSig)
|| "Lorg/aspectj/lang/annotation/AfterThrowing;".equals(annotationSig)
|| "Lorg/aspectj/lang/annotation/Around;".equals(annotationSig)) {
node.setKind(IProgramElement.Kind.ADVICE);
//TODO AV - all are considered anonymous - is that ok?
node.setDetails(POINTCUT_ANONYMOUS);
break;
}
}
}
}
}
node.setName(new String(methodDeclaration.selector));
setParameters(methodDeclaration, node);
}
}
private String genDecaLabel(DeclareAnnotation deca) {
StringBuffer sb = new StringBuffer("");
sb.append(deca.getPatternAsString());
sb.append(" : ");
sb.append(deca.getAnnotationString());
return sb.toString();
}
private String genPrecedenceListLabel(TypePatternList list) {
String tpList = "";
for (int i = 0; i < list.size(); i++) {
tpList += genTypePatternLabel(list.get(i));
if (i < list.size()-1) tpList += ", ";
}
return tpList;
}
// private String genArguments(MethodDeclaration md) {
// String args = "";
// Argument[] argArray = md.arguments;
// if (argArray == null) return args;
// for (int i = 0; i < argArray.length; i++) {
// String argName = new String(argArray[i].name);
// String argType = argArray[i].type.toString();
// if (acceptArgument(argName, argType)) {
// args += argType + ", ";
// }
// }
// int lastSepIndex = args.lastIndexOf(',');
// if (lastSepIndex != -1 && args.endsWith(", ")) args = args.substring(0, lastSepIndex);
// return args;
// }
private void setParameters(MethodDeclaration md, IProgramElement pe) {
Argument[] argArray = md.arguments;
if (argArray == null) {
pe.setParameterNames(Collections.EMPTY_LIST);
pe.setParameterTypes(Collections.EMPTY_LIST);
} else {
List names = new ArrayList();
List types = new ArrayList();
for (int i = 0; i < argArray.length; i++) {
String argName = new String(argArray[i].name);
String argType = "<UnknownType>"; // pr135052
TypeReference typeR = argArray[i].type;
if (typeR!=null) {
TypeBinding typeB = typeR.resolvedType;
if (typeB==null) {
if (typeR.getTypeName()!=null)
argType = CharOperation.toString(typeR.getTypeName());
} else {
argType = typeB.debugName();
}
}
// String argType = argArray[i].type.resolvedType.debugName();
if (acceptArgument(argName, argArray[i].type.toString())) {
names.add(argName);
types.add(argType);
}
}
pe.setParameterNames(names);
pe.setParameterTypes(types);
}
}
// TODO: fix this way of determing ajc-added arguments, make subtype of Argument with extra info
private boolean acceptArgument(String name, String type) {
if (name.charAt(0)!='a' && type.charAt(0)!='o') return true;
return !name.startsWith("ajc$this_")
&& !type.equals("org.aspectj.lang.JoinPoint.StaticPart")
&& !type.equals("org.aspectj.lang.JoinPoint")
&& !type.equals("org.aspectj.runtime.internal.AroundClosure");
}
public String genTypePatternLabel(TypePattern tp) {
final String TYPE_PATTERN_LITERAL = "<type pattern>";
String label;
UnresolvedType typeX = tp.getExactType();
if (!ResolvedType.isMissing(typeX)) {
label = typeX.getName();
if (tp.isIncludeSubtypes()) label += "+";
} else {
label = TYPE_PATTERN_LITERAL;
}
return label;
}
public String genDeclareMessage(String message) {
int length = message.length();
if (length < MAX_MESSAGE_LENGTH) {
return message;
} else {
return message.substring(0, MAX_MESSAGE_LENGTH-1) + "..";
}
}
// // TODO:
// private String translateAdviceName(String label) {
// if (label.indexOf("before") != -1) return "before";
// if (label.indexOf("returning") != -1) return "after returning";
// if (label.indexOf("after") != -1) return "after";
// if (label.indexOf("around") != -1) return "around";
// else return "<advice>";
// }
// // !!! move or replace
// private String translateDeclareName(String name) {
// int colonIndex = name.indexOf(":");
// if (colonIndex != -1) {
// return name.substring(0, colonIndex);
// } else {
// return name;
// }
// }
// !!! move or replace
// private String translateInterTypeDecName(String name) {
// int index = name.lastIndexOf('$');
// if (index != -1) {
// return name.substring(index+1);
// } else {
// return name;
// }
// }
// !!! move or replace
private String translatePointcutName(String name) {
int index = name.indexOf("$$")+2;
int endIndex = name.lastIndexOf('$');
if (index != -1 && endIndex != -1) {
return name.substring(index, endIndex);
} else {
return name;
}
}
}
|
143,930 |
Bug 143930 create constructor ipe in same was as method ipes
| null |
resolved fixed
|
26a8a86
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-05-30T09:59:53Z | 2006-05-26T10:40:00Z |
org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/core/builder/AsmHierarchyBuilder.java
|
/* *******************************************************************
* Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC).
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* PARC initial implementation
* Mik Kersten revisions, added additional relationships
* Alexandre Vasseur support for @AJ style
* ******************************************************************/
package org.aspectj.ajdt.internal.core.builder;
import java.io.File;
import java.io.IOException;
import java.util.*;
import org.aspectj.ajdt.internal.compiler.ast.*;
import org.aspectj.ajdt.internal.compiler.lookup.AjLookupEnvironment;
import org.aspectj.ajdt.internal.compiler.lookup.EclipseFactory;
import org.aspectj.asm.*;
import org.aspectj.asm.internal.ProgramElement;
import org.aspectj.bridge.ISourceLocation;
import org.aspectj.bridge.SourceLocation;
import org.aspectj.org.eclipse.jdt.internal.compiler.ASTVisitor;
import org.aspectj.org.eclipse.jdt.internal.compiler.CompilationResult;
import org.aspectj.org.eclipse.jdt.internal.compiler.ast.*;
import org.aspectj.org.eclipse.jdt.internal.compiler.env.IGenericType;
import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.*;
import org.aspectj.org.eclipse.jdt.internal.compiler.problem.ProblemHandler;
import org.aspectj.util.LangUtil;
import org.aspectj.weaver.*;
import org.aspectj.weaver.patterns.*;
/**
* At each iteration of <CODE>processCompilationUnit</CODE> the declarations for a
* particular compilation unit are added to the hierarchy passed as a a parameter.
* <p>
* Clients who extend this class need to ensure that they do not override any of the existing
* behavior. If they do, the structure model will not be built properly and tools such as IDE
* structure views and ajdoc will fail.
* <p>
* <b>Note:</b> this class is not considered public API and the overridable
* methods are subject to change.
*
* @author Mik Kersten
*/
public class AsmHierarchyBuilder extends ASTVisitor {
protected AsmElementFormatter formatter = new AsmElementFormatter();
public static boolean shouldAddUsesPointcut = true;
/**
* Reset for every compilation unit.
*/
protected AjBuildConfig buildConfig;
/**
* Reset for every compilation unit.
*/
protected Stack stack;
/**
* Reset for every compilation unit.
*/
private CompilationResult currCompilationResult;
private String filename;
int[] lineseps;
/**
*
* @param cuDeclaration
* @param buildConfig
* @param structureModel hiearchy to add this unit's declarations to
*/
public void buildStructureForCompilationUnit(CompilationUnitDeclaration cuDeclaration, IHierarchy structureModel, AjBuildConfig buildConfig) {
currCompilationResult = cuDeclaration.compilationResult();
filename = new String(currCompilationResult.fileName);
lineseps = currCompilationResult.lineSeparatorPositions;
LangUtil.throwIaxIfNull(currCompilationResult, "result");
stack = new Stack();
this.buildConfig = buildConfig;
internalBuild(cuDeclaration, structureModel);
this.buildConfig = null; // clear reference since this structure is anchored in static
currCompilationResult=null;
stack.clear();
// throw new RuntimeException("not implemented");
}
private void internalBuild(CompilationUnitDeclaration unit, IHierarchy structureModel) {
LangUtil.throwIaxIfNull(structureModel, "structureModel");
// if (!currCompilationResult.equals(unit.compilationResult())) {
// throw new IllegalArgumentException("invalid unit: " + unit);
// }
// ---- summary
// add unit to package (or root if no package),
// first removing any duplicate (XXX? removes children if 3 classes in same file?)
// push the node on the stack
// and traverse
// -- create node to add
final File file = new File(new String(unit.getFileName()));
final IProgramElement cuNode;
{
// AMC - use the source start and end from the compilation unit decl
int startLine = getStartLine(unit);
int endLine = getEndLine(unit);
SourceLocation sourceLocation
= new SourceLocation(file, startLine, endLine);
sourceLocation.setOffset(unit.sourceStart);
cuNode = new ProgramElement(
new String(file.getName()),
IProgramElement.Kind.FILE_JAVA,
sourceLocation,
0,null,null);
}
cuNode.addChild(new ProgramElement(
"import declarations",
IProgramElement.Kind.IMPORT_REFERENCE,
null,0,null,null));
final IProgramElement addToNode = genAddToNode(unit, structureModel);
// -- remove duplicates before adding (XXX use them instead?)
if (addToNode!=null && addToNode.getChildren()!=null) {
for (ListIterator itt = addToNode.getChildren().listIterator(); itt.hasNext(); ) {
IProgramElement child = (IProgramElement)itt.next();
ISourceLocation childLoc = child.getSourceLocation();
if (null == childLoc) {
// XXX ok, packages have null source locations
// signal others?
} else if (childLoc.getSourceFile().equals(file)) {
itt.remove();
}
}
}
// -- add and traverse
addToNode.addChild(cuNode);
stack.push(cuNode);
unit.traverse(this, unit.scope);
// -- update file map (XXX do this before traversal?)
try {
structureModel.addToFileMap(file.getCanonicalPath(), cuNode);
} catch (IOException e) {
System.err.println("IOException " + e.getMessage()
+ " creating path for " + file );
// XXX signal IOException when canonicalizing file path
}
}
/**
* Get/create the node (package or root) to add to.
*/
private IProgramElement genAddToNode(
CompilationUnitDeclaration unit,
IHierarchy structureModel) {
final IProgramElement addToNode;
{
ImportReference currentPackage = unit.currentPackage;
if (null == currentPackage) {
addToNode = structureModel.getRoot();
} else {
String pkgName;
{
StringBuffer nameBuffer = new StringBuffer();
final char[][] importName = currentPackage.getImportName();
final int last = importName.length-1;
for (int i = 0; i < importName.length; i++) {
nameBuffer.append(new String(importName[i]));
if (i < last) {
nameBuffer.append('.');
}
}
pkgName = nameBuffer.toString();
}
IProgramElement pkgNode = null;
if (structureModel!=null && structureModel.getRoot()!=null && structureModel.getRoot().getChildren()!=null) {
for (Iterator it = structureModel.getRoot().getChildren().iterator();
it.hasNext(); ) {
IProgramElement currNode = (IProgramElement)it.next();
if (pkgName.equals(currNode.getName())) {
pkgNode = currNode;
break;
}
}
}
if (pkgNode == null) {
// note packages themselves have no source location
pkgNode = new ProgramElement(
pkgName,
IProgramElement.Kind.PACKAGE,
new ArrayList()
);
structureModel.getRoot().addChild(pkgNode);
}
addToNode = pkgNode;
}
}
return addToNode;
}
public boolean visit(TypeDeclaration typeDeclaration, CompilationUnitScope scope) {
String name = new String(typeDeclaration.name);
IProgramElement.Kind kind = IProgramElement.Kind.CLASS;
if (typeDeclaration instanceof AspectDeclaration) kind = IProgramElement.Kind.ASPECT;
else if (typeDeclaration.kind() == IGenericType.INTERFACE_DECL) kind = IProgramElement.Kind.INTERFACE;
else if (typeDeclaration.kind() == IGenericType.ENUM_DECL) kind = IProgramElement.Kind.ENUM;
else if (typeDeclaration.kind() == IGenericType.ANNOTATION_TYPE_DECL) kind = IProgramElement.Kind.ANNOTATION;
//@AJ support
if (typeDeclaration.annotations != null) {
for (int i = 0; i < typeDeclaration.annotations.length; i++) {
Annotation annotation = typeDeclaration.annotations[i];
if (Arrays.equals(annotation.type.getTypeBindingPublic(scope).signature(),
"Lorg/aspectj/lang/annotation/Aspect;".toCharArray())) {
kind = IProgramElement.Kind.ASPECT;
}
}
}
int typeModifiers = typeDeclaration.modifiers;
if (typeDeclaration instanceof AspectDeclaration) {
typeModifiers = ((AspectDeclaration)typeDeclaration).getDeclaredModifiers();
}
IProgramElement peNode = new ProgramElement(
name,
kind,
makeLocation(typeDeclaration),
typeModifiers, null,null);
peNode.setSourceSignature(genSourceSignature(typeDeclaration));
peNode.setFormalComment(generateJavadocComment(typeDeclaration));
((IProgramElement)stack.peek()).addChild(peNode);
stack.push(peNode);
return true;
}
public void endVisit(TypeDeclaration typeDeclaration, CompilationUnitScope scope) {
stack.pop();
}
// ??? share impl with visit(TypeDeclaration, ..) ?
public boolean visit(TypeDeclaration memberTypeDeclaration, ClassScope scope) {
String name = new String(memberTypeDeclaration.name);
IProgramElement.Kind kind = IProgramElement.Kind.CLASS;
if (memberTypeDeclaration instanceof AspectDeclaration) kind = IProgramElement.Kind.ASPECT;
else if (memberTypeDeclaration.kind() == IGenericType.INTERFACE_DECL) kind = IProgramElement.Kind.INTERFACE;
else if (memberTypeDeclaration.kind() == IGenericType.ENUM_DECL) kind = IProgramElement.Kind.ENUM;
else if (memberTypeDeclaration.kind() == IGenericType.ANNOTATION_TYPE_DECL) kind = IProgramElement.Kind.ANNOTATION;
//@AJ support
if (memberTypeDeclaration.annotations != null) {
for (int i = 0; i < memberTypeDeclaration.annotations.length; i++) {
Annotation annotation = memberTypeDeclaration.annotations[i];
if (Arrays.equals(annotation.type.getTypeBindingPublic(scope).signature(),
"Lorg/aspectj/lang/annotation/Aspect;".toCharArray())) {
kind = IProgramElement.Kind.ASPECT;
}
}
}
int typeModifiers = memberTypeDeclaration.modifiers;
if (memberTypeDeclaration instanceof AspectDeclaration) {
typeModifiers = ((AspectDeclaration)memberTypeDeclaration).getDeclaredModifiers();
}
IProgramElement peNode = new ProgramElement(
name,
kind,
makeLocation(memberTypeDeclaration),
typeModifiers,null,null);
peNode.setSourceSignature(genSourceSignature(memberTypeDeclaration));
peNode.setFormalComment(generateJavadocComment(memberTypeDeclaration));
((IProgramElement)stack.peek()).addChild(peNode);
stack.push(peNode);
return true;
}
public void endVisit(TypeDeclaration memberTypeDeclaration, ClassScope scope) {
stack.pop();
}
public boolean visit(TypeDeclaration memberTypeDeclaration, BlockScope scope) {
String fullName = "<undefined>";
if (memberTypeDeclaration.allocation != null
&& memberTypeDeclaration.allocation.type != null) {
// Create a name something like 'new Runnable() {..}'
fullName = "new "+memberTypeDeclaration.allocation.type.toString()+"() {..}";
} else if (memberTypeDeclaration.binding != null
&& memberTypeDeclaration.binding.constantPoolName() != null) {
// If we couldn't find a nice name like 'new Runnable() {..}' then use the number after the $
fullName = new String(memberTypeDeclaration.binding.constantPoolName());
int dollar = fullName.indexOf('$');
fullName = fullName.substring(dollar+1);
}
IProgramElement.Kind kind = IProgramElement.Kind.CLASS;
if (memberTypeDeclaration.kind() == IGenericType.INTERFACE_DECL) kind = IProgramElement.Kind.INTERFACE;
else if (memberTypeDeclaration.kind() == IGenericType.ENUM_DECL) kind = IProgramElement.Kind.ENUM;
else if (memberTypeDeclaration.kind() == IGenericType.ANNOTATION_TYPE_DECL) kind = IProgramElement.Kind.ANNOTATION;
//@AJ support
if (memberTypeDeclaration.annotations != null) {
for (int i = 0; i < memberTypeDeclaration.annotations.length; i++) {
Annotation annotation = memberTypeDeclaration.annotations[i];
if (Arrays.equals(annotation.type.getTypeBindingPublic(scope).signature(),
"Lorg/aspectj/lang/annotation/Aspect;".toCharArray())) {
kind = IProgramElement.Kind.ASPECT;
break;
}
}
}
IProgramElement peNode = new ProgramElement(
fullName,
kind,
makeLocation(memberTypeDeclaration),
memberTypeDeclaration.modifiers,null,null);
peNode.setSourceSignature(genSourceSignature(memberTypeDeclaration));
peNode.setFormalComment(generateJavadocComment(memberTypeDeclaration));
// if we're something like 'new Runnable(){..}' then set the
// bytecodeSignature to be the typename so we can match it later
// when creating the structure model
if (peNode.getBytecodeSignature() == null
&& memberTypeDeclaration.binding != null
&& memberTypeDeclaration.binding.constantPoolName() != null) {
StringTokenizer st = new StringTokenizer(
new String(memberTypeDeclaration.binding.constantPoolName()),"/");
while(st.hasMoreTokens()) {
String s = st.nextToken();
if (!st.hasMoreTokens()) {
peNode.setBytecodeSignature(s);
}
}
}
((IProgramElement)stack.peek()).addChild(peNode);
stack.push(peNode);
return true;
}
public void endVisit(TypeDeclaration memberTypeDeclaration, BlockScope scope) {
stack.pop();
}
private String genSourceSignature(TypeDeclaration typeDeclaration) {
StringBuffer output = new StringBuffer();
typeDeclaration.printHeader(0, output);
return output.toString();
}
private IProgramElement findEnclosingClass(Stack stack) {
for (int i = stack.size()-1; i >= 0; i--) {
IProgramElement pe = (IProgramElement)stack.get(i);
if (pe.getKind() == IProgramElement.Kind.CLASS) {
return pe;
}
}
return (IProgramElement)stack.peek();
}
public boolean visit(MethodDeclaration methodDeclaration, ClassScope scope) {
IProgramElement peNode = null;
// For intertype decls, use the modifiers from the original signature, not the generated method
if (methodDeclaration instanceof InterTypeDeclaration) {
InterTypeDeclaration itd = (InterTypeDeclaration) methodDeclaration;
ResolvedMember sig = itd.getSignature();
peNode = new ProgramElement(
null,
IProgramElement.Kind.ERROR,
makeLocation(methodDeclaration),
(sig!=null?sig.getModifiers():0),null,null);
} else {
peNode = new ProgramElement(
null,
IProgramElement.Kind.ERROR,
makeLocation(methodDeclaration),
methodDeclaration.modifiers,null,null);
}
formatter.genLabelAndKind(methodDeclaration, peNode); // will set the name
genBytecodeInfo(methodDeclaration, peNode);
List namedPointcuts = genNamedPointcuts(methodDeclaration);
if (shouldAddUsesPointcut) addUsesPointcutRelationsForNode(peNode, namedPointcuts, methodDeclaration);
if (methodDeclaration.returnType!=null) {
// if we don't make the distinction between ITD fields and other
// methods, then we loose the type, for example int, for the field
// and instead get "void".
if (peNode.getKind().equals(IProgramElement.Kind.INTER_TYPE_FIELD)) {
peNode.setCorrespondingType(methodDeclaration.returnType.toString());
} else {
if (methodDeclaration.returnType.resolvedType!=null)
peNode.setCorrespondingType(methodDeclaration.returnType.resolvedType.debugName());
else
peNode.setCorrespondingType(null);
}
} else {
peNode.setCorrespondingType(null);
}
peNode.setSourceSignature(genSourceSignature(methodDeclaration));
peNode.setFormalComment(generateJavadocComment(methodDeclaration));
// TODO: add return type test
if (peNode.getKind().equals(IProgramElement.Kind.METHOD)) {
if ((peNode.getName().charAt(0)=='m') &&
(peNode.toLabelString().equals("main(String[])")
|| peNode.toLabelString().equals("main(java.lang.String[])"))
&& peNode.getModifiers().contains(IProgramElement.Modifiers.STATIC)
&& peNode.getAccessibility().equals(IProgramElement.Accessibility.PUBLIC)) {
((IProgramElement)stack.peek()).setRunnable(true);
}
}
stack.push(peNode);
return true;
}
private void addUsesPointcutRelationsForNode(IProgramElement peNode, List namedPointcuts, MethodDeclaration declaration) {
for (Iterator it = namedPointcuts.iterator(); it.hasNext();) {
ReferencePointcut rp = (ReferencePointcut) it.next();
ResolvedMember member = getPointcutDeclaration(rp, declaration);
if (member != null) {
IRelationship foreward = AsmManager.getDefault().getRelationshipMap().get(peNode.getHandleIdentifier(), IRelationship.Kind.USES_POINTCUT, "uses pointcut", false, true);
foreward.addTarget(AsmManager.getDefault().getHandleProvider().createHandleIdentifier(member.getSourceLocation()));
IRelationship back = AsmManager.getDefault().getRelationshipMap().get(AsmManager.getDefault().getHandleProvider().createHandleIdentifier(member.getSourceLocation()), IRelationship.Kind.USES_POINTCUT, "pointcut used by", false, true);
back.addTarget(peNode.getHandleIdentifier());
}
}
}
private ResolvedMember getPointcutDeclaration(ReferencePointcut rp, MethodDeclaration declaration) {
EclipseFactory factory = ((AjLookupEnvironment)declaration.scope.environment()).factory;
World world = factory.getWorld();
UnresolvedType onType = rp.onType;
if (onType == null) {
if (declaration.binding != null) {
Member member = factory.makeResolvedMember(declaration.binding);
onType = member.getDeclaringType();
} else {
return null;
}
}
ResolvedMember[] members = onType.resolve(world).getDeclaredPointcuts();
if (members != null) {
for (int i = 0; i < members.length; i++) {
if (members[i].getName().equals(rp.name)) {
return members[i];
}
}
}
return null;
}
/**
* @param methodDeclaration
* @return all of the named pointcuts referenced by the PCD of this declaration
*/
private List genNamedPointcuts(MethodDeclaration methodDeclaration) {
List pointcuts = new ArrayList();
if (methodDeclaration instanceof AdviceDeclaration) {
if (((AdviceDeclaration)methodDeclaration).pointcutDesignator != null)
addAllNamed(((AdviceDeclaration)methodDeclaration).pointcutDesignator.getPointcut(), pointcuts);
} else if (methodDeclaration instanceof PointcutDeclaration) {
if (((PointcutDeclaration)methodDeclaration).pointcutDesignator != null)
addAllNamed(((PointcutDeclaration)methodDeclaration).pointcutDesignator.getPointcut(), pointcuts);
}
return pointcuts;
}
/**
* @param left
* @param pointcuts accumulator for named pointcuts
*/
private void addAllNamed(Pointcut pointcut, List pointcuts) {
if (pointcut == null) return;
if (pointcut instanceof ReferencePointcut) {
ReferencePointcut rp = (ReferencePointcut)pointcut;
pointcuts.add(rp);
} else if (pointcut instanceof AndPointcut) {
AndPointcut ap = (AndPointcut)pointcut;
addAllNamed(ap.getLeft(), pointcuts);
addAllNamed(ap.getRight(), pointcuts);
} else if (pointcut instanceof OrPointcut) {
OrPointcut op = (OrPointcut)pointcut;
addAllNamed(op.getLeft(), pointcuts);
addAllNamed(op.getRight(), pointcuts);
}
}
private String genSourceSignature(MethodDeclaration methodDeclaration) {
StringBuffer output = new StringBuffer();
ASTNode.printModifiers(methodDeclaration.modifiers, output);
methodDeclaration.printReturnType(0, output).append(methodDeclaration.selector).append('(');
if (methodDeclaration.arguments != null) {
for (int i = 0; i < methodDeclaration.arguments.length; i++) {
if (i > 0) output.append(", "); //$NON-NLS-1$
methodDeclaration.arguments[i].print(0, output);
}
}
output.append(')');
if (methodDeclaration.thrownExceptions != null) {
output.append(" throws "); //$NON-NLS-1$
for (int i = 0; i < methodDeclaration.thrownExceptions.length; i++) {
if (i > 0) output.append(", "); //$NON-NLS-1$
methodDeclaration.thrownExceptions[i].print(0, output);
}
}
return output.toString();
}
// protected void genBytecodeInfo(MethodDeclaration methodDeclaration, IProgramElement peNode) {
// if (methodDeclaration.binding != null) {
// String memberName = "";
// String memberBytecodeSignature = "";
// try {
// EclipseFactory factory = ((AjLookupEnvironment)methodDeclaration.scope.environment()).factory;
// Member member = factory.makeResolvedMember(methodDeclaration.binding);
// memberName = member.getName();
// memberBytecodeSignature = member.getSignature();
// } catch (BCException bce) { // bad type name
// memberName = "<undefined>";
// } catch (NullPointerException npe) {
// memberName = "<undefined>";
// }
//
// peNode.setBytecodeName(memberName);
// peNode.setBytecodeSignature(memberBytecodeSignature);
// }
// ((IProgramElement)stack.peek()).addChild(peNode);
// }
protected void genBytecodeInfo(MethodDeclaration methodDeclaration, IProgramElement peNode) {
if (methodDeclaration.binding != null) {
try {
EclipseFactory factory = ((AjLookupEnvironment)methodDeclaration.scope.environment()).factory;
Member member = factory.makeResolvedMember(methodDeclaration.binding);
peNode.setBytecodeName(member.getName());
peNode.setBytecodeSignature(member.getSignature());
} catch (BCException bce) { // bad type name
bce.printStackTrace();
} catch (NullPointerException npe) {
npe.printStackTrace();
}
}
((IProgramElement)stack.peek()).addChild(peNode);
}
public void endVisit(MethodDeclaration methodDeclaration, ClassScope scope) {
stack.pop();
}
public boolean visit(ImportReference importRef, CompilationUnitScope scope) {
int dotIndex = importRef.toString().lastIndexOf('.');
String currPackageImport = "";
if (dotIndex != -1) {
currPackageImport = importRef.toString().substring(0, dotIndex);
}
if (!((ProgramElement)stack.peek()).getPackageName().equals(currPackageImport)) {
IProgramElement peNode = new ProgramElement(
new String(importRef.toString()),
IProgramElement.Kind.IMPORT_REFERENCE,
makeLocation(importRef),
0,
null,null);
ProgramElement imports = (ProgramElement)((ProgramElement)stack.peek()).getChildren().get(0);
imports.addChild(0, peNode);
stack.push(peNode);
}
return true;
}
public void endVisit(ImportReference importRef, CompilationUnitScope scope) {
int dotIndex = importRef.toString().lastIndexOf('.');
String currPackageImport = "";
if (dotIndex != -1) {
currPackageImport = importRef.toString().substring(0, dotIndex);
}
if (!((ProgramElement)stack.peek()).getPackageName().equals(currPackageImport)) {
stack.pop();
}
}
public boolean visit(FieldDeclaration fieldDeclaration, MethodScope scope) {
IProgramElement peNode = null;
if (fieldDeclaration.type == null) { // The field represents an enum value
peNode = new ProgramElement(
new String(fieldDeclaration.name),IProgramElement.Kind.ENUM_VALUE,
makeLocation(fieldDeclaration), fieldDeclaration.modifiers,
null,null);
peNode.setCorrespondingType(fieldDeclaration.binding.type.debugName());
} else {
peNode = new ProgramElement(
new String(fieldDeclaration.name),IProgramElement.Kind.FIELD,
makeLocation(fieldDeclaration), fieldDeclaration.modifiers,
null,null);
peNode.setCorrespondingType(fieldDeclaration.type.toString());
}
peNode.setSourceSignature(genSourceSignature(fieldDeclaration));
peNode.setFormalComment(generateJavadocComment(fieldDeclaration));
((IProgramElement)stack.peek()).addChild(peNode);
stack.push(peNode);
return true;
}
public void endVisit(FieldDeclaration fieldDeclaration, MethodScope scope) {
stack.pop();
}
/**
* Checks if comments should be added to the model before generating.
*/
protected String generateJavadocComment(ASTNode astNode) {
if (buildConfig != null && !buildConfig.isGenerateJavadocsInModelMode()) return null;
StringBuffer sb = new StringBuffer(); // !!! specify length?
boolean completed = false;
int startIndex = -1;
if (astNode instanceof MethodDeclaration) {
startIndex = ((MethodDeclaration)astNode).declarationSourceStart;
} else if (astNode instanceof FieldDeclaration) {
startIndex = ((FieldDeclaration)astNode).declarationSourceStart;
} else if (astNode instanceof TypeDeclaration) {
startIndex = ((TypeDeclaration)astNode).declarationSourceStart;
}
if (startIndex == -1) {
return null;
} else if (currCompilationResult.compilationUnit.getContents()[startIndex] == '/' // look for /**
&& currCompilationResult.compilationUnit.getContents()[startIndex+1] == '*'
&& currCompilationResult.compilationUnit.getContents()[startIndex+2] == '*') {
for (int i = startIndex; i < astNode.sourceStart && !completed; i++) {
char curr = currCompilationResult.compilationUnit.getContents()[i];
if (curr == '/' && sb.length() > 2 && sb.charAt(sb.length()-1) == '*') completed = true; // found */
sb.append(currCompilationResult.compilationUnit.getContents()[i]);
}
return sb.toString();
} else {
return null;
}
}
/**
* Doesn't print qualified allocation expressions.
*/
protected String genSourceSignature(FieldDeclaration fieldDeclaration) {
StringBuffer output = new StringBuffer();
if (fieldDeclaration.type == null) { // This is an enum value
output.append(fieldDeclaration.name); // the "," or ";" has to be put on by whatever uses the sourceSignature
return output.toString();
} else {
FieldDeclaration.printModifiers(fieldDeclaration.modifiers, output);
fieldDeclaration.type.print(0, output).append(' ').append(fieldDeclaration.name);
}
if (fieldDeclaration.initialization != null
&& !(fieldDeclaration.initialization instanceof QualifiedAllocationExpression)) {
output.append(" = "); //$NON-NLS-1$
if (fieldDeclaration.initialization instanceof ExtendedStringLiteral) {
output.append("\"<extended string literal>\"");
} else {
fieldDeclaration.initialization.printExpression(0, output);
}
}
output.append(';');
return output.toString();
}
// public boolean visit(ImportReference importRef, CompilationUnitScope scope) {
// ProgramElementNode peNode = new ProgramElementNode(
// new String(importRef.toString()),
// ProgramElementNode.Kind.,
// makeLocation(importRef),
// 0,
// "",
// new ArrayList());
// ((IProgramElement)stack.peek()).addChild(0, peNode);
// stack.push(peNode);
// return true;
// }
// public void endVisit(ImportReference importRef,CompilationUnitScope scope) {
// stack.pop();
// }
public boolean visit(ConstructorDeclaration constructorDeclaration, ClassScope scope) {
if (constructorDeclaration.isDefaultConstructor) {
stack.push(null); // a little wierd but does the job
return true;
}
StringBuffer argumentsSignature = new StringBuffer();
argumentsSignature.append("(");
if (constructorDeclaration.arguments!=null) {
for (int i = 0;i<constructorDeclaration.arguments.length;i++) {
argumentsSignature.append(constructorDeclaration.arguments[i].type);
if (i+1<constructorDeclaration.arguments.length) argumentsSignature.append(",");
}
}
argumentsSignature.append(")");
IProgramElement peNode = new ProgramElement(
new String(constructorDeclaration.selector)+argumentsSignature,
IProgramElement.Kind.CONSTRUCTOR,
makeLocation(constructorDeclaration),
constructorDeclaration.modifiers,
null,null);
peNode.setModifiers(constructorDeclaration.modifiers);
peNode.setSourceSignature(genSourceSignature(constructorDeclaration));
// Fix to enable us to anchor things from ctor nodes
if (constructorDeclaration.binding != null) {
String memberName = "";
String memberBytecodeSignature = "";
try {
EclipseFactory factory = ((AjLookupEnvironment)constructorDeclaration.scope.environment()).factory;
Member member = factory.makeResolvedMember(constructorDeclaration.binding);
memberName = member.getName();
memberBytecodeSignature = member.getSignature();
} catch (BCException bce) { // bad type name
memberName = "<undefined>";
} catch (NullPointerException npe) {
memberName = "<undefined>";
}
peNode.setBytecodeName(memberName);
peNode.setBytecodeSignature(memberBytecodeSignature);
}
((IProgramElement)stack.peek()).addChild(peNode);
stack.push(peNode);
return true;
}
public void endVisit(ConstructorDeclaration constructorDeclaration, ClassScope scope) {
stack.pop();
}
private String genSourceSignature(ConstructorDeclaration constructorDeclaration) {
StringBuffer output = new StringBuffer();
ASTNode.printModifiers(constructorDeclaration.modifiers, output);
output.append(constructorDeclaration.selector).append('(');
if (constructorDeclaration.arguments != null) {
for (int i = 0; i < constructorDeclaration.arguments.length; i++) {
if (i > 0) output.append(", "); //$NON-NLS-1$
constructorDeclaration.arguments[i].print(0, output);
}
}
output.append(')');
if (constructorDeclaration.thrownExceptions != null) {
output.append(" throws "); //$NON-NLS-1$
for (int i = 0; i < constructorDeclaration.thrownExceptions.length; i++) {
if (i > 0) output.append(", "); //$NON-NLS-1$
constructorDeclaration.thrownExceptions[i].print(0, output);
}
}
return output.toString();
}
// public boolean visit(Clinit clinit, ClassScope scope) {
// ProgramElementNode peNode = new ProgramElementNode(
// "<clinit>",
// ProgramElementNode.Kind.INITIALIZER,
// makeLocation(clinit),
// clinit.modifiers,
// "",
// new ArrayList());
// ((IProgramElement)stack.peek()).addChild(peNode);
// stack.push(peNode);
// return false;
// }
// public void endVisit(Clinit clinit, ClassScope scope) {
// stack.pop();
// }
/** This method works-around an odd traverse implementation on Initializer
*/
private Initializer inInitializer = null;
public boolean visit(Initializer initializer, MethodScope scope) {
if (initializer == inInitializer) return false;
inInitializer = initializer;
IProgramElement peNode = new ProgramElement(
"...",
IProgramElement.Kind.INITIALIZER,
makeLocation(initializer),
initializer.modifiers,null,null);
// "",
// new ArrayList());
((IProgramElement)stack.peek()).addChild(peNode);
stack.push(peNode);
initializer.block.traverse(this, scope);
stack.pop();
inInitializer=null;
return false;
}
// ??? handle non-existant files
protected ISourceLocation makeLocation(ASTNode node) {
String fileName = "";
if (filename != null) {
fileName = this.filename;
}
// AMC - different strategies based on node kind
int startLine = getStartLine(node);
int endLine = getEndLine(node);
SourceLocation loc = null;
if ( startLine <= endLine ) {
// found a valid end line for this node...
loc = new SourceLocation(new File(fileName), startLine, endLine);
loc.setOffset(node.sourceStart);
} else {
loc = new SourceLocation(new File(fileName), startLine);
loc.setOffset(node.sourceStart);
}
return loc;
}
// AMC - overloaded set of methods to get start and end lines for
// various ASTNode types. They have no common ancestor in the
// hierarchy!!
protected int getStartLine( ASTNode n){
// if ( n instanceof AbstractVariableDeclaration ) return getStartLine( (AbstractVariableDeclaration)n);
// if ( n instanceof AbstractMethodDeclaration ) return getStartLine( (AbstractMethodDeclaration)n);
// if ( n instanceof TypeDeclaration ) return getStartLine( (TypeDeclaration)n);
return ProblemHandler.searchLineNumber(lineseps,
// currCompilationResult.lineSeparatorPositions,
n.sourceStart);
}
// AMC - overloaded set of methods to get start and end lines for
// various ASTNode types. They have no common ancestor in the
// hierarchy!!
protected int getEndLine( ASTNode n){
if ( n instanceof AbstractVariableDeclaration ) return getEndLine( (AbstractVariableDeclaration)n);
if ( n instanceof AbstractMethodDeclaration ) return getEndLine( (AbstractMethodDeclaration)n);
if ( n instanceof TypeDeclaration ) return getEndLine( (TypeDeclaration)n);
return ProblemHandler.searchLineNumber(lineseps,
// currCompilationResult.lineSeparatorPositions,
n.sourceEnd);
}
// AMC - overloaded set of methods to get start and end lines for
// various ASTNode types. They have no common ancestor in the
// hierarchy!!
// private int getStartLine( AbstractVariableDeclaration avd ) {
// return ProblemHandler.searchLineNumber(
// currCompilationResult.lineSeparatorPositions,
// avd.declarationSourceStart);
// }
// AMC - overloaded set of methods to get start and end lines for
// various ASTNode types. They have no common ancestor in the
// hierarchy!!
private int getEndLine( AbstractVariableDeclaration avd ){
return ProblemHandler.searchLineNumber(lineseps,
// currCompilationResult.lineSeparatorPositions,
avd.declarationSourceEnd);
}
// AMC - overloaded set of methods to get start and end lines for
// various ASTNode types. They have no common ancestor in the
// hierarchy!!
// private int getStartLine( AbstractMethodDeclaration amd ){
// return ProblemHandler.searchLineNumber(
// currCompilationResult.lineSeparatorPositions,
// amd.declarationSourceStart);
// }
// AMC - overloaded set of methods to get start and end lines for
// various ASTNode types. They have no common ancestor in the
// hierarchy!!
private int getEndLine( AbstractMethodDeclaration amd) {
return ProblemHandler.searchLineNumber(lineseps,
// currCompilationResult.lineSeparatorPositions,
amd.declarationSourceEnd);
}
// AMC - overloaded set of methods to get start and end lines for
// various ASTNode types. They have no common ancestor in the
// hierarchy!!
// private int getStartLine( TypeDeclaration td ){
// return ProblemHandler.searchLineNumber(
// currCompilationResult.lineSeparatorPositions,
// td.declarationSourceStart);
// }
// AMC - overloaded set of methods to get start and end lines for
// various ASTNode types. They have no common ancestor in the
// hierarchy!!
private int getEndLine( TypeDeclaration td){
return ProblemHandler.searchLineNumber(lineseps,
// currCompilationResult.lineSeparatorPositions,
td.declarationSourceEnd);
}
}
|
143,930 |
Bug 143930 create constructor ipe in same was as method ipes
| null |
resolved fixed
|
26a8a86
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-05-30T09:59:53Z | 2006-05-26T10:40:00Z |
tests/src/org/aspectj/systemtest/ajc151/Ajc151Tests.java
|
/*******************************************************************************
* Copyright (c) 2006 IBM
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* Andy Clement - initial API and implementation
*******************************************************************************/
package org.aspectj.systemtest.ajc151;
import java.io.File;
import java.util.Iterator;
import java.util.List;
import junit.framework.Test;
import org.aspectj.asm.AsmManager;
import org.aspectj.asm.IHierarchy;
import org.aspectj.asm.IProgramElement;
import org.aspectj.asm.internal.Relationship;
import org.aspectj.systemtest.ajc150.GenericsTests;
import org.aspectj.testing.XMLBasedAjcTestCase;
public class Ajc151Tests extends org.aspectj.testing.XMLBasedAjcTestCase {
// Some @DeclareParents testing
public void testAtDecp_1() { runTest("atDecp - simple");}
public void testAtDecp_2() { runTest("atDecp - annotation");}
public void testAtDecp_3() { runTest("atDecp - binary interface");}
public void testAtDecp_4() { runTest("atDecp - binary interface - 2");}
public void testAnnotationsAndItds_pr98901() { runTest("annotations and itds");}
public void testAnnotationsAndItds_pr98901_2() { runTest("annotations and itds - 2");}
public void testCircularGenerics_pr133307() { runTest("circular generics");}
public void testDeca() { runTest("doubly annotating a method with declare");}
public void testDeca2() { runTest("doubly annotating a method with declare - 2");}
public void testCrashingWithASM_pr132926_1() { runTest("crashing on annotation type resolving with asm - 1");}
public void testCrashingWithASM_pr132926_2() { runTest("crashing on annotation type resolving with asm - 2");}
public void testCrashingWithASM_pr132926_3() { runTest("crashing on annotation type resolving with asm - 3");}
public void testGenericAdviceParameters_pr123553() { runTest("generic advice parameters");}
public void testMemberTypesInGenericTypes_pr122458() { runTest("member types in generic types");}
public void testMemberTypesInGenericTypes_pr122458_2() { runTest("member types in generic types - 2");}
public void testNPEOnDeclareAnnotation_pr123695() { runTest("Internal nullptr exception with complex declare annotation");}
public void testHasMemberPackageProblem_pr124105() { runTest("hasMember problems with packages");}
public void testDifferentNumbersofTVars_pr124803() { runTest("generics and different numbers of type variables");}
public void testDifferentNumbersofTVars_pr124803_2() { runTest("generics and different numbers of type variables - classes");}
public void testParameterizedCollectionFieldMatching_pr124808() { runTest("parameterized collection fields matched via pointcut");}
public void testGenericAspectsAndAnnotations_pr124654() { runTest("generic aspects and annotations");}
public void testCallInheritedGenericMethod_pr124999() { runTest("calling inherited generic method from around advice");}
public void testIncorrectlyReferencingPointcuts_pr122452() { runTest("incorrectly referencing pointcuts");}
public void testIncorrectlyReferencingPointcuts_pr122452_2() { runTest("incorrectly referencing pointcuts - 2");}
public void testInlinevisitorNPE_pr123901() { runTest("inlinevisitor NPE");}
//public void testExposingWithintype_enh123423() { runTest("exposing withintype");}
//public void testMissingImport_pr127299() { runTest("missing import gives funny message");}
public void testUnusedInterfaceMessage_pr120527() { runTest("incorrect unused interface message");}
public void testAtAspectInheritsAdviceWithTJPAndThis_pr125699 () { runTest("inherit advice with this() and thisJoinPoint"); }
public void testAtAspectInheritsAdviceWithTJPAndThis_pr125699_2 () {runTest("inherit advice with this() and thisJoinPoint - 2"); }
public void testBrokenLTW_pr128744() { runTest("broken ltw"); }
public void testAtAspectNoInvalidAbsoluteTypeName_pr126560() {
runTest("@AJ deow doesn't throw an invalidAbsoluteTypeName when specify type in the same package");
}
public void testAtAspectNoInvalidAbsoluteTypeName_pr126560_2() {
runTest("@AJ deow doesn't throw an invalidAbsoluteTypeName when specify type in the same file");
}
public void testArrayindexoutofbounds_pr129566() {
runTest("arrayindexoutofbounds");
// public class SkipList<T extends Comparable> extends Object implements Set<T>, Iterable<T>
GenericsTests.verifyClassSignature(ajc,"common.SkipList","<T::Ljava/lang/Comparable;>Ljava/lang/Object;Ljava/util/Set<TT;>;Ljava/lang/Iterable<TT;>;");
// protected class SkipListElement<E> extends Object
GenericsTests.verifyClassSignature(ajc,"common.SkipList$SkipListElement","<E:Ljava/lang/Object;>Ljava/lang/Object;");
// protected class SkipListIterator<E> implements Iterator<T>
GenericsTests.verifyClassSignature(ajc,"common.SkipList$SkipListIterator","<E:Ljava/lang/Object;>Ljava/lang/Object;Ljava/util/Iterator<TT;>;");
}
public void testMixingNumbersOfTypeParameters_pr125080() {
runTest("mixing numbers of type parameters");
GenericsTests.verifyClassSignature(ajc,"AspectInterface","<T:Ljava/lang/Object;S:Ljava/lang/Object;>Ljava/lang/Object;");
GenericsTests.verifyClassSignature(ajc,"AbstractAspect","<T:Ljava/lang/Object;>Ljava/lang/Object;LAspectInterface<TT;Ljava/lang/Integer;>;");
GenericsTests.verifyClassSignature(ajc,"ConcreteAspect","LAbstractAspect<Ljava/lang/String;>;");
}
public void testMixingNumbersOfTypeParameters_pr125080_2() {
runTest("mixing numbers of type parameters - 2");
GenericsTests.verifyClassSignature(ajc,"AspectInterface","<T:Ljava/lang/Object;S:Ljava/lang/Number;>Ljava/lang/Object;");
GenericsTests.verifyClassSignature(ajc,"AbstractAspect","<T:Ljava/lang/Object;>Ljava/lang/Object;LAspectInterface<TT;Ljava/lang/Integer;>;");
GenericsTests.verifyClassSignature(ajc,"ConcreteAspect","LAbstractAspect<LStudent;>;");
}
public void testIProgramElementMethods_pr125295() {
runTest("new IProgramElement methods");
IHierarchy top = AsmManager.getDefault().getHierarchy();
IProgramElement pe = top.findElementForType("pkg","foo");
assertNotNull("Couldn't find 'foo' element in the tree",pe);
// check that the defaults return the fully qualified arg
assertEquals("foo(int,java.lang.Object)",pe.toLabelString());
assertEquals("C.foo(int,java.lang.Object)",pe.toLinkLabelString());
assertEquals("foo(int,java.lang.Object)",pe.toSignatureString());
// check that can get hold of the non qualified args
assertEquals("foo(int,Object)",pe.toLabelString(false));
assertEquals("C.foo(int,Object)",pe.toLinkLabelString(false));
assertEquals("foo(int,Object)",pe.toSignatureString(false));
IProgramElement pe2 = top.findElementForType("pkg","printParameters");
assertNotNull("Couldn't find 'printParameters' element in the tree",pe2);
// the argument is org.aspectj.lang.JoinPoint, check that this is added
assertFalse("printParameters method should have arguments",pe2.getParameterTypes().isEmpty());
}
public void testParameterizedEnum_pr126316() {
runTest("E extends Enum(E) again");
}
public void testSwallowedException() {
runTest("swallowed exceptions");
}
public void testAtAspectVerifyErrorWithAfterThrowingAndthisJoinPoint_pr122742() {
runTest("@AJ VerifyError with @AfterThrowing and thisJoinPoint argument");
}
public void testAtAspectVerifyErrorWithAfterReturningAndthisJoinPoint_pr122742() {
runTest("@AJ VerifyError with @AfterReturning and thisJoinPoint argument");
}
public void testSwallowedExceptionIgnored() {
runTest("swallowed exceptions with xlint");
}
public void testGenericAspectWithUnknownType_pr131933() {
runTest("no ClassCastException with generic aspect and unknown type");
}
public void testStructureModelForGenericITD_pr131932() {
//AsmManager.setReporting("c:/debug.txt",true,true,true,true);
runTest("structure model for generic itd");
IHierarchy top = AsmManager.getDefault().getHierarchy();
// get the IProgramElements corresponding to the ITDs and classes
IProgramElement foo = top.findElementForLabel(top.getRoot(),
IProgramElement.Kind.CLASS,"Foo");
assertNotNull("Couldn't find Foo element in the tree",foo);
IProgramElement bar = top.findElementForLabel(top.getRoot(),
IProgramElement.Kind.CLASS,"Bar");
assertNotNull("Couldn't find Bar element in the tree",bar);
IProgramElement method = top.findElementForLabel(top.getRoot(),
IProgramElement.Kind.INTER_TYPE_METHOD,"Bar.getFirst()");
assertNotNull("Couldn't find 'Bar.getFirst()' element in the tree",method);
IProgramElement field = top.findElementForLabel(top.getRoot(),
IProgramElement.Kind.INTER_TYPE_FIELD,"Bar.children");
assertNotNull("Couldn't find 'Bar.children' element in the tree",field);
IProgramElement constructor = top.findElementForLabel(top.getRoot(),
IProgramElement.Kind.INTER_TYPE_CONSTRUCTOR,"Foo.Foo(List<T>)");
assertNotNull("Couldn't find 'Foo.Foo(List<T>)' element in the tree",constructor);
// check that the relationship map has 'itd method declared on bar'
List matches = AsmManager.getDefault().getRelationshipMap().get(method);
assertNotNull("itd Bar.getFirst() should have some relationships but does not",matches);
assertTrue("method itd should have one relationship but has " + matches.size(), matches.size() == 1);
List matchesTargets = ((Relationship)matches.get(0)).getTargets();
assertTrue("itd Bar.getFirst() should have one target but has " + matchesTargets.size(),matchesTargets.size() == 1);
IProgramElement target = AsmManager.getDefault().getHierarchy().findElementForHandle((String)matchesTargets.get(0));
assertEquals("target of relationship should be the Bar class but is IPE with label "
+ target.toLabelString(),bar,target);
// check that the relationship map has 'itd field declared on bar'
matches = AsmManager.getDefault().getRelationshipMap().get(field);
assertNotNull("itd Bar.children should have some relationships but does not",matches);
assertTrue("field itd should have one relationship but has " + matches.size(), matches.size() == 1);
matchesTargets = ((Relationship)matches.get(0)).getTargets();
assertTrue("itd Bar.children should have one target but has " + matchesTargets.size(),matchesTargets.size() == 1);
target = AsmManager.getDefault().getHierarchy().findElementForHandle((String)matchesTargets.get(0));
assertEquals("target of relationship should be the Bar class but is IPE with label "
+ target.toLabelString(),bar,target);
// check that the relationship map has 'itd constructor declared on foo'
matches = AsmManager.getDefault().getRelationshipMap().get(constructor);
assertNotNull("itd Foo.Foo(List<T>) should have some relationships but does not",matches);
assertTrue("constructor itd should have one relationship but has " + matches.size(), matches.size() == 1);
matchesTargets = ((Relationship)matches.get(0)).getTargets();
assertTrue("itd Foo.Foo(List<T>) should have one target but has " + matchesTargets.size(),matchesTargets.size() == 1);
target = AsmManager.getDefault().getHierarchy().findElementForHandle((String)matchesTargets.get(0));
assertEquals("target of relationship should be the Foo class but is IPE with label "
+ target.toLabelString(),foo,target);
// check that the relationship map has 'bar aspect declarations method and field itd'
matches = AsmManager.getDefault().getRelationshipMap().get(bar);
assertNotNull("Bar should have some relationships but does not",matches);
assertTrue("Bar should have one relationship but has " + matches.size(), matches.size() == 1);
matchesTargets = ((Relationship)matches.get(0)).getTargets();
assertTrue("Bar should have two targets but has " + matchesTargets.size(),matchesTargets.size() == 2);
for (Iterator iter = matchesTargets.iterator(); iter.hasNext();) {
String element = (String) iter.next();
target = AsmManager.getDefault().getHierarchy().findElementForHandle(element);
if (!target.equals(method) && !target.equals(field)) {
fail("Expected rel target to be " + method.toLabelString() + " or " + field.toLabelString()
+ ", found " + target.toLabelString());
}
}
// check that the relationship map has 'foo aspect declarations constructor itd'
matches = AsmManager.getDefault().getRelationshipMap().get(foo);
assertNotNull("Foo should have some relationships but does not",matches);
assertTrue("Foo should have one relationship but has " + matches.size(), matches.size() == 1);
matchesTargets = ((Relationship)matches.get(0)).getTargets();
assertTrue("Foo should have one target but has " + matchesTargets.size(),matchesTargets.size() == 1);
target = AsmManager.getDefault().getHierarchy().findElementForHandle((String)matchesTargets.get(0));
assertEquals("target of relationship should be the Foo.Foo(List<T>) itd but is IPE with label "
+ target.toLabelString(),constructor,target);
}
public void testDeclareAnnotationAppearsInStructureModel_pr132130() {
//AsmManager.setReporting("c:/debug.txt",true,true,true,true);
runTest("declare annotation appears in structure model when in same file");
IHierarchy top = AsmManager.getDefault().getHierarchy();
// get the IProgramElements corresponding to the different code entries
IProgramElement decam = top.findElementForLabel(top.getRoot(),
IProgramElement.Kind.DECLARE_ANNOTATION_AT_METHOD,"declare @method: * debit(..) : @Secured(role = \"supervisor\")");
assertNotNull("Couldn't find 'declare @method' element in the tree",decam);
IProgramElement method = top.findElementForLabel(top.getRoot(),
IProgramElement.Kind.METHOD,"debit(long,long)");
assertNotNull("Couldn't find the 'debit(long,long)' method element in the tree",method);
IProgramElement decac = top.findElementForLabel(top.getRoot(),
IProgramElement.Kind.DECLARE_ANNOTATION_AT_CONSTRUCTOR,"declare @constructor: BankAccount+.new(..) : @Secured(role = \"supervisor\")");
assertNotNull("Couldn't find 'declare @constructor' element in the tree",decac);
IProgramElement ctr = top.findElementForLabel(top.getRoot(),
IProgramElement.Kind.CONSTRUCTOR,"BankAccount(String,int)");
assertNotNull("Couldn't find the 'BankAccount(String,int)' constructor element in the tree",ctr);
// check that decam has a annotates relationship with the debit method
List matches = AsmManager.getDefault().getRelationshipMap().get(decam);
assertNotNull("'declare @method' should have some relationships but does not",matches);
assertTrue("'declare @method' should have one relationships but has " + matches.size(),matches.size()==1);
List matchesTargets = ((Relationship)matches.get(0)).getTargets();
assertTrue("'declare @method' should have one targets but has" + matchesTargets.size(),matchesTargets.size()==1);
IProgramElement target = AsmManager.getDefault().getHierarchy().findElementForHandle((String)matchesTargets.get(0));
assertEquals("target of relationship should be the 'debit(long,long)' method but is IPE with label "
+ target.toLabelString(),method,target);
// check that the debit method has an annotated by relationship with the declare @method
matches = AsmManager.getDefault().getRelationshipMap().get(method);
assertNotNull("'debit(long,long)' should have some relationships but does not",matches);
assertTrue("'debit(long,long)' should have one relationships but has " + matches.size(),matches.size()==1);
matchesTargets = ((Relationship)matches.get(0)).getTargets();
assertTrue("'debit(long,long)' should have one targets but has" + matchesTargets.size(),matchesTargets.size()==1);
target = AsmManager.getDefault().getHierarchy().findElementForHandle((String)matchesTargets.get(0));
assertEquals("target of relationship should be the 'declare @method' ipe but is IPE with label "
+ target.toLabelString(),decam,target);
// check that decac has a annotates relationship with the constructor
matches = AsmManager.getDefault().getRelationshipMap().get(decac);
assertNotNull("'declare @method' should have some relationships but does not",matches);
assertTrue("'declare @method' should have one relationships but has " + matches.size(),matches.size()==1);
matchesTargets = ((Relationship)matches.get(0)).getTargets();
assertTrue("'declare @method' should have one targets but has" + matchesTargets.size(),matchesTargets.size()==1);
target = AsmManager.getDefault().getHierarchy().findElementForHandle((String)matchesTargets.get(0));
assertEquals("target of relationship should be the 'debit(long, long)' method but is IPE with label "
+ target.toLabelString(),ctr,target);
// check that the constructor has an annotated by relationship with the declare @constructor
matches = AsmManager.getDefault().getRelationshipMap().get(ctr);
assertNotNull("'debit(long, long)' should have some relationships but does not",matches);
assertTrue("'debit(long, long)' should have one relationships but has " + matches.size(),matches.size()==1);
matchesTargets = ((Relationship)matches.get(0)).getTargets();
assertTrue("'debit(long, long)' should have one targets but has" + matchesTargets.size(),matchesTargets.size()==1);
target = AsmManager.getDefault().getHierarchy().findElementForHandle((String)matchesTargets.get(0));
assertEquals("target of relationship should be the 'declare @method' ipe but is IPE with label "
+ target.toLabelString(),decac,target);
}
/*
* @AspectJ bugs and enhancements
*/
// public void testAtAspectInheritsAdviceWithTJPAndThis_pr125699 () {
// runTest("inherit adivce with this() and thisJoinPoint");
// }
public void testAtAspectInheritsAbstractPointcut_pr125810 () {
runTest("warning when inherited pointcut not made concrete");
}
public void testAtAspectDEOWInStructureModel_pr120356() {
//AsmManager.setReporting("c:/debug.txt",true,true,true,true);
runTest("@AJ deow appear correctly when structure model is generated");
IHierarchy top = AsmManager.getDefault().getHierarchy();
// get the IProgramElements corresponding to the @DeclareWarning statement
// and the method it matches.
IProgramElement warningMethodIPE = top.findElementForLabel(top.getRoot(),
IProgramElement.Kind.METHOD,"warningMethod()");
assertNotNull("Couldn't find 'warningMethod()' element in the tree",warningMethodIPE);
IProgramElement atDeclareWarningIPE = top.findElementForLabel(top.getRoot(),
IProgramElement.Kind.FIELD,"warning");
assertNotNull("Couldn't find @DeclareWarning element in the tree",atDeclareWarningIPE);
// check that the method has a matches declare relationship with @DeclareWarning
List matches = AsmManager.getDefault().getRelationshipMap().get(warningMethodIPE);
assertNotNull("warningMethod should have some relationships but does not",matches);
assertTrue("warningMethod should have one relationships but has " + matches.size(),matches.size()==1);
List matchesTargets = ((Relationship)matches.get(0)).getTargets();
assertTrue("warningMethod should have one targets but has" + matchesTargets.size(),matchesTargets.size()==1);
IProgramElement target = AsmManager.getDefault().getHierarchy().findElementForHandle((String)matchesTargets.get(0));
assertEquals("target of relationship should be the @DeclareWarning 'warning' but is IPE with label "
+ target.toLabelString(),atDeclareWarningIPE,target);
// check that the @DeclareWarning has a matches relationship with the warningMethod
List matchedBy = AsmManager.getDefault().getRelationshipMap().get(atDeclareWarningIPE);
assertNotNull("@DeclareWarning should have some relationships but does not",matchedBy);
assertTrue("@DeclareWarning should have one relationship but has " + matchedBy.size(), matchedBy.size() == 1);
List matchedByTargets = ((Relationship)matchedBy.get(0)).getTargets();
assertTrue("@DeclareWarning 'matched by' relationship should have one target " +
"but has " + matchedByTargets.size(), matchedByTargets.size() == 1);
IProgramElement matchedByTarget = AsmManager.getDefault().getHierarchy().findElementForHandle((String)matchedByTargets.get(0));
assertEquals("target of relationship should be the warningMethod but is IPE with label "
+ matchedByTarget.toLabelString(),warningMethodIPE,matchedByTarget);
// get the IProgramElements corresponding to the @DeclareError statement
// and the method it matches.
IProgramElement errorMethodIPE = top.findElementForLabel(top.getRoot(),
IProgramElement.Kind.METHOD,"badMethod()");
assertNotNull("Couldn't find 'badMethod()' element in the tree",errorMethodIPE);
IProgramElement atDeclarErrorIPE = top.findElementForLabel(top.getRoot(),
IProgramElement.Kind.FIELD,"error");
assertNotNull("Couldn't find @DeclareError element in the tree",atDeclarErrorIPE);
// check that the @DeclareError has a matches relationship with the badMethod
List matchedByE = AsmManager.getDefault().getRelationshipMap().get(atDeclarErrorIPE);
assertNotNull("@DeclareError should have some relationships but does not",matchedByE);
assertTrue("@DeclareError should have one relationship but has " + matchedByE.size(), matchedByE.size() == 1);
List matchedByTargetsE = ((Relationship)matchedByE.get(0)).getTargets();
assertTrue("@DeclareError 'matched by' relationship should have one target " +
"but has " + matchedByTargetsE.size(), matchedByTargetsE.size() == 1);
IProgramElement matchedByTargetE = AsmManager.getDefault().getHierarchy().findElementForHandle((String)matchedByTargetsE.get(0));
assertEquals("target of relationship should be the badMethod but is IPE with label "
+ matchedByTargetE.toLabelString(),errorMethodIPE,matchedByTargetE);
}
public void testAtAspectNoNPEWithDEOWWithoutStructureModel_pr120356() {
runTest("@AJ no NPE with deow when structure model isn't generated");
}
public void testAtAspectWithoutJoinPointImport_pr121616() {
runTest("@AJ without JoinPoint import");
}
public void testAtAspectDeclareParentsRetainsFieldState_pr122370() {
runTest("@AJ declare parents retains field state");
}
public void testAtAspectNoNPEWithPcdContainingOrThisAndWildcard_pr128237() {
runTest("@AJ no npe with pointcut containing or, this and a wildcard");
}
/*
* Load-time weaving bugs and enhancements
*/
public void testEmptyPointcutInAtAspectJ_pr125475 () {
runTest("define empty pointcut using an annotation");
}
public void testEmptyPointcutInAtAspectJ_pr125475_2() {
runTest("define empty pointcut using an annotation - 2");
}
public void testEmptyPointcutInAtAspectJWithLTW_pr125475 () {
runTest("define empty pointcut using aop.xml");
}
public void testGenericAspectsWithAnnotationTypeParameters() {
runTest("Generic aspects with annotation type parameters");
}
public void testPointcutInterfaces_pr130869() {
runTest("Pointcut interfaces");
}
/////////////////////////////////////////
public static Test suite() {
return XMLBasedAjcTestCase.loadSuite(Ajc151Tests.class);
}
protected File getSpecFile() {
return new File("../tests/src/org/aspectj/systemtest/ajc151/ajc151.xml");
}
}
|
143,930 |
Bug 143930 create constructor ipe in same was as method ipes
| null |
resolved fixed
|
26a8a86
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-05-30T09:59:53Z | 2006-05-26T10:40:00Z |
tests/src/org/aspectj/systemtest/ajc152/Ajc152Tests.java
|
/*******************************************************************************
* Copyright (c) 2006 IBM
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* Andy Clement - initial API and implementation
*******************************************************************************/
package org.aspectj.systemtest.ajc152;
import java.io.File;
import junit.framework.Test;
//import org.aspectj.systemtest.ajc150.GenericsTests;
import org.aspectj.testing.XMLBasedAjcTestCase;
public class Ajc152Tests extends org.aspectj.testing.XMLBasedAjcTestCase {
public void testAspects14PerSingleton_pr122253() { runTest("aspects14 - persingleton");}
public void testAspects14PerCflow_pr122253() { runTest("aspects14 - percflow");}
public void testAspects14PerThis_pr122253() { runTest("aspects14 - perthis");}
public void testAspects14PerTypeWithin_pr122253() { runTest("aspects14 - pertypewithin");}
public void testFunkyGenericErrorWithITDs_pr126355() { runTest("bizarre generic error with itds");}
public void testConcretizingAbstractMethods_pr142466() { runTest("aop.xml aspect inheriting but not concretizing abstract method");}
public void testConcretizingAbstractMethods_pr142466_2() { runTest("aop.xml aspect inheriting but not concretizing abstract method - 2");}
public void testComplexGenericDecl_pr137568() { runTest("complicated generics declaration");}
public void testItdOnInnerTypeOfGenericType_pr132349() { runTest("ITD on inner type of generic type");}
public void testItdOnInnerTypeOfGenericType_pr132349_2() { runTest("ITD on inner type of generic type - 2");}
public void testItdOnInnerTypeOfGenericType_pr132349_3() { runTest("ITD on inner type of generic type - 3");}
// public void testCovarianceAndDecp_pr128443_1() { runTest("covariance and decp - 1"); }
public void testLTWGeneratedAspectAbstractMethod_pr125480() { runTest("aop.xml aspect inheriting abstract method ");}
public void testLTWGeneratedAspectAbstractMethod_pr125480_2() { runTest("aop.xml aspect inheriting abstract method - code style");}
//public void testSuperITDExplosion_pr134425() { runTest("super ITDs");}
//public void testMisbehavingDeclareAnnotation_pr135865() { runTest("misbehaving declare annotation");}
//public void testMisbehavingDeclareAnnotation_pr135865_2() { runTest("misbehaving declare annotation - 2");}
public void testCompletelyBrokenAopConcretization_pr142165_1() { runTest("broken concretization");}
public void testCompletelyBrokenAopConcretization_pr142165_2() { runTest("broken concretization - 2");}
public void testCompletelyBrokenAopConcretization_pr142165_3() { runTest("broken concretization - 3");}
public void testVerifyErrorLTW_pr135068() { runTest("ltw verifyerror");}
public void testVerifyErrorLTW_pr135068_2() { runTest("ltw verifyerror - 2");}
public void testVerifyErrorLTW_pr135068_3() { runTest("ltw verifyerror - 3");}
public void testVerifyErrorLTW_pr135068_4() { runTest("ltw verifyerror - 4");}
public void testVerifyErrorForComplexCflow_pr136026() { runTest("verifyerror");}
public void testVerifyErrorForComplexCflow_pr136026_2() { runTest("verifyerror - 2");}
public void testAnnotationsAndGenericsBCException_pr129704() { runTest("annotations and generics leading to BCException");}
public void testMethodTooBigAfterWeaving_pr138384() { runTest("method too big"); }
public void testNotAtWithincode_pr138158_1() { runTest("not at withincode - 1");}
public void testNotAtWithincode_pr138158_2() { runTest("not at withincode - 2");}
public void testNotAtWithincode_pr138158_3() { runTest("not at within - 3");}
public void testNpeOnDup_pr138143() { runTest("npe on duplicate method with ataj");}
public void testPointcutsAndGenerics_pr137496_1() { runTest("pointcuts and generics - B");}
public void testPointcutsAndGenerics_pr137496_2() { runTest("pointcuts and generics - D");}
public void testPointcutsAndGenerics_pr137496_3() { runTest("pointcuts and generics - E");}
public void testPointcutsAndGenerics_pr137496_4() { runTest("pointcuts and generics - F");}
public void testPointcutsAndGenerics_pr137496_5() { runTest("pointcuts and generics - G");}
public void testPointcutsAndGenerics_pr137496_6() { runTest("pointcuts and generics - H");}
public void testAspectLibrariesAndASM_pr135001() { runTest("aspect libraries and asm");}
public void testStackOverflow_pr136258() { runTest("stack overflow");}
public void testIncorrectOverridesEvaluation13() { runTest("incorrect overrides evaluation - 1.3"); }
public void testIncorrectOverridesEvaluation15() { runTest("incorrect overrides evaluation - 1.5"); }
public void testAtWithinCodeBug_pr138798() { runTest("atWithinCodeBug"); }
public void testReferencePCutInDeclareWarning_pr138215() { runTest("Reference pointcut fails inside @DeclareWarning");}
public void testReferencePCutInPerClause_pr138219() { runTest("Can't use a FQ Reference pointcut in any pointcut expression referenced by a per-clause");}
public void testReferencePCutInPerClause_pr130722() { runTest("FQ Reference pointcut from perclause ref pc"); }
public void testDoubleAnnotationMatching_pr138223() { runTest("Double at annotation matching (no binding)");}
public void testSuperCallsInAtAspectJAdvice_pr139749() { runTest("Super calls in @AspectJ advice");}
public void testNoClassCastExceptionWithPerThis_pr138286() { runTest("No ClassCastException with perThis");}
// this next one reported as a bug by Rob Harrop, but I can't reproduce the failure yet...
//public void testAtAspectWithReferencePCPerClause_pr138220() { runTest("@Aspect with reference pointcut in perclause");}
public void testJarChecking_pr137235_1() { runTest("directory with .jar extension: source and outjar"); }
public void testJarChecking_pr137235_2() { runTest("directory with .jar extension"); }
public void testMakePreMethodNPE_pr136393() { runTest("NPE in makePreMethod");}
// public void testFunkyGenericErrorWithITDs_pr126355_2() {
// runTest("bizarre generic error with itds - 2");
// // public class Pair<F,S> affected by pertarget aspect
// GenericsTests.verifyClassSignature(ajc,"Pair","<F:Ljava/lang/Object;S:Ljava/lang/Object;>Ljava/lang/Object;LIdempotentCache$ajcMightHaveAspect;;");
// }
// tests that can't be included for some reason
// Not valid whilst the ajc compiler forces debug on (ignores -g:none) - it will be green but is invalid, trust me
// public void testLongWindedMessages_pr129408() { runTest("long winded ataj messages");}
/////////////////////////////////////////
public static Test suite() {
return XMLBasedAjcTestCase.loadSuite(Ajc152Tests.class);
}
protected File getSpecFile() {
return new File("../tests/src/org/aspectj/systemtest/ajc152/ajc152.xml");
}
}
|
143,930 |
Bug 143930 create constructor ipe in same was as method ipes
| null |
resolved fixed
|
26a8a86
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-05-30T09:59:53Z | 2006-05-26T10:40:00Z |
weaver/src/org/aspectj/weaver/AsmRelationshipProvider.java
|
/* *******************************************************************
* Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC).
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* PARC initial implementation
* ******************************************************************/
package org.aspectj.weaver;
import java.util.Iterator;
import java.util.List;
import org.aspectj.apache.bcel.classfile.Field;
import org.aspectj.apache.bcel.classfile.Method;
import org.aspectj.apache.bcel.classfile.Utility;
import org.aspectj.apache.bcel.generic.Type;
import org.aspectj.asm.AsmManager;
import org.aspectj.asm.IHierarchy;
import org.aspectj.asm.IProgramElement;
import org.aspectj.asm.IRelationship;
import org.aspectj.asm.IRelationshipMap;
import org.aspectj.asm.internal.ProgramElement;
import org.aspectj.bridge.ISourceLocation;
import org.aspectj.bridge.SourceLocation;
import org.aspectj.weaver.bcel.BcelAdvice;
public class AsmRelationshipProvider {
protected static AsmRelationshipProvider INSTANCE = new AsmRelationshipProvider();
public static final String ADVISES = "advises";
public static final String ADVISED_BY = "advised by";
public static final String DECLARES_ON = "declares on";
public static final String DECLAREDY_BY = "declared by";
public static final String SOFTENS = "softens";
public static final String SOFTENED_BY = "softened by";
public static final String MATCHED_BY = "matched by";
public static final String MATCHES_DECLARE = "matches declare";
public static final String INTER_TYPE_DECLARES = "declared on";
public static final String INTER_TYPE_DECLARED_BY = "aspect declarations";
public static final String ANNOTATES = "annotates";
public static final String ANNOTATED_BY = "annotated by";
public void checkerMunger(IHierarchy model, Shadow shadow, Checker checker) {
if (!AsmManager.isCreatingModel()) return;
if (shadow.getSourceLocation() == null || checker.getSourceLocation() == null) return;
// Ensure a node for the target exists
IProgramElement targetNode = getNode(AsmManager.getDefault().getHierarchy(), shadow);
String sourceHandle = AsmManager.getDefault().getHandleProvider().createHandleIdentifier(
checker.getSourceLocation().getSourceFile(),
checker.getSourceLocation().getLine(),
checker.getSourceLocation().getColumn(),
checker.getSourceLocation().getOffset());
String targetHandle = AsmManager.getDefault().getHandleProvider().createHandleIdentifier(
shadow.getSourceLocation().getSourceFile(),
shadow.getSourceLocation().getLine(),
shadow.getSourceLocation().getColumn(),
shadow.getSourceLocation().getOffset());
IRelationshipMap mapper = AsmManager.getDefault().getRelationshipMap();
if (sourceHandle != null && targetHandle != null) {
IRelationship foreward = mapper.get(sourceHandle, IRelationship.Kind.DECLARE, MATCHED_BY,false,true);
foreward.addTarget(targetHandle);
// foreward.getTargets().add(targetHandle);
IRelationship back = mapper.get(targetHandle, IRelationship.Kind.DECLARE, MATCHES_DECLARE,false,true);
if (back != null && back.getTargets() != null) {
back.addTarget(sourceHandle);
//back.getTargets().add(sourceHandle);
}
}
}
// For ITDs
public void addRelationship(
ResolvedType onType,
ResolvedTypeMunger munger,
ResolvedType originatingAspect) {
if (!AsmManager.isCreatingModel()) return;
String sourceHandle = "";
if (munger.getSourceLocation()!=null && munger.getSourceLocation().getOffset()!=-1) {
sourceHandle = AsmManager.getDefault().getHandleProvider().createHandleIdentifier(
munger.getSourceLocation().getSourceFile(),
munger.getSourceLocation().getLine(),
munger.getSourceLocation().getColumn(),
munger.getSourceLocation().getOffset());
} else {
sourceHandle = AsmManager.getDefault().getHandleProvider().createHandleIdentifier(
originatingAspect.getSourceLocation().getSourceFile(),
originatingAspect.getSourceLocation().getLine(),
originatingAspect.getSourceLocation().getColumn(),
originatingAspect.getSourceLocation().getOffset());
}
if (originatingAspect.getSourceLocation() != null) {
String targetHandle = AsmManager.getDefault().getHandleProvider().createHandleIdentifier(
onType.getSourceLocation().getSourceFile(),
onType.getSourceLocation().getLine(),
onType.getSourceLocation().getColumn(),
onType.getSourceLocation().getOffset());
IRelationshipMap mapper = AsmManager.getDefault().getRelationshipMap();
if (sourceHandle != null && targetHandle != null) {
IRelationship foreward = mapper.get(sourceHandle, IRelationship.Kind.DECLARE_INTER_TYPE, INTER_TYPE_DECLARES,false,true);
foreward.addTarget(targetHandle);
// foreward.getTargets().add(targetHandle);
IRelationship back = mapper.get(targetHandle, IRelationship.Kind.DECLARE_INTER_TYPE, INTER_TYPE_DECLARED_BY,false,true);
back.addTarget(sourceHandle);
// back.getTargets().add(sourceHandle);
}
}
}
public void addDeclareParentsRelationship(ISourceLocation decp,ResolvedType targetType, List newParents) {
if (!AsmManager.isCreatingModel()) return;
String sourceHandle = AsmManager.getDefault().getHandleProvider().createHandleIdentifier(decp.getSourceFile(),decp.getLine(),decp.getColumn(),decp.getOffset());
IProgramElement ipe = AsmManager.getDefault().getHierarchy().findElementForHandle(sourceHandle);
String targetHandle = AsmManager.getDefault().getHandleProvider().createHandleIdentifier(
targetType.getSourceLocation().getSourceFile(),
targetType.getSourceLocation().getLine(),
targetType.getSourceLocation().getColumn(),
targetType.getSourceLocation().getOffset());
IRelationshipMap mapper = AsmManager.getDefault().getRelationshipMap();
if (sourceHandle != null && targetHandle != null) {
IRelationship foreward = mapper.get(sourceHandle, IRelationship.Kind.DECLARE_INTER_TYPE, INTER_TYPE_DECLARES,false,true);
foreward.addTarget(targetHandle);
IRelationship back = mapper.get(targetHandle, IRelationship.Kind.DECLARE_INTER_TYPE, INTER_TYPE_DECLARED_BY,false,true);
back.addTarget(sourceHandle);
}
}
/**
* Adds a declare annotation relationship, sometimes entities don't have source locs (methods/fields) so use other
* variants of this method if that is the case as they will look the entities up in the structure model.
*/
public void addDeclareAnnotationRelationship(ISourceLocation declareAnnotationLocation,ISourceLocation annotatedLocation) {
if (!AsmManager.isCreatingModel()) return;
String sourceHandle = AsmManager.getDefault().getHandleProvider().createHandleIdentifier(declareAnnotationLocation.getSourceFile(),declareAnnotationLocation.getLine(),
declareAnnotationLocation.getColumn(),declareAnnotationLocation.getOffset());
IProgramElement declareAnnotationPE = AsmManager.getDefault().getHierarchy().findElementForHandle(sourceHandle);
String targetHandle = AsmManager.getDefault().getHandleProvider().createHandleIdentifier(
annotatedLocation.getSourceFile(),
annotatedLocation.getLine(),
annotatedLocation.getColumn(),
annotatedLocation.getOffset());
IRelationshipMap mapper = AsmManager.getDefault().getRelationshipMap();
if (sourceHandle != null && targetHandle != null) {
IRelationship foreward = mapper.get(sourceHandle, IRelationship.Kind.DECLARE_INTER_TYPE, ANNOTATES,false,true);
foreward.addTarget(targetHandle);
IRelationship back = mapper.get(targetHandle, IRelationship.Kind.DECLARE_INTER_TYPE, ANNOTATED_BY,false,true);
back.addTarget(sourceHandle);
}
}
public void adviceMunger(IHierarchy model, Shadow shadow, ShadowMunger munger) {
if (!AsmManager.isCreatingModel()) return;
if (munger instanceof Advice) {
Advice advice = (Advice)munger;
if (advice.getKind().isPerEntry() || advice.getKind().isCflow()) {
// TODO: might want to show these in the future
return;
}
IRelationshipMap mapper = AsmManager.getDefault().getRelationshipMap();
IProgramElement targetNode = getNode(AsmManager.getDefault().getHierarchy(), shadow);
boolean runtimeTest = ((BcelAdvice)munger).hasDynamicTests();
// Work out extra info to inform interested UIs !
IProgramElement.ExtraInformation ai = new IProgramElement.ExtraInformation();
String adviceHandle = advice.getHandle();
// What kind of advice is it?
// TODO: Prob a better way to do this but I just want to
// get it into CVS !!!
AdviceKind ak = ((Advice)munger).getKind();
ai.setExtraAdviceInformation(ak.getName());
IProgramElement adviceElement = AsmManager.getDefault().getHierarchy().findElementForHandle(adviceHandle);
adviceElement.setExtraInfo(ai);
if (adviceHandle != null && targetNode != null) {
if (targetNode != null) {
String targetHandle = targetNode.getHandleIdentifier();
if (advice.getKind().equals(AdviceKind.Softener)) {
IRelationship foreward = mapper.get(adviceHandle, IRelationship.Kind.DECLARE_SOFT, SOFTENS,runtimeTest,true);
if (foreward != null) foreward.addTarget(targetHandle);//foreward.getTargets().add(targetHandle);
IRelationship back = mapper.get(targetHandle, IRelationship.Kind.DECLARE, SOFTENED_BY,runtimeTest,true);
if (back != null) back.addTarget(adviceHandle);//back.getTargets().add(adviceHandle);
} else {
IRelationship foreward = mapper.get(adviceHandle, IRelationship.Kind.ADVICE, ADVISES,runtimeTest,true);
if (foreward != null) foreward.addTarget(targetHandle);//foreward.getTargets().add(targetHandle);
IRelationship back = mapper.get(targetHandle, IRelationship.Kind.ADVICE, ADVISED_BY,runtimeTest,true);
if (back != null) back.addTarget(adviceHandle);//back.getTargets().add(adviceHandle);
}
}
}
}
}
protected IProgramElement getNode(IHierarchy model, Shadow shadow) {
Member enclosingMember = shadow.getEnclosingCodeSignature();
IProgramElement enclosingNode = lookupMember(model, enclosingMember);
if (enclosingNode == null) {
Lint.Kind err = shadow.getIWorld().getLint().shadowNotInStructure;
if (err.isEnabled()) {
err.signal(shadow.toString(), shadow.getSourceLocation());
}
return null;
}
Member shadowSig = shadow.getSignature();
if (!shadowSig.equals(enclosingMember)) {
IProgramElement bodyNode = findOrCreateCodeNode(enclosingNode, shadowSig, shadow);
return bodyNode;
} else {
return enclosingNode;
}
}
private boolean sourceLinesMatch(ISourceLocation loc1,ISourceLocation loc2) {
if (loc1.getLine()!=loc2.getLine()) return false;
return true;
}
private IProgramElement findOrCreateCodeNode(IProgramElement enclosingNode, Member shadowSig, Shadow shadow)
{
for (Iterator it = enclosingNode.getChildren().iterator(); it.hasNext(); ) {
IProgramElement node = (IProgramElement)it.next();
if (shadowSig.getName().equals(node.getBytecodeName()) &&
shadowSig.getSignature().equals(node.getBytecodeSignature()) &&
sourceLinesMatch(node.getSourceLocation(),shadow.getSourceLocation()))
{
return node;
}
}
ISourceLocation sl = shadow.getSourceLocation();
// XXX why not use shadow file? new SourceLocation(sl.getSourceFile(), sl.getLine()),
SourceLocation peLoc = new SourceLocation(enclosingNode.getSourceLocation().getSourceFile(),sl.getLine());
peLoc.setOffset(sl.getOffset());
IProgramElement peNode = new ProgramElement(
shadow.toString(),
IProgramElement.Kind.CODE,
peLoc,0,null,null);
peNode.setBytecodeName(shadowSig.getName());
peNode.setBytecodeSignature(shadowSig.getSignature());
enclosingNode.addChild(peNode);
return peNode;
}
protected IProgramElement lookupMember(IHierarchy model, Member member) {
UnresolvedType declaringType = member.getDeclaringType();
IProgramElement classNode =
model.findElementForType(declaringType.getPackageName(), declaringType.getClassName());
return findMemberInClass(classNode, member);
}
protected IProgramElement findMemberInClass(
IProgramElement classNode,
Member member)
{
if (classNode == null) return null; // XXX remove this check
for (Iterator it = classNode.getChildren().iterator(); it.hasNext(); ) {
IProgramElement node = (IProgramElement)it.next();
if (member.getName().equals(node.getBytecodeName()) &&
member.getSignature().equals(node.getBytecodeSignature()))
{
return node;
}
}
// if we can't find the member, we'll just put it in the class
return classNode;
}
// private static IProgramElement.Kind genShadowKind(Shadow shadow) {
// IProgramElement.Kind shadowKind;
// if (shadow.getKind() == Shadow.MethodCall
// || shadow.getKind() == Shadow.ConstructorCall
// || shadow.getKind() == Shadow.FieldGet
// || shadow.getKind() == Shadow.FieldSet
// || shadow.getKind() == Shadow.ExceptionHandler) {
// return IProgramElement.Kind.CODE;
//
// } else if (shadow.getKind() == Shadow.MethodExecution) {
// return IProgramElement.Kind.METHOD;
//
// } else if (shadow.getKind() == Shadow.ConstructorExecution) {
// return IProgramElement.Kind.CONSTRUCTOR;
//
// } else if (shadow.getKind() == Shadow.PreInitialization
// || shadow.getKind() == Shadow.Initialization) {
// return IProgramElement.Kind.CLASS;
//
// } else if (shadow.getKind() == Shadow.AdviceExecution) {
// return IProgramElement.Kind.ADVICE;
//
// } else {
// return IProgramElement.Kind.ERROR;
// }
// }
public static AsmRelationshipProvider getDefault() {
return INSTANCE;
}
/**
* Reset the instance of this class, intended for extensibility.
* This enables a subclass to become used as the default instance.
*/
public static void setDefault(AsmRelationshipProvider instance) {
INSTANCE = instance;
}
/**
* Add a relationship to the known set for a declare @method/@constructor construct.
* Locating the method is a messy (for messy read 'fragile') bit of code that could break at any moment
* but it's working for my simple testcase. Currently just fails silently if any of the lookup code
* doesn't find anything...
*/
public void addDeclareAnnotationRelationship(ISourceLocation sourceLocation, String typename,Method method) {
if (!AsmManager.isCreatingModel()) return;
String pkg = null;
String type = typename;
int packageSeparator = typename.lastIndexOf(".");
if (packageSeparator!=-1) {
pkg = typename.substring(0,packageSeparator);
type = typename.substring(packageSeparator+1);
}
IProgramElement typeElem = AsmManager.getDefault().getHierarchy().findElementForType(pkg,type);
if (typeElem == null) return;
StringBuffer parmString = new StringBuffer("(");
Type[] args = method.getArgumentTypes();
for (int i = 0; i < args.length; i++) {
Type type2 = args[i];
String s = Utility.signatureToString(type2.getSignature());
if (s.lastIndexOf(".")!=-1) s =s.substring(s.lastIndexOf(".")+1);
parmString.append(s);
if ((i+1)<args.length) parmString.append(",");
}
parmString.append(")");
IProgramElement methodElem = null;
if (method.getName().startsWith("<init>")) {
// its a ctor
methodElem = AsmManager.getDefault().getHierarchy().findElementForSignature(typeElem,IProgramElement.Kind.CONSTRUCTOR,type+parmString);
if (methodElem == null && args.length==0) methodElem = typeElem; // assume default ctor
} else {
// its a method
methodElem = AsmManager.getDefault().getHierarchy().findElementForSignature(typeElem,IProgramElement.Kind.METHOD,method.getName()+parmString);
}
if (methodElem == null) return;
try {
String sourceHandle =
AsmManager.getDefault().getHandleProvider().createHandleIdentifier(sourceLocation.getSourceFile(),sourceLocation.getLine(),
sourceLocation.getColumn(),sourceLocation.getOffset());
String targetHandle = methodElem.getHandleIdentifier();
IRelationshipMap mapper = AsmManager.getDefault().getRelationshipMap();
if (sourceHandle != null && targetHandle != null) {
IRelationship foreward = mapper.get(sourceHandle, IRelationship.Kind.DECLARE_INTER_TYPE, ANNOTATES,false,true);
foreward.addTarget(targetHandle);
IRelationship back = mapper.get(targetHandle, IRelationship.Kind.DECLARE_INTER_TYPE, ANNOTATED_BY,false,true);
back.addTarget(sourceHandle);
}
} catch (Throwable t) { // I'm worried about that code above, this will make sure we don't explode if it plays up
t.printStackTrace(); // I know I know .. but I don't want to lose it!
}
}
/**
* Add a relationship to the known set for a declare @field construct. Locating the field is trickier than
* it might seem since we have no line number info for it, we have to dig through the structure model under
* the fields' type in order to locate it. Currently just fails silently if any of the lookup code
* doesn't find anything...
*/
public void addDeclareAnnotationRelationship(ISourceLocation sourceLocation, String typename,Field field) {
if (!AsmManager.isCreatingModel()) return;
String pkg = null;
String type = typename;
int packageSeparator = typename.lastIndexOf(".");
if (packageSeparator!=-1) {
pkg = typename.substring(0,packageSeparator);
type = typename.substring(packageSeparator+1);
}
IProgramElement typeElem = AsmManager.getDefault().getHierarchy().findElementForType(pkg,type);
if (typeElem == null) return;
IProgramElement fieldElem = AsmManager.getDefault().getHierarchy().findElementForSignature(typeElem,IProgramElement.Kind.FIELD,field.getName());
if (fieldElem== null) return;
String sourceHandle =
AsmManager.getDefault().getHandleProvider().createHandleIdentifier(sourceLocation.getSourceFile(),sourceLocation.getLine(),
sourceLocation.getColumn(),sourceLocation.getOffset());
String targetHandle = fieldElem.getHandleIdentifier();
IRelationshipMap mapper = AsmManager.getDefault().getRelationshipMap();
if (sourceHandle != null && targetHandle != null) {
IRelationship foreward = mapper.get(sourceHandle, IRelationship.Kind.DECLARE_INTER_TYPE, ANNOTATES,false,true);
foreward.addTarget(targetHandle);
IRelationship back = mapper.get(targetHandle, IRelationship.Kind.DECLARE_INTER_TYPE, ANNOTATED_BY,false,true);
back.addTarget(sourceHandle);
}
}
}
|
144,717 |
Bug 144717 org.aspectj.weaver.BCException: Do not call nameToSignature with something that looks like a signature (descriptor): '[Ljava.lang.String;'
|
The exception below is produced when parsing a pointcut that uses an array type in args using the reflection world pointcut parser support. org.aspectj.weaver.BCException: Do not call nameToSignature with something that looks like a signature (descriptor): '[Ljava.lang.String;' at org.aspectj.weaver.UnresolvedType.nameToSignature(UnresolvedType.java:741) at org.aspectj.weaver.UnresolvedType.forName(UnresolvedType.java:311) at org.aspectj.weaver.reflect.Java15ReflectionBasedReferenceTypeDelegate.getDeclaredPointcuts(Java15ReflectionBasedReferenceTypeDelegate.java:260) at org.aspectj.weaver.ReferenceType.getDeclaredPointcuts(ReferenceType.java:526) at org.aspectj.weaver.ResolvedType$7.get(ResolvedType.java:468) at org.aspectj.weaver.Iterators$6.hasNext(Iterators.java:118) at org.aspectj.weaver.Iterators$5.hasNext(Iterators.java:128) at org.aspectj.weaver.ResolvedType.findPointcut(ResolvedType.java:479) at org.aspectj.weaver.patterns.ReferencePointcut.resolveBindings(ReferencePointcut.java:151) at org.aspectj.weaver.patterns.Pointcut.resolve(Pointcut.java:194) at org.aspectj.weaver.tools.PointcutParser.resolvePointcutExpression(PointcutParser.java:330) at org.aspectj.weaver.tools.PointcutParser.parsePointcutExpression(PointcutParser.java:308) at org.aspectj.weaver.tools.Java15PointcutExpressionTest.testArrayTypeInArgs(Java15PointcutExpressionTest.java:304) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:585) at junit.framework.TestCase.runTest(TestCase.java:154) at junit.framework.TestCase.runBare(TestCase.java:127) at junit.framework.TestResult$1.protect(TestResult.java:106) at junit.framework.TestResult.runProtected(TestResult.java:124) at junit.framework.TestResult.run(TestResult.java:109) at junit.framework.TestCase.run(TestCase.java:118) at junit.framework.TestSuite.runTest(TestSuite.java:208) at junit.framework.TestSuite.run(TestSuite.java:203) at junit.framework.TestSuite.runTest(TestSuite.java:208) at junit.framework.TestSuite.run(TestSuite.java:203) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:478) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:344) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:196)
|
resolved fixed
|
97cd71a
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-05-31T17:32:36Z | 2006-05-31T15:40:00Z |
weaver/src/org/aspectj/weaver/tools/PointcutParser.java
|
/*******************************************************************************
* Copyright (c) 2004 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.aspectj.weaver.tools;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Properties;
import java.util.Set;
import org.aspectj.bridge.IMessageHandler;
import org.aspectj.bridge.ISourceLocation;
import org.aspectj.bridge.SourceLocation;
import org.aspectj.weaver.IHasPosition;
import org.aspectj.weaver.ISourceContext;
import org.aspectj.weaver.IntMap;
import org.aspectj.weaver.ResolvedType;
import org.aspectj.weaver.Shadow;
import org.aspectj.weaver.UnresolvedType;
import org.aspectj.weaver.World;
import org.aspectj.weaver.bcel.AtAjAttributes;
import org.aspectj.weaver.internal.tools.PointcutExpressionImpl;
import org.aspectj.weaver.internal.tools.TypePatternMatcherImpl;
import org.aspectj.weaver.patterns.AndPointcut;
import org.aspectj.weaver.patterns.CflowPointcut;
import org.aspectj.weaver.patterns.FormalBinding;
import org.aspectj.weaver.patterns.IScope;
import org.aspectj.weaver.patterns.KindedPointcut;
import org.aspectj.weaver.patterns.NotPointcut;
import org.aspectj.weaver.patterns.OrPointcut;
import org.aspectj.weaver.patterns.ParserException;
import org.aspectj.weaver.patterns.PatternParser;
import org.aspectj.weaver.patterns.Pointcut;
import org.aspectj.weaver.patterns.SimpleScope;
import org.aspectj.weaver.patterns.ThisOrTargetAnnotationPointcut;
import org.aspectj.weaver.patterns.ThisOrTargetPointcut;
import org.aspectj.weaver.patterns.TypePattern;
import org.aspectj.weaver.reflect.PointcutParameterImpl;
import org.aspectj.weaver.reflect.ReflectionWorld;
/**
* A PointcutParser can be used to build PointcutExpressions for a
* user-defined subset of AspectJ's pointcut language
*/
public class PointcutParser {
private ReflectionWorld world;
private ClassLoader classLoader;
private Set supportedPrimitives;
private Set pointcutDesignators = new HashSet();
/**
* @return a Set containing every PointcutPrimitive except
* if, cflow, and cflowbelow (useful for passing to
* PointcutParser constructor).
*/
public static Set getAllSupportedPointcutPrimitives() {
Set primitives = new HashSet();
primitives.add(PointcutPrimitive.ADVICE_EXECUTION);
primitives.add(PointcutPrimitive.ARGS);
primitives.add(PointcutPrimitive.CALL);
primitives.add(PointcutPrimitive.EXECUTION);
primitives.add(PointcutPrimitive.GET);
primitives.add(PointcutPrimitive.HANDLER);
primitives.add(PointcutPrimitive.INITIALIZATION);
primitives.add(PointcutPrimitive.PRE_INITIALIZATION);
primitives.add(PointcutPrimitive.SET);
primitives.add(PointcutPrimitive.STATIC_INITIALIZATION);
primitives.add(PointcutPrimitive.TARGET);
primitives.add(PointcutPrimitive.THIS);
primitives.add(PointcutPrimitive.WITHIN);
primitives.add(PointcutPrimitive.WITHIN_CODE);
primitives.add(PointcutPrimitive.AT_ANNOTATION);
primitives.add(PointcutPrimitive.AT_THIS);
primitives.add(PointcutPrimitive.AT_TARGET);
primitives.add(PointcutPrimitive.AT_ARGS);
primitives.add(PointcutPrimitive.AT_WITHIN);
primitives.add(PointcutPrimitive.AT_WITHINCODE);
primitives.add(PointcutPrimitive.REFERENCE);
return primitives;
}
/**
* Returns a pointcut parser that can parse the full AspectJ pointcut
* language with the following exceptions:
* <ul>
* <li>The <code>if, cflow, and cflowbelow</code> pointcut designators are not supported
* <li>Pointcut expressions must be self-contained :- they cannot contain references
* to other named pointcuts
* <li>The pointcut expression must be anonymous with no formals allowed.
* </ul>
* <p>When resolving types in pointcut expressions, the context classloader is used to find types.</p>
*/
public static PointcutParser getPointcutParserSupportingAllPrimitivesAndUsingContextClassloaderForResolution() {
PointcutParser p = new PointcutParser();
p.setClassLoader(Thread.currentThread().getContextClassLoader());
return p;
}
/**
* Returns a pointcut parser that can parse pointcut expressions built
* from a user-defined subset of AspectJ's supported pointcut primitives.
* The following restrictions apply:
* <ul>
* <li>The <code>if, cflow, and cflowbelow</code> pointcut designators are not supported
* <li>Pointcut expressions must be self-contained :- they cannot contain references
* to other named pointcuts
* <li>The pointcut expression must be anonymous with no formals allowed.
* </ul>
* <p>When resolving types in pointcut expressions, the context classloader is used to find types.</p>
* @param supportedPointcutKinds a set of PointcutPrimitives this parser
* should support
* @throws UnsupportedOperationException if the set contains if, cflow, or
* cflow below
*/
public static PointcutParser getPointcutParserSupportingSpecifiedPrimitivesAndUsingContextClassloaderForResolution(Set supportedPointcutKinds) {
PointcutParser p = new PointcutParser(supportedPointcutKinds);
p.setClassLoader(Thread.currentThread().getContextClassLoader());
return p;
}
/**
* Returns a pointcut parser that can parse the full AspectJ pointcut
* language with the following exceptions:
* <ul>
* <li>The <code>if, cflow, and cflowbelow</code> pointcut designators are not supported
* <li>Pointcut expressions must be self-contained :- they cannot contain references
* to other named pointcuts
* <li>The pointcut expression must be anonymous with no formals allowed.
* </ul>
* <p>When resolving types in pointcut expressions, the given classloader is used to find types.</p>
*/
public static PointcutParser getPointcutParserSupportingAllPrimitivesAndUsingSpecifiedClassloaderForResolution(ClassLoader classLoader) {
PointcutParser p = new PointcutParser();
p.setClassLoader(classLoader);
return p;
}
/**
* Returns a pointcut parser that can parse pointcut expressions built
* from a user-defined subset of AspectJ's supported pointcut primitives.
* The following restrictions apply:
* <ul>
* <li>The <code>if, cflow, and cflowbelow</code> pointcut designators are not supported
* <li>Pointcut expressions must be self-contained :- they cannot contain references
* to other named pointcuts
* <li>The pointcut expression must be anonymous with no formals allowed.
* </ul>
* <p>When resolving types in pointcut expressions, the given classloader is used to find types.</p>
* @param supportedPointcutKinds a set of PointcutPrimitives this parser
* should support
* @throws UnsupportedOperationException if the set contains if, cflow, or
* cflow below
*/
public static PointcutParser getPointcutParserSupportingSpecifiedPrimitivesAndUsingSpecifiedClassLoaderForResolution(Set supportedPointcutKinds, ClassLoader classLoader) {
PointcutParser p = new PointcutParser(supportedPointcutKinds);
p.setClassLoader(classLoader);
return p;
}
/**
* Create a pointcut parser that can parse the full AspectJ pointcut
* language with the following exceptions:
* <ul>
* <li>The <code>if, cflow, and cflowbelow</code> pointcut designators are not supported
* <li>Pointcut expressions must be self-contained :- they cannot contain references
* to other named pointcuts
* <li>The pointcut expression must be anonymous with no formals allowed.
* </ul>
*/
protected PointcutParser() {
supportedPrimitives = getAllSupportedPointcutPrimitives();
setClassLoader(PointcutParser.class.getClassLoader());
}
/**
* Create a pointcut parser that can parse pointcut expressions built
* from a user-defined subset of AspectJ's supported pointcut primitives.
* The following restrictions apply:
* <ul>
* <li>The <code>if, cflow, and cflowbelow</code> pointcut designators are not supported
* <li>Pointcut expressions must be self-contained :- they cannot contain references
* to other named pointcuts
* <li>The pointcut expression must be anonymous with no formals allowed.
* </ul>
* @param supportedPointcutKinds a set of PointcutPrimitives this parser
* should support
* @throws UnsupportedOperationException if the set contains if, cflow, or
* cflow below
*/
private PointcutParser(Set/*<PointcutPrimitives>*/ supportedPointcutKinds) {
supportedPrimitives = supportedPointcutKinds;
for (Iterator iter = supportedPointcutKinds.iterator(); iter.hasNext();) {
PointcutPrimitive element = (PointcutPrimitive) iter.next();
if ((element == PointcutPrimitive.IF) ||
(element == PointcutPrimitive.CFLOW) ||
(element == PointcutPrimitive.CFLOW_BELOW)) {
throw new UnsupportedOperationException("Cannot handle if, cflow, and cflowbelow primitives");
}
}
setClassLoader(PointcutParser.class.getClassLoader());
}
protected void setWorld(ReflectionWorld aWorld) {
this.world = aWorld;
}
/**
* Set the classloader that this parser should use for
* type resolution.
* @param aLoader
*/
protected void setClassLoader(ClassLoader aLoader) {
this.classLoader = aLoader;
world = new ReflectionWorld(this.classLoader);
}
/**
* Set the lint properties for this parser from the
* given resource on the classpath.
* @param resourcePath path to a file containing aspectj
* lint properties
*/
public void setLintProperties(String resourcePath)throws IOException {
URL url = this.classLoader.getResource(resourcePath);
InputStream is = url.openStream();
Properties p = new Properties();
p.load(is);
setLintProperties(p);
}
/**
* Set the lint properties for this parser from the
* given properties set.
* @param properties
*/
public void setLintProperties(Properties properties) {
getWorld().getLint().setFromProperties(properties);
}
/**
* Register a new pointcut designator handler with this parser.
* This provides an extension mechansim for the integration of
* domain-specific pointcut designators with the AspectJ
* pointcut language.
* @param designatorHandler
*/
public void registerPointcutDesignatorHandler(PointcutDesignatorHandler designatorHandler) {
this.pointcutDesignators.add(designatorHandler);
}
/**
* Create a pointcut parameter of the given name and type.
* @param name
* @param type
* @return
*/
public PointcutParameter createPointcutParameter(String name, Class type) {
return new PointcutParameterImpl(name,type);
}
/**
* Parse the given pointcut expression.
* A global scope is assumed for resolving any type references, and the pointcut
* must contain no formals (variables to be bound).
* @throws UnsupportedPointcutPrimitiveException if the parser encounters a
* primitive pointcut expression of a kind not supported by this PointcutParser.
* @throws IllegalArgumentException if the expression is not a well-formed
* pointcut expression
*/
public PointcutExpression parsePointcutExpression(String expression)
throws UnsupportedPointcutPrimitiveException, IllegalArgumentException {
return parsePointcutExpression(expression,null,new PointcutParameter[0]);
}
/**
* Parse the given pointcut expression.
* The pointcut is resolved as if it had been declared inside the inScope class
* (this allows the pointcut to contain unqualified references to other pointcuts
* declared in the same type for example).
* The pointcut may contain zero or more formal parameters to be bound at matched
* join points.
* @throws UnsupportedPointcutPrimitiveException if the parser encounters a
* primitive pointcut expression of a kind not supported by this PointcutParser.
* @throws IllegalArgumentException if the expression is not a well-formed
* pointcut expression
*/
public PointcutExpression parsePointcutExpression(
String expression,
Class inScope,
PointcutParameter[] formalParameters)
throws UnsupportedPointcutPrimitiveException, IllegalArgumentException {
PointcutExpressionImpl pcExpr = null;
try {
Pointcut pc = resolvePointcutExpression(expression,inScope,formalParameters);
pc = concretizePointcutExpression(pc,inScope,formalParameters);
validateAgainstSupportedPrimitives(pc,expression); // again, because we have now followed any ref'd pcuts
pcExpr = new PointcutExpressionImpl(pc,expression,formalParameters,getWorld());
} catch (ParserException pEx) {
throw new IllegalArgumentException(buildUserMessageFromParserException(expression,pEx));
} catch (ReflectionWorld.ReflectionWorldException rwEx) {
throw new IllegalArgumentException(rwEx.getMessage());
}
return pcExpr;
}
protected Pointcut resolvePointcutExpression(
String expression,
Class inScope,
PointcutParameter[] formalParameters) {
try {
PatternParser parser = new PatternParser(expression);
parser.setPointcutDesignatorHandlers(pointcutDesignators, world);
Pointcut pc = parser.parsePointcut();
validateAgainstSupportedPrimitives(pc,expression);
IScope resolutionScope = buildResolutionScope((inScope == null ? Object.class : inScope),formalParameters);
pc = pc.resolve(resolutionScope);
return pc;
} catch (ParserException pEx) {
throw new IllegalArgumentException(buildUserMessageFromParserException(expression,pEx));
}
}
protected Pointcut concretizePointcutExpression(Pointcut pc, Class inScope, PointcutParameter[] formalParameters) {
ResolvedType declaringTypeForResolution = null;
if (inScope != null) {
declaringTypeForResolution = getWorld().resolve(inScope.getName());
} else {
declaringTypeForResolution = ResolvedType.OBJECT.resolve(getWorld());
}
IntMap arity = new IntMap(formalParameters.length);
for (int i = 0; i < formalParameters.length; i++) {
arity.put(i, i);
}
return pc.concretize(declaringTypeForResolution, declaringTypeForResolution, arity);
}
/**
* Parse the given aspectj type pattern, and return a
* matcher that can be used to match types using it.
* @param typePattern an aspectj type pattern
* @return a type pattern matcher that matches using the given
* pattern
* @throws IllegalArgumentException if the type pattern cannot
* be successfully parsed.
*/
public TypePatternMatcher parseTypePattern(String typePattern)
throws IllegalArgumentException {
try {
TypePattern tp = new PatternParser(typePattern).parseTypePattern();
tp.resolve(world);
return new TypePatternMatcherImpl(tp,world);
} catch (ParserException pEx) {
throw new IllegalArgumentException(buildUserMessageFromParserException(typePattern,pEx));
} catch (ReflectionWorld.ReflectionWorldException rwEx) {
throw new IllegalArgumentException(rwEx.getMessage());
}
}
private World getWorld() {
return world;
}
/* for testing */
Set getSupportedPrimitives() {
return supportedPrimitives;
}
/* for testing */
IMessageHandler setCustomMessageHandler(IMessageHandler aHandler) {
IMessageHandler current = getWorld().getMessageHandler();
getWorld().setMessageHandler(aHandler);
return current;
}
private IScope buildResolutionScope(Class inScope, PointcutParameter[] formalParameters) {
if (formalParameters == null) formalParameters = new PointcutParameter[0];
FormalBinding[] formalBindings = new FormalBinding[formalParameters.length];
for (int i = 0; i < formalBindings.length; i++) {
formalBindings[i] = new FormalBinding(UnresolvedType.forName(formalParameters[i].getType().getName()),formalParameters[i].getName(),i);
}
if (inScope == null) {
return new SimpleScope(getWorld(),formalBindings);
} else {
ResolvedType inType = getWorld().resolve(inScope.getName());
ISourceContext sourceContext = new ISourceContext() {
public ISourceLocation makeSourceLocation(IHasPosition position) {
return new SourceLocation(new File(""),0);
}
public ISourceLocation makeSourceLocation(int line, int offset) {
return new SourceLocation(new File(""),line);
}
public int getOffset() {
return 0;
}
public void tidy() {}
};
return new AtAjAttributes.BindingScope(inType,sourceContext,formalBindings);
}
}
private void validateAgainstSupportedPrimitives(Pointcut pc, String expression) {
switch(pc.getPointcutKind()) {
case Pointcut.AND:
validateAgainstSupportedPrimitives(((AndPointcut)pc).getLeft(),expression);
validateAgainstSupportedPrimitives(((AndPointcut)pc).getRight(),expression);
break;
case Pointcut.ARGS:
if (!supportedPrimitives.contains(PointcutPrimitive.ARGS))
throw new UnsupportedPointcutPrimitiveException(expression, PointcutPrimitive.ARGS);
break;
case Pointcut.CFLOW:
CflowPointcut cfp = (CflowPointcut) pc;
if (cfp.isCflowBelow()) {
throw new UnsupportedPointcutPrimitiveException(expression, PointcutPrimitive.CFLOW_BELOW);
} else {
throw new UnsupportedPointcutPrimitiveException(expression, PointcutPrimitive.CFLOW);
}
case Pointcut.HANDLER:
if (!supportedPrimitives.contains(PointcutPrimitive.HANDLER))
throw new UnsupportedPointcutPrimitiveException(expression, PointcutPrimitive.HANDLER);
break;
case Pointcut.IF:
case Pointcut.IF_FALSE:
case Pointcut.IF_TRUE:
throw new UnsupportedPointcutPrimitiveException(expression, PointcutPrimitive.IF);
case Pointcut.KINDED:
validateKindedPointcut(((KindedPointcut)pc),expression);
break;
case Pointcut.NOT:
validateAgainstSupportedPrimitives(((NotPointcut)pc).getNegatedPointcut(),expression);
break;
case Pointcut.OR:
validateAgainstSupportedPrimitives(((OrPointcut)pc).getLeft(),expression);
validateAgainstSupportedPrimitives(((OrPointcut)pc).getRight(),expression);
break;
case Pointcut.THIS_OR_TARGET:
boolean isThis = ((ThisOrTargetPointcut)pc).isThis();
if (isThis && !supportedPrimitives.contains(PointcutPrimitive.THIS)) {
throw new UnsupportedPointcutPrimitiveException(expression, PointcutPrimitive.THIS);
} else if (!supportedPrimitives.contains(PointcutPrimitive.TARGET)) {
throw new UnsupportedPointcutPrimitiveException(expression, PointcutPrimitive.TARGET);
}
break;
case Pointcut.WITHIN:
if (!supportedPrimitives.contains(PointcutPrimitive.WITHIN))
throw new UnsupportedPointcutPrimitiveException(expression, PointcutPrimitive.WITHIN);
break;
case Pointcut.WITHINCODE:
if (!supportedPrimitives.contains(PointcutPrimitive.WITHIN_CODE))
throw new UnsupportedPointcutPrimitiveException(expression, PointcutPrimitive.WITHIN_CODE);
break;
case Pointcut.ATTHIS_OR_TARGET:
isThis = ((ThisOrTargetAnnotationPointcut)pc).isThis();
if (isThis && !supportedPrimitives.contains(PointcutPrimitive.AT_THIS)) {
throw new UnsupportedPointcutPrimitiveException(expression, PointcutPrimitive.AT_THIS);
} else if (!supportedPrimitives.contains(PointcutPrimitive.AT_TARGET)) {
throw new UnsupportedPointcutPrimitiveException(expression, PointcutPrimitive.AT_TARGET);
}
break;
case Pointcut.ATARGS:
if (!supportedPrimitives.contains(PointcutPrimitive.AT_ARGS))
throw new UnsupportedPointcutPrimitiveException(expression, PointcutPrimitive.AT_ARGS);
break;
case Pointcut.ANNOTATION:
if (!supportedPrimitives.contains(PointcutPrimitive.AT_ANNOTATION))
throw new UnsupportedPointcutPrimitiveException(expression, PointcutPrimitive.AT_ANNOTATION);
break;
case Pointcut.ATWITHIN:
if (!supportedPrimitives.contains(PointcutPrimitive.AT_WITHIN))
throw new UnsupportedPointcutPrimitiveException(expression, PointcutPrimitive.AT_WITHIN);
break;
case Pointcut.ATWITHINCODE:
if (!supportedPrimitives.contains(PointcutPrimitive.AT_WITHINCODE))
throw new UnsupportedPointcutPrimitiveException(expression, PointcutPrimitive.AT_WITHINCODE);
break;
case Pointcut.REFERENCE:
if (!supportedPrimitives.contains(PointcutPrimitive.REFERENCE))
throw new UnsupportedPointcutPrimitiveException(expression, PointcutPrimitive.REFERENCE);
break;
case Pointcut.USER_EXTENSION:
// always ok...
break;
case Pointcut.NONE: // deliberate fall-through
default:
throw new IllegalArgumentException("Unknown pointcut kind: " + pc.getPointcutKind());
}
}
private void validateKindedPointcut(KindedPointcut pc, String expression) {
Shadow.Kind kind = pc.getKind();
if ((kind == Shadow.MethodCall) || (kind == Shadow.ConstructorCall)) {
if (!supportedPrimitives.contains(PointcutPrimitive.CALL))
throw new UnsupportedPointcutPrimitiveException(expression, PointcutPrimitive.CALL);
} else if ((kind == Shadow.MethodExecution) || (kind == Shadow.ConstructorExecution)) {
if (!supportedPrimitives.contains(PointcutPrimitive.EXECUTION))
throw new UnsupportedPointcutPrimitiveException(expression, PointcutPrimitive.EXECUTION);
} else if (kind == Shadow.AdviceExecution) {
if (!supportedPrimitives.contains(PointcutPrimitive.ADVICE_EXECUTION))
throw new UnsupportedPointcutPrimitiveException(expression, PointcutPrimitive.ADVICE_EXECUTION);
} else if (kind == Shadow.FieldGet) {
if (!supportedPrimitives.contains(PointcutPrimitive.GET))
throw new UnsupportedPointcutPrimitiveException(expression, PointcutPrimitive.GET);
} else if (kind == Shadow.FieldSet) {
if (!supportedPrimitives.contains(PointcutPrimitive.SET))
throw new UnsupportedPointcutPrimitiveException(expression, PointcutPrimitive.SET);
} else if (kind == Shadow.Initialization) {
if (!supportedPrimitives.contains(PointcutPrimitive.INITIALIZATION))
throw new UnsupportedPointcutPrimitiveException(expression, PointcutPrimitive.INITIALIZATION);
} else if (kind == Shadow.PreInitialization) {
if (!supportedPrimitives.contains(PointcutPrimitive.PRE_INITIALIZATION))
throw new UnsupportedPointcutPrimitiveException(expression, PointcutPrimitive.PRE_INITIALIZATION);
} else if (kind == Shadow.StaticInitialization) {
if (!supportedPrimitives.contains(PointcutPrimitive.STATIC_INITIALIZATION))
throw new UnsupportedPointcutPrimitiveException(expression, PointcutPrimitive.STATIC_INITIALIZATION);
}
}
private String buildUserMessageFromParserException(String pc, ParserException ex) {
StringBuffer msg = new StringBuffer();
msg.append("Pointcut is not well-formed: expecting '");
msg.append(ex.getMessage());
msg.append("'");
IHasPosition location = ex.getLocation();
msg.append(" at character position ");
msg.append(location.getStart());
msg.append("\n");
msg.append(pc);
msg.append("\n");
for (int i = 0; i < location.getStart(); i++) {
msg.append(" ");
}
for (int j=location.getStart(); j <= location.getEnd(); j++) {
msg.append("^");
}
msg.append("\n");
return msg.toString();
}
}
|
144,717 |
Bug 144717 org.aspectj.weaver.BCException: Do not call nameToSignature with something that looks like a signature (descriptor): '[Ljava.lang.String;'
|
The exception below is produced when parsing a pointcut that uses an array type in args using the reflection world pointcut parser support. org.aspectj.weaver.BCException: Do not call nameToSignature with something that looks like a signature (descriptor): '[Ljava.lang.String;' at org.aspectj.weaver.UnresolvedType.nameToSignature(UnresolvedType.java:741) at org.aspectj.weaver.UnresolvedType.forName(UnresolvedType.java:311) at org.aspectj.weaver.reflect.Java15ReflectionBasedReferenceTypeDelegate.getDeclaredPointcuts(Java15ReflectionBasedReferenceTypeDelegate.java:260) at org.aspectj.weaver.ReferenceType.getDeclaredPointcuts(ReferenceType.java:526) at org.aspectj.weaver.ResolvedType$7.get(ResolvedType.java:468) at org.aspectj.weaver.Iterators$6.hasNext(Iterators.java:118) at org.aspectj.weaver.Iterators$5.hasNext(Iterators.java:128) at org.aspectj.weaver.ResolvedType.findPointcut(ResolvedType.java:479) at org.aspectj.weaver.patterns.ReferencePointcut.resolveBindings(ReferencePointcut.java:151) at org.aspectj.weaver.patterns.Pointcut.resolve(Pointcut.java:194) at org.aspectj.weaver.tools.PointcutParser.resolvePointcutExpression(PointcutParser.java:330) at org.aspectj.weaver.tools.PointcutParser.parsePointcutExpression(PointcutParser.java:308) at org.aspectj.weaver.tools.Java15PointcutExpressionTest.testArrayTypeInArgs(Java15PointcutExpressionTest.java:304) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:585) at junit.framework.TestCase.runTest(TestCase.java:154) at junit.framework.TestCase.runBare(TestCase.java:127) at junit.framework.TestResult$1.protect(TestResult.java:106) at junit.framework.TestResult.runProtected(TestResult.java:124) at junit.framework.TestResult.run(TestResult.java:109) at junit.framework.TestCase.run(TestCase.java:118) at junit.framework.TestSuite.runTest(TestSuite.java:208) at junit.framework.TestSuite.run(TestSuite.java:203) at junit.framework.TestSuite.runTest(TestSuite.java:208) at junit.framework.TestSuite.run(TestSuite.java:203) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:478) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:344) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:196)
|
resolved fixed
|
97cd71a
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-05-31T17:32:36Z | 2006-05-31T15:40:00Z |
weaver5/java5-src/org/aspectj/weaver/reflect/Java15ReflectionBasedReferenceTypeDelegate.java
|
/* *******************************************************************
* Copyright (c) 2005 Contributors.
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Eclipse Public License v1.0
* which accompanies this distribution and is available at
* http://eclipse.org/legal/epl-v10.html
*
* Contributors:
* Adrian Colyer Initial implementation
* ******************************************************************/
package org.aspectj.weaver.reflect;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Type;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.AjType;
import org.aspectj.lang.reflect.AjTypeSystem;
import org.aspectj.lang.reflect.Pointcut;
import org.aspectj.weaver.AnnotationX;
import org.aspectj.weaver.ReferenceType;
import org.aspectj.weaver.ResolvedMember;
import org.aspectj.weaver.ResolvedPointcutDefinition;
import org.aspectj.weaver.ResolvedType;
import org.aspectj.weaver.TypeVariable;
import org.aspectj.weaver.TypeVariableReferenceType;
import org.aspectj.weaver.UnresolvedType;
import org.aspectj.weaver.World;
import org.aspectj.weaver.tools.PointcutParameter;
/**
* @author colyer
* Provides Java 5 behaviour in reflection based delegates (overriding
* 1.4 behaviour from superclass where appropriate)
*/
public class Java15ReflectionBasedReferenceTypeDelegate extends
ReflectionBasedReferenceTypeDelegate {
private AjType<?> myType;
private ResolvedType[] annotations;
private ResolvedMember[] pointcuts;
private ResolvedMember[] methods;
private ResolvedMember[] fields;
private TypeVariable[] typeVariables;
private ResolvedType superclass;
private ResolvedType[] superInterfaces;
private String genericSignature = null;
private JavaLangTypeToResolvedTypeConverter typeConverter;
private Java15AnnotationFinder annotationFinder = null;
private ArgNameFinder argNameFinder = null;
public Java15ReflectionBasedReferenceTypeDelegate() {}
@Override
public void initialize(ReferenceType aType, Class aClass, ClassLoader classLoader, World aWorld) {
super.initialize(aType, aClass, classLoader, aWorld);
myType = AjTypeSystem.getAjType(aClass);
annotationFinder = new Java15AnnotationFinder();
argNameFinder = annotationFinder;
annotationFinder.setClassLoader(classLoader);
this.typeConverter = new JavaLangTypeToResolvedTypeConverter(aWorld);
}
public ReferenceType buildGenericType() {
return (ReferenceType) UnresolvedType.forGenericTypeVariables(
getResolvedTypeX().getSignature(),
getTypeVariables()).resolve(getWorld());
}
public AnnotationX[] getAnnotations() {
// AMC - we seem not to need to implement this method...
//throw new UnsupportedOperationException("getAnnotations on Java15ReflectionBasedReferenceTypeDelegate is not implemented yet");
// FIXME is this the right implementation in the reflective case?
return super.getAnnotations();
}
public ResolvedType[] getAnnotationTypes() {
if (annotations == null) {
annotations = annotationFinder.getAnnotations(getBaseClass(), getWorld());
}
return annotations;
}
public boolean hasAnnotation(UnresolvedType ofType) {
ResolvedType[] myAnns = getAnnotationTypes();
ResolvedType toLookFor = ofType.resolve(getWorld());
for (int i = 0; i < myAnns.length; i++) {
if (myAnns[i] == toLookFor) return true;
}
return false;
}
// use the MAP to ensure that any aj-synthetic fields are filtered out
public ResolvedMember[] getDeclaredFields() {
if (fields == null) {
Field[] reflectFields = this.myType.getDeclaredFields();
this.fields = new ResolvedMember[reflectFields.length];
for (int i = 0; i < reflectFields.length; i++) {
this.fields[i] = createGenericFieldMember(reflectFields[i]);
}
}
return fields;
}
public String getDeclaredGenericSignature() {
if (this.genericSignature == null && isGeneric()) {
}
return genericSignature;
}
public ResolvedType[] getDeclaredInterfaces() {
if (superInterfaces == null) {
Type[] genericInterfaces = getBaseClass().getGenericInterfaces();
this.superInterfaces = typeConverter.fromTypes(genericInterfaces);
}
return superInterfaces;
}
// If the superclass is null, return Object - same as bcel does
public ResolvedType getSuperclass() {
if (superclass == null && getBaseClass()!=Object.class) {// superclass of Object is null
Type t = this.getBaseClass().getGenericSuperclass();
if (t!=null) superclass = typeConverter.fromType(t);
if (t==null) superclass = getWorld().resolve(UnresolvedType.OBJECT);
}
return superclass;
}
public TypeVariable[] getTypeVariables() {
TypeVariable[] workInProgressSetOfVariables = (TypeVariable[])getResolvedTypeX().getWorld().getTypeVariablesCurrentlyBeingProcessed(getBaseClass());
if (workInProgressSetOfVariables!=null) {
return workInProgressSetOfVariables;
}
if (this.typeVariables == null) {
java.lang.reflect.TypeVariable[] tVars = this.getBaseClass().getTypeParameters();
this.typeVariables = new TypeVariable[tVars.length];
// basic initialization
for (int i = 0; i < tVars.length; i++) {
typeVariables[i] = new TypeVariable(tVars[i].getName());
}
// stash it
this.getResolvedTypeX().getWorld().recordTypeVariablesCurrentlyBeingProcessed(getBaseClass(),typeVariables);
// now fill in the details...
for (int i = 0; i < tVars.length; i++) {
TypeVariableReferenceType tvrt = ((TypeVariableReferenceType) typeConverter.fromType(tVars[i]));
TypeVariable tv = tvrt.getTypeVariable();
typeVariables[i].setUpperBound(tv.getUpperBound());
typeVariables[i].setAdditionalInterfaceBounds(tv.getAdditionalInterfaceBounds());
typeVariables[i].setDeclaringElement(tv.getDeclaringElement());
typeVariables[i].setDeclaringElementKind(tv.getDeclaringElementKind());
typeVariables[i].setRank(tv.getRank());
typeVariables[i].setLowerBound(tv.getLowerBound());
}
this.getResolvedTypeX().getWorld().forgetTypeVariablesCurrentlyBeingProcessed(getBaseClass());
}
return this.typeVariables;
}
// overrides super method since by using the MAP we can filter out advice
// methods that really shouldn't be seen in this list
public ResolvedMember[] getDeclaredMethods() {
if (methods == null) {
Method[] reflectMethods = this.myType.getDeclaredMethods();
Constructor[] reflectCons = this.myType.getDeclaredConstructors();
this.methods = new ResolvedMember[reflectMethods.length + reflectCons.length];
for (int i = 0; i < reflectMethods.length; i++) {
this.methods[i] = createGenericMethodMember(reflectMethods[i]);
}
for (int i = 0; i < reflectCons.length; i++) {
this.methods[i + reflectMethods.length] =
createGenericConstructorMember(reflectCons[i]);
}
}
return methods;
}
/**
* Returns the generic type, regardless of the resolvedType we 'know about'
*/
public ResolvedType getGenericResolvedType() {
ResolvedType rt = getResolvedTypeX();
if (rt.isParameterizedType() || rt.isRawType()) return rt.getGenericType();
return rt;
}
private ResolvedMember createGenericMethodMember(Method forMethod) {
ReflectionBasedResolvedMemberImpl ret =
new ReflectionBasedResolvedMemberImpl(org.aspectj.weaver.Member.METHOD,
getGenericResolvedType(),
forMethod.getModifiers(),
typeConverter.fromType(forMethod.getReturnType()),
forMethod.getName(),
typeConverter.fromTypes(forMethod.getParameterTypes()),
typeConverter.fromTypes(forMethod.getExceptionTypes()),
forMethod
);
ret.setAnnotationFinder(this.annotationFinder);
ret.setGenericSignatureInformationProvider(new Java15GenericSignatureInformationProvider(this.getWorld()));
return ret;
}
private ResolvedMember createGenericConstructorMember(Constructor forConstructor) {
ReflectionBasedResolvedMemberImpl ret =
new ReflectionBasedResolvedMemberImpl(org.aspectj.weaver.Member.METHOD,
getGenericResolvedType(),
forConstructor.getModifiers(),
// to return what BCEL returns the return type is void
ResolvedType.VOID,//getGenericResolvedType(),
"<init>",
typeConverter.fromTypes(forConstructor.getParameterTypes()),
typeConverter.fromTypes(forConstructor.getExceptionTypes()),
forConstructor
);
ret.setAnnotationFinder(this.annotationFinder);
ret.setGenericSignatureInformationProvider(new Java15GenericSignatureInformationProvider(this.getWorld()));
return ret;
}
private ResolvedMember createGenericFieldMember(Field forField) {
ReflectionBasedResolvedMemberImpl ret =
new ReflectionBasedResolvedMemberImpl(
org.aspectj.weaver.Member.FIELD,
getGenericResolvedType(),
forField.getModifiers(),
typeConverter.fromType(forField.getType()),
forField.getName(),
new UnresolvedType[0],
forField);
ret.setAnnotationFinder(this.annotationFinder);
ret.setGenericSignatureInformationProvider(new Java15GenericSignatureInformationProvider(this.getWorld()));
return ret;
}
public ResolvedMember[] getDeclaredPointcuts() {
if (pointcuts == null) {
Pointcut[] pcs = this.myType.getDeclaredPointcuts();
pointcuts = new ResolvedMember[pcs.length];
InternalUseOnlyPointcutParser parser = null;
World world = getWorld();
if (world instanceof ReflectionWorld) {
parser = new InternalUseOnlyPointcutParser(classLoader,(ReflectionWorld)getWorld());
} else {
parser = new InternalUseOnlyPointcutParser(classLoader);
}
// phase 1, create legitimate entries in pointcuts[] before we attempt to resolve *any* of the pointcuts
// resolution can sometimes cause us to recurse, and this two stage process allows us to cope with that
for (int i = 0; i < pcs.length; i++) {
AjType<?>[] ptypes = pcs[i].getParameterTypes();
UnresolvedType[] weaverPTypes = new UnresolvedType[ptypes.length];
for (int j = 0; j < weaverPTypes.length; j++) {
weaverPTypes[j] = UnresolvedType.forName(ptypes[j].getName());
}
pointcuts[i] = new DeferredResolvedPointcutDefinition(getResolvedTypeX(),pcs[i].getModifiers(),pcs[i].getName(),weaverPTypes);
}
// phase 2, now go back round and resolve in-place all of the pointcuts
PointcutParameter[][] parameters = new PointcutParameter[pcs.length][];
for (int i = 0; i < pcs.length; i++) {
AjType<?>[] ptypes = pcs[i].getParameterTypes();
String[] pnames = pcs[i].getParameterNames();
if (pnames.length != ptypes.length) {
pnames = tryToDiscoverParameterNames(pcs[i]);
if (pnames == null || (pnames.length != ptypes.length)) {
throw new IllegalStateException("Required parameter names not available when parsing pointcut " + pcs[i].getName() + " in type " + getResolvedTypeX().getName());
}
}
parameters[i] = new PointcutParameter[ptypes.length];
for (int j = 0; j < parameters[i].length; j++) {
parameters[i][j] = parser.createPointcutParameter(pnames[j],ptypes[j].getJavaClass());
} String pcExpr = pcs[i].getPointcutExpression().toString();
org.aspectj.weaver.patterns.Pointcut pc = parser.resolvePointcutExpression(pcExpr,getBaseClass(),parameters[i]);
((ResolvedPointcutDefinition)pointcuts[i]).setParameterNames(pnames);
((ResolvedPointcutDefinition)pointcuts[i]).setPointcut(pc);
}
// phase 3, now concretize them all
for (int i = 0; i < pointcuts.length; i++) {
ResolvedPointcutDefinition rpd = (ResolvedPointcutDefinition) pointcuts[i];
rpd.setPointcut(parser.concretizePointcutExpression(rpd.getPointcut(), getBaseClass(), parameters[i]));
}
}
return pointcuts;
}
// for @AspectJ pointcuts compiled by javac only...
private String[] tryToDiscoverParameterNames(Pointcut pcut) {
Method[] ms = pcut.getDeclaringType().getJavaClass().getDeclaredMethods();
for(Method m : ms) {
if (m.getName().equals(pcut.getName())) {
return argNameFinder.getParameterNames(m);
}
}
return null;
}
public boolean isAnnotation() {
return getBaseClass().isAnnotation();
}
public boolean isAnnotationStyleAspect() {
return getBaseClass().isAnnotationPresent(Aspect.class);
}
public boolean isAnnotationWithRuntimeRetention() {
if (!isAnnotation()) return false;
if (getBaseClass().isAnnotationPresent(Retention.class)) {
Retention retention = (Retention) getBaseClass().getAnnotation(Retention.class);
RetentionPolicy policy = retention.value();
return policy == RetentionPolicy.RUNTIME;
} else {
return false;
}
}
public boolean isAspect() {
return this.myType.isAspect();
}
public boolean isEnum() {
return getBaseClass().isEnum();
}
public boolean isGeneric() {
//return false; // for now
return getBaseClass().getTypeParameters().length > 0;
}
@Override
public boolean isAnonymous() {
return this.myClass.isAnonymousClass();
}
}
|
144,717 |
Bug 144717 org.aspectj.weaver.BCException: Do not call nameToSignature with something that looks like a signature (descriptor): '[Ljava.lang.String;'
|
The exception below is produced when parsing a pointcut that uses an array type in args using the reflection world pointcut parser support. org.aspectj.weaver.BCException: Do not call nameToSignature with something that looks like a signature (descriptor): '[Ljava.lang.String;' at org.aspectj.weaver.UnresolvedType.nameToSignature(UnresolvedType.java:741) at org.aspectj.weaver.UnresolvedType.forName(UnresolvedType.java:311) at org.aspectj.weaver.reflect.Java15ReflectionBasedReferenceTypeDelegate.getDeclaredPointcuts(Java15ReflectionBasedReferenceTypeDelegate.java:260) at org.aspectj.weaver.ReferenceType.getDeclaredPointcuts(ReferenceType.java:526) at org.aspectj.weaver.ResolvedType$7.get(ResolvedType.java:468) at org.aspectj.weaver.Iterators$6.hasNext(Iterators.java:118) at org.aspectj.weaver.Iterators$5.hasNext(Iterators.java:128) at org.aspectj.weaver.ResolvedType.findPointcut(ResolvedType.java:479) at org.aspectj.weaver.patterns.ReferencePointcut.resolveBindings(ReferencePointcut.java:151) at org.aspectj.weaver.patterns.Pointcut.resolve(Pointcut.java:194) at org.aspectj.weaver.tools.PointcutParser.resolvePointcutExpression(PointcutParser.java:330) at org.aspectj.weaver.tools.PointcutParser.parsePointcutExpression(PointcutParser.java:308) at org.aspectj.weaver.tools.Java15PointcutExpressionTest.testArrayTypeInArgs(Java15PointcutExpressionTest.java:304) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:585) at junit.framework.TestCase.runTest(TestCase.java:154) at junit.framework.TestCase.runBare(TestCase.java:127) at junit.framework.TestResult$1.protect(TestResult.java:106) at junit.framework.TestResult.runProtected(TestResult.java:124) at junit.framework.TestResult.run(TestResult.java:109) at junit.framework.TestCase.run(TestCase.java:118) at junit.framework.TestSuite.runTest(TestSuite.java:208) at junit.framework.TestSuite.run(TestSuite.java:203) at junit.framework.TestSuite.runTest(TestSuite.java:208) at junit.framework.TestSuite.run(TestSuite.java:203) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:478) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:344) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:196)
|
resolved fixed
|
97cd71a
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-05-31T17:32:36Z | 2006-05-31T15:40:00Z |
weaver5/java5-testsrc/org/aspectj/weaver/tools/Java15PointcutExpressionTest.java
|
/* *******************************************************************
* Copyright (c) 2005 Contributors.
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Eclipse Public License v1.0
* which accompanies this distribution and is available at
* http://eclipse.org/legal/epl-v10.html
*
* Contributors:
* Adrian Colyer Initial implementation
* ******************************************************************/
package org.aspectj.weaver.tools;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.reflect.Method;
import java.util.List;
import org.aspectj.lang.annotation.Pointcut;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
/**
* @author colyer
*
*/
public class Java15PointcutExpressionTest extends TestCase {
public static Test suite() {
TestSuite suite = new TestSuite("Java15PointcutExpressionTest");
suite.addTestSuite(Java15PointcutExpressionTest.class);
return suite;
}
private PointcutParser parser;
private Method a;
private Method b;
private Method c;
private Method d;
public void testAtThis() {
PointcutExpression atThis = parser.parsePointcutExpression("@this(org.aspectj.weaver.tools.Java15PointcutExpressionTest.MyAnnotation)");
ShadowMatch sMatch1 = atThis.matchesMethodExecution(a);
ShadowMatch sMatch2 = atThis.matchesMethodExecution(b);
assertTrue("maybe matches A",sMatch1.maybeMatches());
assertTrue("maybe matches B",sMatch2.maybeMatches());
JoinPointMatch jp1 = sMatch1.matchesJoinPoint(new A(), new A(), new Object[0]);
assertFalse("does not match",jp1.matches());
JoinPointMatch jp2 = sMatch2.matchesJoinPoint(new B(), new B(), new Object[0]);
assertTrue("matches",jp2.matches());
}
public void testAtTarget() {
PointcutExpression atTarget = parser.parsePointcutExpression("@target(org.aspectj.weaver.tools.Java15PointcutExpressionTest.MyAnnotation)");
ShadowMatch sMatch1 = atTarget.matchesMethodExecution(a);
ShadowMatch sMatch2 = atTarget.matchesMethodExecution(b);
assertTrue("maybe matches A",sMatch1.maybeMatches());
assertTrue("maybe matches B",sMatch2.maybeMatches());
JoinPointMatch jp1 = sMatch1.matchesJoinPoint(new A(), new A(), new Object[0]);
assertFalse("does not match",jp1.matches());
JoinPointMatch jp2 = sMatch2.matchesJoinPoint(new B(), new B(), new Object[0]);
assertTrue("matches",jp2.matches());
}
public void testAtThisWithBinding() {
PointcutParameter param = parser.createPointcutParameter("a",MyAnnotation.class);
B myB = new B();
MyAnnotation bAnnotation = B.class.getAnnotation(MyAnnotation.class);
PointcutExpression atThis = parser.parsePointcutExpression("@this(a)",A.class,new PointcutParameter[] {param});
ShadowMatch sMatch1 = atThis.matchesMethodExecution(a);
ShadowMatch sMatch2 = atThis.matchesMethodExecution(b);
assertTrue("maybe matches A",sMatch1.maybeMatches());
assertTrue("maybe matches B",sMatch2.maybeMatches());
JoinPointMatch jp1 = sMatch1.matchesJoinPoint(new A(), new A(), new Object[0]);
assertFalse("does not match",jp1.matches());
JoinPointMatch jp2 = sMatch2.matchesJoinPoint(myB, myB, new Object[0]);
assertTrue("matches",jp2.matches());
assertEquals(1,jp2.getParameterBindings().length);
assertEquals("should be myB's annotation",bAnnotation,jp2.getParameterBindings()[0].getBinding());
}
public void testAtTargetWithBinding() {
PointcutParameter param = parser.createPointcutParameter("a",MyAnnotation.class);
B myB = new B();
MyAnnotation bAnnotation = B.class.getAnnotation(MyAnnotation.class);
PointcutExpression atThis = parser.parsePointcutExpression("@target(a)",A.class,new PointcutParameter[] {param});
ShadowMatch sMatch1 = atThis.matchesMethodExecution(a);
ShadowMatch sMatch2 = atThis.matchesMethodExecution(b);
assertTrue("maybe matches A",sMatch1.maybeMatches());
assertTrue("maybe matches B",sMatch2.maybeMatches());
JoinPointMatch jp1 = sMatch1.matchesJoinPoint(new A(), new A(), new Object[0]);
assertFalse("does not match",jp1.matches());
JoinPointMatch jp2 = sMatch2.matchesJoinPoint(myB, myB, new Object[0]);
assertTrue("matches",jp2.matches());
assertEquals(1,jp2.getParameterBindings().length);
assertEquals("should be myB's annotation",bAnnotation,jp2.getParameterBindings()[0].getBinding());
}
public void testAtArgs() {
PointcutExpression atArgs = parser.parsePointcutExpression("@args(..,org.aspectj.weaver.tools.Java15PointcutExpressionTest.MyAnnotation)");
ShadowMatch sMatch1 = atArgs.matchesMethodExecution(a);
ShadowMatch sMatch2 = atArgs.matchesMethodExecution(c);
assertTrue("never matches A",sMatch1.neverMatches());
assertTrue("maybe matches C",sMatch2.maybeMatches());
JoinPointMatch jp2 = sMatch2.matchesJoinPoint(new B(), new B(), new Object[]{new A(),new B()});
assertTrue("matches",jp2.matches());
atArgs = parser.parsePointcutExpression("@args(org.aspectj.weaver.tools.Java15PointcutExpressionTest.MyAnnotation,org.aspectj.weaver.tools.Java15PointcutExpressionTest.MyAnnotation)");
sMatch1 = atArgs.matchesMethodExecution(a);
sMatch2 = atArgs.matchesMethodExecution(c);
assertTrue("never matches A",sMatch1.neverMatches());
assertTrue("maybe matches C",sMatch2.maybeMatches());
JoinPointMatch jp1 = sMatch2.matchesJoinPoint(new A(), new A(), new Object[] {new A(), new B()});
assertFalse("does not match",jp1.matches());
jp2 = sMatch2.matchesJoinPoint(new B(), new B(), new Object[] {new B(),new B()});
assertTrue("matches",jp2.matches());
}
public void testAtArgs2() {
PointcutExpression atArgs = parser.parsePointcutExpression("@args(*, org.aspectj.weaver.tools.Java15PointcutExpressionTest.MyAnnotation)");
ShadowMatch sMatch1 = atArgs.matchesMethodExecution(c);
ShadowMatch sMatch2 = atArgs.matchesMethodExecution(d);
assertTrue("maybe matches c",sMatch1.maybeMatches());
assertTrue("maybe matches d",sMatch2.maybeMatches());
JoinPointMatch jp1 = sMatch1.matchesJoinPoint(new B(), new B(), new Object[] {new A(), new B()});
assertTrue("matches",jp1.matches());
JoinPointMatch jp2 = sMatch2.matchesJoinPoint(new B(), new B(), new Object[] {new A(),new A()});
assertFalse("does not match",jp2.matches());
}
public void testAtArgsWithBinding() {
PointcutParameter p1 = parser.createPointcutParameter("a",MyAnnotation.class);
PointcutParameter p2 = parser.createPointcutParameter("b", MyAnnotation.class);
PointcutExpression atArgs = parser.parsePointcutExpression("@args(..,a)",A.class,new PointcutParameter[] {p1});
ShadowMatch sMatch2 = atArgs.matchesMethodExecution(c);
assertTrue("maybe matches C",sMatch2.maybeMatches());
JoinPointMatch jp2 = sMatch2.matchesJoinPoint(new B(), new B(), new Object[]{new A(),new B()});
assertTrue("matches",jp2.matches());
assertEquals(1,jp2.getParameterBindings().length);
MyAnnotation bAnnotation = B.class.getAnnotation(MyAnnotation.class);
assertEquals("annotation on B",bAnnotation,jp2.getParameterBindings()[0].getBinding());
atArgs = parser.parsePointcutExpression("@args(a,b)",A.class,new PointcutParameter[] {p1,p2});
sMatch2 = atArgs.matchesMethodExecution(c);
assertTrue("maybe matches C",sMatch2.maybeMatches());
jp2 = sMatch2.matchesJoinPoint(new B(), new B(), new Object[] {new B(),new B()});
assertTrue("matches",jp2.matches());
assertEquals(2,jp2.getParameterBindings().length);
assertEquals("annotation on B",bAnnotation,jp2.getParameterBindings()[0].getBinding());
assertEquals("annotation on B",bAnnotation,jp2.getParameterBindings()[1].getBinding());
}
public void testAtWithin() {
PointcutExpression atWithin = parser.parsePointcutExpression("@within(org.aspectj.weaver.tools.Java15PointcutExpressionTest.MyAnnotation)");
ShadowMatch sMatch1 = atWithin.matchesMethodExecution(a);
ShadowMatch sMatch2 = atWithin.matchesMethodExecution(b);
assertTrue("does not match a",sMatch1.neverMatches());
assertTrue("matches b",sMatch2.alwaysMatches());
}
public void testAtWithinWithBinding() {
PointcutParameter p1 = parser.createPointcutParameter("x",MyAnnotation.class);
PointcutExpression atWithin = parser.parsePointcutExpression("@within(x)",B.class,new PointcutParameter[] {p1});
ShadowMatch sMatch1 = atWithin.matchesMethodExecution(a);
ShadowMatch sMatch2 = atWithin.matchesMethodExecution(b);
assertTrue("does not match a",sMatch1.neverMatches());
assertTrue("matches b",sMatch2.alwaysMatches());
JoinPointMatch jpm = sMatch2.matchesJoinPoint(new B(), new B(), new Object[0]);
assertTrue(jpm.matches());
assertEquals(1,jpm.getParameterBindings().length);
MyAnnotation bAnnotation = B.class.getAnnotation(MyAnnotation.class);
assertEquals("annotation on B",bAnnotation,jpm.getParameterBindings()[0].getBinding());
}
public void testAtWithinCode() {
PointcutExpression atWithinCode = parser.parsePointcutExpression("@withincode(org.aspectj.weaver.tools.Java15PointcutExpressionTest.MyAnnotation)");
ShadowMatch sMatch1 = atWithinCode.matchesMethodCall(a,b);
ShadowMatch sMatch2 = atWithinCode.matchesMethodCall(a,a);
assertTrue("does not match from b",sMatch1.neverMatches());
assertTrue("matches from a",sMatch2.alwaysMatches());
}
public void testAtWithinCodeWithBinding() {
PointcutParameter p1 = parser.createPointcutParameter("x",MyAnnotation.class);
PointcutExpression atWithinCode = parser.parsePointcutExpression("@withincode(x)",A.class,new PointcutParameter[] {p1});
ShadowMatch sMatch2 = atWithinCode.matchesMethodCall(a,a);
assertTrue("matches from a",sMatch2.alwaysMatches());
JoinPointMatch jpm = sMatch2.matchesJoinPoint(new A(), new A(), new Object[0]);
assertEquals(1,jpm.getParameterBindings().length);
MyAnnotation annOna = a.getAnnotation(MyAnnotation.class);
assertEquals("MyAnnotation on a",annOna,jpm.getParameterBindings()[0].getBinding());
}
public void testAtAnnotation() {
PointcutExpression atAnnotation = parser.parsePointcutExpression("@annotation(org.aspectj.weaver.tools.Java15PointcutExpressionTest.MyAnnotation)");
ShadowMatch sMatch1 = atAnnotation.matchesMethodCall(b,a);
ShadowMatch sMatch2 = atAnnotation.matchesMethodCall(a,a);
assertTrue("does not match call to b",sMatch1.neverMatches());
assertTrue("matches call to a",sMatch2.alwaysMatches());
}
public void testAtAnnotationWithBinding() {
PointcutParameter p1 = parser.createPointcutParameter("x",MyAnnotation.class);
PointcutExpression atAnnotation = parser.parsePointcutExpression("@annotation(x)",A.class,new PointcutParameter[] {p1});
ShadowMatch sMatch2 = atAnnotation.matchesMethodCall(a,a);
assertTrue("matches call to a",sMatch2.alwaysMatches());
JoinPointMatch jpm = sMatch2.matchesJoinPoint(new A(), new A(), new Object[0]);
assertTrue(jpm.matches());
assertEquals(1,jpm.getParameterBindings().length);
MyAnnotation annOna = a.getAnnotation(MyAnnotation.class);
assertEquals("MyAnnotation on a",annOna,jpm.getParameterBindings()[0].getBinding());
}
public void testReferencePointcutNoParams() {
PointcutExpression pc = parser.parsePointcutExpression("foo()",C.class,new PointcutParameter[0]);
ShadowMatch sMatch1 = pc.matchesMethodCall(a,b);
ShadowMatch sMatch2 = pc.matchesMethodExecution(a);
assertTrue("no match on call",sMatch1.neverMatches());
assertTrue("match on execution",sMatch2.alwaysMatches());
pc = parser.parsePointcutExpression("org.aspectj.weaver.tools.Java15PointcutExpressionTest.C.foo()");
sMatch1 = pc.matchesMethodCall(a,b);
sMatch2 = pc.matchesMethodExecution(a);
assertTrue("no match on call",sMatch1.neverMatches());
assertTrue("match on execution",sMatch2.alwaysMatches());
}
public void testReferencePointcutParams() {
PointcutParameter p1 = parser.createPointcutParameter("x",A.class);
PointcutExpression pc = parser.parsePointcutExpression("goo(x)",C.class,new PointcutParameter[] {p1});
ShadowMatch sMatch1 = pc.matchesMethodCall(a,b);
ShadowMatch sMatch2 = pc.matchesMethodExecution(a);
assertTrue("no match on call",sMatch1.neverMatches());
assertTrue("match on execution",sMatch2.maybeMatches());
A anA = new A();
JoinPointMatch jpm = sMatch2.matchesJoinPoint(anA, new A(), new Object[0]);
assertTrue(jpm.matches());
assertEquals("should be bound to anA",anA,jpm.getParameterBindings()[0].getBinding());
}
public void testExecutionWithClassFileRetentionAnnotation() {
PointcutExpression pc1 = parser.parsePointcutExpression("execution(@org.aspectj.weaver.tools.Java15PointcutExpressionTest.MyAnnotation * *(..))");
PointcutExpression pc2 = parser.parsePointcutExpression("execution(@org.aspectj.weaver.tools.Java15PointcutExpressionTest.MyClassFileRetentionAnnotation * *(..))");
ShadowMatch sMatch = pc1.matchesMethodExecution(a);
assertTrue("matches",sMatch.alwaysMatches());
sMatch = pc2.matchesMethodExecution(a);
assertTrue("no match",sMatch.neverMatches());
sMatch = pc1.matchesMethodExecution(b);
assertTrue("no match",sMatch.neverMatches());
sMatch = pc2.matchesMethodExecution(b);
assertTrue("matches",sMatch.alwaysMatches());
}
public void testGenericMethodSignatures() throws Exception{
PointcutExpression ex = parser.parsePointcutExpression("execution(* set*(java.util.List<org.aspectj.weaver.tools.Java15PointcutExpressionTest.C>))");
Method m = TestBean.class.getMethod("setFriends",List.class);
ShadowMatch sm = ex.matchesMethodExecution(m);
assertTrue("should match",sm.alwaysMatches());
}
public void testAnnotationInExecution() throws Exception {
PointcutExpression ex = parser.parsePointcutExpression("execution(@(org.springframework..*) * *(..))");
}
public void testVarArgsMatching() throws Exception {
PointcutExpression ex = parser.parsePointcutExpression("execution(* *(String...))");
Method usesVarArgs = D.class.getMethod("varArgs",String[].class);
Method noVarArgs = D.class.getMethod("nonVarArgs", String[].class);
ShadowMatch sm1 = ex.matchesMethodExecution(usesVarArgs);
assertTrue("should match",sm1.alwaysMatches());
ShadowMatch sm2 = ex.matchesMethodExecution(noVarArgs);
assertFalse("should not match",sm2.alwaysMatches());
}
public void testJavaLangMatching() throws Exception {
PointcutExpression ex = parser.parsePointcutExpression("@within(java.lang.Deprecated)");
Method foo = GoldenOldie.class.getMethod("foo");
ShadowMatch sm1 = ex.matchesMethodExecution(foo);
assertTrue("should match",sm1.alwaysMatches());
}
public void testReferencePCsInSameType() throws Exception {
PointcutExpression ex = parser.parsePointcutExpression("org.aspectj.weaver.tools.Java15PointcutExpressionTest.NamedPointcutResolution.c()",NamedPointcutResolution.class,new PointcutParameter[0]);
ShadowMatch sm = ex.matchesMethodExecution(a);
assertTrue("should match",sm.alwaysMatches());
sm = ex.matchesMethodExecution(b);
assertTrue("does not match",sm.neverMatches());
}
public void testReferencePCsInOtherType() throws Exception {
PointcutExpression ex = parser.parsePointcutExpression("org.aspectj.weaver.tools.Java15PointcutExpressionTest.ExternalReferrer.d()",ExternalReferrer.class,new PointcutParameter[0]);
ShadowMatch sm = ex.matchesMethodExecution(a);
assertTrue("should match",sm.alwaysMatches());
sm = ex.matchesMethodExecution(b);
assertTrue("does not match",sm.neverMatches());
}
protected void setUp() throws Exception {
super.setUp();
parser = PointcutParser.getPointcutParserSupportingAllPrimitivesAndUsingSpecifiedClassloaderForResolution(this.getClass().getClassLoader());
a = A.class.getMethod("a");
b = B.class.getMethod("b");
c = B.class.getMethod("c",new Class[] {A.class,B.class});
d = B.class.getMethod("d",new Class[] {A.class,A.class});
}
@Retention(RetentionPolicy.RUNTIME)
private @interface MyAnnotation {}
private @interface MyClassFileRetentionAnnotation {}
private static class A {
@MyAnnotation public void a() {}
}
@MyAnnotation
private static class B {
@MyClassFileRetentionAnnotation public void b() {}
public void c(A anA, B aB) {}
public void d(A anA, A anotherA) {}
}
private static class C {
@Pointcut("execution(* *(..))")
public void foo() {}
@Pointcut(value="execution(* *(..)) && this(x)", argNames="x")
public void goo(A x) {}
}
private static class D {
public void nonVarArgs(String[] strings) {};
public void varArgs(String... strings) {};
}
static class TestBean {
public void setFriends(List<C> friends) {}
}
@Deprecated
static class GoldenOldie {
public void foo() {}
}
private static class NamedPointcutResolution {
@Pointcut("execution(* *(..))")
public void a() {}
@Pointcut("this(org.aspectj.weaver.tools.Java15PointcutExpressionTest.A)")
public void b() {}
@Pointcut("a() && b()")
public void c() {}
}
private static class ExternalReferrer {
@Pointcut("org.aspectj.weaver.tools.Java15PointcutExpressionTest.NamedPointcutResolution.a() && " +
"org.aspectj.weaver.tools.Java15PointcutExpressionTest.NamedPointcutResolution.b())")
public void d() {}
}
}
|
120,739 |
Bug 120739 LTW Optimization: Disable World if it has No Aspects
|
This optimization disables weaving for a ClassLoader where there are no aspects defined. This is actually useful if you have aspect exclusions that exclude all the aspects defined in a parent class loader. It is also helpful in the trivial/rare case where there is an aop.xml definition with no aspect definitions.
|
resolved fixed
|
4513e92
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-06-01T16:30:21Z | 2005-12-13T21:40:00Z |
loadtime/src/org/aspectj/weaver/loadtime/ClassLoaderWeavingAdaptor.java
|
/*******************************************************************************
* Copyright (c) 2005 Contributors.
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Eclipse Public License v1.0
* which accompanies this distribution and is available at
* http://eclipse.org/legal/epl-v10.html
*
* Contributors:
* Alexandre Vasseur initial implementation
* David Knibb weaving context enhancments
*******************************************************************************/
package org.aspectj.weaver.loadtime;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.URL;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Properties;
import java.util.StringTokenizer;
import org.aspectj.asm.IRelationship;
import org.aspectj.bridge.AbortException;
import org.aspectj.bridge.ISourceLocation;
import org.aspectj.util.LangUtil;
import org.aspectj.weaver.ICrossReferenceHandler;
import org.aspectj.weaver.Lint;
import org.aspectj.weaver.ResolvedType;
import org.aspectj.weaver.UnresolvedType;
import org.aspectj.weaver.World;
import org.aspectj.weaver.Lint.Kind;
import org.aspectj.weaver.bcel.BcelObjectType;
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.patterns.PatternParser;
import org.aspectj.weaver.patterns.TypePattern;
import org.aspectj.weaver.tools.GeneratedClassHandler;
import org.aspectj.weaver.tools.WeavingAdaptor;
/**
* @author <a href="mailto:alex AT gnilux DOT com">Alexandre Vasseur</a>
*/
public class ClassLoaderWeavingAdaptor extends WeavingAdaptor {
private final static String AOP_XML = "META-INF/aop.xml";
private List m_dumpTypePattern = new ArrayList();
private boolean m_dumpBefore = false;
private List m_includeTypePattern = new ArrayList();
private List m_excludeTypePattern = new ArrayList();
private List m_includeStartsWith = new ArrayList();
private List m_excludeStartsWith = new ArrayList();
private List m_aspectExcludeTypePattern = new ArrayList();
private List m_aspectExcludeStartsWith = new ArrayList();
private List m_aspectIncludeTypePattern = new ArrayList();
private List m_aspectIncludeStartsWith = new ArrayList();
private StringBuffer namespace;
private IWeavingContext weavingContext;
public ClassLoaderWeavingAdaptor(final ClassLoader loader, IWeavingContext wContext) {
this.weavingContext = wContext;
}
protected void initialize(final ClassLoader loader, IWeavingContext wContext) {
//super(null);// at this stage we don't have yet a generatedClassHandler to define to the VM the closures
this.generatedClassHandler = new GeneratedClassHandler() {
/**
* Callback when we need to define a Closure in the JVM
*
* @param name
* @param bytes
*/
public void acceptClass(String name, byte[] bytes) {
try {
if (shouldDump(name.replace('/', '.'), false)) {
dump(name, bytes, false);
}
} catch (Throwable throwable) {
throwable.printStackTrace();
}
defineClass(loader, name, bytes);// could be done lazily using the hook
}
};
if(wContext==null){
weavingContext = new DefaultWeavingContext(loader);
}else{
weavingContext = wContext ;
}
List definitions = parseDefinitions(loader);
if (!enabled) {
return;
}
bcelWorld = new BcelWorld(
loader, getMessageHandler(), new ICrossReferenceHandler() {
public void addCrossReference(ISourceLocation from, ISourceLocation to, IRelationship.Kind kind, boolean runtimeTest) {
;// for tools only
}
}
);
// //TODO this AJ code will call
// //org.aspectj.apache.bcel.Repository.setRepository(this);
// //ie set some static things
// //==> bogus as Bcel is expected to be
// org.aspectj.apache.bcel.Repository.setRepository(new ClassLoaderRepository(loader));
weaver = new BcelWeaver(bcelWorld);
// register the definitions
registerDefinitions(weaver, loader, definitions);
//bcelWorld.setResolutionLoader(loader.getParent());//(ClassLoader)null);//
// after adding aspects
weaver.prepareForWeave();
}
/**
* Load and cache the aop.xml/properties according to the classloader visibility rules
*
* @param weaver
* @param loader
*/
private List parseDefinitions(final ClassLoader loader) {
List definitions = new ArrayList();
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 (ClassLoader.getSystemClassLoader().equals(loader)) {
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);
StringTokenizer st = new StringTokenizer(resourcePath,";");
while(st.hasMoreTokens()){
Enumeration xmls = weavingContext.getResources(st.nextToken());
// System.out.println("? registerDefinitions: found-aop.xml=" + xmls.hasMoreElements() + ", loader=" + loader);
while (xmls.hasMoreElements()) {
URL xml = (URL) xmls.nextElement();
info("using " + xml.getFile());
definitions.add(DocumentParser.parse(xml));
}
}
if (definitions.isEmpty()) {
enabled = false;// will allow very fast skip in shouldWeave()
info("no configuration found. Disabling weaver for class loader " + getClassLoaderName(loader));
}
} catch (Exception e) {
enabled = false;// will allow very fast skip in shouldWeave()
warn("parse definitions failed",e);
}
return definitions;
}
private void registerDefinitions(final BcelWeaver weaver, final ClassLoader loader, List definitions) {
try {
registerOptions(weaver, loader, definitions);
registerAspectExclude(weaver, loader, definitions);
registerAspectInclude(weaver, loader, definitions);
registerAspects(weaver, loader, definitions);
registerIncludeExclude(weaver, loader, definitions);
registerDump(weaver, loader, definitions);
} catch (Exception e) {
enabled = false;// will allow very fast skip in shouldWeave()
warn("register definition failed",(e instanceof AbortException)?null:e);
}
}
private String getClassLoaderName (ClassLoader loader) {
return weavingContext.getClassLoaderName();
}
/**
* Configure the weaver according to the option directives
* TODO av - don't know if it is that good to reuse, since we only allow a small subset of options in LTW
*
* @param weaver
* @param loader
* @param definitions
*/
private void registerOptions(final BcelWeaver weaver, final ClassLoader loader, final List definitions) {
StringBuffer allOptions = new StringBuffer();
for (Iterator iterator = definitions.iterator(); iterator.hasNext();) {
Definition definition = (Definition) iterator.next();
allOptions.append(definition.getWeaverOptions()).append(' ');
}
Options.WeaverOption weaverOption = Options.parse(allOptions.toString(), loader, 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.setOptionalJoinpoints(weaverOption.optionalJoinpoints);
world.setPinpointMode(weaverOption.pinpoint);
weaver.setReweavableMode(weaverOption.notReWeavable);
world.setXnoInline(weaverOption.noInline);
// AMC - autodetect as per line below, needed for AtAjLTWTests.testLTWUnweavable
world.setBehaveInJava5Way(LangUtil.is15VMOrGreater());
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);
}
}
//TODO proceedOnError option
}
private void registerAspectExclude(final BcelWeaver weaver, final ClassLoader loader, final List definitions) {
String fastMatchInfo = null;
for (Iterator iterator = definitions.iterator(); iterator.hasNext();) {
Definition definition = (Definition) iterator.next();
for (Iterator iterator1 = definition.getAspectExcludePatterns().iterator(); iterator1.hasNext();) {
String exclude = (String) iterator1.next();
TypePattern excludePattern = new PatternParser(exclude).parseTypePattern();
m_aspectExcludeTypePattern.add(excludePattern);
fastMatchInfo = looksLikeStartsWith(exclude);
if (fastMatchInfo != null) {
m_aspectExcludeStartsWith.add(fastMatchInfo);
}
}
}
}
private void registerAspectInclude(final BcelWeaver weaver, final ClassLoader loader, final List definitions) {
String fastMatchInfo = null;
for (Iterator iterator = definitions.iterator(); iterator.hasNext();) {
Definition definition = (Definition) iterator.next();
for (Iterator iterator1 = definition.getAspectIncludePatterns().iterator(); iterator1.hasNext();) {
String include = (String) iterator1.next();
TypePattern includePattern = new PatternParser(include).parseTypePattern();
m_aspectIncludeTypePattern.add(includePattern);
fastMatchInfo = looksLikeStartsWith(include);
if (fastMatchInfo != null) {
m_aspectIncludeStartsWith.add(fastMatchInfo);
}
}
}
}
protected void lint (String name, String[] infos) {
Lint lint = bcelWorld.getLint();
Kind kind = lint.getLintKind(name);
kind.signal(infos,null,null);
}
/**
* Register the aspect, following include / exclude rules
*
* @param weaver
* @param loader
* @param definitions
*/
private void registerAspects(final BcelWeaver weaver, final ClassLoader loader, final List definitions) {
//TODO: the exclude aspect allow to exclude aspect defined upper in the CL hierarchy - is it what we want ??
// if not, review the getResource so that we track which resource is defined by which CL
//iterate aspectClassNames
//exclude if in any of the exclude list
for (Iterator iterator = definitions.iterator(); iterator.hasNext();) {
Definition definition = (Definition) iterator.next();
for (Iterator aspects = definition.getAspectClassNames().iterator(); aspects.hasNext();) {
String aspectClassName = (String) aspects.next();
if (acceptAspect(aspectClassName)) {
info("register aspect " + aspectClassName);
/*ResolvedType aspect = */weaver.addLibraryAspect(aspectClassName);
//generate key for SC
if(namespace==null){
namespace=new StringBuffer(aspectClassName);
}else{
namespace = namespace.append(";"+aspectClassName);
}
}
else {
// warn("aspect excluded: " + aspectClassName);
lint("aspectExcludedByConfiguration", new String[] { aspectClassName, getClassLoaderName(loader) });
}
}
}
//iterate concreteAspects
//exclude if in any of the exclude list - note that the user defined name matters for that to happen
for (Iterator iterator = definitions.iterator(); iterator.hasNext();) {
Definition definition = (Definition) iterator.next();
for (Iterator aspects = definition.getConcreteAspects().iterator(); aspects.hasNext();) {
Definition.ConcreteAspect concreteAspect = (Definition.ConcreteAspect) aspects.next();
if (acceptAspect(concreteAspect.name)) {
ConcreteAspectCodeGen gen = new ConcreteAspectCodeGen(concreteAspect, weaver.getWorld());
if (!gen.validate()) {
error("Concrete-aspect '"+concreteAspect.name+"' could not be registered");
break;
}
this.generatedClassHandler.acceptClass(
concreteAspect.name,
gen.getBytes()
);
/*ResolvedType aspect = */weaver.addLibraryAspect(concreteAspect.name);
//generate key for SC
if(namespace==null){
namespace=new StringBuffer(concreteAspect.name);
}else{
namespace = namespace.append(";"+concreteAspect.name);
}
}
}
}
}
/**
* Register the include / exclude filters
* We duplicate simple patterns in startWith filters that will allow faster matching without ResolvedType
*
* @param weaver
* @param loader
* @param definitions
*/
private void registerIncludeExclude(final BcelWeaver weaver, final ClassLoader loader, final List definitions) {
String fastMatchInfo = null;
for (Iterator iterator = definitions.iterator(); iterator.hasNext();) {
Definition definition = (Definition) iterator.next();
for (Iterator iterator1 = definition.getIncludePatterns().iterator(); iterator1.hasNext();) {
String include = (String) iterator1.next();
TypePattern includePattern = new PatternParser(include).parseTypePattern();
m_includeTypePattern.add(includePattern);
fastMatchInfo = looksLikeStartsWith(include);
if (fastMatchInfo != null) {
m_includeStartsWith.add(fastMatchInfo);
}
}
for (Iterator iterator1 = definition.getExcludePatterns().iterator(); iterator1.hasNext();) {
String exclude = (String) iterator1.next();
TypePattern excludePattern = new PatternParser(exclude).parseTypePattern();
m_excludeTypePattern.add(excludePattern);
fastMatchInfo = looksLikeStartsWith(exclude);
if (fastMatchInfo != null) {
m_excludeStartsWith.add(fastMatchInfo);
}
}
}
}
/**
* Checks if the type pattern can be handled as a startswith check
*
* TODO AV - enhance to support "char.sss" ie FQN direclty (match iff equals)
* we could also add support for "*..*charss" endsWith style?
*
* @param typePattern
* @return null if not possible, or the startWith sequence to test against
*/
private String looksLikeStartsWith(String typePattern) {
if (typePattern.indexOf('@') >= 0
|| typePattern.indexOf('+') >= 0
|| typePattern.indexOf(' ') >= 0
|| typePattern.charAt(typePattern.length()-1) != '*') {
return null;
}
// now must looks like with "charsss..*" or "cha.rss..*" etc
// note that "*" and "*..*" won't be fast matched
// and that "charsss.*" will not neither
int length = typePattern.length();
if (typePattern.endsWith("..*") && length > 3) {
if (typePattern.indexOf("..") == length-3 // no ".." before last sequence
&& typePattern.indexOf('*') == length-1) { // no "*" before last sequence
return typePattern.substring(0, length-2).replace('$', '.');
// ie "charsss." or "char.rss." etc
}
}
return null;
}
/**
* Register the dump filter
*
* @param weaver
* @param loader
* @param definitions
*/
private void registerDump(final BcelWeaver weaver, final ClassLoader loader, final List definitions) {
for (Iterator iterator = definitions.iterator(); iterator.hasNext();) {
Definition definition = (Definition) iterator.next();
for (Iterator iterator1 = definition.getDumpPatterns().iterator(); iterator1.hasNext();) {
String dump = (String) iterator1.next();
TypePattern pattern = new PatternParser(dump).parseTypePattern();
m_dumpTypePattern.add(pattern);
}
if (definition.shouldDumpBefore()) {
m_dumpBefore = true;
}
}
}
protected boolean accept(String className, byte[] bytes) {
// avoid ResolvedType if not needed
if (m_excludeTypePattern.isEmpty() && m_includeTypePattern.isEmpty()) {
return true;
}
// still try to avoid ResolvedType if we have simple patterns
String fastClassName = className.replace('/', '.').replace('$', '.');
for (int i = 0; i < m_excludeStartsWith.size(); i++) {
if (fastClassName.startsWith((String)m_excludeStartsWith.get(i))) {
return false;
}
}
/*
* Bug 120363
* If we have an exclude pattern that cannot be matched using "starts with"
* then we cannot fast accept
*/
if (m_excludeTypePattern.isEmpty()) {
boolean fastAccept = false;//defaults to false if no fast include
for (int i = 0; i < m_includeStartsWith.size(); i++) {
fastAccept = fastClassName.startsWith((String)m_includeStartsWith.get(i));
if (fastAccept) {
break;
}
}
}
// needs further analysis
// TODO AV - needs refactoring
// during LTW this calling resolve at that stage is BAD as we do have the bytecode from the classloader hook
// but still go thru resolve that will do a getResourcesAsStream on disk
// this is also problematic for jit stub which are not on disk - as often underlying infra
// does returns null or some other info for getResourceAsStream (f.e. WLS 9 CR248491)
// Instead I parse the given bytecode. But this also means it will be parsed again in
// new WeavingClassFileProvider() from WeavingAdaptor.getWovenBytes()...
BcelObjectType bct = ((BcelWorld)weaver.getWorld()).addSourceObjectType(Utility.makeJavaClass(null, bytes));
ResolvedType classInfo = bct.getResolvedTypeX();//BAD: weaver.getWorld().resolve(UnresolvedType.forName(className), true);
//exclude are "AND"ed
for (Iterator iterator = m_excludeTypePattern.iterator(); iterator.hasNext();) {
TypePattern typePattern = (TypePattern) iterator.next();
if (typePattern.matchesStatically(classInfo)) {
// exclude match - skip
return false;
}
}
//include are "OR"ed
boolean accept = true;//defaults to true if no include
for (Iterator iterator = m_includeTypePattern.iterator(); iterator.hasNext();) {
TypePattern typePattern = (TypePattern) iterator.next();
accept = typePattern.matchesStatically(classInfo);
if (accept) {
break;
}
// goes on if this include did not match ("OR"ed)
}
return accept;
}
//FIXME we don't use include/exclude of others aop.xml
//this can be nice but very dangerous as well to change that
private boolean acceptAspect(String aspectClassName) {
// avoid ResolvedType if not needed
if (m_aspectExcludeTypePattern.isEmpty() && m_aspectIncludeTypePattern.isEmpty()) {
return true;
}
// still try to avoid ResolvedType if we have simple patterns
// EXCLUDE: if one match then reject
String fastClassName = aspectClassName.replace('/', '.').replace('.', '$');
for (int i = 0; i < m_aspectExcludeStartsWith.size(); i++) {
if (fastClassName.startsWith((String)m_aspectExcludeStartsWith.get(i))) {
return false;
}
}
//INCLUDE: if one match then accept
for (int i = 0; i < m_aspectIncludeStartsWith.size(); i++) {
if (fastClassName.startsWith((String)m_aspectIncludeStartsWith.get(i))) {
return true;
}
}
// needs further analysis
ResolvedType classInfo = weaver.getWorld().resolve(UnresolvedType.forName(aspectClassName), true);
//exclude are "AND"ed
for (Iterator iterator = m_aspectExcludeTypePattern.iterator(); iterator.hasNext();) {
TypePattern typePattern = (TypePattern) iterator.next();
if (typePattern.matchesStatically(classInfo)) {
// exclude match - skip
return false;
}
}
//include are "OR"ed
boolean accept = true;//defaults to true if no include
for (Iterator iterator = m_aspectIncludeTypePattern.iterator(); iterator.hasNext();) {
TypePattern typePattern = (TypePattern) iterator.next();
accept = typePattern.matchesStatically(classInfo);
if (accept) {
break;
}
// goes on if this include did not match ("OR"ed)
}
return accept;
}
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;
}
/*
* shared classes methods
*/
/**
* @return Returns the key.
*/
public String getNamespace() {
if(namespace==null) return "";
else return new String(namespace);
}
/**
* Check to see if any classes are stored in the generated classes cache.
* Then flush the cache if it is not empty
* @return true if a class has been generated and is stored in the cache
*/
public boolean generatedClassesExist(){
if(generatedClasses.size()>0) {
return true;
}
return false;
}
/**
* Flush the generated classes cache
*/
public void flushGeneratedClasses(){
generatedClasses = new HashMap();
}
private void defineClass(ClassLoader loader, String name, byte[] bytes) {
info("generating class '" + name + "'");
try {
//TODO av protection domain, and optimize
Method defineClass = ClassLoader.class.getDeclaredMethod(
"defineClass", new Class[] { String.class,
bytes.getClass(), int.class, int.class });
defineClass.setAccessible(true);
defineClass.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);
}
}
}
|
120,739 |
Bug 120739 LTW Optimization: Disable World if it has No Aspects
|
This optimization disables weaving for a ClassLoader where there are no aspects defined. This is actually useful if you have aspect exclusions that exclude all the aspects defined in a parent class loader. It is also helpful in the trivial/rare case where there is an aop.xml definition with no aspect definitions.
|
resolved fixed
|
4513e92
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-06-01T16:30:21Z | 2005-12-13T21:40:00Z |
tests/java5/ataspectj/ataspectj/ltwreweavable/EmptyAtAspect.java
| |
120,739 |
Bug 120739 LTW Optimization: Disable World if it has No Aspects
|
This optimization disables weaving for a ClassLoader where there are no aspects defined. This is actually useful if you have aspect exclusions that exclude all the aspects defined in a parent class loader. It is also helpful in the trivial/rare case where there is an aop.xml definition with no aspect definitions.
|
resolved fixed
|
4513e92
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-06-01T16:30:21Z | 2005-12-13T21:40:00Z |
tests/src/org/aspectj/systemtest/ajc152/Ajc152Tests.java
|
/*******************************************************************************
* Copyright (c) 2006 IBM
* 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.ajc152;
import java.io.File;
import java.util.List;
import junit.framework.Test;
//import org.aspectj.systemtest.ajc150.GenericsTests;
import org.aspectj.asm.AsmManager;
import org.aspectj.asm.IHierarchy;
import org.aspectj.asm.IProgramElement;
import org.aspectj.asm.internal.Relationship;
import org.aspectj.testing.XMLBasedAjcTestCase;
public class Ajc152Tests extends org.aspectj.testing.XMLBasedAjcTestCase {
public void testNoUnnecessaryDeclarationOfThrownExcp_pr129282_1() {runTest("no unnecessary declaration of thrown exception warning - 1");}
public void testNoUnnecessaryDeclarationOfThrownExcp_pr129282_2() {runTest("no unnecessary declaration of thrown exception warning - 2");}
public void testNoUnnecessaryDeclarationOfThrownExcp_pr129282_3() {runTest("no unnecessary declaration of thrown exception warning - 3");}
public void testNoUnnecessaryDeclarationOfThrownExcp_pr129282_4() {runTest("no unnecessary declaration of thrown exception warning - 4");}
public void testNoUnnecessaryDeclarationOfThrownExcp_pr129282_5() {runTest("no unnecessary declaration of thrown exception warning - 5");}
public void testNoUnnecessaryDeclarationOfThrownExcp_pr129282_6() {runTest("no unnecessary declaration of thrown exception warning - 6");}
public void testNoUnnecessaryDeclarationOfThrownExcp_pr129282_7() {runTest("no unnecessary declaration of thrown exception warning - 7");}
public void testNoUnnecessaryDeclarationOfThrownExcp_pr129282_8() {runTest("no unnecessary declaration of thrown exception warning - 8");}
public void testNoUnnecessaryDeclarationOfThrownExcp_pr129282_9() {runTest("no unnecessary declaration of thrown exception warning - 9");}
public void testNoUnnecessaryDeclarationOfThrownExcp_pr129282_10() {runTest("no unnecessary declaration of thrown exception warning - 10");}
public void testAtAJVerificationError_pr144602() { runTest("atAJ perthis aspect verification error");}
public void testLTWAndGeneratingSUID_pr144465() { runTest("ltw with serialversionUID creation"); }
public void testAspects14PerSingleton_pr122253() { runTest("aspects14 - persingleton");}
public void testAspects14PerCflow_pr122253() { runTest("aspects14 - percflow");}
public void testAspects14PerThis_pr122253() { runTest("aspects14 - perthis");}
public void testAspects14PerTypeWithin_pr122253() { runTest("aspects14 - pertypewithin");}
public void testFunkyGenericErrorWithITDs_pr126355() { runTest("bizarre generic error with itds");}
public void testConcretizingAbstractMethods_pr142466() { runTest("aop.xml aspect inheriting but not concretizing abstract method");}
public void testConcretizingAbstractMethods_pr142466_2() { runTest("aop.xml aspect inheriting but not concretizing abstract method - 2");}
public void testComplexGenericDecl_pr137568() { runTest("complicated generics declaration");}
public void testItdOnInnerTypeOfGenericType_pr132349() { runTest("ITD on inner type of generic type");}
public void testItdOnInnerTypeOfGenericType_pr132349_2() { runTest("ITD on inner type of generic type - 2");}
public void testItdOnInnerTypeOfGenericType_pr132349_3() { runTest("ITD on inner type of generic type - 3");}
// public void testCovarianceAndDecp_pr128443_1() { runTest("covariance and decp - 1"); }
public void testLTWGeneratedAspectAbstractMethod_pr125480() { runTest("aop.xml aspect inheriting abstract method ");}
public void testLTWGeneratedAspectAbstractMethod_pr125480_2() { runTest("aop.xml aspect inheriting abstract method - code style");}
//public void testSuperITDExplosion_pr134425() { runTest("super ITDs");}
//public void testMisbehavingDeclareAnnotation_pr135865() { runTest("misbehaving declare annotation");}
//public void testMisbehavingDeclareAnnotation_pr135865_2() { runTest("misbehaving declare annotation - 2");}
public void testCompletelyBrokenAopConcretization_pr142165_1() { runTest("broken concretization");}
public void testCompletelyBrokenAopConcretization_pr142165_2() { runTest("broken concretization - 2");}
public void testCompletelyBrokenAopConcretization_pr142165_3() { runTest("broken concretization - 3");}
public void testVerifyErrorLTW_pr135068() { runTest("ltw verifyerror");}
public void testVerifyErrorLTW_pr135068_2() { runTest("ltw verifyerror - 2");}
public void testVerifyErrorLTW_pr135068_3() { runTest("ltw verifyerror - 3");}
public void testVerifyErrorLTW_pr135068_4() { runTest("ltw verifyerror - 4");}
public void testVerifyErrorForComplexCflow_pr136026() { runTest("verifyerror");}
public void testVerifyErrorForComplexCflow_pr136026_2() { runTest("verifyerror - 2");}
public void testAnnotationsAndGenericsBCException_pr129704() { runTest("annotations and generics leading to BCException");}
public void testMethodTooBigAfterWeaving_pr138384() { runTest("method too big"); }
public void testNotAtWithincode_pr138158_1() { runTest("not at withincode - 1");}
public void testNotAtWithincode_pr138158_2() { runTest("not at withincode - 2");}
public void testNotAtWithincode_pr138158_3() { runTest("not at within - 3");}
public void testNpeOnDup_pr138143() { runTest("npe on duplicate method with ataj");}
public void testPointcutsAndGenerics_pr137496_1() { runTest("pointcuts and generics - B");}
public void testPointcutsAndGenerics_pr137496_2() { runTest("pointcuts and generics - D");}
public void testPointcutsAndGenerics_pr137496_3() { runTest("pointcuts and generics - E");}
public void testPointcutsAndGenerics_pr137496_4() { runTest("pointcuts and generics - F");}
public void testPointcutsAndGenerics_pr137496_5() { runTest("pointcuts and generics - G");}
public void testPointcutsAndGenerics_pr137496_6() { runTest("pointcuts and generics - H");}
public void testAspectLibrariesAndASM_pr135001() { runTest("aspect libraries and asm");}
public void testStackOverflow_pr136258() { runTest("stack overflow");}
public void testIncorrectOverridesEvaluation13() { runTest("incorrect overrides evaluation - 1.3"); }
public void testIncorrectOverridesEvaluation15() { runTest("incorrect overrides evaluation - 1.5"); }
public void testAtWithinCodeBug_pr138798() { runTest("atWithinCodeBug"); }
public void testReferencePCutInDeclareWarning_pr138215() { runTest("Reference pointcut fails inside @DeclareWarning");}
public void testReferencePCutInPerClause_pr138219() { runTest("Can't use a FQ Reference pointcut in any pointcut expression referenced by a per-clause");}
public void testReferencePCutInPerClause_pr130722() { runTest("FQ Reference pointcut from perclause ref pc"); }
public void testDoubleAnnotationMatching_pr138223() { runTest("Double at annotation matching (no binding)");}
public void testSuperCallsInAtAspectJAdvice_pr139749() { runTest("Super calls in @AspectJ advice");}
public void testNoClassCastExceptionWithPerThis_pr138286() { runTest("No ClassCastException with perThis");}
public void testDeclareAtMethodRelationship_pr143924() {
//AsmManager.setReporting("c:/debug.txt",true,true,true,true);
runTest("declare @method relationship");
IHierarchy top = AsmManager.getDefault().getHierarchy();
// get the IProgramElements corresponding to the different code entries
IProgramElement decam = top.findElementForLabel(top.getRoot(),
IProgramElement.Kind.DECLARE_ANNOTATION_AT_METHOD,
"declare @method: * debit(..) : @Secured(role = \"supervisor\")");
assertNotNull("Couldn't find 'declare @method' element in the tree",decam);
IProgramElement method = top.findElementForLabel(top.getRoot(),
IProgramElement.Kind.METHOD,"debit(java.lang.String,long)");
assertNotNull("Couldn't find the 'debit(String,long)' method element in the tree",method);
List matches = AsmManager.getDefault().getRelationshipMap().get(decam);
assertNotNull("'declare @method' should have some relationships but does not",matches);
assertTrue("'declare @method' should have one relationships but has " + matches.size(),matches.size()==1);
List matchesTargets = ((Relationship)matches.get(0)).getTargets();
assertTrue("'declare @method' should have one targets but has" + matchesTargets.size(),matchesTargets.size()==1);
IProgramElement target = AsmManager.getDefault().getHierarchy().findElementForHandle((String)matchesTargets.get(0));
assertEquals("target of relationship should be the 'debit(java.lang.String,long)' method but is IPE with label "
+ target.toLabelString(),method,target);
// check that the debit method has an annotated by relationship with the declare @method
matches = AsmManager.getDefault().getRelationshipMap().get(method);
assertNotNull("'debit(java.lang.String,long)' should have some relationships but does not",matches);
assertTrue("'debit(java.lang.String,long)' should have one relationships but has " + matches.size(),matches.size()==1);
matchesTargets = ((Relationship)matches.get(0)).getTargets();
assertTrue("'debit(java.lang.String,long)' should have one targets but has" + matchesTargets.size(),matchesTargets.size()==1);
target = AsmManager.getDefault().getHierarchy().findElementForHandle((String)matchesTargets.get(0));
assertEquals("target of relationship should be the 'declare @method' ipe but is IPE with label "
+ target.toLabelString(),decam,target);
}
// this next one reported as a bug by Rob Harrop, but I can't reproduce the failure yet...
//public void testAtAspectWithReferencePCPerClause_pr138220() { runTest("@Aspect with reference pointcut in perclause");}
public void testJarChecking_pr137235_1() { runTest("directory with .jar extension: source and outjar"); }
public void testJarChecking_pr137235_2() { runTest("directory with .jar extension"); }
public void testMakePreMethodNPE_pr136393() { runTest("NPE in makePreMethod");}
// public void testFunkyGenericErrorWithITDs_pr126355_2() {
// runTest("bizarre generic error with itds - 2");
// // public class Pair<F,S> affected by pertarget aspect
// GenericsTests.verifyClassSignature(ajc,"Pair","<F:Ljava/lang/Object;S:Ljava/lang/Object;>Ljava/lang/Object;LIdempotentCache$ajcMightHaveAspect;;");
// }
// tests that can't be included for some reason
// Not valid whilst the ajc compiler forces debug on (ignores -g:none) - it will be green but is invalid, trust me
// public void testLongWindedMessages_pr129408() { runTest("long winded ataj messages");}
/////////////////////////////////////////
public static Test suite() {
return XMLBasedAjcTestCase.loadSuite(Ajc152Tests.class);
}
protected File getSpecFile() {
return new File("../tests/src/org/aspectj/systemtest/ajc152/ajc152.xml");
}
}
|
132,591 |
Bug 132591 Duplicate exception with aop.xml file on aspectpath
| null |
resolved fixed
|
319a0d1
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-06-02T12:47:08Z | 2006-03-20T21:26:40Z |
ajde/testsrc/org/aspectj/ajde/NullIdeProperties.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:
* Xerox/PARC initial implementation
* AMC 01.20.2003 extended to support AspectJ 1.1 options
* ******************************************************************/
package org.aspectj.ajde;
import java.io.*;
import java.util.*;
import org.aspectj.tools.ajc.AjcTests;
import org.aspectj.util.FileUtil;
/**
* @author Mik Kersten
*/
public class NullIdeProperties implements ProjectPropertiesAdapter {
private String testProjectPath = "";
private List buildConfigFiles = new ArrayList();
private Set inJars;
private Set inpath;
private Set sourceRoots;
private Set aspectPath;
private String outJar;
private String outputPath = "bin";
public NullIdeProperties(String testProjectPath) {
this.testProjectPath = testProjectPath;
}
public List getBuildConfigFiles() {
return buildConfigFiles;
}
public String getLastActiveBuildConfigFile() {
return null;
}
public String getDefaultBuildConfigFile() {
return null;
}
public String getProjectName() {
return "test";
}
public String getRootProjectDir() {
return testProjectPath;
}
public List getProjectSourceFiles() {
return null;
}
public String getProjectSourcePath() {
return testProjectPath + "/src";
}
public String getClasspath() {
return testProjectPath
+ File.pathSeparator
+ System.getProperty("sun.boot.class.path")
+ File.pathSeparator
+ AjcTests.aspectjrtClasspath();
}
public String getOutputPath() {
return testProjectPath + "/" + outputPath;
}
public void setOutputPath(String outputPath) {
this.outputPath = outputPath;
}
public OutputLocationManager getOutputLocationManager() {
return null;
}
public String getAjcWorkingDir() {
return testProjectPath + "/ajworkingdir";
}
public String getBootClasspath() {
return null;
}
public String getClassToExecute() {
return "figures.Main";
}
public String getExecutionArgs() {
return null;
}
public String getVmArgs() {
return null;
}
public void setInJars( Set jars ) { this.inJars = jars; }
public void setInpath( Set path) { this.inpath = path; }
public Set getInJars( ) {
return inJars;
}
public Set getInpath( ) {
return inpath;
}
public Map getSourcePathResources() {
File srcBase = new File(getProjectSourcePath());
File[] fromResources = FileUtil.listFiles(srcBase, new FileFilter() {
public boolean accept(File pathname) {
String name = pathname.getName().toLowerCase();
return !name.endsWith(".class") && !name.endsWith(".java") && !name.endsWith(".aj");
}
});
Map map = new HashMap();
for (int i = 0; i < fromResources.length; i++) {
String normPath = FileUtil.normalizedPath(fromResources[i] ,srcBase);
map.put(normPath, fromResources[i]);
}
return map;
}
public void setOutJar( String jar ){ this.outJar = jar; }
public String getOutJar() {
return outJar;
}
public void setSourceRoots( Set roots ) { this.sourceRoots = roots; }
public Set getSourceRoots() {
return sourceRoots;
}
public void setAspectPath( Set path ) { this.aspectPath = path; }
public Set getAspectPath() {
return aspectPath;
}
}
|
132,591 |
Bug 132591 Duplicate exception with aop.xml file on aspectpath
| null |
resolved fixed
|
319a0d1
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-06-02T12:47:08Z | 2006-03-20T21:26:40Z |
ajde/testsrc/org/aspectj/ajde/OutxmlTest.java
|
/* *******************************************************************
* Copyright (c) 2003 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:
* Matthew Webster initial implementation
* ******************************************************************/
package org.aspectj.ajde;
import java.io.File;
import java.io.IOException;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import org.aspectj.util.FileUtil;
public class OutxmlTest extends AjdeTestCase {
public static final String PROJECT_DIR = "OutxmlTest";
public static final String BIN_DIR = "bin";
public static final String OUTJAR_NAME = "/bin/test.jar";
public static final String DEFAULT_AOPXML_NAME = "META-INF/aop.xml";
public static final String CUSTOM_AOPXML_NAME = "custom/aop.xml";
/*
* Ensure the output directory is clean
*/
protected void setUp() throws Exception {
super.setUp(PROJECT_DIR);
FileUtil.deleteContents(openFile(BIN_DIR));
}
/*
* Clean up afterwards
*/
protected void tearDown() throws Exception {
super.tearDown();
FileUtil.deleteContents(openFile(BIN_DIR));
openFile(BIN_DIR).delete();
}
/**
* Aim: Test "-outxml" option produces the correct xml file
*
*/
public void testOutxmlToFile () {
// System.out.println("OutxmlTest.testOutxmlToFile() outputpath='" + ideManager.getProjectProperties().getOutputPath() + "'");
assertTrue("Build failed",doSynchronousBuild("outxml-to-file.lst"));
assertTrue("Build warnings",ideManager.getCompilationSourceLineTasks().isEmpty());
File aopxml = openFile(BIN_DIR + "/" + DEFAULT_AOPXML_NAME);
assertTrue(DEFAULT_AOPXML_NAME + " missing",aopxml.exists());
}
/**
* Aim: Test "-outxmlfile filename" option produces the correct
* xml file
*
*/
public void testOutxmlfileToFile () {
assertTrue("Build failed",doSynchronousBuild("outxmlfile-to-file.lst"));
assertTrue("Build warnings",ideManager.getCompilationSourceLineTasks().isEmpty());
File aopxml = openFile(BIN_DIR + "/" + CUSTOM_AOPXML_NAME);
assertTrue(CUSTOM_AOPXML_NAME + " missing",aopxml.exists());
}
/**
* Aim: Test "-outxml" option produces the correct
* xml entry in outjar file
*
*/
public void testOutxmlToOutjar () {
File outjar = openFile(OUTJAR_NAME);
ideManager.getProjectProperties().setOutJar(outjar.getAbsolutePath());
assertTrue("Build failed",doSynchronousBuild("outxml-to-outjar.lst"));
assertTrue("Build warnings",ideManager.getCompilationSourceLineTasks().isEmpty());
File aopxml = openFile(BIN_DIR + "/" + DEFAULT_AOPXML_NAME);
assertFalse(DEFAULT_AOPXML_NAME + " should not exisit",aopxml.exists());
assertJarContainsEntry(outjar,DEFAULT_AOPXML_NAME);
}
/**
* Aim: Test "-outxmlfile filename" option produces the correct
* xml entry in outjar file
*
*/
public void testOutxmlfileToOutjar () {
// System.out.println("OutxmlTest.testOutxmlToOutjar() outputpath='" + ideManager.getProjectProperties().getOutputPath() + "'");
File outjar = openFile(OUTJAR_NAME);
ideManager.getProjectProperties().setOutJar(outjar.getAbsolutePath());
assertTrue("Build failed",doSynchronousBuild("outxmlfile-to-outjar.lst"));
assertTrue("Build warnings",ideManager.getCompilationSourceLineTasks().isEmpty());
File aopxml = openFile(BIN_DIR + "/" + CUSTOM_AOPXML_NAME);
assertFalse(CUSTOM_AOPXML_NAME + " should not exisit",aopxml.exists());
assertJarContainsEntry(outjar,CUSTOM_AOPXML_NAME);
}
private void assertJarContainsEntry (File file, String entryName) {
try {
JarFile jarFile = new JarFile(file);
JarEntry jarEntry = jarFile.getJarEntry(entryName);
assertNotNull(entryName + " missing",jarEntry);
}
catch (IOException ex) {
fail(ex.toString());
}
}
}
|
132,591 |
Bug 132591 Duplicate exception with aop.xml file on aspectpath
| null |
resolved fixed
|
319a0d1
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-06-02T12:47:08Z | 2006-03-20T21:26:40Z |
org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/core/builder/AjBuildManager.java
|
/* *******************************************************************
* Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC).
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the 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.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.jar.Attributes;
import java.util.jar.JarFile;
import java.util.jar.JarInputStream;
import java.util.jar.JarOutputStream;
import java.util.jar.Manifest;
import java.util.zip.ZipEntry;
import org.aspectj.ajdt.internal.compiler.AjCompilerAdapter;
import org.aspectj.ajdt.internal.compiler.IBinarySourceProvider;
import org.aspectj.ajdt.internal.compiler.ICompilerAdapter;
import org.aspectj.ajdt.internal.compiler.ICompilerAdapterFactory;
import org.aspectj.ajdt.internal.compiler.IIntermediateResultsRequestor;
import org.aspectj.ajdt.internal.compiler.IOutputClassFileNameProvider;
import org.aspectj.ajdt.internal.compiler.InterimCompilationResult;
import org.aspectj.ajdt.internal.compiler.lookup.AjLookupEnvironment;
import org.aspectj.ajdt.internal.compiler.lookup.AnonymousClassPublisher;
import org.aspectj.ajdt.internal.compiler.lookup.EclipseFactory;
import org.aspectj.ajdt.internal.compiler.problem.AjProblemReporter;
import org.aspectj.asm.AsmManager;
import org.aspectj.asm.IHierarchy;
import org.aspectj.asm.IProgramElement;
import org.aspectj.asm.internal.ProgramElement;
import org.aspectj.bridge.AbortException;
import org.aspectj.bridge.CountingMessageHandler;
import org.aspectj.bridge.ILifecycleAware;
import org.aspectj.bridge.IMessage;
import org.aspectj.bridge.IMessageHandler;
import org.aspectj.bridge.IProgressListener;
import org.aspectj.bridge.Message;
import org.aspectj.bridge.MessageUtil;
import org.aspectj.bridge.SourceLocation;
import org.aspectj.bridge.Version;
import org.aspectj.bridge.context.CompilationAndWeavingContext;
import org.aspectj.bridge.context.ContextFormatter;
import org.aspectj.bridge.context.ContextToken;
import org.aspectj.org.eclipse.jdt.core.compiler.CharOperation;
import org.aspectj.org.eclipse.jdt.core.compiler.IProblem;
import org.aspectj.org.eclipse.jdt.internal.compiler.ClassFile;
import org.aspectj.org.eclipse.jdt.internal.compiler.CompilationResult;
import org.aspectj.org.eclipse.jdt.internal.compiler.DefaultErrorHandlingPolicies;
import org.aspectj.org.eclipse.jdt.internal.compiler.ICompilerRequestor;
import org.aspectj.org.eclipse.jdt.internal.compiler.IProblemFactory;
import org.aspectj.org.eclipse.jdt.internal.compiler.batch.ClasspathDirectory;
import org.aspectj.org.eclipse.jdt.internal.compiler.batch.CompilationUnit;
import org.aspectj.org.eclipse.jdt.internal.compiler.batch.FileSystem;
import org.aspectj.org.eclipse.jdt.internal.compiler.env.ICompilationUnit;
import org.aspectj.org.eclipse.jdt.internal.compiler.env.INameEnvironment;
import org.aspectj.org.eclipse.jdt.internal.compiler.impl.CompilerOptions;
import org.aspectj.org.eclipse.jdt.internal.compiler.parser.Parser;
import org.aspectj.org.eclipse.jdt.internal.compiler.problem.AbortCompilation;
import org.aspectj.org.eclipse.jdt.internal.compiler.problem.DefaultProblemFactory;
import org.aspectj.util.FileUtil;
import org.aspectj.weaver.Dump;
import org.aspectj.weaver.ResolvedType;
import org.aspectj.weaver.World;
import org.aspectj.weaver.bcel.BcelWeaver;
import org.aspectj.weaver.bcel.BcelWorld;
import org.aspectj.weaver.bcel.UnwovenClassFile;
import org.eclipse.core.runtime.OperationCanceledException;
//import org.aspectj.org.eclipse.jdt.internal.compiler.util.HashtableOfObject;
public class AjBuildManager implements IOutputClassFileNameProvider,IBinarySourceProvider,ICompilerAdapterFactory {
private static final String CROSSREFS_FILE_NAME = "build.lst";
private static final String CANT_WRITE_RESULT = "unable to write compilation result";
private static final String MANIFEST_NAME = "META-INF/MANIFEST.MF";
static final boolean COPY_INPATH_DIR_RESOURCES = false;
static final boolean FAIL_IF_RUNTIME_NOT_FOUND = false;
private static final FileFilter binarySourceFilter =
new FileFilter() {
public boolean accept(File f) {
return f.getName().endsWith(".class");
}};
/**
* This builder is static so that it can be subclassed and reset. However, note
* that there is only one builder present, so if two extendsion reset it, only
* the latter will get used.
*/
public static AsmHierarchyBuilder asmHierarchyBuilder = new AsmHierarchyBuilder();
static {
CompilationAndWeavingContext.registerFormatter(
CompilationAndWeavingContext.BATCH_BUILD, new AjBuildContexFormatter());
CompilationAndWeavingContext.registerFormatter(
CompilationAndWeavingContext.INCREMENTAL_BUILD, new AjBuildContexFormatter());
}
private IProgressListener progressListener = null;
private boolean environmentSupportsIncrementalCompilation = false;
private int compiledCount;
private int sourceFileCount;
private JarOutputStream zos;
private boolean batchCompile = true;
private INameEnvironment environment;
private Map /* String -> List<UCF>*/ binarySourcesForTheNextCompile = new HashMap();
// FIXME asc should this really be in here?
private IHierarchy structureModel;
public AjBuildConfig buildConfig;
AjState state = new AjState(this);
public BcelWeaver getWeaver() { return state.getWeaver();}
public BcelWorld getBcelWorld() { return state.getBcelWorld();}
public CountingMessageHandler handler;
public AjBuildManager(IMessageHandler holder) {
super();
this.handler = CountingMessageHandler.makeCountingMessageHandler(holder);
}
public void environmentSupportsIncrementalCompilation(boolean itDoes) {
this.environmentSupportsIncrementalCompilation = itDoes;
}
/** @return true if we should generate a model as a side-effect */
public boolean doGenerateModel() {
return buildConfig.isGenerateModelMode();
}
public boolean batchBuild(
AjBuildConfig buildConfig,
IMessageHandler baseHandler)
throws IOException, AbortException {
return doBuild(buildConfig, baseHandler, true);
}
public boolean incrementalBuild(
AjBuildConfig buildConfig,
IMessageHandler baseHandler)
throws IOException, AbortException {
return doBuild(buildConfig, baseHandler, false);
}
/** @throws AbortException if check for runtime fails */
protected boolean doBuild(
AjBuildConfig buildConfig,
IMessageHandler baseHandler,
boolean batch) throws IOException, AbortException {
boolean ret = true;
batchCompile = batch;
if (baseHandler instanceof ILifecycleAware) {
((ILifecycleAware)baseHandler).buildStarting(!batch);
}
CompilationAndWeavingContext.reset();
int phase = batch ? CompilationAndWeavingContext.BATCH_BUILD : CompilationAndWeavingContext.INCREMENTAL_BUILD;
ContextToken ct = CompilationAndWeavingContext.enteringPhase(phase ,buildConfig);
try {
if (batch) {
this.state = new AjState(this);
}
this.state.setCouldBeSubsequentIncrementalBuild(this.environmentSupportsIncrementalCompilation);
boolean canIncremental = state.prepareForNextBuild(buildConfig);
if (!canIncremental && !batch) { // retry as batch?
CompilationAndWeavingContext.leavingPhase(ct);
if (state.listenerDefined()) state.getListener().recordDecision("Falling back to batch compilation");
return doBuild(buildConfig, baseHandler, true);
}
this.handler =
CountingMessageHandler.makeCountingMessageHandler(baseHandler);
// XXX duplicate, no? remove?
String check = checkRtJar(buildConfig);
if (check != null) {
if (FAIL_IF_RUNTIME_NOT_FOUND) {
MessageUtil.error(handler, check);
CompilationAndWeavingContext.leavingPhase(ct);
return false;
} else {
MessageUtil.warn(handler, check);
}
}
// if (batch) {
setBuildConfig(buildConfig);
//}
if (batch || !AsmManager.attemptIncrementalModelRepairs) {
// if (buildConfig.isEmacsSymMode() || buildConfig.isGenerateModelMode()) {
setupModel(buildConfig);
// }
}
if (batch) {
initBcelWorld(handler);
}
if (handler.hasErrors()) {
CompilationAndWeavingContext.leavingPhase(ct);
return false;
}
if (buildConfig.getOutputJar() != null) {
if (!openOutputStream(buildConfig.getOutputJar())) {
CompilationAndWeavingContext.leavingPhase(ct);
return false;
}
}
if (batch) {
// System.err.println("XXXX batch: " + buildConfig.getFiles());
if (buildConfig.isEmacsSymMode() || buildConfig.isGenerateModelMode()) {
getWorld().setModel(AsmManager.getDefault().getHierarchy());
// in incremental build, only get updated model?
}
binarySourcesForTheNextCompile = state.getBinaryFilesToCompile(true);
performCompilation(buildConfig.getFiles());
state.clearBinarySourceFiles(); // we don't want these hanging around...
if (handler.hasErrors()) {
CompilationAndWeavingContext.leavingPhase(ct);
return false;
}
if (AsmManager.isReporting())
AsmManager.getDefault().reportModelInfo("After a batch build");
} else {
// done already?
// if (buildConfig.isEmacsSymMode() || buildConfig.isGenerateModelMode()) {
// bcelWorld.setModel(StructureModelManager.INSTANCE.getStructureModel());
// }
// System.err.println("XXXX start inc ");
binarySourcesForTheNextCompile = state.getBinaryFilesToCompile(true);
List files = state.getFilesToCompile(true);
if (buildConfig.isEmacsSymMode() || buildConfig.isGenerateModelMode())
if (AsmManager.attemptIncrementalModelRepairs)
AsmManager.getDefault().processDelta(files,state.getAddedFiles(),state.getDeletedFiles());
boolean hereWeGoAgain = !(files.isEmpty() && binarySourcesForTheNextCompile.isEmpty());
for (int i = 0; (i < 5) && hereWeGoAgain; i++) {
if (state.listenerDefined())
state.getListener().recordInformation("Starting incremental compilation loop "+(i+1)+" of possibly 5");
// System.err.println("XXXX inc: " + files);
performCompilation(files);
if (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)
AsmManager.getDefault().processDelta(files,state.getAddedFiles(),state.getDeletedFiles());
}
}
if (!files.isEmpty()) {
CompilationAndWeavingContext.leavingPhase(ct);
return batchBuild(buildConfig, baseHandler);
} else {
if (AsmManager.isReporting())
AsmManager.getDefault().reportModelInfo("After an incremental build");
}
}
// XXX not in Mik's incremental
if (buildConfig.isEmacsSymMode()) {
new org.aspectj.ajdt.internal.core.builder.EmacsStructureModelManager().externalizeModel();
}
// for bug 113554: support ajsym file generation for command line builds
if (buildConfig.isGenerateCrossRefsMode()) {
String configFileProxy = buildConfig.getOutputDir().getAbsolutePath()
+ File.separator
+ CROSSREFS_FILE_NAME;
AsmManager.getDefault().writeStructureModel(configFileProxy);
}
// have to tell state we succeeded or next is not incremental
state.successfulCompile(buildConfig,batch);
copyResourcesToDestination();
if (buildConfig.getOutxmlName() != null) {
writeOutxmlFile();
}
/*boolean weaved = *///weaveAndGenerateClassFiles();
// if not weaved, then no-op build, no model changes
// but always returns true
// XXX weaved not in Mik's incremental
if (buildConfig.isGenerateModelMode()) {
AsmManager.getDefault().fireModelUpdated();
}
CompilationAndWeavingContext.leavingPhase(ct);
} finally {
if (baseHandler instanceof ILifecycleAware) {
((ILifecycleAware)baseHandler).buildFinished(!batch);
}
if (zos != null) {
closeOutputStream(buildConfig.getOutputJar());
}
ret = !handler.hasErrors();
if (getBcelWorld()!=null) getBcelWorld().tidyUp();
getWeaver().tidyUp();
// bug 59895, don't release reference to handler as may be needed by a nested call
//handler = null;
}
return ret;
}
private String stringifyList(List l) {
if (l==null) return "";
StringBuffer sb = new StringBuffer();
sb.append("{");
for (Iterator iter = l.iterator(); iter.hasNext();) {
Object el = (Object) iter.next();
sb.append(el);
if (iter.hasNext()) sb.append(",");
}
sb.append("}");
return sb.toString();
}
private boolean openOutputStream(File outJar) {
try {
OutputStream os = FileUtil.makeOutputStream(buildConfig.getOutputJar());
zos = new JarOutputStream(os,getWeaver().getManifest(true));
} catch (IOException ex) {
IMessage message =
new Message("Unable to open outjar "
+ outJar.getPath()
+ "(" + ex.getMessage()
+ ")",
new SourceLocation(outJar,0),
true);
handler.handleMessage(message);
return false;
}
return true;
}
private void closeOutputStream(File outJar) {
try {
if (zos != null) zos.close();
zos = null;
/* Ensure we don't write an incomplete JAR bug-71339 */
if (handler.hasErrors()) {
outJar.delete();
}
} catch (IOException ex) {
IMessage message =
new Message("Unable to write outjar "
+ outJar.getPath()
+ "(" + ex.getMessage()
+ ")",
new SourceLocation(outJar,0),
true);
handler.handleMessage(message);
}
}
private void copyResourcesToDestination() throws IOException {
// resources that we need to copy are contained in the injars and inpath only
for (Iterator i = buildConfig.getInJars().iterator(); i.hasNext(); ) {
File inJar = (File)i.next();
copyResourcesFromJarFile(inJar);
}
for (Iterator i = buildConfig.getInpath().iterator(); i.hasNext(); ) {
File inPathElement = (File)i.next();
if (inPathElement.isDirectory()) {
copyResourcesFromDirectory(inPathElement);
} else {
copyResourcesFromJarFile(inPathElement);
}
}
if (buildConfig.getSourcePathResources() != null) {
for (Iterator i = buildConfig.getSourcePathResources().keySet().iterator(); i.hasNext(); ) {
String resource = (String)i.next();
File from = (File)buildConfig.getSourcePathResources().get(resource);
copyResourcesFromFile(from,resource,from);
}
}
writeManifest();
}
private void copyResourcesFromJarFile(File jarFile) throws IOException {
JarInputStream inStream = null;
try {
inStream = new JarInputStream(new FileInputStream(jarFile));
while (true) {
ZipEntry entry = inStream.getNextEntry();
if (entry == null) break;
String filename = entry.getName();
// System.out.println("? copyResourcesFromJarFile() filename='" + filename +"'");
if (!entry.isDirectory() && acceptResource(filename)) {
byte[] bytes = FileUtil.readAsByteArray(inStream);
writeResource(filename,bytes,jarFile);
}
inStream.closeEntry();
}
} finally {
if (inStream != null) inStream.close();
}
}
private void copyResourcesFromDirectory(File dir) throws IOException {
if (!COPY_INPATH_DIR_RESOURCES) return;
// Get a list of all files (i.e. everything that isnt a directory)
File[] files = FileUtil.listFiles(dir,new FileFilter() {
public boolean accept(File f) {
boolean accept = !(f.isDirectory() || f.getName().endsWith(".class")) ;
return accept;
}
});
// For each file, add it either as a real .class file or as a resource
for (int i = 0; i < files.length; i++) {
// ASSERT: files[i].getAbsolutePath().startsWith(inFile.getAbsolutePath()
// or we are in trouble...
String filename = files[i].getAbsolutePath().substring(
dir.getAbsolutePath().length()+1);
copyResourcesFromFile(files[i],filename,dir);
}
}
private void copyResourcesFromFile(File f,String filename,File src) throws IOException {
if (!acceptResource(filename)) return;
FileInputStream fis = null;
try {
fis = new FileInputStream(f);
byte[] bytes = FileUtil.readAsByteArray(fis);
// String relativePath = files[i].getPath();
writeResource(filename,bytes,src);
} finally {
if (fis != null) fis.close();
}
}
private void writeResource(String filename, byte[] content, File srcLocation) throws IOException {
if (state.hasResource(filename)) {
IMessage msg = new Message("duplicate resource: '" + filename + "'",
IMessage.WARNING,
null,
new SourceLocation(srcLocation,0));
handler.handleMessage(msg);
return;
}
if (zos != null) {
ZipEntry newEntry = new ZipEntry(filename); //??? get compression scheme right
zos.putNextEntry(newEntry);
zos.write(content);
zos.closeEntry();
} else {
File destDir = buildConfig.getOutputDir();
if (buildConfig.getCompilationResultDestinationManager() != null) {
destDir = buildConfig.getCompilationResultDestinationManager().getOutputLocationForResource(srcLocation);
}
try {
OutputStream fos =
FileUtil.makeOutputStream(new File(destDir,filename));
fos.write(content);
fos.close();
} 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);
}
/*
* If we are writing to an output directory copy the manifest but only
* if we already have one
*/
private void writeManifest () throws IOException {
Manifest manifest = getWeaver().getManifest(false);
if (manifest != null && zos == null) {
OutputStream fos =
FileUtil.makeOutputStream(new File(buildConfig.getOutputDir(),MANIFEST_NAME));
manifest.write(fos);
fos.close();
}
}
private boolean acceptResource(String resourceName) {
if (
(resourceName.startsWith("CVS/")) ||
(resourceName.indexOf("/CVS/") != -1) ||
(resourceName.endsWith("/CVS")) ||
(resourceName.endsWith(".class")) ||
(resourceName.startsWith(".svn/")) ||
(resourceName.indexOf("/.svn/")!=-1) ||
(resourceName.endsWith("/.svn")) ||
(resourceName.toUpperCase().equals(MANIFEST_NAME))
)
{
return false;
} else {
return true;
}
}
private void writeOutxmlFile () throws IOException {
String filename = buildConfig.getOutxmlName();
// System.err.println("? AjBuildManager.writeOutxmlFile() outxml=" + filename);
// System.err.println("? AjBuildManager.writeOutxmlFile() outputDir=" + buildConfig.getOutputDir());
ByteArrayOutputStream baos = new ByteArrayOutputStream();
PrintStream ps = new PrintStream(baos);
ps.println("<aspectj>");
ps.println("<aspects>");
if (state.getAspectNames() != null) {
for (Iterator i = state.getAspectNames().iterator(); i.hasNext();) {
String name = (String)i.next();
ps.println("<aspect name=\"" + name + "\"/>");
}
}
ps.println("</aspects>");
ps.println("</aspectj>");
ps.println();
ps.close();
if (zos != null) {
ZipEntry newEntry = new ZipEntry(filename);
zos.putNextEntry(newEntry);
zos.write(baos.toByteArray());
zos.closeEntry();
} else {
OutputStream fos =
FileUtil.makeOutputStream(new File(buildConfig.getOutputDir(),filename));
fos.write(baos.toByteArray());
fos.close();
}
}
// public static void dumprels() {
// IRelationshipMap irm = AsmManager.getDefault().getRelationshipMap();
// int ctr = 1;
// Set entries = irm.getEntries();
// for (Iterator iter = entries.iterator(); iter.hasNext();) {
// String hid = (String) iter.next();
// List rels = irm.get(hid);
// for (Iterator iterator = rels.iterator(); iterator.hasNext();) {
// IRelationship ir = (IRelationship) iterator.next();
// List targets = ir.getTargets();
// for (Iterator iterator2 = targets.iterator();
// iterator2.hasNext();
// ) {
// String thid = (String) iterator2.next();
// System.err.println("Hid:"+(ctr++)+":(targets="+targets.size()+") "+hid+" ("+ir.getName()+") "+thid);
// }
// }
// }
// }
/**
* Responsible for managing the ASM model between builds. Contains the policy for
* maintaining the persistance of elements in the model.
*
* This code is driven before each 'fresh' (batch) build to create
* a new model.
*/
private void setupModel(AjBuildConfig config) {
AsmManager.setCreatingModel(config.isEmacsSymMode() || config.isGenerateModelMode());
if (!AsmManager.isCreatingModel()) return;
AsmManager.getDefault().createNewASM();
// AsmManager.getDefault().getRelationshipMap().clear();
IHierarchy model = AsmManager.getDefault().getHierarchy();
String rootLabel = "<root>";
IProgramElement.Kind kind = IProgramElement.Kind.FILE_JAVA;
if (buildConfig.getConfigFile() != null) {
rootLabel = buildConfig.getConfigFile().getName();
model.setConfigFile(buildConfig.getConfigFile().getAbsolutePath());
kind = IProgramElement.Kind.FILE_LST;
}
model.setRoot(new ProgramElement(rootLabel, kind, new ArrayList()));
model.setFileMap(new HashMap());
setStructureModel(model);
state.setStructureModel(model);
state.setRelationshipMap(AsmManager.getDefault().getRelationshipMap());
}
//
// private void dumplist(List l) {
// System.err.println("---- "+l.size());
// for (int i =0 ;i<l.size();i++) System.err.println(i+"\t "+l.get(i));
// }
// private void accumulateFileNodes(IProgramElement ipe,List store) {
// if (ipe.getKind()==IProgramElement.Kind.FILE_JAVA ||
// ipe.getKind()==IProgramElement.Kind.FILE_ASPECTJ) {
// if (!ipe.getName().equals("<root>")) {
// store.add(ipe);
// return;
// }
// }
// for (Iterator i = ipe.getChildren().iterator();i.hasNext();) {
// accumulateFileNodes((IProgramElement)i.next(),store);
// }
// }
/** init only on initial batch compile? no file-specific options */
private void initBcelWorld(IMessageHandler handler) throws IOException {
List cp = buildConfig.getBootclasspath();
cp.addAll(buildConfig.getClasspath());
BcelWorld bcelWorld = new BcelWorld(cp, handler, null);
bcelWorld.setBehaveInJava5Way(buildConfig.getBehaveInJava5Way());
bcelWorld.setAddSerialVerUID(buildConfig.isAddSerialVerUID());
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,buildConfig.getOptions().warningThreshold);
BcelWeaver bcelWeaver = new BcelWeaver(bcelWorld);
state.setWorld(bcelWorld);
state.setWeaver(bcelWeaver);
state.clearBinarySourceFiles();
for (Iterator i = buildConfig.getAspectpath().iterator(); i.hasNext();) {
File f = (File) i.next();
if (!f.exists()) {
IMessage message = new Message("invalid aspectpath entry: "+f.getName(),null,true);
handler.handleMessage(message);
} else {
bcelWeaver.addLibraryJarFile(f);
}
}
// String lintMode = buildConfig.getLintMode();
if (buildConfig.getLintMode().equals(AjBuildConfig.AJLINT_DEFAULT)) {
bcelWorld.getLint().loadDefaultProperties();
} else {
bcelWorld.getLint().setAll(buildConfig.getLintMode());
}
if (buildConfig.getLintSpecFile() != null) {
bcelWorld.getLint().setFromProperties(buildConfig.getLintSpecFile());
}
//??? incremental issues
for (Iterator i = buildConfig.getInJars().iterator(); i.hasNext(); ) {
File inJar = (File)i.next();
List unwovenClasses = bcelWeaver.addJarFile(inJar, buildConfig.getOutputDir(),false);
state.recordBinarySource(inJar.getPath(), unwovenClasses);
}
for (Iterator i = buildConfig.getInpath().iterator(); i.hasNext(); ) {
File inPathElement = (File)i.next();
if (!inPathElement.isDirectory()) {
// its a jar file on the inpath
// the weaver method can actually handle dirs, but we don't call it, see next block
List unwovenClasses = bcelWeaver.addJarFile(inPathElement,buildConfig.getOutputDir(),true);
state.recordBinarySource(inPathElement.getPath(),unwovenClasses);
} else {
// add each class file in an in-dir individually, this gives us the best error reporting
// (they are like 'source' files then), and enables a cleaner incremental treatment of
// class file changes in indirs.
File[] binSrcs = FileUtil.listFiles(inPathElement, binarySourceFilter);
for (int j = 0; j < binSrcs.length; j++) {
UnwovenClassFile ucf =
bcelWeaver.addClassFile(binSrcs[j], inPathElement, buildConfig.getOutputDir());
List ucfl = new ArrayList();
ucfl.add(ucf);
state.recordBinarySource(binSrcs[j].getPath(),ucfl);
}
}
}
bcelWeaver.setReweavableMode(buildConfig.isXNotReweavable());
//check for org.aspectj.runtime.JoinPoint
ResolvedType joinPoint = bcelWorld.resolve("org.aspectj.lang.JoinPoint");
if (joinPoint.isMissing()) {
IMessage message =
new Message("classpath error: unable to find org.aspectj.lang.JoinPoint (check that aspectjrt.jar is in your classpath)",
null,
true);
handler.handleMessage(message);
}
}
public World getWorld() {
return getBcelWorld();
}
void addAspectClassFilesToWeaver(List addedClassFiles) throws IOException {
for (Iterator i = addedClassFiles.iterator(); i.hasNext(); ) {
UnwovenClassFile classFile = (UnwovenClassFile) i.next();
getWeaver().addClassFile(classFile);
}
}
// public boolean weaveAndGenerateClassFiles() throws IOException {
// handler.handleMessage(MessageUtil.info("weaving"));
// if (progressListener != null) progressListener.setText("weaving aspects");
// bcelWeaver.setProgressListener(progressListener, 0.5, 0.5/state.addedClassFiles.size());
// //!!! doesn't provide intermediate progress during weaving
// // XXX add all aspects even during incremental builds?
// addAspectClassFilesToWeaver(state.addedClassFiles);
// if (buildConfig.isNoWeave()) {
// if (buildConfig.getOutputJar() != null) {
// bcelWeaver.dumpUnwoven(buildConfig.getOutputJar());
// } else {
// bcelWeaver.dumpUnwoven();
// bcelWeaver.dumpResourcesToOutPath();
// }
// } else {
// if (buildConfig.getOutputJar() != null) {
// bcelWeaver.weave(buildConfig.getOutputJar());
// } else {
// bcelWeaver.weave();
// bcelWeaver.dumpResourcesToOutPath();
// }
// }
// if (progressListener != null) progressListener.setProgress(1.0);
// return true;
// //return messageAdapter.getErrorCount() == 0; //!javaBuilder.notifier.anyErrors();
// }
public FileSystem getLibraryAccess(String[] classpaths, String[] filenames) {
String defaultEncoding = buildConfig.getOptions().defaultEncoding;
if ("".equals(defaultEncoding)) //$NON-NLS-1$
defaultEncoding = null; //$NON-NLS-1$
// Bug 46671: We need an array as long as the number of elements in the classpath - *even though* not every
// element of the classpath is likely to be a directory. If we ensure every element of the array is set to
// only look for BINARY, then we make sure that for any classpath element that is a directory, we won't build
// a classpathDirectory object that will attempt to look for source when it can't find binary.
int[] classpathModes = new int[classpaths.length];
for (int i =0 ;i<classpaths.length;i++) classpathModes[i]=ClasspathDirectory.BINARY;
return new FileSystem(classpaths, filenames, defaultEncoding,classpathModes);
}
public IProblemFactory getProblemFactory() {
return new DefaultProblemFactory(Locale.getDefault());
}
/*
* Build the set of compilation source units
*/
public CompilationUnit[] getCompilationUnits(String[] filenames, String[] encodings) {
int fileCount = filenames.length;
CompilationUnit[] units = new CompilationUnit[fileCount];
// HashtableOfObject knownFileNames = new HashtableOfObject(fileCount);
String defaultEncoding = buildConfig.getOptions().defaultEncoding;
if ("".equals(defaultEncoding)) //$NON-NLS-1$
defaultEncoding = null; //$NON-NLS-1$
for (int i = 0; i < fileCount; i++) {
String encoding = encodings[i];
if (encoding == null)
encoding = defaultEncoding;
units[i] = new CompilationUnit(null, filenames[i], encoding);
}
return units;
}
public String extractDestinationPathFromSourceFile(CompilationResult result) {
ICompilationUnit compilationUnit = result.compilationUnit;
if (compilationUnit != null) {
char[] fileName = compilationUnit.getFileName();
int lastIndex = CharOperation.lastIndexOf(java.io.File.separatorChar, fileName);
if (lastIndex == -1) {
return System.getProperty("user.dir"); //$NON-NLS-1$
}
return new String(CharOperation.subarray(fileName, 0, lastIndex));
}
return System.getProperty("user.dir"); //$NON-NLS-1$
}
public void performCompilation(List files) {
if (progressListener != null) {
compiledCount=0;
sourceFileCount = files.size();
progressListener.setText("compiling source files");
}
//System.err.println("got files: " + files);
String[] filenames = new String[files.size()];
String[] encodings = new String[files.size()];
//System.err.println("filename: " + this.filenames);
for (int i=0; i < files.size(); i++) {
filenames[i] = ((File)files.get(i)).getPath();
}
List cps = buildConfig.getFullClasspath();
Dump.saveFullClasspath(cps);
String[] classpaths = new String[cps.size()];
for (int i=0; i < cps.size(); i++) {
classpaths[i] = (String)cps.get(i);
}
//System.out.println("compiling");
environment = getLibraryAccess(classpaths, filenames);
if (!state.getClassNameToFileMap().isEmpty()) {
environment = new StatefulNameEnvironment(environment, state.getClassNameToFileMap());
}
org.aspectj.ajdt.internal.compiler.CompilerAdapter.setCompilerAdapterFactory(this);
org.aspectj.org.eclipse.jdt.internal.compiler.Compiler compiler =
new org.aspectj.org.eclipse.jdt.internal.compiler.Compiler(environment,
DefaultErrorHandlingPolicies.proceedWithAllProblems(),
buildConfig.getOptions().getMap(),
getBatchRequestor(),
getProblemFactory());
CompilerOptions options = compiler.options;
options.produceReferenceInfo = true; //TODO turn off when not needed
try {
compiler.compile(getCompilationUnits(filenames, encodings));
} catch (OperationCanceledException oce) {
handler.handleMessage(new Message("build cancelled:"+oce.getMessage(),IMessage.WARNING,null,null));
}
// cleanup
org.aspectj.ajdt.internal.compiler.CompilerAdapter.setCompilerAdapterFactory(null);
AnonymousClassPublisher.aspectOf().setAnonymousClassCreationListener(null);
environment.cleanup();
environment = null;
}
/*
* Answer the component to which will be handed back compilation results from the compiler
*/
public IIntermediateResultsRequestor getInterimResultRequestor() {
return new IIntermediateResultsRequestor() {
public void acceptResult(InterimCompilationResult result) {
if (progressListener != null) {
compiledCount++;
progressListener.setProgress((compiledCount/2.0)/sourceFileCount);
progressListener.setText("compiled: " + result.fileName());
}
state.noteResult(result);
if (progressListener!=null && progressListener.isCancelledRequested()) {
throw new AbortCompilation(true,
new OperationCanceledException("Compilation cancelled as requested"));
}
}
};
}
public ICompilerRequestor getBatchRequestor() {
return new ICompilerRequestor() {
public void acceptResult(CompilationResult unitResult) {
// end of compile, must now write the results to the output destination
// this is either a jar file or a file in a directory
if (!(unitResult.hasErrors() && !proceedOnError())) {
Collection classFiles = unitResult.compiledTypes.values();
boolean shouldAddAspectName = (buildConfig.getOutxmlName() != null);
for (Iterator iter = classFiles.iterator(); iter.hasNext();) {
ClassFile classFile = (ClassFile) iter.next();
String filename = new String(classFile.fileName());
String classname = filename.replace('/', '.');
filename = filename.replace('/', File.separatorChar) + ".class";
try {
if (buildConfig.getOutputJar() == null) {
writeDirectoryEntry(unitResult, classFile,filename);
} else {
writeZipEntry(classFile,filename);
}
if (shouldAddAspectName) addAspectName(classname);
} catch (IOException ex) {
IMessage message = EclipseAdapterUtils.makeErrorMessage(
new String(unitResult.fileName),
CANT_WRITE_RESULT,
ex);
handler.handleMessage(message);
}
}
}
if (unitResult.hasProblems() || unitResult.hasTasks()) {
IProblem[] problems = unitResult.getAllProblems();
for (int i=0; i < problems.length; i++) {
IMessage message =
EclipseAdapterUtils.makeMessage(unitResult.compilationUnit, problems[i]);
handler.handleMessage(message);
}
}
}
private void writeDirectoryEntry(
CompilationResult unitResult,
ClassFile classFile,
String filename)
throws IOException {
File destinationPath = buildConfig.getOutputDir();
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();
}
BufferedOutputStream os =
FileUtil.makeOutputStream(new File(outFile));
os.write(classFile.getBytes());
os.close();
}
private void writeZipEntry(ClassFile classFile, String name)
throws IOException {
name = name.replace(File.separatorChar,'/');
ZipEntry newEntry = new ZipEntry(name); //??? get compression scheme right
zos.putNextEntry(newEntry);
zos.write(classFile.getBytes());
zos.closeEntry();
}
private void addAspectName (String name) {
BcelWorld world = getBcelWorld();
ResolvedType type = world.resolve(name);
// System.err.println("? writeAspectName() type=" + type);
if (type.isAspect()) {
if (state.getAspectNames() == null) {
state.initializeAspectNamesList();
}
if (!state.getAspectNames().contains(name)) {
state.getAspectNames().add(name);
}
}
}
};
}
protected boolean proceedOnError() {
return buildConfig.getProceedOnError();
}
// public void noteClassFiles(AjCompiler.InterimResult result) {
// if (result == null) return;
// CompilationResult unitResult = result.result;
// String sourceFileName = result.fileName();
// if (!(unitResult.hasErrors() && !proceedOnError())) {
// List unwovenClassFiles = new ArrayList();
// Enumeration classFiles = unitResult.compiledTypes.elements();
// while (classFiles.hasMoreElements()) {
// ClassFile classFile = (ClassFile) classFiles.nextElement();
// String filename = new String(classFile.fileName());
// filename = filename.replace('/', File.separatorChar) + ".class";
//
// File destinationPath = buildConfig.getOutputDir();
// if (destinationPath == null) {
// filename = new File(filename).getName();
// filename = new File(extractDestinationPathFromSourceFile(unitResult), filename).getPath();
// } else {
// filename = new File(destinationPath, filename).getPath();
// }
//
// //System.out.println("classfile: " + filename);
// unwovenClassFiles.add(new UnwovenClassFile(filename, classFile.getBytes()));
// }
// state.noteClassesFromFile(unitResult, sourceFileName, unwovenClassFiles);
//// System.out.println("file: " + sourceFileName);
//// for (int i=0; i < unitResult.simpleNameReferences.length; i++) {
//// System.out.println("simple: " + new String(unitResult.simpleNameReferences[i]));
//// }
//// for (int i=0; i < unitResult.qualifiedReferences.length; i++) {
//// System.out.println("qualified: " +
//// new String(CharOperation.concatWith(unitResult.qualifiedReferences[i], '/')));
//// }
// } else {
// state.noteClassesFromFile(null, sourceFileName, Collections.EMPTY_LIST);
// }
// }
//
private void setBuildConfig(AjBuildConfig buildConfig) {
this.buildConfig = buildConfig;
if (!this.environmentSupportsIncrementalCompilation) {
this.environmentSupportsIncrementalCompilation =
(buildConfig.isIncrementalMode() || buildConfig.isIncrementalFileMode());
}
handler.reset();
}
String makeClasspathString(AjBuildConfig buildConfig) {
if (buildConfig == null || buildConfig.getFullClasspath() == null) return "";
StringBuffer buf = new StringBuffer();
boolean first = true;
for (Iterator it = buildConfig.getFullClasspath().iterator(); it.hasNext(); ) {
if (first) { first = false; }
else { buf.append(File.pathSeparator); }
buf.append(it.next().toString());
}
return buf.toString();
}
/**
* This will return null if aspectjrt.jar is present and has the correct version.
* Otherwise it will return a string message indicating the problem.
*/
public String checkRtJar(AjBuildConfig buildConfig) {
// omitting dev info
if (Version.text.equals(Version.DEVELOPMENT)) {
// in the development version we can't do this test usefully
// MessageUtil.info(holder, "running development version of aspectj compiler");
return null;
}
if (buildConfig == null || buildConfig.getFullClasspath() == null) return "no classpath specified";
String ret = null;
for (Iterator it = buildConfig.getFullClasspath().iterator(); it.hasNext(); ) {
File p = new File( (String)it.next() );
// pr112830, allow variations on aspectjrt.jar of the form aspectjrtXXXXXX.jar
if (p.isFile() && p.getName().startsWith("aspectjrt") && p.getName().endsWith(".jar")) {
try {
String version = null;
Manifest manifest = new JarFile(p).getManifest();
if (manifest == null) {
ret = "no manifest found in " + p.getAbsolutePath() +
", expected " + Version.text;
continue;
}
Attributes attr = manifest.getAttributes("org/aspectj/lang/");
if (null != attr) {
version = attr.getValue(Attributes.Name.IMPLEMENTATION_VERSION);
if (null != version) {
version = version.trim();
}
}
// assume that users of development aspectjrt.jar know what they're doing
if (Version.DEVELOPMENT.equals(version)) {
// MessageUtil.info(holder,
// "running with development version of aspectjrt.jar in " +
// p.getAbsolutePath());
return null;
} else if (!Version.text.equals(version)) {
ret = "bad version number found in " + p.getAbsolutePath() +
" expected " + Version.text + " found " + version;
continue;
}
} catch (IOException ioe) {
ret = "bad jar file found in " + p.getAbsolutePath() + " error: " + ioe;
}
return null; // this is the "OK" return value!
} else {
// might want to catch other classpath errors
}
}
if (ret != null) return ret; // last error found in potentially matching jars...
return "couldn't find aspectjrt.jar on classpath, checked: " + makeClasspathString(buildConfig);
}
public String toString() {
StringBuffer buf = new StringBuffer();
buf.append("AjBuildManager(");
buf.append(")");
return buf.toString();
}
public void setStructureModel(IHierarchy structureModel) {
this.structureModel = structureModel;
}
/**
* Returns null if there is no structure model
*/
public IHierarchy getStructureModel() {
return structureModel;
}
public IProgressListener getProgressListener() {
return progressListener;
}
public void setProgressListener(IProgressListener progressListener) {
this.progressListener = progressListener;
}
/* (non-Javadoc)
* @see org.aspectj.ajdt.internal.compiler.AjCompiler.IOutputClassFileNameProvider#getOutputClassFileName(char[])
*/
public String getOutputClassFileName(char[] eclipseClassFileName, CompilationResult result) {
String filename = new String(eclipseClassFileName);
filename = filename.replace('/', File.separatorChar) + ".class";
File destinationPath = buildConfig.getOutputDir();
String outFile;
if (destinationPath == null) {
outFile = new File(filename).getName();
outFile = new File(extractDestinationPathFromSourceFile(result), outFile).getPath();
} else {
outFile = new File(destinationPath, filename).getPath();
}
return outFile;
}
/* (non-Javadoc)
* @see org.eclipse.jdt.internal.compiler.ICompilerAdapterFactory#getAdapter(org.eclipse.jdt.internal.compiler.Compiler)
*/
public ICompilerAdapter getAdapter(org.aspectj.org.eclipse.jdt.internal.compiler.Compiler forCompiler) {
// complete compiler config and return a suitable adapter...
populateCompilerOptionsFromLintSettings(forCompiler);
AjProblemReporter pr =
new AjProblemReporter(DefaultErrorHandlingPolicies.proceedWithAllProblems(),
forCompiler.options, getProblemFactory());
forCompiler.problemReporter = pr;
AjLookupEnvironment le =
new AjLookupEnvironment(forCompiler, forCompiler.options, pr, environment);
EclipseFactory factory = new EclipseFactory(le,this);
le.factory = factory;
pr.factory = factory;
forCompiler.lookupEnvironment = le;
forCompiler.parser =
new Parser(
pr,
forCompiler.options.parseLiteralExpressionsAsConstants);
return new AjCompilerAdapter(forCompiler,batchCompile,getBcelWorld(),getWeaver(),
factory,
getInterimResultRequestor(),
progressListener,
this, // IOutputFilenameProvider
this, // IBinarySourceProvider
state.getBinarySourceMap(),
buildConfig.isTerminateAfterCompilation(),
buildConfig.getProceedOnError(),
buildConfig.isNoAtAspectJAnnotationProcessing(),
state);
}
/**
* Some AspectJ lint options need to be known about in the compiler. This is
* how we pass them over...
* @param forCompiler
*/
private void populateCompilerOptionsFromLintSettings(org.aspectj.org.eclipse.jdt.internal.compiler.Compiler forCompiler) {
BcelWorld world = this.state.getBcelWorld();
IMessage.Kind swallowedExceptionKind = world.getLint().swallowedExceptionInCatchBlock.getKind();
Map optionsMap = new HashMap();
optionsMap.put(CompilerOptions.OPTION_ReportSwallowedExceptionInCatchBlock,
swallowedExceptionKind == null ? "ignore" : swallowedExceptionKind.toString());
forCompiler.options.set(optionsMap);
}
/* (non-Javadoc)
* @see org.aspectj.ajdt.internal.compiler.IBinarySourceProvider#getBinarySourcesForThisWeave()
*/
public Map getBinarySourcesForThisWeave() {
return binarySourcesForTheNextCompile;
}
public static AsmHierarchyBuilder getAsmHierarchyBuilder() {
return asmHierarchyBuilder;
}
/**
* Override the the default hierarchy builder.
*/
public static void setAsmHierarchyBuilder(AsmHierarchyBuilder newBuilder) {
asmHierarchyBuilder = newBuilder;
}
public AjState getState() {
return state;
}
public void setState(AjState buildState) {
state = buildState;
}
private static class AjBuildContexFormatter implements ContextFormatter {
public String formatEntry(int phaseId, Object data) {
StringBuffer sb = new StringBuffer();
if (phaseId == CompilationAndWeavingContext.BATCH_BUILD) {
sb.append("batch building ");
} else {
sb.append("incrementally building ");
}
AjBuildConfig config = (AjBuildConfig) data;
List classpath = config.getClasspath();
sb.append("with classpath: ");
for (Iterator iter = classpath.iterator(); iter.hasNext();) {
sb.append(iter.next().toString());
sb.append(File.pathSeparator);
}
return sb.toString();
}
}
}
|
145,086 |
Bug 145086 NPE when weak reference set in signature
|
Simon ran into the same problem in setting the values. I will attach a patch to fix this, with test cases to properly verify it works in both cases. java.lang.NullPointerException at org.aspectj.runtime.reflect.SignatureImpl$CacheImpl.set(SignatureImpl.java:224) at org.aspectj.runtime.reflect.SignatureImpl.toString(SignatureImpl.java:57) at org.aspectj.runtime.reflect.SignatureImpl.toString(SignatureImpl.java:62)
|
resolved fixed
|
f821ca3
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-06-03T08:27:06Z | 2006-06-02T14:53:20Z |
runtime/src/org/aspectj/runtime/reflect/SignatureImpl.java
|
/* *******************************************************************
* Copyright (c) 1999-2001 Xerox Corporation,
* 2002 Palo Alto Research Center, Incorporated (PARC).
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Eclipse Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Xerox/PARC initial implementation
* ******************************************************************/
package org.aspectj.runtime.reflect;
import org.aspectj.lang.Signature;
import java.util.StringTokenizer;
abstract class SignatureImpl implements Signature {
private static boolean useCache = true;
int modifiers = -1;
String name;
String declaringTypeName;
Class declaringType;
Cache stringCache;
SignatureImpl(int modifiers, String name, Class declaringType) {
this.modifiers = modifiers;
this.name = name;
this.declaringType = declaringType;
}
protected abstract String createToString (StringMaker sm);
/* Use a soft cache for the short, middle and long String representations */
String toString (StringMaker sm) {
String result = null;
if (useCache) {
if (stringCache == null) {
try {
stringCache = new CacheImpl();
} catch (Throwable t) {
useCache = false;
}
} else {
result = stringCache.get(sm.cacheOffset);
}
}
if (result == null) {
result = createToString(sm);
}
if (useCache) {
stringCache.set(sm.cacheOffset, result);
}
return result;
}
public final String toString() { return toString(StringMaker.middleStringMaker); }
public final String toShortString() { return toString(StringMaker.shortStringMaker); }
public final String toLongString() { return toString(StringMaker.longStringMaker); }
public int getModifiers() {
if (modifiers == -1) modifiers = extractInt(0);
return modifiers;
}
public String getName() {
if (name == null) name = extractString(1);
return name;
}
public Class getDeclaringType() {
if (declaringType == null) declaringType = extractType(2);
return declaringType;
}
public String getDeclaringTypeName() {
if (declaringTypeName == null) {
declaringTypeName = getDeclaringType().getName();
}
return declaringTypeName;
}
String fullTypeName(Class type) {
if (type == null) return "ANONYMOUS";
if (type.isArray()) return fullTypeName(type.getComponentType()) + "[]";
return type.getName().replace('$', '.');
}
String stripPackageName(String name) {
int dot = name.lastIndexOf('.');
if (dot == -1) return name;
return name.substring(dot+1);
}
String shortTypeName(Class type) {
if (type == null) return "ANONYMOUS";
if (type.isArray()) return shortTypeName(type.getComponentType()) + "[]";
return stripPackageName(type.getName()).replace('$', '.');
}
void addFullTypeNames(StringBuffer buf, Class[] types) {
for (int i = 0; i < types.length; i++) {
if (i > 0) buf.append(", ");
buf.append(fullTypeName(types[i]));
}
}
void addShortTypeNames(StringBuffer buf, Class[] types) {
for (int i = 0; i < types.length; i++) {
if (i > 0) buf.append(", ");
buf.append(shortTypeName(types[i]));
}
}
void addTypeArray(StringBuffer buf, Class[] types) {
addFullTypeNames(buf, types);
}
// lazy version
private String stringRep;
ClassLoader lookupClassLoader = null;
public void setLookupClassLoader(ClassLoader loader) {
this.lookupClassLoader = loader;
}
private ClassLoader getLookupClassLoader() {
if (lookupClassLoader == null) lookupClassLoader = this.getClass().getClassLoader();
return lookupClassLoader;
}
public SignatureImpl(String stringRep) {
this.stringRep = stringRep;
}
static final char SEP = '-';
String extractString(int n) {
//System.out.println(n + ": from " + stringRep);
int startIndex = 0;
int endIndex = stringRep.indexOf(SEP);
while (n-- > 0) {
startIndex = endIndex+1;
endIndex = stringRep.indexOf(SEP, startIndex);
}
if (endIndex == -1) endIndex = stringRep.length();
//System.out.println(" " + stringRep.substring(startIndex, endIndex));
return stringRep.substring(startIndex, endIndex);
}
int extractInt(int n) {
String s = extractString(n);
return Integer.parseInt(s, 16);
}
Class extractType(int n) {
String s = extractString(n);
return Factory.makeClass(s,getLookupClassLoader());
}
static String[] EMPTY_STRING_ARRAY = new String[0];
static Class[] EMPTY_CLASS_ARRAY = new Class[0];
static final String INNER_SEP = ":";
String[] extractStrings(int n) {
String s = extractString(n);
StringTokenizer st = new StringTokenizer(s, INNER_SEP);
final int N = st.countTokens();
String[] ret = new String[N];
for (int i = 0; i < N; i++) ret[i]= st.nextToken();
return ret;
}
Class[] extractTypes(int n) {
String s = extractString(n);
StringTokenizer st = new StringTokenizer(s, INNER_SEP);
final int N = st.countTokens();
Class[] ret = new Class[N];
for (int i = 0; i < N; i++) ret[i]= Factory.makeClass(st.nextToken(),getLookupClassLoader());
return ret;
}
/*
* Used for testing
*/
static void setUseCache (boolean b) {
useCache = b;
}
static boolean getUseCache () {
return useCache;
}
private static interface Cache {
String get(int cacheOffset);
void set(int cacheOffset, String result);
}
// separate implementation so we don't need SoftReference to hold the field...
private static final class CacheImpl implements Cache {
private java.lang.ref.SoftReference toStringCacheRef;
public CacheImpl() {
toStringCacheRef = new java.lang.ref.SoftReference(new String[3]);
}
public String get(int cacheOffset) {
String[] cachedArray = array();
if (cachedArray == null) {
return null;
}
return cachedArray[cacheOffset];
}
public void set(int cacheOffset, String result) {
array()[cacheOffset] = result;
}
private String[] array() {
return (String[])toStringCacheRef.get();
}
}
}
|
145,086 |
Bug 145086 NPE when weak reference set in signature
|
Simon ran into the same problem in setting the values. I will attach a patch to fix this, with test cases to properly verify it works in both cases. java.lang.NullPointerException at org.aspectj.runtime.reflect.SignatureImpl$CacheImpl.set(SignatureImpl.java:224) at org.aspectj.runtime.reflect.SignatureImpl.toString(SignatureImpl.java:57) at org.aspectj.runtime.reflect.SignatureImpl.toString(SignatureImpl.java:62)
|
resolved fixed
|
f821ca3
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-06-03T08:27:06Z | 2006-06-02T14:53:20Z |
runtime/testsrc/org/aspectj/runtime/reflect/JoinPointImplTest.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.runtime.reflect;
import junit.framework.TestCase;
/**
* @author colyer
*
* TODO To change the template for this generated type comment go to
* Window - Preferences - Java - Code Style - Code Templates
*/
public class JoinPointImplTest extends TestCase {
public void testGetArgs() {
String arg1 = "abc";
StringBuffer arg2 = new StringBuffer("def");
Object arg3 = new Object();
Object[] args = new Object[] { arg1, arg2, arg3 };
JoinPointImpl jpi = new JoinPointImpl(null,null,null,args);
Object[] retrievedArgs = jpi.getArgs();
assertEquals("First arg unchanged",arg1,retrievedArgs[0]);
assertEquals("Second arg unchanged",arg2,retrievedArgs[1]);
assertEquals("Third arg unchanged",arg3,retrievedArgs[2]);
retrievedArgs[0] = "xyz";
((StringBuffer)retrievedArgs[1]).append("ghi");
retrievedArgs[2] = "jkl";
Object[] afterUpdateArgs = jpi.getArgs();
assertEquals("Object reference not changed",arg1,afterUpdateArgs[0]);
assertEquals("Object reference unchanged",arg2,afterUpdateArgs[1]);
assertEquals("state of referenced object updated","defghi",afterUpdateArgs[1].toString());
assertEquals("Object reference not changed",arg3,afterUpdateArgs[2]);
}
}
|
145,086 |
Bug 145086 NPE when weak reference set in signature
|
Simon ran into the same problem in setting the values. I will attach a patch to fix this, with test cases to properly verify it works in both cases. java.lang.NullPointerException at org.aspectj.runtime.reflect.SignatureImpl$CacheImpl.set(SignatureImpl.java:224) at org.aspectj.runtime.reflect.SignatureImpl.toString(SignatureImpl.java:57) at org.aspectj.runtime.reflect.SignatureImpl.toString(SignatureImpl.java:62)
|
resolved fixed
|
f821ca3
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-06-03T08:27:06Z | 2006-06-02T14:53:20Z |
runtime/testsrc/org/aspectj/runtime/reflect/SignatureTest.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.runtime.reflect;
import junit.framework.TestCase;
/**
*/
public class SignatureTest extends TestCase {
public void testGetDeclaringTypeName() {
FieldSignatureImpl fsi = new FieldSignatureImpl(0,"x",SignatureTest.class,String.class);
assertEquals(SignatureTest.class.getName(),fsi.getDeclaringTypeName());
assertSame(fsi.getDeclaringTypeName(),fsi.getDeclaringTypeName()); // should be cached.
}
public void testToShortMiddleLongString () {
MethodSignatureImpl msi = new MethodSignatureImpl(0,"test",SignatureTest.class,new Class[] { String.class, Integer.TYPE }, new String[] { "s", "i" }, new Class[] {}, Runnable.class);
String shortString = msi.toShortString();
assertSame(shortString,msi.toShortString()); // should be cached.
String middleString = msi.toString();
assertSame(middleString,msi.toString()); // should be cached.
String longString = msi.toLongString();
assertSame(longString,msi.toLongString()); // should be cached.
assertTrue("String representations should be different",!(shortString.equals(middleString) || middleString.equals(longString) || longString.equals(shortString)));
}
}
|
145,322 |
Bug 145322 Failure of testCompareSubclassDelegates() on J9 1.5.0 SR1
| null |
resolved fixed
|
3e0650d
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-06-06T08:40:16Z | 2006-06-05T12:20:00Z |
weaver/testsrc/org/aspectj/weaver/reflect/ReflectionBasedReferenceTypeDelegateTest.java
|
/* *******************************************************************
* Copyright (c) 2005 Contributors.
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Eclipse Public License v1.0
* which accompanies this distribution and is available at
* http://eclipse.org/legal/epl-v10.html
*
* Contributors:
* Adrian Colyer Initial implementation
* ******************************************************************/
package org.aspectj.weaver.reflect;
import java.util.HashSet;
import java.util.Set;
import junit.framework.TestCase;
import org.aspectj.bridge.IMessageHandler;
import org.aspectj.weaver.ReferenceType;
import org.aspectj.weaver.ResolvedMember;
import org.aspectj.weaver.ResolvedType;
import org.aspectj.weaver.UnresolvedType;
import org.aspectj.weaver.bcel.BcelWorld;
public class ReflectionBasedReferenceTypeDelegateTest extends TestCase {
protected ReflectionWorld world;
private ResolvedType objectType;
private ResolvedType classType;
public void testIsAspect() {
assertFalse(objectType.isAspect());
}
public void testIsAnnotationStyleAspect() {
assertFalse(objectType.isAnnotationStyleAspect());
}
public void testIsInterface() {
assertFalse(objectType.isInterface());
assertTrue(world.resolve("java.io.Serializable").isInterface());
}
public void testIsEnum() {
assertFalse(objectType.isEnum());
}
public void testIsAnnotation() {
assertFalse(objectType.isAnnotation());
}
public void testIsAnnotationWithRuntimeRetention() {
assertFalse(objectType.isAnnotationWithRuntimeRetention());
}
public void testIsClass() {
assertTrue(objectType.isClass());
assertFalse(world.resolve("java.io.Serializable").isClass());
}
public void testIsGeneric() {
assertFalse(objectType.isGenericType());
}
public void testIsExposedToWeaver() {
assertFalse(objectType.isExposedToWeaver());
}
public void testHasAnnotation() {
assertFalse(objectType.hasAnnotation(UnresolvedType.forName("Foo")));
}
public void testGetAnnotations() {
assertEquals("no entries",0,objectType.getAnnotations().length);
}
public void testGetAnnotationTypes() {
assertEquals("no entries",0,objectType.getAnnotationTypes().length);
}
public void testGetTypeVariables() {
assertEquals("no entries",0,objectType.getTypeVariables().length);
}
public void testGetPerClause() {
assertNull(objectType.getPerClause());
}
public void testGetModifiers() {
assertEquals(Object.class.getModifiers(),objectType.getModifiers());
}
public void testGetSuperclass() {
assertTrue("Superclass of object should be null, but it is: "+objectType.getSuperclass(),objectType.getSuperclass()==null);
assertEquals(objectType,world.resolve("java.lang.Class").getSuperclass());
ResolvedType d = world.resolve("reflect.tests.D");
assertEquals(world.resolve("reflect.tests.C"),d.getSuperclass());
}
protected int findMethod(String name, ResolvedMember[] methods) {
for (int i=0; i<methods.length; i++) {
if (name.equals(methods[i].getName())) {
return i;
}
}
return -1;
}
protected int findMethod(String name, int numArgs, ResolvedMember[] methods) {
for (int i=0; i<methods.length; i++) {
if (name.equals(methods[i].getName()) && (methods[i].getParameterTypes().length == numArgs)) {
return i;
}
}
return -1;
}
public void testGetDeclaredMethods() {
ResolvedMember[] methods = objectType.getDeclaredMethods();
assertEquals(Object.class.getDeclaredMethods().length + Object.class.getDeclaredConstructors().length, methods.length);
ResolvedType c = world.resolve("reflect.tests.C");
methods = c.getDeclaredMethods();
assertEquals(3,methods.length);
int idx = findMethod("foo", methods);
assertTrue(idx > -1);
assertEquals(world.resolve("java.lang.String"),methods[idx].getReturnType());
assertEquals(1, methods[idx].getParameterTypes().length);
assertEquals(objectType,methods[idx].getParameterTypes()[0]);
assertEquals(1,methods[idx].getExceptions().length);
assertEquals(world.resolve("java.lang.Exception"),methods[idx].getExceptions()[0]);
int baridx = findMethod("bar", methods);
int initidx = findMethod("<init>", methods);
assertTrue(baridx > -1);
assertTrue(initidx > -1);
assertTrue(baridx != initidx && baridx != idx && idx <= 2 && initidx <= 2 && baridx <= 2);
ResolvedType d = world.resolve("reflect.tests.D");
methods = d.getDeclaredMethods();
assertEquals(2,methods.length);
classType = world.resolve("java.lang.Class");
methods = classType.getDeclaredMethods();
assertEquals(Class.class.getDeclaredMethods().length + Class.class.getDeclaredConstructors().length, methods.length);
}
public void testGetDeclaredFields() {
ResolvedMember[] fields = objectType.getDeclaredFields();
assertEquals(0,fields.length);
ResolvedType c = world.resolve("reflect.tests.C");
fields = c.getDeclaredFields();
assertEquals(2,fields.length);
assertEquals("f",fields[0].getName());
assertEquals("s",fields[1].getName());
assertEquals(ResolvedType.INT,fields[0].getReturnType());
assertEquals(world.resolve("java.lang.String"),fields[1].getReturnType());
}
public void testGetDeclaredInterfaces() {
ResolvedType[] interfaces = objectType.getDeclaredInterfaces();
assertEquals(0,interfaces.length);
ResolvedType d = world.resolve("reflect.tests.D");
interfaces = d.getDeclaredInterfaces();
assertEquals(1,interfaces.length);
assertEquals(world.resolve("java.io.Serializable"),interfaces[0]);
}
public void testGetDeclaredPointcuts() {
ResolvedMember[] pointcuts = objectType.getDeclaredPointcuts();
assertEquals(0,pointcuts.length);
}
public void testSerializableSuperclass() {
ResolvedType serializableType = world.resolve("java.io.Serializable");
ResolvedType superType = serializableType.getSuperclass();
assertTrue("Superclass of serializable should be Object but was "+superType,superType.equals(UnresolvedType.OBJECT));
BcelWorld bcelworld = new BcelWorld();
bcelworld.setBehaveInJava5Way(true);
ResolvedType bcelSupertype = bcelworld.resolve(UnresolvedType.SERIALIZABLE).getSuperclass();
assertTrue("Should be null but is "+bcelSupertype,bcelSupertype.equals(UnresolvedType.OBJECT));
}
public void testSubinterfaceSuperclass() {
ResolvedType ifaceType = world.resolve("java.security.Key");
ResolvedType superType = ifaceType.getSuperclass();
assertTrue("Superclass should be Object but was "+superType,superType.equals(UnresolvedType.OBJECT));
BcelWorld bcelworld = new BcelWorld();
bcelworld.setBehaveInJava5Way(true);
ResolvedType bcelSupertype = bcelworld.resolve("java.security.Key").getSuperclass();
assertTrue("Should be null but is "+bcelSupertype,bcelSupertype.equals(UnresolvedType.OBJECT));
}
public void testVoidSuperclass() {
ResolvedType voidType = world.resolve(Void.TYPE);
ResolvedType superType = voidType.getSuperclass();
assertNull(superType);
BcelWorld bcelworld = new BcelWorld();
bcelworld.setBehaveInJava5Way(true);
ResolvedType bcelSupertype = bcelworld.resolve("void").getSuperclass();
assertTrue("Should be null but is "+bcelSupertype,bcelSupertype==null);
}
public void testIntSuperclass() {
ResolvedType voidType = world.resolve(Integer.TYPE);
ResolvedType superType = voidType.getSuperclass();
assertNull(superType);
BcelWorld bcelworld = new BcelWorld();
bcelworld.setBehaveInJava5Way(true);
ResolvedType bcelSupertype = bcelworld.resolve("int").getSuperclass();
assertTrue("Should be null but is "+bcelSupertype,bcelSupertype==null);
}
public void testGenericInterfaceSuperclass_BcelWorldResolution() {
BcelWorld bcelworld = new BcelWorld();
bcelworld.setBehaveInJava5Way(true);
UnresolvedType javaUtilMap = UnresolvedType.forName("java.util.Map");
ReferenceType rawType = (ReferenceType) bcelworld.resolve(javaUtilMap);
assertTrue("Should be the raw type ?!? "+rawType.getTypekind(),rawType.isRawType());
ReferenceType genericType = (ReferenceType)rawType.getGenericType();
assertTrue("Should be the generic type ?!? "+genericType.getTypekind(),genericType.isGenericType());
ResolvedType rt = rawType.getSuperclass();
assertTrue("Superclass for Map raw type should be Object but was "+rt,rt.equals(UnresolvedType.OBJECT));
ResolvedType rt2 = genericType.getSuperclass();
assertTrue("Superclass for Map generic type should be Object but was "+rt2,rt2.equals(UnresolvedType.OBJECT));
}
// FIXME asc maybe. The reflection list of methods returned doesn't include <clinit> (the static initializer) ... is that really a problem.
public void testCompareSubclassDelegates() {
boolean barfIfClinitMissing = false;
world.setBehaveInJava5Way(true);
BcelWorld bcelWorld = new BcelWorld(getClass().getClassLoader(),IMessageHandler.THROW,null);
bcelWorld.setBehaveInJava5Way(true);
UnresolvedType javaUtilHashMap = UnresolvedType.forName("java.util.HashMap");
ReferenceType rawType =(ReferenceType)bcelWorld.resolve(javaUtilHashMap );
ReferenceType rawReflectType =(ReferenceType)world.resolve(javaUtilHashMap );
ResolvedMember[] rms1 = rawType.getDelegate().getDeclaredMethods();
ResolvedMember[] rms2 = rawReflectType.getDelegate().getDeclaredMethods();
StringBuffer errors = new StringBuffer();
Set one = new HashSet();
for (int i = 0; i < rms1.length; i++) {
one.add(rms1[i].toString());
}
Set two = new HashSet();
for (int i = 0; i < rms2.length; i++) {
two.add(rms2[i].toString());
}
for (int i = 0;i<rms2.length;i++) {
if (!one.contains(rms2[i].toString())) {
errors.append("Couldn't find "+rms2[i].toString()+" in the bcel set\n");
}
}
for (int i = 0;i<rms1.length;i++) {
if (!two.contains(rms1[i].toString())) {
if (!barfIfClinitMissing && rms1[i].getName().equals("<clinit>")) continue;
errors.append("Couldn't find "+rms1[i].toString()+" in the reflection set\n");
}
}
assertTrue("Errors:"+errors.toString(),errors.length()==0);
if (barfIfClinitMissing) {
// the numbers must be exact
assertEquals(rms1.length,rms2.length);
} else {
// the numbers can be out by one in favour of bcel
assertTrue("Should be one extra (clinit) in BCEL case, but bcel="+rms1.length+" reflect="+rms2.length,rms1.length==rms2.length+1);
}
}
// todo: array of int
protected void setUp() throws Exception {
world = new ReflectionWorld(getClass().getClassLoader());
objectType = world.resolve("java.lang.Object");
}
}
|
122,580 |
Bug 122580 Fix & Bug: Circularity Failure for Verbose Loading on JRockit 1.4.2_08 Agent
|
Here is a stack trace I am getting when I try to use AspectJ 1.5.0 final release's load-time weaving with JRockIt 1.4.2_08 using -Xmanagement:class=org.aspectj.weaver.loadtime.JRockitAgent to load Weblogic Server 8.1 SP2. I debugged the code in Eclipse and discovered that the weaver was being initialized while loading IMessage$Kind, so the JRockIt VM simply hasn't run staticinitialization yet, making IMessage.INFO null. I was able to fix this stack trace by hoisting the check for loading AspectJ code up BEFORE initializing a weaving adaptor i.e., changing line 55 of Aj.java to be if (loader == null || className == null || className.startsWith("org/aspectj/")) { I then commented out line 251 of WeavingAdaptor to avoid a duplicate check: private boolean shouldWeaveName (String name) { return !((/*(name.startsWith("org.apache.bcel.")||//FIXME AV why ? bcel is wrapped in org.aspectj. name.startsWith("org.aspectj.")||*/ // now checked earlier, to avoid circularity issues in initialization name.startsWith("java.") || name.startsWith("javax.")) //|| name.startsWith("$Proxy")//JDK proxies//FIXME AV is that 1.3 proxy ? fe. ataspect.$Proxy0 is a java5 proxy... || name.startsWith("sun.reflect."));//JDK reflect } Note that this bug does NOT occur when using a JRockIt 1.5.0 VM, even with the -Xmanagement command line argument. Stack Trace: java.lang.IllegalArgumentException: null kind at org.aspectj.bridge.Message.<init>(Ljava/lang/String;Ljava/lang/String;Lorg/aspectj/bridge/IMessage$Kind;Lorg/aspectj/bridge/ISourceLocation;Ljava/lang/Throwable;[Lorg/aspectj/bridge/ISourceLocation;ZIII)V(Message.java:89) at org.aspectj.bridge.Message.<init>(Ljava/lang/String;Ljava/lang/String;Lorg/aspectj/bridge/IMessage$Kind;Lorg/aspectj/bridge/ISourceLocation;Ljava/lang/Throwable;[Lorg/aspectj/bridge/ISourceLocation;)V(Message.java:67) at org.aspectj.bridge.Message.<init>(Ljava/lang/String;Lorg/aspectj/bridge/IMessage$Kind;Ljava/lang/Throwable;Lorg/aspectj/bridge/ISourceLocation;)V(Message.java:110) at org.aspectj.bridge.MessageUtil.info(Ljava/lang/String;)Lorg/aspectj/bridge/IMessage;(MessageUtil.java:211) at org.aspectj.bridge.MessageUtil.info(Lorg/aspectj/bridge/IMessageHandler;Ljava/lang/String;)Z(MessageUtil.java:98) at org.aspectj.weaver.tools.WeavingAdaptor.info(Ljava/lang/String;)Z(WeavingAdaptor.java:343) at org.aspectj.weaver.tools.WeavingAdaptor.createMessageHandler()V(WeavingAdaptor.java:168) at org.aspectj.weaver.tools.WeavingAdaptor.<init>()V(WeavingAdaptor.java:80) at org.aspectj.weaver.loadtime.ClassLoaderWeavingAdaptor.<init>(Ljava/lang/ClassLoader;Lorg/aspectj/weaver/loadtime/IWeavingContext;)V(ClassLoaderWeavingAdaptor.java:70) at org.aspectj.weaver.loadtime.Aj$WeaverContainer.getWeaver(Ljava/lang/ClassLoader;Lorg/aspectj/weaver/loadtime/IWeavingContext;)Lorg/aspectj/weaver/tools/WeavingAdaptor;(Aj.java:94) at org.aspectj.weaver.loadtime.Aj.preProcess(Ljava/lang/String;[BLjava/lang/ClassLoader;)[B(Aj.java:61) at org.aspectj.weaver.loadtime.JRockitAgent.preProcess(Ljava/lang/ClassLoader;Ljava/lang/String;[B)[B(JRockitAgent.java:74) at jrockit.vm.ClassPreProcessorManager.notifyClassPreProcessor(ILjava/lang/String;[B)[B(Unknown Source) at jrockit.vm.Classes.defineClass0(ILjava/lang/String;[BII)I(Unknown Source) at jrockit.vm.Classes.defineClass(Ljava/lang/ClassLoader;Ljava/lang/String;[BII)Ljava/lang/Class;(Unknown Source) at java.lang.ClassLoader.defineClass(Ljava/lang/String;[BIILjava/security/ProtectionDomain;)Ljava/lang/Class;(Unknown Source) at java.security.SecureClassLoader.defineClass(Ljava/lang/String;[BIILjava/security/CodeSource;)Ljava/lang/Class;(SecureClassLoader.java:123) at java.net.URLClassLoader.defineClass(Ljava/lang/String;Lsun/misc/Resource;)Ljava/lang/Class;(URLClassLoader.java:251) at java.net.URLClassLoader.access$100(Ljava/net/URLClassLoader;Ljava/lang/String;Lsun/misc/Resource;)Ljava/lang/Class;(URLClassLoader.java:55) at java.net.URLClassLoader$1.run()Ljava/lang/Object;(URLClassLoader.java:194) at jrockit.vm.AccessController.do_privileged_exc(Ljava/security/PrivilegedExceptionAction;Ljava/security/AccessControlContext;I)Ljava/lang/Object;(Unknown Source) at jrockit.vm.AccessController.doPrivileged(Ljava/security/PrivilegedExceptionAction;Ljava/security/AccessControlContext;)Ljava/lang/Object;(Unknown Source) at java.net.URLClassLoader.findClass(Ljava/lang/String;)Ljava/lang/Class;(URLClassLoader.java:187) at java.lang.ClassLoader.loadClass(Ljava/lang/String;Z)Ljava/lang/Class;(Unknown Source) at sun.misc.Launcher$AppClassLoader.loadClass(Ljava/lang/String;Z)Ljava/lang/Class;(Launcher.java:274) at java.lang.ClassLoader.loadClass(Ljava/lang/String;)Ljava/lang/Class;(Unknown Source) at java.lang.ClassLoader.loadClassFromNative(II)Ljava/lang/Class;(Unknown Source) at jrockit.vm.RNI.getRunnableCode(I)I(Unknown Source) at jrockit.vm.RNI.trampoline()V(Unknown Source) at org.aspectj.bridge.MessageUtil.info(Ljava/lang/String;)Lorg/aspectj/bridge/IMessage;(MessageUtil.java:???) at org.aspectj.bridge.MessageUtil.info(Lorg/aspectj/bridge/IMessageHandler;Ljava/lang/String;)Z(MessageUtil.java:98) at org.aspectj.weaver.tools.WeavingAdaptor.info(Ljava/lang/String;)Z(WeavingAdaptor.java:343) java.lang.IllegalArgumentException: null kind at org.aspectj.bridge.Message.<init>(Ljava/lang/String;Ljava/lang/String;Lorg/aspectj/bridge/IMessage$Kind;Lorg/aspectj/bridge/ISourceLocation;Ljava/lang/Throwable;[Lorg/aspectj/bridge/ISourceLocation;ZIII)V(Message.java:89) at org.aspectj.bridge.Message.<init>(Ljava/lang/String;Ljava/lang/String;Lorg/aspectj/bridge/IMessage$Kind;Lorg/aspectj/bridge/ISourceLocation;Ljava/lang/Throwable;[Lorg/aspectj/bridge/ISourceLocation;)V(Message.java:67) at org.aspectj.bridge.Message.<init>(Ljava/lang/String;Lorg/aspectj/bridge/IMessage$Kind;Ljava/lang/Throwable;Lorg/aspectj/bridge/ISourceLocation;)V(Message.java:110) at org.aspectj.bridge.MessageUtil.info(Ljava/lang/String;)Lorg/aspectj/bridge/IMessage;(MessageUtil.java:211) at org.aspectj.bridge.MessageUtil.info(Lorg/aspectj/bridge/IMessageHandler;Ljava/lang/String;)Z(MessageUtil.java:98) at org.aspectj.weaver.tools.WeavingAdaptor.info(Ljava/lang/String;)Z(WeavingAdaptor.java:343) at org.aspectj.weaver.tools.WeavingAdaptor.createMessageHandler()V(WeavingAdaptor.java:168) at org.aspectj.weaver.tools.WeavingAdaptor.<init>()V(WeavingAdaptor.java:80) at org.aspectj.weaver.loadtime.ClassLoaderWeavingAdaptor.<init>(Ljava/lang/ClassLoader;Lorg/aspectj/weaver/loadtime/IWeavingContext;)V(ClassLoaderWeavingAdaptor.java:70) at org.aspectj.weaver.loadtime.Aj$WeaverContainer.getWeaver(Ljava/lang/ClassLoader;Lorg/aspectj/weaver/loadtime/IWeavingContext;)Lorg/aspectj/weaver/tools/WeavingAdaptor;(Aj.java:94) at org.aspectj.weaver.loadtime.Aj.preProcess(Ljava/lang/String;[BLjava/lang/ClassLoader;)[B(Aj.java:61) at org.aspectj.weaver.loadtime.JRockitAgent.preProcess(Ljava/lang/ClassLoader;Ljava/lang/String;[B)[B(JRockitAgent.java:74) at jrockit.vm.ClassPreProcessorManager.notifyClassPreProcessor(ILjava/lang/String;[B)[B(Unknown Source) at jrockit.vm.Classes.defineClass0(ILjava/lang/String;[BII)I(Unknown Source) at jrockit.vm.Classes.defineClass(Ljava/lang/ClassLoader;Ljava/lang/String;[BII)Ljava/lang/Class;(Unknown Source) at java.lang.ClassLoader.defineClass(Ljava/lang/String;[BIILjava/security/ProtectionDomain;)Ljava/lang/Class;(Unknown Source) at java.security.SecureClassLoader.defineClass(Ljava/lang/String;[BIILjava/security/CodeSource;)Ljava/lang/Class;(SecureClassLoader.java:123) at java.net.URLClassLoader.defineClass(Ljava/lang/String;Lsun/misc/Resource;)Ljava/lang/Class;(URLClassLoader.java:251) at java.net.URLClassLoader.access$100(Ljava/net/URLClassLoader;Ljava/lang/String;Lsun/misc/Resource;)Ljava/lang/Class;(URLClassLoader.java:55) at java.net.URLClassLoader$1.run()Ljava/lang/Object;(URLClassLoader.java:194) at jrockit.vm.AccessController.do_privileged_exc(Ljava/security/PrivilegedExceptionAction;Ljava/security/AccessControlContext;I)Ljava/lang/Object;(Unknown Source) at jrockit.vm.AccessController.doPrivileged(Ljava/security/PrivilegedExceptionAction;Ljava/security/AccessControlContext;)Ljava/lang/Object;(Unknown Source) at java.net.URLClassLoader.findClass(Ljava/lang/String;)Ljava/lang/Class;(URLClassLoader.java:187) at java.lang.ClassLoader.loadClass(Ljava/lang/String;Z)Ljava/lang/Class;(Unknown Source) at sun.misc.Launcher$AppClassLoader.loadClass(Ljava/lang/String;Z)Ljava/lang/Class;(Launcher.java:274) at java.lang.ClassLoader.loadClass(Ljava/lang/String;)Ljava/lang/Class;(Unknown Source) at java.lang.ClassLoader.loadClassFromNative(II)Ljava/lang/Class;(Unknown Source) at jrockit.vm.RNI.getRunnableCode(I)I(Unknown Source) at jrockit.vm.RNI.trampoline()V(Unknown Source) at org.aspectj.bridge.MessageUtil.info(Lorg/aspectj/bridge/IMessageHandler;Ljava/lang/String;)Z(MessageUtil.java:???) at org.aspectj.weaver.tools.WeavingAdaptor.info(Ljava/lang/String;)Z(WeavingAdaptor.java:343) at org.aspectj.weaver.tools.WeavingAdaptor.createMessageHandler()V(WeavingAdaptor.java:168)
|
resolved fixed
|
75afb31
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-06-09T10:56:50Z | 2006-01-04T02:00:00Z |
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.util.Map;
import java.util.WeakHashMap;
import org.aspectj.weaver.tools.WeavingAdaptor;
/**
* 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 Aj(){
this(null);
}
public Aj(IWeavingContext context){
weavingContext = context;
}
/**
* Initialization
*/
public void initialize() {
;
}
/**
* Weave
*
* @param className
* @param bytes
* @param loader
* @return weaved bytes
*/
public byte[] preProcess(String className, byte[] bytes, ClassLoader loader) {
//TODO AV needs to doc that
if (loader == null || className == null) {
// skip boot loader or null classes (hibernate)
return bytes;
}
try {
WeavingAdaptor weavingAdaptor = WeaverContainer.getWeaver(loader, weavingContext);
if (weavingAdaptor == null) {
return bytes;
}
return weavingAdaptor.weaveClass(className, bytes);
} catch (Throwable t) {
//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()
t.printStackTrace();
return bytes;
}
}
/**
* Cache of weaver
* There is one weaver per classloader
*/
static class WeaverContainer {
private static Map weavingAdaptors = new WeakHashMap();
static WeavingAdaptor getWeaver(ClassLoader loader, IWeavingContext weavingContext) {
ExplicitlyInitializedClassLoaderWeavingAdaptor adaptor = null;
synchronized(weavingAdaptors) {
adaptor = (ExplicitlyInitializedClassLoaderWeavingAdaptor) weavingAdaptors.get(loader);
if (adaptor == null) {
String loaderClassName = loader.getClass().getName();
if (loaderClassName.equals("sun.reflect.DelegatingClassLoader")) {
// we don't weave reflection generated types at all!
return null;
} else {
// create it and put it back in the weavingAdaptors map but avoid any kind of instantiation
// within the synchronized block
ClassLoaderWeavingAdaptor weavingAdaptor = new ClassLoaderWeavingAdaptor(loader, weavingContext);
adaptor = new ExplicitlyInitializedClassLoaderWeavingAdaptor(weavingAdaptor);
weavingAdaptors.put(loader, adaptor);
}
}
}
// perform the initialization
return adaptor.getWeavingAdaptor(loader, weavingContext);
// old version
// synchronized(loader) {//FIXME AV - temp fix for #99861
// synchronized (weavingAdaptors) {
// WeavingAdaptor weavingAdaptor = (WeavingAdaptor) weavingAdaptors.get(loader);
// if (weavingAdaptor == null) {
// weavingAdaptor = new ClassLoaderWeavingAdaptor(loader, weavingContext);
// weavingAdaptors.put(loader, weavingAdaptor);
// }
// return weavingAdaptor;
// }
// }
}
}
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)).generatedClassesExist();
}
public void flushGeneratedClasses(ClassLoader loader){
((ClassLoaderWeavingAdaptor)WeaverContainer.getWeaver(loader, weavingContext)).flushGeneratedClasses();
}
}
|
122,580 |
Bug 122580 Fix & Bug: Circularity Failure for Verbose Loading on JRockit 1.4.2_08 Agent
|
Here is a stack trace I am getting when I try to use AspectJ 1.5.0 final release's load-time weaving with JRockIt 1.4.2_08 using -Xmanagement:class=org.aspectj.weaver.loadtime.JRockitAgent to load Weblogic Server 8.1 SP2. I debugged the code in Eclipse and discovered that the weaver was being initialized while loading IMessage$Kind, so the JRockIt VM simply hasn't run staticinitialization yet, making IMessage.INFO null. I was able to fix this stack trace by hoisting the check for loading AspectJ code up BEFORE initializing a weaving adaptor i.e., changing line 55 of Aj.java to be if (loader == null || className == null || className.startsWith("org/aspectj/")) { I then commented out line 251 of WeavingAdaptor to avoid a duplicate check: private boolean shouldWeaveName (String name) { return !((/*(name.startsWith("org.apache.bcel.")||//FIXME AV why ? bcel is wrapped in org.aspectj. name.startsWith("org.aspectj.")||*/ // now checked earlier, to avoid circularity issues in initialization name.startsWith("java.") || name.startsWith("javax.")) //|| name.startsWith("$Proxy")//JDK proxies//FIXME AV is that 1.3 proxy ? fe. ataspect.$Proxy0 is a java5 proxy... || name.startsWith("sun.reflect."));//JDK reflect } Note that this bug does NOT occur when using a JRockIt 1.5.0 VM, even with the -Xmanagement command line argument. Stack Trace: java.lang.IllegalArgumentException: null kind at org.aspectj.bridge.Message.<init>(Ljava/lang/String;Ljava/lang/String;Lorg/aspectj/bridge/IMessage$Kind;Lorg/aspectj/bridge/ISourceLocation;Ljava/lang/Throwable;[Lorg/aspectj/bridge/ISourceLocation;ZIII)V(Message.java:89) at org.aspectj.bridge.Message.<init>(Ljava/lang/String;Ljava/lang/String;Lorg/aspectj/bridge/IMessage$Kind;Lorg/aspectj/bridge/ISourceLocation;Ljava/lang/Throwable;[Lorg/aspectj/bridge/ISourceLocation;)V(Message.java:67) at org.aspectj.bridge.Message.<init>(Ljava/lang/String;Lorg/aspectj/bridge/IMessage$Kind;Ljava/lang/Throwable;Lorg/aspectj/bridge/ISourceLocation;)V(Message.java:110) at org.aspectj.bridge.MessageUtil.info(Ljava/lang/String;)Lorg/aspectj/bridge/IMessage;(MessageUtil.java:211) at org.aspectj.bridge.MessageUtil.info(Lorg/aspectj/bridge/IMessageHandler;Ljava/lang/String;)Z(MessageUtil.java:98) at org.aspectj.weaver.tools.WeavingAdaptor.info(Ljava/lang/String;)Z(WeavingAdaptor.java:343) at org.aspectj.weaver.tools.WeavingAdaptor.createMessageHandler()V(WeavingAdaptor.java:168) at org.aspectj.weaver.tools.WeavingAdaptor.<init>()V(WeavingAdaptor.java:80) at org.aspectj.weaver.loadtime.ClassLoaderWeavingAdaptor.<init>(Ljava/lang/ClassLoader;Lorg/aspectj/weaver/loadtime/IWeavingContext;)V(ClassLoaderWeavingAdaptor.java:70) at org.aspectj.weaver.loadtime.Aj$WeaverContainer.getWeaver(Ljava/lang/ClassLoader;Lorg/aspectj/weaver/loadtime/IWeavingContext;)Lorg/aspectj/weaver/tools/WeavingAdaptor;(Aj.java:94) at org.aspectj.weaver.loadtime.Aj.preProcess(Ljava/lang/String;[BLjava/lang/ClassLoader;)[B(Aj.java:61) at org.aspectj.weaver.loadtime.JRockitAgent.preProcess(Ljava/lang/ClassLoader;Ljava/lang/String;[B)[B(JRockitAgent.java:74) at jrockit.vm.ClassPreProcessorManager.notifyClassPreProcessor(ILjava/lang/String;[B)[B(Unknown Source) at jrockit.vm.Classes.defineClass0(ILjava/lang/String;[BII)I(Unknown Source) at jrockit.vm.Classes.defineClass(Ljava/lang/ClassLoader;Ljava/lang/String;[BII)Ljava/lang/Class;(Unknown Source) at java.lang.ClassLoader.defineClass(Ljava/lang/String;[BIILjava/security/ProtectionDomain;)Ljava/lang/Class;(Unknown Source) at java.security.SecureClassLoader.defineClass(Ljava/lang/String;[BIILjava/security/CodeSource;)Ljava/lang/Class;(SecureClassLoader.java:123) at java.net.URLClassLoader.defineClass(Ljava/lang/String;Lsun/misc/Resource;)Ljava/lang/Class;(URLClassLoader.java:251) at java.net.URLClassLoader.access$100(Ljava/net/URLClassLoader;Ljava/lang/String;Lsun/misc/Resource;)Ljava/lang/Class;(URLClassLoader.java:55) at java.net.URLClassLoader$1.run()Ljava/lang/Object;(URLClassLoader.java:194) at jrockit.vm.AccessController.do_privileged_exc(Ljava/security/PrivilegedExceptionAction;Ljava/security/AccessControlContext;I)Ljava/lang/Object;(Unknown Source) at jrockit.vm.AccessController.doPrivileged(Ljava/security/PrivilegedExceptionAction;Ljava/security/AccessControlContext;)Ljava/lang/Object;(Unknown Source) at java.net.URLClassLoader.findClass(Ljava/lang/String;)Ljava/lang/Class;(URLClassLoader.java:187) at java.lang.ClassLoader.loadClass(Ljava/lang/String;Z)Ljava/lang/Class;(Unknown Source) at sun.misc.Launcher$AppClassLoader.loadClass(Ljava/lang/String;Z)Ljava/lang/Class;(Launcher.java:274) at java.lang.ClassLoader.loadClass(Ljava/lang/String;)Ljava/lang/Class;(Unknown Source) at java.lang.ClassLoader.loadClassFromNative(II)Ljava/lang/Class;(Unknown Source) at jrockit.vm.RNI.getRunnableCode(I)I(Unknown Source) at jrockit.vm.RNI.trampoline()V(Unknown Source) at org.aspectj.bridge.MessageUtil.info(Ljava/lang/String;)Lorg/aspectj/bridge/IMessage;(MessageUtil.java:???) at org.aspectj.bridge.MessageUtil.info(Lorg/aspectj/bridge/IMessageHandler;Ljava/lang/String;)Z(MessageUtil.java:98) at org.aspectj.weaver.tools.WeavingAdaptor.info(Ljava/lang/String;)Z(WeavingAdaptor.java:343) java.lang.IllegalArgumentException: null kind at org.aspectj.bridge.Message.<init>(Ljava/lang/String;Ljava/lang/String;Lorg/aspectj/bridge/IMessage$Kind;Lorg/aspectj/bridge/ISourceLocation;Ljava/lang/Throwable;[Lorg/aspectj/bridge/ISourceLocation;ZIII)V(Message.java:89) at org.aspectj.bridge.Message.<init>(Ljava/lang/String;Ljava/lang/String;Lorg/aspectj/bridge/IMessage$Kind;Lorg/aspectj/bridge/ISourceLocation;Ljava/lang/Throwable;[Lorg/aspectj/bridge/ISourceLocation;)V(Message.java:67) at org.aspectj.bridge.Message.<init>(Ljava/lang/String;Lorg/aspectj/bridge/IMessage$Kind;Ljava/lang/Throwable;Lorg/aspectj/bridge/ISourceLocation;)V(Message.java:110) at org.aspectj.bridge.MessageUtil.info(Ljava/lang/String;)Lorg/aspectj/bridge/IMessage;(MessageUtil.java:211) at org.aspectj.bridge.MessageUtil.info(Lorg/aspectj/bridge/IMessageHandler;Ljava/lang/String;)Z(MessageUtil.java:98) at org.aspectj.weaver.tools.WeavingAdaptor.info(Ljava/lang/String;)Z(WeavingAdaptor.java:343) at org.aspectj.weaver.tools.WeavingAdaptor.createMessageHandler()V(WeavingAdaptor.java:168) at org.aspectj.weaver.tools.WeavingAdaptor.<init>()V(WeavingAdaptor.java:80) at org.aspectj.weaver.loadtime.ClassLoaderWeavingAdaptor.<init>(Ljava/lang/ClassLoader;Lorg/aspectj/weaver/loadtime/IWeavingContext;)V(ClassLoaderWeavingAdaptor.java:70) at org.aspectj.weaver.loadtime.Aj$WeaverContainer.getWeaver(Ljava/lang/ClassLoader;Lorg/aspectj/weaver/loadtime/IWeavingContext;)Lorg/aspectj/weaver/tools/WeavingAdaptor;(Aj.java:94) at org.aspectj.weaver.loadtime.Aj.preProcess(Ljava/lang/String;[BLjava/lang/ClassLoader;)[B(Aj.java:61) at org.aspectj.weaver.loadtime.JRockitAgent.preProcess(Ljava/lang/ClassLoader;Ljava/lang/String;[B)[B(JRockitAgent.java:74) at jrockit.vm.ClassPreProcessorManager.notifyClassPreProcessor(ILjava/lang/String;[B)[B(Unknown Source) at jrockit.vm.Classes.defineClass0(ILjava/lang/String;[BII)I(Unknown Source) at jrockit.vm.Classes.defineClass(Ljava/lang/ClassLoader;Ljava/lang/String;[BII)Ljava/lang/Class;(Unknown Source) at java.lang.ClassLoader.defineClass(Ljava/lang/String;[BIILjava/security/ProtectionDomain;)Ljava/lang/Class;(Unknown Source) at java.security.SecureClassLoader.defineClass(Ljava/lang/String;[BIILjava/security/CodeSource;)Ljava/lang/Class;(SecureClassLoader.java:123) at java.net.URLClassLoader.defineClass(Ljava/lang/String;Lsun/misc/Resource;)Ljava/lang/Class;(URLClassLoader.java:251) at java.net.URLClassLoader.access$100(Ljava/net/URLClassLoader;Ljava/lang/String;Lsun/misc/Resource;)Ljava/lang/Class;(URLClassLoader.java:55) at java.net.URLClassLoader$1.run()Ljava/lang/Object;(URLClassLoader.java:194) at jrockit.vm.AccessController.do_privileged_exc(Ljava/security/PrivilegedExceptionAction;Ljava/security/AccessControlContext;I)Ljava/lang/Object;(Unknown Source) at jrockit.vm.AccessController.doPrivileged(Ljava/security/PrivilegedExceptionAction;Ljava/security/AccessControlContext;)Ljava/lang/Object;(Unknown Source) at java.net.URLClassLoader.findClass(Ljava/lang/String;)Ljava/lang/Class;(URLClassLoader.java:187) at java.lang.ClassLoader.loadClass(Ljava/lang/String;Z)Ljava/lang/Class;(Unknown Source) at sun.misc.Launcher$AppClassLoader.loadClass(Ljava/lang/String;Z)Ljava/lang/Class;(Launcher.java:274) at java.lang.ClassLoader.loadClass(Ljava/lang/String;)Ljava/lang/Class;(Unknown Source) at java.lang.ClassLoader.loadClassFromNative(II)Ljava/lang/Class;(Unknown Source) at jrockit.vm.RNI.getRunnableCode(I)I(Unknown Source) at jrockit.vm.RNI.trampoline()V(Unknown Source) at org.aspectj.bridge.MessageUtil.info(Lorg/aspectj/bridge/IMessageHandler;Ljava/lang/String;)Z(MessageUtil.java:???) at org.aspectj.weaver.tools.WeavingAdaptor.info(Ljava/lang/String;)Z(WeavingAdaptor.java:343) at org.aspectj.weaver.tools.WeavingAdaptor.createMessageHandler()V(WeavingAdaptor.java:168)
|
resolved fixed
|
75afb31
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-06-09T10:56:50Z | 2006-01-04T02:00:00Z |
loadtime/src/org/aspectj/weaver/loadtime/JRockitAgent.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 (derivative from AspectWerkz)
*******************************************************************************/
package org.aspectj.weaver.loadtime;
import com.bea.jvm.JVMFactory;
import com.jrockit.management.rmp.RmpSocketListener;
/**
* JRockit (tested with 7SP4 and 8.1) preprocessor Adapter based on JMAPI <p/>JRockit has a low
* level API for hooking ClassPreProcessor, allowing the use of online weaving at full speed.
* Moreover, JRockit does not allow java.lang.ClassLoader overriding thru -Xbootclasspath/p option.
* <p/>The ClassPreProcessor
* implementation and all third party jars CAN reside in the standard classpath. <p/>The command
* line will look like:
* <code>"%JAVA_COMMAND%" -Xmanagement:class=org.aspectj.weaver.loadtime.JRockitAgent -cp ...</code>
* Note: there can be some NoClassDefFoundError due to classpath limitation - as described in
* http://edocs.bea.com/wls/docs81/adminguide/winservice.html <p/>In order to use the BEA JRockit
* management server (for further connection of management console or runtime analyzer), the regular
* option -Xmanagement will not have any effect prior to JRockit 8.1 SP2. Instead, use <code>-Dmanagement</code>.
*
* @author <a href="mailto:alex AT gnilux DOT com">Alexandre Vasseur</a>
*/
public class JRockitAgent implements com.bea.jvm.ClassPreProcessor {
/**
* Concrete preprocessor
*/
private final static ClassPreProcessor s_preProcessor;
private static boolean START_RMP_SERVER = false;
static {
START_RMP_SERVER = System.getProperties().containsKey("management");
try {
s_preProcessor = new Aj();
s_preProcessor.initialize();
} catch (Exception e) {
throw new ExceptionInInitializerError("could not initialize JRockitAgent preprocessor due to: " + e.toString());
}
}
/**
* The JMAPI ClassPreProcessor must be self registrating
*/
public JRockitAgent() {
if (START_RMP_SERVER) {
// the management server will be spawned in a new thread
/*RmpSocketListener management = */new RmpSocketListener();
}
JVMFactory.getJVM().getClassLibrary().setClassPreProcessor(this);
}
/**
* Weave a class
*
* @param caller classloader
* @param name of the class to weave
* @param bytecode original
* @return bytecode weaved
*/
public byte[] preProcess(ClassLoader caller, String name, byte[] bytecode) {
if (caller == null || caller.getParent() == null) {
return bytecode;
} else {
return s_preProcessor.preProcess(name, bytecode, caller);
}
}
}
|
122,580 |
Bug 122580 Fix & Bug: Circularity Failure for Verbose Loading on JRockit 1.4.2_08 Agent
|
Here is a stack trace I am getting when I try to use AspectJ 1.5.0 final release's load-time weaving with JRockIt 1.4.2_08 using -Xmanagement:class=org.aspectj.weaver.loadtime.JRockitAgent to load Weblogic Server 8.1 SP2. I debugged the code in Eclipse and discovered that the weaver was being initialized while loading IMessage$Kind, so the JRockIt VM simply hasn't run staticinitialization yet, making IMessage.INFO null. I was able to fix this stack trace by hoisting the check for loading AspectJ code up BEFORE initializing a weaving adaptor i.e., changing line 55 of Aj.java to be if (loader == null || className == null || className.startsWith("org/aspectj/")) { I then commented out line 251 of WeavingAdaptor to avoid a duplicate check: private boolean shouldWeaveName (String name) { return !((/*(name.startsWith("org.apache.bcel.")||//FIXME AV why ? bcel is wrapped in org.aspectj. name.startsWith("org.aspectj.")||*/ // now checked earlier, to avoid circularity issues in initialization name.startsWith("java.") || name.startsWith("javax.")) //|| name.startsWith("$Proxy")//JDK proxies//FIXME AV is that 1.3 proxy ? fe. ataspect.$Proxy0 is a java5 proxy... || name.startsWith("sun.reflect."));//JDK reflect } Note that this bug does NOT occur when using a JRockIt 1.5.0 VM, even with the -Xmanagement command line argument. Stack Trace: java.lang.IllegalArgumentException: null kind at org.aspectj.bridge.Message.<init>(Ljava/lang/String;Ljava/lang/String;Lorg/aspectj/bridge/IMessage$Kind;Lorg/aspectj/bridge/ISourceLocation;Ljava/lang/Throwable;[Lorg/aspectj/bridge/ISourceLocation;ZIII)V(Message.java:89) at org.aspectj.bridge.Message.<init>(Ljava/lang/String;Ljava/lang/String;Lorg/aspectj/bridge/IMessage$Kind;Lorg/aspectj/bridge/ISourceLocation;Ljava/lang/Throwable;[Lorg/aspectj/bridge/ISourceLocation;)V(Message.java:67) at org.aspectj.bridge.Message.<init>(Ljava/lang/String;Lorg/aspectj/bridge/IMessage$Kind;Ljava/lang/Throwable;Lorg/aspectj/bridge/ISourceLocation;)V(Message.java:110) at org.aspectj.bridge.MessageUtil.info(Ljava/lang/String;)Lorg/aspectj/bridge/IMessage;(MessageUtil.java:211) at org.aspectj.bridge.MessageUtil.info(Lorg/aspectj/bridge/IMessageHandler;Ljava/lang/String;)Z(MessageUtil.java:98) at org.aspectj.weaver.tools.WeavingAdaptor.info(Ljava/lang/String;)Z(WeavingAdaptor.java:343) at org.aspectj.weaver.tools.WeavingAdaptor.createMessageHandler()V(WeavingAdaptor.java:168) at org.aspectj.weaver.tools.WeavingAdaptor.<init>()V(WeavingAdaptor.java:80) at org.aspectj.weaver.loadtime.ClassLoaderWeavingAdaptor.<init>(Ljava/lang/ClassLoader;Lorg/aspectj/weaver/loadtime/IWeavingContext;)V(ClassLoaderWeavingAdaptor.java:70) at org.aspectj.weaver.loadtime.Aj$WeaverContainer.getWeaver(Ljava/lang/ClassLoader;Lorg/aspectj/weaver/loadtime/IWeavingContext;)Lorg/aspectj/weaver/tools/WeavingAdaptor;(Aj.java:94) at org.aspectj.weaver.loadtime.Aj.preProcess(Ljava/lang/String;[BLjava/lang/ClassLoader;)[B(Aj.java:61) at org.aspectj.weaver.loadtime.JRockitAgent.preProcess(Ljava/lang/ClassLoader;Ljava/lang/String;[B)[B(JRockitAgent.java:74) at jrockit.vm.ClassPreProcessorManager.notifyClassPreProcessor(ILjava/lang/String;[B)[B(Unknown Source) at jrockit.vm.Classes.defineClass0(ILjava/lang/String;[BII)I(Unknown Source) at jrockit.vm.Classes.defineClass(Ljava/lang/ClassLoader;Ljava/lang/String;[BII)Ljava/lang/Class;(Unknown Source) at java.lang.ClassLoader.defineClass(Ljava/lang/String;[BIILjava/security/ProtectionDomain;)Ljava/lang/Class;(Unknown Source) at java.security.SecureClassLoader.defineClass(Ljava/lang/String;[BIILjava/security/CodeSource;)Ljava/lang/Class;(SecureClassLoader.java:123) at java.net.URLClassLoader.defineClass(Ljava/lang/String;Lsun/misc/Resource;)Ljava/lang/Class;(URLClassLoader.java:251) at java.net.URLClassLoader.access$100(Ljava/net/URLClassLoader;Ljava/lang/String;Lsun/misc/Resource;)Ljava/lang/Class;(URLClassLoader.java:55) at java.net.URLClassLoader$1.run()Ljava/lang/Object;(URLClassLoader.java:194) at jrockit.vm.AccessController.do_privileged_exc(Ljava/security/PrivilegedExceptionAction;Ljava/security/AccessControlContext;I)Ljava/lang/Object;(Unknown Source) at jrockit.vm.AccessController.doPrivileged(Ljava/security/PrivilegedExceptionAction;Ljava/security/AccessControlContext;)Ljava/lang/Object;(Unknown Source) at java.net.URLClassLoader.findClass(Ljava/lang/String;)Ljava/lang/Class;(URLClassLoader.java:187) at java.lang.ClassLoader.loadClass(Ljava/lang/String;Z)Ljava/lang/Class;(Unknown Source) at sun.misc.Launcher$AppClassLoader.loadClass(Ljava/lang/String;Z)Ljava/lang/Class;(Launcher.java:274) at java.lang.ClassLoader.loadClass(Ljava/lang/String;)Ljava/lang/Class;(Unknown Source) at java.lang.ClassLoader.loadClassFromNative(II)Ljava/lang/Class;(Unknown Source) at jrockit.vm.RNI.getRunnableCode(I)I(Unknown Source) at jrockit.vm.RNI.trampoline()V(Unknown Source) at org.aspectj.bridge.MessageUtil.info(Ljava/lang/String;)Lorg/aspectj/bridge/IMessage;(MessageUtil.java:???) at org.aspectj.bridge.MessageUtil.info(Lorg/aspectj/bridge/IMessageHandler;Ljava/lang/String;)Z(MessageUtil.java:98) at org.aspectj.weaver.tools.WeavingAdaptor.info(Ljava/lang/String;)Z(WeavingAdaptor.java:343) java.lang.IllegalArgumentException: null kind at org.aspectj.bridge.Message.<init>(Ljava/lang/String;Ljava/lang/String;Lorg/aspectj/bridge/IMessage$Kind;Lorg/aspectj/bridge/ISourceLocation;Ljava/lang/Throwable;[Lorg/aspectj/bridge/ISourceLocation;ZIII)V(Message.java:89) at org.aspectj.bridge.Message.<init>(Ljava/lang/String;Ljava/lang/String;Lorg/aspectj/bridge/IMessage$Kind;Lorg/aspectj/bridge/ISourceLocation;Ljava/lang/Throwable;[Lorg/aspectj/bridge/ISourceLocation;)V(Message.java:67) at org.aspectj.bridge.Message.<init>(Ljava/lang/String;Lorg/aspectj/bridge/IMessage$Kind;Ljava/lang/Throwable;Lorg/aspectj/bridge/ISourceLocation;)V(Message.java:110) at org.aspectj.bridge.MessageUtil.info(Ljava/lang/String;)Lorg/aspectj/bridge/IMessage;(MessageUtil.java:211) at org.aspectj.bridge.MessageUtil.info(Lorg/aspectj/bridge/IMessageHandler;Ljava/lang/String;)Z(MessageUtil.java:98) at org.aspectj.weaver.tools.WeavingAdaptor.info(Ljava/lang/String;)Z(WeavingAdaptor.java:343) at org.aspectj.weaver.tools.WeavingAdaptor.createMessageHandler()V(WeavingAdaptor.java:168) at org.aspectj.weaver.tools.WeavingAdaptor.<init>()V(WeavingAdaptor.java:80) at org.aspectj.weaver.loadtime.ClassLoaderWeavingAdaptor.<init>(Ljava/lang/ClassLoader;Lorg/aspectj/weaver/loadtime/IWeavingContext;)V(ClassLoaderWeavingAdaptor.java:70) at org.aspectj.weaver.loadtime.Aj$WeaverContainer.getWeaver(Ljava/lang/ClassLoader;Lorg/aspectj/weaver/loadtime/IWeavingContext;)Lorg/aspectj/weaver/tools/WeavingAdaptor;(Aj.java:94) at org.aspectj.weaver.loadtime.Aj.preProcess(Ljava/lang/String;[BLjava/lang/ClassLoader;)[B(Aj.java:61) at org.aspectj.weaver.loadtime.JRockitAgent.preProcess(Ljava/lang/ClassLoader;Ljava/lang/String;[B)[B(JRockitAgent.java:74) at jrockit.vm.ClassPreProcessorManager.notifyClassPreProcessor(ILjava/lang/String;[B)[B(Unknown Source) at jrockit.vm.Classes.defineClass0(ILjava/lang/String;[BII)I(Unknown Source) at jrockit.vm.Classes.defineClass(Ljava/lang/ClassLoader;Ljava/lang/String;[BII)Ljava/lang/Class;(Unknown Source) at java.lang.ClassLoader.defineClass(Ljava/lang/String;[BIILjava/security/ProtectionDomain;)Ljava/lang/Class;(Unknown Source) at java.security.SecureClassLoader.defineClass(Ljava/lang/String;[BIILjava/security/CodeSource;)Ljava/lang/Class;(SecureClassLoader.java:123) at java.net.URLClassLoader.defineClass(Ljava/lang/String;Lsun/misc/Resource;)Ljava/lang/Class;(URLClassLoader.java:251) at java.net.URLClassLoader.access$100(Ljava/net/URLClassLoader;Ljava/lang/String;Lsun/misc/Resource;)Ljava/lang/Class;(URLClassLoader.java:55) at java.net.URLClassLoader$1.run()Ljava/lang/Object;(URLClassLoader.java:194) at jrockit.vm.AccessController.do_privileged_exc(Ljava/security/PrivilegedExceptionAction;Ljava/security/AccessControlContext;I)Ljava/lang/Object;(Unknown Source) at jrockit.vm.AccessController.doPrivileged(Ljava/security/PrivilegedExceptionAction;Ljava/security/AccessControlContext;)Ljava/lang/Object;(Unknown Source) at java.net.URLClassLoader.findClass(Ljava/lang/String;)Ljava/lang/Class;(URLClassLoader.java:187) at java.lang.ClassLoader.loadClass(Ljava/lang/String;Z)Ljava/lang/Class;(Unknown Source) at sun.misc.Launcher$AppClassLoader.loadClass(Ljava/lang/String;Z)Ljava/lang/Class;(Launcher.java:274) at java.lang.ClassLoader.loadClass(Ljava/lang/String;)Ljava/lang/Class;(Unknown Source) at java.lang.ClassLoader.loadClassFromNative(II)Ljava/lang/Class;(Unknown Source) at jrockit.vm.RNI.getRunnableCode(I)I(Unknown Source) at jrockit.vm.RNI.trampoline()V(Unknown Source) at org.aspectj.bridge.MessageUtil.info(Lorg/aspectj/bridge/IMessageHandler;Ljava/lang/String;)Z(MessageUtil.java:???) at org.aspectj.weaver.tools.WeavingAdaptor.info(Ljava/lang/String;)Z(WeavingAdaptor.java:343) at org.aspectj.weaver.tools.WeavingAdaptor.createMessageHandler()V(WeavingAdaptor.java:168)
|
resolved fixed
|
75afb31
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-06-09T10:56:50Z | 2006-01-04T02:00:00Z |
loadtime/testsrc/LoadtimeModuleTests.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
*******************************************************************************/
import junit.framework.TestCase;
import junit.framework.Test;
import junit.framework.TestSuite;
import junit.textui.TestRunner;
import org.aspectj.weaver.loadtime.WeavingURLClassLoaderTest;
import org.aspectj.weaver.loadtime.test.DocumentParserTest;
/**
* @author <a href="mailto:alex AT gnilux DOT com">Alexandre Vasseur</a>
*/
public class LoadtimeModuleTests extends TestCase {
public static Test suite() {
TestSuite suite = new TestSuite(LoadtimeModuleTests.class.getName());
suite.addTestSuite(DocumentParserTest.class);
suite.addTestSuite(WeavingURLClassLoaderTest.class);
return suite;
}
public static void main(String args[]) throws Throwable {
TestRunner.run(suite());
}
}
|
122,580 |
Bug 122580 Fix & Bug: Circularity Failure for Verbose Loading on JRockit 1.4.2_08 Agent
|
Here is a stack trace I am getting when I try to use AspectJ 1.5.0 final release's load-time weaving with JRockIt 1.4.2_08 using -Xmanagement:class=org.aspectj.weaver.loadtime.JRockitAgent to load Weblogic Server 8.1 SP2. I debugged the code in Eclipse and discovered that the weaver was being initialized while loading IMessage$Kind, so the JRockIt VM simply hasn't run staticinitialization yet, making IMessage.INFO null. I was able to fix this stack trace by hoisting the check for loading AspectJ code up BEFORE initializing a weaving adaptor i.e., changing line 55 of Aj.java to be if (loader == null || className == null || className.startsWith("org/aspectj/")) { I then commented out line 251 of WeavingAdaptor to avoid a duplicate check: private boolean shouldWeaveName (String name) { return !((/*(name.startsWith("org.apache.bcel.")||//FIXME AV why ? bcel is wrapped in org.aspectj. name.startsWith("org.aspectj.")||*/ // now checked earlier, to avoid circularity issues in initialization name.startsWith("java.") || name.startsWith("javax.")) //|| name.startsWith("$Proxy")//JDK proxies//FIXME AV is that 1.3 proxy ? fe. ataspect.$Proxy0 is a java5 proxy... || name.startsWith("sun.reflect."));//JDK reflect } Note that this bug does NOT occur when using a JRockIt 1.5.0 VM, even with the -Xmanagement command line argument. Stack Trace: java.lang.IllegalArgumentException: null kind at org.aspectj.bridge.Message.<init>(Ljava/lang/String;Ljava/lang/String;Lorg/aspectj/bridge/IMessage$Kind;Lorg/aspectj/bridge/ISourceLocation;Ljava/lang/Throwable;[Lorg/aspectj/bridge/ISourceLocation;ZIII)V(Message.java:89) at org.aspectj.bridge.Message.<init>(Ljava/lang/String;Ljava/lang/String;Lorg/aspectj/bridge/IMessage$Kind;Lorg/aspectj/bridge/ISourceLocation;Ljava/lang/Throwable;[Lorg/aspectj/bridge/ISourceLocation;)V(Message.java:67) at org.aspectj.bridge.Message.<init>(Ljava/lang/String;Lorg/aspectj/bridge/IMessage$Kind;Ljava/lang/Throwable;Lorg/aspectj/bridge/ISourceLocation;)V(Message.java:110) at org.aspectj.bridge.MessageUtil.info(Ljava/lang/String;)Lorg/aspectj/bridge/IMessage;(MessageUtil.java:211) at org.aspectj.bridge.MessageUtil.info(Lorg/aspectj/bridge/IMessageHandler;Ljava/lang/String;)Z(MessageUtil.java:98) at org.aspectj.weaver.tools.WeavingAdaptor.info(Ljava/lang/String;)Z(WeavingAdaptor.java:343) at org.aspectj.weaver.tools.WeavingAdaptor.createMessageHandler()V(WeavingAdaptor.java:168) at org.aspectj.weaver.tools.WeavingAdaptor.<init>()V(WeavingAdaptor.java:80) at org.aspectj.weaver.loadtime.ClassLoaderWeavingAdaptor.<init>(Ljava/lang/ClassLoader;Lorg/aspectj/weaver/loadtime/IWeavingContext;)V(ClassLoaderWeavingAdaptor.java:70) at org.aspectj.weaver.loadtime.Aj$WeaverContainer.getWeaver(Ljava/lang/ClassLoader;Lorg/aspectj/weaver/loadtime/IWeavingContext;)Lorg/aspectj/weaver/tools/WeavingAdaptor;(Aj.java:94) at org.aspectj.weaver.loadtime.Aj.preProcess(Ljava/lang/String;[BLjava/lang/ClassLoader;)[B(Aj.java:61) at org.aspectj.weaver.loadtime.JRockitAgent.preProcess(Ljava/lang/ClassLoader;Ljava/lang/String;[B)[B(JRockitAgent.java:74) at jrockit.vm.ClassPreProcessorManager.notifyClassPreProcessor(ILjava/lang/String;[B)[B(Unknown Source) at jrockit.vm.Classes.defineClass0(ILjava/lang/String;[BII)I(Unknown Source) at jrockit.vm.Classes.defineClass(Ljava/lang/ClassLoader;Ljava/lang/String;[BII)Ljava/lang/Class;(Unknown Source) at java.lang.ClassLoader.defineClass(Ljava/lang/String;[BIILjava/security/ProtectionDomain;)Ljava/lang/Class;(Unknown Source) at java.security.SecureClassLoader.defineClass(Ljava/lang/String;[BIILjava/security/CodeSource;)Ljava/lang/Class;(SecureClassLoader.java:123) at java.net.URLClassLoader.defineClass(Ljava/lang/String;Lsun/misc/Resource;)Ljava/lang/Class;(URLClassLoader.java:251) at java.net.URLClassLoader.access$100(Ljava/net/URLClassLoader;Ljava/lang/String;Lsun/misc/Resource;)Ljava/lang/Class;(URLClassLoader.java:55) at java.net.URLClassLoader$1.run()Ljava/lang/Object;(URLClassLoader.java:194) at jrockit.vm.AccessController.do_privileged_exc(Ljava/security/PrivilegedExceptionAction;Ljava/security/AccessControlContext;I)Ljava/lang/Object;(Unknown Source) at jrockit.vm.AccessController.doPrivileged(Ljava/security/PrivilegedExceptionAction;Ljava/security/AccessControlContext;)Ljava/lang/Object;(Unknown Source) at java.net.URLClassLoader.findClass(Ljava/lang/String;)Ljava/lang/Class;(URLClassLoader.java:187) at java.lang.ClassLoader.loadClass(Ljava/lang/String;Z)Ljava/lang/Class;(Unknown Source) at sun.misc.Launcher$AppClassLoader.loadClass(Ljava/lang/String;Z)Ljava/lang/Class;(Launcher.java:274) at java.lang.ClassLoader.loadClass(Ljava/lang/String;)Ljava/lang/Class;(Unknown Source) at java.lang.ClassLoader.loadClassFromNative(II)Ljava/lang/Class;(Unknown Source) at jrockit.vm.RNI.getRunnableCode(I)I(Unknown Source) at jrockit.vm.RNI.trampoline()V(Unknown Source) at org.aspectj.bridge.MessageUtil.info(Ljava/lang/String;)Lorg/aspectj/bridge/IMessage;(MessageUtil.java:???) at org.aspectj.bridge.MessageUtil.info(Lorg/aspectj/bridge/IMessageHandler;Ljava/lang/String;)Z(MessageUtil.java:98) at org.aspectj.weaver.tools.WeavingAdaptor.info(Ljava/lang/String;)Z(WeavingAdaptor.java:343) java.lang.IllegalArgumentException: null kind at org.aspectj.bridge.Message.<init>(Ljava/lang/String;Ljava/lang/String;Lorg/aspectj/bridge/IMessage$Kind;Lorg/aspectj/bridge/ISourceLocation;Ljava/lang/Throwable;[Lorg/aspectj/bridge/ISourceLocation;ZIII)V(Message.java:89) at org.aspectj.bridge.Message.<init>(Ljava/lang/String;Ljava/lang/String;Lorg/aspectj/bridge/IMessage$Kind;Lorg/aspectj/bridge/ISourceLocation;Ljava/lang/Throwable;[Lorg/aspectj/bridge/ISourceLocation;)V(Message.java:67) at org.aspectj.bridge.Message.<init>(Ljava/lang/String;Lorg/aspectj/bridge/IMessage$Kind;Ljava/lang/Throwable;Lorg/aspectj/bridge/ISourceLocation;)V(Message.java:110) at org.aspectj.bridge.MessageUtil.info(Ljava/lang/String;)Lorg/aspectj/bridge/IMessage;(MessageUtil.java:211) at org.aspectj.bridge.MessageUtil.info(Lorg/aspectj/bridge/IMessageHandler;Ljava/lang/String;)Z(MessageUtil.java:98) at org.aspectj.weaver.tools.WeavingAdaptor.info(Ljava/lang/String;)Z(WeavingAdaptor.java:343) at org.aspectj.weaver.tools.WeavingAdaptor.createMessageHandler()V(WeavingAdaptor.java:168) at org.aspectj.weaver.tools.WeavingAdaptor.<init>()V(WeavingAdaptor.java:80) at org.aspectj.weaver.loadtime.ClassLoaderWeavingAdaptor.<init>(Ljava/lang/ClassLoader;Lorg/aspectj/weaver/loadtime/IWeavingContext;)V(ClassLoaderWeavingAdaptor.java:70) at org.aspectj.weaver.loadtime.Aj$WeaverContainer.getWeaver(Ljava/lang/ClassLoader;Lorg/aspectj/weaver/loadtime/IWeavingContext;)Lorg/aspectj/weaver/tools/WeavingAdaptor;(Aj.java:94) at org.aspectj.weaver.loadtime.Aj.preProcess(Ljava/lang/String;[BLjava/lang/ClassLoader;)[B(Aj.java:61) at org.aspectj.weaver.loadtime.JRockitAgent.preProcess(Ljava/lang/ClassLoader;Ljava/lang/String;[B)[B(JRockitAgent.java:74) at jrockit.vm.ClassPreProcessorManager.notifyClassPreProcessor(ILjava/lang/String;[B)[B(Unknown Source) at jrockit.vm.Classes.defineClass0(ILjava/lang/String;[BII)I(Unknown Source) at jrockit.vm.Classes.defineClass(Ljava/lang/ClassLoader;Ljava/lang/String;[BII)Ljava/lang/Class;(Unknown Source) at java.lang.ClassLoader.defineClass(Ljava/lang/String;[BIILjava/security/ProtectionDomain;)Ljava/lang/Class;(Unknown Source) at java.security.SecureClassLoader.defineClass(Ljava/lang/String;[BIILjava/security/CodeSource;)Ljava/lang/Class;(SecureClassLoader.java:123) at java.net.URLClassLoader.defineClass(Ljava/lang/String;Lsun/misc/Resource;)Ljava/lang/Class;(URLClassLoader.java:251) at java.net.URLClassLoader.access$100(Ljava/net/URLClassLoader;Ljava/lang/String;Lsun/misc/Resource;)Ljava/lang/Class;(URLClassLoader.java:55) at java.net.URLClassLoader$1.run()Ljava/lang/Object;(URLClassLoader.java:194) at jrockit.vm.AccessController.do_privileged_exc(Ljava/security/PrivilegedExceptionAction;Ljava/security/AccessControlContext;I)Ljava/lang/Object;(Unknown Source) at jrockit.vm.AccessController.doPrivileged(Ljava/security/PrivilegedExceptionAction;Ljava/security/AccessControlContext;)Ljava/lang/Object;(Unknown Source) at java.net.URLClassLoader.findClass(Ljava/lang/String;)Ljava/lang/Class;(URLClassLoader.java:187) at java.lang.ClassLoader.loadClass(Ljava/lang/String;Z)Ljava/lang/Class;(Unknown Source) at sun.misc.Launcher$AppClassLoader.loadClass(Ljava/lang/String;Z)Ljava/lang/Class;(Launcher.java:274) at java.lang.ClassLoader.loadClass(Ljava/lang/String;)Ljava/lang/Class;(Unknown Source) at java.lang.ClassLoader.loadClassFromNative(II)Ljava/lang/Class;(Unknown Source) at jrockit.vm.RNI.getRunnableCode(I)I(Unknown Source) at jrockit.vm.RNI.trampoline()V(Unknown Source) at org.aspectj.bridge.MessageUtil.info(Lorg/aspectj/bridge/IMessageHandler;Ljava/lang/String;)Z(MessageUtil.java:???) at org.aspectj.weaver.tools.WeavingAdaptor.info(Ljava/lang/String;)Z(WeavingAdaptor.java:343) at org.aspectj.weaver.tools.WeavingAdaptor.createMessageHandler()V(WeavingAdaptor.java:168)
|
resolved fixed
|
75afb31
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-06-09T10:56:50Z | 2006-01-04T02:00:00Z |
loadtime/testsrc/org/aspectj/bea/jvm/ClassLibraryImpl.java
| |
122,580 |
Bug 122580 Fix & Bug: Circularity Failure for Verbose Loading on JRockit 1.4.2_08 Agent
|
Here is a stack trace I am getting when I try to use AspectJ 1.5.0 final release's load-time weaving with JRockIt 1.4.2_08 using -Xmanagement:class=org.aspectj.weaver.loadtime.JRockitAgent to load Weblogic Server 8.1 SP2. I debugged the code in Eclipse and discovered that the weaver was being initialized while loading IMessage$Kind, so the JRockIt VM simply hasn't run staticinitialization yet, making IMessage.INFO null. I was able to fix this stack trace by hoisting the check for loading AspectJ code up BEFORE initializing a weaving adaptor i.e., changing line 55 of Aj.java to be if (loader == null || className == null || className.startsWith("org/aspectj/")) { I then commented out line 251 of WeavingAdaptor to avoid a duplicate check: private boolean shouldWeaveName (String name) { return !((/*(name.startsWith("org.apache.bcel.")||//FIXME AV why ? bcel is wrapped in org.aspectj. name.startsWith("org.aspectj.")||*/ // now checked earlier, to avoid circularity issues in initialization name.startsWith("java.") || name.startsWith("javax.")) //|| name.startsWith("$Proxy")//JDK proxies//FIXME AV is that 1.3 proxy ? fe. ataspect.$Proxy0 is a java5 proxy... || name.startsWith("sun.reflect."));//JDK reflect } Note that this bug does NOT occur when using a JRockIt 1.5.0 VM, even with the -Xmanagement command line argument. Stack Trace: java.lang.IllegalArgumentException: null kind at org.aspectj.bridge.Message.<init>(Ljava/lang/String;Ljava/lang/String;Lorg/aspectj/bridge/IMessage$Kind;Lorg/aspectj/bridge/ISourceLocation;Ljava/lang/Throwable;[Lorg/aspectj/bridge/ISourceLocation;ZIII)V(Message.java:89) at org.aspectj.bridge.Message.<init>(Ljava/lang/String;Ljava/lang/String;Lorg/aspectj/bridge/IMessage$Kind;Lorg/aspectj/bridge/ISourceLocation;Ljava/lang/Throwable;[Lorg/aspectj/bridge/ISourceLocation;)V(Message.java:67) at org.aspectj.bridge.Message.<init>(Ljava/lang/String;Lorg/aspectj/bridge/IMessage$Kind;Ljava/lang/Throwable;Lorg/aspectj/bridge/ISourceLocation;)V(Message.java:110) at org.aspectj.bridge.MessageUtil.info(Ljava/lang/String;)Lorg/aspectj/bridge/IMessage;(MessageUtil.java:211) at org.aspectj.bridge.MessageUtil.info(Lorg/aspectj/bridge/IMessageHandler;Ljava/lang/String;)Z(MessageUtil.java:98) at org.aspectj.weaver.tools.WeavingAdaptor.info(Ljava/lang/String;)Z(WeavingAdaptor.java:343) at org.aspectj.weaver.tools.WeavingAdaptor.createMessageHandler()V(WeavingAdaptor.java:168) at org.aspectj.weaver.tools.WeavingAdaptor.<init>()V(WeavingAdaptor.java:80) at org.aspectj.weaver.loadtime.ClassLoaderWeavingAdaptor.<init>(Ljava/lang/ClassLoader;Lorg/aspectj/weaver/loadtime/IWeavingContext;)V(ClassLoaderWeavingAdaptor.java:70) at org.aspectj.weaver.loadtime.Aj$WeaverContainer.getWeaver(Ljava/lang/ClassLoader;Lorg/aspectj/weaver/loadtime/IWeavingContext;)Lorg/aspectj/weaver/tools/WeavingAdaptor;(Aj.java:94) at org.aspectj.weaver.loadtime.Aj.preProcess(Ljava/lang/String;[BLjava/lang/ClassLoader;)[B(Aj.java:61) at org.aspectj.weaver.loadtime.JRockitAgent.preProcess(Ljava/lang/ClassLoader;Ljava/lang/String;[B)[B(JRockitAgent.java:74) at jrockit.vm.ClassPreProcessorManager.notifyClassPreProcessor(ILjava/lang/String;[B)[B(Unknown Source) at jrockit.vm.Classes.defineClass0(ILjava/lang/String;[BII)I(Unknown Source) at jrockit.vm.Classes.defineClass(Ljava/lang/ClassLoader;Ljava/lang/String;[BII)Ljava/lang/Class;(Unknown Source) at java.lang.ClassLoader.defineClass(Ljava/lang/String;[BIILjava/security/ProtectionDomain;)Ljava/lang/Class;(Unknown Source) at java.security.SecureClassLoader.defineClass(Ljava/lang/String;[BIILjava/security/CodeSource;)Ljava/lang/Class;(SecureClassLoader.java:123) at java.net.URLClassLoader.defineClass(Ljava/lang/String;Lsun/misc/Resource;)Ljava/lang/Class;(URLClassLoader.java:251) at java.net.URLClassLoader.access$100(Ljava/net/URLClassLoader;Ljava/lang/String;Lsun/misc/Resource;)Ljava/lang/Class;(URLClassLoader.java:55) at java.net.URLClassLoader$1.run()Ljava/lang/Object;(URLClassLoader.java:194) at jrockit.vm.AccessController.do_privileged_exc(Ljava/security/PrivilegedExceptionAction;Ljava/security/AccessControlContext;I)Ljava/lang/Object;(Unknown Source) at jrockit.vm.AccessController.doPrivileged(Ljava/security/PrivilegedExceptionAction;Ljava/security/AccessControlContext;)Ljava/lang/Object;(Unknown Source) at java.net.URLClassLoader.findClass(Ljava/lang/String;)Ljava/lang/Class;(URLClassLoader.java:187) at java.lang.ClassLoader.loadClass(Ljava/lang/String;Z)Ljava/lang/Class;(Unknown Source) at sun.misc.Launcher$AppClassLoader.loadClass(Ljava/lang/String;Z)Ljava/lang/Class;(Launcher.java:274) at java.lang.ClassLoader.loadClass(Ljava/lang/String;)Ljava/lang/Class;(Unknown Source) at java.lang.ClassLoader.loadClassFromNative(II)Ljava/lang/Class;(Unknown Source) at jrockit.vm.RNI.getRunnableCode(I)I(Unknown Source) at jrockit.vm.RNI.trampoline()V(Unknown Source) at org.aspectj.bridge.MessageUtil.info(Ljava/lang/String;)Lorg/aspectj/bridge/IMessage;(MessageUtil.java:???) at org.aspectj.bridge.MessageUtil.info(Lorg/aspectj/bridge/IMessageHandler;Ljava/lang/String;)Z(MessageUtil.java:98) at org.aspectj.weaver.tools.WeavingAdaptor.info(Ljava/lang/String;)Z(WeavingAdaptor.java:343) java.lang.IllegalArgumentException: null kind at org.aspectj.bridge.Message.<init>(Ljava/lang/String;Ljava/lang/String;Lorg/aspectj/bridge/IMessage$Kind;Lorg/aspectj/bridge/ISourceLocation;Ljava/lang/Throwable;[Lorg/aspectj/bridge/ISourceLocation;ZIII)V(Message.java:89) at org.aspectj.bridge.Message.<init>(Ljava/lang/String;Ljava/lang/String;Lorg/aspectj/bridge/IMessage$Kind;Lorg/aspectj/bridge/ISourceLocation;Ljava/lang/Throwable;[Lorg/aspectj/bridge/ISourceLocation;)V(Message.java:67) at org.aspectj.bridge.Message.<init>(Ljava/lang/String;Lorg/aspectj/bridge/IMessage$Kind;Ljava/lang/Throwable;Lorg/aspectj/bridge/ISourceLocation;)V(Message.java:110) at org.aspectj.bridge.MessageUtil.info(Ljava/lang/String;)Lorg/aspectj/bridge/IMessage;(MessageUtil.java:211) at org.aspectj.bridge.MessageUtil.info(Lorg/aspectj/bridge/IMessageHandler;Ljava/lang/String;)Z(MessageUtil.java:98) at org.aspectj.weaver.tools.WeavingAdaptor.info(Ljava/lang/String;)Z(WeavingAdaptor.java:343) at org.aspectj.weaver.tools.WeavingAdaptor.createMessageHandler()V(WeavingAdaptor.java:168) at org.aspectj.weaver.tools.WeavingAdaptor.<init>()V(WeavingAdaptor.java:80) at org.aspectj.weaver.loadtime.ClassLoaderWeavingAdaptor.<init>(Ljava/lang/ClassLoader;Lorg/aspectj/weaver/loadtime/IWeavingContext;)V(ClassLoaderWeavingAdaptor.java:70) at org.aspectj.weaver.loadtime.Aj$WeaverContainer.getWeaver(Ljava/lang/ClassLoader;Lorg/aspectj/weaver/loadtime/IWeavingContext;)Lorg/aspectj/weaver/tools/WeavingAdaptor;(Aj.java:94) at org.aspectj.weaver.loadtime.Aj.preProcess(Ljava/lang/String;[BLjava/lang/ClassLoader;)[B(Aj.java:61) at org.aspectj.weaver.loadtime.JRockitAgent.preProcess(Ljava/lang/ClassLoader;Ljava/lang/String;[B)[B(JRockitAgent.java:74) at jrockit.vm.ClassPreProcessorManager.notifyClassPreProcessor(ILjava/lang/String;[B)[B(Unknown Source) at jrockit.vm.Classes.defineClass0(ILjava/lang/String;[BII)I(Unknown Source) at jrockit.vm.Classes.defineClass(Ljava/lang/ClassLoader;Ljava/lang/String;[BII)Ljava/lang/Class;(Unknown Source) at java.lang.ClassLoader.defineClass(Ljava/lang/String;[BIILjava/security/ProtectionDomain;)Ljava/lang/Class;(Unknown Source) at java.security.SecureClassLoader.defineClass(Ljava/lang/String;[BIILjava/security/CodeSource;)Ljava/lang/Class;(SecureClassLoader.java:123) at java.net.URLClassLoader.defineClass(Ljava/lang/String;Lsun/misc/Resource;)Ljava/lang/Class;(URLClassLoader.java:251) at java.net.URLClassLoader.access$100(Ljava/net/URLClassLoader;Ljava/lang/String;Lsun/misc/Resource;)Ljava/lang/Class;(URLClassLoader.java:55) at java.net.URLClassLoader$1.run()Ljava/lang/Object;(URLClassLoader.java:194) at jrockit.vm.AccessController.do_privileged_exc(Ljava/security/PrivilegedExceptionAction;Ljava/security/AccessControlContext;I)Ljava/lang/Object;(Unknown Source) at jrockit.vm.AccessController.doPrivileged(Ljava/security/PrivilegedExceptionAction;Ljava/security/AccessControlContext;)Ljava/lang/Object;(Unknown Source) at java.net.URLClassLoader.findClass(Ljava/lang/String;)Ljava/lang/Class;(URLClassLoader.java:187) at java.lang.ClassLoader.loadClass(Ljava/lang/String;Z)Ljava/lang/Class;(Unknown Source) at sun.misc.Launcher$AppClassLoader.loadClass(Ljava/lang/String;Z)Ljava/lang/Class;(Launcher.java:274) at java.lang.ClassLoader.loadClass(Ljava/lang/String;)Ljava/lang/Class;(Unknown Source) at java.lang.ClassLoader.loadClassFromNative(II)Ljava/lang/Class;(Unknown Source) at jrockit.vm.RNI.getRunnableCode(I)I(Unknown Source) at jrockit.vm.RNI.trampoline()V(Unknown Source) at org.aspectj.bridge.MessageUtil.info(Lorg/aspectj/bridge/IMessageHandler;Ljava/lang/String;)Z(MessageUtil.java:???) at org.aspectj.weaver.tools.WeavingAdaptor.info(Ljava/lang/String;)Z(WeavingAdaptor.java:343) at org.aspectj.weaver.tools.WeavingAdaptor.createMessageHandler()V(WeavingAdaptor.java:168)
|
resolved fixed
|
75afb31
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-06-09T10:56:50Z | 2006-01-04T02:00:00Z |
loadtime/testsrc/org/aspectj/bea/jvm/JVMImpl.java
| |
122,580 |
Bug 122580 Fix & Bug: Circularity Failure for Verbose Loading on JRockit 1.4.2_08 Agent
|
Here is a stack trace I am getting when I try to use AspectJ 1.5.0 final release's load-time weaving with JRockIt 1.4.2_08 using -Xmanagement:class=org.aspectj.weaver.loadtime.JRockitAgent to load Weblogic Server 8.1 SP2. I debugged the code in Eclipse and discovered that the weaver was being initialized while loading IMessage$Kind, so the JRockIt VM simply hasn't run staticinitialization yet, making IMessage.INFO null. I was able to fix this stack trace by hoisting the check for loading AspectJ code up BEFORE initializing a weaving adaptor i.e., changing line 55 of Aj.java to be if (loader == null || className == null || className.startsWith("org/aspectj/")) { I then commented out line 251 of WeavingAdaptor to avoid a duplicate check: private boolean shouldWeaveName (String name) { return !((/*(name.startsWith("org.apache.bcel.")||//FIXME AV why ? bcel is wrapped in org.aspectj. name.startsWith("org.aspectj.")||*/ // now checked earlier, to avoid circularity issues in initialization name.startsWith("java.") || name.startsWith("javax.")) //|| name.startsWith("$Proxy")//JDK proxies//FIXME AV is that 1.3 proxy ? fe. ataspect.$Proxy0 is a java5 proxy... || name.startsWith("sun.reflect."));//JDK reflect } Note that this bug does NOT occur when using a JRockIt 1.5.0 VM, even with the -Xmanagement command line argument. Stack Trace: java.lang.IllegalArgumentException: null kind at org.aspectj.bridge.Message.<init>(Ljava/lang/String;Ljava/lang/String;Lorg/aspectj/bridge/IMessage$Kind;Lorg/aspectj/bridge/ISourceLocation;Ljava/lang/Throwable;[Lorg/aspectj/bridge/ISourceLocation;ZIII)V(Message.java:89) at org.aspectj.bridge.Message.<init>(Ljava/lang/String;Ljava/lang/String;Lorg/aspectj/bridge/IMessage$Kind;Lorg/aspectj/bridge/ISourceLocation;Ljava/lang/Throwable;[Lorg/aspectj/bridge/ISourceLocation;)V(Message.java:67) at org.aspectj.bridge.Message.<init>(Ljava/lang/String;Lorg/aspectj/bridge/IMessage$Kind;Ljava/lang/Throwable;Lorg/aspectj/bridge/ISourceLocation;)V(Message.java:110) at org.aspectj.bridge.MessageUtil.info(Ljava/lang/String;)Lorg/aspectj/bridge/IMessage;(MessageUtil.java:211) at org.aspectj.bridge.MessageUtil.info(Lorg/aspectj/bridge/IMessageHandler;Ljava/lang/String;)Z(MessageUtil.java:98) at org.aspectj.weaver.tools.WeavingAdaptor.info(Ljava/lang/String;)Z(WeavingAdaptor.java:343) at org.aspectj.weaver.tools.WeavingAdaptor.createMessageHandler()V(WeavingAdaptor.java:168) at org.aspectj.weaver.tools.WeavingAdaptor.<init>()V(WeavingAdaptor.java:80) at org.aspectj.weaver.loadtime.ClassLoaderWeavingAdaptor.<init>(Ljava/lang/ClassLoader;Lorg/aspectj/weaver/loadtime/IWeavingContext;)V(ClassLoaderWeavingAdaptor.java:70) at org.aspectj.weaver.loadtime.Aj$WeaverContainer.getWeaver(Ljava/lang/ClassLoader;Lorg/aspectj/weaver/loadtime/IWeavingContext;)Lorg/aspectj/weaver/tools/WeavingAdaptor;(Aj.java:94) at org.aspectj.weaver.loadtime.Aj.preProcess(Ljava/lang/String;[BLjava/lang/ClassLoader;)[B(Aj.java:61) at org.aspectj.weaver.loadtime.JRockitAgent.preProcess(Ljava/lang/ClassLoader;Ljava/lang/String;[B)[B(JRockitAgent.java:74) at jrockit.vm.ClassPreProcessorManager.notifyClassPreProcessor(ILjava/lang/String;[B)[B(Unknown Source) at jrockit.vm.Classes.defineClass0(ILjava/lang/String;[BII)I(Unknown Source) at jrockit.vm.Classes.defineClass(Ljava/lang/ClassLoader;Ljava/lang/String;[BII)Ljava/lang/Class;(Unknown Source) at java.lang.ClassLoader.defineClass(Ljava/lang/String;[BIILjava/security/ProtectionDomain;)Ljava/lang/Class;(Unknown Source) at java.security.SecureClassLoader.defineClass(Ljava/lang/String;[BIILjava/security/CodeSource;)Ljava/lang/Class;(SecureClassLoader.java:123) at java.net.URLClassLoader.defineClass(Ljava/lang/String;Lsun/misc/Resource;)Ljava/lang/Class;(URLClassLoader.java:251) at java.net.URLClassLoader.access$100(Ljava/net/URLClassLoader;Ljava/lang/String;Lsun/misc/Resource;)Ljava/lang/Class;(URLClassLoader.java:55) at java.net.URLClassLoader$1.run()Ljava/lang/Object;(URLClassLoader.java:194) at jrockit.vm.AccessController.do_privileged_exc(Ljava/security/PrivilegedExceptionAction;Ljava/security/AccessControlContext;I)Ljava/lang/Object;(Unknown Source) at jrockit.vm.AccessController.doPrivileged(Ljava/security/PrivilegedExceptionAction;Ljava/security/AccessControlContext;)Ljava/lang/Object;(Unknown Source) at java.net.URLClassLoader.findClass(Ljava/lang/String;)Ljava/lang/Class;(URLClassLoader.java:187) at java.lang.ClassLoader.loadClass(Ljava/lang/String;Z)Ljava/lang/Class;(Unknown Source) at sun.misc.Launcher$AppClassLoader.loadClass(Ljava/lang/String;Z)Ljava/lang/Class;(Launcher.java:274) at java.lang.ClassLoader.loadClass(Ljava/lang/String;)Ljava/lang/Class;(Unknown Source) at java.lang.ClassLoader.loadClassFromNative(II)Ljava/lang/Class;(Unknown Source) at jrockit.vm.RNI.getRunnableCode(I)I(Unknown Source) at jrockit.vm.RNI.trampoline()V(Unknown Source) at org.aspectj.bridge.MessageUtil.info(Ljava/lang/String;)Lorg/aspectj/bridge/IMessage;(MessageUtil.java:???) at org.aspectj.bridge.MessageUtil.info(Lorg/aspectj/bridge/IMessageHandler;Ljava/lang/String;)Z(MessageUtil.java:98) at org.aspectj.weaver.tools.WeavingAdaptor.info(Ljava/lang/String;)Z(WeavingAdaptor.java:343) java.lang.IllegalArgumentException: null kind at org.aspectj.bridge.Message.<init>(Ljava/lang/String;Ljava/lang/String;Lorg/aspectj/bridge/IMessage$Kind;Lorg/aspectj/bridge/ISourceLocation;Ljava/lang/Throwable;[Lorg/aspectj/bridge/ISourceLocation;ZIII)V(Message.java:89) at org.aspectj.bridge.Message.<init>(Ljava/lang/String;Ljava/lang/String;Lorg/aspectj/bridge/IMessage$Kind;Lorg/aspectj/bridge/ISourceLocation;Ljava/lang/Throwable;[Lorg/aspectj/bridge/ISourceLocation;)V(Message.java:67) at org.aspectj.bridge.Message.<init>(Ljava/lang/String;Lorg/aspectj/bridge/IMessage$Kind;Ljava/lang/Throwable;Lorg/aspectj/bridge/ISourceLocation;)V(Message.java:110) at org.aspectj.bridge.MessageUtil.info(Ljava/lang/String;)Lorg/aspectj/bridge/IMessage;(MessageUtil.java:211) at org.aspectj.bridge.MessageUtil.info(Lorg/aspectj/bridge/IMessageHandler;Ljava/lang/String;)Z(MessageUtil.java:98) at org.aspectj.weaver.tools.WeavingAdaptor.info(Ljava/lang/String;)Z(WeavingAdaptor.java:343) at org.aspectj.weaver.tools.WeavingAdaptor.createMessageHandler()V(WeavingAdaptor.java:168) at org.aspectj.weaver.tools.WeavingAdaptor.<init>()V(WeavingAdaptor.java:80) at org.aspectj.weaver.loadtime.ClassLoaderWeavingAdaptor.<init>(Ljava/lang/ClassLoader;Lorg/aspectj/weaver/loadtime/IWeavingContext;)V(ClassLoaderWeavingAdaptor.java:70) at org.aspectj.weaver.loadtime.Aj$WeaverContainer.getWeaver(Ljava/lang/ClassLoader;Lorg/aspectj/weaver/loadtime/IWeavingContext;)Lorg/aspectj/weaver/tools/WeavingAdaptor;(Aj.java:94) at org.aspectj.weaver.loadtime.Aj.preProcess(Ljava/lang/String;[BLjava/lang/ClassLoader;)[B(Aj.java:61) at org.aspectj.weaver.loadtime.JRockitAgent.preProcess(Ljava/lang/ClassLoader;Ljava/lang/String;[B)[B(JRockitAgent.java:74) at jrockit.vm.ClassPreProcessorManager.notifyClassPreProcessor(ILjava/lang/String;[B)[B(Unknown Source) at jrockit.vm.Classes.defineClass0(ILjava/lang/String;[BII)I(Unknown Source) at jrockit.vm.Classes.defineClass(Ljava/lang/ClassLoader;Ljava/lang/String;[BII)Ljava/lang/Class;(Unknown Source) at java.lang.ClassLoader.defineClass(Ljava/lang/String;[BIILjava/security/ProtectionDomain;)Ljava/lang/Class;(Unknown Source) at java.security.SecureClassLoader.defineClass(Ljava/lang/String;[BIILjava/security/CodeSource;)Ljava/lang/Class;(SecureClassLoader.java:123) at java.net.URLClassLoader.defineClass(Ljava/lang/String;Lsun/misc/Resource;)Ljava/lang/Class;(URLClassLoader.java:251) at java.net.URLClassLoader.access$100(Ljava/net/URLClassLoader;Ljava/lang/String;Lsun/misc/Resource;)Ljava/lang/Class;(URLClassLoader.java:55) at java.net.URLClassLoader$1.run()Ljava/lang/Object;(URLClassLoader.java:194) at jrockit.vm.AccessController.do_privileged_exc(Ljava/security/PrivilegedExceptionAction;Ljava/security/AccessControlContext;I)Ljava/lang/Object;(Unknown Source) at jrockit.vm.AccessController.doPrivileged(Ljava/security/PrivilegedExceptionAction;Ljava/security/AccessControlContext;)Ljava/lang/Object;(Unknown Source) at java.net.URLClassLoader.findClass(Ljava/lang/String;)Ljava/lang/Class;(URLClassLoader.java:187) at java.lang.ClassLoader.loadClass(Ljava/lang/String;Z)Ljava/lang/Class;(Unknown Source) at sun.misc.Launcher$AppClassLoader.loadClass(Ljava/lang/String;Z)Ljava/lang/Class;(Launcher.java:274) at java.lang.ClassLoader.loadClass(Ljava/lang/String;)Ljava/lang/Class;(Unknown Source) at java.lang.ClassLoader.loadClassFromNative(II)Ljava/lang/Class;(Unknown Source) at jrockit.vm.RNI.getRunnableCode(I)I(Unknown Source) at jrockit.vm.RNI.trampoline()V(Unknown Source) at org.aspectj.bridge.MessageUtil.info(Lorg/aspectj/bridge/IMessageHandler;Ljava/lang/String;)Z(MessageUtil.java:???) at org.aspectj.weaver.tools.WeavingAdaptor.info(Ljava/lang/String;)Z(WeavingAdaptor.java:343) at org.aspectj.weaver.tools.WeavingAdaptor.createMessageHandler()V(WeavingAdaptor.java:168)
|
resolved fixed
|
75afb31
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-06-09T10:56:50Z | 2006-01-04T02:00:00Z |
loadtime/testsrc/org/aspectj/weaver/loadtime/JRockitAgentTest.java
| |
146,546 |
Bug 146546 Remove hard coded dependency on "|" in getFileName(..) methods
| null |
resolved fixed
|
38cc0dd
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-06-12T14:00:02Z | 2006-06-12T11:00:00Z |
asm/src/org/aspectj/asm/AsmManager.java
|
/* *******************************************************************
* Copyright (c) 2003 Contributors.
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Eclipse Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Mik Kersten initial implementation
* Andy Clement incremental support and switch on/off state
* ******************************************************************/
package org.aspectj.asm;
import java.io.*;
import java.util.*;
import org.aspectj.asm.internal.*;
import org.aspectj.bridge.ISourceLocation;
/**
* The Abstract Structure Model (ASM) represents the containment hierarchy and crossccutting
* structure map for AspectJ programs. It is used by IDE views such as the document outline,
* and by other tools such as ajdoc to show both AspectJ declarations and crosscutting links,
* such as which advice affects which join point shadows.
*
* @author Mik Kersten
*/
public class AsmManager {
/**
* @deprecated use getDefault() method instead
*/
private static AsmManager INSTANCE = new AsmManager();
private IElementHandleProvider handleProvider;
private List structureListeners = new ArrayList();
// private boolean shouldSaveModel = true;
public void setRelationshipMap(IRelationshipMap irm) { mapper = irm;}
public void setHierarchy(IHierarchy ih) { hierarchy=ih;}
// The model is 'manipulated' by the AjBuildManager.setupModel() code which trashes all the
// fields when setting up a new model for a batch build.
// Due to the requirements of incremental compilation we need to tie some of the info
// below to the AjState for a compilation and recover it if switching between projects.
protected IHierarchy hierarchy;
private IRelationshipMap mapper;
private static boolean creatingModel = false;
public static boolean dumpModelPostBuild = false; // Dumping the model is expensive
// SECRETAPI asc pull the secret options together into a system API you lazy fool
public static boolean attemptIncrementalModelRepairs = false;
// For offline debugging, you can now ask for the AsmManager to
// dump the model - see the method setReporting()
private static boolean dumpModel = false;
private static boolean dumpRelationships = false;
private static boolean dumpDeltaProcessing = false;
private static String dumpFilename = "";
private static boolean reporting = false;
private static boolean completingTypeBindings = false;
// static {
// setReporting("c:/model.nfo",true,true,true,true);
// }
protected AsmManager() {
hierarchy = new AspectJElementHierarchy();
// List relationships = new ArrayList();
mapper = new RelationshipMap(hierarchy);
handleProvider = new OptimizedFullPathHandleProvider();
}
public void createNewASM() {
hierarchy = new AspectJElementHierarchy();
mapper = new RelationshipMap(hierarchy);
}
public IHierarchy getHierarchy() {
return hierarchy;
}
public static AsmManager getDefault() {
return INSTANCE;
}
public IRelationshipMap getRelationshipMap() {
return mapper;
}
public void fireModelUpdated() {
notifyListeners();
if (dumpModelPostBuild && hierarchy.getConfigFile() != null) {
writeStructureModel(hierarchy.getConfigFile());
}
}
/**
* Constructs map each time it's called.
*/
public HashMap getInlineAnnotations(
String sourceFile,
boolean showSubMember,
boolean showMemberAndType) {
if (!hierarchy.isValid()) return null;
HashMap annotations = new HashMap();
IProgramElement node = hierarchy.findElementForSourceFile(sourceFile);
if (node == IHierarchy.NO_STRUCTURE) {
return null;
} else {
IProgramElement fileNode = (IProgramElement)node;
ArrayList peNodes = new ArrayList();
getAllStructureChildren(fileNode, peNodes, showSubMember, showMemberAndType);
for (Iterator it = peNodes.iterator(); it.hasNext(); ) {
IProgramElement peNode = (IProgramElement)it.next();
List entries = new ArrayList();
entries.add(peNode);
ISourceLocation sourceLoc = peNode.getSourceLocation();
if (null != sourceLoc) {
Integer hash = new Integer(sourceLoc.getLine());
List existingEntry = (List)annotations.get(hash);
if (existingEntry != null) {
entries.addAll(existingEntry);
}
annotations.put(hash, entries);
}
}
return annotations;
}
}
private void getAllStructureChildren(IProgramElement node, List result, boolean showSubMember, boolean showMemberAndType) {
List children = node.getChildren();
if (node.getChildren() == null) return;
for (Iterator it = children.iterator(); it.hasNext(); ) {
IProgramElement next = (IProgramElement)it.next();
List rels = AsmManager.getDefault().getRelationshipMap().get(next);
if (next != null
&& ((next.getKind() == IProgramElement.Kind.CODE && showSubMember)
|| (next.getKind() != IProgramElement.Kind.CODE && showMemberAndType))
&& rels != null
&& rels.size() > 0) {
result.add(next);
}
getAllStructureChildren((IProgramElement)next, result, showSubMember, showMemberAndType);
}
}
public void addListener(IHierarchyListener listener) {
structureListeners.add(listener);
}
public void removeStructureListener(IHierarchyListener listener) {
structureListeners.remove(listener);
}
// this shouldn't be needed - but none of the people that add listeners
// in the test suite ever remove them. AMC added this to be called in
// setup() so that the test cases would cease leaking listeners and go
// back to executing at a reasonable speed.
public void removeAllListeners() {
structureListeners.clear();
}
private void notifyListeners() {
for (Iterator it = structureListeners.iterator(); it.hasNext(); ) {
((IHierarchyListener)it.next()).elementsUpdated(hierarchy);
}
}
public IElementHandleProvider getHandleProvider() {
return handleProvider;
}
public void setHandleProvider(IElementHandleProvider handleProvider) {
this.handleProvider = handleProvider;
}
/**
* Fails silently.
*/
public void writeStructureModel(String configFilePath) {
try {
String filePath = genExternFilePath(configFilePath);
FileOutputStream fos = new FileOutputStream(filePath);
ObjectOutputStream s = new ObjectOutputStream(fos);
s.writeObject(hierarchy); // Store the program element tree
s.writeObject(mapper); // Store the relationships
s.flush();
fos.flush();
fos.close();
s.close();
} catch (Exception e) {
// System.err.println("AsmManager: Unable to write structure model: "+configFilePath+" because of:");
// e.printStackTrace();
}
}
/**
* @todo add proper handling of bad paths/suffixes/etc
* @param configFilePath path to an ".lst" file
*/
public void readStructureModel(String configFilePath) {
boolean hierarchyReadOK = false;
try {
if (configFilePath == null) {
hierarchy.setRoot(IHierarchy.NO_STRUCTURE);
} else {
String filePath = genExternFilePath(configFilePath);
FileInputStream in = new FileInputStream(filePath);
ObjectInputStream s = new ObjectInputStream(in);
hierarchy = (AspectJElementHierarchy)s.readObject();
hierarchyReadOK = true;
mapper = (RelationshipMap)s.readObject();
((RelationshipMap)mapper).setHierarchy(hierarchy);
}
} catch (FileNotFoundException fnfe) {
// That is OK
hierarchy.setRoot(IHierarchy.NO_STRUCTURE);
} catch (EOFException eofe) {
// Might be an old format sym file that is missing its relationships
if (!hierarchyReadOK) {
System.err.println("AsmManager: Unable to read structure model: "+configFilePath+" because of:");
eofe.printStackTrace();
hierarchy.setRoot(IHierarchy.NO_STRUCTURE);
}
} catch (Exception e) {
// System.err.println("AsmManager: Unable to read structure model: "+configFilePath+" because of:");
// e.printStackTrace();
hierarchy.setRoot(IHierarchy.NO_STRUCTURE);
} finally {
notifyListeners();
}
}
private String genExternFilePath(String configFilePath) {
return configFilePath.substring(0, configFilePath.lastIndexOf(".lst")) + ".ajsym";
}
// public void setShouldSaveModel(boolean shouldSaveModel) {
// this.shouldSaveModel = shouldSaveModel;
// }
// ==== implementation of canonical file path map and accessors ==============
// a more sophisticated optimisation is left here commented out as the
// performance gains don't justify the disturbance this close to a release...
// can't call prepareForWeave until preparedForCompilation has completed...
// public synchronized void prepareForCompilation(List files) {
// canonicalFilePathMap.prepopulate(files);
// }
//
// public synchronized void prepareForWeave() {
// canonicalFilePathMap.handover();
// }
public String getCanonicalFilePath(File f) {
return canonicalFilePathMap.get(f);
}
private CanonicalFilePathMap canonicalFilePathMap = new CanonicalFilePathMap();
private static class CanonicalFilePathMap {
private static final int MAX_SIZE = 4000;
private Map pathMap = new HashMap(20);
// // guards to ensure correctness and liveness
// private boolean cacheInUse = false;
// private boolean stopRequested = false;
//
// private synchronized boolean isCacheInUse() {
// return cacheInUse;
// }
//
// private synchronized void setCacheInUse(boolean val) {
// cacheInUse = val;
// if (val) {
// notifyAll();
// }
// }
//
// private synchronized boolean isStopRequested() {
// return stopRequested;
// }
//
// private synchronized void requestStop() {
// stopRequested = true;
// }
//
// /**
// * Begin prepopulating the map by adding an entry from
// * file.getPath -> file.getCanonicalPath for each file in
// * the list. Do this on a background thread.
// * @param files
// */
// public void prepopulate(final List files) {
// stopRequested = false;
// setCacheInUse(false);
// if (pathMap.size() > MAX_SIZE) {
// pathMap.clear();
// }
// new Thread() {
// public void run() {
// System.out.println("Starting cache population: " + System.currentTimeMillis());
// Iterator it = files.iterator();
// while (!isStopRequested() && it.hasNext()) {
// File f = (File)it.next();
// if (pathMap.get(f.getPath()) == null) {
// // may reuse cache across compiles from ides...
// try {
// pathMap.put(f.getPath(),f.getCanonicalPath());
// } catch (IOException ex) {
// pathMap.put(f.getPath(),f.getPath());
// }
// }
// }
// System.out.println("Cached " + files.size());
// setCacheInUse(true);
// System.out.println("Cache populated: " + System.currentTimeMillis());
// }
// }.start();
// }
//
// /**
// * Stop pre-populating the cache - our customers are ready to use it.
// * If there are any cache misses from this point on, we'll populate the
// * cache as we go.
// * The handover is done this way to ensure that only one thread is ever
// * accessing the cache, and that we minimize synchronization.
// */
// public synchronized void handover() {
// if (!isCacheInUse()) {
// requestStop();
// try {
// while (!isCacheInUse()) wait();
// } catch (InterruptedException intEx) { } // just continue
// }
// }
public String get(File f) {
// if (!cacheInUse) { // unsynchronized test - should never be parallel
// // threads at this point
// throw new IllegalStateException(
// "Must take ownership of cache before using by calling " +
// "handover()");
// }
String ret = (String) pathMap.get(f.getPath());
if (ret == null) {
try {
ret = f.getCanonicalPath();
} catch (IOException ioEx) {
ret = f.getPath();
}
pathMap.put(f.getPath(),ret);
if (pathMap.size() > MAX_SIZE) pathMap.clear();
}
return ret;
}
}
// SECRETAPI
public static void setReporting(String filename,boolean dModel,boolean dRels,boolean dDeltaProcessing,
boolean deletefile) {
reporting = true;
dumpModel = dModel;
dumpRelationships = dRels;
dumpDeltaProcessing = dDeltaProcessing;
if (deletefile) new File(filename).delete();
dumpFilename = filename;
}
public static boolean isReporting() {
return reporting;
}
public void reportModelInfo(String reasonForReport) {
if (!dumpModel && !dumpRelationships) return;
try {
FileWriter fw = new FileWriter(dumpFilename,true);
BufferedWriter bw = new BufferedWriter(fw);
if (dumpModel) {
bw.write("=== MODEL STATUS REPORT ========= "+reasonForReport+"\n");
dumptree(bw,AsmManager.getDefault().getHierarchy().getRoot(),0);
bw.write("=== END OF MODEL REPORT =========\n");
}
if (dumpRelationships) {
bw.write("=== RELATIONSHIPS REPORT ========= "+reasonForReport+"\n");
dumprels(bw);
bw.write("=== END OF RELATIONSHIPS REPORT ==\n");
}
Properties p = ModelInfo.summarizeModel().getProperties();
Enumeration pkeyenum = p.keys();
bw.write("=== Properties of the model and relationships map =====\n");
while (pkeyenum.hasMoreElements()) {
String pkey = (String)pkeyenum.nextElement();
bw.write(pkey+"="+p.getProperty(pkey)+"\n");
}
bw.flush();
fw.close();
} catch (IOException e) {
System.err.println("InternalError: Unable to report model information:");
e.printStackTrace();
}
}
public static void dumptree(Writer w,IProgramElement node,int indent) throws IOException {
for (int i =0 ;i<indent;i++) w.write(" ");
String loc = "";
if (node!=null) {
if (node.getSourceLocation()!=null)
loc = node.getSourceLocation().toString();
}
w.write(node+" ["+(node==null?"null":node.getKind().toString())+"] "+loc+"\n");
if (node!=null)
for (Iterator i = node.getChildren().iterator();i.hasNext();) {
dumptree(w,(IProgramElement)i.next(),indent+2);
}
}
public static void dumptree(IProgramElement node,int indent) throws IOException {
for (int i =0 ;i<indent;i++) System.out.print(" ");
String loc = "";
if (node!=null) {
if (node.getSourceLocation()!=null)
loc = node.getSourceLocation().toString();
}
System.out.println(node+" ["+(node==null?"null":node.getKind().toString())+"] "+loc);
if (node!=null)
for (Iterator i = node.getChildren().iterator();i.hasNext();) {
dumptree((IProgramElement)i.next(),indent+2);
}
}
private void dumprels(Writer w) throws IOException {
IRelationshipMap irm = AsmManager.getDefault().getRelationshipMap();
int ctr = 1;
Set entries = irm.getEntries();
for (Iterator iter = entries.iterator(); iter.hasNext();) {
String hid = (String) iter.next();
List rels = irm.get(hid);
for (Iterator iterator = rels.iterator(); iterator.hasNext();) {
IRelationship ir = (IRelationship) iterator.next();
List targets = ir.getTargets();
for (Iterator iterator2 = targets.iterator();
iterator2.hasNext();
) {
String thid = (String) iterator2.next();
w.write("Hid:"+(ctr++)+":(targets="+targets.size()+") "+hid+" ("+ir.getName()+") "+thid+"\n");
}
}
}
}
private void dumprelsStderr(String key) {
System.err.println("Relationships dump follows: "+key);
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);
}
}
}
System.err.println("End of relationships dump for: "+key);
}
//===================== DELTA PROCESSING CODE ============== start ==========//
// XXX shouldn't be aware of the delimiter
private String getFilename(String hid) {
return hid.substring(0,hid.indexOf("|"));
}
/**
* Removes the hierarchy structure for the specified files from the structure model.
* Returns true if it deleted anything
*/
public boolean removeStructureModelForFiles(Writer fw,Collection files) throws IOException {
IHierarchy model = AsmManager.getDefault().getHierarchy();
boolean modelModified = false;
Set deletedNodes = new HashSet();
for (Iterator iter = files.iterator(); iter.hasNext();) {
File fileForCompilation = (File) iter.next();
String correctedPath = AsmManager.getDefault().getCanonicalFilePath(fileForCompilation);
IProgramElement progElem = (IProgramElement)model.findInFileMap(correctedPath);
if (progElem!=null) {
// Found it, let's remove it
if (dumpDeltaProcessing) {
fw.write("Deleting "+progElem+" node for file "+fileForCompilation+"\n");
}
removeNode(progElem);
deletedNodes.add(getFilename(progElem.getHandleIdentifier()));
if (!model.removeFromFileMap(correctedPath.toString()))
throw new RuntimeException("Whilst repairing model, couldn't remove entry for file: "+correctedPath.toString()+" from the filemap");
modelModified = true;
}
}
if (modelModified) model.updateHandleMap(deletedNodes);
return modelModified;
}
private void flushModelCache() {
IHierarchy model = AsmManager.getDefault().getHierarchy();
model.flushTypeMap();
}
// This code is *SLOW* but it isnt worth fixing until we address the
// bugs in binary weaving.
public void fixupStructureModel(Writer fw,List filesToBeCompiled,Set files_added,Set files_deleted) throws IOException {
// Three kinds of things to worry about:
// 1. New files have been added since the last compile
// 2. Files have been deleted since the last compile
// 3. Files have 'changed' since the last compile (really just those in config.getFiles())
// List files = config.getFiles();
IHierarchy model = AsmManager.getDefault().getHierarchy();
boolean modelModified = false;
// Files to delete are: those to be compiled + those that have been deleted
Set filesToRemoveFromStructureModel = new HashSet(filesToBeCompiled);
filesToRemoveFromStructureModel.addAll(files_deleted);
Set deletedNodes = new HashSet();
for (Iterator iter = filesToRemoveFromStructureModel.iterator(); iter.hasNext();) {
File fileForCompilation = (File) iter.next();
String correctedPath = AsmManager.getDefault().getCanonicalFilePath(fileForCompilation);
IProgramElement progElem = (IProgramElement)model.findInFileMap(correctedPath);
if (progElem!=null) {
// Found it, let's remove it
if (dumpDeltaProcessing) {
fw.write("Deleting "+progElem+" node for file "+fileForCompilation+"\n");
}
removeNode(progElem);
deletedNodes.add(getFilename(progElem.getHandleIdentifier()));
if (!model.removeFromFileMap(correctedPath.toString()))
throw new RuntimeException("Whilst repairing model, couldn't remove entry for file: "+correctedPath.toString()+" from the filemap");
modelModified = true;
}
}
if (modelModified) {
model.flushTypeMap();
model.updateHandleMap(deletedNodes);
}
}
public void processDelta(List files_tobecompiled,Set files_added,Set files_deleted) {
try {
Writer fw = null;
// Are we recording this ?
if (dumpDeltaProcessing) {
FileWriter filew = new FileWriter(dumpFilename,true);
fw = new BufferedWriter(filew);
fw.write("=== Processing delta changes for the model ===\n");
fw.write("Files for compilation:#"+files_tobecompiled.size()+":"+files_tobecompiled+"\n");
fw.write("Files added :#"+files_added.size()+":"+files_added+"\n");
fw.write("Files deleted :#"+files_deleted.size()+":"+files_deleted+"\n");
}
long stime = System.currentTimeMillis();
boolean modificationOccurred = false;
//fixupStructureModel(fw,filesToBeCompiled,files_added,files_deleted);
// Let's remove all the files that are deleted on this compile
modificationOccurred =
removeStructureModelForFiles(fw,files_deleted) |
modificationOccurred;
long etime1 = System.currentTimeMillis(); // etime1-stime = time to fix up the model
repairRelationships(fw);
long etime2 = System.currentTimeMillis(); // etime2-stime = time to repair the relationship map
modificationOccurred =
removeStructureModelForFiles(fw,files_tobecompiled) |
modificationOccurred;
if (dumpDeltaProcessing) {
fw.write("===== Delta Processing timing ==========\n");
fw.write("Hierarchy="+(etime1-stime)+"ms Relationshipmap="+(etime2-etime1)+"ms\n");
fw.write("===== Traversal ========================\n");
// fw.write("Source handles processed="+srchandlecounter+"\n");
// fw.write("Target handles processed="+tgthandlecounter+"\n");
fw.write("========================================\n");
fw.flush();fw.close();
}
reportModelInfo("After delta processing");
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* two kinds of relationships
*
* A affects B
* B affectedBy A
*
* Both of these relationships are added when 'B' is modified. Concrete examples are
* 'advises/advisedby' or 'annotates/annotatedby'.
*
* What we need to do is when 'B' is going to be woven, remove all relationships that may
* reoccur when it is woven.
* So - remove 'affects' relationships where the target is 'B', remove all 'affectedBy'
* relationships where the source is 'B'.
*
*/
public void removeRelationshipsTargettingThisType(String typename) {
boolean debug=false;
if (debug) System.err.println(">>removeRelationshipsTargettingThisType "+typename);
String pkg = null;
String type= typename;
int lastSep = typename.lastIndexOf('.');
if (lastSep != -1) {
pkg = typename.substring(0,lastSep);
type= typename.substring(lastSep+1);
}
boolean didsomething=false;
IProgramElement typeNode = hierarchy.findElementForType(pkg,type);
// Reasons for that being null:
// 1. the file has fundamental errors and so doesn't exist in the model (-proceedOnError probably forced us to weave)
if (typeNode == null) return;
Set sourcesToRemove = new HashSet();
// Iterate over the source handles in the relationships map, the aim here is to remove any 'affected by'
// relationships where the source of the relationship is the specified type (since it will be readded
// when the type is woven)
Set sourcehandlesSet = mapper.getEntries();
List relationshipsToRemove = new ArrayList();
for (Iterator keyiter = sourcehandlesSet.iterator(); keyiter.hasNext();) {
String hid = (String) keyiter.next();
IProgramElement sourceElement = hierarchy.getElement(hid);
if (sourceElement == null || sameType(hid,sourceElement,typeNode)) {
// worth continuing as there may be a relationship to remove
relationshipsToRemove.clear();
List relationships = mapper.get(hid);
for (Iterator reliter = relationships.iterator();reliter.hasNext();) {
IRelationship rel = (IRelationship) reliter.next();
if (rel.getKind()==IRelationship.Kind.USES_POINTCUT) continue; // these relationships are added at compile time, argh
if (rel.isAffects()) continue; // we want 'affected by' relationships - (e.g. advised by)
relationshipsToRemove.add(rel); // all the relationships can be removed, regardless of the target(s)
}
// Now, were any relationships emptied during that processing and so need removing for this source handle
if (relationshipsToRemove.size()>0) {
didsomething=true;
if (relationshipsToRemove.size() == relationships.size()) sourcesToRemove.add(hid);
else {
for (int i = 0 ;i<relationshipsToRemove.size();i++)
relationships.remove(relationshipsToRemove.get(i));
}
}
}
}
// Remove sources that have no valid relationships any more
for (Iterator srciter = sourcesToRemove.iterator(); srciter.hasNext();) {
String hid = (String) srciter.next();
// System.err.println(" source handle: all relationships have gone for "+hid);
mapper.removeAll(hid);
IProgramElement ipe = hierarchy.getElement(hid);
if (ipe!=null) {
// If the relationship was hanging off a 'code' node, delete it.
if (ipe.getKind().equals(IProgramElement.Kind.CODE)) {
if (debug) System.err.println(" source handle: it was code node, removing that as well... code="+ipe+" parent="+ipe.getParent());
removeSingleNode(ipe);
}
}
}
if (debug) dumprelsStderr("after processing 'affectedby'");
if (didsomething) { // did we do anything?
sourcesToRemove.clear();
// removing 'affects' relationships
if (debug) dumprelsStderr("before processing 'affects'");
// Iterate over the source handles in the relationships map
sourcehandlesSet = mapper.getEntries();
for (Iterator keyiter = sourcehandlesSet.iterator(); keyiter.hasNext();) {
String hid = (String) keyiter.next();
IProgramElement sourceElement = hierarchy.getElement(hid);
relationshipsToRemove.clear();
List relationships = mapper.get(hid);
for (Iterator reliter = relationships.iterator();reliter.hasNext();) {
IRelationship rel = (IRelationship) reliter.next();
if (rel.getKind()==IRelationship.Kind.USES_POINTCUT) continue; // these relationships are added at compile time, argh
if (!rel.isAffects()) continue;
List targets = rel.getTargets();
List targetsToRemove = new ArrayList();
// find targets that target the type we are interested in, they need removing
for (Iterator targetsIter = targets.iterator(); targetsIter.hasNext();) {
String targethid = (String) targetsIter.next();
// Does this point to the same type?
IProgramElement existingTarget = hierarchy.getElement(targethid);
if (existingTarget == null || sameType(targethid,existingTarget,typeNode)) targetsToRemove.add(targethid);
}
if (targetsToRemove.size()!=0) {
if (targetsToRemove.size()==targets.size()) relationshipsToRemove.add(rel);
else {
// Remove all the targets that are no longer valid
for (Iterator targsIter = targetsToRemove.iterator();targsIter.hasNext();) {
String togo = (String) targsIter.next();
targets.remove(togo);
}
}
}
}
// Now, were any relationships emptied during that processing and so need removing for this source handle
if (relationshipsToRemove.size()>0) {
// Are we removing *all* of the relationships for this source handle?
if (relationshipsToRemove.size() == relationships.size()) sourcesToRemove.add(hid);
else {
for (int i = 0 ;i<relationshipsToRemove.size();i++)
relationships.remove(relationshipsToRemove.get(i));
}
}
}
// Remove sources that have no valid relationships any more
for (Iterator srciter = sourcesToRemove.iterator(); srciter.hasNext();) {
String hid = (String) srciter.next();
// System.err.println(" source handle: all relationships have gone for "+hid);
mapper.removeAll(hid);
IProgramElement ipe = hierarchy.getElement(hid);
if (ipe!=null) {
// If the relationship was hanging off a 'code' node, delete it.
if (ipe.getKind().equals(IProgramElement.Kind.CODE)) {
if (debug) System.err.println(" source handle: it was code node, removing that as well... code="+ipe+" parent="+ipe.getParent());
removeSingleNode(ipe);
}
}
}
if (debug) dumprelsStderr("after processing 'affects'");
}
if (debug) System.err.println("<<removeRelationshipsTargettingThisFile");
}
/**
* Return true if the target element is in the type specified.
*/
private boolean sameType(String hid,IProgramElement target, IProgramElement type) {
IProgramElement containingType = target;
if (target==null)
throw new RuntimeException("target can't be null!");
if (type==null)
throw new RuntimeException("type can't be null!");
if (target.getKind().isSourceFile()) {
// @AJ aspect with broken relationship endpoint - we couldn't find the real
// endpoint (the declare parents or ITD or similar) so defaulted to the
// first line of the source file...
// FRAGILE
// Let's assume the worst, and that it is the same type if the source files
// are the same. This will break for multiple top level types in a file...
if (target.getSourceLocation()==null) return false; // these four possibilities should really be FIXED so we don't have this situation
if (type.getSourceLocation()==null) return false;
if (target.getSourceLocation().getSourceFile()==null) return false;
if (type.getSourceLocation().getSourceFile()==null) return false;
return (target.getSourceLocation().getSourceFile().equals(type.getSourceLocation().getSourceFile()));
}
while (!containingType.getKind().isType()) {
// System.err.println("Checked: "+containingType.getKind()+" "+containingType);
containingType = containingType.getParent();
}
return (type.equals(containingType));
}
/**
* Go through all the relationships in the model, if any endpoints no longer exist (the node it
* points to has been deleted from the model) then delete the relationship.
*/
private void repairRelationships(Writer fw) {
try {
IHierarchy model = AsmManager.getDefault().getHierarchy();
//TODO Speed this code up by making this assumption:
// the only piece of the handle that is interesting is the file name. We are working at file granularity, if the
// file does not exist (i.e. its not in the filemap) then any handle inside that file cannot exist.
if (dumpDeltaProcessing) fw.write("Repairing relationships map:\n");
// Now sort out the relationships map
IRelationshipMap irm = AsmManager.getDefault().getRelationshipMap();
Set sourcesToRemove = new HashSet();
Set nonExistingHandles = new HashSet(); // Cache of handles that we *know* are invalid
int srchandlecounter = 0;
int tgthandlecounter = 0;
// Iterate over the source handles in the relationships map
Set keyset = irm.getEntries(); // These are source handles
for (Iterator keyiter = keyset.iterator(); keyiter.hasNext();) {
String hid = (String) keyiter.next();
srchandlecounter++;
// Do we already know this handle points to nowhere?
if (nonExistingHandles.contains(hid)) {
sourcesToRemove.add(hid);
} else {
// We better check if it actually exists
IProgramElement existingElement = model.getElement(hid);
if (dumpDeltaProcessing) fw.write("Looking for handle ["+hid+"] in model, found: "+existingElement+"\n");
// Did we find it?
if (existingElement == null) {
// No, so delete this relationship
sourcesToRemove.add(hid);
nonExistingHandles.add(hid); // Speed up a bit you swine
} else {
// Ok, so the source is valid, what about the targets?
List relationships = irm.get(hid);
List relationshipsToRemove = new ArrayList();
// Iterate through the relationships against this source handle
for (Iterator reliter = relationships.iterator();reliter.hasNext();) {
IRelationship rel = (IRelationship) reliter.next();
List targets = rel.getTargets();
List targetsToRemove = new ArrayList();
// Iterate through the targets for this relationship
for (Iterator targetIter = targets.iterator();targetIter.hasNext();) {
String targethid = (String) targetIter.next();
tgthandlecounter++;
// Do we already know it doesn't exist?
if (nonExistingHandles.contains(targethid)) {
if (dumpDeltaProcessing) fw.write("Target handle ["+targethid+"] for srchid["+hid+"]rel["+rel.getName()+"] does not exist\n");
targetsToRemove.add(targethid);
} else {
// We better check
IProgramElement existingTarget = model.getElement(targethid);
if (existingTarget == null) {
if (dumpDeltaProcessing) fw.write("Target handle ["+targethid+"] for srchid["+hid+"]rel["+rel.getName()+"] does not exist\n");
targetsToRemove.add(targethid);
nonExistingHandles.add(targethid);
}
}
}
// Do we have some targets that need removing?
if (targetsToRemove.size()!=0) {
// Are we removing *all* of the targets for this relationship (i.e. removing the relationship)
if (targetsToRemove.size()==targets.size()) {
if (dumpDeltaProcessing) fw.write("No targets remain for srchid["+hid+"] rel["+rel.getName()+"]: removing it\n");
relationshipsToRemove.add(rel);
} else {
// Remove all the targets that are no longer valid
for (Iterator targsIter = targetsToRemove.iterator();targsIter.hasNext();) {
String togo = (String) targsIter.next();
targets.remove(togo);
}
// Should have already been caught above, but lets double check ...
if (targets.size()==0) {
if (dumpDeltaProcessing) fw.write("No targets remain for srchid["+hid+"] rel["+rel.getName()+"]: removing it\n");
relationshipsToRemove.add(rel); // TODO Should only remove this relationship for the srchid?
}
}
}
}
// Now, were any relationships emptied during that processing and so need removing for this source handle
if (relationshipsToRemove.size()>0) {
// Are we removing *all* of the relationships for this source handle?
if (relationshipsToRemove.size() == relationships.size()) {
// We know they are all going to go, so just delete the source handle.
sourcesToRemove.add(hid);
} else {
// MEMORY LEAK - we don't remove the relationships !!
for (int i = 0 ;i<relationshipsToRemove.size();i++) {
IRelationship irel = (IRelationship)relationshipsToRemove.get(i);
verifyAssumption(irm.remove(hid,irel),"Failed to remove relationship "+irel.getName()+" for shid "+hid);
}
List rels = irm.get(hid);
if (rels==null || rels.size()==0) sourcesToRemove.add(hid);
}
}
}
}
}
// Remove sources that have no valid relationships any more
for (Iterator srciter = sourcesToRemove.iterator(); srciter.hasNext();) {
String hid = (String) srciter.next();
irm.removeAll(hid);
IProgramElement ipe = model.getElement(hid);
if (ipe!=null) {
// If the relationship was hanging off a 'code' node, delete it.
if (ipe.getKind().equals(IProgramElement.Kind.CODE)) {
//System.err.println("Deleting code node");
removeSingleNode(ipe);
}
}
}
} catch (IOException ioe) {
System.err.println("Failed to repair relationships:");
ioe.printStackTrace();
}
}
/**
* Removes a specified program element from the structure model.
* We go to the parent of the program element, ask for all its children
* and remove the node we want to delete from the list of children.
*/
private void removeSingleNode(IProgramElement progElem) {
verifyAssumption(progElem!=null);
boolean deleteOK = false;
IProgramElement parent = progElem.getParent();
List kids = parent.getChildren();
for (int i =0 ;i<kids.size();i++) {
if (kids.get(i).equals(progElem)) {
kids.remove(i);
deleteOK=true;
break;
}
}
verifyAssumption(deleteOK);
}
/**
* Removes a specified program element from the structure model.
* Two processing stages:
* <p>First: We go to the parent of the program element, ask for all its children
* and remove the node we want to delete from the list of children.
* <p>Second:We check if that parent has any other children. If it has no other
* children and it is either a CODE node or a PACKAGE node, we delete it too.
*/
private void removeNode(IProgramElement progElem) {
// StringBuffer flightrecorder = new StringBuffer();
try {
// flightrecorder.append("In removeNode, about to chuck away: "+progElem+"\n");
verifyAssumption(progElem!=null);
// boolean deleteOK = false;
IProgramElement parent = progElem.getParent();
// flightrecorder.append("Parent of it is "+parent+"\n");
List kids = parent.getChildren();
// flightrecorder.append("Which has "+kids.size()+" kids\n");
for (int i =0 ;i<kids.size();i++) {
// flightrecorder.append("Comparing with "+kids.get(i)+"\n");
if (kids.get(i).equals(progElem)) {
kids.remove(i);
// flightrecorder.append("Removing it\n");
// deleteOK=true;
break;
}
}
// verifyAssumption(deleteOK,flightrecorder.toString());
// Are there any kids left for this node?
if (parent.getChildren().size()==0 && parent.getParent()!=null &&
(parent.getKind().equals(IProgramElement.Kind.CODE) ||
parent.getKind().equals(IProgramElement.Kind.PACKAGE))) {
// This node is on its own, we should trim it too *as long as its not a structural node* which we currently check by making sure its a code node
// We should trim if it
// System.err.println("Deleting parent:"+parent);
removeNode(parent);
}
} catch (NullPointerException npe ){
// Occurred when commenting out other 2 ras classes in wsif?? reproducable?
// System.err.println(flightrecorder.toString());
npe.printStackTrace();
}
}
public static void verifyAssumption(boolean b,String info) {
if (!b) {
System.err.println("=========== ASSERTION IS NOT TRUE =========v");
System.err.println(info);
Thread.dumpStack();
System.err.println("=========== ASSERTION IS NOT TRUE =========^");
throw new RuntimeException("Assertion is false");
}
}
public static void verifyAssumption(boolean b) {
if (!b) {
Thread.dumpStack();
throw new RuntimeException("Assertion is false");
}
}
//===================== DELTA PROCESSING CODE ============== end ==========//
/**
* A ModelInfo object captures basic information about the structure model.
* It is used for testing and producing debug info.
*/
public static class ModelInfo {
private Hashtable nodeTypeCount = new Hashtable();
private Properties extraProperties = new Properties();
private ModelInfo(IHierarchy hierarchy,IRelationshipMap relationshipMap) {
IProgramElement ipe = hierarchy.getRoot();
walkModel(ipe);
recordStat("FileMapSize",
new Integer(hierarchy.getFileMapEntrySet().size()).toString());
recordStat("RelationshipMapSize",
new Integer(relationshipMap.getEntries().size()).toString());
}
private void walkModel(IProgramElement ipe) {
countNode(ipe);
List kids = ipe.getChildren();
for (Iterator iter = kids.iterator(); iter.hasNext();) {
IProgramElement nextElement = (IProgramElement) iter.next();
walkModel(nextElement);
}
}
private void countNode(IProgramElement ipe) {
String node = ipe.getKind().toString();
Integer ctr = (Integer)nodeTypeCount.get(node);
if (ctr==null) {
nodeTypeCount.put(node,new Integer(1));
} else {
ctr = new Integer(ctr.intValue()+1);
nodeTypeCount.put(node,ctr);
}
}
public String toString() {
StringBuffer sb = new StringBuffer();
sb.append("Model node summary:\n");
Enumeration nodeKeys = nodeTypeCount.keys();
while (nodeKeys.hasMoreElements()) {
String key = (String)nodeKeys.nextElement();
Integer ct = (Integer)nodeTypeCount.get(key);
sb.append(key+"="+ct+"\n");
}
sb.append("Model stats:\n");
Enumeration ks = extraProperties.keys();
while (ks.hasMoreElements()) {
String k = (String)ks.nextElement();
String v = extraProperties.getProperty(k);
sb.append(k+"="+v+"\n");
}
return sb.toString();
}
public Properties getProperties() {
Properties p = new Properties();
Enumeration nodeKeys = nodeTypeCount.keys();
while (nodeKeys.hasMoreElements()) {
String key = (String)nodeKeys.nextElement();
Integer ct = (Integer)nodeTypeCount.get(key);
p.setProperty(key,ct.toString());
}
p.putAll(extraProperties);
return p;
}
public void recordStat(String string, String string2) {
extraProperties.setProperty(string,string2);
}
public static ModelInfo summarizeModel() {
return new ModelInfo(AsmManager.getDefault().getHierarchy(),
AsmManager.getDefault().getRelationshipMap());
}
}
/**
* Set to indicate whether we are currently building a structure model, should
* be set up front.
*/
public static void setCreatingModel(boolean b) {
creatingModel = b;
}
/**
* returns true if we are currently generating a structure model, enables
* guarding of expensive operations on an empty/null model.
*/
public static boolean isCreatingModel() { return creatingModel;}
public static void setCompletingTypeBindings(boolean b) {
completingTypeBindings = b;
}
public static boolean isCompletingTypeBindings() { return completingTypeBindings; }
}
|
146,546 |
Bug 146546 Remove hard coded dependency on "|" in getFileName(..) methods
| null |
resolved fixed
|
38cc0dd
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-06-12T14:00:02Z | 2006-06-12T11:00:00Z |
asm/src/org/aspectj/asm/internal/AspectJElementHierarchy.java
|
/* *******************************************************************
* Copyright (c) 2003 Contributors.
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Eclipse Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Mik Kersten initial implementation
* Andy Clement Extensions for better IDE representation
* ******************************************************************/
package org.aspectj.asm.internal;
import java.io.*;
import java.util.*;
import org.aspectj.asm.*;
import org.aspectj.bridge.*;
/**
* @author Mik Kersten
*/
public class AspectJElementHierarchy implements IHierarchy {
private static final long serialVersionUID = 6462734311117048620L;
protected IProgramElement root = null;
protected String configFile = null;
private Map fileMap = null;
private Map handleMap = null;
private Map typeMap = null;
public IProgramElement getElement(String handle) {
IProgramElement cachedEntry = (IProgramElement)handleMap.get(handle);
if (cachedEntry!=null) return cachedEntry;
// StringTokenizer st = new StringTokenizer(handle, ProgramElement.ID_DELIM);
// int line = new Integer(st.nextToken()).intValue();
// int col = new Integer(st.nextToken()).intValue(); TODO: use column number when available
String file = AsmManager.getDefault().getHandleProvider().getFileForHandle(handle); // st.nextToken();
int line = AsmManager.getDefault().getHandleProvider().getLineNumberForHandle(handle); // st.nextToken();
int offSet = AsmManager.getDefault().getHandleProvider().getOffSetForHandle(handle);
String canonicalSFP = AsmManager.getDefault().getCanonicalFilePath(new File(file));
IProgramElement ret = findNodeForSourceLineHelper(root,canonicalSFP, line, offSet);
if (ret!=null) {
cache(handle,ret);
}
return ret;
}
public IProgramElement getRoot() {
return root;
}
public void setRoot(IProgramElement root) {
this.root = root;
handleMap = new HashMap();
typeMap = new HashMap();
}
public void addToFileMap( Object key, Object value ){
fileMap.put( key, value );
}
public boolean removeFromFileMap(Object key) {
return (fileMap.remove(key)!=null);
}
public void setFileMap(HashMap fileMap) {
this.fileMap = fileMap;
}
public Object findInFileMap( Object key ) {
return fileMap.get(key);
}
public Set getFileMapEntrySet() {
return fileMap.entrySet();
}
public boolean isValid() {
return root != null && fileMap != null;
}
/**
* Returns the first match
*
* @param parent
* @param kind not null
* @return null if not found
*/
public IProgramElement findElementForSignature(IProgramElement parent, IProgramElement.Kind kind, String signature) {
for (Iterator it = parent.getChildren().iterator(); it.hasNext(); ) {
IProgramElement node = (IProgramElement)it.next();
if (node.getKind() == kind && signature.equals(node.toSignatureString())) {
return node;
} else {
IProgramElement childSearch = findElementForSignature(node, kind, signature);
if (childSearch != null) return childSearch;
}
}
return null;
}
public IProgramElement findElementForLabel(
IProgramElement parent,
IProgramElement.Kind kind,
String label) {
for (Iterator it = parent.getChildren().iterator(); it.hasNext(); ) {
IProgramElement node = (IProgramElement)it.next();
if (node.getKind() == kind && label.equals(node.toLabelString())) {
return node;
} else {
IProgramElement childSearch = findElementForLabel(node, kind, label);
if (childSearch != null) return childSearch;
}
}
return null;
}
/**
* @param packageName if null default package is searched
* @param className can't be null
*/
public IProgramElement findElementForType(String packageName, String typeName) {
StringBuffer keyb = (packageName == null) ? new StringBuffer() :
new StringBuffer(packageName);
keyb.append(".");
keyb.append(typeName);
String key = keyb.toString();
IProgramElement ret = (IProgramElement) typeMap.get(key);
if (ret == null) {
IProgramElement packageNode = null;
if (packageName == null) {
packageNode = root;
} else {
if (root == null) return null;
List kids = root.getChildren();
if (kids == null) return null;
for (Iterator it = kids.iterator(); it.hasNext(); ) {
IProgramElement node = (IProgramElement)it.next();
if (packageName.equals(node.getName())) {
packageNode = node;
}
}
if (packageNode == null) return null;
}
// this searches each file for a class
for (Iterator it = packageNode.getChildren().iterator(); it.hasNext(); ) {
IProgramElement fileNode = (IProgramElement)it.next();
IProgramElement cNode = findClassInNodes(fileNode.getChildren(), typeName, typeName);
if (cNode != null) {
ret = cNode;
typeMap.put(key,ret);
}
}
}
return ret;
}
private IProgramElement findClassInNodes(Collection nodes, String name, String typeName) {
String baseName;
String innerName;
int dollar = name.indexOf('$');
if (dollar == -1) {
baseName = name;
innerName = null;
} else {
baseName = name.substring(0, dollar);
innerName = name.substring(dollar+1);
}
for (Iterator j = nodes.iterator(); j.hasNext(); ) {
IProgramElement classNode = (IProgramElement)j.next();
if (baseName.equals(classNode.getName())) {
if (innerName == null) return classNode;
else return findClassInNodes(classNode.getChildren(), innerName, typeName);
} else if (name.equals(classNode.getName())) {
return classNode;
} else if (typeName.equals(classNode.getBytecodeSignature())) {
return classNode;
} else if (classNode.getChildren() != null && !classNode.getChildren().isEmpty()){
IProgramElement node = findClassInNodes(classNode.getChildren(),name, typeName);
if (node != null) {
return node;
}
}
}
return null;
}
/**
* @param sourceFilePath modified to '/' delimited path for consistency
* @return a new structure node for the file if it was not found in the model
*/
public IProgramElement findElementForSourceFile(String sourceFile) {
try {
if (!isValid() || sourceFile == null) {
return IHierarchy.NO_STRUCTURE;
} else {
String correctedPath =
AsmManager.getDefault().getCanonicalFilePath(new File(sourceFile));
//StructureNode node = (StructureNode)getFileMap().get(correctedPath);//findFileNode(filePath, model);
IProgramElement node = (IProgramElement)findInFileMap(correctedPath);//findFileNode(filePath, model);
if (node != null) {
return node;
} else {
return createFileStructureNode(correctedPath);
}
}
} catch (Exception e) {
return IHierarchy.NO_STRUCTURE;
}
}
/**
* TODO: discriminate columns
*/
public IProgramElement findElementForSourceLine(ISourceLocation location) {
try {
return findElementForSourceLine(
AsmManager.getDefault().getCanonicalFilePath(
location.getSourceFile()),
location.getLine());
} catch (Exception e) {
return null;
}
}
/**
* Never returns null
*
* @param sourceFilePath canonicalized path for consistency
* @param lineNumber if 0 or 1 the corresponding file node will be returned
* @return a new structure node for the file if it was not found in the model
*/
public IProgramElement findElementForSourceLine(String sourceFilePath, int lineNumber) {
String canonicalSFP = AsmManager.getDefault().getCanonicalFilePath(
new File(sourceFilePath));
IProgramElement node = findNodeForSourceLineHelper(root, canonicalSFP, lineNumber, -1);
if (node != null) {
return node;
} else {
return createFileStructureNode(sourceFilePath);
}
}
public IProgramElement findElementForOffSet(String sourceFilePath, int lineNumber, int offSet) {
String canonicalSFP = AsmManager.getDefault().getCanonicalFilePath(
new File(sourceFilePath));
IProgramElement node = findNodeForSourceLineHelper(root, canonicalSFP, lineNumber, offSet);
if (node != null) {
return node;
} else {
return createFileStructureNode(sourceFilePath);
}
}
private IProgramElement createFileStructureNode(String sourceFilePath) {
// SourceFilePath might have originated on windows on linux...
int lastSlash = sourceFilePath.lastIndexOf('\\');
if (lastSlash == -1) {
lastSlash = sourceFilePath.lastIndexOf('/');
}
String fileName = sourceFilePath.substring(lastSlash+1);
IProgramElement fileNode = new ProgramElement(fileName, IProgramElement.Kind.FILE_JAVA, new SourceLocation(new File(sourceFilePath), 1, 1),0,null,null);
//fileNode.setSourceLocation();
fileNode.addChild(NO_STRUCTURE);
return fileNode;
}
private IProgramElement findNodeForSourceLineHelper(IProgramElement node, String sourceFilePath, int lineNumber, int offSet) {
if (matches(node, sourceFilePath, lineNumber, offSet)
&& !hasMoreSpecificChild(node, sourceFilePath, lineNumber, offSet)) {
return node;
}
if (node != null && node.getChildren() != null) {
for (Iterator it = node.getChildren().iterator(); it.hasNext(); ) {
IProgramElement foundNode = findNodeForSourceLineHelper(
(IProgramElement)it.next(),
sourceFilePath,
lineNumber,
offSet);
if (foundNode != null) return foundNode;
}
}
return null;
}
private boolean matches(IProgramElement node, String sourceFilePath, int lineNumber, int offSet) {
// try {
// if (node != null && node.getSourceLocation() != null)
// System.err.println("====\n1: " +
// sourceFilePath + "\n2: " +
// node.getSourceLocation().getSourceFile().getCanonicalPath().equals(sourceFilePath)
// );
return node != null
&& node.getSourceLocation() != null
&& node.getSourceLocation().getSourceFile().getAbsolutePath().equals(sourceFilePath)
&& ((offSet != -1 && node.getSourceLocation().getOffset() == offSet)
|| offSet == -1 )
&& ((node.getSourceLocation().getLine() <= lineNumber
&& node.getSourceLocation().getEndLine() >= lineNumber)
||
(lineNumber <= 1
&& node.getKind().isSourceFile())
);
// } catch (IOException ioe) {
// return false;
// }
}
private boolean hasMoreSpecificChild(IProgramElement node, String sourceFilePath, int lineNumber, int offSet) {
for (Iterator it = node.getChildren().iterator(); it.hasNext(); ) {
IProgramElement child = (IProgramElement)it.next();
if (matches(child, sourceFilePath, lineNumber, offSet)) return true;
}
return false;
}
public String getConfigFile() {
return configFile;
}
public void setConfigFile(String configFile) {
this.configFile = configFile;
}
// TODO: optimize this lookup
public IProgramElement findElementForHandle(String handle) {
// try the cache first...
IProgramElement ret = (IProgramElement) handleMap.get(handle);
if (ret != null) return ret;
// StringTokenizer st = new StringTokenizer(handle, ProgramElement.ID_DELIM);
// String file = st.nextToken();
// int line = new Integer(st.nextToken()).intValue();
// int col = new Integer(st.nextToken()).intValue();
// TODO: use column number when available
String file = AsmManager.getDefault().getHandleProvider().getFileForHandle(handle); // st.nextToken();
int line = AsmManager.getDefault().getHandleProvider().getLineNumberForHandle(handle); // st.nextToken();
int offSet = AsmManager.getDefault().getHandleProvider().getOffSetForHandle(handle);
ret = findElementForOffSet(file, line, offSet);
if (ret != null) {
cache(handle,(ProgramElement)ret);
}
return ret;
// IProgramElement parent = findElementForType(packageName, typeName);
// if (parent == null) return null;
// if (kind == IProgramElement.Kind.CLASS ||
// kind == IProgramElement.Kind.ASPECT) {
// return parent;
// } else {
// return findElementForSignature(parent, kind, name);
// }
}
//
// private IProgramElement findElementForBytecodeInfo(
// IProgramElement node,
// String parentName,
// String name,
// String signature) {
// for (Iterator it = node.getChildren().iterator(); it.hasNext(); ) {
// IProgramElement curr = (IProgramElement)it.next();
// if (parentName.equals(curr.getParent().getBytecodeName())
// && name.equals(curr.getBytecodeName())
// && signature.equals(curr.getBytecodeSignature())) {
// return node;
// } else {
// IProgramElement childSearch = findElementForBytecodeInfo(curr, parentName, name, signature);
// if (childSearch != null) return childSearch;
// }
// }
// return null;
// }
protected void cache(String handle, IProgramElement pe) {
if (!AsmManager.isCompletingTypeBindings()) {
handleMap.put(handle,pe);
}
}
public void flushTypeMap() {
typeMap.clear();
}
public void flushHandleMap() {
handleMap.clear();
}
public void flushFileMap() {
fileMap.clear();
}
// TODO rename this method ... it does more than just the handle map
public void updateHandleMap(Set deletedFiles) {
// Only delete the entries we need to from the handle map - for performance reasons
List forRemoval = new ArrayList();
Set k = handleMap.keySet();
for (Iterator iter = k.iterator(); iter.hasNext();) {
String handle = (String) iter.next();
if (deletedFiles.contains(getFilename(handle))) forRemoval.add(handle);
}
for (Iterator iter = forRemoval.iterator(); iter.hasNext();) {
String handle = (String) iter.next();
handleMap.remove(handle);
}
forRemoval.clear();
k = typeMap.keySet();
for (Iterator iter = k.iterator(); iter.hasNext();) {
String element = (String) iter.next();
IProgramElement ipe = (IProgramElement)typeMap.get(element);
if (deletedFiles.contains(getFilename(ipe.getHandleIdentifier()))) forRemoval.add(element);
}
for (Iterator iter = forRemoval.iterator(); iter.hasNext();) {
String handle = (String) iter.next();
typeMap.remove(handle);
}
forRemoval.clear();
k = fileMap.keySet();
for (Iterator iter = k.iterator(); iter.hasNext();) {
String element = (String) iter.next();
IProgramElement ipe = (IProgramElement)fileMap.get(element);
if (deletedFiles.contains(getFilename(ipe.getHandleIdentifier()))) forRemoval.add(element);
}
for (Iterator iter = forRemoval.iterator(); iter.hasNext();) {
String handle = (String) iter.next();
fileMap.remove(handle);
}
}
// XXX shouldn't be aware of the delimiter
private String getFilename(String hid) {
return hid.substring(0,hid.indexOf("|"));
}
}
|
136,707 |
Bug 136707 iajc should print summary like javac
|
The iajc ant task should produce a summary of what it is doing, like the javac task does: [javac] Compiling 189 source files to C:\project\classes
|
resolved fixed
|
008efca
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-06-13T19:45:44Z | 2006-04-13T17:40:00Z |
taskdefs/src/org/aspectj/tools/ant/taskdefs/AjcTask.java
|
/* *******************************************************************
* Copyright (c) 2001-2001 Xerox Corporation,
* 2002 Palo Alto Research Center, Incorporated (PARC)
* 2003-2004 Contributors.
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Eclipse Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Xerox/PARC initial implementation
* Wes Isberg 2003-2004 changes
* ******************************************************************/
package org.aspectj.tools.ant.taskdefs;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.StringTokenizer;
import org.apache.tools.ant.AntClassLoader;
import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.Location;
import org.apache.tools.ant.Project;
import org.apache.tools.ant.taskdefs.Copy;
import org.apache.tools.ant.taskdefs.Delete;
import org.apache.tools.ant.taskdefs.Execute;
import org.apache.tools.ant.taskdefs.Expand;
import org.apache.tools.ant.taskdefs.Javac;
import org.apache.tools.ant.taskdefs.LogStreamHandler;
import org.apache.tools.ant.taskdefs.MatchingTask;
import org.apache.tools.ant.taskdefs.Mkdir;
import org.apache.tools.ant.taskdefs.PumpStreamHandler;
import org.apache.tools.ant.taskdefs.Zip;
import org.apache.tools.ant.taskdefs.compilers.DefaultCompilerAdapter;
import org.apache.tools.ant.types.Commandline;
import org.apache.tools.ant.types.CommandlineJava;
import org.apache.tools.ant.types.FileSet;
import org.apache.tools.ant.types.Path;
import org.apache.tools.ant.types.PatternSet;
import org.apache.tools.ant.types.Reference;
import org.apache.tools.ant.types.ZipFileSet;
import org.apache.tools.ant.util.TaskLogger;
import org.aspectj.bridge.AbortException;
import org.aspectj.bridge.IMessage;
import org.aspectj.bridge.IMessageHandler;
import org.aspectj.bridge.IMessageHolder;
import org.aspectj.bridge.MessageHandler;
import org.aspectj.bridge.MessageUtil;
import org.aspectj.bridge.IMessage.Kind;
import org.aspectj.tools.ajc.Main;
import org.aspectj.util.FileUtil;
import org.aspectj.util.LangUtil;
/**
* This runs the AspectJ 1.1 compiler,
* supporting all the command-line options.
* In 1.1.1, ajc copies resources from input jars,
* but you can copy resources from the source directories
* using sourceRootCopyFilter.
* When not forking, things will be copied as needed
* for each iterative compile,
* but when forking things are only copied at the
* completion of a successful compile.
* <p>
* See the development environment guide for
* usage documentation.
*
* @since AspectJ 1.1, Ant 1.5
*/
public class AjcTask extends MatchingTask {
/*
* This task mainly converts ant specification for ajc,
* verbosely ignoring improper input.
* It also has some special features for non-obvious clients:
* (1) Javac compiler adapter supported in
* <code>setupAjc(AjcTask, Javac, File)</code>
* and
* <code>readArguments(String[])</code>;
* (2) testing is supported by
* (a) permitting the same specification to be re-run
* with added flags (settings once made cannot be
* removed); and
* (b) permitting recycling the task with
* <code>reset()</code> (untested).
*
* The parts that do more than convert ant specs are
* (a) code for forking;
* (b) code for copying resources.
*
* If you maintain/upgrade this task, keep in mind:
* (1) changes to the semantics of ajc (new options, new
* values permitted, etc.) will have to be reflected here.
* (2) the clients:
* the iajc ant script, Javac compiler adapter,
* maven clients of iajc, and testing code.
*/
// XXX move static methods after static initializer
/**
* This method extracts javac arguments to ajc,
* and add arguments to make ajc behave more like javac
* in copying resources.
* <p>
* Pass ajc-specific options using compilerarg sub-element:
* <pre>
* <javac srcdir="src">
* <compilerarg compiler="..." line="-argfile src/args.lst"/>
* <javac>
* </pre>
* Some javac arguments are not supported in this component (yet):
* <pre>
* String memoryInitialSize;
* boolean includeAntRuntime = true;
* boolean includeJavaRuntime = false;
* </pre>
* Other javac arguments are not supported in ajc 1.1:
* <pre>
* boolean optimize;
* String forkedExecutable;
* FacadeTaskHelper facade;
* boolean depend;
* String debugLevel;
* Path compileSourcepath;
* </pre>
* @param javac the Javac command to implement (not null)
* @param ajc the AjcTask to adapt (not null)
* @param destDir the File class destination directory (may be null)
* @return null if no error, or String error otherwise
*/
public String setupAjc(Javac javac) {
if (null == javac) {
return "null javac";
}
AjcTask ajc = this;
// no null checks b/c AjcTask handles null input gracefully
ajc.setProject(javac.getProject());
ajc.setLocation(javac.getLocation());
ajc.setTaskName("javac-iajc");
ajc.setDebug(javac.getDebug());
ajc.setDeprecation(javac.getDeprecation());
ajc.setFailonerror(javac.getFailonerror());
final boolean fork = javac.isForkedJavac();
ajc.setFork(fork);
if (fork) {
ajc.setMaxmem(javac.getMemoryMaximumSize());
}
ajc.setNowarn(javac.getNowarn());
ajc.setListFileArgs(javac.getListfiles());
ajc.setVerbose(javac.getVerbose());
ajc.setTarget(javac.getTarget());
ajc.setSource(javac.getSource());
ajc.setEncoding(javac.getEncoding());
File javacDestDir = javac.getDestdir();
if (null != javacDestDir) {
ajc.setDestdir(javacDestDir);
// filter requires dest dir
// mimic Javac task's behavior in copying resources,
ajc.setSourceRootCopyFilter("**/CVS/*,**/*.java,**/*.aj");
}
ajc.setBootclasspath(javac.getBootclasspath());
ajc.setExtdirs(javac.getExtdirs());
ajc.setClasspath(javac.getClasspath());
// ignore srcDir -- all files picked up in recalculated file list
// ajc.setSrcDir(javac.getSrcdir());
ajc.addFiles(javac.getFileList());
// arguments can override the filter, add to paths, override options
ajc.readArguments(javac.getCurrentCompilerArgs());
return null;
}
/**
* Find aspectjtools.jar on the task or system classpath.
* Accept <code>aspectj{-}tools{...}.jar</code>
* mainly to support build systems using maven-style
* re-naming
* (e.g., <code>aspectj-tools-1.1.0.jar</code>.
* Note that we search the task classpath first,
* though an entry on the system classpath would be loaded first,
* because it seems more correct as the more specific one.
* @return readable File for aspectjtools.jar, or null if not found.
*/
public static File findAspectjtoolsJar() {
File result = null;
ClassLoader loader = AjcTask.class.getClassLoader();
if (loader instanceof AntClassLoader) {
AntClassLoader taskLoader = (AntClassLoader) loader;
String cp = taskLoader.getClasspath();
String[] cps = LangUtil.splitClasspath(cp);
for (int i = 0; (i < cps.length) && (null == result); i++) {
result = isAspectjtoolsjar(cps[i]);
}
}
if (null == result) {
final Path classpath = Path.systemClasspath;
final String[] paths = classpath.list();
for (int i = 0; (i < paths.length) && (null == result); i++) {
result = isAspectjtoolsjar(paths[i]);
}
}
return (null == result? null : result.getAbsoluteFile());
}
/** @return File if readable jar with aspectj tools name, or null */
private static File isAspectjtoolsjar(String path) {
if (null == path) {
return null;
}
final String prefix = "aspectj";
final String infix = "tools";
final String altInfix = "-tools";
final String suffix = ".jar";
final int prefixLength = 7; // prefix.length();
final int minLength = 16;
// prefixLength + infix.length() + suffix.length();
if (!path.endsWith(suffix)) {
return null;
}
int loc = path.lastIndexOf(prefix);
if ((-1 != loc) && ((loc + minLength) <= path.length())) {
String rest = path.substring(loc+prefixLength);
if (-1 != rest.indexOf(File.pathSeparator)) {
return null;
}
if (rest.startsWith(infix)
|| rest.startsWith(altInfix)) {
File result = new File(path);
if (result.canRead() && result.isFile()) {
return result;
}
}
}
return null;
}
/**
* Maximum length (in chars) of command line
* before converting to an argfile when forking
*/
private static final int MAX_COMMANDLINE = 4096;
private static final File DEFAULT_DESTDIR = new File(".") {
public String toString() {
return "(no destination dir specified)";
}
};
/** do not throw BuildException on fail/abort message with usage */
private static final String USAGE_SUBSTRING = "AspectJ-specific options";
/** valid -X[...] options other than -Xlint variants */
private static final List VALID_XOPTIONS;
/** valid warning (-warn:[...]) variants */
private static final List VALID_WARNINGS;
/** valid debugging (-g:[...]) variants */
private static final List VALID_DEBUG;
/**
* -Xlint variants (error, warning, ignore)
* @see org.aspectj.weaver.Lint
*/
private static final List VALID_XLINT;
public static final String COMMAND_EDITOR_NAME
= AjcTask.class.getName() + ".COMMAND_EDITOR";
static final String[] TARGET_INPUTS = new String []
{ "1.1", "1.2", "1.3", "1.4", "1.5" };
static final String[] SOURCE_INPUTS = new String []
{ "1.3", "1.4", "1.5" };
static final String[] COMPLIANCE_INPUTS = new String []
{ "-1.3", "-1.4", "-1.5" };
private static final ICommandEditor COMMAND_EDITOR;
static {
// many now deprecated: reweavable*
String[] xs = new String[]
{ "serializableAspects", "incrementalFile", "lazyTjp",
"reweavable", "reweavable:compress", "notReweavable", "noInline",
"terminateAfterCompilation","hasMember",
"ajruntimetarget:1.2", "ajruntimetarget:1.5",
"addSerialVersionUID"
//, "targetNearSource", "OcodeSize",
};
VALID_XOPTIONS = Collections.unmodifiableList(Arrays.asList(xs));
xs = new String[]
{"constructorName", "packageDefaultMethod", "deprecation",
"maskedCatchBlocks", "unusedLocals", "unusedArguments",
"unusedImports", "syntheticAccess", "assertIdentifier", "none" };
VALID_WARNINGS = Collections.unmodifiableList(Arrays.asList(xs));
xs = new String[] {"none", "lines", "vars", "source" };
VALID_DEBUG = Collections.unmodifiableList(Arrays.asList(xs));
xs = new String[] { "error", "warning", "ignore"};
VALID_XLINT = Collections.unmodifiableList(Arrays.asList(xs));
ICommandEditor editor = null;
try {
String editorClassName = System.getProperty(COMMAND_EDITOR_NAME);
if (null != editorClassName) {
ClassLoader cl = AjcTask.class.getClassLoader();
Class editorClass = cl.loadClass(editorClassName);
editor = (ICommandEditor) editorClass.newInstance();
}
} catch (Throwable t) {
System.err.println("Warning: unable to load command editor");
t.printStackTrace(System.err);
}
COMMAND_EDITOR = editor;
}
// ---------------------------- state and Ant interface thereto
private boolean verbose;
private boolean listFileArgs;
private boolean failonerror;
private boolean fork;
private String maxMem;
private TaskLogger logger;
// ------- single entries dumped into cmd
protected GuardedCommand cmd;
// ------- lists resolved in addListArgs() at execute() time
private Path srcdir;
private Path injars;
private Path inpath;
private Path classpath;
private Path bootclasspath;
private Path forkclasspath;
private Path extdirs;
private Path aspectpath;
private Path argfiles;
private List ignored;
private Path sourceRoots;
private File xweaveDir;
private String xdoneSignal;
// ----- added by adapter - integrate better?
private List /* File */ adapterFiles;
private String[] adapterArguments;
private IMessageHolder messageHolder;
private ICommandEditor commandEditor;
// -------- resource-copying
/** true if copying injar non-.class files to the output jar */
private boolean copyInjars;
private boolean copyInpath;
/** non-null if copying all source root files but the filtered ones */
private String sourceRootCopyFilter;
/** non-null if copying all inpath dir files but the filtered ones */
private String inpathDirCopyFilter;
/** directory sink for classes */
private File destDir;
/** zip file sink for classes */
private File outjar;
/** track whether we've supplied any temp outjar */
private boolean outjarFixedup;
/**
* When possibly copying resources to the output jar,
* pass ajc a fake output jar to copy from,
* so we don't change the modification time of the output jar
* when copying injars/inpath into the actual outjar.
*/
private File tmpOutjar;
private boolean executing;
/** non-null only while executing in same vm */
private Main main;
/** true only when executing in other vm */
private boolean executingInOtherVM;
/** true if -incremental */
private boolean inIncrementalMode;
/** true if -XincrementalFile (i.e, setTagFile)*/
private boolean inIncrementalFileMode;
/** used when forking */
private CommandlineJava javaCmd = new CommandlineJava();
// also note MatchingTask grabs source files...
public AjcTask() {
reset();
}
/** to use this same Task more than once (testing) */
public void reset() { // XXX possible to reset MatchingTask?
// need declare for "all fields initialized in ..."
adapterArguments = null;
adapterFiles = new ArrayList();
argfiles = null;
executing = false;
aspectpath = null;
bootclasspath = null;
classpath = null;
cmd = new GuardedCommand();
copyInjars = false;
copyInpath = false;
destDir = DEFAULT_DESTDIR;
executing = false;
executingInOtherVM = false;
extdirs = null;
failonerror = true; // non-standard default
forkclasspath = null;
inIncrementalMode = false;
inIncrementalFileMode = false;
ignored = new ArrayList();
injars = null;
inpath = null;
listFileArgs = false;
maxMem = null;
messageHolder = null;
outjar = null;
sourceRootCopyFilter = null;
inpathDirCopyFilter = null;
sourceRoots = null;
srcdir = null;
tmpOutjar = null;
verbose = false;
xweaveDir = null;
xdoneSignal = null;
javaCmd = new CommandlineJava();
}
protected void ignore(String ignored) {
this.ignored.add(ignored + " at " + getLocation());
}
//---------------------- option values
// used by entries with internal commas
protected String validCommaList(String list, List valid, String label) {
return validCommaList(list, valid, label, valid.size());
}
protected String validCommaList(String list, List valid, String label, int max) {
StringBuffer result = new StringBuffer();
StringTokenizer st = new StringTokenizer(list, ",");
int num = 0;
while (st.hasMoreTokens()) {
String token = st.nextToken().trim();
num++;
if (num > max) {
ignore("too many entries for -"
+ label
+ ": "
+ token);
break;
}
if (!valid.contains(token)) {
ignore("bad commaList entry for -"
+ label
+ ": "
+ token);
} else {
if (0 < result.length()) {
result.append(",");
}
result.append(token);
}
}
return (0 == result.length() ? null : result.toString());
}
public void setIncremental(boolean incremental) {
cmd.addFlag("-incremental", incremental);
inIncrementalMode = incremental;
}
public void setHelp(boolean help) {
cmd.addFlag("-help", help);
}
public void setVersion(boolean version) {
cmd.addFlag("-version", version);
}
public void setXTerminateAfterCompilation(boolean b) {
cmd.addFlag("-XterminateAfterCompilation", b);
}
public void setXReweavable(boolean reweavable) {
cmd.addFlag("-Xreweavable",reweavable);
}
public void setXJoinpoints(String optionalJoinpoints) {
cmd.addFlag("-Xjoinpoints:"+optionalJoinpoints,true);
}
public void setXNoWeave(boolean b) {
if (logger!=null) logger.warning("the noweave option is no longer required and is being ignored");
}
public void setNoWeave(boolean b) {
if (logger!=null) logger.warning("the noweave option is no longer required and is being ignored");
}
public void setXNotReweavable(boolean notReweavable) {
cmd.addFlag("-XnotReweavable",notReweavable);
}
public void setXaddSerialVersionUID(boolean addUID) {
cmd.addFlag("-XaddSerialVersionUID",addUID);
}
public void setXNoInline(boolean noInline) {
cmd.addFlag("-XnoInline",noInline);
}
public void setShowWeaveInfo(boolean showweaveinfo) {
cmd.addFlag("-showWeaveInfo",showweaveinfo);
}
public void setNowarn(boolean nowarn) {
cmd.addFlag("-nowarn", nowarn);
}
public void setDeprecation(boolean deprecation) {
cmd.addFlag("-deprecation", deprecation);
}
public void setWarn(String warnings) {
warnings = validCommaList(warnings, VALID_WARNINGS, "warn");
cmd.addFlag("-warn:" + warnings, (null != warnings));
}
public void setDebug(boolean debug) {
cmd.addFlag("-g", debug);
}
public void setDebugLevel(String level) {
level = validCommaList(level, VALID_DEBUG, "g");
cmd.addFlag("-g:" + level, (null != level));
}
public void setEmacssym(boolean emacssym) {
cmd.addFlag("-emacssym", emacssym);
}
public void setCrossrefs(boolean on) {
cmd.addFlag("-crossrefs", on);
}
/**
* -Xlint - set default level of -Xlint messages to warning
* (same as </code>-Xlint:warning</code>)
*/
public void setXlintwarnings(boolean xlintwarnings) {
cmd.addFlag("-Xlint", xlintwarnings);
}
/** -Xlint:{error|warning|info} - set default level for -Xlint messages
* @param xlint the String with one of error, warning, ignored
*/
public void setXlint(String xlint) {
xlint = validCommaList(xlint, VALID_XLINT, "Xlint", 1);
cmd.addFlag("-Xlint:" + xlint, (null != xlint));
}
/**
* -Xlintfile {lint.properties} - enable or disable specific forms
* of -Xlint messages based on a lint properties file
* (default is
* <code>org/aspectj/weaver/XLintDefault.properties</code>)
* @param xlintFile the File with lint properties
*/
public void setXlintfile(File xlintFile) {
cmd.addFlagged("-Xlintfile", xlintFile.getAbsolutePath());
}
public void setPreserveAllLocals(boolean preserveAllLocals) {
cmd.addFlag("-preserveAllLocals", preserveAllLocals);
}
public void setNoImportError(boolean noImportError) {
cmd.addFlag("-warn:-unusedImport", noImportError);
}
public void setEncoding(String encoding) {
cmd.addFlagged("-encoding", encoding);
}
public void setLog(File file) {
cmd.addFlagged("-log", file.getAbsolutePath());
}
public void setProceedOnError(boolean proceedOnError) {
cmd.addFlag("-proceedOnError", proceedOnError);
}
public void setVerbose(boolean verbose) {
cmd.addFlag("-verbose", verbose);
this.verbose = verbose;
}
public void setListFileArgs(boolean listFileArgs) {
this.listFileArgs = listFileArgs;
}
public void setReferenceInfo(boolean referenceInfo) {
cmd.addFlag("-referenceInfo", referenceInfo);
}
public void setTime(boolean time) {
cmd.addFlag("-time", time);
}
public void setNoExit(boolean noExit) {
cmd.addFlag("-noExit", noExit);
}
public void setFailonerror(boolean failonerror) {
this.failonerror = failonerror;
}
/**
* @return true if fork was set
*/
public boolean isForked() {
return fork;
}
public void setFork(boolean fork) {
this.fork = fork;
}
public void setMaxmem(String maxMem) {
this.maxMem = maxMem;
}
/** support for nested <jvmarg> elements */
public Commandline.Argument createJvmarg() {
return this.javaCmd.createVmArgument();
}
// ----------------
public void setTagFile(File file) {
inIncrementalMode = true;
cmd.addFlagged(Main.CommandController.TAG_FILE_OPTION,
file.getAbsolutePath());
inIncrementalFileMode = true;
}
public void setOutjar(File file) {
if (DEFAULT_DESTDIR != destDir) {
String e = "specifying both output jar ("
+ file
+ ") and destination dir ("
+ destDir
+ ")";
throw new BuildException(e);
}
outjar = file;
outjarFixedup = false;
tmpOutjar = null;
}
public void setOutxml(boolean outxml) {
cmd.addFlag("-outxml",outxml);
}
public void setOutxmlfile(String name) {
cmd.addFlagged("-outxmlfile", name);
}
public void setDestdir(File dir) {
if (null != outjar) {
String e = "specifying both output jar ("
+ outjar
+ ") and destination dir ("
+ dir
+ ")";
throw new BuildException(e);
}
cmd.addFlagged("-d", dir.getAbsolutePath());
destDir = dir;
}
/**
* @param input a String in TARGET_INPUTS
*/
public void setTarget(String input) {
String ignore = cmd.addOption("-target", TARGET_INPUTS, input);
if (null != ignore) {
ignore(ignore);
}
}
/**
* Language compliance level.
* If not set explicitly, eclipse default holds.
* @param input a String in COMPLIANCE_INPUTS
*/
public void setCompliance(String input) {
String ignore = cmd.addOption(null, COMPLIANCE_INPUTS, input);
if (null != ignore) {
ignore(ignore);
}
}
/**
* Source compliance level.
* If not set explicitly, eclipse default holds.
* @param input a String in SOURCE_INPUTS
*/
public void setSource(String input) {
String ignore = cmd.addOption("-source", SOURCE_INPUTS, input);
if (null != ignore) {
ignore(ignore);
}
}
/**
* Flag to copy all non-.class contents of injars
* to outjar after compile completes.
* Requires both injars and outjar.
* @param doCopy
*/
public void setCopyInjars(boolean doCopy){
ignore("copyInJars");
log("copyInjars not required since 1.1.1.\n", Project.MSG_WARN);
//this.copyInjars = doCopy;
}
/**
* Option to copy all files from
* all source root directories
* except those specified here.
* If this is specified and sourceroots are specified,
* then this will copy all files except
* those specified in the filter pattern.
* Requires sourceroots.
*
* @param filter a String acceptable as an excludes
* filter for an Ant Zip fileset.
*/
public void setSourceRootCopyFilter(String filter){
this.sourceRootCopyFilter = filter;
}
/**
* Option to copy all files from
* all inpath directories
* except the files specified here.
* If this is specified and inpath directories are specified,
* then this will copy all files except
* those specified in the filter pattern.
* Requires inpath.
* If the input does not contain "**\/*.class", then
* this prepends it, to avoid overwriting woven classes
* with unwoven input.
* @param filter a String acceptable as an excludes
* filter for an Ant Zip fileset.
*/
public void setInpathDirCopyFilter(String filter){
if (null != filter) {
if (-1 == filter.indexOf("**/*.class")) {
filter = "**/*.class," + filter;
}
}
this.inpathDirCopyFilter = filter;
}
public void setX(String input) { // ajc-only eajc-also docDone
StringTokenizer tokens = new StringTokenizer(input, ",", false);
while (tokens.hasMoreTokens()) {
String token = tokens.nextToken().trim();
if (1 < token.length()) {
// new special case: allow -Xset:anything
if (VALID_XOPTIONS.contains(token) || token.indexOf("set:")==0 ||
token.indexOf("joinpoints:")==0) {
cmd.addFlag("-X" + token, true);
} else {
ignore("-X" + token);
}
}
}
}
public void setXDoneSignal(String doneSignal) {
this.xdoneSignal = doneSignal;
}
/** direct API for testing */
public void setMessageHolder(IMessageHolder holder) {
this.messageHolder = holder;
}
/**
* Setup custom message handling.
* @param className the String fully-qualified-name of a class
* reachable from this object's class loader,
* implementing IMessageHolder, and
* having a public no-argument constructor.
* @throws BuildException if unable to create instance of className
*/
public void setMessageHolderClass(String className) {
try {
Class mclass = Class.forName(className);
IMessageHolder holder = (IMessageHolder) mclass.newInstance();
setMessageHolder(holder);
} catch (Throwable t) {
String m = "unable to instantiate message holder: " + className;
throw new BuildException(m, t);
}
}
/** direct API for testing */
public void setCommandEditor(ICommandEditor editor) {
this.commandEditor = editor;
}
/**
* Setup command-line filter.
* To do this staticly, define the environment variable
* <code>org.aspectj.tools.ant.taskdefs.AjcTask.COMMAND_EDITOR</code>
* with the <code>className</code> parameter.
* @param className the String fully-qualified-name of a class
* reachable from this object's class loader,
* implementing ICommandEditor, and
* having a public no-argument constructor.
* @throws BuildException if unable to create instance of className
*/
public void setCommandEditorClass(String className) { // skip Ant interface?
try {
Class mclass = Class.forName(className);
setCommandEditor((ICommandEditor) mclass.newInstance());
} catch (Throwable t) {
String m = "unable to instantiate command editor: " + className;
throw new BuildException(m, t);
}
}
//---------------------- Path lists
/**
* Add path elements to source path and return result.
* Elements are added even if they do not exist.
* @param source the Path to add to - may be null
* @param toAdd the Path to add - may be null
* @return the (never-null) Path that results
*/
protected Path incPath(Path source, Path toAdd) {
if (null == source) {
source = new Path(project);
}
if (null != toAdd) {
source.append(toAdd);
}
return source;
}
public void setSourcerootsref(Reference ref) {
createSourceRoots().setRefid(ref);
}
public void setSourceRoots(Path roots) {
sourceRoots = incPath(sourceRoots, roots);
}
public Path createSourceRoots() {
if (sourceRoots == null) {
sourceRoots = new Path(project);
}
return sourceRoots.createPath();
}
public void setXWeaveDir(File file) {
if ((null != file) && file.isDirectory()
&& file.canRead()) {
xweaveDir = file;
}
}
public void setInjarsref(Reference ref) {
createInjars().setRefid(ref);
}
public void setInpathref(Reference ref) {
createInpath().setRefid(ref);
}
public void setInjars(Path path) {
injars = incPath(injars, path);
}
public void setInpath(Path path) {
inpath = incPath(inpath,path);
}
public Path createInjars() {
if (injars == null) {
injars = new Path(project);
}
return injars.createPath();
}
public Path createInpath() {
if (inpath == null) {
inpath = new Path(project);
}
return inpath.createPath();
}
public void setClasspath(Path path) {
classpath = incPath(classpath, path);
}
public void setClasspathref(Reference classpathref) {
createClasspath().setRefid(classpathref);
}
public Path createClasspath() {
if (classpath == null) {
classpath = new Path(project);
}
return classpath.createPath();
}
public void setBootclasspath(Path path) {
bootclasspath = incPath(bootclasspath, path);
}
public void setBootclasspathref(Reference bootclasspathref) {
createBootclasspath().setRefid(bootclasspathref);
}
public Path createBootclasspath() {
if (bootclasspath == null) {
bootclasspath = new Path(project);
}
return bootclasspath.createPath();
}
public void setForkclasspath(Path path) {
forkclasspath = incPath(forkclasspath, path);
}
public void setForkclasspathref(Reference forkclasspathref) {
createForkclasspath().setRefid(forkclasspathref);
}
public Path createForkclasspath() {
if (forkclasspath == null) {
forkclasspath = new Path(project);
}
return forkclasspath.createPath();
}
public void setExtdirs(Path path) {
extdirs = incPath(extdirs, path);
}
public void setExtdirsref(Reference ref) {
createExtdirs().setRefid(ref);
}
public Path createExtdirs() {
if (extdirs == null) {
extdirs = new Path(project);
}
return extdirs.createPath();
}
public void setAspectpathref(Reference ref) {
createAspectpath().setRefid(ref);
}
public void setAspectpath(Path path) {
aspectpath = incPath(aspectpath, path);
}
public Path createAspectpath() {
if (aspectpath == null) {
aspectpath = new Path(project);
}
return aspectpath.createPath();
}
public void setSrcDir(Path path) {
srcdir = incPath(srcdir, path);
}
public Path createSrc() {
return createSrcdir();
}
public Path createSrcdir() {
if (srcdir == null) {
srcdir = new Path(project);
}
return srcdir.createPath();
}
/** @return true if in incremental mode (command-line or file) */
public boolean isInIncrementalMode() {
return inIncrementalMode;
}
/** @return true if in incremental file mode */
public boolean isInIncrementalFileMode() {
return inIncrementalFileMode;
}
public void setArgfilesref(Reference ref) {
createArgfiles().setRefid(ref);
}
public void setArgfiles(Path path) { // ajc-only eajc-also docDone
argfiles = incPath(argfiles, path);
}
public Path createArgfiles() {
if (argfiles == null) {
argfiles = new Path(project);
}
return argfiles.createPath();
}
// ------------------------------ run
/**
* Compile using ajc per settings.
* @exception BuildException if the compilation has problems
* or if there were compiler errors and failonerror is true.
*/
public void execute() throws BuildException {
this.logger = new TaskLogger(this);
if (executing) {
throw new IllegalStateException("already executing");
} else {
executing = true;
}
setupOptions();
verifyOptions();
try {
String[] args = makeCommand();
logVerbose("ajc " + Arrays.asList(args));
if (!fork) {
executeInSameVM(args);
} else { // when forking, Adapter handles failonerror
executeInOtherVM(args);
}
} catch (BuildException e) {
throw e;
} catch (Throwable x) {
this.logger.error(Main.renderExceptionForUser(x));
throw new BuildException("IGNORE -- See "
+ LangUtil.unqualifiedClassName(x)
+ " rendered to ant logger");
} finally {
executing = false;
if (null != tmpOutjar) {
tmpOutjar.delete();
}
}
}
/**
* Halt processing.
* This tells main in the same vm to quit.
* It fails when running in forked mode.
* @return true if not in forked mode
* and main has quit or been told to quit
*/
public boolean quit() {
if (executingInOtherVM) {
return false;
}
Main me = main;
if (null != me) {
me.quit();
}
return true;
}
// package-private for testing
String[] makeCommand() {
ArrayList result = new ArrayList();
if (0 < ignored.size()) {
for (Iterator iter = ignored.iterator(); iter.hasNext();) {
logVerbose("ignored: " + iter.next());
}
}
// when copying resources, use temp jar for class output
// then copy temp jar contents and resources to output jar
if ((null != outjar) && !outjarFixedup) {
if (copyInjars || copyInpath || (null != sourceRootCopyFilter)
|| (null != inpathDirCopyFilter)) {
String path = outjar.getAbsolutePath();
int len = FileUtil.zipSuffixLength(path);
path = path.substring(0, path.length()-len) + ".tmp.jar";
tmpOutjar = new File(path);
}
if (null == tmpOutjar) {
cmd.addFlagged("-outjar", outjar.getAbsolutePath());
} else {
cmd.addFlagged("-outjar", tmpOutjar.getAbsolutePath());
}
outjarFixedup = true;
}
result.addAll(cmd.extractArguments());
addListArgs(result);
String[] command = (String[]) result.toArray(new String[0]);
if (null != commandEditor) {
command = commandEditor.editCommand(command);
} else if (null != COMMAND_EDITOR) {
command = COMMAND_EDITOR.editCommand(command);
}
return command;
}
/**
* Create any pseudo-options required to implement
* some of the macro options
* @throws BuildException if options conflict
*/
protected void setupOptions() {
if (null != xweaveDir) {
if (DEFAULT_DESTDIR != destDir) {
throw new BuildException("weaveDir forces destdir");
}
if (null != outjar) {
throw new BuildException("weaveDir forces outjar");
}
if (null != injars) {
throw new BuildException("weaveDir incompatible with injars now");
}
if (null != inpath) {
throw new BuildException("weaveDir incompatible with inpath now");
}
File injar = zipDirectory(xweaveDir);
setInjars(new Path(getProject(), injar.getAbsolutePath()));
setDestdir(xweaveDir);
}
}
protected File zipDirectory(File dir) {
File tempDir = new File(".");
try {
tempDir = File.createTempFile("AjcTest", ".tmp");
tempDir.mkdirs();
tempDir.deleteOnExit(); // XXX remove zip explicitly..
} catch (IOException e) {
// ignore
}
// File result = new File(tempDir,
String filename = "AjcTask-"
+ System.currentTimeMillis()
+ ".zip";
File result = new File(filename);
Zip zip = new Zip();
zip.setProject(getProject());
zip.setDestFile(result);
zip.setTaskName(getTaskName() + " - zip");
FileSet fileset = new FileSet();
fileset.setDir(dir);
zip.addFileset(fileset);
zip.execute();
Delete delete = new Delete();
delete.setProject(getProject());
delete.setTaskName(getTaskName() + " - delete");
delete.setDir(dir);
delete.execute();
Mkdir mkdir = new Mkdir();
mkdir.setProject(getProject());
mkdir.setTaskName(getTaskName() + " - mkdir");
mkdir.setDir(dir);
mkdir.execute();
return result;
}
/**
* @throw BuildException if options conflict
*/
protected void verifyOptions() {
StringBuffer sb = new StringBuffer();
if (fork && isInIncrementalMode() && !isInIncrementalFileMode()) {
sb.append("can fork incremental only using tag file.\n");
}
if (((null != inpathDirCopyFilter) || (null != sourceRootCopyFilter))
&& (null == outjar) && (DEFAULT_DESTDIR == destDir)) {
final String REQ = " requires dest dir or output jar.\n";
if (null == inpathDirCopyFilter) {
sb.append("sourceRootCopyFilter");
} else if (null == sourceRootCopyFilter) {
sb.append("inpathDirCopyFilter");
} else {
sb.append("sourceRootCopyFilter and inpathDirCopyFilter");
}
sb.append(REQ);
}
if (0 < sb.length()) {
throw new BuildException(sb.toString());
}
}
/**
* Run the compile in the same VM by
* loading the compiler (Main),
* setting up any message holders,
* doing the compile,
* and converting abort/failure and error messages
* to BuildException, as appropriate.
* @throws BuildException if abort or failure messages
* or if errors and failonerror.
*
*/
protected void executeInSameVM(String[] args) {
if (null != maxMem) {
log("maxMem ignored unless forked: " + maxMem, Project.MSG_WARN);
}
IMessageHolder holder = messageHolder;
int numPreviousErrors;
if (null == holder) {
MessageHandler mhandler = new MessageHandler(true);
final IMessageHandler delegate;
delegate = new AntMessageHandler(this.logger,this.verbose, false);
mhandler.setInterceptor(delegate);
holder = mhandler;
numPreviousErrors = 0;
} else {
numPreviousErrors = holder.numMessages(IMessage.ERROR, true);
}
{
Main newmain = new Main();
newmain.setHolder(holder);
newmain.setCompletionRunner(new Runnable() {
public void run() {
doCompletionTasks();
}
});
if (null != main) {
MessageUtil.fail(holder, "still running prior main");
return;
}
main = newmain;
}
main.runMain(args, false);
if (failonerror) {
int errs = holder.numMessages(IMessage.ERROR, false);
errs -= numPreviousErrors;
if (0 < errs) {
String m = errs + " errors";
MessageUtil.print(System.err, holder, "", MessageUtil.MESSAGE_ALL, MessageUtil.PICK_ERROR, true);
throw new BuildException(m);
}
}
// Throw BuildException if there are any fail or abort
// messages.
// The BuildException message text has a list of class names
// for the exceptions found in the messages, or the
// number of fail/abort messages found if there were
// no exceptions for any of the fail/abort messages.
// The interceptor message handler should have already
// printed the messages, including any stack traces.
// HACK: this ignores the Usage message
{
IMessage[] fails = holder.getMessages(IMessage.FAIL, true);
if (!LangUtil.isEmpty(fails)) {
StringBuffer sb = new StringBuffer();
String prefix = "fail due to ";
int numThrown = 0;
for (int i = 0; i < fails.length; i++) {
String message = fails[i].getMessage();
if (LangUtil.isEmpty(message)) {
message = "<no message>";
} else if (-1 != message.indexOf(USAGE_SUBSTRING)) {
continue;
}
Throwable t = fails[i].getThrown();
if (null != t) {
numThrown++;
sb.append(prefix);
sb.append(LangUtil.unqualifiedClassName(t.getClass()));
String thrownMessage = t.getMessage();
if (!LangUtil.isEmpty(thrownMessage)) {
sb.append(" \"" + thrownMessage + "\"");
}
}
sb.append("\"" + message + "\"");
prefix = ", ";
}
if (0 < sb.length()) {
sb.append(" (" + numThrown + " exceptions)");
throw new BuildException(sb.toString());
}
}
}
}
/**
* Execute in a separate VM.
* Differences from normal same-VM execution:
* <ul>
* <li>ignores any message holder {class} set</li>
* <li>No resource-copying between interative runs</li>
* <li>failonerror fails when process interface fails
* to return negative values</li>
* </ul>
* @param args String[] of the complete compiler command to execute
*
* @see DefaultCompilerAdapter#executeExternalCompile(String[], int)
* @throws BuildException if ajc aborts (negative value)
* or if failonerror and there were compile errors.
*/
protected void executeInOtherVM(String[] args) {
javaCmd.setClassname(org.aspectj.tools.ajc.Main.class.getName());
final Path vmClasspath = javaCmd.createClasspath(getProject());
{
File aspectjtools = null;
int vmClasspathSize = vmClasspath.size();
if ((null != forkclasspath)
&& (0 != forkclasspath.size())) {
vmClasspath.addExisting(forkclasspath);
} else {
aspectjtools = findAspectjtoolsJar();
if (null != aspectjtools) {
vmClasspath.createPathElement().setLocation(aspectjtools);
}
}
int newVmClasspathSize = vmClasspath.size();
if (vmClasspathSize == newVmClasspathSize) {
String m = "unable to find aspectjtools to fork - ";
if (null != aspectjtools) {
m += "tried " + aspectjtools.toString();
} else if (null != forkclasspath) {
m += "tried " + forkclasspath.toString();
} else {
m += "define forkclasspath or put aspectjtools on classpath";
}
throw new BuildException(m);
}
}
if (null != maxMem) {
javaCmd.setMaxmemory(maxMem);
}
File tempFile = null;
int numArgs = args.length;
args = GuardedCommand.limitTo(args, MAX_COMMANDLINE, getLocation());
if (args.length != numArgs) {
tempFile = new File(args[1]);
}
try {
boolean setMessageHolderOnForking = (this.messageHolder != null);
String[] javaArgs = javaCmd.getCommandline();
String[] both = new String[javaArgs.length + args.length + (setMessageHolderOnForking ? 2 : 0)];
System.arraycopy(javaArgs,0,both,0,javaArgs.length);
System.arraycopy(args,0,both,javaArgs.length,args.length);
if (setMessageHolderOnForking) {
both[both.length - 2] = "-messageHolder";
both[both.length - 1] = this.messageHolder.getClass().getName();
}
// try to use javaw instead on windows
if (both[0].endsWith("java.exe")) {
String path = both[0];
path = path.substring(0, path.length()-4);
path = path + "w.exe";
File javaw = new File(path);
if (javaw.canRead() && javaw.isFile()) {
both[0] = path;
}
}
logVerbose("forking " + Arrays.asList(both));
int result = execInOtherVM(both);
if (0 > result) {
throw new BuildException("failure[" + result + "] running ajc");
} else if (failonerror && (0 < result)) {
throw new BuildException("compile errors: " + result);
}
// when forking, do completion only at end and when successful
doCompletionTasks();
} finally {
if (null != tempFile) {
tempFile.delete();
}
}
}
/**
* Execute in another process using the same JDK
* and the base directory of the project. XXX correct?
* @param args
* @return
*/
protected int execInOtherVM(String[] args) {
try {
Project project = getProject();
PumpStreamHandler handler = new LogStreamHandler(this,
verbose ? Project.MSG_VERBOSE : Project.MSG_INFO,
Project.MSG_WARN);
// replace above two lines with what follows as an aid to debugging when running the unit tests....
// LogStreamHandler handler = new LogStreamHandler(this,
// Project.MSG_INFO, Project.MSG_WARN) {
//
// ByteArrayOutputStream baos = new ByteArrayOutputStream();
// /* (non-Javadoc)
// * @see org.apache.tools.ant.taskdefs.PumpStreamHandler#createProcessOutputPump(java.io.InputStream, java.io.OutputStream)
// */
// protected void createProcessErrorPump(InputStream is,
// OutputStream os) {
// super.createProcessErrorPump(is, baos);
// }
//
// /* (non-Javadoc)
// * @see org.apache.tools.ant.taskdefs.LogStreamHandler#stop()
// */
// public void stop() {
// byte[] written = baos.toByteArray();
// System.err.print(new String(written));
// super.stop();
// }
// };
Execute exe = new Execute(handler);
exe.setAntRun(project);
exe.setWorkingDirectory(project.getBaseDir());
exe.setCommandline(args);
try {
if (executingInOtherVM) {
String s = "already running in other vm?";
throw new BuildException(s, location);
}
executingInOtherVM = true;
exe.execute();
} finally {
executingInOtherVM = false;
}
return exe.getExitValue();
} catch (IOException e) {
String m = "Error executing command " + Arrays.asList(args);
throw new BuildException(m, e, location);
}
}
// ------------------------------ setup and reporting
/** @return null if path null or empty, String rendition otherwise */
protected static void addFlaggedPath(String flag, Path path, List list) {
if (!LangUtil.isEmpty(flag)
&& ((null != path) && (0 < path.size()))) {
list.add(flag);
list.add(path.toString());
}
}
/**
* Add to list any path or plural arguments.
*/
protected void addListArgs(List list) throws BuildException {
addFlaggedPath("-classpath", classpath, list);
addFlaggedPath("-bootclasspath", bootclasspath, list);
addFlaggedPath("-extdirs", extdirs, list);
addFlaggedPath("-aspectpath", aspectpath, list);
addFlaggedPath("-injars", injars, list);
addFlaggedPath("-inpath", inpath, list);
addFlaggedPath("-sourceroots", sourceRoots, list);
if (argfiles != null) {
String[] files = argfiles.list();
for (int i = 0; i < files.length; i++) {
File argfile = project.resolveFile(files[i]);
if (check(argfile, files[i], false, location)) {
list.add("-argfile");
list.add(argfile.getAbsolutePath());
}
}
}
if (srcdir != null) {
// todo: ignore any srcdir if any argfiles and no explicit includes
String[] dirs = srcdir.list();
for (int i = 0; i < dirs.length; i++) {
File dir = project.resolveFile(dirs[i]);
check(dir, dirs[i], true, location);
// relies on compiler to prune non-source files
String[] files = getDirectoryScanner(dir).getIncludedFiles();
for (int j = 0; j < files.length; j++) {
File file = new File(dir, files[j]);
if (FileUtil.hasSourceSuffix(file)) {
list.add(file.getAbsolutePath());
}
}
}
}
if (0 < adapterFiles.size()) {
for (Iterator iter = adapterFiles.iterator(); iter.hasNext();) {
File file = (File) iter.next();
if (file.canRead() && FileUtil.hasSourceSuffix(file)) {
list.add(file.getAbsolutePath());
} else {
this.logger.warning("skipping file: " + file);
}
}
}
}
/**
* Throw BuildException unless file is valid.
* @param file the File to check
* @param name the symbolic name to print on error
* @param isDir if true, verify file is a directory
* @param loc the Location used to create sensible BuildException
* @return
* @throws BuildException unless file valid
*/
protected final boolean check(File file, String name,
boolean isDir, Location loc) {
loc = loc != null ? loc : location;
if (file == null) {
throw new BuildException(name + " is null!", loc);
}
if (!file.exists()) {
throw new BuildException(file + " doesn't exist!", loc);
}
if (isDir ^ file.isDirectory()) {
String e = file + " should" + (isDir ? "" : "n't") +
" be a directory!";
throw new BuildException(e, loc);
}
return true;
}
/**
* Called when compile or incremental compile is completing,
* this completes the output jar or directory
* by copying resources if requested.
* Note: this is a callback run synchronously by the compiler.
* That means exceptions thrown here are caught by Main.run(..)
* and passed to the message handler.
*/
protected void doCompletionTasks() {
if (!executing) {
throw new IllegalStateException("should be executing");
}
if (null != outjar) {
completeOutjar();
} else {
completeDestdir();
}
if (null != xdoneSignal) {
MessageUtil.info(messageHolder, xdoneSignal);
}
}
/**
* Complete the destination directory
* by copying resources from the source root directories
* (if the filter is specified)
* and non-.class files from the input jars
* (if XCopyInjars is enabled).
*/
private void completeDestdir() {
if (!copyInjars && (null == sourceRootCopyFilter)
&& (null == inpathDirCopyFilter)) {
return;
} else if ((destDir == DEFAULT_DESTDIR)
|| !destDir.canWrite()) {
String s = "unable to copy resources to destDir: " + destDir;
throw new BuildException(s);
}
final Project project = getProject();
if (copyInjars) { // XXXX remove as unused since 1.1.1
if (null != inpath) {
log("copyInjars does not support inpath.\n", Project.MSG_WARN);
}
String taskName = getTaskName() + " - unzip";
String[] paths = injars.list();
if (!LangUtil.isEmpty(paths)) {
PatternSet patternSet = new PatternSet();
patternSet.setProject(project);
patternSet.setIncludes("**/*");
patternSet.setExcludes("**/*.class");
for (int i = 0; i < paths.length; i++) {
Expand unzip = new Expand();
unzip.setProject(project);
unzip.setTaskName(taskName);
unzip.setDest(destDir);
unzip.setSrc(new File(paths[i]));
unzip.addPatternset(patternSet);
unzip.execute();
}
}
}
if ((null != sourceRootCopyFilter) && (null != sourceRoots)) {
String[] paths = sourceRoots.list();
if (!LangUtil.isEmpty(paths)) {
Copy copy = new Copy();
copy.setProject(project);
copy.setTodir(destDir);
for (int i = 0; i < paths.length; i++) {
FileSet fileSet = new FileSet();
fileSet.setDir(new File(paths[i]));
fileSet.setIncludes("**/*");
fileSet.setExcludes(sourceRootCopyFilter);
copy.addFileset(fileSet);
}
copy.execute();
}
}
if ((null != inpathDirCopyFilter) && (null != inpath)) {
String[] paths = inpath.list();
if (!LangUtil.isEmpty(paths)) {
Copy copy = new Copy();
copy.setProject(project);
copy.setTodir(destDir);
boolean gotDir = false;
for (int i = 0; i < paths.length; i++) {
File inpathDir = new File(paths[i]);
if (inpathDir.isDirectory() && inpathDir.canRead()) {
if (!gotDir) {
gotDir = true;
}
FileSet fileSet = new FileSet();
fileSet.setDir(inpathDir);
fileSet.setIncludes("**/*");
fileSet.setExcludes(inpathDirCopyFilter);
copy.addFileset(fileSet);
}
}
if (gotDir) {
copy.execute();
}
}
}
}
/**
* Complete the output jar
* by copying resources from the source root directories
* if the filter is specified.
* and non-.class files from the input jars if enabled.
*/
private void completeOutjar() {
if (((null == tmpOutjar) || !tmpOutjar.canRead())
|| (!copyInjars && (null == sourceRootCopyFilter)
&& (null == inpathDirCopyFilter))) {
return;
}
Zip zip = new Zip();
Project project = getProject();
zip.setProject(project);
zip.setTaskName(getTaskName() + " - zip");
zip.setDestFile(outjar);
ZipFileSet zipfileset = new ZipFileSet();
zipfileset.setProject(project);
zipfileset.setSrc(tmpOutjar);
zipfileset.setIncludes("**/*.class");
zip.addZipfileset(zipfileset);
if (copyInjars) {
String[] paths = injars.list();
if (!LangUtil.isEmpty(paths)) {
for (int i = 0; i < paths.length; i++) {
File jarFile = new File(paths[i]);
zipfileset = new ZipFileSet();
zipfileset.setProject(project);
zipfileset.setSrc(jarFile);
zipfileset.setIncludes("**/*");
zipfileset.setExcludes("**/*.class");
zip.addZipfileset(zipfileset);
}
}
}
if ((null != sourceRootCopyFilter) && (null != sourceRoots)) {
String[] paths = sourceRoots.list();
if (!LangUtil.isEmpty(paths)) {
for (int i = 0; i < paths.length; i++) {
File srcRoot = new File(paths[i]);
FileSet fileset = new FileSet();
fileset.setProject(project);
fileset.setDir(srcRoot);
fileset.setIncludes("**/*");
fileset.setExcludes(sourceRootCopyFilter);
zip.addFileset(fileset);
}
}
}
if ((null != inpathDirCopyFilter) && (null != inpath)) {
String[] paths = inpath.list();
if (!LangUtil.isEmpty(paths)) {
for (int i = 0; i < paths.length; i++) {
File inpathDir = new File(paths[i]);
if (inpathDir.isDirectory() && inpathDir.canRead()) {
FileSet fileset = new FileSet();
fileset.setProject(project);
fileset.setDir(inpathDir);
fileset.setIncludes("**/*");
fileset.setExcludes(inpathDirCopyFilter);
zip.addFileset(fileset);
}
}
}
}
zip.execute();
}
// -------------------------- compiler adapter interface extras
/**
* Add specified source files.
*/
void addFiles(File[] paths) {
for (int i = 0; i < paths.length; i++) {
addFile(paths[i]);
}
}
/**
* Add specified source file.
*/
void addFile(File path) {
if (null != path) {
adapterFiles.add(path);
}
}
/**
* Read arguments in as if from a command line,
* mainly to support compiler adapter compilerarg subelement.
*
* @param args the String[] of arguments to read
*/
public void readArguments(String[] args) { // XXX slow, stupid, unmaintainable
if ((null == args) || (0 == args.length)) {
return;
}
/** String[] wrapper with increment, error reporting */
class Args {
final String[] args;
int index = 0;
Args(String[] args) {
this.args = args; // not null or empty
}
boolean hasNext() {
return index < args.length;
}
String next() {
String err = null;
if (!hasNext()) {
err = "need arg for flag " + args[args.length-1];
} else {
String s = args[index++];
if (null == s) {
err = "null value";
} else {
s = s.trim();
if (0 == s.trim().length()) {
err = "no value";
} else {
return s;
}
}
}
err += " at [" + index + "] of " + Arrays.asList(args);
throw new BuildException(err);
}
} // class Args
Args in = new Args(args);
String flag;
while (in.hasNext()) {
flag = in.next();
if ("-1.3".equals(flag)) {
setCompliance(flag);
} else if ("-1.4".equals(flag)) {
setCompliance(flag);
} else if ("-1.5".equals(flag)) {
setCompliance("1.5");
} else if ("-argfile".equals(flag)) {
setArgfiles(new Path(project, in.next()));
} else if ("-aspectpath".equals(flag)) {
setAspectpath(new Path(project, in.next()));
} else if ("-classpath".equals(flag)) {
setClasspath(new Path(project, in.next()));
} else if ("-extdirs".equals(flag)) {
setExtdirs(new Path(project, in.next()));
} else if ("-Xcopyinjars".equals(flag)) {
setCopyInjars(true); // ignored - will be flagged by setter
} else if ("-g".equals(flag)) {
setDebug(true);
} else if (flag.startsWith("-g:")) {
setDebugLevel(flag.substring(2));
} else if ("-deprecation".equals(flag)) {
setDeprecation(true);
} else if ("-d".equals(flag)) {
setDestdir(new File(in.next()));
} else if ("-crossrefs".equals(flag)) {
setCrossrefs(true);
} else if ("-emacssym".equals(flag)) {
setEmacssym(true);
} else if ("-encoding".equals(flag)) {
setEncoding(in.next());
} else if ("-Xfailonerror".equals(flag)) {
setFailonerror(true);
} else if ("-fork".equals(flag)) {
setFork(true);
} else if ("-forkclasspath".equals(flag)) {
setForkclasspath(new Path(project, in.next()));
} else if ("-help".equals(flag)) {
setHelp(true);
} else if ("-incremental".equals(flag)) {
setIncremental(true);
} else if ("-injars".equals(flag)) {
setInjars(new Path(project, in.next()));
} else if ("-inpath".equals(flag)) {
setInpath(new Path(project,in.next()));
} else if ("-Xlistfileargs".equals(flag)) {
setListFileArgs(true);
} else if ("-Xmaxmem".equals(flag)) {
setMaxmem(in.next());
} else if ("-Xmessageholderclass".equals(flag)) {
setMessageHolderClass(in.next());
} else if ("-noexit".equals(flag)) {
setNoExit(true);
} else if ("-noimport".equals(flag)) {
setNoExit(true);
} else if ("-noExit".equals(flag)) {
setNoExit(true);
} else if ("-noImportError".equals(flag)) {
setNoImportError(true);
} else if ("-noWarn".equals(flag)) {
setNowarn(true);
} else if ("-noexit".equals(flag)) {
setNoExit(true);
} else if ("-outjar".equals(flag)) {
setOutjar(new File(in.next()));
} else if ("-outxml".equals(flag)) {
setOutxml(true);
} else if ("-outxmlfile".equals(flag)) {
setOutxmlfile(in.next());
} else if ("-preserveAllLocals".equals(flag)) {
setPreserveAllLocals(true);
} else if ("-proceedOnError".equals(flag)) {
setProceedOnError(true);
} else if ("-referenceInfo".equals(flag)) {
setReferenceInfo(true);
} else if ("-source".equals(flag)) {
setSource(in.next());
} else if ("-Xsourcerootcopyfilter".equals(flag)) {
setSourceRootCopyFilter(in.next());
} else if ("-sourceroots".equals(flag)) {
setSourceRoots(new Path(project, in.next()));
} else if ("-Xsrcdir".equals(flag)) {
setSrcDir(new Path(project, in.next()));
} else if ("-Xtagfile".equals(flag)) {
setTagFile(new File(in.next()));
} else if ("-target".equals(flag)) {
setTarget(in.next());
} else if ("-time".equals(flag)) {
setTime(true);
} else if ("-time".equals(flag)) {
setTime(true);
} else if ("-verbose".equals(flag)) {
setVerbose(true);
} else if ("-showWeaveInfo".equals(flag)) {
setShowWeaveInfo(true);
} else if ("-version".equals(flag)) {
setVersion(true);
} else if ("-warn".equals(flag)) {
setWarn(in.next());
} else if (flag.startsWith("-warn:")) {
setWarn(flag.substring(6));
} else if ("-Xlint".equals(flag)) {
setXlintwarnings(true);
} else if (flag.startsWith("-Xlint:")) {
setXlint(flag.substring(7));
} else if ("-Xlintfile".equals(flag)) {
setXlintfile(new File(in.next()));
} else if ("-XterminateAfterCompilation".equals(flag)) {
setXTerminateAfterCompilation(true);
} else if ("-Xreweavable".equals(flag)) {
setXReweavable(true);
} else if ("-XnotReweavable".equals(flag)) {
setXNotReweavable(true);
} else if (flag.startsWith("@")) {
File file = new File(flag.substring(1));
if (file.canRead()) {
setArgfiles(new Path(project, file.getPath()));
} else {
ignore(flag);
}
} else {
File file = new File(flag);
if (file.isFile()
&& file.canRead()
&& FileUtil.hasSourceSuffix(file)) {
addFile(file);
} else {
ignore(flag);
}
}
}
}
protected void logVerbose(String text) {
if (this.verbose) {
this.logger.info(text);
} else {
this.logger.verbose(text);
}
}
/**
* Commandline wrapper that
* only permits addition of non-empty values
* and converts to argfile form if necessary.
*/
public static class GuardedCommand {
Commandline command;
//int size;
static boolean isEmpty(String s) {
return ((null == s) || (0 == s.trim().length()));
}
GuardedCommand() {
command = new Commandline();
}
void addFlag(String flag, boolean doAdd) {
if (doAdd && !isEmpty(flag)) {
command.createArgument().setValue(flag);
//size += 1 + flag.length();
}
}
/** @return null if added or ignoreString otherwise */
String addOption(String prefix, String[] validOptions, String input) {
if (isEmpty(input)) {
return null;
}
for (int i = 0; i < validOptions.length; i++) {
if (input.equals(validOptions[i])) {
if (isEmpty(prefix)) {
addFlag(input, true);
} else {
addFlagged(prefix, input);
}
return null;
}
}
return (null == prefix ? input : prefix + " " + input);
}
void addFlagged(String flag, String argument) {
if (!isEmpty(flag) && !isEmpty(argument)) {
command.addArguments(new String[] {flag, argument});
//size += 1 + flag.length() + argument.length();
}
}
// private void addFile(File file) {
// if (null != file) {
// String path = file.getAbsolutePath();
// addFlag(path, true);
// }
// }
List extractArguments() {
ArrayList result = new ArrayList();
String[] cmds = command.getArguments();
if (!LangUtil.isEmpty(cmds)) {
result.addAll(Arrays.asList(cmds));
}
return result;
}
/**
* Adjust args for size if necessary by creating
* an argument file, which should be deleted by the client
* after the compiler run has completed.
* @param max the int maximum length of the command line (in char)
* @return the temp File for the arguments (if generated),
* for deletion when done.
* @throws IllegalArgumentException if max is negative
*/
static String[] limitTo(String[] args, int max,
Location location) {
if (max < 0) {
throw new IllegalArgumentException("negative max: " + max);
}
// sigh - have to count anyway for now
int size = 0;
for (int i = 0; (i < args.length) && (size < max); i++) {
size += 1 + (null == args[i] ? 0 : args[i].length());
}
if (size <= max) {
return args;
}
File tmpFile = null;
PrintWriter out = null;
// adapted from DefaultCompilerAdapter.executeExternalCompile
try {
String userDirName = System.getProperty("user.dir");
File userDir = new File(userDirName);
tmpFile = File.createTempFile("argfile", "", userDir);
out = new PrintWriter(new FileWriter(tmpFile));
for (int i = 0; i < args.length; i++) {
out.println(args[i]);
}
out.flush();
return new String[] {"-argfile", tmpFile.getAbsolutePath()};
} catch (IOException e) {
throw new BuildException("Error creating temporary file",
e, location);
} finally {
if (out != null) {
try {out.close();} catch (Throwable t) {}
}
}
}
}
private static class AntMessageHandler implements IMessageHandler {
private TaskLogger logger;
private final boolean taskLevelVerbose;
private final boolean handledMessage;
public AntMessageHandler(TaskLogger logger, boolean taskVerbose, boolean handledMessage) {
this.logger = logger;
this.taskLevelVerbose = taskVerbose;
this.handledMessage = handledMessage;
}
/* (non-Javadoc)
* @see org.aspectj.bridge.IMessageHandler#handleMessage(org.aspectj.bridge.IMessage)
*/
public boolean handleMessage(IMessage message) throws AbortException {
Kind messageKind = message.getKind();
String messageText = message.toString();
if (messageKind == IMessage.ABORT) {
this.logger.error(messageText);
} else if (messageKind == IMessage.DEBUG) {
this.logger.debug(messageText);
} else if (messageKind == IMessage.ERROR) {
this.logger.error(messageText);
} else if (messageKind == IMessage.FAIL){
this.logger.error(messageText);
} else if (messageKind == IMessage.INFO) {
if (this.taskLevelVerbose) {
this.logger.info(messageText);
}
else {
this.logger.verbose(messageText);
}
} else if (messageKind == IMessage.WARNING) {
this.logger.warning(messageText);
} else if (messageKind == IMessage.WEAVEINFO) {
this.logger.info(messageText);
} else if (messageKind == IMessage.TASKTAG) {
// ignore
} else {
throw new BuildException("Unknown message kind from AspectJ compiler: " + messageKind.toString());
}
return handledMessage;
}
/* (non-Javadoc)
* @see org.aspectj.bridge.IMessageHandler#isIgnoring(org.aspectj.bridge.IMessage.Kind)
*/
public boolean isIgnoring(Kind kind) {
return false;
}
/* (non-Javadoc)
* @see org.aspectj.bridge.IMessageHandler#dontIgnore(org.aspectj.bridge.IMessage.Kind)
*/
public void dontIgnore(Kind kind) {
}
}
}
|
136,707 |
Bug 136707 iajc should print summary like javac
|
The iajc ant task should produce a summary of what it is doing, like the javac task does: [javac] Compiling 189 source files to C:\project\classes
|
resolved fixed
|
008efca
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-06-13T19:45:44Z | 2006-04-13T17:40:00Z |
taskdefs/testsrc/org/aspectj/tools/ant/taskdefs/AjcTaskTest.java
|
/* *******************************************************************
* Copyright (c) 1999-2001 Xerox Corporation,
* 2002 Palo Alto Research Center, Incorporated (PARC)
* 2003 Contributors.
* 2005 Contributors
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Eclipse Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Xerox/PARC initial implementation
* IBM ongoing maintenance
* ******************************************************************/
package org.aspectj.tools.ant.taskdefs;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileFilter;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintStream;
import java.util.Arrays;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import junit.framework.TestCase;
import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.Location;
import org.apache.tools.ant.Project;
import org.apache.tools.ant.types.Path;
import org.apache.tools.ant.types.selectors.FilenameSelector;
import org.aspectj.bridge.IMessage;
import org.aspectj.bridge.IMessageHolder;
import org.aspectj.bridge.MessageHandler;
import org.aspectj.bridge.MessageUtil;
import org.aspectj.util.FileUtil;
import org.aspectj.util.LangUtil;
/**
* AjcTask test cases.
* Please put new ones with others between ------- comments.
*
* Some API tests, but mostly functional tests driving
* the task execute using data in ../taskdefs/testdata.
* This will re-run in forked mode for any nonfailing
* compile if aspectjtools-dist is built into
* ../aj-build/dist/tools/lib/aspectjtools.jar.
*/
public class AjcTaskTest extends TestCase {
private static final Class NO_EXCEPTION = null;
private static final String NOFILE = "NOFILE";
private static final File tempDir;
private static final String aspectjtoolsJar;
private static final String testdataDir;
private static final StringBuffer MESSAGES = new StringBuffer();
/** accept writable .class files */
private static FileFilter PICK_CLASS_FILES;
static {
tempDir = new File("IncrementalAjcTaskTest-temp");
String toolsPath = "../aj-build/dist/tools/lib/aspectjtools.jar";
File toolsjar = new File(toolsPath);
if (toolsjar.canRead()) {
aspectjtoolsJar = toolsjar.getAbsolutePath();
} else {
aspectjtoolsJar = null;
String s =
"AjcTaskTest not forking - build aspectjtools-dist to get "
+ toolsPath;
System.out.println(s);
}
File dir = new File("../taskdefs/testdata");
if (dir.canRead() && dir.isDirectory()) {
testdataDir = dir.getAbsolutePath();
} else {
testdataDir = null;
}
PICK_CLASS_FILES = new FileFilter() {
public boolean accept(File file) {
return (
(null != file)
&& file.isFile()
&& file.canWrite()
&& file.getPath().endsWith(".class"));
}
};
}
/**
* Check that aspectjtools are found on the classpath,
* reporting any errors to System.err.
*
* Run multiple times with different classpaths.
* This should find variants
* aspectjtools.jar,
* aspectj-tools.jar,
* aspectj-tools-1.1.jar, and
* aspectjtools-1.0.6.jar
* but not
* aspectjrt.jar or
* aspectj/tools.jar.
* XXX use testing aspect to stub out
* <code>System.getProperty("java.class.path")</code>
* @param args a String[], first is expected path, if any
*/
public static void main(String[] args) {
java.io.File toolsjar = AjcTask.findAspectjtoolsJar();
if ((null == args) || (0 == args.length)) {
if (null != toolsjar) {
System.err.println("FAIL - not expected: " + toolsjar);
}
} else if ("-help".equals(args[0])) {
System.out.println(
"java "
+ AjcTaskTest.class.getName()
+ " <expectedPathToAspectjtoolsJar>");
} else if (null == toolsjar) {
System.err.println("FAIL - expected: " + args[0]);
} else {
String path = toolsjar.getAbsolutePath();
if (!path.equals(args[0])) {
System.err.println(
"FAIL - expected: " + args[0] + " actual: " + path);
}
}
}
public static void collectMessage(String s) {
MESSAGES.append(s);
}
private static void deleteTempDir() {
if ((null != tempDir) && tempDir.exists()) {
FileUtil.deleteContents(tempDir);
tempDir.delete();
// when tempDir not used...
if (null != testdataDir) {
File dataDir = new File(testdataDir);
if (dataDir.canRead()) {
FileUtil.deleteContents(dataDir, PICK_CLASS_FILES, false);
}
}
}
}
private static final File getTempDir() {
return tempDir;
}
public AjcTaskTest(String name) {
super(name);
}
public void tearDown() {
deleteTempDir();
MESSAGES.setLength(0);
}
private void checkRun(AjcTask task, String exceptionString) {
try {
task.execute();
assertTrue(null == exceptionString);
} catch (BuildException e) {
if (null == exceptionString) {
assertTrue("unexpected " + e.getMessage(), false);
} else {
String m = e.getMessage();
if (null == m) {
assertTrue("not " + exceptionString, false);
} else if (-1 == m.indexOf(exceptionString)) {
assertEquals(exceptionString, e.getMessage());
}
}
}
}
private void checkContains(String[] cmd, String option, boolean contains) {
for (int i = 0; i < cmd.length; i++) {
if (option.equals(cmd[i])) {
if (contains) {
return;
} else {
assertTrue(
"not expecting " + option + " in " + Arrays.asList(cmd),
false);
}
}
}
if (contains) {
assertTrue(
"expecting " + option + " in " + Arrays.asList(cmd),
false);
}
}
protected AjcTask getTask(String input) {
return getTask(input, getTempDir());
}
protected AjcTask getTask(String input, File destDir) {
AjcTask task = new AjcTask();
Project p = new Project();
task.setProject(p);
if (null != destDir) {
task.setDestdir(destDir);
}
if (NOFILE.equals(input)) {
// add nothing
} else if (input.endsWith(".lst")) {
if (-1 != input.indexOf(",")) {
throw new IllegalArgumentException(
"lists not supported: " + input);
} else if (null == testdataDir) {
throw new Error("testdata not found - run in ../taskdefs");
} else {
String path = testdataDir + File.separator + input;
task.setArgfiles(new Path(task.getProject(), path));
}
} else if ((input.endsWith(".java") || input.endsWith(".aj"))) {
FilenameSelector fns = new FilenameSelector();
fns.setName(input);
task.addFilename(fns);
} else {
String path = testdataDir + File.separator + input;
task.setSourceRoots(new Path(task.getProject(), path));
}
task.setClasspath(new Path(p, "../lib/test/aspectjrt.jar"));
return task;
}
/** used in testMessageHolderClassName */
public static class InfoHolder extends MessageHandler {
public InfoHolder() {
}
public boolean handleMessage(IMessage message) {
if (0 == IMessage.INFO.compareTo(message.getKind())) {
AjcTaskTest.collectMessage(message.getMessage());
}
return true;
}
}
/** used in testMessageHolderClassName */
public static class Holder extends MessageHandler {
public Holder() {
}
public boolean handleMessage(IMessage message) {
IMessage.Kind kind = message.getKind();
if (IMessage.ERROR.isSameOrLessThan(kind)) {
String m = kind.toString();
AjcTaskTest.collectMessage(m.substring(0, 1));
}
return true;
}
}
// ------------------------------------------------------
// ------------------------------------------------------
// ------------------------------------------------------
// ------------------------------------------------------
// ------------------------------------------------------
// ------------------------------------------------------
// Start of test cases
public void testNullDestDir() {
AjcTask task = getTask(NOFILE, null);
String[] cmd = task.makeCommand();
for (int i = 0; i < cmd.length; i++) {
assertTrue(!"-d".equals(cmd[i]));
}
}
public void testOutputRequirement() {
AjcTask task = getTask("default.lst");
checkRun(task, null);
// copyInJars now just emits warning b/c unused
task = getTask("default.lst", null);
task.setCopyInjars(true);
checkRun(task, null);
// sourceRootCopyFilter requires destDir
task = getTask("default.lst", null);
task.setSourceRootCopyFilter("**/*.java");
checkRun(task, "sourceRoot");
}
public void testSourceRootCopyFilter() {
// sourceRootCopyFilter works..
File destDir = getTempDir();
assertTrue(
"unable to create " + destDir,
destDir.canRead() || destDir.mkdirs());
AjcTask task = getTask("sourceroot", destDir);
task.setSourceRootCopyFilter("doNotCopy,**/*.txt");
File file = new File(destDir, "Default.java").getAbsoluteFile();
assertTrue(file + ".canRead() prematurely", !file.canRead());
checkRun(task, null);
// got expected resources
assertTrue(file + ".canRead() failed", file.canRead());
File pack = new File(destDir, "pack");
file = new File(pack, "Pack.java").getAbsoluteFile();
assertTrue(file + ".canRead() failed", file.canRead());
file = new File(pack, "includeme").getAbsoluteFile();
assertTrue(file + ".canRead() failed", file.canRead());
// didn't get unexpected resources
file = new File(pack, "something.txt");
assertTrue(file + ".canRead() passed", !file.canRead());
file = new File(destDir, "doNotCopy");
assertTrue(file + ".canRead() passed", !file.canRead());
file = new File(destDir, "skipTxtFiles.txt");
assertTrue(file + ".canRead() passed", !file.canRead());
}
public void testInpathDirCopyFilter() {
// inpathDirCopyFilter works with output directory
File destDir = getTempDir();
assertTrue(
"unable to create " + destDir,
destDir.canRead() || destDir.mkdirs());
AjcTask task = getTask(NOFILE, destDir);
Project p = task.getProject();
Path indirs = new Path(p);
File dir = new File(testdataDir, "inpathDirs").getAbsoluteFile();
indirs.addExisting(new Path(p, new File(dir, "inpathDirOne").getAbsolutePath()));
indirs.addExisting(new Path(p, new File(dir, "inpathDirTwo").getAbsolutePath()));
task.setInpath(indirs);
task.setInpathDirCopyFilter("doNotCopy,**/*.txt");
File file = new File(destDir, "Default.java").getAbsoluteFile();
assertTrue(file + ".canRead() prematurely", !file.canRead());
checkRun(task, null);
// got expected resources
File pack = new File(destDir, "pack");
file = new File(pack, "includeme").getAbsoluteFile();
assertTrue(file + ".canRead() failed", file.canRead());
file = new File(pack, "Pack.class").getAbsoluteFile();
assertTrue(file + ".canRead() failed", file.canRead());
file = new File(destDir, "copyMe.htm").getAbsoluteFile();
assertTrue(file + ".canRead() failed", file.canRead());
file = new File(destDir, "Default.class").getAbsoluteFile();
assertTrue(file + ".canRead() failed", file.canRead());
// didn't get unexpected resources
file = new File(pack, "something.txt");
assertTrue(file + ".canRead() passed", !file.canRead());
file = new File(destDir, "doNotCopy");
assertTrue(file + ".canRead() passed", !file.canRead());
file = new File(destDir, "skipTxtFiles.txt");
assertTrue(file + ".canRead() passed", !file.canRead());
}
public void testInpathDirCopyFilterWithJar() throws IOException {
checkInpathCopy("testInpathDirCopyFilterWithJar-out.jar");
}
// test resource copying for oddball jar files that don't end in .jar
public void testInpathDirCopyFilterWithOddjar() throws IOException {
checkInpathCopy("testInpathDirCopyFilterWithJar-outJarFile");
}
private void checkInpathCopy(String outjarFileStr) throws IOException {
// inpathDirCopyFilter works with output jar
File destDir = getTempDir();
assertTrue(
"unable to create " + destDir,
destDir.canRead() || destDir.mkdirs());
AjcTask task = getTask(NOFILE, null);
File destJar = new File(destDir, outjarFileStr);
task.setOutjar(destJar);
Project p = task.getProject();
Path indirs = new Path(p);
File dir = new File(testdataDir, "inpathDirs").getAbsoluteFile();
indirs.addExisting(new Path(p, new File(dir, "inpathDirOne").getAbsolutePath()));
indirs.addExisting(new Path(p, new File(dir, "inpathDirTwo").getAbsolutePath()));
task.setInpath(indirs);
task.setInpathDirCopyFilter("doNotCopy,**/*.txt,**/*.class");
checkRun(task, null);
JarFile jarFile = new JarFile(destJar);
String[] expected = {"copyMe.htm", "pack/includeme",
"pack/Pack.class", "Default.class"};
String[] unexpected = {"doNotCopy", "skipTxtFiles.txt", "pack/something.txt"};
for (int i = 0; i < expected.length; i++) {
JarEntry entry = jarFile.getJarEntry(expected[i]);
assertTrue(expected[i] + " not found", null != entry);
}
for (int i = 0; i < unexpected.length; i++) {
JarEntry entry = jarFile.getJarEntry(unexpected[i]);
assertTrue(unexpected[i] + " found", null == entry);
}
}
public void testInpathDirCopyFilterError() {
// inpathDirCopyFilter fails with no output directory or jar iff specified
AjcTask task = getTask(NOFILE, null);
Project p = task.getProject();
Path indirs = new Path(p);
File dir = new File(testdataDir, "inpathDirs").getAbsoluteFile();
indirs.addExisting(new Path(p, new File(dir, "inpathDirOne").getAbsolutePath()));
indirs.addExisting(new Path(p, new File(dir, "inpathDirTwo").getAbsolutePath()));
task.setInpath(indirs);
task.setInpathDirCopyFilter("doNotCopy,**/*.txt,**/*.class");
// expecting error
checkRun(task, "inpathDirCopyFilter");
}
// this test method submitted by patch from Andrew Huff (IBM)
// verifies that the log attribute of AjcTask writes output to the given log file
public void testLoggingMode() {
AjcTask task = getTask("default.lst");
task.setFailonerror(false);
File logFile = new File("testLogFile1.txt");
String s = logFile.getAbsolutePath();
logFile.delete();
long initialLength = logFile.length();
task.setLog(logFile);
runTest(task,null,null);
long newLength = logFile.length();
assertTrue(newLength > initialLength);
logFile.delete();
}
public void testCommandEditor() {
String className = VerboseCommandEditor.class.getName();
System.setProperty(AjcTask.COMMAND_EDITOR_NAME, className);
assertEquals(
className,
System.getProperty(AjcTask.COMMAND_EDITOR_NAME));
AjcTask task = getTask(NOFILE);
task.setCommandEditor(new VerboseCommandEditor());
String[] cmd = task.makeCommand();
assertEquals(VerboseCommandEditor.VERBOSE, cmd[0]);
task = getTask(NOFILE);
task.setCommandEditorClass(VerboseCommandEditor.class.getName());
cmd = task.makeCommand();
assertEquals(VerboseCommandEditor.VERBOSE, cmd[0]);
}
// public void testStaticCommandEditor() {
// // XXX need to test COMMAND_EDITOR, but can't require property when run
// }
public void testLimitTo() {
int numArgs = 100;
String arg = "123456789";
String[] args = new String[numArgs];
for (int i = 0; i < args.length; i++) {
args[i] = arg;
}
// no limit
int max = numArgs * (arg.length() + 1);
Location location = new Location("AjcTaskTest.java");
String[] newArgs = AjcTask.GuardedCommand.limitTo(args, max, location);
assertTrue("same", args == newArgs);
// limited - read file and verify arguments
max--;
newArgs = AjcTask.GuardedCommand.limitTo(args, max, location);
assertTrue("not same", args != newArgs);
assertTrue("not null", null != newArgs);
String label = "newArgs " + Arrays.asList(newArgs);
assertTrue("size 2" + label, 2 == newArgs.length);
assertEquals("-argfile", newArgs[0]);
File file = new File(newArgs[1]);
assertTrue("readable newArgs[1]" + label, file.canRead());
FileReader fin = null;
try {
fin = new FileReader(file);
BufferedReader reader = new BufferedReader(fin);
String line;
int i = 0;
while (null != (line = reader.readLine())) {
assertEquals(i + ": ", args[i++], line);
}
assertEquals("num entries", i, args.length);
} catch (IOException e) {
assertTrue("IOException " + e.getMessage(), false);
} finally {
if (null != fin) {
try {
fin.close();
} catch (IOException e) {
// ignore
}
}
file.delete();
}
}
public void testFindAspectjtoolsJar() {
File toolsJar = AjcTask.findAspectjtoolsJar();
if (null != toolsJar) {
assertNull("tools jar found?: " + toolsJar, toolsJar);
}
// not found when unit testing b/c not on system classpath
// so just checking for exceptions.
// XXX need aspect to stub out System.getProperty(..)
}
public void testMessageHolderClassName() {
AjcTask task = getTask("compileError.lst");
task.setFailonerror(false);
MESSAGES.setLength(0);
runTest(
task,
null,
MessageHolderChecker.ONE_ERROR,
Holder.class.getName());
String result = MESSAGES.toString();
MESSAGES.setLength(0);
assertEquals("messages", "e", result);
}
// TODO skipped test - works locally but not on build machine?
public void skip_testMessageHolderClassWithDoneSignal() {
AjcTask task = getTask("default.lst");
task.setFailonerror(false);
String DONE = "This is a unique message, not confused with others.";
task.setXDoneSignal(DONE);
MESSAGES.setLength(0);
runTest(
task,
null,
MessageHolderChecker.INFOS,
InfoHolder.class.getName());
final String result = MESSAGES.toString();
String temp = new String(result);
MESSAGES.setLength(0);
if (!temp.endsWith(DONE)) {
if (temp.length() > 20) {
temp = "..." + temp.substring(temp.length()-20, temp.length());
}
assertTrue(DONE + " is not suffix of \"" + temp + "\"", false);
}
// exactly one such message
temp = new String(result);
temp = temp.substring(0, temp.length()-DONE.length());
if (temp.endsWith(DONE)) {
temp = new String(result);
if (temp.length() > 20) {
temp = "..." + temp.substring(temp.length()-20, temp.length());
}
assertTrue(DONE + " signalled twice: \"" + temp + "\"", false);
}
}
public void testDefaultListForkedNoTools() {
AjcTask task = getTask("default.lst");
task.setFork(true);
boolean passed = false;
try {
runTest(task, BuildException.class, MessageHolderChecker.NONE);
passed = true;
} finally {
if (!passed) {
String m =
"AjcTaskTest.testDefaultListForkedNoTools()"
+ " fails if aspectjtools.jar is on the classpath";
System.err.println(m);
}
}
}
public void testDefaultListForkedIncremental() {
AjcTask task = getTask("default.lst");
task.setFork(true);
task.setIncremental(true);
runTest(task, BuildException.class, MessageHolderChecker.NONE);
}
/** failonerror should default to true, unlike other booleans */
public void testCompileErrorFailOnErrorDefault() {
AjcTask task = getTask("compileError.lst");
final PrintStream serr = System.err;
try {
System.setErr(new PrintStream(new java.io.ByteArrayOutputStream()));
runTest(task, BuildException.class, MessageHolderChecker.ONE_ERROR);
} finally {
System.setErr(serr);
}
}
public void testCompileErrorListDefaultHolder() {
AjcTask task = getTask("compileError.lst");
final PrintStream serr = System.err;
try {
System.setErr(new PrintStream(new java.io.ByteArrayOutputStream()));
task.execute();
fail("expected BuildException from failed compile by default");
} catch (BuildException t) {
// ok
} finally {
System.setErr(serr);
deleteTempDir();
}
}
public void testDefaultList() {
AjcTask task = getTask("default.lst");
runTest(task, NO_EXCEPTION, MessageHolderChecker.INFOS);
}
public void testCompileErrorList() {
AjcTask task = getTask("compileError.lst");
task.setFailonerror(false);
runTest(task, NO_EXCEPTION, MessageHolderChecker.ONE_ERROR);
}
public void testShowWeaveInfo() {
AjcTask task = getTask("showweaveinfo.lst");
task.setShowWeaveInfo(true);
MessageHandler mh = new MessageHandler(false);
mh.dontIgnore(IMessage.WEAVEINFO);
MessageHolderChecker mhc = new MessageHolderChecker(0,0,0,0,MessageHolderChecker.IGNORE);
mhc.weaveinfos = 2; // Expect 2 weaving messages
runTest(task,NO_EXCEPTION,mhc);
mhc.weaveinfos = MessageHolderChecker.IGNORE;
}
public void testCompileWarningList() {
AjcTask task = getTask("compileWarning.lst");
runTest(task, NO_EXCEPTION, MessageHolderChecker.ONE_WARNING);
}
public void testNoSuchFileList() {
AjcTask task = getTask("NoSuchFile.lst");
task.setFailonerror(false);
runTest(task, NO_EXCEPTION, MessageHolderChecker.ONE_ERROR_ONE_ABORT);
}
public void testVersions() {
String[] inputs = AjcTask.TARGET_INPUTS;
for (int i = 0; i < inputs.length; i++) {
AjcTask task = getTask(NOFILE);
task.setTarget(inputs[i]);
String[] cmd = task.makeCommand();
checkContains(cmd, "-target", true);
checkContains(cmd, inputs[i], true);
}
inputs = AjcTask.SOURCE_INPUTS;
for (int i = 0; i < inputs.length; i++) {
AjcTask task = getTask(NOFILE);
task.setSource(inputs[i]);
String[] cmd = task.makeCommand();
checkContains(cmd, "-source", true);
checkContains(cmd, inputs[i], true);
}
inputs = AjcTask.COMPLIANCE_INPUTS;
for (int i = 0; i < inputs.length; i++) {
AjcTask task = getTask(NOFILE);
task.setCompliance(inputs[i]);
String[] cmd = task.makeCommand();
checkContains(cmd, inputs[i], true);
}
}
public void testClasspath() {
AjcTask task = getTask(NOFILE);
String[] cmd = task.makeCommand();
checkContains(cmd, "-bootclasspath", false);
String classpath = null;
for (int i = 0; i < cmd.length; i++) {
if ("-classpath".equals(cmd[i])) {
classpath = cmd[i + 1];
break;
}
}
assertTrue(
"expecting aspectj in classpath",
(-1 != classpath.indexOf("aspectjrt.jar")));
}
// ---------------------------------------- sourcefile
// XXX need to figure out how to specify files directly programmatically
// public void testDefaultFile() {
// AjcTask task = getTask("testdata/Default.java");
// runTest(task, NO_EXCEPTION, MessageHolderChecker.INFOS);
// }
public void testNoFile() {
AjcTask task = getTask(NOFILE);
task.setFailonerror(false);
runTest(task, NO_EXCEPTION, MessageHolderChecker.ONE_ERROR_ONE_ABORT);
}
public void testCompileErrorFile() {
AjcTask task = getTask("compileError.lst");
task.setFailonerror(false);
runTest(task, NO_EXCEPTION, MessageHolderChecker.ONE_ERROR);
}
public void testCompileWarningFile() {
AjcTask task = getTask("compileWarning.lst");
task.setFailonerror(false);
runTest(task, NO_EXCEPTION, MessageHolderChecker.ONE_WARNING);
}
public void testNoSuchFile() {
AjcTask task = getTask("NoSuchFile.lst");
task.setFailonerror(false);
runTest(task, NO_EXCEPTION, MessageHolderChecker.ONE_ERROR_ONE_ABORT);
}
public void testDefaultFileComplete() {
AjcTask task = getTask("default.lst");
task.setDebugLevel("none");
task.setDeprecation(true);
task.setFailonerror(false);
task.setNoExit(true); // ok to override Ant?
task.setNoImportError(true);
task.setNowarn(true);
task.setXTerminateAfterCompilation(true);
task.setPreserveAllLocals(true);
task.setProceedOnError(true);
task.setReferenceInfo(true);
task.setSource("1.3");
task.setTarget("1.1");
task.setTime(true);
task.setVerbose(true);
task.setXlint("info");
runTest(task, NO_EXCEPTION, MessageHolderChecker.INFOS);
}
public void testXOptions() {
String[] xopts = new String[] {
"serializableAspects",
"lazyTjp",
"reweavable",
"reweavable:compress",
"noInline"
};
for (int i = 0; i < xopts.length; i++) {
AjcTask task = getTask(NOFILE);
task.setX(xopts[i]);
String[] cmd = task.makeCommand();
checkContains(cmd,"-X" + xopts[i],true);
}
}
public void testOutxml () {
File destDir = getTempDir();
assertTrue(
"unable to create " + destDir,
destDir.canRead() || destDir.mkdirs());
AjcTask task = getTask("showweaveinfo.lst",destDir);
task.setOutxml(true);
checkRun(task,null);
File outxmlFile = new File(destDir,"META-INF/aop.xml");
assertTrue("META-INF/aop.xml missing",outxmlFile.exists());
}
public void testOutxmlFile () {
String customName = "custom/aop.xml";
File destDir = getTempDir();
assertTrue(
"unable to create " + destDir,
destDir.canRead() || destDir.mkdirs());
AjcTask task = getTask("showweaveinfo.lst",destDir);
task.setOutxmlfile(customName);
checkRun(task,null);
File outxmlFile = new File(destDir,customName);
assertTrue(customName + " missing",outxmlFile.exists());
}
// End of test cases
// ------------------------------------------------------
// ------------------------------------------------------
// ------------------------------------------------------
// ------------------------------------------------------
// ------------------------------------------------------
// ------------------------------------------------------
protected void runTest(
AjcTask task,
Class exceptionType,
MessageHolderChecker checker,
String messageHolderClass) {
task.setMessageHolderClass(messageHolderClass);
runTest(task, exceptionType, checker, (MessageHandler) null);
}
protected void runTest(
AjcTask task,
Class exceptionType,
MessageHolderChecker checker) {
MessageHandler holder = new MessageHandler();
task.setMessageHolder(holder);
runTest(task, exceptionType, checker, holder);
}
protected void runTest(
AjcTask task,
Class exceptionType,
MessageHolderChecker checker,
MessageHandler holder) {
Throwable thrown = null;
// re-run forked iff tools.jar and expect to pass
boolean rerunForked =
((null != aspectjtoolsJar)
&& (null == exceptionType)
&& ((null == checker) || !checker.expectFail()));
String label = "same-vm ";
while (true) { // same vm, then perhaps forked
try {
task.execute();
} catch (Throwable t) {
thrown = t;
} finally {
deleteTempDir();
}
if (null == exceptionType) {
if (null != thrown) {
assertTrue(label + "thrown: " + render(thrown), false);
}
} else if (null == thrown) {
assertTrue(
label + "expected " + exceptionType.getName(),
false);
} else if (!(exceptionType.isAssignableFrom(thrown.getClass()))) {
assertTrue(
label
+ "expected "
+ exceptionType.getName()
+ " got "
+ render(thrown),
false);
}
if (null != holder) {
if (null == checker) {
checker = MessageHolderChecker.NONE;
}
checker.check(holder, label);
}
if (!rerunForked) {
break;
} else {
label = "other-vm ";
rerunForked = false;
// can't reset without losing values...
task.setFork(true);
task.setFailonerror(true);
task.setForkclasspath(
new Path(task.getProject(), aspectjtoolsJar));
}
}
}
protected String render(Throwable thrown) {
return LangUtil.renderException(thrown);
}
static class MessageHolderChecker { // XXX export to testing-utils
/** use as value to ignore results */
static int IGNORE = Integer.MIN_VALUE;
static MessageHolderChecker NONE =
new MessageHolderChecker(0, 0, 0, 0, 0);
/** any number (0+) of info messages */
static MessageHolderChecker INFOS =
new MessageHolderChecker(0, 0, 0, 0, IGNORE);
/** one error, any number of info messages */
static MessageHolderChecker ONE_ERROR =
new MessageHolderChecker(0, 0, 1, 0, IGNORE);
static MessageHolderChecker ONE_ERROR_ONE_ABORT =
new MessageHolderChecker(1, 0, 1, 0, IGNORE);
/** one warning, any number of info messages */
static MessageHolderChecker ONE_WARNING =
new MessageHolderChecker(0, 0, 0, 1, IGNORE);
int aborts, fails, errors, warnings, infos;
int weaveinfos;
public MessageHolderChecker(
int aborts,
int fails,
int errors,
int warnings,
int infos) {
this.aborts = aborts;
this.fails = fails;
this.errors = errors;
this.warnings = warnings;
this.infos = infos;
this.weaveinfos = IGNORE;
}
public boolean expectFail() {
return (0 < (aborts + fails + errors));
}
public void check(IMessageHolder holder, String label) {
boolean failed = true;
try {
check(holder, aborts, IMessage.ABORT);
check(holder, fails, IMessage.FAIL);
check(holder, errors, IMessage.ERROR);
check(holder, warnings, IMessage.WARNING);
check(holder, infos, IMessage.INFO);
check(holder, weaveinfos, IMessage.WEAVEINFO);
failed = false;
} finally {
if (failed) {
MessageUtil.print(System.err, holder, label + "failed?");
}
}
}
private void check(
IMessageHolder holder,
int num,
IMessage.Kind kind) {
if (num != IGNORE) {
int actual = holder.numMessages(kind, false);
if (num != actual) {
if (actual > 0) {
MessageUtil.print(
System.err,
holder,
kind + " expected " + num + " got " + actual);
}
assertEquals(kind.toString(), num, actual);
}
}
}
}
}
class SnoopingCommandEditor implements ICommandEditor {
private static final String[] NONE = new String[0];
String[] lastCommand;
public String[] editCommand(String[] command) {
lastCommand = (String[]) LangUtil.safeCopy(command, NONE);
return command;
}
public String[] lastCommand() {
return (String[]) LangUtil.safeCopy(lastCommand, NONE);
}
}
class VerboseCommandEditor implements ICommandEditor {
public static final String VERBOSE = "-verbose";
public String[] editCommand(String[] command) {
for (int i = 0; i < command.length; i++) {
if (VERBOSE.equals(command[i])) {
return command;
}
}
String[] result = new String[1 + command.length];
result[0] = VERBOSE;
System.arraycopy(result, 1, command, 0, command.length);
return result;
}
}
class AppendingCommandEditor implements ICommandEditor {
private static String[] NONE = new String[0];
public static ICommandEditor VERBOSE =
new AppendingCommandEditor(new String[] { "-verbose" }, NONE);
public static ICommandEditor INVALID =
new AppendingCommandEditor(NONE, new String[] { "-invalidOption" });
final String[] prefix;
final String[] suffix;
public AppendingCommandEditor(String[] prefix, String[] suffix) {
this.prefix = prefix;
this.suffix = suffix;
}
public String[] editCommand(String[] command) {
int len = command.length + prefix.length + suffix.length;
String[] result = new String[len];
System.arraycopy(result, 0, prefix, 0, prefix.length);
System.arraycopy(result, prefix.length, command, 0, command.length);
System.arraycopy(
result,
prefix.length + command.length,
suffix,
0,
suffix.length);
return result;
}
}
|
147,845 |
Bug 147845 Generic abstract aspect hierarchies 3 deep or higher can fail when type parameters have bounds
|
The program below should compile happily, but fails with: [error] Type B does not meet the specification for type parameter 1 (A extends MyBase) in generic type Base abstract aspect Middle<B extends MyBase> extends Base<B> {} ^^^^^ The test program: ------------------ interface MyBase {}; interface MyMarker extends MyBase {} abstract aspect Base<A extends MyBase> {} abstract aspect Middle<B extends MyBase> extends Base<B> {} aspect Sub extends Middle<MyMarker> {}
|
resolved fixed
|
791f8a7
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-06-20T11:12:49Z | 2006-06-20T10:40:00Z |
tests/src/org/aspectj/systemtest/ajc152/Ajc152Tests.java
|
/*******************************************************************************
* Copyright (c) 2006 IBM
* 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.ajc152;
import java.io.File;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import junit.framework.Test;
import org.aspectj.asm.AsmManager;
import org.aspectj.asm.IHierarchy;
import org.aspectj.asm.IProgramElement;
import org.aspectj.asm.IRelationshipMap;
import org.aspectj.asm.internal.Relationship;
import org.aspectj.testing.XMLBasedAjcTestCase;
import org.aspectj.util.CharOperation;
import org.aspectj.weaver.World;
public class Ajc152Tests extends org.aspectj.testing.XMLBasedAjcTestCase {
// public void testverifyErrNoTypeCflowField_pr145693() {runTest("verifyErrNoTypeCflowField");}
// public void testBrokenIfArgsCflowAtAj_pr145018() { runTest("ataj crashing with cflow, if and args");}
// public void testItdCallingGenericMethod_pr145391() { runTest("itd calling generic method");}
// public void testItdCallingGenericMethod_pr145391_2() { runTest("itd calling generic method - 2");}
public void testPackageIgnoredForException_pr147701_1() { runTest("package for exception ignored");}
public void testPackageIgnoredForException_pr147701_2() { runTest("package for exception ignored - 2");}
public void testPackageIgnoredForException_pr147701_3() { runTest("package for exception ignored - 3");}
public void testBrokenAddSerialVersionUID_pr145950() {runTest("fails to discover Serializable");}
public void testNoUnnecessaryDeclarationOfThrownExcp_pr129282_1() {runTest("no unnecessary declaration of thrown exception warning - 1");}
public void testNoUnnecessaryDeclarationOfThrownExcp_pr129282_2() {runTest("no unnecessary declaration of thrown exception warning - 2");}
public void testNoUnnecessaryDeclarationOfThrownExcp_pr129282_3() {runTest("no unnecessary declaration of thrown exception warning - 3");}
public void testNoUnnecessaryDeclarationOfThrownExcp_pr129282_4() {runTest("no unnecessary declaration of thrown exception warning - 4");}
public void testNoUnnecessaryDeclarationOfThrownExcp_pr129282_5() {runTest("no unnecessary declaration of thrown exception warning - 5");}
public void testNoUnnecessaryDeclarationOfThrownExcp_pr129282_6() {runTest("no unnecessary declaration of thrown exception warning - 6");}
public void testNoUnnecessaryDeclarationOfThrownExcp_pr129282_7() {runTest("no unnecessary declaration of thrown exception warning - 7");}
public void testNoUnnecessaryDeclarationOfThrownExcp_pr129282_8() {runTest("no unnecessary declaration of thrown exception warning - 8");}
public void testNoUnnecessaryDeclarationOfThrownExcp_pr129282_9() {runTest("no unnecessary declaration of thrown exception warning - 9");}
public void testNoUnnecessaryDeclarationOfThrownExcp_pr129282_10() {runTest("no unnecessary declaration of thrown exception warning - 10");}
public void testAtAJVerificationError_pr144602() { runTest("atAJ perthis aspect verification error");}
public void testLTWAndGeneratingSUID_pr144465() { runTest("ltw with serialversionUID creation"); }
public void testAspects14PerSingleton_pr122253() { runTest("aspects14 - persingleton");}
public void testAspects14PerCflow_pr122253() { runTest("aspects14 - percflow");}
public void testAspects14PerThis_pr122253() { runTest("aspects14 - perthis");}
public void testAspects14PerTypeWithin_pr122253() { runTest("aspects14 - pertypewithin");}
public void testFunkyGenericErrorWithITDs_pr126355() { runTest("bizarre generic error with itds");}
public void testConcretizingAbstractMethods_pr142466() { runTest("aop.xml aspect inheriting but not concretizing abstract method");}
public void testConcretizingAbstractMethods_pr142466_2() { runTest("aop.xml aspect inheriting but not concretizing abstract method - 2");}
public void testComplexGenericDecl_pr137568() { runTest("complicated generics declaration");}
public void testItdOnInnerTypeOfGenericType_pr132349() { runTest("ITD on inner type of generic type");}
public void testItdOnInnerTypeOfGenericType_pr132349_2() { runTest("ITD on inner type of generic type - 2");}
public void testItdOnInnerTypeOfGenericType_pr132349_3() { runTest("ITD on inner type of generic type - 3");}
// public void testCovarianceAndDecp_pr128443_1() { runTest("covariance and decp - 1"); }
public void testLTWGeneratedAspectAbstractMethod_pr125480() { runTest("aop.xml aspect inheriting abstract method ");}
public void testLTWGeneratedAspectAbstractMethod_pr125480_2() { runTest("aop.xml aspect inheriting abstract method - code style");}
//public void testSuperITDExplosion_pr134425() { runTest("super ITDs");}
//public void testMisbehavingDeclareAnnotation_pr135865() { runTest("misbehaving declare annotation");}
//public void testMisbehavingDeclareAnnotation_pr135865_2() { runTest("misbehaving declare annotation - 2");}
public void testCompletelyBrokenAopConcretization_pr142165_1() { runTest("broken concretization");}
public void testCompletelyBrokenAopConcretization_pr142165_2() { runTest("broken concretization - 2");}
public void testCompletelyBrokenAopConcretization_pr142165_3() { runTest("broken concretization - 3");}
public void testVerifyErrorLTW_pr135068() { runTest("ltw verifyerror");}
public void testVerifyErrorLTW_pr135068_2() { runTest("ltw verifyerror - 2");}
public void testVerifyErrorLTW_pr135068_3() { runTest("ltw verifyerror - 3");}
public void testVerifyErrorLTW_pr135068_4() { runTest("ltw verifyerror - 4");}
public void testVerifyErrorForComplexCflow_pr136026() { runTest("verifyerror");}
public void testVerifyErrorForComplexCflow_pr136026_2() { runTest("verifyerror - 2");}
public void testAnnotationsAndGenericsBCException_pr129704() { runTest("annotations and generics leading to BCException");}
public void testMethodTooBigAfterWeaving_pr138384() { runTest("method too big"); }
public void testNotAtWithincode_pr138158_1() { runTest("not at withincode - 1");}
public void testNotAtWithincode_pr138158_2() { runTest("not at withincode - 2");}
public void testNotAtWithincode_pr138158_3() { runTest("not at within - 3");}
public void testNpeOnDup_pr138143() { runTest("npe on duplicate method with ataj");}
public void testPointcutsAndGenerics_pr137496_1() { runTest("pointcuts and generics - B");}
public void testPointcutsAndGenerics_pr137496_2() { runTest("pointcuts and generics - D");}
public void testPointcutsAndGenerics_pr137496_3() { runTest("pointcuts and generics - E");}
public void testPointcutsAndGenerics_pr137496_4() { runTest("pointcuts and generics - F");}
public void testPointcutsAndGenerics_pr137496_5() { runTest("pointcuts and generics - G");}
public void testPointcutsAndGenerics_pr137496_6() { runTest("pointcuts and generics - H");}
public void testAspectLibrariesAndASM_pr135001() { runTest("aspect libraries and asm");}
public void testStackOverflow_pr136258() { runTest("stack overflow");}
public void testIncorrectOverridesEvaluation13() { runTest("incorrect overrides evaluation - 1.3"); }
public void testIncorrectOverridesEvaluation15() { runTest("incorrect overrides evaluation - 1.5"); }
public void testAtWithinCodeBug_pr138798() { runTest("atWithinCodeBug"); }
public void testReferencePCutInDeclareWarning_pr138215() { runTest("Reference pointcut fails inside @DeclareWarning");}
public void testReferencePCutInPerClause_pr138219() { runTest("Can't use a FQ Reference pointcut in any pointcut expression referenced by a per-clause");}
public void testReferencePCutInPerClause_pr130722() { runTest("FQ Reference pointcut from perclause ref pc"); }
public void testDoubleAnnotationMatching_pr138223() { runTest("Double at annotation matching (no binding)");}
public void testSuperCallsInAtAspectJAdvice_pr139749() { runTest("Super calls in @AspectJ advice");}
public void testNoClassCastExceptionWithPerThis_pr138286() { runTest("No ClassCastException with perThis");}
public void testDeclareAtMethodRelationship_pr143924() {
//AsmManager.setReporting("c:/debug.txt",true,true,true,true);
runTest("declare @method relationship");
IHierarchy top = AsmManager.getDefault().getHierarchy();
// get the IProgramElements corresponding to the different code entries
IProgramElement decam = top.findElementForLabel(top.getRoot(),
IProgramElement.Kind.DECLARE_ANNOTATION_AT_METHOD,
"declare @method: * debit(..) : @Secured(role = \"supervisor\")");
assertNotNull("Couldn't find 'declare @method' element in the tree",decam);
IProgramElement method = top.findElementForLabel(top.getRoot(),
IProgramElement.Kind.METHOD,"debit(java.lang.String,long)");
assertNotNull("Couldn't find the 'debit(String,long)' method element in the tree",method);
List matches = AsmManager.getDefault().getRelationshipMap().get(decam);
assertNotNull("'declare @method' should have some relationships but does not",matches);
assertTrue("'declare @method' should have one relationships but has " + matches.size(),matches.size()==1);
List matchesTargets = ((Relationship)matches.get(0)).getTargets();
assertTrue("'declare @method' should have one targets but has" + matchesTargets.size(),matchesTargets.size()==1);
IProgramElement target = AsmManager.getDefault().getHierarchy().findElementForHandle((String)matchesTargets.get(0));
assertEquals("target of relationship should be the 'debit(java.lang.String,long)' method but is IPE with label "
+ target.toLabelString(),method,target);
// check that the debit method has an annotated by relationship with the declare @method
matches = AsmManager.getDefault().getRelationshipMap().get(method);
assertNotNull("'debit(java.lang.String,long)' should have some relationships but does not",matches);
assertTrue("'debit(java.lang.String,long)' should have one relationships but has " + matches.size(),matches.size()==1);
matchesTargets = ((Relationship)matches.get(0)).getTargets();
assertTrue("'debit(java.lang.String,long)' should have one targets but has" + matchesTargets.size(),matchesTargets.size()==1);
target = AsmManager.getDefault().getHierarchy().findElementForHandle((String)matchesTargets.get(0));
assertEquals("target of relationship should be the 'declare @method' ipe but is IPE with label "
+ target.toLabelString(),decam,target);
}
// this next one reported as a bug by Rob Harrop, but I can't reproduce the failure yet...
//public void testAtAspectWithReferencePCPerClause_pr138220() { runTest("@Aspect with reference pointcut in perclause");}
public void testJarChecking_pr137235_1() { runTest("directory with .jar extension: source and outjar"); }
public void testJarChecking_pr137235_2() { runTest("directory with .jar extension"); }
public void testMakePreMethodNPE_pr136393() { runTest("NPE in makePreMethod");}
public void testGetParameterHandles_pr141730() {
runTest("new IProgramElement handle methods");
checkParametersForIPE("intMethod(int)",IProgramElement.Kind.METHOD,"I",true);
checkParametersForIPE("stringMethod(java.lang.String)",IProgramElement.Kind.METHOD,"Ljava/lang/String;",true);
checkParametersForIPE("myClassMethod(MyClass)",IProgramElement.Kind.METHOD,"LMyClass;",true);
checkParametersForIPE("genericMethod(java.util.List<java.lang.String>)",IProgramElement.Kind.METHOD,"Pjava/util/List<Ljava/lang/String;>;",true);
checkParametersForIPE("genericMethod2(MyGenericClass<java.lang.String,MyClass>)",IProgramElement.Kind.METHOD,"PMyGenericClass<Ljava/lang/String;LMyClass;>;",true);
checkParametersForIPE("main(java.lang.String[])",IProgramElement.Kind.METHOD,"[Ljava/lang/String;",true);
checkParametersForIPE("multiMethod(java.lang.String[][])",IProgramElement.Kind.METHOD,"[[Ljava/lang/String;",true);
checkParametersForIPE("intArray(int[])",IProgramElement.Kind.METHOD,"[I",true);
IHierarchy top = AsmManager.getDefault().getHierarchy();
IProgramElement twoArgsMethod = top.findElementForLabel(
top.getRoot(),IProgramElement.Kind.METHOD,"twoArgsMethod(int,java.lang.String)");
assertNotNull("Couldn't find 'twoArgsMethod(int,java.lang.String)' element in the tree",twoArgsMethod);
List l = twoArgsMethod.getParameterSignatures();
assertEquals("",((char[])l.get(0))[0],'I');
boolean eq = CharOperation.equals(((char[])l.get(1)),"Ljava/lang/String;".toCharArray());
assertTrue("expected parameter to be 'Ljava/lang/String;' but found '" +
new String(((char[])l.get(1))) + "'",eq);
}
public void testGetParameterTypes_pr141730() {
runTest("new IProgramElement handle methods");
checkParametersForIPE("intMethod(int)",IProgramElement.Kind.METHOD,"int",false);
checkParametersForIPE("stringMethod(java.lang.String)",IProgramElement.Kind.METHOD,"java.lang.String",false);
checkParametersForIPE("myClassMethod(MyClass)",IProgramElement.Kind.METHOD,"MyClass",false);
checkParametersForIPE("genericMethod(java.util.List<java.lang.String>)",IProgramElement.Kind.METHOD,"java.util.List<java.lang.String>",false);
checkParametersForIPE("genericMethod2(MyGenericClass<java.lang.String,MyClass>)",IProgramElement.Kind.METHOD,"MyGenericClass<java.lang.String,MyClass>",false);
checkParametersForIPE("main(java.lang.String[])",IProgramElement.Kind.METHOD,"java.lang.String[]",false);
checkParametersForIPE("multiMethod(java.lang.String[][])",IProgramElement.Kind.METHOD,"java.lang.String[][]",false);
checkParametersForIPE("intArray(int[])",IProgramElement.Kind.METHOD,"int[]",false);
}
public void testToSignatureString_pr141730() {
runTest("new IProgramElement handle methods");
checkSignatureOfIPE("main(java.lang.String[])",IProgramElement.Kind.METHOD);
checkSignatureOfIPE("C",IProgramElement.Kind.CLASS);
checkSignatureOfIPE("C()",IProgramElement.Kind.CONSTRUCTOR);
checkSignatureOfIPE("method()",IProgramElement.Kind.METHOD);
checkSignatureOfIPE("p()",IProgramElement.Kind.POINTCUT);
checkSignatureOfIPE("before(): p..",IProgramElement.Kind.ADVICE,"before()");
checkSignatureOfIPE("MyClass.method()",IProgramElement.Kind.INTER_TYPE_METHOD);
checkSignatureOfIPE("multiMethod(java.lang.String[][])",IProgramElement.Kind.METHOD);
checkSignatureOfIPE("intArray(int[])",IProgramElement.Kind.METHOD);
checkSignatureOfIPE("MyClass.MyClass()",IProgramElement.Kind.INTER_TYPE_CONSTRUCTOR);
}
// if not filling in the model for aspects contained in jar files then
// want to ensure that the relationship map is correct and has nodes
// which can be used in AJDT - ensure no NPE occurs for the end of
// the relationship with aspectpath
public void testAspectPathRelWhenNotFillingInModel_pr141730() {
World.createInjarHierarchy = false;
try {
runTest("ensure aspectpath injar relationships are correct when not filling in model");
// expecting:
// sourceOfRelationship main in MyFoo.java
// relationship advised by
// target MyBar.aj
//
// and
//
// sourceOfRelationship MyBar.aj
// relationship advises
// target main in MyFoo.java
IHierarchy top = AsmManager.getDefault().getHierarchy();
IRelationshipMap asmRelMap = AsmManager.getDefault().getRelationshipMap();
assertEquals("expected two sources of relationships but only found "
+ asmRelMap.getEntries().size(),2,asmRelMap.getEntries().size());
for (Iterator iter = asmRelMap.getEntries().iterator(); iter.hasNext();) {
String sourceOfRelationship = (String) iter.next();
IProgramElement ipe = top.findElementForHandle(sourceOfRelationship);
List relationships = asmRelMap.get(ipe);
if (ipe.getName().equals("MyBar.aj")) {
assertEquals("expected MyBar.aj to have one relationships but found "
+ relationships.size(),1,relationships.size());
Relationship rel = (Relationship)relationships.get(0);
assertEquals("expected relationship to be 'advises' but was "
+ rel.getName(), "advises", rel.getName());
List targets = rel.getTargets();
assertEquals("expected one target but found " + targets.size(),1,targets.size());
IProgramElement link = top.findElementForHandle((String)targets.get(0));
assertEquals("expected target 'method-call(void foo.MyFoo.main())' but target " + link.getName(),
"method-call(void foo.MyFoo.main())",link.getName());
String fileName = link.getSourceLocation().getSourceFile().toString();
assertTrue("expected 'main' to be in class MyFoo.java but found it " +
"in " + fileName,fileName.indexOf("MyFoo.java") != -1);
} else if (ipe.getName().equals("method-call(void foo.MyFoo.main())")) {
String fileName = ipe.getSourceLocation().getSourceFile().toString();
assertTrue("expected 'method-call(void foo.MyFoo.main())' to be in " +
"class MyFoo.java but found it in"
+ fileName,fileName.indexOf("MyFoo.java") != -1);
assertEquals("expected 'method-call(void foo.MyFoo.main())' " +
"to have one relationships but found "
+ relationships.size(),1,relationships.size());
Relationship rel = (Relationship)relationships.get(0);
assertEquals("expected relationship to be 'advised by' but was "
+ rel.getName(), "advised by", rel.getName());
List targets = rel.getTargets();
assertEquals("expected one target but found " + targets.size(),1,targets.size());
IProgramElement link = top.findElementForHandle((String)targets.get(0));
assertEquals("expected target 'MyBar.aj' but target " + link.getName(),
"MyBar.aj",link.getName());
} else {
fail("unexpected element " + ipe.getName() + " in the relationship map");
}
}
} finally {
World.createInjarHierarchy = true;
}
}
// if not filling in the model for classes contained in jar files then
// want to ensure that the relationship map is correct and has nodes
// which can be used in AJDT - ensure no NPE occurs for the end of
// the relationship with inpath
public void testNoNPEWithInpathWhenNotFillingInModel_pr141730() {
World.createInjarHierarchy = false;
try {
runTest("ensure inpath injar relationships are correct when not filling in model");
// the aspect used for this test has advice, declare parents, deow,
// and declare @type, @constructor, @field and @method. We only expect
// there to be relationships in the map for declare parents and declare @type
// (provided the model isn't being filled in) because the logic in the other
// addXXXRelationship methods use AspectJElementHierarchy.findElementForType().
// This method which returns null because there is no such ipe. The relationship is
// therefore not added to the model. Adding declare @type and declare parents
// uses AspectJElementHierarchy.findElementForHandle() which returns the file
// node ipe if it can't find one for the given handle. Therefore the relationships
// are added against the file node. Before change to using ipe's to create handles
// we also had the deow relationship, however, now we don't because this also
// uses findElementForType to find the targetNode which in the inpath case is null.
// just check that the number of entries is what we expect:
// We expect 3 (the declare @type and declare parents statements plus the filenode)
IRelationshipMap relMap = AsmManager.getDefault().getRelationshipMap();
assertEquals("expected 3 entries in the relationship map but found "
+ relMap.getEntries().size(), 3, relMap.getEntries().size());
} finally {
World.createInjarHierarchy = true;
}
}
// public void testFunkyGenericErrorWithITDs_pr126355_2() {
// runTest("bizarre generic error with itds - 2");
// // public class Pair<F,S> affected by pertarget aspect
// GenericsTests.verifyClassSignature(ajc,"Pair","<F:Ljava/lang/Object;S:Ljava/lang/Object;>Ljava/lang/Object;LIdempotentCache$ajcMightHaveAspect;;");
// }
public void testNoAspects(){
// setSystemProperty(WeavingAdaptor.WEAVING_ADAPTOR_VERBOSE,"true");
runTest("Ensure no weaving without included aspects");
}
public void testWeaveinfoMessages (){
runTest("weaveinfo messages with include and exclude");
}
// tests that can't be included for some reason
// Not valid whilst the ajc compiler forces debug on (ignores -g:none) - it will be green but is invalid, trust me
// public void testLongWindedMessages_pr129408() { runTest("long winded ataj messages");}
// ---------------- helper methods ---------------
private void checkParametersForIPE(String ipeLabel, IProgramElement.Kind kind, String expectedParm, boolean getHandles) {
IHierarchy top = AsmManager.getDefault().getHierarchy();
IProgramElement ipe = top.findElementForLabel(top.getRoot(),kind,ipeLabel);
assertNotNull("Couldn't find '" + ipeLabel + "' element in the tree",ipe);
List l = new ArrayList();
if (getHandles) {
l = ipe.getParameterSignatures();
} else {
l = ipe.getParameterTypes();
}
boolean eq = CharOperation.equals(((char[])l.get(0)),expectedParm.toCharArray());
assertTrue("expected parameter to be '" + expectedParm + "' but found '" +
new String(((char[])l.get(0))) + "'",eq);
}
private void checkSignatureOfIPE(String ipeLabel, IProgramElement.Kind kind) {
checkSignatureOfIPE(ipeLabel,kind,ipeLabel);
}
private void checkSignatureOfIPE(String ipeLabel, IProgramElement.Kind kind, String expectedSig) {
IHierarchy top = AsmManager.getDefault().getHierarchy();
IProgramElement ipe = top.findElementForLabel(
top.getRoot(),kind,ipeLabel);
assertNotNull("Couldn't find '" + ipeLabel + "' element in the tree",ipe);
assertEquals("expected signature to be '"+ expectedSig + "' but was " +
ipe.toSignatureString(true),expectedSig,ipe.toSignatureString(true));
}
/////////////////////////////////////////
public static Test suite() {
return XMLBasedAjcTestCase.loadSuite(Ajc152Tests.class);
}
protected File getSpecFile() {
return new File("../tests/src/org/aspectj/systemtest/ajc152/ajc152.xml");
}
}
|
147,845 |
Bug 147845 Generic abstract aspect hierarchies 3 deep or higher can fail when type parameters have bounds
|
The program below should compile happily, but fails with: [error] Type B does not meet the specification for type parameter 1 (A extends MyBase) in generic type Base abstract aspect Middle<B extends MyBase> extends Base<B> {} ^^^^^ The test program: ------------------ interface MyBase {}; interface MyMarker extends MyBase {} abstract aspect Base<A extends MyBase> {} abstract aspect Middle<B extends MyBase> extends Base<B> {} aspect Sub extends Middle<MyMarker> {}
|
resolved fixed
|
791f8a7
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-06-20T11:12:49Z | 2006-06-20T10:40:00Z |
weaver/src/org/aspectj/weaver/TypeVariable.java
|
/* *******************************************************************
* Copyright (c) 2005 Contributors.
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Eclipse Public License v1.0
* which accompanies this distribution and is available at
* http://eclipse.org/legal/epl-v10.html
*
* Contributors:
* Adrian Colyer Initial implementation
* ******************************************************************/
package org.aspectj.weaver;
import java.io.DataOutputStream;
import java.io.IOException;
import java.util.HashSet;
import java.util.Set;
/**
* Represents a type variable with bounds
*/
public class TypeVariable {
public static final TypeVariable[] NONE = new TypeVariable[0];
/**
* whether or not the bounds of this type variable have been
* resolved
*/
private boolean isResolved = false;
private boolean beingResolved = false;
/**
* the name of the type variable as recorded in the generic signature
*/
private String name;
private int rank;
// 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...)
/**
* What kind of element declared this type variable?
*/
private int declaringElementKind = UNKNOWN;
public static final int UNKNOWN = -1;
public static final int METHOD = 1;
public static final int TYPE = 2;
private TypeVariableDeclaringElement declaringElement;
/**
* the upper bound of the type variable (default to Object).
* From the extends clause, eg. T extends Number.
*/
private UnresolvedType upperBound = UnresolvedType.OBJECT;
/**
* any additional upper (interface) bounds.
* from the extends clause, e.g. T extends Number & Comparable
*/
private UnresolvedType[] additionalInterfaceBounds = new UnresolvedType[0];
/**
* any lower bound.
* from the super clause, eg T super Foo
*/
private UnresolvedType lowerBound = null;
public TypeVariable(String aName) {
this.name = aName;
}
public TypeVariable(String aName, UnresolvedType anUpperBound) {
this(aName);
this.upperBound = anUpperBound;
}
public TypeVariable(String aName, UnresolvedType anUpperBound,
UnresolvedType[] someAdditionalInterfaceBounds) {
this(aName,anUpperBound);
this.additionalInterfaceBounds = someAdditionalInterfaceBounds;
}
public TypeVariable(String aName, UnresolvedType anUpperBound,
UnresolvedType[] someAdditionalInterfaceBounds, UnresolvedType aLowerBound) {
this(aName,anUpperBound,someAdditionalInterfaceBounds);
this.lowerBound = aLowerBound;
}
// First bound is the first 'real' bound, this can be an interface if
// no class bound was specified (it will default to object)
public UnresolvedType getFirstBound() {
if (upperBound.equals(UnresolvedType.OBJECT) && additionalInterfaceBounds!=null && additionalInterfaceBounds.length!=0) {
return additionalInterfaceBounds[0];
}
return upperBound;
}
public UnresolvedType getUpperBound() {
return upperBound;
}
public UnresolvedType[] getAdditionalInterfaceBounds() {
return additionalInterfaceBounds;
}
public UnresolvedType getLowerBound() {
return lowerBound;
}
public String getName() {
return name;
}
/**
* resolve all the bounds of this type variable
*/
public TypeVariable resolve(World inSomeWorld) {
if (beingResolved) { return this; } // avoid spiral of death
beingResolved = true;
if (isResolved) return this;
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(inSomeWorld);
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) {
// 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;
}
upperBound = resolvedTVar.upperBound;
lowerBound = resolvedTVar.lowerBound;
additionalInterfaceBounds = resolvedTVar.additionalInterfaceBounds;
upperBound = upperBound.resolve(inSomeWorld);
if (lowerBound != null) lowerBound = lowerBound.resolve(inSomeWorld);
if (additionalInterfaceBounds!=null) {
for (int i = 0; i < additionalInterfaceBounds.length; i++) {
additionalInterfaceBounds[i] = additionalInterfaceBounds[i].resolve(inSomeWorld);
}
}
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 aCandidateType) {
if (!isResolved) throw new IllegalStateException("Can't answer binding questions prior to resolving");
if (aCandidateType.isTypeVariableReference()) {
return matchingBounds((TypeVariableReferenceType)aCandidateType);
}
// wildcard can accept any binding
if (aCandidateType.isGenericWildcard()) { // AMC - need a more robust test!
return true;
}
// otherwise can be bound iff...
// aCandidateType is a subtype of upperBound
if (!isASubtypeOf(upperBound,aCandidateType)) {
return false;
}
// aCandidateType is a subtype of all additionalInterfaceBounds
for (int i = 0; i < additionalInterfaceBounds.length; i++) {
if (!isASubtypeOf(additionalInterfaceBounds[i], aCandidateType)) {
return false;
}
}
// lowerBound is a subtype of aCandidateType
if ((lowerBound != null) && (!isASubtypeOf(aCandidateType,lowerBound))) {
return false;
}
return true;
}
// can match any type in the range of the type variable...
// XXX what about interfaces?
private boolean matchingBounds(TypeVariableReferenceType tvrt) {
if (tvrt.getUpperBound() != getUpperBound()) return false;
if (tvrt.hasLowerBound() != (getLowerBound() != null)) return false;
if (tvrt.hasLowerBound() && tvrt.getLowerBound() != getLowerBound()) return false;
// either we both have bounds, or neither of us have bounds
if ((tvrt.additionalInterfaceBounds != null) != (additionalInterfaceBounds != null)) return false;
if (additionalInterfaceBounds != null) {
// we both have bounds, compare
if (tvrt.additionalInterfaceBounds.length != additionalInterfaceBounds.length) return false;
Set aAndNotB = new HashSet();
Set bAndNotA = new HashSet();
for (int i = 0; i < additionalInterfaceBounds.length; i++) {
aAndNotB.add(additionalInterfaceBounds[i]);
}
for (int i = 0; i < tvrt.additionalInterfaceBounds.length; i++) {
bAndNotA.add(tvrt.additionalInterfaceBounds[i]);
}
for (int i = 0; i < additionalInterfaceBounds.length; i++) {
bAndNotA.remove(additionalInterfaceBounds[i]);
}
for (int i = 0; i < tvrt.additionalInterfaceBounds.length; i++) {
aAndNotB.remove(tvrt.additionalInterfaceBounds[i]);
}
if (! (aAndNotB.isEmpty() && bAndNotA.isEmpty()) ) 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 aTypeX) {
this.upperBound = aTypeX;
}
// only used when resolving
public void setLowerBound(UnresolvedType aTypeX) {
this.lowerBound = aTypeX;
}
// only used when resolving
public void setAdditionalInterfaceBounds(UnresolvedType[] someTypeXs) {
this.additionalInterfaceBounds = someTypeXs;
}
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 (additionalInterfaceBounds != null) {
for (int i = 0; i < additionalInterfaceBounds.length; i++) {
if (!getFirstBound().equals(additionalInterfaceBounds[i])) {
ret.append(" & ");
ret.append(additionalInterfaceBounds[i].getName());
}
}
}
}
if (lowerBound != null) {
ret.append(" super ");
ret.append(lowerBound.getName());
}
return ret.toString();
}
// good enough approximation
public String toString() {
return "TypeVar " + getDisplayName();
}
/**
* Return *full* signature for insertion in signature attribute, e.g. "T extends Number" would return "T:Ljava/lang/Number;"
*/
public String getSignature() {
StringBuffer sb = new StringBuffer();
sb.append(name);
sb.append(":");
sb.append(upperBound.getSignature());
if (additionalInterfaceBounds!=null && additionalInterfaceBounds.length!=0) {
sb.append(":");
for (int i = 0; i < additionalInterfaceBounds.length; i++) {
UnresolvedType iBound = additionalInterfaceBounds[i];
sb.append(iBound.getSignature());
}
}
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(DataOutputStream s) throws IOException {
// name, upperbound, additionalInterfaceBounds, lowerbound
s.writeUTF(name);
upperBound.write(s);
if (additionalInterfaceBounds==null || additionalInterfaceBounds.length==0) {
s.writeInt(0);
} else {
s.writeInt(additionalInterfaceBounds.length);
for (int i = 0; i < additionalInterfaceBounds.length; i++) {
UnresolvedType ibound = additionalInterfaceBounds[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 = null;
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;
}
}
|
147,801 |
Bug 147801 java.lang.ClassFormatError: Repetitive method name/signature
|
I get a ClassFormatError trying to perform runtime-weaving on a DB2 class. The class being woven is COM.ibm.db2.jdbc.app.DB2PreparedStatement. The full message exception is: java.lang.ClassFormatError: Repetitive method name/signature in class file COM/ibm/db2/jdbc/app/DB2PreparedStatement. In examining the post-weave class file, it looks as if Aspectj is defining a duplicate method within the class called getParameterMetaData(). Here are the messages from the weaver: 04:21:13,640 INFO [STDOUT] info weaving 'COM.ibm.db2.jdbc.app.DB2CallableStatement' 04:21:13,640 INFO [STDOUT] info weaver operating in reweavable mode. Need to verify any required types exist. 04:21:13,671 INFO [STDOUT] info weaving 'COM.ibm.db2.jdbc.app.DB2PreparedStatement' 04:21:13,671 INFO [STDOUT] info weaver operating in reweavable mode. Need to verify any required types exist. 04:21:13,703 INFO [STDOUT] weaveinfo Join point 'method-execution(java.sql.ResultSet COM.ibm.db2.jdbc.app.DB2PreparedStatement.executeQuery())' in Type 'COM.ibm.db2.jdbc.app.DB2PreparedStatement' (DB2PreparedStatement.java:1679) advised by before advice from 'com.ibm.tivoli.itcam.toolkit.ai.aspectj.captureJDBC.CaptureSQLStatement' (CaptureSQLStatement.aj:747) [with runtime test] 04:21:13,703 INFO [STDOUT] weaveinfo Join point 'method-execution(java.sql.ResultSet COM.ibm.db2.jdbc.app.DB2PreparedStatement.executeQuery())' in Type 'COM.ibm.db2.jdbc.app.DB2PreparedStatement' (DB2PreparedStatement.java:1679) advised by afterReturning advice from 'com.ibm.tivoli.itcam.toolkit.ai.aspectj.captureJDBC.CaptureSQLStatement' (CaptureSQLStatement.aj:946) [with runtime test] 04:21:13,718 INFO [STDOUT] weaveinfo Join point 'method-execution(java.sql.ResultSet COM.ibm.db2.jdbc.app.DB2PreparedStatement.executeQuery())' in Type 'COM.ibm.db2.jdbc.app.DB2PreparedStatement' (DB2PreparedStatement.java:1679) advised by afterThrowing advice from 'com.ibm.tivoli.itcam.toolkit.ai.aspectj.captureJDBC.CaptureSQLStatement' (CaptureSQLStatement.aj:971) [with runtime test] 04:21:13,718 INFO [STDOUT] weaveinfo Join point 'method-execution(boolean COM.ibm.db2.jdbc.app.DB2PreparedStatement.execute())' in Type 'COM.ibm.db2.jdbc.app.DB2PreparedStatement' (DB2PreparedStatement.java:3971) advised by before advice from 'com.ibm.tivoli.itcam.toolkit.ai.aspectj.captureJDBC.CaptureSQLStatement' (CaptureSQLStatement.aj:833) [with runtime test] 04:21:13,718 INFO [STDOUT] weaveinfo Join point 'method-execution(boolean COM.ibm.db2.jdbc.app.DB2PreparedStatement.execute())' in Type 'COM.ibm.db2.jdbc.app.DB2PreparedStatement' (DB2PreparedStatement.java:3971) advised by afterReturning advice from 'com.ibm.tivoli.itcam.toolkit.ai.aspectj.captureJDBC.CaptureSQLStatement' (CaptureSQLStatement.aj:946) [with runtime test]
|
resolved fixed
|
13dde4e
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-06-21T11:33:21Z | 2006-06-19T20:46:40Z |
tests/bugs152/pr147801/Foo.java
| |
147,801 |
Bug 147801 java.lang.ClassFormatError: Repetitive method name/signature
|
I get a ClassFormatError trying to perform runtime-weaving on a DB2 class. The class being woven is COM.ibm.db2.jdbc.app.DB2PreparedStatement. The full message exception is: java.lang.ClassFormatError: Repetitive method name/signature in class file COM/ibm/db2/jdbc/app/DB2PreparedStatement. In examining the post-weave class file, it looks as if Aspectj is defining a duplicate method within the class called getParameterMetaData(). Here are the messages from the weaver: 04:21:13,640 INFO [STDOUT] info weaving 'COM.ibm.db2.jdbc.app.DB2CallableStatement' 04:21:13,640 INFO [STDOUT] info weaver operating in reweavable mode. Need to verify any required types exist. 04:21:13,671 INFO [STDOUT] info weaving 'COM.ibm.db2.jdbc.app.DB2PreparedStatement' 04:21:13,671 INFO [STDOUT] info weaver operating in reweavable mode. Need to verify any required types exist. 04:21:13,703 INFO [STDOUT] weaveinfo Join point 'method-execution(java.sql.ResultSet COM.ibm.db2.jdbc.app.DB2PreparedStatement.executeQuery())' in Type 'COM.ibm.db2.jdbc.app.DB2PreparedStatement' (DB2PreparedStatement.java:1679) advised by before advice from 'com.ibm.tivoli.itcam.toolkit.ai.aspectj.captureJDBC.CaptureSQLStatement' (CaptureSQLStatement.aj:747) [with runtime test] 04:21:13,703 INFO [STDOUT] weaveinfo Join point 'method-execution(java.sql.ResultSet COM.ibm.db2.jdbc.app.DB2PreparedStatement.executeQuery())' in Type 'COM.ibm.db2.jdbc.app.DB2PreparedStatement' (DB2PreparedStatement.java:1679) advised by afterReturning advice from 'com.ibm.tivoli.itcam.toolkit.ai.aspectj.captureJDBC.CaptureSQLStatement' (CaptureSQLStatement.aj:946) [with runtime test] 04:21:13,718 INFO [STDOUT] weaveinfo Join point 'method-execution(java.sql.ResultSet COM.ibm.db2.jdbc.app.DB2PreparedStatement.executeQuery())' in Type 'COM.ibm.db2.jdbc.app.DB2PreparedStatement' (DB2PreparedStatement.java:1679) advised by afterThrowing advice from 'com.ibm.tivoli.itcam.toolkit.ai.aspectj.captureJDBC.CaptureSQLStatement' (CaptureSQLStatement.aj:971) [with runtime test] 04:21:13,718 INFO [STDOUT] weaveinfo Join point 'method-execution(boolean COM.ibm.db2.jdbc.app.DB2PreparedStatement.execute())' in Type 'COM.ibm.db2.jdbc.app.DB2PreparedStatement' (DB2PreparedStatement.java:3971) advised by before advice from 'com.ibm.tivoli.itcam.toolkit.ai.aspectj.captureJDBC.CaptureSQLStatement' (CaptureSQLStatement.aj:833) [with runtime test] 04:21:13,718 INFO [STDOUT] weaveinfo Join point 'method-execution(boolean COM.ibm.db2.jdbc.app.DB2PreparedStatement.execute())' in Type 'COM.ibm.db2.jdbc.app.DB2PreparedStatement' (DB2PreparedStatement.java:3971) advised by afterReturning advice from 'com.ibm.tivoli.itcam.toolkit.ai.aspectj.captureJDBC.CaptureSQLStatement' (CaptureSQLStatement.aj:946) [with runtime test]
|
resolved fixed
|
13dde4e
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-06-21T11:33:21Z | 2006-06-19T20:46:40Z |
tests/bugs152/pr147801/PreparedStatement.java
| |
147,801 |
Bug 147801 java.lang.ClassFormatError: Repetitive method name/signature
|
I get a ClassFormatError trying to perform runtime-weaving on a DB2 class. The class being woven is COM.ibm.db2.jdbc.app.DB2PreparedStatement. The full message exception is: java.lang.ClassFormatError: Repetitive method name/signature in class file COM/ibm/db2/jdbc/app/DB2PreparedStatement. In examining the post-weave class file, it looks as if Aspectj is defining a duplicate method within the class called getParameterMetaData(). Here are the messages from the weaver: 04:21:13,640 INFO [STDOUT] info weaving 'COM.ibm.db2.jdbc.app.DB2CallableStatement' 04:21:13,640 INFO [STDOUT] info weaver operating in reweavable mode. Need to verify any required types exist. 04:21:13,671 INFO [STDOUT] info weaving 'COM.ibm.db2.jdbc.app.DB2PreparedStatement' 04:21:13,671 INFO [STDOUT] info weaver operating in reweavable mode. Need to verify any required types exist. 04:21:13,703 INFO [STDOUT] weaveinfo Join point 'method-execution(java.sql.ResultSet COM.ibm.db2.jdbc.app.DB2PreparedStatement.executeQuery())' in Type 'COM.ibm.db2.jdbc.app.DB2PreparedStatement' (DB2PreparedStatement.java:1679) advised by before advice from 'com.ibm.tivoli.itcam.toolkit.ai.aspectj.captureJDBC.CaptureSQLStatement' (CaptureSQLStatement.aj:747) [with runtime test] 04:21:13,703 INFO [STDOUT] weaveinfo Join point 'method-execution(java.sql.ResultSet COM.ibm.db2.jdbc.app.DB2PreparedStatement.executeQuery())' in Type 'COM.ibm.db2.jdbc.app.DB2PreparedStatement' (DB2PreparedStatement.java:1679) advised by afterReturning advice from 'com.ibm.tivoli.itcam.toolkit.ai.aspectj.captureJDBC.CaptureSQLStatement' (CaptureSQLStatement.aj:946) [with runtime test] 04:21:13,718 INFO [STDOUT] weaveinfo Join point 'method-execution(java.sql.ResultSet COM.ibm.db2.jdbc.app.DB2PreparedStatement.executeQuery())' in Type 'COM.ibm.db2.jdbc.app.DB2PreparedStatement' (DB2PreparedStatement.java:1679) advised by afterThrowing advice from 'com.ibm.tivoli.itcam.toolkit.ai.aspectj.captureJDBC.CaptureSQLStatement' (CaptureSQLStatement.aj:971) [with runtime test] 04:21:13,718 INFO [STDOUT] weaveinfo Join point 'method-execution(boolean COM.ibm.db2.jdbc.app.DB2PreparedStatement.execute())' in Type 'COM.ibm.db2.jdbc.app.DB2PreparedStatement' (DB2PreparedStatement.java:3971) advised by before advice from 'com.ibm.tivoli.itcam.toolkit.ai.aspectj.captureJDBC.CaptureSQLStatement' (CaptureSQLStatement.aj:833) [with runtime test] 04:21:13,718 INFO [STDOUT] weaveinfo Join point 'method-execution(boolean COM.ibm.db2.jdbc.app.DB2PreparedStatement.execute())' in Type 'COM.ibm.db2.jdbc.app.DB2PreparedStatement' (DB2PreparedStatement.java:3971) advised by afterReturning advice from 'com.ibm.tivoli.itcam.toolkit.ai.aspectj.captureJDBC.CaptureSQLStatement' (CaptureSQLStatement.aj:946) [with runtime test]
|
resolved fixed
|
13dde4e
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-06-21T11:33:21Z | 2006-06-19T20:46:40Z |
tests/src/org/aspectj/systemtest/ajc152/Ajc152Tests.java
|
/*******************************************************************************
* Copyright (c) 2006 IBM
* 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.ajc152;
import java.io.File;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import junit.framework.Test;
import org.aspectj.asm.AsmManager;
import org.aspectj.asm.IHierarchy;
import org.aspectj.asm.IProgramElement;
import org.aspectj.asm.IRelationshipMap;
import org.aspectj.asm.internal.Relationship;
import org.aspectj.testing.XMLBasedAjcTestCase;
import org.aspectj.util.CharOperation;
import org.aspectj.weaver.World;
public class Ajc152Tests extends org.aspectj.testing.XMLBasedAjcTestCase {
// public void testverifyErrNoTypeCflowField_pr145693() {runTest("verifyErrNoTypeCflowField");}
// public void testBrokenIfArgsCflowAtAj_pr145018() { runTest("ataj crashing with cflow, if and args");}
// public void testItdCallingGenericMethod_pr145391() { runTest("itd calling generic method");}
// public void testItdCallingGenericMethod_pr145391_2() { runTest("itd calling generic method - 2");}
public void testPackageIgnoredForException_pr147701_1() { runTest("package for exception ignored");}
public void testPackageIgnoredForException_pr147701_2() { runTest("package for exception ignored - 2");}
public void testPackageIgnoredForException_pr147701_3() { runTest("package for exception ignored - 3");}
public void testBrokenAddSerialVersionUID_pr145950() {runTest("fails to discover Serializable");}
public void testNoUnnecessaryDeclarationOfThrownExcp_pr129282_1() {runTest("no unnecessary declaration of thrown exception warning - 1");}
public void testNoUnnecessaryDeclarationOfThrownExcp_pr129282_2() {runTest("no unnecessary declaration of thrown exception warning - 2");}
public void testNoUnnecessaryDeclarationOfThrownExcp_pr129282_3() {runTest("no unnecessary declaration of thrown exception warning - 3");}
public void testNoUnnecessaryDeclarationOfThrownExcp_pr129282_4() {runTest("no unnecessary declaration of thrown exception warning - 4");}
public void testNoUnnecessaryDeclarationOfThrownExcp_pr129282_5() {runTest("no unnecessary declaration of thrown exception warning - 5");}
public void testNoUnnecessaryDeclarationOfThrownExcp_pr129282_6() {runTest("no unnecessary declaration of thrown exception warning - 6");}
public void testNoUnnecessaryDeclarationOfThrownExcp_pr129282_7() {runTest("no unnecessary declaration of thrown exception warning - 7");}
public void testNoUnnecessaryDeclarationOfThrownExcp_pr129282_8() {runTest("no unnecessary declaration of thrown exception warning - 8");}
public void testNoUnnecessaryDeclarationOfThrownExcp_pr129282_9() {runTest("no unnecessary declaration of thrown exception warning - 9");}
public void testNoUnnecessaryDeclarationOfThrownExcp_pr129282_10() {runTest("no unnecessary declaration of thrown exception warning - 10");}
public void testAtAJVerificationError_pr144602() { runTest("atAJ perthis aspect verification error");}
public void testLTWAndGeneratingSUID_pr144465() { runTest("ltw with serialversionUID creation"); }
public void testAspects14PerSingleton_pr122253() { runTest("aspects14 - persingleton");}
public void testAspects14PerCflow_pr122253() { runTest("aspects14 - percflow");}
public void testAspects14PerThis_pr122253() { runTest("aspects14 - perthis");}
public void testAspects14PerTypeWithin_pr122253() { runTest("aspects14 - pertypewithin");}
public void testFunkyGenericErrorWithITDs_pr126355() { runTest("bizarre generic error with itds");}
public void testConcretizingAbstractMethods_pr142466() { runTest("aop.xml aspect inheriting but not concretizing abstract method");}
public void testConcretizingAbstractMethods_pr142466_2() { runTest("aop.xml aspect inheriting but not concretizing abstract method - 2");}
public void testComplexGenericDecl_pr137568() { runTest("complicated generics declaration");}
public void testItdOnInnerTypeOfGenericType_pr132349() { runTest("ITD on inner type of generic type");}
public void testItdOnInnerTypeOfGenericType_pr132349_2() { runTest("ITD on inner type of generic type - 2");}
public void testItdOnInnerTypeOfGenericType_pr132349_3() { runTest("ITD on inner type of generic type - 3");}
// public void testCovarianceAndDecp_pr128443_1() { runTest("covariance and decp - 1"); }
public void testLTWGeneratedAspectAbstractMethod_pr125480() { runTest("aop.xml aspect inheriting abstract method ");}
public void testLTWGeneratedAspectAbstractMethod_pr125480_2() { runTest("aop.xml aspect inheriting abstract method - code style");}
//public void testSuperITDExplosion_pr134425() { runTest("super ITDs");}
//public void testMisbehavingDeclareAnnotation_pr135865() { runTest("misbehaving declare annotation");}
//public void testMisbehavingDeclareAnnotation_pr135865_2() { runTest("misbehaving declare annotation - 2");}
public void testCompletelyBrokenAopConcretization_pr142165_1() { runTest("broken concretization");}
public void testCompletelyBrokenAopConcretization_pr142165_2() { runTest("broken concretization - 2");}
public void testCompletelyBrokenAopConcretization_pr142165_3() { runTest("broken concretization - 3");}
public void testVerifyErrorLTW_pr135068() { runTest("ltw verifyerror");}
public void testVerifyErrorLTW_pr135068_2() { runTest("ltw verifyerror - 2");}
public void testVerifyErrorLTW_pr135068_3() { runTest("ltw verifyerror - 3");}
public void testVerifyErrorLTW_pr135068_4() { runTest("ltw verifyerror - 4");}
public void testVerifyErrorForComplexCflow_pr136026() { runTest("verifyerror");}
public void testVerifyErrorForComplexCflow_pr136026_2() { runTest("verifyerror - 2");}
public void testAnnotationsAndGenericsBCException_pr129704() { runTest("annotations and generics leading to BCException");}
public void testMethodTooBigAfterWeaving_pr138384() { runTest("method too big"); }
public void testNotAtWithincode_pr138158_1() { runTest("not at withincode - 1");}
public void testNotAtWithincode_pr138158_2() { runTest("not at withincode - 2");}
public void testNotAtWithincode_pr138158_3() { runTest("not at within - 3");}
public void testNpeOnDup_pr138143() { runTest("npe on duplicate method with ataj");}
public void testPointcutsAndGenerics_pr137496_1() { runTest("pointcuts and generics - B");}
public void testPointcutsAndGenerics_pr137496_2() { runTest("pointcuts and generics - D");}
public void testPointcutsAndGenerics_pr137496_3() { runTest("pointcuts and generics - E");}
public void testPointcutsAndGenerics_pr137496_4() { runTest("pointcuts and generics - F");}
public void testPointcutsAndGenerics_pr137496_5() { runTest("pointcuts and generics - G");}
public void testPointcutsAndGenerics_pr137496_6() { runTest("pointcuts and generics - H");}
public void testAspectLibrariesAndASM_pr135001() { runTest("aspect libraries and asm");}
public void testStackOverflow_pr136258() { runTest("stack overflow");}
public void testIncorrectOverridesEvaluation13() { runTest("incorrect overrides evaluation - 1.3"); }
public void testIncorrectOverridesEvaluation15() { runTest("incorrect overrides evaluation - 1.5"); }
public void testAtWithinCodeBug_pr138798() { runTest("atWithinCodeBug"); }
public void testReferencePCutInDeclareWarning_pr138215() { runTest("Reference pointcut fails inside @DeclareWarning");}
public void testReferencePCutInPerClause_pr138219() { runTest("Can't use a FQ Reference pointcut in any pointcut expression referenced by a per-clause");}
public void testReferencePCutInPerClause_pr130722() { runTest("FQ Reference pointcut from perclause ref pc"); }
public void testDoubleAnnotationMatching_pr138223() { runTest("Double at annotation matching (no binding)");}
public void testSuperCallsInAtAspectJAdvice_pr139749() { runTest("Super calls in @AspectJ advice");}
public void testNoClassCastExceptionWithPerThis_pr138286() { runTest("No ClassCastException with perThis");}
public void testGenericAspectHierarchyWithBounds_pr147845() { runTest("Generic abstract aspect hierarchy with bounds"); }
public void testDeclareAtMethodRelationship_pr143924() {
//AsmManager.setReporting("c:/debug.txt",true,true,true,true);
runTest("declare @method relationship");
IHierarchy top = AsmManager.getDefault().getHierarchy();
// get the IProgramElements corresponding to the different code entries
IProgramElement decam = top.findElementForLabel(top.getRoot(),
IProgramElement.Kind.DECLARE_ANNOTATION_AT_METHOD,
"declare @method: * debit(..) : @Secured(role = \"supervisor\")");
assertNotNull("Couldn't find 'declare @method' element in the tree",decam);
IProgramElement method = top.findElementForLabel(top.getRoot(),
IProgramElement.Kind.METHOD,"debit(java.lang.String,long)");
assertNotNull("Couldn't find the 'debit(String,long)' method element in the tree",method);
List matches = AsmManager.getDefault().getRelationshipMap().get(decam);
assertNotNull("'declare @method' should have some relationships but does not",matches);
assertTrue("'declare @method' should have one relationships but has " + matches.size(),matches.size()==1);
List matchesTargets = ((Relationship)matches.get(0)).getTargets();
assertTrue("'declare @method' should have one targets but has" + matchesTargets.size(),matchesTargets.size()==1);
IProgramElement target = AsmManager.getDefault().getHierarchy().findElementForHandle((String)matchesTargets.get(0));
assertEquals("target of relationship should be the 'debit(java.lang.String,long)' method but is IPE with label "
+ target.toLabelString(),method,target);
// check that the debit method has an annotated by relationship with the declare @method
matches = AsmManager.getDefault().getRelationshipMap().get(method);
assertNotNull("'debit(java.lang.String,long)' should have some relationships but does not",matches);
assertTrue("'debit(java.lang.String,long)' should have one relationships but has " + matches.size(),matches.size()==1);
matchesTargets = ((Relationship)matches.get(0)).getTargets();
assertTrue("'debit(java.lang.String,long)' should have one targets but has" + matchesTargets.size(),matchesTargets.size()==1);
target = AsmManager.getDefault().getHierarchy().findElementForHandle((String)matchesTargets.get(0));
assertEquals("target of relationship should be the 'declare @method' ipe but is IPE with label "
+ target.toLabelString(),decam,target);
}
// this next one reported as a bug by Rob Harrop, but I can't reproduce the failure yet...
//public void testAtAspectWithReferencePCPerClause_pr138220() { runTest("@Aspect with reference pointcut in perclause");}
public void testJarChecking_pr137235_1() { runTest("directory with .jar extension: source and outjar"); }
public void testJarChecking_pr137235_2() { runTest("directory with .jar extension"); }
public void testMakePreMethodNPE_pr136393() { runTest("NPE in makePreMethod");}
public void testGetParameterHandles_pr141730() {
runTest("new IProgramElement handle methods");
checkParametersForIPE("intMethod(int)",IProgramElement.Kind.METHOD,"I",true);
checkParametersForIPE("stringMethod(java.lang.String)",IProgramElement.Kind.METHOD,"Ljava/lang/String;",true);
checkParametersForIPE("myClassMethod(MyClass)",IProgramElement.Kind.METHOD,"LMyClass;",true);
checkParametersForIPE("genericMethod(java.util.List<java.lang.String>)",IProgramElement.Kind.METHOD,"Pjava/util/List<Ljava/lang/String;>;",true);
checkParametersForIPE("genericMethod2(MyGenericClass<java.lang.String,MyClass>)",IProgramElement.Kind.METHOD,"PMyGenericClass<Ljava/lang/String;LMyClass;>;",true);
checkParametersForIPE("main(java.lang.String[])",IProgramElement.Kind.METHOD,"[Ljava/lang/String;",true);
checkParametersForIPE("multiMethod(java.lang.String[][])",IProgramElement.Kind.METHOD,"[[Ljava/lang/String;",true);
checkParametersForIPE("intArray(int[])",IProgramElement.Kind.METHOD,"[I",true);
IHierarchy top = AsmManager.getDefault().getHierarchy();
IProgramElement twoArgsMethod = top.findElementForLabel(
top.getRoot(),IProgramElement.Kind.METHOD,"twoArgsMethod(int,java.lang.String)");
assertNotNull("Couldn't find 'twoArgsMethod(int,java.lang.String)' element in the tree",twoArgsMethod);
List l = twoArgsMethod.getParameterSignatures();
assertEquals("",((char[])l.get(0))[0],'I');
boolean eq = CharOperation.equals(((char[])l.get(1)),"Ljava/lang/String;".toCharArray());
assertTrue("expected parameter to be 'Ljava/lang/String;' but found '" +
new String(((char[])l.get(1))) + "'",eq);
}
public void testGetParameterTypes_pr141730() {
runTest("new IProgramElement handle methods");
checkParametersForIPE("intMethod(int)",IProgramElement.Kind.METHOD,"int",false);
checkParametersForIPE("stringMethod(java.lang.String)",IProgramElement.Kind.METHOD,"java.lang.String",false);
checkParametersForIPE("myClassMethod(MyClass)",IProgramElement.Kind.METHOD,"MyClass",false);
checkParametersForIPE("genericMethod(java.util.List<java.lang.String>)",IProgramElement.Kind.METHOD,"java.util.List<java.lang.String>",false);
checkParametersForIPE("genericMethod2(MyGenericClass<java.lang.String,MyClass>)",IProgramElement.Kind.METHOD,"MyGenericClass<java.lang.String,MyClass>",false);
checkParametersForIPE("main(java.lang.String[])",IProgramElement.Kind.METHOD,"java.lang.String[]",false);
checkParametersForIPE("multiMethod(java.lang.String[][])",IProgramElement.Kind.METHOD,"java.lang.String[][]",false);
checkParametersForIPE("intArray(int[])",IProgramElement.Kind.METHOD,"int[]",false);
}
public void testToSignatureString_pr141730() {
runTest("new IProgramElement handle methods");
checkSignatureOfIPE("main(java.lang.String[])",IProgramElement.Kind.METHOD);
checkSignatureOfIPE("C",IProgramElement.Kind.CLASS);
checkSignatureOfIPE("C()",IProgramElement.Kind.CONSTRUCTOR);
checkSignatureOfIPE("method()",IProgramElement.Kind.METHOD);
checkSignatureOfIPE("p()",IProgramElement.Kind.POINTCUT);
checkSignatureOfIPE("before(): p..",IProgramElement.Kind.ADVICE,"before()");
checkSignatureOfIPE("MyClass.method()",IProgramElement.Kind.INTER_TYPE_METHOD);
checkSignatureOfIPE("multiMethod(java.lang.String[][])",IProgramElement.Kind.METHOD);
checkSignatureOfIPE("intArray(int[])",IProgramElement.Kind.METHOD);
checkSignatureOfIPE("MyClass.MyClass()",IProgramElement.Kind.INTER_TYPE_CONSTRUCTOR);
}
// if not filling in the model for aspects contained in jar files then
// want to ensure that the relationship map is correct and has nodes
// which can be used in AJDT - ensure no NPE occurs for the end of
// the relationship with aspectpath
public void testAspectPathRelWhenNotFillingInModel_pr141730() {
World.createInjarHierarchy = false;
try {
runTest("ensure aspectpath injar relationships are correct when not filling in model");
// expecting:
// sourceOfRelationship main in MyFoo.java
// relationship advised by
// target MyBar.aj
//
// and
//
// sourceOfRelationship MyBar.aj
// relationship advises
// target main in MyFoo.java
IHierarchy top = AsmManager.getDefault().getHierarchy();
IRelationshipMap asmRelMap = AsmManager.getDefault().getRelationshipMap();
assertEquals("expected two sources of relationships but only found "
+ asmRelMap.getEntries().size(),2,asmRelMap.getEntries().size());
for (Iterator iter = asmRelMap.getEntries().iterator(); iter.hasNext();) {
String sourceOfRelationship = (String) iter.next();
IProgramElement ipe = top.findElementForHandle(sourceOfRelationship);
List relationships = asmRelMap.get(ipe);
if (ipe.getName().equals("MyBar.aj")) {
assertEquals("expected MyBar.aj to have one relationships but found "
+ relationships.size(),1,relationships.size());
Relationship rel = (Relationship)relationships.get(0);
assertEquals("expected relationship to be 'advises' but was "
+ rel.getName(), "advises", rel.getName());
List targets = rel.getTargets();
assertEquals("expected one target but found " + targets.size(),1,targets.size());
IProgramElement link = top.findElementForHandle((String)targets.get(0));
assertEquals("expected target 'method-call(void foo.MyFoo.main())' but target " + link.getName(),
"method-call(void foo.MyFoo.main())",link.getName());
String fileName = link.getSourceLocation().getSourceFile().toString();
assertTrue("expected 'main' to be in class MyFoo.java but found it " +
"in " + fileName,fileName.indexOf("MyFoo.java") != -1);
} else if (ipe.getName().equals("method-call(void foo.MyFoo.main())")) {
String fileName = ipe.getSourceLocation().getSourceFile().toString();
assertTrue("expected 'method-call(void foo.MyFoo.main())' to be in " +
"class MyFoo.java but found it in"
+ fileName,fileName.indexOf("MyFoo.java") != -1);
assertEquals("expected 'method-call(void foo.MyFoo.main())' " +
"to have one relationships but found "
+ relationships.size(),1,relationships.size());
Relationship rel = (Relationship)relationships.get(0);
assertEquals("expected relationship to be 'advised by' but was "
+ rel.getName(), "advised by", rel.getName());
List targets = rel.getTargets();
assertEquals("expected one target but found " + targets.size(),1,targets.size());
IProgramElement link = top.findElementForHandle((String)targets.get(0));
assertEquals("expected target 'MyBar.aj' but target " + link.getName(),
"MyBar.aj",link.getName());
} else {
fail("unexpected element " + ipe.getName() + " in the relationship map");
}
}
} finally {
World.createInjarHierarchy = true;
}
}
// if not filling in the model for classes contained in jar files then
// want to ensure that the relationship map is correct and has nodes
// which can be used in AJDT - ensure no NPE occurs for the end of
// the relationship with inpath
public void testNoNPEWithInpathWhenNotFillingInModel_pr141730() {
World.createInjarHierarchy = false;
try {
runTest("ensure inpath injar relationships are correct when not filling in model");
// the aspect used for this test has advice, declare parents, deow,
// and declare @type, @constructor, @field and @method. We only expect
// there to be relationships in the map for declare parents and declare @type
// (provided the model isn't being filled in) because the logic in the other
// addXXXRelationship methods use AspectJElementHierarchy.findElementForType().
// This method which returns null because there is no such ipe. The relationship is
// therefore not added to the model. Adding declare @type and declare parents
// uses AspectJElementHierarchy.findElementForHandle() which returns the file
// node ipe if it can't find one for the given handle. Therefore the relationships
// are added against the file node. Before change to using ipe's to create handles
// we also had the deow relationship, however, now we don't because this also
// uses findElementForType to find the targetNode which in the inpath case is null.
// just check that the number of entries is what we expect:
// We expect 3 (the declare @type and declare parents statements plus the filenode)
IRelationshipMap relMap = AsmManager.getDefault().getRelationshipMap();
assertEquals("expected 3 entries in the relationship map but found "
+ relMap.getEntries().size(), 3, relMap.getEntries().size());
} finally {
World.createInjarHierarchy = true;
}
}
// public void testFunkyGenericErrorWithITDs_pr126355_2() {
// runTest("bizarre generic error with itds - 2");
// // public class Pair<F,S> affected by pertarget aspect
// GenericsTests.verifyClassSignature(ajc,"Pair","<F:Ljava/lang/Object;S:Ljava/lang/Object;>Ljava/lang/Object;LIdempotentCache$ajcMightHaveAspect;;");
// }
public void testNoAspects(){
// setSystemProperty(WeavingAdaptor.WEAVING_ADAPTOR_VERBOSE,"true");
runTest("Ensure no weaving without included aspects");
}
public void testWeaveinfoMessages (){
runTest("weaveinfo messages with include and exclude");
}
// tests that can't be included for some reason
// Not valid whilst the ajc compiler forces debug on (ignores -g:none) - it will be green but is invalid, trust me
// public void testLongWindedMessages_pr129408() { runTest("long winded ataj messages");}
// ---------------- helper methods ---------------
private void checkParametersForIPE(String ipeLabel, IProgramElement.Kind kind, String expectedParm, boolean getHandles) {
IHierarchy top = AsmManager.getDefault().getHierarchy();
IProgramElement ipe = top.findElementForLabel(top.getRoot(),kind,ipeLabel);
assertNotNull("Couldn't find '" + ipeLabel + "' element in the tree",ipe);
List l = new ArrayList();
if (getHandles) {
l = ipe.getParameterSignatures();
} else {
l = ipe.getParameterTypes();
}
boolean eq = CharOperation.equals(((char[])l.get(0)),expectedParm.toCharArray());
assertTrue("expected parameter to be '" + expectedParm + "' but found '" +
new String(((char[])l.get(0))) + "'",eq);
}
private void checkSignatureOfIPE(String ipeLabel, IProgramElement.Kind kind) {
checkSignatureOfIPE(ipeLabel,kind,ipeLabel);
}
private void checkSignatureOfIPE(String ipeLabel, IProgramElement.Kind kind, String expectedSig) {
IHierarchy top = AsmManager.getDefault().getHierarchy();
IProgramElement ipe = top.findElementForLabel(
top.getRoot(),kind,ipeLabel);
assertNotNull("Couldn't find '" + ipeLabel + "' element in the tree",ipe);
assertEquals("expected signature to be '"+ expectedSig + "' but was " +
ipe.toSignatureString(true),expectedSig,ipe.toSignatureString(true));
}
/////////////////////////////////////////
public static Test suite() {
return XMLBasedAjcTestCase.loadSuite(Ajc152Tests.class);
}
protected File getSpecFile() {
return new File("../tests/src/org/aspectj/systemtest/ajc152/ajc152.xml");
}
}
|
147,801 |
Bug 147801 java.lang.ClassFormatError: Repetitive method name/signature
|
I get a ClassFormatError trying to perform runtime-weaving on a DB2 class. The class being woven is COM.ibm.db2.jdbc.app.DB2PreparedStatement. The full message exception is: java.lang.ClassFormatError: Repetitive method name/signature in class file COM/ibm/db2/jdbc/app/DB2PreparedStatement. In examining the post-weave class file, it looks as if Aspectj is defining a duplicate method within the class called getParameterMetaData(). Here are the messages from the weaver: 04:21:13,640 INFO [STDOUT] info weaving 'COM.ibm.db2.jdbc.app.DB2CallableStatement' 04:21:13,640 INFO [STDOUT] info weaver operating in reweavable mode. Need to verify any required types exist. 04:21:13,671 INFO [STDOUT] info weaving 'COM.ibm.db2.jdbc.app.DB2PreparedStatement' 04:21:13,671 INFO [STDOUT] info weaver operating in reweavable mode. Need to verify any required types exist. 04:21:13,703 INFO [STDOUT] weaveinfo Join point 'method-execution(java.sql.ResultSet COM.ibm.db2.jdbc.app.DB2PreparedStatement.executeQuery())' in Type 'COM.ibm.db2.jdbc.app.DB2PreparedStatement' (DB2PreparedStatement.java:1679) advised by before advice from 'com.ibm.tivoli.itcam.toolkit.ai.aspectj.captureJDBC.CaptureSQLStatement' (CaptureSQLStatement.aj:747) [with runtime test] 04:21:13,703 INFO [STDOUT] weaveinfo Join point 'method-execution(java.sql.ResultSet COM.ibm.db2.jdbc.app.DB2PreparedStatement.executeQuery())' in Type 'COM.ibm.db2.jdbc.app.DB2PreparedStatement' (DB2PreparedStatement.java:1679) advised by afterReturning advice from 'com.ibm.tivoli.itcam.toolkit.ai.aspectj.captureJDBC.CaptureSQLStatement' (CaptureSQLStatement.aj:946) [with runtime test] 04:21:13,718 INFO [STDOUT] weaveinfo Join point 'method-execution(java.sql.ResultSet COM.ibm.db2.jdbc.app.DB2PreparedStatement.executeQuery())' in Type 'COM.ibm.db2.jdbc.app.DB2PreparedStatement' (DB2PreparedStatement.java:1679) advised by afterThrowing advice from 'com.ibm.tivoli.itcam.toolkit.ai.aspectj.captureJDBC.CaptureSQLStatement' (CaptureSQLStatement.aj:971) [with runtime test] 04:21:13,718 INFO [STDOUT] weaveinfo Join point 'method-execution(boolean COM.ibm.db2.jdbc.app.DB2PreparedStatement.execute())' in Type 'COM.ibm.db2.jdbc.app.DB2PreparedStatement' (DB2PreparedStatement.java:3971) advised by before advice from 'com.ibm.tivoli.itcam.toolkit.ai.aspectj.captureJDBC.CaptureSQLStatement' (CaptureSQLStatement.aj:833) [with runtime test] 04:21:13,718 INFO [STDOUT] weaveinfo Join point 'method-execution(boolean COM.ibm.db2.jdbc.app.DB2PreparedStatement.execute())' in Type 'COM.ibm.db2.jdbc.app.DB2PreparedStatement' (DB2PreparedStatement.java:3971) advised by afterReturning advice from 'com.ibm.tivoli.itcam.toolkit.ai.aspectj.captureJDBC.CaptureSQLStatement' (CaptureSQLStatement.aj:946) [with runtime test]
|
resolved fixed
|
13dde4e
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-06-21T11:33:21Z | 2006-06-19T20:46:40Z |
weaver/src/org/aspectj/weaver/World.java
|
/* *******************************************************************
* Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC).
* 2005 Contributors
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the 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, Andy Clement, overhaul for generics
* ******************************************************************/
package org.aspectj.weaver;
import java.lang.ref.ReferenceQueue;
import java.lang.ref.SoftReference;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.WeakHashMap;
import org.aspectj.asm.IHierarchy;
import org.aspectj.bridge.IMessageHandler;
import org.aspectj.bridge.ISourceLocation;
import org.aspectj.bridge.Message;
import org.aspectj.bridge.MessageUtil;
import org.aspectj.bridge.IMessage.Kind;
import org.aspectj.bridge.context.PinpointingMessageHandler;
import org.aspectj.weaver.UnresolvedType.TypeKind;
import org.aspectj.weaver.bcel.BcelObjectType;
import org.aspectj.weaver.patterns.DeclarePrecedence;
import org.aspectj.weaver.patterns.PerClause;
import org.aspectj.weaver.patterns.Pointcut;
import org.aspectj.weaver.reflect.ReflectionBasedReferenceTypeDelegate;
/**
* A World is a collection of known types and crosscutting members.
*/
public abstract class World implements Dump.INode {
/** handler for any messages produced during resolution etc. */
private IMessageHandler messageHandler = IMessageHandler.SYSTEM_ERR;
/** handler for cross-reference information produced during the weaving process */
private ICrossReferenceHandler xrefHandler = null;
/** Currently 'active' scope in which to lookup (resolve) typevariable references */
private TypeVariableDeclaringElement typeVariableLookupScope;
/** The heart of the world, a map from type signatures to resolved types */
protected TypeMap typeMap = new TypeMap(this); // Signature to ResolvedType
// See pr134471 - we would like to set this false but need for handles in the structure model
// to be independent of location before we can do that.
/** Should we take into account source location when comparing mungers - which may trigger full builds */
public final static boolean compareLocations = true;
// see pr145963
/** Should we create the hierarchy for binary classes and aspects*/
public static boolean createInjarHierarchy = true;
/** Calculator for working out aspect precedence */
private AspectPrecedenceCalculator precedenceCalculator;
/** All of the type and shadow mungers known to us */
private CrosscuttingMembersSet crosscuttingMembersSet =
new CrosscuttingMembersSet(this);
/** Model holds ASM relationships */
private IHierarchy model = null;
/** for processing Xlint messages */
private Lint lint = new Lint(this);
/** XnoInline option setting passed down to weaver */
private boolean XnoInline;
/** XlazyTjp option setting passed down to weaver */
private boolean XlazyTjp;
/** XhasMember option setting passed down to weaver */
private boolean XhasMember = false;
/** Xpinpoint controls whether we put out developer info showing the source of messages */
private boolean Xpinpoint = false;
/** When behaving in a Java 5 way autoboxing is considered */
private boolean behaveInJava5Way = false;
/** Determines if this world could be used for multiple compiles */
private boolean incrementalCompileCouldFollow = false;
/** The level of the aspectjrt.jar the code we generate needs to run on */
private String targetAspectjRuntimeLevel = Constants.RUNTIME_LEVEL_DEFAULT;
/** Flags for the new joinpoints that are 'optional' */
private boolean optionalJoinpoint_ArrayConstruction = false; // Command line flag: "-Xjoinpoints:arrayconstruction"
private boolean optionalJoinpoint_Synchronization = false; // Command line flag: "-Xjoinpoints:synchronization"
private boolean addSerialVerUID = false;
private Properties extraConfiguration = null;
private boolean checkedAdvancedConfiguration=false;
private boolean synchronizationPointcutsInUse = false;
// Xset'table options
private boolean fastDelegateSupportEnabled = isASMAround;
private boolean runMinimalMemory = false;
public boolean forDEBUG_structuralChangesCode = false;
// Records whether ASM is around ... so we might use it for delegates
protected static boolean isASMAround;
private long errorThreshold;
private long warningThreshold;
static {
try {
Class c = Class.forName("org.aspectj.org.objectweb.asm.ClassVisitor");
isASMAround = true;
} catch (ClassNotFoundException cnfe) {
isASMAround = false;
}
}
/**
* A list of RuntimeExceptions containing full stack information for every
* type we couldn't find.
*/
private List dumpState_cantFindTypeExceptions = null;
/**
* Play God.
* On the first day, God created the primitive types and put them in the type
* map.
*/
protected World() {
super();
Dump.registerNode(this.getClass(),this);
typeMap.put("B", ResolvedType.BYTE);
typeMap.put("S", ResolvedType.SHORT);
typeMap.put("I", ResolvedType.INT);
typeMap.put("J", ResolvedType.LONG);
typeMap.put("F", ResolvedType.FLOAT);
typeMap.put("D", ResolvedType.DOUBLE);
typeMap.put("C", ResolvedType.CHAR);
typeMap.put("Z", ResolvedType.BOOLEAN);
typeMap.put("V", ResolvedType.VOID);
precedenceCalculator = new AspectPrecedenceCalculator(this);
}
/**
* Dump processing when a fatal error occurs
*/
public void accept (Dump.IVisitor visitor) {
visitor.visitString("Shadow mungers:");
visitor.visitList(crosscuttingMembersSet.getShadowMungers());
visitor.visitString("Type mungers:");
visitor.visitList(crosscuttingMembersSet.getTypeMungers());
visitor.visitString("Late Type mungers:");
visitor.visitList(crosscuttingMembersSet.getLateTypeMungers());
if (dumpState_cantFindTypeExceptions!=null) {
visitor.visitString("Cant find type problems:");
visitor.visitList(dumpState_cantFindTypeExceptions);
dumpState_cantFindTypeExceptions = null;
}
}
// =============================================================================
// T Y P E R E S O L U T I O N
// =============================================================================
/**
* Resolve a type that we require to be present in the world
*/
public ResolvedType resolve(UnresolvedType ty) {
return resolve(ty, false);
}
/**
* Attempt to resolve a type - the source location gives you some context in which
* resolution is taking place. In the case of an error where we can't find the
* type - we can then at least report why (source location) we were trying to resolve it.
*/
public ResolvedType resolve(UnresolvedType ty,ISourceLocation isl) {
ResolvedType ret = resolve(ty,true);
if (ResolvedType.isMissing(ty)) {
//IMessage msg = null;
getLint().cantFindType.signal(WeaverMessages.format(WeaverMessages.CANT_FIND_TYPE,ty.getName()),isl);
//if (isl!=null) {
//msg = MessageUtil.error(WeaverMessages.format(WeaverMessages.CANT_FIND_TYPE,ty.getName()),isl);
//} else {
//msg = MessageUtil.error(WeaverMessages.format(WeaverMessages.CANT_FIND_TYPE,ty.getName()));
//}
//messageHandler.handleMessage(msg);
}
return ret;
}
/**
* Convenience method for resolving an array of unresolved types
* in one hit. Useful for e.g. resolving type parameters in signatures.
*/
public ResolvedType[] resolve(UnresolvedType[] types) {
if (types == null) return new ResolvedType[0];
ResolvedType[] ret = new ResolvedType[types.length];
for (int i=0; i<types.length; i++) {
ret[i] = resolve(types[i]);
}
return ret;
}
/**
* Resolve a type. This the hub of type resolution. The resolved type is added
* to the type map by signature.
*/
public ResolvedType resolve(UnresolvedType ty, boolean allowMissing) {
// special resolution processing for already resolved types.
if (ty instanceof ResolvedType) {
ResolvedType rty = (ResolvedType) ty;
rty = resolve(rty);
return rty;
}
// dispatch back to the type variable reference to resolve its constituent parts
// don't do this for other unresolved types otherwise you'll end up in a loop
if (ty.isTypeVariableReference()) {
return ty.resolve(this);
}
// if we've already got a resolved type for the signature, just return it
// after updating the world
String signature = ty.getSignature();
ResolvedType ret = typeMap.get(signature);
if (ret != null) {
ret.world = this; // Set the world for the RTX
return ret;
} else if ( signature.equals("?") || signature.equals("*")) {
// might be a problem here, not sure '?' should make it to here as a signature, the
// proper signature for wildcard '?' is '*'
// fault in generic wildcard, can't be done earlier because of init issues
ResolvedType something = new BoundedReferenceType("?","Ljava/lang/Object",this);
typeMap.put("?",something);
return something;
}
// no existing resolved type, create one
if (ty.isArray()) {
ResolvedType componentType = resolve(ty.getComponentType(),allowMissing);
//String brackets = signature.substring(0,signature.lastIndexOf("[")+1);
ret = new ResolvedType.Array(signature, "["+componentType.getErasureSignature(),
this,
componentType);
} else {
ret = resolveToReferenceType(ty);
if (!allowMissing && ret.isMissing()) {
ret = handleRequiredMissingTypeDuringResolution(ty);
}
}
// Pulling in the type may have already put the right entry in the map
if (typeMap.get(signature)==null && !ret.isMissing()) {
typeMap.put(signature, ret);
}
return ret;
}
/**
* We tried to resolve a type and couldn't find it...
*/
private ResolvedType handleRequiredMissingTypeDuringResolution(UnresolvedType ty) {
// defer the message until someone asks a question of the type that we can't answer
// just from the signature.
// MessageUtil.error(messageHandler,
// WeaverMessages.format(WeaverMessages.CANT_FIND_TYPE,ty.getName()));
if (dumpState_cantFindTypeExceptions==null) {
dumpState_cantFindTypeExceptions = new ArrayList();
}
dumpState_cantFindTypeExceptions.add(new RuntimeException("Can't find type "+ty.getName()));
return new MissingResolvedTypeWithKnownSignature(ty.getSignature(),this);
}
/**
* Some TypeFactory operations create resolved types directly, but these won't be
* in the typeMap - this resolution process puts them there. Resolved types are
* also told their world which is needed for the special autoboxing resolved types.
*/
public ResolvedType resolve(ResolvedType ty) {
if (ty.isTypeVariableReference()) return ty; // until type variables have proper sigs...
ResolvedType resolved = typeMap.get(ty.getSignature());
if (resolved == null) {
typeMap.put(ty.getSignature(), ty);
resolved = ty;
}
resolved.world = this;
return resolved;
}
/**
* Convenience method for finding a type by name and resolving it in one step.
*/
public ResolvedType resolve(String name) {
return resolve(UnresolvedType.forName(name));
}
public ResolvedType resolve(String name,boolean allowMissing) {
return resolve(UnresolvedType.forName(name),allowMissing);
}
private ResolvedType currentlyResolvingBaseType;
/**
* Resolve to a ReferenceType - simple, raw, parameterized, or generic.
* Raw, parameterized, and generic versions of a type share a delegate.
*/
private final ResolvedType resolveToReferenceType(UnresolvedType ty) {
if (ty.isParameterizedType()) {
// ======= parameterized types ================
ReferenceType genericType = (ReferenceType)resolveGenericTypeFor(ty,false);
currentlyResolvingBaseType = genericType;
ReferenceType parameterizedType =
TypeFactory.createParameterizedType(genericType, ty.typeParameters, this);
currentlyResolvingBaseType = null;
return parameterizedType;
} else if (ty.isGenericType()) {
// ======= generic types ======================
ReferenceType genericType = (ReferenceType)resolveGenericTypeFor(ty,false);
return genericType;
} else if (ty.isGenericWildcard()) {
// ======= generic wildcard types =============
return resolveGenericWildcardFor(ty);
} else {
// ======= simple and raw types ===============
String erasedSignature = ty.getErasureSignature();
ReferenceType simpleOrRawType = new ReferenceType(erasedSignature, this);
if (ty.needsModifiableDelegate()) simpleOrRawType.setNeedsModifiableDelegate(true);
ReferenceTypeDelegate delegate = resolveDelegate(simpleOrRawType);
// 117854
// if (delegate == null) return ResolvedType.MISSING;
if (delegate == null) return new MissingResolvedTypeWithKnownSignature(ty.getSignature(),erasedSignature,this);//ResolvedType.MISSING;
if (delegate.isGeneric() && behaveInJava5Way) {
// ======== raw type ===========
simpleOrRawType.typeKind = TypeKind.RAW;
ReferenceType genericType = makeGenericTypeFrom(delegate,simpleOrRawType);
// name = ReferenceType.fromTypeX(UnresolvedType.forRawTypeNames(ty.getName()),this);
simpleOrRawType.setDelegate(delegate);
genericType.setDelegate(delegate);
simpleOrRawType.setGenericType(genericType);
return simpleOrRawType;
} else {
// ======== simple type =========
simpleOrRawType.setDelegate(delegate);
return simpleOrRawType;
}
}
}
/**
* Attempt to resolve a type that should be a generic type.
*/
public ResolvedType resolveGenericTypeFor(UnresolvedType anUnresolvedType, boolean allowMissing) {
// Look up the raw type by signature
String rawSignature = anUnresolvedType.getRawType().getSignature();
ResolvedType rawType = (ResolvedType) typeMap.get(rawSignature);
if (rawType==null) {
rawType = resolve(UnresolvedType.forSignature(rawSignature),false);
typeMap.put(rawSignature,rawType);
}
// Does the raw type know its generic form? (It will if we created the
// raw type from a source type, it won't if its been created just through
// being referenced, e.g. java.util.List
ResolvedType genericType = rawType.getGenericType();
// There is a special case to consider here (testGenericsBang_pr95993 highlights it)
// You may have an unresolvedType for a parameterized type but it
// is backed by a simple type rather than a generic type. This occurs for
// inner types of generic types that inherit their enclosing types
// type variables.
if (rawType.isSimpleType() && (anUnresolvedType.typeParameters==null || anUnresolvedType.typeParameters.length==0)) {
rawType.world = this;
return rawType;
}
if (genericType != null) {
genericType.world = this;
return genericType;
} else {
// Fault in the generic that underpins the raw type ;)
ReferenceTypeDelegate delegate = resolveDelegate((ReferenceType)rawType);
ReferenceType genericRefType = makeGenericTypeFrom(delegate,((ReferenceType)rawType));
((ReferenceType)rawType).setGenericType(genericRefType);
genericRefType.setDelegate(delegate);
((ReferenceType)rawType).setDelegate(delegate);
return genericRefType;
}
}
private ReferenceType makeGenericTypeFrom(ReferenceTypeDelegate delegate, ReferenceType rawType) {
String genericSig = delegate.getDeclaredGenericSignature();
if (genericSig != null) {
return new ReferenceType(
UnresolvedType.forGenericTypeSignature(rawType.getSignature(),delegate.getDeclaredGenericSignature()),this);
} else {
return new ReferenceType(
UnresolvedType.forGenericTypeVariables(rawType.getSignature(), delegate.getTypeVariables()),this);
}
}
/**
* Go from an unresolved generic wildcard (represented by UnresolvedType) to a resolved version (BoundedReferenceType).
*/
private ReferenceType resolveGenericWildcardFor(UnresolvedType aType) {
BoundedReferenceType ret = null;
// FIXME asc doesnt take account of additional interface bounds (e.g. ? super R & Serializable - can you do that?)
if (aType.isExtends()) {
ReferenceType upperBound = (ReferenceType)resolve(aType.getUpperBound());
ret = new BoundedReferenceType(upperBound,true,this);
} else if (aType.isSuper()) {
ReferenceType lowerBound = (ReferenceType) resolve(aType.getLowerBound());
ret = new BoundedReferenceType(lowerBound,false,this);
} else {
// must be ? on its own!
}
return ret;
}
/**
* Find the ReferenceTypeDelegate behind this reference type so that it can
* fulfill its contract.
*/
protected abstract ReferenceTypeDelegate resolveDelegate(ReferenceType ty);
/**
* Special resolution for "core" types like OBJECT. These are resolved just like
* any other type, but if they are not found it is more serious and we issue an
* error message immediately.
*/
public ResolvedType getCoreType(UnresolvedType tx) {
ResolvedType coreTy = resolve(tx,true);
if (coreTy.isMissing()) {
MessageUtil.error(messageHandler,
WeaverMessages.format(WeaverMessages.CANT_FIND_CORE_TYPE,tx.getName()));
}
return coreTy;
}
/**
* Lookup a type by signature, if not found then build one and put it in the
* map.
*/
public ReferenceType lookupOrCreateName(UnresolvedType ty) {
String signature = ty.getSignature();
ReferenceType ret = lookupBySignature(signature);
if (ret == null) {
ret = ReferenceType.fromTypeX(ty, this);
typeMap.put(signature, ret);
}
return ret;
}
/**
* Lookup a reference type in the world by its signature. Returns
* null if not found.
*/
public ReferenceType lookupBySignature(String signature) {
return (ReferenceType) typeMap.get(signature);
}
// =============================================================================
// T Y P E R E S O L U T I O N -- E N D
// =============================================================================
/**
* Member resolution is achieved by resolving the declaring type and then
* looking up the member in the resolved declaring type.
*/
public ResolvedMember resolve(Member member) {
ResolvedType declaring = member.getDeclaringType().resolve(this);
if (declaring.isRawType()) declaring = declaring.getGenericType();
ResolvedMember ret;
if (member.getKind() == Member.FIELD) {
ret = declaring.lookupField(member);
} else {
ret = declaring.lookupMethod(member);
}
if (ret != null) return ret;
return declaring.lookupSyntheticMember(member);
}
// Methods for creating various cross-cutting members...
// ===========================================================
/**
* Create an advice shadow munger from the given advice attribute
*/
public abstract Advice createAdviceMunger(
AjAttribute.AdviceAttribute attribute,
Pointcut pointcut,
Member signature);
/**
* Create an advice shadow munger for the given advice kind
*/
public final Advice createAdviceMunger(
AdviceKind kind,
Pointcut p,
Member signature,
int extraParameterFlags,
IHasSourceLocation loc)
{
AjAttribute.AdviceAttribute attribute =
new AjAttribute.AdviceAttribute(kind, p, extraParameterFlags, loc.getStart(), loc.getEnd(), loc.getSourceContext());
return createAdviceMunger(attribute, p, signature);
}
public abstract ConcreteTypeMunger makeCflowStackFieldAdder(ResolvedMember cflowField);
public abstract ConcreteTypeMunger makeCflowCounterFieldAdder(ResolvedMember cflowField);
/**
* Register a munger for perclause @AJ aspect so that we add aspectOf(..) to them as needed
* @see org.aspectj.weaver.bcel.BcelWorld#makePerClauseAspect(ResolvedType, org.aspectj.weaver.patterns.PerClause.Kind)
*/
public abstract ConcreteTypeMunger makePerClauseAspect(ResolvedType aspect, PerClause.Kind kind);
public abstract ConcreteTypeMunger concreteTypeMunger(ResolvedTypeMunger munger, ResolvedType aspectType);
/**
* Same signature as org.aspectj.util.PartialOrder.PartialComparable.compareTo
*/
public int compareByPrecedence(ResolvedType aspect1, ResolvedType aspect2) {
return precedenceCalculator.compareByPrecedence(aspect1, aspect2);
}
public Integer getPrecedenceIfAny(ResolvedType aspect1, ResolvedType aspect2) {
return precedenceCalculator.getPrecedenceIfAny(aspect1, aspect2);
}
/**
* compares by precedence with the additional rule that a super-aspect is
* sorted before its sub-aspects
*/
public int compareByPrecedenceAndHierarchy(ResolvedType aspect1, ResolvedType aspect2) {
return precedenceCalculator.compareByPrecedenceAndHierarchy(aspect1, aspect2);
}
// simple property getter and setters
// ===========================================================
/**
* Nobody should hold onto a copy of this message handler, or setMessageHandler won't
* work right.
*/
public IMessageHandler getMessageHandler() {
return messageHandler;
}
public void setMessageHandler(IMessageHandler messageHandler) {
if (this.isInPinpointMode()) {
this.messageHandler = new PinpointingMessageHandler(messageHandler);
} else {
this.messageHandler = messageHandler;
}
}
/**
* convenenience method for creating and issuing messages via the message handler -
* if you supply two locations you will get two messages.
*/
public void showMessage(
Kind kind,
String message,
ISourceLocation loc1,
ISourceLocation loc2)
{
if (loc1 != null) {
messageHandler.handleMessage(new Message(message, kind, null, loc1));
if (loc2 != null) {
messageHandler.handleMessage(new Message(message, kind, null, loc2));
}
} else {
messageHandler.handleMessage(new Message(message, kind, null, loc2));
}
}
public void setCrossReferenceHandler(ICrossReferenceHandler xrefHandler) {
this.xrefHandler = xrefHandler;
}
/**
* Get the cross-reference handler for the world, may be null.
*/
public ICrossReferenceHandler getCrossReferenceHandler() {
return this.xrefHandler;
}
public void setTypeVariableLookupScope(TypeVariableDeclaringElement scope) {
this.typeVariableLookupScope = scope;
}
public TypeVariableDeclaringElement getTypeVariableLookupScope() {
return typeVariableLookupScope;
}
public List getDeclareParents() {
return crosscuttingMembersSet.getDeclareParents();
}
public List getDeclareAnnotationOnTypes() {
return crosscuttingMembersSet.getDeclareAnnotationOnTypes();
}
public List getDeclareAnnotationOnFields() {
return crosscuttingMembersSet.getDeclareAnnotationOnFields();
}
public List getDeclareAnnotationOnMethods() {
return crosscuttingMembersSet.getDeclareAnnotationOnMethods();
}
public List getDeclareSoft() {
return crosscuttingMembersSet.getDeclareSofts();
}
public CrosscuttingMembersSet getCrosscuttingMembersSet() {
return crosscuttingMembersSet;
}
public IHierarchy getModel() {
return model;
}
public void setModel(IHierarchy model) {
this.model = model;
}
public Lint getLint() {
return lint;
}
public void setLint(Lint lint) {
this.lint = lint;
}
public boolean isXnoInline() {
return XnoInline;
}
public void setXnoInline(boolean xnoInline) {
XnoInline = xnoInline;
}
public boolean isXlazyTjp() {
return XlazyTjp;
}
public void setXlazyTjp(boolean b) {
XlazyTjp = b;
}
public boolean isHasMemberSupportEnabled() {
return XhasMember;
}
public void setXHasMemberSupportEnabled(boolean b) {
XhasMember = b;
}
public boolean isInPinpointMode() {
return Xpinpoint;
}
public void setPinpointMode(boolean b) {
this.Xpinpoint = b;
}
public void setBehaveInJava5Way(boolean b) {
behaveInJava5Way = b;
}
/**
* Set the error and warning threashold which can be taken from
* CompilerOptions (see bug 129282)
*
* @param errorThreshold
* @param warningThreshold
*/
public void setErrorAndWarningThreshold(long errorThreshold, long warningThreshold) {
this.errorThreshold = errorThreshold;
this.warningThreshold = warningThreshold;
}
/**
* @return true if ignoring the UnusedDeclaredThrownException and false if
* this compiler option is set to error or warning
*/
public boolean isIgnoringUnusedDeclaredThrownException() {
// the 0x800000 is CompilerOptions.UnusedDeclaredThrownException
// which is ASTNode.bit24
if((this.errorThreshold & 0x800000) != 0
|| (this.warningThreshold & 0x800000) != 0)
return false;
return true;
}
public void performExtraConfiguration(String config) {
if (config==null) return;
// Bunch of name value pairs to split
extraConfiguration = new Properties();
int pos =-1;
while ((pos=config.indexOf(","))!=-1) {
String nvpair = config.substring(0,pos);
int pos2 = nvpair.indexOf("=");
if (pos2!=-1) {
String n = nvpair.substring(0,pos2);
String v = nvpair.substring(pos2+1);
extraConfiguration.setProperty(n,v);
}
config = config.substring(pos+1);
}
if (config.length()>0) {
int pos2 = config.indexOf("=");
if (pos2!=-1) {
String n = config.substring(0,pos2);
String v = config.substring(pos2+1);
extraConfiguration.setProperty(n,v);
}
}
}
/**
* may return null
*/
public Properties getExtraConfiguration() {
return extraConfiguration;
}
public final static String xsetCAPTURE_ALL_CONTEXT = "captureAllContext"; // default false
public final static String xsetACTIVATE_LIGHTWEIGHT_DELEGATES = "activateLightweightDelegates"; // default true
public final static String xsetRUN_MINIMAL_MEMORY ="runMinimalMemory"; // default true
public final static String xsetDEBUG_STRUCTURAL_CHANGES_CODE = "debugStructuralChangesCode"; // default false
public boolean isInJava5Mode() {
return behaveInJava5Way;
}
public void setTargetAspectjRuntimeLevel(String s) {
targetAspectjRuntimeLevel = s;
}
public void setOptionalJoinpoints(String jps) {
if (jps==null) return;
if (jps.indexOf("arrayconstruction")!=-1) optionalJoinpoint_ArrayConstruction = true;
if (jps.indexOf("synchronization")!=-1) optionalJoinpoint_Synchronization = true;
}
public boolean isJoinpointArrayConstructionEnabled() {
return optionalJoinpoint_ArrayConstruction;
}
public boolean isJoinpointSynchronizationEnabled() {
return optionalJoinpoint_Synchronization;
}
public String getTargetAspectjRuntimeLevel() {
return targetAspectjRuntimeLevel;
}
public boolean isTargettingAspectJRuntime12() {
boolean b = false; // pr116679
if (!isInJava5Mode()) b=true;
else b = getTargetAspectjRuntimeLevel().equals(org.aspectj.weaver.Constants.RUNTIME_LEVEL_12);
//System.err.println("Asked if targetting runtime 1.2 , returning: "+b);
return b;
}
/*
* Map of types in the world, can have 'references' to expendable ones which
* can be garbage collected to recover memory.
* An expendable type is a reference type that is not exposed to the weaver (ie
* just pulled in for type resolution purposes).
*/
protected static class TypeMap {
private static boolean debug = false;
// Strategy for entries in the expendable map
public static int DONT_USE_REFS = 0; // Hang around forever
public static int USE_WEAK_REFS = 1; // Collected asap
public static int USE_SOFT_REFS = 2; // Collected when short on memory
// SECRETAPI - Can switch to a policy of choice ;)
public static int policy = USE_SOFT_REFS;
// Map of types that never get thrown away
private Map /* String -> ResolvedType */ tMap = new HashMap();
// Map of types that may be ejected from the cache if we need space
private Map expendableMap = new WeakHashMap();
private World w;
// profiling tools...
private boolean memoryProfiling = false;
private int maxExpendableMapSize = -1;
private int collectedTypes = 0;
private ReferenceQueue rq = new ReferenceQueue();
TypeMap(World w) {
this.w = w;
memoryProfiling = false;// !w.getMessageHandler().isIgnoring(Message.INFO);
}
/**
* Add a new type into the map, the key is the type signature.
* Some types do *not* go in the map, these are ones involving
* *member* type variables. The reason is that when all you have is the
* signature which gives you a type variable name, you cannot
* guarantee you are using the type variable in the same way
* as someone previously working with a similarly
* named type variable. So, these do not go into the map:
* - TypeVariableReferenceType.
* - ParameterizedType where a member type variable is involved.
* - BoundedReferenceType when one of the bounds is a type variable.
*
* definition: "member type variables" - a tvar declared on a generic
* method/ctor as opposed to those you see declared on a generic type.
*/
public ResolvedType put(String key, ResolvedType type) {
if (type.isParameterizedType() && type.isParameterizedWithAMemberTypeVariable()) {
if (debug)
System.err.println("Not putting a parameterized type that utilises member declared type variables into the typemap: key="+key+" type="+type);
return type;
}
if (type.isTypeVariableReference()) {
if (debug)
System.err.println("Not putting a type variable reference type into the typemap: key="+key+" type="+type);
return type;
}
// this test should be improved - only avoid putting them in if one of the
// bounds is a member type variable
if (type instanceof BoundedReferenceType) {
if (debug)
System.err.println("Not putting a bounded reference type into the typemap: key="+key+" type="+type);
return type;
}
if (type instanceof MissingResolvedTypeWithKnownSignature) {
if (debug)
System.err.println("Not putting a missing type into the typemap: key="+key+" type="+type);
return type;
}
if ((type instanceof ReferenceType) && (((ReferenceType)type).getDelegate()==null) && w.isExpendable(type)) {
if (debug)
System.err.println("Not putting expendable ref type with null delegate into typemap: key="+key+" type="+type);
return type;
}
if (w.isExpendable(type)) {
// Dont use reference queue for tracking if not profiling...
if (policy==USE_WEAK_REFS) {
if (memoryProfiling) expendableMap.put(key,new WeakReference(type,rq));
else expendableMap.put(key,new WeakReference(type));
} else if (policy==USE_SOFT_REFS) {
if (memoryProfiling) expendableMap.put(key,new SoftReference(type,rq));
else expendableMap.put(key,new SoftReference(type));
} else {
expendableMap.put(key,type);
}
if (memoryProfiling && expendableMap.size()>maxExpendableMapSize) {
maxExpendableMapSize = expendableMap.size();
}
return type;
} else {
return (ResolvedType) tMap.put(key,type);
}
}
public void report() {
if (!memoryProfiling) return;
checkq();
w.getMessageHandler().handleMessage(MessageUtil.info("MEMORY: world expendable type map reached maximum size of #"+maxExpendableMapSize+" entries"));
w.getMessageHandler().handleMessage(MessageUtil.info("MEMORY: types collected through garbage collection #"+collectedTypes+" entries"));
}
public void checkq() {
if (!memoryProfiling) return;
while (rq.poll()!=null) collectedTypes++;
}
/**
* Lookup a type by its signature, always look
* in the real map before the expendable map
*/
public ResolvedType get(String key) {
checkq();
ResolvedType ret = (ResolvedType) tMap.get(key);
if (ret == null) {
if (policy==USE_WEAK_REFS) {
WeakReference ref = (WeakReference)expendableMap.get(key);
if (ref != null) {
ret = (ResolvedType) ref.get();
}
} else if (policy==USE_SOFT_REFS) {
SoftReference ref = (SoftReference)expendableMap.get(key);
if (ref != null) {
ret = (ResolvedType) ref.get();
}
} else {
return (ResolvedType)expendableMap.get(key);
}
}
return ret;
}
/** Remove a type from the map */
public ResolvedType remove(String key) {
ResolvedType ret = (ResolvedType) tMap.remove(key);
if (ret == null) {
if (policy==USE_WEAK_REFS) {
WeakReference wref = (WeakReference)expendableMap.remove(key);
if (wref!=null) ret = (ResolvedType)wref.get();
} else if (policy==USE_SOFT_REFS) {
SoftReference wref = (SoftReference)expendableMap.remove(key);
if (wref!=null) ret = (ResolvedType)wref.get();
} else {
ret = (ResolvedType)expendableMap.remove(key);
}
}
return ret;
}
public String toString() {
StringBuffer sb = new StringBuffer();
sb.append("types:\n");
sb.append(dumpthem(tMap));
sb.append("expendables:\n");
sb.append(dumpthem(expendableMap));
return sb.toString();
}
private String dumpthem(Map m) {
StringBuffer sb = new StringBuffer();
int otherTypes = 0;
int bcelDel = 0;
int refDel = 0;
for (Iterator iter = m.entrySet().iterator(); iter.hasNext();) {
Map.Entry entry = (Map.Entry) iter.next();
Object val = entry.getValue();
if (val instanceof WeakReference) {
val = ((WeakReference)val).get();
} else
if (val instanceof SoftReference) {
val = ((SoftReference)val).get();
}
sb.append(entry.getKey()+"="+val).append("\n");
if (val instanceof ReferenceType) {
ReferenceType refType = (ReferenceType)val;
if (refType.getDelegate() instanceof BcelObjectType) {
bcelDel++;
} else if (refType.getDelegate() instanceof ReflectionBasedReferenceTypeDelegate) {
refDel++;
} else {
otherTypes++;
}
} else {
otherTypes++;
}
}
sb.append("# BCEL = "+bcelDel+", # REF = "+refDel+", # Other = "+otherTypes);
return sb.toString();
}
public int totalSize() {
return tMap.size()+expendableMap.size();
}
public int hardSize() {
return tMap.size();
}
}
/** Reference types we don't intend to weave may be ejected from
* the cache if we need the space.
*/
protected boolean isExpendable(ResolvedType type) {
return (
!type.equals(UnresolvedType.OBJECT) &&
(type != null) &&
(!type.isExposedToWeaver()) &&
(!type.isPrimitiveType())
);
}
/**
* This class is used to compute and store precedence relationships between
* aspects.
*/
private static class AspectPrecedenceCalculator {
private World world;
private Map cachedResults;
public AspectPrecedenceCalculator(World forSomeWorld) {
this.world = forSomeWorld;
this.cachedResults = new HashMap();
}
/**
* Ask every declare precedence in the world to order the two aspects.
* If more than one declare precedence gives an ordering, and the orderings
* conflict, then that's an error.
*/
public int compareByPrecedence(ResolvedType firstAspect, ResolvedType secondAspect) {
PrecedenceCacheKey key = new PrecedenceCacheKey(firstAspect,secondAspect);
if (cachedResults.containsKey(key)) {
return ((Integer) cachedResults.get(key)).intValue();
} else {
int order = 0;
DeclarePrecedence orderer = null; // Records the declare precedence statement that gives the first ordering
for (Iterator i = world.getCrosscuttingMembersSet().getDeclareDominates().iterator(); i.hasNext(); ) {
DeclarePrecedence d = (DeclarePrecedence)i.next();
int thisOrder = d.compare(firstAspect, secondAspect);
if (thisOrder != 0) {
if (orderer==null) orderer = d;
if (order != 0 && order != thisOrder) {
ISourceLocation[] isls = new ISourceLocation[2];
isls[0]=orderer.getSourceLocation();
isls[1]=d.getSourceLocation();
Message m =
new Message("conflicting declare precedence orderings for aspects: "+
firstAspect.getName()+" and "+secondAspect.getName(),null,true,isls);
world.getMessageHandler().handleMessage(m);
} else {
order = thisOrder;
}
}
}
cachedResults.put(key, new Integer(order));
return order;
}
}
public Integer getPrecedenceIfAny(ResolvedType aspect1,ResolvedType aspect2) {
return (Integer)cachedResults.get(new PrecedenceCacheKey(aspect1,aspect2));
}
public int compareByPrecedenceAndHierarchy(ResolvedType firstAspect, ResolvedType secondAspect) {
if (firstAspect.equals(secondAspect)) return 0;
int ret = compareByPrecedence(firstAspect, secondAspect);
if (ret != 0) return ret;
if (firstAspect.isAssignableFrom(secondAspect)) return -1;
else if (secondAspect.isAssignableFrom(firstAspect)) return +1;
return 0;
}
private static class PrecedenceCacheKey {
public ResolvedType aspect1;
public ResolvedType aspect2;
public PrecedenceCacheKey(ResolvedType a1, ResolvedType a2) {
this.aspect1 = a1;
this.aspect2 = a2;
}
public boolean equals(Object obj) {
if (!(obj instanceof PrecedenceCacheKey)) return false;
PrecedenceCacheKey other = (PrecedenceCacheKey) obj;
return (aspect1 == other.aspect1 && aspect2 == other.aspect2);
}
public int hashCode() {
return aspect1.hashCode() + aspect2.hashCode();
}
}
}
public void validateType(UnresolvedType type) { }
// --- with java5 we can get into a recursive mess if we aren't careful when resolving types (*cough* java.lang.Enum) ---
// --- this first map is for java15 delegates which may try and recursively access the same type variables.
// --- I would rather stash this against a reference type - but we don't guarantee referencetypes are unique for
// so we can't :(
private Map workInProgress1 = new HashMap();
public TypeVariable[] getTypeVariablesCurrentlyBeingProcessed(Class baseClass) {
return (TypeVariable[])workInProgress1.get(baseClass);
}
public void recordTypeVariablesCurrentlyBeingProcessed(Class baseClass, TypeVariable[] typeVariables) {
workInProgress1.put(baseClass,typeVariables);
}
public void forgetTypeVariablesCurrentlyBeingProcessed(Class baseClass) {
workInProgress1.remove(baseClass);
}
public void setAddSerialVerUID(boolean b) { addSerialVerUID=b;}
public boolean isAddSerialVerUID() { return addSerialVerUID;}
public void flush() {
typeMap.expendableMap.clear();
}
public void ensureAdvancedConfigurationProcessed() {
// Check *once* whether the user has switched asm support off
if (!checkedAdvancedConfiguration) {
Properties p = getExtraConfiguration();
if (p!=null) {
if (isASMAround) { // dont bother if its not...
String s = p.getProperty(xsetACTIVATE_LIGHTWEIGHT_DELEGATES,"true");
fastDelegateSupportEnabled = s.equalsIgnoreCase("true");
if (!fastDelegateSupportEnabled)
getMessageHandler().handleMessage(MessageUtil.info("[activateLightweightDelegates=false] Disabling optimization to use lightweight delegates for non-woven types"));
}
String s = p.getProperty(xsetRUN_MINIMAL_MEMORY,"false");
runMinimalMemory = s.equalsIgnoreCase("true");
// if (runMinimalMemory)
// getMessageHandler().handleMessage(MessageUtil.info("[runMinimalMemory=true] Optimizing bcel processing (and cost of performance) to use less memory"));
s = p.getProperty(xsetDEBUG_STRUCTURAL_CHANGES_CODE,"false");
forDEBUG_structuralChangesCode = s.equalsIgnoreCase("true");
}
checkedAdvancedConfiguration=true;
}
}
public boolean isRunMinimalMemory() {
ensureAdvancedConfigurationProcessed();
return runMinimalMemory;
}
public void setFastDelegateSupport(boolean b) {
if (b && !isASMAround) {
throw new BCException("Unable to activate fast delegate support, ASM classes cannot be found");
}
fastDelegateSupportEnabled = b;
}
public boolean isFastDelegateSupportEnabled() {
ensureAdvancedConfigurationProcessed();
return fastDelegateSupportEnabled;
}
public void setIncrementalCompileCouldFollow(boolean b) {incrementalCompileCouldFollow = b;}
public boolean couldIncrementalCompileFollow() {return incrementalCompileCouldFollow;}
public void setSynchronizationPointcutsInUse() {synchronizationPointcutsInUse =true;}
public boolean areSynchronizationPointcutsInUse() {return synchronizationPointcutsInUse;}
}
|
147,801 |
Bug 147801 java.lang.ClassFormatError: Repetitive method name/signature
|
I get a ClassFormatError trying to perform runtime-weaving on a DB2 class. The class being woven is COM.ibm.db2.jdbc.app.DB2PreparedStatement. The full message exception is: java.lang.ClassFormatError: Repetitive method name/signature in class file COM/ibm/db2/jdbc/app/DB2PreparedStatement. In examining the post-weave class file, it looks as if Aspectj is defining a duplicate method within the class called getParameterMetaData(). Here are the messages from the weaver: 04:21:13,640 INFO [STDOUT] info weaving 'COM.ibm.db2.jdbc.app.DB2CallableStatement' 04:21:13,640 INFO [STDOUT] info weaver operating in reweavable mode. Need to verify any required types exist. 04:21:13,671 INFO [STDOUT] info weaving 'COM.ibm.db2.jdbc.app.DB2PreparedStatement' 04:21:13,671 INFO [STDOUT] info weaver operating in reweavable mode. Need to verify any required types exist. 04:21:13,703 INFO [STDOUT] weaveinfo Join point 'method-execution(java.sql.ResultSet COM.ibm.db2.jdbc.app.DB2PreparedStatement.executeQuery())' in Type 'COM.ibm.db2.jdbc.app.DB2PreparedStatement' (DB2PreparedStatement.java:1679) advised by before advice from 'com.ibm.tivoli.itcam.toolkit.ai.aspectj.captureJDBC.CaptureSQLStatement' (CaptureSQLStatement.aj:747) [with runtime test] 04:21:13,703 INFO [STDOUT] weaveinfo Join point 'method-execution(java.sql.ResultSet COM.ibm.db2.jdbc.app.DB2PreparedStatement.executeQuery())' in Type 'COM.ibm.db2.jdbc.app.DB2PreparedStatement' (DB2PreparedStatement.java:1679) advised by afterReturning advice from 'com.ibm.tivoli.itcam.toolkit.ai.aspectj.captureJDBC.CaptureSQLStatement' (CaptureSQLStatement.aj:946) [with runtime test] 04:21:13,718 INFO [STDOUT] weaveinfo Join point 'method-execution(java.sql.ResultSet COM.ibm.db2.jdbc.app.DB2PreparedStatement.executeQuery())' in Type 'COM.ibm.db2.jdbc.app.DB2PreparedStatement' (DB2PreparedStatement.java:1679) advised by afterThrowing advice from 'com.ibm.tivoli.itcam.toolkit.ai.aspectj.captureJDBC.CaptureSQLStatement' (CaptureSQLStatement.aj:971) [with runtime test] 04:21:13,718 INFO [STDOUT] weaveinfo Join point 'method-execution(boolean COM.ibm.db2.jdbc.app.DB2PreparedStatement.execute())' in Type 'COM.ibm.db2.jdbc.app.DB2PreparedStatement' (DB2PreparedStatement.java:3971) advised by before advice from 'com.ibm.tivoli.itcam.toolkit.ai.aspectj.captureJDBC.CaptureSQLStatement' (CaptureSQLStatement.aj:833) [with runtime test] 04:21:13,718 INFO [STDOUT] weaveinfo Join point 'method-execution(boolean COM.ibm.db2.jdbc.app.DB2PreparedStatement.execute())' in Type 'COM.ibm.db2.jdbc.app.DB2PreparedStatement' (DB2PreparedStatement.java:3971) advised by afterReturning advice from 'com.ibm.tivoli.itcam.toolkit.ai.aspectj.captureJDBC.CaptureSQLStatement' (CaptureSQLStatement.aj:946) [with runtime test]
|
resolved fixed
|
13dde4e
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-06-21T11:33:21Z | 2006-06-19T20:46: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.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.Field;
import org.aspectj.apache.bcel.classfile.Method;
import org.aspectj.apache.bcel.classfile.annotation.Annotation;
import org.aspectj.apache.bcel.generic.ANEWARRAY;
import org.aspectj.apache.bcel.generic.BranchInstruction;
import org.aspectj.apache.bcel.generic.CPInstruction;
import org.aspectj.apache.bcel.generic.ConstantPoolGen;
import org.aspectj.apache.bcel.generic.FieldGen;
import org.aspectj.apache.bcel.generic.FieldInstruction;
import org.aspectj.apache.bcel.generic.GOTO;
import org.aspectj.apache.bcel.generic.GOTO_W;
import org.aspectj.apache.bcel.generic.INVOKESPECIAL;
import org.aspectj.apache.bcel.generic.IndexedInstruction;
import org.aspectj.apache.bcel.generic.Instruction;
import org.aspectj.apache.bcel.generic.InstructionConstants;
import org.aspectj.apache.bcel.generic.InstructionFactory;
import org.aspectj.apache.bcel.generic.InstructionHandle;
import org.aspectj.apache.bcel.generic.InstructionList;
import org.aspectj.apache.bcel.generic.InstructionTargeter;
import org.aspectj.apache.bcel.generic.InvokeInstruction;
import org.aspectj.apache.bcel.generic.LineNumberTag;
import org.aspectj.apache.bcel.generic.LocalVariableInstruction;
import org.aspectj.apache.bcel.generic.LocalVariableTag;
import org.aspectj.apache.bcel.generic.MONITORENTER;
import org.aspectj.apache.bcel.generic.MONITOREXIT;
import org.aspectj.apache.bcel.generic.MULTIANEWARRAY;
import org.aspectj.apache.bcel.generic.MethodGen;
import org.aspectj.apache.bcel.generic.NEW;
import org.aspectj.apache.bcel.generic.NEWARRAY;
import org.aspectj.apache.bcel.generic.ObjectType;
import org.aspectj.apache.bcel.generic.PUTFIELD;
import org.aspectj.apache.bcel.generic.PUTSTATIC;
import org.aspectj.apache.bcel.generic.RET;
import org.aspectj.apache.bcel.generic.ReturnInstruction;
import org.aspectj.apache.bcel.generic.Select;
import org.aspectj.apache.bcel.generic.Tag;
import org.aspectj.apache.bcel.generic.Type;
import org.aspectj.apache.bcel.generic.annotation.AnnotationGen;
import org.aspectj.bridge.IMessage;
import org.aspectj.bridge.ISourceLocation;
import org.aspectj.bridge.Message;
import org.aspectj.bridge.MessageUtil;
import org.aspectj.bridge.WeaveMessage;
import org.aspectj.bridge.context.CompilationAndWeavingContext;
import org.aspectj.bridge.context.ContextToken;
import org.aspectj.util.PartialOrder;
import org.aspectj.weaver.AjAttribute;
import org.aspectj.weaver.AjcMemberMaker;
import org.aspectj.weaver.AsmRelationshipProvider;
import org.aspectj.weaver.BCException;
import org.aspectj.weaver.ConcreteTypeMunger;
import org.aspectj.weaver.IClassWeaver;
import org.aspectj.weaver.IntMap;
import org.aspectj.weaver.Member;
import org.aspectj.weaver.MissingResolvedTypeWithKnownSignature;
import org.aspectj.weaver.NameMangler;
import org.aspectj.weaver.NewConstructorTypeMunger;
import org.aspectj.weaver.NewFieldTypeMunger;
import org.aspectj.weaver.NewMethodTypeMunger;
import org.aspectj.weaver.ResolvedMember;
import org.aspectj.weaver.ResolvedMemberImpl;
import org.aspectj.weaver.ResolvedType;
import org.aspectj.weaver.ResolvedTypeMunger;
import org.aspectj.weaver.Shadow;
import org.aspectj.weaver.ShadowMunger;
import org.aspectj.weaver.UnresolvedType;
import org.aspectj.weaver.WeaverMessages;
import org.aspectj.weaver.WeaverMetrics;
import org.aspectj.weaver.WeaverStateInfo;
import org.aspectj.weaver.World;
import org.aspectj.weaver.patterns.DeclareAnnotation;
import org.aspectj.weaver.patterns.ExactTypePattern;
class BcelClassWeaver implements IClassWeaver {
/**
* This is called from {@link BcelWeaver} to perform the per-class weaving process.
*/
public static boolean weave(
BcelWorld world,
LazyClassGen clazz,
List shadowMungers,
List typeMungers,
List lateTypeMungers)
{
boolean b = new BcelClassWeaver(world, clazz, shadowMungers, typeMungers, lateTypeMungers).weave();
//System.out.println(clazz.getClassName() + ", " + clazz.getType().getWeaverState());
//clazz.print();
return b;
}
// --------------------------------------------
private final LazyClassGen clazz;
private final List shadowMungers;
private final List typeMungers;
private final List lateTypeMungers;
private final BcelObjectType ty; // alias of clazz.getType()
private final BcelWorld world; // alias of ty.getWorld()
private final ConstantPoolGen cpg; // alias of clazz.getConstantPoolGen()
private final InstructionFactory fact; // alias of clazz.getFactory();
private final List addedLazyMethodGens = new ArrayList();
private final Set addedDispatchTargets = new HashSet();
// Static setting across BcelClassWeavers
private static boolean inReweavableMode = false;
private List addedSuperInitializersAsList = null; // List<IfaceInitList>
private final Map addedSuperInitializers = new HashMap(); // Interface -> IfaceInitList
private List addedThisInitializers = new ArrayList(); // List<NewFieldMunger>
private List addedClassInitializers = new ArrayList(); // List<NewFieldMunger>
private Map mapToAnnotations = new HashMap();
private BcelShadow clinitShadow = null;
/**
* This holds the initialization and pre-initialization shadows for this class
* that were actually matched by mungers (if no match, then we don't even create the
* shadows really).
*/
private final List initializationShadows = new ArrayList(1);
private BcelClassWeaver(
BcelWorld world,
LazyClassGen clazz,
List shadowMungers,
List typeMungers,
List lateTypeMungers)
{
super();
// assert world == clazz.getType().getWorld()
this.world = world;
this.clazz = clazz;
this.shadowMungers = shadowMungers;
this.typeMungers = typeMungers;
this.lateTypeMungers = lateTypeMungers;
this.ty = clazz.getBcelObjectType();
this.cpg = clazz.getConstantPoolGen();
this.fact = clazz.getFactory();
fastMatchShadowMungers(shadowMungers);
initializeSuperInitializerMap(ty.getResolvedTypeX());
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 List[] perKindShadowMungers;
private boolean canMatchBodyShadows = false;
private boolean canMatchInitialization = false;
private void fastMatchShadowMungers(List shadowMungers) {
// beware the annoying property that SHADOW_KINDS[i].getKey == (i+1) !
perKindShadowMungers = new List[Shadow.MAX_SHADOW_KIND + 1];
for (int i = 0; i < perKindShadowMungers.length; i++) {
perKindShadowMungers[i] = new ArrayList(0);
}
for (Iterator iter = shadowMungers.iterator(); iter.hasNext();) {
ShadowMunger munger = (ShadowMunger) iter.next();
int couldMatchKinds = munger.getPointcut().couldMatchKinds();
for (int i = 0; i < Shadow.SHADOW_KINDS.length; i++) {
Shadow.Kind kind = Shadow.SHADOW_KINDS[i];
if (kind.isSet(couldMatchKinds)) perKindShadowMungers[kind.getKey()].add(munger);
}
// Set couldMatchKinds = munger.getPointcut().couldMatchKinds();
// for (Iterator kindIterator = couldMatchKinds.iterator();
// kindIterator.hasNext();) {
// Shadow.Kind aKind = (Shadow.Kind) kindIterator.next();
// perKindShadowMungers[aKind.getKey()].add(munger);
// }
}
if (!perKindShadowMungers[Shadow.Initialization.getKey()].isEmpty())
canMatchInitialization = true;
for (int i = 0; i < Shadow.SHADOW_KINDS.length; i++) {
Shadow.Kind kind = Shadow.SHADOW_KINDS[i];
if (!kind.isEnclosingKind() && !perKindShadowMungers[i+1].isEmpty()) {
canMatchBodyShadows = true;
}
if (perKindShadowMungers[i+1].isEmpty()) {
perKindShadowMungers[i+1] = null;
}
}
}
private boolean canMatch(Shadow.Kind kind) {
return perKindShadowMungers[kind.getKey()] != null;
}
// private void fastMatchShadowMungers(List shadowMungers, ArrayList mungers, Kind kind) {
// FastMatchInfo info = new FastMatchInfo(clazz.getType(), kind);
// for (Iterator i = shadowMungers.iterator(); i.hasNext();) {
// ShadowMunger munger = (ShadowMunger) i.next();
// FuzzyBoolean fb = munger.getPointcut().fastMatch(info);
// WeaverMetrics.recordFastMatchResult(fb);// Could pass: munger.getPointcut().toString()
// if (fb.maybeTrue()) mungers.add(munger);
// }
// }
private void initializeSuperInitializerMap(ResolvedType child) {
ResolvedType[] superInterfaces = child.getDeclaredInterfaces();
for (int i=0, len=superInterfaces.length; i < len; i++) {
if (ty.getResolvedTypeX().isTopmostImplementor(superInterfaces[i])) {
if (addSuperInitializer(superInterfaces[i])) {
initializeSuperInitializerMap(superInterfaces[i]);
}
}
}
}
private boolean addSuperInitializer(ResolvedType onType) {
if (onType.isRawType() || onType.isParameterizedType()) onType = onType.getGenericType();
IfaceInitList l = (IfaceInitList) addedSuperInitializers.get(onType);
if (l != null) return false;
l = new IfaceInitList(onType);
addedSuperInitializers.put(onType, l);
return true;
}
public void addInitializer(ConcreteTypeMunger cm) {
NewFieldTypeMunger m = (NewFieldTypeMunger) cm.getMunger();
ResolvedType onType = m.getSignature().getDeclaringType().resolve(world);
if (onType.isRawType()) onType = onType.getGenericType();
if (m.getSignature().isStatic()) {
addedClassInitializers.add(cm);
} else {
if (onType == ty.getResolvedTypeX()) {
addedThisInitializers.add(cm);
} else {
IfaceInitList l = (IfaceInitList) addedSuperInitializers.get(onType);
l.list.add(cm);
}
}
}
private static class IfaceInitList implements PartialOrder.PartialComparable {
final ResolvedType onType;
List list = new ArrayList();
IfaceInitList(ResolvedType onType) {
this.onType = onType;
}
public int compareTo(Object other) {
IfaceInitList o = (IfaceInitList)other;
if (onType.isAssignableFrom(o.onType)) return +1;
else if (o.onType.isAssignableFrom(onType)) return -1;
else return 0;
}
public int fallbackCompareTo(Object other) {
return 0;
}
}
// XXX this is being called, but the result doesn't seem to be being used
public boolean addDispatchTarget(ResolvedMember m) {
return addedDispatchTargets.add(m);
}
public void addLazyMethodGen(LazyMethodGen gen) {
addedLazyMethodGens.add(gen);
}
public void addOrReplaceLazyMethodGen(LazyMethodGen mg) {
if (alreadyDefined(clazz, mg)) return;
for (Iterator i = addedLazyMethodGens.iterator(); i.hasNext(); ) {
LazyMethodGen existing = (LazyMethodGen)i.next();
if (signaturesMatch(mg, existing)) {
if (existing.definingType == null) {
// this means existing was introduced on the class itself
return;
} else if (mg.definingType.isAssignableFrom(existing.definingType)) {
// existing is mg's subtype and dominates mg
return;
} else if (existing.definingType.isAssignableFrom(mg.definingType)) {
// mg is existing's subtype and dominates existing
i.remove();
addedLazyMethodGens.add(mg);
return;
} else {
throw new BCException("conflict between: " + mg + " and " + existing);
}
}
}
addedLazyMethodGens.add(mg);
}
private boolean alreadyDefined(LazyClassGen clazz, LazyMethodGen mg) {
for (Iterator i = clazz.getMethodGens().iterator(); i.hasNext(); ) {
LazyMethodGen existing = (LazyMethodGen)i.next();
if (signaturesMatch(mg, existing)) {
if (!mg.isAbstract() && existing.isAbstract()) {
i.remove();
return false;
}
return true;
}
}
return false;
}
private boolean signaturesMatch(LazyMethodGen mg, LazyMethodGen existing) {
return mg.getName().equals(existing.getName()) &&
mg.getSignature().equals(existing.getSignature());
}
protected static LazyMethodGen makeBridgeMethod(LazyClassGen gen, ResolvedMember member) {
// remove abstract modifier
int mods = member.getModifiers();
if (Modifier.isAbstract(mods)) mods = mods - Modifier.ABSTRACT;
LazyMethodGen ret = new LazyMethodGen(
mods,
BcelWorld.makeBcelType(member.getReturnType()),
member.getName(),
BcelWorld.makeBcelTypes(member.getParameterTypes()),
UnresolvedType.getNames(member.getExceptions()),
gen);
// 43972 : Static crosscutting makes interfaces unusable for javac
// ret.makeSynthetic();
return ret;
}
/**
* Create a single bridge method called 'theBridgeMethod' that bridges to 'whatToBridgeTo'
*/
private static void createBridgeMethod(BcelWorld world, LazyMethodGen whatToBridgeToMethodGen, LazyClassGen clazz,ResolvedMember theBridgeMethod) {
InstructionList body;
InstructionFactory fact;
int pos = 0;
ResolvedMember whatToBridgeTo = whatToBridgeToMethodGen.getMemberView();
if (whatToBridgeTo==null) {
whatToBridgeTo =
new ResolvedMemberImpl(Member.METHOD,
whatToBridgeToMethodGen.getEnclosingClass().getType(),
whatToBridgeToMethodGen.getAccessFlags(),
whatToBridgeToMethodGen.getName(),
whatToBridgeToMethodGen.getSignature());
}
LazyMethodGen bridgeMethod = makeBridgeMethod(clazz,theBridgeMethod); // The bridge method in this type will have the same signature as the one in the supertype
bridgeMethod.setAccessFlags(bridgeMethod.getAccessFlags() | 0x00000040 /*BRIDGE = 0x00000040*/ );
Type returnType = BcelWorld.makeBcelType(theBridgeMethod.getReturnType());
Type[] paramTypes = BcelWorld.makeBcelTypes(theBridgeMethod.getParameterTypes());
Type[] newParamTypes=whatToBridgeToMethodGen.getArgumentTypes();
body = bridgeMethod.getBody();
fact = clazz.getFactory();
if (!whatToBridgeToMethodGen.isStatic()) {
body.append(InstructionFactory.createThis());
pos++;
}
for (int i = 0, len = paramTypes.length; i < len; i++) {
Type paramType = paramTypes[i];
body.append(InstructionFactory.createLoad(paramType, pos));
if (!newParamTypes[i].equals(paramTypes[i])) {
if (debug) System.err.println("Cast "+newParamTypes[i]+" from "+paramTypes[i]);
body.append(fact.createCast(paramTypes[i],newParamTypes[i]));
}
pos+=paramType.getSize();
}
body.append(Utility.createInvoke(fact, world,whatToBridgeTo));
body.append(InstructionFactory.createReturn(returnType));
clazz.addMethodGen(bridgeMethod);
}
// ----
public boolean weave() {
if (clazz.isWoven() && !clazz.isReweavable()) {
world.showMessage(IMessage.ERROR,
WeaverMessages.format(WeaverMessages.ALREADY_WOVEN,clazz.getType().getName()),
ty.getSourceLocation(), null);
return false;
}
Set aspectsAffectingType = null;
if (inReweavableMode || clazz.getType().isAspect()) aspectsAffectingType = new HashSet();
boolean isChanged = false;
// we want to "touch" all aspects
if (clazz.getType().isAspect()) isChanged = true;
// start by munging all typeMungers
for (Iterator i = typeMungers.iterator(); i.hasNext(); ) {
Object o = i.next();
if ( !(o instanceof BcelTypeMunger) ) {
//???System.err.println("surprising: " + o);
continue;
}
BcelTypeMunger munger = (BcelTypeMunger)o;
boolean typeMungerAffectedType = munger.munge(this);
if (typeMungerAffectedType) {
isChanged = true;
if (inReweavableMode || clazz.getType().isAspect()) aspectsAffectingType.add(munger.getAspectType().getName());
}
}
// Weave special half type/half shadow mungers...
isChanged = weaveDeclareAtMethodCtor(clazz) || isChanged;
isChanged = weaveDeclareAtField(clazz) || isChanged;
// XXX do major sort of stuff
// sort according to: Major: type hierarchy
// within each list: dominates
// don't forget to sort addedThisInitialiers according to dominates
addedSuperInitializersAsList = new ArrayList(addedSuperInitializers.values());
addedSuperInitializersAsList = PartialOrder.sort(addedSuperInitializersAsList);
if (addedSuperInitializersAsList == null) {
throw new BCException("circularity in inter-types");
}
// this will create a static initializer if there isn't one
// this is in just as bad taste as NOPs
LazyMethodGen staticInit = clazz.getStaticInitializer();
staticInit.getBody().insert(genInitInstructions(addedClassInitializers, true));
// now go through each method, and match against each method. This
// sets up each method's {@link LazyMethodGen#matchedShadows} field,
// and it also possibly adds to {@link #initializationShadows}.
List methodGens = new ArrayList(clazz.getMethodGens());
for (Iterator i = methodGens.iterator(); i.hasNext();) {
LazyMethodGen mg = (LazyMethodGen)i.next();
if (! mg.hasBody()) continue;
if (world.isJoinpointSynchronizationEnabled() &&
world.areSynchronizationPointcutsInUse() &&
mg.getMethod().isSynchronized()) {
transformSynchronizedMethod(mg);
}
boolean shadowMungerMatched = match(mg);
if (shadowMungerMatched) {
// For matching mungers, add their declaring aspects to the list that affected this type
if (inReweavableMode || clazz.getType().isAspect()) aspectsAffectingType.addAll(findAspectsForMungers(mg));
isChanged = true;
}
}
// now we weave all but the initialization shadows
for (Iterator i = methodGens.iterator(); i.hasNext();) {
LazyMethodGen mg = (LazyMethodGen)i.next();
if (! mg.hasBody()) continue;
implement(mg);
}
// if we matched any initialization shadows, we inline and weave
if (!initializationShadows.isEmpty()) {
// Repeat next step until nothing left to inline...cant go on
// infinetly as compiler will have detected and reported
// "Recursive constructor invocation"
while (inlineSelfConstructors(methodGens));
positionAndImplement(initializationShadows);
}
// now proceed with late type mungers
if (lateTypeMungers != null) {
for (Iterator i = lateTypeMungers.iterator(); i.hasNext(); ) {
BcelTypeMunger munger = (BcelTypeMunger)i.next();
if (munger.matches(clazz.getType())) {
boolean typeMungerAffectedType = munger.munge(this);
if (typeMungerAffectedType) {
isChanged = true;
if (inReweavableMode || clazz.getType().isAspect()) aspectsAffectingType.add(munger.getAspectType().getName());
}
}
}
}
//FIXME AV - see #75442, for now this is not enough to fix the bug, comment that out until we really fix it
// // flush to save some memory
// PerObjectInterfaceTypeMunger.unregisterFromAsAdvisedBy(clazz.getType());
// finally, if we changed, we add in the introduced methods.
if (isChanged) {
clazz.getOrCreateWeaverStateInfo(inReweavableMode);
weaveInAddedMethods(); // FIXME asc are these potentially affected by declare annotation?
}
if (inReweavableMode) {
WeaverStateInfo wsi = clazz.getOrCreateWeaverStateInfo(true);
wsi.addAspectsAffectingType(aspectsAffectingType);
wsi.setUnwovenClassFileData(ty.getJavaClass().getBytes());
wsi.setReweavable(true);
} else {
clazz.getOrCreateWeaverStateInfo(false).setReweavable(false);
}
return isChanged;
}
// **************************** start of bridge method creation code *****************
// debug flag for bridge method creation
public static boolean debug=false;
// FIXME asc tidy this lot up !!
// FIXME asc refactor into ResolvedType or even ResolvedMember?
/**
* Check if a particular method is overriding another - refactored into this helper so it
* can be used from multiple places.
*/
private static ResolvedMember isOverriding(ResolvedType typeToCheck,ResolvedMember methodThatMightBeGettingOverridden,String mname,String mrettype,int mmods,boolean inSamePackage,UnresolvedType[] methodParamsArray) {
// Check if we can be an override...
if (methodThatMightBeGettingOverridden.isStatic()) return null; // we can't be overriding a static method
if (methodThatMightBeGettingOverridden.isPrivate()) return null; // we can't be overriding a private method
if (!methodThatMightBeGettingOverridden.getName().equals(mname)) return null; // names dont match (this will also skip <init> and <clinit> too)
if (methodThatMightBeGettingOverridden.getParameterTypes().length!=methodParamsArray.length) return null; // check same number of parameters
if (!isVisibilityOverride(mmods,methodThatMightBeGettingOverridden,inSamePackage)) return null;
if (debug) System.err.println(" Seriously considering this might be getting overridden "+methodThatMightBeGettingOverridden);
// Look at erasures of parameters (List<String> erased is List)
boolean sameParams = true;
for (int p = 0;p<methodThatMightBeGettingOverridden.getParameterTypes().length;p++) {
if (!methodThatMightBeGettingOverridden.getParameterTypes()[p].getErasureSignature().equals(methodParamsArray[p].getErasureSignature())) sameParams = false;
}
// If the 'typeToCheck' represents a parameterized type then the method will be the parameterized form of the
// generic method in the generic type. So if the method was 'void m(List<T> lt, T t)' and the parameterized type here
// is I<String> then the method we are looking at will be 'void m(List<String> lt, String t)' which when erased
// is 'void m(List lt,String t)' - so if the parameters *do* match then there is a generic method we are
// overriding
if (sameParams) {
// check for covariance
if (typeToCheck.isParameterizedType()) {
return methodThatMightBeGettingOverridden.getBackingGenericMember();
} else if (!methodThatMightBeGettingOverridden.getReturnType().getErasureSignature().equals(mrettype)) {
return methodThatMightBeGettingOverridden; // covariance
}
}
return null;
}
/**
* Looks at the visibility modifiers between two methods, and knows whether they are from classes in
* the same package, and decides whether one overrides the other.
* @return true if there is an overrides rather than a 'hides' relationship
*/
static boolean isVisibilityOverride(int methodMods, ResolvedMember inheritedMethod,boolean inSamePackage) {
if (inheritedMethod.isStatic()) return false;
if (methodMods == inheritedMethod.getModifiers()) return true;
if (inheritedMethod.isPrivate()) return false;
boolean isPackageVisible = !inheritedMethod.isPrivate() && !inheritedMethod.isProtected()
&& !inheritedMethod.isPublic();
if (isPackageVisible && !inSamePackage) return false;
return true;
}
/**
* This method recurses up a specified type looking for a method that overrides the one passed in.
*
* @return the method being overridden or null if none is found
*/
public static ResolvedMember checkForOverride(ResolvedType typeToCheck,String mname,String mparams,String mrettype,int mmods,String mpkg,UnresolvedType[] methodParamsArray) {
if (typeToCheck==null) return null;
if (typeToCheck instanceof MissingResolvedTypeWithKnownSignature) return null; // we just can't tell !
if (debug) System.err.println(" Checking for override of "+mname+" in "+typeToCheck);
String packageName = typeToCheck.getPackageName();
if (packageName==null) packageName="";
boolean inSamePackage = packageName.equals(mpkg); // used when looking at visibility rules
ResolvedMember [] methods = typeToCheck.getDeclaredMethods();
for (int ii=0;ii<methods.length;ii++) {
ResolvedMember methodThatMightBeGettingOverridden = methods[ii]; // the method we are going to check
ResolvedMember isOverriding = isOverriding(typeToCheck,methodThatMightBeGettingOverridden,mname,mrettype,mmods,inSamePackage,methodParamsArray);
if (isOverriding!=null) return isOverriding;
}
List l = typeToCheck.getInterTypeMungers();
for (Iterator iterator = l.iterator(); iterator.hasNext();) {
Object 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 (debug) System.err.println("Possible ITD candidate "+element);
ResolvedMember aMethod = element.getSignature();
ResolvedMember isOverriding = isOverriding(typeToCheck,aMethod,mname,mrettype,mmods,inSamePackage,methodParamsArray);
if (isOverriding!=null) return isOverriding;
}
}
}
if (typeToCheck.equals(UnresolvedType.OBJECT)) return null;
ResolvedType superclass = typeToCheck.getSuperclass();
ResolvedMember overriddenMethod = checkForOverride(superclass,mname,mparams,mrettype,mmods,mpkg,methodParamsArray);
if (overriddenMethod!=null) return overriddenMethod;
ResolvedType[] interfaces = typeToCheck.getDeclaredInterfaces();
for (int i = 0; i < interfaces.length; i++) {
ResolvedType anInterface = interfaces[i];
overriddenMethod = checkForOverride(anInterface,mname,mparams,mrettype,mmods,mpkg,methodParamsArray);
if (overriddenMethod!=null) return overriddenMethod;
}
return null;
}
/**
* We need to determine if any methods in this type require bridge methods - this method should only
* be called if necessary to do this calculation, i.e. we are on a 1.5 VM (where covariance/generics exist) and
* the type hierarchy for the specified class has changed (via decp/itd).
*
* See pr108101
*/
public static boolean calculateAnyRequiredBridgeMethods(BcelWorld world,LazyClassGen clazz) {
if (!world.isInJava5Mode()) return false; // just double check... the caller should have already verified this
if (clazz.isInterface()) return false; // dont bother if we're an interface
boolean didSomething=false; // set if we build any bridge methods
// So what methods do we have right now in this class?
List /*LazyMethodGen*/ methods = clazz.getMethodGens();
// Keep a set of all methods from this type - it'll help us to check if bridge methods
// have already been created, we don't want to do it twice!
Set methodsSet = new HashSet();
for (int i = 0; i < methods.size(); i++) {
LazyMethodGen aMethod = (LazyMethodGen)methods.get(i);
methodsSet.add(aMethod.getName()+aMethod.getSignature()); // e.g. "foo(Ljava/lang/String;)V"
}
// Now go through all the methods in this type
for (int i = 0; i < methods.size(); i++) {
// This is the local method that we *might* have to bridge to
LazyMethodGen bridgeToCandidate = (LazyMethodGen)methods.get(i);
if (bridgeToCandidate.isBridgeMethod()) continue; // Doh!
String name = bridgeToCandidate.getName();
String psig = bridgeToCandidate.getParameterSignature();
String rsig = bridgeToCandidate.getReturnType().getSignature();
//if (bridgeToCandidate.isAbstract()) continue;
if (bridgeToCandidate.isStatic()) continue; // ignore static methods
if (name.endsWith("init>")) continue; // Skip constructors and static initializers
if (debug) System.err.println("Determining if we have to bridge to "+clazz.getName()+"."+name+""+bridgeToCandidate.getSignature());
// Let's take a look at the superclass
ResolvedType theSuperclass= clazz.getSuperClass();
if (debug) System.err.println("Checking supertype "+theSuperclass);
String pkgName = clazz.getPackageName();
UnresolvedType[] bm = BcelWorld.fromBcel(bridgeToCandidate.getArgumentTypes());
ResolvedMember overriddenMethod = checkForOverride(theSuperclass,name,psig,rsig,bridgeToCandidate.getAccessFlags(),pkgName,bm);
if (overriddenMethod!=null) {
boolean alreadyHaveABridgeMethod = methodsSet.contains(overriddenMethod.getName()+overriddenMethod.getSignature());
if (!alreadyHaveABridgeMethod) {
if (debug) System.err.println("Bridging to "+overriddenMethod);
createBridgeMethod(world, bridgeToCandidate, clazz, overriddenMethod);
didSomething = true;
continue; // look at the next method
}
}
// Check superinterfaces
String[] interfaces = clazz.getInterfaceNames();
for (int j = 0; j < interfaces.length; j++) {
if (debug) System.err.println("Checking superinterface "+interfaces[j]);
ResolvedType interfaceType = world.resolve(interfaces[j]);
overriddenMethod = checkForOverride(interfaceType,name,psig,rsig,bridgeToCandidate.getAccessFlags(),clazz.getPackageName(),bm);
if (overriddenMethod!=null) {
boolean alreadyHaveABridgeMethod = methodsSet.contains(overriddenMethod.getName()+overriddenMethod.getSignature());
if (!alreadyHaveABridgeMethod) {
createBridgeMethod(world, bridgeToCandidate, clazz, overriddenMethod);
didSomething=true;
if (debug) System.err.println("Bridging to "+overriddenMethod);
continue; // look at the next method
}
}
}
}
return didSomething;
}
// **************************** end of bridge method creation code *****************
/**
* Weave any declare @method/@ctor statements into the members of the supplied class
*/
private boolean weaveDeclareAtMethodCtor(LazyClassGen clazz) {
List reportedProblems = new ArrayList();
List allDecams = world.getDeclareAnnotationOnMethods();
if (allDecams.isEmpty()) return false; // nothing to do
boolean isChanged = false;
// deal with ITDs
List itdMethodsCtors = getITDSubset(clazz,ResolvedTypeMunger.Method);
itdMethodsCtors.addAll(getITDSubset(clazz,ResolvedTypeMunger.Constructor));
if (!itdMethodsCtors.isEmpty()) {
// Can't use the subset called 'decaMs' as it won't be right for ITDs...
isChanged = weaveAtMethodOnITDSRepeatedly(allDecams,itdMethodsCtors,reportedProblems);
}
// deal with all the other methods...
List members = clazz.getMethodGens();
List decaMs = getMatchingSubset(allDecams,clazz.getType());
if (decaMs.isEmpty()) return false; // nothing to do
if (!members.isEmpty()) {
Set unusedDecams = new HashSet();
unusedDecams.addAll(decaMs);
for (int memberCounter = 0;memberCounter<members.size();memberCounter++) {
LazyMethodGen mg = (LazyMethodGen)members.get(memberCounter);
if (!mg.getName().startsWith(NameMangler.PREFIX)) {
// Single first pass
List worthRetrying = new ArrayList();
boolean modificationOccured = false;
List /*AnnotationGen*/ annotationsToAdd = null;
for (Iterator iter = decaMs.iterator(); iter.hasNext();) {
DeclareAnnotation decaM = (DeclareAnnotation) iter.next();
if (decaM.matches(mg.getMemberView(),world)) {
if (doesAlreadyHaveAnnotation(mg.getMemberView(),decaM,reportedProblems)) {
// remove the declare @method since don't want an error when
// the annotation is already there
unusedDecams.remove(decaM);
continue; // skip this one...
}
if (annotationsToAdd==null) annotationsToAdd = new ArrayList();
Annotation a = decaM.getAnnotationX().getBcelAnnotation();
AnnotationGen ag = new AnnotationGen(a,clazz.getConstantPoolGen(),true);
annotationsToAdd.add(ag);
mg.addAnnotation(decaM.getAnnotationX());
AsmRelationshipProvider.getDefault().addDeclareAnnotationRelationship(decaM.getSourceLocation(),clazz.getName(),mg.getMethod());
reportMethodCtorWeavingMessage(clazz, mg.getMemberView(), decaM,mg.getDeclarationLineNumber());
isChanged = true;
modificationOccured = true;
// remove the declare @method since have matched against it
unusedDecams.remove(decaM);
} else {
if (!decaM.isStarredAnnotationPattern())
worthRetrying.add(decaM); // an annotation is specified that might be put on by a subsequent decaf
}
}
// Multiple secondary passes
while (!worthRetrying.isEmpty() && modificationOccured) {
modificationOccured = false;
// lets have another go
List forRemoval = new ArrayList();
for (Iterator iter = worthRetrying.iterator(); iter.hasNext();) {
DeclareAnnotation decaM = (DeclareAnnotation) iter.next();
if (decaM.matches(mg.getMemberView(),world)) {
if (doesAlreadyHaveAnnotation(mg.getMemberView(),decaM,reportedProblems)) {
// remove the declare @method since don't want an error when
// the annotation is already there
unusedDecams.remove(decaM);
continue; // skip this one...
}
if (annotationsToAdd==null) annotationsToAdd = new ArrayList();
Annotation a = decaM.getAnnotationX().getBcelAnnotation();
AnnotationGen ag = new AnnotationGen(a,clazz.getConstantPoolGen(),true);
annotationsToAdd.add(ag);
mg.addAnnotation(decaM.getAnnotationX());
AsmRelationshipProvider.getDefault().addDeclareAnnotationRelationship(decaM.getSourceLocation(),clazz.getName(),mg.getMethod());
isChanged = true;
modificationOccured = true;
forRemoval.add(decaM);
// remove the declare @method since have matched against it
unusedDecams.remove(decaM);
}
}
worthRetrying.removeAll(forRemoval);
}
if (annotationsToAdd!=null) {
Method oldMethod = mg.getMethod();
MethodGen myGen = new MethodGen(oldMethod,clazz.getClassName(),clazz.getConstantPoolGen(),false);// dont use tags, they won't get repaired like for woven methods.
for (Iterator iter = annotationsToAdd.iterator(); iter.hasNext();) {
AnnotationGen a = (AnnotationGen) iter.next();
myGen.addAnnotation(a);
}
Method newMethod = myGen.getMethod();
members.set(memberCounter,new LazyMethodGen(newMethod,clazz));
}
}
}
checkUnusedDeclareAtTypes(unusedDecams, false);
}
return isChanged;
}
// TAG: WeavingMessage
private void reportMethodCtorWeavingMessage(LazyClassGen clazz, ResolvedMember member, DeclareAnnotation decaM,int memberLineNumber) {
if (!getWorld().getMessageHandler().isIgnoring(IMessage.WEAVEINFO)){
StringBuffer parmString = new StringBuffer("(");
UnresolvedType[] paramTypes = member.getParameterTypes();
for (int i = 0; i < paramTypes.length; i++) {
UnresolvedType type = paramTypes[i];
String s = org.aspectj.apache.bcel.classfile.Utility.signatureToString(type.getSignature());
if (s.lastIndexOf(".")!=-1) s =s.substring(s.lastIndexOf(".")+1);
parmString.append(s);
if ((i+1)<paramTypes.length) parmString.append(",");
}
parmString.append(")");
String methodName = member.getName();
StringBuffer sig = new StringBuffer();
sig.append(org.aspectj.apache.bcel.classfile.Utility.accessToString(member.getModifiers()));
sig.append(" ");
sig.append(member.getReturnType().toString());
sig.append(" ");
sig.append(member.getDeclaringType().toString());
sig.append(".");
sig.append(methodName.equals("<init>")?"new":methodName);
sig.append(parmString);
StringBuffer loc = new StringBuffer();
if (clazz.getFileName()==null) {
loc.append("no debug info available");
} else {
loc.append(clazz.getFileName());
if (memberLineNumber!=-1) {
loc.append(":"+memberLineNumber);
}
}
getWorld().getMessageHandler().handleMessage(
WeaveMessage.constructWeavingMessage(WeaveMessage.WEAVEMESSAGE_ANNOTATES,
new String[]{
sig.toString(),
loc.toString(),
decaM.getAnnotationString(),
methodName.startsWith("<init>")?"constructor":"method",
decaM.getAspect().toString(),
Utility.beautifyLocation(decaM.getSourceLocation())
}));
}
}
/**
* Looks through a list of declare annotation statements and only returns
* those that could possibly match on a field/method/ctor in type.
*/
private List getMatchingSubset(List declareAnnotations, ResolvedType type) {
List subset = new ArrayList();
for (Iterator iter = declareAnnotations.iterator(); iter.hasNext();) {
DeclareAnnotation da = (DeclareAnnotation) iter.next();
if (da.couldEverMatch(type)) {
subset.add(da);
}
}
return subset;
}
/**
* Get a subset of all the type mungers defined on this aspect
*/
private List getITDSubset(LazyClassGen clazz,ResolvedTypeMunger.Kind wantedKind) {
List subset = new ArrayList();
Collection c = clazz.getBcelObjectType().getTypeMungers();
for (Iterator iter = c.iterator();iter.hasNext();) {
BcelTypeMunger typeMunger = (BcelTypeMunger)iter.next();
if (typeMunger.getMunger().getKind()==wantedKind)
subset.add(typeMunger);
}
return subset;
}
public LazyMethodGen locateAnnotationHolderForFieldMunger(LazyClassGen clazz,BcelTypeMunger fieldMunger) {
NewFieldTypeMunger nftm = (NewFieldTypeMunger)fieldMunger.getMunger();
ResolvedMember lookingFor =AjcMemberMaker.interFieldInitializer(nftm.getSignature(),clazz.getType());
List meths = clazz.getMethodGens();
for (Iterator iter = meths.iterator(); iter.hasNext();) {
LazyMethodGen element = (LazyMethodGen) iter.next();
if (element.getName().equals(lookingFor.getName())) return element;
}
return null;
}
// FIXME asc refactor this to neaten it up
public LazyMethodGen locateAnnotationHolderForMethodCtorMunger(LazyClassGen clazz,BcelTypeMunger methodCtorMunger) {
if (methodCtorMunger.getMunger() instanceof NewMethodTypeMunger) {
NewMethodTypeMunger nftm = (NewMethodTypeMunger)methodCtorMunger.getMunger();
ResolvedMember lookingFor = AjcMemberMaker.interMethodDispatcher(nftm.getSignature(),methodCtorMunger.getAspectType());
List meths = clazz.getMethodGens();
for (Iterator iter = meths.iterator(); iter.hasNext();) {
LazyMethodGen element = (LazyMethodGen) iter.next();
if (element.getName().equals(lookingFor.getName()) && element.getParameterSignature().equals(lookingFor.getParameterSignature())) return element;
}
return null;
} else if (methodCtorMunger.getMunger() instanceof NewConstructorTypeMunger) {
NewConstructorTypeMunger nftm = (NewConstructorTypeMunger)methodCtorMunger.getMunger();
ResolvedMember lookingFor =AjcMemberMaker.postIntroducedConstructor(methodCtorMunger.getAspectType(),nftm.getSignature().getDeclaringType(),nftm.getSignature().getParameterTypes());
List meths = clazz.getMethodGens();
for (Iterator iter = meths.iterator(); iter.hasNext();) {
LazyMethodGen element = (LazyMethodGen) iter.next();
if (element.getName().equals(lookingFor.getName()) && element.getParameterSignature().equals(lookingFor.getParameterSignature())) return element;
}
return null;
} else {
throw new RuntimeException("Not sure what this is: "+methodCtorMunger);
}
}
/**
* Applies some set of declare @field constructs (List<DeclareAnnotation>) to some bunch
* of ITDfields (List<BcelTypeMunger>. It will iterate over the fields repeatedly until
* everything has been applied.
*
*/
private boolean weaveAtFieldRepeatedly(List decaFs, List itdFields,List reportedErrors) {
boolean isChanged = false;
for (Iterator iter = itdFields.iterator(); iter.hasNext();) {
BcelTypeMunger fieldMunger = (BcelTypeMunger) iter.next();
ResolvedMember itdIsActually = fieldMunger.getSignature();
List worthRetrying = new ArrayList();
boolean modificationOccured = false;
for (Iterator iter2 = decaFs.iterator(); iter2.hasNext();) {
DeclareAnnotation decaF = (DeclareAnnotation) iter2.next();
if (decaF.matches(itdIsActually,world)) {
LazyMethodGen annotationHolder = locateAnnotationHolderForFieldMunger(clazz,fieldMunger);
if (doesAlreadyHaveAnnotation(annotationHolder,itdIsActually,decaF,reportedErrors)) continue; // skip this one...
annotationHolder.addAnnotation(decaF.getAnnotationX());
AsmRelationshipProvider.getDefault().addDeclareAnnotationRelationship(decaF.getSourceLocation(),itdIsActually.getSourceLocation());
isChanged = true;
modificationOccured = true;
} else {
if (!decaF.isStarredAnnotationPattern())
worthRetrying.add(decaF); // an annotation is specified that might be put on by a subsequent decaf
}
}
while (!worthRetrying.isEmpty() && modificationOccured) {
modificationOccured = false;
List forRemoval = new ArrayList();
for (Iterator iter2 = worthRetrying.iterator(); iter.hasNext();) {
DeclareAnnotation decaF = (DeclareAnnotation) iter2.next();
if (decaF.matches(itdIsActually,world)) {
LazyMethodGen annotationHolder = locateAnnotationHolderForFieldMunger(clazz,fieldMunger);
if (doesAlreadyHaveAnnotation(annotationHolder,itdIsActually,decaF,reportedErrors)) continue; // skip this one...
annotationHolder.addAnnotation(decaF.getAnnotationX());
AsmRelationshipProvider.getDefault().addDeclareAnnotationRelationship(decaF.getSourceLocation(),itdIsActually.getSourceLocation());
isChanged = true;
modificationOccured = true;
forRemoval.add(decaF);
}
worthRetrying.removeAll(forRemoval);
}
}
}
return isChanged;
}
/**
* Applies some set of declare @method/@ctor constructs (List<DeclareAnnotation>) to some bunch
* of ITDmembers (List<BcelTypeMunger>. It will iterate over the fields repeatedly until
* everything has been applied.
*/
private boolean weaveAtMethodOnITDSRepeatedly(List decaMCs, List itdMethodsCtors,List reportedErrors) {
boolean isChanged = false;
for (Iterator iter = itdMethodsCtors.iterator(); iter.hasNext();) {
BcelTypeMunger methodctorMunger = (BcelTypeMunger) iter.next();
ResolvedMember unMangledInterMethod = methodctorMunger.getSignature();
List worthRetrying = new ArrayList();
boolean modificationOccured = false;
for (Iterator iter2 = decaMCs.iterator(); iter2.hasNext();) {
DeclareAnnotation decaMC = (DeclareAnnotation) iter2.next();
if (decaMC.matches(unMangledInterMethod,world)) {
LazyMethodGen annotationHolder = locateAnnotationHolderForMethodCtorMunger(clazz,methodctorMunger);
if (annotationHolder == null || doesAlreadyHaveAnnotation(annotationHolder,unMangledInterMethod,decaMC,reportedErrors)){
continue; // skip this one...
}
annotationHolder.addAnnotation(decaMC.getAnnotationX());
isChanged=true;
AsmRelationshipProvider.getDefault().addDeclareAnnotationRelationship(decaMC.getSourceLocation(),unMangledInterMethod.getSourceLocation());
reportMethodCtorWeavingMessage(clazz, unMangledInterMethod, decaMC,-1);
modificationOccured = true;
} else {
if (!decaMC.isStarredAnnotationPattern())
worthRetrying.add(decaMC); // an annotation is specified that might be put on by a subsequent decaf
}
}
while (!worthRetrying.isEmpty() && modificationOccured) {
modificationOccured = false;
List forRemoval = new ArrayList();
for (Iterator iter2 = worthRetrying.iterator(); iter.hasNext();) {
DeclareAnnotation decaMC = (DeclareAnnotation) iter2.next();
if (decaMC.matches(unMangledInterMethod,world)) {
LazyMethodGen annotationHolder = locateAnnotationHolderForFieldMunger(clazz,methodctorMunger);
if (doesAlreadyHaveAnnotation(annotationHolder,unMangledInterMethod,decaMC,reportedErrors)) continue; // skip this one...
annotationHolder.addAnnotation(decaMC.getAnnotationX());
unMangledInterMethod.addAnnotation(decaMC.getAnnotationX());
AsmRelationshipProvider.getDefault().addDeclareAnnotationRelationship(decaMC.getSourceLocation(),unMangledInterMethod.getSourceLocation());
isChanged = true;
modificationOccured = true;
forRemoval.add(decaMC);
}
worthRetrying.removeAll(forRemoval);
}
}
}
return isChanged;
}
private boolean dontAddTwice(DeclareAnnotation decaF, Annotation [] dontAddMeTwice){
for (int i = 0; i < dontAddMeTwice.length; i++){
Annotation ann = dontAddMeTwice[i];
if (ann != null && decaF.getAnnotationX().getTypeName().equals(ann.getTypeName())){
//dontAddMeTwice[i] = null; // incase it really has been added twice!
return true;
}
}
return false;
}
/**
* Weave any declare @field statements into the fields of the supplied class
*
* Interesting case relating to public ITDd fields. The annotations are really stored against
* the interfieldinit method in the aspect, but the public field is placed in the target
* type and then is processed in the 2nd pass over fields that occurs. I think it would be
* more expensive to avoid putting the annotation on that inserted public field than just to
* have it put there as well as on the interfieldinit method.
*/
private boolean weaveDeclareAtField(LazyClassGen clazz) {
// BUGWARNING not getting enough warnings out on declare @field ?
// There is a potential problem here with warnings not coming out - this
// will occur if they are created on the second iteration round this loop.
// We currently deactivate error reporting for the second time round.
// A possible solution is to record what annotations were added by what
// decafs and check that to see if an error needs to be reported - this
// would be expensive so lets skip it for now
List reportedProblems = new ArrayList();
List allDecafs = world.getDeclareAnnotationOnFields();
if (allDecafs.isEmpty()) return false; // nothing to do
boolean isChanged = false;
List itdFields = getITDSubset(clazz,ResolvedTypeMunger.Field);
if (itdFields!=null) {
isChanged = weaveAtFieldRepeatedly(allDecafs,itdFields,reportedProblems);
}
List decaFs = getMatchingSubset(allDecafs,clazz.getType());
if (decaFs.isEmpty()) return false; // nothing more to do
Field[] fields = clazz.getFieldGens();
if (fields!=null) {
Set unusedDecafs = new HashSet();
unusedDecafs.addAll(decaFs);
for (int fieldCounter = 0;fieldCounter<fields.length;fieldCounter++) {
BcelField aBcelField = new BcelField(clazz.getBcelObjectType(),fields[fieldCounter]);
if (!aBcelField.getName().startsWith(NameMangler.PREFIX)) {
// Single first pass
List worthRetrying = new ArrayList();
boolean modificationOccured = false;
Annotation [] dontAddMeTwice = fields[fieldCounter].getAnnotations();
// go through all the declare @field statements
for (Iterator iter = decaFs.iterator(); iter.hasNext();) {
DeclareAnnotation decaF = (DeclareAnnotation) iter.next();
if (decaF.matches(aBcelField,world)) {
if (!dontAddTwice(decaF,dontAddMeTwice)){
if (doesAlreadyHaveAnnotation(aBcelField,decaF,reportedProblems)){
// remove the declare @field since don't want an error when
// the annotation is already there
unusedDecafs.remove(decaF);
continue;
}
if(decaF.getAnnotationX().isRuntimeVisible()){ // isAnnotationWithRuntimeRetention(clazz.getJavaClass(world))){
//if(decaF.getAnnotationTypeX().isAnnotationWithRuntimeRetention(world)){
// it should be runtime visible, so put it on the Field
Annotation a = decaF.getAnnotationX().getBcelAnnotation();
AnnotationGen ag = new AnnotationGen(a,clazz.getConstantPoolGen(),true);
FieldGen myGen = new FieldGen(fields[fieldCounter],clazz.getConstantPoolGen());
myGen.addAnnotation(ag);
Field newField = myGen.getField();
aBcelField.addAnnotation(decaF.getAnnotationX());
clazz.replaceField(fields[fieldCounter],newField);
fields[fieldCounter]=newField;
} else{
aBcelField.addAnnotation(decaF.getAnnotationX());
}
}
AsmRelationshipProvider.getDefault().addDeclareAnnotationRelationship(decaF.getSourceLocation(),clazz.getName(),fields[fieldCounter]);
reportFieldAnnotationWeavingMessage(clazz, fields, fieldCounter, decaF);
isChanged = true;
modificationOccured = true;
// remove the declare @field since have matched against it
unusedDecafs.remove(decaF);
} else {
if (!decaF.isStarredAnnotationPattern())
worthRetrying.add(decaF); // an annotation is specified that might be put on by a subsequent decaf
}
}
// Multiple secondary passes
while (!worthRetrying.isEmpty() && modificationOccured) {
modificationOccured = false;
// lets have another go
List forRemoval = new ArrayList();
for (Iterator iter = worthRetrying.iterator(); iter.hasNext();) {
DeclareAnnotation decaF = (DeclareAnnotation) iter.next();
if (decaF.matches(aBcelField,world)) {
// below code is for recursive things
if (doesAlreadyHaveAnnotation(aBcelField,decaF,reportedProblems)) {
// remove the declare @field since don't want an error when
// the annotation is already there
unusedDecafs.remove(decaF);
continue; // skip this one...
}
aBcelField.addAnnotation(decaF.getAnnotationX());
AsmRelationshipProvider.getDefault().addDeclareAnnotationRelationship(decaF.getSourceLocation(),clazz.getName(),fields[fieldCounter]);
isChanged = true;
modificationOccured = true;
forRemoval.add(decaF);
// remove the declare @field since have matched against it
unusedDecafs.remove(decaF);
}
}
worthRetrying.removeAll(forRemoval);
}
}
}
checkUnusedDeclareAtTypes(unusedDecafs,true);
}
return isChanged;
}
// bug 99191 - put out an error message if the type doesn't exist
/**
* Report an error if the reason a "declare @method/ctor/field" was not used was because the member
* specified does not exist. This method is passed some set of declare statements that didn't
* match and a flag indicating whether the set contains declare @field or declare @method/ctor
* entries.
*/
private void checkUnusedDeclareAtTypes(Set unusedDecaTs, boolean isDeclareAtField) {
for (Iterator iter = unusedDecaTs.iterator(); iter.hasNext();) {
DeclareAnnotation declA = (DeclareAnnotation) iter.next();
// Error if an exact type pattern was specified
if ((declA.isExactPattern() ||
(declA.getSignaturePattern().getDeclaringType() instanceof ExactTypePattern))
&& (!declA.getSignaturePattern().getName().isAny()
|| (declA.getKind() == DeclareAnnotation.AT_CONSTRUCTOR))) {
// Quickly check if an ITD meets supplies the 'missing' member
boolean itdMatch = false;
List lst = clazz.getType().getInterTypeMungers();
for (Iterator iterator = lst.iterator(); iterator.hasNext() && !itdMatch;) {
BcelTypeMunger element = (BcelTypeMunger) iterator.next();
if (element.getMunger() instanceof NewFieldTypeMunger) {
NewFieldTypeMunger nftm = (NewFieldTypeMunger)element.getMunger();
itdMatch = declA.getSignaturePattern().matches(nftm.getSignature(),world,false);
}else if (element.getMunger() instanceof NewMethodTypeMunger) {
NewMethodTypeMunger nmtm = (NewMethodTypeMunger)element.getMunger();
itdMatch = declA.getSignaturePattern().matches(nmtm.getSignature(),world,false);
} else if (element.getMunger() instanceof NewConstructorTypeMunger) {
NewConstructorTypeMunger nctm = (NewConstructorTypeMunger)element.getMunger();
itdMatch = declA.getSignaturePattern().matches(nctm.getSignature(),world,false);
}
}
if (!itdMatch) {
IMessage message = null;
if (isDeclareAtField) {
message = new Message(
"The field '"+ declA.getSignaturePattern().toString() +
"' does not exist", declA.getSourceLocation() , true);
} else {
message = new Message(
"The method '"+ declA.getSignaturePattern().toString() +
"' does not exist", declA.getSourceLocation() , true);
}
world.getMessageHandler().handleMessage(message);
}
}
}
}
// TAG: WeavingMessage
private void reportFieldAnnotationWeavingMessage(LazyClassGen clazz, Field[] fields, int fieldCounter, DeclareAnnotation decaF) {
if (!getWorld().getMessageHandler().isIgnoring(IMessage.WEAVEINFO)){
Field theField = fields[fieldCounter];
world.getMessageHandler().handleMessage(
WeaveMessage.constructWeavingMessage(WeaveMessage.WEAVEMESSAGE_ANNOTATES,
new String[]{
theField.toString() + "' of type '" + clazz.getName(),
clazz.getFileName(),
decaF.getAnnotationString(),
"field",
decaF.getAspect().toString(),
Utility.beautifyLocation(decaF.getSourceLocation())}));
}
}
/**
* Check if a resolved member (field/method/ctor) already has an annotation, if it
* does then put out a warning and return true
*/
private boolean doesAlreadyHaveAnnotation(ResolvedMember rm,DeclareAnnotation deca,List reportedProblems) {
if (rm.hasAnnotation(deca.getAnnotationTypeX())) {
if (world.getLint().elementAlreadyAnnotated.isEnabled()) {
Integer uniqueID = new Integer(rm.hashCode()*deca.hashCode());
if (!reportedProblems.contains(uniqueID)) {
reportedProblems.add(uniqueID);
world.getLint().elementAlreadyAnnotated.signal(
new String[]{rm.toString(),deca.getAnnotationTypeX().toString()},
rm.getSourceLocation(),new ISourceLocation[]{deca.getSourceLocation()});
}
}
return true;
}
return false;
}
private boolean doesAlreadyHaveAnnotation(LazyMethodGen rm,ResolvedMember itdfieldsig,DeclareAnnotation deca,List reportedProblems) {
if (rm != null && rm.hasAnnotation(deca.getAnnotationTypeX())) {
if (world.getLint().elementAlreadyAnnotated.isEnabled()) {
Integer uniqueID = new Integer(rm.hashCode()*deca.hashCode());
if (!reportedProblems.contains(uniqueID)) {
reportedProblems.add(uniqueID);
reportedProblems.add(new Integer(itdfieldsig.hashCode()*deca.hashCode()));
world.getLint().elementAlreadyAnnotated.signal(
new String[]{rm.toString(),deca.getAnnotationTypeX().toString()},
rm.getSourceLocation(),new ISourceLocation[]{deca.getSourceLocation()});
}
}
return true;
}
return false;
}
private Set findAspectsForMungers(LazyMethodGen mg) {
Set aspectsAffectingType = new HashSet();
for (Iterator iter = mg.matchedShadows.iterator(); iter.hasNext();) {
BcelShadow aShadow = (BcelShadow) iter.next();
// Mungers in effect on that shadow
for (Iterator iter2 = aShadow.getMungers().iterator();iter2.hasNext();) {
ShadowMunger aMunger = (ShadowMunger) iter2.next();
if (aMunger instanceof BcelAdvice) {
BcelAdvice bAdvice = (BcelAdvice)aMunger;
if(bAdvice.getConcreteAspect() != null){
aspectsAffectingType.add(bAdvice.getConcreteAspect().getName());
}
} else {
// It is a 'Checker' - we don't need to remember aspects that only contributed Checkers...
}
}
}
return aspectsAffectingType;
}
private boolean inlineSelfConstructors(List methodGens) {
boolean inlinedSomething = false;
for (Iterator i = methodGens.iterator(); i.hasNext();) {
LazyMethodGen mg = (LazyMethodGen) i.next();
if (! mg.getName().equals("<init>")) continue;
InstructionHandle ih = findSuperOrThisCall(mg);
if (ih != null && isThisCall(ih)) {
LazyMethodGen donor = getCalledMethod(ih);
inlineMethod(donor, mg, ih);
inlinedSomething = true;
}
}
return inlinedSomething;
}
private void positionAndImplement(List initializationShadows) {
for (Iterator i = initializationShadows.iterator(); i.hasNext(); ) {
BcelShadow s = (BcelShadow) i.next();
positionInitializationShadow(s);
//s.getEnclosingMethod().print();
s.implement();
}
}
private void positionInitializationShadow(BcelShadow s) {
LazyMethodGen mg = s.getEnclosingMethod();
InstructionHandle call = findSuperOrThisCall(mg);
InstructionList body = mg.getBody();
ShadowRange r = new ShadowRange(body);
r.associateWithShadow((BcelShadow) s);
if (s.getKind() == Shadow.PreInitialization) {
// XXX assert first instruction is an ALOAD_0.
// a pre shadow goes from AFTER the first instruction (which we believe to
// be an ALOAD_0) to just before the call to super
r.associateWithTargets(
Range.genStart(body, body.getStart().getNext()),
Range.genEnd(body, call.getPrev()));
} else {
// assert s.getKind() == Shadow.Initialization
r.associateWithTargets(
Range.genStart(body, call.getNext()),
Range.genEnd(body));
}
}
private boolean isThisCall(InstructionHandle ih) {
INVOKESPECIAL inst = (INVOKESPECIAL) ih.getInstruction();
return inst.getClassName(cpg).equals(clazz.getName());
}
/** inline a particular call in bytecode.
*
* @param donor the method we want to inline
* @param recipient the method containing the call we want to inline
* @param call the instructionHandle in recipient's body holding the call we want to
* inline.
*/
public static void inlineMethod(
LazyMethodGen donor,
LazyMethodGen recipient,
InstructionHandle call)
{
// assert recipient.contains(call)
/* Implementation notes:
*
* We allocate two slots for every tempvar so we don't screw up
* longs and doubles which may share space. This could be conservatively avoided
* (no reference to a long/double instruction, don't do it) or packed later.
* Right now we don't bother to pack.
*
* Allocate a new var for each formal param of the inlined. Fill with stack
* contents. Then copy the inlined instructions in with the appropriate remap
* table. Any framelocs used by locals in inlined are reallocated to top of
* frame,
*/
final InstructionFactory fact = recipient.getEnclosingClass().getFactory();
IntMap frameEnv = new IntMap();
// this also sets up the initial environment
InstructionList argumentStores =
genArgumentStores(donor, recipient, frameEnv, fact);
InstructionList inlineInstructions =
genInlineInstructions(donor, recipient, frameEnv, fact, false);
inlineInstructions.insert(argumentStores);
recipient.getBody().append(call, inlineInstructions);
Utility.deleteInstruction(call, recipient);
}
// 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) {
// 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());
Type javaLangClassType = Type.getType(Class.class);
// 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 rets = new ArrayList();
while (walker!=null) {
if (walker.getInstruction() instanceof ReturnInstruction) {
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 (Iterator iter = rets.iterator(); iter.hasNext();) {
InstructionHandle element = (InstructionHandle) 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
InstructionTargeter[] targeters = element.getTargeters();
if (targeters!=null) {
for (int i = 0; i < targeters.length; i++) {
InstructionTargeter targeter = targeters[i];
// 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 BranchInstruction) {
// move it
targeter.updateTarget(element, monitorExitBlockStart);
} else {
throw new RuntimeException("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$");
System.err.println("Going to use field name "+fieldname);
Field f = new FieldGen(Modifier.STATIC | Modifier.PRIVATE,
Type.getType(Class.class),fieldname,synchronizedMethod.getEnclosingClass().getConstantPoolGen()).getField();
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
prepend.append(fact.createGetStatic("C", 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("C"));
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 rets = new ArrayList();
while (walker!=null) { //!walker.equals(body.getEnd())) {
if (walker.getInstruction() instanceof ReturnInstruction) {
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 (Iterator iter = rets.iterator(); iter.hasNext();) {
InstructionHandle element = (InstructionHandle) 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
InstructionTargeter[] targeters = element.getTargeters();
if (targeters!=null) {
for (int i = 0; i < targeters.length; i++) {
InstructionTargeter targeter = targeters[i];
// 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 BranchInstruction) {
// move it
targeter.updateTarget(element, monitorExitBlockStart);
} else {
throw new RuntimeException("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 rets = new ArrayList();
while (walker!=null) { //!walker.equals(body.getEnd())) {
if (walker.getInstruction() instanceof ReturnInstruction) {
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 (Iterator iter = rets.iterator(); iter.hasNext();) {
InstructionHandle element = (InstructionHandle) 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
InstructionTargeter[] targeters = element.getTargeters();
if (targeters!=null) {
for (int i = 0; i < targeters.length; i++) {
InstructionTargeter targeter = targeters[i];
// 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 BranchInstruction) {
// move it
targeter.updateTarget(element, monitorExitBlockStart);
} else {
throw new RuntimeException("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
}
/** generate the instructions to be inlined.
*
* @param donor the method from which we will copy (and adjust frame and jumps)
* instructions.
* @param recipient the method the instructions will go into. Used to get the frame
* size so we can allocate new frame locations for locals in donor.
* @param frameEnv an environment to map from donor frame to recipient frame,
* initially populated with argument locations.
* @param fact an instruction factory for recipient
*/
static InstructionList genInlineInstructions(
LazyMethodGen donor,
LazyMethodGen recipient,
IntMap frameEnv,
InstructionFactory fact,
boolean keepReturns)
{
InstructionList footer = new InstructionList();
InstructionHandle end = footer.append(InstructionConstants.NOP);
InstructionList ret = new InstructionList();
InstructionList sourceList = donor.getBody();
Map srcToDest = new HashMap();
ConstantPoolGen donorCpg = donor.getEnclosingClass().getConstantPoolGen();
ConstantPoolGen recipientCpg = recipient.getEnclosingClass().getConstantPoolGen();
boolean isAcrossClass = donorCpg != recipientCpg;
// first pass: copy the instructions directly, populate the srcToDest map,
// fix frame instructions
for (InstructionHandle src = sourceList.getStart();
src != null;
src = src.getNext())
{
Instruction fresh = Utility.copyInstruction(src.getInstruction());
InstructionHandle dest;
if (fresh instanceof CPInstruction) {
// need to reset index to go to new constant pool. This is totally
// a computation leak... we're testing this LOTS of times. Sigh.
if (isAcrossClass) {
CPInstruction cpi = (CPInstruction) fresh;
cpi.setIndex(
recipientCpg.addConstant(
donorCpg.getConstant(cpi.getIndex()),
donorCpg));
}
}
if (src.getInstruction() == Range.RANGEINSTRUCTION) {
dest = ret.append(Range.RANGEINSTRUCTION);
} else if (fresh instanceof ReturnInstruction) {
if (keepReturns) {
dest = ret.append(fresh);
} else {
dest =
ret.append(InstructionFactory.createBranchInstruction(Constants.GOTO, end));
}
} else if (fresh instanceof BranchInstruction) {
dest = ret.append((BranchInstruction) fresh);
} else if (
fresh instanceof LocalVariableInstruction || fresh instanceof RET) {
IndexedInstruction indexed = (IndexedInstruction) fresh;
int oldIndex = indexed.getIndex();
int freshIndex;
if (!frameEnv.hasKey(oldIndex)) {
freshIndex = recipient.allocateLocal(2);
frameEnv.put(oldIndex, freshIndex);
} else {
freshIndex = frameEnv.get(oldIndex);
}
indexed.setIndex(freshIndex);
dest = ret.append(fresh);
} else {
dest = ret.append(fresh);
}
srcToDest.put(src, dest);
}
// second pass: retarget branch instructions, copy ranges and tags
Map tagMap = new HashMap();
Map shadowMap = new HashMap();
for (InstructionHandle dest = ret.getStart(), src = sourceList.getStart();
dest != null;
dest = dest.getNext(), src = src.getNext()) {
Instruction inst = dest.getInstruction();
// retarget branches
if (inst instanceof BranchInstruction) {
BranchInstruction branch = (BranchInstruction) inst;
InstructionHandle oldTarget = branch.getTarget();
InstructionHandle newTarget =
(InstructionHandle) srcToDest.get(oldTarget);
if (newTarget == null) {
// assert this is a GOTO
// this was a return instruction we previously replaced
} else {
branch.setTarget(newTarget);
if (branch instanceof Select) {
Select select = (Select) branch;
InstructionHandle[] oldTargets = select.getTargets();
for (int k = oldTargets.length - 1; k >= 0; k--) {
select.setTarget(
k,
(InstructionHandle) srcToDest.get(oldTargets[k]));
}
}
}
}
//copy over tags and range attributes
InstructionTargeter[] srcTargeters = src.getTargeters();
if (srcTargeters != null) {
for (int j = srcTargeters.length - 1; j >= 0; j--) {
InstructionTargeter old = srcTargeters[j];
if (old instanceof Tag) {
Tag oldTag = (Tag) old;
Tag fresh = (Tag) tagMap.get(oldTag);
if (fresh == null) {
fresh = oldTag.copy();
tagMap.put(oldTag, fresh);
}
dest.addTargeter(fresh);
} else if (old instanceof ExceptionRange) {
ExceptionRange er = (ExceptionRange) old;
if (er.getStart() == src) {
ExceptionRange freshEr =
new ExceptionRange(
recipient.getBody(),
er.getCatchType(),
er.getPriority());
freshEr.associateWithTargets(
dest,
(InstructionHandle)srcToDest.get(er.getEnd()),
(InstructionHandle)srcToDest.get(er.getHandler()));
}
} else if (old instanceof ShadowRange) {
ShadowRange oldRange = (ShadowRange) old;
if (oldRange.getStart() == src) {
BcelShadow oldShadow = oldRange.getShadow();
BcelShadow freshEnclosing =
oldShadow.getEnclosingShadow() == null
? null
: (BcelShadow) shadowMap.get(oldShadow.getEnclosingShadow());
BcelShadow freshShadow =
oldShadow.copyInto(recipient, freshEnclosing);
ShadowRange freshRange = new ShadowRange(recipient.getBody());
freshRange.associateWithShadow(freshShadow);
freshRange.associateWithTargets(
dest,
(InstructionHandle) srcToDest.get(oldRange.getEnd()));
shadowMap.put(oldRange, freshRange);
//recipient.matchedShadows.add(freshShadow);
// XXX should go through the NEW copied shadow and update
// the thisVar, targetVar, and argsVar
// ??? Might want to also go through at this time and add
// "extra" vars to the shadow.
}
}
}
}
}
if (!keepReturns) ret.append(footer);
return ret;
}
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 instanceof ReturnInstruction) {
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 BranchInstruction) {
dest = newList.append((BranchInstruction) fresh);
} else if (
fresh instanceof LocalVariableInstruction || fresh instanceof RET) {
IndexedInstruction indexed = (IndexedInstruction) fresh;
int oldIndex = indexed.getIndex();
int freshIndex;
// if (!frameEnv.hasKey(oldIndex)) {
// freshIndex = recipient.allocateLocal(2);
// frameEnv.put(oldIndex, freshIndex);
// } else {
freshIndex = oldIndex;//frameEnv.get(oldIndex);
// }
indexed.setIndex(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();
Map shadowMap = 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 BranchInstruction) {
BranchInstruction branch = (BranchInstruction) inst;
InstructionHandle oldTarget = branch.getTarget();
InstructionHandle newTarget =
(InstructionHandle) srcToDest.get(oldTarget);
if (newTarget == null) {
// assert this is a GOTO
// this was a return instruction we previously replaced
} else {
branch.setTarget(newTarget);
if (branch instanceof Select) {
Select select = (Select) branch;
InstructionHandle[] oldTargets = select.getTargets();
for (int k = oldTargets.length - 1; k >= 0; k--) {
select.setTarget(
k,
(InstructionHandle) srcToDest.get(oldTargets[k]));
}
}
}
}
//copy over tags and range attributes
InstructionTargeter[] srcTargeters = src.getTargeters();
if (srcTargeters != null) {
for (int j = srcTargeters.length - 1; j >= 0; j--) {
InstructionTargeter old = srcTargeters[j];
if (old instanceof Tag) {
Tag oldTag = (Tag) old;
Tag fresh = (Tag) tagMap.get(oldTag);
if (fresh == null) {
fresh = oldTag.copy();
tagMap.put(oldTag, fresh);
}
dest.addTargeter(fresh);
} else if (old instanceof ExceptionRange) {
ExceptionRange er = (ExceptionRange) old;
if (er.getStart() == src) {
ExceptionRange freshEr =
new ExceptionRange(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() {
public int compare(Object a, Object b) {
LazyMethodGen aa = (LazyMethodGen) a;
LazyMethodGen bb = (LazyMethodGen) b;
int i = aa.getName().compareTo(bb.getName());
if (i != 0) return i;
return aa.getSignature().compareTo(bb.getSignature());
}
}
);
for (Iterator i = addedLazyMethodGens.iterator(); i.hasNext(); ) {
clazz.addMethodGen((LazyMethodGen)i.next());
}
}
void addPerSingletonField(Member field) {
ObjectType aspectType = (ObjectType) BcelWorld.makeBcelType(field.getReturnType());
String aspectName = field.getReturnType().getName();
LazyMethodGen clinit = clazz.getStaticInitializer();
InstructionList setup = new InstructionList();
InstructionFactory fact = clazz.getFactory();
setup.append(fact.createNew(aspectType));
setup.append(InstructionFactory.createDup(1));
setup.append(fact.createInvoke(
aspectName,
"<init>",
Type.VOID,
new Type[0],
Constants.INVOKESPECIAL));
setup.append(
fact.createFieldAccess(
aspectName,
field.getName(),
aspectType,
Constants.PUTSTATIC));
clinit.getBody().insert(setup);
}
/**
* Returns null if this is not a Java constructor, and then we won't
* weave into it at all
*/
private InstructionHandle findSuperOrThisCall(LazyMethodGen mg) {
int depth = 1;
InstructionHandle start = mg.getBody().getStart();
while (true) {
if (start == null) return null;
Instruction inst = start.getInstruction();
if (inst instanceof INVOKESPECIAL
&& ((INVOKESPECIAL) inst).getName(cpg).equals("<init>")) {
depth--;
if (depth == 0) return start;
} else if (inst instanceof NEW) {
depth++;
}
start = start.getNext();
}
}
// ----
private boolean match(LazyMethodGen mg) {
BcelShadow enclosingShadow;
List shadowAccumulator = new ArrayList();
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)) { //.isAjSynthetic()) {
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) {
enclosingShadow = BcelShadow.makeMethodExecution(world, mg, !canMatchBodyShadows);
} else if (effective.isWeaveBody()) {
ResolvedMember rm = effective.getEffectiveSignature();
// Annotations for things with effective signatures are never stored in the effective
// signature itself - we have to hunt for them. Storing them in the effective signature
// would mean keeping two sets up to date (no way!!)
fixAnnotationsForResolvedMember(rm,mg.getMemberView());
enclosingShadow =
BcelShadow.makeShadowForMethod(world,mg,effective.getShadowKind(),rm);
} else {
return false;
}
}
if (canMatchBodyShadows) {
for (InstructionHandle h = mg.getBody().getStart();
h != null;
h = h.getNext()) {
match(mg, h, enclosingShadow, shadowAccumulator);
}
}
// FIXME asc change from string match if we can, rather brittle. this check actually prevents field-exec jps
if (canMatch(enclosingShadow.getKind()) && !(mg.getName().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 shadowAccumulator) {
BcelShadow enclosingShadow;
// XXX the enclosing join point is wrong for things before ignoreMe.
InstructionHandle superOrThisCall = findSuperOrThisCall(mg);
// we don't walk bodies of things where it's a wrong constructor thingie
if (superOrThisCall == null) return false;
enclosingShadow = BcelShadow.makeConstructorExecution(world, mg, superOrThisCall);
if (mg.getEffectiveSignature() != null) {
enclosingShadow.setMatchingSignature(mg.getEffectiveSignature().getEffectiveSignature());
}
// walk the body
boolean beforeSuperOrThisCall = true;
if (shouldWeaveBody(mg)) {
if (canMatchBodyShadows) {
for (InstructionHandle h = mg.getBody().getStart();
h != null;
h = h.getNext()) {
if (h == superOrThisCall) {
beforeSuperOrThisCall = false;
continue;
}
match(mg, h, beforeSuperOrThisCall ? null : enclosingShadow, shadowAccumulator);
}
}
if (canMatch(Shadow.ConstructorExecution))
match(enclosingShadow, shadowAccumulator);
}
// XXX we don't do pre-inits of interfaces
// now add interface inits
if (superOrThisCall != null && ! isThisCall(superOrThisCall)) {
InstructionHandle curr = enclosingShadow.getRange().getStart();
for (Iterator i = addedSuperInitializersAsList.iterator(); i.hasNext(); ) {
IfaceInitList l = (IfaceInitList) i.next();
Member ifaceInitSig = AjcMemberMaker.interfaceConstructor(l.onType);
BcelShadow initShadow =
BcelShadow.makeIfaceInitialization(world, mg, ifaceInitSig);
// insert code in place
InstructionList inits = genInitInstructions(l.list, false);
if (match(initShadow, shadowAccumulator) || !inits.isEmpty()) {
initShadow.initIfaceInitializer(curr);
initShadow.getRange().insert(inits, Range.OutsideBefore);
}
}
// now we add our initialization code
InstructionList inits = genInitInstructions(addedThisInitializers, false);
enclosingShadow.getRange().insert(inits, Range.OutsideBefore);
}
// actually, you only need to inline the self constructors that are
// in a particular group (partition the constructors into groups where members
// call or are called only by those in the group). Then only inline
// constructors
// in groups where at least one initialization jp matched. Future work.
boolean addedInitialization =
match(
BcelShadow.makeUnfinishedInitialization(world, mg),
initializationShadows);
addedInitialization |=
match(
BcelShadow.makeUnfinishedPreinitialization(world, mg),
initializationShadows);
mg.matchedShadows = shadowAccumulator;
return addedInitialization || !shadowAccumulator.isEmpty();
}
private boolean shouldWeaveBody(LazyMethodGen mg) {
if (mg.isBridgeMethod()) return false;
if (mg.isAjSynthetic()) return mg.getName().equals("<clinit>");
AjAttribute.EffectiveSignatureAttribute a = mg.getEffectiveSignature();
if (a != null) return a.isWeaveBody();
return true;
}
/**
* first sorts the mungers, then gens the initializers in the right order
*/
private InstructionList genInitInstructions(List list, boolean isStatic) {
list = PartialOrder.sort(list);
if (list == null) {
throw new BCException("circularity in inter-types");
}
InstructionList ret = new InstructionList();
for (Iterator i = list.iterator(); i.hasNext();) {
ConcreteTypeMunger cmunger = (ConcreteTypeMunger) i.next();
NewFieldTypeMunger munger = (NewFieldTypeMunger) cmunger.getMunger();
ResolvedMember initMethod = munger.getInitMethod(cmunger.getAspectType());
if (!isStatic) ret.append(InstructionConstants.ALOAD_0);
ret.append(Utility.createInvoke(fact, world, initMethod));
}
return ret;
}
private void match(
LazyMethodGen mg,
InstructionHandle ih,
BcelShadow enclosingShadow,
List shadowAccumulator)
{
Instruction i = ih.getInstruction();
if ((i instanceof FieldInstruction) &&
(canMatch(Shadow.FieldGet) || canMatch(Shadow.FieldSet))
) {
FieldInstruction fi = (FieldInstruction) i;
if (fi instanceof PUTFIELD || fi instanceof PUTSTATIC) {
// check for sets of constant fields. We first check the previous
// instruction. If the previous instruction is a LD_WHATEVER (push
// constant on the stack) then we must resolve the field to determine
// if it's final. If it is final, then we don't generate a shadow.
InstructionHandle prevHandle = ih.getPrev();
Instruction prevI = prevHandle.getInstruction();
if (Utility.isConstantPushInstruction(prevI)) {
Member field = BcelWorld.makeFieldJoinPointSignature(clazz, (FieldInstruction) i);
ResolvedMember resolvedField = field.resolve(world);
if (resolvedField == null) {
// we can't find the field, so it's not a join point.
} else if (Modifier.isFinal(resolvedField.getModifiers())) {
// it's final, so it's the set of a final constant, so it's
// not a join point according to 1.0.6 and 1.1.
} else {
if (canMatch(Shadow.FieldSet))
matchSetInstruction(mg, ih, enclosingShadow, shadowAccumulator);
}
} else {
if (canMatch(Shadow.FieldSet))
matchSetInstruction(mg, ih, enclosingShadow, shadowAccumulator);
}
} else {
if (canMatch(Shadow.FieldGet))
matchGetInstruction(mg, ih, enclosingShadow, shadowAccumulator);
}
} else if (i instanceof InvokeInstruction) {
InvokeInstruction ii = (InvokeInstruction) i;
if (ii.getMethodName(clazz.getConstantPoolGen()).equals("<init>")) {
if (canMatch(Shadow.ConstructorCall))
match(
BcelShadow.makeConstructorCall(world, mg, ih, enclosingShadow),
shadowAccumulator);
} else if (ii instanceof INVOKESPECIAL) {
String onTypeName = ii.getClassName(cpg);
if (onTypeName.equals(mg.getEnclosingClass().getName())) {
// we are private
matchInvokeInstruction(mg, ih, ii, enclosingShadow, shadowAccumulator);
} else {
// we are a super call, and this is not a join point in AspectJ-1.{0,1}
}
} else {
matchInvokeInstruction(mg, ih, ii, enclosingShadow, shadowAccumulator);
}
} else if (world.isJoinpointArrayConstructionEnabled() &&
(i instanceof NEWARRAY || i instanceof ANEWARRAY || i instanceof MULTIANEWARRAY)) {
if (canMatch(Shadow.ConstructorCall)) {
boolean debug = false;
if (debug) System.err.println("Found new array instruction: "+i);
if (i instanceof ANEWARRAY) {
ANEWARRAY arrayInstruction = (ANEWARRAY)i;
ObjectType arrayType = arrayInstruction.getLoadClassType(clazz.getConstantPoolGen());
if (debug) System.err.println("Array type is "+arrayType);
BcelShadow ctorCallShadow = BcelShadow.makeArrayConstructorCall(world,mg,ih,enclosingShadow);
match(ctorCallShadow,shadowAccumulator);
} else if (i instanceof NEWARRAY) {
NEWARRAY arrayInstruction = (NEWARRAY)i;
Type arrayType = arrayInstruction.getType();
if (debug) System.err.println("Array type is "+arrayType);
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.getConstantPoolGen());
if (debug) System.err.println("Array type is "+arrayType);
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 instanceof MONITORENTER) || (i instanceof MONITOREXIT))) {
// if (canMatch(Shadow.Monitoring)) {
if (i instanceof MONITORENTER) {
BcelShadow monitorEntryShadow = BcelShadow.makeMonitorEnter(world,mg,ih,enclosingShadow);
match(monitorEntryShadow,shadowAccumulator);
} else {
BcelShadow monitorExitShadow = BcelShadow.makeMonitorExit(world,mg,ih,enclosingShadow);
match(monitorExitShadow,shadowAccumulator);
}
// }
}
// performance optimization... we only actually care about ASTORE instructions,
// since that's what every javac type thing ever uses to start a handler, but for
// now we'll do this for everybody.
if (!canMatch(Shadow.ExceptionHandler)) return;
if (Range.isRangeHandle(ih)) return;
InstructionTargeter[] targeters = ih.getTargeters();
if (targeters != null) {
for (int j = 0; j < targeters.length; j++) {
InstructionTargeter t = targeters[j];
if (t instanceof ExceptionRange) {
// assert t.getHandler() == ih
ExceptionRange er = (ExceptionRange) t;
if (er.getCatchType() == null) continue;
if (isInitFailureHandler(ih)) return;
match(
BcelShadow.makeExceptionHandler(
world,
er,
mg, ih, enclosingShadow),
shadowAccumulator);
}
}
}
}
private boolean isInitFailureHandler(InstructionHandle ih) {
// Skip the astore_0 and aload_0 at the start of the handler and
// then check if the instruction following these is
// 'putstatic ajc$initFailureCause'. If it is then we are
// in the handler we created in AspectClinit.generatePostSyntheticCode()
InstructionHandle twoInstructionsAway = ih.getNext().getNext();
if (twoInstructionsAway.getInstruction() instanceof PUTSTATIC) {
String name = ((PUTSTATIC)twoInstructionsAway.getInstruction()).getFieldName(cpg);
if (name.equals(NameMangler.INITFAILURECAUSE_FIELD_NAME)) return true;
}
return false;
}
private void matchSetInstruction(
LazyMethodGen mg,
InstructionHandle ih,
BcelShadow enclosingShadow,
List shadowAccumulator) {
FieldInstruction fi = (FieldInstruction) ih.getInstruction();
Member field = BcelWorld.makeFieldJoinPointSignature(clazz, fi);
// synthetic fields are never join points
if (field.getName().startsWith(NameMangler.PREFIX)) return;
ResolvedMember resolvedField = field.resolve(world);
if (resolvedField == null) {
// we can't find the field, so it's not a join point.
return;
} else if (
Modifier.isFinal(resolvedField.getModifiers())
&& Utility.isConstantPushInstruction(ih.getPrev().getInstruction())) {
// it's the set of a final constant, so it's
// not a join point according to 1.0.6 and 1.1.
return;
} else if (resolvedField.isSynthetic()) {
// sets of synthetics aren't join points in 1.1
return;
} else {
match(
BcelShadow.makeFieldSet(world, mg, ih, enclosingShadow),
shadowAccumulator);
}
}
private void matchGetInstruction(LazyMethodGen mg, InstructionHandle ih, BcelShadow enclosingShadow, List shadowAccumulator) {
FieldInstruction fi = (FieldInstruction) ih.getInstruction();
Member field = BcelWorld.makeFieldJoinPointSignature(clazz, fi);
// synthetic fields are never join points
if (field.getName().startsWith(NameMangler.PREFIX)) return;
ResolvedMember resolvedField = field.resolve(world);
if (resolvedField == null) {
// we can't find the field, so it's not a join point.
return;
} else if (resolvedField.isSynthetic()) {
// sets of synthetics aren't join points in 1.1
return;
} else {
BcelShadow bs = BcelShadow.makeFieldGet(world,resolvedField,mg,ih,enclosingShadow);
String cname = fi.getClassName(cpg);
if (!resolvedField.getDeclaringType().getName().equals(cname)) {
bs.setActualTargetType(cname);
}
match(bs, shadowAccumulator);
}
}
/**
* For some named resolved type, this method looks for a member with a particular name -
* it should only be used when you truly believe there is only one member with that
* name in the type as it returns the first one it finds.
*/
private ResolvedMember findResolvedMemberNamed(ResolvedType type,String methodName) {
ResolvedMember[] allMethods = type.getDeclaredMethods();
for (int i = 0; i < allMethods.length; i++) {
ResolvedMember member = allMethods[i];
if (member.getName().equals(methodName)) return member;
}
return null;
}
/**
* For a given resolvedmember, this will discover the real annotations for it.
* <b>Should only be used when the resolvedmember is the contents of an effective signature
* attribute, as thats the only time when the annotations aren't stored directly in the
* resolvedMember</b>
* @param rm the sig we want it to pretend to be 'int A.m()' or somesuch ITD like thing
* @param declaredSig the real sig 'blah.ajc$xxx'
*/
private void fixAnnotationsForResolvedMember(ResolvedMember rm,ResolvedMember declaredSig) {
try {
UnresolvedType memberHostType = declaredSig.getDeclaringType();
ResolvedType[] annotations = (ResolvedType[])mapToAnnotations.get(rm);
String methodName = declaredSig.getName();
// FIXME asc shouldnt really rely on string names !
if (annotations == null) {
if (rm.getKind()==Member.FIELD) {
if (methodName.startsWith("ajc$inlineAccessField")) {
ResolvedMember resolvedDooberry = world.resolve(rm);
annotations = resolvedDooberry.getAnnotationTypes();
} else {
ResolvedMember realthing = AjcMemberMaker.interFieldInitializer(rm,memberHostType);
ResolvedMember resolvedDooberry = world.resolve(realthing);
annotations = resolvedDooberry.getAnnotationTypes();
}
} else if (rm.getKind()==Member.METHOD && !rm.isAbstract()) {
if (methodName.startsWith("ajc$inlineAccessMethod") || methodName.startsWith("ajc$superDispatch")) {
ResolvedMember resolvedDooberry = world.resolve(declaredSig);
annotations = resolvedDooberry.getAnnotationTypes();
} else {
ResolvedMember realthing = AjcMemberMaker.interMethodDispatcher(rm.resolve(world),memberHostType).resolve(world);
// ResolvedMember resolvedDooberry = world.resolve(realthing);
ResolvedMember theRealMember = findResolvedMemberNamed(memberHostType.resolve(world),realthing.getName());
// AMC temp guard for M4
if (theRealMember == null) {
throw new UnsupportedOperationException("Known limitation in M4 - can't find ITD members when type variable is used as an argument and has upper bound specified");
}
annotations = theRealMember.getAnnotationTypes();
}
} else if (rm.getKind()==Member.CONSTRUCTOR) {
ResolvedMember realThing = AjcMemberMaker.postIntroducedConstructor(memberHostType.resolve(world),rm.getDeclaringType(),rm.getParameterTypes());
ResolvedMember resolvedDooberry = world.resolve(realThing);
// AMC temp guard for M4
if (resolvedDooberry == null) {
throw new UnsupportedOperationException("Known limitation in M4 - can't find ITD members when type variable is used as an argument and has upper bound specified");
}
annotations = resolvedDooberry.getAnnotationTypes();
}
if (annotations == null)
annotations = new ResolvedType[0];
mapToAnnotations.put(rm,annotations);
}
rm.setAnnotationTypes(annotations);
}
catch (UnsupportedOperationException ex) {
throw ex;
} catch (Throwable t) {
//FIXME asc remove this catch after more testing has confirmed the above stuff is OK
throw new BCException("Unexpectedly went bang when searching for annotations on "+rm,t);
}
}
private void matchInvokeInstruction(LazyMethodGen mg,
InstructionHandle ih,
InvokeInstruction invoke,
BcelShadow enclosingShadow,
List shadowAccumulator)
{
String methodName = invoke.getName(cpg);
if (methodName.startsWith(NameMangler.PREFIX)) {
Member jpSig =
world.makeJoinPointSignatureForMethodInvocation(clazz, invoke);
ResolvedMember declaredSig = jpSig.resolve(world);
//System.err.println(method + ", declaredSig: " +declaredSig);
if (declaredSig == null) return;
if (declaredSig.getKind() == Member.FIELD) {
Shadow.Kind kind;
if (jpSig.getReturnType().equals(ResolvedType.VOID)) {
kind = Shadow.FieldSet;
} else {
kind = Shadow.FieldGet;
}
if (canMatch(Shadow.FieldGet) || canMatch(Shadow.FieldSet))
match(BcelShadow.makeShadowForMethodCall(world, mg, ih, enclosingShadow,
kind, declaredSig),
shadowAccumulator);
} else {
AjAttribute.EffectiveSignatureAttribute effectiveSig =
declaredSig.getEffectiveSignature();
if (effectiveSig == null) return;
//System.err.println("call to inter-type member: " + effectiveSig);
if (effectiveSig.isWeaveBody()) return;
ResolvedMember rm = effectiveSig.getEffectiveSignature();
fixAnnotationsForResolvedMember(rm,declaredSig); // abracadabra
if (canMatch(effectiveSig.getShadowKind()))
match(BcelShadow.makeShadowForMethodCall(world, mg, ih, enclosingShadow,
effectiveSig.getShadowKind(), rm), shadowAccumulator);
}
} else {
if (canMatch(Shadow.MethodCall))
match(
BcelShadow.makeMethodCall(world, mg, ih, enclosingShadow),
shadowAccumulator);
}
}
// 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 shadowAccumulator) {
//System.err.println("match: " + shadow);
if (captureLowLevelContext) { // duplicate blocks - one with context capture, one without, seems faster than multiple 'ifs()'
ContextToken shadowMatchToken = CompilationAndWeavingContext.enteringPhase(CompilationAndWeavingContext.MATCHING_SHADOW, shadow);
boolean isMatched = false;
for (Iterator i = shadowMungers.iterator(); i.hasNext(); ) {
ShadowMunger munger = (ShadowMunger)i.next();
ContextToken mungerMatchToken = CompilationAndWeavingContext.enteringPhase(CompilationAndWeavingContext.MATCHING_POINTCUT, munger.getPointcut());
if (munger.match(shadow, world)) {
WeaverMetrics.recordMatchResult(true);// Could pass: munger
shadow.addMunger(munger);
isMatched = true;
if (shadow.getKind() == Shadow.StaticInitialization) {
clazz.warnOnAddedStaticInitializer(shadow,munger.getSourceLocation());
}
} else {
WeaverMetrics.recordMatchResult(false); // Could pass: munger
}
CompilationAndWeavingContext.leavingPhase(mungerMatchToken);
}
if (isMatched) shadowAccumulator.add(shadow);
CompilationAndWeavingContext.leavingPhase(shadowMatchToken);
return isMatched;
} else {
boolean isMatched = false;
for (Iterator i = shadowMungers.iterator(); i.hasNext(); ) {
ShadowMunger munger = (ShadowMunger)i.next();
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 shadows = mg.matchedShadows;
if (shadows == null) return;
// We depend on a partial order such that inner shadows are earlier on the list
// than outer shadows. That's fine. This order is preserved if:
// A preceeds B iff B.getStart() is LATER THAN A.getStart().
for (Iterator i = shadows.iterator(); i.hasNext(); ) {
BcelShadow shadow = (BcelShadow)i.next();
ContextToken tok = CompilationAndWeavingContext.enteringPhase(CompilationAndWeavingContext.IMPLEMENTING_ON_SHADOW,shadow);
shadow.implement();
CompilationAndWeavingContext.leavingPhase(tok);
}
int ii = mg.getMaxLocals();
mg.matchedShadows = null;
}
// ----
public LazyClassGen getLazyClassGen() {
return clazz;
}
public List getShadowMungers() {
return shadowMungers;
}
public BcelWorld getWorld() {
return world;
}
// Called by the BcelWeaver to let us know all BcelClassWeavers need to collect reweavable info
public static void setReweavableMode(boolean mode) {
inReweavableMode = mode;
}
public static boolean getReweavableMode() {
return inReweavableMode;
}
public String toString() {
return "BcelClassWeaver instance for : "+clazz;
}
}
|
148,007 |
Bug 148007 boolean methods with after advice return incorrect result on JRockit under WLS
| null |
resolved fixed
|
426cbdc
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-06-22T04:49:26Z | 2006-06-21T08:53:20Z |
tests/bugs152/pr148007/purejava/test/BooleanUnitTest.java
| |
148,007 |
Bug 148007 boolean methods with after advice return incorrect result on JRockit under WLS
| null |
resolved fixed
|
426cbdc
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-06-22T04:49:26Z | 2006-06-21T08:53:20Z |
tests/bugs152/pr148007/purejava/test/LoggingAspect.java
| |
148,007 |
Bug 148007 boolean methods with after advice return incorrect result on JRockit under WLS
| null |
resolved fixed
|
426cbdc
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-06-22T04:49:26Z | 2006-06-21T08:53:20Z |
tests/bugs152/pr148007/test/BooleanUnitTest.java
| |
148,007 |
Bug 148007 boolean methods with after advice return incorrect result on JRockit under WLS
| null |
resolved fixed
|
426cbdc
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-06-22T04:49:26Z | 2006-06-21T08:53:20Z |
tests/bugs152/pr148007/test/TestServlet.java
| |
148,007 |
Bug 148007 boolean methods with after advice return incorrect result on JRockit under WLS
| null |
resolved fixed
|
426cbdc
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-06-22T04:49:26Z | 2006-06-21T08:53:20Z |
tests/src/org/aspectj/systemtest/ajc152/Ajc152Tests.java
|
/*******************************************************************************
* Copyright (c) 2006 IBM
* 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.ajc152;
import java.io.File;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import junit.framework.Test;
import org.aspectj.asm.AsmManager;
import org.aspectj.asm.IHierarchy;
import org.aspectj.asm.IProgramElement;
import org.aspectj.asm.IRelationshipMap;
import org.aspectj.asm.internal.Relationship;
import org.aspectj.testing.XMLBasedAjcTestCase;
import org.aspectj.util.CharOperation;
import org.aspectj.weaver.World;
public class Ajc152Tests extends org.aspectj.testing.XMLBasedAjcTestCase {
// public void testverifyErrNoTypeCflowField_pr145693() {runTest("verifyErrNoTypeCflowField");}
// public void testBrokenIfArgsCflowAtAj_pr145018() { runTest("ataj crashing with cflow, if and args");}
// public void testItdCallingGenericMethod_pr145391() { runTest("itd calling generic method");}
// public void testItdCallingGenericMethod_pr145391_2() { runTest("itd calling generic method - 2");}
public void testDuplicateBridgeMethods_pr147801_1() { runTest("duplicate bridge methods");}
public void testPackageIgnoredForException_pr147701_1() { runTest("package for exception ignored");}
public void testPackageIgnoredForException_pr147701_2() { runTest("package for exception ignored - 2");}
public void testPackageIgnoredForException_pr147701_3() { runTest("package for exception ignored - 3");}
public void testBrokenAddSerialVersionUID_pr145950() {runTest("fails to discover Serializable");}
public void testNoUnnecessaryDeclarationOfThrownExcp_pr129282_1() {runTest("no unnecessary declaration of thrown exception warning - 1");}
public void testNoUnnecessaryDeclarationOfThrownExcp_pr129282_2() {runTest("no unnecessary declaration of thrown exception warning - 2");}
public void testNoUnnecessaryDeclarationOfThrownExcp_pr129282_3() {runTest("no unnecessary declaration of thrown exception warning - 3");}
public void testNoUnnecessaryDeclarationOfThrownExcp_pr129282_4() {runTest("no unnecessary declaration of thrown exception warning - 4");}
public void testNoUnnecessaryDeclarationOfThrownExcp_pr129282_5() {runTest("no unnecessary declaration of thrown exception warning - 5");}
public void testNoUnnecessaryDeclarationOfThrownExcp_pr129282_6() {runTest("no unnecessary declaration of thrown exception warning - 6");}
public void testNoUnnecessaryDeclarationOfThrownExcp_pr129282_7() {runTest("no unnecessary declaration of thrown exception warning - 7");}
public void testNoUnnecessaryDeclarationOfThrownExcp_pr129282_8() {runTest("no unnecessary declaration of thrown exception warning - 8");}
public void testNoUnnecessaryDeclarationOfThrownExcp_pr129282_9() {runTest("no unnecessary declaration of thrown exception warning - 9");}
public void testNoUnnecessaryDeclarationOfThrownExcp_pr129282_10() {runTest("no unnecessary declaration of thrown exception warning - 10");}
public void testAtAJVerificationError_pr144602() { runTest("atAJ perthis aspect verification error");}
public void testLTWAndGeneratingSUID_pr144465() { runTest("ltw with serialversionUID creation"); }
public void testAspects14PerSingleton_pr122253() { runTest("aspects14 - persingleton");}
public void testAspects14PerCflow_pr122253() { runTest("aspects14 - percflow");}
public void testAspects14PerThis_pr122253() { runTest("aspects14 - perthis");}
public void testAspects14PerTypeWithin_pr122253() { runTest("aspects14 - pertypewithin");}
public void testFunkyGenericErrorWithITDs_pr126355() { runTest("bizarre generic error with itds");}
public void testConcretizingAbstractMethods_pr142466() { runTest("aop.xml aspect inheriting but not concretizing abstract method");}
public void testConcretizingAbstractMethods_pr142466_2() { runTest("aop.xml aspect inheriting but not concretizing abstract method - 2");}
public void testComplexGenericDecl_pr137568() { runTest("complicated generics declaration");}
public void testItdOnInnerTypeOfGenericType_pr132349() { runTest("ITD on inner type of generic type");}
public void testItdOnInnerTypeOfGenericType_pr132349_2() { runTest("ITD on inner type of generic type - 2");}
public void testItdOnInnerTypeOfGenericType_pr132349_3() { runTest("ITD on inner type of generic type - 3");}
// public void testCovarianceAndDecp_pr128443_1() { runTest("covariance and decp - 1"); }
public void testLTWGeneratedAspectAbstractMethod_pr125480() { runTest("aop.xml aspect inheriting abstract method ");}
public void testLTWGeneratedAspectAbstractMethod_pr125480_2() { runTest("aop.xml aspect inheriting abstract method - code style");}
//public void testSuperITDExplosion_pr134425() { runTest("super ITDs");}
//public void testMisbehavingDeclareAnnotation_pr135865() { runTest("misbehaving declare annotation");}
//public void testMisbehavingDeclareAnnotation_pr135865_2() { runTest("misbehaving declare annotation - 2");}
public void testCompletelyBrokenAopConcretization_pr142165_1() { runTest("broken concretization");}
public void testCompletelyBrokenAopConcretization_pr142165_2() { runTest("broken concretization - 2");}
public void testCompletelyBrokenAopConcretization_pr142165_3() { runTest("broken concretization - 3");}
public void testVerifyErrorLTW_pr135068() { runTest("ltw verifyerror");}
public void testVerifyErrorLTW_pr135068_2() { runTest("ltw verifyerror - 2");}
public void testVerifyErrorLTW_pr135068_3() { runTest("ltw verifyerror - 3");}
public void testVerifyErrorLTW_pr135068_4() { runTest("ltw verifyerror - 4");}
public void testVerifyErrorForComplexCflow_pr136026() { runTest("verifyerror");}
public void testVerifyErrorForComplexCflow_pr136026_2() { runTest("verifyerror - 2");}
public void testAnnotationsAndGenericsBCException_pr129704() { runTest("annotations and generics leading to BCException");}
public void testMethodTooBigAfterWeaving_pr138384() { runTest("method too big"); }
public void testNotAtWithincode_pr138158_1() { runTest("not at withincode - 1");}
public void testNotAtWithincode_pr138158_2() { runTest("not at withincode - 2");}
public void testNotAtWithincode_pr138158_3() { runTest("not at within - 3");}
public void testNpeOnDup_pr138143() { runTest("npe on duplicate method with ataj");}
public void testPointcutsAndGenerics_pr137496_1() { runTest("pointcuts and generics - B");}
public void testPointcutsAndGenerics_pr137496_2() { runTest("pointcuts and generics - D");}
public void testPointcutsAndGenerics_pr137496_3() { runTest("pointcuts and generics - E");}
public void testPointcutsAndGenerics_pr137496_4() { runTest("pointcuts and generics - F");}
public void testPointcutsAndGenerics_pr137496_5() { runTest("pointcuts and generics - G");}
public void testPointcutsAndGenerics_pr137496_6() { runTest("pointcuts and generics - H");}
public void testAspectLibrariesAndASM_pr135001() { runTest("aspect libraries and asm");}
public void testStackOverflow_pr136258() { runTest("stack overflow");}
public void testIncorrectOverridesEvaluation13() { runTest("incorrect overrides evaluation - 1.3"); }
public void testIncorrectOverridesEvaluation15() { runTest("incorrect overrides evaluation - 1.5"); }
public void testAtWithinCodeBug_pr138798() { runTest("atWithinCodeBug"); }
public void testReferencePCutInDeclareWarning_pr138215() { runTest("Reference pointcut fails inside @DeclareWarning");}
public void testReferencePCutInPerClause_pr138219() { runTest("Can't use a FQ Reference pointcut in any pointcut expression referenced by a per-clause");}
public void testReferencePCutInPerClause_pr130722() { runTest("FQ Reference pointcut from perclause ref pc"); }
public void testDoubleAnnotationMatching_pr138223() { runTest("Double at annotation matching (no binding)");}
public void testSuperCallsInAtAspectJAdvice_pr139749() { runTest("Super calls in @AspectJ advice");}
public void testNoClassCastExceptionWithPerThis_pr138286() { runTest("No ClassCastException with perThis");}
public void testGenericAspectHierarchyWithBounds_pr147845() { runTest("Generic abstract aspect hierarchy with bounds"); }
public void testDeclareAtMethodRelationship_pr143924() {
//AsmManager.setReporting("c:/debug.txt",true,true,true,true);
runTest("declare @method relationship");
IHierarchy top = AsmManager.getDefault().getHierarchy();
// get the IProgramElements corresponding to the different code entries
IProgramElement decam = top.findElementForLabel(top.getRoot(),
IProgramElement.Kind.DECLARE_ANNOTATION_AT_METHOD,
"declare @method: * debit(..) : @Secured(role = \"supervisor\")");
assertNotNull("Couldn't find 'declare @method' element in the tree",decam);
IProgramElement method = top.findElementForLabel(top.getRoot(),
IProgramElement.Kind.METHOD,"debit(java.lang.String,long)");
assertNotNull("Couldn't find the 'debit(String,long)' method element in the tree",method);
List matches = AsmManager.getDefault().getRelationshipMap().get(decam);
assertNotNull("'declare @method' should have some relationships but does not",matches);
assertTrue("'declare @method' should have one relationships but has " + matches.size(),matches.size()==1);
List matchesTargets = ((Relationship)matches.get(0)).getTargets();
assertTrue("'declare @method' should have one targets but has" + matchesTargets.size(),matchesTargets.size()==1);
IProgramElement target = AsmManager.getDefault().getHierarchy().findElementForHandle((String)matchesTargets.get(0));
assertEquals("target of relationship should be the 'debit(java.lang.String,long)' method but is IPE with label "
+ target.toLabelString(),method,target);
// check that the debit method has an annotated by relationship with the declare @method
matches = AsmManager.getDefault().getRelationshipMap().get(method);
assertNotNull("'debit(java.lang.String,long)' should have some relationships but does not",matches);
assertTrue("'debit(java.lang.String,long)' should have one relationships but has " + matches.size(),matches.size()==1);
matchesTargets = ((Relationship)matches.get(0)).getTargets();
assertTrue("'debit(java.lang.String,long)' should have one targets but has" + matchesTargets.size(),matchesTargets.size()==1);
target = AsmManager.getDefault().getHierarchy().findElementForHandle((String)matchesTargets.get(0));
assertEquals("target of relationship should be the 'declare @method' ipe but is IPE with label "
+ target.toLabelString(),decam,target);
}
// this next one reported as a bug by Rob Harrop, but I can't reproduce the failure yet...
//public void testAtAspectWithReferencePCPerClause_pr138220() { runTest("@Aspect with reference pointcut in perclause");}
public void testJarChecking_pr137235_1() { runTest("directory with .jar extension: source and outjar"); }
public void testJarChecking_pr137235_2() { runTest("directory with .jar extension"); }
public void testMakePreMethodNPE_pr136393() { runTest("NPE in makePreMethod");}
public void testGetParameterHandles_pr141730() {
runTest("new IProgramElement handle methods");
checkParametersForIPE("intMethod(int)",IProgramElement.Kind.METHOD,"I",true);
checkParametersForIPE("stringMethod(java.lang.String)",IProgramElement.Kind.METHOD,"Ljava/lang/String;",true);
checkParametersForIPE("myClassMethod(MyClass)",IProgramElement.Kind.METHOD,"LMyClass;",true);
checkParametersForIPE("genericMethod(java.util.List<java.lang.String>)",IProgramElement.Kind.METHOD,"Pjava/util/List<Ljava/lang/String;>;",true);
checkParametersForIPE("genericMethod2(MyGenericClass<java.lang.String,MyClass>)",IProgramElement.Kind.METHOD,"PMyGenericClass<Ljava/lang/String;LMyClass;>;",true);
checkParametersForIPE("main(java.lang.String[])",IProgramElement.Kind.METHOD,"[Ljava/lang/String;",true);
checkParametersForIPE("multiMethod(java.lang.String[][])",IProgramElement.Kind.METHOD,"[[Ljava/lang/String;",true);
checkParametersForIPE("intArray(int[])",IProgramElement.Kind.METHOD,"[I",true);
IHierarchy top = AsmManager.getDefault().getHierarchy();
IProgramElement twoArgsMethod = top.findElementForLabel(
top.getRoot(),IProgramElement.Kind.METHOD,"twoArgsMethod(int,java.lang.String)");
assertNotNull("Couldn't find 'twoArgsMethod(int,java.lang.String)' element in the tree",twoArgsMethod);
List l = twoArgsMethod.getParameterSignatures();
assertEquals("",((char[])l.get(0))[0],'I');
boolean eq = CharOperation.equals(((char[])l.get(1)),"Ljava/lang/String;".toCharArray());
assertTrue("expected parameter to be 'Ljava/lang/String;' but found '" +
new String(((char[])l.get(1))) + "'",eq);
}
public void testGetParameterTypes_pr141730() {
runTest("new IProgramElement handle methods");
checkParametersForIPE("intMethod(int)",IProgramElement.Kind.METHOD,"int",false);
checkParametersForIPE("stringMethod(java.lang.String)",IProgramElement.Kind.METHOD,"java.lang.String",false);
checkParametersForIPE("myClassMethod(MyClass)",IProgramElement.Kind.METHOD,"MyClass",false);
checkParametersForIPE("genericMethod(java.util.List<java.lang.String>)",IProgramElement.Kind.METHOD,"java.util.List<java.lang.String>",false);
checkParametersForIPE("genericMethod2(MyGenericClass<java.lang.String,MyClass>)",IProgramElement.Kind.METHOD,"MyGenericClass<java.lang.String,MyClass>",false);
checkParametersForIPE("main(java.lang.String[])",IProgramElement.Kind.METHOD,"java.lang.String[]",false);
checkParametersForIPE("multiMethod(java.lang.String[][])",IProgramElement.Kind.METHOD,"java.lang.String[][]",false);
checkParametersForIPE("intArray(int[])",IProgramElement.Kind.METHOD,"int[]",false);
}
public void testToSignatureString_pr141730() {
runTest("new IProgramElement handle methods");
checkSignatureOfIPE("main(java.lang.String[])",IProgramElement.Kind.METHOD);
checkSignatureOfIPE("C",IProgramElement.Kind.CLASS);
checkSignatureOfIPE("C()",IProgramElement.Kind.CONSTRUCTOR);
checkSignatureOfIPE("method()",IProgramElement.Kind.METHOD);
checkSignatureOfIPE("p()",IProgramElement.Kind.POINTCUT);
checkSignatureOfIPE("before(): p..",IProgramElement.Kind.ADVICE,"before()");
checkSignatureOfIPE("MyClass.method()",IProgramElement.Kind.INTER_TYPE_METHOD);
checkSignatureOfIPE("multiMethod(java.lang.String[][])",IProgramElement.Kind.METHOD);
checkSignatureOfIPE("intArray(int[])",IProgramElement.Kind.METHOD);
checkSignatureOfIPE("MyClass.MyClass()",IProgramElement.Kind.INTER_TYPE_CONSTRUCTOR);
}
// if not filling in the model for aspects contained in jar files then
// want to ensure that the relationship map is correct and has nodes
// which can be used in AJDT - ensure no NPE occurs for the end of
// the relationship with aspectpath
public void testAspectPathRelWhenNotFillingInModel_pr141730() {
World.createInjarHierarchy = false;
try {
runTest("ensure aspectpath injar relationships are correct when not filling in model");
// expecting:
// sourceOfRelationship main in MyFoo.java
// relationship advised by
// target MyBar.aj
//
// and
//
// sourceOfRelationship MyBar.aj
// relationship advises
// target main in MyFoo.java
IHierarchy top = AsmManager.getDefault().getHierarchy();
IRelationshipMap asmRelMap = AsmManager.getDefault().getRelationshipMap();
assertEquals("expected two sources of relationships but only found "
+ asmRelMap.getEntries().size(),2,asmRelMap.getEntries().size());
for (Iterator iter = asmRelMap.getEntries().iterator(); iter.hasNext();) {
String sourceOfRelationship = (String) iter.next();
IProgramElement ipe = top.findElementForHandle(sourceOfRelationship);
List relationships = asmRelMap.get(ipe);
if (ipe.getName().equals("MyBar.aj")) {
assertEquals("expected MyBar.aj to have one relationships but found "
+ relationships.size(),1,relationships.size());
Relationship rel = (Relationship)relationships.get(0);
assertEquals("expected relationship to be 'advises' but was "
+ rel.getName(), "advises", rel.getName());
List targets = rel.getTargets();
assertEquals("expected one target but found " + targets.size(),1,targets.size());
IProgramElement link = top.findElementForHandle((String)targets.get(0));
assertEquals("expected target 'method-call(void foo.MyFoo.main())' but target " + link.getName(),
"method-call(void foo.MyFoo.main())",link.getName());
String fileName = link.getSourceLocation().getSourceFile().toString();
assertTrue("expected 'main' to be in class MyFoo.java but found it " +
"in " + fileName,fileName.indexOf("MyFoo.java") != -1);
} else if (ipe.getName().equals("method-call(void foo.MyFoo.main())")) {
String fileName = ipe.getSourceLocation().getSourceFile().toString();
assertTrue("expected 'method-call(void foo.MyFoo.main())' to be in " +
"class MyFoo.java but found it in"
+ fileName,fileName.indexOf("MyFoo.java") != -1);
assertEquals("expected 'method-call(void foo.MyFoo.main())' " +
"to have one relationships but found "
+ relationships.size(),1,relationships.size());
Relationship rel = (Relationship)relationships.get(0);
assertEquals("expected relationship to be 'advised by' but was "
+ rel.getName(), "advised by", rel.getName());
List targets = rel.getTargets();
assertEquals("expected one target but found " + targets.size(),1,targets.size());
IProgramElement link = top.findElementForHandle((String)targets.get(0));
assertEquals("expected target 'MyBar.aj' but target " + link.getName(),
"MyBar.aj",link.getName());
} else {
fail("unexpected element " + ipe.getName() + " in the relationship map");
}
}
} finally {
World.createInjarHierarchy = true;
}
}
// if not filling in the model for classes contained in jar files then
// want to ensure that the relationship map is correct and has nodes
// which can be used in AJDT - ensure no NPE occurs for the end of
// the relationship with inpath
public void testNoNPEWithInpathWhenNotFillingInModel_pr141730() {
World.createInjarHierarchy = false;
try {
runTest("ensure inpath injar relationships are correct when not filling in model");
// the aspect used for this test has advice, declare parents, deow,
// and declare @type, @constructor, @field and @method. We only expect
// there to be relationships in the map for declare parents and declare @type
// (provided the model isn't being filled in) because the logic in the other
// addXXXRelationship methods use AspectJElementHierarchy.findElementForType().
// This method which returns null because there is no such ipe. The relationship is
// therefore not added to the model. Adding declare @type and declare parents
// uses AspectJElementHierarchy.findElementForHandle() which returns the file
// node ipe if it can't find one for the given handle. Therefore the relationships
// are added against the file node. Before change to using ipe's to create handles
// we also had the deow relationship, however, now we don't because this also
// uses findElementForType to find the targetNode which in the inpath case is null.
// just check that the number of entries is what we expect:
// We expect 3 (the declare @type and declare parents statements plus the filenode)
IRelationshipMap relMap = AsmManager.getDefault().getRelationshipMap();
assertEquals("expected 3 entries in the relationship map but found "
+ relMap.getEntries().size(), 3, relMap.getEntries().size());
} finally {
World.createInjarHierarchy = true;
}
}
// public void testFunkyGenericErrorWithITDs_pr126355_2() {
// runTest("bizarre generic error with itds - 2");
// // public class Pair<F,S> affected by pertarget aspect
// GenericsTests.verifyClassSignature(ajc,"Pair","<F:Ljava/lang/Object;S:Ljava/lang/Object;>Ljava/lang/Object;LIdempotentCache$ajcMightHaveAspect;;");
// }
public void testNoAspects(){
// setSystemProperty(WeavingAdaptor.WEAVING_ADAPTOR_VERBOSE,"true");
runTest("Ensure no weaving without included aspects");
}
public void testWeaveinfoMessages (){
runTest("weaveinfo messages with include and exclude");
}
// tests that can't be included for some reason
// Not valid whilst the ajc compiler forces debug on (ignores -g:none) - it will be green but is invalid, trust me
// public void testLongWindedMessages_pr129408() { runTest("long winded ataj messages");}
// ---------------- helper methods ---------------
private void checkParametersForIPE(String ipeLabel, IProgramElement.Kind kind, String expectedParm, boolean getHandles) {
IHierarchy top = AsmManager.getDefault().getHierarchy();
IProgramElement ipe = top.findElementForLabel(top.getRoot(),kind,ipeLabel);
assertNotNull("Couldn't find '" + ipeLabel + "' element in the tree",ipe);
List l = new ArrayList();
if (getHandles) {
l = ipe.getParameterSignatures();
} else {
l = ipe.getParameterTypes();
}
boolean eq = CharOperation.equals(((char[])l.get(0)),expectedParm.toCharArray());
assertTrue("expected parameter to be '" + expectedParm + "' but found '" +
new String(((char[])l.get(0))) + "'",eq);
}
private void checkSignatureOfIPE(String ipeLabel, IProgramElement.Kind kind) {
checkSignatureOfIPE(ipeLabel,kind,ipeLabel);
}
private void checkSignatureOfIPE(String ipeLabel, IProgramElement.Kind kind, String expectedSig) {
IHierarchy top = AsmManager.getDefault().getHierarchy();
IProgramElement ipe = top.findElementForLabel(
top.getRoot(),kind,ipeLabel);
assertNotNull("Couldn't find '" + ipeLabel + "' element in the tree",ipe);
assertEquals("expected signature to be '"+ expectedSig + "' but was " +
ipe.toSignatureString(true),expectedSig,ipe.toSignatureString(true));
}
/////////////////////////////////////////
public static Test suite() {
return XMLBasedAjcTestCase.loadSuite(Ajc152Tests.class);
}
protected File getSpecFile() {
return new File("../tests/src/org/aspectj/systemtest/ajc152/ajc152.xml");
}
}
|
148,007 |
Bug 148007 boolean methods with after advice return incorrect result on JRockit under WLS
| null |
resolved fixed
|
426cbdc
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-06-22T04:49:26Z | 2006-06-21T08:53:20Z |
weaver/src/org/aspectj/weaver/bcel/BcelShadow.java
|
/* *******************************************************************
* Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC).
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the 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 support for @AJ aspects
* ******************************************************************/
package org.aspectj.weaver.bcel;
import java.lang.reflect.Modifier;
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 org.aspectj.apache.bcel.Constants;
import org.aspectj.apache.bcel.classfile.Field;
import org.aspectj.apache.bcel.generic.ACONST_NULL;
import org.aspectj.apache.bcel.generic.ALOAD;
import org.aspectj.apache.bcel.generic.ANEWARRAY;
import org.aspectj.apache.bcel.generic.ArrayType;
import org.aspectj.apache.bcel.generic.BranchInstruction;
import org.aspectj.apache.bcel.generic.ConstantPoolGen;
import org.aspectj.apache.bcel.generic.DUP;
import org.aspectj.apache.bcel.generic.DUP_X1;
import org.aspectj.apache.bcel.generic.FieldInstruction;
import org.aspectj.apache.bcel.generic.INVOKEINTERFACE;
import org.aspectj.apache.bcel.generic.INVOKESPECIAL;
import org.aspectj.apache.bcel.generic.INVOKESTATIC;
import org.aspectj.apache.bcel.generic.Instruction;
import org.aspectj.apache.bcel.generic.InstructionConstants;
import org.aspectj.apache.bcel.generic.InstructionFactory;
import org.aspectj.apache.bcel.generic.InstructionHandle;
import org.aspectj.apache.bcel.generic.InstructionList;
import org.aspectj.apache.bcel.generic.InstructionTargeter;
import org.aspectj.apache.bcel.generic.InvokeInstruction;
import org.aspectj.apache.bcel.generic.LoadInstruction;
import org.aspectj.apache.bcel.generic.LocalVariableTag;
import org.aspectj.apache.bcel.generic.MULTIANEWARRAY;
import org.aspectj.apache.bcel.generic.NEW;
import org.aspectj.apache.bcel.generic.ObjectType;
import org.aspectj.apache.bcel.generic.PUSH;
import org.aspectj.apache.bcel.generic.ReturnInstruction;
import org.aspectj.apache.bcel.generic.SWAP;
import org.aspectj.apache.bcel.generic.StoreInstruction;
import org.aspectj.apache.bcel.generic.TargetLostException;
import org.aspectj.apache.bcel.generic.Type;
import org.aspectj.bridge.ISourceLocation;
import org.aspectj.weaver.Advice;
import org.aspectj.weaver.AdviceKind;
import org.aspectj.weaver.AjcMemberMaker;
import org.aspectj.weaver.BCException;
import org.aspectj.weaver.IntMap;
import org.aspectj.weaver.Member;
import org.aspectj.weaver.MemberImpl;
import org.aspectj.weaver.NameMangler;
import org.aspectj.weaver.NewConstructorTypeMunger;
import org.aspectj.weaver.NewFieldTypeMunger;
import org.aspectj.weaver.NewMethodTypeMunger;
import org.aspectj.weaver.ResolvedMember;
import org.aspectj.weaver.ResolvedMemberImpl;
import org.aspectj.weaver.ResolvedType;
import org.aspectj.weaver.Shadow;
import org.aspectj.weaver.ShadowMunger;
import org.aspectj.weaver.UnresolvedType;
import org.aspectj.weaver.WeaverMessages;
import org.aspectj.weaver.World;
import org.aspectj.weaver.ast.Var;
import org.aspectj.weaver.patterns.AndPointcut;
import org.aspectj.weaver.patterns.IdentityPointcutVisitor;
import org.aspectj.weaver.patterns.NotPointcut;
import org.aspectj.weaver.patterns.OrPointcut;
import org.aspectj.weaver.patterns.Pointcut;
import org.aspectj.weaver.patterns.ThisOrTargetPointcut;
/*
* Some fun implementation stuff:
*
* * expressionKind advice is non-execution advice
* * may have a target.
* * if the body is extracted, it will be extracted into
* a static method. The first argument to the static
* method is the target
* * advice may expose a this object, but that's the advice's
* consideration, not ours. This object will NOT be cached in another
* local, but will always come from frame zero.
*
* * non-expressionKind advice is execution advice
* * may have a this.
* * target is same as this, and is exposed that way to advice
* (i.e., target will not be cached, will always come from frame zero)
* * if the body is extracted, it will be extracted into a method
* with same static/dynamic modifier as enclosing method. If non-static,
* target of callback call will be this.
*
* * because of these two facts, the setup of the actual arguments (including
* possible target) callback method is the same for both kinds of advice:
* push the targetVar, if it exists (it will not exist for advice on static
* things), then push all the argVars.
*
* Protected things:
*
* * the above is sufficient for non-expressionKind advice for protected things,
* since the target will always be this.
*
* * For expressionKind things, we have to modify the signature of the callback
* method slightly. For non-static expressionKind things, we modify
* the first argument of the callback method NOT to be the type specified
* by the method/field signature (the owner), but rather we type it to
* the currentlyEnclosing type. We are guaranteed this will be fine,
* since the verifier verifies that the target is a subtype of the currently
* enclosingType.
*
* Worries:
*
* * ConstructorCalls will be weirder than all of these, since they
* supposedly don't have a target (according to AspectJ), but they clearly
* do have a target of sorts, just one that needs to be pushed on the stack,
* dupped, and not touched otherwise until the constructor runs.
*
* @author Jim Hugunin
* @author Erik Hilsdale
*
*/
public class BcelShadow extends Shadow {
private ShadowRange range;
private final BcelWorld world;
private final LazyMethodGen enclosingMethod;
// private boolean fallsThrough; //XXX not used anymore
// SECRETAPI - for testing, this will tell us if the optimization succeeded *on the last shadow processed*
public static boolean appliedLazyTjpOptimization;
// Some instructions have a target type that will vary
// from the signature (pr109728) (1.4 declaring type issue)
private String actualInstructionTargetType;
// ---- initialization
/**
* This generates an unassociated shadow, rooted in a particular method but not rooted
* to any particular point in the code. It should be given to a rooted ShadowRange
* in the {@link ShadowRange#associateWithShadow(BcelShadow)} method.
*/
public BcelShadow(
BcelWorld world,
Kind kind,
Member signature,
LazyMethodGen enclosingMethod,
BcelShadow enclosingShadow)
{
super(kind, signature, enclosingShadow);
this.world = world;
this.enclosingMethod = enclosingMethod;
// fallsThrough = kind.argsOnStack();
}
// ---- copies all state, including Shadow's mungers...
public BcelShadow copyInto(LazyMethodGen recipient, BcelShadow enclosing) {
BcelShadow s = new BcelShadow(world, getKind(), getSignature(), recipient, enclosing);
if (mungers.size()>0) {
List src = mungers;
if (s.mungers==Collections.EMPTY_LIST) s.mungers = new ArrayList();
List dest = s.mungers;
for (Iterator i = src.iterator(); i.hasNext(); ) {
dest.add(i.next());
}
}
return s;
}
// ---- overridden behaviour
public World getIWorld() {
return world;
}
private void deleteNewAndDup() {
final ConstantPoolGen cpg = getEnclosingClass().getConstantPoolGen();
int depth = 1;
InstructionHandle ih = range.getStart();
while (true) {
Instruction inst = ih.getInstruction();
if (inst instanceof INVOKESPECIAL
&& ((INVOKESPECIAL) inst).getName(cpg).equals("<init>")) {
depth++;
} else if (inst instanceof NEW) {
depth--;
if (depth == 0) break;
}
ih = ih.getPrev();
}
// now IH points to the NEW. We're followed by the DUP, and that is followed
// by the actual instruction we care about.
InstructionHandle newHandle = ih;
InstructionHandle endHandle = newHandle.getNext();
InstructionHandle nextHandle;
if (endHandle.getInstruction() instanceof DUP) {
nextHandle = endHandle.getNext();
retargetFrom(newHandle, nextHandle);
retargetFrom(endHandle, nextHandle);
} else if (endHandle.getInstruction() instanceof DUP_X1) {
InstructionHandle dupHandle = endHandle;
endHandle = endHandle.getNext();
nextHandle = endHandle.getNext();
if (endHandle.getInstruction() instanceof SWAP) {}
else {
// XXX see next XXX comment
throw new RuntimeException("Unhandled kind of new " + endHandle);
}
// Now make any jumps to the 'new', the 'dup' or the 'end' now target the nextHandle
retargetFrom(newHandle, nextHandle);
retargetFrom(dupHandle, nextHandle);
retargetFrom(endHandle, nextHandle);
} else {
endHandle = newHandle;
nextHandle = endHandle.getNext();
retargetFrom(newHandle, nextHandle);
// add a POP here... we found a NEW w/o a dup or anything else, so
// we must be in statement context.
getRange().insert(InstructionConstants.POP, Range.OutsideAfter);
}
// assert (dupHandle.getInstruction() instanceof DUP);
try {
range.getBody().delete(newHandle, endHandle);
} catch (TargetLostException e) {
throw new BCException("shouldn't happen");
}
}
private void retargetFrom(InstructionHandle old, InstructionHandle fresh) {
InstructionTargeter[] sources = old.getTargeters();
if (sources != null) {
for (int i = sources.length - 1; i >= 0; i--) {
if (sources[i] instanceof ExceptionRange) {
ExceptionRange it = (ExceptionRange)sources[i];
System.err.println("...");
it.updateTarget(old,fresh,it.getBody());
} else {
sources[i].updateTarget(old, fresh);
}
}
}
}
// records advice that is stopping us doing the lazyTjp optimization
private List badAdvice = null;
public void addAdvicePreventingLazyTjp(BcelAdvice advice) {
if (badAdvice == null) badAdvice = new ArrayList();
badAdvice.add(advice);
}
protected void prepareForMungers() {
// if we're a constructor call, we need to remove the new:dup or the new:dup_x1:swap,
// and store all our
// arguments on the frame.
// ??? This is a bit of a hack (for the Java langauge). We do this because
// we sometime add code "outsideBefore" when dealing with weaving join points. We only
// do this for exposing state that is on the stack. It turns out to just work for
// everything except for constructor calls and exception handlers. If we were to clean
// this up, every ShadowRange would have three instructionHandle points, the start of
// the arg-setup code, the start of the running code, and the end of the running code.
if (getKind() == ConstructorCall) {
if (!world.isJoinpointArrayConstructionEnabled() || !this.getSignature().getDeclaringType().isArray())
deleteNewAndDup(); // no new/dup for new array construction
initializeArgVars();
} else if (getKind() == PreInitialization) { // pr74952
ShadowRange range = getRange();
range.insert(InstructionConstants.NOP,Range.InsideAfter);
} else if (getKind() == ExceptionHandler) {
ShadowRange range = getRange();
InstructionList body = range.getBody();
InstructionHandle start = range.getStart();
// Create a store instruction to put the value from the top of the
// stack into a local variable slot. This is a trimmed version of
// what is in initializeArgVars() (since there is only one argument
// at a handler jp and only before advice is supported) (pr46298)
argVars = new BcelVar[1];
//int positionOffset = (hasTarget() ? 1 : 0) + ((hasThis() && !getKind().isTargetSameAsThis()) ? 1 : 0);
UnresolvedType tx = getArgType(0);
argVars[0] = genTempVar(tx, "ajc$arg0");
InstructionHandle insertedInstruction =
range.insert(argVars[0].createStore(getFactory()), Range.OutsideBefore);
// Now the exception range starts just after our new instruction.
// The next bit of code changes the exception range to point at
// the store instruction
InstructionTargeter[] targeters = start.getTargeters();
for (int i = 0; i < targeters.length; i++) {
InstructionTargeter t = targeters[i];
if (t instanceof ExceptionRange) {
ExceptionRange er = (ExceptionRange) t;
er.updateTarget(start, insertedInstruction, body);
}
}
}
// now we ask each munger to request our state
isThisJoinPointLazy = true;//world.isXlazyTjp(); // lazy is default now
badAdvice = null;
for (Iterator iter = mungers.iterator(); iter.hasNext();) {
ShadowMunger munger = (ShadowMunger) iter.next();
munger.specializeOn(this);
}
initializeThisJoinPoint();
if (thisJoinPointVar!=null && !isThisJoinPointLazy && badAdvice!=null && badAdvice.size()>1) {
// something stopped us making it a lazy tjp
// can't build tjp lazily, no suitable test...
int valid = 0;
for (Iterator iter = badAdvice.iterator(); iter.hasNext();) {
BcelAdvice element = (BcelAdvice) iter.next();
ISourceLocation sLoc = element.getSourceLocation();
if (sLoc!=null && sLoc.getLine()>0) valid++;
}
if (valid!=0) {
ISourceLocation[] badLocs = new ISourceLocation[valid];
int i = 0;
for (Iterator iter = badAdvice.iterator(); iter.hasNext();) {
BcelAdvice element = (BcelAdvice) iter.next();
ISourceLocation sLoc = element.getSourceLocation();
if (sLoc!=null) badLocs[i++]=sLoc;
}
world.getLint().multipleAdviceStoppingLazyTjp.signal(
new String[] {this.toString()},
getSourceLocation(),badLocs
);
}
}
badAdvice=null;
// If we are an expression kind, we require our target/arguments on the stack
// before we do our actual thing. However, they may have been removed
// from the stack as the shadowMungers have requested state.
// if any of our shadowMungers requested either the arguments or target,
// the munger will have added code
// to pop the target/arguments into temporary variables, represented by
// targetVar and argVars. In such a case, we must make sure to re-push the
// values.
// If we are nonExpressionKind, we don't expect arguments on the stack
// so this is moot. If our argVars happen to be null, then we know that
// no ShadowMunger has squirrelled away our arguments, so they're still
// on the stack.
InstructionFactory fact = getFactory();
if (getKind().argsOnStack() && argVars != null) {
// Special case first (pr46298). If we are an exception handler and the instruction
// just after the shadow is a POP then we should remove the pop. The code
// above which generated the store instruction has already cleared the stack.
// We also don't generate any code for the arguments in this case as it would be
// an incorrect aload.
if (getKind() == ExceptionHandler
&& range.getEnd().getNext().getInstruction().equals(InstructionConstants.POP)) {
// easier than deleting it ...
range.getEnd().getNext().setInstruction(InstructionConstants.NOP);
} else {
range.insert(
BcelRenderer.renderExprs(fact, world, argVars),
Range.InsideBefore);
if (targetVar != null) {
range.insert(
BcelRenderer.renderExpr(fact, world, targetVar),
Range.InsideBefore);
}
if (getKind() == ConstructorCall) {
if (!world.isJoinpointArrayConstructionEnabled() || !this.getSignature().getDeclaringType().isArray()) {
range.insert((Instruction) InstructionFactory.createDup(1), Range.InsideBefore);
range.insert(
fact.createNew(
(ObjectType) BcelWorld.makeBcelType(
getSignature().getDeclaringType())),
Range.InsideBefore);
}
}
}
}
}
// ---- getters
public ShadowRange getRange() {
return range;
}
public void setRange(ShadowRange range) {
this.range = range;
}
public int getSourceLine() {
// if the kind of join point for which we are a shadow represents
// a method or constructor execution, then the best source line is
// the one from the enclosingMethod declarationLineNumber if available.
Kind kind = getKind();
if ( (kind == MethodExecution) ||
(kind == ConstructorExecution) ||
(kind == AdviceExecution) ||
(kind == StaticInitialization) ||
(kind == PreInitialization) ||
(kind == Initialization)) {
if (getEnclosingMethod().hasDeclaredLineNumberInfo()) {
return getEnclosingMethod().getDeclarationLineNumber();
}
}
if (range == null) {
if (getEnclosingMethod().hasBody()) {
return Utility.getSourceLine(getEnclosingMethod().getBody().getStart());
} else {
return 0;
}
}
int ret = Utility.getSourceLine(range.getStart());
if (ret < 0) return 0;
return ret;
}
// overrides
public UnresolvedType getEnclosingType() {
return getEnclosingClass().getType();
}
public LazyClassGen getEnclosingClass() {
return enclosingMethod.getEnclosingClass();
}
public BcelWorld getWorld() {
return world;
}
// ---- factory methods
public static BcelShadow makeConstructorExecution(
BcelWorld world,
LazyMethodGen enclosingMethod,
InstructionHandle justBeforeStart)
{
final InstructionList body = enclosingMethod.getBody();
BcelShadow s =
new BcelShadow(
world,
ConstructorExecution,
world.makeJoinPointSignature(enclosingMethod),
enclosingMethod,
null);
ShadowRange r = new ShadowRange(body);
r.associateWithShadow(s);
r.associateWithTargets(
Range.genStart(body, justBeforeStart.getNext()),
Range.genEnd(body));
return s;
}
public static BcelShadow makeStaticInitialization(
BcelWorld world,
LazyMethodGen enclosingMethod)
{
InstructionList body = enclosingMethod.getBody();
// move the start past ajc$preClinit
InstructionHandle clinitStart = body.getStart();
if (clinitStart.getInstruction() instanceof InvokeInstruction) {
InvokeInstruction ii = (InvokeInstruction)clinitStart.getInstruction();
if (ii
.getName(enclosingMethod.getEnclosingClass().getConstantPoolGen())
.equals(NameMangler.AJC_PRE_CLINIT_NAME)) {
clinitStart = clinitStart.getNext();
}
}
InstructionHandle clinitEnd = body.getEnd();
//XXX should move the end before the postClinit, but the return is then tricky...
// if (clinitEnd.getInstruction() instanceof InvokeInstruction) {
// InvokeInstruction ii = (InvokeInstruction)clinitEnd.getInstruction();
// if (ii.getName(enclosingMethod.getEnclosingClass().getConstantPoolGen()).equals(NameMangler.AJC_POST_CLINIT_NAME)) {
// clinitEnd = clinitEnd.getPrev();
// }
// }
BcelShadow s =
new BcelShadow(
world,
StaticInitialization,
world.makeJoinPointSignature(enclosingMethod),
enclosingMethod,
null);
ShadowRange r = new ShadowRange(body);
r.associateWithShadow(s);
r.associateWithTargets(
Range.genStart(body, clinitStart),
Range.genEnd(body, clinitEnd));
return s;
}
/** Make the shadow for an exception handler. Currently makes an empty shadow that
* only allows before advice to be woven into it.
*/
public static BcelShadow makeExceptionHandler(
BcelWorld world,
ExceptionRange exceptionRange,
LazyMethodGen enclosingMethod,
InstructionHandle startOfHandler,
BcelShadow enclosingShadow)
{
InstructionList body = enclosingMethod.getBody();
UnresolvedType catchType = exceptionRange.getCatchType();
UnresolvedType inType = enclosingMethod.getEnclosingClass().getType();
ResolvedMemberImpl sig = MemberImpl.makeExceptionHandlerSignature(inType, catchType);
sig.setParameterNames(new String[] {findHandlerParamName(startOfHandler)});
BcelShadow s =
new BcelShadow(
world,
ExceptionHandler,
sig,
enclosingMethod,
enclosingShadow);
ShadowRange r = new ShadowRange(body);
r.associateWithShadow(s);
InstructionHandle start = Range.genStart(body, startOfHandler);
InstructionHandle end = Range.genEnd(body, start);
r.associateWithTargets(start, end);
exceptionRange.updateTarget(startOfHandler, start, body);
return s;
}
private static String findHandlerParamName(InstructionHandle startOfHandler) {
if (startOfHandler.getInstruction() instanceof StoreInstruction &&
startOfHandler.getNext() != null)
{
int slot = ((StoreInstruction)startOfHandler.getInstruction()).getIndex();
//System.out.println("got store: " + startOfHandler.getInstruction() + ", " + index);
InstructionTargeter[] targeters = startOfHandler.getNext().getTargeters();
if (targeters!=null) {
for (int i=targeters.length-1; i >= 0; i--) {
if (targeters[i] instanceof LocalVariableTag) {
LocalVariableTag t = (LocalVariableTag)targeters[i];
if (t.getSlot() == slot) {
return t.getName();
}
//System.out.println("tag: " + targeters[i]);
}
}
}
}
return "<missing>";
}
/** create an init join point associated w/ an interface in the body of a constructor */
public static BcelShadow makeIfaceInitialization(
BcelWorld world,
LazyMethodGen constructor,
Member interfaceConstructorSignature)
{
// this call marks the instruction list as changed
constructor.getBody();
// UnresolvedType inType = constructor.getEnclosingClass().getType();
BcelShadow s =
new BcelShadow(
world,
Initialization,
interfaceConstructorSignature,
constructor,
null);
// s.fallsThrough = true;
// ShadowRange r = new ShadowRange(body);
// r.associateWithShadow(s);
// InstructionHandle start = Range.genStart(body, handle);
// InstructionHandle end = Range.genEnd(body, handle);
//
// r.associateWithTargets(start, end);
return s;
}
public void initIfaceInitializer(InstructionHandle end) {
final InstructionList body = enclosingMethod.getBody();
ShadowRange r = new ShadowRange(body);
r.associateWithShadow(this);
InstructionHandle nop = body.insert(end, InstructionConstants.NOP);
r.associateWithTargets(
Range.genStart(body, nop),
Range.genEnd(body, nop));
}
// public static BcelShadow makeIfaceConstructorExecution(
// BcelWorld world,
// LazyMethodGen constructor,
// InstructionHandle next,
// Member interfaceConstructorSignature)
// {
// // final InstructionFactory fact = constructor.getEnclosingClass().getFactory();
// InstructionList body = constructor.getBody();
// // UnresolvedType inType = constructor.getEnclosingClass().getType();
// BcelShadow s =
// new BcelShadow(
// world,
// ConstructorExecution,
// interfaceConstructorSignature,
// constructor,
// null);
// s.fallsThrough = true;
// ShadowRange r = new ShadowRange(body);
// r.associateWithShadow(s);
// // ??? this may or may not work
// InstructionHandle start = Range.genStart(body, next);
// //InstructionHandle end = Range.genEnd(body, body.append(start, fact.NOP));
// InstructionHandle end = Range.genStart(body, next);
// //body.append(start, fact.NOP);
//
// r.associateWithTargets(start, end);
// return s;
// }
/** Create an initialization join point associated with a constructor, but not
* with any body of code yet. If this is actually matched, it's range will be set
* when we inline self constructors.
*
* @param constructor The constructor starting this initialization.
*/
public static BcelShadow makeUnfinishedInitialization(
BcelWorld world,
LazyMethodGen constructor)
{
BcelShadow ret = new BcelShadow(
world,
Initialization,
world.makeJoinPointSignature(constructor),
constructor,
null);
if (constructor.getEffectiveSignature() != null) {
ret.setMatchingSignature(constructor.getEffectiveSignature().getEffectiveSignature());
}
return ret;
}
public static BcelShadow makeUnfinishedPreinitialization(
BcelWorld world,
LazyMethodGen constructor)
{
BcelShadow ret = new BcelShadow(
world,
PreInitialization,
world.makeJoinPointSignature(constructor),
constructor,
null);
// ret.fallsThrough = true;
if (constructor.getEffectiveSignature() != null) {
ret.setMatchingSignature(constructor.getEffectiveSignature().getEffectiveSignature());
}
return ret;
}
public static BcelShadow makeMethodExecution(
BcelWorld world,
LazyMethodGen enclosingMethod,
boolean lazyInit)
{
if (!lazyInit) return makeMethodExecution(world, enclosingMethod);
BcelShadow s =
new BcelShadow(
world,
MethodExecution,
enclosingMethod.getMemberView(),
enclosingMethod,
null);
return s;
}
public void init() {
if (range != null) return;
final InstructionList body = enclosingMethod.getBody();
ShadowRange r = new ShadowRange(body);
r.associateWithShadow(this);
r.associateWithTargets(
Range.genStart(body),
Range.genEnd(body));
}
public static BcelShadow makeMethodExecution(
BcelWorld world,
LazyMethodGen enclosingMethod)
{
return makeShadowForMethod(world, enclosingMethod, MethodExecution,
enclosingMethod.getMemberView()); //world.makeMethodSignature(enclosingMethod));
}
public static BcelShadow makeShadowForMethod(BcelWorld world,
LazyMethodGen enclosingMethod, Shadow.Kind kind, Member sig)
{
final InstructionList body = enclosingMethod.getBody();
BcelShadow s =
new BcelShadow(
world,
kind,
sig,
enclosingMethod,
null);
ShadowRange r = new ShadowRange(body);
r.associateWithShadow(s);
r.associateWithTargets(
Range.genStart(body),
Range.genEnd(body));
return s;
}
public static BcelShadow makeAdviceExecution(
BcelWorld world,
LazyMethodGen enclosingMethod)
{
final InstructionList body = enclosingMethod.getBody();
BcelShadow s =
new BcelShadow(
world,
AdviceExecution,
world.makeJoinPointSignatureFromMethod(enclosingMethod, Member.ADVICE),
enclosingMethod,
null);
ShadowRange r = new ShadowRange(body);
r.associateWithShadow(s);
r.associateWithTargets(Range.genStart(body), Range.genEnd(body));
return s;
}
// constructor call shadows are <em>initially</em> just around the
// call to the constructor. If ANY advice gets put on it, we move
// the NEW instruction inside the join point, which involves putting
// all the arguments in temps.
public static BcelShadow makeConstructorCall(
BcelWorld world,
LazyMethodGen enclosingMethod,
InstructionHandle callHandle,
BcelShadow enclosingShadow)
{
final InstructionList body = enclosingMethod.getBody();
Member sig = world.makeJoinPointSignatureForMethodInvocation(
enclosingMethod.getEnclosingClass(),
(InvokeInstruction) callHandle.getInstruction());
BcelShadow s =
new BcelShadow(
world,
ConstructorCall,
sig,
enclosingMethod,
enclosingShadow);
ShadowRange r = new ShadowRange(body);
r.associateWithShadow(s);
r.associateWithTargets(
Range.genStart(body, callHandle),
Range.genEnd(body, callHandle));
retargetAllBranches(callHandle, r.getStart());
return s;
}
public static BcelShadow makeArrayConstructorCall(BcelWorld world,LazyMethodGen enclosingMethod,InstructionHandle arrayInstruction,BcelShadow enclosingShadow) {
final InstructionList body = enclosingMethod.getBody();
Member sig = world.makeJoinPointSignatureForArrayConstruction(enclosingMethod.getEnclosingClass(),arrayInstruction);
BcelShadow s =
new BcelShadow(
world,
ConstructorCall,
sig,
enclosingMethod,
enclosingShadow);
ShadowRange r = new ShadowRange(body);
r.associateWithShadow(s);
r.associateWithTargets(
Range.genStart(body, arrayInstruction),
Range.genEnd(body, arrayInstruction));
retargetAllBranches(arrayInstruction, r.getStart());
return s;
}
public static BcelShadow makeMonitorEnter(BcelWorld world,LazyMethodGen enclosingMethod,InstructionHandle monitorInstruction,BcelShadow enclosingShadow) {
final InstructionList body = enclosingMethod.getBody();
Member sig = world.makeJoinPointSignatureForMonitorEnter(enclosingMethod.getEnclosingClass(),monitorInstruction);
BcelShadow s = new BcelShadow(world,SynchronizationLock,sig,enclosingMethod,enclosingShadow);
ShadowRange r = new ShadowRange(body);
r.associateWithShadow(s);
r.associateWithTargets(
Range.genStart(body, monitorInstruction),
Range.genEnd(body, monitorInstruction));
retargetAllBranches(monitorInstruction, r.getStart());
return s;
}
public static BcelShadow makeMonitorExit(BcelWorld world,LazyMethodGen enclosingMethod,InstructionHandle monitorInstruction,BcelShadow enclosingShadow) {
final InstructionList body = enclosingMethod.getBody();
Member sig = world.makeJoinPointSignatureForMonitorExit(enclosingMethod.getEnclosingClass(),monitorInstruction);
BcelShadow s = new BcelShadow(world,SynchronizationUnlock,sig,enclosingMethod,enclosingShadow);
ShadowRange r = new ShadowRange(body);
r.associateWithShadow(s);
r.associateWithTargets(
Range.genStart(body, monitorInstruction),
Range.genEnd(body, monitorInstruction));
retargetAllBranches(monitorInstruction, r.getStart());
return s;
}
// see pr77166
// public static BcelShadow makeArrayLoadCall(
// BcelWorld world,
// LazyMethodGen enclosingMethod,
// InstructionHandle arrayInstruction,
// BcelShadow enclosingShadow)
// {
// final InstructionList body = enclosingMethod.getBody();
// Member sig = world.makeJoinPointSignatureForArrayLoad(enclosingMethod.getEnclosingClass(),arrayInstruction);
// BcelShadow s =
// new BcelShadow(
// world,
// MethodCall,
// sig,
// enclosingMethod,
// enclosingShadow);
// ShadowRange r = new ShadowRange(body);
// r.associateWithShadow(s);
// r.associateWithTargets(
// Range.genStart(body, arrayInstruction),
// Range.genEnd(body, arrayInstruction));
// retargetAllBranches(arrayInstruction, r.getStart());
// return s;
// }
public static BcelShadow makeMethodCall(
BcelWorld world,
LazyMethodGen enclosingMethod,
InstructionHandle callHandle,
BcelShadow enclosingShadow)
{
final InstructionList body = enclosingMethod.getBody();
BcelShadow s =
new BcelShadow(
world,
MethodCall,
world.makeJoinPointSignatureForMethodInvocation(
enclosingMethod.getEnclosingClass(),
(InvokeInstruction) callHandle.getInstruction()),
enclosingMethod,
enclosingShadow);
ShadowRange r = new ShadowRange(body);
r.associateWithShadow(s);
r.associateWithTargets(
Range.genStart(body, callHandle),
Range.genEnd(body, callHandle));
retargetAllBranches(callHandle, r.getStart());
return s;
}
public static BcelShadow makeShadowForMethodCall(
BcelWorld world,
LazyMethodGen enclosingMethod,
InstructionHandle callHandle,
BcelShadow enclosingShadow,
Kind kind,
ResolvedMember sig)
{
final InstructionList body = enclosingMethod.getBody();
BcelShadow s =
new BcelShadow(
world,
kind,
sig,
enclosingMethod,
enclosingShadow);
ShadowRange r = new ShadowRange(body);
r.associateWithShadow(s);
r.associateWithTargets(
Range.genStart(body, callHandle),
Range.genEnd(body, callHandle));
retargetAllBranches(callHandle, r.getStart());
return s;
}
public static BcelShadow makeFieldGet(
BcelWorld world,
ResolvedMember field,
LazyMethodGen enclosingMethod,
InstructionHandle getHandle,
BcelShadow enclosingShadow)
{
final InstructionList body = enclosingMethod.getBody();
BcelShadow s =
new BcelShadow(
world,
FieldGet,
field,
// BcelWorld.makeFieldSignature(
// enclosingMethod.getEnclosingClass(),
// (FieldInstruction) getHandle.getInstruction()),
enclosingMethod,
enclosingShadow);
ShadowRange r = new ShadowRange(body);
r.associateWithShadow(s);
r.associateWithTargets(
Range.genStart(body, getHandle),
Range.genEnd(body, getHandle));
retargetAllBranches(getHandle, r.getStart());
return s;
}
public static BcelShadow makeFieldSet(
BcelWorld world,
LazyMethodGen enclosingMethod,
InstructionHandle setHandle,
BcelShadow enclosingShadow)
{
final InstructionList body = enclosingMethod.getBody();
BcelShadow s =
new BcelShadow(
world,
FieldSet,
BcelWorld.makeFieldJoinPointSignature(
enclosingMethod.getEnclosingClass(),
(FieldInstruction) setHandle.getInstruction()),
enclosingMethod,
enclosingShadow);
ShadowRange r = new ShadowRange(body);
r.associateWithShadow(s);
r.associateWithTargets(
Range.genStart(body, setHandle),
Range.genEnd(body, setHandle));
retargetAllBranches(setHandle, r.getStart());
return s;
}
public static void retargetAllBranches(InstructionHandle from, InstructionHandle to) {
InstructionTargeter[] sources = from.getTargeters();
if (sources != null) {
for (int i = sources.length - 1; i >= 0; i--) {
InstructionTargeter source = sources[i];
if (source instanceof BranchInstruction) {
source.updateTarget(from, to);
}
}
}
}
// // ---- type access methods
// private ObjectType getTargetBcelType() {
// return (ObjectType) BcelWorld.makeBcelType(getTargetType());
// }
// private Type getArgBcelType(int arg) {
// return BcelWorld.makeBcelType(getArgType(arg));
// }
// ---- kinding
/**
* If the end of my range has no real instructions following then
* my context needs a return at the end.
*/
public boolean terminatesWithReturn() {
return getRange().getRealNext() == null;
}
/**
* Is arg0 occupied with the value of this
*/
public boolean arg0HoldsThis() {
if (getKind().isEnclosingKind()) {
return !getSignature().isStatic();
} else if (enclosingShadow == null) {
//XXX this is mostly right
// this doesn't do the right thing for calls in the pre part of introduced constructors.
return !enclosingMethod.isStatic();
} else {
return ((BcelShadow)enclosingShadow).arg0HoldsThis();
}
}
// ---- argument getting methods
private BcelVar thisVar = null;
private BcelVar targetVar = null;
private BcelVar[] argVars = null;
private Map/*<UnresolvedType,BcelVar>*/ kindedAnnotationVars = null;
private Map/*<UnresolvedType,BcelVar>*/ thisAnnotationVars = null;
private Map/*<UnresolvedType,BcelVar>*/ targetAnnotationVars = null;
private Map/*<UnresolvedType,BcelVar>*/[] argAnnotationVars = null;
private Map/*<UnresolvedType,BcelVar>*/ withinAnnotationVars = null;
private Map/*<UnresolvedType,BcelVar>*/ withincodeAnnotationVars = null;
public Var getThisVar() {
if (!hasThis()) {
throw new IllegalStateException("no this");
}
initializeThisVar();
return thisVar;
}
public Var getThisAnnotationVar(UnresolvedType forAnnotationType) {
if (!hasThis()) {
throw new IllegalStateException("no this");
}
initializeThisAnnotationVars(); // FIXME asc Why bother with this if we always return one?
// Even if we can't find one, we have to return one as we might have this annotation at runtime
Var v = (Var) thisAnnotationVars.get(forAnnotationType);
if (v==null)
v = new TypeAnnotationAccessVar(forAnnotationType.resolve(world),(BcelVar)getThisVar());
return v;
}
public Var getTargetVar() {
if (!hasTarget()) {
throw new IllegalStateException("no target");
}
initializeTargetVar();
return targetVar;
}
public Var getTargetAnnotationVar(UnresolvedType forAnnotationType) {
if (!hasTarget()) {
throw new IllegalStateException("no target");
}
initializeTargetAnnotationVars(); // FIXME asc why bother with this if we always return one?
Var v =(Var) targetAnnotationVars.get(forAnnotationType);
// Even if we can't find one, we have to return one as we might have this annotation at runtime
if (v==null)
v = new TypeAnnotationAccessVar(forAnnotationType.resolve(world),(BcelVar)getTargetVar());
return v;
}
public Var getArgVar(int i) {
initializeArgVars();
return argVars[i];
}
public Var getArgAnnotationVar(int i,UnresolvedType forAnnotationType) {
initializeArgAnnotationVars();
Var v= (Var) argAnnotationVars[i].get(forAnnotationType);
if (v==null)
v = new TypeAnnotationAccessVar(forAnnotationType.resolve(world),(BcelVar)getArgVar(i));
return v;
}
public Var getKindedAnnotationVar(UnresolvedType forAnnotationType) {
initializeKindedAnnotationVars();
return (Var) kindedAnnotationVars.get(forAnnotationType);
}
public Var getWithinAnnotationVar(UnresolvedType forAnnotationType) {
initializeWithinAnnotationVars();
return (Var) withinAnnotationVars.get(forAnnotationType);
}
public Var getWithinCodeAnnotationVar(UnresolvedType forAnnotationType) {
initializeWithinCodeAnnotationVars();
return (Var) withincodeAnnotationVars.get(forAnnotationType);
}
// reflective thisJoinPoint support
private BcelVar thisJoinPointVar = null;
private boolean isThisJoinPointLazy;
private int lazyTjpConsumers = 0;
private BcelVar thisJoinPointStaticPartVar = null;
// private BcelVar thisEnclosingJoinPointStaticPartVar = null;
public final Var getThisJoinPointStaticPartVar() {
return getThisJoinPointStaticPartBcelVar();
}
public final Var getThisEnclosingJoinPointStaticPartVar() {
return getThisEnclosingJoinPointStaticPartBcelVar();
}
public void requireThisJoinPoint(boolean hasGuardTest, boolean isAround) {
if (!isAround){
if (!hasGuardTest) {
isThisJoinPointLazy = false;
} else {
lazyTjpConsumers++;
}
}
// if (!hasGuardTest) {
// isThisJoinPointLazy = false;
// } else {
// lazyTjpConsumers++;
// }
if (thisJoinPointVar == null) {
thisJoinPointVar = genTempVar(UnresolvedType.forName("org.aspectj.lang.JoinPoint"));
}
}
public Var getThisJoinPointVar() {
requireThisJoinPoint(false,false);
return thisJoinPointVar;
}
void initializeThisJoinPoint() {
if (thisJoinPointVar == null) return;
if (isThisJoinPointLazy) {
isThisJoinPointLazy = checkLazyTjp();
}
if (isThisJoinPointLazy) {
appliedLazyTjpOptimization = true;
createThisJoinPoint(); // make sure any state needed is initialized, but throw the instructions out
if (lazyTjpConsumers == 1) return; // special case only one lazyTjpUser
InstructionFactory fact = getFactory();
InstructionList il = new InstructionList();
il.append(InstructionConstants.ACONST_NULL);
il.append(thisJoinPointVar.createStore(fact));
range.insert(il, Range.OutsideBefore);
} else {
appliedLazyTjpOptimization = false;
InstructionFactory fact = getFactory();
InstructionList il = createThisJoinPoint();
il.append(thisJoinPointVar.createStore(fact));
range.insert(il, Range.OutsideBefore);
}
}
private boolean checkLazyTjp() {
// check for around advice
for (Iterator i = mungers.iterator(); i.hasNext();) {
ShadowMunger munger = (ShadowMunger) i.next();
if (munger instanceof Advice) {
if ( ((Advice)munger).getKind() == AdviceKind.Around) {
if (munger.getSourceLocation()!=null) { // do we know enough to bother reporting?
if (world.getLint().canNotImplementLazyTjp.isEnabled()) {
world.getLint().canNotImplementLazyTjp.signal(
new String[] {toString()},
getSourceLocation(),
new ISourceLocation[] { munger.getSourceLocation() }
);
}
}
return false;
}
}
}
return true;
}
InstructionList loadThisJoinPoint() {
InstructionFactory fact = getFactory();
InstructionList il = new InstructionList();
if (isThisJoinPointLazy) {
// If we're lazy, build the join point right here.
il.append(createThisJoinPoint());
// Does someone else need it? If so, store it for later retrieval
if (lazyTjpConsumers > 1) {
il.append(thisJoinPointVar.createStore(fact));
InstructionHandle end = il.append(thisJoinPointVar.createLoad(fact));
il.insert(InstructionFactory.createBranchInstruction(Constants.IFNONNULL, end));
il.insert(thisJoinPointVar.createLoad(fact));
}
} else {
// If not lazy, its already been built and stored, just retrieve it
thisJoinPointVar.appendLoad(il, fact);
}
return il;
}
InstructionList createThisJoinPoint() {
InstructionFactory fact = getFactory();
InstructionList il = new InstructionList();
BcelVar staticPart = getThisJoinPointStaticPartBcelVar();
staticPart.appendLoad(il, fact);
if (hasThis()) {
((BcelVar)getThisVar()).appendLoad(il, fact);
} else {
il.append(new ACONST_NULL());
}
if (hasTarget()) {
((BcelVar)getTargetVar()).appendLoad(il, fact);
} else {
il.append(new ACONST_NULL());
}
switch(getArgCount()) {
case 0:
il.append(fact.createInvoke("org.aspectj.runtime.reflect.Factory",
"makeJP", LazyClassGen.tjpType,
new Type[] { LazyClassGen.staticTjpType,
Type.OBJECT, Type.OBJECT},
Constants.INVOKESTATIC));
break;
case 1:
((BcelVar)getArgVar(0)).appendLoadAndConvert(il, fact, world.getCoreType(ResolvedType.OBJECT));
il.append(fact.createInvoke("org.aspectj.runtime.reflect.Factory",
"makeJP", LazyClassGen.tjpType,
new Type[] { LazyClassGen.staticTjpType,
Type.OBJECT, Type.OBJECT, Type.OBJECT},
Constants.INVOKESTATIC));
break;
case 2:
((BcelVar)getArgVar(0)).appendLoadAndConvert(il, fact, world.getCoreType(ResolvedType.OBJECT));
((BcelVar)getArgVar(1)).appendLoadAndConvert(il, fact, world.getCoreType(ResolvedType.OBJECT));
il.append(fact.createInvoke("org.aspectj.runtime.reflect.Factory",
"makeJP", LazyClassGen.tjpType,
new Type[] { LazyClassGen.staticTjpType,
Type.OBJECT, Type.OBJECT, Type.OBJECT, Type.OBJECT},
Constants.INVOKESTATIC));
break;
default:
il.append(makeArgsObjectArray());
il.append(fact.createInvoke("org.aspectj.runtime.reflect.Factory",
"makeJP", LazyClassGen.tjpType,
new Type[] { LazyClassGen.staticTjpType,
Type.OBJECT, Type.OBJECT, new ArrayType(Type.OBJECT, 1)},
Constants.INVOKESTATIC));
break;
}
return il;
}
/**
* Get the Var for the jpStaticPart
* @return
*/
public BcelVar getThisJoinPointStaticPartBcelVar() {
return getThisJoinPointStaticPartBcelVar(false);
}
/**
* Get the Var for the xxxxJpStaticPart, xxx = this or enclosing
* @param isEnclosingJp true to have the enclosingJpStaticPart
* @return
*/
public BcelVar getThisJoinPointStaticPartBcelVar(final boolean isEnclosingJp) {
if (thisJoinPointStaticPartVar == null) {
Field field = getEnclosingClass().getTjpField(this, isEnclosingJp);
ResolvedType sjpType = null;
if (world.isTargettingAspectJRuntime12()) { // TAG:SUPPORTING12: We didn't have different jpsp types in 1.2
sjpType = world.getCoreType(UnresolvedType.forName("org.aspectj.lang.JoinPoint$StaticPart"));
} else {
sjpType = isEnclosingJp?
world.getCoreType(UnresolvedType.forName("org.aspectj.lang.JoinPoint$EnclosingStaticPart")):
world.getCoreType(UnresolvedType.forName("org.aspectj.lang.JoinPoint$StaticPart"));
}
thisJoinPointStaticPartVar = new BcelFieldRef(
sjpType,
getEnclosingClass().getClassName(),
field.getName());
// getEnclosingClass().warnOnAddedStaticInitializer(this,munger.getSourceLocation());
}
return thisJoinPointStaticPartVar;
}
/**
* Get the Var for the enclosingJpStaticPart
* @return
*/
public BcelVar getThisEnclosingJoinPointStaticPartBcelVar() {
if (enclosingShadow == null) {
// the enclosing of an execution is itself
return getThisJoinPointStaticPartBcelVar(true);
} else {
return ((BcelShadow)enclosingShadow).getThisJoinPointStaticPartBcelVar(true);
}
}
//??? need to better understand all the enclosing variants
public Member getEnclosingCodeSignature() {
if (getKind().isEnclosingKind()) {
return getSignature();
} else if (getKind() == Shadow.PreInitialization) {
// PreInit doesn't enclose code but its signature
// is correctly the signature of the ctor.
return getSignature();
} else if (enclosingShadow == null) {
return getEnclosingMethod().getMemberView();
} else {
return enclosingShadow.getSignature();
}
}
private InstructionList makeArgsObjectArray() {
InstructionFactory fact = getFactory();
BcelVar arrayVar = genTempVar(UnresolvedType.OBJECTARRAY);
final InstructionList il = new InstructionList();
int alen = getArgCount() ;
il.append(Utility.createConstant(fact, alen));
il.append((Instruction)fact.createNewArray(Type.OBJECT, (short)1));
arrayVar.appendStore(il, fact);
int stateIndex = 0;
for (int i = 0, len = getArgCount(); i<len; i++) {
arrayVar.appendConvertableArrayStore(il, fact, stateIndex, (BcelVar)getArgVar(i));
stateIndex++;
}
arrayVar.appendLoad(il, fact);
return il;
}
// ---- initializing var tables
/* initializing this is doesn't do anything, because this
* is protected from side-effects, so we don't need to copy its location
*/
private void initializeThisVar() {
if (thisVar != null) return;
thisVar = new BcelVar(getThisType().resolve(world), 0);
thisVar.setPositionInAroundState(0);
}
public void initializeTargetVar() {
InstructionFactory fact = getFactory();
if (targetVar != null) return;
if (getKind().isTargetSameAsThis()) {
if (hasThis()) initializeThisVar();
targetVar = thisVar;
} else {
initializeArgVars(); // gotta pop off the args before we find the target
UnresolvedType type = getTargetType();
type = ensureTargetTypeIsCorrect(type);
targetVar = genTempVar(type, "ajc$target");
range.insert(targetVar.createStore(fact), Range.OutsideBefore);
targetVar.setPositionInAroundState(hasThis() ? 1 : 0);
}
}
/* PR 72528
* This method double checks the target type under certain conditions. The Java 1.4
* compilers seem to take calls to clone methods on array types and create bytecode that
* looks like clone is being called on Object. If we advise a clone call with around
* advice we extract the call into a helper method which we can then refer to. Because the
* type in the bytecode for the call to clone is Object we create a helper method with
* an Object parameter - this is not correct as we have lost the fact that the actual
* type is an array type. If we don't do the check below we will create code that fails
* java verification. This method checks for the peculiar set of conditions and if they
* are true, it has a sneak peek at the code before the call to see what is on the stack.
*/
public UnresolvedType ensureTargetTypeIsCorrect(UnresolvedType tx) {
Member msig = getSignature();
if (msig.getArity()==0 &&
getKind() == MethodCall &&
msig.getName().charAt(0) == 'c' &&
tx.equals(ResolvedType.OBJECT) &&
msig.getReturnType().equals(ResolvedType.OBJECT) &&
msig.getName().equals("clone")) {
// Lets go back through the code from the start of the shadow
InstructionHandle searchPtr = range.getStart().getPrev();
while (Range.isRangeHandle(searchPtr) ||
searchPtr.getInstruction() instanceof StoreInstruction) { // ignore this instruction - it doesnt give us the info we want
searchPtr = searchPtr.getPrev();
}
// A load instruction may tell us the real type of what the clone() call is on
if (searchPtr.getInstruction() instanceof LoadInstruction) {
LoadInstruction li = (LoadInstruction)searchPtr.getInstruction();
li.getIndex();
LocalVariableTag lvt = LazyMethodGen.getLocalVariableTag(searchPtr,li.getIndex());
if (lvt!=null) return UnresolvedType.forSignature(lvt.getType());
}
// A field access instruction may tell us the real type of what the clone() call is on
if (searchPtr.getInstruction() instanceof FieldInstruction) {
FieldInstruction si = (FieldInstruction)searchPtr.getInstruction();
Type t = si.getFieldType(getEnclosingClass().getConstantPoolGen());
return BcelWorld.fromBcel(t);
}
// A new array instruction obviously tells us it is an array type !
if (searchPtr.getInstruction() instanceof ANEWARRAY) {
//ANEWARRAY ana = (ANEWARRAY)searchPoint.getInstruction();
//Type t = ana.getType(getEnclosingClass().getConstantPoolGen());
// Just use a standard java.lang.object array - that will work fine
return BcelWorld.fromBcel(new ArrayType(Type.OBJECT,1));
}
// A multi new array instruction obviously tells us it is an array type !
if (searchPtr.getInstruction() instanceof MULTIANEWARRAY) {
MULTIANEWARRAY ana = (MULTIANEWARRAY)searchPtr.getInstruction();
// Type t = ana.getType(getEnclosingClass().getConstantPoolGen());
// t = new ArrayType(t,ana.getDimensions());
// Just use a standard java.lang.object array - that will work fine
return BcelWorld.fromBcel(new ArrayType(Type.OBJECT,ana.getDimensions()));
}
throw new BCException("Can't determine real target of clone() when processing instruction "+
searchPtr.getInstruction()+". Perhaps avoid selecting clone with your pointcut?");
}
return tx;
}
public void initializeArgVars() {
if (argVars != null) return;
InstructionFactory fact = getFactory();
int len = getArgCount();
argVars = new BcelVar[len];
int positionOffset = (hasTarget() ? 1 : 0) +
((hasThis() && !getKind().isTargetSameAsThis()) ? 1 : 0);
if (getKind().argsOnStack()) {
// we move backwards because we're popping off the stack
for (int i = len - 1; i >= 0; i--) {
UnresolvedType type = getArgType(i);
BcelVar tmp = genTempVar(type, "ajc$arg" + i);
range.insert(tmp.createStore(getFactory()), Range.OutsideBefore);
int position = i;
position += positionOffset;
tmp.setPositionInAroundState(position);
argVars[i] = tmp;
}
} else {
int index = 0;
if (arg0HoldsThis()) index++;
for (int i = 0; i < len; i++) {
UnresolvedType type = getArgType(i);
BcelVar tmp = genTempVar(type, "ajc$arg" + i);
range.insert(tmp.createCopyFrom(fact, index), Range.OutsideBefore);
argVars[i] = tmp;
int position = i;
position += positionOffset;
// System.out.println("set position: " + tmp + ", " + position + " in " + this);
// System.out.println(" hasThis: " + hasThis() + ", hasTarget: " + hasTarget());
tmp.setPositionInAroundState(position);
index += type.getSize();
}
}
}
public void initializeForAroundClosure() {
initializeArgVars();
if (hasTarget()) initializeTargetVar();
if (hasThis()) initializeThisVar();
// System.out.println("initialized: " + this + " thisVar = " + thisVar);
}
public void initializeThisAnnotationVars() {
if (thisAnnotationVars != null) return;
thisAnnotationVars = new HashMap();
// populate..
}
public void initializeTargetAnnotationVars() {
if (targetAnnotationVars != null) return;
if (getKind().isTargetSameAsThis()) {
if (hasThis()) initializeThisAnnotationVars();
targetAnnotationVars = thisAnnotationVars;
} else {
targetAnnotationVars = new HashMap();
ResolvedType[] rtx = this.getTargetType().resolve(world).getAnnotationTypes(); // what about annotations we havent gotten yet but we will get in subclasses?
for (int i = 0; i < rtx.length; i++) {
ResolvedType typeX = rtx[i];
targetAnnotationVars.put(typeX,new TypeAnnotationAccessVar(typeX,(BcelVar)getTargetVar()));
}
// populate.
}
}
public void initializeArgAnnotationVars() {
if (argAnnotationVars != null) return;
int numArgs = getArgCount();
argAnnotationVars = new Map[numArgs];
for (int i = 0; i < argAnnotationVars.length; i++) {
argAnnotationVars[i] = new HashMap();
//FIXME asc just delete this logic - we always build the Var on demand, as we don't know at weave time
// what the full set of annotations could be (due to static/dynamic type differences...)
}
}
protected Member getRelevantMember(Member foundMember, Member relevantMember, ResolvedType relevantType){
if (foundMember != null){
return foundMember;
}
foundMember = getSignature().resolve(world);
if (foundMember == null && relevantMember != null) {
foundMember = relevantType.lookupMemberWithSupersAndITDs(relevantMember);
}
// check the ITD'd dooberries
List mungers = relevantType.resolve(world).getInterTypeMungers();
for (Iterator iter = mungers.iterator(); iter.hasNext();) {
BcelTypeMunger typeMunger = (BcelTypeMunger) iter.next();
if (typeMunger.getMunger() instanceof NewMethodTypeMunger ||
typeMunger.getMunger() instanceof NewConstructorTypeMunger) {
ResolvedMember fakerm = typeMunger.getSignature();
if (fakerm.getName().equals(getSignature().getName()) &&
fakerm.getParameterSignature().equals(getSignature().getParameterSignature())){
if (foundMember.getKind()==ResolvedMember.CONSTRUCTOR){
foundMember = AjcMemberMaker.interConstructor(
relevantType,
(ResolvedMember)foundMember,
typeMunger.getAspectType());
} else {
foundMember = AjcMemberMaker.interMethod((ResolvedMember)foundMember,
typeMunger.getAspectType(), false);
}
// in the above.. what about if it's on an Interface? Can that happen?
// then the last arg of the above should be true
return foundMember;
}
}
}
return foundMember;
}
protected ResolvedType [] getAnnotations(Member foundMember, Member relevantMember, ResolvedType relevantType){
if (foundMember == null){
// check the ITD'd dooberries
List mungers = relevantType.resolve(world).getInterTypeMungers();
for (Iterator iter = mungers.iterator(); iter.hasNext();) {
BcelTypeMunger typeMunger = (BcelTypeMunger) iter.next();
if (typeMunger.getMunger() instanceof NewMethodTypeMunger ||
typeMunger.getMunger() instanceof NewConstructorTypeMunger) {
ResolvedMember fakerm = typeMunger.getSignature();
//if (fakerm.hasAnnotations())
ResolvedMember ajcMethod = (getSignature().getKind()==ResolvedMember.CONSTRUCTOR?
AjcMemberMaker.postIntroducedConstructor(typeMunger.getAspectType(),fakerm.getDeclaringType(),fakerm.getParameterTypes()):
AjcMemberMaker.interMethodDispatcher(fakerm,typeMunger.getAspectType()));
//AjcMemberMaker.interMethodBody(fakerm,typeMunger.getAspectType()));
ResolvedMember rmm = findMethod(typeMunger.getAspectType(),ajcMethod);
if (fakerm.getName().equals(getSignature().getName()) &&
fakerm.getParameterSignature().equals(getSignature().getParameterSignature())) {
relevantType = typeMunger.getAspectType();
foundMember = rmm;
return foundMember.getAnnotationTypes();
}
}
}
// didn't find in ITDs, look in supers
foundMember = relevantType.lookupMemberWithSupersAndITDs(relevantMember);
if (foundMember == null) {
throw new IllegalStateException("Couldn't find member " + relevantMember + " for type " + relevantType);
}
}
return foundMember.getAnnotationTypes();
}
public void initializeKindedAnnotationVars() {
if (kindedAnnotationVars != null) return;
kindedAnnotationVars = new HashMap();
// by determining what "kind" of shadow we are, we can find out the
// annotations on the appropriate element (method, field, constructor, type).
// Then create one BcelVar entry in the map for each annotation, keyed by
// annotation type (UnresolvedType).
// FIXME asc Refactor this code, there is duplication
ResolvedType[] annotations = null;
Member relevantMember = getSignature();
ResolvedType relevantType = relevantMember.getDeclaringType().resolve(world);
if (relevantType.isRawType() || relevantType.isParameterizedType()) relevantType = relevantType.getGenericType();
if (getKind() == Shadow.StaticInitialization) {
annotations = relevantType.resolve(world).getAnnotationTypes();
} else if (getKind() == Shadow.MethodCall || getKind() == Shadow.ConstructorCall) {
Member foundMember = findMethod2(relevantType.resolve(world).getDeclaredMethods(),getSignature());
annotations = getAnnotations(foundMember, relevantMember, relevantType);
relevantMember = getRelevantMember(foundMember,relevantMember,relevantType);
relevantType = relevantMember.getDeclaringType().resolve(world);
} else if (getKind() == Shadow.FieldSet || getKind() == Shadow.FieldGet) {
relevantMember = findField(relevantType.getDeclaredFields(),getSignature());
if (relevantMember==null) {
// check the ITD'd dooberries
List mungers = relevantType.resolve(world).getInterTypeMungers();
for (Iterator iter = mungers.iterator(); iter.hasNext();) {
BcelTypeMunger typeMunger = (BcelTypeMunger) iter.next();
if (typeMunger.getMunger() instanceof NewFieldTypeMunger) {
ResolvedMember fakerm = typeMunger.getSignature();
//if (fakerm.hasAnnotations())
ResolvedMember ajcMethod = AjcMemberMaker.interFieldInitializer(fakerm,typeMunger.getAspectType());
ResolvedMember rmm = findMethod(typeMunger.getAspectType(),ajcMethod);
if (fakerm.equals(getSignature())) {
relevantType = typeMunger.getAspectType();
relevantMember = rmm;
}
}
}
}
annotations = relevantMember.getAnnotationTypes();
} else if (getKind() == Shadow.MethodExecution || getKind() == Shadow.ConstructorExecution ||
getKind() == Shadow.AdviceExecution) {
//ResolvedMember rm[] = relevantType.getDeclaredMethods();
Member foundMember = findMethod2(relevantType.getDeclaredMethods(),getSignature());
annotations = getAnnotations(foundMember, relevantMember, relevantType);
relevantMember = foundMember;
relevantMember = getRelevantMember(foundMember, relevantMember,relevantType);
} else if (getKind() == Shadow.ExceptionHandler) {
relevantType = getSignature().getParameterTypes()[0].resolve(world);
annotations = relevantType.getAnnotationTypes();
} else if (getKind() == Shadow.PreInitialization || getKind() == Shadow.Initialization) {
ResolvedMember found = findMethod2(relevantType.getDeclaredMethods(),getSignature());
annotations = found.getAnnotationTypes();
}
if (annotations == null) {
// We can't have recognized the shadow - should blow up now to be on the safe side
throw new BCException("Couldn't discover annotations for shadow: "+getKind());
}
for (int i = 0; i < annotations.length; i++) {
ResolvedType aTX = annotations[i];
KindedAnnotationAccessVar kaav = new KindedAnnotationAccessVar(getKind(),aTX.resolve(world),relevantType,relevantMember);
kindedAnnotationVars.put(aTX,kaav);
}
}
//FIXME asc whats the real diff between this one and the version in findMethod()?
ResolvedMember findMethod2(ResolvedMember rm[], Member sig) {
ResolvedMember found = null;
// String searchString = getSignature().getName()+getSignature().getParameterSignature();
for (int i = 0; i < rm.length && found==null; i++) {
ResolvedMember member = rm[i];
if (member.getName().equals(sig.getName()) && member.getParameterSignature().equals(sig.getParameterSignature()))
found = member;
}
return found;
}
private ResolvedMember findMethod(ResolvedType aspectType, ResolvedMember ajcMethod) {
ResolvedMember decMethods[] = aspectType.getDeclaredMethods();
for (int i = 0; i < decMethods.length; i++) {
ResolvedMember member = decMethods[i];
if (member.equals(ajcMethod)) return member;
}
return null;
}
private ResolvedMember findField(ResolvedMember[] members,Member lookingFor) {
for (int i = 0; i < members.length; i++) {
ResolvedMember member = members[i];
if ( member.getName().equals(getSignature().getName()) &&
member.getType().equals(getSignature().getType())) {
return member;
}
}
return null;
}
public void initializeWithinAnnotationVars() {
if (withinAnnotationVars != null) return;
withinAnnotationVars = new HashMap();
ResolvedType[] annotations = getEnclosingType().resolve(world).getAnnotationTypes();
for (int i = 0; i < annotations.length; i++) {
ResolvedType ann = annotations[i];
Kind k = Shadow.StaticInitialization;
withinAnnotationVars.put(ann,new KindedAnnotationAccessVar(k,ann,getEnclosingType(),null));
}
}
public void initializeWithinCodeAnnotationVars() {
if (withincodeAnnotationVars != null) return;
withincodeAnnotationVars = new HashMap();
// For some shadow we are interested in annotations on the method containing that shadow.
ResolvedType[] annotations = getEnclosingMethod().getMemberView().getAnnotationTypes();
for (int i = 0; i < annotations.length; i++) {
ResolvedType ann = annotations[i];
Kind k = (getEnclosingMethod().getMemberView().getKind()==Member.CONSTRUCTOR?
Shadow.ConstructorExecution:Shadow.MethodExecution);
withincodeAnnotationVars.put(ann,
new KindedAnnotationAccessVar(k,ann,getEnclosingType(),getEnclosingCodeSignature()));
}
}
// ---- weave methods
void weaveBefore(BcelAdvice munger) {
range.insert(
munger.getAdviceInstructions(this, null, range.getRealStart()),
Range.InsideBefore);
}
public void weaveAfter(BcelAdvice munger) {
weaveAfterThrowing(munger, UnresolvedType.THROWABLE);
weaveAfterReturning(munger);
}
/**
* We guarantee that the return value is on the top of the stack when
* munger.getAdviceInstructions() will be run
* (Unless we have a void return type in which case there's nothing)
*/
public void weaveAfterReturning(BcelAdvice munger) {
// InstructionFactory fact = getFactory();
List returns = new ArrayList();
Instruction ret = null;
for (InstructionHandle ih = range.getStart(); ih != range.getEnd(); ih = ih.getNext()) {
if (ih.getInstruction() instanceof ReturnInstruction) {
returns.add(ih);
ret = Utility.copyInstruction(ih.getInstruction());
}
}
InstructionList retList;
InstructionHandle afterAdvice;
if (ret != null) {
retList = new InstructionList(ret);
afterAdvice = retList.getStart();
} else /* if (munger.hasDynamicTests()) */ {
/*
*
27: getstatic #72; //Field ajc$cflowCounter$0:Lorg/aspectj/runtime/internal/CFlowCounter;
30: invokevirtual #87; //Method org/aspectj/runtime/internal/CFlowCounter.dec:()V
33: aload 6
35: athrow
36: nop
37: getstatic #72; //Field ajc$cflowCounter$0:Lorg/aspectj/runtime/internal/CFlowCounter;
40: invokevirtual #87; //Method org/aspectj/runtime/internal/CFlowCounter.dec:()V
43: d2i
44: invokespecial #23; //Method java/lang/Object."<init>":()V
*/
retList = new InstructionList(InstructionConstants.NOP);
afterAdvice = retList.getStart();
// } else {
// retList = new InstructionList();
// afterAdvice = null;
}
InstructionList advice = new InstructionList();
BcelVar tempVar = null;
if (munger.hasExtraParameter()) {
UnresolvedType tempVarType = getReturnType();
if (tempVarType.equals(ResolvedType.VOID)) {
tempVar = genTempVar(UnresolvedType.OBJECT);
advice.append(InstructionConstants.ACONST_NULL);
tempVar.appendStore(advice, getFactory());
} else {
tempVar = genTempVar(tempVarType);
advice.append(InstructionFactory.createDup(tempVarType.getSize()));
tempVar.appendStore(advice, getFactory());
}
}
advice.append(munger.getAdviceInstructions(this, tempVar, afterAdvice));
if (ret != null) {
InstructionHandle gotoTarget = advice.getStart();
for (Iterator i = returns.iterator(); i.hasNext();) {
InstructionHandle ih = (InstructionHandle) i.next();
Utility.replaceInstruction(
ih,
InstructionFactory.createBranchInstruction(
Constants.GOTO,
gotoTarget),
enclosingMethod);
}
range.append(advice);
range.append(retList);
} else {
range.append(advice);
range.append(retList);
}
}
public void weaveAfterThrowing(BcelAdvice munger, UnresolvedType catchType) {
// a good optimization would be not to generate anything here
// if the shadow is GUARANTEED empty (i.e., there's NOTHING, not even
// a shadow, inside me).
if (getRange().getStart().getNext() == getRange().getEnd()) return;
InstructionFactory fact = getFactory();
InstructionList handler = new InstructionList();
BcelVar exceptionVar = genTempVar(catchType);
exceptionVar.appendStore(handler, fact);
// pr62642
// I will now jump through some firey BCEL hoops to generate a trivial bit of code:
// if (exc instanceof ExceptionInInitializerError)
// throw (ExceptionInInitializerError)exc;
if (this.getEnclosingMethod().getName().equals("<clinit>")) {
ResolvedType eiieType = world.resolve("java.lang.ExceptionInInitializerError");
ObjectType eiieBcelType = (ObjectType)BcelWorld.makeBcelType(eiieType);
InstructionList ih = new InstructionList(InstructionConstants.NOP);
handler.append(exceptionVar.createLoad(fact));
handler.append(fact.createInstanceOf(eiieBcelType));
BranchInstruction bi =
InstructionFactory.createBranchInstruction(Constants.IFEQ,ih.getStart());
handler.append(bi);
handler.append(exceptionVar.createLoad(fact));
handler.append(fact.createCheckCast(eiieBcelType));
handler.append(InstructionConstants.ATHROW);
handler.append(ih);
}
InstructionList endHandler = new InstructionList(
exceptionVar.createLoad(fact));
handler.append(munger.getAdviceInstructions(this, exceptionVar, endHandler.getStart()));
handler.append(endHandler);
handler.append(InstructionConstants.ATHROW);
InstructionHandle handlerStart = handler.getStart();
if (isFallsThrough()) {
InstructionHandle jumpTarget = handler.append(InstructionConstants.NOP);
handler.insert(InstructionFactory.createBranchInstruction(Constants.GOTO, jumpTarget));
}
InstructionHandle protectedEnd = handler.getStart();
range.insert(handler, Range.InsideAfter);
enclosingMethod.addExceptionHandler(range.getStart().getNext(), protectedEnd.getPrev(),
handlerStart, (ObjectType)BcelWorld.makeBcelType(catchType), //???Type.THROWABLE,
// high priority if our args are on the stack
getKind().hasHighPriorityExceptions());
}
//??? this shares a lot of code with the above weaveAfterThrowing
//??? would be nice to abstract that to say things only once
public void weaveSoftener(BcelAdvice munger, UnresolvedType catchType) {
// a good optimization would be not to generate anything here
// if the shadow is GUARANTEED empty (i.e., there's NOTHING, not even
// a shadow, inside me).
if (getRange().getStart().getNext() == getRange().getEnd()) return;
InstructionFactory fact = getFactory();
InstructionList handler = new InstructionList();
InstructionList rtExHandler = new InstructionList();
BcelVar exceptionVar = genTempVar(catchType);
handler.append(fact.createNew(NameMangler.SOFT_EXCEPTION_TYPE));
handler.append(InstructionFactory.createDup(1));
handler.append(exceptionVar.createLoad(fact));
handler.append(fact.createInvoke(NameMangler.SOFT_EXCEPTION_TYPE, "<init>",
Type.VOID, new Type[] { Type.THROWABLE }, Constants.INVOKESPECIAL)); //??? special
handler.append(InstructionConstants.ATHROW);
// ENH 42737
exceptionVar.appendStore(rtExHandler, fact);
// aload_1
rtExHandler.append(exceptionVar.createLoad(fact));
// instanceof class java/lang/RuntimeException
rtExHandler.append(fact.createInstanceOf(new ObjectType("java.lang.RuntimeException")));
// ifeq go to new SOFT_EXCEPTION_TYPE instruction
rtExHandler.append(InstructionFactory.createBranchInstruction(Constants.IFEQ,handler.getStart()));
// aload_1
rtExHandler.append(exceptionVar.createLoad(fact));
// athrow
rtExHandler.append(InstructionFactory.ATHROW);
InstructionHandle handlerStart = rtExHandler.getStart();
if (isFallsThrough()) {
InstructionHandle jumpTarget = range.getEnd();//handler.append(fact.NOP);
rtExHandler.insert(InstructionFactory.createBranchInstruction(Constants.GOTO, jumpTarget));
}
rtExHandler.append(handler);
InstructionHandle protectedEnd = rtExHandler.getStart();
range.insert(rtExHandler, Range.InsideAfter);
enclosingMethod.addExceptionHandler(range.getStart().getNext(), protectedEnd.getPrev(),
handlerStart, (ObjectType)BcelWorld.makeBcelType(catchType),
// high priority if our args are on the stack
getKind().hasHighPriorityExceptions());
}
public void weavePerObjectEntry(final BcelAdvice munger, final BcelVar onVar) {
final InstructionFactory fact = getFactory();
InstructionList entryInstructions = new InstructionList();
InstructionList entrySuccessInstructions = new InstructionList();
onVar.appendLoad(entrySuccessInstructions, fact);
entrySuccessInstructions.append(
Utility.createInvoke(fact, world,
AjcMemberMaker.perObjectBind(munger.getConcreteAspect())));
InstructionList testInstructions =
munger.getTestInstructions(this, entrySuccessInstructions.getStart(),
range.getRealStart(),
entrySuccessInstructions.getStart());
entryInstructions.append(testInstructions);
entryInstructions.append(entrySuccessInstructions);
range.insert(entryInstructions, Range.InsideBefore);
}
// PTWIMPL Create static initializer to call the aspect factory
/**
* Causes the aspect instance to be *set* for later retrievable through localAspectof()/aspectOf()
*/
public void weavePerTypeWithinAspectInitialization(final BcelAdvice munger,UnresolvedType t) {
if (t.resolve(world).isInterface()) return; // Don't initialize statics in
final InstructionFactory fact = getFactory();
InstructionList entryInstructions = new InstructionList();
InstructionList entrySuccessInstructions = new InstructionList();
BcelWorld.getBcelObjectType(munger.getConcreteAspect());
String aspectname = munger.getConcreteAspect().getName();
String ptwField = NameMangler.perTypeWithinFieldForTarget(munger.getConcreteAspect());
entrySuccessInstructions.append(new PUSH(fact.getConstantPool(),t.getName()));
entrySuccessInstructions.append(fact.createInvoke(aspectname,"ajc$createAspectInstance",new ObjectType(aspectname),
new Type[]{new ObjectType("java.lang.String")},Constants.INVOKESTATIC));
entrySuccessInstructions.append(fact.createPutStatic(t.getName(),ptwField,
new ObjectType(aspectname)));
entryInstructions.append(entrySuccessInstructions);
range.insert(entryInstructions, Range.InsideBefore);
}
public void weaveCflowEntry(final BcelAdvice munger, final Member cflowField) {
final boolean isPer = munger.getKind() == AdviceKind.PerCflowBelowEntry ||
munger.getKind() == AdviceKind.PerCflowEntry;
final Type objectArrayType = new ArrayType(Type.OBJECT, 1);
final InstructionFactory fact = getFactory();
final BcelVar testResult = genTempVar(ResolvedType.BOOLEAN);
InstructionList entryInstructions = new InstructionList();
{
InstructionList entrySuccessInstructions = new InstructionList();
if (munger.hasDynamicTests()) {
entryInstructions.append(Utility.createConstant(fact, 0));
testResult.appendStore(entryInstructions, fact);
entrySuccessInstructions.append(Utility.createConstant(fact, 1));
testResult.appendStore(entrySuccessInstructions, fact);
}
if (isPer) {
entrySuccessInstructions.append(
fact.createInvoke(munger.getConcreteAspect().getName(),
NameMangler.PERCFLOW_PUSH_METHOD,
Type.VOID,
new Type[] { },
Constants.INVOKESTATIC));
} else {
BcelVar[] cflowStateVars = munger.getExposedStateAsBcelVars(false);
if (cflowStateVars.length == 0) {
// This should be getting managed by a counter - lets make sure.
if (!cflowField.getType().getName().endsWith("CFlowCounter"))
throw new RuntimeException("Incorrectly attempting counter operation on stacked cflow");
entrySuccessInstructions.append(
Utility.createGet(fact, cflowField));
//arrayVar.appendLoad(entrySuccessInstructions, fact);
entrySuccessInstructions.append(fact.createInvoke(NameMangler.CFLOW_COUNTER_TYPE,"inc",Type.VOID,new Type[] { },Constants.INVOKEVIRTUAL));
} else {
BcelVar arrayVar = genTempVar(UnresolvedType.OBJECTARRAY);
int alen = cflowStateVars.length;
entrySuccessInstructions.append(Utility.createConstant(fact, alen));
entrySuccessInstructions.append(
(Instruction) fact.createNewArray(Type.OBJECT, (short) 1));
arrayVar.appendStore(entrySuccessInstructions, fact);
for (int i = 0; i < alen; i++) {
arrayVar.appendConvertableArrayStore(
entrySuccessInstructions,
fact,
i,
cflowStateVars[i]);
}
entrySuccessInstructions.append(
Utility.createGet(fact, cflowField));
arrayVar.appendLoad(entrySuccessInstructions, fact);
entrySuccessInstructions.append(
fact.createInvoke(NameMangler.CFLOW_STACK_TYPE, "push", Type.VOID,
new Type[] { objectArrayType },
Constants.INVOKEVIRTUAL));
}
}
InstructionList testInstructions =
munger.getTestInstructions(this, entrySuccessInstructions.getStart(),
range.getRealStart(),
entrySuccessInstructions.getStart());
entryInstructions.append(testInstructions);
entryInstructions.append(entrySuccessInstructions);
}
// this is the same for both per and non-per
weaveAfter(new BcelAdvice(null, null, null, 0, 0, 0, null, null) {
public InstructionList getAdviceInstructions(
BcelShadow s,
BcelVar extraArgVar,
InstructionHandle ifNoAdvice) {
InstructionList exitInstructions = new InstructionList();
if (munger.hasDynamicTests()) {
testResult.appendLoad(exitInstructions, fact);
exitInstructions.append(
InstructionFactory.createBranchInstruction(
Constants.IFEQ,
ifNoAdvice));
}
exitInstructions.append(Utility.createGet(fact, cflowField));
if (munger.getKind() != AdviceKind.PerCflowEntry &&
munger.getKind() != AdviceKind.PerCflowBelowEntry &&
munger.getExposedStateAsBcelVars(false).length==0) {
exitInstructions
.append(
fact
.createInvoke(
NameMangler.CFLOW_COUNTER_TYPE,
"dec",
Type.VOID,
new Type[] {
}, Constants.INVOKEVIRTUAL));
} else {
exitInstructions
.append(
fact
.createInvoke(
NameMangler.CFLOW_STACK_TYPE,
"pop",
Type.VOID,
new Type[] {
}, Constants.INVOKEVIRTUAL));
}
return exitInstructions;
}
});
range.insert(entryInstructions, Range.InsideBefore);
}
public void weaveAroundInline(
BcelAdvice munger,
boolean hasDynamicTest)
{
/* Implementation notes:
*
* AroundInline still extracts the instructions of the original shadow into
* an extracted method. This allows inlining of even that advice that doesn't
* call proceed or calls proceed more than once.
*
* It extracts the instructions of the original shadow into a method.
*
* Then it extracts the instructions of the advice into a new method defined on
* this enclosing class. This new method can then be specialized as below.
*
* Then it searches in the instructions of the advice for any call to the
* proceed method.
*
* At such a call, there is stuff on the stack representing the arguments to
* proceed. Pop these into the frame.
*
* Now build the stack for the call to the extracted method, taking values
* either from the join point state or from the new frame locs from proceed.
* Now call the extracted method. The right return value should be on the
* stack, so no cast is necessary.
*
* If only one call to proceed is made, we can re-inline the original shadow.
* We are not doing that presently.
*
* If the body of the advice can be determined to not alter the stack, or if
* this shadow doesn't care about the stack, i.e. method-execution, then the
* new method for the advice can also be re-lined. We are not doing that
* presently.
*/
// !!! THIS BLOCK OF CODE SHOULD BE IN A METHOD CALLED weaveAround(...);
Member mungerSig = munger.getSignature();
//Member originalSig = mungerSig; // If mungerSig is on a parameterized type, originalSig is the member on the generic type
if (mungerSig instanceof ResolvedMember) {
ResolvedMember rm = (ResolvedMember)mungerSig;
if (rm.hasBackingGenericMember()) mungerSig = rm.getBackingGenericMember();
}
ResolvedType declaringType = world.resolve(mungerSig.getDeclaringType(),true);
if (declaringType.isMissing()) {
world.getLint().cantFindType.signal(
new String[] {WeaverMessages.format(WeaverMessages.CANT_FIND_TYPE_DURING_AROUND_WEAVE,declaringType.getClassName())},
getSourceLocation(),
new ISourceLocation[]{ munger.getSourceLocation()}
);
// IMessage msg = new Message(
// WeaverMessages.format(WeaverMessages.CANT_FIND_TYPE_DURING_AROUND_WEAVE,declaringType.getClassName()),
// "",IMessage.ERROR,getSourceLocation(),null,
// new ISourceLocation[]{ munger.getSourceLocation()});
// world.getMessageHandler().handleMessage(msg);
}
//??? might want some checks here to give better errors
ResolvedType rt = (declaringType.isParameterizedType()?declaringType.getGenericType():declaringType);
BcelObjectType ot = BcelWorld.getBcelObjectType(rt);
// if (ot==null) {
// world.getMessageHandler().handleMessage(
// MessageUtil.warn("Unable to find modifiable delegate for the aspect '"+rt.getName()+"' containing around advice - cannot implement inlining",munger.getSourceLocation()));
// weaveAroundClosure(munger, hasDynamicTest);
// return;
// }
LazyMethodGen adviceMethod = ot.getLazyClassGen().getLazyMethodGen(mungerSig);
if (!adviceMethod.getCanInline()) {
weaveAroundClosure(munger, hasDynamicTest);
return;
}
// specific test for @AJ proceedInInners
if (munger.getConcreteAspect().isAnnotationStyleAspect()) {
// if we can't find one proceed()
// we suspect that the call is happening in an inner class
// so we don't inline it.
// Note: for code style, this is done at Aspect compilation time.
boolean canSeeProceedPassedToOther = false;
InstructionHandle curr = adviceMethod.getBody().getStart();
InstructionHandle end = adviceMethod.getBody().getEnd();
ConstantPoolGen cpg = adviceMethod.getEnclosingClass().getConstantPoolGen();
while (curr != end) {
InstructionHandle next = curr.getNext();
Instruction inst = curr.getInstruction();
if ((inst instanceof InvokeInstruction)
&& ((InvokeInstruction)inst).getSignature(cpg).indexOf("Lorg/aspectj/lang/ProceedingJoinPoint;") > 0) {
// we may want to refine to exclude stuff returning jp ?
// does code style skip inline if i write dump(thisJoinPoint) ?
canSeeProceedPassedToOther = true;// we see one pjp passed around - dangerous
break;
}
curr = next;
}
if (canSeeProceedPassedToOther) {
// remember this decision to avoid re-analysis
adviceMethod.setCanInline(false);
weaveAroundClosure(munger, hasDynamicTest);
return;
}
}
// We can't inline around methods if they have around advice on them, this
// is because the weaving will extract the body and hence the proceed call.
//??? should consider optimizations to recognize simple cases that don't require body extraction
enclosingMethod.setCanInline(false);
// start by exposing various useful things into the frame
final InstructionFactory fact = getFactory();
// now generate the aroundBody method
LazyMethodGen extractedMethod =
extractMethod(
NameMangler.aroundCallbackMethodName(
getSignature(),
getEnclosingClass()),
Modifier.PRIVATE,
munger
);
// now extract the advice into its own method
String adviceMethodName =
NameMangler.aroundCallbackMethodName(
getSignature(),
getEnclosingClass()) + "$advice";
List argVarList = new ArrayList();
List proceedVarList = new ArrayList();
int extraParamOffset = 0;
// Create the extra parameters that are needed for passing to proceed
// This code is very similar to that found in makeCallToCallback and should
// be rationalized in the future
if (thisVar != null) {
argVarList.add(thisVar);
proceedVarList.add(new BcelVar(thisVar.getType(), extraParamOffset));
extraParamOffset += thisVar.getType().getSize();
}
if (targetVar != null && targetVar != thisVar) {
argVarList.add(targetVar);
proceedVarList.add(new BcelVar(targetVar.getType(), extraParamOffset));
extraParamOffset += targetVar.getType().getSize();
}
for (int i = 0, len = getArgCount(); i < len; i++) {
argVarList.add(argVars[i]);
proceedVarList.add(new BcelVar(argVars[i].getType(), extraParamOffset));
extraParamOffset += argVars[i].getType().getSize();
}
if (thisJoinPointVar != null) {
argVarList.add(thisJoinPointVar);
proceedVarList.add(new BcelVar(thisJoinPointVar.getType(), extraParamOffset));
extraParamOffset += thisJoinPointVar.getType().getSize();
}
Type[] adviceParameterTypes = adviceMethod.getArgumentTypes();
Type[] extractedMethodParameterTypes = extractedMethod.getArgumentTypes();
Type[] parameterTypes =
new Type[extractedMethodParameterTypes.length
+ adviceParameterTypes.length
+ 1];
int parameterIndex = 0;
System.arraycopy(
extractedMethodParameterTypes,
0,
parameterTypes,
parameterIndex,
extractedMethodParameterTypes.length);
parameterIndex += extractedMethodParameterTypes.length;
parameterTypes[parameterIndex++] =
BcelWorld.makeBcelType(adviceMethod.getEnclosingClass().getType());
System.arraycopy(
adviceParameterTypes,
0,
parameterTypes,
parameterIndex,
adviceParameterTypes.length);
LazyMethodGen localAdviceMethod =
new LazyMethodGen(
Modifier.PRIVATE | Modifier.FINAL | Modifier.STATIC,
BcelWorld.makeBcelType(mungerSig.getReturnType()),
adviceMethodName,
parameterTypes,
new String[0],
getEnclosingClass());
String donorFileName = adviceMethod.getEnclosingClass().getInternalFileName();
String recipientFileName = getEnclosingClass().getInternalFileName();
// System.err.println("donor " + donorFileName);
// System.err.println("recip " + recipientFileName);
if (! donorFileName.equals(recipientFileName)) {
localAdviceMethod.fromFilename = donorFileName;
getEnclosingClass().addInlinedSourceFileInfo(
donorFileName,
adviceMethod.highestLineNumber);
}
getEnclosingClass().addMethodGen(localAdviceMethod);
// create a map that will move all slots in advice method forward by extraParamOffset
// in order to make room for the new proceed-required arguments that are added at
// the beginning of the parameter list
int nVars = adviceMethod.getMaxLocals() + extraParamOffset;
IntMap varMap = IntMap.idMap(nVars);
for (int i=extraParamOffset; i < nVars; i++) {
varMap.put(i-extraParamOffset, i);
}
localAdviceMethod.getBody().insert(
BcelClassWeaver.genInlineInstructions(adviceMethod,
localAdviceMethod, varMap, fact, true));
localAdviceMethod.setMaxLocals(nVars);
//System.err.println(localAdviceMethod);
// the shadow is now empty. First, create a correct call
// to the around advice. This includes both the call (which may involve
// value conversion of the advice arguments) and the return
// (which may involve value conversion of the return value). Right now
// we push a null for the unused closure. It's sad, but there it is.
InstructionList advice = new InstructionList();
// InstructionHandle adviceMethodInvocation;
{
for (Iterator i = argVarList.iterator(); i.hasNext(); ) {
BcelVar var = (BcelVar)i.next();
var.appendLoad(advice, fact);
}
// ??? we don't actually need to push NULL for the closure if we take care
advice.append(
munger.getAdviceArgSetup(
this,
null,
(munger.getConcreteAspect().isAnnotationStyleAspect() && munger.getDeclaringAspect()!=null && munger.getDeclaringAspect().resolve(world).isAnnotationStyleAspect())?
this.loadThisJoinPoint():
new InstructionList(InstructionConstants.ACONST_NULL)));
// adviceMethodInvocation =
advice.append(
Utility.createInvoke(fact, localAdviceMethod)); //(fact, getWorld(), munger.getSignature()));
advice.append(
Utility.createConversion(
getFactory(),
BcelWorld.makeBcelType(mungerSig.getReturnType()),
extractedMethod.getReturnType(),world.isInJava5Mode()));
if (! isFallsThrough()) {
advice.append(InstructionFactory.createReturn(extractedMethod.getReturnType()));
}
}
// now, situate the call inside the possible dynamic tests,
// and actually add the whole mess to the shadow
if (! hasDynamicTest) {
range.append(advice);
} else {
InstructionList afterThingie = new InstructionList(InstructionConstants.NOP);
InstructionList callback = makeCallToCallback(extractedMethod);
if (terminatesWithReturn()) {
callback.append(
InstructionFactory.createReturn(extractedMethod.getReturnType()));
} else {
//InstructionHandle endNop = range.insert(fact.NOP, Range.InsideAfter);
advice.append(
InstructionFactory.createBranchInstruction(
Constants.GOTO,
afterThingie.getStart()));
}
range.append(
munger.getTestInstructions(
this,
advice.getStart(),
callback.getStart(),
advice.getStart()));
range.append(advice);
range.append(callback);
range.append(afterThingie);
}
// now search through the advice, looking for a call to PROCEED.
// Then we replace the call to proceed with some argument setup, and a
// call to the extracted method.
// inlining support for code style aspects
if (!munger.getConcreteAspect().isAnnotationStyleAspect()) {
String proceedName =
NameMangler.proceedMethodName(munger.getSignature().getName());
InstructionHandle curr = localAdviceMethod.getBody().getStart();
InstructionHandle end = localAdviceMethod.getBody().getEnd();
ConstantPoolGen cpg = localAdviceMethod.getEnclosingClass().getConstantPoolGen();
while (curr != end) {
InstructionHandle next = curr.getNext();
Instruction inst = curr.getInstruction();
if ((inst instanceof INVOKESTATIC)
&& proceedName.equals(((INVOKESTATIC) inst).getMethodName(cpg))) {
localAdviceMethod.getBody().append(
curr,
getRedoneProceedCall(
fact,
extractedMethod,
munger,
localAdviceMethod,
proceedVarList));
Utility.deleteInstruction(curr, localAdviceMethod);
}
curr = next;
}
// and that's it.
} else {
//ATAJ inlining support for @AJ aspects
// [TODO document @AJ code rule: don't manipulate 2 jps proceed at the same time.. in an advice body]
InstructionHandle curr = localAdviceMethod.getBody().getStart();
InstructionHandle end = localAdviceMethod.getBody().getEnd();
ConstantPoolGen cpg = localAdviceMethod.getEnclosingClass().getConstantPoolGen();
while (curr != end) {
InstructionHandle next = curr.getNext();
Instruction inst = curr.getInstruction();
if ((inst instanceof INVOKEINTERFACE)
&& "proceed".equals(((INVOKEINTERFACE) inst).getMethodName(cpg))) {
final boolean isProceedWithArgs;
if (((INVOKEINTERFACE) inst).getArgumentTypes(cpg).length == 1) {
// proceed with args as a boxed Object[]
isProceedWithArgs = true;
} else {
isProceedWithArgs = false;
}
InstructionList insteadProceedIl = getRedoneProceedCallForAnnotationStyle(
fact,
extractedMethod,
munger,
localAdviceMethod,
proceedVarList,
isProceedWithArgs
);
localAdviceMethod.getBody().append(curr, insteadProceedIl);
Utility.deleteInstruction(curr, localAdviceMethod);
}
curr = next;
}
}
}
private InstructionList getRedoneProceedCall(
InstructionFactory fact,
LazyMethodGen callbackMethod,
BcelAdvice munger,
LazyMethodGen localAdviceMethod,
List argVarList)
{
InstructionList ret = new InstructionList();
// we have on stack all the arguments for the ADVICE call.
// we have in frame somewhere all the arguments for the non-advice call.
BcelVar[] adviceVars = munger.getExposedStateAsBcelVars(true);
IntMap proceedMap = makeProceedArgumentMap(adviceVars);
// System.out.println(proceedMap + " for " + this);
// System.out.println(argVarList);
ResolvedType[] proceedParamTypes =
world.resolve(munger.getSignature().getParameterTypes());
// remove this*JoinPoint* as arguments to proceed
if (munger.getBaseParameterCount()+1 < proceedParamTypes.length) {
int len = munger.getBaseParameterCount()+1;
ResolvedType[] newTypes = new ResolvedType[len];
System.arraycopy(proceedParamTypes, 0, newTypes, 0, len);
proceedParamTypes = newTypes;
}
//System.out.println("stateTypes: " + Arrays.asList(stateTypes));
BcelVar[] proceedVars =
Utility.pushAndReturnArrayOfVars(proceedParamTypes, ret, fact, localAdviceMethod);
Type[] stateTypes = callbackMethod.getArgumentTypes();
// System.out.println("stateTypes: " + Arrays.asList(stateTypes));
for (int i=0, len=stateTypes.length; i < len; i++) {
Type stateType = stateTypes[i];
ResolvedType stateTypeX = BcelWorld.fromBcel(stateType).resolve(world);
if (proceedMap.hasKey(i)) {
//throw new RuntimeException("unimplemented");
proceedVars[proceedMap.get(i)].appendLoadAndConvert(ret, fact, stateTypeX);
} else {
((BcelVar) argVarList.get(i)).appendLoad(ret, fact);
}
}
ret.append(Utility.createInvoke(fact, callbackMethod));
ret.append(Utility.createConversion(fact, callbackMethod.getReturnType(),
BcelWorld.makeBcelType(munger.getSignature().getReturnType())));
return ret;
}
private static boolean bindsThisOrTarget(Pointcut pointcut) {
ThisTargetFinder visitor = new ThisTargetFinder();
pointcut.accept(visitor, null);
return visitor.bindsThisOrTarget;
}
private static class ThisTargetFinder extends IdentityPointcutVisitor {
boolean bindsThisOrTarget = false;
public Object visit(ThisOrTargetPointcut node, Object data) {
if (node.isBinding()) {
bindsThisOrTarget = true;
}
return node;
}
public Object visit(AndPointcut node, Object data) {
if (!bindsThisOrTarget) node.getLeft().accept(this, data);
if (!bindsThisOrTarget) node.getRight().accept(this, data);
return node;
}
public Object visit(NotPointcut node, Object data) {
if (!bindsThisOrTarget) node.getNegatedPointcut().accept(this, data);
return node;
}
public Object visit(OrPointcut node, Object data) {
if (!bindsThisOrTarget) node.getLeft().accept(this, data);
if (!bindsThisOrTarget) node.getRight().accept(this, data);
return node;
}
}
/**
* ATAJ Handle the inlining for @AJ aspects
*
* @param fact
* @param callbackMethod
* @param munger
* @param localAdviceMethod
* @param argVarList
* @param isProceedWithArgs
* @return
*/
private InstructionList getRedoneProceedCallForAnnotationStyle(
InstructionFactory fact,
LazyMethodGen callbackMethod,
BcelAdvice munger,
LazyMethodGen localAdviceMethod,
List argVarList,
boolean isProceedWithArgs)
{
// Notes:
// proceedingjp is on stack (since user was calling pjp.proceed(...)
// the boxed args to proceed() are on stack as well (Object[]) unless
// the call is to pjp.proceed(<noarg>)
// new Object[]{new Integer(argAdvice1-1)};// arg of proceed
// call to proceed(..) is NOT made
// instead we do
// itar callback args i
// get from array i, convert it to the callback arg i
// if ask for JP, push the one we got on the stack
// invoke callback, create conversion back to Object/Integer
// rest of method -- (hence all those conversions)
// intValue() from original code
// int res = .. from original code
//Note: we just don't care about the proceed map etc
InstructionList ret = new InstructionList();
// store the Object[] array on stack if proceed with args
if (isProceedWithArgs) {
Type objectArrayType = Type.getType("[Ljava/lang/Object;");
int localProceedArgArray = localAdviceMethod.allocateLocal(objectArrayType);
ret.append(InstructionFactory.createStore(objectArrayType, localProceedArgArray));
Type proceedingJpType = Type.getType("Lorg/aspectj/lang/ProceedingJoinPoint;");
int localJp = localAdviceMethod.allocateLocal(proceedingJpType);
ret.append(InstructionFactory.createStore(proceedingJpType, localJp));
// push on stack each element of the object array
// that is assumed to be consistent with the callback argument (ie munger args)
// TODO do we want to try catch ClassCast and AOOBE exception ?
// special logic when withincode is static or not
int startIndex = 0;
if (thisVar != null) {
startIndex = 1;
//TODO this logic is actually depending on target as well - test me
ret.append(new ALOAD(0));//thisVar
}
// if (bindsThisOrTarget(munger.getPointcut())) {
for (int i = startIndex, len=callbackMethod.getArgumentTypes().length; i < len; i++) {
Type stateType = callbackMethod.getArgumentTypes()[i];
BcelWorld.fromBcel(stateType).resolve(world);
if ("Lorg/aspectj/lang/JoinPoint;".equals(stateType.getSignature())) {
ret.append(new ALOAD(localJp));// from localAdvice signature
} else {
ret.append(InstructionFactory.createLoad(objectArrayType, localProceedArgArray));
ret.append(Utility.createConstant(fact, i-startIndex));
ret.append(InstructionFactory.createArrayLoad(Type.OBJECT));
ret.append(Utility.createConversion(
fact,
Type.OBJECT,
stateType
));
}
}
} else {
Type proceedingJpType = Type.getType("Lorg/aspectj/lang/ProceedingJoinPoint;");
int localJp = localAdviceMethod.allocateLocal(proceedingJpType);
ret.append(InstructionFactory.createStore(proceedingJpType, localJp));
for (int i = 0, len=callbackMethod.getArgumentTypes().length; i < len; i++) {
Type stateType = callbackMethod.getArgumentTypes()[i];
/*ResolvedType stateTypeX =*/
BcelWorld.fromBcel(stateType).resolve(world);
if ("Lorg/aspectj/lang/JoinPoint;".equals(stateType.getSignature())) {
ret.append(new ALOAD(localJp));// from localAdvice signature
// } else if ("Lorg/aspectj/lang/ProceedingJoinPoint;".equals(stateType.getSignature())) {
// //FIXME ALEX?
// ret.append(new ALOAD(localJp));// from localAdvice signature
//// ret.append(fact.createCheckCast(
//// (ReferenceType) BcelWorld.makeBcelType(stateTypeX)
//// ));
// // cast ?
//
} else {
ret.append(InstructionFactory.createLoad(stateType, i));
}
}
}
// do the callback invoke
ret.append(Utility.createInvoke(fact, callbackMethod));
// box it again. Handles cases where around advice does return something else than Object
if (!UnresolvedType.OBJECT.equals(munger.getSignature().getReturnType())) {
ret.append(Utility.createConversion(
fact,
callbackMethod.getReturnType(),
Type.OBJECT
));
}
ret.append(Utility.createConversion(
fact,
callbackMethod.getReturnType(),
BcelWorld.makeBcelType(munger.getSignature().getReturnType())
));
return ret;
//
//
//
// if (proceedMap.hasKey(i)) {
// ret.append(new ALOAD(i));
// //throw new RuntimeException("unimplemented");
// //proceedVars[proceedMap.get(i)].appendLoadAndConvert(ret, fact, stateTypeX);
// } else {
// //((BcelVar) argVarList.get(i)).appendLoad(ret, fact);
// //ret.append(new ALOAD(i));
// if ("Lorg/aspectj/lang/JoinPoint;".equals(stateType.getSignature())) {
// ret.append(new ALOAD(i));
// } else {
// ret.append(new ALOAD(i));
// }
// }
// }
//
// ret.append(Utility.createInvoke(fact, callbackMethod));
// ret.append(Utility.createConversion(fact, callbackMethod.getReturnType(),
// BcelWorld.makeBcelType(munger.getSignature().getReturnType())));
//
// //ret.append(new ACONST_NULL());//will be POPed
// if (true) return ret;
//
//
//
// // we have on stack all the arguments for the ADVICE call.
// // we have in frame somewhere all the arguments for the non-advice call.
//
// BcelVar[] adviceVars = munger.getExposedStateAsBcelVars();
// IntMap proceedMap = makeProceedArgumentMap(adviceVars);
//
// System.out.println(proceedMap + " for " + this);
// System.out.println(argVarList);
//
// ResolvedType[] proceedParamTypes =
// world.resolve(munger.getSignature().getParameterTypes());
// // remove this*JoinPoint* as arguments to proceed
// if (munger.getBaseParameterCount()+1 < proceedParamTypes.length) {
// int len = munger.getBaseParameterCount()+1;
// ResolvedType[] newTypes = new ResolvedType[len];
// System.arraycopy(proceedParamTypes, 0, newTypes, 0, len);
// proceedParamTypes = newTypes;
// }
//
// //System.out.println("stateTypes: " + Arrays.asList(stateTypes));
// BcelVar[] proceedVars =
// Utility.pushAndReturnArrayOfVars(proceedParamTypes, ret, fact, localAdviceMethod);
//
// Type[] stateTypes = callbackMethod.getArgumentTypes();
//// System.out.println("stateTypes: " + Arrays.asList(stateTypes));
//
// for (int i=0, len=stateTypes.length; i < len; i++) {
// Type stateType = stateTypes[i];
// ResolvedType stateTypeX = BcelWorld.fromBcel(stateType).resolve(world);
// if (proceedMap.hasKey(i)) {
// //throw new RuntimeException("unimplemented");
// proceedVars[proceedMap.get(i)].appendLoadAndConvert(ret, fact, stateTypeX);
// } else {
// ((BcelVar) argVarList.get(i)).appendLoad(ret, fact);
// }
// }
//
// ret.append(Utility.createInvoke(fact, callbackMethod));
// ret.append(Utility.createConversion(fact, callbackMethod.getReturnType(),
// BcelWorld.makeBcelType(munger.getSignature().getReturnType())));
// return ret;
}
public void weaveAroundClosure(BcelAdvice munger, boolean hasDynamicTest) {
InstructionFactory fact = getFactory();
enclosingMethod.setCanInline(false);
// MOVE OUT ALL THE INSTRUCTIONS IN MY SHADOW INTO ANOTHER METHOD!
LazyMethodGen callbackMethod =
extractMethod(
NameMangler.aroundCallbackMethodName(
getSignature(),
getEnclosingClass()),
0,
munger);
BcelVar[] adviceVars = munger.getExposedStateAsBcelVars(true);
String closureClassName =
NameMangler.makeClosureClassName(
getEnclosingClass().getType(),
getEnclosingClass().getNewGeneratedNameTag());
Member constructorSig = new MemberImpl(Member.CONSTRUCTOR,
UnresolvedType.forName(closureClassName), 0, "<init>",
"([Ljava/lang/Object;)V");
BcelVar closureHolder = null;
// This is not being used currently since getKind() == preinitializaiton
// cannot happen in around advice
if (getKind() == PreInitialization) {
closureHolder = genTempVar(AjcMemberMaker.AROUND_CLOSURE_TYPE);
}
InstructionList closureInstantiation =
makeClosureInstantiation(constructorSig, closureHolder);
/*LazyMethodGen constructor = */
makeClosureClassAndReturnConstructor(
closureClassName,
callbackMethod,
makeProceedArgumentMap(adviceVars)
);
InstructionList returnConversionCode;
if (getKind() == PreInitialization) {
returnConversionCode = new InstructionList();
BcelVar stateTempVar = genTempVar(UnresolvedType.OBJECTARRAY);
closureHolder.appendLoad(returnConversionCode, fact);
returnConversionCode.append(
Utility.createInvoke(
fact,
world,
AjcMemberMaker.aroundClosurePreInitializationGetter()));
stateTempVar.appendStore(returnConversionCode, fact);
Type[] stateTypes = getSuperConstructorParameterTypes();
returnConversionCode.append(InstructionConstants.ALOAD_0); // put "this" back on the stack
for (int i = 0, len = stateTypes.length; i < len; i++) {
UnresolvedType bcelTX = BcelWorld.fromBcel(stateTypes[i]);
ResolvedType stateRTX = world.resolve(bcelTX,true);
if (stateRTX.isMissing()) {
world.getLint().cantFindType.signal(
new String[] {WeaverMessages.format(WeaverMessages.CANT_FIND_TYPE_DURING_AROUND_WEAVE_PREINIT,bcelTX.getClassName())},
getSourceLocation(),
new ISourceLocation[]{ munger.getSourceLocation()}
);
// IMessage msg = new Message(
// WeaverMessages.format(WeaverMessages.CANT_FIND_TYPE_DURING_AROUND_WEAVE_PREINIT,bcelTX.getClassName()),
// "",IMessage.ERROR,getSourceLocation(),null,
// new ISourceLocation[]{ munger.getSourceLocation()});
// world.getMessageHandler().handleMessage(msg);
}
stateTempVar.appendConvertableArrayLoad(
returnConversionCode,
fact,
i,
stateRTX);
}
} else {
returnConversionCode =
Utility.createConversion(
getFactory(),
BcelWorld.makeBcelType(munger.getSignature().getReturnType()),
callbackMethod.getReturnType(),world.isInJava5Mode());
if (!isFallsThrough()) {
returnConversionCode.append(
InstructionFactory.createReturn(callbackMethod.getReturnType()));
}
}
// ATAJ for @AJ aspect we need to link the closure with the joinpoint instance
if (munger.getConcreteAspect()!=null && munger.getConcreteAspect().isAnnotationStyleAspect()
&& munger.getDeclaringAspect()!=null && munger.getDeclaringAspect().resolve(world).isAnnotationStyleAspect()) {
closureInstantiation.append(Utility.createInvoke(
getFactory(),
getWorld(),
new MemberImpl(
Member.METHOD,
UnresolvedType.forName("org.aspectj.runtime.internal.AroundClosure"),
Modifier.PUBLIC,
"linkClosureAndJoinPoint",
"()Lorg/aspectj/lang/ProceedingJoinPoint;"
)
));
}
InstructionList advice = new InstructionList();
advice.append(munger.getAdviceArgSetup(this, null, closureInstantiation));
// invoke the advice
advice.append(munger.getNonTestAdviceInstructions(this));
advice.append(returnConversionCode);
if (!hasDynamicTest) {
range.append(advice);
} else {
InstructionList callback = makeCallToCallback(callbackMethod);
InstructionList postCallback = new InstructionList();
if (terminatesWithReturn()) {
callback.append(
InstructionFactory.createReturn(callbackMethod.getReturnType()));
} else {
advice.append(
InstructionFactory.createBranchInstruction(
Constants.GOTO,
postCallback.append(InstructionConstants.NOP)));
}
range.append(
munger.getTestInstructions(
this,
advice.getStart(),
callback.getStart(),
advice.getStart()));
range.append(advice);
range.append(callback);
range.append(postCallback);
}
}
// exposed for testing
InstructionList makeCallToCallback(LazyMethodGen callbackMethod) {
InstructionFactory fact = getFactory();
InstructionList callback = new InstructionList();
if (thisVar != null) {
callback.append(InstructionConstants.ALOAD_0);
}
if (targetVar != null && targetVar != thisVar) {
callback.append(BcelRenderer.renderExpr(fact, world, targetVar));
}
callback.append(BcelRenderer.renderExprs(fact, world, argVars));
// remember to render tjps
if (thisJoinPointVar != null) {
callback.append(BcelRenderer.renderExpr(fact, world, thisJoinPointVar));
}
callback.append(Utility.createInvoke(fact, callbackMethod));
return callback;
}
/** side-effect-free */
private InstructionList makeClosureInstantiation(Member constructor, BcelVar holder) {
// LazyMethodGen constructor) {
InstructionFactory fact = getFactory();
BcelVar arrayVar = genTempVar(UnresolvedType.OBJECTARRAY);
//final Type objectArrayType = new ArrayType(Type.OBJECT, 1);
final InstructionList il = new InstructionList();
int alen = getArgCount() + (thisVar == null ? 0 : 1) +
((targetVar != null && targetVar != thisVar) ? 1 : 0) +
(thisJoinPointVar == null ? 0 : 1);
il.append(Utility.createConstant(fact, alen));
il.append((Instruction)fact.createNewArray(Type.OBJECT, (short)1));
arrayVar.appendStore(il, fact);
int stateIndex = 0;
if (thisVar != null) {
arrayVar.appendConvertableArrayStore(il, fact, stateIndex, thisVar);
thisVar.setPositionInAroundState(stateIndex);
stateIndex++;
}
if (targetVar != null && targetVar != thisVar) {
arrayVar.appendConvertableArrayStore(il, fact, stateIndex, targetVar);
targetVar.setPositionInAroundState(stateIndex);
stateIndex++;
}
for (int i = 0, len = getArgCount(); i<len; i++) {
arrayVar.appendConvertableArrayStore(il, fact, stateIndex, argVars[i]);
argVars[i].setPositionInAroundState(stateIndex);
stateIndex++;
}
if (thisJoinPointVar != null) {
arrayVar.appendConvertableArrayStore(il, fact, stateIndex, thisJoinPointVar);
thisJoinPointVar.setPositionInAroundState(stateIndex);
stateIndex++;
}
il.append(fact.createNew(new ObjectType(constructor.getDeclaringType().getName())));
il.append(new DUP());
arrayVar.appendLoad(il, fact);
il.append(Utility.createInvoke(fact, world, constructor));
if (getKind() == PreInitialization) {
il.append(InstructionConstants.DUP);
holder.appendStore(il, fact);
}
return il;
}
private IntMap makeProceedArgumentMap(BcelVar[] adviceArgs) {
//System.err.println("coming in with " + Arrays.asList(adviceArgs));
IntMap ret = new IntMap();
for(int i = 0, len = adviceArgs.length; i < len; i++) {
BcelVar v = (BcelVar) adviceArgs[i];
if (v == null) continue; // XXX we don't know why this is required
int pos = v.getPositionInAroundState();
if (pos >= 0) { // need this test to avoid args bound via cflow
ret.put(pos, i);
}
}
//System.err.println("returning " + ret);
return ret;
}
/**
*
*
* @param callbackMethod the method we will call back to when our run method gets called.
*
* @param proceedMap A map from state position to proceed argument position. May be
* non covering on state position.
*/
private LazyMethodGen makeClosureClassAndReturnConstructor(
String closureClassName,
LazyMethodGen callbackMethod,
IntMap proceedMap)
{
String superClassName = "org.aspectj.runtime.internal.AroundClosure";
Type objectArrayType = new ArrayType(Type.OBJECT, 1);
LazyClassGen closureClass = new LazyClassGen(closureClassName,
superClassName,
getEnclosingClass().getFileName(),
Modifier.PUBLIC,
new String[] {},
getWorld());
InstructionFactory fact = new InstructionFactory(closureClass.getConstantPoolGen());
// constructor
LazyMethodGen constructor = new LazyMethodGen(Modifier.PUBLIC,
Type.VOID,
"<init>",
new Type[] {objectArrayType},
new String[] {},
closureClass);
InstructionList cbody = constructor.getBody();
cbody.append(InstructionFactory.createLoad(Type.OBJECT, 0));
cbody.append(InstructionFactory.createLoad(objectArrayType, 1));
cbody.append(fact.createInvoke(superClassName, "<init>", Type.VOID,
new Type[] {objectArrayType}, Constants.INVOKESPECIAL));
cbody.append(InstructionFactory.createReturn(Type.VOID));
closureClass.addMethodGen(constructor);
// method
LazyMethodGen runMethod = new LazyMethodGen(Modifier.PUBLIC,
Type.OBJECT,
"run",
new Type[] {objectArrayType},
new String[] {},
closureClass);
InstructionList mbody = runMethod.getBody();
BcelVar proceedVar = new BcelVar(UnresolvedType.OBJECTARRAY.resolve(world), 1);
// int proceedVarIndex = 1;
BcelVar stateVar =
new BcelVar(UnresolvedType.OBJECTARRAY.resolve(world), runMethod.allocateLocal(1));
// int stateVarIndex = runMethod.allocateLocal(1);
mbody.append(InstructionFactory.createThis());
mbody.append(fact.createGetField(superClassName, "state", objectArrayType));
mbody.append(stateVar.createStore(fact));
// mbody.append(fact.createStore(objectArrayType, stateVarIndex));
Type[] stateTypes = callbackMethod.getArgumentTypes();
for (int i=0, len=stateTypes.length; i < len; i++) {
Type stateType = stateTypes[i];
ResolvedType stateTypeX = BcelWorld.fromBcel(stateType).resolve(world);
if (proceedMap.hasKey(i)) {
mbody.append(
proceedVar.createConvertableArrayLoad(fact, proceedMap.get(i),
stateTypeX));
} else {
mbody.append(
stateVar.createConvertableArrayLoad(fact, i,
stateTypeX));
}
}
mbody.append(Utility.createInvoke(fact, callbackMethod));
if (getKind() == PreInitialization) {
mbody.append(Utility.createSet(
fact,
AjcMemberMaker.aroundClosurePreInitializationField()));
mbody.append(InstructionConstants.ACONST_NULL);
} else {
mbody.append(
Utility.createConversion(
fact,
callbackMethod.getReturnType(),
Type.OBJECT));
}
mbody.append(InstructionFactory.createReturn(Type.OBJECT));
closureClass.addMethodGen(runMethod);
// class
getEnclosingClass().addGeneratedInner(closureClass);
return constructor;
}
// ---- extraction methods
public LazyMethodGen extractMethod(String newMethodName, int visibilityModifier, ShadowMunger munger) {
LazyMethodGen.assertGoodBody(range.getBody(), newMethodName);
if (!getKind().allowsExtraction()) throw new BCException("Attempt to extract method from a shadow kind that does not support this operation (" + getKind() + ")");
LazyMethodGen freshMethod = createMethodGen(newMethodName,visibilityModifier);
// System.err.println("******");
// System.err.println("ABOUT TO EXTRACT METHOD for" + this);
// enclosingMethod.print(System.err);
// System.err.println("INTO");
// freshMethod.print(System.err);
// System.err.println("WITH REMAP");
// System.err.println(makeRemap());
range.extractInstructionsInto(freshMethod, makeRemap(),
(getKind() != PreInitialization) &&
isFallsThrough());
if (getKind() == PreInitialization) {
addPreInitializationReturnCode(
freshMethod,
getSuperConstructorParameterTypes());
}
getEnclosingClass().addMethodGen(freshMethod,munger.getSourceLocation());
return freshMethod;
}
private void addPreInitializationReturnCode(
LazyMethodGen extractedMethod,
Type[] superConstructorTypes)
{
InstructionList body = extractedMethod.getBody();
final InstructionFactory fact = getFactory();
BcelVar arrayVar = new BcelVar(
world.getCoreType(UnresolvedType.OBJECTARRAY),
extractedMethod.allocateLocal(1));
int len = superConstructorTypes.length;
body.append(Utility.createConstant(fact, len));
body.append((Instruction)fact.createNewArray(Type.OBJECT, (short)1));
arrayVar.appendStore(body, fact);
for (int i = len - 1; i >= 0; i++) {
// convert thing on top of stack to object
body.append(
Utility.createConversion(fact, superConstructorTypes[i], Type.OBJECT));
// push object array
arrayVar.appendLoad(body, fact);
// swap
body.append(InstructionConstants.SWAP);
// do object array store.
body.append(Utility.createConstant(fact, i));
body.append(InstructionConstants.SWAP);
body.append(InstructionFactory.createArrayStore(Type.OBJECT));
}
arrayVar.appendLoad(body, fact);
body.append(InstructionConstants.ARETURN);
}
private Type[] getSuperConstructorParameterTypes() {
// assert getKind() == PreInitialization
InstructionHandle superCallHandle = getRange().getEnd().getNext();
InvokeInstruction superCallInstruction =
(InvokeInstruction) superCallHandle.getInstruction();
return superCallInstruction.getArgumentTypes(
getEnclosingClass().getConstantPoolGen());
}
/** make a map from old frame location to new frame location. Any unkeyed frame
* location picks out a copied local */
private IntMap makeRemap() {
IntMap ret = new IntMap(5);
int reti = 0;
if (thisVar != null) {
ret.put(0, reti++); // thisVar guaranteed to be 0
}
if (targetVar != null && targetVar != thisVar) {
ret.put(targetVar.getSlot(), reti++);
}
for (int i = 0, len = argVars.length; i < len; i++) {
ret.put(argVars[i].getSlot(), reti);
reti += argVars[i].getType().getSize();
}
if (thisJoinPointVar != null) {
ret.put(thisJoinPointVar.getSlot(), reti++);
}
// we not only need to put the arguments, we also need to remap their
// aliases, which we so helpfully put into temps at the beginning of this join
// point.
if (! getKind().argsOnStack()) {
int oldi = 0;
int newi = 0;
// if we're passing in a this and we're not argsOnStack we're always
// passing in a target too
if (arg0HoldsThis()) { ret.put(0, 0); oldi++; newi+=1; }
//assert targetVar == thisVar
for (int i = 0; i < getArgCount(); i++) {
UnresolvedType type = getArgType(i);
ret.put(oldi, newi);
oldi += type.getSize();
newi += type.getSize();
}
}
// System.err.println("making remap for : " + this);
// if (targetVar != null) System.err.println("target slot : " + targetVar.getSlot());
// if (thisVar != null) System.err.println(" this slot : " + thisVar.getSlot());
// System.err.println(ret);
return ret;
}
/**
* The new method always static.
* It may take some extra arguments: this, target.
* If it's argsOnStack, then it must take both this/target
* If it's argsOnFrame, it shares this and target.
* ??? rewrite this to do less array munging, please
*/
private LazyMethodGen createMethodGen(String newMethodName, int visibilityModifier) {
Type[] parameterTypes = BcelWorld.makeBcelTypes(getArgTypes());
int modifiers = Modifier.FINAL | visibilityModifier;
// XXX some bug
// if (! isExpressionKind() && getSignature().isStrict(world)) {
// modifiers |= Modifier.STRICT;
// }
modifiers |= Modifier.STATIC;
if (targetVar != null && targetVar != thisVar) {
UnresolvedType targetType = getTargetType();
targetType = ensureTargetTypeIsCorrect(targetType);
// see pr109728 - this fixes the case when the declaring class is sometype 'X' but the getfield
// in the bytecode refers to a subtype of 'X'. This makes sure we use the type originally
// mentioned in the fieldget instruction as the method parameter and *not* the type upon which the
// field is declared because when the instructions are extracted into the new around body,
// they will still refer to the subtype.
if (getKind()==FieldGet && getActualTargetType()!=null &&
!getActualTargetType().equals(targetType.getName())) {
targetType = UnresolvedType.forName(getActualTargetType()).resolve(world);
}
ResolvedMember resolvedMember = getSignature().resolve(world);
if (resolvedMember != null && Modifier.isProtected(resolvedMember.getModifiers()) &&
!samePackage(targetType.getPackageName(), getEnclosingType().getPackageName()) &&
!resolvedMember.getName().equals("clone"))
{
if (!targetType.resolve(world).isAssignableFrom(getThisType().resolve(world))) {
throw new BCException("bad bytecode");
}
targetType = getThisType();
}
parameterTypes = addType(BcelWorld.makeBcelType(targetType), parameterTypes);
}
if (thisVar != null) {
UnresolvedType thisType = getThisType();
parameterTypes = addType(BcelWorld.makeBcelType(thisType), parameterTypes);
}
// We always want to pass down thisJoinPoint in case we have already woven
// some advice in here. If we only have a single piece of around advice on a
// join point, it is unnecessary to accept (and pass) tjp.
if (thisJoinPointVar != null) {
parameterTypes = addTypeToEnd(LazyClassGen.tjpType, parameterTypes);
//FIXME ALEX? which one
//parameterTypes = addTypeToEnd(LazyClassGen.proceedingTjpType, parameterTypes);
}
UnresolvedType returnType;
if (getKind() == PreInitialization) {
returnType = UnresolvedType.OBJECTARRAY;
} else {
if (getKind() == ConstructorCall) returnType = getSignature().getDeclaringType();
else if (getKind() == FieldSet) returnType = ResolvedType.VOID;
else returnType = getSignature().getReturnType().resolve(world);
// returnType = getReturnType(); // for this and above lines, see pr137496
}
return
new LazyMethodGen(
modifiers,
BcelWorld.makeBcelType(returnType),
newMethodName,
parameterTypes,
new String[0],
// XXX again, we need to look up methods!
// UnresolvedType.getNames(getSignature().getExceptions(world)),
getEnclosingClass());
}
private boolean samePackage(String p1, String p2) {
if (p1 == null) return p2 == null;
if (p2 == null) return false;
return p1.equals(p2);
}
private Type[] addType(Type type, Type[] types) {
int len = types.length;
Type[] ret = new Type[len+1];
ret[0] = type;
System.arraycopy(types, 0, ret, 1, len);
return ret;
}
private Type[] addTypeToEnd(Type type, Type[] types) {
int len = types.length;
Type[] ret = new Type[len+1];
ret[len] = type;
System.arraycopy(types, 0, ret, 0, len);
return ret;
}
public BcelVar genTempVar(UnresolvedType typeX) {
return new BcelVar(typeX.resolve(world), genTempVarIndex(typeX.getSize()));
}
// public static final boolean CREATE_TEMP_NAMES = true;
public BcelVar genTempVar(UnresolvedType typeX, String localName) {
BcelVar tv = genTempVar(typeX);
// if (CREATE_TEMP_NAMES) {
// for (InstructionHandle ih = range.getStart(); ih != range.getEnd(); ih = ih.getNext()) {
// if (Range.isRangeHandle(ih)) continue;
// ih.addTargeter(new LocalVariableTag(typeX, localName, tv.getSlot()));
// }
// }
return tv;
}
// eh doesn't think we need to garbage collect these (64K is a big number...)
private int genTempVarIndex(int size) {
return enclosingMethod.allocateLocal(size);
}
public InstructionFactory getFactory() {
return getEnclosingClass().getFactory();
}
public ISourceLocation getSourceLocation() {
int sourceLine = getSourceLine();
if (sourceLine == 0 || sourceLine == -1) {
// Thread.currentThread().dumpStack();
// System.err.println(this + ": " + range);
return getEnclosingClass().getType().getSourceLocation();
} else {
// For staticinitialization, if we have a nice offset, don't build a new source loc
if (getKind()==Shadow.StaticInitialization && getEnclosingClass().getType().getSourceLocation().getOffset()!=0) {
return getEnclosingClass().getType().getSourceLocation();
} else {
int offset = 0;
Kind kind = getKind();
if ( (kind == MethodExecution) ||
(kind == ConstructorExecution) ||
(kind == AdviceExecution) ||
(kind == StaticInitialization) ||
(kind == PreInitialization) ||
(kind == Initialization)) {
if (getEnclosingMethod().hasDeclaredLineNumberInfo()) {
offset = getEnclosingMethod().getDeclarationOffset();
}
}
return getEnclosingClass().getType().getSourceContext().makeSourceLocation(sourceLine, offset);
}
}
}
public Shadow getEnclosingShadow() {
return enclosingShadow;
}
public LazyMethodGen getEnclosingMethod() {
return enclosingMethod;
}
public boolean isFallsThrough() {
return !terminatesWithReturn(); //fallsThrough;
}
public void setActualTargetType(String className) {
this.actualInstructionTargetType = className;
}
public String getActualTargetType() {
return actualInstructionTargetType;
}
}
|
148,007 |
Bug 148007 boolean methods with after advice return incorrect result on JRockit under WLS
| null |
resolved fixed
|
426cbdc
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-06-22T04:49:26Z | 2006-06-21T08:53:20Z |
weaver/src/org/aspectj/weaver/bcel/Utility.java
|
/* *******************************************************************
* Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC).
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the 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.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Hashtable;
import java.util.List;
import org.aspectj.apache.bcel.Constants;
import org.aspectj.apache.bcel.classfile.ClassParser;
import org.aspectj.apache.bcel.classfile.JavaClass;
import org.aspectj.apache.bcel.classfile.Method;
import org.aspectj.apache.bcel.classfile.annotation.ArrayElementValue;
import org.aspectj.apache.bcel.classfile.annotation.ElementNameValuePair;
import org.aspectj.apache.bcel.classfile.annotation.ElementValue;
import org.aspectj.apache.bcel.classfile.annotation.SimpleElementValue;
import org.aspectj.apache.bcel.generic.ArrayType;
import org.aspectj.apache.bcel.generic.BIPUSH;
import org.aspectj.apache.bcel.generic.BasicType;
import org.aspectj.apache.bcel.generic.BranchInstruction;
import org.aspectj.apache.bcel.generic.ConstantPushInstruction;
import org.aspectj.apache.bcel.generic.INSTANCEOF;
import org.aspectj.apache.bcel.generic.Instruction;
import org.aspectj.apache.bcel.generic.InstructionConstants;
import org.aspectj.apache.bcel.generic.InstructionFactory;
import org.aspectj.apache.bcel.generic.InstructionHandle;
import org.aspectj.apache.bcel.generic.InstructionList;
import org.aspectj.apache.bcel.generic.InstructionTargeter;
import org.aspectj.apache.bcel.generic.InvokeInstruction;
import org.aspectj.apache.bcel.generic.LDC;
import org.aspectj.apache.bcel.generic.LineNumberTag;
import org.aspectj.apache.bcel.generic.ObjectType;
import org.aspectj.apache.bcel.generic.ReferenceType;
import org.aspectj.apache.bcel.generic.SIPUSH;
import org.aspectj.apache.bcel.generic.SWITCH;
import org.aspectj.apache.bcel.generic.Select;
import org.aspectj.apache.bcel.generic.TargetLostException;
import org.aspectj.apache.bcel.generic.Type;
import org.aspectj.bridge.ISourceLocation;
import org.aspectj.weaver.AnnotationX;
import org.aspectj.weaver.BCException;
import org.aspectj.weaver.Lint;
import org.aspectj.weaver.Member;
import org.aspectj.weaver.ResolvedType;
import org.aspectj.weaver.UnresolvedType;
public class Utility {
private Utility() {
super();
}
/*
* Ensure we report a nice source location - particular in the case
* where the source info is missing (binary weave).
*/
public static String beautifyLocation(ISourceLocation isl) {
StringBuffer nice = new StringBuffer();
if (isl==null || isl.getSourceFile()==null || isl.getSourceFile().getName().indexOf("no debug info available")!=-1) {
nice.append("no debug info available");
} else {
// can't use File.getName() as this fails when a Linux box encounters a path created on Windows and vice-versa
int takeFrom = isl.getSourceFile().getPath().lastIndexOf('/');
if (takeFrom == -1) {
takeFrom = isl.getSourceFile().getPath().lastIndexOf('\\');
}
nice.append(isl.getSourceFile().getPath().substring(takeFrom +1));
if (isl.getLine()!=0) nice.append(":").append(isl.getLine());
}
return nice.toString();
}
public static Instruction createSuperInvoke(
InstructionFactory fact,
BcelWorld world,
Member signature) {
short kind;
if (signature.isInterface()) {
throw new RuntimeException("bad");
} else if (signature.isPrivate() || signature.getName().equals("<init>")) {
throw new RuntimeException("unimplemented, possibly bad");
} else if (signature.isStatic()) {
throw new RuntimeException("bad");
} else {
kind = Constants.INVOKESPECIAL;
}
return fact.createInvoke(
signature.getDeclaringType().getName(),
signature.getName(),
BcelWorld.makeBcelType(signature.getReturnType()),
BcelWorld.makeBcelTypes(signature.getParameterTypes()),
kind);
}
// XXX don't need the world now
public static Instruction createInvoke(
InstructionFactory fact,
BcelWorld world,
Member signature) {
short kind;
if (signature.isInterface()) {
kind = Constants.INVOKEINTERFACE;
} else if (signature.isStatic()) {
kind = Constants.INVOKESTATIC;
} else if (signature.isPrivate() || signature.getName().equals("<init>")) {
kind = Constants.INVOKESPECIAL;
} else {
kind = Constants.INVOKEVIRTUAL;
}
UnresolvedType targetType = signature.getDeclaringType();
if (targetType.isParameterizedType()) {
targetType = targetType.resolve(world).getGenericType();
}
return fact.createInvoke(
targetType.getName(),
signature.getName(),
BcelWorld.makeBcelType(signature.getReturnType()),
BcelWorld.makeBcelTypes(signature.getParameterTypes()),
kind);
}
public static Instruction createGet(InstructionFactory fact, Member signature) {
short kind;
if (signature.isStatic()) {
kind = Constants.GETSTATIC;
} else {
kind = Constants.GETFIELD;
}
return fact.createFieldAccess(
signature.getDeclaringType().getName(),
signature.getName(),
BcelWorld.makeBcelType(signature.getReturnType()),
kind);
}
/**
* Creae a field GET instruction
*
* @param fact
* @param signature
* @param declaringType
* @return
*/
public static Instruction createGetOn(InstructionFactory fact, Member signature, UnresolvedType declaringType) {
short kind;
if (signature.isStatic()) {
kind = Constants.GETSTATIC;
} else {
kind = Constants.GETFIELD;
}
return fact.createFieldAccess(
declaringType.getName(),
signature.getName(),
BcelWorld.makeBcelType(signature.getReturnType()),
kind);
}
public static Instruction createSet(InstructionFactory fact, Member signature) {
short kind;
if (signature.isStatic()) {
kind = Constants.PUTSTATIC;
} else {
kind = Constants.PUTFIELD;
}
return fact.createFieldAccess(
signature.getDeclaringType().getName(),
signature.getName(),
BcelWorld.makeBcelType(signature.getReturnType()),
kind);
}
public static Instruction createInvoke(
InstructionFactory fact,
JavaClass declaringClass,
Method newMethod) {
short kind;
if (newMethod.isInterface()) {
kind = Constants.INVOKEINTERFACE;
} else if (newMethod.isStatic()) {
kind = Constants.INVOKESTATIC;
} else if (newMethod.isPrivate() || newMethod.getName().equals("<init>")) {
kind = Constants.INVOKESPECIAL;
} else {
kind = Constants.INVOKEVIRTUAL;
}
return fact.createInvoke(
declaringClass.getClassName(),
newMethod.getName(),
Type.getReturnType(newMethod.getSignature()),
Type.getArgumentTypes(newMethod.getSignature()),
kind);
}
public static byte[] stringToUTF(String s) {
try {
ByteArrayOutputStream out0 = new ByteArrayOutputStream();
DataOutputStream out1 = new DataOutputStream(out0);
out1.writeUTF(s);
return out0.toByteArray();
} catch (IOException e) {
throw new RuntimeException("sanity check");
}
}
public static Instruction createInstanceof(InstructionFactory fact, ReferenceType t) {
int cpoolEntry =
(t instanceof ArrayType)
? fact.getConstantPool().addArrayClass((ArrayType)t)
: fact.getConstantPool().addClass((ObjectType)t);
return new INSTANCEOF(cpoolEntry);
}
public static Instruction createInvoke(
InstructionFactory fact,
LazyMethodGen m) {
short kind;
if (m.getEnclosingClass().isInterface()) {
kind = Constants.INVOKEINTERFACE;
} else if (m.isStatic()) {
kind = Constants.INVOKESTATIC;
} else if (m.isPrivate() || m.getName().equals("<init>")) {
kind = Constants.INVOKESPECIAL;
} else {
kind = Constants.INVOKEVIRTUAL;
}
return fact.createInvoke(
m.getClassName(),
m.getName(),
m.getReturnType(),
m.getArgumentTypes(),
kind);
}
/**
* Create an invoke instruction
*
* @param fact
* @param kind INVOKEINTERFACE, INVOKEVIRTUAL..
* @param member
* @return
*/
public static Instruction createInvoke(
InstructionFactory fact,
short kind,
Member member) {
return fact.createInvoke(
member.getDeclaringType().getName(),
member.getName(),
BcelWorld.makeBcelType(member.getReturnType()),
BcelWorld.makeBcelTypes(member.getParameterTypes()),
kind);
}
// ??? these should perhaps be cached. Remember to profile this to see if it's a problem.
public static String[] makeArgNames(int n) {
String[] ret = new String[n];
for (int i=0; i<n; i++) {
ret[i] = "arg" + i;
}
return ret;
}
// Lookup table, for converting between pairs of types, it gives
// us the method name in the Conversions class
private static Hashtable validBoxing = new Hashtable();
static {
validBoxing.put("Ljava/lang/Byte;B","byteObject");
validBoxing.put("Ljava/lang/Character;C","charObject");
validBoxing.put("Ljava/lang/Double;D","doubleObject");
validBoxing.put("Ljava/lang/Float;F","floatObject");
validBoxing.put("Ljava/lang/Integer;I","intObject");
validBoxing.put("Ljava/lang/Long;J","longObject");
validBoxing.put("Ljava/lang/Short;S","shortObject");
validBoxing.put("Ljava/lang/Boolean;Z","booleanObject");
validBoxing.put("BLjava/lang/Byte;","byteValue");
validBoxing.put("CLjava/lang/Character;","charValue");
validBoxing.put("DLjava/lang/Double;","doubleValue");
validBoxing.put("FLjava/lang/Float;","floatValue");
validBoxing.put("ILjava/lang/Integer;","intValue");
validBoxing.put("JLjava/lang/Long;","longValue");
validBoxing.put("SLjava/lang/Short;","shortValue");
validBoxing.put("ZLjava/lang/Boolean;","booleanValue");
}
public static void appendConversion(
InstructionList il,
InstructionFactory fact,
ResolvedType fromType,
ResolvedType toType)
{
if (! toType.isConvertableFrom(fromType) &&
! fromType.isConvertableFrom(toType)) {
throw new BCException("can't convert from " + fromType + " to " + toType);
}
// XXX I'm sure this test can be simpler but my brain hurts and this works
if (!toType.getWorld().isInJava5Mode()) {
if (toType.needsNoConversionFrom(fromType)) return;
} else {
if (toType.needsNoConversionFrom(fromType) && !(toType.isPrimitiveType()^fromType.isPrimitiveType())) return;
}
if (toType.equals(ResolvedType.VOID)) {
// assert fromType.equals(UnresolvedType.OBJECT)
il.append(InstructionFactory.createPop(fromType.getSize()));
} else if (fromType.equals(ResolvedType.VOID)) {
// assert toType.equals(UnresolvedType.OBJECT)
il.append(InstructionFactory.createNull(Type.OBJECT));
return;
} else if (fromType.equals(UnresolvedType.OBJECT)) {
Type to = BcelWorld.makeBcelType(toType);
if (toType.isPrimitiveType()) {
String name = toType.toString() + "Value";
il.append(
fact.createInvoke(
"org.aspectj.runtime.internal.Conversions",
name,
to,
new Type[] { Type.OBJECT },
Constants.INVOKESTATIC));
} else {
il.append(fact.createCheckCast((ReferenceType)to));
}
} else if (toType.equals(UnresolvedType.OBJECT)) {
// assert fromType.isPrimitive()
Type from = BcelWorld.makeBcelType(fromType);
String name = fromType.toString() + "Object";
il.append(
fact.createInvoke(
"org.aspectj.runtime.internal.Conversions",
name,
Type.OBJECT,
new Type[] { from },
Constants.INVOKESTATIC));
} else if (toType.getWorld().isInJava5Mode() && validBoxing.get(toType.getSignature()+fromType.getSignature())!=null) {
// XXX could optimize by using any java boxing code that may be just before the call...
Type from = BcelWorld.makeBcelType(fromType);
Type to = BcelWorld.makeBcelType(toType);
String name = (String)validBoxing.get(toType.getSignature()+fromType.getSignature());
if (toType.isPrimitiveType()) {
il.append(
fact.createInvoke(
"org.aspectj.runtime.internal.Conversions",
name,
to,
new Type[]{Type.OBJECT},
Constants.INVOKESTATIC));
} else {
il.append(
fact.createInvoke(
"org.aspectj.runtime.internal.Conversions",
name,
Type.OBJECT,
new Type[] { from },
Constants.INVOKESTATIC));
il.append(fact.createCheckCast((ReferenceType) to));
}
} else if (fromType.isPrimitiveType()) {
// assert toType.isPrimitive()
Type from = BcelWorld.makeBcelType(fromType);
Type to = BcelWorld.makeBcelType(toType);
try {
il.append(fact.createCast(from, to));
} catch (RuntimeException e) {
il.append(fact.createCast(from, Type.INT));
il.append(fact.createCast(Type.INT, to));
}
} else {
Type to = BcelWorld.makeBcelType(toType);
// assert ! fromType.isPrimitive() && ! toType.isPrimitive()
il.append(fact.createCheckCast((ReferenceType) to));
}
}
public static InstructionList createConversion(InstructionFactory factory,Type fromType,Type toType) {
return createConversion(factory,fromType,toType,false);
}
public static InstructionList createConversion(
InstructionFactory fact,
Type fromType,
Type toType,
boolean allowAutoboxing) {
//System.out.println("cast to: " + toType);
InstructionList il = new InstructionList();
//PR71273
if ((fromType.equals(Type.BYTE) || fromType.equals(Type.CHAR) || fromType.equals(Type.SHORT)) &&
(toType.equals(Type.INT))) {
return il;
}
if (fromType.equals(toType))
return il;
if (toType.equals(Type.VOID)) {
il.append(InstructionFactory.createPop(fromType.getSize()));
return il;
}
if (fromType.equals(Type.VOID)) {
if (toType instanceof BasicType)
throw new BCException("attempting to cast from void to basic type");
il.append(InstructionFactory.createNull(Type.OBJECT));
return il;
}
if (fromType.equals(Type.OBJECT)) {
if (toType instanceof BasicType) {
String name = toType.toString() + "Value";
il.append(
fact.createInvoke(
"org.aspectj.runtime.internal.Conversions",
name,
toType,
new Type[] { Type.OBJECT },
Constants.INVOKESTATIC));
return il;
}
}
if (toType.equals(Type.OBJECT)) {
if (fromType instanceof BasicType) {
String name = fromType.toString() + "Object";
il.append(
fact.createInvoke(
"org.aspectj.runtime.internal.Conversions",
name,
Type.OBJECT,
new Type[] { fromType },
Constants.INVOKESTATIC));
return il;
} else if (fromType instanceof ReferenceType) {
return il;
} else {
throw new RuntimeException();
}
}
if (fromType instanceof ReferenceType
&& ((ReferenceType)fromType).isAssignmentCompatibleWith(toType)) {
return il;
}
if (allowAutoboxing) {
if (toType instanceof BasicType && fromType instanceof ReferenceType) {
// unboxing
String name = toType.toString() + "Value";
il.append(
fact.createInvoke(
"org.aspectj.runtime.internal.Conversions",
name,
toType,
new Type[] { Type.OBJECT },
Constants.INVOKESTATIC));
return il;
}
if (fromType instanceof BasicType && toType instanceof ReferenceType) {
// boxing
String name = fromType.toString() + "Object";
il.append(
fact.createInvoke(
"org.aspectj.runtime.internal.Conversions",
name,
Type.OBJECT,
new Type[] { fromType },
Constants.INVOKESTATIC));
il.append(fact.createCast(Type.OBJECT, toType));
return il;
}
}
il.append(fact.createCast(fromType, toType));
return il;
}
public static Instruction createConstant(
InstructionFactory fact,
int i) {
Instruction inst;
switch(i) {
case -1: inst = InstructionConstants.ICONST_M1; break;
case 0: inst = InstructionConstants.ICONST_0; break;
case 1: inst = InstructionConstants.ICONST_1; break;
case 2: inst = InstructionConstants.ICONST_2; break;
case 3: inst = InstructionConstants.ICONST_3; break;
case 4: inst = InstructionConstants.ICONST_4; break;
case 5: inst = InstructionConstants.ICONST_5; break;
}
if (i <= Byte.MAX_VALUE && i >= Byte.MIN_VALUE) {
inst = new BIPUSH((byte)i);
} else if (i <= Short.MAX_VALUE && i >= Short.MIN_VALUE) {
inst = new SIPUSH((short)i);
} else {
inst = new LDC(fact.getClassGen().getConstantPool().addInteger(i));
}
return inst;
}
public static JavaClass makeJavaClass(String filename, byte[] bytes) {
try {
ClassParser parser = new ClassParser(new ByteArrayInputStream(bytes), filename);
return parser.parse();
} catch (IOException e) {
throw new BCException("malformed class file");
}
}
public static String arrayToString(int[] a) {
int len = a.length;
if (len == 0) return "[]";
StringBuffer buf = new StringBuffer("[");
buf.append(a[0]);
for (int i = 1; i < len; i++) {
buf.append(", ");
buf.append(a[i]);
}
buf.append("]");
return buf.toString();
}
/**
* replace an instruction handle with another instruction, in this case, a branch instruction.
*
* @param ih the instruction handle to replace.
* @param branchInstruction the branch instruction to replace ih with
* @param enclosingMethod where to find ih's instruction list.
*/
public static void replaceInstruction(
InstructionHandle ih,
BranchInstruction branchInstruction,
LazyMethodGen enclosingMethod)
{
InstructionList il = enclosingMethod.getBody();
InstructionHandle fresh = il.append(ih, branchInstruction);
deleteInstruction(ih, fresh, enclosingMethod);
}
/** delete an instruction handle and retarget all targeters of the deleted instruction
* to the next instruction. Obviously, this should not be used to delete
* a control transfer instruction unless you know what you're doing.
*
* @param ih the instruction handle to delete.
* @param enclosingMethod where to find ih's instruction list.
*/
public static void deleteInstruction(
InstructionHandle ih,
LazyMethodGen enclosingMethod)
{
deleteInstruction(ih, ih.getNext(), enclosingMethod);
}
/** delete an instruction handle and retarget all targeters of the deleted instruction
* to the provided target.
*
* @param ih the instruction handle to delete
* @param retargetTo the instruction handle to retarget targeters of ih to.
* @param enclosingMethod where to find ih's instruction list.
*/
public static void deleteInstruction(
InstructionHandle ih,
InstructionHandle retargetTo,
LazyMethodGen enclosingMethod)
{
InstructionList il = enclosingMethod.getBody();
InstructionTargeter[] targeters = ih.getTargeters();
if (targeters != null) {
for (int i = targeters.length - 1; i >= 0; i--) {
InstructionTargeter targeter = targeters[i];
targeter.updateTarget(ih, retargetTo);
}
ih.removeAllTargeters();
}
try {
il.delete(ih);
} catch (TargetLostException e) {
throw new BCException("this really can't happen");
}
}
/**
* Fix for Bugzilla #39479, #40109 patch contributed by Andy Clement
*
* Need to manually copy Select instructions - if we rely on the the 'fresh' object
* created by copy(), the InstructionHandle array 'targets' inside the Select
* object will not have been deep copied, so modifying targets in fresh will modify
* the original Select - not what we want ! (It is a bug in BCEL to do with cloning
* Select objects).
*
* <pre>
* declare error:
* call(* Instruction.copy()) && within(org.aspectj.weaver)
* && !withincode(* Utility.copyInstruction(Instruction)):
* "use Utility.copyInstruction to work-around bug in Select.copy()";
* </pre>
*/
public static Instruction copyInstruction(Instruction i) {
if (i instanceof Select) {
Select freshSelect = (Select)i;
// Create a new targets array that looks just like the existing one
InstructionHandle[] targets = new InstructionHandle[freshSelect.getTargets().length];
for (int ii = 0; ii < targets.length; ii++) {
targets[ii] = freshSelect.getTargets()[ii];
}
// Create a new select statement with the new targets array
SWITCH switchStatement =
new SWITCH(freshSelect.getMatchs(), targets, freshSelect.getTarget());
return (Select)switchStatement.getInstruction();
} else {
return i.copy(); // Use clone for shallow copy...
}
}
/** returns -1 if no source line attribute */
// this naive version overruns the JVM stack size, if only Java understood tail recursion...
// public static int getSourceLine(InstructionHandle ih) {
// if (ih == null) return -1;
//
// InstructionTargeter[] ts = ih.getTargeters();
// if (ts != null) {
// for (int j = ts.length - 1; j >= 0; j--) {
// InstructionTargeter t = ts[j];
// if (t instanceof LineNumberTag) {
// return ((LineNumberTag)t).getLineNumber();
// }
// }
// }
// return getSourceLine(ih.getNext());
// }
public static int getSourceLine(InstructionHandle ih) {//,boolean goforwards) {
int lookahead=0;
// arbitrary rule that we will never lookahead more than 100 instructions for a line #
while (lookahead++ < 100) {
if (ih == null) return -1;
InstructionTargeter[] ts = ih.getTargeters();
if (ts != null) {
for (int j = ts.length - 1; j >= 0; j--) {
InstructionTargeter t = ts[j];
if (t instanceof LineNumberTag) {
return ((LineNumberTag)t).getLineNumber();
}
}
}
// if (goforwards) ih=ih.getNext(); else
ih=ih.getPrev();
}
//System.err.println("no line information available for: " + ih);
return -1;
}
// public static int getSourceLine(InstructionHandle ih) {
// return getSourceLine(ih,false);
// }
// assumes that there is no already extant source line tag. Otherwise we'll have to be better.
public static void setSourceLine(InstructionHandle ih, int lineNumber) {
ih.addTargeter(new LineNumberTag(lineNumber));
}
public static int makePublic(int i) {
return i & ~(Modifier.PROTECTED | Modifier.PRIVATE) | Modifier.PUBLIC;
}
public static int makePrivate(int i) {
return i & ~(Modifier.PROTECTED | Modifier.PUBLIC) | Modifier.PRIVATE;
}
public static BcelVar[] pushAndReturnArrayOfVars(
ResolvedType[] proceedParamTypes,
InstructionList il,
InstructionFactory fact,
LazyMethodGen enclosingMethod)
{
int len = proceedParamTypes.length;
BcelVar[] ret = new BcelVar[len];
for (int i = len - 1; i >= 0; i--) {
ResolvedType typeX = proceedParamTypes[i];
Type type = BcelWorld.makeBcelType(typeX);
int local = enclosingMethod.allocateLocal(type);
il.append(InstructionFactory.createStore(type, local));
ret[i] = new BcelVar(typeX, local);
}
return ret;
}
public static boolean isConstantPushInstruction(Instruction i) {
return (i instanceof ConstantPushInstruction) || (i instanceof LDC);
}
/**
* Check if the annotations contain a SuppressAjWarnings annotation and
* if that annotation specifies that the given lint message (identified
* by its key) should be ignored.
*
*/
public static boolean isSuppressing(AnnotationX[] anns,String lintkey) {
if (anns == null) return false;
boolean suppressed = false;
// Go through the annotation types on the advice
for (int i = 0;!suppressed && i<anns.length;i++) {
// Check for the SuppressAjWarnings annotation
if (UnresolvedType.SUPPRESS_AJ_WARNINGS.getSignature().equals(anns[i].getBcelAnnotation().getTypeSignature())) {
// Two possibilities:
// 1. there are no values specified (i.e. @SuppressAjWarnings)
// 2. there are values specified (i.e. @SuppressAjWarnings("A") or @SuppressAjWarnings({"A","B"})
List vals = anns[i].getBcelAnnotation().getValues();
if (vals == null || vals.size()==0) { // (1)
suppressed = true;
} else { // (2)
// We know the value is an array value
ArrayElementValue array = (ArrayElementValue)((ElementNameValuePair)vals.get(0)).getValue();
ElementValue[] values = array.getElementValuesArray();
for (int j = 0; j < values.length; j++) {
// We know values in the array are strings
SimpleElementValue value = (SimpleElementValue)values[j];
if (value.getValueString().equals(lintkey)) {
suppressed = true;
}
}
}
}
}
return suppressed;
}
public static List/*Lint.Kind*/ getSuppressedWarnings(AnnotationX[] anns, Lint lint) {
if (anns == null) return Collections.EMPTY_LIST;
// Go through the annotation types
List suppressedWarnings = new ArrayList();
boolean found = false;
for (int i = 0;!found && i<anns.length;i++) {
// Check for the SuppressAjWarnings annotation
if (UnresolvedType.SUPPRESS_AJ_WARNINGS.getSignature().equals(anns[i].getBcelAnnotation().getTypeSignature())) {
found = true;
// Two possibilities:
// 1. there are no values specified (i.e. @SuppressAjWarnings)
// 2. there are values specified (i.e. @SuppressAjWarnings("A") or @SuppressAjWarnings({"A","B"})
List vals = anns[i].getBcelAnnotation().getValues();
if (vals == null || vals.size()==0) { // (1)
suppressedWarnings.addAll(lint.allKinds());
} else { // (2)
// We know the value is an array value
ArrayElementValue array = (ArrayElementValue)((ElementNameValuePair)vals.get(0)).getValue();
ElementValue[] values = array.getElementValuesArray();
for (int j = 0; j < values.length; j++) {
// We know values in the array are strings
SimpleElementValue value = (SimpleElementValue)values[j];
Lint.Kind lintKind = lint.getLintKind(value.getValueString());
if (lintKind != null) suppressedWarnings.add(lintKind);
}
}
}
}
return suppressedWarnings;
}
// not yet used...
public static boolean isSimple(Method method) {
if (method.getCode()==null) return true;
if (method.getCode().getCode().length>10) return false;
InstructionList instrucs = new InstructionList(method.getCode().getCode()); // expensive!
InstructionHandle InstrHandle = instrucs.getStart();
while (InstrHandle != null) {
Instruction Instr = InstrHandle.getInstruction();
int opCode = Instr.getOpcode();
// if current instruction is a branch instruction, see if it's a backward branch.
// if it is return immediately (can't be trivial)
if (Instr instanceof BranchInstruction) {
BranchInstruction BI = (BranchInstruction) Instr;
if (BI.getIndex() < 0) return false;
} else if (Instr instanceof InvokeInstruction) {
// if current instruction is an invocation, indicate that it can't be trivial
return false;
}
InstrHandle = InstrHandle.getNext();
}
return true;
}
}
|
147,711 |
Bug 147711 Add an option to generate aj-synthetics with true synthetic flag
|
In a number of cases tools are getting confused over generated aj members that are "aj-synthetic" but not marked with the synthetic attribute (because in the past, this has upset other tools). The most recent example was a JAXB posting on the list - by having a perthis() clause in an aspect that matched a type with JAXB 2 annotations the user was no longer able to use JAXB. This is a serious issue, and will prevent the usage of JAXB 2 with any type into which we introduce properties as aj-synthetic members. The JAXB 2 solution to ignore such fields is to annotate them with @XmlTransient, but since the field does not exist in the user program they can't even do this!
|
resolved fixed
|
c9f311a
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-06-24T11:36:59Z | 2006-06-19T12:26:40Z |
org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/compiler/ast/AdviceDeclaration.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.compiler.ast;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.List;
import org.aspectj.ajdt.internal.compiler.lookup.AjTypeConstants;
import org.aspectj.ajdt.internal.compiler.lookup.EclipseFactory;
import org.aspectj.ajdt.internal.compiler.lookup.PrivilegedHandler;
import org.aspectj.bridge.context.CompilationAndWeavingContext;
import org.aspectj.bridge.context.ContextToken;
import org.aspectj.org.eclipse.jdt.core.compiler.CharOperation;
import org.aspectj.org.eclipse.jdt.internal.compiler.ClassFile;
import org.aspectj.org.eclipse.jdt.internal.compiler.CompilationResult;
import org.aspectj.org.eclipse.jdt.internal.compiler.ast.Annotation;
import org.aspectj.org.eclipse.jdt.internal.compiler.ast.Argument;
import org.aspectj.org.eclipse.jdt.internal.compiler.ast.TypeDeclaration;
import org.aspectj.org.eclipse.jdt.internal.compiler.ast.TypeReference;
import org.aspectj.org.eclipse.jdt.internal.compiler.codegen.CodeStream;
import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.ArrayBinding;
import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.ClassScope;
import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.MethodBinding;
import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.ReferenceBinding;
import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.TypeBinding;
import org.aspectj.weaver.Advice;
import org.aspectj.weaver.AdviceKind;
import org.aspectj.weaver.AjAttribute;
import org.aspectj.weaver.NameMangler;
import org.aspectj.weaver.ResolvedMember;
import org.aspectj.weaver.UnresolvedType;
/**
* Represents before, after and around advice in an aspect.
* Will generate a method corresponding to the body of the advice with an
* attribute including additional information.
*
* @author Jim Hugunin
*/
public class AdviceDeclaration extends AjMethodDeclaration {
public PointcutDesignator pointcutDesignator; // set during parsing
int baseArgumentCount; // referenced by IfPseudoToken.makeArguments
public Argument extraArgument; // set during parsing, referenced by Proceed
public AdviceKind kind; // set during parsing, referenced by Proceed and AsmElementFormatter
private int extraArgumentFlags = 0;
public MethodBinding proceedMethodBinding; // set during this.resolveStaments, referenced by Proceed
public List proceedCalls = new ArrayList(2); // populated during Proceed.findEnclosingAround
private boolean proceedInInners;
private ResolvedMember[] proceedCallSignatures;
private boolean[] formalsUnchangedToProceed;
private UnresolvedType[] declaredExceptions;
public AdviceDeclaration(CompilationResult result, AdviceKind kind) {
super(result);
this.returnType = TypeReference.baseTypeReference(T_void, 0);
this.kind = kind;
}
// override
protected int generateInfoAttributes(ClassFile classFile) {
List l = new ArrayList(1);
l.add(new EclipseAttributeAdapter(makeAttribute()));
addDeclarationStartLineAttribute(l,classFile);
return classFile.generateMethodInfoAttribute(binding, false, l);
}
private AjAttribute makeAttribute() {
if (kind == AdviceKind.Around) {
return new AjAttribute.AdviceAttribute(kind, pointcutDesignator.getPointcut(),
extraArgumentFlags, sourceStart, sourceEnd, null,
proceedInInners, proceedCallSignatures, formalsUnchangedToProceed,
declaredExceptions);
} else {
return new AjAttribute.AdviceAttribute(kind, pointcutDesignator.getPointcut(),
extraArgumentFlags, sourceStart, sourceEnd, null);
}
}
// override
public void resolveStatements() {
if (binding == null || ignoreFurtherInvestigation) return;
ClassScope upperScope = (ClassScope)scope.parent; //!!! safety
modifiers = checkAndSetModifiers(modifiers, upperScope);
int bindingModifiers = (modifiers | (binding.modifiers & AccGenericSignature));
binding.modifiers = bindingModifiers;
if (kind == AdviceKind.AfterThrowing && extraArgument != null) {
TypeBinding argTb = extraArgument.binding.type;
TypeBinding expectedTb = upperScope.getJavaLangThrowable();
if (!argTb.isCompatibleWith(expectedTb)) {
scope.problemReporter().typeMismatchError(argTb, expectedTb, extraArgument);
ignoreFurtherInvestigation = true;
return;
}
}
pointcutDesignator.finishResolveTypes(this, this.binding,
baseArgumentCount, upperScope.referenceContext.binding);
if (binding == null || ignoreFurtherInvestigation) return;
if (kind == AdviceKind.Around) {
ReferenceBinding[] exceptions =
new ReferenceBinding[] { upperScope.getJavaLangThrowable() };
proceedMethodBinding = new MethodBinding(Modifier.STATIC,
"proceed".toCharArray(), binding.returnType,
resize(baseArgumentCount+1, binding.parameters),
exceptions, binding.declaringClass);
proceedMethodBinding.selector =
CharOperation.concat(selector, proceedMethodBinding.selector);
}
super.resolveStatements(); //upperScope);
if (binding != null) determineExtraArgumentFlags();
if (kind == AdviceKind.Around) {
int n = proceedCalls.size();
// EclipseFactory world = EclipseFactory.fromScopeLookupEnvironment(upperScope);
//System.err.println("access to: " + Arrays.asList(handler.getMembers()));
//XXX set these correctly
formalsUnchangedToProceed = new boolean[baseArgumentCount];
proceedCallSignatures = new ResolvedMember[0];
proceedInInners = false;
declaredExceptions = new UnresolvedType[0];
for (int i=0; i < n; i++) {
Proceed call = (Proceed)proceedCalls.get(i);
if (call.inInner) {
//System.err.println("proceed in inner: " + call);
proceedInInners = true;
//XXX wrong
//proceedCallSignatures[i] = world.makeResolvedMember(call.binding);
}
}
// ??? should reorganize into AspectDeclaration
// if we have proceed in inners we won't ever be inlined so the code below is unneeded
if (!proceedInInners) {
PrivilegedHandler handler = (PrivilegedHandler)upperScope.referenceContext.binding.privilegedHandler;
if (handler == null) {
handler = new PrivilegedHandler((AspectDeclaration)upperScope.referenceContext);
//upperScope.referenceContext.binding.privilegedHandler = handler;
}
this.traverse(new MakeDeclsPublicVisitor(), (ClassScope)null);
AccessForInlineVisitor v = new AccessForInlineVisitor((AspectDeclaration)upperScope.referenceContext, handler);
ContextToken tok = CompilationAndWeavingContext.enteringPhase(CompilationAndWeavingContext.ACCESS_FOR_INLINE, selector);
this.traverse(v, (ClassScope) null);
CompilationAndWeavingContext.leavingPhase(tok);
// ??? if we found a construct that we can't inline, set
// proceedInInners so that we won't try to inline this body
if (!v.isInlinable) proceedInInners = true;
}
}
}
// called by Proceed.resolveType
public int getDeclaredParameterCount() {
// this only works before code generation
return this.arguments.length - 3 - ((extraArgument == null) ? 0 : 1);
//Advice.countOnes(extraArgumentFlags);
}
private void generateProceedMethod(ClassScope classScope, ClassFile classFile) {
MethodBinding binding = (MethodBinding)proceedMethodBinding;
classFile.generateMethodInfoHeader(binding);
int methodAttributeOffset = classFile.contentsOffset;
int attributeNumber = classFile.generateMethodInfoAttribute(binding, false, AstUtil.getAjSyntheticAttribute());
int codeAttributeOffset = classFile.contentsOffset;
classFile.generateCodeAttributeHeader();
CodeStream codeStream = classFile.codeStream;
codeStream.reset(this, classFile);
// push the closure
int nargs = binding.parameters.length;
int closureIndex = 0;
for (int i=0; i < nargs-1; i++) {
closureIndex += AstUtil.slotsNeeded(binding.parameters[i]);
}
codeStream.loadObject(closureIndex);
// build the Object[]
codeStream.generateInlinedValue(nargs-1);
codeStream.newArray(
new ArrayBinding(
classScope.getType(TypeBinding.JAVA_LANG_OBJECT,
TypeBinding.JAVA_LANG_OBJECT.length),
1,
classScope.environment()));
int index = 0;
for (int i=0; i < nargs-1; i++) {
TypeBinding type = binding.parameters[i];
codeStream.dup();
codeStream.generateInlinedValue(i);
codeStream.load(type, index);
index += AstUtil.slotsNeeded(type);
if (type.isBaseType()) {
codeStream.invokestatic(AjTypeConstants.getConversionMethodToObject(classScope, type));
}
codeStream.aastore();
}
// call run
ReferenceBinding closureType = (ReferenceBinding)binding.parameters[nargs-1];
MethodBinding runMethod = closureType.getMethods("run".toCharArray())[0];
codeStream.invokevirtual(runMethod);
TypeBinding returnType = binding.returnType;
if (returnType.isBaseType()) {
codeStream.invokestatic(AjTypeConstants.getConversionMethodFromObject(classScope, returnType));
} else {
codeStream.checkcast(returnType);
}
AstUtil.generateReturn(returnType, codeStream);
codeStream.recordPositionsFrom(0,1);
classFile.completeCodeAttribute(codeAttributeOffset);
attributeNumber++;
classFile.completeMethodInfo(methodAttributeOffset, attributeNumber);
}
// override
public void generateCode(ClassScope classScope, ClassFile classFile) {
if (ignoreFurtherInvestigation) return;
super.generateCode(classScope, classFile);
if (proceedMethodBinding != null) {
generateProceedMethod(classScope, classFile);
}
}
private void determineExtraArgumentFlags() {
if (extraArgument != null) extraArgumentFlags |= Advice.ExtraArgument;
ThisJoinPointVisitor tjp = new ThisJoinPointVisitor(this);
extraArgumentFlags |= tjp.removeUnusedExtraArguments();
}
private static TypeBinding[] resize(int newSize, TypeBinding[] bindings) {
int len = bindings.length;
TypeBinding[] ret = new TypeBinding[newSize];
System.arraycopy(bindings, 0, ret, 0, Math.min(newSize, len));
return ret;
}
/**
* Add either the @Before, @After, @Around, @AfterReturning or @AfterThrowing annotation
*/
public void addAtAspectJAnnotations() {
Annotation adviceAnnotation = null;
String pointcutExpression = pointcutDesignator.getPointcut().toString();
String extraArgumentName = "";
if (extraArgument != null) {
extraArgumentName = new String(extraArgument.name);
}
String argNames = buildArgNameRepresentation();
if (kind == AdviceKind.Before) {
adviceAnnotation = AtAspectJAnnotationFactory.createBeforeAnnotation(pointcutExpression,argNames,declarationSourceStart);
} else if (kind == AdviceKind.After) {
adviceAnnotation = AtAspectJAnnotationFactory.createAfterAnnotation(pointcutExpression,argNames,declarationSourceStart);
} else if (kind == AdviceKind.AfterReturning) {
adviceAnnotation = AtAspectJAnnotationFactory.createAfterReturningAnnotation(pointcutExpression,argNames,extraArgumentName,declarationSourceStart);
} else if (kind == AdviceKind.AfterThrowing) {
adviceAnnotation = AtAspectJAnnotationFactory.createAfterThrowingAnnotation(pointcutExpression,argNames,extraArgumentName,declarationSourceStart);
} else if (kind == AdviceKind.Around) {
adviceAnnotation = AtAspectJAnnotationFactory.createAroundAnnotation(pointcutExpression,argNames,declarationSourceStart);
}
AtAspectJAnnotationFactory.addAnnotation(this, adviceAnnotation,this.scope);
}
private String buildArgNameRepresentation() {
StringBuffer args = new StringBuffer();
int numArgsWeCareAbout = getDeclaredParameterCount();
if (this.arguments != null) {
for (int i = 0; i < numArgsWeCareAbout; i++) {
if (i != 0) args.append(",");
args.append(new String(this.arguments[i].name));
}
}
if (extraArgument != null) {
if (numArgsWeCareAbout > 0) { args.append(","); }
args.append(new String(extraArgument.name));
}
return args.toString();
}
// override, Called by ClassScope.postParse
public void postParse(TypeDeclaration typeDec) {
AspectDeclaration aspectDecl = (AspectDeclaration)typeDec;
int adviceSequenceNumberInType = aspectDecl.adviceCounter++;
StringBuffer stringifiedPointcut = new StringBuffer(30);
pointcutDesignator.print(0,stringifiedPointcut);
this.selector =
NameMangler.adviceName(
EclipseFactory.getName(typeDec.binding).replace('.', '_'),
kind,
adviceSequenceNumberInType,
stringifiedPointcut.toString().hashCode()).toCharArray();
if (arguments != null) {
baseArgumentCount = arguments.length;
}
if (kind == AdviceKind.Around) {
extraArgument = makeFinalArgument("ajc_aroundClosure",
AjTypeConstants.getAroundClosureType());
}
int addedArguments = 3;
if (extraArgument != null) {
addedArguments += 1;
}
arguments = extendArgumentsLength(arguments, addedArguments);
int index = baseArgumentCount;
if (extraArgument != null) {
arguments[index++] = extraArgument;
}
arguments[index++] = makeFinalArgument("thisJoinPointStaticPart", AjTypeConstants.getJoinPointStaticPartType());
arguments[index++] = makeFinalArgument("thisJoinPoint", AjTypeConstants.getJoinPointType());
arguments[index++] = makeFinalArgument("thisEnclosingJoinPointStaticPart", AjTypeConstants.getJoinPointStaticPartType());
if (pointcutDesignator.isError()) {
this.ignoreFurtherInvestigation = true;
}
pointcutDesignator.postParse(typeDec, this);
}
private int checkAndSetModifiers(int modifiers, ClassScope scope) {
if (modifiers == 0) return Modifier.PUBLIC;
else if (modifiers == Modifier.STRICT) return Modifier.PUBLIC | Modifier.STRICT;
else {
tagAsHavingErrors();
scope.problemReporter().signalError(declarationSourceStart, sourceStart-1, "illegal modifier on advice, only strictfp is allowed");
return Modifier.PUBLIC;
}
}
// called by IfPseudoToken
public static Argument[] addTjpArguments(Argument[] arguments) {
int index = arguments.length;
arguments = extendArgumentsLength(arguments, 3);
arguments[index++] = makeFinalArgument("thisJoinPointStaticPart", AjTypeConstants.getJoinPointStaticPartType());
arguments[index++] = makeFinalArgument("thisJoinPoint", AjTypeConstants.getJoinPointType());
arguments[index++] = makeFinalArgument("thisEnclosingJoinPointStaticPart", AjTypeConstants.getJoinPointStaticPartType());
return arguments;
}
private static Argument makeFinalArgument(String name, TypeReference typeRef) {
long pos = 0; //XXX encode start and end location
return new Argument(name.toCharArray(), pos, typeRef, Modifier.FINAL);
}
private static Argument[] extendArgumentsLength(Argument[] args, int addedArguments) {
if (args == null) {
return new Argument[addedArguments];
}
int len = args.length;
Argument[] ret = new Argument[len + addedArguments];
System.arraycopy(args, 0, ret, 0, len);
return ret;
}
// public String toString(int tab) {
// String s = tabString(tab);
// if (modifiers != AccDefault) {
// s += modifiersString(modifiers);
// }
//
// if (kind == AdviceKind.Around) {
// s += returnTypeToString(0);
// }
//
// s += new String(selector) + "("; //$NON-NLS-1$
// if (arguments != null) {
// for (int i = 0; i < arguments.length; i++) {
// s += arguments[i].toString(0);
// if (i != (arguments.length - 1))
// s = s + ", "; //$NON-NLS-1$
// };
// };
// s += ")"; //$NON-NLS-1$
//
// if (extraArgument != null) {
// s += "(" + extraArgument.toString(0) + ")";
// }
//
//
//
// if (thrownExceptions != null) {
// s += " throws "; //$NON-NLS-1$
// for (int i = 0; i < thrownExceptions.length; i++) {
// s += thrownExceptions[i].toString(0);
// if (i != (thrownExceptions.length - 1))
// s = s + ", "; //$NON-NLS-1$
// };
// };
//
// s += ": ";
// if (pointcutDesignator != null) {
// s += pointcutDesignator.toString(0);
// }
//
// s += toStringStatements(tab + 1);
// return s;
// }
public StringBuffer printBody(int indent, StringBuffer output) {
output.append(": ");
if (pointcutDesignator != null) {
output.append(pointcutDesignator.toString());
}
return super.printBody(indent,output);
}
public StringBuffer printReturnType(int indent, StringBuffer output) {
if (this.kind == AdviceKind.Around) {
return super.printReturnType(indent,output);
}
return output;
}
}
|
147,711 |
Bug 147711 Add an option to generate aj-synthetics with true synthetic flag
|
In a number of cases tools are getting confused over generated aj members that are "aj-synthetic" but not marked with the synthetic attribute (because in the past, this has upset other tools). The most recent example was a JAXB posting on the list - by having a perthis() clause in an aspect that matched a type with JAXB 2 annotations the user was no longer able to use JAXB. This is a serious issue, and will prevent the usage of JAXB 2 with any type into which we introduce properties as aj-synthetic members. The JAXB 2 solution to ignore such fields is to annotate them with @XmlTransient, but since the field does not exist in the user program they can't even do this!
|
resolved fixed
|
c9f311a
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-06-24T11:36:59Z | 2006-06-19T12:26:40Z |
org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/compiler/ast/DeclareDeclaration.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.compiler.ast;
//import java.util.List;
import java.util.Collection;
import java.util.Iterator;
import org.aspectj.ajdt.internal.compiler.lookup.EclipseScope;
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.ast.Annotation;
import org.aspectj.org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration;
import org.aspectj.org.eclipse.jdt.internal.compiler.ast.TypeDeclaration;
import org.aspectj.org.eclipse.jdt.internal.compiler.ast.TypeReference;
import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.ClassScope;
import org.aspectj.org.eclipse.jdt.internal.compiler.parser.Parser;
import org.aspectj.weaver.AjAttribute;
import org.aspectj.weaver.UnresolvedType;
import org.aspectj.weaver.patterns.Declare;
import org.aspectj.weaver.patterns.DeclareAnnotation;
import org.aspectj.weaver.patterns.DeclareErrorOrWarning;
import org.aspectj.weaver.patterns.DeclareParents;
import org.aspectj.weaver.patterns.DeclarePrecedence;
import org.aspectj.weaver.patterns.DeclareSoft;
import org.aspectj.weaver.patterns.FormalBinding;
public class DeclareDeclaration extends AjMethodDeclaration {
public Declare declareDecl;
/**
* Constructor for IntraTypeDeclaration.
*/
public DeclareDeclaration(CompilationResult result, Declare symbolicDeclare) {
super(result);
this.declareDecl = symbolicDeclare;
if (declareDecl != null) {
// AMC added init of declarationSourceXXX fields which are used
// in AsmBuilder for processing of MethodDeclaration locations.
declarationSourceStart = sourceStart = declareDecl.getStart();
declarationSourceEnd = sourceEnd = declareDecl.getEnd();
}
//??? we might need to set parameters to be empty
this.returnType = TypeReference.baseTypeReference(T_void, 0);
}
public void addAtAspectJAnnotations() {
Annotation annotation = null;
if (declareDecl instanceof DeclareAnnotation) {
DeclareAnnotation da = (DeclareAnnotation) declareDecl;
String patternString = da.getPatternAsString();
String annString = da.getAnnotationString();
String kind = da.getKind().toString();
annotation = AtAspectJAnnotationFactory.createDeclareAnnAnnotation(
patternString,annString,kind,declarationSourceStart);
} else if (declareDecl instanceof DeclareErrorOrWarning) {
DeclareErrorOrWarning dd = (DeclareErrorOrWarning) declareDecl;
annotation = AtAspectJAnnotationFactory
.createDeclareErrorOrWarningAnnotation(dd.getPointcut().toString(),dd.getMessage(),dd.isError(),declarationSourceStart);
} else if (declareDecl instanceof DeclareParents) {
DeclareParents dp = (DeclareParents) declareDecl;
String childPattern = dp.getChild().toString();
Collection parentPatterns = dp.getParents().getExactTypes();
StringBuffer parents = new StringBuffer();
for (Iterator iter = parentPatterns.iterator(); iter.hasNext();) {
UnresolvedType urt = ((UnresolvedType) iter.next());
parents.append(urt.getName());
if (iter.hasNext()) parents.append(", ");
}
annotation = AtAspectJAnnotationFactory
.createDeclareParentsAnnotation(childPattern,parents.toString(),dp.isExtends(),declarationSourceStart);
} else if (declareDecl instanceof DeclarePrecedence) {
DeclarePrecedence dp = (DeclarePrecedence) declareDecl;
String precedenceList = dp.getPatterns().toString();
annotation = AtAspectJAnnotationFactory.createDeclarePrecedenceAnnotation(precedenceList,declarationSourceStart);
} else if (declareDecl instanceof DeclareSoft) {
DeclareSoft ds = (DeclareSoft) declareDecl;
annotation = AtAspectJAnnotationFactory
.createDeclareSoftAnnotation(ds.getPointcut().toString(),ds.getException().getExactType().getName(),declarationSourceStart);
}
if (annotation != null) AtAspectJAnnotationFactory.addAnnotation(this,annotation,this.scope);
}
/**
* A declare declaration exists in a classfile only as an attibute on the
* class. Unlike advice and inter-type declarations, it has no corresponding
* method.
* **AMC** changed the above policy in the case of declare annotation, which uses a
* corresponding method as the anchor for the declared annotation
*/
public void generateCode(ClassScope classScope, ClassFile classFile) {
classFile.extraAttributes.add(new EclipseAttributeAdapter(new AjAttribute.DeclareAttribute(declareDecl)));
if (shouldDelegateCodeGeneration()) {
super.generateCode(classScope,classFile);
}
return;
}
protected boolean shouldDelegateCodeGeneration() {
return true;
}
public void parseStatements(
Parser parser,
CompilationUnitDeclaration unit) {
// do nothing
}
public void resolveStatements(ClassScope upperScope) {
// do nothing
}
// public boolean finishResolveTypes(SourceTypeBinding sourceTypeBinding) {
// // there's nothing for our super to resolve usefully
// //if (!super.finishResolveTypes(sourceTypeBinding)) return false;
//// if (declare == null) return true;
////
//// EclipseScope scope = new EclipseScope(new FormalBinding[0], this.scope);
////
//// declare.resolve(scope);
//// return true;
// }
public Declare build(ClassScope classScope) {
if (declareDecl == null) return null;
EclipseScope scope = new EclipseScope(new FormalBinding[0], classScope);
declareDecl.resolve(scope);
return declareDecl;
}
public StringBuffer print(int tab, StringBuffer output) {
printIndent(tab, output);
if (declareDecl == null) {
output.append("<declare>");
} else {
output.append(declareDecl.toString());
}
return output;
}
/**
* We need the ajc$declare method that is created to represent this declare to
* be marked as synthetic
*/
protected int generateInfoAttributes(ClassFile classFile) {
return super.generateInfoAttributes(classFile,true);
}
public void postParse(TypeDeclaration typeDec) {
super.postParse(typeDec);
int declareSequenceNumberInType = ((AspectDeclaration)typeDec).declareCounter++;
//FIXME asc the name should perhaps include the hashcode of the pattern (type/sig) for binary compatibility reasons!
StringBuffer sb = new StringBuffer();
sb.append("ajc$declare");
// Declares can choose to provide a piece of the name - to enable
// them to be easily distinguised at weave time (e.g. see declare annotation)
if (declareDecl!=null) {
String suffix = declareDecl.getNameSuffix();
if (suffix.length()!=0) {
sb.append("_");
sb.append(suffix);
}
}
sb.append("_");
sb.append(declareSequenceNumberInType);
this.selector = sb.toString().toCharArray();
}
}
|
147,711 |
Bug 147711 Add an option to generate aj-synthetics with true synthetic flag
|
In a number of cases tools are getting confused over generated aj members that are "aj-synthetic" but not marked with the synthetic attribute (because in the past, this has upset other tools). The most recent example was a JAXB posting on the list - by having a perthis() clause in an aspect that matched a type with JAXB 2 annotations the user was no longer able to use JAXB. This is a serious issue, and will prevent the usage of JAXB 2 with any type into which we introduce properties as aj-synthetic members. The JAXB 2 solution to ignore such fields is to annotate them with @XmlTransient, but since the field does not exist in the user program they can't even do this!
|
resolved fixed
|
c9f311a
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-06-24T11:36:59Z | 2006-06-19T12:26:40Z |
org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/compiler/ast/PointcutDeclaration.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.compiler.ast;
import java.lang.reflect.Modifier;
import java.util.Iterator;
import org.aspectj.ajdt.internal.compiler.lookup.EclipseFactory;
import org.aspectj.ajdt.internal.core.builder.EclipseSourceContext;
import org.aspectj.org.eclipse.jdt.core.compiler.CharOperation;
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.ast.Annotation;
import org.aspectj.org.eclipse.jdt.internal.compiler.ast.Argument;
import org.aspectj.org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration;
import org.aspectj.org.eclipse.jdt.internal.compiler.ast.TypeDeclaration;
import org.aspectj.org.eclipse.jdt.internal.compiler.ast.TypeReference;
import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.ClassScope;
import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.TagBits;
import org.aspectj.org.eclipse.jdt.internal.compiler.parser.Parser;
import org.aspectj.weaver.AjAttribute;
import org.aspectj.weaver.ResolvedPointcutDefinition;
import org.aspectj.weaver.patterns.Pointcut;
/**
* pointcut [declaredModifiers] [declaredName]([arguments]): [pointcutDesignator];
*
* <p>No method will actually be generated for this node but an attribute
* will be added to the enclosing class.</p>
*
* @author Jim Hugunin
*/
public class PointcutDeclaration extends AjMethodDeclaration {
public static final char[] mangledPrefix = "ajc$pointcut$".toCharArray();
public PointcutDesignator pointcutDesignator;
private int declaredModifiers;
private String declaredName;
private boolean generateSyntheticPointcutMethod = false;
private EclipseFactory world = null;
//private boolean mangleSelector = true;
private ResolvedPointcutDefinition resolvedPointcutDeclaration = null;
public PointcutDeclaration(CompilationResult compilationResult) {
super(compilationResult);
this.returnType = TypeReference.baseTypeReference(T_void, 0);
}
private Pointcut getPointcut() {
if (pointcutDesignator == null) {
return Pointcut.makeMatchesNothing(Pointcut.RESOLVED);
} else {
return pointcutDesignator.getPointcut();
}
}
public void parseStatements(
Parser parser,
CompilationUnitDeclaration unit) {
// do nothing
}
public void postParse(TypeDeclaration typeDec) {
if (arguments == null) arguments = new Argument[0];
this.declaredModifiers = modifiers;
this.declaredName = new String(selector);
// amc - if we set mangle selector to false, then the generated bytecode has the
// pointcut method name that the user of an @Pointcut would expect.
// But then we will unpack it again in the weaver which may cause redundant
// error messages to be issued. This seems the better trade-off...
//if (mangleSelector) {
selector = CharOperation.concat(mangledPrefix, '$', selector, '$',
Integer.toHexString(sourceStart).toCharArray());
//}
if (Modifier.isAbstract(this.declaredModifiers)) {
if (!(typeDec instanceof AspectDeclaration)) {
// check for @Aspect
if (isAtAspectJ(typeDec)) {
;//no need to check abstract class as JDT does that
} else {
typeDec.scope.problemReporter().signalError(sourceStart, sourceEnd,
"The abstract pointcut " + new String(declaredName) +
" can only be defined in an aspect");
ignoreFurtherInvestigation = true;
return;
}
} else if (!Modifier.isAbstract(typeDec.modifiers)) {
typeDec.scope.problemReporter().signalError(sourceStart, sourceEnd,
"The abstract pointcut " + new String(declaredName) +
" can only be defined in an abstract aspect");
ignoreFurtherInvestigation = true;
return;
}
}
if (pointcutDesignator != null) {
pointcutDesignator.postParse(typeDec, this);
}
}
private boolean isAtAspectJ(TypeDeclaration typeDec) {
if (typeDec.annotations == null)
return false;
for (int i = 0; i < typeDec.annotations.length; i++) {
Annotation annotation = typeDec.annotations[i];
if ("Lorg/aspectj/lang/annotation/Aspect;".equals(new String(annotation.resolvedType.signature()))) {
return true;
}
}
return false;
}
/**
* Called from the AtAspectJVisitor to create the @Pointcut annotation
* (and corresponding method) for this pointcut
*
*/
public void addAtAspectJAnnotations() {
String argNames = buildArgNameRepresentation();
Annotation pcutAnnotation =
AtAspectJAnnotationFactory.createPointcutAnnotation(getPointcutText(),argNames,declarationSourceStart);;
if (annotations == null) {
annotations = new Annotation[] { pcutAnnotation };
} else {
Annotation[] old = annotations;
annotations = new Annotation[old.length +1];
System.arraycopy(old,0,annotations,0,old.length);
annotations[old.length] = pcutAnnotation;
}
generateSyntheticPointcutMethod = true;
}
private String getPointcutText() {
String text = getPointcut().toString();
if (text.indexOf("BindingTypePattern") == -1) return text;
// has been wrecked by resolution, try to reconstruct from tokens
if (pointcutDesignator != null) {
text = pointcutDesignator.getPointcutDeclarationText();
}
return text;
}
private String buildArgNameRepresentation() {
StringBuffer args = new StringBuffer();
if (this.arguments != null) {
for (int i = 0; i < this.arguments.length; i++) {
if (i != 0) args.append(",");
args.append(new String(this.arguments[i].name));
}
}
return args.toString();
}
// coming from an @Pointcut declaration
public void setGenerateSyntheticPointcutMethod() {
generateSyntheticPointcutMethod = true;
//mangleSelector = false;
}
public void resolve(ClassScope upperScope) {
// we attempted to resolve annotations below, but that was too early, so we do it again
// now at the 'right' time.
if (binding!= null) {
binding.tagBits -= TagBits.AnnotationResolved;
resolveAnnotations(scope, this.annotations, this.binding);
}
// for the rest of the resolution process, this method should do nothing, use the entry point below...
}
public void resolvePointcut(ClassScope upperScope) {
this.world = EclipseFactory.fromScopeLookupEnvironment(upperScope);
super.resolve(upperScope);
}
public void resolveStatements() {
if (isAbstract()) {
this.modifiers |= AccSemicolonBody;
}
if (binding == null || ignoreFurtherInvestigation) return;
if (Modifier.isAbstract(this.declaredModifiers)&& (pointcutDesignator != null)) {
scope.problemReporter().signalError(sourceStart, sourceEnd, "abstract pointcut can't have body");
ignoreFurtherInvestigation = true;
return;
}
if (pointcutDesignator != null) {
pointcutDesignator.finishResolveTypes(this, this.binding, arguments.length,
scope.enclosingSourceType());
}
//System.out.println("resolved: " + getPointcut() + ", " + getPointcut().state);
makeResolvedPointcutDefinition(world);
resolvedPointcutDeclaration.setPointcut(getPointcut());
super.resolveStatements();
}
public ResolvedPointcutDefinition makeResolvedPointcutDefinition(EclipseFactory inWorld) {
if (resolvedPointcutDeclaration != null) return resolvedPointcutDeclaration;
//System.out.println("pc: " + getPointcut() + ", " + getPointcut().state);
resolvedPointcutDeclaration = new ResolvedPointcutDefinition(
inWorld.fromBinding(this.binding.declaringClass),
declaredModifiers,
declaredName,
inWorld.fromBindings(this.binding.parameters),
getPointcut()); //??? might want to use null
resolvedPointcutDeclaration.setPosition(sourceStart, sourceEnd);
resolvedPointcutDeclaration.setSourceContext(new EclipseSourceContext(compilationResult));
return resolvedPointcutDeclaration;
}
public AjAttribute makeAttribute() {
return new AjAttribute.PointcutDeclarationAttribute(makeResolvedPointcutDefinition(world));
}
/**
* A pointcut declaration exists in a classfile only as an attibute on the
* class. Unlike advice and inter-type declarations, it has no corresponding
* method.
*/
public void generateCode(ClassScope classScope, ClassFile classFile) {
this.world = EclipseFactory.fromScopeLookupEnvironment(classScope);
if (ignoreFurtherInvestigation) return ;
classFile.extraAttributes.add(new EclipseAttributeAdapter(makeAttribute()));
addVersionAttributeIfNecessary(classFile);
if (generateSyntheticPointcutMethod) {
super.generateCode(classScope,classFile);
}
return;
}
/**
* Normally, pointcuts occur in aspects - aspects are always tagged with a weaver version attribute,
* see AspectDeclaration. However, pointcuts can also occur in regular classes and in this case there
* is no AspectDeclaration to ensure the attribute is added. So, this method adds the attribute
* if someone else hasn't already.
*/
private void addVersionAttributeIfNecessary(ClassFile classFile) {
for (Iterator iter = classFile.extraAttributes.iterator(); iter.hasNext();) {
EclipseAttributeAdapter element = (EclipseAttributeAdapter) iter.next();
if (CharOperation.equals(element.getNameChars(),weaverVersionChars)) return;
}
classFile.extraAttributes.add(new EclipseAttributeAdapter(new AjAttribute.WeaverVersionInfo()));
}
private static char[] weaverVersionChars = "org.aspectj.weaver.WeaverVersion".toCharArray();
protected int generateInfoAttributes(ClassFile classFile) {
return super.generateInfoAttributes(classFile,true);
}
public StringBuffer printReturnType(int indent, StringBuffer output) {
return output.append("pointcut");
}
/* (non-Javadoc)
* @see org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration#printBody(int, java.lang.StringBuffer)
*/
public StringBuffer printBody(int indent, StringBuffer output) {
output.append(": ");
output.append(getPointcut());
output.append(";");
return output;
}
}
|
147,711 |
Bug 147711 Add an option to generate aj-synthetics with true synthetic flag
|
In a number of cases tools are getting confused over generated aj members that are "aj-synthetic" but not marked with the synthetic attribute (because in the past, this has upset other tools). The most recent example was a JAXB posting on the list - by having a perthis() clause in an aspect that matched a type with JAXB 2 annotations the user was no longer able to use JAXB. This is a serious issue, and will prevent the usage of JAXB 2 with any type into which we introduce properties as aj-synthetic members. The JAXB 2 solution to ignore such fields is to annotate them with @XmlTransient, but since the field does not exist in the user program they can't even do this!
|
resolved fixed
|
c9f311a
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-06-24T11:36:59Z | 2006-06-19T12:26:40Z |
org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/compiler/lookup/EclipseFactory.java
|
/* *******************************************************************
* Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC).
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the 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
* Mik Kersten 2004-07-26 extended to allow overloading of
* hierarchy builder
* ******************************************************************/
package org.aspectj.ajdt.internal.compiler.lookup;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.aspectj.ajdt.internal.compiler.ast.AspectDeclaration;
import org.aspectj.ajdt.internal.compiler.ast.AstUtil;
import org.aspectj.ajdt.internal.core.builder.AjBuildManager;
import org.aspectj.bridge.ISourceLocation;
import org.aspectj.bridge.IMessage.Kind;
import org.aspectj.org.eclipse.jdt.core.compiler.CharOperation;
import org.aspectj.org.eclipse.jdt.internal.compiler.ast.ASTNode;
import org.aspectj.org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration;
import org.aspectj.org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration;
import org.aspectj.org.eclipse.jdt.internal.compiler.ast.EmptyStatement;
import org.aspectj.org.eclipse.jdt.internal.compiler.ast.TypeDeclaration;
import org.aspectj.org.eclipse.jdt.internal.compiler.ast.Wildcard;
import org.aspectj.org.eclipse.jdt.internal.compiler.impl.Constant;
import org.aspectj.org.eclipse.jdt.internal.compiler.impl.ReferenceContext;
import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.ArrayBinding;
import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.BaseTypes;
import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.Binding;
import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.FieldBinding;
import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.LocalTypeBinding;
import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.LookupEnvironment;
import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.MethodBinding;
import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.ParameterizedTypeBinding;
import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.RawTypeBinding;
import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.ReferenceBinding;
import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.Scope;
import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.SourceTypeBinding;
import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.TypeBinding;
import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.TypeVariableBinding;
import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.WildcardBinding;
import org.aspectj.weaver.BoundedReferenceType;
import org.aspectj.weaver.ConcreteTypeMunger;
import org.aspectj.weaver.IHasPosition;
import org.aspectj.weaver.Member;
import org.aspectj.weaver.NewFieldTypeMunger;
import org.aspectj.weaver.NewMethodTypeMunger;
import org.aspectj.weaver.ReferenceType;
import org.aspectj.weaver.ResolvedMember;
import org.aspectj.weaver.ResolvedMemberImpl;
import org.aspectj.weaver.ResolvedType;
import org.aspectj.weaver.Shadow;
import org.aspectj.weaver.TypeFactory;
import org.aspectj.weaver.TypeVariable;
import org.aspectj.weaver.TypeVariableDeclaringElement;
import org.aspectj.weaver.TypeVariableReference;
import org.aspectj.weaver.UnresolvedType;
import org.aspectj.weaver.UnresolvedTypeVariableReferenceType;
import org.aspectj.weaver.World;
import org.aspectj.weaver.UnresolvedType.TypeKind;
/**
* @author Jim Hugunin
*/
public class EclipseFactory {
public static boolean DEBUG = false;
public static int debug_mungerCount = -1;
private AjBuildManager buildManager;
private LookupEnvironment lookupEnvironment;
private boolean xSerializableAspects;
private World world;
public Collection finishedTypeMungers = null;
// We can get clashes if we don't treat raw types differently - we end up looking
// up a raw and getting the generic type (pr115788)
private Map/*UnresolvedType, TypeBinding*/ typexToBinding = new HashMap();
private Map/*UnresolvedType, TypeBinding*/ rawTypeXToBinding = new HashMap();
//XXX currently unused
// private Map/*TypeBinding, ResolvedType*/ bindingToResolvedTypeX = new HashMap();
public static EclipseFactory fromLookupEnvironment(LookupEnvironment env) {
AjLookupEnvironment aenv = (AjLookupEnvironment)env;
return aenv.factory;
}
public static EclipseFactory fromScopeLookupEnvironment(Scope scope) {
return fromLookupEnvironment(AstUtil.getCompilationUnitScope(scope).environment);
}
public EclipseFactory(LookupEnvironment lookupEnvironment,AjBuildManager buildManager) {
this.lookupEnvironment = lookupEnvironment;
this.buildManager = buildManager;
this.world = buildManager.getWorld();
this.xSerializableAspects = buildManager.buildConfig.isXserializableAspects();
}
public EclipseFactory(LookupEnvironment lookupEnvironment, World world, boolean xSer) {
this.lookupEnvironment = lookupEnvironment;
this.world = world;
this.xSerializableAspects = xSer;
this.buildManager = null;
}
public World getWorld() {
return world;
}
public void showMessage(
Kind kind,
String message,
ISourceLocation loc1,
ISourceLocation loc2)
{
getWorld().showMessage(kind, message, loc1, loc2);
}
public ResolvedType fromEclipse(ReferenceBinding binding) {
if (binding == null) return ResolvedType.MISSING;
//??? this seems terribly inefficient
//System.err.println("resolving: " + binding.getClass() + ", name = " + getName(binding));
ResolvedType ret = getWorld().resolve(fromBinding(binding));
//System.err.println(" got: " + ret);
return ret;
}
public ResolvedType fromTypeBindingToRTX(TypeBinding tb) {
if (tb == null) return ResolvedType.MISSING;
ResolvedType ret = getWorld().resolve(fromBinding(tb));
return ret;
}
public ResolvedType[] fromEclipse(ReferenceBinding[] bindings) {
if (bindings == null) {
return ResolvedType.NONE;
}
int len = bindings.length;
ResolvedType[] ret = new ResolvedType[len];
for (int i=0; i < len; i++) {
ret[i] = fromEclipse(bindings[i]);
}
return ret;
}
public static String getName(TypeBinding binding) {
if (binding instanceof TypeVariableBinding) {
// The first bound may be null - so default to object?
TypeVariableBinding tvb = (TypeVariableBinding)binding;
if (tvb.firstBound!=null) {
return getName(tvb.firstBound);
} else {
return getName(tvb.superclass);
}
}
if (binding instanceof ReferenceBinding) {
return new String(
CharOperation.concatWith(((ReferenceBinding)binding).compoundName, '.'));
}
String packageName = new String(binding.qualifiedPackageName());
String className = new String(binding.qualifiedSourceName()).replace('.', '$');
if (packageName.length() > 0) {
className = packageName + "." + className;
}
//XXX doesn't handle arrays correctly (or primitives?)
return new String(className);
}
/**
* Some generics notes:
*
* Andy 6-May-05
* We were having trouble with parameterized types in a couple of places - due to TypeVariableBindings. When we
* see a TypeVariableBinding now we default to either the firstBound if it is specified or java.lang.Object. Not
* sure when/if this gets us unstuck? It does mean we forget that it is a type variable when going back
* the other way from the UnresolvedType and that would seem a bad thing - but I've yet to see the reason we need to
* remember the type variable.
* Adrian 10-July-05
* When we forget it's a type variable we come unstuck when getting the declared members of a parameterized
* type - since we don't know it's a type variable we can't replace it with the type parameter.
*/
//??? going back and forth between strings and bindings is a waste of cycles
public UnresolvedType fromBinding(TypeBinding binding) {
if (binding instanceof HelperInterfaceBinding) {
return ((HelperInterfaceBinding) binding).getTypeX();
}
if (binding == null || binding.qualifiedSourceName() == null) {
return ResolvedType.MISSING;
}
// first piece of generics support!
if (binding instanceof TypeVariableBinding) {
TypeVariableBinding tb = (TypeVariableBinding) binding;
UnresolvedTypeVariableReferenceType utvrt = (UnresolvedTypeVariableReferenceType) fromTypeVariableBinding(tb);
return utvrt;
}
// handle arrays since the component type may need special treatment too...
if (binding instanceof ArrayBinding) {
ArrayBinding aBinding = (ArrayBinding) binding;
UnresolvedType componentType = fromBinding(aBinding.leafComponentType);
return UnresolvedType.makeArray(componentType, aBinding.dimensions);
}
if (binding instanceof WildcardBinding) {
WildcardBinding eWB = (WildcardBinding) binding;
UnresolvedType theType = TypeFactory.createTypeFromSignature(CharOperation.charToString(eWB.genericTypeSignature()));
// Repair the bound
// e.g. If the bound for the wildcard is a typevariable, e.g. '? extends E' then
// the type variable in the unresolvedtype will be correct only in name. In that
// case let's set it correctly based on the one in the eclipse WildcardBinding
UnresolvedType theBound = null;
if (eWB.bound instanceof TypeVariableBinding) {
theBound = fromTypeVariableBinding((TypeVariableBinding)eWB.bound);
} else {
theBound = fromBinding(eWB.bound);
}
if (theType.isGenericWildcard() && theType.isSuper()) theType.setLowerBound(theBound);
if (theType.isGenericWildcard() && theType.isExtends()) theType.setUpperBound(theBound);
return theType;
}
if (binding instanceof ParameterizedTypeBinding) {
if (binding instanceof RawTypeBinding) {
// special case where no parameters are specified!
return UnresolvedType.forRawTypeName(getName(binding));
}
ParameterizedTypeBinding ptb = (ParameterizedTypeBinding) binding;
UnresolvedType[] arguments = null;
if (ptb.arguments!=null) { // null can mean this is an inner type of a Parameterized Type with no bounds of its own (pr100227)
arguments = new UnresolvedType[ptb.arguments.length];
for (int i = 0; i < arguments.length; i++) {
arguments[i] = fromBinding(ptb.arguments[i]);
}
}
String baseTypeSignature = null;
ResolvedType baseType = getWorld().resolve(UnresolvedType.forName(getName(binding)),true);
if (!baseType.isMissing()) {
// can legitimately be missing if a bound refers to a type we haven't added to the world yet...
if (!baseType.isGenericType() && arguments!=null) baseType = baseType.getGenericType();
baseTypeSignature = baseType.getErasureSignature();
} else {
baseTypeSignature = UnresolvedType.forName(getName(binding)).getSignature();
}
// Create an unresolved parameterized type. We can't create a resolved one as the
// act of resolution here may cause recursion problems since the parameters may
// be type variables that we haven't fixed up yet.
if (arguments==null) arguments=new UnresolvedType[0];
String parameterizedSig = ResolvedType.PARAMETERIZED_TYPE_IDENTIFIER+CharOperation.charToString(binding.genericTypeSignature()).substring(1);
return TypeFactory.createUnresolvedParameterizedType(parameterizedSig,baseTypeSignature,arguments);
}
// Convert the source type binding for a generic type into a generic UnresolvedType
// notice we can easily determine the type variables from the eclipse object
// and we can recover the generic signature from it too - so we pass those
// to the forGenericType() method.
if (binding.isGenericType() &&
!binding.isParameterizedType() &&
!binding.isRawType()) {
TypeVariableBinding[] tvbs = binding.typeVariables();
TypeVariable[] tVars = new TypeVariable[tvbs.length];
for (int i = 0; i < tvbs.length; i++) {
TypeVariableBinding eclipseV = tvbs[i];
tVars[i] = ((TypeVariableReference)fromTypeVariableBinding(eclipseV)).getTypeVariable();
}
//TODO asc generics - temporary guard....
if (!(binding instanceof SourceTypeBinding))
throw new RuntimeException("Cant get the generic sig for "+binding.debugName());
return UnresolvedType.forGenericType(getName(binding),tVars,
CharOperation.charToString(((SourceTypeBinding)binding).genericSignature()));
}
// LocalTypeBinding have a name $Local$, we can get the real name by using the signature....
if (binding instanceof LocalTypeBinding) {
LocalTypeBinding ltb = (LocalTypeBinding) binding;
if (ltb.constantPoolName() != null && ltb.constantPoolName().length > 0) {
return UnresolvedType.forSignature(new String(binding.signature()));
} else {
// we're reporting a problem and don't have a resolved name for an
// anonymous local type yet, report the issue on the enclosing type
return UnresolvedType.forSignature(new String(ltb.enclosingType.signature()));
}
}
return UnresolvedType.forName(getName(binding));
}
/**
* Some type variables refer to themselves recursively, this enables us to avoid
* recursion problems.
*/
private static Map typeVariableBindingsInProgress = new HashMap();
/**
* Convert from the eclipse form of type variable (TypeVariableBinding) to the AspectJ
* form (TypeVariable).
*/
private UnresolvedType fromTypeVariableBinding(TypeVariableBinding aTypeVariableBinding) {
// first, check for recursive call to this method for the same tvBinding
if (typeVariableBindingsInProgress.containsKey(aTypeVariableBinding)) {
return (UnresolvedType) typeVariableBindingsInProgress.get(aTypeVariableBinding);
}
// Check if its a type variable binding that we need to recover to an alias...
if (typeVariablesForAliasRecovery!=null) {
String aliasname = (String)typeVariablesForAliasRecovery.get(aTypeVariableBinding);
if (aliasname!=null) {
UnresolvedTypeVariableReferenceType ret = new UnresolvedTypeVariableReferenceType();
ret.setTypeVariable(new TypeVariable(aliasname));
return ret;
}
}
if (typeVariablesForThisMember.containsKey(new String(aTypeVariableBinding.sourceName))) {
return (UnresolvedType)typeVariablesForThisMember.get(new String(aTypeVariableBinding.sourceName));
}
// Create the UnresolvedTypeVariableReferenceType for the type variable
String name = CharOperation.charToString(aTypeVariableBinding.sourceName());
UnresolvedTypeVariableReferenceType ret = new UnresolvedTypeVariableReferenceType();
typeVariableBindingsInProgress.put(aTypeVariableBinding,ret);
TypeVariable tv = new TypeVariable(name);
ret.setTypeVariable(tv);
// Dont set any bounds here, you'll get in a recursive mess
// TODO -- what about lower bounds??
UnresolvedType superclassType = fromBinding(aTypeVariableBinding.superclass());
UnresolvedType[] superinterfaces = new UnresolvedType[aTypeVariableBinding.superInterfaces.length];
for (int i = 0; i < superinterfaces.length; i++) {
superinterfaces[i] = fromBinding(aTypeVariableBinding.superInterfaces[i]);
}
tv.setUpperBound(superclassType);
tv.setAdditionalInterfaceBounds(superinterfaces);
tv.setRank(aTypeVariableBinding.rank);
if (aTypeVariableBinding.declaringElement instanceof MethodBinding) {
tv.setDeclaringElementKind(TypeVariable.METHOD);
// tv.setDeclaringElement(fromBinding((MethodBinding)aTypeVariableBinding.declaringElement);
} else {
tv.setDeclaringElementKind(TypeVariable.TYPE);
// // tv.setDeclaringElement(fromBinding(aTypeVariableBinding.declaringElement));
}
if (aTypeVariableBinding.declaringElement instanceof MethodBinding)
typeVariablesForThisMember.put(new String(aTypeVariableBinding.sourceName),ret);
typeVariableBindingsInProgress.remove(aTypeVariableBinding);
return ret;
}
public UnresolvedType[] fromBindings(TypeBinding[] bindings) {
if (bindings == null) return UnresolvedType.NONE;
int len = bindings.length;
UnresolvedType[] ret = new UnresolvedType[len];
for (int i=0; i<len; i++) {
ret[i] = fromBinding(bindings[i]);
}
return ret;
}
public static ASTNode astForLocation(IHasPosition location) {
return new EmptyStatement(location.getStart(), location.getEnd());
}
public Collection getDeclareParents() {
return getWorld().getDeclareParents();
}
public Collection getDeclareAnnotationOnTypes() {
return getWorld().getDeclareAnnotationOnTypes();
}
public Collection getDeclareAnnotationOnFields() {
return getWorld().getDeclareAnnotationOnFields();
}
public Collection getDeclareAnnotationOnMethods() {
return getWorld().getDeclareAnnotationOnMethods();
}
public boolean areTypeMungersFinished() {
return finishedTypeMungers != null;
}
public void finishTypeMungers() {
// make sure that type mungers are
Collection ret = new ArrayList();
Collection baseTypeMungers = getWorld().getCrosscuttingMembersSet().getTypeMungers();
// XXX by Andy: why do we mix up the mungers here? it means later we know about two sets
// and the late ones are a subset of the complete set? (see pr114436)
// XXX by Andy removed this line finally, see pr141956
// baseTypeMungers.addAll(getWorld().getCrosscuttingMembersSet().getLateTypeMungers());
debug_mungerCount=baseTypeMungers.size();
for (Iterator i = baseTypeMungers.iterator(); i.hasNext(); ) {
ConcreteTypeMunger munger = (ConcreteTypeMunger) i.next();
EclipseTypeMunger etm = makeEclipseTypeMunger(munger);
if (etm != null) ret.add(etm);
}
finishedTypeMungers = ret;
}
public EclipseTypeMunger makeEclipseTypeMunger(ConcreteTypeMunger concrete) {
//System.err.println("make munger: " + concrete);
//!!! can't do this if we want incremental to work right
//if (concrete instanceof EclipseTypeMunger) return (EclipseTypeMunger)concrete;
//System.err.println(" was not eclipse");
if (concrete.getMunger() != null && EclipseTypeMunger.supportsKind(concrete.getMunger().getKind())) {
AbstractMethodDeclaration method = null;
if (concrete instanceof EclipseTypeMunger) {
method = ((EclipseTypeMunger)concrete).getSourceMethod();
}
EclipseTypeMunger ret =
new EclipseTypeMunger(this, concrete.getMunger(), concrete.getAspectType(), method);
if (ret.getSourceLocation() == null) {
ret.setSourceLocation(concrete.getSourceLocation());
}
return ret;
} else {
return null;
}
}
public Collection getTypeMungers() {
//??? assert finishedTypeMungers != null
return finishedTypeMungers;
}
public ResolvedMember makeResolvedMember(MethodBinding binding) {
return makeResolvedMember(binding, binding.declaringClass);
}
public ResolvedMember makeResolvedMember(MethodBinding binding, Shadow.Kind shadowKind) {
Member.Kind memberKind = binding.isConstructor() ? Member.CONSTRUCTOR : Member.METHOD;
if (shadowKind == Shadow.AdviceExecution) memberKind = Member.ADVICE;
return makeResolvedMember(binding,binding.declaringClass,memberKind);
}
/**
* Conversion from a methodbinding (eclipse) to a resolvedmember (aspectj) is now done
* in the scope of some type variables. Before converting the parts of a methodbinding
* (params, return type) we store the type variables in this structure, then should any
* component of the method binding refer to them, we grab them from the map.
*/
private Map typeVariablesForThisMember = new HashMap();
/**
* This is a map from typevariablebindings (eclipsey things) to the names the user
* originally specified in their ITD. For example if the target is 'interface I<N extends Number> {}'
* and the ITD was 'public void I<X>.m(List<X> lxs) {}' then this map would contain a pointer
* from the eclipse type 'N extends Number' to the letter 'X'.
*/
private Map typeVariablesForAliasRecovery;
/**
* Construct a resolvedmember from a methodbinding. The supplied map tells us about any
* typevariablebindings that replaced typevariables whilst the compiler was resolving types -
* this only happens if it is a generic itd that shares type variables with its target type.
*/
public ResolvedMember makeResolvedMemberForITD(MethodBinding binding,TypeBinding declaringType,
Map /*TypeVariableBinding > original alias name*/ recoveryAliases) {
ResolvedMember result = null;
try {
typeVariablesForAliasRecovery = recoveryAliases;
result = makeResolvedMember(binding,declaringType);
} finally {
typeVariablesForAliasRecovery = null;
}
return result;
}
public ResolvedMember makeResolvedMember(MethodBinding binding, TypeBinding declaringType) {
return makeResolvedMember(binding,declaringType,
binding.isConstructor() ? Member.CONSTRUCTOR : Member.METHOD);
}
public ResolvedMember makeResolvedMember(MethodBinding binding, TypeBinding declaringType, Member.Kind memberKind) {
//System.err.println("member for: " + binding + ", " + new String(binding.declaringClass.sourceName));
// Convert the type variables and store them
UnresolvedType[] ajTypeRefs = null;
typeVariablesForThisMember.clear();
// This is the set of type variables available whilst building the resolved member...
if (binding.typeVariables!=null) {
ajTypeRefs = new UnresolvedType[binding.typeVariables.length];
for (int i = 0; i < binding.typeVariables.length; i++) {
ajTypeRefs[i] = fromBinding(binding.typeVariables[i]);
typeVariablesForThisMember.put(new String(binding.typeVariables[i].sourceName),/*new Integer(binding.typeVariables[i].rank),*/ajTypeRefs[i]);
}
}
// AMC these next two lines shouldn't be needed once we sort out generic types properly in the world map
ResolvedType realDeclaringType = world.resolve(fromBinding(declaringType));
if (realDeclaringType.isRawType()) realDeclaringType = realDeclaringType.getGenericType();
ResolvedMemberImpl ret = new ResolvedMemberImpl(
memberKind,
realDeclaringType,
binding.modifiers,
fromBinding(binding.returnType),
new String(binding.selector),
fromBindings(binding.parameters),
fromBindings(binding.thrownExceptions)
);
if (binding.isVarargs()) {
ret.setVarargsMethod();
}
if (ajTypeRefs!=null) {
TypeVariable[] tVars = new TypeVariable[ajTypeRefs.length];
for (int i=0;i<ajTypeRefs.length;i++) {
tVars[i]=((TypeVariableReference)ajTypeRefs[i]).getTypeVariable();
}
ret.setTypeVariables(tVars);
}
typeVariablesForThisMember.clear();
ret.resolve(world);
return ret;
}
public ResolvedMember makeResolvedMember(FieldBinding binding) {
return makeResolvedMember(binding, binding.declaringClass);
}
public ResolvedMember makeResolvedMember(FieldBinding binding, TypeBinding receiverType) {
// AMC these next two lines shouldn't be needed once we sort out generic types properly in the world map
ResolvedType realDeclaringType = world.resolve(fromBinding(receiverType));
if (realDeclaringType.isRawType()) realDeclaringType = realDeclaringType.getGenericType();
return new ResolvedMemberImpl(
Member.FIELD,
realDeclaringType,
binding.modifiers,
world.resolve(fromBinding(binding.type)),
new String(binding.name),
UnresolvedType.NONE);
}
public TypeBinding makeTypeBinding(UnresolvedType typeX) {
TypeBinding ret = null;
// looking up type variables can get us into trouble
if (!typeX.isTypeVariableReference()) {
if (typeX.isRawType()) {
ret = (TypeBinding)rawTypeXToBinding.get(typeX);
} else {
ret = (TypeBinding)typexToBinding.get(typeX);
}
}
if (ret == null) {
ret = makeTypeBinding1(typeX);
if (!(typeX instanceof BoundedReferenceType) &&
!(typeX instanceof UnresolvedTypeVariableReferenceType)
) {
if (typeX.isRawType()) {
rawTypeXToBinding.put(typeX,ret);
} else {
typexToBinding.put(typeX, ret);
}
}
}
if (ret == null) {
System.out.println("can't find: " + typeX);
}
return ret;
}
// When converting a parameterized type from our world to the eclipse world, these get set so that
// resolution of the type parameters may known in what context it is occurring (pr114744)
private ReferenceBinding baseTypeForParameterizedType;
private int indexOfTypeParameterBeingConverted;
private TypeBinding makeTypeBinding1(UnresolvedType typeX) {
if (typeX.isPrimitiveType()) {
if (typeX == ResolvedType.BOOLEAN) return BaseTypes.BooleanBinding;
if (typeX == ResolvedType.BYTE) return BaseTypes.ByteBinding;
if (typeX == ResolvedType.CHAR) return BaseTypes.CharBinding;
if (typeX == ResolvedType.DOUBLE) return BaseTypes.DoubleBinding;
if (typeX == ResolvedType.FLOAT) return BaseTypes.FloatBinding;
if (typeX == ResolvedType.INT) return BaseTypes.IntBinding;
if (typeX == ResolvedType.LONG) return BaseTypes.LongBinding;
if (typeX == ResolvedType.SHORT) return BaseTypes.ShortBinding;
if (typeX == ResolvedType.VOID) return BaseTypes.VoidBinding;
throw new RuntimeException("weird primitive type " + typeX);
} else if (typeX.isArray()) {
int dim = 0;
while (typeX.isArray()) {
dim++;
typeX = typeX.getComponentType();
}
return lookupEnvironment.createArrayType(makeTypeBinding(typeX), dim);
} else if (typeX.isParameterizedType()) {
// Converting back to a binding from a UnresolvedType
UnresolvedType[] typeParameters = typeX.getTypeParameters();
ReferenceBinding baseTypeBinding = lookupBinding(typeX.getBaseName());
TypeBinding[] argumentBindings = new TypeBinding[typeParameters.length];
baseTypeForParameterizedType = baseTypeBinding;
for (int i = 0; i < argumentBindings.length; i++) {
indexOfTypeParameterBeingConverted = i;
argumentBindings[i] = makeTypeBinding(typeParameters[i]);
}
indexOfTypeParameterBeingConverted = 0;
baseTypeForParameterizedType = null;
ParameterizedTypeBinding ptb =
lookupEnvironment.createParameterizedType(baseTypeBinding,argumentBindings,baseTypeBinding.enclosingType());
return ptb;
} else if (typeX.isTypeVariableReference()) {
// return makeTypeVariableBinding((TypeVariableReference)typeX);
return makeTypeVariableBindingFromAJTypeVariable(((TypeVariableReference)typeX).getTypeVariable());
} else if (typeX.isRawType()) {
ReferenceBinding baseTypeBinding = lookupBinding(typeX.getBaseName());
RawTypeBinding rtb = lookupEnvironment.createRawType(baseTypeBinding,baseTypeBinding.enclosingType());
return rtb;
} else if (typeX.isGenericWildcard()) {
// translate from boundedreferencetype to WildcardBinding
BoundedReferenceType brt = (BoundedReferenceType)typeX;
// Work out 'kind' for the WildcardBinding
int boundkind = Wildcard.UNBOUND;
TypeBinding bound = null;
if (brt.isExtends()) {
boundkind = Wildcard.EXTENDS;
bound = makeTypeBinding(brt.getUpperBound());
} else if (brt.isSuper()) {
boundkind = Wildcard.SUPER;
bound = makeTypeBinding(brt.getLowerBound());
}
TypeBinding[] otherBounds = null;
if (brt.getAdditionalBounds()!=null && brt.getAdditionalBounds().length!=0) otherBounds = makeTypeBindings(brt.getAdditionalBounds());
WildcardBinding wb = lookupEnvironment.createWildcard(baseTypeForParameterizedType,indexOfTypeParameterBeingConverted,bound,otherBounds,boundkind);
return wb;
} else {
return lookupBinding(typeX.getName());
}
}
private ReferenceBinding lookupBinding(String sname) {
char[][] name = CharOperation.splitOn('.', sname.toCharArray());
ReferenceBinding rb = lookupEnvironment.getType(name);
return rb;
}
public TypeBinding[] makeTypeBindings(UnresolvedType[] types) {
int len = types.length;
TypeBinding[] ret = new TypeBinding[len];
for (int i = 0; i < len; i++) {
ret[i] = makeTypeBinding(types[i]);
}
return ret;
}
// just like the code above except it returns an array of ReferenceBindings
private ReferenceBinding[] makeReferenceBindings(UnresolvedType[] types) {
int len = types.length;
ReferenceBinding[] ret = new ReferenceBinding[len];
for (int i = 0; i < len; i++) {
ret[i] = (ReferenceBinding)makeTypeBinding(types[i]);
}
return ret;
}
// field related
public FieldBinding makeFieldBinding(NewFieldTypeMunger nftm) {
return internalMakeFieldBinding(nftm.getSignature(),nftm.getTypeVariableAliases());
}
/**
* Convert a resolvedmember into an eclipse field binding
*/
public FieldBinding makeFieldBinding(ResolvedMember member,List aliases) {
return internalMakeFieldBinding(member,aliases);
}
/**
* Convert a resolvedmember into an eclipse field binding
*/
public FieldBinding makeFieldBinding(ResolvedMember member) {
return internalMakeFieldBinding(member,null);
}
/**
* Take a normal AJ member and convert it into an eclipse fieldBinding.
* Taking into account any aliases that it may include due to being
* a generic itd. Any aliases are put into the typeVariableToBinding
* map so that they will be substituted as appropriate in the returned
* fieldbinding.
*/
public FieldBinding internalMakeFieldBinding(ResolvedMember member,List aliases) {
typeVariableToTypeBinding.clear();
TypeVariableBinding[] tvbs = null;
ReferenceBinding declaringType = (ReferenceBinding)makeTypeBinding(member.getDeclaringType());
// If there are aliases, place them in the map
if (aliases!=null && aliases.size()>0) {
int i =0;
for (Iterator iter = aliases.iterator(); iter.hasNext();) {
String element = (String) iter.next();
typeVariableToTypeBinding.put(element,declaringType.typeVariables()[i++]);
}
}
currentType = declaringType;
FieldBinding fb = new FieldBinding(member.getName().toCharArray(),
makeTypeBinding(member.getReturnType()),
member.getModifiers(),
currentType,
Constant.NotAConstant);
typeVariableToTypeBinding.clear();
currentType = null;
return fb;
}
private ReferenceBinding currentType = null;
// method binding related
public MethodBinding makeMethodBinding(NewMethodTypeMunger nmtm) {
return internalMakeMethodBinding(nmtm.getSignature(),nmtm.getTypeVariableAliases());
}
/**
* Convert a resolvedmember into an eclipse method binding.
*/
public MethodBinding makeMethodBinding(ResolvedMember member,List aliases) {
return internalMakeMethodBinding(member,aliases);
}
/**
* Creates a method binding for a resolvedmember taking into account type variable aliases -
* this variant can take an aliasTargetType and should be used when the alias target type
* cannot be retrieved from the resolvedmember.
*/
public MethodBinding makeMethodBinding(ResolvedMember member,List aliases,UnresolvedType aliasTargetType) {
return internalMakeMethodBinding(member,aliases,aliasTargetType);
}
/**
* Convert a resolvedmember into an eclipse method binding.
*/
public MethodBinding makeMethodBinding(ResolvedMember member) {
return internalMakeMethodBinding(member,null); // there are no aliases
}
public MethodBinding internalMakeMethodBinding(ResolvedMember member,List aliases) {
return internalMakeMethodBinding(member,aliases,member.getDeclaringType());
}
/**
* Take a normal AJ member and convert it into an eclipse methodBinding.
* Taking into account any aliases that it may include due to being a
* generic ITD. Any aliases are put into the typeVariableToBinding
* map so that they will be substituted as appropriate in the returned
* methodbinding
*/
public MethodBinding internalMakeMethodBinding(ResolvedMember member,List aliases,UnresolvedType aliasTargetType) {
typeVariableToTypeBinding.clear();
TypeVariableBinding[] tvbs = null;
if (member.getTypeVariables()!=null) {
if (member.getTypeVariables().length==0) {
tvbs = MethodBinding.NoTypeVariables;
} else {
tvbs = makeTypeVariableBindingsFromAJTypeVariables(member.getTypeVariables());
// QQQ do we need to bother fixing up the declaring element here?
}
}
ReferenceBinding declaringType = (ReferenceBinding)makeTypeBinding(member.getDeclaringType());
// If there are aliases, place them in the map
if (aliases!=null && aliases.size()!=0) {
int i=0;
ReferenceBinding aliasTarget = (ReferenceBinding)makeTypeBinding(aliasTargetType);
for (Iterator iter = aliases.iterator(); iter.hasNext();) {
String element = (String) iter.next();
typeVariableToTypeBinding.put(element,aliasTarget.typeVariables()[i++]);
}
}
currentType = declaringType;
MethodBinding mb = new MethodBinding(member.getModifiers(),
member.getName().toCharArray(),
makeTypeBinding(member.getReturnType()),
makeTypeBindings(member.getParameterTypes()),
makeReferenceBindings(member.getExceptions()),
declaringType);
if (tvbs!=null) mb.typeVariables = tvbs;
typeVariableToTypeBinding.clear();
currentType = null;
return mb;
}
/**
* Convert a bunch of type variables in one go, from AspectJ form to Eclipse form.
*/
// private TypeVariableBinding[] makeTypeVariableBindings(UnresolvedType[] typeVariables) {
// int len = typeVariables.length;
// TypeVariableBinding[] ret = new TypeVariableBinding[len];
// for (int i = 0; i < len; i++) {
// ret[i] = makeTypeVariableBinding((TypeVariableReference)typeVariables[i]);
// }
// return ret;
// }
private TypeVariableBinding[] makeTypeVariableBindingsFromAJTypeVariables(TypeVariable[] typeVariables) {
int len = typeVariables.length;
TypeVariableBinding[] ret = new TypeVariableBinding[len];
for (int i = 0; i < len; i++) {
ret[i] = makeTypeVariableBindingFromAJTypeVariable(typeVariables[i]);
}
return ret;
}
// only accessed through private methods in this class. Ensures all type variables we encounter
// map back to the same type binding - this is important later when Eclipse code is processing
// a methodbinding trying to come up with possible bindings for the type variables.
// key is currently the name of the type variable...is that ok?
private Map typeVariableToTypeBinding = new HashMap();
/**
* Converts from an TypeVariableReference to a TypeVariableBinding. A TypeVariableReference
* in AspectJ world holds a TypeVariable and it is this type variable that is converted
* to the TypeVariableBinding.
*/
private TypeVariableBinding makeTypeVariableBinding(TypeVariableReference tvReference) {
TypeVariable tv = tvReference.getTypeVariable();
TypeVariableBinding tvBinding = (TypeVariableBinding)typeVariableToTypeBinding.get(tv.getName());
if (currentType!=null) {
TypeVariableBinding tvb = currentType.getTypeVariable(tv.getName().toCharArray());
if (tvb!=null) return tvb;
}
if (tvBinding==null) {
Binding declaringElement = null;
// this will cause an infinite loop or NPE... not required yet luckily.
// if (tVar.getDeclaringElement() instanceof Member) {
// declaringElement = makeMethodBinding((ResolvedMember)tVar.getDeclaringElement());
// } else {
// declaringElement = makeTypeBinding((UnresolvedType)tVar.getDeclaringElement());
// }
tvBinding = new TypeVariableBinding(tv.getName().toCharArray(),declaringElement,tv.getRank());
typeVariableToTypeBinding.put(tv.getName(),tvBinding);
tvBinding.superclass=(ReferenceBinding)makeTypeBinding(tv.getUpperBound());
tvBinding.firstBound=(ReferenceBinding)makeTypeBinding(tv.getFirstBound());
if (tv.getAdditionalInterfaceBounds()==null) {
tvBinding.superInterfaces=TypeVariableBinding.NoSuperInterfaces;
} else {
TypeBinding tbs[] = makeTypeBindings(tv.getAdditionalInterfaceBounds());
ReferenceBinding[] rbs= new ReferenceBinding[tbs.length];
for (int i = 0; i < tbs.length; i++) {
rbs[i] = (ReferenceBinding)tbs[i];
}
tvBinding.superInterfaces=rbs;
}
}
return tvBinding;
}
private TypeVariableBinding makeTypeVariableBindingFromAJTypeVariable(TypeVariable tv) {
TypeVariableBinding tvBinding = (TypeVariableBinding)typeVariableToTypeBinding.get(tv.getName());
if (currentType!=null) {
TypeVariableBinding tvb = currentType.getTypeVariable(tv.getName().toCharArray());
if (tvb!=null) return tvb;
}
if (tvBinding==null) {
Binding declaringElement = null;
// this will cause an infinite loop or NPE... not required yet luckily.
// if (tVar.getDeclaringElement() instanceof Member) {
// declaringElement = makeMethodBinding((ResolvedMember)tVar.getDeclaringElement());
// } else {
// declaringElement = makeTypeBinding((UnresolvedType)tVar.getDeclaringElement());
// }
tvBinding = new TypeVariableBinding(tv.getName().toCharArray(),declaringElement,tv.getRank());
typeVariableToTypeBinding.put(tv.getName(),tvBinding);
tvBinding.superclass=(ReferenceBinding)makeTypeBinding(tv.getUpperBound());
tvBinding.firstBound=(ReferenceBinding)makeTypeBinding(tv.getFirstBound());
if (tv.getAdditionalInterfaceBounds()==null) {
tvBinding.superInterfaces=TypeVariableBinding.NoSuperInterfaces;
} else {
TypeBinding tbs[] = makeTypeBindings(tv.getAdditionalInterfaceBounds());
ReferenceBinding[] rbs= new ReferenceBinding[tbs.length];
for (int i = 0; i < tbs.length; i++) {
rbs[i] = (ReferenceBinding)tbs[i];
}
tvBinding.superInterfaces=rbs;
}
}
return tvBinding;
}
public MethodBinding makeMethodBindingForCall(Member member) {
return new MethodBinding(member.getCallsiteModifiers(),
member.getName().toCharArray(),
makeTypeBinding(member.getReturnType()),
makeTypeBindings(member.getParameterTypes()),
new ReferenceBinding[0],
(ReferenceBinding)makeTypeBinding(member.getDeclaringType()));
}
public void finishedCompilationUnit(CompilationUnitDeclaration unit) {
if ((buildManager != null) && buildManager.doGenerateModel()) {
AjBuildManager.getAsmHierarchyBuilder().buildStructureForCompilationUnit(unit, buildManager.getStructureModel(), buildManager.buildConfig);
}
}
public void addTypeBinding(TypeBinding binding) {
typexToBinding.put(fromBinding(binding), binding);
}
public void addTypeBindingAndStoreInWorld(TypeBinding binding) {
UnresolvedType ut = fromBinding(binding);
typexToBinding.put(ut, binding);
world.lookupOrCreateName(ut);
}
public Shadow makeShadow(ASTNode location, ReferenceContext context) {
return EclipseShadow.makeShadow(this, location, context);
}
public Shadow makeShadow(ReferenceContext context) {
return EclipseShadow.makeShadow(this, (ASTNode) context, context);
}
public void addSourceTypeBinding(SourceTypeBinding binding, CompilationUnitDeclaration unit) {
TypeDeclaration decl = binding.scope.referenceContext;
// Deal with the raw/basic type to give us an entry in the world type map
UnresolvedType simpleTx = null;
if (binding.isGenericType()) {
simpleTx = UnresolvedType.forRawTypeName(getName(binding));
} else if (binding.isLocalType()) {
LocalTypeBinding ltb = (LocalTypeBinding) binding;
if (ltb.constantPoolName() != null && ltb.constantPoolName().length > 0) {
simpleTx = UnresolvedType.forSignature(new String(binding.signature()));
} else {
simpleTx = UnresolvedType.forName(getName(binding));
}
}else {
simpleTx = UnresolvedType.forName(getName(binding));
}
ReferenceType name = getWorld().lookupOrCreateName(simpleTx);
// A type can change from simple > generic > simple across a set of compiles. We need
// to ensure the entry in the typemap is promoted and demoted correctly. The call
// to setGenericType() below promotes a simple to a raw. This call demotes it back
// to simple
// pr125405
if (!binding.isRawType() && !binding.isGenericType() && name.getTypekind()==TypeKind.RAW) {
name.demoteToSimpleType();
}
EclipseSourceType t = new EclipseSourceType(name, this, binding, decl, unit);
// For generics, go a bit further - build a typex for the generic type
// give it the same delegate and link it to the raw type
if (binding.isGenericType()) {
UnresolvedType complexTx = fromBinding(binding); // fully aware of any generics info
ResolvedType cName = world.resolve(complexTx,true);
ReferenceType complexName = null;
if (!cName.isMissing()) {
complexName = (ReferenceType) cName;
complexName = (ReferenceType) complexName.getGenericType();
if (complexName == null) complexName = new ReferenceType(complexTx,world);
} else {
complexName = new ReferenceType(complexTx,world);
}
name.setGenericType(complexName);
complexName.setDelegate(t);
}
name.setDelegate(t);
if (decl instanceof AspectDeclaration) {
((AspectDeclaration)decl).typeX = name;
((AspectDeclaration)decl).concreteName = t;
}
ReferenceBinding[] memberTypes = binding.memberTypes;
for (int i = 0, length = memberTypes.length; i < length; i++) {
addSourceTypeBinding((SourceTypeBinding) memberTypes[i], unit);
}
}
// XXX this doesn't feel like it belongs here, but it breaks a hard dependency on
// exposing AjBuildManager (needed by AspectDeclaration).
public boolean isXSerializableAspects() {
return xSerializableAspects;
}
public ResolvedMember fromBinding(MethodBinding binding) {
return new ResolvedMemberImpl(Member.METHOD,fromBinding(binding.declaringClass),binding.modifiers,
fromBinding(binding.returnType),CharOperation.charToString(binding.selector),fromBindings(binding.parameters));
}
public TypeVariableDeclaringElement fromBinding(Binding declaringElement) {
if (declaringElement instanceof TypeBinding) {
return fromBinding(((TypeBinding)declaringElement));
} else {
return fromBinding((MethodBinding)declaringElement);
}
}
public void cleanup() {
this.typexToBinding.clear();
this.rawTypeXToBinding.clear();
this.finishedTypeMungers = null;
}
}
|
147,711 |
Bug 147711 Add an option to generate aj-synthetics with true synthetic flag
|
In a number of cases tools are getting confused over generated aj members that are "aj-synthetic" but not marked with the synthetic attribute (because in the past, this has upset other tools). The most recent example was a JAXB posting on the list - by having a perthis() clause in an aspect that matched a type with JAXB 2 annotations the user was no longer able to use JAXB. This is a serious issue, and will prevent the usage of JAXB 2 with any type into which we introduce properties as aj-synthetic members. The JAXB 2 solution to ignore such fields is to annotate them with @XmlTransient, but since the field does not exist in the user program they can't even do this!
|
resolved fixed
|
c9f311a
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-06-24T11:36:59Z | 2006-06-19T12:26:40Z |
tests/src/org/aspectj/systemtest/ajc152/Ajc152Tests.java
|
/*******************************************************************************
* Copyright (c) 2006 IBM
* 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.ajc152;
import java.io.File;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import junit.framework.Test;
import org.aspectj.ajdt.internal.core.builder.AsmHierarchyBuilder;
import org.aspectj.asm.AsmManager;
import org.aspectj.asm.IHierarchy;
import org.aspectj.asm.IProgramElement;
import org.aspectj.asm.IRelationshipMap;
import org.aspectj.asm.internal.Relationship;
import org.aspectj.testing.XMLBasedAjcTestCase;
import org.aspectj.util.CharOperation;
import org.aspectj.weaver.World;
public class Ajc152Tests extends org.aspectj.testing.XMLBasedAjcTestCase {
// public void testverifyErrNoTypeCflowField_pr145693() {runTest("verifyErrNoTypeCflowField");}
// public void testBrokenIfArgsCflowAtAj_pr145018() { runTest("ataj crashing with cflow, if and args");}
// public void testItdCallingGenericMethod_pr145391() { runTest("itd calling generic method");}
// public void testItdCallingGenericMethod_pr145391_2() { runTest("itd calling generic method - 2");}
// public void testAdviceNotWovenAspectPath_pr147841() { runTest("advice not woven on aspectpath");}
public void testDuplicateBridgeMethods_pr147801_1() { runTest("duplicate bridge methods");}
public void testPackageIgnoredForException_pr147701_1() { runTest("package for exception ignored");}
public void testPackageIgnoredForException_pr147701_2() { runTest("package for exception ignored - 2");}
public void testPackageIgnoredForException_pr147701_3() { runTest("package for exception ignored - 3");}
public void testBrokenAddSerialVersionUID_pr145950() {runTest("fails to discover Serializable");}
public void testNoUnnecessaryDeclarationOfThrownExcp_pr129282_1() {runTest("no unnecessary declaration of thrown exception warning - 1");}
public void testNoUnnecessaryDeclarationOfThrownExcp_pr129282_2() {runTest("no unnecessary declaration of thrown exception warning - 2");}
public void testNoUnnecessaryDeclarationOfThrownExcp_pr129282_3() {runTest("no unnecessary declaration of thrown exception warning - 3");}
public void testNoUnnecessaryDeclarationOfThrownExcp_pr129282_4() {runTest("no unnecessary declaration of thrown exception warning - 4");}
public void testNoUnnecessaryDeclarationOfThrownExcp_pr129282_5() {runTest("no unnecessary declaration of thrown exception warning - 5");}
public void testNoUnnecessaryDeclarationOfThrownExcp_pr129282_6() {runTest("no unnecessary declaration of thrown exception warning - 6");}
public void testNoUnnecessaryDeclarationOfThrownExcp_pr129282_7() {runTest("no unnecessary declaration of thrown exception warning - 7");}
public void testNoUnnecessaryDeclarationOfThrownExcp_pr129282_8() {runTest("no unnecessary declaration of thrown exception warning - 8");}
public void testNoUnnecessaryDeclarationOfThrownExcp_pr129282_9() {runTest("no unnecessary declaration of thrown exception warning - 9");}
public void testNoUnnecessaryDeclarationOfThrownExcp_pr129282_10() {runTest("no unnecessary declaration of thrown exception warning - 10");}
public void testAtAJVerificationError_pr144602() { runTest("atAJ perthis aspect verification error");}
public void testLTWAndGeneratingSUID_pr144465() { runTest("ltw with serialversionUID creation"); }
public void testAspects14PerSingleton_pr122253() { runTest("aspects14 - persingleton");}
public void testAspects14PerCflow_pr122253() { runTest("aspects14 - percflow");}
public void testAspects14PerThis_pr122253() { runTest("aspects14 - perthis");}
public void testAspects14PerTypeWithin_pr122253() { runTest("aspects14 - pertypewithin");}
public void testFunkyGenericErrorWithITDs_pr126355() { runTest("bizarre generic error with itds");}
public void testConcretizingAbstractMethods_pr142466() { runTest("aop.xml aspect inheriting but not concretizing abstract method");}
public void testConcretizingAbstractMethods_pr142466_2() { runTest("aop.xml aspect inheriting but not concretizing abstract method - 2");}
public void testComplexGenericDecl_pr137568() { runTest("complicated generics declaration");}
public void testItdOnInnerTypeOfGenericType_pr132349() { runTest("ITD on inner type of generic type");}
public void testItdOnInnerTypeOfGenericType_pr132349_2() { runTest("ITD on inner type of generic type - 2");}
public void testItdOnInnerTypeOfGenericType_pr132349_3() { runTest("ITD on inner type of generic type - 3");}
// public void testCovarianceAndDecp_pr128443_1() { runTest("covariance and decp - 1"); }
public void testLTWGeneratedAspectAbstractMethod_pr125480() { runTest("aop.xml aspect inheriting abstract method ");}
public void testLTWGeneratedAspectAbstractMethod_pr125480_2() { runTest("aop.xml aspect inheriting abstract method - code style");}
//public void testSuperITDExplosion_pr134425() { runTest("super ITDs");}
//public void testMisbehavingDeclareAnnotation_pr135865() { runTest("misbehaving declare annotation");}
//public void testMisbehavingDeclareAnnotation_pr135865_2() { runTest("misbehaving declare annotation - 2");}
public void testCompletelyBrokenAopConcretization_pr142165_1() { runTest("broken concretization");}
public void testCompletelyBrokenAopConcretization_pr142165_2() { runTest("broken concretization - 2");}
public void testCompletelyBrokenAopConcretization_pr142165_3() { runTest("broken concretization - 3");}
public void testVerifyErrorLTW_pr135068() { runTest("ltw verifyerror");}
public void testVerifyErrorLTW_pr135068_2() { runTest("ltw verifyerror - 2");}
public void testVerifyErrorLTW_pr135068_3() { runTest("ltw verifyerror - 3");}
public void testVerifyErrorLTW_pr135068_4() { runTest("ltw verifyerror - 4");}
public void testVerifyErrorForComplexCflow_pr136026() { runTest("verifyerror");}
public void testVerifyErrorForComplexCflow_pr136026_2() { runTest("verifyerror - 2");}
public void testAnnotationsAndGenericsBCException_pr129704() { runTest("annotations and generics leading to BCException");}
public void testMethodTooBigAfterWeaving_pr138384() { runTest("method too big"); }
public void testNotAtWithincode_pr138158_1() { runTest("not at withincode - 1");}
public void testNotAtWithincode_pr138158_2() { runTest("not at withincode - 2");}
public void testNotAtWithincode_pr138158_3() { runTest("not at within - 3");}
public void testNpeOnDup_pr138143() { runTest("npe on duplicate method with ataj");}
public void testPointcutsAndGenerics_pr137496_1() { runTest("pointcuts and generics - B");}
public void testPointcutsAndGenerics_pr137496_2() { runTest("pointcuts and generics - D");}
public void testPointcutsAndGenerics_pr137496_3() { runTest("pointcuts and generics - E");}
public void testPointcutsAndGenerics_pr137496_4() { runTest("pointcuts and generics - F");}
public void testPointcutsAndGenerics_pr137496_5() { runTest("pointcuts and generics - G");}
public void testPointcutsAndGenerics_pr137496_6() { runTest("pointcuts and generics - H");}
public void testAspectLibrariesAndASM_pr135001() { runTest("aspect libraries and asm");}
public void testStackOverflow_pr136258() { runTest("stack overflow");}
public void testIncorrectOverridesEvaluation13() { runTest("incorrect overrides evaluation - 1.3"); }
public void testIncorrectOverridesEvaluation15() { runTest("incorrect overrides evaluation - 1.5"); }
public void testAtWithinCodeBug_pr138798() { runTest("atWithinCodeBug"); }
public void testReferencePCutInDeclareWarning_pr138215() { runTest("Reference pointcut fails inside @DeclareWarning");}
public void testReferencePCutInPerClause_pr138219() { runTest("Can't use a FQ Reference pointcut in any pointcut expression referenced by a per-clause");}
public void testReferencePCutInPerClause_pr130722() { runTest("FQ Reference pointcut from perclause ref pc"); }
public void testDoubleAnnotationMatching_pr138223() { runTest("Double at annotation matching (no binding)");}
public void testSuperCallsInAtAspectJAdvice_pr139749() { runTest("Super calls in @AspectJ advice");}
public void testNoClassCastExceptionWithPerThis_pr138286() { runTest("No ClassCastException with perThis");}
public void testGenericAspectHierarchyWithBounds_pr147845() { runTest("Generic abstract aspect hierarchy with bounds"); }
public void testJRockitBooleanReturn_pr148007() { runTest("jrockit boolean fun");}
public void testJRockitBooleanReturn2_pr148007() { runTest("jrockit boolean fun (no aspects)");}
public void testDeclareAtMethodRelationship_pr143924() {
//AsmManager.setReporting("c:/debug.txt",true,true,true,true);
runTest("declare @method relationship");
IHierarchy top = AsmManager.getDefault().getHierarchy();
// get the IProgramElements corresponding to the different code entries
IProgramElement decam = top.findElementForLabel(top.getRoot(),
IProgramElement.Kind.DECLARE_ANNOTATION_AT_METHOD,
"declare @method: * debit(..) : @Secured(role = \"supervisor\")");
assertNotNull("Couldn't find 'declare @method' element in the tree",decam);
IProgramElement method = top.findElementForLabel(top.getRoot(),
IProgramElement.Kind.METHOD,"debit(java.lang.String,long)");
assertNotNull("Couldn't find the 'debit(String,long)' method element in the tree",method);
List matches = AsmManager.getDefault().getRelationshipMap().get(decam);
assertNotNull("'declare @method' should have some relationships but does not",matches);
assertTrue("'declare @method' should have one relationships but has " + matches.size(),matches.size()==1);
List matchesTargets = ((Relationship)matches.get(0)).getTargets();
assertTrue("'declare @method' should have one targets but has" + matchesTargets.size(),matchesTargets.size()==1);
IProgramElement target = AsmManager.getDefault().getHierarchy().findElementForHandle((String)matchesTargets.get(0));
assertEquals("target of relationship should be the 'debit(java.lang.String,long)' method but is IPE with label "
+ target.toLabelString(),method,target);
// check that the debit method has an annotated by relationship with the declare @method
matches = AsmManager.getDefault().getRelationshipMap().get(method);
assertNotNull("'debit(java.lang.String,long)' should have some relationships but does not",matches);
assertTrue("'debit(java.lang.String,long)' should have one relationships but has " + matches.size(),matches.size()==1);
matchesTargets = ((Relationship)matches.get(0)).getTargets();
assertTrue("'debit(java.lang.String,long)' should have one targets but has" + matchesTargets.size(),matchesTargets.size()==1);
target = AsmManager.getDefault().getHierarchy().findElementForHandle((String)matchesTargets.get(0));
assertEquals("target of relationship should be the 'declare @method' ipe but is IPE with label "
+ target.toLabelString(),decam,target);
}
// this next one reported as a bug by Rob Harrop, but I can't reproduce the failure yet...
//public void testAtAspectWithReferencePCPerClause_pr138220() { runTest("@Aspect with reference pointcut in perclause");}
public void testJarChecking_pr137235_1() { runTest("directory with .jar extension: source and outjar"); }
public void testJarChecking_pr137235_2() { runTest("directory with .jar extension"); }
public void testMakePreMethodNPE_pr136393() { runTest("NPE in makePreMethod");}
public void testGetParameterHandles_pr141730() {
runTest("new IProgramElement handle methods");
checkParametersForIPE("intMethod(int)",IProgramElement.Kind.METHOD,"I",true);
checkParametersForIPE("stringMethod(java.lang.String)",IProgramElement.Kind.METHOD,"Ljava/lang/String;",true);
checkParametersForIPE("myClassMethod(MyClass)",IProgramElement.Kind.METHOD,"LMyClass;",true);
checkParametersForIPE("genericMethod(java.util.List<java.lang.String>)",IProgramElement.Kind.METHOD,"Pjava/util/List<Ljava/lang/String;>;",true);
checkParametersForIPE("genericMethod2(MyGenericClass<java.lang.String,MyClass>)",IProgramElement.Kind.METHOD,"PMyGenericClass<Ljava/lang/String;LMyClass;>;",true);
checkParametersForIPE("main(java.lang.String[])",IProgramElement.Kind.METHOD,"[Ljava/lang/String;",true);
checkParametersForIPE("multiMethod(java.lang.String[][])",IProgramElement.Kind.METHOD,"[[Ljava/lang/String;",true);
checkParametersForIPE("intArray(int[])",IProgramElement.Kind.METHOD,"[I",true);
IHierarchy top = AsmManager.getDefault().getHierarchy();
IProgramElement twoArgsMethod = top.findElementForLabel(
top.getRoot(),IProgramElement.Kind.METHOD,"twoArgsMethod(int,java.lang.String)");
assertNotNull("Couldn't find 'twoArgsMethod(int,java.lang.String)' element in the tree",twoArgsMethod);
List l = twoArgsMethod.getParameterSignatures();
assertEquals("",((char[])l.get(0))[0],'I');
boolean eq = CharOperation.equals(((char[])l.get(1)),"Ljava/lang/String;".toCharArray());
assertTrue("expected parameter to be 'Ljava/lang/String;' but found '" +
new String(((char[])l.get(1))) + "'",eq);
}
public void testGetParameterTypes_pr141730() {
runTest("new IProgramElement handle methods");
checkParametersForIPE("intMethod(int)",IProgramElement.Kind.METHOD,"int",false);
checkParametersForIPE("stringMethod(java.lang.String)",IProgramElement.Kind.METHOD,"java.lang.String",false);
checkParametersForIPE("myClassMethod(MyClass)",IProgramElement.Kind.METHOD,"MyClass",false);
checkParametersForIPE("genericMethod(java.util.List<java.lang.String>)",IProgramElement.Kind.METHOD,"java.util.List<java.lang.String>",false);
checkParametersForIPE("genericMethod2(MyGenericClass<java.lang.String,MyClass>)",IProgramElement.Kind.METHOD,"MyGenericClass<java.lang.String,MyClass>",false);
checkParametersForIPE("main(java.lang.String[])",IProgramElement.Kind.METHOD,"java.lang.String[]",false);
checkParametersForIPE("multiMethod(java.lang.String[][])",IProgramElement.Kind.METHOD,"java.lang.String[][]",false);
checkParametersForIPE("intArray(int[])",IProgramElement.Kind.METHOD,"int[]",false);
}
public void testToSignatureString_pr141730() {
runTest("new IProgramElement handle methods");
checkSignatureOfIPE("main(java.lang.String[])",IProgramElement.Kind.METHOD);
checkSignatureOfIPE("C",IProgramElement.Kind.CLASS);
checkSignatureOfIPE("C()",IProgramElement.Kind.CONSTRUCTOR);
checkSignatureOfIPE("method()",IProgramElement.Kind.METHOD);
checkSignatureOfIPE("p()",IProgramElement.Kind.POINTCUT);
checkSignatureOfIPE("before(): p..",IProgramElement.Kind.ADVICE,"before()");
checkSignatureOfIPE("MyClass.method()",IProgramElement.Kind.INTER_TYPE_METHOD);
checkSignatureOfIPE("multiMethod(java.lang.String[][])",IProgramElement.Kind.METHOD);
checkSignatureOfIPE("intArray(int[])",IProgramElement.Kind.METHOD);
checkSignatureOfIPE("MyClass.MyClass()",IProgramElement.Kind.INTER_TYPE_CONSTRUCTOR);
}
// if not filling in the model for aspects contained in jar files then
// want to ensure that the relationship map is correct and has nodes
// which can be used in AJDT - ensure no NPE occurs for the end of
// the relationship with aspectpath
public void testAspectPathRelWhenNotFillingInModel_pr141730() {
World.createInjarHierarchy = false;
try {
runTest("ensure aspectpath injar relationships are correct when not filling in model");
// expecting:
// sourceOfRelationship main in MyFoo.java
// relationship advised by
// target MyBar.aj
//
// and
//
// sourceOfRelationship MyBar.aj
// relationship advises
// target main in MyFoo.java
IHierarchy top = AsmManager.getDefault().getHierarchy();
IRelationshipMap asmRelMap = AsmManager.getDefault().getRelationshipMap();
assertEquals("expected two sources of relationships but only found "
+ asmRelMap.getEntries().size(),2,asmRelMap.getEntries().size());
for (Iterator iter = asmRelMap.getEntries().iterator(); iter.hasNext();) {
String sourceOfRelationship = (String) iter.next();
IProgramElement ipe = top.findElementForHandle(sourceOfRelationship);
List relationships = asmRelMap.get(ipe);
if (ipe.getName().equals("MyBar.aj")) {
assertEquals("expected MyBar.aj to have one relationships but found "
+ relationships.size(),1,relationships.size());
Relationship rel = (Relationship)relationships.get(0);
assertEquals("expected relationship to be 'advises' but was "
+ rel.getName(), "advises", rel.getName());
List targets = rel.getTargets();
assertEquals("expected one target but found " + targets.size(),1,targets.size());
IProgramElement link = top.findElementForHandle((String)targets.get(0));
assertEquals("expected target 'method-call(void foo.MyFoo.main())' but target " + link.getName(),
"method-call(void foo.MyFoo.main())",link.getName());
String fileName = link.getSourceLocation().getSourceFile().toString();
assertTrue("expected 'main' to be in class MyFoo.java but found it " +
"in " + fileName,fileName.indexOf("MyFoo.java") != -1);
} else if (ipe.getName().equals("method-call(void foo.MyFoo.main())")) {
String fileName = ipe.getSourceLocation().getSourceFile().toString();
assertTrue("expected 'method-call(void foo.MyFoo.main())' to be in " +
"class MyFoo.java but found it in"
+ fileName,fileName.indexOf("MyFoo.java") != -1);
assertEquals("expected 'method-call(void foo.MyFoo.main())' " +
"to have one relationships but found "
+ relationships.size(),1,relationships.size());
Relationship rel = (Relationship)relationships.get(0);
assertEquals("expected relationship to be 'advised by' but was "
+ rel.getName(), "advised by", rel.getName());
List targets = rel.getTargets();
assertEquals("expected one target but found " + targets.size(),1,targets.size());
IProgramElement link = top.findElementForHandle((String)targets.get(0));
assertEquals("expected target 'MyBar.aj' but target " + link.getName(),
"MyBar.aj",link.getName());
} else {
fail("unexpected element " + ipe.getName() + " in the relationship map");
}
}
} finally {
World.createInjarHierarchy = true;
}
}
// if not filling in the model for classes contained in jar files then
// want to ensure that the relationship map is correct and has nodes
// which can be used in AJDT - ensure no NPE occurs for the end of
// the relationship with inpath
public void testNoNPEWithInpathWhenNotFillingInModel_pr141730() {
World.createInjarHierarchy = false;
try {
runTest("ensure inpath injar relationships are correct when not filling in model");
// the aspect used for this test has advice, declare parents, deow,
// and declare @type, @constructor, @field and @method. We only expect
// there to be relationships in the map for declare parents and declare @type
// (provided the model isn't being filled in) because the logic in the other
// addXXXRelationship methods use AspectJElementHierarchy.findElementForType().
// This method which returns null because there is no such ipe. The relationship is
// therefore not added to the model. Adding declare @type and declare parents
// uses AspectJElementHierarchy.findElementForHandle() which returns the file
// node ipe if it can't find one for the given handle. Therefore the relationships
// are added against the file node. Before change to using ipe's to create handles
// we also had the deow relationship, however, now we don't because this also
// uses findElementForType to find the targetNode which in the inpath case is null.
// just check that the number of entries is what we expect:
// We expect 3 (the declare @type and declare parents statements plus the filenode)
IRelationshipMap relMap = AsmManager.getDefault().getRelationshipMap();
assertEquals("expected 3 entries in the relationship map but found "
+ relMap.getEntries().size(), 3, relMap.getEntries().size());
} finally {
World.createInjarHierarchy = true;
}
}
public void testPCDInClassAppearsInModel_pr148027() {
// only want to test that its there if we're creating the uses pointcut
// relationship. This should be addressed by pr148027
if (!AsmHierarchyBuilder.shouldAddUsesPointcut) return;
World.createInjarHierarchy = false;
try {
runTest("ensure pcd declare in class appears in model");
IHierarchy top = AsmManager.getDefault().getHierarchy();
IProgramElement pcd = top.findElementForLabel(top.getRoot(),IProgramElement.Kind.POINTCUT,"pointcutInClass()");
IRelationshipMap relMap = AsmManager.getDefault().getRelationshipMap();
List relationships = relMap.get(pcd);
assertNotNull("expected relationships for pointcut " + pcd.toLinkLabelString()
+ " but didn't", relationships);
pcd = top.findElementForLabel(top.getRoot(),IProgramElement.Kind.POINTCUT,"pointcutInAspect()");
relationships = relMap.get(pcd);
assertNotNull("expected relationships for pointcut " + pcd.toLinkLabelString()
+ " but didn't", relationships);
} finally {
World.createInjarHierarchy = true;
}
}
// public void testFunkyGenericErrorWithITDs_pr126355_2() {
// runTest("bizarre generic error with itds - 2");
// // public class Pair<F,S> affected by pertarget aspect
// GenericsTests.verifyClassSignature(ajc,"Pair","<F:Ljava/lang/Object;S:Ljava/lang/Object;>Ljava/lang/Object;LIdempotentCache$ajcMightHaveAspect;;");
// }
public void testNoAspects(){
// setSystemProperty(WeavingAdaptor.WEAVING_ADAPTOR_VERBOSE,"true");
runTest("Ensure no weaving without included aspects");
}
public void testWeaveinfoMessages (){
runTest("weaveinfo messages with include and exclude");
}
// tests that can't be included for some reason
// Not valid whilst the ajc compiler forces debug on (ignores -g:none) - it will be green but is invalid, trust me
// public void testLongWindedMessages_pr129408() { runTest("long winded ataj messages");}
// ---------------- helper methods ---------------
private void checkParametersForIPE(String ipeLabel, IProgramElement.Kind kind, String expectedParm, boolean getHandles) {
IHierarchy top = AsmManager.getDefault().getHierarchy();
IProgramElement ipe = top.findElementForLabel(top.getRoot(),kind,ipeLabel);
assertNotNull("Couldn't find '" + ipeLabel + "' element in the tree",ipe);
List l = new ArrayList();
if (getHandles) {
l = ipe.getParameterSignatures();
} else {
l = ipe.getParameterTypes();
}
boolean eq = CharOperation.equals(((char[])l.get(0)),expectedParm.toCharArray());
assertTrue("expected parameter to be '" + expectedParm + "' but found '" +
new String(((char[])l.get(0))) + "'",eq);
}
private void checkSignatureOfIPE(String ipeLabel, IProgramElement.Kind kind) {
checkSignatureOfIPE(ipeLabel,kind,ipeLabel);
}
private void checkSignatureOfIPE(String ipeLabel, IProgramElement.Kind kind, String expectedSig) {
IHierarchy top = AsmManager.getDefault().getHierarchy();
IProgramElement ipe = top.findElementForLabel(
top.getRoot(),kind,ipeLabel);
assertNotNull("Couldn't find '" + ipeLabel + "' element in the tree",ipe);
assertEquals("expected signature to be '"+ expectedSig + "' but was " +
ipe.toSignatureString(true),expectedSig,ipe.toSignatureString(true));
}
/////////////////////////////////////////
public static Test suite() {
return XMLBasedAjcTestCase.loadSuite(Ajc152Tests.class);
}
protected File getSpecFile() {
return new File("../tests/src/org/aspectj/systemtest/ajc152/ajc152.xml");
}
}
|
147,711 |
Bug 147711 Add an option to generate aj-synthetics with true synthetic flag
|
In a number of cases tools are getting confused over generated aj members that are "aj-synthetic" but not marked with the synthetic attribute (because in the past, this has upset other tools). The most recent example was a JAXB posting on the list - by having a perthis() clause in an aspect that matched a type with JAXB 2 annotations the user was no longer able to use JAXB. This is a serious issue, and will prevent the usage of JAXB 2 with any type into which we introduce properties as aj-synthetic members. The JAXB 2 solution to ignore such fields is to annotate them with @XmlTransient, but since the field does not exist in the user program they can't even do this!
|
resolved fixed
|
c9f311a
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-06-24T11:36:59Z | 2006-06-19T12:26:40Z |
weaver/src/org/aspectj/weaver/NameMangler.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.bcel.LazyClassGen;
public class NameMangler {
private NameMangler() {
throw new RuntimeException("static");
}
public static final char[] AJC_DOLLAR_PREFIX = {'a', 'j', 'c','$'};
public static final char[] CLINIT={'<','c','l','i','n','i','t','>'};
public static final String PREFIX = "ajc$";
public static final char[] INIT = {'<','i','n','i','t','>'};
public static final String ITD_PREFIX = PREFIX + "interType$";
public static final char[] METHOD_ASPECTOF = {'a', 's', 'p','e','c','t','O','f'};
public static final char[] METHOD_HASASPECT = {'h', 'a', 's','A','s','p','e','c','t'};
public static final char[] STATIC_INITIALIZER = {'<', 'c', 'l','i','n','i','t','>'};
public static final String CFLOW_STACK_TYPE = "org.aspectj.runtime.internal.CFlowStack";
public static final String CFLOW_COUNTER_TYPE="org.aspectj.runtime.internal.CFlowCounter";
public static final String SOFT_EXCEPTION_TYPE = "org.aspectj.lang.SoftException";
public static final String PERSINGLETON_FIELD_NAME = PREFIX + "perSingletonInstance";
public static final String PERCFLOW_FIELD_NAME = PREFIX + "perCflowStack";
//public static final String PERTHIS_FIELD_NAME = PREFIX + "perSingletonInstance";
// -----
public static final String PERCFLOW_PUSH_METHOD = PREFIX + "perCflowPush";
public static final String PEROBJECT_BIND_METHOD = PREFIX + "perObjectBind";
// PTWIMPL Method and field names
public static final String PERTYPEWITHIN_GETINSTANCE_METHOD = PREFIX + "getInstance";
public static final String PERTYPEWITHIN_CREATEASPECTINSTANCE_METHOD = PREFIX + "createAspectInstance";
public static final String PERTYPEWITHIN_WITHINTYPEFIELD = PREFIX + "withinType";
public static final String AJC_PRE_CLINIT_NAME = PREFIX + "preClinit";
public static final String AJC_POST_CLINIT_NAME = PREFIX + "postClinit";
public static final String INITFAILURECAUSE_FIELD_NAME = PREFIX + "initFailureCause";
public static String perObjectInterfaceGet(UnresolvedType aspectType) {
return makeName(aspectType.getNameAsIdentifier(), "perObjectGet");
}
public static String perObjectInterfaceSet(UnresolvedType aspectType) {
return makeName(aspectType.getNameAsIdentifier(), "perObjectSet");
}
public static String perObjectInterfaceField(UnresolvedType aspectType) {
return makeName(aspectType.getNameAsIdentifier(), "perObjectField");
}
// PTWIMPL method names that must include aspect type
public static String perTypeWithinFieldForTarget(UnresolvedType aspectType) {
return makeName(aspectType.getNameAsIdentifier(), "ptwAspectInstance");
}
public static String perTypeWithinLocalAspectOf(UnresolvedType aspectType) {
return makeName(aspectType.getNameAsIdentifier(), "localAspectOf");
}
public static String itdAtDeclareParentsField(UnresolvedType aspectType, UnresolvedType itdType) {
return makeName(aspectType.getNameAsIdentifier(), itdType.getNameAsIdentifier());
}
public static String privilegedAccessMethodForMethod(String name, UnresolvedType objectType, UnresolvedType aspectType) {
return makeName("privMethod", aspectType.getNameAsIdentifier(),
objectType.getNameAsIdentifier(), name);
}
public static String privilegedAccessMethodForFieldGet(String name, UnresolvedType objectType, UnresolvedType aspectType) {
return makeName("privFieldGet", aspectType.getNameAsIdentifier(),
objectType.getNameAsIdentifier(), name);
}
public static String privilegedAccessMethodForFieldSet(String name, UnresolvedType objectType, UnresolvedType aspectType) {
return makeName("privFieldSet", aspectType.getNameAsIdentifier(),
objectType.getNameAsIdentifier(), name);
}
public static String inlineAccessMethodForMethod(String name, UnresolvedType objectType, UnresolvedType aspectType) {
return makeName("inlineAccessMethod", aspectType.getNameAsIdentifier(),
objectType.getNameAsIdentifier(), name);
}
public static String inlineAccessMethodForFieldGet(String name, UnresolvedType objectType, UnresolvedType aspectType) {
return makeName("inlineAccessFieldGet", aspectType.getNameAsIdentifier(),
objectType.getNameAsIdentifier(), name);
}
public static String inlineAccessMethodForFieldSet(String name, UnresolvedType objectType, UnresolvedType aspectType) {
return makeName("inlineAccessFieldSet", aspectType.getNameAsIdentifier(),
objectType.getNameAsIdentifier(), name);
}
/**
* The name of methods corresponding to advice declarations
* Of the form: "ajc$[AdviceKind]$[AspectName]$[NumberOfAdviceInAspect]$[PointcutHash]"
*/
public static String adviceName(String nameAsIdentifier, AdviceKind kind, int adviceSeqNumber,int pcdHash) {
String newname = makeName(
kind.getName(),
nameAsIdentifier,
Integer.toString(adviceSeqNumber),
Integer.toHexString(pcdHash));
return newname;
}
/**
* This field goes on top-most implementers of the interface the field
* is declared onto
*/
public static String interFieldInterfaceField(UnresolvedType aspectType, UnresolvedType interfaceType, String name) {
return makeName("interField", aspectType.getNameAsIdentifier(),
interfaceType.getNameAsIdentifier(), name);
}
/**
* This instance method goes on the interface the field is declared onto
* as well as its top-most implementors
*/
public static String interFieldInterfaceSetter(UnresolvedType aspectType, UnresolvedType interfaceType, String name) {
return makeName("interFieldSet", aspectType.getNameAsIdentifier(),
interfaceType.getNameAsIdentifier(), name);
}
/**
* This instance method goes on the interface the field is declared onto
* as well as its top-most implementors
*/
public static String interFieldInterfaceGetter(UnresolvedType aspectType, UnresolvedType interfaceType, String name) {
return makeName("interFieldGet", aspectType.getNameAsIdentifier(),
interfaceType.getNameAsIdentifier(), name);
}
/**
* This static method goes on the aspect that declares the inter-type field
*/
public static String interFieldSetDispatcher(UnresolvedType aspectType, UnresolvedType onType, String name) {
return makeName("interFieldSetDispatch", aspectType.getNameAsIdentifier(),
onType.getNameAsIdentifier(), name);
}
/**
* This static method goes on the aspect that declares the inter-type field
*/
public static String interFieldGetDispatcher(UnresolvedType aspectType, UnresolvedType onType, String name) {
return makeName("interFieldGetDispatch", aspectType.getNameAsIdentifier(),
onType.getNameAsIdentifier(), name);
}
/**
* This field goes on the class the field
* is declared onto
*/
public static String interFieldClassField(int modifiers, UnresolvedType aspectType, UnresolvedType classType, String name) {
if (Modifier.isPublic(modifiers)) return name;
//??? might want to handle case where aspect and class are in same package similar to public
return makeName("interField", makeVisibilityName(modifiers, aspectType), name);
}
// /**
// * This static method goes on the aspect that declares the inter-type field
// */
// public static String classFieldSetDispatcher(UnresolvedType aspectType, UnresolvedType classType, String name) {
// return makeName("interFieldSetDispatch", aspectType.getNameAsIdentifier(),
// classType.getNameAsIdentifier(), name);
// }
//
// /**
// * This static method goes on the aspect that declares the inter-type field
// */
// public static String classFieldGetDispatcher(UnresolvedType aspectType, UnresolvedType classType, String name)
// {
// return makeName(
// "interFieldGetDispatch",
// aspectType.getNameAsIdentifier(),
// classType.getNameAsIdentifier(),
// name);
// }
/**
* This static void method goes on the aspect that declares the inter-type field and is called
* from the appropriate place (target's initializer, or clinit, or topmost implementer's inits),
* to initialize the field;
*/
public static String interFieldInitializer(UnresolvedType aspectType, UnresolvedType classType, String name)
{
return makeName(
"interFieldInit",
aspectType.getNameAsIdentifier(),
classType.getNameAsIdentifier(),
name);
}
// ----
/**
* This method goes on the target type of the inter-type method. (and possibly the topmost-implemeters,
* if the target type is an interface)
*/
public static String interMethod(int modifiers, UnresolvedType aspectType, UnresolvedType classType, String name)
{
if (Modifier.isPublic(modifiers)) return name;
//??? might want to handle case where aspect and class are in same package similar to public
return makeName("interMethodDispatch2", makeVisibilityName(modifiers, aspectType), name);
}
/**
* This static method goes on the declaring aspect of the inter-type method.
*/
public static String interMethodDispatcher(UnresolvedType aspectType, UnresolvedType classType, String name)
{
return makeName("interMethodDispatch1", aspectType.getNameAsIdentifier(),
classType.getNameAsIdentifier(), name);
}
/**
* This static method goes on the declaring aspect of the inter-type method.
*/
public static String interMethodBody(UnresolvedType aspectType, UnresolvedType classType, String name)
{
return makeName("interMethod", aspectType.getNameAsIdentifier(),
classType.getNameAsIdentifier(), name);
}
// ----
/**
* This static method goes on the declaring aspect of the inter-type constructor.
*/
public static String preIntroducedConstructor(
UnresolvedType aspectType,
UnresolvedType targetType)
{
return makeName("preInterConstructor", aspectType.getNameAsIdentifier(),
targetType.getNameAsIdentifier());
}
/**
* This static method goes on the declaring aspect of the inter-type constructor.
*/
public static String postIntroducedConstructor(
UnresolvedType aspectType,
UnresolvedType targetType)
{
return makeName("postInterConstructor", aspectType.getNameAsIdentifier(),
targetType.getNameAsIdentifier());
}
// ----
/**
* This static method goes on the target class of the inter-type method.
*/
public static String superDispatchMethod(UnresolvedType classType, String name)
{
return makeName("superDispatch",
classType.getNameAsIdentifier(), name);
}
/**
* This static method goes on the target class of the inter-type method.
*/
public static String protectedDispatchMethod(UnresolvedType classType, String name)
{
return makeName("protectedDispatch",
classType.getNameAsIdentifier(), name);
}
// ----
private static String makeVisibilityName(int modifiers, UnresolvedType aspectType) {
if (Modifier.isPrivate(modifiers)) {
return aspectType.getOutermostType().getNameAsIdentifier();
} else if (Modifier.isProtected(modifiers)) {
throw new RuntimeException("protected inter-types not allowed");
} else if (Modifier.isPublic(modifiers)) {
return "";
} else {
return aspectType.getPackageNameAsIdentifier();
}
}
private static String makeName(String s1, String s2) {
return "ajc$" + s1 + "$" + s2;
}
public static String makeName(String s1, String s2, String s3) {
return "ajc$" + s1 + "$" + s2 + "$" + s3;
}
public static String makeName(String s1, String s2, String s3, String s4) {
return "ajc$" + s1 + "$" + s2 + "$" + s3 + "$" + s4;
}
public static String cflowStack(CrosscuttingMembers xcut) {
return makeName("cflowStack", Integer.toHexString(xcut.getCflowEntries().size()));
}
public static String cflowCounter(CrosscuttingMembers xcut) {
return makeName("cflowCounter",Integer.toHexString(xcut.getCflowEntries().size()));
}
public static String makeClosureClassName(
UnresolvedType enclosingType,
int index)
{
return enclosingType.getName() + "$AjcClosure" + index;
}
public static String aroundCallbackMethodName(
Member shadowSig,
LazyClassGen enclosingType)
{
String ret =
shadowSig.getExtractableName()
+ "_aroundBody"
+ enclosingType.getNewGeneratedNameTag();
return ret;
}
public static String proceedMethodName(String adviceMethodName) {
return adviceMethodName + "proceed";
}
}
|
147,711 |
Bug 147711 Add an option to generate aj-synthetics with true synthetic flag
|
In a number of cases tools are getting confused over generated aj members that are "aj-synthetic" but not marked with the synthetic attribute (because in the past, this has upset other tools). The most recent example was a JAXB posting on the list - by having a perthis() clause in an aspect that matched a type with JAXB 2 annotations the user was no longer able to use JAXB. This is a serious issue, and will prevent the usage of JAXB 2 with any type into which we introduce properties as aj-synthetic members. The JAXB 2 solution to ignore such fields is to annotate them with @XmlTransient, but since the field does not exist in the user program they can't even do this!
|
resolved fixed
|
c9f311a
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-06-24T11:36:59Z | 2006-06-19T12:26:40Z |
weaver/src/org/aspectj/weaver/bcel/LazyClassGen.java
|
/* *******************************************************************
* Copyright (c) 2002 Contributors
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the 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 6Jul05 generics - signature attribute
* ******************************************************************/
package org.aspectj.weaver.bcel;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.SortedMap;
import java.util.TreeMap;
import org.aspectj.apache.bcel.Constants;
import org.aspectj.apache.bcel.classfile.Attribute;
import org.aspectj.apache.bcel.classfile.ConstantUtf8;
import org.aspectj.apache.bcel.classfile.Field;
import org.aspectj.apache.bcel.classfile.JavaClass;
import org.aspectj.apache.bcel.classfile.Method;
import org.aspectj.apache.bcel.classfile.Signature;
import org.aspectj.apache.bcel.classfile.Unknown;
import org.aspectj.apache.bcel.classfile.annotation.Annotation;
import org.aspectj.apache.bcel.generic.BasicType;
import org.aspectj.apache.bcel.generic.ClassGen;
import org.aspectj.apache.bcel.generic.ConstantPoolGen;
import org.aspectj.apache.bcel.generic.FieldGen;
import org.aspectj.apache.bcel.generic.InstructionConstants;
import org.aspectj.apache.bcel.generic.InstructionFactory;
import org.aspectj.apache.bcel.generic.InstructionHandle;
import org.aspectj.apache.bcel.generic.InstructionList;
import org.aspectj.apache.bcel.generic.ObjectType;
import org.aspectj.apache.bcel.generic.PUSH;
import org.aspectj.apache.bcel.generic.RETURN;
import org.aspectj.apache.bcel.generic.Type;
import org.aspectj.apache.bcel.generic.annotation.AnnotationGen;
import org.aspectj.bridge.IMessage;
import org.aspectj.bridge.ISourceLocation;
import org.aspectj.bridge.SourceLocation;
import org.aspectj.util.CollectionUtil;
import org.aspectj.weaver.AjAttribute;
import org.aspectj.weaver.BCException;
import org.aspectj.weaver.Member;
import org.aspectj.weaver.NameMangler;
import org.aspectj.weaver.ResolvedMember;
import org.aspectj.weaver.ResolvedType;
import org.aspectj.weaver.Shadow;
import org.aspectj.weaver.TypeVariable;
import org.aspectj.weaver.UnresolvedType;
import org.aspectj.weaver.WeaverMessages;
import org.aspectj.weaver.WeaverStateInfo;
import org.aspectj.weaver.World;
import org.aspectj.weaver.AjAttribute.WeaverVersionInfo;
/**
* Lazy lazy lazy.
* We don't unpack the underlying class unless necessary. Things
* like new methods and annotations accumulate in here until they
* must be written out, don't add them to the underlying MethodGen!
* Things are slightly different if this represents an Aspect.
*/
public final class LazyClassGen {
int highestLineNumber = 0; // ---- JSR 45 info
private SortedMap /* <String, InlinedSourceFileInfo> */ inlinedFiles = new TreeMap();
private boolean regenerateGenericSignatureAttribute = false;
private BcelObjectType myType; // XXX is not set for types we create
private ClassGen myGen;
private ConstantPoolGen constantPoolGen;
private World world;
private String packageName = null;
private List /*LazyMethodGen*/ methodGens = new ArrayList();
private List /*LazyClassGen*/ classGens = new ArrayList();
private List /*AnnotationGen*/ annotations = new ArrayList();
private int childCounter = 0;
private InstructionFactory fact;
private boolean isSerializable = false;
private boolean hasSerialVersionUIDField = false;
private boolean serialVersionUIDRequiresInitialization = false;
private long calculatedSerialVersionUID;
private boolean hasClinit = false;
// ---
static class InlinedSourceFileInfo {
int highestLineNumber;
int offset; // calculated
InlinedSourceFileInfo(int highestLineNumber) {
this.highestLineNumber = highestLineNumber;
}
}
void addInlinedSourceFileInfo(String fullpath, int highestLineNumber) {
Object o = inlinedFiles.get(fullpath);
if (o != null) {
InlinedSourceFileInfo info = (InlinedSourceFileInfo) o;
if (info.highestLineNumber < highestLineNumber) {
info.highestLineNumber = highestLineNumber;
}
} else {
inlinedFiles.put(fullpath, new InlinedSourceFileInfo(highestLineNumber));
}
}
void calculateSourceDebugExtensionOffsets() {
int i = roundUpToHundreds(highestLineNumber);
for (Iterator iter = inlinedFiles.values().iterator(); iter.hasNext();) {
InlinedSourceFileInfo element = (InlinedSourceFileInfo) iter.next();
element.offset = i;
i = roundUpToHundreds(i + element.highestLineNumber);
}
}
private static int roundUpToHundreds(int i) {
return ((i / 100) + 1) * 100;
}
int getSourceDebugExtensionOffset(String fullpath) {
return ((InlinedSourceFileInfo) inlinedFiles.get(fullpath)).offset;
}
private Unknown getSourceDebugExtensionAttribute() {
int nameIndex = constantPoolGen.addUtf8("SourceDebugExtension");
String data = getSourceDebugExtensionString();
//System.err.println(data);
byte[] bytes = Utility.stringToUTF(data);
int length = bytes.length;
return new Unknown(nameIndex, length, bytes, constantPoolGen.getConstantPool());
}
// private LazyClassGen() {}
// public static void main(String[] args) {
// LazyClassGen m = new LazyClassGen();
// m.highestLineNumber = 37;
// m.inlinedFiles.put("boo/baz/foo.java", new InlinedSourceFileInfo( 83));
// m.inlinedFiles.put("boo/barz/foo.java", new InlinedSourceFileInfo(292));
// m.inlinedFiles.put("boo/baz/moo.java", new InlinedSourceFileInfo(128));
// m.calculateSourceDebugExtensionOffsets();
// System.err.println(m.getSourceDebugExtensionString());
// }
// For the entire pathname, we're using package names. This is probably wrong.
private String getSourceDebugExtensionString() {
StringBuffer out = new StringBuffer();
String myFileName = getFileName();
// header section
out.append("SMAP\n");
out.append(myFileName);
out.append("\nAspectJ\n");
// stratum section
out.append("*S AspectJ\n");
// file section
out.append("*F\n");
out.append("1 ");
out.append(myFileName);
out.append("\n");
int i = 2;
for (Iterator iter = inlinedFiles.keySet().iterator(); iter.hasNext();) {
String element = (String) iter.next();
int ii = element.lastIndexOf('/');
if (ii == -1) {
out.append(i++); out.append(' ');
out.append(element); out.append('\n');
} else {
out.append("+ "); out.append(i++); out.append(' ');
out.append(element.substring(ii+1)); out.append('\n');
out.append(element); out.append('\n');
}
}
// emit line section
out.append("*L\n");
out.append("1#1,");
out.append(highestLineNumber);
out.append(":1,1\n");
i = 2;
for (Iterator iter = inlinedFiles.values().iterator(); iter.hasNext();) {
InlinedSourceFileInfo element = (InlinedSourceFileInfo) iter.next();
out.append("1#");
out.append(i++); out.append(',');
out.append(element.highestLineNumber); out.append(":");
out.append(element.offset + 1); out.append(",1\n");
}
// end section
out.append("*E\n");
// and finish up...
return out.toString();
}
// ---- end JSR45-related stuff
/** Emit disassembled class and newline to out */
public static void disassemble(String path, String name, PrintStream out)
throws IOException {
if (null == out) {
return;
}
//out.println("classPath: " + classPath);
BcelWorld world = new BcelWorld(path);
UnresolvedType ut = UnresolvedType.forName(name);
ut.setNeedsModifiableDelegate(true);
LazyClassGen clazz = new LazyClassGen(BcelWorld.getBcelObjectType(world.resolve(ut)));
clazz.print(out);
out.println();
}
public int getNewGeneratedNameTag() {
return childCounter++;
}
// ----
public LazyClassGen(
String class_name,
String super_class_name,
String file_name,
int access_flags,
String[] interfaces,
World world)
{
myGen = new ClassGen(class_name, super_class_name, file_name, access_flags, interfaces);
constantPoolGen = myGen.getConstantPool();
fact = new InstructionFactory(myGen, constantPoolGen);
regenerateGenericSignatureAttribute = true;
this.world = world;
}
//Non child type, so it comes from a real type in the world.
public LazyClassGen(BcelObjectType myType) {
myGen = new ClassGen(myType.getJavaClass());
constantPoolGen = myGen.getConstantPool();
fact = new InstructionFactory(myGen, constantPoolGen);
this.myType = myType;
this.world = myType.getResolvedTypeX().getWorld();
/* Does this class support serialization */
if (implementsSerializable(getType())) {
isSerializable = true;
// ResolvedMember[] fields = getType().getDeclaredFields();
// for (int i = 0; i < fields.length; i++) {
// ResolvedMember field = fields[i];
// if (field.getName().equals("serialVersionUID")
// && field.isStatic() && field.getType().equals(ResolvedType.LONG)) {
// hasSerialVersionUIDField = true;
// }
// }
hasSerialVersionUIDField = hasSerialVersionUIDField(getType());
ResolvedMember[] methods = getType().getDeclaredMethods();
for (int i = 0; i < methods.length; i++) {
ResolvedMember method = methods[i];
if (method.getName().equals("<clinit>")) {
hasClinit = true;
}
}
// Do we need to calculate an SUID and add it?
if (!hasSerialVersionUIDField && world.isAddSerialVerUID()) {
calculatedSerialVersionUID = myGen.getSUID();
Field fg = new FieldGen(
Constants.ACC_PRIVATE|Constants.ACC_FINAL|Constants.ACC_STATIC,
BasicType.LONG,"serialVersionUID",getConstantPoolGen()).getField();
addField(fg);
hasSerialVersionUIDField=true;
serialVersionUIDRequiresInitialization=true;
// warn about what we've done?
if (world.getLint().calculatingSerialVersionUID.isEnabled())
world.getLint().calculatingSerialVersionUID.signal(
new String[]{getClassName(),Long.toString(calculatedSerialVersionUID)+"L"},null,null);
}
}
Method[] methods = myGen.getMethods();
for (int i = 0; i < methods.length; i++) {
addMethodGen(new LazyMethodGen(methods[i], this));
}
}
public static boolean hasSerialVersionUIDField (ResolvedType type) {
ResolvedMember[] fields = type.getDeclaredFields();
for (int i = 0; i < fields.length; i++) {
ResolvedMember field = fields[i];
if (field.getName().equals("serialVersionUID")
&& field.isStatic() && field.getType().equals(ResolvedType.LONG)) {
return true;
}
}
return false;
}
// public void addAttribute(Attribute i) {
// myGen.addAttribute(i);
// }
// ----
public String getInternalClassName() {
return getConstantPoolGen().getConstantPool().getConstantString(
myGen.getClassNameIndex(),
Constants.CONSTANT_Class);
}
public String getInternalFileName() {
String str = getInternalClassName();
int index = str.lastIndexOf('/');
if (index == -1) {
return getFileName();
} else {
return str.substring(0, index + 1) + getFileName();
}
}
public File getPackagePath(File root) {
String str = getInternalClassName();
int index = str.lastIndexOf('/');
if (index == -1)
return root;
return new File(root, str.substring(0, index));
}
/** Returns the packagename - if its the default package we return an empty string
*/
public String getPackageName() {
if (packageName!=null) return packageName;
String str = getInternalClassName();
int index = str.indexOf("<");
if (index!=-1) str = str.substring(0,index); // strip off the generics guff
index= str.lastIndexOf("/");
if (index==-1) return "";
return str.substring(0,index).replace('/','.');
}
public String getClassId() {
String str = getInternalClassName();
int index = str.lastIndexOf('/');
if (index == -1)
return str;
return str.substring(index + 1);
}
public void addMethodGen(LazyMethodGen gen) {
//assert gen.getClassName() == super.getClassName();
methodGens.add(gen);
if (highestLineNumber < gen.highestLineNumber) highestLineNumber = gen.highestLineNumber;
}
public void addMethodGen(LazyMethodGen gen, ISourceLocation sourceLocation) {
addMethodGen(gen);
if (!gen.getMethod().isPrivate()) {
warnOnAddedMethod(gen.getMethod(),sourceLocation);
}
}
public void errorOnAddedField (Field field, ISourceLocation sourceLocation) {
if (isSerializable && !hasSerialVersionUIDField) {
getWorld().getLint().serialVersionUIDBroken.signal(
new String[] {
myType.getResolvedTypeX().getName().toString(),
field.getName()
},
sourceLocation,
null);
}
}
public void warnOnAddedInterface (String name, ISourceLocation sourceLocation) {
warnOnModifiedSerialVersionUID(sourceLocation,"added interface " + name);
}
public void warnOnAddedMethod (Method method, ISourceLocation sourceLocation) {
warnOnModifiedSerialVersionUID(sourceLocation,"added non-private method " + method.getName());
}
public void warnOnAddedStaticInitializer (Shadow shadow, ISourceLocation sourceLocation) {
if (!hasClinit) {
warnOnModifiedSerialVersionUID(sourceLocation,"added static initializer");
}
}
public void warnOnModifiedSerialVersionUID (ISourceLocation sourceLocation, String reason) {
if (isSerializable && !hasSerialVersionUIDField)
getWorld().getLint().needsSerialVersionUIDField.signal(
new String[] {
myType.getResolvedTypeX().getName().toString(),
reason
},
sourceLocation,
null);
}
public World getWorld () {
return world;
}
public List getMethodGens() {
return methodGens; //???Collections.unmodifiableList(methodGens);
}
// FIXME asc Should be collection returned here
public Field[] getFieldGens() {
return myGen.getFields();
}
public Field getField(String name) {
Field[] allFields = myGen.getFields();
if (allFields==null) return null;
for (int i = 0; i < allFields.length; i++) {
Field field = allFields[i];
if (field.getName().equals(name)) return field;
}
return null;
}
// FIXME asc How do the ones on the underlying class surface if this just returns new ones added?
// FIXME asc ...although no one calls this right now !
public List getAnnotations() {
return annotations;
}
private void writeBack(BcelWorld world) {
if (getConstantPoolGen().getSize() > Short.MAX_VALUE) {
reportClassTooBigProblem();
return;
}
if (annotations.size()>0) {
for (Iterator iter = annotations.iterator(); iter.hasNext();) {
AnnotationGen element = (AnnotationGen) iter.next();
myGen.addAnnotation(element);
}
// Attribute[] annAttributes = org.aspectj.apache.bcel.classfile.Utility.getAnnotationAttributes(getConstantPoolGen(),annotations);
// for (int i = 0; i < annAttributes.length; i++) {
// Attribute attribute = annAttributes[i];
// System.err.println("Adding attribute for "+attribute);
// myGen.addAttribute(attribute);
// }
}
// Add a weaver version attribute to the file being produced (if necessary...)
boolean hasVersionAttribute = false;
Attribute[] attrs = myGen.getAttributes();
for (int i = 0; i < attrs.length && !hasVersionAttribute; i++) {
Attribute attribute = attrs[i];
if (attribute.getName().equals("org.aspectj.weaver.WeaverVersion")) hasVersionAttribute=true;
}
if (!hasVersionAttribute)
myGen.addAttribute(BcelAttributes.bcelAttribute(new AjAttribute.WeaverVersionInfo(),getConstantPoolGen()));
if (myType != null && myType.getWeaverState() != null) {
myGen.addAttribute(BcelAttributes.bcelAttribute(
new AjAttribute.WeaverState(myType.getWeaverState()),
getConstantPoolGen()));
}
//FIXME ATAJ needed only for slow Aspects.aspectOf() - keep or remove
//make a lot of test fail since the test compare weaved class file
// based on some test data as text files...
// if (!myGen.isInterface()) {
// addAjClassField();
// }
addAjcInitializers();
int len = methodGens.size();
myGen.setMethods(new Method[0]);
calculateSourceDebugExtensionOffsets();
for (int i = 0; i < len; i++) {
LazyMethodGen gen = (LazyMethodGen) methodGens.get(i);
// we skip empty clinits
if (isEmptyClinit(gen)) continue;
myGen.addMethod(gen.getMethod());
}
if (inlinedFiles.size() != 0) {
if (hasSourceDebugExtensionAttribute(myGen)) {
world.showMessage(
IMessage.WARNING,
WeaverMessages.format(WeaverMessages.OVERWRITE_JSR45,getFileName()),
null,
null);
}
// 17Feb05 - ASC - Skip this for now - it crashes IBM 1.4.2 jvms (pr80430). Will be revisited when contents
// of attribute are confirmed to be correct.
// myGen.addAttribute(getSourceDebugExtensionAttribute());
}
fixupGenericSignatureAttribute();
}
/**
* When working with 1.5 generics, a signature attribute is attached to the type which indicates
* how it was declared. This routine ensures the signature attribute for what we are about
* to write out is correct. Basically its responsibilities are:
* 1. Checking whether the attribute needs changing (i.e. did weaving change the type hierarchy)
* 2. If it did, removing the old attribute
* 3. Check if we need an attribute at all, are we generic? are our supertypes parameterized/generic?
* 4. Build the new attribute which includes all typevariable, supertype and superinterface information
*/
private void fixupGenericSignatureAttribute () {
if (getWorld() != null && !getWorld().isInJava5Mode()) return;
// TODO asc generics Temporarily assume that types we generate dont need a signature attribute (closure/etc).. will need revisiting no doubt...
if (myType==null) return;
// 1. Has anything changed that would require us to modify this attribute?
if (!regenerateGenericSignatureAttribute) return;
// 2. Find the old attribute
Signature sigAttr = null;
if (myType!=null) { // if null, this is a type built from scratch, it won't already have a sig attribute
Attribute[] as = myGen.getAttributes();
for (int i = 0; i < as.length; i++) {
Attribute attribute = as[i];
if (attribute.getName().equals("Signature")) sigAttr = (Signature)attribute;
}
}
// 3. Do we need an attribute?
boolean needAttribute = false;
if (sigAttr!=null) needAttribute = true; // If we had one before, we definetly still need one as types can't be 'removed' from the hierarchy
// check the interfaces
if (!needAttribute) {
if (myType==null) {
boolean stop = true;
}
ResolvedType[] interfaceRTXs = myType.getDeclaredInterfaces();
for (int i = 0; i < interfaceRTXs.length; i++) {
ResolvedType typeX = interfaceRTXs[i];
if (typeX.isGenericType() || typeX.isParameterizedType()) needAttribute = true;
}
// check the supertype
ResolvedType superclassRTX = myType.getSuperclass();
if (superclassRTX.isGenericType() || superclassRTX.isParameterizedType()) needAttribute = true;
}
if (needAttribute) {
StringBuffer signature = new StringBuffer();
// first, the type variables...
TypeVariable[] tVars = myType.getTypeVariables();
if (tVars.length>0) {
signature.append("<");
for (int i = 0; i < tVars.length; i++) {
TypeVariable variable = tVars[i];
signature.append(variable.getSignature());
}
signature.append(">");
}
// now the supertype
String supersig = myType.getSuperclass().getSignatureForAttribute();
signature.append(supersig);
ResolvedType[] interfaceRTXs = myType.getDeclaredInterfaces();
for (int i = 0; i < interfaceRTXs.length; i++) {
String s = interfaceRTXs[i].getSignatureForAttribute();
signature.append(s);
}
if (sigAttr!=null) myGen.removeAttribute(sigAttr);
myGen.addAttribute(createSignatureAttribute(signature.toString()));
}
}
/**
* Helper method to create a signature attribute based on a string signature:
* e.g. "Ljava/lang/Object;LI<Ljava/lang/Double;>;"
*/
private Signature createSignatureAttribute(String signature) {
int nameIndex = constantPoolGen.addUtf8("Signature");
int sigIndex = constantPoolGen.addUtf8(signature);
return new Signature(nameIndex,2,sigIndex,constantPoolGen.getConstantPool());
}
/**
*
*/
private void reportClassTooBigProblem() {
// PR 59208
// we've generated a class that is just toooooooooo big (you've been generating programs
// again haven't you? come on, admit it, no-one writes classes this big by hand).
// create an empty myGen so that we can give back a return value that doesn't upset the
// rest of the process.
myGen = new ClassGen(myGen.getClassName(), myGen.getSuperclassName(),
myGen.getFileName(), myGen.getAccessFlags(), myGen.getInterfaceNames());
// raise an error against this compilation unit.
getWorld().showMessage(
IMessage.ERROR,
WeaverMessages.format(WeaverMessages.CLASS_TOO_BIG,
this.getClassName()),
new SourceLocation(new File(myGen.getFileName()),0), null
);
}
private static boolean hasSourceDebugExtensionAttribute(ClassGen gen) {
ConstantPoolGen pool = gen.getConstantPool();
Attribute[] attrs = gen.getAttributes();
for (int i = 0; i < attrs.length; i++) {
if ("SourceDebugExtension"
.equals(((ConstantUtf8) pool.getConstant(attrs[i].getNameIndex())).getBytes())) {
return true;
}
}
return false;
}
public JavaClass getJavaClass(BcelWorld world) {
writeBack(world);
return myGen.getJavaClass();
}
public byte [] getJavaClassBytesIncludingReweavable(BcelWorld world){
writeBack(world);
byte [] wovenClassFileData = myGen.getJavaClass().getBytes();
WeaverStateInfo wsi = myType.getWeaverState();//getOrCreateWeaverStateInfo();
if(wsi != null && wsi.isReweavable()){ // && !reweavableDataInserted
//reweavableDataInserted = true;
return wsi.replaceKeyWithDiff(wovenClassFileData);
} else{
return wovenClassFileData;
}
}
public void addGeneratedInner(LazyClassGen newClass) {
classGens.add(newClass);
}
public void addInterface(UnresolvedType typeX, ISourceLocation sourceLocation) {
regenerateGenericSignatureAttribute = true;
myGen.addInterface(typeX.getRawName());
if (!typeX.equals(UnresolvedType.SERIALIZABLE))
warnOnAddedInterface(typeX.getName(),sourceLocation);
}
public void setSuperClass(ResolvedType typeX) {
regenerateGenericSignatureAttribute = true;
myType.addParent(typeX); // used for the attribute
if (typeX.getGenericType()!=null) typeX = typeX.getGenericType();
myGen.setSuperclassName(typeX.getName()); // used in the real class data
}
public String getSuperClassname() {
return myGen.getSuperclassName();
}
// FIXME asc not great that some of these ask the gen and some ask the type ! (see the related setters too)
public ResolvedType getSuperClass() {
return myType.getSuperclass();
}
public String[] getInterfaceNames() {
return myGen.getInterfaceNames();
}
// non-recursive, may be a bug, ha ha.
private List getClassGens() {
List ret = new ArrayList();
ret.add(this);
ret.addAll(classGens);
return ret;
}
public List getChildClasses(BcelWorld world) {
if (classGens.isEmpty()) return Collections.EMPTY_LIST;
List ret = new ArrayList();
for (Iterator i = classGens.iterator(); i.hasNext();) {
LazyClassGen clazz = (LazyClassGen) i.next();
byte[] bytes = clazz.getJavaClass(world).getBytes();
String name = clazz.getName();
int index = name.lastIndexOf('$');
// XXX this could be bad, check use of dollar signs.
name = name.substring(index+1);
ret.add(new UnwovenClassFile.ChildClass(name, bytes));
}
return ret;
}
public String toString() {
return toShortString();
}
public String toShortString() {
String s =
org.aspectj.apache.bcel.classfile.Utility.accessToString(myGen.getAccessFlags(), true);
if (s != "")
s += " ";
s += org.aspectj.apache.bcel.classfile.Utility.classOrInterface(myGen.getAccessFlags());
s += " ";
s += myGen.getClassName();
return s;
}
public String toLongString() {
ByteArrayOutputStream s = new ByteArrayOutputStream();
print(new PrintStream(s));
return new String(s.toByteArray());
}
public void print() { print(System.out); }
public void print(PrintStream out) {
List classGens = getClassGens();
for (Iterator iter = classGens.iterator(); iter.hasNext();) {
LazyClassGen element = (LazyClassGen) iter.next();
element.printOne(out);
if (iter.hasNext()) out.println();
}
}
private void printOne(PrintStream out) {
out.print(toShortString());
out.print(" extends ");
out.print(
org.aspectj.apache.bcel.classfile.Utility.compactClassName(
myGen.getSuperclassName(),
false));
int size = myGen.getInterfaces().length;
if (size > 0) {
out.print(" implements ");
for (int i = 0; i < size; i++) {
out.print(myGen.getInterfaceNames()[i]);
if (i < size - 1)
out.print(", ");
}
}
out.print(":");
out.println();
// XXX make sure to pass types correctly around, so this doesn't happen.
if (myType != null) {
myType.printWackyStuff(out);
}
Field[] fields = myGen.getFields();
for (int i = 0, len = fields.length; i < len; i++) {
out.print(" ");
out.println(fields[i]);
}
List methodGens = getMethodGens();
for (Iterator iter = methodGens.iterator(); iter.hasNext();) {
LazyMethodGen gen = (LazyMethodGen) iter.next();
// we skip empty clinits
if (isEmptyClinit(gen)) continue;
gen.print(out, (myType != null ? myType.getWeaverVersionAttribute() : WeaverVersionInfo.UNKNOWN));
if (iter.hasNext()) out.println();
}
// out.println(" ATTRIBS: " + Arrays.asList(myGen.getAttributes()));
out.println("end " + toShortString());
}
private boolean isEmptyClinit(LazyMethodGen gen) {
if (!gen.getName().equals("<clinit>")) return false;
//System.err.println("checking clinig: " + gen);
InstructionHandle start = gen.getBody().getStart();
while (start != null) {
if (Range.isRangeHandle(start) || (start.getInstruction() instanceof RETURN)) {
start = start.getNext();
} else {
return false;
}
}
return true;
}
public ConstantPoolGen getConstantPoolGen() {
return constantPoolGen;
}
public String getName() {
return myGen.getClassName();
}
public boolean isWoven() {
return myType.getWeaverState() != null;
}
public boolean isReweavable() {
if (myType.getWeaverState()==null) return true;
return myType.getWeaverState().isReweavable();
}
public Set getAspectsAffectingType() {
if (myType.getWeaverState()==null) return null;
return myType.getWeaverState().getAspectsAffectingType();
}
public WeaverStateInfo getOrCreateWeaverStateInfo(boolean inReweavableMode) {
WeaverStateInfo ret = myType.getWeaverState();
if (ret != null) return ret;
ret = new WeaverStateInfo(inReweavableMode);
myType.setWeaverState(ret);
return ret;
}
public InstructionFactory getFactory() {
return fact;
}
public LazyMethodGen getStaticInitializer() {
for (Iterator i = methodGens.iterator(); i.hasNext();) {
LazyMethodGen gen = (LazyMethodGen) i.next();
if (gen.getName().equals("<clinit>")) return gen;
}
LazyMethodGen clinit = new LazyMethodGen(
Modifier.STATIC,
Type.VOID,
"<clinit>",
new Type[0],
CollectionUtil.NO_STRINGS,
this);
clinit.getBody().insert(InstructionConstants.RETURN);
methodGens.add(clinit);
return clinit;
}
public LazyMethodGen getAjcPreClinit() {
for (Iterator i = methodGens.iterator(); i.hasNext();) {
LazyMethodGen gen = (LazyMethodGen) i.next();
if (gen.getName().equals(NameMangler.AJC_PRE_CLINIT_NAME)) return gen;
}
LazyMethodGen ajcClinit = new LazyMethodGen(
Modifier.STATIC,
Type.VOID,
NameMangler.AJC_PRE_CLINIT_NAME,
new Type[0],
CollectionUtil.NO_STRINGS,
this);
ajcClinit.getBody().insert(InstructionConstants.RETURN);
methodGens.add(ajcClinit);
getStaticInitializer().getBody().insert(Utility.createInvoke(getFactory(), ajcClinit));
return ajcClinit;
}
// reflective thisJoinPoint support
Map/*BcelShadow, Field*/ tjpFields = new HashMap();
public static final ObjectType proceedingTjpType =
new ObjectType("org.aspectj.lang.ProceedingJoinPoint");
public static final ObjectType tjpType =
new ObjectType("org.aspectj.lang.JoinPoint");
public static final ObjectType staticTjpType =
new ObjectType("org.aspectj.lang.JoinPoint$StaticPart");
public static final ObjectType enclosingStaticTjpType =
new ObjectType("org.aspectj.lang.JoinPoint$EnclosingStaticPart");
private static final ObjectType sigType =
new ObjectType("org.aspectj.lang.Signature");
// private static final ObjectType slType =
// new ObjectType("org.aspectj.lang.reflect.SourceLocation");
private static final ObjectType factoryType =
new ObjectType("org.aspectj.runtime.reflect.Factory");
private static final ObjectType classType =
new ObjectType("java.lang.Class");
public Field getTjpField(BcelShadow shadow, final boolean isEnclosingJp) {
Field ret = (Field)tjpFields.get(shadow);
if (ret != null) return ret;
int modifiers = Modifier.STATIC | Modifier.FINAL;
// XXX - Do we ever inline before or after advice? If we do, then we
// better include them in the check below. (or just change it to
// shadow.getEnclosingMethod().getCanInline())
// If the enclosing method is around advice, we could inline the join point
// that has led to this shadow. If we do that then the TJP we are creating
// here must be PUBLIC so it is visible to the type in which the
// advice is inlined. (PR71377)
LazyMethodGen encMethod = shadow.getEnclosingMethod();
boolean shadowIsInAroundAdvice = false;
if (encMethod!=null && encMethod.getName().startsWith(NameMangler.PREFIX+"around")) {
shadowIsInAroundAdvice = true;
}
if (getType().isInterface() || shadowIsInAroundAdvice) {
modifiers |= Modifier.PUBLIC;
}
else {
modifiers |= Modifier.PRIVATE;
}
ObjectType jpType = null;
if (world.isTargettingAspectJRuntime12()) { // TAG:SUPPORTING12: We didn't have different staticjp types in 1.2
jpType = staticTjpType;
} else {
jpType = isEnclosingJp?enclosingStaticTjpType:staticTjpType;
}
ret = new FieldGen(modifiers,jpType,"ajc$tjp_" + tjpFields.size(),getConstantPoolGen()).getField();
addField(ret);
tjpFields.put(shadow, ret);
return ret;
}
//FIXME ATAJ needed only for slow Aspects.aspectOf - keep or remove
// private void addAjClassField() {
// // Andy: Why build it again??
// Field ajClassField = new FieldGen(
// Modifier.PRIVATE | Modifier.FINAL | Modifier.STATIC,
// classType,
// "aj$class",
// getConstantPoolGen()).getField();
// addField(ajClassField);
//
// InstructionList il = new InstructionList();
// il.append(new PUSH(getConstantPoolGen(), getClassName()));
// il.append(fact.createInvoke("java.lang.Class", "forName", classType,
// new Type[] {Type.STRING}, Constants.INVOKESTATIC));
// il.append(fact.createFieldAccess(getClassName(), ajClassField.getName(),
// classType, Constants.PUTSTATIC));
//
// getStaticInitializer().getBody().insert(il);
// }
private void addAjcInitializers() {
if (tjpFields.size() == 0 && !serialVersionUIDRequiresInitialization) return;
InstructionList il = null;
if (tjpFields.size()>0) {
il = initializeAllTjps();
}
if (serialVersionUIDRequiresInitialization) {
if (il==null) {
il= new InstructionList();
}
il.append(new PUSH(getConstantPoolGen(),calculatedSerialVersionUID));
il.append(getFactory().createFieldAccess(getClassName(), "serialVersionUID", BasicType.LONG, Constants.PUTSTATIC));
}
getStaticInitializer().getBody().insert(il);
}
private InstructionList initializeAllTjps() {
InstructionList list = new InstructionList();
InstructionFactory fact = getFactory();
// make a new factory
list.append(fact.createNew(factoryType));
list.append(InstructionFactory.createDup(1));
list.append(new PUSH(getConstantPoolGen(), getFileName()));
// load the current Class object
//XXX check that this works correctly for inners/anonymous
list.append(new PUSH(getConstantPoolGen(), getClassName()));
//XXX do we need to worry about the fact the theorectically this could throw
//a ClassNotFoundException
list.append(fact.createInvoke("java.lang.Class", "forName", classType,
new Type[] {Type.STRING}, Constants.INVOKESTATIC));
list.append(fact.createInvoke(factoryType.getClassName(), "<init>",
Type.VOID, new Type[] {Type.STRING, classType},
Constants.INVOKESPECIAL));
list.append(InstructionFactory.createStore(factoryType, 0));
List entries = new ArrayList(tjpFields.entrySet());
Collections.sort(entries, new Comparator() {
public int compare(Object a, Object b) {
Map.Entry ae = (Map.Entry) a;
Map.Entry be = (Map.Entry) b;
return ((Field) ae.getValue())
.getName()
.compareTo(((Field)be.getValue()).getName());
}
});
for (Iterator i = entries.iterator(); i.hasNext(); ) {
Map.Entry entry = (Map.Entry)i.next();
initializeTjp(fact, list, (Field)entry.getValue(), (BcelShadow)entry.getKey());
}
return list;
}
private void initializeTjp(InstructionFactory fact, InstructionList list,
Field field, BcelShadow shadow)
{
Member sig = shadow.getSignature();
//ResolvedMember mem = shadow.getSignature().resolve(shadow.getWorld());
// load the factory
list.append(InstructionFactory.createLoad(factoryType, 0));
// load the kind
list.append(new PUSH(getConstantPoolGen(), shadow.getKind().getName()));
// create the signature
list.append(InstructionFactory.createLoad(factoryType, 0));
if (world.isTargettingAspectJRuntime12()) { // TAG:SUPPORTING12: We didn't have optimized factory methods in 1.2
list.append(new PUSH(getConstantPoolGen(), sig.getSignatureString(shadow.getWorld())));
list.append(fact.createInvoke(factoryType.getClassName(),
sig.getSignatureMakerName(),
new ObjectType(sig.getSignatureType()),
new Type[] { Type.STRING },
Constants.INVOKEVIRTUAL));
} else if (sig.getKind().equals(Member.METHOD)) {
BcelWorld w = shadow.getWorld();
// For methods, push the parts of the signature on.
list.append(new PUSH(getConstantPoolGen(),makeString(sig.getModifiers(w))));
list.append(new PUSH(getConstantPoolGen(),sig.getName()));
list.append(new PUSH(getConstantPoolGen(),makeString(sig.getDeclaringType())));
list.append(new PUSH(getConstantPoolGen(),makeString(sig.getParameterTypes())));
list.append(new PUSH(getConstantPoolGen(),makeString(sig.getParameterNames(w))));
list.append(new PUSH(getConstantPoolGen(),makeString(sig.getExceptions(w))));
list.append(new PUSH(getConstantPoolGen(),makeString(sig.getReturnType())));
// And generate a call to the variant of makeMethodSig() that takes 7 strings
list.append(fact.createInvoke(factoryType.getClassName(),
sig.getSignatureMakerName(),
new ObjectType(sig.getSignatureType()),
new Type[] { Type.STRING,Type.STRING,Type.STRING,Type.STRING,Type.STRING,Type.STRING,Type.STRING },
Constants.INVOKEVIRTUAL));
} else if (sig.getKind().equals(Member.MONITORENTER)) {
list.append(new PUSH(getConstantPoolGen(),makeString(sig.getDeclaringType())));
list.append(fact.createInvoke(factoryType.getClassName(),
sig.getSignatureMakerName(),
new ObjectType(sig.getSignatureType()),
new Type[] { Type.STRING},
Constants.INVOKEVIRTUAL));
} else if (sig.getKind().equals(Member.MONITOREXIT)) {
list.append(new PUSH(getConstantPoolGen(),makeString(sig.getDeclaringType())));
list.append(fact.createInvoke(factoryType.getClassName(),
sig.getSignatureMakerName(),
new ObjectType(sig.getSignatureType()),
new Type[] { Type.STRING},
Constants.INVOKEVIRTUAL));
} else if (sig.getKind().equals(Member.HANDLER)) {
BcelWorld w = shadow.getWorld();
list.append(new PUSH(getConstantPoolGen(),makeString(sig.getDeclaringType())));
list.append(new PUSH(getConstantPoolGen(),makeString(sig.getParameterTypes())));
list.append(new PUSH(getConstantPoolGen(),makeString(sig.getParameterNames(w))));
list.append(fact.createInvoke(factoryType.getClassName(),
sig.getSignatureMakerName(),
new ObjectType(sig.getSignatureType()),
new Type[] { Type.STRING, Type.STRING, Type.STRING },
Constants.INVOKEVIRTUAL));
} else if(sig.getKind().equals(Member.CONSTRUCTOR)) {
BcelWorld w = shadow.getWorld();
if (w.isJoinpointArrayConstructionEnabled() && sig.getDeclaringType().isArray()) {
// its the magical new jp
list.append(new PUSH(getConstantPoolGen(),makeString(Modifier.PUBLIC)));
list.append(new PUSH(getConstantPoolGen(),makeString(sig.getDeclaringType())));
list.append(new PUSH(getConstantPoolGen(),makeString(sig.getParameterTypes())));
list.append(new PUSH(getConstantPoolGen(),""));//makeString("")));//sig.getParameterNames(w))));
list.append(new PUSH(getConstantPoolGen(),""));//makeString("")));//sig.getExceptions(w))));
list.append(fact.createInvoke(factoryType.getClassName(),
sig.getSignatureMakerName(),
new ObjectType(sig.getSignatureType()),
new Type[] { Type.STRING, Type.STRING, Type.STRING, Type.STRING, Type.STRING },
Constants.INVOKEVIRTUAL));
} else {
list.append(new PUSH(getConstantPoolGen(),makeString(sig.getModifiers(w))));
list.append(new PUSH(getConstantPoolGen(),makeString(sig.getDeclaringType())));
list.append(new PUSH(getConstantPoolGen(),makeString(sig.getParameterTypes())));
list.append(new PUSH(getConstantPoolGen(),makeString(sig.getParameterNames(w))));
list.append(new PUSH(getConstantPoolGen(),makeString(sig.getExceptions(w))));
list.append(fact.createInvoke(factoryType.getClassName(),
sig.getSignatureMakerName(),
new ObjectType(sig.getSignatureType()),
new Type[] { Type.STRING, Type.STRING, Type.STRING, Type.STRING, Type.STRING },
Constants.INVOKEVIRTUAL));
}
} else if(sig.getKind().equals(Member.FIELD)) {
BcelWorld w = shadow.getWorld();
list.append(new PUSH(getConstantPoolGen(),makeString(sig.getModifiers(w))));
list.append(new PUSH(getConstantPoolGen(),sig.getName()));
list.append(new PUSH(getConstantPoolGen(),makeString(sig.getDeclaringType())));
list.append(new PUSH(getConstantPoolGen(),makeString(sig.getReturnType())));
list.append(fact.createInvoke(factoryType.getClassName(),
sig.getSignatureMakerName(),
new ObjectType(sig.getSignatureType()),
new Type[] { Type.STRING, Type.STRING, Type.STRING, Type.STRING },
Constants.INVOKEVIRTUAL));
} else if(sig.getKind().equals(Member.ADVICE)) {
BcelWorld w = shadow.getWorld();
list.append(new PUSH(getConstantPoolGen(),makeString(sig.getModifiers(w))));
list.append(new PUSH(getConstantPoolGen(),sig.getName()));
list.append(new PUSH(getConstantPoolGen(),makeString(sig.getDeclaringType())));
list.append(new PUSH(getConstantPoolGen(),makeString(sig.getParameterTypes())));
list.append(new PUSH(getConstantPoolGen(),makeString(sig.getParameterNames(w))));
list.append(new PUSH(getConstantPoolGen(),makeString(sig.getExceptions(w))));
list.append(new PUSH(getConstantPoolGen(),makeString((sig.getReturnType()))));
list.append(fact.createInvoke(factoryType.getClassName(),
sig.getSignatureMakerName(),
new ObjectType(sig.getSignatureType()),
new Type[] { Type.STRING, Type.STRING, Type.STRING, Type.STRING, Type.STRING, Type.STRING, Type.STRING },
Constants.INVOKEVIRTUAL));
} else if(sig.getKind().equals(Member.STATIC_INITIALIZATION)) {
BcelWorld w = shadow.getWorld();
list.append(new PUSH(getConstantPoolGen(),makeString(sig.getModifiers(w))));
list.append(new PUSH(getConstantPoolGen(),makeString(sig.getDeclaringType())));
list.append(fact.createInvoke(factoryType.getClassName(),
sig.getSignatureMakerName(),
new ObjectType(sig.getSignatureType()),
new Type[] { Type.STRING, Type.STRING },
Constants.INVOKEVIRTUAL));
} else {
list.append(new PUSH(getConstantPoolGen(), sig.getSignatureString(shadow.getWorld())));
list.append(fact.createInvoke(factoryType.getClassName(),
sig.getSignatureMakerName(),
new ObjectType(sig.getSignatureType()),
new Type[] { Type.STRING },
Constants.INVOKEVIRTUAL));
}
//XXX should load source location from shadow
list.append(Utility.createConstant(fact, shadow.getSourceLine()));
final String factoryMethod;
if (world.isTargettingAspectJRuntime12()) { // TAG:SUPPORTING12: We didn't have makeESJP() in 1.2
list.append(fact.createInvoke(factoryType.getClassName(),
"makeSJP", staticTjpType,
new Type[] { Type.STRING, sigType, Type.INT},
Constants.INVOKEVIRTUAL));
// put it in the field
list.append(fact.createFieldAccess(getClassName(), field.getName(),staticTjpType, Constants.PUTSTATIC));
} else {
if (staticTjpType.equals(field.getType())) {
factoryMethod = "makeSJP";
} else if (enclosingStaticTjpType.equals(field.getType())) {
factoryMethod = "makeESJP";
} else {
throw new Error("should not happen");
}
list.append(fact.createInvoke(factoryType.getClassName(),
factoryMethod, field.getType(),
new Type[] { Type.STRING, sigType, Type.INT},
Constants.INVOKEVIRTUAL));
// put it in the field
list.append(fact.createFieldAccess(getClassName(), field.getName(), field.getType(), Constants.PUTSTATIC));
}
}
protected String makeString(int i) {
return Integer.toString(i, 16); //??? expensive
}
protected String makeString(UnresolvedType t) {
// this is the inverse of the odd behavior for Class.forName w/ arrays
if (t.isArray()) {
// this behavior matches the string used by the eclipse compiler for Foo.class literals
return t.getSignature().replace('/', '.');
} else {
return t.getName();
}
}
protected String makeString(UnresolvedType[] types) {
if (types == null) return "";
StringBuffer buf = new StringBuffer();
for (int i = 0, len=types.length; i < len; i++) {
buf.append(makeString(types[i]));
buf.append(':');
}
return buf.toString();
}
protected String makeString(String[] names) {
if (names == null) return "";
StringBuffer buf = new StringBuffer();
for (int i = 0, len=names.length; i < len; i++) {
buf.append(names[i]);
buf.append(':');
}
return buf.toString();
}
public ResolvedType getType() {
if (myType == null) return null;
return myType.getResolvedTypeX();
}
public BcelObjectType getBcelObjectType() {
return myType;
}
public String getFileName() {
return myGen.getFileName();
}
private void addField(Field field) {
myGen.addField(field);
}
public void replaceField(Field oldF, Field newF){
myGen.removeField(oldF);
myGen.addField(newF);
}
public void addField(Field field, ISourceLocation sourceLocation) {
addField(field);
if (!(field.isPrivate()
&& (field.isStatic() || field.isTransient()))) {
errorOnAddedField(field,sourceLocation);
}
}
public String getClassName() {
return myGen.getClassName();
}
public boolean isInterface() {
return myGen.isInterface();
}
public boolean isAbstract() {
return myGen.isAbstract();
}
public LazyMethodGen getLazyMethodGen(Member m) {
return getLazyMethodGen(m.getName(), m.getSignature(),false);
}
public LazyMethodGen getLazyMethodGen(String name, String signature) {
return getLazyMethodGen(name,signature,false);
}
public LazyMethodGen getLazyMethodGen(String name, String signature,boolean allowMissing) {
for (Iterator i = methodGens.iterator(); i.hasNext();) {
LazyMethodGen gen = (LazyMethodGen) i.next();
if (gen.getName().equals(name) && gen.getSignature().equals(signature))
return gen;
}
if (!allowMissing) {
throw new BCException("Class " + this.getName() + " does not have a method "
+ name + " with signature " + signature);
}
return null;
}
public void forcePublic() {
myGen.setAccessFlags(Utility.makePublic(myGen.getAccessFlags()));
}
public boolean hasAnnotation(UnresolvedType t) {
// annotations on the real thing
AnnotationGen agens[] = myGen.getAnnotations();
if (agens==null) return false;
for (int i = 0; i < agens.length; i++) {
AnnotationGen gen = agens[i];
if (t.equals(UnresolvedType.forSignature(gen.getTypeSignature()))) return true;
}
// annotations added during this weave
return false;
}
public void addAnnotation(Annotation a) {
if (!hasAnnotation(UnresolvedType.forSignature(a.getTypeSignature()))) {
annotations.add(new AnnotationGen(a,getConstantPoolGen(),true));
}
}
// this test is like asking:
// if (UnresolvedType.SERIALIZABLE.resolve(getType().getWorld()).isAssignableFrom(getType())) {
// only we don't do that because this forces us to find all the supertypes of the type,
// and if one of them is missing we fail, and it's not worth failing just to put out
// a warning message!
private boolean implementsSerializable(ResolvedType aType) {
if (aType.getSignature().equals(UnresolvedType.SERIALIZABLE.getSignature())) return true;
ResolvedType[] interfaces = aType.getDeclaredInterfaces();
for (int i = 0; i < interfaces.length; i++) {
if (interfaces[i].isMissing()) continue;
if (implementsSerializable(interfaces[i])) return true;
}
ResolvedType superType = aType.getSuperclass();
if (superType != null && !superType.isMissing()) {
return implementsSerializable(superType);
}
return false;
}
public boolean isAtLeastJava5() {
return (myGen.getMajor()>=Constants.MAJOR_1_5);
}
/**
* Return the next available field name with the specified 'prefix', e.g.
* for prefix 'class$' where class$0, class$1 exist then return class$2
*/
public String allocateField(String prefix) {
int highestAllocated = -1;
Field[] fs = getFieldGens();
for (int i = 0; i < fs.length; i++) {
Field field = fs[i];
if (field.getName().startsWith(prefix)) {
try {
int num = Integer.parseInt(field.getName().substring(prefix.length()));
if (num>highestAllocated) highestAllocated = num;
} catch (NumberFormatException nfe) {
// something wrong with the number on the end of that field...
}
}
}
return prefix+Integer.toString(highestAllocated+1);
}
}
|
147,711 |
Bug 147711 Add an option to generate aj-synthetics with true synthetic flag
|
In a number of cases tools are getting confused over generated aj members that are "aj-synthetic" but not marked with the synthetic attribute (because in the past, this has upset other tools). The most recent example was a JAXB posting on the list - by having a perthis() clause in an aspect that matched a type with JAXB 2 annotations the user was no longer able to use JAXB. This is a serious issue, and will prevent the usage of JAXB 2 with any type into which we introduce properties as aj-synthetic members. The JAXB 2 solution to ignore such fields is to annotate them with @XmlTransient, but since the field does not exist in the user program they can't even do this!
|
resolved fixed
|
c9f311a
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-06-24T11:36:59Z | 2006-06-19T12: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.Properties;
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.Annotation;
import org.aspectj.apache.bcel.generic.BranchHandle;
import org.aspectj.apache.bcel.generic.BranchInstruction;
import org.aspectj.apache.bcel.generic.CPInstruction;
import org.aspectj.apache.bcel.generic.ClassGenException;
import org.aspectj.apache.bcel.generic.CodeExceptionGen;
import org.aspectj.apache.bcel.generic.ConstantPoolGen;
import org.aspectj.apache.bcel.generic.Instruction;
import org.aspectj.apache.bcel.generic.InstructionHandle;
import org.aspectj.apache.bcel.generic.InstructionList;
import org.aspectj.apache.bcel.generic.InstructionTargeter;
import org.aspectj.apache.bcel.generic.LineNumberGen;
import org.aspectj.apache.bcel.generic.LineNumberTag;
import org.aspectj.apache.bcel.generic.LocalVariableGen;
import org.aspectj.apache.bcel.generic.LocalVariableInstruction;
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.Select;
import org.aspectj.apache.bcel.generic.Tag;
import org.aspectj.apache.bcel.generic.Type;
import org.aspectj.apache.bcel.generic.annotation.AnnotationGen;
import org.aspectj.bridge.IMessage;
import org.aspectj.bridge.ISourceLocation;
import org.aspectj.bridge.MessageUtil;
import org.aspectj.weaver.AjAttribute;
import org.aspectj.weaver.AnnotationX;
import org.aspectj.weaver.BCException;
import org.aspectj.weaver.ISourceContext;
import org.aspectj.weaver.MemberImpl;
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.AjAttribute.WeaverVersionInfo;
/**
* A LazyMethodGen should be treated as a MethodGen. It's our way of abstracting over the
* low-level Method objects. It converts through {@link MethodGen} to create
* and to serialize, but that's it.
*
* <p> At any rate, there are two ways to create LazyMethodGens.
* One is from a method, which
* does work through MethodGen to do the correct thing.
* The other is the creation of a completely empty
* LazyMethodGen, and it is used when we're constructing code from scratch.
*
* <p> We stay away from targeters for rangey things like Shadows and Exceptions.
*/
public final class LazyMethodGen {
private int accessFlags;
private Type returnType;
private final String name;
private Type[] argumentTypes;
//private final String[] argumentNames;
private String[] declaredExceptions;
private InstructionList body; // leaving null for abstracts
private Attribute[] attributes;
private List newAnnotations;
private final LazyClassGen enclosingClass;
private BcelMethod memberView;
private AjAttribute.EffectiveSignatureAttribute effectiveSignature;
int highestLineNumber = 0;
/*
* 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 targetting *it* - this reduces the amount
* of targeter manipulation we have to do.
*
* Because this *could* go wrong - it passes all our tests, but you never know, the option:
* -Xset:optimizeWithTags=false
* will turn it *OFF*
*/
public static boolean avoidUseOfBcelGenObjects = true;
public static boolean checkedXsetOption = false;
/** This is nonnull if this method is the result of an "inlining". We currently
* copy methods into other classes for around advice. We add this field so
* we can get JSR45 information correct. If/when we do _actual_ inlining,
* we'll need to subtype LineNumberTag to have external line numbers.
*/
String fromFilename = null;
private int maxLocals;
private boolean canInline = true;
// private boolean hasExceptionHandlers;
private boolean isSynthetic = false;
/**
* only used by {@link BcelClassWeaver}
*/
List /*ShadowMungers*/ matchedShadows;
List /*Test*/ matchedShadowTests;
// Used for interface introduction
// this is the type of the interface the method is technically on
public ResolvedType definingType = null;
public LazyMethodGen(
int accessFlags,
Type returnType,
String name,
Type[] paramTypes,
String[] declaredExceptions,
LazyClassGen enclosingClass)
{
//System.err.println("raw create of: " + name + ", " + enclosingClass.getName() + ", " + returnType);
this.memberView = null; // ??? should be okay, since constructed ones aren't woven into
this.accessFlags = accessFlags;
this.returnType = returnType;
this.name = name;
this.argumentTypes = paramTypes;
//this.argumentNames = Utility.makeArgNames(paramTypes.length);
this.declaredExceptions = declaredExceptions;
if (!Modifier.isAbstract(accessFlags)) {
body = new InstructionList();
setMaxLocals(calculateMaxLocals());
} else {
body = null;
}
this.attributes = new Attribute[0];
this.enclosingClass = enclosingClass;
assertGoodBody();
// @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 = 0;
if (!Modifier.isStatic(accessFlags)) ret++;
for (int i = 0, len = argumentTypes.length; i < len; i++) {
ret += argumentTypes[i].getSize();
}
return ret;
}
private Method savedMethod = null;
// build from an existing method, lazy build saves most work for initialization
public LazyMethodGen(Method m, LazyClassGen enclosingClass) {
savedMethod = m;
this.enclosingClass = enclosingClass;
if (!(m.isAbstract() || m.isNative()) && m.getCode() == null) {
throw new RuntimeException("bad non-abstract method with no code: " + m + " on " + enclosingClass);
}
if ((m.isAbstract() || m.isNative()) && m.getCode() != null) {
throw new RuntimeException("bad abstract method with code: " + m + " on " + enclosingClass);
}
this.memberView = new BcelMethod(enclosingClass.getBcelObjectType(), m);
this.accessFlags = m.getAccessFlags();
this.name = m.getName();
// @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(AnnotationX ax) {
initialize();
if (memberView==null) {
// If member view is null, we manage them in newAnnotations
if (newAnnotations==null) newAnnotations = new ArrayList();
newAnnotations.add(ax);
} else {
memberView.addAnnotation(ax);
}
}
public boolean hasAnnotation(UnresolvedType annotationTypeX) {
initialize();
if (memberView==null) {
// Check local annotations first
if (newAnnotations!=null) {
for (Iterator iter = newAnnotations.iterator(); iter.hasNext();) {
AnnotationX element = (AnnotationX) iter.next();
if (element.getBcelAnnotation().getTypeName().equals(annotationTypeX.getName())) return true;
}
}
memberView = new BcelMethod(getEnclosingClass().getBcelObjectType(), getMethod());
return memberView.hasAnnotation(annotationTypeX);
}
return memberView.hasAnnotation(annotationTypeX);
}
private void initialize() {
if (returnType != null) return;
// Check whether we need to configure the optimization
if (!checkedXsetOption) {
Properties p = enclosingClass.getWorld().getExtraConfiguration();
if (p!=null) {
String s = p.getProperty("optimizeWithTags","true");
avoidUseOfBcelGenObjects = s.equalsIgnoreCase("true");
if (!avoidUseOfBcelGenObjects)
enclosingClass.getWorld().getMessageHandler().handleMessage(MessageUtil.info("[optimizeWithTags=false] Disabling optimization to use Tags rather than Gens"));
}
checkedXsetOption=true;
}
//System.err.println("initializing: " + getName() + ", " + enclosingClass.getName() + ", " + returnType + ", " + savedMethod);
MethodGen gen = new MethodGen(savedMethod, enclosingClass.getName(), enclosingClass.getConstantPoolGen(),avoidUseOfBcelGenObjects);
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);
if (avoidUseOfBcelGenObjects) {
ensureAllLineNumberSetup(gen);
highestLineNumber = gen.getHighestlinenumber();
} else {
unpackLineNumbers(gen);
unpackLocals(gen);
}
}
assertGoodBody();
//System.err.println("initialized: " + this.getClassName() + "." + this.getName());
}
// XXX we're relying on the javac promise I've just made up that we won't have an early exception
// in the list mask a later exception: That is, for two exceptions E and F,
// if E preceeds F, then either E \cup F = {}, or E \nonstrictsubset F. So when we add F,
// we add it on the _OUTSIDE_ of any handlers that share starts or ends with it.
// with that in mind, we merrily go adding ranges for exceptions.
private void unpackHandlers(MethodGen gen) {
CodeExceptionGen[] exns = gen.getExceptionHandlers();
if (exns != null) {
int len = exns.length;
// if (len > 0) hasExceptionHandlers = true;
int priority = len - 1;
for (int i = 0; i < len; i++, priority--) {
CodeExceptionGen exn = exns[i];
InstructionHandle start =
Range.genStart(
body,
getOutermostExceptionStart(exn.getStartPC()));
InstructionHandle end = Range.genEnd(body, getOutermostExceptionEnd(exn.getEndPC()));
// this doesn't necessarily handle overlapping correctly!!!
ExceptionRange er =
new ExceptionRange(
body,
exn.getCatchType() == null
? null
: BcelWorld.fromBcel(exn.getCatchType()),
priority);
er.associateWithTargets(start, end, exn.getHandlerPC());
exn.setStartPC(null); // also removes from target
exn.setEndPC(null); // also removes from target
exn.setHandlerPC(null); // also removes from target
}
gen.removeExceptionHandlers();
}
}
private InstructionHandle getOutermostExceptionStart(InstructionHandle ih) {
while (true) {
if (ExceptionRange.isExceptionStart(ih.getPrev())) {
ih = ih.getPrev();
} else {
return ih;
}
}
}
private InstructionHandle getOutermostExceptionEnd(InstructionHandle ih) {
while (true) {
if (ExceptionRange.isExceptionEnd(ih.getNext())) {
ih = ih.getNext();
} else {
return ih;
}
}
}
private void unpackLineNumbers(MethodGen gen) {
LineNumberTag lr = null;
for (InstructionHandle ih = body.getStart(); ih != null; ih = ih.getNext()) {
InstructionTargeter[] targeters = ih.getTargeters();
if (targeters != null) {
for (int i = targeters.length - 1; i >= 0; i--) {
InstructionTargeter targeter = targeters[i];
if (targeter instanceof LineNumberGen) {
LineNumberGen lng = (LineNumberGen) targeter;
lng.updateTarget(ih, null);
int lineNumber = lng.getSourceLine();
if (highestLineNumber < lineNumber) highestLineNumber = lineNumber;
lr = new LineNumberTag(lineNumber);
}
}
}
if (lr != null) {
ih.addTargeter(lr);
}
}
gen.removeLineNumbers();
}
/**
* 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.
*/
private void ensureAllLineNumberSetup(MethodGen gen) {
LineNumberTag lr = null;
boolean skip = false;
for (InstructionHandle ih = body.getStart(); ih != null; ih = ih.getNext()) {
InstructionTargeter[] targeters = ih.getTargeters();
skip = false;
if (targeters != null) {
for (int i = targeters.length - 1; i >= 0; i--) {
InstructionTargeter targeter = targeters[i];
if (targeter instanceof LineNumberTag) {
lr = (LineNumberTag) targeter;
skip=true;
}
}
}
if (lr != null && !skip) {
ih.addTargeter(lr);
}
}
}
private void unpackLocals(MethodGen gen) {
Set locals = new HashSet();
for (InstructionHandle ih = body.getStart(); ih != null; ih = ih.getNext()) {
InstructionTargeter[] targeters = ih.getTargeters();
List ends = new ArrayList(0);
if (targeters != null) {
for (int i = targeters.length - 1; i >= 0; i--) {
InstructionTargeter targeter = targeters[i];
if (targeter instanceof LocalVariableGen) {
LocalVariableGen lng = (LocalVariableGen) targeter;
LocalVariableTag lr = new LocalVariableTag(lng.getType().getSignature()/*BcelWorld.fromBcel(lng.getType())*/, lng.getName(), lng.getIndex(), lng.getStart().getPosition());
if (lng.getStart() == ih) {
locals.add(lr);
} else {
ends.add(lr);
}
}
}
}
for (Iterator i = locals.iterator(); i.hasNext(); ) {
ih.addTargeter((LocalVariableTag) i.next());
}
locals.removeAll(ends);
}
gen.removeLocalVariables();
}
// ===============
public int allocateLocal(Type type) {
return allocateLocal(type.getSize());
}
public int allocateLocal(int slots) {
int max = getMaxLocals();
setMaxLocals(max + slots);
return max;
}
public Method getMethod() {
if (savedMethod != null) return savedMethod; //??? this relies on gentle treatment of constant pool
try {
MethodGen gen = pack();
return gen.getMethod();
} catch (ClassGenException e) {
enclosingClass.getBcelObjectType().getResolvedTypeX().getWorld().showMessage(
IMessage.ERROR,
WeaverMessages.format(WeaverMessages.PROBLEM_GENERATING_METHOD,
this.getClassName(),
this.getName(),
e.getMessage()),
this.getMemberView() == null ? null : this.getMemberView().getSourceLocation(), null);
// throw e; PR 70201.... let the normal problem reporting infrastructure deal with this rather than crashing.
body = null;
MethodGen gen = pack();
return gen.getMethod();
}
}
public void markAsChanged() {
initialize();
savedMethod = null;
}
// =============================
public String toString() {
WeaverVersionInfo weaverVersion = enclosingClass.getBcelObjectType().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 as = BcelAttributes.readAjAttributes(getClassName(),attributes, context,null,weaverVersion);
if (! as.isEmpty()) {
out.println(" " + as.get(0)); // XXX assuming exactly one attribute, munger...
}
}
private class BodyPrinter {
Map prefixMap = new HashMap();
Map suffixMap = new HashMap();
Map labelMap = new HashMap();
InstructionList body;
PrintStream out;
ConstantPool pool;
List ranges;
BodyPrinter(PrintStream out) {
this.pool = enclosingClass.getConstantPoolGen().getConstantPool();
this.body = getBody();
this.out = out;
}
void run() {
//killNops();
assignLabels();
print();
}
// label assignment
void assignLabels() {
LinkedList exnTable = new LinkedList();
String pendingLabel = null;
// boolean hasPendingTargeters = false;
int lcounter = 0;
for (InstructionHandle ih = body.getStart(); ih != null; ih = ih.getNext()) {
InstructionTargeter[] targeters = ih.getTargeters();
if (targeters != null) {
for (int i = targeters.length - 1; i >= 0; i--) {
InstructionTargeter t = targeters[i];
if (t instanceof ExceptionRange) {
// assert isRangeHandle(h);
ExceptionRange r = (ExceptionRange) t;
if (r.getStart() == ih) {
insertHandler(r, exnTable);
}
} else if (t instanceof BranchInstruction) {
if (pendingLabel == null) {
pendingLabel = "L" + lcounter++;
}
} else {
// assert isRangeHandle(h)
}
}
}
if (pendingLabel != null) {
labelMap.put(ih, pendingLabel);
if (! Range.isRangeHandle(ih)) {
pendingLabel = null;
}
}
}
int ecounter = 0;
for (Iterator i = exnTable.iterator(); i.hasNext();) {
ExceptionRange er = (ExceptionRange) i.next();
String exceptionLabel = "E" + ecounter++;
labelMap.put(Range.getRealStart(er.getHandler()), exceptionLabel);
labelMap.put(er.getHandler(), exceptionLabel);
}
}
// printing
void print() {
int depth = 0;
int currLine = -1;
bodyPrint:
for (InstructionHandle ih = body.getStart(); ih != null; ih = ih.getNext()) {
if (Range.isRangeHandle(ih)) {
Range r = Range.getRange(ih);
// don't print empty ranges, that is, ranges who contain no actual instructions
for (InstructionHandle xx = r.getStart(); Range.isRangeHandle(xx); xx = xx.getNext()) {
if (xx == r.getEnd()) continue bodyPrint;
}
// doesn't handle nested: if (r.getStart().getNext() == r.getEnd()) continue;
if (r.getStart() == ih) {
printRangeString(r, depth++);
} else {
if (r.getEnd() != ih) throw new RuntimeException("bad");
printRangeString(r, --depth);
}
} else {
printInstruction(ih, depth);
int line = getLineNumber(ih, currLine);
if (line != currLine) {
currLine = line;
out.println(" (line " + line + ")");
} else {
out.println();
}
}
}
}
void printRangeString(Range r, int depth) {
printDepth(depth);
out.println(getRangeString(r, labelMap));
}
String getRangeString(Range r, Map labelMap) {
if (r instanceof ExceptionRange) {
ExceptionRange er = (ExceptionRange) r;
return er.toString() + " -> " + labelMap.get(er.getHandler());
//
// + " PRI " + er.getPriority();
} else {
return r.toString();
}
}
void printDepth(int depth) {
pad(BODY_INDENT);
while (depth > 0) {
out.print("| ");
depth--;
}
}
void printLabel(String s, int depth) {
int space = Math.max(CODE_INDENT - depth * 2, 0);
if (s == null) {
pad(space);
} else {
space = Math.max(space - (s.length() + 2), 0);
pad(space);
out.print(s);
out.print(": ");
}
}
void printInstruction(InstructionHandle h, int depth) {
printDepth(depth);
printLabel((String) labelMap.get(h), depth);
Instruction inst = h.getInstruction();
if (inst instanceof CPInstruction) {
CPInstruction cpinst = (CPInstruction) inst;
out.print(Constants.OPCODE_NAMES[cpinst.getOpcode()].toUpperCase());
out.print(" ");
out.print(pool.constantToString(pool.getConstant(cpinst.getIndex())));
} else if (inst instanceof Select) {
Select sinst = (Select) inst;
out.println(Constants.OPCODE_NAMES[sinst.getOpcode()].toUpperCase());
int[] matches = sinst.getMatchs();
InstructionHandle[] targets = sinst.getTargets();
InstructionHandle defaultTarget = sinst.getTarget();
for (int i = 0, len = matches.length; i < len; i++) {
printDepth(depth);
printLabel(null, depth);
out.print(" ");
out.print(matches[i]);
out.print(": \t");
out.println(labelMap.get(targets[i]));
}
printDepth(depth);
printLabel(null, depth);
out.print(" ");
out.print("default: \t");
out.print(labelMap.get(defaultTarget));
} else if (inst instanceof BranchInstruction) {
BranchInstruction brinst = (BranchInstruction) inst;
out.print(Constants.OPCODE_NAMES[brinst.getOpcode()].toUpperCase());
out.print(" ");
out.print(labelMap.get(brinst.getTarget()));
} else if (inst instanceof LocalVariableInstruction) {
LocalVariableInstruction lvinst = (LocalVariableInstruction) inst;
out.print(inst.toString(false).toUpperCase());
int index = lvinst.getIndex();
LocalVariableTag tag = getLocalVariableTag(h, index);
if (tag != null) {
out.print(" // ");
out.print(tag.getType());
out.print(" ");
out.print(tag.getName());
}
} else {
out.print(inst.toString(false).toUpperCase());
}
}
static final int BODY_INDENT = 4;
static final int CODE_INDENT = 16;
void pad(int size) {
for (int i = 0; i < size; i++) {
out.print(" ");
}
}
}
static LocalVariableTag getLocalVariableTag(
InstructionHandle ih,
int index)
{
InstructionTargeter[] targeters = ih.getTargeters();
if (targeters == null) return null;
for (int i = targeters.length - 1; i >= 0; i--) {
InstructionTargeter t = targeters[i];
if (t instanceof LocalVariableTag) {
LocalVariableTag lvt = (LocalVariableTag) t;
if (lvt.getSlot() == index) return lvt;
}
}
return null;
}
static int getLineNumber(
InstructionHandle ih,
int prevLine)
{
InstructionTargeter[] targeters = ih.getTargeters();
if (targeters == null) return prevLine;
for (int i = targeters.length - 1; i >= 0; i--) {
InstructionTargeter t = targeters[i];
if (t instanceof LineNumberTag) {
return ((LineNumberTag)t).getLineNumber();
}
}
return prevLine;
}
public boolean isStatic() {
return Modifier.isStatic(getAccessFlags());
}
public boolean isAbstract() {
return Modifier.isAbstract(getAccessFlags());
}
public boolean isBridgeMethod() {
return (getAccessFlags() & Constants.ACC_BRIDGE) != 0;
}
public void addExceptionHandler(
InstructionHandle start,
InstructionHandle end,
InstructionHandle handlerStart,
ObjectType catchType,
boolean highPriority) {
InstructionHandle start1 = Range.genStart(body, start);
InstructionHandle end1 = Range.genEnd(body, end);
ExceptionRange er =
new ExceptionRange(body, (catchType==null?null:BcelWorld.fromBcel(catchType)), highPriority);
er.associateWithTargets(start1, end1, handlerStart);
}
public int getAccessFlags() {
return accessFlags;
}
public int getAccessFlagsWithoutSynchronized() {
if (isSynchronized()) return accessFlags - Modifier.SYNCHRONIZED;
return accessFlags;
}
public boolean isSynchronized() {
return (accessFlags & Modifier.SYNCHRONIZED)!=0;
}
public void setAccessFlags(int newFlags) {
this.accessFlags = newFlags;
}
public Type[] getArgumentTypes() {
initialize();
return argumentTypes;
}
public LazyClassGen getEnclosingClass() {
return enclosingClass;
}
public int getMaxLocals() {
return maxLocals;
}
public String getName() {
return name;
}
public Type getReturnType() {
initialize();
return returnType;
}
public void setMaxLocals(int maxLocals) {
this.maxLocals = maxLocals;
}
public InstructionList getBody() {
markAsChanged();
return body;
}
public boolean hasBody() {
if (savedMethod != null) return savedMethod.getCode() != null;
return body != null;
}
public Attribute[] getAttributes() {
return attributes;
}
public String[] getDeclaredExceptions() {
return declaredExceptions;
}
public String getClassName() {
return enclosingClass.getName();
}
// ---- packing!
public MethodGen pack() {
//killNops();
int flags = getAccessFlags();
if (enclosingClass.getWorld().isJoinpointSynchronizationEnabled()) {
flags = getAccessFlagsWithoutSynchronized();
}
MethodGen gen =
new MethodGen(
flags,
getReturnType(),
getArgumentTypes(),
null, //getArgumentNames(),
getName(),
getEnclosingClass().getName(),
new InstructionList(),
getEnclosingClass().getConstantPoolGen());
for (int i = 0, len = declaredExceptions.length; i < len; i++) {
gen.addException(declaredExceptions[i]);
}
for (int i = 0, len = attributes.length; i < len; i++) {
gen.addAttribute(attributes[i]);
}
if (newAnnotations!=null) {
for (Iterator iter = newAnnotations.iterator(); iter.hasNext();) {
AnnotationX element = (AnnotationX) iter.next();
gen.addAnnotation(new AnnotationGen(element.getBcelAnnotation(),gen.getConstantPool(),true));
}
}
if (memberView!=null && memberView.getAnnotations()!=null && memberView.getAnnotations().length!=0) {
AnnotationX[] ans = memberView.getAnnotations();
for (int i = 0, len = ans.length; i < len; i++) {
Annotation a= ans[i].getBcelAnnotation();
gen.addAnnotation(new AnnotationGen(a,gen.getConstantPool(),true));
}
}
if (isSynthetic) {
ConstantPoolGen cpg = gen.getConstantPool();
int index = cpg.addUtf8("Synthetic");
gen.addAttribute(new Synthetic(index, 0, new byte[0], cpg.getConstantPool()));
}
if (hasBody()) {
packBody(gen);
gen.setMaxLocals();
gen.setMaxStack();
} else {
gen.setInstructionList(null);
}
return gen;
}
public void makeSynthetic() {
isSynthetic = true;
}
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 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 exceptionList = new LinkedList();
// map from localvariabletag to instruction handle
Map localVariables = new HashMap();
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 BranchInstruction) {
handleBranchInstruction(map, oldInstruction, newInstruction);
}
// now deal with line numbers
// and store up info for local variables
InstructionTargeter[] targeters = oldInstructionHandle.getTargeters();
if (targeters != null) {
for (int k = targeters.length - 1; k >= 0; k--) {
InstructionTargeter targeter = targeters[k];
if (targeter instanceof LineNumberTag) {
int line = ((LineNumberTag)targeter).getLineNumber();
if (line != currLine) {
gen.addLineNumber(newInstructionHandle, line + lineNumberOffset);
currLine = line;
}
} else if (targeter instanceof LocalVariableTag) {
LocalVariableTag lvt = (LocalVariableTag) targeter;
LVPosition p = (LVPosition)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);
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 addLocalVariables(MethodGen gen, Map 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.
Map duplicatedLocalMap = new HashMap();
for (Iterator iter = localVariables.keySet().iterator(); iter.hasNext(); ) {
LocalVariableTag tag = (LocalVariableTag) iter.next();
// have we already added one with the same slot number and start location?
// if so, just continue.
LVPosition lvpos = (LVPosition)localVariables.get(tag);
InstructionHandle start = lvpos.start;
Set slots = (Set) duplicatedLocalMap.get(start);
if (slots == null) {
slots = new HashSet();
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(new Integer(tag.getSlot()));
Type t = tag.getRealType();
if (t==null) {
t = BcelWorld.makeBcelType(UnresolvedType.forSignature(tag.getType()));
}
gen.addLocalVariable(
tag.getName(),
t,
tag.getSlot(),(InstructionHandle) start,(InstructionHandle) lvpos.end);
}
}
private void addExceptionHandlers(MethodGen gen, Map map, LinkedList exnList) {
// now add exception handlers
for (Iterator iter = exnList.iterator(); iter.hasNext();) {
ExceptionRange r = (ExceptionRange) iter.next();
if (r.isEmpty()) continue;
gen.addExceptionHandler(
remap(r.getRealStart(), map),
remap(r.getRealEnd(), map),
remap(r.getHandler(), map),
(r.getCatchType() == null)
? null
: (ObjectType) BcelWorld.makeBcelType(r.getCatchType()));
}
}
private void handleBranchInstruction(Map map, Instruction oldInstruction, Instruction newInstruction) {
BranchInstruction oldBranchInstruction = (BranchInstruction) oldInstruction;
BranchInstruction newBranchInstruction = (BranchInstruction) newInstruction;
InstructionHandle oldTarget = oldBranchInstruction.getTarget(); // old target
// try {
// New target is in hash map
newBranchInstruction.setTarget(remap(oldTarget, map));
// } catch (NullPointerException e) {
// print();
// System.out.println("Was trying to remap " + bi);
// System.out.println("who's target was supposedly " + itarget);
// throw e;
// }
if (oldBranchInstruction instanceof Select) {
// Either LOOKUPSWITCH or TABLESWITCH
InstructionHandle[] oldTargets = ((Select) oldBranchInstruction).getTargets();
InstructionHandle[] newTargets = ((Select) 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 void handleRangeInstruction(InstructionHandle ih, LinkedList 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 copyAllInstructionsExceptRangeInstructionsInto(InstructionList intoList) {
HashMap map = new HashMap();
for (InstructionHandle ih = getBody().getStart(); ih != null; ih = ih.getNext()) {
if (Range.isRangeHandle(ih)) {
continue;
}
Instruction i = ih.getInstruction();
Instruction c = Utility.copyInstruction(i);
if (c instanceof BranchInstruction)
map.put(ih, intoList.append((BranchInstruction) c));
else
map.put(ih, intoList.append(c));
}
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 remap(InstructionHandle ih, Map map) {
while (true) {
Object ret = map.get(ih);
if (ret == null) {
ih = ih.getNext();
} else {
return (InstructionHandle) ret;
}
}
}
// Update to all these comments, ASC 11-01-2005
// The right thing to do may be to do more with priorities as
// we create new exception handlers, but that is a relatively
// complex task. In the meantime, just taking account of the
// priority here enables a couple of bugs to be fixed to do
// with using return or break in code that contains a finally
// block (pr78021,pr79554).
// exception ordering.
// What we should be doing is dealing with priority inversions way earlier than we are
// and counting on the tree structure. In which case, the below code is in fact right.
// XXX THIS COMMENT BELOW IS CURRENTLY WRONG.
// An exception A preceeds an exception B in the exception table iff:
// * A and B were in the original method, and A preceeded B in the original exception table
// * If A has a higher priority than B, than it preceeds B.
// * If A and B have the same priority, then the one whose START happens EARLIEST has LEAST priority.
// in short, the outermost exception has least priority.
// we implement this with a LinkedList. We could possibly implement this with a java.util.SortedSet,
// but I don't trust the only implementation, TreeSet, to do the right thing.
/* private */ static void insertHandler(ExceptionRange fresh, LinkedList l) {
// Old implementation, simply: l.add(0,fresh);
for (ListIterator iter = l.listIterator(); iter.hasNext();) {
ExceptionRange r = (ExceptionRange) iter.next();
// int freal = fresh.getRealStart().getPosition();
// int rreal = r.getRealStart().getPosition();
if (fresh.getPriority() >= r.getPriority()) {
iter.previous();
iter.add(fresh);
return;
}
}
// we have reached the end
l.add(fresh);
}
public boolean isPrivate() {
return Modifier.isPrivate(getAccessFlags());
}
public boolean isProtected() {
return Modifier.isProtected(getAccessFlags());
}
public boolean isDefault() {
return !(isProtected() || isPrivate() || isPublic());
}
public boolean isPublic() {
return Modifier.isPublic(getAccessFlags());
}
// ----
/** A good body is a body with the following properties:
*
* <ul>
* <li> For each branch instruction S in body, target T of S is in body.
* <li> For each branch instruction S in body, target T of S has S as a targeter.
* <li> For each instruction T in body, for each branch instruction S that is a
* targeter of T, S is in body.
* <li> For each non-range-handle instruction T in body, for each instruction S
* that is a targeter of T, S is
* either a branch instruction, an exception range or a tag
* <li> For each range-handle instruction T in body, there is exactly one targeter S
* that is a range.
* <li> For each range-handle instruction T in body, the range R targeting T is in body.
* <li> For each instruction T in body, for each exception range R targeting T, R is
* in body.
* <li> For each exception range R in body, let T := R.handler. T is in body, and R is one
* of T's targeters
* <li> All ranges are properly nested: For all ranges Q and R, if Q.start preceeds
* R.start, then R.end preceeds Q.end.
* </ul>
*
* Where the shorthand "R is in body" means "R.start is in body, R.end is in body, and
* any InstructionHandle stored in a field of R (such as an exception handle) is in body".
*/
public void assertGoodBody() {
if (true) return; // only enable for debugging, consider using cheaper toString()
assertGoodBody(getBody(), toString()); //definingType.getNameAsIdentifier() + "." + getName()); //toString());
}
public static void assertGoodBody(InstructionList il, String from) {
if (true) return; // only to be enabled for debugging
if (il == null) return;
Set body = new HashSet();
Stack ranges = new Stack();
for (InstructionHandle ih = il.getStart(); ih != null; ih = ih.getNext()) {
body.add(ih);
if (ih.getInstruction() instanceof BranchInstruction) {
body.add(ih.getInstruction());
}
}
for (InstructionHandle ih = il.getStart(); ih != null; ih = ih.getNext()) {
assertGoodHandle(ih, body, ranges, from);
InstructionTargeter[] ts = ih.getTargeters();
if (ts != null) {
for (int i = ts.length - 1; i >= 0; i--) {
assertGoodTargeter(ts[i], ih, body, from);
}
}
}
}
private static void assertGoodHandle(InstructionHandle ih, Set body, Stack ranges, String from) {
Instruction inst = ih.getInstruction();
if ((inst instanceof BranchInstruction) ^ (ih instanceof BranchHandle)) {
throw new BCException("bad instruction/handle pair in " + from);
}
if (Range.isRangeHandle(ih)) {
assertGoodRangeHandle(ih, body, ranges, from);
} else if (inst instanceof BranchInstruction) {
assertGoodBranchInstruction((BranchHandle) ih, (BranchInstruction) inst, body, ranges, from);
}
}
private static void assertGoodBranchInstruction(
BranchHandle ih,
BranchInstruction inst,
Set body,
Stack ranges,
String from)
{
if (ih.getTarget() != inst.getTarget()) {
throw new BCException("bad branch instruction/handle pair in " + from);
}
InstructionHandle target = ih.getTarget();
assertInBody(target, body, from);
assertTargetedBy(target, inst, from);
if (inst instanceof Select) {
Select sel = (Select) inst;
InstructionHandle[] itargets = sel.getTargets();
for (int k = itargets.length - 1; k >= 0; k--) {
assertInBody(itargets[k], body, from);
assertTargetedBy(itargets[k], inst, from);
}
}
}
/** ih is an InstructionHandle or a BranchInstruction */
private static void assertInBody(Object ih, Set body, String from) {
if (! body.contains(ih)) throw new BCException("thing not in body in " + from);
}
private static void assertGoodRangeHandle(InstructionHandle ih, Set body, Stack ranges, String from) {
Range r = getRangeAndAssertExactlyOne(ih, from);
assertGoodRange(r, body, from);
if (r.getStart() == ih) {
ranges.push(r);
} else if (r.getEnd() == ih) {
if (ranges.peek() != r) throw new BCException("bad range inclusion in " + from);
ranges.pop();
}
}
private static void assertGoodRange(Range r, Set body, String from) {
assertInBody(r.getStart(), body, from);
assertRangeHandle(r.getStart(), from);
assertTargetedBy(r.getStart(), r, from);
assertInBody(r.getEnd(), body, from);
assertRangeHandle(r.getEnd(), from);
assertTargetedBy(r.getEnd(), r, from);
if (r instanceof ExceptionRange) {
ExceptionRange er = (ExceptionRange) r;
assertInBody(er.getHandler(), body, from);
assertTargetedBy(er.getHandler(), r, from);
}
}
private static void assertRangeHandle(InstructionHandle ih, String from) {
if (! Range.isRangeHandle(ih)) throw new BCException("bad range handle " + ih + " in " + from);
}
private static void assertTargetedBy(
InstructionHandle target,
InstructionTargeter targeter,
String from)
{
InstructionTargeter[] ts = target.getTargeters();
if (ts == null) throw new BCException("bad targeting relationship in " + from);
for (int i = ts.length - 1; i >= 0; i--) {
if (ts[i] == targeter) return;
}
throw new RuntimeException("bad targeting relationship in " + from);
}
private static void assertTargets(InstructionTargeter targeter, InstructionHandle target, String from) {
if (targeter instanceof Range) {
Range r = (Range) targeter;
if (r.getStart() == target || r.getEnd() == target) return;
if (r instanceof ExceptionRange) {
if (((ExceptionRange)r).getHandler() == target) return;
}
} else if (targeter instanceof BranchInstruction) {
BranchInstruction bi = (BranchInstruction) targeter;
if (bi.getTarget() == target) return;
if (targeter instanceof Select) {
Select sel = (Select) targeter;
InstructionHandle[] itargets = sel.getTargets();
for (int k = itargets.length - 1; k >= 0; k--) {
if (itargets[k] == target) return;
}
}
} else if (targeter instanceof Tag) {
return;
}
throw new BCException(targeter + " doesn't target " + target + " in " + from );
}
private static Range getRangeAndAssertExactlyOne(InstructionHandle ih, String from) {
Range ret = null;
InstructionTargeter[] ts = ih.getTargeters();
if (ts == null) throw new BCException("range handle with no range in " + from);
for (int i = ts.length - 1; i >= 0; i--) {
if (ts[i] instanceof Range) {
if (ret != null) throw new BCException("range handle with multiple ranges in " + from);
ret = (Range) ts[i];
}
}
if (ret == null) throw new BCException("range handle with no range in " + from);
return ret;
}
private static void assertGoodTargeter(
InstructionTargeter t,
InstructionHandle ih,
Set body,
String from)
{
assertTargets(t, ih, from);
if (t instanceof Range) {
assertGoodRange((Range) t, body, from);
} else if (t instanceof BranchInstruction) {
assertInBody(t, body, from);
}
}
// ----
boolean isAdviceMethod() {
return memberView.getAssociatedShadowMunger() != null;
}
boolean isAjSynthetic() {
if (memberView == null) return true;
return memberView.isAjSynthetic();
}
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();
accessFlags = Utility.makePublic(accessFlags);
}
public boolean getCanInline() {
return canInline;
}
public void setCanInline(boolean canInline) {
this.canInline = canInline;
}
/**
* Adds an attribute to the method
* @param attr
*/
public void addAttribute(Attribute attr) {
Attribute[] newAttributes = new Attribute[attributes.length + 1];
System.arraycopy(attributes, 0, newAttributes, 0, attributes.length);
newAttributes[attributes.length] = attr;
attributes = newAttributes;
}
}
|
148,786 |
Bug 148786 new array construction join point can fail for freaky array constructors
|
Took me a while to discover how to recreate this problem, but this class: public class A { public static void main(String []argv) { byte[][] bytes = new byte[][]{{0},{1}}; } } causes this bytecode: 0: iconst_2 1: anewarray #18; //class "[B" and this causes the newarray joinpoint code to go bang. (eg. before(): call(*[].new(..)) {}) java.lang.NullPointerException at org.aspectj.weaver.bcel.BcelWorld.fromBcel(BcelWorld.java:236) at org.aspectj.weaver.bcel.BcelWorld.makeJoinPointSignatureForArrayConstruction(BcelWorld.java:483) at org.aspectj.weaver.bcel.BcelShadow.makeArrayConstructorCall(BcelShadow.java:801) at org.aspectj.weaver.bcel.BcelClassWeaver.match(BcelClassWeaver.java:2510) at org.aspectj.weaver.bcel.BcelClassWeaver.match(BcelClassWeaver.java:2325) at org.aspectj.weaver.bcel.BcelClassWeaver.weave(BcelClassWeaver.java:490) at org.aspectj.weaver.bcel.BcelClassWeaver.weave(BcelClassWeaver.java:115) at org.aspectj.weaver.bcel.BcelWeaver.weave(BcelWeaver.java:1574) at org.aspectj.weaver.bcel.BcelWeaver.weaveWithoutDump(BcelWeaver.java:1525) at org.aspectj.weaver.bcel.BcelWeaver.weaveAndNotify(BcelWeaver.java:1305) at org.aspectj.weaver.bcel.BcelWeaver.weave(BcelWeaver.java:1127)
|
resolved fixed
|
792d1df
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-06-27T11:34:41Z | 2006-06-27T09:20:00Z |
tests/bugs152/pr148786/A.java
| |
148,786 |
Bug 148786 new array construction join point can fail for freaky array constructors
|
Took me a while to discover how to recreate this problem, but this class: public class A { public static void main(String []argv) { byte[][] bytes = new byte[][]{{0},{1}}; } } causes this bytecode: 0: iconst_2 1: anewarray #18; //class "[B" and this causes the newarray joinpoint code to go bang. (eg. before(): call(*[].new(..)) {}) java.lang.NullPointerException at org.aspectj.weaver.bcel.BcelWorld.fromBcel(BcelWorld.java:236) at org.aspectj.weaver.bcel.BcelWorld.makeJoinPointSignatureForArrayConstruction(BcelWorld.java:483) at org.aspectj.weaver.bcel.BcelShadow.makeArrayConstructorCall(BcelShadow.java:801) at org.aspectj.weaver.bcel.BcelClassWeaver.match(BcelClassWeaver.java:2510) at org.aspectj.weaver.bcel.BcelClassWeaver.match(BcelClassWeaver.java:2325) at org.aspectj.weaver.bcel.BcelClassWeaver.weave(BcelClassWeaver.java:490) at org.aspectj.weaver.bcel.BcelClassWeaver.weave(BcelClassWeaver.java:115) at org.aspectj.weaver.bcel.BcelWeaver.weave(BcelWeaver.java:1574) at org.aspectj.weaver.bcel.BcelWeaver.weaveWithoutDump(BcelWeaver.java:1525) at org.aspectj.weaver.bcel.BcelWeaver.weaveAndNotify(BcelWeaver.java:1305) at org.aspectj.weaver.bcel.BcelWeaver.weave(BcelWeaver.java:1127)
|
resolved fixed
|
792d1df
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-06-27T11:34:41Z | 2006-06-27T09:20:00Z |
tests/src/org/aspectj/systemtest/ajc152/Ajc152Tests.java
|
/*******************************************************************************
* Copyright (c) 2006 IBM
* 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.ajc152;
import java.io.File;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import junit.framework.Test;
import org.aspectj.ajdt.internal.core.builder.AsmHierarchyBuilder;
import org.aspectj.asm.AsmManager;
import org.aspectj.asm.IHierarchy;
import org.aspectj.asm.IProgramElement;
import org.aspectj.asm.IRelationshipMap;
import org.aspectj.asm.internal.Relationship;
import org.aspectj.testing.XMLBasedAjcTestCase;
import org.aspectj.util.CharOperation;
import org.aspectj.weaver.World;
public class Ajc152Tests extends org.aspectj.testing.XMLBasedAjcTestCase {
// public void testverifyErrNoTypeCflowField_pr145693() {runTest("verifyErrNoTypeCflowField");}
// public void testBrokenIfArgsCflowAtAj_pr145018() { runTest("ataj crashing with cflow, if and args");}
// public void testItdCallingGenericMethod_pr145391() { runTest("itd calling generic method");}
// public void testItdCallingGenericMethod_pr145391_2() { runTest("itd calling generic method - 2");}
// public void testAdviceNotWovenAspectPath_pr147841() { runTest("advice not woven on aspectpath");}
// public void testClassCastForInvalidAnnotationValue_pr148537() { runTest("classcast annotation value");}
public void testPrivilegeGeneric_pr148545() { runTest("nosuchmethoderror for privileged aspect");}
public void testPrivilegeGeneric_pr148545_2() { runTest("nosuchmethoderror for privileged aspect - 2");}
public void testUnknownAnnotationNPE() { runTest("NPE for unknown annotation");}
public void testDuplicateBridgeMethods_pr147801_1() { runTest("duplicate bridge methods");}
public void testPackageIgnoredForException_pr147701_1() { runTest("package for exception ignored");}
public void testPackageIgnoredForException_pr147701_2() { runTest("package for exception ignored - 2");}
public void testPackageIgnoredForException_pr147701_3() { runTest("package for exception ignored - 3");}
public void testBrokenAddSerialVersionUID_pr145950() {runTest("fails to discover Serializable");}
public void testNoUnnecessaryDeclarationOfThrownExcp_pr129282_1() {runTest("no unnecessary declaration of thrown exception warning - 1");}
public void testNoUnnecessaryDeclarationOfThrownExcp_pr129282_2() {runTest("no unnecessary declaration of thrown exception warning - 2");}
public void testNoUnnecessaryDeclarationOfThrownExcp_pr129282_3() {runTest("no unnecessary declaration of thrown exception warning - 3");}
public void testNoUnnecessaryDeclarationOfThrownExcp_pr129282_4() {runTest("no unnecessary declaration of thrown exception warning - 4");}
public void testNoUnnecessaryDeclarationOfThrownExcp_pr129282_5() {runTest("no unnecessary declaration of thrown exception warning - 5");}
public void testNoUnnecessaryDeclarationOfThrownExcp_pr129282_6() {runTest("no unnecessary declaration of thrown exception warning - 6");}
public void testNoUnnecessaryDeclarationOfThrownExcp_pr129282_7() {runTest("no unnecessary declaration of thrown exception warning - 7");}
public void testNoUnnecessaryDeclarationOfThrownExcp_pr129282_8() {runTest("no unnecessary declaration of thrown exception warning - 8");}
public void testNoUnnecessaryDeclarationOfThrownExcp_pr129282_9() {runTest("no unnecessary declaration of thrown exception warning - 9");}
public void testNoUnnecessaryDeclarationOfThrownExcp_pr129282_10() {runTest("no unnecessary declaration of thrown exception warning - 10");}
public void testAtAJVerificationError_pr144602() { runTest("atAJ perthis aspect verification error");}
public void testLTWAndGeneratingSUID_pr144465() { runTest("ltw with serialversionUID creation"); }
public void testAspects14PerSingleton_pr122253() { runTest("aspects14 - persingleton");}
public void testAspects14PerCflow_pr122253() { runTest("aspects14 - percflow");}
public void testAspects14PerThis_pr122253() { runTest("aspects14 - perthis");}
public void testAspects14PerTypeWithin_pr122253() { runTest("aspects14 - pertypewithin");}
public void testFunkyGenericErrorWithITDs_pr126355() { runTest("bizarre generic error with itds");}
public void testConcretizingAbstractMethods_pr142466() { runTest("aop.xml aspect inheriting but not concretizing abstract method");}
public void testConcretizingAbstractMethods_pr142466_2() { runTest("aop.xml aspect inheriting but not concretizing abstract method - 2");}
public void testComplexGenericDecl_pr137568() { runTest("complicated generics declaration");}
public void testItdOnInnerTypeOfGenericType_pr132349() { runTest("ITD on inner type of generic type");}
public void testItdOnInnerTypeOfGenericType_pr132349_2() { runTest("ITD on inner type of generic type - 2");}
public void testItdOnInnerTypeOfGenericType_pr132349_3() { runTest("ITD on inner type of generic type - 3");}
// public void testCovarianceAndDecp_pr128443_1() { runTest("covariance and decp - 1"); }
public void testLTWGeneratedAspectAbstractMethod_pr125480() { runTest("aop.xml aspect inheriting abstract method ");}
public void testLTWGeneratedAspectAbstractMethod_pr125480_2() { runTest("aop.xml aspect inheriting abstract method - code style");}
//public void testSuperITDExplosion_pr134425() { runTest("super ITDs");}
//public void testMisbehavingDeclareAnnotation_pr135865() { runTest("misbehaving declare annotation");}
//public void testMisbehavingDeclareAnnotation_pr135865_2() { runTest("misbehaving declare annotation - 2");}
public void testCompletelyBrokenAopConcretization_pr142165_1() { runTest("broken concretization");}
public void testCompletelyBrokenAopConcretization_pr142165_2() { runTest("broken concretization - 2");}
public void testCompletelyBrokenAopConcretization_pr142165_3() { runTest("broken concretization - 3");}
public void testVerifyErrorLTW_pr135068() { runTest("ltw verifyerror");}
public void testVerifyErrorLTW_pr135068_2() { runTest("ltw verifyerror - 2");}
public void testVerifyErrorLTW_pr135068_3() { runTest("ltw verifyerror - 3");}
public void testVerifyErrorLTW_pr135068_4() { runTest("ltw verifyerror - 4");}
public void testVerifyErrorForComplexCflow_pr136026() { runTest("verifyerror");}
public void testVerifyErrorForComplexCflow_pr136026_2() { runTest("verifyerror - 2");}
public void testAnnotationsAndGenericsBCException_pr129704() { runTest("annotations and generics leading to BCException");}
public void testMethodTooBigAfterWeaving_pr138384() { runTest("method too big"); }
public void testNotAtWithincode_pr138158_1() { runTest("not at withincode - 1");}
public void testNotAtWithincode_pr138158_2() { runTest("not at withincode - 2");}
public void testNotAtWithincode_pr138158_3() { runTest("not at within - 3");}
public void testNpeOnDup_pr138143() { runTest("npe on duplicate method with ataj");}
public void testPointcutsAndGenerics_pr137496_1() { runTest("pointcuts and generics - B");}
public void testPointcutsAndGenerics_pr137496_2() { runTest("pointcuts and generics - D");}
public void testPointcutsAndGenerics_pr137496_3() { runTest("pointcuts and generics - E");}
public void testPointcutsAndGenerics_pr137496_4() { runTest("pointcuts and generics - F");}
public void testPointcutsAndGenerics_pr137496_5() { runTest("pointcuts and generics - G");}
public void testPointcutsAndGenerics_pr137496_6() { runTest("pointcuts and generics - H");}
public void testAspectLibrariesAndASM_pr135001() { runTest("aspect libraries and asm");}
public void testStackOverflow_pr136258() { runTest("stack overflow");}
public void testIncorrectOverridesEvaluation13() { runTest("incorrect overrides evaluation - 1.3"); }
public void testIncorrectOverridesEvaluation15() { runTest("incorrect overrides evaluation - 1.5"); }
public void testAtWithinCodeBug_pr138798() { runTest("atWithinCodeBug"); }
public void testReferencePCutInDeclareWarning_pr138215() { runTest("Reference pointcut fails inside @DeclareWarning");}
public void testReferencePCutInPerClause_pr138219() { runTest("Can't use a FQ Reference pointcut in any pointcut expression referenced by a per-clause");}
public void testReferencePCutInPerClause_pr130722() { runTest("FQ Reference pointcut from perclause ref pc"); }
public void testDoubleAnnotationMatching_pr138223() { runTest("Double at annotation matching (no binding)");}
public void testSuperCallsInAtAspectJAdvice_pr139749() { runTest("Super calls in @AspectJ advice");}
public void testNoClassCastExceptionWithPerThis_pr138286() { runTest("No ClassCastException with perThis");}
public void testGenericAspectHierarchyWithBounds_pr147845() { runTest("Generic abstract aspect hierarchy with bounds"); }
public void testJRockitBooleanReturn_pr148007() { runTest("jrockit boolean fun");}
public void testJRockitBooleanReturn2_pr148007() { runTest("jrockit boolean fun (no aspects)");}
public void testSyntheticAjcMembers_pr147711() { runTest("synthetic ajc$ members"); }
public void testDeclareAtMethodRelationship_pr143924() {
//AsmManager.setReporting("c:/debug.txt",true,true,true,true);
runTest("declare @method relationship");
IHierarchy top = AsmManager.getDefault().getHierarchy();
// get the IProgramElements corresponding to the different code entries
IProgramElement decam = top.findElementForLabel(top.getRoot(),
IProgramElement.Kind.DECLARE_ANNOTATION_AT_METHOD,
"declare @method: * debit(..) : @Secured(role = \"supervisor\")");
assertNotNull("Couldn't find 'declare @method' element in the tree",decam);
IProgramElement method = top.findElementForLabel(top.getRoot(),
IProgramElement.Kind.METHOD,"debit(java.lang.String,long)");
assertNotNull("Couldn't find the 'debit(String,long)' method element in the tree",method);
List matches = AsmManager.getDefault().getRelationshipMap().get(decam);
assertNotNull("'declare @method' should have some relationships but does not",matches);
assertTrue("'declare @method' should have one relationships but has " + matches.size(),matches.size()==1);
List matchesTargets = ((Relationship)matches.get(0)).getTargets();
assertTrue("'declare @method' should have one targets but has" + matchesTargets.size(),matchesTargets.size()==1);
IProgramElement target = AsmManager.getDefault().getHierarchy().findElementForHandle((String)matchesTargets.get(0));
assertEquals("target of relationship should be the 'debit(java.lang.String,long)' method but is IPE with label "
+ target.toLabelString(),method,target);
// check that the debit method has an annotated by relationship with the declare @method
matches = AsmManager.getDefault().getRelationshipMap().get(method);
assertNotNull("'debit(java.lang.String,long)' should have some relationships but does not",matches);
assertTrue("'debit(java.lang.String,long)' should have one relationships but has " + matches.size(),matches.size()==1);
matchesTargets = ((Relationship)matches.get(0)).getTargets();
assertTrue("'debit(java.lang.String,long)' should have one targets but has" + matchesTargets.size(),matchesTargets.size()==1);
target = AsmManager.getDefault().getHierarchy().findElementForHandle((String)matchesTargets.get(0));
assertEquals("target of relationship should be the 'declare @method' ipe but is IPE with label "
+ target.toLabelString(),decam,target);
}
// this next one reported as a bug by Rob Harrop, but I can't reproduce the failure yet...
//public void testAtAspectWithReferencePCPerClause_pr138220() { runTest("@Aspect with reference pointcut in perclause");}
public void testJarChecking_pr137235_1() { runTest("directory with .jar extension: source and outjar"); }
public void testJarChecking_pr137235_2() { runTest("directory with .jar extension"); }
public void testMakePreMethodNPE_pr136393() { runTest("NPE in makePreMethod");}
public void testGetParameterHandles_pr141730() {
runTest("new IProgramElement handle methods");
checkParametersForIPE("intMethod(int)",IProgramElement.Kind.METHOD,"I",true);
checkParametersForIPE("stringMethod(java.lang.String)",IProgramElement.Kind.METHOD,"Ljava/lang/String;",true);
checkParametersForIPE("myClassMethod(MyClass)",IProgramElement.Kind.METHOD,"LMyClass;",true);
checkParametersForIPE("genericMethod(java.util.List<java.lang.String>)",IProgramElement.Kind.METHOD,"Pjava/util/List<Ljava/lang/String;>;",true);
checkParametersForIPE("genericMethod2(MyGenericClass<java.lang.String,MyClass>)",IProgramElement.Kind.METHOD,"PMyGenericClass<Ljava/lang/String;LMyClass;>;",true);
checkParametersForIPE("main(java.lang.String[])",IProgramElement.Kind.METHOD,"[Ljava/lang/String;",true);
checkParametersForIPE("multiMethod(java.lang.String[][])",IProgramElement.Kind.METHOD,"[[Ljava/lang/String;",true);
checkParametersForIPE("intArray(int[])",IProgramElement.Kind.METHOD,"[I",true);
IHierarchy top = AsmManager.getDefault().getHierarchy();
IProgramElement twoArgsMethod = top.findElementForLabel(
top.getRoot(),IProgramElement.Kind.METHOD,"twoArgsMethod(int,java.lang.String)");
assertNotNull("Couldn't find 'twoArgsMethod(int,java.lang.String)' element in the tree",twoArgsMethod);
List l = twoArgsMethod.getParameterSignatures();
assertEquals("",((char[])l.get(0))[0],'I');
boolean eq = CharOperation.equals(((char[])l.get(1)),"Ljava/lang/String;".toCharArray());
assertTrue("expected parameter to be 'Ljava/lang/String;' but found '" +
new String(((char[])l.get(1))) + "'",eq);
}
public void testGetParameterTypes_pr141730() {
runTest("new IProgramElement handle methods");
checkParametersForIPE("intMethod(int)",IProgramElement.Kind.METHOD,"int",false);
checkParametersForIPE("stringMethod(java.lang.String)",IProgramElement.Kind.METHOD,"java.lang.String",false);
checkParametersForIPE("myClassMethod(MyClass)",IProgramElement.Kind.METHOD,"MyClass",false);
checkParametersForIPE("genericMethod(java.util.List<java.lang.String>)",IProgramElement.Kind.METHOD,"java.util.List<java.lang.String>",false);
checkParametersForIPE("genericMethod2(MyGenericClass<java.lang.String,MyClass>)",IProgramElement.Kind.METHOD,"MyGenericClass<java.lang.String,MyClass>",false);
checkParametersForIPE("main(java.lang.String[])",IProgramElement.Kind.METHOD,"java.lang.String[]",false);
checkParametersForIPE("multiMethod(java.lang.String[][])",IProgramElement.Kind.METHOD,"java.lang.String[][]",false);
checkParametersForIPE("intArray(int[])",IProgramElement.Kind.METHOD,"int[]",false);
}
public void testToSignatureString_pr141730() {
runTest("new IProgramElement handle methods");
checkSignatureOfIPE("main(java.lang.String[])",IProgramElement.Kind.METHOD);
checkSignatureOfIPE("C",IProgramElement.Kind.CLASS);
checkSignatureOfIPE("C()",IProgramElement.Kind.CONSTRUCTOR);
checkSignatureOfIPE("method()",IProgramElement.Kind.METHOD);
checkSignatureOfIPE("p()",IProgramElement.Kind.POINTCUT);
checkSignatureOfIPE("before(): p..",IProgramElement.Kind.ADVICE,"before()");
checkSignatureOfIPE("MyClass.method()",IProgramElement.Kind.INTER_TYPE_METHOD);
checkSignatureOfIPE("multiMethod(java.lang.String[][])",IProgramElement.Kind.METHOD);
checkSignatureOfIPE("intArray(int[])",IProgramElement.Kind.METHOD);
checkSignatureOfIPE("MyClass.MyClass()",IProgramElement.Kind.INTER_TYPE_CONSTRUCTOR);
}
// if not filling in the model for aspects contained in jar files then
// want to ensure that the relationship map is correct and has nodes
// which can be used in AJDT - ensure no NPE occurs for the end of
// the relationship with aspectpath
public void testAspectPathRelWhenNotFillingInModel_pr141730() {
World.createInjarHierarchy = false;
try {
runTest("ensure aspectpath injar relationships are correct when not filling in model");
// expecting:
// sourceOfRelationship main in MyFoo.java
// relationship advised by
// target MyBar.aj
//
// and
//
// sourceOfRelationship MyBar.aj
// relationship advises
// target main in MyFoo.java
IHierarchy top = AsmManager.getDefault().getHierarchy();
IRelationshipMap asmRelMap = AsmManager.getDefault().getRelationshipMap();
assertEquals("expected two sources of relationships but only found "
+ asmRelMap.getEntries().size(),2,asmRelMap.getEntries().size());
for (Iterator iter = asmRelMap.getEntries().iterator(); iter.hasNext();) {
String sourceOfRelationship = (String) iter.next();
IProgramElement ipe = top.findElementForHandle(sourceOfRelationship);
List relationships = asmRelMap.get(ipe);
if (ipe.getName().equals("MyBar.aj")) {
assertEquals("expected MyBar.aj to have one relationships but found "
+ relationships.size(),1,relationships.size());
Relationship rel = (Relationship)relationships.get(0);
assertEquals("expected relationship to be 'advises' but was "
+ rel.getName(), "advises", rel.getName());
List targets = rel.getTargets();
assertEquals("expected one target but found " + targets.size(),1,targets.size());
IProgramElement link = top.findElementForHandle((String)targets.get(0));
assertEquals("expected target 'method-call(void foo.MyFoo.main())' but target " + link.getName(),
"method-call(void foo.MyFoo.main())",link.getName());
String fileName = link.getSourceLocation().getSourceFile().toString();
assertTrue("expected 'main' to be in class MyFoo.java but found it " +
"in " + fileName,fileName.indexOf("MyFoo.java") != -1);
} else if (ipe.getName().equals("method-call(void foo.MyFoo.main())")) {
String fileName = ipe.getSourceLocation().getSourceFile().toString();
assertTrue("expected 'method-call(void foo.MyFoo.main())' to be in " +
"class MyFoo.java but found it in"
+ fileName,fileName.indexOf("MyFoo.java") != -1);
assertEquals("expected 'method-call(void foo.MyFoo.main())' " +
"to have one relationships but found "
+ relationships.size(),1,relationships.size());
Relationship rel = (Relationship)relationships.get(0);
assertEquals("expected relationship to be 'advised by' but was "
+ rel.getName(), "advised by", rel.getName());
List targets = rel.getTargets();
assertEquals("expected one target but found " + targets.size(),1,targets.size());
IProgramElement link = top.findElementForHandle((String)targets.get(0));
assertEquals("expected target 'MyBar.aj' but target " + link.getName(),
"MyBar.aj",link.getName());
} else {
fail("unexpected element " + ipe.getName() + " in the relationship map");
}
}
} finally {
World.createInjarHierarchy = true;
}
}
// if not filling in the model for classes contained in jar files then
// want to ensure that the relationship map is correct and has nodes
// which can be used in AJDT - ensure no NPE occurs for the end of
// the relationship with inpath
public void testNoNPEWithInpathWhenNotFillingInModel_pr141730() {
World.createInjarHierarchy = false;
try {
runTest("ensure inpath injar relationships are correct when not filling in model");
// the aspect used for this test has advice, declare parents, deow,
// and declare @type, @constructor, @field and @method. We only expect
// there to be relationships in the map for declare parents and declare @type
// (provided the model isn't being filled in) because the logic in the other
// addXXXRelationship methods use AspectJElementHierarchy.findElementForType().
// This method which returns null because there is no such ipe. The relationship is
// therefore not added to the model. Adding declare @type and declare parents
// uses AspectJElementHierarchy.findElementForHandle() which returns the file
// node ipe if it can't find one for the given handle. Therefore the relationships
// are added against the file node. Before change to using ipe's to create handles
// we also had the deow relationship, however, now we don't because this also
// uses findElementForType to find the targetNode which in the inpath case is null.
// just check that the number of entries is what we expect:
// We expect 3 (the declare @type and declare parents statements plus the filenode)
IRelationshipMap relMap = AsmManager.getDefault().getRelationshipMap();
assertEquals("expected 3 entries in the relationship map but found "
+ relMap.getEntries().size(), 3, relMap.getEntries().size());
} finally {
World.createInjarHierarchy = true;
}
}
public void testPCDInClassAppearsInModel_pr148027() {
// only want to test that its there if we're creating the uses pointcut
// relationship. This should be addressed by pr148027
if (!AsmHierarchyBuilder.shouldAddUsesPointcut) return;
World.createInjarHierarchy = false;
try {
runTest("ensure pcd declare in class appears in model");
IHierarchy top = AsmManager.getDefault().getHierarchy();
IProgramElement pcd = top.findElementForLabel(top.getRoot(),IProgramElement.Kind.POINTCUT,"pointcutInClass()");
IRelationshipMap relMap = AsmManager.getDefault().getRelationshipMap();
List relationships = relMap.get(pcd);
assertNotNull("expected relationships for pointcut " + pcd.toLinkLabelString()
+ " but didn't", relationships);
pcd = top.findElementForLabel(top.getRoot(),IProgramElement.Kind.POINTCUT,"pointcutInAspect()");
relationships = relMap.get(pcd);
assertNotNull("expected relationships for pointcut " + pcd.toLinkLabelString()
+ " but didn't", relationships);
} finally {
World.createInjarHierarchy = true;
}
}
// public void testFunkyGenericErrorWithITDs_pr126355_2() {
// runTest("bizarre generic error with itds - 2");
// // public class Pair<F,S> affected by pertarget aspect
// GenericsTests.verifyClassSignature(ajc,"Pair","<F:Ljava/lang/Object;S:Ljava/lang/Object;>Ljava/lang/Object;LIdempotentCache$ajcMightHaveAspect;;");
// }
public void testNoAspects(){
// setSystemProperty(WeavingAdaptor.WEAVING_ADAPTOR_VERBOSE,"true");
runTest("Ensure no weaving without included aspects");
}
public void testWeaveinfoMessages (){
runTest("weaveinfo messages with include and exclude");
}
// tests that can't be included for some reason
// Not valid whilst the ajc compiler forces debug on (ignores -g:none) - it will be green but is invalid, trust me
// public void testLongWindedMessages_pr129408() { runTest("long winded ataj messages");}
// ---------------- helper methods ---------------
private void checkParametersForIPE(String ipeLabel, IProgramElement.Kind kind, String expectedParm, boolean getHandles) {
IHierarchy top = AsmManager.getDefault().getHierarchy();
IProgramElement ipe = top.findElementForLabel(top.getRoot(),kind,ipeLabel);
assertNotNull("Couldn't find '" + ipeLabel + "' element in the tree",ipe);
List l = new ArrayList();
if (getHandles) {
l = ipe.getParameterSignatures();
} else {
l = ipe.getParameterTypes();
}
boolean eq = CharOperation.equals(((char[])l.get(0)),expectedParm.toCharArray());
assertTrue("expected parameter to be '" + expectedParm + "' but found '" +
new String(((char[])l.get(0))) + "'",eq);
}
private void checkSignatureOfIPE(String ipeLabel, IProgramElement.Kind kind) {
checkSignatureOfIPE(ipeLabel,kind,ipeLabel);
}
private void checkSignatureOfIPE(String ipeLabel, IProgramElement.Kind kind, String expectedSig) {
IHierarchy top = AsmManager.getDefault().getHierarchy();
IProgramElement ipe = top.findElementForLabel(
top.getRoot(),kind,ipeLabel);
assertNotNull("Couldn't find '" + ipeLabel + "' element in the tree",ipe);
assertEquals("expected signature to be '"+ expectedSig + "' but was " +
ipe.toSignatureString(true),expectedSig,ipe.toSignatureString(true));
}
/////////////////////////////////////////
public static Test suite() {
return XMLBasedAjcTestCase.loadSuite(Ajc152Tests.class);
}
protected File getSpecFile() {
return new File("../tests/src/org/aspectj/systemtest/ajc152/ajc152.xml");
}
}
|
148,786 |
Bug 148786 new array construction join point can fail for freaky array constructors
|
Took me a while to discover how to recreate this problem, but this class: public class A { public static void main(String []argv) { byte[][] bytes = new byte[][]{{0},{1}}; } } causes this bytecode: 0: iconst_2 1: anewarray #18; //class "[B" and this causes the newarray joinpoint code to go bang. (eg. before(): call(*[].new(..)) {}) java.lang.NullPointerException at org.aspectj.weaver.bcel.BcelWorld.fromBcel(BcelWorld.java:236) at org.aspectj.weaver.bcel.BcelWorld.makeJoinPointSignatureForArrayConstruction(BcelWorld.java:483) at org.aspectj.weaver.bcel.BcelShadow.makeArrayConstructorCall(BcelShadow.java:801) at org.aspectj.weaver.bcel.BcelClassWeaver.match(BcelClassWeaver.java:2510) at org.aspectj.weaver.bcel.BcelClassWeaver.match(BcelClassWeaver.java:2325) at org.aspectj.weaver.bcel.BcelClassWeaver.weave(BcelClassWeaver.java:490) at org.aspectj.weaver.bcel.BcelClassWeaver.weave(BcelClassWeaver.java:115) at org.aspectj.weaver.bcel.BcelWeaver.weave(BcelWeaver.java:1574) at org.aspectj.weaver.bcel.BcelWeaver.weaveWithoutDump(BcelWeaver.java:1525) at org.aspectj.weaver.bcel.BcelWeaver.weaveAndNotify(BcelWeaver.java:1305) at org.aspectj.weaver.bcel.BcelWeaver.weave(BcelWeaver.java:1127)
|
resolved fixed
|
792d1df
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-06-27T11:34:41Z | 2006-06-27T09:20:00Z |
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.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Properties;
import java.util.StringTokenizer;
import org.aspectj.apache.bcel.classfile.Attribute;
import org.aspectj.apache.bcel.classfile.ClassParser;
import org.aspectj.apache.bcel.classfile.JavaClass;
import org.aspectj.apache.bcel.classfile.Method;
import org.aspectj.apache.bcel.classfile.annotation.Annotation;
import org.aspectj.apache.bcel.generic.ANEWARRAY;
import org.aspectj.apache.bcel.generic.ConstantPoolGen;
import org.aspectj.apache.bcel.generic.FieldInstruction;
import org.aspectj.apache.bcel.generic.GETSTATIC;
import org.aspectj.apache.bcel.generic.INVOKEINTERFACE;
import org.aspectj.apache.bcel.generic.INVOKESPECIAL;
import org.aspectj.apache.bcel.generic.INVOKESTATIC;
import org.aspectj.apache.bcel.generic.Instruction;
import org.aspectj.apache.bcel.generic.InstructionHandle;
import org.aspectj.apache.bcel.generic.InvokeInstruction;
import org.aspectj.apache.bcel.generic.MONITORENTER;
import org.aspectj.apache.bcel.generic.MONITOREXIT;
import org.aspectj.apache.bcel.generic.MULTIANEWARRAY;
import org.aspectj.apache.bcel.generic.NEWARRAY;
import org.aspectj.apache.bcel.generic.ObjectType;
import org.aspectj.apache.bcel.generic.PUTSTATIC;
import org.aspectj.apache.bcel.generic.Type;
import org.aspectj.apache.bcel.util.ClassLoaderRepository;
import org.aspectj.apache.bcel.util.ClassPath;
import org.aspectj.apache.bcel.util.Repository;
import org.aspectj.bridge.IMessageHandler;
import org.aspectj.weaver.Advice;
import org.aspectj.weaver.AdviceKind;
import org.aspectj.weaver.AjAttribute;
import org.aspectj.weaver.BCException;
import org.aspectj.weaver.ConcreteTypeMunger;
import org.aspectj.weaver.ICrossReferenceHandler;
import org.aspectj.weaver.Member;
import org.aspectj.weaver.MemberImpl;
import org.aspectj.weaver.ReferenceType;
import org.aspectj.weaver.ReferenceTypeDelegate;
import org.aspectj.weaver.ResolvedMember;
import org.aspectj.weaver.ResolvedMemberImpl;
import org.aspectj.weaver.ResolvedType;
import org.aspectj.weaver.ResolvedTypeMunger;
import org.aspectj.weaver.UnresolvedType;
import org.aspectj.weaver.World;
import org.aspectj.weaver.AjAttribute.Aspect;
import org.aspectj.weaver.asm.AsmDelegate;
import org.aspectj.weaver.patterns.FormalBinding;
import org.aspectj.weaver.patterns.PerClause;
import org.aspectj.weaver.patterns.Pointcut;
import org.aspectj.weaver.patterns.SimpleScope;
public class BcelWorld extends World implements Repository {
private ClassPathManager classPath;
private Repository delegate;
//private ClassPathManager aspectPath = null;
// private List aspectPathEntries;
// ---- constructors
public BcelWorld() {
this("");
}
public BcelWorld(String cp) {
this(makeDefaultClasspath(cp), IMessageHandler.THROW, null);
}
private static List makeDefaultClasspath(String cp) {
List classPath = new ArrayList();
classPath.addAll(getPathEntries(cp));
classPath.addAll(getPathEntries(ClassPath.getClassPath()));
//System.err.println("classpath: " + classPath);
return classPath;
}
private static List getPathEntries(String s) {
List ret = new ArrayList();
StringTokenizer tok = new StringTokenizer(s, File.pathSeparator);
while(tok.hasMoreTokens()) ret.add(tok.nextToken());
return ret;
}
public BcelWorld(List classPath, IMessageHandler handler, ICrossReferenceHandler xrefHandler) {
//this.aspectPath = new ClassPathManager(aspectPath, handler);
this.classPath = new ClassPathManager(classPath, handler);
setMessageHandler(handler);
setCrossReferenceHandler(xrefHandler);
// Tell BCEL to use us for resolving any classes
delegate = this;
// TODO Alex do we need to call org.aspectj.apache.bcel.Repository.setRepository(delegate);
// if so, how can that be safe in J2EE ?? (static stuff in Bcel)
}
public BcelWorld(ClassPathManager cpm, IMessageHandler handler, ICrossReferenceHandler xrefHandler) {
this.classPath = cpm;
setMessageHandler(handler);
setCrossReferenceHandler(xrefHandler);
// Tell BCEL to use us for resolving any classes
delegate = this;
// TODO Alex do we need to call org.aspectj.apache.bcel.Repository.setRepository(delegate);
// if so, how can that be safe in J2EE ?? (static stuff in Bcel)
}
/**
* Build a World from a ClassLoader, for LTW support
*
* @param loader
* @param handler
* @param xrefHandler
*/
public BcelWorld(ClassLoader loader, IMessageHandler handler, ICrossReferenceHandler xrefHandler) {
this.classPath = null;
setMessageHandler(handler);
setCrossReferenceHandler(xrefHandler);
// Tell BCEL to use us for resolving any classes
delegate = new ClassLoaderRepository(loader);
// TODO Alex do we need to call org.aspectj.apache.bcel.Repository.setRepository(delegate);
// if so, how can that be safe in J2EE ?? (static stuff in Bcel)
}
public void addPath (String name) {
classPath.addPath(name, this.getMessageHandler());
}
/**
* Parse a string into advice.
*
* <blockquote><pre>
* Kind ( Id , ... ) : Pointcut -> MethodSignature
* </pre></blockquote>
*/
public Advice shadowMunger(String str, int extraFlag) {
str = str.trim();
int start = 0;
int i = str.indexOf('(');
AdviceKind kind =
AdviceKind.stringToKind(str.substring(start, i));
start = ++i;
i = str.indexOf(')', i);
String[] ids = parseIds(str.substring(start, i).trim());
//start = ++i;
i = str.indexOf(':', i);
start = ++i;
i = str.indexOf("->", i);
Pointcut pointcut = Pointcut.fromString(str.substring(start, i).trim());
Member m = MemberImpl.methodFromString(str.substring(i+2, str.length()).trim());
// now, we resolve
UnresolvedType[] types = m.getParameterTypes();
FormalBinding[] bindings = new FormalBinding[ids.length];
for (int j = 0, len = ids.length; j < len; j++) {
bindings[j] = new FormalBinding(types[j], ids[j], j, 0, 0, "fromString");
}
Pointcut p =
pointcut.resolve(new SimpleScope(this, bindings));
return new BcelAdvice(kind, p, m, extraFlag, 0, 0, null, null);
}
private String[] parseIds(String str) {
if (str.length() == 0) return ZERO_STRINGS;
List l = new ArrayList();
int start = 0;
while (true) {
int i = str.indexOf(',', start);
if (i == -1) {
l.add(str.substring(start).trim());
break;
}
l.add(str.substring(start, i).trim());
start = i+1;
}
return (String[]) l.toArray(new String[l.size()]);
}
// ---- various interactions with bcel
public static Type makeBcelType(UnresolvedType type) {
return Type.getType(type.getErasureSignature());
}
static Type[] makeBcelTypes(UnresolvedType[] types) {
Type[] ret = new Type[types.length];
for (int i = 0, len = types.length; i < len; i++) {
ret[i] = makeBcelType(types[i]);
}
return ret;
}
static String[] makeBcelTypesAsClassNames(UnresolvedType[] types) {
String[] ret = new String[types.length];
for (int i = 0, len = types.length; i < len; i++) {
ret[i] = types[i].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));
}
// SECRETAPI: used for testing ASM loading of delegates...
public boolean fallbackToLoadingBcelDelegatesForAspects = true;
private int packageRestrictionsForFastDelegates = 0; // 0=dontknow 1=no 2=yes
private List packagePrefixRestrictionList = null;
public boolean isNotOnPackageRestrictedList(String s) {
if (packageRestrictionsForFastDelegates==0) {
Properties p = getExtraConfiguration();
String possiblePackageRestrictions = (p==null?null:p.getProperty("fastDelegateRestrictions"));
if (possiblePackageRestrictions==null) {
packageRestrictionsForFastDelegates=1;
} else {
packageRestrictionsForFastDelegates=2;
packagePrefixRestrictionList=new ArrayList();
StringTokenizer st = new StringTokenizer(possiblePackageRestrictions,":");
while (st.hasMoreTokens()) {
packagePrefixRestrictionList.add(st.nextToken());
}
}
}
if (packageRestrictionsForFastDelegates==1) return true;
if (packageRestrictionsForFastDelegates==2) {
for (Iterator iter = packagePrefixRestrictionList.iterator(); iter.hasNext();) {
String element = (String) iter.next();
if (s.startsWith(element)) {
// System.err.println("Not creating fast delegate for "+s);
return false;
}
}
}
return true;
}
protected ReferenceTypeDelegate resolveDelegate(ReferenceType ty) {
String name = ty.getName();
JavaClass jc = null;
ensureAdvancedConfigurationProcessed();
//UnwovenClassFile classFile = (UnwovenClassFile)sourceJavaClasses.get(name);
//if (classFile != null) jc = classFile.getJavaClass();
if (isFastDelegateSupportEnabled() && classPath!=null && !ty.needsModifiableDelegate() && isNotOnPackageRestrictedList(name)) {
ClassPathManager.ClassFile cf = classPath.find(ty);
if (cf==null) {
return null;
} else {
ReferenceTypeDelegate delegate = buildAsmDelegate(ty,cf);
if (fallbackToLoadingBcelDelegatesForAspects && delegate.isAspect()) {
// bugger - pr135001 - we can't inline around advice from an aspect because we don't load the instructions.
// fixing this quick to get AJDT upgraded with a good 1.5.2dev build.
// other fixes would be:
// 1. record that we are loading the superclass for an aspect, so we know to make it a BCEL delegate
//
// the 'fix' here is only reasonable because there are many less aspects than classes!
// Create a BCEL delegate
if (jc == null) jc = lookupJavaClass(classPath, name);
if (jc == null) return delegate; // worrying situation ?!?
else return buildBcelDelegate(ty, jc, false);
} else {
return delegate;
}
}
} else {
if (jc == null) {
jc = lookupJavaClass(classPath, name);
}
if (jc == null) {
return null;
} else {
return buildBcelDelegate(ty, jc, false);
}
}
}
private ReferenceTypeDelegate buildAsmDelegate(ReferenceType type,ClassPathManager.ClassFile t) {
AsmDelegate asmDelegate;
try {
asmDelegate = new AsmDelegate(type,t.getInputStream());
} catch (IOException e) {
e.printStackTrace();
return null;
}
return asmDelegate;
}
public BcelObjectType buildBcelDelegate(ReferenceType resolvedTypeX, JavaClass jc, boolean exposedToWeaver) {
BcelObjectType ret = new BcelObjectType(resolvedTypeX, jc, exposedToWeaver);
return ret;
}
private JavaClass lookupJavaClass(ClassPathManager classPath, String name) {
if (classPath == null) {
try {
return delegate.loadClass(name);
} catch (ClassNotFoundException e) {
return null;
}
}
try {
ClassPathManager.ClassFile file = classPath.find(UnresolvedType.forName(name));
if (file == null) return null;
ClassParser parser = new ClassParser(file.getInputStream(), file.getPath());
JavaClass jc = parser.parse();
file.close();
return jc;
} catch (IOException ioe) {
return null;
}
}
public BcelObjectType addSourceObjectType(JavaClass jc) {
BcelObjectType ret = null;
String signature = UnresolvedType.forName(jc.getClassName()).getSignature();
Object fromTheMap = typeMap.get(signature);
if (fromTheMap!=null && !(fromTheMap instanceof ReferenceType)) {
// what on earth is it then? See pr 112243
StringBuffer exceptionText = new StringBuffer();
exceptionText.append("Found invalid (not a ReferenceType) entry in the type map. ");
exceptionText.append("Signature=["+signature+"] Found=["+fromTheMap+"] Class=["+fromTheMap.getClass()+"]");
throw new BCException(exceptionText.toString());
}
ReferenceType nameTypeX = (ReferenceType)fromTheMap;
if (nameTypeX == null) {
if (jc.isGeneric() && isInJava5Mode()) {
nameTypeX = ReferenceType.fromTypeX(UnresolvedType.forRawTypeName(jc.getClassName()),this);
ret = buildBcelDelegate(nameTypeX, jc, true);
ReferenceType genericRefType = new ReferenceType(
UnresolvedType.forGenericTypeSignature(signature,ret.getDeclaredGenericSignature()),this);
nameTypeX.setDelegate(ret);
genericRefType.setDelegate(ret);
nameTypeX.setGenericType(genericRefType);
typeMap.put(signature, nameTypeX);
} else {
nameTypeX = new ReferenceType(signature, this);
ret = buildBcelDelegate(nameTypeX, jc, true);
typeMap.put(signature, nameTypeX);
}
} else {
ret = buildBcelDelegate(nameTypeX, jc, true);
}
return ret;
}
void deleteSourceObjectType(UnresolvedType ty) {
typeMap.remove(ty.getSignature());
}
public static Member makeFieldJoinPointSignature(LazyClassGen cg, FieldInstruction fi) {
ConstantPoolGen cpg = cg.getConstantPoolGen();
return
MemberImpl.field(
fi.getClassName(cpg),
(fi instanceof GETSTATIC || fi instanceof PUTSTATIC)
? Modifier.STATIC: 0,
fi.getName(cpg),
fi.getSignature(cpg));
}
// public static Member makeFieldSetSignature(LazyClassGen cg, FieldInstruction fi) {
// ConstantPoolGen cpg = cg.getConstantPoolGen();
// return
// MemberImpl.field(
// fi.getClassName(cpg),
// (fi instanceof GETSTATIC || fi instanceof PUTSTATIC)
// ? Modifier.STATIC
// : 0,
// fi.getName(cpg),
// "(" + fi.getSignature(cpg) + ")" +fi.getSignature(cpg));
// }
public Member makeJoinPointSignature(LazyMethodGen mg) {
return makeJoinPointSignatureFromMethod(mg, null);
}
public Member makeJoinPointSignatureFromMethod(LazyMethodGen mg, MemberImpl.Kind kind) {
Member ret = mg.getMemberView();
if (ret == null) {
int mods = mg.getAccessFlags();
if (mg.getEnclosingClass().isInterface()) {
mods |= Modifier.INTERFACE;
}
if (kind == null) {
if (mg.getName().equals("<init>")) {
kind = Member.CONSTRUCTOR;
} else if (mg.getName().equals("<clinit>")) {
kind = Member.STATIC_INITIALIZATION;
} else {
kind = Member.METHOD;
}
}
return new ResolvedMemberImpl(kind,
UnresolvedType.forName(mg.getClassName()),
mods,
fromBcel(mg.getReturnType()),
mg.getName(),
fromBcel(mg.getArgumentTypes())
);
} else {
return ret;
}
}
public Member makeJoinPointSignatureForMonitorEnter(LazyClassGen cg,InstructionHandle h) {
MONITORENTER i = (MONITORENTER)h.getInstruction();
return MemberImpl.monitorEnter();
}
public Member makeJoinPointSignatureForMonitorExit(LazyClassGen cg,InstructionHandle h) {
MONITOREXIT i = (MONITOREXIT)h.getInstruction();
return MemberImpl.monitorExit();
}
public Member makeJoinPointSignatureForArrayConstruction(LazyClassGen cg, InstructionHandle handle) {
Instruction i = handle.getInstruction();
ConstantPoolGen cpg = cg.getConstantPoolGen();
Member retval = null;
if (i instanceof ANEWARRAY) {
ANEWARRAY arrayInstruction = (ANEWARRAY)i;
ObjectType ot = arrayInstruction.getLoadClassType(cpg);
UnresolvedType ut = fromBcel(ot);
ut = UnresolvedType.makeArray(ut,1);
retval = MemberImpl.method(ut, Modifier.PUBLIC, ResolvedType.VOID, "<init>", new ResolvedType[]{ResolvedType.INT});
} else if (i instanceof MULTIANEWARRAY) {
MULTIANEWARRAY arrayInstruction = (MULTIANEWARRAY)i;
UnresolvedType ut = null;
short dimensions = arrayInstruction.getDimensions();
ObjectType ot = arrayInstruction.getLoadClassType(cpg);
if (ot!=null) {
ut = fromBcel(ot);
ut = UnresolvedType.makeArray(ut,dimensions);
} else {
Type t = arrayInstruction.getType(cpg);
ut = fromBcel(t);
}
ResolvedType[] parms = new ResolvedType[dimensions];
for (int ii=0;ii<dimensions;ii++) parms[ii] = ResolvedType.INT;
retval = MemberImpl.method(ut, Modifier.PUBLIC, ResolvedType.VOID, "<init>", parms);
} else if (i instanceof NEWARRAY) {
NEWARRAY arrayInstruction = (NEWARRAY)i;
Type ot = arrayInstruction.getType();
UnresolvedType ut = fromBcel(ot);
retval = MemberImpl.method(ut, Modifier.PUBLIC, ResolvedType.VOID, "<init>", new ResolvedType[]{ResolvedType.INT});
} else {
throw new BCException("Cannot create array construction signature for this non-array instruction:"+i);
}
return retval;
}
public Member makeJoinPointSignatureForMethodInvocation(LazyClassGen cg, InvokeInstruction ii) {
ConstantPoolGen cpg = cg.getConstantPoolGen();
String name = ii.getName(cpg);
String declaring = ii.getClassName(cpg);
UnresolvedType declaringType = null;
String signature = ii.getSignature(cpg);
int modifier =
(ii instanceof INVOKEINTERFACE)
? Modifier.INTERFACE
: (ii instanceof INVOKESTATIC)
? Modifier.STATIC
: (ii instanceof INVOKESPECIAL && ! name.equals("<init>"))
? Modifier.PRIVATE
: 0;
// in Java 1.4 and after, static method call of super class within subclass method appears
// as declared by the subclass in the bytecode - but they are not
// see #104212
if (ii instanceof INVOKESTATIC) {
ResolvedType appearsDeclaredBy = resolve(declaring);
// look for the method there
for (Iterator iterator = appearsDeclaredBy.getMethods(); iterator.hasNext();) {
ResolvedMember method = (ResolvedMember) iterator.next();
if (method.isStatic()) {
if (name.equals(method.getName()) && signature.equals(method.getSignature())) {
// we found it
declaringType = method.getDeclaringType();
break;
}
}
}
}
if (declaringType == null) {
if (declaring.charAt(0)=='[') declaringType = UnresolvedType.forSignature(declaring);
else declaringType = UnresolvedType.forName(declaring);
}
return MemberImpl.method(declaringType, modifier, name, signature);
}
public static Member makeMungerMethodSignature(JavaClass javaClass, Method method) {
int mods = 0;
if (method.isStatic()) mods = Modifier.STATIC;
else if (javaClass.isInterface()) mods = Modifier.INTERFACE;
else if (method.isPrivate()) mods = Modifier.PRIVATE;
return MemberImpl.method(
UnresolvedType.forName(javaClass.getClassName()), mods, method.getName(), method.getSignature());
}
private static final String[] ZERO_STRINGS = new String[0];
public String toString() {
StringBuffer buf = new StringBuffer();
buf.append("BcelWorld(");
//buf.append(shadowMungerMap);
buf.append(")");
return buf.toString();
}
public Advice createAdviceMunger(
AjAttribute.AdviceAttribute attribute,
Pointcut pointcut,
Member signature)
{
//System.err.println("concrete advice: " + signature + " context " + sourceContext);
return new BcelAdvice(attribute, pointcut, signature, null);
}
public ConcreteTypeMunger concreteTypeMunger(
ResolvedTypeMunger munger, ResolvedType aspectType)
{
return new BcelTypeMunger(munger, aspectType);
}
public ConcreteTypeMunger makeCflowStackFieldAdder(ResolvedMember cflowField) {
return new BcelCflowStackFieldAdder(cflowField);
}
public ConcreteTypeMunger makeCflowCounterFieldAdder(ResolvedMember cflowField) {
return new BcelCflowCounterFieldAdder(cflowField);
}
/**
* Register a munger for perclause @AJ aspect so that we add aspectOf(..) to them as needed
*
* @param aspect
* @param kind
* @return munger
*/
public ConcreteTypeMunger makePerClauseAspect(ResolvedType aspect, PerClause.Kind kind) {
return new BcelPerClauseAspectAdder(aspect, kind);
}
/**
* Retrieve a bcel delegate for an aspect - this will return NULL if the
* delegate is an EclipseSourceType and not a BcelObjectType - this happens
* quite often when incrementally compiling.
*/
public static BcelObjectType getBcelObjectType(ResolvedType concreteAspect) {
ReferenceTypeDelegate rtDelegate = ((ReferenceType)concreteAspect).getDelegate();
if (rtDelegate instanceof BcelObjectType) {
return (BcelObjectType)rtDelegate;
} else {
return null;
}
}
public void tidyUp() {
// At end of compile, close any open files so deletion of those archives is possible
classPath.closeArchives();
typeMap.report();
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) {
throw new RuntimeException("Not implemented");
}
public void removeClass(JavaClass clazz) {
throw new RuntimeException("Not implemented");
}
public JavaClass loadClass(Class clazz) throws ClassNotFoundException {
throw new RuntimeException("Not implemented");
}
public void clear() {
throw new RuntimeException("Not implemented");
}
// @Override
/**
* The aim of this method is to make sure a particular type is 'ok'. Some
* operations on the delegate for a type modify it and this method is
* intended to undo that... see pr85132
*/
public void validateType(UnresolvedType type) {
ResolvedType result = typeMap.get(type.getSignature());
if (result==null) return; // We haven't heard of it yet
if (!result.isExposedToWeaver()) return; // cant need resetting
ReferenceType rt = (ReferenceType)result;
rt.getDelegate().ensureDelegateConsistent();
// If we want to rebuild it 'from scratch' then:
// ClassParser cp = new ClassParser(new ByteArrayInputStream(newbytes),new String(cs));
// try {
// rt.setDelegate(makeBcelObjectType(rt,cp.parse(),true));
// } catch (ClassFormatException e) {
// e.printStackTrace();
// } catch (IOException e) {
// e.printStackTrace();
// }
}
/**
* Checks if given bytecode is an @AspectJ aspect
*
* @param name
* @param bytes
* @return true if so
*/
public boolean isAnnotationStyleAspect(String name, byte[] bytes) {
try {
ClassParser cp = new ClassParser(new ByteArrayInputStream(bytes), null);
JavaClass jc = cp.parse();
if (!jc.isClass()) {
return false;
}
Annotation anns[] = jc.getAnnotations();
if (anns.length == 0) {
return false;
}
boolean couldBeAtAspectJStyle = false;
for (int i = 0; i < anns.length; i++) {
Annotation ann = anns[i];
if ("Lorg/aspectj/lang/annotation/Aspect;".equals(ann.getTypeSignature())) {
couldBeAtAspectJStyle = true;
}
}
if (!couldBeAtAspectJStyle) return false;
// ok, so it has the annotation, but it could have been put
// on a code style aspect by the annotation visitor
Attribute[] attributes = jc.getAttributes();
for (int i = 0; i < attributes.length; i++) {
if (attributes[i].getName().equals(Aspect.AttributeName)) {
return false;
}
}
return true;
} catch (IOException e) {
// assume it is one as a best effort
return true;
}
}
}
|
148,388 |
Bug 148388 LTW weaver produces a debug message at the begining
| null |
resolved fixed
|
99d1c18
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-06-27T18:28:17Z | 2006-06-23T13:40:00Z |
weaver/src/org/aspectj/weaver/tools/WeavingAdaptor.java
|
/* *******************************************************************
* Copyright (c) 2004 IBM Corporation
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Eclipse Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Matthew Webster, Adrian Colyer,
* Martin Lippert initial implementation
* ******************************************************************/
package org.aspectj.weaver.tools;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.StringTokenizer;
import org.aspectj.bridge.AbortException;
import org.aspectj.bridge.IMessage;
import org.aspectj.bridge.IMessageHandler;
import org.aspectj.bridge.Message;
import org.aspectj.bridge.MessageUtil;
import org.aspectj.bridge.MessageWriter;
import org.aspectj.bridge.Version;
import org.aspectj.bridge.IMessage.Kind;
import org.aspectj.util.FileUtil;
import org.aspectj.util.LangUtil;
import org.aspectj.weaver.IClassFileProvider;
import org.aspectj.weaver.IWeaveRequestor;
import org.aspectj.weaver.ResolvedType;
import org.aspectj.weaver.bcel.BcelObjectType;
import org.aspectj.weaver.bcel.BcelWeaver;
import org.aspectj.weaver.bcel.BcelWorld;
import org.aspectj.weaver.bcel.UnwovenClassFile;
/**
* This adaptor allows the AspectJ compiler to be embedded in an existing
* system to facilitate load-time weaving. It provides an interface for a
* weaving class loader to provide a classpath to be woven by a set of
* aspects. A callback is supplied to allow a class loader to define classes
* generated by the compiler during the weaving process.
* <p>
* A weaving class loader should create a <code>WeavingAdaptor</code> before
* any classes are defined, typically during construction. The set of aspects
* passed to the adaptor is fixed for the lifetime of the adaptor although the
* classpath can be augmented. A system property can be set to allow verbose
* weaving messages to be written to the console.
*
*/
public class WeavingAdaptor {
/**
* System property used to turn on verbose weaving messages
*/
public static final String WEAVING_ADAPTOR_VERBOSE = "aj.weaving.verbose";
public static final String SHOW_WEAVE_INFO_PROPERTY = "org.aspectj.weaver.showWeaveInfo";
protected boolean enabled = true;
protected boolean verbose = getVerbose();
protected BcelWorld bcelWorld;
protected BcelWeaver weaver;
private IMessageHandler messageHandler;
private WeavingAdaptorMessageHandler messageHolder;
protected GeneratedClassHandler generatedClassHandler;
protected Map generatedClasses = new HashMap(); /* String -> UnwovenClassFile */
protected WeavingAdaptor () {
createMessageHandler();
}
/**
* Construct a WeavingAdaptor with a reference to a weaving class loader. The
* adaptor will automatically search the class loader hierarchy to resolve
* classes. The adaptor will also search the hierarchy for WeavingClassLoader
* instances to determine the set of aspects to be used ofr weaving.
* @param loader instance of <code>ClassLoader</code>
*/
public WeavingAdaptor (WeavingClassLoader loader) {
// System.err.println("? WeavingAdaptor.<init>(" + loader +"," + aspectURLs.length + ")");
generatedClassHandler = loader;
init(getFullClassPath((ClassLoader)loader),getFullAspectPath((ClassLoader)loader/*,aspectURLs*/));
}
/**
* Construct a WeavingAdator with a reference to a
* <code>GeneratedClassHandler</code>, a full search path for resolving
* classes and a complete set of aspects. The search path must include
* classes loaded by the class loader constructing the WeavingAdaptor and
* all its parents in the hierarchy.
* @param handler <code>GeneratedClassHandler</code>
* @param classURLs the URLs from which to resolve classes
* @param aspectURLs the aspects used to weave classes defined by this class loader
*/
public WeavingAdaptor (GeneratedClassHandler handler, URL[] classURLs, URL[] aspectURLs) {
// System.err.println("? WeavingAdaptor.<init>()");
generatedClassHandler = handler;
init(FileUtil.makeClasspath(classURLs),FileUtil.makeClasspath(aspectURLs));
}
private List getFullClassPath (ClassLoader loader) {
List list = new LinkedList();
for (; loader != null; loader = loader.getParent()) {
if (loader instanceof URLClassLoader) {
URL[] urls = ((URLClassLoader)loader).getURLs();
list.addAll(0,FileUtil.makeClasspath(urls));
}
else {
warn("cannot determine classpath");
}
}
list.addAll(0,makeClasspath(System.getProperty("sun.boot.class.path")));
return list;
}
private List getFullAspectPath (ClassLoader loader) {
List list = new LinkedList();
for (; loader != null; loader = loader.getParent()) {
if (loader instanceof WeavingClassLoader) {
URL[] urls = ((WeavingClassLoader)loader).getAspectURLs();
list.addAll(0,FileUtil.makeClasspath(urls));
}
}
return list;
}
private static boolean getVerbose () {
return Boolean.getBoolean(WEAVING_ADAPTOR_VERBOSE);
}
private void init(List classPath, List aspectPath) {
createMessageHandler();
info("using classpath: " + classPath);
info("using aspectpath: " + aspectPath);
bcelWorld = new BcelWorld(classPath,messageHandler,null);
bcelWorld.setXnoInline(false);
bcelWorld.getLint().loadDefaultProperties();
if (LangUtil.is15VMOrGreater()) {
bcelWorld.setBehaveInJava5Way(true);
}
weaver = new BcelWeaver(bcelWorld);
registerAspectLibraries(aspectPath);
}
private void createMessageHandler() {
messageHolder = new WeavingAdaptorMessageHandler(new PrintWriter(System.err));
messageHandler = messageHolder;
if (verbose) messageHandler.dontIgnore(IMessage.INFO);
if (Boolean.getBoolean(SHOW_WEAVE_INFO_PROPERTY)) messageHandler.dontIgnore(IMessage.WEAVEINFO);
info("AspectJ Weaver Version " + Version.text + " built on " + Version.time_text); //$NON-NLS-1$
}
protected IMessageHandler getMessageHandler () {
return messageHandler;
}
protected void setMessageHandler (IMessageHandler mh) {
if (messageHolder != null) {
messageHolder.flushMessages();
messageHolder = null;
}
messageHandler = mh;
bcelWorld.setMessageHandler(mh);
}
/**
* Appends URL to path used by the WeavingAdptor to resolve classes
* @param url to be appended to search path
*/
public void addURL(URL url) {
File libFile = new File(url.getPath());
try {
weaver.addLibraryJarFile(libFile);
}
catch (IOException ex) {
warn("bad library: '" + libFile + "'");
}
}
/**
* Weave a class using aspects previously supplied to the adaptor.
* @param name the name of the class
* @param bytes the class bytes
* @return the woven bytes
* @exception IOException weave failed
*/
public byte[] weaveClass (String name, byte[] bytes) throws IOException {
if (enabled) {
if (shouldWeave(name, bytes)) {
info("weaving '" + name + "'");
bytes = getWovenBytes(name, bytes);
} else if (shouldWeaveAnnotationStyleAspect(name, bytes)) {
// an @AspectJ aspect needs to be at least munged by the aspectOf munger
info("weaving '" + name + "'");
bytes = getAtAspectJAspectBytes(name, bytes);
}
else {
info("not weaving '" + name + "'");
}
}
return bytes;
}
/**
* @param name
* @return true if should weave (but maybe we still need to munge it for @AspectJ aspectof support)
*/
private boolean shouldWeave (String name, byte[] bytes) {
name = name.replace('/','.');
boolean b = !generatedClasses.containsKey(name) && shouldWeaveName(name);
return b && accept(name, bytes);
// && shouldWeaveAnnotationStyleAspect(name);
// // we recall shouldWeaveAnnotationStyleAspect as we need to add aspectOf methods for @Aspect anyway
// //FIXME AV - this is half ok as the aspect will be weaved by others. In theory if the aspect
// // is excluded from include/exclude config we should only weave late type mungers for aspectof
// return b && (accept(name) || shouldWeaveAnnotationStyleAspect(name));
}
//ATAJ
protected boolean accept(String name, byte[] bytes) {
return true;
}
protected boolean shouldDump(String name, boolean before) {
return false;
}
private boolean shouldWeaveName (String name) {
boolean should =
!((/*(name.startsWith("org.apache.bcel.")//FIXME AV why ? bcel is wrapped in org.aspectj.
||*/ name.startsWith("org.aspectj.")
|| name.startsWith("java.")
|| name.startsWith("javax."))
//|| name.startsWith("$Proxy")//JDK proxies//FIXME AV is that 1.3 proxy ? fe. ataspect.$Proxy0 is a java5 proxy...
|| name.startsWith("sun.reflect."));//JDK reflect
return should;
}
/**
* We allow @AJ aspect weaving so that we can add aspectOf() as part of the weaving
* (and not part of the source compilation)
*
* @param name
* @param bytes bytecode (from classloader), allow to NOT lookup stuff on disk again during resolve
* @return true if @Aspect
*/
private boolean shouldWeaveAnnotationStyleAspect(String name, byte[] bytes) {
// AV: instead of doing resolve that would lookup stuff on disk thru BCEL ClassLoaderRepository
// we reuse bytes[] here to do a fast lookup for @Aspect annotation
return bcelWorld.isAnnotationStyleAspect(name, bytes);
}
/**
* Weave a set of bytes defining a class.
* @param name the name of the class being woven
* @param bytes the bytes that define the class
* @return byte[] the woven bytes for the class
* @throws IOException
*/
private byte[] getWovenBytes(String name, byte[] bytes) throws IOException {
WeavingClassFileProvider wcp = new WeavingClassFileProvider(name,bytes);
weaver.weave(wcp);
return wcp.getBytes();
}
/**
* Weave a set of bytes defining a class for only what is needed to turn @AspectJ aspect
* in a usefull form ie with aspectOf method - see #113587
* @param name the name of the class being woven
* @param bytes the bytes that define the class
* @return byte[] the woven bytes for the class
* @throws IOException
*/
private byte[] getAtAspectJAspectBytes(String name, byte[] bytes) throws IOException {
WeavingClassFileProvider wcp = new WeavingClassFileProvider(name,bytes);
wcp.setApplyAtAspectJMungersOnly();
weaver.weave(wcp);
return wcp.getBytes();
}
private void registerAspectLibraries(List aspectPath) {
// System.err.println("? WeavingAdaptor.registerAspectLibraries(" + aspectPath + ")");
for (Iterator i = aspectPath.iterator(); i.hasNext();) {
String libName = (String)i.next();
addAspectLibrary(libName);
}
weaver.prepareForWeave();
}
/*
* Register an aspect library with this classloader for use during
* weaving. This class loader will also return (unmodified) any of the
* classes in the library in response to a <code>findClass()</code> request.
* The library is not required to be on the weavingClasspath given when this
* classloader was constructed.
* @param aspectLibraryJarFile a jar file representing an aspect library
* @throws IOException
*/
private void addAspectLibrary(String aspectLibraryName) {
File aspectLibrary = new File(aspectLibraryName);
if (aspectLibrary.isDirectory()
|| (FileUtil.isZipFile(aspectLibrary))) {
try {
info("adding aspect library: '" + aspectLibrary + "'");
weaver.addLibraryJarFile(aspectLibrary);
} catch (IOException ex) {
error("exception adding aspect library: '" + ex + "'");
}
} else {
error("bad aspect library: '" + aspectLibrary + "'");
}
}
private static List makeClasspath(String cp) {
List ret = new ArrayList();
if (cp != null) {
StringTokenizer tok = new StringTokenizer(cp,File.pathSeparator);
while (tok.hasMoreTokens()) {
ret.add(tok.nextToken());
}
}
return ret;
}
protected boolean info (String message) {
return MessageUtil.info(messageHandler,message);
}
protected boolean warn (String message) {
return MessageUtil.warn(messageHandler,message);
}
protected boolean warn (String message, Throwable th) {
return messageHandler.handleMessage(new Message(message, IMessage.WARNING, th, null));
}
protected boolean error (String message) {
return MessageUtil.error(messageHandler,message);
}
/**
* Dump the given bytcode in _dump/... (dev mode)
*
* @param name
* @param b
* @param before whether we are dumping before weaving
* @throws Throwable
*/
protected void dump(String name, byte[] b, boolean before) {
String dirName = "_ajdump";
if (before) dirName = dirName + File.separator + "_before";
String className = name.replace('.', '/');
final File dir;
if (className.indexOf('/') > 0) {
dir = new File(dirName + File.separator + className.substring(0, className.lastIndexOf('/')));
} else {
dir = new File(dirName);
}
dir.mkdirs();
String fileName = dirName + File.separator + className + ".class";
try {
// System.out.println("WeavingAdaptor.dump() fileName=" + new File(fileName).getAbsolutePath());
FileOutputStream os = new FileOutputStream(fileName);
os.write(b);
os.close();
}
catch (IOException ex) {
warn("unable to dump class " + name + " in directory " + dirName,ex);
}
}
/**
* Processes messages arising from weaver operations.
* Tell weaver to abort on any message more severe than warning.
*/
protected class WeavingAdaptorMessageHandler extends MessageWriter {
private Set ignoring = new HashSet();
private IMessage.Kind failKind;
private boolean accumulating = true;
private List messages = new ArrayList();
public WeavingAdaptorMessageHandler (PrintWriter writer) {
super(writer,true);
ignore(IMessage.WEAVEINFO);
ignore(IMessage.INFO);
this.failKind = IMessage.ERROR;
}
public boolean handleMessage(IMessage message) throws AbortException {
addMessage(message);
boolean result = super.handleMessage(message);
if (0 <= message.getKind().compareTo(failKind)) {
throw new AbortException(message);
}
return true;
}
public boolean isIgnoring (Kind kind) {
return ((null != kind) && (ignoring.contains(kind)));
}
/**
* Set a message kind to be ignored from now on
*/
public void ignore (IMessage.Kind kind) {
if ((null != kind) && (!ignoring.contains(kind))) {
ignoring.add(kind);
}
}
/**
* Remove a message kind from the list of those ignored from now on.
*/
public void dontIgnore (IMessage.Kind kind) {
if (null != kind) {
ignoring.remove(kind);
if (kind.equals(IMessage.INFO)) accumulating = false;
}
}
private void addMessage (IMessage message) {
if (accumulating && isIgnoring(message.getKind())) {
messages.add(message);
}
}
public void flushMessages () {
for (Iterator iter = messages.iterator(); iter.hasNext();) {
IMessage message = (IMessage)iter.next();
super.handleMessage(message);
}
accumulating = false;
messages.clear();
}
}
private class WeavingClassFileProvider implements IClassFileProvider {
private UnwovenClassFile unwovenClass;
private List unwovenClasses = new ArrayList(); /* List<UnovenClassFile> */
private UnwovenClassFile wovenClass;
private boolean isApplyAtAspectJMungersOnly = false;
private BcelObjectType delegate;
public WeavingClassFileProvider (String name, byte[] bytes) {
this.unwovenClass = new UnwovenClassFile(name,bytes);
this.unwovenClasses.add(unwovenClass);
if (shouldDump(name.replace('/', '.'),true)) {
dump(name, bytes, true);
}
delegate = bcelWorld.addSourceObjectType(unwovenClass.getJavaClass());
}
public void setApplyAtAspectJMungersOnly() {
isApplyAtAspectJMungersOnly = true;
}
public boolean isApplyAtAspectJMungersOnly() {
return isApplyAtAspectJMungersOnly;
}
public byte[] getBytes () {
if (wovenClass != null) return wovenClass.getBytes();
else return unwovenClass.getBytes();
}
public Iterator getClassFileIterator() {
return unwovenClasses.iterator();
}
public IWeaveRequestor getRequestor() {
return new IWeaveRequestor() {
public void acceptResult(UnwovenClassFile result) {
if (wovenClass == null) {
wovenClass = result;
String name = result.getClassName();
if (shouldDump(name.replace('/', '.'), false)) {
dump(name, result.getBytes(), false);
}
}
/* Classes generated by weaver e.g. around closure advice */
else {
String className = result.getClassName();
System.err.println("? WeavingClassFileProvider.acceptResult() " + wovenClass.getClassName() + "->" + className);
generatedClasses.put(className,result);
generatedClasses.put(wovenClass.getClassName(),result);
generatedClassHandler.acceptClass(className,result.getBytes());
}
}
public void processingReweavableState() { }
public void addingTypeMungers() {}
public void weavingAspects() {}
public void weavingClasses() {}
public void weaveCompleted() {
if (delegate!=null) delegate.weavingCompleted();
ResolvedType.resetPrimitives();
}
};
}
}
}
|
148,911 |
Bug 148911 NPR compiling Spring
|
The Spring 2.0 RC1 project contains two directories with aspects. Since the eclipse project does not compile cleanly with just the java nature, I decided to try adding the aspectj nature and giving the aspectj builder a shot. I don't have any idea what might be the trigger to the problem, but simply checking out Spring 2.0 RC1 and adding the aspectj nature should be able to reproduce. If I learn more I will add to this bug. ---- java.lang.NullPointerException at org.aspectj.org.eclipse.jdt.internal.compiler.ast.SingleTypeReference.getTypeBinding(SingleTypeReference.java:39) at org.aspectj.org.eclipse.jdt.internal.compiler.ast.TypeReference.resolveType(TypeReference.java:132) at org.aspectj.org.eclipse.jdt.internal.compiler.ast.TypeReference.resolveType(TypeReference.java:123) at org.aspectj.ajdt.internal.core.builder.AsmElementFormatter.setParameters(AsmElementFormatter.java:311) at org.aspectj.ajdt.internal.core.builder.AsmElementFormatter.genLabelAndKind(AsmElementFormatter.java:258) at org.aspectj.ajdt.internal.core.builder.AsmHierarchyBuilder.visit(AsmHierarchyBuilder.java:392) at org.aspectj.org.eclipse.jdt.internal.compiler.ast.MethodDeclaration.traverse(MethodDeclaration.java:185) at org.aspectj.org.eclipse.jdt.internal.compiler.ast.TypeDeclaration.traverse(TypeDeclaration.java:1250) at org.aspectj.org.eclipse.jdt.internal.compiler.ast.QualifiedAllocationExpression.traverse(QualifiedAllocationExpression.java:392) at org.aspectj.org.eclipse.jdt.internal.compiler.ast.LocalDeclaration.traverse(LocalDeclaration.java:242) at org.aspectj.org.eclipse.jdt.internal.compiler.ast.MethodDeclaration.traverse(MethodDeclaration.java:212) at org.aspectj.org.eclipse.jdt.internal.compiler.ast.TypeDeclaration.traverse(TypeDeclaration.java:1195) at org.aspectj.org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration.traverse(CompilationUnitDeclaration.java:339) at org.aspectj.ajdt.internal.core.builder.AsmHierarchyBuilder.internalBuild(AsmHierarchyBuilder.java:145) at org.aspectj.ajdt.internal.core.builder.AsmHierarchyBuilder.buildStructureForCompilationUnit(AsmHierarchyBuilder.java:87) at org.aspectj.ajdt.internal.compiler.lookup.EclipseFactory.finishedCompilationUnit(EclipseFactory.java:941) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.afterProcessing(AjCompilerAdapter.java:210) at org.aspectj.ajdt.internal.compiler.CompilerAdapter.ajc$after$org_aspectj_ajdt_internal_compiler_CompilerAdapter$4$6b855184(CompilerAdapter.aj:91) at org.aspectj.org.eclipse.jdt.internal.compiler.Compiler.process(Compiler.java:533) at org.aspectj.org.eclipse.jdt.internal.compiler.Compiler.compile(Compiler.java:329) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.performCompilation(AjBuildManager.java:887) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.doBuild(AjBuildManager.java:244) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.batchBuild(AjBuildManager.java:163) at org.aspectj.ajde.internal.CompilerAdapter.compile(CompilerAdapter.java:122) at org.aspectj.ajde.internal.AspectJBuildManager$CompilerThread.run(AspectJBuildManager.java:191) NullPointerException thrown: null
|
resolved fixed
|
b59b036
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-06-28T07:32:35Z | 2006-06-27T23:13:20Z |
org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/core/builder/AsmElementFormatter.java
|
/* *******************************************************************
* Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC).
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the 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 support for @AJ style
* ******************************************************************/
package org.aspectj.ajdt.internal.core.builder;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.aspectj.ajdt.internal.compiler.ast.AdviceDeclaration;
import org.aspectj.ajdt.internal.compiler.ast.DeclareDeclaration;
import org.aspectj.ajdt.internal.compiler.ast.InterTypeConstructorDeclaration;
import org.aspectj.ajdt.internal.compiler.ast.InterTypeDeclaration;
import org.aspectj.ajdt.internal.compiler.ast.InterTypeFieldDeclaration;
import org.aspectj.ajdt.internal.compiler.ast.InterTypeMethodDeclaration;
import org.aspectj.ajdt.internal.compiler.ast.PointcutDeclaration;
import org.aspectj.ajdt.internal.compiler.lookup.AjLookupEnvironment;
import org.aspectj.ajdt.internal.compiler.lookup.EclipseFactory;
import org.aspectj.asm.IProgramElement;
import org.aspectj.org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration;
import org.aspectj.org.eclipse.jdt.internal.compiler.ast.Annotation;
import org.aspectj.org.eclipse.jdt.internal.compiler.ast.Argument;
import org.aspectj.org.eclipse.jdt.internal.compiler.ast.MethodDeclaration;
import org.aspectj.org.eclipse.jdt.internal.compiler.ast.TypeReference;
import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.TypeBinding;
import org.aspectj.weaver.AdviceKind;
import org.aspectj.weaver.ResolvedType;
import org.aspectj.weaver.UnresolvedType;
import org.aspectj.weaver.patterns.AndPointcut;
import org.aspectj.weaver.patterns.DeclareAnnotation;
import org.aspectj.weaver.patterns.DeclareErrorOrWarning;
import org.aspectj.weaver.patterns.DeclareParents;
import org.aspectj.weaver.patterns.DeclarePrecedence;
import org.aspectj.weaver.patterns.DeclareSoft;
import org.aspectj.weaver.patterns.OrPointcut;
import org.aspectj.weaver.patterns.ReferencePointcut;
import org.aspectj.weaver.patterns.TypePattern;
import org.aspectj.weaver.patterns.TypePatternList;
/**
* @author Mik Kersten
*/
public class AsmElementFormatter {
public static final String UNDEFINED="<undefined>";
public static final String DECLARE_PRECEDENCE = "precedence";
public static final String DECLARE_SOFT = "soft";
public static final String DECLARE_PARENTS = "parents";
public static final String DECLARE_WARNING = "warning";
public static final String DECLARE_ERROR = "error";
public static final String DECLARE_UNKNONWN = "<unknown declare>";
public static final String POINTCUT_ABSTRACT = "<abstract pointcut>";
public static final String POINTCUT_ANONYMOUS = "<anonymous pointcut>";
public static final String DOUBLE_DOTS = "..";
public static final int MAX_MESSAGE_LENGTH = 18;
public static final String DEC_LABEL = "declare";
public void genLabelAndKind(MethodDeclaration methodDeclaration, IProgramElement node) {
if (methodDeclaration instanceof AdviceDeclaration) {
AdviceDeclaration ad = (AdviceDeclaration)methodDeclaration;
node.setKind(IProgramElement.Kind.ADVICE);
if (ad.kind == AdviceKind.Around) {
node.setCorrespondingType(ad.returnType.toString()); //returnTypeToString(0));
}
StringBuffer details = new StringBuffer();
if (ad.pointcutDesignator != null) {
if (ad.pointcutDesignator.getPointcut() instanceof ReferencePointcut) {
ReferencePointcut rp = (ReferencePointcut)ad.pointcutDesignator.getPointcut();
details.append(rp.name).append("..");
} else if (ad.pointcutDesignator.getPointcut() instanceof AndPointcut) {
AndPointcut ap = (AndPointcut)ad.pointcutDesignator.getPointcut();
if (ap.getLeft() instanceof ReferencePointcut) {
details.append(ap.getLeft().toString()).append(DOUBLE_DOTS);
} else {
details.append(POINTCUT_ANONYMOUS).append(DOUBLE_DOTS);
}
} else if (ad.pointcutDesignator.getPointcut() instanceof OrPointcut) {
OrPointcut op = (OrPointcut)ad.pointcutDesignator.getPointcut();
if (op.getLeft() instanceof ReferencePointcut) {
details.append(op.getLeft().toString()).append(DOUBLE_DOTS);
} else {
details.append(POINTCUT_ANONYMOUS).append(DOUBLE_DOTS);
}
} else {
details.append(POINTCUT_ANONYMOUS);
}
} else {
details.append(POINTCUT_ABSTRACT);
}
node.setName(ad.kind.toString());
//if (details.length()!=0)
node.setDetails(details.toString());
setParameters(methodDeclaration, node);
} else if (methodDeclaration instanceof PointcutDeclaration) {
PointcutDeclaration pd = (PointcutDeclaration)methodDeclaration;
node.setKind(IProgramElement.Kind.POINTCUT);
node.setName(translatePointcutName(new String(methodDeclaration.selector)));
setParameters(methodDeclaration, node);
} else if (methodDeclaration instanceof DeclareDeclaration) {
DeclareDeclaration declare = (DeclareDeclaration)methodDeclaration;
String name = DEC_LABEL + " ";
if (declare.declareDecl instanceof DeclareErrorOrWarning) {
DeclareErrorOrWarning deow = (DeclareErrorOrWarning)declare.declareDecl;
if (deow.isError()) {
node.setKind( IProgramElement.Kind.DECLARE_ERROR);
name += DECLARE_ERROR;
} else {
node.setKind( IProgramElement.Kind.DECLARE_WARNING);
name += DECLARE_WARNING;
}
node.setName(name) ;
node.setDetails("\"" + genDeclareMessage(deow.getMessage()) + "\"");
} else if (declare.declareDecl instanceof DeclareParents) {
node.setKind( IProgramElement.Kind.DECLARE_PARENTS);
DeclareParents dp = (DeclareParents)declare.declareDecl;
node.setName(name + DECLARE_PARENTS);
String kindOfDP = null;
StringBuffer details = new StringBuffer("");
TypePattern[] newParents = dp.getParents().getTypePatterns();
for (int i = 0; i < newParents.length; i++) {
TypePattern tp = newParents[i];
UnresolvedType tx = tp.getExactType();
if (kindOfDP == null) {
kindOfDP = "implements ";
try {
ResolvedType rtx = tx.resolve(((AjLookupEnvironment)declare.scope.environment()).factory.getWorld());
if (!rtx.isInterface()) kindOfDP = "extends ";
} catch (Throwable t) {
// What can go wrong???? who knows!
}
}
String typename= tp.toString();
if (typename.lastIndexOf(".")!=-1) {
typename=typename.substring(typename.lastIndexOf(".")+1);
}
details.append(typename);
if ((i+1)<newParents.length) details.append(",");
}
node.setDetails(kindOfDP+details.toString());
} else if (declare.declareDecl instanceof DeclareSoft) {
node.setKind( IProgramElement.Kind.DECLARE_SOFT);
DeclareSoft ds = (DeclareSoft)declare.declareDecl;
node.setName(name + DECLARE_SOFT);
node.setDetails(genTypePatternLabel(ds.getException()));
} else if (declare.declareDecl instanceof DeclarePrecedence) {
node.setKind( IProgramElement.Kind.DECLARE_PRECEDENCE);
DeclarePrecedence ds = (DeclarePrecedence)declare.declareDecl;
node.setName(name + DECLARE_PRECEDENCE);
node.setDetails(genPrecedenceListLabel(ds.getPatterns()));
} else if (declare.declareDecl instanceof DeclareAnnotation) {
DeclareAnnotation deca = (DeclareAnnotation)declare.declareDecl;
String thekind = deca.getKind().toString();
node.setName(name+"@"+thekind.substring(3));
if (deca.getKind()==DeclareAnnotation.AT_CONSTRUCTOR) {
node.setKind(IProgramElement.Kind.DECLARE_ANNOTATION_AT_CONSTRUCTOR);
} else if (deca.getKind()==DeclareAnnotation.AT_FIELD) {
node.setKind(IProgramElement.Kind.DECLARE_ANNOTATION_AT_FIELD);
} else if (deca.getKind()==DeclareAnnotation.AT_METHOD) {
node.setKind(IProgramElement.Kind.DECLARE_ANNOTATION_AT_METHOD);
} else if (deca.getKind()==DeclareAnnotation.AT_TYPE) {
node.setKind(IProgramElement.Kind.DECLARE_ANNOTATION_AT_TYPE);
}
node.setDetails(genDecaLabel(deca));
} else {
node.setKind(IProgramElement.Kind.ERROR);
node.setName(DECLARE_UNKNONWN);
}
} else if (methodDeclaration instanceof InterTypeDeclaration) {
InterTypeDeclaration itd = (InterTypeDeclaration)methodDeclaration;
String name = itd.getOnType().toString() + "." + new String(itd.getDeclaredSelector());
if (methodDeclaration instanceof InterTypeFieldDeclaration) {
node.setKind(IProgramElement.Kind.INTER_TYPE_FIELD);
node.setName(name);
} else if (methodDeclaration instanceof InterTypeMethodDeclaration) {
node.setKind(IProgramElement.Kind.INTER_TYPE_METHOD);
node.setName(name);
} else if (methodDeclaration instanceof InterTypeConstructorDeclaration) {
node.setKind(IProgramElement.Kind.INTER_TYPE_CONSTRUCTOR);
// StringBuffer argumentsSignature = new StringBuffer("fubar");
// argumentsSignature.append("(");
// if (methodDeclaration.arguments!=null && methodDeclaration.arguments.length>1) {
//
// for (int i = 1;i<methodDeclaration.arguments.length;i++) {
// argumentsSignature.append(methodDeclaration.arguments[i]);
// if (i+1<methodDeclaration.arguments.length) argumentsSignature.append(",");
// }
// }
// argumentsSignature.append(")");
// InterTypeConstructorDeclaration itcd = (InterTypeConstructorDeclaration)methodDeclaration;
node.setName(itd.getOnType().toString() + "." + itd.getOnType().toString()/*+argumentsSignature.toString()*/);
} else {
node.setKind(IProgramElement.Kind.ERROR);
node.setName(name);
}
node.setCorrespondingType(itd.returnType.toString());
if (node.getKind() != IProgramElement.Kind.INTER_TYPE_FIELD) {
setParameters(methodDeclaration, node);
}
} else {
if (methodDeclaration.isConstructor()) {
node.setKind(IProgramElement.Kind.CONSTRUCTOR);
} else {
node.setKind(IProgramElement.Kind.METHOD);
//TODO AV - could speed up if we could dig only for @Aspect declaring types (or aspect if mixed style allowed)
//??? how to : node.getParent().getKind().equals(IProgramElement.Kind.ASPECT)) {
if (true && methodDeclaration!=null && methodDeclaration.annotations != null && methodDeclaration.scope!=null) {
for (int i = 0; i < methodDeclaration.annotations.length; i++) {
//Note: AV: implicit single advice type support here (should be enforced somewhere as well (APT etc))
Annotation annotation = methodDeclaration.annotations[i];
String annotationSig = new String(annotation.type.getTypeBindingPublic(methodDeclaration.scope).signature());
if (annotationSig!=null && annotationSig.charAt(1)=='o') {
if ("Lorg/aspectj/lang/annotation/Pointcut;".equals(annotationSig)) {
node.setKind(IProgramElement.Kind.POINTCUT);
break;
} else if ("Lorg/aspectj/lang/annotation/Before;".equals(annotationSig)
|| "Lorg/aspectj/lang/annotation/After;".equals(annotationSig)
|| "Lorg/aspectj/lang/annotation/AfterReturning;".equals(annotationSig)
|| "Lorg/aspectj/lang/annotation/AfterThrowing;".equals(annotationSig)
|| "Lorg/aspectj/lang/annotation/Around;".equals(annotationSig)) {
node.setKind(IProgramElement.Kind.ADVICE);
//TODO AV - all are considered anonymous - is that ok?
node.setDetails(POINTCUT_ANONYMOUS);
break;
}
}
}
}
}
node.setName(new String(methodDeclaration.selector));
setParameters(methodDeclaration, node);
}
}
private String genDecaLabel(DeclareAnnotation deca) {
StringBuffer sb = new StringBuffer("");
sb.append(deca.getPatternAsString());
sb.append(" : ");
sb.append(deca.getAnnotationString());
return sb.toString();
}
private String genPrecedenceListLabel(TypePatternList list) {
String tpList = "";
for (int i = 0; i < list.size(); i++) {
tpList += genTypePatternLabel(list.get(i));
if (i < list.size()-1) tpList += ", ";
}
return tpList;
}
// private String genArguments(MethodDeclaration md) {
// String args = "";
// Argument[] argArray = md.arguments;
// if (argArray == null) return args;
// for (int i = 0; i < argArray.length; i++) {
// String argName = new String(argArray[i].name);
// String argType = argArray[i].type.toString();
// if (acceptArgument(argName, argType)) {
// args += argType + ", ";
// }
// }
// int lastSepIndex = args.lastIndexOf(',');
// if (lastSepIndex != -1 && args.endsWith(", ")) args = args.substring(0, lastSepIndex);
// return args;
// }
public void setParameters(AbstractMethodDeclaration md, IProgramElement pe) {
Argument[] argArray = md.arguments;
if (argArray == null) {
pe.setParameterNames(Collections.EMPTY_LIST);
pe.setParameterSignatures(Collections.EMPTY_LIST);
} else {
List names = new ArrayList();
List paramSigs = new ArrayList();
for (int i = 0; i < argArray.length; i++) {
String argName = new String(argArray[i].name);
//String argType = "<UnknownType>"; // pr135052
if (acceptArgument(argName, argArray[i].type.toString())) {
TypeReference typeR = argArray[i].type;
if (typeR!=null) {
TypeBinding typeB = typeR.resolvedType;
if (typeB==null) {
typeB = typeR.resolveType(md.scope);
}
EclipseFactory factory = EclipseFactory.fromScopeLookupEnvironment(md.scope);
UnresolvedType ut = factory.fromBinding(typeB);
paramSigs.add(ut.getSignature().toCharArray());
}
names.add(argName);
}
}
pe.setParameterNames(names);
if (!paramSigs.isEmpty()) {
pe.setParameterSignatures(paramSigs);
}
}
}
// TODO: fix this way of determing ajc-added arguments, make subtype of Argument with extra info
private boolean acceptArgument(String name, String type) {
if (name.charAt(0)!='a' && type.charAt(0)!='o') return true;
return !name.startsWith("ajc$this_")
&& !type.equals("org.aspectj.lang.JoinPoint.StaticPart")
&& !type.equals("org.aspectj.lang.JoinPoint")
&& !type.equals("org.aspectj.runtime.internal.AroundClosure");
}
public String genTypePatternLabel(TypePattern tp) {
final String TYPE_PATTERN_LITERAL = "<type pattern>";
String label;
UnresolvedType typeX = tp.getExactType();
if (!ResolvedType.isMissing(typeX)) {
label = typeX.getName();
if (tp.isIncludeSubtypes()) label += "+";
} else {
label = TYPE_PATTERN_LITERAL;
}
return label;
}
public String genDeclareMessage(String message) {
int length = message.length();
if (length < MAX_MESSAGE_LENGTH) {
return message;
} else {
return message.substring(0, MAX_MESSAGE_LENGTH-1) + "..";
}
}
// // TODO:
// private String translateAdviceName(String label) {
// if (label.indexOf("before") != -1) return "before";
// if (label.indexOf("returning") != -1) return "after returning";
// if (label.indexOf("after") != -1) return "after";
// if (label.indexOf("around") != -1) return "around";
// else return "<advice>";
// }
// // !!! move or replace
// private String translateDeclareName(String name) {
// int colonIndex = name.indexOf(":");
// if (colonIndex != -1) {
// return name.substring(0, colonIndex);
// } else {
// return name;
// }
// }
// !!! move or replace
// private String translateInterTypeDecName(String name) {
// int index = name.lastIndexOf('$');
// if (index != -1) {
// return name.substring(index+1);
// } else {
// return name;
// }
// }
// !!! move or replace
private String translatePointcutName(String name) {
int index = name.indexOf("$$")+2;
int endIndex = name.lastIndexOf('$');
if (index != -1 && endIndex != -1) {
return name.substring(index, endIndex);
} else {
return name;
}
}
}
|
148,727 |
Bug 148727 Can't call synthetic aspectOf method on aspect in library jar
|
Separate compilation of the following program breaks on 1.5.2rc1 because of the recent change to marking aspect methods as synthetic: public aspect Asp { } public class Client { public static void main(String argz[]) { System.out.println("Can call aspectOf? "+Asp.aspectOf()); } } C:\devel\scratch\synthetic>ajc -classpath asp.jar;%CLASSPATH% Client.java C:\devel\scratch\synthetic\Client.java:3 [error] The method aspectOf() is undefi ned for the type Asp System.out.println("Can call aspectOf? "+Asp.aspectOf()); 1 error C:\devel\scratch\synthetic>javac -classpath asp.jar;%CLASSPATH% Client.java Client.java:3: cannot find symbol symbol : method aspectOf() location: class Asp System.out.println("Can call aspectOf? "+Asp.aspectOf()); ^ 1 error Clearly it's vital that external users of a library be able to call API methods like aspectOf on library aspects. This works: C:\devel\scratch\synthetic>ajc *.aj Client.java C:\devel\scratch\synthetic>java Client Can call aspectOf? Asp@b89838 Patch with test integrated into CVS tree to follow...
|
resolved fixed
|
21e06a6
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-06-28T09:16:01Z | 2006-06-26T19:26:40Z |
tests/bugs152/pr148727/Client.java
| |
148,727 |
Bug 148727 Can't call synthetic aspectOf method on aspect in library jar
|
Separate compilation of the following program breaks on 1.5.2rc1 because of the recent change to marking aspect methods as synthetic: public aspect Asp { } public class Client { public static void main(String argz[]) { System.out.println("Can call aspectOf? "+Asp.aspectOf()); } } C:\devel\scratch\synthetic>ajc -classpath asp.jar;%CLASSPATH% Client.java C:\devel\scratch\synthetic\Client.java:3 [error] The method aspectOf() is undefi ned for the type Asp System.out.println("Can call aspectOf? "+Asp.aspectOf()); 1 error C:\devel\scratch\synthetic>javac -classpath asp.jar;%CLASSPATH% Client.java Client.java:3: cannot find symbol symbol : method aspectOf() location: class Asp System.out.println("Can call aspectOf? "+Asp.aspectOf()); ^ 1 error Clearly it's vital that external users of a library be able to call API methods like aspectOf on library aspects. This works: C:\devel\scratch\synthetic>ajc *.aj Client.java C:\devel\scratch\synthetic>java Client Can call aspectOf? Asp@b89838 Patch with test integrated into CVS tree to follow...
|
resolved fixed
|
21e06a6
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-06-28T09:16:01Z | 2006-06-26T19:26:40Z |
tests/src/org/aspectj/systemtest/ajc152/Ajc152Tests.java
|
/*******************************************************************************
* Copyright (c) 2006 IBM
* 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.ajc152;
import java.io.File;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import junit.framework.Test;
import org.aspectj.ajdt.internal.core.builder.AsmHierarchyBuilder;
import org.aspectj.asm.AsmManager;
import org.aspectj.asm.IHierarchy;
import org.aspectj.asm.IProgramElement;
import org.aspectj.asm.IRelationshipMap;
import org.aspectj.asm.internal.Relationship;
import org.aspectj.testing.XMLBasedAjcTestCase;
import org.aspectj.util.CharOperation;
import org.aspectj.weaver.World;
public class Ajc152Tests extends org.aspectj.testing.XMLBasedAjcTestCase {
// public void testverifyErrNoTypeCflowField_pr145693() {runTest("verifyErrNoTypeCflowField");}
// public void testBrokenIfArgsCflowAtAj_pr145018() { runTest("ataj crashing with cflow, if and args");}
// public void testItdCallingGenericMethod_pr145391() { runTest("itd calling generic method");}
// public void testItdCallingGenericMethod_pr145391_2() { runTest("itd calling generic method - 2");}
// public void testAdviceNotWovenAspectPath_pr147841() { runTest("advice not woven on aspectpath");}
// public void testClassCastForInvalidAnnotationValue_pr148537() { runTest("classcast annotation value");}
public void testFreakyNewArrayJoinpoint_pr148786() { runTest("freaky new array joinpoint"); }
public void testPrivilegeGeneric_pr148545() { runTest("nosuchmethoderror for privileged aspect");}
public void testPrivilegeGeneric_pr148545_2() { runTest("nosuchmethoderror for privileged aspect - 2");}
public void testUnknownAnnotationNPE() { runTest("NPE for unknown annotation");}
public void testDuplicateBridgeMethods_pr147801_1() { runTest("duplicate bridge methods");}
public void testPackageIgnoredForException_pr147701_1() { runTest("package for exception ignored");}
public void testPackageIgnoredForException_pr147701_2() { runTest("package for exception ignored - 2");}
public void testPackageIgnoredForException_pr147701_3() { runTest("package for exception ignored - 3");}
public void testBrokenAddSerialVersionUID_pr145950() {runTest("fails to discover Serializable");}
public void testNoUnnecessaryDeclarationOfThrownExcp_pr129282_1() {runTest("no unnecessary declaration of thrown exception warning - 1");}
public void testNoUnnecessaryDeclarationOfThrownExcp_pr129282_2() {runTest("no unnecessary declaration of thrown exception warning - 2");}
public void testNoUnnecessaryDeclarationOfThrownExcp_pr129282_3() {runTest("no unnecessary declaration of thrown exception warning - 3");}
public void testNoUnnecessaryDeclarationOfThrownExcp_pr129282_4() {runTest("no unnecessary declaration of thrown exception warning - 4");}
public void testNoUnnecessaryDeclarationOfThrownExcp_pr129282_5() {runTest("no unnecessary declaration of thrown exception warning - 5");}
public void testNoUnnecessaryDeclarationOfThrownExcp_pr129282_6() {runTest("no unnecessary declaration of thrown exception warning - 6");}
public void testNoUnnecessaryDeclarationOfThrownExcp_pr129282_7() {runTest("no unnecessary declaration of thrown exception warning - 7");}
public void testNoUnnecessaryDeclarationOfThrownExcp_pr129282_8() {runTest("no unnecessary declaration of thrown exception warning - 8");}
public void testNoUnnecessaryDeclarationOfThrownExcp_pr129282_9() {runTest("no unnecessary declaration of thrown exception warning - 9");}
public void testNoUnnecessaryDeclarationOfThrownExcp_pr129282_10() {runTest("no unnecessary declaration of thrown exception warning - 10");}
public void testAtAJVerificationError_pr144602() { runTest("atAJ perthis aspect verification error");}
public void testLTWAndGeneratingSUID_pr144465() { runTest("ltw with serialversionUID creation"); }
public void testAspects14PerSingleton_pr122253() { runTest("aspects14 - persingleton");}
public void testAspects14PerCflow_pr122253() { runTest("aspects14 - percflow");}
public void testAspects14PerThis_pr122253() { runTest("aspects14 - perthis");}
public void testAspects14PerTypeWithin_pr122253() { runTest("aspects14 - pertypewithin");}
public void testFunkyGenericErrorWithITDs_pr126355() { runTest("bizarre generic error with itds");}
public void testConcretizingAbstractMethods_pr142466() { runTest("aop.xml aspect inheriting but not concretizing abstract method");}
public void testConcretizingAbstractMethods_pr142466_2() { runTest("aop.xml aspect inheriting but not concretizing abstract method - 2");}
public void testComplexGenericDecl_pr137568() { runTest("complicated generics declaration");}
public void testItdOnInnerTypeOfGenericType_pr132349() { runTest("ITD on inner type of generic type");}
public void testItdOnInnerTypeOfGenericType_pr132349_2() { runTest("ITD on inner type of generic type - 2");}
public void testItdOnInnerTypeOfGenericType_pr132349_3() { runTest("ITD on inner type of generic type - 3");}
// public void testCovarianceAndDecp_pr128443_1() { runTest("covariance and decp - 1"); }
public void testLTWGeneratedAspectAbstractMethod_pr125480() { runTest("aop.xml aspect inheriting abstract method ");}
public void testLTWGeneratedAspectAbstractMethod_pr125480_2() { runTest("aop.xml aspect inheriting abstract method - code style");}
//public void testSuperITDExplosion_pr134425() { runTest("super ITDs");}
//public void testMisbehavingDeclareAnnotation_pr135865() { runTest("misbehaving declare annotation");}
//public void testMisbehavingDeclareAnnotation_pr135865_2() { runTest("misbehaving declare annotation - 2");}
public void testCompletelyBrokenAopConcretization_pr142165_1() { runTest("broken concretization");}
public void testCompletelyBrokenAopConcretization_pr142165_2() { runTest("broken concretization - 2");}
public void testCompletelyBrokenAopConcretization_pr142165_3() { runTest("broken concretization - 3");}
public void testVerifyErrorLTW_pr135068() { runTest("ltw verifyerror");}
public void testVerifyErrorLTW_pr135068_2() { runTest("ltw verifyerror - 2");}
public void testVerifyErrorLTW_pr135068_3() { runTest("ltw verifyerror - 3");}
public void testVerifyErrorLTW_pr135068_4() { runTest("ltw verifyerror - 4");}
public void testVerifyErrorForComplexCflow_pr136026() { runTest("verifyerror");}
public void testVerifyErrorForComplexCflow_pr136026_2() { runTest("verifyerror - 2");}
public void testAnnotationsAndGenericsBCException_pr129704() { runTest("annotations and generics leading to BCException");}
public void testMethodTooBigAfterWeaving_pr138384() { runTest("method too big"); }
public void testNotAtWithincode_pr138158_1() { runTest("not at withincode - 1");}
public void testNotAtWithincode_pr138158_2() { runTest("not at withincode - 2");}
public void testNotAtWithincode_pr138158_3() { runTest("not at within - 3");}
public void testNpeOnDup_pr138143() { runTest("npe on duplicate method with ataj");}
public void testPointcutsAndGenerics_pr137496_1() { runTest("pointcuts and generics - B");}
public void testPointcutsAndGenerics_pr137496_2() { runTest("pointcuts and generics - D");}
public void testPointcutsAndGenerics_pr137496_3() { runTest("pointcuts and generics - E");}
public void testPointcutsAndGenerics_pr137496_4() { runTest("pointcuts and generics - F");}
public void testPointcutsAndGenerics_pr137496_5() { runTest("pointcuts and generics - G");}
public void testPointcutsAndGenerics_pr137496_6() { runTest("pointcuts and generics - H");}
public void testAspectLibrariesAndASM_pr135001() { runTest("aspect libraries and asm");}
public void testStackOverflow_pr136258() { runTest("stack overflow");}
public void testIncorrectOverridesEvaluation13() { runTest("incorrect overrides evaluation - 1.3"); }
public void testIncorrectOverridesEvaluation15() { runTest("incorrect overrides evaluation - 1.5"); }
public void testAtWithinCodeBug_pr138798() { runTest("atWithinCodeBug"); }
public void testReferencePCutInDeclareWarning_pr138215() { runTest("Reference pointcut fails inside @DeclareWarning");}
public void testReferencePCutInPerClause_pr138219() { runTest("Can't use a FQ Reference pointcut in any pointcut expression referenced by a per-clause");}
public void testReferencePCutInPerClause_pr130722() { runTest("FQ Reference pointcut from perclause ref pc"); }
public void testDoubleAnnotationMatching_pr138223() { runTest("Double at annotation matching (no binding)");}
public void testSuperCallsInAtAspectJAdvice_pr139749() { runTest("Super calls in @AspectJ advice");}
public void testNoClassCastExceptionWithPerThis_pr138286() { runTest("No ClassCastException with perThis");}
public void testGenericAspectHierarchyWithBounds_pr147845() { runTest("Generic abstract aspect hierarchy with bounds"); }
public void testJRockitBooleanReturn_pr148007() { runTest("jrockit boolean fun");}
public void testJRockitBooleanReturn2_pr148007() { runTest("jrockit boolean fun (no aspects)");}
public void testSyntheticAjcMembers_pr147711() { runTest("synthetic ajc$ members"); }
public void testDeclareAtMethodRelationship_pr143924() {
//AsmManager.setReporting("c:/debug.txt",true,true,true,true);
runTest("declare @method relationship");
IHierarchy top = AsmManager.getDefault().getHierarchy();
// get the IProgramElements corresponding to the different code entries
IProgramElement decam = top.findElementForLabel(top.getRoot(),
IProgramElement.Kind.DECLARE_ANNOTATION_AT_METHOD,
"declare @method: * debit(..) : @Secured(role = \"supervisor\")");
assertNotNull("Couldn't find 'declare @method' element in the tree",decam);
IProgramElement method = top.findElementForLabel(top.getRoot(),
IProgramElement.Kind.METHOD,"debit(java.lang.String,long)");
assertNotNull("Couldn't find the 'debit(String,long)' method element in the tree",method);
List matches = AsmManager.getDefault().getRelationshipMap().get(decam);
assertNotNull("'declare @method' should have some relationships but does not",matches);
assertTrue("'declare @method' should have one relationships but has " + matches.size(),matches.size()==1);
List matchesTargets = ((Relationship)matches.get(0)).getTargets();
assertTrue("'declare @method' should have one targets but has" + matchesTargets.size(),matchesTargets.size()==1);
IProgramElement target = AsmManager.getDefault().getHierarchy().findElementForHandle((String)matchesTargets.get(0));
assertEquals("target of relationship should be the 'debit(java.lang.String,long)' method but is IPE with label "
+ target.toLabelString(),method,target);
// check that the debit method has an annotated by relationship with the declare @method
matches = AsmManager.getDefault().getRelationshipMap().get(method);
assertNotNull("'debit(java.lang.String,long)' should have some relationships but does not",matches);
assertTrue("'debit(java.lang.String,long)' should have one relationships but has " + matches.size(),matches.size()==1);
matchesTargets = ((Relationship)matches.get(0)).getTargets();
assertTrue("'debit(java.lang.String,long)' should have one targets but has" + matchesTargets.size(),matchesTargets.size()==1);
target = AsmManager.getDefault().getHierarchy().findElementForHandle((String)matchesTargets.get(0));
assertEquals("target of relationship should be the 'declare @method' ipe but is IPE with label "
+ target.toLabelString(),decam,target);
}
// this next one reported as a bug by Rob Harrop, but I can't reproduce the failure yet...
//public void testAtAspectWithReferencePCPerClause_pr138220() { runTest("@Aspect with reference pointcut in perclause");}
public void testJarChecking_pr137235_1() { runTest("directory with .jar extension: source and outjar"); }
public void testJarChecking_pr137235_2() { runTest("directory with .jar extension"); }
public void testMakePreMethodNPE_pr136393() { runTest("NPE in makePreMethod");}
public void testGetParameterHandles_pr141730() {
runTest("new IProgramElement handle methods");
checkParametersForIPE("intMethod(int)",IProgramElement.Kind.METHOD,"I",true);
checkParametersForIPE("stringMethod(java.lang.String)",IProgramElement.Kind.METHOD,"Ljava/lang/String;",true);
checkParametersForIPE("myClassMethod(MyClass)",IProgramElement.Kind.METHOD,"LMyClass;",true);
checkParametersForIPE("genericMethod(java.util.List<java.lang.String>)",IProgramElement.Kind.METHOD,"Pjava/util/List<Ljava/lang/String;>;",true);
checkParametersForIPE("genericMethod2(MyGenericClass<java.lang.String,MyClass>)",IProgramElement.Kind.METHOD,"PMyGenericClass<Ljava/lang/String;LMyClass;>;",true);
checkParametersForIPE("main(java.lang.String[])",IProgramElement.Kind.METHOD,"[Ljava/lang/String;",true);
checkParametersForIPE("multiMethod(java.lang.String[][])",IProgramElement.Kind.METHOD,"[[Ljava/lang/String;",true);
checkParametersForIPE("intArray(int[])",IProgramElement.Kind.METHOD,"[I",true);
IHierarchy top = AsmManager.getDefault().getHierarchy();
IProgramElement twoArgsMethod = top.findElementForLabel(
top.getRoot(),IProgramElement.Kind.METHOD,"twoArgsMethod(int,java.lang.String)");
assertNotNull("Couldn't find 'twoArgsMethod(int,java.lang.String)' element in the tree",twoArgsMethod);
List l = twoArgsMethod.getParameterSignatures();
assertEquals("",((char[])l.get(0))[0],'I');
boolean eq = CharOperation.equals(((char[])l.get(1)),"Ljava/lang/String;".toCharArray());
assertTrue("expected parameter to be 'Ljava/lang/String;' but found '" +
new String(((char[])l.get(1))) + "'",eq);
}
public void testGetParameterTypes_pr141730() {
runTest("new IProgramElement handle methods");
checkParametersForIPE("intMethod(int)",IProgramElement.Kind.METHOD,"int",false);
checkParametersForIPE("stringMethod(java.lang.String)",IProgramElement.Kind.METHOD,"java.lang.String",false);
checkParametersForIPE("myClassMethod(MyClass)",IProgramElement.Kind.METHOD,"MyClass",false);
checkParametersForIPE("genericMethod(java.util.List<java.lang.String>)",IProgramElement.Kind.METHOD,"java.util.List<java.lang.String>",false);
checkParametersForIPE("genericMethod2(MyGenericClass<java.lang.String,MyClass>)",IProgramElement.Kind.METHOD,"MyGenericClass<java.lang.String,MyClass>",false);
checkParametersForIPE("main(java.lang.String[])",IProgramElement.Kind.METHOD,"java.lang.String[]",false);
checkParametersForIPE("multiMethod(java.lang.String[][])",IProgramElement.Kind.METHOD,"java.lang.String[][]",false);
checkParametersForIPE("intArray(int[])",IProgramElement.Kind.METHOD,"int[]",false);
}
public void testToSignatureString_pr141730() {
runTest("new IProgramElement handle methods");
checkSignatureOfIPE("main(java.lang.String[])",IProgramElement.Kind.METHOD);
checkSignatureOfIPE("C",IProgramElement.Kind.CLASS);
checkSignatureOfIPE("C()",IProgramElement.Kind.CONSTRUCTOR);
checkSignatureOfIPE("method()",IProgramElement.Kind.METHOD);
checkSignatureOfIPE("p()",IProgramElement.Kind.POINTCUT);
checkSignatureOfIPE("before(): p..",IProgramElement.Kind.ADVICE,"before()");
checkSignatureOfIPE("MyClass.method()",IProgramElement.Kind.INTER_TYPE_METHOD);
checkSignatureOfIPE("multiMethod(java.lang.String[][])",IProgramElement.Kind.METHOD);
checkSignatureOfIPE("intArray(int[])",IProgramElement.Kind.METHOD);
checkSignatureOfIPE("MyClass.MyClass()",IProgramElement.Kind.INTER_TYPE_CONSTRUCTOR);
}
// if not filling in the model for aspects contained in jar files then
// want to ensure that the relationship map is correct and has nodes
// which can be used in AJDT - ensure no NPE occurs for the end of
// the relationship with aspectpath
public void testAspectPathRelWhenNotFillingInModel_pr141730() {
World.createInjarHierarchy = false;
try {
runTest("ensure aspectpath injar relationships are correct when not filling in model");
// expecting:
// sourceOfRelationship main in MyFoo.java
// relationship advised by
// target MyBar.aj
//
// and
//
// sourceOfRelationship MyBar.aj
// relationship advises
// target main in MyFoo.java
IHierarchy top = AsmManager.getDefault().getHierarchy();
IRelationshipMap asmRelMap = AsmManager.getDefault().getRelationshipMap();
assertEquals("expected two sources of relationships but only found "
+ asmRelMap.getEntries().size(),2,asmRelMap.getEntries().size());
for (Iterator iter = asmRelMap.getEntries().iterator(); iter.hasNext();) {
String sourceOfRelationship = (String) iter.next();
IProgramElement ipe = top.findElementForHandle(sourceOfRelationship);
List relationships = asmRelMap.get(ipe);
if (ipe.getName().equals("MyBar.aj")) {
assertEquals("expected MyBar.aj to have one relationships but found "
+ relationships.size(),1,relationships.size());
Relationship rel = (Relationship)relationships.get(0);
assertEquals("expected relationship to be 'advises' but was "
+ rel.getName(), "advises", rel.getName());
List targets = rel.getTargets();
assertEquals("expected one target but found " + targets.size(),1,targets.size());
IProgramElement link = top.findElementForHandle((String)targets.get(0));
assertEquals("expected target 'method-call(void foo.MyFoo.main())' but target " + link.getName(),
"method-call(void foo.MyFoo.main())",link.getName());
String fileName = link.getSourceLocation().getSourceFile().toString();
assertTrue("expected 'main' to be in class MyFoo.java but found it " +
"in " + fileName,fileName.indexOf("MyFoo.java") != -1);
} else if (ipe.getName().equals("method-call(void foo.MyFoo.main())")) {
String fileName = ipe.getSourceLocation().getSourceFile().toString();
assertTrue("expected 'method-call(void foo.MyFoo.main())' to be in " +
"class MyFoo.java but found it in"
+ fileName,fileName.indexOf("MyFoo.java") != -1);
assertEquals("expected 'method-call(void foo.MyFoo.main())' " +
"to have one relationships but found "
+ relationships.size(),1,relationships.size());
Relationship rel = (Relationship)relationships.get(0);
assertEquals("expected relationship to be 'advised by' but was "
+ rel.getName(), "advised by", rel.getName());
List targets = rel.getTargets();
assertEquals("expected one target but found " + targets.size(),1,targets.size());
IProgramElement link = top.findElementForHandle((String)targets.get(0));
assertEquals("expected target 'MyBar.aj' but target " + link.getName(),
"MyBar.aj",link.getName());
} else {
fail("unexpected element " + ipe.getName() + " in the relationship map");
}
}
} finally {
World.createInjarHierarchy = true;
}
}
// if not filling in the model for classes contained in jar files then
// want to ensure that the relationship map is correct and has nodes
// which can be used in AJDT - ensure no NPE occurs for the end of
// the relationship with inpath
public void testNoNPEWithInpathWhenNotFillingInModel_pr141730() {
World.createInjarHierarchy = false;
try {
runTest("ensure inpath injar relationships are correct when not filling in model");
// the aspect used for this test has advice, declare parents, deow,
// and declare @type, @constructor, @field and @method. We only expect
// there to be relationships in the map for declare parents and declare @type
// (provided the model isn't being filled in) because the logic in the other
// addXXXRelationship methods use AspectJElementHierarchy.findElementForType().
// This method which returns null because there is no such ipe. The relationship is
// therefore not added to the model. Adding declare @type and declare parents
// uses AspectJElementHierarchy.findElementForHandle() which returns the file
// node ipe if it can't find one for the given handle. Therefore the relationships
// are added against the file node. Before change to using ipe's to create handles
// we also had the deow relationship, however, now we don't because this also
// uses findElementForType to find the targetNode which in the inpath case is null.
// just check that the number of entries is what we expect:
// We expect 3 (the declare @type and declare parents statements plus the filenode)
IRelationshipMap relMap = AsmManager.getDefault().getRelationshipMap();
assertEquals("expected 3 entries in the relationship map but found "
+ relMap.getEntries().size(), 3, relMap.getEntries().size());
} finally {
World.createInjarHierarchy = true;
}
}
public void testPCDInClassAppearsInModel_pr148027() {
// only want to test that its there if we're creating the uses pointcut
// relationship. This should be addressed by pr148027
if (!AsmHierarchyBuilder.shouldAddUsesPointcut) return;
World.createInjarHierarchy = false;
try {
runTest("ensure pcd declare in class appears in model");
IHierarchy top = AsmManager.getDefault().getHierarchy();
IProgramElement pcd = top.findElementForLabel(top.getRoot(),IProgramElement.Kind.POINTCUT,"pointcutInClass()");
IRelationshipMap relMap = AsmManager.getDefault().getRelationshipMap();
List relationships = relMap.get(pcd);
assertNotNull("expected relationships for pointcut " + pcd.toLinkLabelString()
+ " but didn't", relationships);
pcd = top.findElementForLabel(top.getRoot(),IProgramElement.Kind.POINTCUT,"pointcutInAspect()");
relationships = relMap.get(pcd);
assertNotNull("expected relationships for pointcut " + pcd.toLinkLabelString()
+ " but didn't", relationships);
} finally {
World.createInjarHierarchy = true;
}
}
// public void testFunkyGenericErrorWithITDs_pr126355_2() {
// runTest("bizarre generic error with itds - 2");
// // public class Pair<F,S> affected by pertarget aspect
// GenericsTests.verifyClassSignature(ajc,"Pair","<F:Ljava/lang/Object;S:Ljava/lang/Object;>Ljava/lang/Object;LIdempotentCache$ajcMightHaveAspect;;");
// }
public void testNoAspects(){
// setSystemProperty(WeavingAdaptor.WEAVING_ADAPTOR_VERBOSE,"true");
runTest("Ensure no weaving without included aspects");
}
public void testWeaveinfoMessages (){
runTest("weaveinfo messages with include and exclude");
}
// tests that can't be included for some reason
// Not valid whilst the ajc compiler forces debug on (ignores -g:none) - it will be green but is invalid, trust me
// public void testLongWindedMessages_pr129408() { runTest("long winded ataj messages");}
// ---------------- helper methods ---------------
private void checkParametersForIPE(String ipeLabel, IProgramElement.Kind kind, String expectedParm, boolean getHandles) {
IHierarchy top = AsmManager.getDefault().getHierarchy();
IProgramElement ipe = top.findElementForLabel(top.getRoot(),kind,ipeLabel);
assertNotNull("Couldn't find '" + ipeLabel + "' element in the tree",ipe);
List l = new ArrayList();
if (getHandles) {
l = ipe.getParameterSignatures();
} else {
l = ipe.getParameterTypes();
}
boolean eq = CharOperation.equals(((char[])l.get(0)),expectedParm.toCharArray());
assertTrue("expected parameter to be '" + expectedParm + "' but found '" +
new String(((char[])l.get(0))) + "'",eq);
}
private void checkSignatureOfIPE(String ipeLabel, IProgramElement.Kind kind) {
checkSignatureOfIPE(ipeLabel,kind,ipeLabel);
}
private void checkSignatureOfIPE(String ipeLabel, IProgramElement.Kind kind, String expectedSig) {
IHierarchy top = AsmManager.getDefault().getHierarchy();
IProgramElement ipe = top.findElementForLabel(
top.getRoot(),kind,ipeLabel);
assertNotNull("Couldn't find '" + ipeLabel + "' element in the tree",ipe);
assertEquals("expected signature to be '"+ expectedSig + "' but was " +
ipe.toSignatureString(true),expectedSig,ipe.toSignatureString(true));
}
/////////////////////////////////////////
public static Test suite() {
return XMLBasedAjcTestCase.loadSuite(Ajc152Tests.class);
}
protected File getSpecFile() {
return new File("../tests/src/org/aspectj/systemtest/ajc152/ajc152.xml");
}
}
|
148,727 |
Bug 148727 Can't call synthetic aspectOf method on aspect in library jar
|
Separate compilation of the following program breaks on 1.5.2rc1 because of the recent change to marking aspect methods as synthetic: public aspect Asp { } public class Client { public static void main(String argz[]) { System.out.println("Can call aspectOf? "+Asp.aspectOf()); } } C:\devel\scratch\synthetic>ajc -classpath asp.jar;%CLASSPATH% Client.java C:\devel\scratch\synthetic\Client.java:3 [error] The method aspectOf() is undefi ned for the type Asp System.out.println("Can call aspectOf? "+Asp.aspectOf()); 1 error C:\devel\scratch\synthetic>javac -classpath asp.jar;%CLASSPATH% Client.java Client.java:3: cannot find symbol symbol : method aspectOf() location: class Asp System.out.println("Can call aspectOf? "+Asp.aspectOf()); ^ 1 error Clearly it's vital that external users of a library be able to call API methods like aspectOf on library aspects. This works: C:\devel\scratch\synthetic>ajc *.aj Client.java C:\devel\scratch\synthetic>java Client Can call aspectOf? Asp@b89838 Patch with test integrated into CVS tree to follow...
|
resolved fixed
|
21e06a6
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-06-28T09:16:01Z | 2006-06-26T19:26:40Z |
weaver/src/org/aspectj/weaver/NameMangler.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.bcel.LazyClassGen;
public class NameMangler {
private NameMangler() {
throw new RuntimeException("static");
}
public static final char[] AJC_DOLLAR_PREFIX = {'a', 'j', 'c','$'};
public static final char[] CLINIT={'<','c','l','i','n','i','t','>'};
public static final String PREFIX = "ajc$";
public static final char[] INIT = {'<','i','n','i','t','>'};
public static final String ITD_PREFIX = PREFIX + "interType$";
public static final char[] METHOD_ASPECTOF = {'a', 's', 'p','e','c','t','O','f'};
public static final char[] METHOD_HASASPECT = {'h', 'a', 's','A','s','p','e','c','t'};
public static final char[] STATIC_INITIALIZER = {'<', 'c', 'l','i','n','i','t','>'};
public static final String CFLOW_STACK_TYPE = "org.aspectj.runtime.internal.CFlowStack";
public static final String CFLOW_COUNTER_TYPE="org.aspectj.runtime.internal.CFlowCounter";
public static final String SOFT_EXCEPTION_TYPE = "org.aspectj.lang.SoftException";
public static final String PERSINGLETON_FIELD_NAME = PREFIX + "perSingletonInstance";
public static final String PERCFLOW_FIELD_NAME = PREFIX + "perCflowStack";
//public static final String PERTHIS_FIELD_NAME = PREFIX + "perSingletonInstance";
// -----
public static final String PERCFLOW_PUSH_METHOD = PREFIX + "perCflowPush";
public static final String PEROBJECT_BIND_METHOD = PREFIX + "perObjectBind";
// PTWIMPL Method and field names
public static final String PERTYPEWITHIN_GETINSTANCE_METHOD = PREFIX + "getInstance";
public static final String PERTYPEWITHIN_CREATEASPECTINSTANCE_METHOD = PREFIX + "createAspectInstance";
public static final String PERTYPEWITHIN_WITHINTYPEFIELD = PREFIX + "withinType";
public static final String AJC_PRE_CLINIT_NAME = PREFIX + "preClinit";
public static final String AJC_POST_CLINIT_NAME = PREFIX + "postClinit";
public static final String INITFAILURECAUSE_FIELD_NAME = PREFIX + "initFailureCause";
public static boolean isSyntheticMethod(String methodName, boolean declaredInAspect) {
if (methodName.startsWith(PREFIX)) {
// it's synthetic unless it is an advice method
if (methodName.startsWith("ajc$before") ||
methodName.startsWith("ajc$after")) {
return false;
} else if (methodName.startsWith("ajc$around")) {
// around advice method is not synthetic, but generated proceed is...
return (methodName.endsWith("proceed"));
} else if (methodName.startsWith("ajc$interMethod$")) {
return false; // body of an itd-m
}
return true;
}
else if (methodName.indexOf("_aroundBody") != -1) {
return true;
}
else if (declaredInAspect) {
if (methodName.equals("aspectOf") || methodName.equals("hasAspect")) {
return true;
}
}
return false;
}
public static String perObjectInterfaceGet(UnresolvedType aspectType) {
return makeName(aspectType.getNameAsIdentifier(), "perObjectGet");
}
public static String perObjectInterfaceSet(UnresolvedType aspectType) {
return makeName(aspectType.getNameAsIdentifier(), "perObjectSet");
}
public static String perObjectInterfaceField(UnresolvedType aspectType) {
return makeName(aspectType.getNameAsIdentifier(), "perObjectField");
}
// PTWIMPL method names that must include aspect type
public static String perTypeWithinFieldForTarget(UnresolvedType aspectType) {
return makeName(aspectType.getNameAsIdentifier(), "ptwAspectInstance");
}
public static String perTypeWithinLocalAspectOf(UnresolvedType aspectType) {
return makeName(aspectType.getNameAsIdentifier(), "localAspectOf");
}
public static String itdAtDeclareParentsField(UnresolvedType aspectType, UnresolvedType itdType) {
return makeName(aspectType.getNameAsIdentifier(), itdType.getNameAsIdentifier());
}
public static String privilegedAccessMethodForMethod(String name, UnresolvedType objectType, UnresolvedType aspectType) {
return makeName("privMethod", aspectType.getNameAsIdentifier(),
objectType.getNameAsIdentifier(), name);
}
public static String privilegedAccessMethodForFieldGet(String name, UnresolvedType objectType, UnresolvedType aspectType) {
return makeName("privFieldGet", aspectType.getNameAsIdentifier(),
objectType.getNameAsIdentifier(), name);
}
public static String privilegedAccessMethodForFieldSet(String name, UnresolvedType objectType, UnresolvedType aspectType) {
return makeName("privFieldSet", aspectType.getNameAsIdentifier(),
objectType.getNameAsIdentifier(), name);
}
public static String inlineAccessMethodForMethod(String name, UnresolvedType objectType, UnresolvedType aspectType) {
return makeName("inlineAccessMethod", aspectType.getNameAsIdentifier(),
objectType.getNameAsIdentifier(), name);
}
public static String inlineAccessMethodForFieldGet(String name, UnresolvedType objectType, UnresolvedType aspectType) {
return makeName("inlineAccessFieldGet", aspectType.getNameAsIdentifier(),
objectType.getNameAsIdentifier(), name);
}
public static String inlineAccessMethodForFieldSet(String name, UnresolvedType objectType, UnresolvedType aspectType) {
return makeName("inlineAccessFieldSet", aspectType.getNameAsIdentifier(),
objectType.getNameAsIdentifier(), name);
}
/**
* The name of methods corresponding to advice declarations
* Of the form: "ajc$[AdviceKind]$[AspectName]$[NumberOfAdviceInAspect]$[PointcutHash]"
*/
public static String adviceName(String nameAsIdentifier, AdviceKind kind, int adviceSeqNumber,int pcdHash) {
String newname = makeName(
kind.getName(),
nameAsIdentifier,
Integer.toString(adviceSeqNumber),
Integer.toHexString(pcdHash));
return newname;
}
/**
* This field goes on top-most implementers of the interface the field
* is declared onto
*/
public static String interFieldInterfaceField(UnresolvedType aspectType, UnresolvedType interfaceType, String name) {
return makeName("interField", aspectType.getNameAsIdentifier(),
interfaceType.getNameAsIdentifier(), name);
}
/**
* This instance method goes on the interface the field is declared onto
* as well as its top-most implementors
*/
public static String interFieldInterfaceSetter(UnresolvedType aspectType, UnresolvedType interfaceType, String name) {
return makeName("interFieldSet", aspectType.getNameAsIdentifier(),
interfaceType.getNameAsIdentifier(), name);
}
/**
* This instance method goes on the interface the field is declared onto
* as well as its top-most implementors
*/
public static String interFieldInterfaceGetter(UnresolvedType aspectType, UnresolvedType interfaceType, String name) {
return makeName("interFieldGet", aspectType.getNameAsIdentifier(),
interfaceType.getNameAsIdentifier(), name);
}
/**
* This static method goes on the aspect that declares the inter-type field
*/
public static String interFieldSetDispatcher(UnresolvedType aspectType, UnresolvedType onType, String name) {
return makeName("interFieldSetDispatch", aspectType.getNameAsIdentifier(),
onType.getNameAsIdentifier(), name);
}
/**
* This static method goes on the aspect that declares the inter-type field
*/
public static String interFieldGetDispatcher(UnresolvedType aspectType, UnresolvedType onType, String name) {
return makeName("interFieldGetDispatch", aspectType.getNameAsIdentifier(),
onType.getNameAsIdentifier(), name);
}
/**
* This field goes on the class the field
* is declared onto
*/
public static String interFieldClassField(int modifiers, UnresolvedType aspectType, UnresolvedType classType, String name) {
if (Modifier.isPublic(modifiers)) return name;
//??? might want to handle case where aspect and class are in same package similar to public
return makeName("interField", makeVisibilityName(modifiers, aspectType), name);
}
// /**
// * This static method goes on the aspect that declares the inter-type field
// */
// public static String classFieldSetDispatcher(UnresolvedType aspectType, UnresolvedType classType, String name) {
// return makeName("interFieldSetDispatch", aspectType.getNameAsIdentifier(),
// classType.getNameAsIdentifier(), name);
// }
//
// /**
// * This static method goes on the aspect that declares the inter-type field
// */
// public static String classFieldGetDispatcher(UnresolvedType aspectType, UnresolvedType classType, String name)
// {
// return makeName(
// "interFieldGetDispatch",
// aspectType.getNameAsIdentifier(),
// classType.getNameAsIdentifier(),
// name);
// }
/**
* This static void method goes on the aspect that declares the inter-type field and is called
* from the appropriate place (target's initializer, or clinit, or topmost implementer's inits),
* to initialize the field;
*/
public static String interFieldInitializer(UnresolvedType aspectType, UnresolvedType classType, String name)
{
return makeName(
"interFieldInit",
aspectType.getNameAsIdentifier(),
classType.getNameAsIdentifier(),
name);
}
// ----
/**
* This method goes on the target type of the inter-type method. (and possibly the topmost-implemeters,
* if the target type is an interface)
*/
public static String interMethod(int modifiers, UnresolvedType aspectType, UnresolvedType classType, String name)
{
if (Modifier.isPublic(modifiers)) return name;
//??? might want to handle case where aspect and class are in same package similar to public
return makeName("interMethodDispatch2", makeVisibilityName(modifiers, aspectType), name);
}
/**
* This static method goes on the declaring aspect of the inter-type method.
*/
public static String interMethodDispatcher(UnresolvedType aspectType, UnresolvedType classType, String name)
{
return makeName("interMethodDispatch1", aspectType.getNameAsIdentifier(),
classType.getNameAsIdentifier(), name);
}
/**
* This static method goes on the declaring aspect of the inter-type method.
*/
public static String interMethodBody(UnresolvedType aspectType, UnresolvedType classType, String name)
{
return makeName("interMethod", aspectType.getNameAsIdentifier(),
classType.getNameAsIdentifier(), name);
}
// ----
/**
* This static method goes on the declaring aspect of the inter-type constructor.
*/
public static String preIntroducedConstructor(
UnresolvedType aspectType,
UnresolvedType targetType)
{
return makeName("preInterConstructor", aspectType.getNameAsIdentifier(),
targetType.getNameAsIdentifier());
}
/**
* This static method goes on the declaring aspect of the inter-type constructor.
*/
public static String postIntroducedConstructor(
UnresolvedType aspectType,
UnresolvedType targetType)
{
return makeName("postInterConstructor", aspectType.getNameAsIdentifier(),
targetType.getNameAsIdentifier());
}
// ----
/**
* This static method goes on the target class of the inter-type method.
*/
public static String superDispatchMethod(UnresolvedType classType, String name)
{
return makeName("superDispatch",
classType.getNameAsIdentifier(), name);
}
/**
* This static method goes on the target class of the inter-type method.
*/
public static String protectedDispatchMethod(UnresolvedType classType, String name)
{
return makeName("protectedDispatch",
classType.getNameAsIdentifier(), name);
}
// ----
private static String makeVisibilityName(int modifiers, UnresolvedType aspectType) {
if (Modifier.isPrivate(modifiers)) {
return aspectType.getOutermostType().getNameAsIdentifier();
} else if (Modifier.isProtected(modifiers)) {
throw new RuntimeException("protected inter-types not allowed");
} else if (Modifier.isPublic(modifiers)) {
return "";
} else {
return aspectType.getPackageNameAsIdentifier();
}
}
private static String makeName(String s1, String s2) {
return "ajc$" + s1 + "$" + s2;
}
public static String makeName(String s1, String s2, String s3) {
return "ajc$" + s1 + "$" + s2 + "$" + s3;
}
public static String makeName(String s1, String s2, String s3, String s4) {
return "ajc$" + s1 + "$" + s2 + "$" + s3 + "$" + s4;
}
public static String cflowStack(CrosscuttingMembers xcut) {
return makeName("cflowStack", Integer.toHexString(xcut.getCflowEntries().size()));
}
public static String cflowCounter(CrosscuttingMembers xcut) {
return makeName("cflowCounter",Integer.toHexString(xcut.getCflowEntries().size()));
}
public static String makeClosureClassName(
UnresolvedType enclosingType,
int index)
{
return enclosingType.getName() + "$AjcClosure" + index;
}
public static String aroundCallbackMethodName(
Member shadowSig,
LazyClassGen enclosingType)
{
String ret =
shadowSig.getExtractableName()
+ "_aroundBody"
+ enclosingType.getNewGeneratedNameTag();
return ret;
}
public static String proceedMethodName(String adviceMethodName) {
return adviceMethodName + "proceed";
}
}
|
148,972 |
Bug 148972 problems with binary weaving declare parents in mixed environment.
|
These have been reported to me on a large system doing some intricate weaving where some classes are 1.2, some 1.4, some 1.5 and the VM is 1.5. Binary weaving declare parents sometimes refuses to allow the modification of the hierarchy because it sees a clash between two methods when there is none. The two cases I'm fixing are: 1. sometimes the signatures of the return types differ with the '.' or '/' problem (fix == be consistent) 2. sometimes the syntheticness of the methods in the relationship isn't determined correctly
|
resolved fixed
|
2f2f568
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-06-28T11:44:10Z | 2006-06-28T10:20:00Z |
tests/src/org/aspectj/systemtest/ajc152/Ajc152Tests.java
|
/*******************************************************************************
* Copyright (c) 2006 IBM
* 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.ajc152;
import java.io.File;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import junit.framework.Test;
import org.aspectj.ajdt.internal.core.builder.AsmHierarchyBuilder;
import org.aspectj.asm.AsmManager;
import org.aspectj.asm.IHierarchy;
import org.aspectj.asm.IProgramElement;
import org.aspectj.asm.IRelationshipMap;
import org.aspectj.asm.internal.Relationship;
import org.aspectj.testing.XMLBasedAjcTestCase;
import org.aspectj.util.CharOperation;
import org.aspectj.weaver.World;
public class Ajc152Tests extends org.aspectj.testing.XMLBasedAjcTestCase {
// public void testverifyErrNoTypeCflowField_pr145693() {runTest("verifyErrNoTypeCflowField");}
// public void testBrokenIfArgsCflowAtAj_pr145018() { runTest("ataj crashing with cflow, if and args");}
// public void testItdCallingGenericMethod_pr145391() { runTest("itd calling generic method");}
// public void testItdCallingGenericMethod_pr145391_2() { runTest("itd calling generic method - 2");}
// public void testAdviceNotWovenAspectPath_pr147841() { runTest("advice not woven on aspectpath");}
// public void testClassCastForInvalidAnnotationValue_pr148537() { runTest("classcast annotation value");}
public void testSeparateCallAspectOf_pr148727() { runTest("separate compilation calling aspectOf and hasAspect"); }
public void testIntegratedCallAspectOf_pr148727() { runTest("integrated compilation calling aspectOf and hasAspect"); }
public void testFreakyNewArrayJoinpoint_pr148786() { runTest("freaky new array joinpoint"); }
public void testPrivilegeGeneric_pr148545() { runTest("nosuchmethoderror for privileged aspect");}
public void testPrivilegeGeneric_pr148545_2() { runTest("nosuchmethoderror for privileged aspect - 2");}
public void testUnknownAnnotationNPE() { runTest("NPE for unknown annotation");}
public void testDuplicateBridgeMethods_pr147801_1() { runTest("duplicate bridge methods");}
public void testPackageIgnoredForException_pr147701_1() { runTest("package for exception ignored");}
public void testPackageIgnoredForException_pr147701_2() { runTest("package for exception ignored - 2");}
public void testPackageIgnoredForException_pr147701_3() { runTest("package for exception ignored - 3");}
public void testBrokenAddSerialVersionUID_pr145950() {runTest("fails to discover Serializable");}
public void testNoUnnecessaryDeclarationOfThrownExcp_pr129282_1() {runTest("no unnecessary declaration of thrown exception warning - 1");}
public void testNoUnnecessaryDeclarationOfThrownExcp_pr129282_2() {runTest("no unnecessary declaration of thrown exception warning - 2");}
public void testNoUnnecessaryDeclarationOfThrownExcp_pr129282_3() {runTest("no unnecessary declaration of thrown exception warning - 3");}
public void testNoUnnecessaryDeclarationOfThrownExcp_pr129282_4() {runTest("no unnecessary declaration of thrown exception warning - 4");}
public void testNoUnnecessaryDeclarationOfThrownExcp_pr129282_5() {runTest("no unnecessary declaration of thrown exception warning - 5");}
public void testNoUnnecessaryDeclarationOfThrownExcp_pr129282_6() {runTest("no unnecessary declaration of thrown exception warning - 6");}
public void testNoUnnecessaryDeclarationOfThrownExcp_pr129282_7() {runTest("no unnecessary declaration of thrown exception warning - 7");}
public void testNoUnnecessaryDeclarationOfThrownExcp_pr129282_8() {runTest("no unnecessary declaration of thrown exception warning - 8");}
public void testNoUnnecessaryDeclarationOfThrownExcp_pr129282_9() {runTest("no unnecessary declaration of thrown exception warning - 9");}
public void testNoUnnecessaryDeclarationOfThrownExcp_pr129282_10() {runTest("no unnecessary declaration of thrown exception warning - 10");}
public void testAtAJVerificationError_pr144602() { runTest("atAJ perthis aspect verification error");}
public void testLTWAndGeneratingSUID_pr144465() { runTest("ltw with serialversionUID creation"); }
public void testAspects14PerSingleton_pr122253() { runTest("aspects14 - persingleton");}
public void testAspects14PerCflow_pr122253() { runTest("aspects14 - percflow");}
public void testAspects14PerThis_pr122253() { runTest("aspects14 - perthis");}
public void testAspects14PerTypeWithin_pr122253() { runTest("aspects14 - pertypewithin");}
public void testFunkyGenericErrorWithITDs_pr126355() { runTest("bizarre generic error with itds");}
public void testConcretizingAbstractMethods_pr142466() { runTest("aop.xml aspect inheriting but not concretizing abstract method");}
public void testConcretizingAbstractMethods_pr142466_2() { runTest("aop.xml aspect inheriting but not concretizing abstract method - 2");}
public void testComplexGenericDecl_pr137568() { runTest("complicated generics declaration");}
public void testItdOnInnerTypeOfGenericType_pr132349() { runTest("ITD on inner type of generic type");}
public void testItdOnInnerTypeOfGenericType_pr132349_2() { runTest("ITD on inner type of generic type - 2");}
public void testItdOnInnerTypeOfGenericType_pr132349_3() { runTest("ITD on inner type of generic type - 3");}
// public void testCovarianceAndDecp_pr128443_1() { runTest("covariance and decp - 1"); }
public void testLTWGeneratedAspectAbstractMethod_pr125480() { runTest("aop.xml aspect inheriting abstract method ");}
public void testLTWGeneratedAspectAbstractMethod_pr125480_2() { runTest("aop.xml aspect inheriting abstract method - code style");}
//public void testSuperITDExplosion_pr134425() { runTest("super ITDs");}
//public void testMisbehavingDeclareAnnotation_pr135865() { runTest("misbehaving declare annotation");}
//public void testMisbehavingDeclareAnnotation_pr135865_2() { runTest("misbehaving declare annotation - 2");}
public void testCompletelyBrokenAopConcretization_pr142165_1() { runTest("broken concretization");}
public void testCompletelyBrokenAopConcretization_pr142165_2() { runTest("broken concretization - 2");}
public void testCompletelyBrokenAopConcretization_pr142165_3() { runTest("broken concretization - 3");}
public void testVerifyErrorLTW_pr135068() { runTest("ltw verifyerror");}
public void testVerifyErrorLTW_pr135068_2() { runTest("ltw verifyerror - 2");}
public void testVerifyErrorLTW_pr135068_3() { runTest("ltw verifyerror - 3");}
public void testVerifyErrorLTW_pr135068_4() { runTest("ltw verifyerror - 4");}
public void testVerifyErrorForComplexCflow_pr136026() { runTest("verifyerror");}
public void testVerifyErrorForComplexCflow_pr136026_2() { runTest("verifyerror - 2");}
public void testAnnotationsAndGenericsBCException_pr129704() { runTest("annotations and generics leading to BCException");}
public void testMethodTooBigAfterWeaving_pr138384() { runTest("method too big"); }
public void testNotAtWithincode_pr138158_1() { runTest("not at withincode - 1");}
public void testNotAtWithincode_pr138158_2() { runTest("not at withincode - 2");}
public void testNotAtWithincode_pr138158_3() { runTest("not at within - 3");}
public void testNpeOnDup_pr138143() { runTest("npe on duplicate method with ataj");}
public void testPointcutsAndGenerics_pr137496_1() { runTest("pointcuts and generics - B");}
public void testPointcutsAndGenerics_pr137496_2() { runTest("pointcuts and generics - D");}
public void testPointcutsAndGenerics_pr137496_3() { runTest("pointcuts and generics - E");}
public void testPointcutsAndGenerics_pr137496_4() { runTest("pointcuts and generics - F");}
public void testPointcutsAndGenerics_pr137496_5() { runTest("pointcuts and generics - G");}
public void testPointcutsAndGenerics_pr137496_6() { runTest("pointcuts and generics - H");}
public void testAspectLibrariesAndASM_pr135001() { runTest("aspect libraries and asm");}
public void testStackOverflow_pr136258() { runTest("stack overflow");}
public void testIncorrectOverridesEvaluation13() { runTest("incorrect overrides evaluation - 1.3"); }
// public void testIncorrectOverridesEvaluation14() { runTest("incorrect overrides evaluation - 1.4"); }
public void testIncorrectOverridesEvaluation15() { runTest("incorrect overrides evaluation - 1.5"); }
public void testAtWithinCodeBug_pr138798() { runTest("atWithinCodeBug"); }
public void testReferencePCutInDeclareWarning_pr138215() { runTest("Reference pointcut fails inside @DeclareWarning");}
public void testReferencePCutInPerClause_pr138219() { runTest("Can't use a FQ Reference pointcut in any pointcut expression referenced by a per-clause");}
public void testReferencePCutInPerClause_pr130722() { runTest("FQ Reference pointcut from perclause ref pc"); }
public void testDoubleAnnotationMatching_pr138223() { runTest("Double at annotation matching (no binding)");}
public void testSuperCallsInAtAspectJAdvice_pr139749() { runTest("Super calls in @AspectJ advice");}
public void testNoClassCastExceptionWithPerThis_pr138286() { runTest("No ClassCastException with perThis");}
public void testGenericAspectHierarchyWithBounds_pr147845() { runTest("Generic abstract aspect hierarchy with bounds"); }
public void testJRockitBooleanReturn_pr148007() { runTest("jrockit boolean fun");}
public void testJRockitBooleanReturn2_pr148007() { runTest("jrockit boolean fun (no aspects)");}
public void testSyntheticAjcMembers_pr147711() { runTest("synthetic ajc$ members"); }
public void testDeclareAtMethodRelationship_pr143924() {
//AsmManager.setReporting("c:/debug.txt",true,true,true,true);
runTest("declare @method relationship");
IHierarchy top = AsmManager.getDefault().getHierarchy();
// get the IProgramElements corresponding to the different code entries
IProgramElement decam = top.findElementForLabel(top.getRoot(),
IProgramElement.Kind.DECLARE_ANNOTATION_AT_METHOD,
"declare @method: * debit(..) : @Secured(role = \"supervisor\")");
assertNotNull("Couldn't find 'declare @method' element in the tree",decam);
IProgramElement method = top.findElementForLabel(top.getRoot(),
IProgramElement.Kind.METHOD,"debit(java.lang.String,long)");
assertNotNull("Couldn't find the 'debit(String,long)' method element in the tree",method);
List matches = AsmManager.getDefault().getRelationshipMap().get(decam);
assertNotNull("'declare @method' should have some relationships but does not",matches);
assertTrue("'declare @method' should have one relationships but has " + matches.size(),matches.size()==1);
List matchesTargets = ((Relationship)matches.get(0)).getTargets();
assertTrue("'declare @method' should have one targets but has" + matchesTargets.size(),matchesTargets.size()==1);
IProgramElement target = AsmManager.getDefault().getHierarchy().findElementForHandle((String)matchesTargets.get(0));
assertEquals("target of relationship should be the 'debit(java.lang.String,long)' method but is IPE with label "
+ target.toLabelString(),method,target);
// check that the debit method has an annotated by relationship with the declare @method
matches = AsmManager.getDefault().getRelationshipMap().get(method);
assertNotNull("'debit(java.lang.String,long)' should have some relationships but does not",matches);
assertTrue("'debit(java.lang.String,long)' should have one relationships but has " + matches.size(),matches.size()==1);
matchesTargets = ((Relationship)matches.get(0)).getTargets();
assertTrue("'debit(java.lang.String,long)' should have one targets but has" + matchesTargets.size(),matchesTargets.size()==1);
target = AsmManager.getDefault().getHierarchy().findElementForHandle((String)matchesTargets.get(0));
assertEquals("target of relationship should be the 'declare @method' ipe but is IPE with label "
+ target.toLabelString(),decam,target);
}
// this next one reported as a bug by Rob Harrop, but I can't reproduce the failure yet...
//public void testAtAspectWithReferencePCPerClause_pr138220() { runTest("@Aspect with reference pointcut in perclause");}
public void testJarChecking_pr137235_1() { runTest("directory with .jar extension: source and outjar"); }
public void testJarChecking_pr137235_2() { runTest("directory with .jar extension"); }
public void testMakePreMethodNPE_pr136393() { runTest("NPE in makePreMethod");}
public void testGetParameterHandles_pr141730() {
runTest("new IProgramElement handle methods");
checkParametersForIPE("intMethod(int)",IProgramElement.Kind.METHOD,"I",true);
checkParametersForIPE("stringMethod(java.lang.String)",IProgramElement.Kind.METHOD,"Ljava/lang/String;",true);
checkParametersForIPE("myClassMethod(MyClass)",IProgramElement.Kind.METHOD,"LMyClass;",true);
checkParametersForIPE("genericMethod(java.util.List<java.lang.String>)",IProgramElement.Kind.METHOD,"Pjava/util/List<Ljava/lang/String;>;",true);
checkParametersForIPE("genericMethod2(MyGenericClass<java.lang.String,MyClass>)",IProgramElement.Kind.METHOD,"PMyGenericClass<Ljava/lang/String;LMyClass;>;",true);
checkParametersForIPE("main(java.lang.String[])",IProgramElement.Kind.METHOD,"[Ljava/lang/String;",true);
checkParametersForIPE("multiMethod(java.lang.String[][])",IProgramElement.Kind.METHOD,"[[Ljava/lang/String;",true);
checkParametersForIPE("intArray(int[])",IProgramElement.Kind.METHOD,"[I",true);
IHierarchy top = AsmManager.getDefault().getHierarchy();
IProgramElement twoArgsMethod = top.findElementForLabel(
top.getRoot(),IProgramElement.Kind.METHOD,"twoArgsMethod(int,java.lang.String)");
assertNotNull("Couldn't find 'twoArgsMethod(int,java.lang.String)' element in the tree",twoArgsMethod);
List l = twoArgsMethod.getParameterSignatures();
assertEquals("",((char[])l.get(0))[0],'I');
boolean eq = CharOperation.equals(((char[])l.get(1)),"Ljava/lang/String;".toCharArray());
assertTrue("expected parameter to be 'Ljava/lang/String;' but found '" +
new String(((char[])l.get(1))) + "'",eq);
}
public void testGetParameterTypes_pr141730() {
runTest("new IProgramElement handle methods");
checkParametersForIPE("intMethod(int)",IProgramElement.Kind.METHOD,"int",false);
checkParametersForIPE("stringMethod(java.lang.String)",IProgramElement.Kind.METHOD,"java.lang.String",false);
checkParametersForIPE("myClassMethod(MyClass)",IProgramElement.Kind.METHOD,"MyClass",false);
checkParametersForIPE("genericMethod(java.util.List<java.lang.String>)",IProgramElement.Kind.METHOD,"java.util.List<java.lang.String>",false);
checkParametersForIPE("genericMethod2(MyGenericClass<java.lang.String,MyClass>)",IProgramElement.Kind.METHOD,"MyGenericClass<java.lang.String,MyClass>",false);
checkParametersForIPE("main(java.lang.String[])",IProgramElement.Kind.METHOD,"java.lang.String[]",false);
checkParametersForIPE("multiMethod(java.lang.String[][])",IProgramElement.Kind.METHOD,"java.lang.String[][]",false);
checkParametersForIPE("intArray(int[])",IProgramElement.Kind.METHOD,"int[]",false);
}
public void testToSignatureString_pr141730() {
runTest("new IProgramElement handle methods");
checkSignatureOfIPE("main(java.lang.String[])",IProgramElement.Kind.METHOD);
checkSignatureOfIPE("C",IProgramElement.Kind.CLASS);
checkSignatureOfIPE("C()",IProgramElement.Kind.CONSTRUCTOR);
checkSignatureOfIPE("method()",IProgramElement.Kind.METHOD);
checkSignatureOfIPE("p()",IProgramElement.Kind.POINTCUT);
checkSignatureOfIPE("before(): p..",IProgramElement.Kind.ADVICE,"before()");
checkSignatureOfIPE("MyClass.method()",IProgramElement.Kind.INTER_TYPE_METHOD);
checkSignatureOfIPE("multiMethod(java.lang.String[][])",IProgramElement.Kind.METHOD);
checkSignatureOfIPE("intArray(int[])",IProgramElement.Kind.METHOD);
checkSignatureOfIPE("MyClass.MyClass()",IProgramElement.Kind.INTER_TYPE_CONSTRUCTOR);
}
// if not filling in the model for aspects contained in jar files then
// want to ensure that the relationship map is correct and has nodes
// which can be used in AJDT - ensure no NPE occurs for the end of
// the relationship with aspectpath
public void testAspectPathRelWhenNotFillingInModel_pr141730() {
World.createInjarHierarchy = false;
try {
runTest("ensure aspectpath injar relationships are correct when not filling in model");
// expecting:
// sourceOfRelationship main in MyFoo.java
// relationship advised by
// target MyBar.aj
//
// and
//
// sourceOfRelationship MyBar.aj
// relationship advises
// target main in MyFoo.java
IHierarchy top = AsmManager.getDefault().getHierarchy();
IRelationshipMap asmRelMap = AsmManager.getDefault().getRelationshipMap();
assertEquals("expected two sources of relationships but only found "
+ asmRelMap.getEntries().size(),2,asmRelMap.getEntries().size());
for (Iterator iter = asmRelMap.getEntries().iterator(); iter.hasNext();) {
String sourceOfRelationship = (String) iter.next();
IProgramElement ipe = top.findElementForHandle(sourceOfRelationship);
List relationships = asmRelMap.get(ipe);
if (ipe.getName().equals("MyBar.aj")) {
assertEquals("expected MyBar.aj to have one relationships but found "
+ relationships.size(),1,relationships.size());
Relationship rel = (Relationship)relationships.get(0);
assertEquals("expected relationship to be 'advises' but was "
+ rel.getName(), "advises", rel.getName());
List targets = rel.getTargets();
assertEquals("expected one target but found " + targets.size(),1,targets.size());
IProgramElement link = top.findElementForHandle((String)targets.get(0));
assertEquals("expected target 'method-call(void foo.MyFoo.main())' but target " + link.getName(),
"method-call(void foo.MyFoo.main())",link.getName());
String fileName = link.getSourceLocation().getSourceFile().toString();
assertTrue("expected 'main' to be in class MyFoo.java but found it " +
"in " + fileName,fileName.indexOf("MyFoo.java") != -1);
} else if (ipe.getName().equals("method-call(void foo.MyFoo.main())")) {
String fileName = ipe.getSourceLocation().getSourceFile().toString();
assertTrue("expected 'method-call(void foo.MyFoo.main())' to be in " +
"class MyFoo.java but found it in"
+ fileName,fileName.indexOf("MyFoo.java") != -1);
assertEquals("expected 'method-call(void foo.MyFoo.main())' " +
"to have one relationships but found "
+ relationships.size(),1,relationships.size());
Relationship rel = (Relationship)relationships.get(0);
assertEquals("expected relationship to be 'advised by' but was "
+ rel.getName(), "advised by", rel.getName());
List targets = rel.getTargets();
assertEquals("expected one target but found " + targets.size(),1,targets.size());
IProgramElement link = top.findElementForHandle((String)targets.get(0));
assertEquals("expected target 'MyBar.aj' but target " + link.getName(),
"MyBar.aj",link.getName());
} else {
fail("unexpected element " + ipe.getName() + " in the relationship map");
}
}
} finally {
World.createInjarHierarchy = true;
}
}
// if not filling in the model for classes contained in jar files then
// want to ensure that the relationship map is correct and has nodes
// which can be used in AJDT - ensure no NPE occurs for the end of
// the relationship with inpath
public void testNoNPEWithInpathWhenNotFillingInModel_pr141730() {
World.createInjarHierarchy = false;
try {
runTest("ensure inpath injar relationships are correct when not filling in model");
// the aspect used for this test has advice, declare parents, deow,
// and declare @type, @constructor, @field and @method. We only expect
// there to be relationships in the map for declare parents and declare @type
// (provided the model isn't being filled in) because the logic in the other
// addXXXRelationship methods use AspectJElementHierarchy.findElementForType().
// This method which returns null because there is no such ipe. The relationship is
// therefore not added to the model. Adding declare @type and declare parents
// uses AspectJElementHierarchy.findElementForHandle() which returns the file
// node ipe if it can't find one for the given handle. Therefore the relationships
// are added against the file node. Before change to using ipe's to create handles
// we also had the deow relationship, however, now we don't because this also
// uses findElementForType to find the targetNode which in the inpath case is null.
// just check that the number of entries is what we expect:
// We expect 3 (the declare @type and declare parents statements plus the filenode)
IRelationshipMap relMap = AsmManager.getDefault().getRelationshipMap();
assertEquals("expected 3 entries in the relationship map but found "
+ relMap.getEntries().size(), 3, relMap.getEntries().size());
} finally {
World.createInjarHierarchy = true;
}
}
public void testPCDInClassAppearsInModel_pr148027() {
// only want to test that its there if we're creating the uses pointcut
// relationship. This should be addressed by pr148027
if (!AsmHierarchyBuilder.shouldAddUsesPointcut) return;
World.createInjarHierarchy = false;
try {
runTest("ensure pcd declare in class appears in model");
IHierarchy top = AsmManager.getDefault().getHierarchy();
IProgramElement pcd = top.findElementForLabel(top.getRoot(),IProgramElement.Kind.POINTCUT,"pointcutInClass()");
IRelationshipMap relMap = AsmManager.getDefault().getRelationshipMap();
List relationships = relMap.get(pcd);
assertNotNull("expected relationships for pointcut " + pcd.toLinkLabelString()
+ " but didn't", relationships);
pcd = top.findElementForLabel(top.getRoot(),IProgramElement.Kind.POINTCUT,"pointcutInAspect()");
relationships = relMap.get(pcd);
assertNotNull("expected relationships for pointcut " + pcd.toLinkLabelString()
+ " but didn't", relationships);
} finally {
World.createInjarHierarchy = true;
}
}
// public void testFunkyGenericErrorWithITDs_pr126355_2() {
// runTest("bizarre generic error with itds - 2");
// // public class Pair<F,S> affected by pertarget aspect
// GenericsTests.verifyClassSignature(ajc,"Pair","<F:Ljava/lang/Object;S:Ljava/lang/Object;>Ljava/lang/Object;LIdempotentCache$ajcMightHaveAspect;;");
// }
public void testNoAspects(){
// setSystemProperty(WeavingAdaptor.WEAVING_ADAPTOR_VERBOSE,"true");
runTest("Ensure no weaving without included aspects");
}
public void testWeaveinfoMessages (){
runTest("weaveinfo messages with include and exclude");
}
// tests that can't be included for some reason
// Not valid whilst the ajc compiler forces debug on (ignores -g:none) - it will be green but is invalid, trust me
// public void testLongWindedMessages_pr129408() { runTest("long winded ataj messages");}
// ---------------- helper methods ---------------
private void checkParametersForIPE(String ipeLabel, IProgramElement.Kind kind, String expectedParm, boolean getHandles) {
IHierarchy top = AsmManager.getDefault().getHierarchy();
IProgramElement ipe = top.findElementForLabel(top.getRoot(),kind,ipeLabel);
assertNotNull("Couldn't find '" + ipeLabel + "' element in the tree",ipe);
List l = new ArrayList();
if (getHandles) {
l = ipe.getParameterSignatures();
} else {
l = ipe.getParameterTypes();
}
boolean eq = CharOperation.equals(((char[])l.get(0)),expectedParm.toCharArray());
assertTrue("expected parameter to be '" + expectedParm + "' but found '" +
new String(((char[])l.get(0))) + "'",eq);
}
private void checkSignatureOfIPE(String ipeLabel, IProgramElement.Kind kind) {
checkSignatureOfIPE(ipeLabel,kind,ipeLabel);
}
private void checkSignatureOfIPE(String ipeLabel, IProgramElement.Kind kind, String expectedSig) {
IHierarchy top = AsmManager.getDefault().getHierarchy();
IProgramElement ipe = top.findElementForLabel(
top.getRoot(),kind,ipeLabel);
assertNotNull("Couldn't find '" + ipeLabel + "' element in the tree",ipe);
assertEquals("expected signature to be '"+ expectedSig + "' but was " +
ipe.toSignatureString(true),expectedSig,ipe.toSignatureString(true));
}
/////////////////////////////////////////
public static Test suite() {
return XMLBasedAjcTestCase.loadSuite(Ajc152Tests.class);
}
protected File getSpecFile() {
return new File("../tests/src/org/aspectj/systemtest/ajc152/ajc152.xml");
}
}
|
148,972 |
Bug 148972 problems with binary weaving declare parents in mixed environment.
|
These have been reported to me on a large system doing some intricate weaving where some classes are 1.2, some 1.4, some 1.5 and the VM is 1.5. Binary weaving declare parents sometimes refuses to allow the modification of the hierarchy because it sees a clash between two methods when there is none. The two cases I'm fixing are: 1. sometimes the signatures of the return types differ with the '.' or '/' problem (fix == be consistent) 2. sometimes the syntheticness of the methods in the relationship isn't determined correctly
|
resolved fixed
|
2f2f568
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-06-28T11:44:10Z | 2006-06-28T10:20:00Z |
weaver/src/org/aspectj/weaver/bcel/BcelTypeMunger.java
|
/* *******************************************************************
* Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC).
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the 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.Iterator;
import java.util.List;
import java.util.Set;
import org.aspectj.apache.bcel.Constants;
import org.aspectj.apache.bcel.classfile.annotation.Annotation;
import org.aspectj.apache.bcel.generic.BranchInstruction;
import org.aspectj.apache.bcel.generic.ConstantPoolGen;
import org.aspectj.apache.bcel.generic.FieldGen;
import org.aspectj.apache.bcel.generic.INVOKESPECIAL;
import org.aspectj.apache.bcel.generic.InstructionConstants;
import org.aspectj.apache.bcel.generic.InstructionFactory;
import org.aspectj.apache.bcel.generic.InstructionHandle;
import org.aspectj.apache.bcel.generic.InstructionList;
import org.aspectj.apache.bcel.generic.Type;
import org.aspectj.apache.bcel.generic.annotation.AnnotationGen;
import org.aspectj.bridge.IMessage;
import org.aspectj.bridge.ISourceLocation;
import org.aspectj.bridge.Message;
import org.aspectj.bridge.MessageUtil;
import org.aspectj.bridge.WeaveMessage;
import org.aspectj.bridge.context.CompilationAndWeavingContext;
import org.aspectj.bridge.context.ContextToken;
import org.aspectj.weaver.AjcMemberMaker;
import org.aspectj.weaver.AnnotationOnTypeMunger;
import org.aspectj.weaver.AnnotationX;
import org.aspectj.weaver.AsmRelationshipProvider;
import org.aspectj.weaver.BCException;
import org.aspectj.weaver.ConcreteTypeMunger;
import org.aspectj.weaver.Member;
import org.aspectj.weaver.MethodDelegateTypeMunger;
import org.aspectj.weaver.NameMangler;
import org.aspectj.weaver.NewConstructorTypeMunger;
import org.aspectj.weaver.NewFieldTypeMunger;
import org.aspectj.weaver.NewMethodTypeMunger;
import org.aspectj.weaver.NewParentTypeMunger;
import org.aspectj.weaver.PerObjectInterfaceTypeMunger;
import org.aspectj.weaver.PrivilegedAccessMunger;
import org.aspectj.weaver.ResolvedMember;
import org.aspectj.weaver.ResolvedType;
import org.aspectj.weaver.ResolvedTypeMunger;
import org.aspectj.weaver.Shadow;
import org.aspectj.weaver.TypeVariableReference;
import org.aspectj.weaver.UnresolvedType;
import org.aspectj.weaver.WeaverMessages;
import org.aspectj.weaver.WeaverStateInfo;
import org.aspectj.weaver.World;
import org.aspectj.weaver.patterns.DeclareAnnotation;
import org.aspectj.weaver.patterns.Pointcut;
//XXX addLazyMethodGen is probably bad everywhere
public class BcelTypeMunger extends ConcreteTypeMunger {
public BcelTypeMunger(ResolvedTypeMunger munger, ResolvedType aspectType) {
super(munger, aspectType);
}
public String toString() {
return "(BcelTypeMunger " + getMunger() + ")";
}
public boolean munge(BcelClassWeaver weaver) {
ContextToken tok = CompilationAndWeavingContext.enteringPhase(CompilationAndWeavingContext.MUNGING_WITH, this);
boolean changed = false;
boolean worthReporting = true;
if (munger.getKind() == ResolvedTypeMunger.Field) {
changed = mungeNewField(weaver, (NewFieldTypeMunger)munger);
} else if (munger.getKind() == ResolvedTypeMunger.Method) {
changed = mungeNewMethod(weaver, (NewMethodTypeMunger)munger);
} else if (munger.getKind() == ResolvedTypeMunger.MethodDelegate) {
changed = mungeMethodDelegate(weaver, (MethodDelegateTypeMunger)munger);
} else if (munger.getKind() == ResolvedTypeMunger.FieldHost) {
changed = mungeFieldHost(weaver, (MethodDelegateTypeMunger.FieldHostTypeMunger)munger);
} else if (munger.getKind() == ResolvedTypeMunger.PerObjectInterface) {
changed = mungePerObjectInterface(weaver, (PerObjectInterfaceTypeMunger)munger);
worthReporting = false;
} else if (munger.getKind() == ResolvedTypeMunger.PerTypeWithinInterface) {
// PTWIMPL Transform the target type (add the aspect instance field)
changed = mungePerTypeWithinTransformer(weaver);
worthReporting = false;
} else if (munger.getKind() == ResolvedTypeMunger.PrivilegedAccess) {
changed = mungePrivilegedAccess(weaver, (PrivilegedAccessMunger)munger);
worthReporting = false;
} else if (munger.getKind() == ResolvedTypeMunger.Constructor) {
changed = mungeNewConstructor(weaver, (NewConstructorTypeMunger)munger);
} else if (munger.getKind() == ResolvedTypeMunger.Parent) {
changed = mungeNewParent(weaver, (NewParentTypeMunger)munger);
} else if (munger.getKind() == ResolvedTypeMunger.AnnotationOnType) {
changed = mungeNewAnnotationOnType(weaver,(AnnotationOnTypeMunger)munger);
worthReporting=false;
} else {
throw new RuntimeException("unimplemented");
}
if (changed && munger.changesPublicSignature()) {
WeaverStateInfo info =
weaver.getLazyClassGen().getOrCreateWeaverStateInfo(BcelClassWeaver.getReweavableMode());
info.addConcreteMunger(this);
}
if (changed && worthReporting) {
if (munger.getKind().equals(ResolvedTypeMunger.Parent)) {
AsmRelationshipProvider.getDefault().addRelationship(weaver.getLazyClassGen().getType(), munger,getAspectType());
} else {
AsmRelationshipProvider.getDefault().addRelationship(weaver.getLazyClassGen().getType(), munger,getAspectType());
}
}
// TAG: WeavingMessage
if (changed && worthReporting && munger!=null && !weaver.getWorld().getMessageHandler().isIgnoring(IMessage.WEAVEINFO)) {
String tName = weaver.getLazyClassGen().getType().getSourceLocation().getSourceFile().getName();
if (tName.indexOf("no debug info available")!=-1) tName = "no debug info available";
else tName = getShortname(weaver.getLazyClassGen().getType().getSourceLocation().getSourceFile().getPath());
String fName = getShortname(getAspectType().getSourceLocation().getSourceFile().getPath());
if (munger.getKind().equals(ResolvedTypeMunger.Parent)) {
// This message could come out of AjLookupEnvironment.addParent if doing parents
// munging at compile time only...
NewParentTypeMunger parentTM = (NewParentTypeMunger)munger;
if (parentTM.getNewParent().isInterface()) {
weaver.getWorld().getMessageHandler().handleMessage(WeaveMessage.constructWeavingMessage(WeaveMessage.WEAVEMESSAGE_DECLAREPARENTSIMPLEMENTS,
new String[]{weaver.getLazyClassGen().getType().getName(),
tName,parentTM.getNewParent().getName(),fName},
weaver.getLazyClassGen().getClassName(), getAspectType().getName()));
} else {
weaver.getWorld().getMessageHandler().handleMessage(
WeaveMessage.constructWeavingMessage(WeaveMessage.WEAVEMESSAGE_DECLAREPARENTSEXTENDS,
new String[]{weaver.getLazyClassGen().getType().getName(),
tName,parentTM.getNewParent().getName(),fName
}));
// TAG: WeavingMessage DECLARE PARENTS: EXTENDS
// reportDeclareParentsMessage(WeaveMessage.WEAVEMESSAGE_DECLAREPARENTSEXTENDS,sourceType,parent);
}
} else if (munger.getKind().equals(ResolvedTypeMunger.FieldHost)) {
;//hidden
} else {
ResolvedMember declaredSig = munger.getDeclaredSignature();
if (declaredSig==null) declaredSig= munger.getSignature();
weaver.getWorld().getMessageHandler().handleMessage(WeaveMessage.constructWeavingMessage(WeaveMessage.WEAVEMESSAGE_ITD,
new String[]{weaver.getLazyClassGen().getType().getName(),
tName,munger.getKind().toString().toLowerCase(),
getAspectType().getName(),
fName+":'"+declaredSig+"'"},
weaver.getLazyClassGen().getClassName(), getAspectType().getName()));
}
}
CompilationAndWeavingContext.leavingPhase(tok);
return changed;
}
private String getShortname(String path) {
int takefrom = path.lastIndexOf('/');
if (takefrom == -1) {
takefrom = path.lastIndexOf('\\');
}
return path.substring(takefrom+1);
}
private boolean mungeNewAnnotationOnType(BcelClassWeaver weaver,AnnotationOnTypeMunger munger) {
// FIXME asc this has already been done up front, need to do it here too?
weaver.getLazyClassGen().addAnnotation(munger.getNewAnnotation().getBcelAnnotation());
return true;
}
/**
* For a long time, AspectJ did not allow binary weaving of declare parents. This restriction is now lifted
* but could do with more testing!
*/
private boolean mungeNewParent(BcelClassWeaver weaver, NewParentTypeMunger munger) {
LazyClassGen newParentTarget = weaver.getLazyClassGen();
ResolvedType newParent = munger.getNewParent();
boolean cont = true; // Set to false when we error, so we don't actually *do* the munge
cont = enforceDecpRule1_abstractMethodsImplemented(weaver, munger.getSourceLocation(),newParentTarget, newParent);
cont = enforceDecpRule2_cantExtendFinalClass(weaver,munger.getSourceLocation(),newParentTarget,newParent) && cont;
List methods = newParent.getMethodsWithoutIterator(false,true);
for (Iterator iter = methods.iterator(); iter.hasNext();) {
ResolvedMember superMethod = (ResolvedMember) iter.next();
if (!superMethod.getName().equals("<init>")) {
LazyMethodGen subMethod = findMatchingMethod(newParentTarget, superMethod);
if (subMethod!=null && !subMethod.isBridgeMethod()) { // FIXME asc is this safe for all bridge methods?
if (!(subMethod.isSynthetic() && superMethod.isSynthetic())) {
cont = enforceDecpRule3_visibilityChanges(weaver, newParent, superMethod, subMethod) && cont;
cont = enforceDecpRule4_compatibleReturnTypes(weaver, superMethod, subMethod) && cont;
cont = enforceDecpRule5_cantChangeFromStaticToNonstatic(weaver,munger.getSourceLocation(),superMethod,subMethod) && cont;
}
}
}
}
if (!cont) return false; // A rule was violated and an error message already reported
if (newParent.isClass()) { // Changing the supertype
if (!attemptToModifySuperCalls(weaver,newParentTarget,newParent)) return false;
newParentTarget.setSuperClass(newParent);
} else { // Adding a new interface
newParentTarget.addInterface(newParent,getSourceLocation());
}
return true;
}
/**
* Rule 1: For the declare parents to be allowed, the target type must override and implement
* inherited abstract methods (if the type is not declared abstract)
*/
private boolean enforceDecpRule1_abstractMethodsImplemented(BcelClassWeaver weaver, ISourceLocation mungerLoc,LazyClassGen newParentTarget, ResolvedType newParent) {
boolean ruleCheckingSucceeded = true;
if (!(newParentTarget.isAbstract() || newParentTarget.isInterface())) { // Ignore abstract classes or interfaces
List methods = newParent.getMethodsWithoutIterator(false,true);
for (Iterator i = methods.iterator(); i.hasNext();) {
ResolvedMember o = (ResolvedMember)i.next();
if (o.isAbstract() && !o.getName().startsWith("ajc$interField")) { // Ignore abstract methods of ajc$interField prefixed methods
ResolvedMember discoveredImpl = null;
List newParentTargetMethods = newParentTarget.getType().getMethodsWithoutIterator(false,true);
for (Iterator ii = newParentTargetMethods.iterator(); ii.hasNext() && discoveredImpl==null;) {
ResolvedMember gen2 = (ResolvedMember) ii.next();
if (gen2.getName().equals(o.getName()) &&
gen2.getParameterSignature().equals(o.getParameterSignature()) && !gen2.isAbstract()) {
discoveredImpl = gen2; // Found a valid implementation !
}
}
if (discoveredImpl == null) {
// didnt find a valid implementation, lets check the ITDs on this type to see if they satisfy it
boolean satisfiedByITD = false;
for (Iterator ii = newParentTarget.getType().getInterTypeMungersIncludingSupers().iterator(); ii.hasNext(); ) {
ConcreteTypeMunger m = (ConcreteTypeMunger)ii.next();
if (m.getMunger().getKind() == ResolvedTypeMunger.Method) {
ResolvedMember sig = m.getSignature();
if (!Modifier.isAbstract(sig.getModifiers())) {
// If the ITD shares a type variable with some target type, we need to tailor it for that
// type
if (m.isTargetTypeParameterized()) {
ResolvedType genericOnType = getWorld().resolve(sig.getDeclaringType()).getGenericType();
m = m.parameterizedFor(newParent.discoverActualOccurrenceOfTypeInHierarchy(genericOnType));
sig = m.getSignature(); // possible sig change when type parameters filled in
}
if (ResolvedType
.matches(
AjcMemberMaker.interMethod(
sig,m.getAspectType(),sig.getDeclaringType().resolve(weaver.getWorld()).isInterface()),o)) {
satisfiedByITD = true;
}
}
} else if (m.getMunger().getKind() == ResolvedTypeMunger.MethodDelegate) {
satisfiedByITD = true;//AV - that should be enough, no need to check more
}
}
if (!satisfiedByITD) {
error(weaver,
"The type " + newParentTarget.getName() + " must implement the inherited abstract method "+o.getDeclaringType()+"."+o.getName()+o.getParameterSignature(),
newParentTarget.getType().getSourceLocation(),new ISourceLocation[]{o.getSourceLocation(),mungerLoc});
ruleCheckingSucceeded=false;
}
}
}
}
}
return ruleCheckingSucceeded;
}
/**
* Rule 2. Can't extend final types
*/
private boolean enforceDecpRule2_cantExtendFinalClass(BcelClassWeaver weaver, ISourceLocation mungerLoc,
LazyClassGen newParentTarget, ResolvedType newParent) {
if (newParent.isFinal()) {
error(weaver,"Cannot make type "+newParentTarget.getName()+" extend final class "+newParent.getName(),
newParentTarget.getType().getSourceLocation(),
new ISourceLocation[]{mungerLoc});
return false;
}
return true;
}
/**
* Rule 3. Can't narrow visibility of methods when overriding
*/
private boolean enforceDecpRule3_visibilityChanges(BcelClassWeaver weaver, ResolvedType newParent, ResolvedMember superMethod, LazyMethodGen subMethod) {
boolean cont = true;
if (superMethod.isPublic()) {
if (subMethod.isProtected() || subMethod.isDefault() || subMethod.isPrivate()) {
weaver.getWorld().getMessageHandler().handleMessage(MessageUtil.error(
"Cannot reduce the visibility of the inherited method '"+superMethod+"' from "+newParent.getName(),
superMethod.getSourceLocation()));
cont=false;
}
} else if (superMethod.isProtected()) {
if (subMethod.isDefault() || subMethod.isPrivate()) {
weaver.getWorld().getMessageHandler().handleMessage(MessageUtil.error(
"Cannot reduce the visibility of the inherited method '"+superMethod+"' from "+newParent.getName(),
superMethod.getSourceLocation()));
cont=false;
}
} else if (superMethod.isDefault()) {
if (subMethod.isPrivate()) {
weaver.getWorld().getMessageHandler().handleMessage(MessageUtil.error(
"Cannot reduce the visibility of the inherited method '"+superMethod+"' from "+newParent.getName(),
superMethod.getSourceLocation()));
cont=false;
}
}
return cont;
}
/**
* Rule 4. Can't have incompatible return types
*/
private boolean enforceDecpRule4_compatibleReturnTypes(BcelClassWeaver weaver, ResolvedMember superMethod, LazyMethodGen subMethod) {
boolean cont = true;
String superReturnTypeSig = superMethod.getReturnType().getSignature();
String subReturnTypeSig = subMethod.getReturnType().getSignature();
if (!superReturnTypeSig.equals(subReturnTypeSig)) {
// Allow for covariance - wish I could test this (need Java5...)
ResolvedType subType = weaver.getWorld().resolve(subMethod.getReturnType());
ResolvedType superType = weaver.getWorld().resolve(superMethod.getReturnType());
if (!superType.isAssignableFrom(subType)) {
ISourceLocation sloc = subMethod.getSourceLocation();
weaver.getWorld().getMessageHandler().handleMessage(MessageUtil.error(
"The return type is incompatible with "+superMethod.getDeclaringType()+"."+superMethod.getName()+superMethod.getParameterSignature(),
subMethod.getSourceLocation()));
cont=false;
}
}
return cont;
}
/**
* Rule5. Method overrides can't change the staticality (word?) - you can't override and make an instance
* method static or override and make a static method an instance method.
*/
private boolean enforceDecpRule5_cantChangeFromStaticToNonstatic(BcelClassWeaver weaver,ISourceLocation mungerLoc,ResolvedMember superMethod, LazyMethodGen subMethod ) {
if (superMethod.isStatic() && !subMethod.isStatic()) {
error(weaver,"This instance method "+subMethod.getName()+subMethod.getParameterSignature()+
" cannot override the static method from "+superMethod.getDeclaringType().getName(),
subMethod.getSourceLocation(),new ISourceLocation[]{mungerLoc});
return false;
} else if (!superMethod.isStatic() && subMethod.isStatic()) {
error(weaver,"The static method "+subMethod.getName()+subMethod.getParameterSignature()+
" cannot hide the instance method from "+superMethod.getDeclaringType().getName(),
subMethod.getSourceLocation(),new ISourceLocation[]{mungerLoc});
return false;
}
return true;
}
public void error(BcelClassWeaver weaver,String text,ISourceLocation primaryLoc,ISourceLocation[] extraLocs) {
IMessage msg = new Message(text, primaryLoc, true, extraLocs);
weaver.getWorld().getMessageHandler().handleMessage(msg);
}
private LazyMethodGen findMatchingMethod(LazyClassGen newParentTarget, ResolvedMember m) {
LazyMethodGen found = null;
// Search the type for methods overriding super methods (methods that come from the new parent)
// Don't use the return value in the comparison as overriding doesnt
for (Iterator i = newParentTarget.getMethodGens().iterator(); i.hasNext() && found==null;) {
LazyMethodGen gen = (LazyMethodGen) i.next();
if (gen.getName().equals(m.getName()) &&
gen.getParameterSignature().equals(m.getParameterSignature())) {
found = gen;
}
}
return found;
}
/**
* The main part of implementing declare parents extends. Modify super ctor calls to target the new type.
*/
public boolean attemptToModifySuperCalls(BcelClassWeaver weaver,LazyClassGen newParentTarget, ResolvedType newParent) {
String currentParent = newParentTarget.getSuperClassname();
if (newParent.getGenericType()!=null) newParent = newParent.getGenericType(); // target new super calls at the generic type if its raw or parameterized
List mgs = newParentTarget.getMethodGens();
// Look for ctors to modify
for (Iterator iter = mgs.iterator(); iter.hasNext();) {
LazyMethodGen aMethod = (LazyMethodGen) iter.next();
if (aMethod.getName().equals("<init>")) {
InstructionList insList = aMethod.getBody();
InstructionHandle handle = insList.getStart();
while (handle!= null) {
if (handle.getInstruction() instanceof INVOKESPECIAL) {
ConstantPoolGen cpg = newParentTarget.getConstantPoolGen();
INVOKESPECIAL invokeSpecial = (INVOKESPECIAL)handle.getInstruction();
if (invokeSpecial.getClassName(cpg).equals(currentParent) && invokeSpecial.getMethodName(cpg).equals("<init>")) {
// System.err.println("Transforming super call '<init>"+sp.getSignature(cpg)+"'");
// 1. Check there is a ctor in the new parent with the same signature
ResolvedMember newCtor = getConstructorWithSignature(newParent,invokeSpecial.getSignature(cpg));
if (newCtor == null) {
// 2. Check ITDCs to see if the necessary ctor is provided that way
boolean satisfiedByITDC = false;
for (Iterator ii = newParentTarget.getType().getInterTypeMungersIncludingSupers().iterator(); ii.hasNext() && !satisfiedByITDC; ) {
ConcreteTypeMunger m = (ConcreteTypeMunger)ii.next();
if (m.getMunger() instanceof NewConstructorTypeMunger) {
if (m.getSignature().getSignature().equals(invokeSpecial.getSignature(cpg))) {
satisfiedByITDC = true;
}
}
}
if (!satisfiedByITDC) {
String csig = createReadableCtorSig(newParent, cpg, invokeSpecial);
weaver.getWorld().getMessageHandler().handleMessage(MessageUtil.error(
"Unable to modify hierarchy for "+newParentTarget.getClassName()+" - the constructor "+
csig+" is missing",this.getSourceLocation()));
return false;
}
}
int idx = cpg.addMethodref(newParent.getName(), invokeSpecial.getMethodName(cpg), invokeSpecial.getSignature(cpg));
invokeSpecial.setIndex(idx);
}
}
handle = handle.getNext();
}
}
}
return true;
}
/**
* Creates a nice signature for the ctor, something like "(int,Integer,String)"
*/
private String createReadableCtorSig(ResolvedType newParent, ConstantPoolGen cpg, INVOKESPECIAL invokeSpecial) {
StringBuffer sb = new StringBuffer();
Type[] ctorArgs = invokeSpecial.getArgumentTypes(cpg);
sb.append(newParent.getClassName());
sb.append("(");
for (int i = 0; i < ctorArgs.length; i++) {
String argtype = ctorArgs[i].toString();
if (argtype.lastIndexOf(".")!=-1)
sb.append(argtype.substring(argtype.lastIndexOf(".")+1));
else
sb.append(argtype);
if (i+1<ctorArgs.length) sb.append(",");
}
sb.append(")");
return sb.toString();
}
private ResolvedMember getConstructorWithSignature(ResolvedType tx,String signature) {
ResolvedMember[] mems = tx.getDeclaredJavaMethods();
for (int i = 0; i < mems.length; i++) {
ResolvedMember rm = mems[i];
if (rm.getName().equals("<init>")) {
if (rm.getSignature().equals(signature)) return rm;
}
}
return null;
}
private boolean mungePrivilegedAccess(
BcelClassWeaver weaver,
PrivilegedAccessMunger munger)
{
LazyClassGen gen = weaver.getLazyClassGen();
ResolvedMember member = munger.getMember();
ResolvedType onType = weaver.getWorld().resolve(member.getDeclaringType(),munger.getSourceLocation());
if (onType.isRawType()) onType = onType.getGenericType();
//System.out.println("munging: " + gen + " with " + member);
if (onType.equals(gen.getType())) {
if (member.getKind() == Member.FIELD) {
//System.out.println("matched: " + gen);
addFieldGetter(gen, member,
AjcMemberMaker.privilegedAccessMethodForFieldGet(aspectType, member));
addFieldSetter(gen, member,
AjcMemberMaker.privilegedAccessMethodForFieldSet(aspectType, member));
return true;
} else if (member.getKind() == Member.METHOD) {
addMethodDispatch(gen, member,
AjcMemberMaker.privilegedAccessMethodForMethod(aspectType, member));
return true;
} else if (member.getKind() == Member.CONSTRUCTOR) {
for (Iterator i = gen.getMethodGens().iterator(); i.hasNext(); ) {
LazyMethodGen m = (LazyMethodGen)i.next();
if (m.getMemberView() != null
&& m.getMemberView().getKind() == Member.CONSTRUCTOR) {
// m.getMemberView().equals(member)) {
m.forcePublic();
//return true;
}
}
return true;
//throw new BCException("no match for " + member + " in " + gen);
} else if (member.getKind() == Member.STATIC_INITIALIZATION) {
gen.forcePublic();
return true;
} else {
throw new RuntimeException("unimplemented");
}
}
return false;
}
private void addFieldGetter(
LazyClassGen gen,
ResolvedMember field,
ResolvedMember accessMethod)
{
LazyMethodGen mg = makeMethodGen(gen, accessMethod);
InstructionList il = new InstructionList();
InstructionFactory fact = gen.getFactory();
if (field.isStatic()) {
il.append(fact.createFieldAccess(
gen.getClassName(),
field.getName(),
BcelWorld.makeBcelType(field.getType()), Constants.GETSTATIC));
} else {
il.append(InstructionConstants.ALOAD_0);
il.append(fact.createFieldAccess(
gen.getClassName(),
field.getName(),
BcelWorld.makeBcelType(field.getType()), Constants.GETFIELD));
}
il.append(InstructionFactory.createReturn(BcelWorld.makeBcelType(field.getType())));
mg.getBody().insert(il);
gen.addMethodGen(mg,getSignature().getSourceLocation());
}
private void addFieldSetter(
LazyClassGen gen,
ResolvedMember field,
ResolvedMember accessMethod)
{
LazyMethodGen mg = makeMethodGen(gen, accessMethod);
InstructionList il = new InstructionList();
InstructionFactory fact = gen.getFactory();
Type fieldType = BcelWorld.makeBcelType(field.getType());
if (field.isStatic()) {
il.append(InstructionFactory.createLoad(fieldType, 0));
il.append(fact.createFieldAccess(
gen.getClassName(),
field.getName(),
fieldType, Constants.PUTSTATIC));
} else {
il.append(InstructionConstants.ALOAD_0);
il.append(InstructionFactory.createLoad(fieldType, 1));
il.append(fact.createFieldAccess(
gen.getClassName(),
field.getName(),
fieldType, Constants.PUTFIELD));
}
il.append(InstructionFactory.createReturn(Type.VOID));
mg.getBody().insert(il);
gen.addMethodGen(mg,getSignature().getSourceLocation());
}
private void addMethodDispatch(
LazyClassGen gen,
ResolvedMember method,
ResolvedMember accessMethod)
{
LazyMethodGen mg = makeMethodGen(gen, accessMethod);
InstructionList il = new InstructionList();
InstructionFactory fact = gen.getFactory();
//Type fieldType = BcelWorld.makeBcelType(field.getType());
Type[] paramTypes = BcelWorld.makeBcelTypes(method.getParameterTypes());
int pos = 0;
if (!method.isStatic()) {
il.append(InstructionConstants.ALOAD_0);
pos++;
}
for (int i = 0, len = paramTypes.length; i < len; i++) {
Type paramType = paramTypes[i];
il.append(InstructionFactory.createLoad(paramType, pos));
pos+=paramType.getSize();
}
il.append(Utility.createInvoke(fact, (BcelWorld)aspectType.getWorld(),
method));
il.append(InstructionFactory.createReturn(BcelWorld.makeBcelType(method.getReturnType())));
mg.getBody().insert(il);
gen.addMethodGen(mg);
}
protected LazyMethodGen makeMethodGen(LazyClassGen gen, ResolvedMember member) {
LazyMethodGen ret = new LazyMethodGen(
member.getModifiers(),
BcelWorld.makeBcelType(member.getReturnType()),
member.getName(),
BcelWorld.makeBcelTypes(member.getParameterTypes()),
UnresolvedType.getNames(member.getExceptions()),
gen);
// 43972 : Static crosscutting makes interfaces unusable for javac
// ret.makeSynthetic();
return ret;
}
protected FieldGen makeFieldGen(LazyClassGen gen, ResolvedMember member) {
return new FieldGen(
member.getModifiers(),
BcelWorld.makeBcelType(member.getReturnType()),
member.getName(),
gen.getConstantPoolGen());
}
private boolean mungePerObjectInterface(
BcelClassWeaver weaver,
PerObjectInterfaceTypeMunger munger)
{
//System.err.println("Munging perobject ["+munger+"] onto "+weaver.getLazyClassGen().getClassName());
LazyClassGen gen = weaver.getLazyClassGen();
if (couldMatch(gen.getBcelObjectType(), munger.getTestPointcut())) {
FieldGen fg = makeFieldGen(gen,
AjcMemberMaker.perObjectField(gen.getType(), aspectType));
gen.addField(fg.getField(),getSourceLocation());
Type fieldType = BcelWorld.makeBcelType(aspectType);
LazyMethodGen mg = new LazyMethodGen(
Modifier.PUBLIC,
fieldType,
NameMangler.perObjectInterfaceGet(aspectType),
new Type[0], new String[0],
gen);
InstructionList il = new InstructionList();
InstructionFactory fact = gen.getFactory();
il.append(InstructionConstants.ALOAD_0);
il.append(fact.createFieldAccess(
gen.getClassName(),
fg.getName(),
fieldType, Constants.GETFIELD));
il.append(InstructionFactory.createReturn(fieldType));
mg.getBody().insert(il);
gen.addMethodGen(mg);
LazyMethodGen mg1 = new LazyMethodGen(
Modifier.PUBLIC,
Type.VOID,
NameMangler.perObjectInterfaceSet(aspectType),
new Type[]{fieldType,}, new String[0],
gen);
InstructionList il1 = new InstructionList();
il1.append(InstructionConstants.ALOAD_0);
il1.append(InstructionFactory.createLoad(fieldType, 1));
il1.append(fact.createFieldAccess(
gen.getClassName(),
fg.getName(),
fieldType, Constants.PUTFIELD));
il1.append(InstructionFactory.createReturn(Type.VOID));
mg1.getBody().insert(il1);
gen.addMethodGen(mg1);
gen.addInterface(munger.getInterfaceType(),getSourceLocation());
return true;
} else {
return false;
}
}
// PTWIMPL Add field to hold aspect instance and an accessor
private boolean mungePerTypeWithinTransformer(BcelClassWeaver weaver) {
LazyClassGen gen = weaver.getLazyClassGen();
// if (couldMatch(gen.getBcelObjectType(), munger.getTestPointcut())) {
// Add (to the target type) the field that will hold the aspect instance
// e.g ajc$com_blah_SecurityAspect$ptwAspectInstance
FieldGen fg = makeFieldGen(gen, AjcMemberMaker.perTypeWithinField(gen.getType(), aspectType));
gen.addField(fg.getField(),getSourceLocation());
// Add an accessor for this new field, the ajc$<aspectname>$localAspectOf() method
// e.g. "public com_blah_SecurityAspect ajc$com_blah_SecurityAspect$localAspectOf()"
Type fieldType = BcelWorld.makeBcelType(aspectType);
LazyMethodGen mg = new LazyMethodGen(
Modifier.PUBLIC | Modifier.STATIC,fieldType,
NameMangler.perTypeWithinLocalAspectOf(aspectType),
new Type[0], new String[0],gen);
InstructionList il = new InstructionList();
//PTWIMPL ?? Should check if it is null and throw NoAspectBoundException
InstructionFactory fact = gen.getFactory();
il.append(fact.createFieldAccess(
gen.getClassName(),
fg.getName(),
fieldType, Constants.GETSTATIC));
il.append(InstructionFactory.createReturn(fieldType));
mg.getBody().insert(il);
gen.addMethodGen(mg);
return true;
// } else {
// return false;
// }
}
// ??? Why do we have this method? I thought by now we would know if it matched or not
private boolean couldMatch(
BcelObjectType bcelObjectType,
Pointcut pointcut) {
return !bcelObjectType.isInterface();
}
private boolean mungeNewMethod(BcelClassWeaver weaver, NewMethodTypeMunger munger) {
World w = weaver.getWorld();
// Resolving it will sort out the tvars
ResolvedMember unMangledInterMethod = munger.getSignature().resolve(w);
// do matching on the unMangled one, but actually add them to the mangled method
ResolvedMember interMethodBody = munger.getDeclaredInterMethodBody(aspectType,w);
ResolvedMember interMethodDispatcher = munger.getDeclaredInterMethodDispatcher(aspectType,w);
ResolvedMember memberHoldingAnyAnnotations = interMethodDispatcher;
ResolvedType onType = weaver.getWorld().resolve(unMangledInterMethod.getDeclaringType(),munger.getSourceLocation());
LazyClassGen gen = weaver.getLazyClassGen();
boolean mungingInterface = gen.isInterface();
if (onType.isRawType()) onType = onType.getGenericType();
boolean onInterface = onType.isInterface();
// Simple checks, can't ITD on annotations or enums
if (onType.isAnnotation()) {
signalError(WeaverMessages.ITDM_ON_ANNOTATION_NOT_ALLOWED,weaver,onType);
return false;
}
if (onType.isEnum()) {
signalError(WeaverMessages.ITDM_ON_ENUM_NOT_ALLOWED,weaver,onType);
return false;
}
if (onInterface && gen.getLazyMethodGen(unMangledInterMethod.getName(), unMangledInterMethod.getSignature(),true) != null) {
// this is ok, we could be providing the default implementation of a method
// that the target has already declared
return false;
}
// If we are processing the intended ITD target type (might be an interface)
if (onType.equals(gen.getType())) {
ResolvedMember mangledInterMethod =
AjcMemberMaker.interMethod(unMangledInterMethod, aspectType, onInterface);
LazyMethodGen newMethod = makeMethodGen(gen, mangledInterMethod);
if (mungingInterface) {
// we want the modifiers of the ITD to be used for all *implementors* of the
// interface, but the method itself we add to the interface must be public abstract
newMethod.setAccessFlags(Modifier.PUBLIC | Modifier.ABSTRACT);
}
// pr98901
// For copying the annotations across, we have to discover the real member in the aspect
// which is holding them.
if (weaver.getWorld().isInJava5Mode()){
AnnotationX annotationsOnRealMember[] = null;
ResolvedType toLookOn = aspectType;
if (aspectType.isRawType()) toLookOn = aspectType.getGenericType();
ResolvedMember realMember = getRealMemberForITDFromAspect(toLookOn,memberHoldingAnyAnnotations,false);
if (realMember==null) throw new BCException("Couldn't find ITD holder member '"+
memberHoldingAnyAnnotations+"' on aspect "+aspectType);
annotationsOnRealMember = realMember.getAnnotations();
if (annotationsOnRealMember!=null) {
for (int i = 0; i < annotationsOnRealMember.length; i++) {
AnnotationX annotationX = annotationsOnRealMember[i];
Annotation a = annotationX.getBcelAnnotation();
AnnotationGen ag = new AnnotationGen(a,weaver.getLazyClassGen().getConstantPoolGen(),true);
newMethod.addAnnotation(new AnnotationX(ag.getAnnotation(),weaver.getWorld()));
}
}
// the below loop fixes the very special (and very stupid)
// case where an aspect declares an annotation
// on an ITD it declared on itself.
List allDecams = weaver.getWorld().getDeclareAnnotationOnMethods();
for (Iterator i = allDecams.iterator(); i.hasNext();){
DeclareAnnotation decaMC = (DeclareAnnotation) i.next();
if (decaMC.matches(unMangledInterMethod,weaver.getWorld())
&& newMethod.getEnclosingClass().getType() == aspectType) {
newMethod.addAnnotation(decaMC.getAnnotationX());
}
}
}
// If it doesn't target an interface and there is a body (i.e. it isnt abstract)
if (!onInterface && !Modifier.isAbstract(mangledInterMethod.getModifiers())) {
InstructionList body = newMethod.getBody();
InstructionFactory fact = gen.getFactory();
int pos = 0;
if (!unMangledInterMethod.isStatic()) {
body.append(InstructionFactory.createThis());
pos++;
}
Type[] paramTypes = BcelWorld.makeBcelTypes(mangledInterMethod.getParameterTypes());
for (int i = 0, len = paramTypes.length; i < len; i++) {
Type paramType = paramTypes[i];
body.append(InstructionFactory.createLoad(paramType, pos));
pos+=paramType.getSize();
}
body.append(Utility.createInvoke(fact, weaver.getWorld(), interMethodBody));
body.append(
InstructionFactory.createReturn(
BcelWorld.makeBcelType(mangledInterMethod.getReturnType())));
if (weaver.getWorld().isInJava5Mode()) { // Don't need bridge methods if not in 1.5 mode.
createAnyBridgeMethodsForCovariance(weaver, munger, unMangledInterMethod, onType, gen, paramTypes);
}
} else {
//??? this is okay
//if (!(mg.getBody() == null)) throw new RuntimeException("bas");
}
// XXX make sure to check that we set exceptions properly on this guy.
weaver.addLazyMethodGen(newMethod);
weaver.getLazyClassGen().warnOnAddedMethod(newMethod.getMethod(),getSignature().getSourceLocation());
addNeededSuperCallMethods(weaver, onType, munger.getSuperMethodsCalled());
return true;
} else if (onInterface && !Modifier.isAbstract(unMangledInterMethod.getModifiers())) {
// This means the 'gen' should be the top most implementor
// - if it is *not* then something went wrong after we worked
// out that it was the top most implementor (see pr49657)
if (!gen.getType().isTopmostImplementor(onType)) {
ResolvedType rtx = gen.getType().getTopmostImplementor(onType);
if (!rtx.isExposedToWeaver()) {
ISourceLocation sLoc = munger.getSourceLocation();
weaver.getWorld().getMessageHandler().handleMessage(MessageUtil.error(
WeaverMessages.format(WeaverMessages.ITD_NON_EXPOSED_IMPLEMENTOR,rtx,getAspectType().getName()),
(sLoc==null?getAspectType().getSourceLocation():sLoc)));
} else {
// XXX what does this state mean?
// We have incorrectly identified what is the top most implementor and its not because
// a type wasn't exposed to the weaver
}
return false;
} else {
ResolvedMember mangledInterMethod =
AjcMemberMaker.interMethod(unMangledInterMethod, aspectType, false);
LazyMethodGen mg = makeMethodGen(gen, mangledInterMethod);
// From 98901#29 - need to copy annotations across
if (weaver.getWorld().isInJava5Mode()){
AnnotationX annotationsOnRealMember[] = null;
ResolvedType toLookOn = aspectType;
if (aspectType.isRawType()) toLookOn = aspectType.getGenericType();
ResolvedMember realMember = getRealMemberForITDFromAspect(toLookOn,memberHoldingAnyAnnotations,false);
if (realMember==null) throw new BCException("Couldn't find ITD holder member '"+
memberHoldingAnyAnnotations+"' on aspect "+aspectType);
annotationsOnRealMember = realMember.getAnnotations();
if (annotationsOnRealMember!=null) {
for (int i = 0; i < annotationsOnRealMember.length; i++) {
AnnotationX annotationX = annotationsOnRealMember[i];
Annotation a = annotationX.getBcelAnnotation();
AnnotationGen ag = new AnnotationGen(a,weaver.getLazyClassGen().getConstantPoolGen(),true);
mg.addAnnotation(new AnnotationX(ag.getAnnotation(),weaver.getWorld()));
}
}
}
if (mungingInterface) {
// we want the modifiers of the ITD to be used for all *implementors* of the
// interface, but the method itself we add to the interface must be public abstract
mg.setAccessFlags(Modifier.PUBLIC | Modifier.ABSTRACT);
}
Type[] paramTypes = BcelWorld.makeBcelTypes(mangledInterMethod.getParameterTypes());
Type returnType = BcelWorld.makeBcelType(mangledInterMethod.getReturnType());
InstructionList body = mg.getBody();
InstructionFactory fact = gen.getFactory();
int pos = 0;
if (!mangledInterMethod.isStatic()) {
body.append(InstructionFactory.createThis());
pos++;
}
for (int i = 0, len = paramTypes.length; i < len; i++) {
Type paramType = paramTypes[i];
body.append(InstructionFactory.createLoad(paramType, pos));
pos+=paramType.getSize();
}
body.append(Utility.createInvoke(fact, weaver.getWorld(), interMethodBody));
Type t= BcelWorld.makeBcelType(interMethodBody.getReturnType());
if (!t.equals(returnType)) {
body.append(fact.createCast(t,returnType));
}
body.append(InstructionFactory.createReturn(returnType));
mg.definingType = onType;
weaver.addOrReplaceLazyMethodGen(mg);
addNeededSuperCallMethods(weaver, onType, munger.getSuperMethodsCalled());
// Work out if we need a bridge method for the new method added to the topmostimplementor.
if (munger.getDeclaredSignature()!=null) { // Check if the munger being processed is a parameterized form of some original munger.
boolean needsbridging = false;
ResolvedMember toBridgeTo = munger.getDeclaredSignature().parameterizedWith(null,munger.getSignature().getDeclaringType().resolve(getWorld()),false,munger.getTypeVariableAliases());
if (!toBridgeTo.getReturnType().getErasureSignature().equals(munger.getSignature().getReturnType().getErasureSignature())) needsbridging = true;
UnresolvedType[] originalParams = toBridgeTo.getParameterTypes();
UnresolvedType[] newParams = munger.getSignature().getParameterTypes();
for (int ii = 0;ii<originalParams.length;ii++) {
if (!originalParams[ii].getErasureSignature().equals(newParams[ii].getErasureSignature())) needsbridging=true;
}
if (toBridgeTo!=null && needsbridging) {
ResolvedMember bridgerMethod = AjcMemberMaker.bridgerToInterMethod(unMangledInterMethod,gen.getType());
ResolvedMember bridgingSetter = AjcMemberMaker.interMethod(toBridgeTo, aspectType, false);
// FIXME asc ----------------8<---------------- extract method
LazyMethodGen bridgeMethod = makeMethodGen(gen,bridgingSetter);
paramTypes = BcelWorld.makeBcelTypes(bridgingSetter.getParameterTypes());
Type[] bridgingToParms = BcelWorld.makeBcelTypes(unMangledInterMethod.getParameterTypes());
returnType = BcelWorld.makeBcelType(bridgingSetter.getReturnType());
body = bridgeMethod.getBody();
fact = gen.getFactory();
pos = 0;
if (!bridgingSetter.isStatic()) {
body.append(InstructionFactory.createThis());
pos++;
}
for (int i = 0, len = paramTypes.length; i < len; i++) {
Type paramType = paramTypes[i];
body.append(InstructionFactory.createLoad(paramType, pos));
if (!bridgingSetter.getParameterTypes()[i].getErasureSignature().equals(unMangledInterMethod.getParameterTypes()[i].getErasureSignature()) ) {
// System.err.println("Putting in cast from "+paramType+" to "+bridgingToParms[i]);
body.append(fact.createCast(paramType,bridgingToParms[i]));
}
pos+=paramType.getSize();
}
body.append(Utility.createInvoke(fact, weaver.getWorld(), bridgerMethod));
body.append(InstructionFactory.createReturn(returnType));
gen.addMethodGen(bridgeMethod);
// mg.definingType = onType;
// FIXME asc (see above) ---------------------8<--------------- extract method
}
}
return true;
}
} else {
return false;
}
}
/**
* Create any bridge method required because of covariant returns being used. This method is used in the case
* where an ITD is applied to some type and it may be in an override relationship with a method from the supertype - but
* due to covariance there is a mismatch in return values.
* Example of when required:
Super defines: Object m(String s)
Sub defines: String m(String s)
then we need a bridge method in Sub called 'Object m(String s)' that forwards to 'String m(String s)'
*/
private void createAnyBridgeMethodsForCovariance(BcelClassWeaver weaver, NewMethodTypeMunger munger, ResolvedMember unMangledInterMethod, ResolvedType onType, LazyClassGen gen, Type[] paramTypes) {
// PERFORMANCE BOTTLENECK? Might need investigating, method analysis between types in a hierarchy just seems expensive...
// COVARIANCE BRIDGING
// Algorithm: Step1. Check in this type - has someone already created the bridge method?
// Step2. Look above us - do we 'override' a method and yet differ in return type (i.e. covariance)
// Step3. Create a forwarding bridge method
ResolvedType superclass = onType.getSuperclass();
boolean quitRightNow = false;
String localMethodName = unMangledInterMethod.getName();
String localParameterSig = unMangledInterMethod.getParameterSignature();
String localReturnTypeESig = unMangledInterMethod.getReturnType().getErasureSignature();
// Step1
boolean alreadyDone = false; // Compiler might have done it
ResolvedMember[] localMethods = onType.getDeclaredMethods();
for (int i = 0; i < localMethods.length; i++) {
ResolvedMember member = localMethods[i];
if (member.getName().equals(localMethodName)) {
// Check the params
if (member.getParameterSignature().equals(localParameterSig)) alreadyDone = true;
}
}
// Step2
if (!alreadyDone) {
// Use the iterator form of 'getMethods()' so we do as little work as necessary
for (Iterator iter = onType.getSuperclass().getMethods();iter.hasNext() && !quitRightNow;) {
ResolvedMember aMethod = (ResolvedMember) iter.next();
if (aMethod.getName().equals(localMethodName) && aMethod.getParameterSignature().equals(localParameterSig)) {
// check the return types, if they are different we need a bridging method.
if (!aMethod.getReturnType().getErasureSignature().equals(localReturnTypeESig) && !Modifier.isPrivate(aMethod.getModifiers())) {
// Step3
createBridgeMethod(weaver.getWorld(), munger, unMangledInterMethod, gen, paramTypes, aMethod);
quitRightNow = true;
}
}
}
}
}
/**
* Create a bridge method for a particular munger.
* @param world
* @param munger
* @param unMangledInterMethod the method to bridge 'to' that we have already created in the 'subtype'
* @param clazz the class in which to put the bridge method
* @param paramTypes Parameter types for the bridge method, passed in as an optimization since the caller is likely to have already created them.
* @param theBridgeMethod
*/
private void createBridgeMethod(BcelWorld world, NewMethodTypeMunger munger,
ResolvedMember unMangledInterMethod, LazyClassGen clazz, Type[] paramTypes, ResolvedMember theBridgeMethod) {
InstructionList body;
InstructionFactory fact;
int pos = 0;
LazyMethodGen bridgeMethod = makeMethodGen(clazz,theBridgeMethod); // The bridge method in this type will have the same signature as the one in the supertype
bridgeMethod.setAccessFlags(bridgeMethod.getAccessFlags() | 0x00000040 /*BRIDGE = 0x00000040*/ );
UnresolvedType[] newParams = munger.getSignature().getParameterTypes();
Type returnType = BcelWorld.makeBcelType(theBridgeMethod.getReturnType());
body = bridgeMethod.getBody();
fact = clazz.getFactory();
if (!unMangledInterMethod.isStatic()) {
body.append(InstructionFactory.createThis());
pos++;
}
for (int i = 0, len = paramTypes.length; i < len; i++) {
Type paramType = paramTypes[i];
body.append(InstructionFactory.createLoad(paramType, pos));
// if (!bridgingSetter.getParameterTypes()[i].getErasureSignature().equals(unMangledInterMethod.getParameterTypes()[i].getErasureSignature())) {
// System.err.println("Putting in cast from "+paramType+" to "+bridgingToParms[i]);
// body.append(fact.createCast(paramType,bridgingToParms[i]));
// }
pos+=paramType.getSize();
}
body.append(Utility.createInvoke(fact, world,unMangledInterMethod));
body.append(InstructionFactory.createReturn(returnType));
clazz.addMethodGen(bridgeMethod);
}
private boolean mungeMethodDelegate(BcelClassWeaver weaver, MethodDelegateTypeMunger munger) {
ResolvedMember introduced = munger.getSignature();
LazyClassGen gen = weaver.getLazyClassGen();
ResolvedType fromType = weaver.getWorld().resolve(introduced.getDeclaringType(),munger.getSourceLocation());
if (fromType.isRawType()) fromType = fromType.getGenericType();
if (gen.getType().isAnnotation() || gen.getType().isEnum()) {
// don't signal error as it could be a consequence of a wild type pattern
return false;
}
boolean shouldApply = munger.matches(weaver.getLazyClassGen().getType(), aspectType);
if (shouldApply) {
LazyMethodGen mg = new LazyMethodGen(
introduced.getModifiers() - Modifier.ABSTRACT,
BcelWorld.makeBcelType(introduced.getReturnType()),
introduced.getName(),
BcelWorld.makeBcelTypes(introduced.getParameterTypes()),
BcelWorld.makeBcelTypesAsClassNames(introduced.getExceptions()),
gen
);
//annotation copy from annotation on ITD interface
if (weaver.getWorld().isInJava5Mode()){
AnnotationX annotationsOnRealMember[] = null;
ResolvedType toLookOn = weaver.getWorld().lookupOrCreateName(introduced.getDeclaringType());
if (fromType.isRawType()) toLookOn = fromType.getGenericType();
// lookup the method
ResolvedMember[] ms = toLookOn.getDeclaredJavaMethods();
for (int i = 0; i < ms.length; i++) {
ResolvedMember m = ms[i];
if (introduced.getName().equals(m.getName()) && introduced.getSignature().equals(m.getSignature())) {
annotationsOnRealMember = m.getAnnotations();
}
}
if (annotationsOnRealMember!=null) {
for (int i = 0; i < annotationsOnRealMember.length; i++) {
AnnotationX annotationX = annotationsOnRealMember[i];
Annotation a = annotationX.getBcelAnnotation();
AnnotationGen ag = new AnnotationGen(a,weaver.getLazyClassGen().getConstantPoolGen(),true);
mg.addAnnotation(new AnnotationX(ag.getAnnotation(),weaver.getWorld()));
}
}
}
InstructionList body = new InstructionList();
InstructionFactory fact = gen.getFactory();
// getfield
body.append(InstructionConstants.ALOAD_0);
body.append(Utility.createGet(fact, munger.getDelegate(weaver.getLazyClassGen().getType())));
BranchInstruction ifNonNull = InstructionFactory.createBranchInstruction(Constants.IFNONNULL, null);
body.append(ifNonNull);
// Create and store a new instance
body.append(InstructionConstants.ALOAD_0);
body.append(fact.createNew(munger.getImplClassName()));
body.append(InstructionConstants.DUP);
body.append(fact.createInvoke(munger.getImplClassName(), "<init>", Type.VOID, Type.NO_ARGS, Constants.INVOKESPECIAL));
body.append(Utility.createSet(fact, munger.getDelegate(weaver.getLazyClassGen().getType())));
// 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 (!introduced.isStatic()) { // skip 'this' (?? can this really happen)
//body.append(InstructionFactory.createThis());
pos++;
}
Type[] paramTypes = BcelWorld.makeBcelTypes(introduced.getParameterTypes());
for (int i = 0, len = paramTypes.length; i < len; i++) {
Type paramType = paramTypes[i];
body.append(InstructionFactory.createLoad(paramType, pos));
pos+=paramType.getSize();
}
body.append(Utility.createInvoke(fact, Constants.INVOKEINTERFACE, introduced));
body.append(
InstructionFactory.createReturn(
BcelWorld.makeBcelType(introduced.getReturnType())
)
);
mg.getBody().append(body);
weaver.addLazyMethodGen(mg);
weaver.getLazyClassGen().warnOnAddedMethod(mg.getMethod(),getSignature().getSourceLocation());
return true;
}
return false;
}
private boolean mungeFieldHost(BcelClassWeaver weaver, MethodDelegateTypeMunger.FieldHostTypeMunger munger) {
LazyClassGen gen = weaver.getLazyClassGen();
if (gen.getType().isAnnotation() || gen.getType().isEnum()) {
// don't signal error as it could be a consequence of a wild type pattern
return false;
}
boolean shouldApply = munger.matches(weaver.getLazyClassGen().getType(), aspectType);
ResolvedMember host = AjcMemberMaker.itdAtDeclareParentsField(
weaver.getLazyClassGen().getType(),
munger.getSignature().getType(),
aspectType);
weaver.getLazyClassGen().addField(makeFieldGen(
weaver.getLazyClassGen(),
host).getField(), null);
return true;
}
private ResolvedMember getRealMemberForITDFromAspect(ResolvedType aspectType,ResolvedMember lookingFor,boolean isCtorRelated) {
World world = aspectType.getWorld();
boolean debug = false;
if (debug) {
System.err.println("Searching for a member on type: "+aspectType);
System.err.println("Member we are looking for: "+lookingFor);
}
ResolvedMember aspectMethods[] = aspectType.getDeclaredMethods();
UnresolvedType [] lookingForParams = lookingFor.getParameterTypes();
ResolvedMember realMember = null;
for (int i = 0; realMember==null && i < aspectMethods.length; i++) {
ResolvedMember member = aspectMethods[i];
if (member.getName().equals(lookingFor.getName())){
UnresolvedType [] memberParams = member.getGenericParameterTypes();
if (memberParams.length == lookingForParams.length){
if (debug) System.err.println("Reviewing potential candidates: "+member);
boolean matchOK = true;
// If not related to a ctor ITD then the name is enough to confirm we have the
// right one. If it is ctor related we need to check the params all match, although
// only the erasure.
if (isCtorRelated) {
for (int j = 0; j < memberParams.length && matchOK; j++){
ResolvedType pMember = memberParams[j].resolve(world);
ResolvedType pLookingFor = lookingForParams[j].resolve(world);
if (pMember.isTypeVariableReference())
pMember = ((TypeVariableReference)pMember).getTypeVariable().getFirstBound().resolve(world);
if (pMember.isParameterizedType() || pMember.isGenericType())
pMember = pMember.getRawType().resolve(aspectType.getWorld());
if (pLookingFor.isTypeVariableReference())
pLookingFor = ((TypeVariableReference)pLookingFor).getTypeVariable().getFirstBound().resolve(world);
if (pLookingFor.isParameterizedType() || pLookingFor.isGenericType())
pLookingFor = pLookingFor.getRawType().resolve(world);
if (debug) System.err.println("Comparing parameter "+j+" member="+pMember+" lookingFor="+pLookingFor);
if (!pMember.equals(pLookingFor)){
matchOK=false;
}
}
}
if (matchOK) realMember = member;
}
}
}
if (debug && realMember==null) System.err.println("Didn't find a match");
return realMember;
}
private void addNeededSuperCallMethods(
BcelClassWeaver weaver,
ResolvedType onType,
Set neededSuperCalls)
{
LazyClassGen gen = weaver.getLazyClassGen();
for (Iterator iter = neededSuperCalls.iterator(); iter.hasNext();) {
ResolvedMember superMethod = (ResolvedMember) iter.next();
if (weaver.addDispatchTarget(superMethod)) {
//System.err.println("super type: " + superMethod.getDeclaringType() + ", " + gen.getType());
boolean isSuper = !superMethod.getDeclaringType().equals(gen.getType());
String dispatchName;
if (isSuper)
dispatchName =
NameMangler.superDispatchMethod(onType, superMethod.getName());
else
dispatchName =
NameMangler.protectedDispatchMethod(
onType,
superMethod.getName());
LazyMethodGen dispatcher =
makeDispatcher(
gen,
dispatchName,
superMethod,
weaver.getWorld(),
isSuper);
weaver.addLazyMethodGen(dispatcher);
}
}
}
private void signalError(String msgid,BcelClassWeaver weaver,UnresolvedType onType) {
IMessage msg = MessageUtil.error(
WeaverMessages.format(msgid,onType.getName()),getSourceLocation());
weaver.getWorld().getMessageHandler().handleMessage(msg);
}
private boolean mungeNewConstructor(
BcelClassWeaver weaver,
NewConstructorTypeMunger newConstructorTypeMunger)
{
final LazyClassGen currentClass = weaver.getLazyClassGen();
final InstructionFactory fact = currentClass.getFactory();
ResolvedMember newConstructorMember = newConstructorTypeMunger.getSyntheticConstructor();
ResolvedType onType = newConstructorMember.getDeclaringType().resolve(weaver.getWorld());
if (onType.isRawType()) onType = onType.getGenericType();
if (onType.isAnnotation()) {
signalError(WeaverMessages.ITDC_ON_ANNOTATION_NOT_ALLOWED,weaver,onType);
return false;
}
if (onType.isEnum()) {
signalError(WeaverMessages.ITDC_ON_ENUM_NOT_ALLOWED,weaver,onType);
return false;
}
if (! onType.equals(currentClass.getType())) return false;
ResolvedMember explicitConstructor = newConstructorTypeMunger.getExplicitConstructor();
//int declaredParameterCount = newConstructorTypeMunger.getDeclaredParameterCount();
LazyMethodGen mg =
makeMethodGen(currentClass, newConstructorMember);
mg.setEffectiveSignature(newConstructorTypeMunger.getSignature(),Shadow.ConstructorExecution,true);
// pr98901
// For copying the annotations across, we have to discover the real member in the aspect
// which is holding them.
if (weaver.getWorld().isInJava5Mode()){
ResolvedMember interMethodDispatcher =AjcMemberMaker.postIntroducedConstructor(aspectType,onType,newConstructorTypeMunger.getSignature().getParameterTypes());
AnnotationX annotationsOnRealMember[] = null;
ResolvedMember realMember = getRealMemberForITDFromAspect(aspectType,interMethodDispatcher,true);
if (realMember==null) throw new BCException("Couldn't find ITD holder member '"+
interMethodDispatcher+"' on aspect "+aspectType);
annotationsOnRealMember = realMember.getAnnotations();
if (annotationsOnRealMember!=null) {
for (int i = 0; i < annotationsOnRealMember.length; i++) {
AnnotationX annotationX = annotationsOnRealMember[i];
Annotation a = annotationX.getBcelAnnotation();
AnnotationGen ag = new AnnotationGen(a,weaver.getLazyClassGen().getConstantPoolGen(),true);
mg.addAnnotation(new AnnotationX(ag.getAnnotation(),weaver.getWorld()));
}
}
// the below loop fixes the very special (and very stupid)
// case where an aspect declares an annotation
// on an ITD it declared on itself.
List allDecams = weaver.getWorld().getDeclareAnnotationOnMethods();
for (Iterator i = allDecams.iterator(); i.hasNext();){
DeclareAnnotation decaMC = (DeclareAnnotation) i.next();
if (decaMC.matches(explicitConstructor,weaver.getWorld())
&& mg.getEnclosingClass().getType() == aspectType) {
mg.addAnnotation(decaMC.getAnnotationX());
}
}
}
currentClass.addMethodGen(mg);
//weaver.addLazyMethodGen(freshConstructor);
InstructionList body = mg.getBody();
// add to body: push arts for call to pre, from actual args starting at 1 (skipping this), going to
// declared argcount + 1
UnresolvedType[] declaredParams = newConstructorTypeMunger.getSignature().getParameterTypes();
Type[] paramTypes = mg.getArgumentTypes();
int frameIndex = 1;
for (int i = 0, len = declaredParams.length; i < len; i++) {
body.append(InstructionFactory.createLoad(paramTypes[i], frameIndex));
frameIndex += paramTypes[i].getSize();
}
// do call to pre
Member preMethod =
AjcMemberMaker.preIntroducedConstructor(aspectType, onType, declaredParams);
body.append(Utility.createInvoke(fact, null, preMethod));
// create a local, and store return pre stuff into it.
int arraySlot = mg.allocateLocal(1);
body.append(InstructionFactory.createStore(Type.OBJECT, arraySlot));
// put this on the stack
body.append(InstructionConstants.ALOAD_0);
// unpack pre args onto stack
UnresolvedType[] superParamTypes = explicitConstructor.getParameterTypes();
for (int i = 0, len = superParamTypes.length; i < len; i++) {
body.append(InstructionFactory.createLoad(Type.OBJECT, arraySlot));
body.append(Utility.createConstant(fact, i));
body.append(InstructionFactory.createArrayLoad(Type.OBJECT));
body.append(
Utility.createConversion(
fact,
Type.OBJECT,
BcelWorld.makeBcelType(superParamTypes[i])));
}
// call super/this
body.append(Utility.createInvoke(fact, null, explicitConstructor));
// put this back on the stack
body.append(InstructionConstants.ALOAD_0);
// unpack params onto stack
Member postMethod =
AjcMemberMaker.postIntroducedConstructor(aspectType, onType, declaredParams);
UnresolvedType[] postParamTypes = postMethod.getParameterTypes();
for (int i = 1, len = postParamTypes.length; i < len; i++) {
body.append(InstructionFactory.createLoad(Type.OBJECT, arraySlot));
body.append(Utility.createConstant(fact, superParamTypes.length + i-1));
body.append(InstructionFactory.createArrayLoad(Type.OBJECT));
body.append(
Utility.createConversion(
fact,
Type.OBJECT,
BcelWorld.makeBcelType(postParamTypes[i])));
}
// call post
body.append(Utility.createInvoke(fact, null, postMethod));
// don't forget to return!!
body.append(InstructionConstants.RETURN);
return true;
}
private static LazyMethodGen makeDispatcher(
LazyClassGen onGen,
String dispatchName,
ResolvedMember superMethod,
BcelWorld world,
boolean isSuper)
{
Type[] paramTypes = BcelWorld.makeBcelTypes(superMethod.getParameterTypes());
Type returnType = BcelWorld.makeBcelType(superMethod.getReturnType());
int modifiers = Modifier.PUBLIC;
if (onGen.isInterface()) modifiers |= Modifier.ABSTRACT;
LazyMethodGen mg =
new LazyMethodGen(
modifiers,
returnType,
dispatchName,
paramTypes,
UnresolvedType.getNames(superMethod.getExceptions()),
onGen);
InstructionList body = mg.getBody();
if (onGen.isInterface()) return mg;
// assert (!superMethod.isStatic())
InstructionFactory fact = onGen.getFactory();
int pos = 0;
body.append(InstructionFactory.createThis());
pos++;
for (int i = 0, len = paramTypes.length; i < len; i++) {
Type paramType = paramTypes[i];
body.append(InstructionFactory.createLoad(paramType, pos));
pos+=paramType.getSize();
}
if (isSuper) {
body.append(Utility.createSuperInvoke(fact, world, superMethod));
} else {
body.append(Utility.createInvoke(fact, world, superMethod));
}
body.append(InstructionFactory.createReturn(returnType));
return mg;
}
private boolean mungeNewField(BcelClassWeaver weaver, NewFieldTypeMunger munger) {
/*ResolvedMember initMethod = */munger.getInitMethod(aspectType);
LazyClassGen gen = weaver.getLazyClassGen();
ResolvedMember field = munger.getSignature();
ResolvedType onType = weaver.getWorld().resolve(field.getDeclaringType(),munger.getSourceLocation());
if (onType.isRawType()) onType = onType.getGenericType();
boolean onInterface = onType.isInterface();
if (onType.isAnnotation()) {
signalError(WeaverMessages.ITDF_ON_ANNOTATION_NOT_ALLOWED,weaver,onType);
return false;
}
if (onType.isEnum()) {
signalError(WeaverMessages.ITDF_ON_ENUM_NOT_ALLOWED,weaver,onType);
return false;
}
ResolvedMember interMethodBody = munger.getInitMethod(aspectType);
AnnotationX annotationsOnRealMember[] = null;
// pr98901
// For copying the annotations across, we have to discover the real member in the aspect
// which is holding them.
if (weaver.getWorld().isInJava5Mode()){
// the below line just gets the method with the same name in aspectType.getDeclaredMethods();
ResolvedType toLookOn = aspectType;
if (aspectType.isRawType()) toLookOn = aspectType.getGenericType();
ResolvedMember realMember = getRealMemberForITDFromAspect(toLookOn,interMethodBody,false);
if (realMember==null) throw new BCException("Couldn't find ITD init member '"+
interMethodBody+"' on aspect "+aspectType);
annotationsOnRealMember = realMember.getAnnotations();
}
if (onType.equals(gen.getType())) {
if (onInterface) {
ResolvedMember itdfieldGetter = AjcMemberMaker.interFieldInterfaceGetter(field, onType, aspectType);
LazyMethodGen mg = makeMethodGen(gen, itdfieldGetter);
gen.addMethodGen(mg);
LazyMethodGen mg1 = makeMethodGen(gen,
AjcMemberMaker.interFieldInterfaceSetter(field, onType, aspectType));
gen.addMethodGen(mg1);
} else {
weaver.addInitializer(this);
FieldGen fg = makeFieldGen(gen,
AjcMemberMaker.interFieldClassField(field, aspectType));
if (annotationsOnRealMember!=null) {
for (int i = 0; i < annotationsOnRealMember.length; i++) {
AnnotationX annotationX = annotationsOnRealMember[i];
Annotation a = annotationX.getBcelAnnotation();
AnnotationGen ag = new AnnotationGen(a,weaver.getLazyClassGen().getConstantPoolGen(),true);
fg.addAnnotation(ag);
}
}
gen.addField(fg.getField(),getSourceLocation());
}
return true;
} else if (onInterface && gen.getType().isTopmostImplementor(onType)) {
// wew know that we can't be static since we don't allow statics on interfaces
if (field.isStatic()) throw new RuntimeException("unimplemented");
weaver.addInitializer(this);
//System.err.println("impl body on " + gen.getType() + " for " + munger);
Type fieldType = BcelWorld.makeBcelType(field.getType());
FieldGen fg = makeFieldGen(gen,AjcMemberMaker.interFieldInterfaceField(field, onType, aspectType));
if (annotationsOnRealMember!=null) {
for (int i = 0; i < annotationsOnRealMember.length; i++) {
AnnotationX annotationX = annotationsOnRealMember[i];
Annotation a = annotationX.getBcelAnnotation();
AnnotationGen ag = new AnnotationGen(a,weaver.getLazyClassGen().getConstantPoolGen(),true);
fg.addAnnotation(ag);
}
}
gen.addField(fg.getField(),getSourceLocation());
//this uses a shadow munger to add init method to constructors
//weaver.getShadowMungers().add(makeInitCallShadowMunger(initMethod));
ResolvedMember itdfieldGetter = AjcMemberMaker.interFieldInterfaceGetter(field, gen.getType()/*onType*/, aspectType);
LazyMethodGen mg = makeMethodGen(gen, itdfieldGetter);
InstructionList il = new InstructionList();
InstructionFactory fact = gen.getFactory();
if (field.isStatic()) {
il.append(fact.createFieldAccess(
gen.getClassName(),
fg.getName(),
fieldType, Constants.GETSTATIC));
} else {
il.append(InstructionConstants.ALOAD_0);
il.append(fact.createFieldAccess(
gen.getClassName(),
fg.getName(),
fieldType, Constants.GETFIELD));
}
il.append(InstructionFactory.createReturn(fieldType));
mg.getBody().insert(il);
gen.addMethodGen(mg);
// Check if we need bridge methods for the field getter and setter
if (munger.getDeclaredSignature()!=null) { // is this munger a parameterized form of some original munger?
ResolvedMember toBridgeTo = munger.getDeclaredSignature().parameterizedWith(null,munger.getSignature().getDeclaringType().resolve(getWorld()),false,munger.getTypeVariableAliases());
boolean needsbridging = false;
if (!toBridgeTo.getReturnType().getErasureSignature().equals(munger.getSignature().getReturnType().getErasureSignature())) needsbridging = true;
if (toBridgeTo!=null && needsbridging) {
ResolvedMember bridgingGetter = AjcMemberMaker.interFieldInterfaceGetter(toBridgeTo, gen.getType(), aspectType);
createBridgeMethodForITDF(weaver,gen,itdfieldGetter,bridgingGetter);
}
}
ResolvedMember itdfieldSetter = AjcMemberMaker.interFieldInterfaceSetter(field, gen.getType(), aspectType);
LazyMethodGen mg1 = makeMethodGen(gen, itdfieldSetter);
InstructionList il1 = new InstructionList();
if (field.isStatic()) {
il1.append(InstructionFactory.createLoad(fieldType, 0));
il1.append(fact.createFieldAccess(
gen.getClassName(),
fg.getName(),
fieldType, Constants.PUTSTATIC));
} else {
il1.append(InstructionConstants.ALOAD_0);
il1.append(InstructionFactory.createLoad(fieldType, 1));
il1.append(fact.createFieldAccess(
gen.getClassName(),
fg.getName(),
fieldType, Constants.PUTFIELD));
}
il1.append(InstructionFactory.createReturn(Type.VOID));
mg1.getBody().insert(il1);
gen.addMethodGen(mg1);
if (munger.getDeclaredSignature()!=null) {
ResolvedMember toBridgeTo = munger.getDeclaredSignature().parameterizedWith(null,munger.getSignature().getDeclaringType().resolve(getWorld()),false,munger.getTypeVariableAliases());
boolean needsbridging = false;
if (!toBridgeTo.getReturnType().getErasureSignature().equals(munger.getSignature().getReturnType().getErasureSignature())) needsbridging = true;
if (toBridgeTo!=null && needsbridging) {
ResolvedMember bridgingSetter = AjcMemberMaker.interFieldInterfaceSetter(toBridgeTo, gen.getType(), aspectType);
createBridgeMethodForITDF(weaver, gen, itdfieldSetter, bridgingSetter);
}
}
return true;
} else {
return false;
}
}
// FIXME asc combine with other createBridge.. method in this class, avoid the duplication...
private void createBridgeMethodForITDF(BcelClassWeaver weaver, LazyClassGen gen, ResolvedMember itdfieldSetter, ResolvedMember bridgingSetter) {
InstructionFactory fact;
LazyMethodGen bridgeMethod = makeMethodGen(gen,bridgingSetter);
Type[] paramTypes = BcelWorld.makeBcelTypes(bridgingSetter.getParameterTypes());
Type[] bridgingToParms = BcelWorld.makeBcelTypes(itdfieldSetter.getParameterTypes());
Type returnType = BcelWorld.makeBcelType(bridgingSetter.getReturnType());
InstructionList body = bridgeMethod.getBody();
fact = gen.getFactory();
int pos = 0;
if (!bridgingSetter.isStatic()) {
body.append(InstructionFactory.createThis());
pos++;
}
for (int i = 0, len = paramTypes.length; i < len; i++) {
Type paramType = paramTypes[i];
body.append(InstructionFactory.createLoad(paramType, pos));
if (!bridgingSetter.getParameterTypes()[i].getErasureSignature().equals(itdfieldSetter.getParameterTypes()[i].getErasureSignature()) ) {
// une cast est required
System.err.println("Putting in cast from "+paramType+" to "+bridgingToParms[i]);
body.append(fact.createCast(paramType,bridgingToParms[i]));
}
pos+=paramType.getSize();
}
body.append(Utility.createInvoke(fact, weaver.getWorld(), itdfieldSetter));
body.append(InstructionFactory.createReturn(returnType));
gen.addMethodGen(bridgeMethod);
}
public ConcreteTypeMunger parameterizedFor(ResolvedType target) {
return new BcelTypeMunger(munger.parameterizedFor(target),aspectType);
}
/**
* Returns a list of type variable aliases used in this munger. For example, if the
* ITD is 'int I<A,B>.m(List<A> las,List<B> lbs) {}' then this returns a list containing
* the strings "A" and "B".
*/
public List /*String*/ getTypeVariableAliases() {
return munger.getTypeVariableAliases();
}
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()))
&& (World.compareLocations?((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;
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;
}
/**
* Some type mungers are created purely to help with the implementation of shadow mungers.
* For example to support the cflow() pointcut we create a new cflow field in the aspect, and
* that is added via a BcelCflowCounterFieldAdder.
*
* During compilation we need to compare sets of type mungers, and if some only come into
* existence after the 'shadowy' type things have been processed, we need to ignore
* them during the comparison.
*
* Returning true from this method indicates the type munger exists to support 'shadowy' stuff -
* and so can be ignored in some comparison.
*/
public boolean existsToSupportShadowMunging() {
if (munger != null) {
return munger.existsToSupportShadowMunging();
}
return false;
}
}
|
148,737 |
Bug 148737 IllegalStateException for non-generic type
|
I believe this is similar to 112880. The message and stack trace I am getting are -- (IllegalStateException) Can't ask to parameterize a member of non-generic type: com...object kind(raw) Can't ask to parameterize a member of non-generic type: com...object kind(raw) java.lang.IllegalStateException: Can't ask to parameterize a member of non-generic type: com....object kind(raw) at org.aspectj.weaver.ResolvedMemberImpl.parameterizedWith(ResolvedMemberImpl.java:612) at org.aspectj.weaver.ResolvedMemberImpl.parameterizedWith(ResolvedMemberImpl.java:597) at org.aspectj.weaver.ReferenceType.getDeclaredMethods(ReferenceType.java:508) at org.aspectj.weaver.ResolvedType$4.get(ResolvedType.java:225) at org.aspectj.weaver.Iterators$3$1.hasNext(Iterators.java:118) at org.aspectj.weaver.Iterators$5.hasNext(Iterators.java:171) at org.aspectj.weaver.Iterators$3.hasNext(Iterators.java:128) at org.aspectj.weaver.ResolvedType.lookupMember(ResolvedType.java:345) at org.aspectj.weaver.ResolvedType.lookupMethod(ResolvedType.java:326) . . . The same code was able to be weaved under 1.5.0. The reason why this is a major issue is 1.5.0 suffers from a StackOverflowException.
|
resolved fixed
|
f6834c7
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-07-03T13:49:07Z | 2006-06-27T01:00:00Z |
org.aspectj.ajdt.core/src/org/aspectj/ajdt/ajc/BuildArgParser.java
|
/* *******************************************************************
* Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC).
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the 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.ajc;
import java.io.*;
import java.util.*;
import org.aspectj.ajdt.internal.core.builder.*;
import org.aspectj.bridge.*;
import org.aspectj.util.*;
import org.aspectj.weaver.Constants;
import org.aspectj.weaver.Dump;
import org.aspectj.weaver.WeaverMessages;
import org.aspectj.org.eclipse.jdt.core.compiler.InvalidInputException;
import org.aspectj.org.eclipse.jdt.internal.compiler.batch.Main;
import org.aspectj.org.eclipse.jdt.internal.compiler.impl.CompilerOptions;
public class BuildArgParser extends Main {
private static final String BUNDLE_NAME = "org.aspectj.ajdt.ajc.messages";
private static boolean LOADED_BUNDLE = false;
static {
bundle = ResourceBundle.getBundle(BUNDLE_NAME);
if (!LOADED_BUNDLE) {
LOADED_BUNDLE = true;
}
}
/** to initialize super's PrintWriter but refer to underlying StringWriter */
private static class StringPrintWriter extends PrintWriter {
public final StringWriter stringWriter;
StringPrintWriter(StringWriter sw) {
super(sw);
this.stringWriter = sw;
}
}
/** @return multi-line String usage for the compiler */
public static String getUsage() {
return Main.bind("misc.usage",Main.bind("compiler.name"));
}
public static String getXOptionUsage() {
return Main.bind("xoption.usage",Main.bind("compiler.name"));
}
/**
* StringWriter sink for some errors.
* This only captures errors not handled by any IMessageHandler parameter
* and only when no PrintWriter is set in the constructor.
* XXX This relies on (Sun's) implementation of StringWriter,
* which returns the actual (not copy) internal StringBuffer.
*/
private final StringBuffer errorSink;
private IMessageHandler handler;
/**
* Overrides super's bundle.
*/
public BuildArgParser(PrintWriter writer, IMessageHandler handler) {
super(writer, writer, false);
if (writer instanceof StringPrintWriter) {
errorSink = ((StringPrintWriter) writer).stringWriter.getBuffer();
} else {
errorSink = null;
}
this.handler = handler;
}
/** Set up to capture messages using getOtherMessages(boolean) */
public BuildArgParser(IMessageHandler handler) {
this(new StringPrintWriter(new StringWriter()),handler);
}
/**
* Generate build configuration for the input args,
* passing to handler any error messages.
* @param args the String[] arguments for the build configuration
* @return AjBuildConfig per args,
* which will be invalid unless there are no handler errors.
*/
public AjBuildConfig genBuildConfig(String[] args) {
AjBuildConfig config = new AjBuildConfig();
populateBuildConfig(config, args, true, null);
return config;
}
/**
* Generate build configuration for the input args,
* passing to handler any error messages.
* @param args the String[] arguments for the build configuration
* @param setClasspath determines if the classpath should be parsed and set on the build configuration
* @param configFile can be null
* @return AjBuildConfig per args,
* which will be invalid unless there are no handler errors.
*/
public AjBuildConfig populateBuildConfig(AjBuildConfig buildConfig, String[] args, boolean setClasspath, File configFile) {
Dump.saveCommandLine(args);
buildConfig.setConfigFile(configFile);
try {
// sets filenames to be non-null in order to make sure that file paramters are ignored
super.filenames = new String[] { "" };
AjcConfigParser parser = new AjcConfigParser(buildConfig, handler);
parser.parseCommandLine(args);
boolean swi = buildConfig.getShowWeavingInformation();
// Now jump through firey hoops to turn them on/off
if (handler instanceof CountingMessageHandler) {
IMessageHandler delegate = ((CountingMessageHandler)handler).delegate;
// Without dontIgnore() on the IMessageHandler interface, we have to do this *blurgh*
if (delegate instanceof MessageHandler) {
if (swi)
((MessageHandler)delegate).dontIgnore(IMessage.WEAVEINFO);
else
((MessageHandler)delegate).ignore(IMessage.WEAVEINFO);
}
}
boolean incrementalMode = buildConfig.isIncrementalMode()
|| buildConfig.isIncrementalFileMode();
List fileList = new ArrayList();
List files = parser.getFiles();
if (!LangUtil.isEmpty(files)) {
if (incrementalMode) {
MessageUtil.error(handler, "incremental mode only handles source files using -sourceroots");
} else {
fileList.addAll(files);
}
}
List javaArgList = new ArrayList();
// disable all special eclipse warnings by default - why???
//??? might want to instead override getDefaultOptions()
javaArgList.add("-warn:none");
// these next four lines are some nonsense to fool the eclipse batch compiler
// without these it will go searching for reasonable values from properties
//TODO fix org.eclipse.jdt.internal.compiler.batch.Main so this hack isn't needed
javaArgList.add("-classpath");
javaArgList.add(System.getProperty("user.dir"));
javaArgList.add("-bootclasspath");
javaArgList.add(System.getProperty("user.dir"));
javaArgList.addAll(parser.getUnparsedArgs());
super.configure((String[])javaArgList.toArray(new String[javaArgList.size()]));
if (!proceed) {
buildConfig.doNotProceed();
return buildConfig;
}
if (buildConfig.getSourceRoots() != null) {
for (Iterator i = buildConfig.getSourceRoots().iterator(); i.hasNext(); ) {
fileList.addAll(collectSourceRootFiles((File)i.next()));
}
}
buildConfig.setFiles(fileList);
if (destinationPath != null) { // XXX ?? unparsed but set?
buildConfig.setOutputDir(new File(destinationPath));
}
if (setClasspath) {
buildConfig.setClasspath(getClasspath(parser));
buildConfig.setBootclasspath(getBootclasspath(parser));
}
if (incrementalMode
&& (0 == buildConfig.getSourceRoots().size())) {
MessageUtil.error(handler, "specify a source root when in incremental mode");
}
/*
* Ensure we don't overwrite injars, inpath or aspectpath with outjar
* bug-71339
*/
File outjar = buildConfig.getOutputJar();
if (outjar != null) {
/* Search injars */
for (Iterator i = buildConfig.getInJars().iterator(); i.hasNext(); ) {
File injar = (File)i.next();
if (injar.equals(outjar)) {
String message = WeaverMessages.format(WeaverMessages.OUTJAR_IN_INPUT_PATH);
MessageUtil.error(handler,message);
}
}
/* Search inpath */
for (Iterator i = buildConfig.getInpath().iterator(); i.hasNext(); ) {
File inPathElement = (File)i.next();
if (!inPathElement.isDirectory() && inPathElement.equals(outjar)) {
String message = WeaverMessages.format(WeaverMessages.OUTJAR_IN_INPUT_PATH);
MessageUtil.error(handler,message);
}
}
/* Search aspectpath */
for (Iterator i = buildConfig.getAspectpath().iterator(); i.hasNext(); ) {
File pathElement = (File)i.next();
if (!pathElement.isDirectory() && pathElement.equals(outjar)) {
String message = WeaverMessages.format(WeaverMessages.OUTJAR_IN_INPUT_PATH);
MessageUtil.error(handler,message);
}
}
}
setDebugOptions();
buildConfig.getOptions().set(options);
} catch (InvalidInputException iie) {
ISourceLocation location = null;
if (buildConfig.getConfigFile() != null) {
location = new SourceLocation(buildConfig.getConfigFile(), 0);
}
IMessage m = new Message(iie.getMessage(), IMessage.ERROR, null, location);
handler.handleMessage(m);
}
return buildConfig;
}
// from super...
public void printVersion() {
System.err.println("AspectJ Compiler " + Version.text + " built on " + Version.time_text); //$NON-NLS-1$
System.err.flush();
}
public void printUsage() {
System.out.println(bind("misc.usage")); //$NON-NLS-1$
System.out.flush();
}
/**
* Get messages not dumped to handler or any PrintWriter.
* @param flush if true, empty errors
* @return null if none, String otherwise
* @see BuildArgParser()
*/
public String getOtherMessages(boolean flush) {
if (null == errorSink) {
return null;
}
String result = errorSink.toString().trim();
if (0 == result.length()) {
result = null;
}
if (flush) {
errorSink.setLength(0);
}
return result;
}
private void setDebugOptions() {
options.put(
CompilerOptions.OPTION_LocalVariableAttribute,
CompilerOptions.GENERATE);
options.put(
CompilerOptions.OPTION_LineNumberAttribute,
CompilerOptions.GENERATE);
options.put(
CompilerOptions.OPTION_SourceFileAttribute,
CompilerOptions.GENERATE);
}
private Collection collectSourceRootFiles(File dir) {
return Arrays.asList(FileUtil.listFiles(dir, FileUtil.aspectjSourceFileFilter));
}
public List getBootclasspath(AjcConfigParser parser) {
List ret = new ArrayList();
if (parser.bootclasspath == null) {
addClasspath(System.getProperty("sun.boot.class.path", ""), ret);
} else {
addClasspath(parser.bootclasspath, ret);
}
return ret;
}
/**
* If the classpath is not set, we use the environment's java.class.path, but remove
* the aspectjtools.jar entry from that list in order to prevent wierd bootstrap issues
* (refer to bug#39959).
*/
public List getClasspath(AjcConfigParser parser) {
List ret = new ArrayList();
// if (parser.bootclasspath == null) {
// addClasspath(System.getProperty("sun.boot.class.path", ""), ret);
// } else {
// addClasspath(parser.bootclasspath, ret);
// }
String extdirs = parser.extdirs;
if (extdirs == null) {
extdirs = System.getProperty("java.ext.dirs", "");
}
addExtDirs(extdirs, ret);
if (parser.classpath == null) {
addClasspath(System.getProperty("java.class.path", ""), ret);
List fixedList = new ArrayList();
for (Iterator it = ret.iterator(); it.hasNext(); ) {
String entry = (String)it.next();
if (!entry.endsWith("aspectjtools.jar")) {
fixedList.add(entry);
}
}
ret = fixedList;
} else {
addClasspath(parser.classpath, ret);
}
//??? eclipse seems to put outdir on the classpath
//??? we're brave and believe we don't need it
return ret;
}
private void addExtDirs(String extdirs, List classpathCollector) {
StringTokenizer tokenizer = new StringTokenizer(extdirs, File.pathSeparator);
while (tokenizer.hasMoreTokens()) {
// classpathCollector.add(tokenizer.nextToken());
File dirFile = new File((String)tokenizer.nextToken());
if (dirFile.canRead() && dirFile.isDirectory()) {
File[] files = dirFile.listFiles(FileUtil.ZIP_FILTER);
for (int i = 0; i < files.length; i++) {
classpathCollector.add(files[i].getAbsolutePath());
}
} else {
// XXX alert on invalid -extdirs entries
}
}
}
private void addClasspath(String classpath, List classpathCollector) {
StringTokenizer tokenizer = new StringTokenizer(classpath, File.pathSeparator);
while (tokenizer.hasMoreTokens()) {
classpathCollector.add(tokenizer.nextToken());
}
}
private class AjcConfigParser extends ConfigParser {
private String bootclasspath = null;
private String classpath = null;
private String extdirs = null;
private List unparsedArgs = new ArrayList();
private AjBuildConfig buildConfig;
private IMessageHandler handler;
public AjcConfigParser(AjBuildConfig buildConfig, IMessageHandler handler) {
this.buildConfig = buildConfig;
this.handler = handler;
}
public List getUnparsedArgs() {
return unparsedArgs;
}
/**
* Extract AspectJ-specific options (except for argfiles).
* Caller should warn when sourceroots is empty but in
* incremental mode.
* Signals warnings or errors through handler set in constructor.
*/
public void parseOption(String arg, LinkedList args) { // XXX use ListIterator.remove()
int nextArgIndex = args.indexOf(arg)+1; // XXX assumes unique
// trim arg?
buildConfig.setXlazyTjp(true); // now default - MINOR could be pushed down and made default at a lower level
if (LangUtil.isEmpty(arg)) {
showWarning("empty arg found");
} else if (arg.equals("-inpath")) {;
if (args.size() > nextArgIndex) {
// buildConfig.getAjOptions().put(AjCompilerOptions.OPTION_Inpath, CompilerOptions.PRESERVE);
List inPath = buildConfig.getInpath();
StringTokenizer st = new StringTokenizer(
((ConfigParser.Arg)args.get(nextArgIndex)).getValue(),
File.pathSeparator);
while (st.hasMoreTokens()) {
String filename = st.nextToken();
File file = makeFile(filename);
if (FileUtil.isZipFile(file)) {
inPath.add(file);
} else {
if (file.isDirectory()) {
inPath.add(file);
} else
showWarning("skipping missing, empty or corrupt inpath entry: " + filename);
}
}
buildConfig.setInPath(inPath);
args.remove(args.get(nextArgIndex));
}
} else if (arg.equals("-injars")) {;
if (args.size() > nextArgIndex) {
// buildConfig.getAjOptions().put(AjCompilerOptions.OPTION_InJARs, CompilerOptions.PRESERVE);
StringTokenizer st = new StringTokenizer(
((ConfigParser.Arg)args.get(nextArgIndex)).getValue(),
File.pathSeparator);
while (st.hasMoreTokens()) {
String filename = st.nextToken();
File jarFile = makeFile(filename);
if (FileUtil.isZipFile(jarFile)) {
buildConfig.getInJars().add(jarFile);
} else {
File dirFile = makeFile(filename);
if (dirFile.isDirectory()) {
buildConfig.getInJars().add(dirFile);
} else
showWarning("skipping missing, empty or corrupt injar: " + filename);
}
}
args.remove(args.get(nextArgIndex));
}
} else if (arg.equals("-aspectpath")) {;
if (args.size() > nextArgIndex) {
StringTokenizer st = new StringTokenizer(
((ConfigParser.Arg)args.get(nextArgIndex)).getValue(),
File.pathSeparator);
while (st.hasMoreTokens()) {
String filename = st.nextToken();
File jarFile = makeFile(filename);
if (FileUtil.isZipFile(jarFile) || jarFile.isDirectory()) {
buildConfig.getAspectpath().add(jarFile);
} else {
showWarning("skipping missing, empty or corrupt aspectpath entry: " + filename);
}
}
args.remove(args.get(nextArgIndex));
}
} else if (arg.equals("-sourceroots")) {
if (args.size() > nextArgIndex) {
List sourceRoots = new ArrayList();
StringTokenizer st = new StringTokenizer(
((ConfigParser.Arg)args.get(nextArgIndex)).getValue(),
File.pathSeparator);
while (st.hasMoreTokens()) {
File f = makeFile(st.nextToken());
if (f.isDirectory() && f.canRead()) {
sourceRoots.add(f);
} else {
showError("bad sourceroot: " + f);
}
}
if (0 < sourceRoots.size()) {
buildConfig.setSourceRoots(sourceRoots);
}
args.remove(args.get(nextArgIndex));
} else {
showError("-sourceroots requires list of directories");
}
} else if (arg.equals("-outjar")) {
if (args.size() > nextArgIndex) {
// buildConfig.getAjOptions().put(AjCompilerOptions.OPTION_OutJAR, CompilerOptions.GENERATE);
File jarFile = makeFile(((ConfigParser.Arg)args.get(nextArgIndex)).getValue());
if (!jarFile.isDirectory()) {
try {
if (!jarFile.exists()) {
jarFile.createNewFile();
}
buildConfig.setOutputJar(jarFile);
} catch (IOException ioe) {
showError("unable to create outjar file: " + jarFile);
}
} else {
showError("invalid -outjar file: " + jarFile);
}
args.remove(args.get(nextArgIndex));
} else {
showError("-outjar requires jar path argument");
}
} else if (arg.equals("-outxml")) {
buildConfig.setOutxmlName("META-INF/aop.xml");
} else if (arg.equals("-outxmlfile")) {
if (args.size() > nextArgIndex) {
String name = ((ConfigParser.Arg)args.get(nextArgIndex)).getValue();
buildConfig.setOutxmlName(name);
args.remove(args.get(nextArgIndex));
} else {
showError("-outxmlfile requires file name argument");
}
} else if (arg.equals("-log")){
// remove it as it's already been handled in org.aspectj.tools.ajc.Main
args.remove(args.get(nextArgIndex));
} else if (arg.equals("-messageHolder")) {
// remove it as it's already been handled in org.aspectj.tools.ajc.Main
args.remove(args.get(nextArgIndex));
}else if (arg.equals("-incremental")) {
buildConfig.setIncrementalMode(true);
} else if (arg.equals("-XincrementalFile")) {
if (args.size() > nextArgIndex) {
File file = makeFile(((ConfigParser.Arg)args.get(nextArgIndex)).getValue());
buildConfig.setIncrementalFile(file);
if (!file.canRead()) {
showError("bad -XincrementalFile : " + file);
// if not created before recompile test, stop after first compile
}
args.remove(args.get(nextArgIndex));
} else {
showError("-XincrementalFile requires file argument");
}
} else if (arg.equals("-crossrefs")) {
buildConfig.setGenerateCrossRefsMode(true);
buildConfig.setGenerateModelMode(true);
} else if (arg.equals("-emacssym")) {
buildConfig.setEmacsSymMode(true);
buildConfig.setGenerateModelMode(true);
} else if (arg.equals("-XjavadocsInModel")) {
buildConfig.setGenerateModelMode(true);
buildConfig.setGenerateJavadocsInModelMode(true);
} else if (arg.equals("-Xdev:NoAtAspectJProcessing")) {
buildConfig.setNoAtAspectJAnnotationProcessing(true);
} else if (arg.equals("-XaddSerialVersionUID")) {
buildConfig.setAddSerialVerUID(true);
} else if (arg.equals("-Xdev:Pinpoint")) {
buildConfig.setXdevPinpointMode(true);
} else if (arg.startsWith("-Xjoinpoints:")) {
buildConfig.setXJoinpoints(arg.substring(13));
} else if (arg.equals("-noWeave") || arg.equals( "-XnoWeave")) {
showWarning("the noweave option is no longer required and is being ignored");
} else if (arg.equals( "-XterminateAfterCompilation")) {
buildConfig.setTerminateAfterCompilation(true);
} else if (arg.equals("-XserializableAspects")) {
buildConfig.setXserializableAspects(true);
} else if (arg.equals("-XlazyTjp")) {
// do nothing as this is now on by default
showWarning("-XlazyTjp should no longer be used, build tjps lazily is now the default");
} else if (arg.startsWith("-Xreweavable")) {
showWarning("-Xreweavable is on by default");
if (arg.endsWith(":compress")) {
showWarning("-Xreweavable:compress is no longer available - reweavable is now default");
}
} else if (arg.startsWith("-Xset:")) {
buildConfig.setXconfigurationInfo(arg.substring(6));
} else if (arg.startsWith("-XnotReweavable")) {
buildConfig.setXnotReweavable(true);
} else if (arg.equals("-XnoInline")) {
buildConfig.setXnoInline(true);
} else if (arg.equals("-XhasMember")) {
buildConfig.setXHasMemberSupport(true);
} else if (arg.startsWith("-showWeaveInfo")) {
buildConfig.setShowWeavingInformation(true);
} else if (arg.equals("-Xlintfile")) {
if (args.size() > nextArgIndex) {
File lintSpecFile = makeFile(((ConfigParser.Arg)args.get(nextArgIndex)).getValue());
// XXX relax restriction on props file suffix?
if (lintSpecFile.canRead() && lintSpecFile.getName().endsWith(".properties")) {
buildConfig.setLintSpecFile(lintSpecFile);
} else {
showError("bad -Xlintfile file: " + lintSpecFile);
buildConfig.setLintSpecFile(null);
}
args.remove(args.get(nextArgIndex));
} else {
showError("-Xlintfile requires .properties file argument");
}
} else if (arg.equals("-Xlint")) {
// buildConfig.getAjOptions().put(
// AjCompilerOptions.OPTION_Xlint,
// CompilerOptions.GENERATE);
buildConfig.setLintMode(AjBuildConfig.AJLINT_DEFAULT);
} else if (arg.startsWith("-Xlint:")) {
if (7 < arg.length()) {
buildConfig.setLintMode(arg.substring(7));
} else {
showError("invalid lint option " + arg);
}
} else if (arg.equals("-bootclasspath")) {
if (args.size() > nextArgIndex) {
String bcpArg = ((ConfigParser.Arg)args.get(nextArgIndex)).getValue();
StringBuffer bcp = new StringBuffer();
StringTokenizer strTok = new StringTokenizer(bcpArg,File.pathSeparator);
while (strTok.hasMoreTokens()) {
bcp.append(makeFile(strTok.nextToken()));
if (strTok.hasMoreTokens()) {
bcp.append(File.pathSeparator);
}
}
bootclasspath = bcp.toString();
args.remove(args.get(nextArgIndex));
} else {
showError("-bootclasspath requires classpath entries");
}
} else if (arg.equals("-classpath") || arg.equals("-cp")) {
if (args.size() > nextArgIndex) {
String cpArg = ((ConfigParser.Arg)args.get(nextArgIndex)).getValue();
StringBuffer cp = new StringBuffer();
StringTokenizer strTok = new StringTokenizer(cpArg,File.pathSeparator);
while (strTok.hasMoreTokens()) {
cp.append(makeFile(strTok.nextToken()));
if (strTok.hasMoreTokens()) {
cp.append(File.pathSeparator);
}
}
classpath = cp.toString();
args.remove(args.get(nextArgIndex));
} else {
showError("-classpath requires classpath entries");
}
} else if (arg.equals("-extdirs")) {
if (args.size() > nextArgIndex) {
String extdirsArg = ((ConfigParser.Arg)args.get(nextArgIndex)).getValue();
StringBuffer ed = new StringBuffer();
StringTokenizer strTok = new StringTokenizer(extdirsArg,File.pathSeparator);
while (strTok.hasMoreTokens()) {
ed.append(makeFile(strTok.nextToken()));
if (strTok.hasMoreTokens()) {
ed.append(File.pathSeparator);
}
}
extdirs = ed.toString();
args.remove(args.get(nextArgIndex));
} else {
showError("-extdirs requires list of external directories");
}
// error on directory unless -d, -{boot}classpath, or -extdirs
} else if (arg.equals("-d")) {
dirLookahead(arg, args, nextArgIndex);
// } else if (arg.equals("-classpath")) {
// dirLookahead(arg, args, nextArgIndex);
// } else if (arg.equals("-bootclasspath")) {
// dirLookahead(arg, args, nextArgIndex);
// } else if (arg.equals("-extdirs")) {
// dirLookahead(arg, args, nextArgIndex);
} else if (arg.equals("-proceedOnError")) {
buildConfig.setProceedOnError(true);
} else if (new File(arg).isDirectory()) {
showError("dir arg not permitted: " + arg);
} else if (arg.startsWith("-Xajruntimetarget")) {
if (arg.endsWith(":1.2")) {
buildConfig.setTargetAspectjRuntimeLevel(Constants.RUNTIME_LEVEL_12);
} else if (arg.endsWith(":1.5")) {
buildConfig.setTargetAspectjRuntimeLevel(Constants.RUNTIME_LEVEL_15);
} else {
showError("-Xajruntimetarget:<level> only supports a target level of 1.2 or 1.5");
}
} else if (arg.equals("-1.5")) {
buildConfig.setBehaveInJava5Way(true);
unparsedArgs.add("-1.5");
// this would enable the '-source 1.5' to do the same as '-1.5' but doesnt sound quite right as
// as an option right now as it doesnt mean we support 1.5 source code - people will get confused...
} else if (arg.equals("-source")) {
if (args.size() > nextArgIndex) {
String level = ((ConfigParser.Arg)args.get(nextArgIndex)).getValue();
if (level.equals("1.5")){
buildConfig.setBehaveInJava5Way(true);
}
unparsedArgs.add("-source");
unparsedArgs.add(level);
args.remove(args.get(nextArgIndex));
}
} else {
// argfile, @file parsed by superclass
// no eclipse options parsed:
// -d args, -help (handled),
// -classpath, -target, -1.3, -1.4, -source [1.3|1.4]
// -nowarn, -warn:[...], -deprecation, -noImportError,
// -g:[...], -preserveAllLocals,
// -referenceInfo, -encoding, -verbose, -log, -time
// -noExit, -repeat
// (Actually, -noExit grabbed by Main)
unparsedArgs.add(arg);
}
}
protected void dirLookahead(String arg, LinkedList argList, int nextArgIndex) {
unparsedArgs.add(arg);
ConfigParser.Arg next = (ConfigParser.Arg) argList.get(nextArgIndex);
String value = next.getValue();
if (!LangUtil.isEmpty(value)) {
if (new File(value).isDirectory()) {
unparsedArgs.add(value);
argList.remove(next);
return;
}
}
}
public void showError(String message) {
ISourceLocation location = null;
if (buildConfig.getConfigFile() != null) {
location = new SourceLocation(buildConfig.getConfigFile(), 0);
}
IMessage errorMessage = new Message(CONFIG_MSG + message, IMessage.ERROR, null, location);
handler.handleMessage(errorMessage);
// MessageUtil.error(handler, CONFIG_MSG + message);
}
protected void showWarning(String message) {
ISourceLocation location = null;
if (buildConfig.getConfigFile() != null) {
location = new SourceLocation(buildConfig.getConfigFile(), 0);
}
IMessage errorMessage = new Message(CONFIG_MSG + message, IMessage.WARNING, null, location);
handler.handleMessage(errorMessage);
// MessageUtil.warn(handler, message);
}
protected File makeFile(File dir, String name) {
name = name.replace('/', File.separatorChar);
File ret = new File(name);
if (dir == null || ret.isAbsolute()) return ret;
try {
dir = dir.getCanonicalFile();
} catch (IOException ioe) { }
return new File(dir, name);
}
}
}
|
148,737 |
Bug 148737 IllegalStateException for non-generic type
|
I believe this is similar to 112880. The message and stack trace I am getting are -- (IllegalStateException) Can't ask to parameterize a member of non-generic type: com...object kind(raw) Can't ask to parameterize a member of non-generic type: com...object kind(raw) java.lang.IllegalStateException: Can't ask to parameterize a member of non-generic type: com....object kind(raw) at org.aspectj.weaver.ResolvedMemberImpl.parameterizedWith(ResolvedMemberImpl.java:612) at org.aspectj.weaver.ResolvedMemberImpl.parameterizedWith(ResolvedMemberImpl.java:597) at org.aspectj.weaver.ReferenceType.getDeclaredMethods(ReferenceType.java:508) at org.aspectj.weaver.ResolvedType$4.get(ResolvedType.java:225) at org.aspectj.weaver.Iterators$3$1.hasNext(Iterators.java:118) at org.aspectj.weaver.Iterators$5.hasNext(Iterators.java:171) at org.aspectj.weaver.Iterators$3.hasNext(Iterators.java:128) at org.aspectj.weaver.ResolvedType.lookupMember(ResolvedType.java:345) at org.aspectj.weaver.ResolvedType.lookupMethod(ResolvedType.java:326) . . . The same code was able to be weaved under 1.5.0. The reason why this is a major issue is 1.5.0 suffers from a StackOverflowException.
|
resolved fixed
|
f6834c7
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-07-03T13:49:07Z | 2006-06-27T01:00:00Z |
tests/bugs153/pr148737/A.java
| |
148,737 |
Bug 148737 IllegalStateException for non-generic type
|
I believe this is similar to 112880. The message and stack trace I am getting are -- (IllegalStateException) Can't ask to parameterize a member of non-generic type: com...object kind(raw) Can't ask to parameterize a member of non-generic type: com...object kind(raw) java.lang.IllegalStateException: Can't ask to parameterize a member of non-generic type: com....object kind(raw) at org.aspectj.weaver.ResolvedMemberImpl.parameterizedWith(ResolvedMemberImpl.java:612) at org.aspectj.weaver.ResolvedMemberImpl.parameterizedWith(ResolvedMemberImpl.java:597) at org.aspectj.weaver.ReferenceType.getDeclaredMethods(ReferenceType.java:508) at org.aspectj.weaver.ResolvedType$4.get(ResolvedType.java:225) at org.aspectj.weaver.Iterators$3$1.hasNext(Iterators.java:118) at org.aspectj.weaver.Iterators$5.hasNext(Iterators.java:171) at org.aspectj.weaver.Iterators$3.hasNext(Iterators.java:128) at org.aspectj.weaver.ResolvedType.lookupMember(ResolvedType.java:345) at org.aspectj.weaver.ResolvedType.lookupMethod(ResolvedType.java:326) . . . The same code was able to be weaved under 1.5.0. The reason why this is a major issue is 1.5.0 suffers from a StackOverflowException.
|
resolved fixed
|
f6834c7
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-07-03T13:49:07Z | 2006-06-27T01:00:00Z |
tests/src/org/aspectj/systemtest/ajc153/Ajc153Tests.java
|
/*******************************************************************************
* Copyright (c) 2006 IBM
* 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.ajc153;
import java.io.File;
import junit.framework.Test;
import org.aspectj.testing.XMLBasedAjcTestCase;
public class Ajc153Tests extends org.aspectj.testing.XMLBasedAjcTestCase {
// public void testArgnamesAndJavac_pr148381() { runTest("argNames and javac");}
/////////////////////////////////////////
public static Test suite() {
return XMLBasedAjcTestCase.loadSuite(Ajc153Tests.class);
}
protected File getSpecFile() {
return new File("../tests/src/org/aspectj/systemtest/ajc153/ajc153.xml");
}
}
|
148,693 |
Bug 148693 woven class does not pass org.apache.bcel.verifier.statics.Pass2Verifier
| null |
resolved fixed
|
82f217f
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-07-05T08:22:55Z | 2006-06-26T16:40:00Z |
org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/compiler/ast/AspectDeclaration.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.compiler.ast;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.aspectj.ajdt.internal.compiler.lookup.EclipseFactory;
import org.aspectj.ajdt.internal.compiler.lookup.EclipseScope;
import org.aspectj.ajdt.internal.compiler.lookup.EclipseSourceType;
import org.aspectj.ajdt.internal.compiler.lookup.EclipseTypeMunger;
import org.aspectj.ajdt.internal.compiler.lookup.HelperInterfaceBinding;
import org.aspectj.ajdt.internal.compiler.lookup.InlineAccessFieldBinding;
import org.aspectj.ajdt.internal.compiler.lookup.PrivilegedHandler;
import org.aspectj.org.eclipse.jdt.core.compiler.CharOperation;
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.ast.Annotation;
import org.aspectj.org.eclipse.jdt.internal.compiler.ast.Clinit;
import org.aspectj.org.eclipse.jdt.internal.compiler.ast.MethodDeclaration;
import org.aspectj.org.eclipse.jdt.internal.compiler.ast.TypeDeclaration;
import org.aspectj.org.eclipse.jdt.internal.compiler.codegen.CodeStream;
import org.aspectj.org.eclipse.jdt.internal.compiler.codegen.ExceptionLabel;
import org.aspectj.org.eclipse.jdt.internal.compiler.codegen.Label;
import org.aspectj.org.eclipse.jdt.internal.compiler.env.IGenericType;
import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.BaseTypes;
import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.BinaryTypeBinding;
import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.Binding;
import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.ClassScope;
import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.FieldBinding;
import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.InvocationSite;
import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.MethodBinding;
import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.ParameterizedTypeBinding;
import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.ReferenceBinding;
import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.Scope;
import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.SourceTypeBinding;
import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.TypeBinding;
import org.aspectj.weaver.AjAttribute;
import org.aspectj.weaver.AjcMemberMaker;
import org.aspectj.weaver.NameMangler;
import org.aspectj.weaver.ReferenceType;
import org.aspectj.weaver.ResolvedMember;
import org.aspectj.weaver.ResolvedType;
import org.aspectj.weaver.Shadow;
import org.aspectj.weaver.UnresolvedType;
import org.aspectj.weaver.patterns.Declare;
import org.aspectj.weaver.patterns.FormalBinding;
import org.aspectj.weaver.patterns.PerClause;
import org.aspectj.weaver.patterns.PerFromSuper;
import org.aspectj.weaver.patterns.PerSingleton;
import org.aspectj.weaver.patterns.TypePattern;
//import org.aspectj.org.eclipse.jdt.internal.compiler.parser.Parser;
// (we used to...) making all aspects member types avoids a nasty hierarchy pain
// switched from MemberTypeDeclaration to TypeDeclaration
public class AspectDeclaration extends TypeDeclaration {
//public IAjDeclaration[] ajDeclarations;
private AjAttribute.Aspect aspectAttribute;
public PerClause perClause;
public ResolvedMember aspectOfMethod;
//public ResolvedMember ptwGetWithinTypeMethod;
public ResolvedMember hasAspectMethod;
public Map accessForInline = new HashMap();
public Map superAccessForInline = new HashMap();
public boolean isPrivileged;
private int declaredModifiers;
public EclipseSourceType concreteName;
public ReferenceType typeX;
public EclipseFactory factory; //??? should use this consistently
public int adviceCounter = 1; // Used as a part of the generated name for advice methods
public int declareCounter= 1; // Used as a part of the generated name for methods representing declares
// for better error messages in 1.0 to 1.1 transition
public TypePattern dominatesPattern;
public AspectDeclaration(CompilationResult compilationResult) {
super(compilationResult);
//perClause = new PerSingleton();
}
public boolean isAbstract() {
return (modifiers & AccAbstract) != 0;
}
public void resolve() {
declaredModifiers = modifiers; // remember our modifiers, we're going to be public in generateCode
if (binding == null) {
ignoreFurtherInvestigation = true;
return;
}
super.resolve();
}
public void checkSpec(ClassScope scope) {
if (ignoreFurtherInvestigation) return;
if (dominatesPattern != null) {
scope.problemReporter().signalError(
dominatesPattern.getStart(), dominatesPattern.getEnd(),
"dominates has changed for 1.1, use 'declare precedence: " +
new String(this.name) + ", " + dominatesPattern.toString() + ";' " +
"in the body of the aspect instead");
}
if (!isAbstract()) {
MethodBinding[] methods = binding.methods();
for (int i=0, len = methods.length; i < len; i++) {
MethodBinding m = methods[i];
if (m.isConstructor()) {
// this make all constructors in aspects invisible and thus uncallable
//XXX this only works for aspects that come from source
methods[i] = new MethodBinding(m, binding) {
public boolean canBeSeenBy(
InvocationSite invocationSite,
Scope scope) {
return false;
}
};
if (m.parameters != null && m.parameters.length != 0) {
scope.problemReporter().signalError(m.sourceStart(), m.sourceEnd(),
"only zero-argument constructors allowed in concrete aspect");
}
}
}
// check the aspect was not declared generic, only abstract aspects can have type params
if (typeParameters != null && typeParameters.length > 0) {
scope.problemReporter().signalError(sourceStart(), sourceEnd(),
"only abstract aspects can have type parameters");
}
}
if (this.enclosingType != null) {
if (!Modifier.isStatic(modifiers)) {
scope.problemReporter().signalError(sourceStart, sourceEnd,
"inner aspects must be static");
ignoreFurtherInvestigation = true;
return;
}
}
EclipseFactory world = EclipseFactory.fromScopeLookupEnvironment(scope);
ResolvedType myType = typeX;
//if (myType == null) System.err.println("bad myType for: " + this);
ResolvedType superType = myType.getSuperclass();
// can't be Serializable/Cloneable unless -XserializableAspects
if (!world.isXSerializableAspects()) {
if (world.getWorld().getCoreType(UnresolvedType.SERIALIZABLE).isAssignableFrom(myType)) {
scope.problemReporter().signalError(sourceStart, sourceEnd,
"aspects may not implement Serializable");
ignoreFurtherInvestigation = true;
return;
}
if (world.getWorld().getCoreType(UnresolvedType.CLONEABLE).isAssignableFrom(myType)) {
scope.problemReporter().signalError(sourceStart, sourceEnd,
"aspects may not implement Cloneable");
ignoreFurtherInvestigation = true;
return;
}
}
if (superType.isAspect()) {
if (!superType.isAbstract()) {
scope.problemReporter().signalError(sourceStart, sourceEnd,
"can not extend a concrete aspect");
ignoreFurtherInvestigation = true;
return;
}
// if super type is generic, check that we have fully parameterized it
if (superType.isRawType()) {
scope.problemReporter().signalError(sourceStart, sourceEnd,
"a generic super-aspect must be fully parameterized in an extends clause");
ignoreFurtherInvestigation = true;
return;
}
}
}
private FieldBinding initFailureField= null;
/**
* AMC - this method is called by the AtAspectJVisitor during beforeCompilation processing in
* the AjCompiler adapter. We use this hook to add in the @AspectJ annotations.
*/
public void addAtAspectJAnnotations() {
Annotation atAspectAnnotation = AtAspectJAnnotationFactory.createAspectAnnotation(perClause.toDeclarationString(), declarationSourceStart);
Annotation privilegedAnnotation = null;
if (isPrivileged) privilegedAnnotation = AtAspectJAnnotationFactory.createPrivilegedAnnotation(declarationSourceStart);
Annotation[] toAdd = new Annotation[isPrivileged ? 2 : 1];
toAdd[0] = atAspectAnnotation;
if (isPrivileged) toAdd[1] = privilegedAnnotation;
if (annotations == null) {
annotations = toAdd;
} else {
Annotation[] old = annotations;
annotations = new Annotation[annotations.length + toAdd.length];
System.arraycopy(old,0,annotations,0,old.length);
System.arraycopy(toAdd,0,annotations,old.length,toAdd.length);
}
}
public void generateCode(ClassFile enclosingClassFile) {
if (ignoreFurtherInvestigation) {
if (binding == null)
return;
ClassFile.createProblemType(
this,
scope.referenceCompilationUnit().compilationResult);
return;
}
// make me and my binding public
this.modifiers = AstUtil.makePublic(this.modifiers);
this.binding.modifiers = AstUtil.makePublic(this.binding.modifiers);
if (!isAbstract()) {
initFailureField = factory.makeFieldBinding(AjcMemberMaker.initFailureCauseField(typeX));
binding.addField(initFailureField);
if (perClause == null) {
// we've already produced an error for this
} else if (perClause.getKind() == PerClause.SINGLETON) {
binding.addField(factory.makeFieldBinding(AjcMemberMaker.perSingletonField(
typeX)));
methods[0] = new AspectClinit((Clinit)methods[0], compilationResult, false, true, initFailureField);
} else if (perClause.getKind() == PerClause.PERCFLOW) {
binding.addField(
factory.makeFieldBinding(
AjcMemberMaker.perCflowField(
typeX)));
methods[0] = new AspectClinit((Clinit)methods[0], compilationResult, true, false, null);
} else if (perClause.getKind() == PerClause.PEROBJECT) {
// binding.addField(
// world.makeFieldBinding(
// AjcMemberMaker.perCflowField(
// typeX)));
} else if (perClause.getKind() == PerClause.PERTYPEWITHIN) {
//PTWIMPL Add field for storing typename in aspect for which the aspect instance exists
binding.addField(factory.makeFieldBinding(AjcMemberMaker.perTypeWithinWithinTypeField(typeX,typeX)));
} else {
throw new RuntimeException("unimplemented");
}
}
if (EclipseFactory.DEBUG) System.out.println(toString());
super.generateCode(enclosingClassFile);
}
public boolean needClassInitMethod() {
return true;
}
protected void generateAttributes(ClassFile classFile) {
if (!isAbstract()) generatePerSupportMembers(classFile);
generateInlineAccessMembers(classFile);
addVersionAttributeIfNecessary(classFile);
classFile.extraAttributes.add(
new EclipseAttributeAdapter(new AjAttribute.Aspect(perClause)));
if (binding.privilegedHandler != null) {
ResolvedMember[] members = ((PrivilegedHandler)binding.privilegedHandler).getMembers();
classFile.extraAttributes.add(
new EclipseAttributeAdapter(new AjAttribute.PrivilegedAttribute(members)));
}
//XXX need to get this attribute on anyone with a pointcut for good errors
classFile.extraAttributes.add(
new EclipseAttributeAdapter(new AjAttribute.SourceContextAttribute(
new String(compilationResult().getFileName()),
compilationResult().lineSeparatorPositions)));
super.generateAttributes(classFile);
}
/**
* A pointcut might have already added the attribute, let's not add it again.
*/
private void addVersionAttributeIfNecessary(ClassFile classFile) {
for (Iterator iter = classFile.extraAttributes.iterator(); iter.hasNext();) {
EclipseAttributeAdapter element = (EclipseAttributeAdapter) iter.next();
if (CharOperation.equals(element.getNameChars(),weaverVersionChars)) return;
}
classFile.extraAttributes.add(new EclipseAttributeAdapter(new AjAttribute.WeaverVersionInfo()));
}
private static char[] weaverVersionChars = "org.aspectj.weaver.WeaverVersion".toCharArray();
private void generateInlineAccessMembers(ClassFile classFile) {
for (Iterator i = superAccessForInline.values().iterator(); i.hasNext(); ) {
AccessForInlineVisitor.SuperAccessMethodPair pair = (AccessForInlineVisitor.SuperAccessMethodPair)i.next();
generateSuperAccessMethod(classFile, pair.accessMethod, pair.originalMethod);
}
for (Iterator i = accessForInline.entrySet().iterator(); i.hasNext(); ) {
Map.Entry e = (Map.Entry)i.next();
generateInlineAccessMethod(classFile, (Binding)e.getValue(), (ResolvedMember)e.getKey());
}
}
private void generatePerSupportMembers(ClassFile classFile) {
if (isAbstract()) return;
//XXX otherwise we need to have this (error handling?)
if (aspectOfMethod == null) return;
if (perClause == null) {
System.err.println("has null perClause: " + this);
return;
}
EclipseFactory world = EclipseFactory.fromScopeLookupEnvironment(this.scope);
if (perClause.getKind() == PerClause.SINGLETON) {
generatePerSingletonAspectOfMethod(classFile);
generatePerSingletonHasAspectMethod(classFile);
generatePerSingletonAjcClinitMethod(classFile);
} else if (perClause.getKind() == PerClause.PERCFLOW) {
generatePerCflowAspectOfMethod(classFile);
generatePerCflowHasAspectMethod(classFile);
generatePerCflowPushMethod(classFile);
generatePerCflowAjcClinitMethod(classFile);
} else if (perClause.getKind() == PerClause.PEROBJECT) {
TypeBinding interfaceType =
generatePerObjectInterface(classFile);
generatePerObjectAspectOfMethod(classFile, interfaceType);
generatePerObjectHasAspectMethod(classFile, interfaceType);
generatePerObjectBindMethod(classFile, interfaceType);
} else if (perClause.getKind() == PerClause.PERTYPEWITHIN) {
//PTWIMPL Generate the methods required *in the aspect*
generatePerTypeWithinAspectOfMethod(classFile); // public static <aspecttype> aspectOf(java.lang.Class)
generatePerTypeWithinGetInstanceMethod(classFile); // private static <aspecttype> ajc$getInstance(Class c) throws Exception
generatePerTypeWithinHasAspectMethod(classFile);
generatePerTypeWithinCreateAspectInstanceMethod(classFile); // generate public static X ajc$createAspectInstance(Class forClass) {
// PTWIMPL getWithinType() would need this...
//generatePerTypeWithinGetWithinTypeMethod(classFile); // generate public Class getWithinType() {
} else {
throw new RuntimeException("unimplemented");
}
}
private static interface BodyGenerator {
public void generate(CodeStream codeStream);
}
private void generateMethod(ClassFile classFile, ResolvedMember member, BodyGenerator gen) {
final EclipseFactory world = EclipseFactory.fromScopeLookupEnvironment(this.scope);
generateMethod(classFile, world.makeMethodBinding(member), gen);
}
private void generateMethod(ClassFile classFile, MethodBinding methodBinding, BodyGenerator gen) {
generateMethod(classFile,methodBinding,null,gen);
}
protected List makeEffectiveSignatureAttribute(ResolvedMember sig,Shadow.Kind kind,boolean weaveBody) {
List l = new ArrayList(1);
l.add(new EclipseAttributeAdapter(
new AjAttribute.EffectiveSignatureAttribute(sig, kind, weaveBody)));
return l;
}
/*
* additionalAttributes allows us to pass some optional attributes we want to attach to the method we generate.
* Currently this is used for inline accessor methods that have been generated to allow private field references or
* private method calls to be inlined (PR71377). In these cases the optional attribute is an effective signature
* attribute which means calls to these methods are able to masquerade as any join point (a field set, field get or
* method call). The effective signature attribute is 'unwrapped' in BcelClassWeaver.matchInvokeInstruction()
*/
private void generateMethod(ClassFile classFile, MethodBinding methodBinding, List additionalAttributes/*ResolvedMember realMember*/, BodyGenerator gen) {
// EclipseFactory world = EclipseFactory.fromScopeLookupEnvironment(this.scope);
classFile.generateMethodInfoHeader(methodBinding);
int methodAttributeOffset = classFile.contentsOffset;
int attributeNumber;
if (additionalAttributes!=null) { // mini optimization
List attrs = new ArrayList();
attrs.addAll(AstUtil.getAjSyntheticAttribute());
attrs.addAll(additionalAttributes);
attributeNumber = classFile.generateMethodInfoAttribute(methodBinding, false, attrs);
} else {
attributeNumber = classFile.generateMethodInfoAttribute(methodBinding, false, AstUtil.getAjSyntheticAttribute());
}
int codeAttributeOffset = classFile.contentsOffset;
classFile.generateCodeAttributeHeader();
CodeStream codeStream = classFile.codeStream;
// Use reset() rather than init()
// XXX We need a scope to keep reset happy, initializerScope is *not* the right one, but it works !
// codeStream.init(classFile);
// codeStream.initializeMaxLocals(methodBinding);
MethodDeclaration md = AstUtil.makeMethodDeclaration(methodBinding);
md.scope = initializerScope;
codeStream.reset(md,classFile);
// body starts here
gen.generate(codeStream);
// body ends here
if (codeStream.pcToSourceMapSize==0) codeStream.recordPositionsFrom(0,1);
classFile.completeCodeAttribute(codeAttributeOffset);
attributeNumber++;
classFile.completeMethodInfo(methodAttributeOffset, attributeNumber);
}
private void generatePerCflowAspectOfMethod(
ClassFile classFile)
{
final EclipseFactory world = EclipseFactory.fromScopeLookupEnvironment(this.scope);
generateMethod(classFile, aspectOfMethod, new BodyGenerator() {
public void generate(CodeStream codeStream) {
// body starts here
codeStream.getstatic(
world.makeFieldBinding(
AjcMemberMaker.perCflowField(
typeX)));
codeStream.invokevirtual(world.makeMethodBindingForCall(
AjcMemberMaker.cflowStackPeekInstance()));
codeStream.checkcast(binding);
codeStream.areturn();
// body ends here
}});
}
private void generatePerCflowHasAspectMethod(ClassFile classFile) {
final EclipseFactory world = EclipseFactory.fromScopeLookupEnvironment(this.scope);
generateMethod(classFile, hasAspectMethod, new BodyGenerator() {
public void generate(CodeStream codeStream) {
// body starts here
codeStream.getstatic(
world.makeFieldBinding(
AjcMemberMaker.perCflowField(
typeX)));
codeStream.invokevirtual(world.makeMethodBindingForCall(
AjcMemberMaker.cflowStackIsValid()));
codeStream.ireturn();
// body ends here
}});
}
private void generatePerCflowPushMethod(
ClassFile classFile)
{
final EclipseFactory world = EclipseFactory.fromScopeLookupEnvironment(this.scope);
generateMethod(classFile, world.makeMethodBinding(AjcMemberMaker.perCflowPush(
factory.fromBinding(binding))),
new BodyGenerator() {
public void generate(CodeStream codeStream) {
// body starts here
codeStream.getstatic(
world.makeFieldBinding(
AjcMemberMaker.perCflowField(
typeX)));
codeStream.new_(binding);
codeStream.dup();
codeStream.invokespecial(
new MethodBinding(0, "<init>".toCharArray(),
BaseTypes.VoidBinding, new TypeBinding[0],
new ReferenceBinding[0], binding));
codeStream.invokevirtual(world.makeMethodBindingForCall(
AjcMemberMaker.cflowStackPushInstance()));
codeStream.return_();
// body ends here
}});
}
private void generatePerCflowAjcClinitMethod(
ClassFile classFile)
{
final EclipseFactory world = EclipseFactory.fromScopeLookupEnvironment(this.scope);
generateMethod(classFile, world.makeMethodBinding(AjcMemberMaker.ajcPreClinitMethod(
world.fromBinding(binding))),
new BodyGenerator() {
public void generate(CodeStream codeStream) {
// body starts here
codeStream.new_(world.makeTypeBinding(AjcMemberMaker.CFLOW_STACK_TYPE));
codeStream.dup();
codeStream.invokespecial(world.makeMethodBindingForCall(AjcMemberMaker.cflowStackInit()));
codeStream.putstatic(
world.makeFieldBinding(
AjcMemberMaker.perCflowField(
typeX)));
codeStream.return_();
// body ends here
}});
}
private TypeBinding generatePerObjectInterface(
ClassFile classFile)
{
final EclipseFactory world = EclipseFactory.fromScopeLookupEnvironment(this.scope);
UnresolvedType interfaceTypeX =
AjcMemberMaker.perObjectInterfaceType(typeX);
HelperInterfaceBinding interfaceType =
new HelperInterfaceBinding(this.binding, interfaceTypeX);
world.addTypeBindingAndStoreInWorld(interfaceType);
interfaceType.addMethod(world, AjcMemberMaker.perObjectInterfaceGet(typeX));
interfaceType.addMethod(world, AjcMemberMaker.perObjectInterfaceSet(typeX));
interfaceType.generateClass(compilationResult, classFile);
return interfaceType;
}
/*private void generatePerTypeWithinGetWithinTypeMethod(ClassFile classFile) {
final EclipseFactory world = EclipseFactory.fromScopeLookupEnvironment(this.scope);
generateMethod(classFile,ptwGetWithinTypeMethod,new BodyGenerator() {
public void generate(CodeStream codeStream) {
codeStream.aload_0();
codeStream.getfield(world.makeFieldBinding(AjcMemberMaker.perTypeWithinWithinTypeField(typeX,typeX)));
codeStream.areturn();
}});
}*/
// PTWIMPL Generate aspectOf() method
private void generatePerTypeWithinAspectOfMethod(ClassFile classFile) {
final EclipseFactory world = EclipseFactory.fromScopeLookupEnvironment(this.scope);
generateMethod(classFile, aspectOfMethod, new BodyGenerator() {
public void generate(CodeStream codeStream) {
Label instanceFound = new Label(codeStream);
ExceptionLabel anythingGoesWrong = new ExceptionLabel(codeStream,world.makeTypeBinding(UnresolvedType.JAVA_LANG_EXCEPTION));
codeStream.aload_0();
codeStream.invokestatic(world.makeMethodBindingForCall(AjcMemberMaker.perTypeWithinGetInstance(typeX)));
codeStream.astore_1();
codeStream.aload_1();
codeStream.ifnonnull(instanceFound);
codeStream.new_(world.makeTypeBinding(AjcMemberMaker.NO_ASPECT_BOUND_EXCEPTION));
codeStream.dup();
codeStream.ldc(typeX.getName());
codeStream.aconst_null();
codeStream.invokespecial(world.makeMethodBindingForCall(AjcMemberMaker.noAspectBoundExceptionInit2()));
codeStream.athrow();
instanceFound.place();
codeStream.aload_1();
codeStream.areturn();
anythingGoesWrong.placeEnd();
anythingGoesWrong.place();
codeStream.astore_1();
codeStream.new_(world.makeTypeBinding(AjcMemberMaker.NO_ASPECT_BOUND_EXCEPTION));
codeStream.dup();
// Run the simple ctor for NABE
codeStream.invokespecial(world.makeMethodBindingForCall(AjcMemberMaker.noAspectBoundExceptionInit()));
codeStream.athrow();
}});
}
private void generatePerObjectAspectOfMethod(
ClassFile classFile,
final TypeBinding interfaceType)
{
final EclipseFactory world = EclipseFactory.fromScopeLookupEnvironment(this.scope);
generateMethod(classFile, aspectOfMethod, new BodyGenerator() {
public void generate(CodeStream codeStream) {
// body starts here
Label wrongType = new Label(codeStream);
Label popWrongType = new Label(codeStream);
codeStream.aload_0();
codeStream.instance_of(interfaceType);
codeStream.ifeq(wrongType);
codeStream.aload_0();
codeStream.checkcast(interfaceType);
codeStream.invokeinterface(world.makeMethodBindingForCall(
AjcMemberMaker.perObjectInterfaceGet(typeX)));
codeStream.dup();
codeStream.ifnull(popWrongType);
codeStream.areturn();
popWrongType.place();
codeStream.pop();
wrongType.place();
codeStream.new_(world.makeTypeBinding(AjcMemberMaker.NO_ASPECT_BOUND_EXCEPTION));
codeStream.dup();
codeStream.invokespecial(world.makeMethodBindingForCall(
AjcMemberMaker.noAspectBoundExceptionInit()
));
codeStream.athrow();
// body ends here
}});
}
private void generatePerObjectHasAspectMethod(ClassFile classFile,
final TypeBinding interfaceType) {
final EclipseFactory world = EclipseFactory.fromScopeLookupEnvironment(this.scope);
generateMethod(classFile, hasAspectMethod, new BodyGenerator() {
public void generate(CodeStream codeStream) {
// body starts here
Label wrongType = new Label(codeStream);
codeStream.aload_0();
codeStream.instance_of(interfaceType);
codeStream.ifeq(wrongType);
codeStream.aload_0();
codeStream.checkcast(interfaceType);
codeStream.invokeinterface(world.makeMethodBindingForCall(
AjcMemberMaker.perObjectInterfaceGet(typeX)));
codeStream.ifnull(wrongType);
codeStream.iconst_1();
codeStream.ireturn();
wrongType.place();
codeStream.iconst_0();
codeStream.ireturn();
// body ends here
}});
}
// PTWIMPL Generate hasAspect() method
private void generatePerTypeWithinHasAspectMethod(ClassFile classFile) {
final EclipseFactory world = EclipseFactory.fromScopeLookupEnvironment(this.scope);
generateMethod(classFile, hasAspectMethod, new BodyGenerator() {
public void generate(CodeStream codeStream) {
ExceptionLabel goneBang = new ExceptionLabel(codeStream,world.makeTypeBinding(UnresolvedType.JAVA_LANG_EXCEPTION));
Label noInstanceExists = new Label(codeStream);
Label leave = new Label(codeStream);
goneBang.placeStart();
codeStream.aload_0();
codeStream.invokestatic(world.makeMethodBinding(AjcMemberMaker.perTypeWithinGetInstance(typeX)));
codeStream.ifnull(noInstanceExists);
codeStream.iconst_1();
codeStream.goto_(leave);
noInstanceExists.place();
codeStream.iconst_0();
leave.place();
goneBang.placeEnd();
codeStream.ireturn();
goneBang.place();
codeStream.astore_1();
codeStream.iconst_0();
codeStream.ireturn();
}});
}
private void generatePerObjectBindMethod(
ClassFile classFile,
final TypeBinding interfaceType)
{
final EclipseFactory world = EclipseFactory.fromScopeLookupEnvironment(this.scope);
generateMethod(classFile, AjcMemberMaker.perObjectBind(world.fromBinding(binding)),
new BodyGenerator() {
public void generate(CodeStream codeStream) {
// body starts here
Label wrongType = new Label(codeStream);
codeStream.aload_0();
codeStream.instance_of(interfaceType);
codeStream.ifeq(wrongType); //XXX this case might call for screaming
codeStream.aload_0();
codeStream.checkcast(interfaceType);
codeStream.invokeinterface(world.makeMethodBindingForCall(
AjcMemberMaker.perObjectInterfaceGet(typeX)));
//XXX should do a check for null here and throw a NoAspectBound
codeStream.ifnonnull(wrongType);
codeStream.aload_0();
codeStream.checkcast(interfaceType);
codeStream.new_(binding);
codeStream.dup();
codeStream.invokespecial(
new MethodBinding(0, "<init>".toCharArray(),
BaseTypes.VoidBinding, new TypeBinding[0],
new ReferenceBinding[0], binding));
codeStream.invokeinterface(world.makeMethodBindingForCall(
AjcMemberMaker.perObjectInterfaceSet(typeX)));
wrongType.place();
codeStream.return_();
// body ends here
}});
}
// PTWIMPL Generate getInstance method
private void generatePerTypeWithinGetInstanceMethod(ClassFile classFile) {
final EclipseFactory world = EclipseFactory.fromScopeLookupEnvironment(this.scope);
generateMethod(classFile, AjcMemberMaker.perTypeWithinGetInstance(world.fromBinding(binding)),
new BodyGenerator() {
public void generate(CodeStream codeStream) {
ExceptionLabel exc = new ExceptionLabel(codeStream,world.makeTypeBinding(UnresolvedType.JAVA_LANG_EXCEPTION));
exc.placeStart();
codeStream.aload_0();
codeStream.ldc(NameMangler.perTypeWithinLocalAspectOf(typeX));
codeStream.aconst_null();
codeStream.invokevirtual(
new MethodBinding(
0,
"getDeclaredMethod".toCharArray(),
world.makeTypeBinding(UnresolvedType.forSignature("Ljava/lang/reflect/Method;")), // return type
new TypeBinding[]{world.makeTypeBinding(UnresolvedType.forSignature("Ljava/lang/String;")),
world.makeTypeBinding(UnresolvedType.forSignature("[Ljava/lang/Class;"))},
new ReferenceBinding[0],
(ReferenceBinding)world.makeTypeBinding(UnresolvedType.JAVA_LANG_CLASS)));
codeStream.astore_1();
codeStream.aload_1();
codeStream.aconst_null();
codeStream.aconst_null();
codeStream.invokevirtual(
new MethodBinding(
0,
"invoke".toCharArray(),
world.makeTypeBinding(UnresolvedType.OBJECT),
new TypeBinding[]{world.makeTypeBinding(UnresolvedType.OBJECT),world.makeTypeBinding(UnresolvedType.forSignature("[Ljava/lang/Object;"))},
new ReferenceBinding[0],
(ReferenceBinding)world.makeTypeBinding(UnresolvedType.JAVA_LANG_REFLECT_METHOD)));
codeStream.checkcast(world.makeTypeBinding(typeX));
codeStream.astore_2();
codeStream.aload_2();
exc.placeEnd();
codeStream.areturn();
exc.place();
codeStream.astore_1();
// this just returns null now - the old version used to throw the caught exception!
codeStream.aconst_null();
codeStream.areturn();
}});
}
private void generatePerTypeWithinCreateAspectInstanceMethod(ClassFile classFile) {
final EclipseFactory world = EclipseFactory.fromScopeLookupEnvironment(this.scope);
generateMethod(classFile, AjcMemberMaker.perTypeWithinCreateAspectInstance(world.fromBinding(binding)),
new BodyGenerator() {
public void generate(CodeStream codeStream) {
codeStream.new_(world.makeTypeBinding(typeX));
codeStream.dup();
codeStream.invokespecial(new MethodBinding(0, "<init>".toCharArray(),
BaseTypes.VoidBinding, new TypeBinding[0],
new ReferenceBinding[0], binding));
codeStream.astore_1();
codeStream.aload_1();
codeStream.aload_0();
codeStream.putfield(world.makeFieldBinding(AjcMemberMaker.perTypeWithinWithinTypeField(typeX,typeX)));
codeStream.aload_1();
codeStream.areturn();
}});
}
private void generatePerSingletonAspectOfMethod(ClassFile classFile) {
final EclipseFactory world = EclipseFactory.fromScopeLookupEnvironment(this.scope);
generateMethod(classFile, aspectOfMethod, new BodyGenerator() {
public void generate(CodeStream codeStream) {
// Old style aspectOf() method which confused decompilers
// // body starts here
// codeStream.getstatic(world.makeFieldBinding(AjcMemberMaker.perSingletonField(
// typeX)));
// Label isNull = new Label(codeStream);
// codeStream.dup();
// codeStream.ifnull(isNull);
// codeStream.areturn();
// isNull.place();
//
// codeStream.incrStackSize(+1); // the dup trick above confuses the stack counter
// codeStream.new_(world.makeTypeBinding(AjcMemberMaker.NO_ASPECT_BOUND_EXCEPTION));
// codeStream.dup();
// codeStream.ldc(typeX.getNameAsIdentifier());
// codeStream.getstatic(initFailureField);
// codeStream.invokespecial(world.makeMethodBindingForCall(
// AjcMemberMaker.noAspectBoundExceptionInitWithCause()
// ));
// codeStream.athrow();
// // body ends here
// The stuff below generates code that looks like this:
/*
* if (ajc$perSingletonInstance == null)
* throw new NoAspectBoundException("A", ajc$initFailureCause);
* else
* return ajc$perSingletonInstance;
*/
// body starts here (see end of each line for what it is doing!)
FieldBinding fb = world.makeFieldBinding(AjcMemberMaker.perSingletonField(typeX));
codeStream.getstatic(fb); // GETSTATIC
Label isNonNull = new Label(codeStream);
codeStream.ifnonnull(isNonNull); // IFNONNULL
codeStream.new_(world.makeTypeBinding(AjcMemberMaker.NO_ASPECT_BOUND_EXCEPTION)); // NEW
codeStream.dup(); // DUP
codeStream.ldc(typeX.getNameAsIdentifier()); // LDC
codeStream.getstatic(initFailureField); // GETSTATIC
codeStream.invokespecial(world.makeMethodBindingForCall(
AjcMemberMaker.noAspectBoundExceptionInitWithCause())); // INVOKESPECIAL
codeStream.athrow(); // ATHROW
isNonNull.place();
codeStream.getstatic(fb); // GETSTATIC
codeStream.areturn(); // ARETURN
// body ends here
}});
}
private void generatePerSingletonHasAspectMethod(ClassFile classFile) {
final EclipseFactory world = EclipseFactory.fromScopeLookupEnvironment(this.scope);
generateMethod(classFile, hasAspectMethod, new BodyGenerator() {
public void generate(CodeStream codeStream) {
// body starts here
codeStream.getstatic(world.makeFieldBinding(AjcMemberMaker.perSingletonField(
typeX)));
Label isNull = new Label(codeStream);
codeStream.ifnull(isNull);
codeStream.iconst_1();
codeStream.ireturn();
isNull.place();
codeStream.iconst_0();
codeStream.ireturn();
// body ends here
}});
}
private void generatePerSingletonAjcClinitMethod(
ClassFile classFile)
{
final EclipseFactory world = EclipseFactory.fromScopeLookupEnvironment(this.scope);
generateMethod(classFile, world.makeMethodBinding(AjcMemberMaker.ajcPostClinitMethod(
world.fromBinding(binding))),
new BodyGenerator() {
public void generate(CodeStream codeStream) {
// body starts here
codeStream.new_(binding);
codeStream.dup();
codeStream.invokespecial(
new MethodBinding(0, "<init>".toCharArray(),
BaseTypes.VoidBinding, new TypeBinding[0],
new ReferenceBinding[0], binding));
codeStream.putstatic(
world.makeFieldBinding(
AjcMemberMaker.perSingletonField(
typeX)));
codeStream.return_();
// body ends here
}});
}
private void generateSuperAccessMethod(ClassFile classFile, final MethodBinding accessMethod, final ResolvedMember method) {
generateMethod(classFile, accessMethod,
new BodyGenerator() {
public void generate(CodeStream codeStream) {
// body starts here
codeStream.aload_0();
AstUtil.generateParameterLoads(accessMethod.parameters, codeStream);
codeStream.invokespecial(
factory.makeMethodBinding(method));
AstUtil.generateReturn(accessMethod.returnType, codeStream);
// body ends here
}});
}
private void generateInlineAccessMethod(ClassFile classFile, final Binding binding, final ResolvedMember member) {
if (binding instanceof InlineAccessFieldBinding) {
generateInlineAccessors(classFile, (InlineAccessFieldBinding)binding, member);
} else {
generateInlineAccessMethod(classFile, (MethodBinding)binding, member);
}
}
private void generateInlineAccessors(ClassFile classFile, final InlineAccessFieldBinding accessField, final ResolvedMember field) {
final FieldBinding fieldBinding = factory.makeFieldBinding(field);
generateMethod(classFile, accessField.reader,
makeEffectiveSignatureAttribute(field,Shadow.FieldGet,false),
new BodyGenerator() {
public void generate(CodeStream codeStream) {
// body starts here
if (field.isStatic()) {
codeStream.getstatic(fieldBinding);
} else {
codeStream.aload_0();
codeStream.getfield(fieldBinding);
}
AstUtil.generateReturn(accessField.reader.returnType, codeStream);
// body ends here
}});
generateMethod(classFile, accessField.writer,
makeEffectiveSignatureAttribute(field,Shadow.FieldSet,false),
new BodyGenerator() {
public void generate(CodeStream codeStream) {
// body starts here
if (field.isStatic()) {
codeStream.load(fieldBinding.type, 0);
codeStream.putstatic(fieldBinding);
} else {
codeStream.aload_0();
codeStream.load(fieldBinding.type, 1);
codeStream.putfield(fieldBinding);
}
codeStream.return_();
// body ends here
}});
}
private void generateInlineAccessMethod(ClassFile classFile, final MethodBinding accessMethod, final ResolvedMember method) {
generateMethod(classFile, accessMethod,
makeEffectiveSignatureAttribute(method, Shadow.MethodCall, false),
new BodyGenerator() {
public void generate(CodeStream codeStream) {
// body starts here
AstUtil.generateParameterLoads(accessMethod.parameters, codeStream);
if (method.isStatic()) {
codeStream.invokestatic(factory.makeMethodBinding(method));
} else {
codeStream.invokevirtual(factory.makeMethodBinding(method));
}
AstUtil.generateReturn(accessMethod.returnType, codeStream);
// body ends here
}});
}
private PerClause.Kind lookupPerClauseKind(ReferenceBinding binding) {
PerClause perClause;
if (binding instanceof BinaryTypeBinding) {
ResolvedType superTypeX = factory.fromEclipse(binding);
perClause = superTypeX.getPerClause();
} else if (binding instanceof SourceTypeBinding ) {
SourceTypeBinding sourceSc = (SourceTypeBinding)binding;
if (sourceSc.scope.referenceContext instanceof AspectDeclaration) {
perClause = ((AspectDeclaration)sourceSc.scope.referenceContext).perClause;
} else {
return null;
}
} else if (binding instanceof ParameterizedTypeBinding) {
ParameterizedTypeBinding pBinding = (ParameterizedTypeBinding)binding;
if (pBinding.type instanceof SourceTypeBinding) {
SourceTypeBinding sourceSc = (SourceTypeBinding)pBinding.type;
if (sourceSc.scope != null && sourceSc.scope.referenceContext instanceof AspectDeclaration) {
perClause = ((AspectDeclaration)sourceSc.scope.referenceContext).perClause;
} else {
return null;
}
} else {
perClause=null;
}
} else {
//XXX need to handle this too
return null;
}
if (perClause == null) {
return lookupPerClauseKind(binding.superclass());
} else {
return perClause.getKind();
}
}
private void buildPerClause(ClassScope scope) {
EclipseFactory world = EclipseFactory.fromScopeLookupEnvironment(scope);
if (perClause == null) {
PerClause.Kind kind = lookupPerClauseKind(binding.superclass);
if (kind == null) {
perClause = new PerSingleton();
} else {
perClause = new PerFromSuper(kind);
}
}
aspectAttribute = new AjAttribute.Aspect(perClause);
if (ignoreFurtherInvestigation) return; //???
if (!isAbstract()) {
if (perClause.getKind() == PerClause.SINGLETON) {
aspectOfMethod = AjcMemberMaker.perSingletonAspectOfMethod(typeX);
hasAspectMethod = AjcMemberMaker.perSingletonHasAspectMethod(typeX);
} else if (perClause.getKind() == PerClause.PERCFLOW) {
aspectOfMethod = AjcMemberMaker.perCflowAspectOfMethod(typeX);
hasAspectMethod = AjcMemberMaker.perCflowHasAspectMethod(typeX);
} else if (perClause.getKind() == PerClause.PEROBJECT) {
aspectOfMethod = AjcMemberMaker.perObjectAspectOfMethod(typeX);
hasAspectMethod = AjcMemberMaker.perObjectHasAspectMethod(typeX);
} else if (perClause.getKind() == PerClause.PERTYPEWITHIN) {
// PTWIMPL Use these variants of aspectOf()/hasAspect()
aspectOfMethod = AjcMemberMaker.perTypeWithinAspectOfMethod(typeX,world.getWorld().isInJava5Mode());
hasAspectMethod = AjcMemberMaker.perTypeWithinHasAspectMethod(typeX,world.getWorld().isInJava5Mode());
//ptwGetWithinTypeMethod = AjcMemberMaker.perTypeWithinGetWithinTypeMethod(typeX,world.getWorld().isInJava5Mode());
//binding.addMethod(world.makeMethodBinding(ptwGetWithinTypeMethod));
} else {
throw new RuntimeException("bad per clause: " + perClause);
}
binding.addMethod(world.makeMethodBinding(aspectOfMethod));
binding.addMethod(world.makeMethodBinding(hasAspectMethod));
}
resolvePerClause(); //XXX might be too soon for some error checking
}
private PerClause resolvePerClause() {
EclipseScope iscope = new EclipseScope(new FormalBinding[0], scope);
perClause.resolve(iscope);
return perClause;
}
public void buildInterTypeAndPerClause(ClassScope classScope) {
factory = EclipseFactory.fromScopeLookupEnvironment(scope);
if (isPrivileged) {
binding.privilegedHandler = new PrivilegedHandler(this);
}
checkSpec(classScope);
if (ignoreFurtherInvestigation) return;
buildPerClause(scope);
if (methods != null) {
for (int i = 0; i < methods.length; i++) {
if (methods[i] instanceof InterTypeDeclaration) {
EclipseTypeMunger m = ((InterTypeDeclaration)methods[i]).build(classScope);
if (m != null) concreteName.typeMungers.add(m);
} else if (methods[i] instanceof DeclareDeclaration) {
Declare d = ((DeclareDeclaration)methods[i]).build(classScope);
if (d != null) concreteName.declares.add(d);
}
}
}
concreteName.getDeclaredPointcuts();
}
// public String toString(int tab) {
// return tabString(tab) + toStringHeader() + toStringBody(tab);
// }
//
// public String toStringBody(int tab) {
//
// String s = " {"; //$NON-NLS-1$
//
//
// if (memberTypes != null) {
// for (int i = 0; i < memberTypes.length; i++) {
// if (memberTypes[i] != null) {
// s += "\n" + memberTypes[i].toString(tab + 1); //$NON-NLS-1$
// }
// }
// }
// if (fields != null) {
// for (int fieldI = 0; fieldI < fields.length; fieldI++) {
// if (fields[fieldI] != null) {
// s += "\n" + fields[fieldI].toString(tab + 1); //$NON-NLS-1$
// if (fields[fieldI].isField())
// s += ";"; //$NON-NLS-1$
// }
// }
// }
// if (methods != null) {
// for (int i = 0; i < methods.length; i++) {
// if (methods[i] != null) {
// s += "\n" + methods[i].toString(tab + 1); //$NON-NLS-1$
// }
// }
// }
// s += "\n" + tabString(tab) + "}"; //$NON-NLS-2$ //$NON-NLS-1$
// return s;
// }
public StringBuffer printHeader(int indent, StringBuffer output) {
// since all aspects are made public we want to print the
// modifiers that were supplied in the original source code
printModifiers(this.declaredModifiers,output);
output.append("aspect " );
output.append(name);
if (superclass != null) {
output.append(" extends "); //$NON-NLS-1$
superclass.print(0, output);
}
if (superInterfaces != null && superInterfaces.length > 0) {
output.append((kind() == IGenericType.INTERFACE_DECL) ? " extends " : " implements ");//$NON-NLS-2$ //$NON-NLS-1$
for (int i = 0; i < superInterfaces.length; i++) {
if (i > 0) output.append( ", "); //$NON-NLS-1$
superInterfaces[i].print(0, output);
}
}
return output;
//XXX we should append the per-clause
}
/**
* All aspects are made public after type checking etc. and before generating code
* (so that the advice can be called!).
* This method returns the modifiers as specified in the original source code declaration
* so that the structure model sees the right thing.
*/
public int getDeclaredModifiers() {
return declaredModifiers;
}
}
|
148,693 |
Bug 148693 woven class does not pass org.apache.bcel.verifier.statics.Pass2Verifier
| null |
resolved fixed
|
82f217f
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-07-05T08:22:55Z | 2006-06-26T16:40:00Z |
tests/src/org/aspectj/systemtest/ajc153/Ajc153Tests.java
|
/*******************************************************************************
* Copyright (c) 2006 IBM
* 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.ajc153;
import java.io.File;
import junit.framework.Test;
import org.aspectj.apache.bcel.Repository;
import org.aspectj.apache.bcel.classfile.JavaClass;
import org.aspectj.apache.bcel.classfile.Method;
import org.aspectj.apache.bcel.util.ClassPath;
import org.aspectj.apache.bcel.util.SyntheticRepository;
import org.aspectj.apache.bcel.verifier.VerificationResult;
import org.aspectj.apache.bcel.verifier.Verifier;
import org.aspectj.apache.bcel.verifier.VerifierFactory;
import org.aspectj.testing.XMLBasedAjcTestCase;
public class Ajc153Tests extends org.aspectj.testing.XMLBasedAjcTestCase {
// public void testArgnamesAndJavac_pr148381() { runTest("argNames and javac");}
// public void testCFlowXMLAspectLTW_pr149096() { runTest("cflow xml concrete aspect"); }
public void testIllegalStateException_pr148737() { runTest("illegalstateexception for non generic type");}
public void testAtajInheritance_pr149305_1() { runTest("ataj inheritance - 1");}
public void testAtajInheritance_pr149305_2() { runTest("ataj inheritance - 2");}
public void testAtajInheritance_pr149305_3() { runTest("ataj inheritance - 3");}
// work in progress
// public void testVerificationFailureForAspectOf_pr148693() throws ClassNotFoundException {
// runTest("verification problem");
// verifyClass("mypackage.MyAspect");
// }
// TODO refactor into a util class
/**
* Performs verification of a class - the supplied class is expected to exist in the sandbox
* directory so typically this is called after a small compile step has been invoked to build it.
*/
public void verifyClass(String clazzname) {
JavaClass jc = null;
try {
jc = getClassFrom(ajc.getSandboxDirectory().getAbsolutePath(),clazzname);
} catch (ClassNotFoundException cnfe) {
fail("Could not find "+clazzname+" in the sandbox: "+ajc.getSandboxDirectory());
}
assertTrue("Could not find class",jc!=null);
Repository.setRepository(jc.getRepository());
Verifier v = VerifierFactory.getVerifier("mypackage.MyAspect");
VerificationResult vr = v.doPass1();
System.err.println(vr);
assertTrue("Verification: "+vr,vr.getStatus()==VerificationResult.VERIFIED_OK);
vr = v.doPass2();
System.err.println(vr);
assertTrue("Verification: "+vr,vr.getStatus()==VerificationResult.VERIFIED_OK);
Method[] ms = jc.getMethods();
for (int i = 0; i < ms.length; i++) {
System.err.println("Pass3a for "+ms[i]);
vr = v.doPass3a(i);
System.err.println(vr);
assertTrue("Verification: "+vr,vr.getStatus()==VerificationResult.VERIFIED_OK);
System.err.println("Pass3b for "+ms[i]);
vr = v.doPass3b(i);
System.err.println(vr);
assertTrue("Verification: "+vr,vr.getStatus()==VerificationResult.VERIFIED_OK);
}
}
protected JavaClass getClassFrom(String frompath,String clazzname) throws ClassNotFoundException {
SyntheticRepository repos = createRepos(frompath);
return repos.loadClass(clazzname);
}
public SyntheticRepository createRepos(String cpentry) {
ClassPath cp = new ClassPath(
cpentry+File.pathSeparator+
System.getProperty("java.class.path"));
return SyntheticRepository.getInstance(cp);
}
/////////////////////////////////////////
public static Test suite() {
return XMLBasedAjcTestCase.loadSuite(Ajc153Tests.class);
}
protected File getSpecFile() {
return new File("../tests/src/org/aspectj/systemtest/ajc153/ajc153.xml");
}
}
|
148,693 |
Bug 148693 woven class does not pass org.apache.bcel.verifier.statics.Pass2Verifier
| null |
resolved fixed
|
82f217f
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-07-05T08:22:55Z | 2006-06-26T16:40:00Z |
tests/src/org/aspectj/testing/Utils.java
| |
148,409 |
Bug 148409 [generics] ClassCastException in UnresolvedType.java:348
|
I am using AspectJ load time weaving with Spring 2.0 RC1 to inject my entities, and I am getting the following exception: java.lang.ClassCastException: org.aspectj.apache.bcel.classfile.Signature$TypeVariableSignature at org.aspectj.weaver.UnresolvedType.forGenericTypeSignature(UnresolvedType.java:348) at org.aspectj.weaver.bcel.BcelWorld.addSourceObjectType(BcelWorld.java:385) at org.aspectj.weaver.loadtime.ClassLoaderWeavingAdaptor.accept(ClassLoaderWeavingAdaptor.java:492) at org.aspectj.weaver.tools.WeavingAdaptor.shouldWeave(WeavingAdaptor.java:230) at org.aspectj.weaver.tools.WeavingAdaptor.weaveClass(WeavingAdaptor.java:210) at org.aspectj.weaver.loadtime.Aj.preProcess(Aj.java:65) at org.aspectj.weaver.loadtime.ClassPreProcessorAgentAdapter.transform(ClassPreProcessorAgentAdapter.java:55) at sun.instrument.TransformerManager.transform(TransformerManager.java:122) at sun.instrument.InstrumentationImpl.transform(InstrumentationImpl.java:155) at java.lang.ClassLoader.defineClass1(Native Method) . . . Having examined the call stack under the debugger, this seems to happening when the weaver is attempting to determine whether a particular class should be weaved. The exception is thrown in the following method, at the cast highlighted below. public static UnresolvedType forGenericTypeSignature(String sig,String declaredGenericSig) { UnresolvedType ret = UnresolvedType.forSignature(sig); ret.typeKind=TypeKind.GENERIC; ClassSignature csig = new GenericSignatureParser().parseAsClassSignature(declaredGenericSig); Signature.FormalTypeParameter[] ftps = csig.formalTypeParameters; ret.typeVariables = new TypeVariable[ftps.length]; for (int i = 0; i < ftps.length; i++) { Signature.FormalTypeParameter parameter = ftps[i]; Signature.ClassTypeSignature cts = (Signature.ClassTypeSignature)parameter.classBound; // EXCEPTION HERE! ret.typeVariables[i]=new TypeVariable(ftps[i].identifier,UnresolvedType.forSignature(cts.outerType.identifier+";")); } ret.signatureErasure = sig; ret.signature = ret.signatureErasure; return ret; } The class in question (which is not one that requires weaving), has the following signature: public class HibernateEntityDAO<interfaceT extends SecurityEntity, concreteT extends interfaceT> extends HibernateDaoSupport implements EntityDAO<interfaceT> The exception is happening because the parameter.classBound member is not of type Signature.ClassTypeSignature, but an instance of Signature.TypeVariableSignature. The loop variable i is 1, and parameter.identifier is concreteT, so it looks like it's the signature of the second type parameter (concreteT) that is tripping up the weaver.
|
resolved fixed
|
369de87
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-07-06T12:12:07Z | 2006-06-23T16:26:40Z |
tests/bugs153/pr148409/Blurgh.java
| |
148,409 |
Bug 148409 [generics] ClassCastException in UnresolvedType.java:348
|
I am using AspectJ load time weaving with Spring 2.0 RC1 to inject my entities, and I am getting the following exception: java.lang.ClassCastException: org.aspectj.apache.bcel.classfile.Signature$TypeVariableSignature at org.aspectj.weaver.UnresolvedType.forGenericTypeSignature(UnresolvedType.java:348) at org.aspectj.weaver.bcel.BcelWorld.addSourceObjectType(BcelWorld.java:385) at org.aspectj.weaver.loadtime.ClassLoaderWeavingAdaptor.accept(ClassLoaderWeavingAdaptor.java:492) at org.aspectj.weaver.tools.WeavingAdaptor.shouldWeave(WeavingAdaptor.java:230) at org.aspectj.weaver.tools.WeavingAdaptor.weaveClass(WeavingAdaptor.java:210) at org.aspectj.weaver.loadtime.Aj.preProcess(Aj.java:65) at org.aspectj.weaver.loadtime.ClassPreProcessorAgentAdapter.transform(ClassPreProcessorAgentAdapter.java:55) at sun.instrument.TransformerManager.transform(TransformerManager.java:122) at sun.instrument.InstrumentationImpl.transform(InstrumentationImpl.java:155) at java.lang.ClassLoader.defineClass1(Native Method) . . . Having examined the call stack under the debugger, this seems to happening when the weaver is attempting to determine whether a particular class should be weaved. The exception is thrown in the following method, at the cast highlighted below. public static UnresolvedType forGenericTypeSignature(String sig,String declaredGenericSig) { UnresolvedType ret = UnresolvedType.forSignature(sig); ret.typeKind=TypeKind.GENERIC; ClassSignature csig = new GenericSignatureParser().parseAsClassSignature(declaredGenericSig); Signature.FormalTypeParameter[] ftps = csig.formalTypeParameters; ret.typeVariables = new TypeVariable[ftps.length]; for (int i = 0; i < ftps.length; i++) { Signature.FormalTypeParameter parameter = ftps[i]; Signature.ClassTypeSignature cts = (Signature.ClassTypeSignature)parameter.classBound; // EXCEPTION HERE! ret.typeVariables[i]=new TypeVariable(ftps[i].identifier,UnresolvedType.forSignature(cts.outerType.identifier+";")); } ret.signatureErasure = sig; ret.signature = ret.signatureErasure; return ret; } The class in question (which is not one that requires weaving), has the following signature: public class HibernateEntityDAO<interfaceT extends SecurityEntity, concreteT extends interfaceT> extends HibernateDaoSupport implements EntityDAO<interfaceT> The exception is happening because the parameter.classBound member is not of type Signature.ClassTypeSignature, but an instance of Signature.TypeVariableSignature. The loop variable i is 1, and parameter.identifier is concreteT, so it looks like it's the signature of the second type parameter (concreteT) that is tripping up the weaver.
|
resolved fixed
|
369de87
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-07-06T12:12:07Z | 2006-06-23T16:26:40Z |
tests/bugs153/pr148409/X.java
| |
148,409 |
Bug 148409 [generics] ClassCastException in UnresolvedType.java:348
|
I am using AspectJ load time weaving with Spring 2.0 RC1 to inject my entities, and I am getting the following exception: java.lang.ClassCastException: org.aspectj.apache.bcel.classfile.Signature$TypeVariableSignature at org.aspectj.weaver.UnresolvedType.forGenericTypeSignature(UnresolvedType.java:348) at org.aspectj.weaver.bcel.BcelWorld.addSourceObjectType(BcelWorld.java:385) at org.aspectj.weaver.loadtime.ClassLoaderWeavingAdaptor.accept(ClassLoaderWeavingAdaptor.java:492) at org.aspectj.weaver.tools.WeavingAdaptor.shouldWeave(WeavingAdaptor.java:230) at org.aspectj.weaver.tools.WeavingAdaptor.weaveClass(WeavingAdaptor.java:210) at org.aspectj.weaver.loadtime.Aj.preProcess(Aj.java:65) at org.aspectj.weaver.loadtime.ClassPreProcessorAgentAdapter.transform(ClassPreProcessorAgentAdapter.java:55) at sun.instrument.TransformerManager.transform(TransformerManager.java:122) at sun.instrument.InstrumentationImpl.transform(InstrumentationImpl.java:155) at java.lang.ClassLoader.defineClass1(Native Method) . . . Having examined the call stack under the debugger, this seems to happening when the weaver is attempting to determine whether a particular class should be weaved. The exception is thrown in the following method, at the cast highlighted below. public static UnresolvedType forGenericTypeSignature(String sig,String declaredGenericSig) { UnresolvedType ret = UnresolvedType.forSignature(sig); ret.typeKind=TypeKind.GENERIC; ClassSignature csig = new GenericSignatureParser().parseAsClassSignature(declaredGenericSig); Signature.FormalTypeParameter[] ftps = csig.formalTypeParameters; ret.typeVariables = new TypeVariable[ftps.length]; for (int i = 0; i < ftps.length; i++) { Signature.FormalTypeParameter parameter = ftps[i]; Signature.ClassTypeSignature cts = (Signature.ClassTypeSignature)parameter.classBound; // EXCEPTION HERE! ret.typeVariables[i]=new TypeVariable(ftps[i].identifier,UnresolvedType.forSignature(cts.outerType.identifier+";")); } ret.signatureErasure = sig; ret.signature = ret.signatureErasure; return ret; } The class in question (which is not one that requires weaving), has the following signature: public class HibernateEntityDAO<interfaceT extends SecurityEntity, concreteT extends interfaceT> extends HibernateDaoSupport implements EntityDAO<interfaceT> The exception is happening because the parameter.classBound member is not of type Signature.ClassTypeSignature, but an instance of Signature.TypeVariableSignature. The loop variable i is 1, and parameter.identifier is concreteT, so it looks like it's the signature of the second type parameter (concreteT) that is tripping up the weaver.
|
resolved fixed
|
369de87
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-07-06T12:12:07Z | 2006-06-23T16:26:40Z |
tests/src/org/aspectj/systemtest/ajc153/Ajc153Tests.java
|
/*******************************************************************************
* Copyright (c) 2006 IBM
* 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.ajc153;
import java.io.File;
import junit.framework.Test;
import org.aspectj.testing.Utils;
import org.aspectj.testing.XMLBasedAjcTestCase;
public class Ajc153Tests extends org.aspectj.testing.XMLBasedAjcTestCase {
// public void testArgnamesAndJavac_pr148381() { runTest("argNames and javac");}
// public void testCFlowXMLAspectLTW_pr149096() { runTest("cflow xml concrete aspect"); }
public void testIllegalStateException_pr148737() { runTest("illegalstateexception for non generic type");}
public void testAtajInheritance_pr149305_1() { runTest("ataj inheritance - 1");}
public void testAtajInheritance_pr149305_2() { runTest("ataj inheritance - 2");}
public void testAtajInheritance_pr149305_3() { runTest("ataj inheritance - 3");}
public void testVerificationFailureForAspectOf_pr148693() {
runTest("verification problem"); // build the code
Utils.verifyClass(ajc,"mypackage.MyAspect"); // verify it <<< BRAND NEW VERIFY UTILITY FOR EVERYONE TO TRY ;)
}
public void testIncorrectAnnotationValue_pr148537() { runTest("incorrect annotation value");}
public void testVerifyErrNoTypeCflowField_pr145693_1() { runTest("verifyErrNoTypeCflowField"); }
public void testVerifyErrInpathNoTypeCflowField_pr145693_2() { runTest("verifyErrInpathNoTypeCflowField"); }
public void testCpathNoTypeCflowField_pr145693_3() { runTest("cpathNoTypeCflowField"); }
//public void testVisibilityProblem_pr149071() { runTest("visibility problem");}
//public void testAdviceNotWovenAspectPath_pr147841() { runTest("advice not woven on aspectpath");}
/////////////////////////////////////////
public static Test suite() {
return XMLBasedAjcTestCase.loadSuite(Ajc153Tests.class);
}
protected File getSpecFile() {
return new File("../tests/src/org/aspectj/systemtest/ajc153/ajc153.xml");
}
}
|
148,409 |
Bug 148409 [generics] ClassCastException in UnresolvedType.java:348
|
I am using AspectJ load time weaving with Spring 2.0 RC1 to inject my entities, and I am getting the following exception: java.lang.ClassCastException: org.aspectj.apache.bcel.classfile.Signature$TypeVariableSignature at org.aspectj.weaver.UnresolvedType.forGenericTypeSignature(UnresolvedType.java:348) at org.aspectj.weaver.bcel.BcelWorld.addSourceObjectType(BcelWorld.java:385) at org.aspectj.weaver.loadtime.ClassLoaderWeavingAdaptor.accept(ClassLoaderWeavingAdaptor.java:492) at org.aspectj.weaver.tools.WeavingAdaptor.shouldWeave(WeavingAdaptor.java:230) at org.aspectj.weaver.tools.WeavingAdaptor.weaveClass(WeavingAdaptor.java:210) at org.aspectj.weaver.loadtime.Aj.preProcess(Aj.java:65) at org.aspectj.weaver.loadtime.ClassPreProcessorAgentAdapter.transform(ClassPreProcessorAgentAdapter.java:55) at sun.instrument.TransformerManager.transform(TransformerManager.java:122) at sun.instrument.InstrumentationImpl.transform(InstrumentationImpl.java:155) at java.lang.ClassLoader.defineClass1(Native Method) . . . Having examined the call stack under the debugger, this seems to happening when the weaver is attempting to determine whether a particular class should be weaved. The exception is thrown in the following method, at the cast highlighted below. public static UnresolvedType forGenericTypeSignature(String sig,String declaredGenericSig) { UnresolvedType ret = UnresolvedType.forSignature(sig); ret.typeKind=TypeKind.GENERIC; ClassSignature csig = new GenericSignatureParser().parseAsClassSignature(declaredGenericSig); Signature.FormalTypeParameter[] ftps = csig.formalTypeParameters; ret.typeVariables = new TypeVariable[ftps.length]; for (int i = 0; i < ftps.length; i++) { Signature.FormalTypeParameter parameter = ftps[i]; Signature.ClassTypeSignature cts = (Signature.ClassTypeSignature)parameter.classBound; // EXCEPTION HERE! ret.typeVariables[i]=new TypeVariable(ftps[i].identifier,UnresolvedType.forSignature(cts.outerType.identifier+";")); } ret.signatureErasure = sig; ret.signature = ret.signatureErasure; return ret; } The class in question (which is not one that requires weaving), has the following signature: public class HibernateEntityDAO<interfaceT extends SecurityEntity, concreteT extends interfaceT> extends HibernateDaoSupport implements EntityDAO<interfaceT> The exception is happening because the parameter.classBound member is not of type Signature.ClassTypeSignature, but an instance of Signature.TypeVariableSignature. The loop variable i is 1, and parameter.identifier is concreteT, so it looks like it's the signature of the second type parameter (concreteT) that is tripping up the weaver.
|
resolved fixed
|
369de87
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-07-06T12:12:07Z | 2006-06-23T16:26:40Z |
weaver/src/org/aspectj/weaver/UnresolvedType.java
|
/* *******************************************************************
* Copyright (c) 2002,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://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* PARC initial implementation
* Andy Clement start of generics upgrade...
* Adrian Colyer - overhaul
* ******************************************************************/
package org.aspectj.weaver;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.util.Map;
import org.aspectj.apache.bcel.classfile.GenericSignatureParser;
import org.aspectj.apache.bcel.classfile.Signature;
import org.aspectj.apache.bcel.classfile.Signature.ClassSignature;
/**
* A UnresolvedType represents a type to the weaver. It has a basic signature that knows
* nothing about type variables, type parameters, etc.. TypeXs are resolved in some World
* (a repository of types). When a UnresolvedType is resolved it turns into a
* ResolvedType which may be a primitive type, an array type or a ReferenceType.
* ReferenceTypes may refer to simple, generic, parameterized or type-variable
* based reference types. A ReferenceType is backed by a delegate that provides
* information about the type based on some repository (currently either BCEL
* or an EclipseSourceType, but in the future we probably need to support
* java.lang.reflect based delegates too).
*
* Every UnresolvedType has a signature, the unique key for the type in the world.
*
*
* TypeXs are fully aware of their complete type information (there is no
* erasure in the UnresolvedType world). To achieve this, the signature of TypeXs
* combines the basic Java signature and the generic signature information
* into one complete signature.
*
* The format of a UnresolvedType signature is as follows:
*
* a simple (non-generic, non-parameterized) type has the as its signature
* the Java signature.
* e.g. Ljava/lang/String;
*
* a generic type has signature:
* TypeParamsOpt ClassSig SuperClassSig SuperIntfListOpt
*
* following the Generic signature grammar in the JVM spec., but with the
* addition of the ClassSignature (which is not in the generic signature). In addition
* type variable names are replaced by a simple number which represents their
* declaration order in the type declaration.
*
* e.g. public class Foo<T extends Number> would have signature:
* <1:Ljava/lang/Number>Lorg.xyz.Foo;Ljava/lang/Object;
*
* A parameterized type is a distinct type in the world with its own signature
* following the grammar:
*
* TypeParamsOpt ClassSig<ParamSigList>;
*
* but with the L for the class sig replaced by "P". For example List<String> has
* signature
*
* Pjava/util/List<Ljava/lang/String>;
*
* and List<T> in the following class :
* class Foo<T> { List<T> lt; }
*
* has signature:
* <1:>Pjava/util/List<T1;>;
*
* A typex that represents a type variable has its own unique signature,
* following the grammar for a FormalTypeParameter in the JVM spec.
*
* A generic typex has its true signature and also an erasure signature.
* Both of these are keys pointing to the same UnresolvedType in the world. For example
* List has signature:
*
* <1:>Ljava/util/List;Ljava/lang/Object;
*
* and the erasure signature
*
* Ljava/util/List;
*
* Generics wildcards introduce their own special signatures for type parameters.
* The wildcard ? has signature *
* The wildcard ? extends Foo has signature +LFoo;
* The wildcard ? super Foo has signature -LFoo;
*/
public class UnresolvedType implements TypeVariableDeclaringElement {
// common types referred to by the weaver
public static final UnresolvedType[] NONE = new UnresolvedType[0];
public static final UnresolvedType OBJECT = forSignature("Ljava/lang/Object;");
public static final UnresolvedType OBJECTARRAY = forSignature("[Ljava/lang/Object;");
public static final UnresolvedType CLONEABLE = forSignature("Ljava/lang/Cloneable;");
public static final UnresolvedType SERIALIZABLE = forSignature("Ljava/io/Serializable;");
public static final UnresolvedType THROWABLE = forSignature("Ljava/lang/Throwable;");
public static final UnresolvedType RUNTIME_EXCEPTION = forSignature("Ljava/lang/RuntimeException;");
public static final UnresolvedType ERROR = forSignature("Ljava/lang/Error;");
public static final UnresolvedType AT_INHERITED = forSignature("Ljava/lang/annotation/Inherited;");
public static final UnresolvedType AT_RETENTION = forSignature("Ljava/lang/annotation/Retention;");
public static final UnresolvedType ENUM = forSignature("Ljava/lang/Enum;");
public static final UnresolvedType ANNOTATION = forSignature("Ljava/lang/annotation/Annotation;");
public static final UnresolvedType JAVA_LANG_CLASS = forSignature("Ljava/lang/Class;");
public static final UnresolvedType JAVA_LANG_STRING = forSignature("Ljava/lang/String;");
public static final UnresolvedType JAVA_LANG_EXCEPTION = forSignature("Ljava/lang/Exception;");
public static final UnresolvedType JAVA_LANG_REFLECT_METHOD = forSignature("Ljava/lang/reflect/Method;");
public static final UnresolvedType SUPPRESS_AJ_WARNINGS = forSignature("Lorg/aspectj/lang/annotation/SuppressAjWarnings;");
public static final UnresolvedType AT_TARGET = forSignature("Ljava/lang/annotation/Target;");
public static final UnresolvedType SOMETHING = new UnresolvedType("?");
public static final UnresolvedType[] ARRAY_WITH_JUST_OBJECT = new UnresolvedType[]{OBJECT};
// this doesn't belong here and will get moved to ResolvedType later in the refactoring
public static final String MISSING_NAME = "@missing@";
protected TypeKind typeKind = TypeKind.SIMPLE; // what kind of type am I?
/**
* THE SIGNATURE - see the comments above for how this is defined
*/
protected String signature;
/**
* The erasure of the signature. Contains only the Java signature of the type
* with all supertype, superinterface, type variable, and parameter information
* removed.
*/
protected String signatureErasure;
/**
* Iff isParameterized(), then these are the type parameters
*/
protected UnresolvedType[] typeParameters;
/**
* Iff isGeneric(), then these are the type variables declared on the type
* Iff isParameterized(), then these are the type variables bound as parameters
* in the type
*/
protected TypeVariable[] typeVariables;
/**
* Iff isGenericWildcard, then this is the upper bound type for ? extends Foo
*/
private UnresolvedType upperBound;
/**
* Iff isGenericWildcard, then this is the lower bound type for ? super Foo
*/
private UnresolvedType lowerBound;
/**
* for wildcards '? extends' or for type variables 'T extends'
*/
private boolean isSuper = false;
private boolean isExtends = false;
/**
* Determines if this represents a primitive type. A primitive type
* is one of nine predefined resolved types.
*
* @return true iff this type represents a primitive type
*
* @see ResolvedType#Boolean
* @see ResolvedType#Character
* @see ResolvedType#Byte
* @see ResolvedType#Short
* @see ResolvedType#Integer
* @see ResolvedType#Long
* @see ResolvedType#Float
* @see ResolvedType#Double
* @see ResolvedType#Void
*/
public boolean isPrimitiveType() { return typeKind == TypeKind.PRIMITIVE; }
public boolean isSimpleType() { return typeKind == TypeKind.SIMPLE; }
public boolean isRawType() { return typeKind == TypeKind.RAW; }
public boolean isGenericType() { return typeKind == TypeKind.GENERIC; }
public boolean isParameterizedType() { return typeKind == TypeKind.PARAMETERIZED; }
public boolean isTypeVariableReference() { return typeKind == TypeKind.TYPE_VARIABLE; }
public boolean isGenericWildcard() { return typeKind == TypeKind.WILDCARD; }
public boolean isExtends() { return isExtends;}
public boolean isSuper() { return isSuper; }
public TypeKind getTypekind() { return typeKind;}
// for any reference type, we can get some extra information...
public final boolean isArray() { return signature.startsWith("["); }
/**
* Equality is checked based on the underlying signature.
* {@link ResolvedType} objects' equals is by reference.
*/
public boolean equals(Object other) {
if (! (other instanceof UnresolvedType)) return false;
return signature.equals(((UnresolvedType) other).signature);
}
/**
* Equality is checked based on the underlying signature, so the hash code
* of a particular type is the hash code of its signature string.
*/
public final int hashCode() {
return signature.hashCode();
}
/**
* Return a version of this parameterized type in which any type parameters
* that are type variable references are replaced by their matching type variable
* binding.
*/
public UnresolvedType parameterize(Map typeBindings) {
throw new UnsupportedOperationException("unable to parameterize unresolved type: " + signature);
}
/**
* protected constructor for use only within UnresolvedType hierarchy. Use
* one of the UnresolvedType.forXXX static methods for normal creation of
* TypeXs.
* Picks apart the signature string to set the type kind and calculates the
* corresponding signatureErasure. A SIMPLE type created from a plain
* Java signature may turn into a GENERIC type when it is resolved.
*
* This method should never be called for a primitive type. (UnresolvedType. forSignature
* deals with those).
*
* @param signature in the form described in the class comment at the
* top of this file.
*/
// protected UnresolvedType(String aSignature) {
// this.signature = aSignature;
//
//
// }
// -----------------------------
// old stuff...
/**
* @param signature the bytecode string representation of this Type
*/
protected UnresolvedType(String signature) {
super();
this.signature = signature;
this.signatureErasure = signature;
if (signature.charAt(0)=='-') isSuper = true;
if (signature.charAt(0)=='+') isExtends = true;
}
protected UnresolvedType(String signature, String signatureErasure) {
this.signature = signature;
this.signatureErasure = signatureErasure;
if (signature.charAt(0)=='-') isSuper = true;
if (signature.charAt(0)=='+') isExtends = true;
}
// called from TypeFactory
public UnresolvedType(String signature, String signatureErasure, UnresolvedType[] typeParams) {
this.signature = signature;
this.signatureErasure = signatureErasure;
this.typeParameters = typeParams;
if (typeParams != null) this.typeKind = TypeKind.PARAMETERIZED;
}
// ---- Things we can do without a world
/**
* This is the size of this type as used in JVM.
*/
public int getSize() {
return 1;
}
public static UnresolvedType makeArray(UnresolvedType base, int dims) {
StringBuffer sig = new StringBuffer();
for (int i=0; i < dims; i++) sig.append("[");
sig.append(base.getSignature());
return UnresolvedType.forSignature(sig.toString());
}
/**
* NOTE: Use forSignature() if you can, it'll be cheaper !
* Constructs a UnresolvedType for a java language type name. For example:
*
* <blockquote><pre>
* UnresolvedType.forName("java.lang.Thread[]")
* UnresolvedType.forName("int")
* </pre></blockquote>
*
* Types may equivalently be produced by this or by {@link #forSignature(String)}.
*
* <blockquote><pre>
* UnresolvedType.forName("java.lang.Thread[]").equals(Type.forSignature("[Ljava/lang/Thread;")
* UnresolvedType.forName("int").equals(Type.forSignature("I"))
* </pre></blockquote>
*
* @param name the java language type name in question.
* @return a type object representing that java language type.
*/
public static UnresolvedType forName(String name) {
return forSignature(nameToSignature(name));
}
/** Constructs a UnresolvedType for each java language type name in an incoming array.
*
* @param names an array of java language type names.
* @return an array of UnresolvedType objects.
* @see #forName(String)
*/
public static UnresolvedType[] forNames(String[] names) {
UnresolvedType[] ret = new UnresolvedType[names.length];
for (int i = 0, len = names.length; i < len; i++) {
ret[i] = UnresolvedType.forName(names[i]);
}
return ret;
}
public static UnresolvedType forGenericType(String name,TypeVariable[] tvbs,String genericSig) {
// TODO asc generics needs a declared sig
String sig = nameToSignature(name);
UnresolvedType ret = UnresolvedType.forSignature(sig);
ret.typeKind=TypeKind.GENERIC;
ret.typeVariables = tvbs;
ret.signatureErasure = sig;
return ret;
}
public static UnresolvedType forGenericTypeSignature(String sig,String declaredGenericSig) {
UnresolvedType ret = UnresolvedType.forSignature(sig);
ret.typeKind=TypeKind.GENERIC;
ClassSignature csig = new GenericSignatureParser().parseAsClassSignature(declaredGenericSig);
Signature.FormalTypeParameter[] ftps = csig.formalTypeParameters;
ret.typeVariables = new TypeVariable[ftps.length];
for (int i = 0; i < ftps.length; i++) {
Signature.FormalTypeParameter parameter = ftps[i];
Signature.ClassTypeSignature cts = (Signature.ClassTypeSignature)parameter.classBound;
ret.typeVariables[i]=new TypeVariable(ftps[i].identifier,UnresolvedType.forSignature(cts.outerType.identifier+";"));
}
ret.signatureErasure = sig;
ret.signature = ret.signatureErasure;
return ret;
}
public static UnresolvedType forGenericTypeVariables(String sig, TypeVariable[] tVars) {
UnresolvedType ret = UnresolvedType.forSignature(sig);
ret.typeKind=TypeKind.GENERIC;
ret.typeVariables = tVars;
ret.signatureErasure = sig;
ret.signature = ret.signatureErasure;
return ret;
}
public static UnresolvedType forRawTypeName(String name) {
UnresolvedType ret = UnresolvedType.forName(name);
ret.typeKind = TypeKind.RAW;
return ret;
}
/**
* Creates a new type array with a fresh type appended to the end.
*
* @param types the left hand side of the new array
* @param end the right hand side of the new array
*/
public static UnresolvedType[] add(UnresolvedType[] types, UnresolvedType end) {
int len = types.length;
UnresolvedType[] ret = new UnresolvedType[len + 1];
System.arraycopy(types, 0, ret, 0, len);
ret[len] = end;
return ret;
}
/**
* Creates a new type array with a fresh type inserted at the beginning.
*
*
* @param start the left hand side of the new array
* @param types the right hand side of the new array
*/
public static UnresolvedType[] insert(UnresolvedType start, UnresolvedType[] types) {
int len = types.length;
UnresolvedType[] ret = new UnresolvedType[len + 1];
ret[0] = start;
System.arraycopy(types, 0, ret, 1, len);
return ret;
}
/**
* Constructs a Type for a JVM bytecode signature string. For example:
*
* <blockquote><pre>
* UnresolvedType.forSignature("[Ljava/lang/Thread;")
* UnresolvedType.forSignature("I");
* </pre></blockquote>
*
* Types may equivalently be produced by this or by {@link #forName(String)}.
*
* <blockquote><pre>
* UnresolvedType.forName("java.lang.Thread[]").equals(Type.forSignature("[Ljava/lang/Thread;")
* UnresolvedType.forName("int").equals(Type.forSignature("I"))
* </pre></blockquote>
*
* @param signature the JVM bytecode signature string for the desired type.
* @return a type object represnting that JVM bytecode signature.
*/
public static UnresolvedType forSignature(String signature) {
switch (signature.charAt(0)) {
case 'B': return ResolvedType.BYTE;
case 'C': return ResolvedType.CHAR;
case 'D': return ResolvedType.DOUBLE;
case 'F': return ResolvedType.FLOAT;
case 'I': return ResolvedType.INT;
case 'J': return ResolvedType.LONG;
case 'L': return TypeFactory.createTypeFromSignature(signature);
case 'P': return TypeFactory.createTypeFromSignature(signature);
case 'S': return ResolvedType.SHORT;
case 'V': return ResolvedType.VOID;
case 'Z': return ResolvedType.BOOLEAN;
case '[': return TypeFactory.createTypeFromSignature(signature);
case '+': return TypeFactory.createTypeFromSignature(signature);
case '-' : return TypeFactory.createTypeFromSignature(signature);
case '?' : return TypeFactory.createTypeFromSignature(signature);
case 'T' : return TypeFactory.createTypeFromSignature(signature);
default: throw new BCException("Bad type signature " + signature);
}
}
/** Constructs a UnresolvedType for each JVM bytecode type signature in an incoming array.
*
* @param names an array of JVM bytecode type signatures
* @return an array of UnresolvedType objects.
* @see #forSignature(String)
*/
public static UnresolvedType[] forSignatures(String[] sigs) {
UnresolvedType[] ret = new UnresolvedType[sigs.length];
for (int i = 0, len = sigs.length; i < len; i++) {
ret[i] = UnresolvedType.forSignature(sigs[i]);
}
return ret;
}
/**
* Returns the name of this type in java language form (e.g. java.lang.Thread or boolean[]).
* This produces a more esthetically pleasing string than {@link java.lang.Class#getName()}.
*
* @return the java language name of this type.
*/
public String getName() {
return signatureToName(signature);
}
public String getSimpleName() {
String name = getRawName();
int lastDot = name.lastIndexOf('.');
if (lastDot != -1) {
name = name.substring(lastDot+1);
}
if (isParameterizedType()) {
StringBuffer sb = new StringBuffer(name);
sb.append("<");
for (int i = 0; i < (typeParameters.length -1); i++) {
sb.append(typeParameters[i].getSimpleName());
sb.append(",");
}
sb.append(typeParameters[typeParameters.length -1].getSimpleName());
sb.append(">");
name = sb.toString();
}
return name;
}
public String getRawName() {
return signatureToName((signatureErasure==null?signature:signatureErasure));
}
public String getBaseName() {
String name = getName();
if (isParameterizedType() || isGenericType()) {
if (typeParameters==null) return name;
else return name.substring(0,name.indexOf("<"));
} else {
return name;
}
}
public String getSimpleBaseName() {
String name = getBaseName();
int lastDot = name.lastIndexOf('.');
if (lastDot != -1) {
name = name.substring(lastDot+1);
}
return name;
}
/**
* Returns an array of strings representing the java langauge names of
* an array of types.
*
* @param types an array of UnresolvedType objects
* @return an array of Strings fo the java language names of types.
* @see #getName()
*/
public static String[] getNames(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;
}
/**
* Returns the name of this type in JVM signature form. For all
* UnresolvedType t:
*
* <blockquote><pre>
* UnresolvedType.forSignature(t.getSignature()).equals(t)
* </pre></blockquote>
*
* and for all String s where s is a lexically valid JVM type signature string:
*
* <blockquote><pre>
* UnresolvedType.forSignature(s).getSignature().equals(s)
* </pre></blockquote>
*
* @return the java JVM signature string for this type.
*/
public String getSignature() {
return signature;
}
// public String getParameterizedSignature() {
// return signature;
// }
/**
* For parameterized types, return the signature for the raw type
*/
public String getErasureSignature() {
if (signatureErasure==null) return signature;
return signatureErasure;
}
private boolean needsModifiableDelegate =false;
public boolean needsModifiableDelegate() {
return needsModifiableDelegate;
}
public void setNeedsModifiableDelegate(boolean b) {
this.needsModifiableDelegate=b;
}
public UnresolvedType getRawType() {
return UnresolvedType.forSignature(getErasureSignature());
}
/**
* Get the upper bound for a generic wildcard
*/
public UnresolvedType getUpperBound() {
return upperBound;
}
/**
* Get the lower bound for a generic wildcard
*/
public UnresolvedType getLowerBound() {
return lowerBound;
}
/**
* Set the upper bound for a generic wildcard
*/
public void setUpperBound(UnresolvedType aBound) {
this.upperBound = aBound;
}
/**
* Set the lower bound for a generic wildcard
*/
public void setLowerBound(UnresolvedType aBound) {
this.lowerBound = aBound;
}
/**
* Returns a UnresolvedType object representing the effective outermost enclosing type
* for a name type. For all other types, this will return the type itself.
*
* The only guarantee is given in JLS 13.1 where code generated according to
* those rules will have type names that can be split apart in this way.
* @return the outermost enclosing UnresolvedType object or this.
*/
public UnresolvedType getOutermostType() {
if (isArray() || isPrimitiveType()) return this;
String sig = getErasureSignature();
int dollar = sig.indexOf('$');
if (dollar != -1) {
return UnresolvedType.forSignature(sig.substring(0, dollar) + ';');
} else {
return this;
}
}
/**
* Returns a UnresolvedType object representing the component type of this array, or
* null if this type does not represent an array type.
*
* @return the component UnresolvedType object, or null.
*/
public UnresolvedType getComponentType() {
if (isArray()) {
return forSignature(signature.substring(1));
} else {
return null;
}
}
/**
* Returns a java language string representation of this type.
*/
public String toString() {
return getName(); // + " - " + getKind();
}
public String toDebugString() {
return getName();
}
// ---- requires worlds
/**
* Returns a resolved version of this type according to a particular world.
*
* @param world thie {@link World} within which to resolve.
* @return a resolved type representing this type in the appropriate world.
*/
public ResolvedType resolve(World world) {
return world.resolve(this);
}
// ---- helpers
private static String signatureToName(String signature) {
switch (signature.charAt(0)) {
case 'B': return "byte";
case 'C': return "char";
case 'D': return "double";
case 'F': return "float";
case 'I': return "int";
case 'J': return "long";
case 'L':
String name = signature.substring(1, signature.length() - 1).replace('/', '.');
return name;
case 'T':
StringBuffer nameBuff2 = new StringBuffer();
int colon = signature.indexOf(";");
String tvarName = signature.substring(1,colon);
nameBuff2.append(tvarName);
return nameBuff2.toString();
case 'P': // it's one of our parameterized type sigs
StringBuffer nameBuff = new StringBuffer();
// signature for parameterized types is e.g.
// List<String> -> Ljava/util/List<Ljava/lang/String;>;
// Map<String,List<Integer>> -> Ljava/util/Map<java/lang/String;Ljava/util/List<Ljava/lang/Integer;>;>;
int paramNestLevel = 0;
for (int i = 1 ; i < signature.length(); i++) {
char c = signature.charAt(i);
switch (c) {
case '/' : nameBuff.append('.'); break;
case '<' :
nameBuff.append("<");
paramNestLevel++;
StringBuffer innerBuff = new StringBuffer();
while(paramNestLevel > 0) {
c = signature.charAt(++i);
if (c == '<') paramNestLevel++;
if (c == '>') paramNestLevel--;
if (paramNestLevel > 0) innerBuff.append(c);
if (c == ';' && paramNestLevel == 1) {
nameBuff.append(signatureToName(innerBuff.toString()));
if (signature.charAt(i+1) != '>') nameBuff.append(',');
innerBuff = new StringBuffer();
}
}
nameBuff.append(">");
break;
case ';' : break;
default:
nameBuff.append(c);
}
}
return nameBuff.toString();
case 'S': return "short";
case 'V': return "void";
case 'Z': return "boolean";
case '[':
return signatureToName(signature.substring(1, signature.length())) + "[]";
// case '<':
// // its a generic!
// if (signature.charAt(1)=='>') return signatureToName(signature.substring(2));
case '+' : return "? extends " + signatureToName(signature.substring(1, signature.length()));
case '-' : return "? super " + signatureToName(signature.substring(1, signature.length()));
case '?' : return "?";
default:
throw new BCException("Bad type signature: " + signature);
}
}
private static String nameToSignature(String name) {
if (name.equals("byte")) return "B";
if (name.equals("char")) return "C";
if (name.equals("double")) return "D";
if (name.equals("float")) return "F";
if (name.equals("int")) return "I";
if (name.equals("long")) return "J";
if (name.equals("short")) return "S";
if (name.equals("boolean")) return "Z";
if (name.equals("void")) return "V";
if (name.equals("?")) return name;
if (name.endsWith("[]"))
return "[" + nameToSignature(name.substring(0, name.length() - 2));
if (name.length() != 0) {
// lots more tests could be made here...
// check if someone is calling us with something that is a signature already
if (name.charAt(0)=='[') {
throw new BCException("Do not call nameToSignature with something that looks like a signature (descriptor): '"+name+"'");
}
if (name.indexOf("<") == -1) {
// not parameterised
return "L" + name.replace('.', '/') + ";";
} else {
StringBuffer nameBuff = new StringBuffer();
int nestLevel = 0;
nameBuff.append("P");
for (int i = 0; i < name.length(); i++) {
char c = name.charAt(i);
switch (c) {
case '.' : nameBuff.append('/'); break;
case '<' :
nameBuff.append("<");
nestLevel++;
StringBuffer innerBuff = new StringBuffer();
while(nestLevel > 0) {
c = name.charAt(++i);
if (c == '<') nestLevel++;
if (c == '>') nestLevel--;
if (c == ',' && nestLevel == 1) {
nameBuff.append(nameToSignature(innerBuff.toString()));
innerBuff = new StringBuffer();
} else {
if (nestLevel > 0) innerBuff.append(c);
}
}
nameBuff.append(nameToSignature(innerBuff.toString()));
nameBuff.append('>');
break;
case '>' :
throw new IllegalStateException("Should by matched by <");
case ',' :
throw new IllegalStateException("Should only happen inside <...>");
default: nameBuff.append(c);
}
}
nameBuff.append(";");
return nameBuff.toString();
}
}
else
throw new BCException("Bad type name: " + name);
}
public void write(DataOutputStream s) throws IOException {
s.writeUTF(getSignature());
}
public static UnresolvedType read(DataInputStream s) throws IOException {
String sig = s.readUTF();
if (sig.equals(MISSING_NAME)) {
return ResolvedType.MISSING;
} else {
UnresolvedType ret = UnresolvedType.forSignature(sig);
return ret;
}
}
public static void writeArray(UnresolvedType[] types, DataOutputStream s) throws IOException {
int len = types.length;
s.writeShort(len);
for (int i=0; i < len; i++) {
types[i].write(s);
}
}
public static UnresolvedType[] readArray(DataInputStream s) throws IOException {
int len = s.readShort();
if (len==0) return UnresolvedType.NONE;
UnresolvedType[] types = new UnresolvedType[len];
for (int i=0; i < len; i++) {
types[i] = UnresolvedType.read(s);
}
return types;
}
public String getNameAsIdentifier() {
return getName().replace('.', '_');
}
public String getPackageNameAsIdentifier() {
String name = getName();
int index = name.lastIndexOf('.');
if (index == -1) {
return "";
} else {
return name.substring(0, index).replace('.', '_');
}
}
public String getPackageName() {
String name = getName();
if (name.indexOf("<")!=-1) {
name = name.substring(0,name.indexOf("<"));
}
int index = name.lastIndexOf('.');
if (index == -1) {
return null;
} else {
return name.substring(0, index);
}
}
public UnresolvedType[] getTypeParameters() {
return typeParameters == null ? new UnresolvedType[0] : typeParameters;
}
/**
* Doesn't include the package
*/
public String getClassName() {
String name = getName();
int index = name.lastIndexOf('.');
if (index == -1) {
return name;
} else {
return name.substring(index+1);
}
}
public TypeVariable[] getTypeVariables() {
return typeVariables;
}
public static class TypeKind {
// Note: It is not sufficient to say that a parameterized type with no type parameters in fact
// represents a raw type - a parameterized type with no type parameters can represent
// an inner type of a parameterized type that specifies no type parameters of its own.
public final static TypeKind PRIMITIVE = new TypeKind("primitive");
public final static TypeKind SIMPLE = new TypeKind("simple"); // a type with NO type parameters/vars
public final static TypeKind RAW = new TypeKind("raw"); // the erasure of a generic type
public final static TypeKind GENERIC = new TypeKind("generic"); // a generic type
public final static TypeKind PARAMETERIZED= new TypeKind("parameterized"); // a parameterized type
public final static TypeKind TYPE_VARIABLE= new TypeKind("type_variable"); // a type variable
public final static TypeKind WILDCARD = new TypeKind("wildcard"); // a generic wildcard type
public String toString() {
return type;
}
private TypeKind(String type) {
this.type = type;
}
private final String type;
}
/**
* Will return true if the type being represented is parameterized with a type variable
* from a generic method/ctor rather than a type variable from a generic type.
* Only subclasses know the answer...
*/
public boolean isParameterizedWithAMemberTypeVariable() {
throw new RuntimeException("I dont know - you should ask a resolved version of me: "+this);
}
public TypeVariable getTypeVariableNamed(String name) {
TypeVariable[] vars = getTypeVariables();
if (vars==null || vars.length==0) return null;
for (int i = 0; i < vars.length; i++) {
TypeVariable aVar = vars[i];
if (aVar.getName().equals(name)) return aVar;
}
return null;
}
}
|
150,671 |
Bug 150671 declare error on set of volatile field does not work
|
When an aspect has a declare error statement involving a pointcut that captures the setting of a volatile field, a compilation error is not produced. This bug can be reproduced as follows. Consider the following class: class A { private volatile int state; public void foo() { state = 0; } } Now consider this aspect: aspect FSM { declare error: set(* A.state): "Changing state"; } The setting of the state field in method foo() does not result in a compilation error as expected. I originally noticed this bug when using AJDT 1.4 with Eclipse 3.2. However this has been reproduced and confirmed with the aspectj 1.5.2 compiler.
|
resolved fixed
|
357bbe9
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-07-25T07:46:13Z | 2006-07-14T15:13:20Z |
tests/src/org/aspectj/systemtest/ajc153/Ajc153Tests.java
|
/*******************************************************************************
* Copyright (c) 2006 IBM
* 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.ajc153;
import java.io.File;
import junit.framework.Test;
import org.aspectj.testing.Utils;
import org.aspectj.testing.XMLBasedAjcTestCase;
public class Ajc153Tests extends org.aspectj.testing.XMLBasedAjcTestCase {
public void testMissingLineNumbersInStacktraceBefore_pr145442() { runTest("missing line numbers in stacktrace before");}
public void testMissingLineNumbersInStacktraceAfter_pr145442() { runTest("missing line numbers in stacktrace after");}
public void testMissingLineNumbersInStacktraceAround_pr145442() { runTest("missing line numbers in stacktrace around");}
// public void testArgnamesAndJavac_pr148381() { runTest("argNames and javac");}
// public void testCFlowXMLAspectLTW_pr149096() { runTest("cflow xml concrete aspect"); }
// public void testAmbiguousBinding_pr121805() { runTest("ambiguous binding");}
public void testGenericInheritanceDecp_pr150095() { runTest("generics, inheritance and decp");}
public void testIllegalStateException_pr148737() { runTest("illegalstateexception for non generic type");}
public void testAtajInheritance_pr149305_1() { runTest("ataj inheritance - 1");}
public void testAtajInheritance_pr149305_2() { runTest("ataj inheritance - 2");}
public void testAtajInheritance_pr149305_3() { runTest("ataj inheritance - 3");}
public void testVerificationFailureForAspectOf_pr148693() {
runTest("verification problem"); // build the code
Utils.verifyClass(ajc,"mypackage.MyAspect"); // verify it <<< BRAND NEW VERIFY UTILITY FOR EVERYONE TO TRY ;)
}
public void testIncorrectAnnotationValue_pr148537() { runTest("incorrect annotation value");}
public void testVerifyErrNoTypeCflowField_pr145693_1() { runTest("verifyErrNoTypeCflowField"); }
public void testVerifyErrInpathNoTypeCflowField_pr145693_2() { runTest("verifyErrInpathNoTypeCflowField"); }
public void testCpathNoTypeCflowField_pr145693_3() { runTest("cpathNoTypeCflowField"); }
// public void testVisibilityProblem_pr149071() { runTest("visibility problem");}
// public void testAdviceNotWovenAspectPath_pr147841() { runTest("advice not woven on aspectpath");}
public void testGenericSignatures_pr148409() { runTest("generic signature problem"); }
// public void testBrokenIfArgsCflowAtAj_pr145018() { runTest("ataj crashing with cflow, if and args");}
public void testCantFindType_pr149322_01() {runTest("can't find type on interface call 1");}
public void testCantFindType_pr149322_02() {runTest("can't find type on interface call 2");}
public void testCantFindType_pr149322_03() {runTest("can't find type on interface call 3");}
/////////////////////////////////////////
public static Test suite() {
return XMLBasedAjcTestCase.loadSuite(Ajc153Tests.class);
}
protected File getSpecFile() {
return new File("../tests/src/org/aspectj/systemtest/ajc153/ajc153.xml");
}
}
|
150,671 |
Bug 150671 declare error on set of volatile field does not work
|
When an aspect has a declare error statement involving a pointcut that captures the setting of a volatile field, a compilation error is not produced. This bug can be reproduced as follows. Consider the following class: class A { private volatile int state; public void foo() { state = 0; } } Now consider this aspect: aspect FSM { declare error: set(* A.state): "Changing state"; } The setting of the state field in method foo() does not result in a compilation error as expected. I originally noticed this bug when using AJDT 1.4 with Eclipse 3.2. However this has been reproduced and confirmed with the aspectj 1.5.2 compiler.
|
resolved fixed
|
357bbe9
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-07-25T07:46:13Z | 2006-07-14T15:13:20Z |
weaver/src/org/aspectj/weaver/ResolvedMemberImpl.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.DataOutputStream;
import java.io.IOException;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.aspectj.bridge.ISourceLocation;
/**
* This is the declared member, i.e. it will always correspond to an
* actual method/... declaration
*/
public class ResolvedMemberImpl extends MemberImpl implements IHasPosition, AnnotatedElement, TypeVariableDeclaringElement, ResolvedMember {
private String[] parameterNames = null;
protected UnresolvedType[] checkedExceptions = UnresolvedType.NONE;
/**
* if this member is a parameterized version of a member in a generic type,
* then this field holds a reference to the member we parameterize.
*/
protected ResolvedMember backingGenericMember = null;
protected Set annotationTypes = null;
// Some members are 'created' to represent other things (for example ITDs). These
// members have their annotations stored elsewhere, and this flag indicates that is
// the case. It is up to the caller to work out where that is!
// Once determined the caller may choose to stash the annotations in this member...
private boolean isAnnotatedElsewhere = false; // this field is not serialized.
private boolean isAjSynthetic = false;
// generic methods have type variables
protected TypeVariable[] typeVariables;
// these three fields hold the source location of this member
protected int start, end;
protected ISourceContext sourceContext = null;
//XXX deprecate this in favor of the constructor below
public ResolvedMemberImpl(
Kind kind,
UnresolvedType declaringType,
int modifiers,
UnresolvedType returnType,
String name,
UnresolvedType[] parameterTypes)
{
super(kind, declaringType, modifiers, returnType, name, parameterTypes);
}
public ResolvedMemberImpl(
Kind kind,
UnresolvedType declaringType,
int modifiers,
UnresolvedType returnType,
String name,
UnresolvedType[] parameterTypes,
UnresolvedType[] checkedExceptions)
{
super(kind, declaringType, modifiers, returnType, name, parameterTypes);
this.checkedExceptions = checkedExceptions;
}
public ResolvedMemberImpl(
Kind kind,
UnresolvedType declaringType,
int modifiers,
UnresolvedType returnType,
String name,
UnresolvedType[] parameterTypes,
UnresolvedType[] checkedExceptions,
ResolvedMember backingGenericMember)
{
this(kind, declaringType, modifiers, returnType, name, parameterTypes,checkedExceptions);
this.backingGenericMember = backingGenericMember;
this.isAjSynthetic = backingGenericMember.isAjSynthetic();
}
public ResolvedMemberImpl(
Kind kind,
UnresolvedType declaringType,
int modifiers,
String name,
String signature)
{
super(kind, declaringType, modifiers, name, signature);
}
/**
* Compute the full set of signatures for a member. This walks up the hierarchy
* giving the ResolvedMember in each defining type in the hierarchy. A shadowMember
* can be created with a target type (declaring type) that does not actually define
* the member. This is ok as long as the member is inherited in the declaring type.
* Each declaring type in the line to the actual declaring type is added as an additional
* signature. For example:
*
* class A { void foo(); }
* class B extends A {}
*
* shadowMember : void B.foo()
*
* gives { void B.foo(), void A.foo() }
* @param joinPointSignature
* @param inAWorld
*/
public static JoinPointSignature[] getJoinPointSignatures(Member joinPointSignature, World inAWorld) {
// Walk up hierarchy creating one member for each type up to and including the
// first defining type
ResolvedType originalDeclaringType = joinPointSignature.getDeclaringType().resolve(inAWorld);
ResolvedMemberImpl firstDefiningMember = (ResolvedMemberImpl) joinPointSignature.resolve(inAWorld);
if (firstDefiningMember == null) {
return new JoinPointSignature[0];
}
// declaringType can be unresolved if we matched a synthetic member generated by Aj...
// should be fixed elsewhere but add this resolve call on the end for now so that we can
// focus on one problem at a time...
ResolvedType firstDefiningType = firstDefiningMember.getDeclaringType().resolve(inAWorld);
if (firstDefiningType != originalDeclaringType) {
if (joinPointSignature.getKind() == Member.CONSTRUCTOR) {
return new JoinPointSignature[0];
}
// else if (shadowMember.isStatic()) {
// return new ResolvedMember[] {firstDefiningMember};
// }
}
List declaringTypes = new ArrayList();
accumulateTypesInBetween(originalDeclaringType,
firstDefiningType,
declaringTypes);
Set memberSignatures = new HashSet();
for (Iterator iter = declaringTypes.iterator(); iter.hasNext();) {
ResolvedType declaringType = (ResolvedType) iter.next();
ResolvedMember member = firstDefiningMember.withSubstituteDeclaringType(declaringType);
memberSignatures.add(member);
}
if (shouldWalkUpHierarchyFor(firstDefiningMember)) {
// now walk up the hierarchy from the firstDefiningMember and include the signature for
// every type between the firstDefiningMember and the root defining member.
Iterator superTypeIterator = firstDefiningType.getDirectSupertypes();
List typesAlreadyVisited = new ArrayList();
accumulateMembersMatching(firstDefiningMember,superTypeIterator,typesAlreadyVisited,memberSignatures);
}
JoinPointSignature[] ret = new JoinPointSignature[memberSignatures.size()];
memberSignatures.toArray(ret);
return ret;
}
private static boolean shouldWalkUpHierarchyFor(Member aMember) {
if (aMember.getKind() == Member.CONSTRUCTOR) return false;
if (aMember.getKind() == Member.FIELD) return false;
if (aMember.isStatic()) return false;
return true;
}
/**
* Build a list containing every type between subtype and supertype, inclusively.
*/
private static void accumulateTypesInBetween(ResolvedType subType, ResolvedType superType, List types) {
types.add(subType);
if (subType == superType) {
return;
} else {
for (Iterator iter = subType.getDirectSupertypes(); iter.hasNext();) {
ResolvedType parent = (ResolvedType) iter.next();
if (superType.isAssignableFrom(parent)) {
accumulateTypesInBetween(parent, superType,types);
}
}
}
}
/**
* We have a resolved member, possibly with type parameter references as parameters or return
* type. We need to find all its ancestor members. When doing this, a type parameter matches
* regardless of bounds (bounds can be narrowed down the hierarchy).
*/
private static void accumulateMembersMatching(
ResolvedMemberImpl memberToMatch,
Iterator typesToLookIn,
List typesAlreadyVisited,
Set foundMembers) {
while(typesToLookIn.hasNext()) {
ResolvedType toLookIn = (ResolvedType) typesToLookIn.next();
if (!typesAlreadyVisited.contains(toLookIn)) {
typesAlreadyVisited.add(toLookIn);
ResolvedMemberImpl foundMember = (ResolvedMemberImpl) toLookIn.lookupResolvedMember(memberToMatch,true);
if (foundMember != null && isVisibleTo(memberToMatch,foundMember)) {
List declaringTypes = new ArrayList();
// declaring type can be unresolved if the member can from an ITD...
ResolvedType resolvedDeclaringType = foundMember.getDeclaringType().resolve(toLookIn.getWorld());
accumulateTypesInBetween(toLookIn, resolvedDeclaringType, declaringTypes);
for (Iterator iter = declaringTypes.iterator(); iter.hasNext();) {
ResolvedType declaringType = (ResolvedType) iter.next();
// typesAlreadyVisited.add(declaringType);
ResolvedMember member = foundMember.withSubstituteDeclaringType(declaringType);
foundMembers.add(member);
}
if (toLookIn.isParameterizedType() && (foundMember.backingGenericMember != null)) {
foundMembers.add(new JoinPointSignature(foundMember.backingGenericMember,foundMember.declaringType.resolve(toLookIn.getWorld())));
}
accumulateMembersMatching(foundMember,toLookIn.getDirectSupertypes(),typesAlreadyVisited,foundMembers);
// if this was a parameterized type, look in the generic type that backs it too
}
}
}
}
/**
* Returns true if the parent member is visible to the child member
* In the same declaring type this is always true, otherwise if parent is private
* it is false.
* @param childMember
* @param parentMember
* @return
*/
private static boolean isVisibleTo(ResolvedMember childMember, ResolvedMember parentMember) {
if (childMember.getDeclaringType().equals(parentMember.getDeclaringType())) return true;
if (Modifier.isPrivate(parentMember.getModifiers())) {
return false;
} else {
return true;
}
}
// ----
public final int getModifiers(World world) {
return modifiers;
}
public final int getModifiers() {
return modifiers;
}
// ----
public final UnresolvedType[] getExceptions(World world) {
return getExceptions();
}
public UnresolvedType[] getExceptions() {
return checkedExceptions;
}
public ShadowMunger getAssociatedShadowMunger() {
return null;
}
// ??? true or false?
public boolean isAjSynthetic() {
return isAjSynthetic;
}
protected void setAjSynthetic(boolean b) {isAjSynthetic= b;}
public boolean hasAnnotations() {
return (annotationTypes!=null);
}
public boolean hasAnnotation(UnresolvedType ofType) {
// The ctors don't allow annotations to be specified ... yet - but
// that doesn't mean it is an error to call this method.
// Normally the weaver will be working with subtypes of
// this type - BcelField/BcelMethod
if (annotationTypes==null) return false;
return annotationTypes.contains(ofType);
}
public ResolvedType[] getAnnotationTypes() {
// The ctors don't allow annotations to be specified ... yet - but
// that doesn't mean it is an error to call this method.
// Normally the weaver will be working with subtypes of
// this type - BcelField/BcelMethod
if (annotationTypes == null) return null;
return (ResolvedType[])annotationTypes.toArray(new ResolvedType[]{});
}
public AnnotationX[] getAnnotations() {
if (backingGenericMember != null) return backingGenericMember.getAnnotations();
return super.getAnnotations();
}
public void setAnnotationTypes(UnresolvedType[] annotationtypes) {
if (annotationTypes == null) annotationTypes = new HashSet();
for (int i = 0; i < annotationtypes.length; i++) {
UnresolvedType typeX = annotationtypes[i];
annotationTypes.add(typeX);
}
}
public void addAnnotation(AnnotationX annotation) {
// FIXME asc only allows for annotation types, not instances - should it?
if (annotationTypes == null) annotationTypes = new HashSet();
annotationTypes.add(annotation.getSignature());
}
public boolean isBridgeMethod() {
return (modifiers & Constants.ACC_BRIDGE)!=0;
}
public boolean isVarargsMethod() {
return (modifiers & Constants.ACC_VARARGS)!=0;
}
public void setVarargsMethod() {
modifiers = modifiers | Constants.ACC_VARARGS;
}
public boolean isSynthetic() {
// See Bcelmethod.isSynthetic() which takes account of preJava5 Synthetic modifier
return (modifiers & 4096)!=0; // do we know better?
}
public void write(DataOutputStream s) throws IOException {
getKind().write(s);
getDeclaringType().write(s);
s.writeInt(modifiers);
s.writeUTF(getName());
s.writeUTF(getSignature());
UnresolvedType.writeArray(getExceptions(), s);
s.writeInt(getStart());
s.writeInt(getEnd());
s.writeBoolean(isVarargsMethod());
// Write out any type variables...
if (typeVariables==null) {
s.writeInt(0);
} else {
s.writeInt(typeVariables.length);
for (int i = 0; i < typeVariables.length; i++) {
typeVariables[i].write(s);
}
}
String gsig = getGenericSignature();
if (getSignature().equals(gsig)) {
s.writeBoolean(false);
} else {
s.writeBoolean(true);
s.writeInt(parameterTypes.length);
for (int i = 0; i < parameterTypes.length; i++) {
UnresolvedType array_element = parameterTypes[i];
array_element.write(s);
}
returnType.write(s);
}
}
public String getGenericSignature() {
StringBuffer sb = new StringBuffer();
if (typeVariables!=null) {
sb.append("<");
for (int i = 0; i < typeVariables.length; i++) {
sb.append(typeVariables[i].getSignature());
}
sb.append(">");
}
sb.append("(");
for (int i = 0; i < parameterTypes.length; i++) {
UnresolvedType array_element = parameterTypes[i];
sb.append(array_element.getSignature());
}
sb.append(")");
sb.append(returnType.getSignature());
return sb.toString();
}
public static void writeArray(ResolvedMember[] members, DataOutputStream s) throws IOException {
s.writeInt(members.length);
for (int i = 0, len = members.length; i < len; i++) {
members[i].write(s);
}
}
public static ResolvedMemberImpl readResolvedMember(VersionedDataInputStream s, ISourceContext sourceContext) throws IOException {
ResolvedMemberImpl m = new ResolvedMemberImpl(Kind.read(s), UnresolvedType.read(s), s.readInt(),
s.readUTF(), s.readUTF());
m.checkedExceptions = UnresolvedType.readArray(s);
m.start = s.readInt();
m.end = s.readInt();
m.sourceContext = sourceContext;
if (s.getMajorVersion()>=AjAttribute.WeaverVersionInfo.WEAVER_VERSION_MAJOR_AJ150) {
if (s.getMajorVersion()>=AjAttribute.WeaverVersionInfo.WEAVER_VERSION_MAJOR_AJ150M4) {
boolean isvarargs = s.readBoolean();
if (isvarargs) m.setVarargsMethod();
}
int tvcount = s.readInt();
if (tvcount!=0) {
m.typeVariables = new TypeVariable[tvcount];
for (int i=0;i<tvcount;i++) {
m.typeVariables[i]=TypeVariable.read(s);
m.typeVariables[i].setDeclaringElement(m);
}
}
if (s.getMajorVersion()>=AjAttribute.WeaverVersionInfo.WEAVER_VERSION_MAJOR_AJ150M4) {
boolean hasAGenericSignature = s.readBoolean();
if (hasAGenericSignature) {
int ps = s.readInt();
UnresolvedType[] params = new UnresolvedType[ps];
for (int i = 0; i < params.length; i++) {
UnresolvedType type = params[i];
params[i]=TypeFactory.createTypeFromSignature(s.readUTF());
}
UnresolvedType rt = TypeFactory.createTypeFromSignature(s.readUTF());
m.parameterTypes = params;
m.returnType = rt;
}
}
}
return m;
}
public static ResolvedMember[] readResolvedMemberArray(VersionedDataInputStream s, ISourceContext context) throws IOException {
int len = s.readInt();
ResolvedMember[] members = new ResolvedMember[len];
for (int i=0; i < len; i++) {
members[i] = ResolvedMemberImpl.readResolvedMember(s, context);
}
return members;
}
public ResolvedMember resolve(World world) {
// make sure all the pieces of a resolvedmember really are resolved
try {
if (typeVariables!=null && typeVariables.length>0) {
for (int i = 0; i < typeVariables.length; i++) {
typeVariables[i] = typeVariables[i].resolve(world);
}
}
world.setTypeVariableLookupScope(this);
if (annotationTypes!=null) {
Set r = new HashSet();
for (Iterator iter = annotationTypes.iterator(); iter.hasNext();) {
UnresolvedType element = (UnresolvedType) iter.next();
r.add(world.resolve(element));
}
annotationTypes = r;
}
declaringType = declaringType.resolve(world);
if (declaringType.isRawType()) declaringType = ((ReferenceType)declaringType).getGenericType();
if (parameterTypes!=null && parameterTypes.length>0) {
for (int i = 0; i < parameterTypes.length; i++) {
parameterTypes[i] = parameterTypes[i].resolve(world);
}
}
returnType = returnType.resolve(world);
} finally {
world.setTypeVariableLookupScope(null);
}
return this;
}
public ISourceContext getSourceContext(World world) {
return getDeclaringType().resolve(world).getSourceContext();
}
public String[] getParameterNames() {
return parameterNames;
}
public final void setParameterNames(String[] pnames) {
parameterNames = pnames;
}
public final String[] getParameterNames(World world) {
return getParameterNames();
}
public AjAttribute.EffectiveSignatureAttribute getEffectiveSignature() {
return null;
}
public ISourceLocation getSourceLocation() {
//System.out.println("get context: " + this + " is " + sourceContext);
if (getSourceContext() == null) {
//System.err.println("no context: " + this);
return null;
}
return getSourceContext().makeSourceLocation(this);
}
public int getEnd() {
return end;
}
public ISourceContext getSourceContext() {
return sourceContext;
}
public int getStart() {
return start;
}
public void setPosition(int sourceStart, int sourceEnd) {
this.start = sourceStart;
this.end = sourceEnd;
}
public void setDeclaringType(ReferenceType rt) {
declaringType = rt;
}
public void setSourceContext(ISourceContext sourceContext) {
this.sourceContext = sourceContext;
}
public boolean isAbstract() {
return Modifier.isAbstract(modifiers);
}
public boolean isPublic() {
return Modifier.isPublic(modifiers);
}
public boolean isProtected() {
return Modifier.isProtected(modifiers);
}
public boolean isNative() {
return Modifier.isNative(modifiers);
}
public boolean isDefault() {
return !(isPublic() || isProtected() || isPrivate());
}
public boolean isVisible(ResolvedType fromType) {
World world = fromType.getWorld();
return ResolvedType.isVisible(getModifiers(), getDeclaringType().resolve(world),
fromType);
}
public void setCheckedExceptions(UnresolvedType[] checkedExceptions) {
this.checkedExceptions = checkedExceptions;
}
public void setAnnotatedElsewhere(boolean b) {
isAnnotatedElsewhere = b;
}
public boolean isAnnotatedElsewhere() {
return isAnnotatedElsewhere;
}
/**
* Get the UnresolvedType for the return type, taking generic signature into account
*/
public UnresolvedType getGenericReturnType() {
return getReturnType();
}
/**
* Get the TypeXs of the parameter types, taking generic signature into account
*/
public UnresolvedType[] getGenericParameterTypes() {
return getParameterTypes();
}
public ResolvedMemberImpl parameterizedWith(UnresolvedType[] typeParameters,ResolvedType newDeclaringType, boolean isParameterized) {
return parameterizedWith(typeParameters,newDeclaringType,isParameterized,null);
}
/**
* Return a resolvedmember in which all the type variables in the signature
* have been replaced with the given bindings.
* The 'isParameterized' flag tells us whether we are creating a raw type
* version or not. if (isParameterized) then List<T> will turn into
* List<String> (for example) - if (!isParameterized) then List<T> will turn
* into List.
*/
public ResolvedMemberImpl parameterizedWith(UnresolvedType[] typeParameters,ResolvedType newDeclaringType, boolean isParameterized,List aliases) {
if (//isParameterized && <-- might need this bit...
!getDeclaringType().isGenericType()) {
throw new IllegalStateException("Can't ask to parameterize a member of non-generic type: "+getDeclaringType()+" kind("+getDeclaringType().typeKind+")");
}
TypeVariable[] typeVariables = getDeclaringType().getTypeVariables();
if (isParameterized && (typeVariables.length != typeParameters.length)) {
throw new IllegalStateException("Wrong number of type parameters supplied");
}
Map typeMap = new HashMap();
boolean typeParametersSupplied = typeParameters!=null && typeParameters.length>0;
if (typeVariables!=null) {
// If no 'replacements' were supplied in the typeParameters array then collapse
// type variables to their first bound.
for (int i = 0; i < typeVariables.length; i++) {
UnresolvedType ut = (!typeParametersSupplied?typeVariables[i].getFirstBound():typeParameters[i]);
typeMap.put(typeVariables[i].getName(),ut);
}
}
// For ITDs on generic types that use type variables from the target type, the aliases
// record the alternative names used throughout the ITD expression that must map to
// the same value as the type variables real name.
if (aliases!=null) {
int posn = 0;
for (Iterator iter = aliases.iterator(); iter.hasNext();) {
String typeVariableAlias = (String) iter.next();
typeMap.put(typeVariableAlias,(!typeParametersSupplied?typeVariables[posn].getFirstBound():typeParameters[posn]));
posn++;
}
}
UnresolvedType parameterizedReturnType = parameterize(getGenericReturnType(),typeMap,isParameterized);
UnresolvedType[] parameterizedParameterTypes = new UnresolvedType[getGenericParameterTypes().length];
for (int i = 0; i < parameterizedParameterTypes.length; i++) {
parameterizedParameterTypes[i] =
parameterize(getGenericParameterTypes()[i], typeMap,isParameterized);
}
ResolvedMemberImpl ret = new ResolvedMemberImpl(
getKind(),
newDeclaringType,
getModifiers(),
parameterizedReturnType,
getName(),
parameterizedParameterTypes,
getExceptions(),
this
);
ret.setTypeVariables(getTypeVariables());
ret.setSourceContext(getSourceContext());
ret.setPosition(getStart(),getEnd());
ret.setParameterNames(getParameterNames());
return ret;
}
public void setTypeVariables(TypeVariable[] tvars) {
typeVariables = tvars;
}
public TypeVariable[] getTypeVariables() {
return typeVariables;
}
protected UnresolvedType parameterize(UnresolvedType aType, Map typeVariableMap, boolean inParameterizedType) {
if (aType instanceof TypeVariableReference) {
String variableName = ((TypeVariableReference)aType).getTypeVariable().getName();
if (!typeVariableMap.containsKey(variableName)) {
return aType; // if the type variable comes from the method (and not the type) thats OK
}
return (UnresolvedType) typeVariableMap.get(variableName);
} else if (aType.isParameterizedType()) {
if (inParameterizedType) {
return aType.parameterize(typeVariableMap);
} else {
return aType.getRawType();
}
} else if (aType.isArray()) {
// The component type might be a type variable (pr150095)
int dims = 1;
String sig = aType.getSignature();
while (sig.charAt(dims)=='[') dims++;
UnresolvedType componentSig = UnresolvedType.forSignature(sig.substring(dims));
UnresolvedType arrayType = ResolvedType.makeArray(parameterize(componentSig,typeVariableMap,inParameterizedType),dims);
return arrayType;
}
return aType;
}
/**
* If this member is defined by a parameterized super-type, return the erasure
* of that member.
* For example:
* interface I<T> { T foo(T aTea); }
* class C implements I<String> {
* String foo(String aString) { return "something"; }
* }
* The resolved member for C.foo has signature String foo(String). The
* erasure of that member is Object foo(Object) -- use upper bound of type
* variable.
* A type is a supertype of itself.
*/
public ResolvedMember getErasure() {
if (calculatedMyErasure) return myErasure;
calculatedMyErasure = true;
ResolvedType resolvedDeclaringType = (ResolvedType) getDeclaringType();
// this next test is fast, and the result is cached.
if (!resolvedDeclaringType.hasParameterizedSuperType()) {
return null;
} else {
// we have one or more parameterized super types.
// this member may be defined by one of them... we need to find out.
Collection declaringTypes = this.getDeclaringTypes(resolvedDeclaringType.getWorld());
for (Iterator iter = declaringTypes.iterator(); iter.hasNext();) {
ResolvedType aDeclaringType = (ResolvedType) iter.next();
if (aDeclaringType.isParameterizedType()) {
// we've found the (a?) parameterized type that defines this member.
// now get the erasure of it
ResolvedMemberImpl matchingMember = (ResolvedMemberImpl) aDeclaringType.lookupMemberNoSupers(this);
if (matchingMember != null && matchingMember.backingGenericMember != null) {
myErasure = matchingMember.backingGenericMember;
return myErasure;
}
}
}
}
return null;
}
private ResolvedMember myErasure = null;
private boolean calculatedMyErasure = false;
public boolean hasBackingGenericMember() {
return backingGenericMember!=null;
}
public ResolvedMember getBackingGenericMember() {
return backingGenericMember;
}
/**
* For ITDs, we use the default factory methods to build a resolved member, then alter a couple of characteristics
* using this method - this is safe.
*/
public void resetName(String newName) {this.name = newName;}
public void resetKind(Kind newKind) {this.kind=newKind; }
public void resetModifiers(int newModifiers) {this.modifiers=newModifiers;}
public void resetReturnTypeToObjectArray() {
returnType = UnresolvedType.OBJECTARRAY;
}
/**
* Returns a copy of this member but with the declaring type swapped.
* Copy only needs to be shallow.
* @param newDeclaringType
*/
public JoinPointSignature withSubstituteDeclaringType(ResolvedType newDeclaringType) {
JoinPointSignature ret = new JoinPointSignature(this,newDeclaringType);
return ret;
}
/**
* Returns true if this member matches the other. The matching takes into account
* name and parameter types only. When comparing parameter types, we allow any type
* variable to match any other type variable regardless of bounds.
*/
public boolean matches(ResolvedMember aCandidateMatch) {
ResolvedMemberImpl candidateMatchImpl = (ResolvedMemberImpl)aCandidateMatch;
if (!getName().equals(aCandidateMatch.getName())) return false;
UnresolvedType[] myParameterTypes = getGenericParameterTypes();
UnresolvedType[] candidateParameterTypes = aCandidateMatch.getGenericParameterTypes();
if (myParameterTypes.length != candidateParameterTypes.length) return false;
String myParameterSignature = getParameterSigWithBoundsRemoved();
String candidateParameterSignature = candidateMatchImpl.getParameterSigWithBoundsRemoved();
if (myParameterSignature.equals(candidateParameterSignature)) {
return true;
} else {
// try erasure
myParameterSignature = getParameterSigErasure();
candidateParameterSignature = candidateMatchImpl.getParameterSigErasure();
return myParameterSignature.equals(candidateParameterSignature);
}
}
/** converts e.g. <T extends Number>.... List<T> to just Ljava/util/List<T;>;
* whereas the full signature would be Ljava/util/List<T:Ljava/lang/Number;>;
*/
private String myParameterSignatureWithBoundsRemoved = null;
/**
* converts e.g. <T extends Number>.... List<T> to just Ljava/util/List;
*/
private String myParameterSignatureErasure = null;
// does NOT produce a meaningful java signature, but does give a unique string suitable for
// comparison.
private String getParameterSigWithBoundsRemoved() {
if (myParameterSignatureWithBoundsRemoved != null) return myParameterSignatureWithBoundsRemoved;
StringBuffer sig = new StringBuffer();
UnresolvedType[] myParameterTypes = getGenericParameterTypes();
for (int i = 0; i < myParameterTypes.length; i++) {
appendSigWithTypeVarBoundsRemoved(myParameterTypes[i], sig);
}
myParameterSignatureWithBoundsRemoved = sig.toString();
return myParameterSignatureWithBoundsRemoved;
}
private String getParameterSigErasure() {
if (myParameterSignatureErasure != null) return myParameterSignatureErasure;
StringBuffer sig = new StringBuffer();
UnresolvedType[] myParameterTypes = getParameterTypes();
for (int i = 0; i < myParameterTypes.length; i++) {
UnresolvedType thisParameter = myParameterTypes[i];
if (thisParameter.isTypeVariableReference()) {
sig.append(thisParameter.getUpperBound().getSignature());
} else {
sig.append(thisParameter.getSignature());
}
}
myParameterSignatureErasure = sig.toString();
return myParameterSignatureErasure;
}
// does NOT produce a meaningful java signature, but does give a unique string suitable for
// comparison.
private void appendSigWithTypeVarBoundsRemoved(UnresolvedType aType, StringBuffer toBuffer) {
if (aType.isTypeVariableReference()) {
toBuffer.append("T;");
} else if (aType.isParameterizedType()) {
toBuffer.append(aType.getRawType().getSignature());
toBuffer.append("<");
for (int i = 0; i < aType.getTypeParameters().length; i++) {
appendSigWithTypeVarBoundsRemoved(aType.getTypeParameters()[i], toBuffer);
}
toBuffer.append(">;");
} else {
toBuffer.append(aType.getSignature());
}
}
/**
* Useful for writing tests, returns *everything* we know about this member.
*/
public String toDebugString() {
StringBuffer r = new StringBuffer();
// modifiers
int mods = modifiers;
if ((mods & 4096)>0) mods = mods -4096; // remove synthetic (added in the ASM case but not in the BCEL case...)
if ((mods & 512)>0) mods = mods -512; // remove interface (added in the BCEL case but not in the ASM case...)
if ((mods & 131072)>0) mods = mods -131072; // remove deprecated (added in the ASM case but not in the BCEL case...)
String modsStr = Modifier.toString(mods);
if (modsStr.length()!=0) r.append(modsStr).append("("+mods+")").append(" ");
// type variables
if (typeVariables!=null && typeVariables.length>0) {
r.append("<");
for (int i = 0; i < typeVariables.length; i++) {
if (i>0) r.append(",");
TypeVariable t = typeVariables[i];
r.append(t.toDebugString());
}
r.append("> ");
}
// 'declaring' type
r.append(getGenericReturnType().toDebugString());
r.append(' ');
// name
r.append(declaringType.getName());
r.append('.');
r.append(name);
// parameter signature if a method
if (kind != FIELD) {
r.append("(");
UnresolvedType[] params = getGenericParameterTypes();
boolean parameterNamesExist = showParameterNames && parameterNames!=null && parameterNames.length==params.length;
if (params.length != 0) {
for (int i=0, len = params.length; i < len; i++) {
if (i>0) r.append(", ");
r.append(params[i].toDebugString());
if (parameterNamesExist) r.append(" ").append(parameterNames[i]);
}
}
r.append(")");
}
return r.toString();
}
// SECRETAPI - controlling whether parameter names come out in the debug string (for testing purposes)
public static boolean showParameterNames = true;
public String toGenericString() {
StringBuffer buf = new StringBuffer();
buf.append(getGenericReturnType().getSimpleName());
buf.append(' ');
buf.append(declaringType.getName());
buf.append('.');
buf.append(name);
if (kind != FIELD) {
buf.append("(");
UnresolvedType[] params = getGenericParameterTypes();
if (params.length != 0) {
buf.append(params[0].getSimpleName());
for (int i=1, len = params.length; i < len; i++) {
buf.append(", ");
buf.append(params[i].getSimpleName());
}
}
buf.append(")");
}
return buf.toString();
}
public TypeVariable getTypeVariableNamed(String name) {
// Check locally...
if (typeVariables!=null) {
for (int i = 0; i < typeVariables.length; i++) {
if (typeVariables[i].getName().equals(name)) return typeVariables[i];
}
}
// check the declaring type!
return declaringType.getTypeVariableNamed(name);
// Do generic aspects with ITDs that share type variables with the aspect and the target type and have their own tvars cause this to be messier?
}
public void evictWeavingState() { }
}
|
151,182 |
Bug 151182 NPE in BcelWeaver using LTW
|
Hi, I created a logging aspect for our application some time ago using 1.5.0 of AspectJ. I enabled this from time to time using Load Time Weaving. I have recently recompiled the aspect using 1.5.2 and tried to run it also using the 1.5.2 weaver jar, but it fails with a NullPointerException. This is part of one of the many stacktraces: 20 jul 2006 07:42:49,046 - java.lang.NullPointerException 20 jul 2006 07:42:49,062 - at org.aspectj.weaver.bcel.BcelWeaver.weaveParentTypeMungers(BcelWeaver.java:1367) 20 jul 2006 07:42:49,062 - at org.aspectj.weaver.bcel.BcelWeaver.weaveParentsFor(BcelWeaver.java:1237) 20 jul 2006 07:42:49,062 - at org.aspectj.weaver.bcel.BcelWeaver.weave(BcelWeaver.java:1072) 20 jul 2006 07:42:49,062 - at org.aspectj.weaver.tools.WeavingAdaptor.getWovenBytes(WeavingAdaptor.java:284) 20 jul 2006 07:42:49,062 - at org.aspectj.weaver.tools.WeavingAdaptor.weaveClass(WeavingAdaptor.java:212) 20 jul 2006 07:42:49,062 - at org.aspectj.weaver.loadtime.Aj.preProcess(Aj.java:65) 20 jul 2006 07:42:49,062 - at org.aspectj.weaver.loadtime.ClassPreProcessorAgentAdapter.transform(ClassPreProcessorAgentAdapter.java:55) 20 jul 2006 07:42:49,062 - at sun.instrument.TransformerManager.transform(Unknown Source) 20 jul 2006 07:42:49,062 - at sun.instrument.InstrumentationImpl.transform(Unknown Source) 20 jul 2006 07:42:49,062 - at java.lang.ClassLoader.defineClass1(Native Method) 20 jul 2006 07:42:49,062 - at java.lang.ClassLoader.defineClass(Unknown Source) I then tried with the 1.5.0 weaver jar (although the aspect was compiled using 1.5.2) and this ran without problems.
|
resolved fixed
|
397a19d
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-07-27T09:25:50Z | 2006-07-20T07:20:00Z |
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.util.Map;
import java.util.WeakHashMap;
import org.aspectj.weaver.tools.Trace;
import org.aspectj.weaver.tools.TraceFactory;
import org.aspectj.weaver.tools.WeavingAdaptor;
/**
* 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;
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});
this.weavingContext = context;
if (trace.isTraceEnabled()) trace.exit("<init>");
}
/**
* Initialization
*/
public void initialize() {
;
}
/**
* Weave
*
* @param className
* @param bytes
* @param loader
* @return weaved bytes
*/
public byte[] preProcess(String className, byte[] bytes, ClassLoader loader) {
if (trace.isTraceEnabled()) trace.enter("preProcess",this,new Object[] {className,bytes,loader});
//TODO AV needs to doc that
if (loader == null || className == null) {
// skip boot loader or null classes (hibernate)
if (trace.isTraceEnabled()) trace.exit("preProcess",bytes);
return bytes;
}
try {
WeavingAdaptor weavingAdaptor = WeaverContainer.getWeaver(loader, weavingContext);
if (weavingAdaptor == null) {
if (trace.isTraceEnabled()) trace.exit("preProcess",bytes);
return bytes;
}
return weavingAdaptor.weaveClass(className, bytes);
} catch (Exception t) {
trace.error("preProcess",t);
//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()
t.printStackTrace();
if (trace.isTraceEnabled()) trace.exit("preProcess",bytes);
return bytes;
}
}
/**
* Cache of weaver
* There is one weaver per classloader
*/
static class WeaverContainer {
private static Map weavingAdaptors = new WeakHashMap();
static WeavingAdaptor getWeaver(ClassLoader loader, IWeavingContext weavingContext) {
ExplicitlyInitializedClassLoaderWeavingAdaptor adaptor = null;
synchronized(weavingAdaptors) {
adaptor = (ExplicitlyInitializedClassLoaderWeavingAdaptor) weavingAdaptors.get(loader);
if (adaptor == null) {
String loaderClassName = loader.getClass().getName();
if (loaderClassName.equals("sun.reflect.DelegatingClassLoader")) {
// we don't weave reflection generated types at all!
return null;
} else {
// 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);
weavingAdaptors.put(loader, adaptor);
}
}
}
// perform the initialization
return adaptor.getWeavingAdaptor(loader, weavingContext);
// old version
// synchronized(loader) {//FIXME AV - temp fix for #99861
// synchronized (weavingAdaptors) {
// WeavingAdaptor weavingAdaptor = (WeavingAdaptor) weavingAdaptors.get(loader);
// if (weavingAdaptor == null) {
// weavingAdaptor = new ClassLoaderWeavingAdaptor(loader, weavingContext);
// weavingAdaptors.put(loader, weavingAdaptor);
// }
// return weavingAdaptor;
// }
// }
}
}
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();
}
}
|
151,845 |
Bug 151845 NPE while building
|
Building of a large project fails while weaving. NPE in EclipseSourceContext.removeUnnecessaryProblems(..) The project was just migrated to Eclipse 3.2 Eclipse newly installed with Eclipse SDK and via Update manager with AJDT, CDT, Web/J2EE tools, SubClipse, SpringIDE. Same Project workes in Eclipse 3.1. Simple Test AspectJ-Project workes OK Building with Ant/AspectJ compiler (as external Tools Launch in Eclipse) works. I tried the following, but got the error anyway: - Checked out as a new AspectJ Project - upgraded to the developement Version of AJDT
|
resolved fixed
|
54f7bb4
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-07-27T09:27:55Z | 2006-07-26T13:20:00Z |
org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/core/builder/EclipseSourceContext.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.File;
import org.aspectj.ajdt.internal.compiler.lookup.EclipseSourceLocation;
import org.aspectj.bridge.ISourceLocation;
import org.aspectj.bridge.SourceLocation;
import org.aspectj.org.eclipse.jdt.core.compiler.IProblem;
import org.aspectj.org.eclipse.jdt.internal.compiler.CompilationResult;
import org.aspectj.org.eclipse.jdt.internal.compiler.CompilationResult.ProblemsForRemovalFilter;
import org.aspectj.weaver.IEclipseSourceContext;
import org.aspectj.weaver.IHasPosition;
import org.aspectj.weaver.Member;
public class EclipseSourceContext implements IEclipseSourceContext {
CompilationResult result;
int offset = 0;
public EclipseSourceContext(CompilationResult result) {
this.result = result;
}
public EclipseSourceContext(CompilationResult result, int offset) {
this.result = result;
this.offset = offset;
}
public int getOffset() {
return offset;
}
private File getSourceFile() {
return new File(new String(result.fileName));
}
public ISourceLocation makeSourceLocation(IHasPosition position) {
return new EclipseSourceLocation(result, position.getStart(), position.getEnd());
}
public ISourceLocation makeSourceLocation(int line, int offset) {
SourceLocation sl = new SourceLocation(getSourceFile(), line);
if (offset > 0) {
sl.setOffset(offset);
} else {
// compute the offset
//TODO AV - should we do it lazily?
int[] offsets = result.lineSeparatorPositions;
int likelyOffset = 0;
if (line > 0 && line < offsets.length) {
//1st char of given line is next char after previous end of line
likelyOffset = offsets[line-1];//FIXME may be need -2
}
sl.setOffset(likelyOffset);
}
return sl;
}
public void tidy() {
result=null;
}
public void removeUnnecessaryProblems(Member member, int problemLineNumber) {
if (result == null) return;
IProblem[] probs = result.getProblems();
for (int i = 0; i < probs.length; i++) {
IProblem problem = probs[i];
if (problem == null) continue;
if (problem.getID() == IProblem.UnusedMethodDeclaredThrownException
|| problem.getID() == IProblem.UnusedConstructorDeclaredThrownException) {
if (problem.getSourceLineNumber() == problemLineNumber) {
UnusedDeclaredThrownExceptionFilter filter =
new UnusedDeclaredThrownExceptionFilter(problem);
result.removeProblems(filter);
}
}
}
}
private class UnusedDeclaredThrownExceptionFilter implements ProblemsForRemovalFilter {
private IProblem problemToRemove;
public UnusedDeclaredThrownExceptionFilter(IProblem p) {
problemToRemove = p;
}
public boolean accept(IProblem p) {
if (p.equals(problemToRemove)) {
return true;
}
return false;
}
}
}
|
151,673 |
Bug 151673 Incorrect weaving of after returning when 'input' bytecode is of a strange form
|
We have had a user report a problem where after advice being woven into a particular method is producing code that does not verify. The problem occurs if the bytecode being input to the weaving process includes a subroutine that contains the return from the method. Here is the problematic snippet produced by some unknown compiler: 200: invokespecial #17; //Method com/MyException."<init>":(Ljava/lang/String;)V 203: athrow 204: aload_3 205: astore 6 207: jsr 234 210: aload 6 212: areturn 213: astore 4 215: aload 4 217: invokevirtual #79; //Method java/lang/Throwable.printStackTrace:()V 220: jsr 234 223: goto 238 226: astore 7 228: jsr 234 231: aload 7 233: athrow 234: astore 8 236: aload_3 237: areturn 238: return Exception table: from to target type 2 213 213 Class javax/ejb/FinderException 2 226 226 any see the jsr's jump to 234, but before the subroutine return at 238 there is an areturn out of the method (this method returns a String). After weaving we get something like this: 200: invokespecial #17; //Method com/MyException."<init>":(Ljava/lang/String;)V 203: athrow 204: aload_3 205: astore 6 207: jsr 238 210: aload 6 212: astore 9 214: goto 248 217: astore 4 219: aload 4 221: invokevirtual #79; //Method java/lang/Throwable.printStackTrace:()V 224: jsr 238 227: goto 246 230: astore 7 232: jsr 238 235: aload 7 237: athrow 238: astore 8 240: aload_3 241: astore 9 243: goto 248 246: astore 9 248: invokestatic #299; //Method After.aspectOf:()LAfter; 251: invokevirtual #302; //Method After.ajc$afterReturning$After$1$26d6d4a7:()V 254: aload 9 256: return see how the areturn has been lost - this code will blow up with a verify error (the string is on the stack, we just ignore it and 'return' normally)
|
resolved fixed
|
e4ab0ae
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-07-27T09:57:26Z | 2006-07-25T09:33:20Z |
weaver/src/org/aspectj/weaver/bcel/BcelShadow.java
|
/* *******************************************************************
* Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC).
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the 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 support for @AJ aspects
* ******************************************************************/
package org.aspectj.weaver.bcel;
import java.lang.reflect.Modifier;
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 org.aspectj.apache.bcel.Constants;
import org.aspectj.apache.bcel.classfile.Field;
import org.aspectj.apache.bcel.generic.ACONST_NULL;
import org.aspectj.apache.bcel.generic.ALOAD;
import org.aspectj.apache.bcel.generic.ANEWARRAY;
import org.aspectj.apache.bcel.generic.ArrayType;
import org.aspectj.apache.bcel.generic.BranchInstruction;
import org.aspectj.apache.bcel.generic.ConstantPoolGen;
import org.aspectj.apache.bcel.generic.DUP;
import org.aspectj.apache.bcel.generic.DUP_X1;
import org.aspectj.apache.bcel.generic.FieldInstruction;
import org.aspectj.apache.bcel.generic.INVOKEINTERFACE;
import org.aspectj.apache.bcel.generic.INVOKESPECIAL;
import org.aspectj.apache.bcel.generic.INVOKESTATIC;
import org.aspectj.apache.bcel.generic.Instruction;
import org.aspectj.apache.bcel.generic.InstructionConstants;
import org.aspectj.apache.bcel.generic.InstructionFactory;
import org.aspectj.apache.bcel.generic.InstructionHandle;
import org.aspectj.apache.bcel.generic.InstructionList;
import org.aspectj.apache.bcel.generic.InstructionTargeter;
import org.aspectj.apache.bcel.generic.InvokeInstruction;
import org.aspectj.apache.bcel.generic.LoadInstruction;
import org.aspectj.apache.bcel.generic.LocalVariableTag;
import org.aspectj.apache.bcel.generic.MULTIANEWARRAY;
import org.aspectj.apache.bcel.generic.NEW;
import org.aspectj.apache.bcel.generic.ObjectType;
import org.aspectj.apache.bcel.generic.PUSH;
import org.aspectj.apache.bcel.generic.ReturnInstruction;
import org.aspectj.apache.bcel.generic.SWAP;
import org.aspectj.apache.bcel.generic.StoreInstruction;
import org.aspectj.apache.bcel.generic.TargetLostException;
import org.aspectj.apache.bcel.generic.Type;
import org.aspectj.bridge.ISourceLocation;
import org.aspectj.weaver.Advice;
import org.aspectj.weaver.AdviceKind;
import org.aspectj.weaver.AjcMemberMaker;
import org.aspectj.weaver.BCException;
import org.aspectj.weaver.IntMap;
import org.aspectj.weaver.Member;
import org.aspectj.weaver.MemberImpl;
import org.aspectj.weaver.NameMangler;
import org.aspectj.weaver.NewConstructorTypeMunger;
import org.aspectj.weaver.NewFieldTypeMunger;
import org.aspectj.weaver.NewMethodTypeMunger;
import org.aspectj.weaver.ResolvedMember;
import org.aspectj.weaver.ResolvedMemberImpl;
import org.aspectj.weaver.ResolvedType;
import org.aspectj.weaver.Shadow;
import org.aspectj.weaver.ShadowMunger;
import org.aspectj.weaver.UnresolvedType;
import org.aspectj.weaver.WeaverMessages;
import org.aspectj.weaver.World;
import org.aspectj.weaver.ast.Var;
import org.aspectj.weaver.patterns.AndPointcut;
import org.aspectj.weaver.patterns.IdentityPointcutVisitor;
import org.aspectj.weaver.patterns.NotPointcut;
import org.aspectj.weaver.patterns.OrPointcut;
import org.aspectj.weaver.patterns.Pointcut;
import org.aspectj.weaver.patterns.ThisOrTargetPointcut;
/*
* Some fun implementation stuff:
*
* * expressionKind advice is non-execution advice
* * may have a target.
* * if the body is extracted, it will be extracted into
* a static method. The first argument to the static
* method is the target
* * advice may expose a this object, but that's the advice's
* consideration, not ours. This object will NOT be cached in another
* local, but will always come from frame zero.
*
* * non-expressionKind advice is execution advice
* * may have a this.
* * target is same as this, and is exposed that way to advice
* (i.e., target will not be cached, will always come from frame zero)
* * if the body is extracted, it will be extracted into a method
* with same static/dynamic modifier as enclosing method. If non-static,
* target of callback call will be this.
*
* * because of these two facts, the setup of the actual arguments (including
* possible target) callback method is the same for both kinds of advice:
* push the targetVar, if it exists (it will not exist for advice on static
* things), then push all the argVars.
*
* Protected things:
*
* * the above is sufficient for non-expressionKind advice for protected things,
* since the target will always be this.
*
* * For expressionKind things, we have to modify the signature of the callback
* method slightly. For non-static expressionKind things, we modify
* the first argument of the callback method NOT to be the type specified
* by the method/field signature (the owner), but rather we type it to
* the currentlyEnclosing type. We are guaranteed this will be fine,
* since the verifier verifies that the target is a subtype of the currently
* enclosingType.
*
* Worries:
*
* * ConstructorCalls will be weirder than all of these, since they
* supposedly don't have a target (according to AspectJ), but they clearly
* do have a target of sorts, just one that needs to be pushed on the stack,
* dupped, and not touched otherwise until the constructor runs.
*
* @author Jim Hugunin
* @author Erik Hilsdale
*
*/
public class BcelShadow extends Shadow {
private ShadowRange range;
private final BcelWorld world;
private final LazyMethodGen enclosingMethod;
// private boolean fallsThrough; //XXX not used anymore
// SECRETAPI - for testing, this will tell us if the optimization succeeded *on the last shadow processed*
public static boolean appliedLazyTjpOptimization;
// Some instructions have a target type that will vary
// from the signature (pr109728) (1.4 declaring type issue)
private String actualInstructionTargetType;
// ---- initialization
/**
* This generates an unassociated shadow, rooted in a particular method but not rooted
* to any particular point in the code. It should be given to a rooted ShadowRange
* in the {@link ShadowRange#associateWithShadow(BcelShadow)} method.
*/
public BcelShadow(
BcelWorld world,
Kind kind,
Member signature,
LazyMethodGen enclosingMethod,
BcelShadow enclosingShadow)
{
super(kind, signature, enclosingShadow);
this.world = world;
this.enclosingMethod = enclosingMethod;
// fallsThrough = kind.argsOnStack();
}
// ---- copies all state, including Shadow's mungers...
public BcelShadow copyInto(LazyMethodGen recipient, BcelShadow enclosing) {
BcelShadow s = new BcelShadow(world, getKind(), getSignature(), recipient, enclosing);
if (mungers.size()>0) {
List src = mungers;
if (s.mungers==Collections.EMPTY_LIST) s.mungers = new ArrayList();
List dest = s.mungers;
for (Iterator i = src.iterator(); i.hasNext(); ) {
dest.add(i.next());
}
}
return s;
}
// ---- overridden behaviour
public World getIWorld() {
return world;
}
private void deleteNewAndDup() {
final ConstantPoolGen cpg = getEnclosingClass().getConstantPoolGen();
int depth = 1;
InstructionHandle ih = range.getStart();
while (true) {
Instruction inst = ih.getInstruction();
if (inst instanceof INVOKESPECIAL
&& ((INVOKESPECIAL) inst).getName(cpg).equals("<init>")) {
depth++;
} else if (inst instanceof NEW) {
depth--;
if (depth == 0) break;
}
ih = ih.getPrev();
}
// now IH points to the NEW. We're followed by the DUP, and that is followed
// by the actual instruction we care about.
InstructionHandle newHandle = ih;
InstructionHandle endHandle = newHandle.getNext();
InstructionHandle nextHandle;
if (endHandle.getInstruction() instanceof DUP) {
nextHandle = endHandle.getNext();
retargetFrom(newHandle, nextHandle);
retargetFrom(endHandle, nextHandle);
} else if (endHandle.getInstruction() instanceof DUP_X1) {
InstructionHandle dupHandle = endHandle;
endHandle = endHandle.getNext();
nextHandle = endHandle.getNext();
if (endHandle.getInstruction() instanceof SWAP) {}
else {
// XXX see next XXX comment
throw new RuntimeException("Unhandled kind of new " + endHandle);
}
// Now make any jumps to the 'new', the 'dup' or the 'end' now target the nextHandle
retargetFrom(newHandle, nextHandle);
retargetFrom(dupHandle, nextHandle);
retargetFrom(endHandle, nextHandle);
} else {
endHandle = newHandle;
nextHandle = endHandle.getNext();
retargetFrom(newHandle, nextHandle);
// add a POP here... we found a NEW w/o a dup or anything else, so
// we must be in statement context.
getRange().insert(InstructionConstants.POP, Range.OutsideAfter);
}
// assert (dupHandle.getInstruction() instanceof DUP);
try {
range.getBody().delete(newHandle, endHandle);
} catch (TargetLostException e) {
throw new BCException("shouldn't happen");
}
}
private void retargetFrom(InstructionHandle old, InstructionHandle fresh) {
InstructionTargeter[] sources = old.getTargeters();
if (sources != null) {
for (int i = sources.length - 1; i >= 0; i--) {
if (sources[i] instanceof ExceptionRange) {
ExceptionRange it = (ExceptionRange)sources[i];
System.err.println("...");
it.updateTarget(old,fresh,it.getBody());
} else {
sources[i].updateTarget(old, fresh);
}
}
}
}
// records advice that is stopping us doing the lazyTjp optimization
private List badAdvice = null;
public void addAdvicePreventingLazyTjp(BcelAdvice advice) {
if (badAdvice == null) badAdvice = new ArrayList();
badAdvice.add(advice);
}
protected void prepareForMungers() {
// if we're a constructor call, we need to remove the new:dup or the new:dup_x1:swap,
// and store all our
// arguments on the frame.
// ??? This is a bit of a hack (for the Java langauge). We do this because
// we sometime add code "outsideBefore" when dealing with weaving join points. We only
// do this for exposing state that is on the stack. It turns out to just work for
// everything except for constructor calls and exception handlers. If we were to clean
// this up, every ShadowRange would have three instructionHandle points, the start of
// the arg-setup code, the start of the running code, and the end of the running code.
if (getKind() == ConstructorCall) {
if (!world.isJoinpointArrayConstructionEnabled() || !this.getSignature().getDeclaringType().isArray())
deleteNewAndDup(); // no new/dup for new array construction
initializeArgVars();
} else if (getKind() == PreInitialization) { // pr74952
ShadowRange range = getRange();
range.insert(InstructionConstants.NOP,Range.InsideAfter);
} else if (getKind() == ExceptionHandler) {
ShadowRange range = getRange();
InstructionList body = range.getBody();
InstructionHandle start = range.getStart();
// Create a store instruction to put the value from the top of the
// stack into a local variable slot. This is a trimmed version of
// what is in initializeArgVars() (since there is only one argument
// at a handler jp and only before advice is supported) (pr46298)
argVars = new BcelVar[1];
//int positionOffset = (hasTarget() ? 1 : 0) + ((hasThis() && !getKind().isTargetSameAsThis()) ? 1 : 0);
UnresolvedType tx = getArgType(0);
argVars[0] = genTempVar(tx, "ajc$arg0");
InstructionHandle insertedInstruction =
range.insert(argVars[0].createStore(getFactory()), Range.OutsideBefore);
// Now the exception range starts just after our new instruction.
// The next bit of code changes the exception range to point at
// the store instruction
InstructionTargeter[] targeters = start.getTargeters();
for (int i = 0; i < targeters.length; i++) {
InstructionTargeter t = targeters[i];
if (t instanceof ExceptionRange) {
ExceptionRange er = (ExceptionRange) t;
er.updateTarget(start, insertedInstruction, body);
}
}
}
// now we ask each munger to request our state
isThisJoinPointLazy = true;//world.isXlazyTjp(); // lazy is default now
badAdvice = null;
for (Iterator iter = mungers.iterator(); iter.hasNext();) {
ShadowMunger munger = (ShadowMunger) iter.next();
munger.specializeOn(this);
}
initializeThisJoinPoint();
if (thisJoinPointVar!=null && !isThisJoinPointLazy && badAdvice!=null && badAdvice.size()>1) {
// something stopped us making it a lazy tjp
// can't build tjp lazily, no suitable test...
int valid = 0;
for (Iterator iter = badAdvice.iterator(); iter.hasNext();) {
BcelAdvice element = (BcelAdvice) iter.next();
ISourceLocation sLoc = element.getSourceLocation();
if (sLoc!=null && sLoc.getLine()>0) valid++;
}
if (valid!=0) {
ISourceLocation[] badLocs = new ISourceLocation[valid];
int i = 0;
for (Iterator iter = badAdvice.iterator(); iter.hasNext();) {
BcelAdvice element = (BcelAdvice) iter.next();
ISourceLocation sLoc = element.getSourceLocation();
if (sLoc!=null) badLocs[i++]=sLoc;
}
world.getLint().multipleAdviceStoppingLazyTjp.signal(
new String[] {this.toString()},
getSourceLocation(),badLocs
);
}
}
badAdvice=null;
// If we are an expression kind, we require our target/arguments on the stack
// before we do our actual thing. However, they may have been removed
// from the stack as the shadowMungers have requested state.
// if any of our shadowMungers requested either the arguments or target,
// the munger will have added code
// to pop the target/arguments into temporary variables, represented by
// targetVar and argVars. In such a case, we must make sure to re-push the
// values.
// If we are nonExpressionKind, we don't expect arguments on the stack
// so this is moot. If our argVars happen to be null, then we know that
// no ShadowMunger has squirrelled away our arguments, so they're still
// on the stack.
InstructionFactory fact = getFactory();
if (getKind().argsOnStack() && argVars != null) {
// Special case first (pr46298). If we are an exception handler and the instruction
// just after the shadow is a POP then we should remove the pop. The code
// above which generated the store instruction has already cleared the stack.
// We also don't generate any code for the arguments in this case as it would be
// an incorrect aload.
if (getKind() == ExceptionHandler
&& range.getEnd().getNext().getInstruction().equals(InstructionConstants.POP)) {
// easier than deleting it ...
range.getEnd().getNext().setInstruction(InstructionConstants.NOP);
} else {
range.insert(
BcelRenderer.renderExprs(fact, world, argVars),
Range.InsideBefore);
if (targetVar != null) {
range.insert(
BcelRenderer.renderExpr(fact, world, targetVar),
Range.InsideBefore);
}
if (getKind() == ConstructorCall) {
if (!world.isJoinpointArrayConstructionEnabled() || !this.getSignature().getDeclaringType().isArray()) {
range.insert((Instruction) InstructionFactory.createDup(1), Range.InsideBefore);
range.insert(
fact.createNew(
(ObjectType) BcelWorld.makeBcelType(
getSignature().getDeclaringType())),
Range.InsideBefore);
}
}
}
}
}
// ---- getters
public ShadowRange getRange() {
return range;
}
public void setRange(ShadowRange range) {
this.range = range;
}
public int getSourceLine() {
// if the kind of join point for which we are a shadow represents
// a method or constructor execution, then the best source line is
// the one from the enclosingMethod declarationLineNumber if available.
Kind kind = getKind();
if ( (kind == MethodExecution) ||
(kind == ConstructorExecution) ||
(kind == AdviceExecution) ||
(kind == StaticInitialization) ||
(kind == PreInitialization) ||
(kind == Initialization)) {
if (getEnclosingMethod().hasDeclaredLineNumberInfo()) {
return getEnclosingMethod().getDeclarationLineNumber();
}
}
if (range == null) {
if (getEnclosingMethod().hasBody()) {
return Utility.getSourceLine(getEnclosingMethod().getBody().getStart());
} else {
return 0;
}
}
int ret = Utility.getSourceLine(range.getStart());
if (ret < 0) return 0;
return ret;
}
// overrides
public UnresolvedType getEnclosingType() {
return getEnclosingClass().getType();
}
public LazyClassGen getEnclosingClass() {
return enclosingMethod.getEnclosingClass();
}
public BcelWorld getWorld() {
return world;
}
// ---- factory methods
public static BcelShadow makeConstructorExecution(
BcelWorld world,
LazyMethodGen enclosingMethod,
InstructionHandle justBeforeStart)
{
final InstructionList body = enclosingMethod.getBody();
BcelShadow s =
new BcelShadow(
world,
ConstructorExecution,
world.makeJoinPointSignature(enclosingMethod),
enclosingMethod,
null);
ShadowRange r = new ShadowRange(body);
r.associateWithShadow(s);
r.associateWithTargets(
Range.genStart(body, justBeforeStart.getNext()),
Range.genEnd(body));
return s;
}
public static BcelShadow makeStaticInitialization(
BcelWorld world,
LazyMethodGen enclosingMethod)
{
InstructionList body = enclosingMethod.getBody();
// move the start past ajc$preClinit
InstructionHandle clinitStart = body.getStart();
if (clinitStart.getInstruction() instanceof InvokeInstruction) {
InvokeInstruction ii = (InvokeInstruction)clinitStart.getInstruction();
if (ii
.getName(enclosingMethod.getEnclosingClass().getConstantPoolGen())
.equals(NameMangler.AJC_PRE_CLINIT_NAME)) {
clinitStart = clinitStart.getNext();
}
}
InstructionHandle clinitEnd = body.getEnd();
//XXX should move the end before the postClinit, but the return is then tricky...
// if (clinitEnd.getInstruction() instanceof InvokeInstruction) {
// InvokeInstruction ii = (InvokeInstruction)clinitEnd.getInstruction();
// if (ii.getName(enclosingMethod.getEnclosingClass().getConstantPoolGen()).equals(NameMangler.AJC_POST_CLINIT_NAME)) {
// clinitEnd = clinitEnd.getPrev();
// }
// }
BcelShadow s =
new BcelShadow(
world,
StaticInitialization,
world.makeJoinPointSignature(enclosingMethod),
enclosingMethod,
null);
ShadowRange r = new ShadowRange(body);
r.associateWithShadow(s);
r.associateWithTargets(
Range.genStart(body, clinitStart),
Range.genEnd(body, clinitEnd));
return s;
}
/** Make the shadow for an exception handler. Currently makes an empty shadow that
* only allows before advice to be woven into it.
*/
public static BcelShadow makeExceptionHandler(
BcelWorld world,
ExceptionRange exceptionRange,
LazyMethodGen enclosingMethod,
InstructionHandle startOfHandler,
BcelShadow enclosingShadow)
{
InstructionList body = enclosingMethod.getBody();
UnresolvedType catchType = exceptionRange.getCatchType();
UnresolvedType inType = enclosingMethod.getEnclosingClass().getType();
ResolvedMemberImpl sig = MemberImpl.makeExceptionHandlerSignature(inType, catchType);
sig.setParameterNames(new String[] {findHandlerParamName(startOfHandler)});
BcelShadow s =
new BcelShadow(
world,
ExceptionHandler,
sig,
enclosingMethod,
enclosingShadow);
ShadowRange r = new ShadowRange(body);
r.associateWithShadow(s);
InstructionHandle start = Range.genStart(body, startOfHandler);
InstructionHandle end = Range.genEnd(body, start);
r.associateWithTargets(start, end);
exceptionRange.updateTarget(startOfHandler, start, body);
return s;
}
private static String findHandlerParamName(InstructionHandle startOfHandler) {
if (startOfHandler.getInstruction() instanceof StoreInstruction &&
startOfHandler.getNext() != null)
{
int slot = ((StoreInstruction)startOfHandler.getInstruction()).getIndex();
//System.out.println("got store: " + startOfHandler.getInstruction() + ", " + index);
InstructionTargeter[] targeters = startOfHandler.getNext().getTargeters();
if (targeters!=null) {
for (int i=targeters.length-1; i >= 0; i--) {
if (targeters[i] instanceof LocalVariableTag) {
LocalVariableTag t = (LocalVariableTag)targeters[i];
if (t.getSlot() == slot) {
return t.getName();
}
//System.out.println("tag: " + targeters[i]);
}
}
}
}
return "<missing>";
}
/** create an init join point associated w/ an interface in the body of a constructor */
public static BcelShadow makeIfaceInitialization(
BcelWorld world,
LazyMethodGen constructor,
Member interfaceConstructorSignature)
{
// this call marks the instruction list as changed
constructor.getBody();
// UnresolvedType inType = constructor.getEnclosingClass().getType();
BcelShadow s =
new BcelShadow(
world,
Initialization,
interfaceConstructorSignature,
constructor,
null);
// s.fallsThrough = true;
// ShadowRange r = new ShadowRange(body);
// r.associateWithShadow(s);
// InstructionHandle start = Range.genStart(body, handle);
// InstructionHandle end = Range.genEnd(body, handle);
//
// r.associateWithTargets(start, end);
return s;
}
public void initIfaceInitializer(InstructionHandle end) {
final InstructionList body = enclosingMethod.getBody();
ShadowRange r = new ShadowRange(body);
r.associateWithShadow(this);
InstructionHandle nop = body.insert(end, InstructionConstants.NOP);
r.associateWithTargets(
Range.genStart(body, nop),
Range.genEnd(body, nop));
}
// public static BcelShadow makeIfaceConstructorExecution(
// BcelWorld world,
// LazyMethodGen constructor,
// InstructionHandle next,
// Member interfaceConstructorSignature)
// {
// // final InstructionFactory fact = constructor.getEnclosingClass().getFactory();
// InstructionList body = constructor.getBody();
// // UnresolvedType inType = constructor.getEnclosingClass().getType();
// BcelShadow s =
// new BcelShadow(
// world,
// ConstructorExecution,
// interfaceConstructorSignature,
// constructor,
// null);
// s.fallsThrough = true;
// ShadowRange r = new ShadowRange(body);
// r.associateWithShadow(s);
// // ??? this may or may not work
// InstructionHandle start = Range.genStart(body, next);
// //InstructionHandle end = Range.genEnd(body, body.append(start, fact.NOP));
// InstructionHandle end = Range.genStart(body, next);
// //body.append(start, fact.NOP);
//
// r.associateWithTargets(start, end);
// return s;
// }
/** Create an initialization join point associated with a constructor, but not
* with any body of code yet. If this is actually matched, it's range will be set
* when we inline self constructors.
*
* @param constructor The constructor starting this initialization.
*/
public static BcelShadow makeUnfinishedInitialization(
BcelWorld world,
LazyMethodGen constructor)
{
BcelShadow ret = new BcelShadow(
world,
Initialization,
world.makeJoinPointSignature(constructor),
constructor,
null);
if (constructor.getEffectiveSignature() != null) {
ret.setMatchingSignature(constructor.getEffectiveSignature().getEffectiveSignature());
}
return ret;
}
public static BcelShadow makeUnfinishedPreinitialization(
BcelWorld world,
LazyMethodGen constructor)
{
BcelShadow ret = new BcelShadow(
world,
PreInitialization,
world.makeJoinPointSignature(constructor),
constructor,
null);
// ret.fallsThrough = true;
if (constructor.getEffectiveSignature() != null) {
ret.setMatchingSignature(constructor.getEffectiveSignature().getEffectiveSignature());
}
return ret;
}
public static BcelShadow makeMethodExecution(
BcelWorld world,
LazyMethodGen enclosingMethod,
boolean lazyInit)
{
if (!lazyInit) return makeMethodExecution(world, enclosingMethod);
BcelShadow s =
new BcelShadow(
world,
MethodExecution,
enclosingMethod.getMemberView(),
enclosingMethod,
null);
return s;
}
public void init() {
if (range != null) return;
final InstructionList body = enclosingMethod.getBody();
ShadowRange r = new ShadowRange(body);
r.associateWithShadow(this);
r.associateWithTargets(
Range.genStart(body),
Range.genEnd(body));
}
public static BcelShadow makeMethodExecution(
BcelWorld world,
LazyMethodGen enclosingMethod)
{
return makeShadowForMethod(world, enclosingMethod, MethodExecution,
enclosingMethod.getMemberView()); //world.makeMethodSignature(enclosingMethod));
}
public static BcelShadow makeShadowForMethod(BcelWorld world,
LazyMethodGen enclosingMethod, Shadow.Kind kind, Member sig)
{
final InstructionList body = enclosingMethod.getBody();
BcelShadow s =
new BcelShadow(
world,
kind,
sig,
enclosingMethod,
null);
ShadowRange r = new ShadowRange(body);
r.associateWithShadow(s);
r.associateWithTargets(
Range.genStart(body),
Range.genEnd(body));
return s;
}
public static BcelShadow makeAdviceExecution(
BcelWorld world,
LazyMethodGen enclosingMethod)
{
final InstructionList body = enclosingMethod.getBody();
BcelShadow s =
new BcelShadow(
world,
AdviceExecution,
world.makeJoinPointSignatureFromMethod(enclosingMethod, Member.ADVICE),
enclosingMethod,
null);
ShadowRange r = new ShadowRange(body);
r.associateWithShadow(s);
r.associateWithTargets(Range.genStart(body), Range.genEnd(body));
return s;
}
// constructor call shadows are <em>initially</em> just around the
// call to the constructor. If ANY advice gets put on it, we move
// the NEW instruction inside the join point, which involves putting
// all the arguments in temps.
public static BcelShadow makeConstructorCall(
BcelWorld world,
LazyMethodGen enclosingMethod,
InstructionHandle callHandle,
BcelShadow enclosingShadow)
{
final InstructionList body = enclosingMethod.getBody();
Member sig = world.makeJoinPointSignatureForMethodInvocation(
enclosingMethod.getEnclosingClass(),
(InvokeInstruction) callHandle.getInstruction());
BcelShadow s =
new BcelShadow(
world,
ConstructorCall,
sig,
enclosingMethod,
enclosingShadow);
ShadowRange r = new ShadowRange(body);
r.associateWithShadow(s);
r.associateWithTargets(
Range.genStart(body, callHandle),
Range.genEnd(body, callHandle));
retargetAllBranches(callHandle, r.getStart());
return s;
}
public static BcelShadow makeArrayConstructorCall(BcelWorld world,LazyMethodGen enclosingMethod,InstructionHandle arrayInstruction,BcelShadow enclosingShadow) {
final InstructionList body = enclosingMethod.getBody();
Member sig = world.makeJoinPointSignatureForArrayConstruction(enclosingMethod.getEnclosingClass(),arrayInstruction);
BcelShadow s =
new BcelShadow(
world,
ConstructorCall,
sig,
enclosingMethod,
enclosingShadow);
ShadowRange r = new ShadowRange(body);
r.associateWithShadow(s);
r.associateWithTargets(
Range.genStart(body, arrayInstruction),
Range.genEnd(body, arrayInstruction));
retargetAllBranches(arrayInstruction, r.getStart());
return s;
}
public static BcelShadow makeMonitorEnter(BcelWorld world,LazyMethodGen enclosingMethod,InstructionHandle monitorInstruction,BcelShadow enclosingShadow) {
final InstructionList body = enclosingMethod.getBody();
Member sig = world.makeJoinPointSignatureForMonitorEnter(enclosingMethod.getEnclosingClass(),monitorInstruction);
BcelShadow s = new BcelShadow(world,SynchronizationLock,sig,enclosingMethod,enclosingShadow);
ShadowRange r = new ShadowRange(body);
r.associateWithShadow(s);
r.associateWithTargets(
Range.genStart(body, monitorInstruction),
Range.genEnd(body, monitorInstruction));
retargetAllBranches(monitorInstruction, r.getStart());
return s;
}
public static BcelShadow makeMonitorExit(BcelWorld world,LazyMethodGen enclosingMethod,InstructionHandle monitorInstruction,BcelShadow enclosingShadow) {
final InstructionList body = enclosingMethod.getBody();
Member sig = world.makeJoinPointSignatureForMonitorExit(enclosingMethod.getEnclosingClass(),monitorInstruction);
BcelShadow s = new BcelShadow(world,SynchronizationUnlock,sig,enclosingMethod,enclosingShadow);
ShadowRange r = new ShadowRange(body);
r.associateWithShadow(s);
r.associateWithTargets(
Range.genStart(body, monitorInstruction),
Range.genEnd(body, monitorInstruction));
retargetAllBranches(monitorInstruction, r.getStart());
return s;
}
// see pr77166
// public static BcelShadow makeArrayLoadCall(
// BcelWorld world,
// LazyMethodGen enclosingMethod,
// InstructionHandle arrayInstruction,
// BcelShadow enclosingShadow)
// {
// final InstructionList body = enclosingMethod.getBody();
// Member sig = world.makeJoinPointSignatureForArrayLoad(enclosingMethod.getEnclosingClass(),arrayInstruction);
// BcelShadow s =
// new BcelShadow(
// world,
// MethodCall,
// sig,
// enclosingMethod,
// enclosingShadow);
// ShadowRange r = new ShadowRange(body);
// r.associateWithShadow(s);
// r.associateWithTargets(
// Range.genStart(body, arrayInstruction),
// Range.genEnd(body, arrayInstruction));
// retargetAllBranches(arrayInstruction, r.getStart());
// return s;
// }
public static BcelShadow makeMethodCall(
BcelWorld world,
LazyMethodGen enclosingMethod,
InstructionHandle callHandle,
BcelShadow enclosingShadow)
{
final InstructionList body = enclosingMethod.getBody();
BcelShadow s =
new BcelShadow(
world,
MethodCall,
world.makeJoinPointSignatureForMethodInvocation(
enclosingMethod.getEnclosingClass(),
(InvokeInstruction) callHandle.getInstruction()),
enclosingMethod,
enclosingShadow);
ShadowRange r = new ShadowRange(body);
r.associateWithShadow(s);
r.associateWithTargets(
Range.genStart(body, callHandle),
Range.genEnd(body, callHandle));
retargetAllBranches(callHandle, r.getStart());
return s;
}
public static BcelShadow makeShadowForMethodCall(
BcelWorld world,
LazyMethodGen enclosingMethod,
InstructionHandle callHandle,
BcelShadow enclosingShadow,
Kind kind,
ResolvedMember sig)
{
final InstructionList body = enclosingMethod.getBody();
BcelShadow s =
new BcelShadow(
world,
kind,
sig,
enclosingMethod,
enclosingShadow);
ShadowRange r = new ShadowRange(body);
r.associateWithShadow(s);
r.associateWithTargets(
Range.genStart(body, callHandle),
Range.genEnd(body, callHandle));
retargetAllBranches(callHandle, r.getStart());
return s;
}
public static BcelShadow makeFieldGet(
BcelWorld world,
ResolvedMember field,
LazyMethodGen enclosingMethod,
InstructionHandle getHandle,
BcelShadow enclosingShadow)
{
final InstructionList body = enclosingMethod.getBody();
BcelShadow s =
new BcelShadow(
world,
FieldGet,
field,
// BcelWorld.makeFieldSignature(
// enclosingMethod.getEnclosingClass(),
// (FieldInstruction) getHandle.getInstruction()),
enclosingMethod,
enclosingShadow);
ShadowRange r = new ShadowRange(body);
r.associateWithShadow(s);
r.associateWithTargets(
Range.genStart(body, getHandle),
Range.genEnd(body, getHandle));
retargetAllBranches(getHandle, r.getStart());
return s;
}
public static BcelShadow makeFieldSet(
BcelWorld world,
LazyMethodGen enclosingMethod,
InstructionHandle setHandle,
BcelShadow enclosingShadow)
{
final InstructionList body = enclosingMethod.getBody();
BcelShadow s =
new BcelShadow(
world,
FieldSet,
BcelWorld.makeFieldJoinPointSignature(
enclosingMethod.getEnclosingClass(),
(FieldInstruction) setHandle.getInstruction()),
enclosingMethod,
enclosingShadow);
ShadowRange r = new ShadowRange(body);
r.associateWithShadow(s);
r.associateWithTargets(
Range.genStart(body, setHandle),
Range.genEnd(body, setHandle));
retargetAllBranches(setHandle, r.getStart());
return s;
}
public static void retargetAllBranches(InstructionHandle from, InstructionHandle to) {
InstructionTargeter[] sources = from.getTargeters();
if (sources != null) {
for (int i = sources.length - 1; i >= 0; i--) {
InstructionTargeter source = sources[i];
if (source instanceof BranchInstruction) {
source.updateTarget(from, to);
}
}
}
}
// // ---- type access methods
// private ObjectType getTargetBcelType() {
// return (ObjectType) BcelWorld.makeBcelType(getTargetType());
// }
// private Type getArgBcelType(int arg) {
// return BcelWorld.makeBcelType(getArgType(arg));
// }
// ---- kinding
/**
* If the end of my range has no real instructions following then
* my context needs a return at the end.
*/
public boolean terminatesWithReturn() {
return getRange().getRealNext() == null;
}
/**
* Is arg0 occupied with the value of this
*/
public boolean arg0HoldsThis() {
if (getKind().isEnclosingKind()) {
return !getSignature().isStatic();
} else if (enclosingShadow == null) {
//XXX this is mostly right
// this doesn't do the right thing for calls in the pre part of introduced constructors.
return !enclosingMethod.isStatic();
} else {
return ((BcelShadow)enclosingShadow).arg0HoldsThis();
}
}
// ---- argument getting methods
private BcelVar thisVar = null;
private BcelVar targetVar = null;
private BcelVar[] argVars = null;
private Map/*<UnresolvedType,BcelVar>*/ kindedAnnotationVars = null;
private Map/*<UnresolvedType,BcelVar>*/ thisAnnotationVars = null;
private Map/*<UnresolvedType,BcelVar>*/ targetAnnotationVars = null;
private Map/*<UnresolvedType,BcelVar>*/[] argAnnotationVars = null;
private Map/*<UnresolvedType,BcelVar>*/ withinAnnotationVars = null;
private Map/*<UnresolvedType,BcelVar>*/ withincodeAnnotationVars = null;
public Var getThisVar() {
if (!hasThis()) {
throw new IllegalStateException("no this");
}
initializeThisVar();
return thisVar;
}
public Var getThisAnnotationVar(UnresolvedType forAnnotationType) {
if (!hasThis()) {
throw new IllegalStateException("no this");
}
initializeThisAnnotationVars(); // FIXME asc Why bother with this if we always return one?
// Even if we can't find one, we have to return one as we might have this annotation at runtime
Var v = (Var) thisAnnotationVars.get(forAnnotationType);
if (v==null)
v = new TypeAnnotationAccessVar(forAnnotationType.resolve(world),(BcelVar)getThisVar());
return v;
}
public Var getTargetVar() {
if (!hasTarget()) {
throw new IllegalStateException("no target");
}
initializeTargetVar();
return targetVar;
}
public Var getTargetAnnotationVar(UnresolvedType forAnnotationType) {
if (!hasTarget()) {
throw new IllegalStateException("no target");
}
initializeTargetAnnotationVars(); // FIXME asc why bother with this if we always return one?
Var v =(Var) targetAnnotationVars.get(forAnnotationType);
// Even if we can't find one, we have to return one as we might have this annotation at runtime
if (v==null)
v = new TypeAnnotationAccessVar(forAnnotationType.resolve(world),(BcelVar)getTargetVar());
return v;
}
public Var getArgVar(int i) {
initializeArgVars();
return argVars[i];
}
public Var getArgAnnotationVar(int i,UnresolvedType forAnnotationType) {
initializeArgAnnotationVars();
Var v= (Var) argAnnotationVars[i].get(forAnnotationType);
if (v==null)
v = new TypeAnnotationAccessVar(forAnnotationType.resolve(world),(BcelVar)getArgVar(i));
return v;
}
public Var getKindedAnnotationVar(UnresolvedType forAnnotationType) {
initializeKindedAnnotationVars();
return (Var) kindedAnnotationVars.get(forAnnotationType);
}
public Var getWithinAnnotationVar(UnresolvedType forAnnotationType) {
initializeWithinAnnotationVars();
return (Var) withinAnnotationVars.get(forAnnotationType);
}
public Var getWithinCodeAnnotationVar(UnresolvedType forAnnotationType) {
initializeWithinCodeAnnotationVars();
return (Var) withincodeAnnotationVars.get(forAnnotationType);
}
// reflective thisJoinPoint support
private BcelVar thisJoinPointVar = null;
private boolean isThisJoinPointLazy;
private int lazyTjpConsumers = 0;
private BcelVar thisJoinPointStaticPartVar = null;
// private BcelVar thisEnclosingJoinPointStaticPartVar = null;
public final Var getThisJoinPointStaticPartVar() {
return getThisJoinPointStaticPartBcelVar();
}
public final Var getThisEnclosingJoinPointStaticPartVar() {
return getThisEnclosingJoinPointStaticPartBcelVar();
}
public void requireThisJoinPoint(boolean hasGuardTest, boolean isAround) {
if (!isAround){
if (!hasGuardTest) {
isThisJoinPointLazy = false;
} else {
lazyTjpConsumers++;
}
}
// if (!hasGuardTest) {
// isThisJoinPointLazy = false;
// } else {
// lazyTjpConsumers++;
// }
if (thisJoinPointVar == null) {
thisJoinPointVar = genTempVar(UnresolvedType.forName("org.aspectj.lang.JoinPoint"));
}
}
public Var getThisJoinPointVar() {
requireThisJoinPoint(false,false);
return thisJoinPointVar;
}
void initializeThisJoinPoint() {
if (thisJoinPointVar == null) return;
if (isThisJoinPointLazy) {
isThisJoinPointLazy = checkLazyTjp();
}
if (isThisJoinPointLazy) {
appliedLazyTjpOptimization = true;
createThisJoinPoint(); // make sure any state needed is initialized, but throw the instructions out
if (lazyTjpConsumers == 1) return; // special case only one lazyTjpUser
InstructionFactory fact = getFactory();
InstructionList il = new InstructionList();
il.append(InstructionConstants.ACONST_NULL);
il.append(thisJoinPointVar.createStore(fact));
range.insert(il, Range.OutsideBefore);
} else {
appliedLazyTjpOptimization = false;
InstructionFactory fact = getFactory();
InstructionList il = createThisJoinPoint();
il.append(thisJoinPointVar.createStore(fact));
range.insert(il, Range.OutsideBefore);
}
}
private boolean checkLazyTjp() {
// check for around advice
for (Iterator i = mungers.iterator(); i.hasNext();) {
ShadowMunger munger = (ShadowMunger) i.next();
if (munger instanceof Advice) {
if ( ((Advice)munger).getKind() == AdviceKind.Around) {
if (munger.getSourceLocation()!=null) { // do we know enough to bother reporting?
if (world.getLint().canNotImplementLazyTjp.isEnabled()) {
world.getLint().canNotImplementLazyTjp.signal(
new String[] {toString()},
getSourceLocation(),
new ISourceLocation[] { munger.getSourceLocation() }
);
}
}
return false;
}
}
}
return true;
}
InstructionList loadThisJoinPoint() {
InstructionFactory fact = getFactory();
InstructionList il = new InstructionList();
if (isThisJoinPointLazy) {
// If we're lazy, build the join point right here.
il.append(createThisJoinPoint());
// Does someone else need it? If so, store it for later retrieval
if (lazyTjpConsumers > 1) {
il.append(thisJoinPointVar.createStore(fact));
InstructionHandle end = il.append(thisJoinPointVar.createLoad(fact));
il.insert(InstructionFactory.createBranchInstruction(Constants.IFNONNULL, end));
il.insert(thisJoinPointVar.createLoad(fact));
}
} else {
// If not lazy, its already been built and stored, just retrieve it
thisJoinPointVar.appendLoad(il, fact);
}
return il;
}
InstructionList createThisJoinPoint() {
InstructionFactory fact = getFactory();
InstructionList il = new InstructionList();
BcelVar staticPart = getThisJoinPointStaticPartBcelVar();
staticPart.appendLoad(il, fact);
if (hasThis()) {
((BcelVar)getThisVar()).appendLoad(il, fact);
} else {
il.append(new ACONST_NULL());
}
if (hasTarget()) {
((BcelVar)getTargetVar()).appendLoad(il, fact);
} else {
il.append(new ACONST_NULL());
}
switch(getArgCount()) {
case 0:
il.append(fact.createInvoke("org.aspectj.runtime.reflect.Factory",
"makeJP", LazyClassGen.tjpType,
new Type[] { LazyClassGen.staticTjpType,
Type.OBJECT, Type.OBJECT},
Constants.INVOKESTATIC));
break;
case 1:
((BcelVar)getArgVar(0)).appendLoadAndConvert(il, fact, world.getCoreType(ResolvedType.OBJECT));
il.append(fact.createInvoke("org.aspectj.runtime.reflect.Factory",
"makeJP", LazyClassGen.tjpType,
new Type[] { LazyClassGen.staticTjpType,
Type.OBJECT, Type.OBJECT, Type.OBJECT},
Constants.INVOKESTATIC));
break;
case 2:
((BcelVar)getArgVar(0)).appendLoadAndConvert(il, fact, world.getCoreType(ResolvedType.OBJECT));
((BcelVar)getArgVar(1)).appendLoadAndConvert(il, fact, world.getCoreType(ResolvedType.OBJECT));
il.append(fact.createInvoke("org.aspectj.runtime.reflect.Factory",
"makeJP", LazyClassGen.tjpType,
new Type[] { LazyClassGen.staticTjpType,
Type.OBJECT, Type.OBJECT, Type.OBJECT, Type.OBJECT},
Constants.INVOKESTATIC));
break;
default:
il.append(makeArgsObjectArray());
il.append(fact.createInvoke("org.aspectj.runtime.reflect.Factory",
"makeJP", LazyClassGen.tjpType,
new Type[] { LazyClassGen.staticTjpType,
Type.OBJECT, Type.OBJECT, new ArrayType(Type.OBJECT, 1)},
Constants.INVOKESTATIC));
break;
}
return il;
}
/**
* Get the Var for the jpStaticPart
* @return
*/
public BcelVar getThisJoinPointStaticPartBcelVar() {
return getThisJoinPointStaticPartBcelVar(false);
}
/**
* Get the Var for the xxxxJpStaticPart, xxx = this or enclosing
* @param isEnclosingJp true to have the enclosingJpStaticPart
* @return
*/
public BcelVar getThisJoinPointStaticPartBcelVar(final boolean isEnclosingJp) {
if (thisJoinPointStaticPartVar == null) {
Field field = getEnclosingClass().getTjpField(this, isEnclosingJp);
ResolvedType sjpType = null;
if (world.isTargettingAspectJRuntime12()) { // TAG:SUPPORTING12: We didn't have different jpsp types in 1.2
sjpType = world.getCoreType(UnresolvedType.forName("org.aspectj.lang.JoinPoint$StaticPart"));
} else {
sjpType = isEnclosingJp?
world.getCoreType(UnresolvedType.forName("org.aspectj.lang.JoinPoint$EnclosingStaticPart")):
world.getCoreType(UnresolvedType.forName("org.aspectj.lang.JoinPoint$StaticPart"));
}
thisJoinPointStaticPartVar = new BcelFieldRef(
sjpType,
getEnclosingClass().getClassName(),
field.getName());
// getEnclosingClass().warnOnAddedStaticInitializer(this,munger.getSourceLocation());
}
return thisJoinPointStaticPartVar;
}
/**
* Get the Var for the enclosingJpStaticPart
* @return
*/
public BcelVar getThisEnclosingJoinPointStaticPartBcelVar() {
if (enclosingShadow == null) {
// the enclosing of an execution is itself
return getThisJoinPointStaticPartBcelVar(true);
} else {
return ((BcelShadow)enclosingShadow).getThisJoinPointStaticPartBcelVar(true);
}
}
//??? need to better understand all the enclosing variants
public Member getEnclosingCodeSignature() {
if (getKind().isEnclosingKind()) {
return getSignature();
} else if (getKind() == Shadow.PreInitialization) {
// PreInit doesn't enclose code but its signature
// is correctly the signature of the ctor.
return getSignature();
} else if (enclosingShadow == null) {
return getEnclosingMethod().getMemberView();
} else {
return enclosingShadow.getSignature();
}
}
private InstructionList makeArgsObjectArray() {
InstructionFactory fact = getFactory();
BcelVar arrayVar = genTempVar(UnresolvedType.OBJECTARRAY);
final InstructionList il = new InstructionList();
int alen = getArgCount() ;
il.append(Utility.createConstant(fact, alen));
il.append((Instruction)fact.createNewArray(Type.OBJECT, (short)1));
arrayVar.appendStore(il, fact);
int stateIndex = 0;
for (int i = 0, len = getArgCount(); i<len; i++) {
arrayVar.appendConvertableArrayStore(il, fact, stateIndex, (BcelVar)getArgVar(i));
stateIndex++;
}
arrayVar.appendLoad(il, fact);
return il;
}
// ---- initializing var tables
/* initializing this is doesn't do anything, because this
* is protected from side-effects, so we don't need to copy its location
*/
private void initializeThisVar() {
if (thisVar != null) return;
thisVar = new BcelVar(getThisType().resolve(world), 0);
thisVar.setPositionInAroundState(0);
}
public void initializeTargetVar() {
InstructionFactory fact = getFactory();
if (targetVar != null) return;
if (getKind().isTargetSameAsThis()) {
if (hasThis()) initializeThisVar();
targetVar = thisVar;
} else {
initializeArgVars(); // gotta pop off the args before we find the target
UnresolvedType type = getTargetType();
type = ensureTargetTypeIsCorrect(type);
targetVar = genTempVar(type, "ajc$target");
range.insert(targetVar.createStore(fact), Range.OutsideBefore);
targetVar.setPositionInAroundState(hasThis() ? 1 : 0);
}
}
/* PR 72528
* This method double checks the target type under certain conditions. The Java 1.4
* compilers seem to take calls to clone methods on array types and create bytecode that
* looks like clone is being called on Object. If we advise a clone call with around
* advice we extract the call into a helper method which we can then refer to. Because the
* type in the bytecode for the call to clone is Object we create a helper method with
* an Object parameter - this is not correct as we have lost the fact that the actual
* type is an array type. If we don't do the check below we will create code that fails
* java verification. This method checks for the peculiar set of conditions and if they
* are true, it has a sneak peek at the code before the call to see what is on the stack.
*/
public UnresolvedType ensureTargetTypeIsCorrect(UnresolvedType tx) {
Member msig = getSignature();
if (msig.getArity()==0 &&
getKind() == MethodCall &&
msig.getName().charAt(0) == 'c' &&
tx.equals(ResolvedType.OBJECT) &&
msig.getReturnType().equals(ResolvedType.OBJECT) &&
msig.getName().equals("clone")) {
// Lets go back through the code from the start of the shadow
InstructionHandle searchPtr = range.getStart().getPrev();
while (Range.isRangeHandle(searchPtr) ||
searchPtr.getInstruction() instanceof StoreInstruction) { // ignore this instruction - it doesnt give us the info we want
searchPtr = searchPtr.getPrev();
}
// A load instruction may tell us the real type of what the clone() call is on
if (searchPtr.getInstruction() instanceof LoadInstruction) {
LoadInstruction li = (LoadInstruction)searchPtr.getInstruction();
li.getIndex();
LocalVariableTag lvt = LazyMethodGen.getLocalVariableTag(searchPtr,li.getIndex());
if (lvt!=null) return UnresolvedType.forSignature(lvt.getType());
}
// A field access instruction may tell us the real type of what the clone() call is on
if (searchPtr.getInstruction() instanceof FieldInstruction) {
FieldInstruction si = (FieldInstruction)searchPtr.getInstruction();
Type t = si.getFieldType(getEnclosingClass().getConstantPoolGen());
return BcelWorld.fromBcel(t);
}
// A new array instruction obviously tells us it is an array type !
if (searchPtr.getInstruction() instanceof ANEWARRAY) {
//ANEWARRAY ana = (ANEWARRAY)searchPoint.getInstruction();
//Type t = ana.getType(getEnclosingClass().getConstantPoolGen());
// Just use a standard java.lang.object array - that will work fine
return BcelWorld.fromBcel(new ArrayType(Type.OBJECT,1));
}
// A multi new array instruction obviously tells us it is an array type !
if (searchPtr.getInstruction() instanceof MULTIANEWARRAY) {
MULTIANEWARRAY ana = (MULTIANEWARRAY)searchPtr.getInstruction();
// Type t = ana.getType(getEnclosingClass().getConstantPoolGen());
// t = new ArrayType(t,ana.getDimensions());
// Just use a standard java.lang.object array - that will work fine
return BcelWorld.fromBcel(new ArrayType(Type.OBJECT,ana.getDimensions()));
}
throw new BCException("Can't determine real target of clone() when processing instruction "+
searchPtr.getInstruction()+". Perhaps avoid selecting clone with your pointcut?");
}
return tx;
}
public void initializeArgVars() {
if (argVars != null) return;
InstructionFactory fact = getFactory();
int len = getArgCount();
argVars = new BcelVar[len];
int positionOffset = (hasTarget() ? 1 : 0) +
((hasThis() && !getKind().isTargetSameAsThis()) ? 1 : 0);
if (getKind().argsOnStack()) {
// we move backwards because we're popping off the stack
for (int i = len - 1; i >= 0; i--) {
UnresolvedType type = getArgType(i);
BcelVar tmp = genTempVar(type, "ajc$arg" + i);
range.insert(tmp.createStore(getFactory()), Range.OutsideBefore);
int position = i;
position += positionOffset;
tmp.setPositionInAroundState(position);
argVars[i] = tmp;
}
} else {
int index = 0;
if (arg0HoldsThis()) index++;
for (int i = 0; i < len; i++) {
UnresolvedType type = getArgType(i);
BcelVar tmp = genTempVar(type, "ajc$arg" + i);
range.insert(tmp.createCopyFrom(fact, index), Range.OutsideBefore);
argVars[i] = tmp;
int position = i;
position += positionOffset;
// System.out.println("set position: " + tmp + ", " + position + " in " + this);
// System.out.println(" hasThis: " + hasThis() + ", hasTarget: " + hasTarget());
tmp.setPositionInAroundState(position);
index += type.getSize();
}
}
}
public void initializeForAroundClosure() {
initializeArgVars();
if (hasTarget()) initializeTargetVar();
if (hasThis()) initializeThisVar();
// System.out.println("initialized: " + this + " thisVar = " + thisVar);
}
public void initializeThisAnnotationVars() {
if (thisAnnotationVars != null) return;
thisAnnotationVars = new HashMap();
// populate..
}
public void initializeTargetAnnotationVars() {
if (targetAnnotationVars != null) return;
if (getKind().isTargetSameAsThis()) {
if (hasThis()) initializeThisAnnotationVars();
targetAnnotationVars = thisAnnotationVars;
} else {
targetAnnotationVars = new HashMap();
ResolvedType[] rtx = this.getTargetType().resolve(world).getAnnotationTypes(); // what about annotations we havent gotten yet but we will get in subclasses?
for (int i = 0; i < rtx.length; i++) {
ResolvedType typeX = rtx[i];
targetAnnotationVars.put(typeX,new TypeAnnotationAccessVar(typeX,(BcelVar)getTargetVar()));
}
// populate.
}
}
public void initializeArgAnnotationVars() {
if (argAnnotationVars != null) return;
int numArgs = getArgCount();
argAnnotationVars = new Map[numArgs];
for (int i = 0; i < argAnnotationVars.length; i++) {
argAnnotationVars[i] = new HashMap();
//FIXME asc just delete this logic - we always build the Var on demand, as we don't know at weave time
// what the full set of annotations could be (due to static/dynamic type differences...)
}
}
protected Member getRelevantMember(Member foundMember, Member relevantMember, ResolvedType relevantType){
if (foundMember != null){
return foundMember;
}
foundMember = getSignature().resolve(world);
if (foundMember == null && relevantMember != null) {
foundMember = relevantType.lookupMemberWithSupersAndITDs(relevantMember);
}
// check the ITD'd dooberries
List mungers = relevantType.resolve(world).getInterTypeMungers();
for (Iterator iter = mungers.iterator(); iter.hasNext();) {
BcelTypeMunger typeMunger = (BcelTypeMunger) iter.next();
if (typeMunger.getMunger() instanceof NewMethodTypeMunger ||
typeMunger.getMunger() instanceof NewConstructorTypeMunger) {
ResolvedMember fakerm = typeMunger.getSignature();
if (fakerm.getName().equals(getSignature().getName()) &&
fakerm.getParameterSignature().equals(getSignature().getParameterSignature())){
if (foundMember.getKind()==ResolvedMember.CONSTRUCTOR){
foundMember = AjcMemberMaker.interConstructor(
relevantType,
(ResolvedMember)foundMember,
typeMunger.getAspectType());
} else {
foundMember = AjcMemberMaker.interMethod((ResolvedMember)foundMember,
typeMunger.getAspectType(), false);
}
// in the above.. what about if it's on an Interface? Can that happen?
// then the last arg of the above should be true
return foundMember;
}
}
}
return foundMember;
}
protected ResolvedType [] getAnnotations(Member foundMember, Member relevantMember, ResolvedType relevantType){
if (foundMember == null){
// check the ITD'd dooberries
List mungers = relevantType.resolve(world).getInterTypeMungers();
for (Iterator iter = mungers.iterator(); iter.hasNext();) {
BcelTypeMunger typeMunger = (BcelTypeMunger) iter.next();
if (typeMunger.getMunger() instanceof NewMethodTypeMunger ||
typeMunger.getMunger() instanceof NewConstructorTypeMunger) {
ResolvedMember fakerm = typeMunger.getSignature();
//if (fakerm.hasAnnotations())
ResolvedMember ajcMethod = (getSignature().getKind()==ResolvedMember.CONSTRUCTOR?
AjcMemberMaker.postIntroducedConstructor(typeMunger.getAspectType(),fakerm.getDeclaringType(),fakerm.getParameterTypes()):
AjcMemberMaker.interMethodDispatcher(fakerm,typeMunger.getAspectType()));
//AjcMemberMaker.interMethodBody(fakerm,typeMunger.getAspectType()));
ResolvedMember rmm = findMethod(typeMunger.getAspectType(),ajcMethod);
if (fakerm.getName().equals(getSignature().getName()) &&
fakerm.getParameterSignature().equals(getSignature().getParameterSignature())) {
relevantType = typeMunger.getAspectType();
foundMember = rmm;
return foundMember.getAnnotationTypes();
}
}
}
// didn't find in ITDs, look in supers
foundMember = relevantType.lookupMemberWithSupersAndITDs(relevantMember);
if (foundMember == null) {
throw new IllegalStateException("Couldn't find member " + relevantMember + " for type " + relevantType);
}
}
return foundMember.getAnnotationTypes();
}
public void initializeKindedAnnotationVars() {
if (kindedAnnotationVars != null) return;
kindedAnnotationVars = new HashMap();
// by determining what "kind" of shadow we are, we can find out the
// annotations on the appropriate element (method, field, constructor, type).
// Then create one BcelVar entry in the map for each annotation, keyed by
// annotation type (UnresolvedType).
// FIXME asc Refactor this code, there is duplication
ResolvedType[] annotations = null;
Member relevantMember = getSignature();
ResolvedType relevantType = relevantMember.getDeclaringType().resolve(world);
if (relevantType.isRawType() || relevantType.isParameterizedType()) relevantType = relevantType.getGenericType();
if (getKind() == Shadow.StaticInitialization) {
annotations = relevantType.resolve(world).getAnnotationTypes();
} else if (getKind() == Shadow.MethodCall || getKind() == Shadow.ConstructorCall) {
Member foundMember = findMethod2(relevantType.resolve(world).getDeclaredMethods(),getSignature());
annotations = getAnnotations(foundMember, relevantMember, relevantType);
relevantMember = getRelevantMember(foundMember,relevantMember,relevantType);
relevantType = relevantMember.getDeclaringType().resolve(world);
} else if (getKind() == Shadow.FieldSet || getKind() == Shadow.FieldGet) {
relevantMember = findField(relevantType.getDeclaredFields(),getSignature());
if (relevantMember==null) {
// check the ITD'd dooberries
List mungers = relevantType.resolve(world).getInterTypeMungers();
for (Iterator iter = mungers.iterator(); iter.hasNext();) {
BcelTypeMunger typeMunger = (BcelTypeMunger) iter.next();
if (typeMunger.getMunger() instanceof NewFieldTypeMunger) {
ResolvedMember fakerm = typeMunger.getSignature();
//if (fakerm.hasAnnotations())
ResolvedMember ajcMethod = AjcMemberMaker.interFieldInitializer(fakerm,typeMunger.getAspectType());
ResolvedMember rmm = findMethod(typeMunger.getAspectType(),ajcMethod);
if (fakerm.equals(getSignature())) {
relevantType = typeMunger.getAspectType();
relevantMember = rmm;
}
}
}
}
annotations = relevantMember.getAnnotationTypes();
} else if (getKind() == Shadow.MethodExecution || getKind() == Shadow.ConstructorExecution ||
getKind() == Shadow.AdviceExecution) {
//ResolvedMember rm[] = relevantType.getDeclaredMethods();
Member foundMember = findMethod2(relevantType.getDeclaredMethods(),getSignature());
annotations = getAnnotations(foundMember, relevantMember, relevantType);
relevantMember = foundMember;
relevantMember = getRelevantMember(foundMember, relevantMember,relevantType);
} else if (getKind() == Shadow.ExceptionHandler) {
relevantType = getSignature().getParameterTypes()[0].resolve(world);
annotations = relevantType.getAnnotationTypes();
} else if (getKind() == Shadow.PreInitialization || getKind() == Shadow.Initialization) {
ResolvedMember found = findMethod2(relevantType.getDeclaredMethods(),getSignature());
annotations = found.getAnnotationTypes();
}
if (annotations == null) {
// We can't have recognized the shadow - should blow up now to be on the safe side
throw new BCException("Couldn't discover annotations for shadow: "+getKind());
}
for (int i = 0; i < annotations.length; i++) {
ResolvedType aTX = annotations[i];
KindedAnnotationAccessVar kaav = new KindedAnnotationAccessVar(getKind(),aTX.resolve(world),relevantType,relevantMember);
kindedAnnotationVars.put(aTX,kaav);
}
}
//FIXME asc whats the real diff between this one and the version in findMethod()?
ResolvedMember findMethod2(ResolvedMember rm[], Member sig) {
ResolvedMember found = null;
// String searchString = getSignature().getName()+getSignature().getParameterSignature();
for (int i = 0; i < rm.length && found==null; i++) {
ResolvedMember member = rm[i];
if (member.getName().equals(sig.getName()) && member.getParameterSignature().equals(sig.getParameterSignature()))
found = member;
}
return found;
}
private ResolvedMember findMethod(ResolvedType aspectType, ResolvedMember ajcMethod) {
ResolvedMember decMethods[] = aspectType.getDeclaredMethods();
for (int i = 0; i < decMethods.length; i++) {
ResolvedMember member = decMethods[i];
if (member.equals(ajcMethod)) return member;
}
return null;
}
private ResolvedMember findField(ResolvedMember[] members,Member lookingFor) {
for (int i = 0; i < members.length; i++) {
ResolvedMember member = members[i];
if ( member.getName().equals(getSignature().getName()) &&
member.getType().equals(getSignature().getType())) {
return member;
}
}
return null;
}
public void initializeWithinAnnotationVars() {
if (withinAnnotationVars != null) return;
withinAnnotationVars = new HashMap();
ResolvedType[] annotations = getEnclosingType().resolve(world).getAnnotationTypes();
for (int i = 0; i < annotations.length; i++) {
ResolvedType ann = annotations[i];
Kind k = Shadow.StaticInitialization;
withinAnnotationVars.put(ann,new KindedAnnotationAccessVar(k,ann,getEnclosingType(),null));
}
}
public void initializeWithinCodeAnnotationVars() {
if (withincodeAnnotationVars != null) return;
withincodeAnnotationVars = new HashMap();
// For some shadow we are interested in annotations on the method containing that shadow.
ResolvedType[] annotations = getEnclosingMethod().getMemberView().getAnnotationTypes();
for (int i = 0; i < annotations.length; i++) {
ResolvedType ann = annotations[i];
Kind k = (getEnclosingMethod().getMemberView().getKind()==Member.CONSTRUCTOR?
Shadow.ConstructorExecution:Shadow.MethodExecution);
withincodeAnnotationVars.put(ann,
new KindedAnnotationAccessVar(k,ann,getEnclosingType(),getEnclosingCodeSignature()));
}
}
// ---- weave methods
void weaveBefore(BcelAdvice munger) {
range.insert(
munger.getAdviceInstructions(this, null, range.getRealStart()),
Range.InsideBefore);
}
public void weaveAfter(BcelAdvice munger) {
weaveAfterThrowing(munger, UnresolvedType.THROWABLE);
weaveAfterReturning(munger);
}
/**
* The basic strategy here is to add a set of instructions at the end of
* the shadow range that dispatch the advice, and then return whatever the
* shadow was going to return anyway.
*
* To achieve this, we note all the return statements in the advice, and
* replace them with code that:
* 1) stores the return value on top of the stack in a temp var
* 2) jumps to the start of our advice block
* 3) restores the return value at the end of the advice block before
* ultimately returning
*
* We also need to bind the return value into a returning parameter, if the
* advice specified one.
*/
public void weaveAfterReturning(BcelAdvice munger) {
List returns = findReturnInstructions();
boolean hasReturnInstructions = !returns.isEmpty();
// list of instructions that handle the actual return from the join point
InstructionList retList = new InstructionList();
// variable that holds the return value
BcelVar returnValueVar = null;
if (hasReturnInstructions) {
returnValueVar = generateReturnInstructions(returns,retList);
} else {
// we need at least one instruction, as the target for jumps
retList.append(InstructionConstants.NOP);
}
// list of instructions for dispatching to the advice itself
InstructionList advice = getAfterReturningAdviceDispatchInstructions(
munger, retList.getStart());
if (hasReturnInstructions) {
InstructionHandle gotoTarget = advice.getStart();
for (Iterator i = returns.iterator(); i.hasNext();) {
InstructionHandle ih = (InstructionHandle) i.next();
retargetReturnInstruction(munger.hasExtraParameter(), returnValueVar, gotoTarget, ih);
}
}
range.append(advice);
range.append(retList);
}
/**
* @return a list of all the return instructions in the range of this shadow
*/
private List findReturnInstructions() {
List returns = new ArrayList();
for (InstructionHandle ih = range.getStart(); ih != range.getEnd(); ih = ih.getNext()) {
if (ih.getInstruction() instanceof ReturnInstruction) {
returns.add(ih);
}
}
return returns;
}
/**
* Given a list containing all the return instruction handles for this shadow,
* finds the last return instruction and copies it, making this the ultimate
* return. If the shadow has a non-void return type, we also create a temporary
* variable to hold the return value, and load the value from this var before
* returning (see pr148007 for why we do this - it works around a JRockit bug,
* and is also closer to what javac generates)
* @param returns list of all the return instructions in the shadow
* @param returnInstructions instruction list into which the return instructions should
* be generated
* @return the variable holding the return value, if needed
*/
private BcelVar generateReturnInstructions(List returns, InstructionList returnInstructions) {
BcelVar returnValueVar = null;
InstructionHandle lastReturnHandle = (InstructionHandle)returns.get(returns.size() - 1);
Instruction newReturnInstruction = Utility.copyInstruction(lastReturnHandle.getInstruction());
if (this.hasANonVoidReturnType()) {
returnValueVar = genTempVar(this.getReturnType());
returnValueVar.appendLoad(returnInstructions,getFactory());
} else {
returnInstructions.append(newReturnInstruction);
}
returnInstructions.append(newReturnInstruction);
return returnValueVar;
}
/**
* @return true, iff this shadow returns a value
*/
private boolean hasANonVoidReturnType() {
return this.getReturnType() != ResolvedType.VOID;
}
/**
* Get the list of instructions used to dispatch to the after advice
* @param munger
* @param firstInstructionInReturnSequence
* @return
*/
private InstructionList getAfterReturningAdviceDispatchInstructions(BcelAdvice munger, InstructionHandle firstInstructionInReturnSequence) {
InstructionList advice = new InstructionList();
BcelVar tempVar = null;
if (munger.hasExtraParameter()) {
tempVar = insertAdviceInstructionsForBindingReturningParameter(advice);
}
advice.append(munger.getAdviceInstructions(this, tempVar, firstInstructionInReturnSequence));
return advice;
}
/**
* If the after() returning(Foo f) form is used, bind the return value to the parameter.
* If the shadow returns void, bind null.
* @param advice
* @return
*/
private BcelVar insertAdviceInstructionsForBindingReturningParameter(InstructionList advice) {
BcelVar tempVar;
UnresolvedType tempVarType = getReturnType();
if (tempVarType.equals(ResolvedType.VOID)) {
tempVar = genTempVar(UnresolvedType.OBJECT);
advice.append(InstructionConstants.ACONST_NULL);
tempVar.appendStore(advice, getFactory());
} else {
tempVar = genTempVar(tempVarType);
advice.append(InstructionFactory.createDup(tempVarType.getSize()));
tempVar.appendStore(advice, getFactory());
}
return tempVar;
}
/**
* Helper method for weaveAfterReturning
*
* Each return instruction in the method body is retargeted by calling this method.
* The return instruction is replaced by up to three instructions:
* 1) if the shadow returns a value, and that value is bound to an after returning
* parameter, then we DUP the return value on the top of the stack
* 2) if the shadow returns a value, we store it in the returnValueVar (it will
* be retrieved from here when we ultimately return after the advice dispatch)
* 3) if the return was the last instruction, we add a NOP (it will fall through
* to the advice dispatch), otherwise we add a GOTO that branches to the
* supplied gotoTarget (start of the advice dispatch)
*/
private void retargetReturnInstruction(boolean hasReturningParameter, BcelVar returnValueVar, InstructionHandle gotoTarget, InstructionHandle returnHandle) {
// pr148007, work around JRockit bug
// replace ret with store into returnValueVar, followed by goto if not
// at the end of the instruction list...
InstructionList newInstructions = new InstructionList();
if (returnValueVar != null) {
if (hasReturningParameter) {
// we have to dup the return val before consuming it...
newInstructions.append(InstructionFactory.createDup(this.getReturnType().getSize()));
}
// store the return value into this var
returnValueVar.appendStore(newInstructions,getFactory());
}
if (!isLastInstructionInRange(returnHandle,range)) {
newInstructions.append(InstructionFactory.createBranchInstruction(
Constants.GOTO,
gotoTarget));
}
if (newInstructions.isEmpty()) {
newInstructions.append(InstructionConstants.NOP);
}
Utility.replaceInstruction(returnHandle,newInstructions,enclosingMethod);
}
private boolean isLastInstructionInRange(InstructionHandle ih, ShadowRange aRange) {
return ih.getNext() == aRange.getEnd();
}
public void weaveAfterThrowing(BcelAdvice munger, UnresolvedType catchType) {
// a good optimization would be not to generate anything here
// if the shadow is GUARANTEED empty (i.e., there's NOTHING, not even
// a shadow, inside me).
if (getRange().getStart().getNext() == getRange().getEnd()) return;
InstructionFactory fact = getFactory();
InstructionList handler = new InstructionList();
BcelVar exceptionVar = genTempVar(catchType);
exceptionVar.appendStore(handler, fact);
// pr62642
// I will now jump through some firey BCEL hoops to generate a trivial bit of code:
// if (exc instanceof ExceptionInInitializerError)
// throw (ExceptionInInitializerError)exc;
if (this.getEnclosingMethod().getName().equals("<clinit>")) {
ResolvedType eiieType = world.resolve("java.lang.ExceptionInInitializerError");
ObjectType eiieBcelType = (ObjectType)BcelWorld.makeBcelType(eiieType);
InstructionList ih = new InstructionList(InstructionConstants.NOP);
handler.append(exceptionVar.createLoad(fact));
handler.append(fact.createInstanceOf(eiieBcelType));
BranchInstruction bi =
InstructionFactory.createBranchInstruction(Constants.IFEQ,ih.getStart());
handler.append(bi);
handler.append(exceptionVar.createLoad(fact));
handler.append(fact.createCheckCast(eiieBcelType));
handler.append(InstructionConstants.ATHROW);
handler.append(ih);
}
InstructionList endHandler = new InstructionList(
exceptionVar.createLoad(fact));
handler.append(munger.getAdviceInstructions(this, exceptionVar, endHandler.getStart()));
handler.append(endHandler);
handler.append(InstructionConstants.ATHROW);
InstructionHandle handlerStart = handler.getStart();
if (isFallsThrough()) {
InstructionHandle jumpTarget = handler.append(InstructionConstants.NOP);
handler.insert(InstructionFactory.createBranchInstruction(Constants.GOTO, jumpTarget));
}
InstructionHandle protectedEnd = handler.getStart();
range.insert(handler, Range.InsideAfter);
enclosingMethod.addExceptionHandler(range.getStart().getNext(), protectedEnd.getPrev(),
handlerStart, (ObjectType)BcelWorld.makeBcelType(catchType), //???Type.THROWABLE,
// high priority if our args are on the stack
getKind().hasHighPriorityExceptions());
}
//??? this shares a lot of code with the above weaveAfterThrowing
//??? would be nice to abstract that to say things only once
public void weaveSoftener(BcelAdvice munger, UnresolvedType catchType) {
// a good optimization would be not to generate anything here
// if the shadow is GUARANTEED empty (i.e., there's NOTHING, not even
// a shadow, inside me).
if (getRange().getStart().getNext() == getRange().getEnd()) return;
InstructionFactory fact = getFactory();
InstructionList handler = new InstructionList();
InstructionList rtExHandler = new InstructionList();
BcelVar exceptionVar = genTempVar(catchType);
handler.append(fact.createNew(NameMangler.SOFT_EXCEPTION_TYPE));
handler.append(InstructionFactory.createDup(1));
handler.append(exceptionVar.createLoad(fact));
handler.append(fact.createInvoke(NameMangler.SOFT_EXCEPTION_TYPE, "<init>",
Type.VOID, new Type[] { Type.THROWABLE }, Constants.INVOKESPECIAL)); //??? special
handler.append(InstructionConstants.ATHROW);
// ENH 42737
exceptionVar.appendStore(rtExHandler, fact);
// aload_1
rtExHandler.append(exceptionVar.createLoad(fact));
// instanceof class java/lang/RuntimeException
rtExHandler.append(fact.createInstanceOf(new ObjectType("java.lang.RuntimeException")));
// ifeq go to new SOFT_EXCEPTION_TYPE instruction
rtExHandler.append(InstructionFactory.createBranchInstruction(Constants.IFEQ,handler.getStart()));
// aload_1
rtExHandler.append(exceptionVar.createLoad(fact));
// athrow
rtExHandler.append(InstructionFactory.ATHROW);
InstructionHandle handlerStart = rtExHandler.getStart();
if (isFallsThrough()) {
InstructionHandle jumpTarget = range.getEnd();//handler.append(fact.NOP);
rtExHandler.insert(InstructionFactory.createBranchInstruction(Constants.GOTO, jumpTarget));
}
rtExHandler.append(handler);
InstructionHandle protectedEnd = rtExHandler.getStart();
range.insert(rtExHandler, Range.InsideAfter);
enclosingMethod.addExceptionHandler(range.getStart().getNext(), protectedEnd.getPrev(),
handlerStart, (ObjectType)BcelWorld.makeBcelType(catchType),
// high priority if our args are on the stack
getKind().hasHighPriorityExceptions());
}
public void weavePerObjectEntry(final BcelAdvice munger, final BcelVar onVar) {
final InstructionFactory fact = getFactory();
InstructionList entryInstructions = new InstructionList();
InstructionList entrySuccessInstructions = new InstructionList();
onVar.appendLoad(entrySuccessInstructions, fact);
entrySuccessInstructions.append(
Utility.createInvoke(fact, world,
AjcMemberMaker.perObjectBind(munger.getConcreteAspect())));
InstructionList testInstructions =
munger.getTestInstructions(this, entrySuccessInstructions.getStart(),
range.getRealStart(),
entrySuccessInstructions.getStart());
entryInstructions.append(testInstructions);
entryInstructions.append(entrySuccessInstructions);
range.insert(entryInstructions, Range.InsideBefore);
}
// PTWIMPL Create static initializer to call the aspect factory
/**
* Causes the aspect instance to be *set* for later retrievable through localAspectof()/aspectOf()
*/
public void weavePerTypeWithinAspectInitialization(final BcelAdvice munger,UnresolvedType t) {
if (t.resolve(world).isInterface()) return; // Don't initialize statics in
final InstructionFactory fact = getFactory();
InstructionList entryInstructions = new InstructionList();
InstructionList entrySuccessInstructions = new InstructionList();
BcelWorld.getBcelObjectType(munger.getConcreteAspect());
String aspectname = munger.getConcreteAspect().getName();
String ptwField = NameMangler.perTypeWithinFieldForTarget(munger.getConcreteAspect());
entrySuccessInstructions.append(new PUSH(fact.getConstantPool(),t.getName()));
entrySuccessInstructions.append(fact.createInvoke(aspectname,"ajc$createAspectInstance",new ObjectType(aspectname),
new Type[]{new ObjectType("java.lang.String")},Constants.INVOKESTATIC));
entrySuccessInstructions.append(fact.createPutStatic(t.getName(),ptwField,
new ObjectType(aspectname)));
entryInstructions.append(entrySuccessInstructions);
range.insert(entryInstructions, Range.InsideBefore);
}
public void weaveCflowEntry(final BcelAdvice munger, final Member cflowField) {
final boolean isPer = munger.getKind() == AdviceKind.PerCflowBelowEntry ||
munger.getKind() == AdviceKind.PerCflowEntry;
final Type objectArrayType = new ArrayType(Type.OBJECT, 1);
final InstructionFactory fact = getFactory();
final BcelVar testResult = genTempVar(ResolvedType.BOOLEAN);
InstructionList entryInstructions = new InstructionList();
{
InstructionList entrySuccessInstructions = new InstructionList();
if (munger.hasDynamicTests()) {
entryInstructions.append(Utility.createConstant(fact, 0));
testResult.appendStore(entryInstructions, fact);
entrySuccessInstructions.append(Utility.createConstant(fact, 1));
testResult.appendStore(entrySuccessInstructions, fact);
}
if (isPer) {
entrySuccessInstructions.append(
fact.createInvoke(munger.getConcreteAspect().getName(),
NameMangler.PERCFLOW_PUSH_METHOD,
Type.VOID,
new Type[] { },
Constants.INVOKESTATIC));
} else {
BcelVar[] cflowStateVars = munger.getExposedStateAsBcelVars(false);
if (cflowStateVars.length == 0) {
// This should be getting managed by a counter - lets make sure.
if (!cflowField.getType().getName().endsWith("CFlowCounter"))
throw new RuntimeException("Incorrectly attempting counter operation on stacked cflow");
entrySuccessInstructions.append(
Utility.createGet(fact, cflowField));
//arrayVar.appendLoad(entrySuccessInstructions, fact);
entrySuccessInstructions.append(fact.createInvoke(NameMangler.CFLOW_COUNTER_TYPE,"inc",Type.VOID,new Type[] { },Constants.INVOKEVIRTUAL));
} else {
BcelVar arrayVar = genTempVar(UnresolvedType.OBJECTARRAY);
int alen = cflowStateVars.length;
entrySuccessInstructions.append(Utility.createConstant(fact, alen));
entrySuccessInstructions.append(
(Instruction) fact.createNewArray(Type.OBJECT, (short) 1));
arrayVar.appendStore(entrySuccessInstructions, fact);
for (int i = 0; i < alen; i++) {
arrayVar.appendConvertableArrayStore(
entrySuccessInstructions,
fact,
i,
cflowStateVars[i]);
}
entrySuccessInstructions.append(
Utility.createGet(fact, cflowField));
arrayVar.appendLoad(entrySuccessInstructions, fact);
entrySuccessInstructions.append(
fact.createInvoke(NameMangler.CFLOW_STACK_TYPE, "push", Type.VOID,
new Type[] { objectArrayType },
Constants.INVOKEVIRTUAL));
}
}
InstructionList testInstructions =
munger.getTestInstructions(this, entrySuccessInstructions.getStart(),
range.getRealStart(),
entrySuccessInstructions.getStart());
entryInstructions.append(testInstructions);
entryInstructions.append(entrySuccessInstructions);
}
// this is the same for both per and non-per
weaveAfter(new BcelAdvice(null, null, null, 0, 0, 0, null, null) {
public InstructionList getAdviceInstructions(
BcelShadow s,
BcelVar extraArgVar,
InstructionHandle ifNoAdvice) {
InstructionList exitInstructions = new InstructionList();
if (munger.hasDynamicTests()) {
testResult.appendLoad(exitInstructions, fact);
exitInstructions.append(
InstructionFactory.createBranchInstruction(
Constants.IFEQ,
ifNoAdvice));
}
exitInstructions.append(Utility.createGet(fact, cflowField));
if (munger.getKind() != AdviceKind.PerCflowEntry &&
munger.getKind() != AdviceKind.PerCflowBelowEntry &&
munger.getExposedStateAsBcelVars(false).length==0) {
exitInstructions
.append(
fact
.createInvoke(
NameMangler.CFLOW_COUNTER_TYPE,
"dec",
Type.VOID,
new Type[] {
}, Constants.INVOKEVIRTUAL));
} else {
exitInstructions
.append(
fact
.createInvoke(
NameMangler.CFLOW_STACK_TYPE,
"pop",
Type.VOID,
new Type[] {
}, Constants.INVOKEVIRTUAL));
}
return exitInstructions;
}
});
range.insert(entryInstructions, Range.InsideBefore);
}
/* Implementation notes:
*
* AroundInline still extracts the instructions of the original shadow into
* an extracted method. This allows inlining of even that advice that doesn't
* call proceed or calls proceed more than once.
*
* It extracts the instructions of the original shadow into a method.
*
* Then it extracts the instructions of the advice into a new method defined on
* this enclosing class. This new method can then be specialized as below.
*
* Then it searches in the instructions of the advice for any call to the
* proceed method.
*
* At such a call, there is stuff on the stack representing the arguments to
* proceed. Pop these into the frame.
*
* Now build the stack for the call to the extracted method, taking values
* either from the join point state or from the new frame locs from proceed.
* Now call the extracted method. The right return value should be on the
* stack, so no cast is necessary.
*
* If only one call to proceed is made, we can re-inline the original shadow.
* We are not doing that presently.
*
* If the body of the advice can be determined to not alter the stack, or if
* this shadow doesn't care about the stack, i.e. method-execution, then the
* new method for the advice can also be re-lined. We are not doing that
* presently.
*/
public void weaveAroundInline(BcelAdvice munger,boolean hasDynamicTest) {
// !!! THIS BLOCK OF CODE SHOULD BE IN A METHOD CALLED weaveAround(...);
Member mungerSig = munger.getSignature();
//Member originalSig = mungerSig; // If mungerSig is on a parameterized type, originalSig is the member on the generic type
if (mungerSig instanceof ResolvedMember) {
ResolvedMember rm = (ResolvedMember)mungerSig;
if (rm.hasBackingGenericMember()) mungerSig = rm.getBackingGenericMember();
}
ResolvedType declaringType = world.resolve(mungerSig.getDeclaringType(),true);
if (declaringType.isMissing()) {
world.getLint().cantFindType.signal(
new String[] {WeaverMessages.format(WeaverMessages.CANT_FIND_TYPE_DURING_AROUND_WEAVE,declaringType.getClassName())},
getSourceLocation(),
new ISourceLocation[]{ munger.getSourceLocation()}
);
// IMessage msg = new Message(
// WeaverMessages.format(WeaverMessages.CANT_FIND_TYPE_DURING_AROUND_WEAVE,declaringType.getClassName()),
// "",IMessage.ERROR,getSourceLocation(),null,
// new ISourceLocation[]{ munger.getSourceLocation()});
// world.getMessageHandler().handleMessage(msg);
}
//??? might want some checks here to give better errors
ResolvedType rt = (declaringType.isParameterizedType()?declaringType.getGenericType():declaringType);
BcelObjectType ot = BcelWorld.getBcelObjectType(rt);
// if (ot==null) {
// world.getMessageHandler().handleMessage(
// MessageUtil.warn("Unable to find modifiable delegate for the aspect '"+rt.getName()+"' containing around advice - cannot implement inlining",munger.getSourceLocation()));
// weaveAroundClosure(munger, hasDynamicTest);
// return;
// }
LazyMethodGen adviceMethod = ot.getLazyClassGen().getLazyMethodGen(mungerSig);
if (!adviceMethod.getCanInline()) {
weaveAroundClosure(munger, hasDynamicTest);
return;
}
// specific test for @AJ proceedInInners
if (munger.getConcreteAspect().isAnnotationStyleAspect()) {
// if we can't find one proceed() we suspect that the call
// is happening in an inner class so we don't inline it.
// Note: for code style, this is done at Aspect compilation time.
boolean canSeeProceedPassedToOther = false;
InstructionHandle curr = adviceMethod.getBody().getStart();
InstructionHandle end = adviceMethod.getBody().getEnd();
ConstantPoolGen cpg = adviceMethod.getEnclosingClass().getConstantPoolGen();
while (curr != end) {
InstructionHandle next = curr.getNext();
Instruction inst = curr.getInstruction();
if ((inst instanceof InvokeInstruction)
&& ((InvokeInstruction)inst).getSignature(cpg).indexOf("Lorg/aspectj/lang/ProceedingJoinPoint;") > 0) {
// we may want to refine to exclude stuff returning jp ?
// does code style skip inline if i write dump(thisJoinPoint) ?
canSeeProceedPassedToOther = true;// we see one pjp passed around - dangerous
break;
}
curr = next;
}
if (canSeeProceedPassedToOther) {
// remember this decision to avoid re-analysis
adviceMethod.setCanInline(false);
weaveAroundClosure(munger, hasDynamicTest);
return;
}
}
// We can't inline around methods if they have around advice on them, this
// is because the weaving will extract the body and hence the proceed call.
//??? should consider optimizations to recognize simple cases that don't require body extraction
enclosingMethod.setCanInline(false);
// start by exposing various useful things into the frame
final InstructionFactory fact = getFactory();
// now generate the aroundBody method
// eg. "private static final void method_aroundBody0(M, M, String, org.aspectj.lang.JoinPoint)"
LazyMethodGen extractedMethod =
extractMethod(
NameMangler.aroundCallbackMethodName(getSignature(),getEnclosingClass()),
Modifier.PRIVATE,
munger);
// now extract the advice into its own method
String adviceMethodName =
NameMangler.aroundCallbackMethodName(getSignature(),getEnclosingClass()) + "$advice";
List argVarList = new ArrayList();
List proceedVarList = new ArrayList();
int extraParamOffset = 0;
// Create the extra parameters that are needed for passing to proceed
// This code is very similar to that found in makeCallToCallback and should
// be rationalized in the future
if (thisVar != null) {
argVarList.add(thisVar);
proceedVarList.add(new BcelVar(thisVar.getType(), extraParamOffset));
extraParamOffset += thisVar.getType().getSize();
}
if (targetVar != null && targetVar != thisVar) {
argVarList.add(targetVar);
proceedVarList.add(new BcelVar(targetVar.getType(), extraParamOffset));
extraParamOffset += targetVar.getType().getSize();
}
for (int i = 0, len = getArgCount(); i < len; i++) {
argVarList.add(argVars[i]);
proceedVarList.add(new BcelVar(argVars[i].getType(), extraParamOffset));
extraParamOffset += argVars[i].getType().getSize();
}
if (thisJoinPointVar != null) {
argVarList.add(thisJoinPointVar);
proceedVarList.add(new BcelVar(thisJoinPointVar.getType(), extraParamOffset));
extraParamOffset += thisJoinPointVar.getType().getSize();
}
Type[] adviceParameterTypes = adviceMethod.getArgumentTypes();
Type[] extractedMethodParameterTypes = extractedMethod.getArgumentTypes();
Type[] parameterTypes =
new Type[extractedMethodParameterTypes.length
+ adviceParameterTypes.length
+ 1];
int parameterIndex = 0;
System.arraycopy(
extractedMethodParameterTypes,
0,
parameterTypes,
parameterIndex,
extractedMethodParameterTypes.length);
parameterIndex += extractedMethodParameterTypes.length;
parameterTypes[parameterIndex++] =
BcelWorld.makeBcelType(adviceMethod.getEnclosingClass().getType());
System.arraycopy(
adviceParameterTypes,
0,
parameterTypes,
parameterIndex,
adviceParameterTypes.length);
LazyMethodGen localAdviceMethod =
new LazyMethodGen(
Modifier.PRIVATE | Modifier.FINAL | Modifier.STATIC,
BcelWorld.makeBcelType(mungerSig.getReturnType()),
adviceMethodName,
parameterTypes,
new String[0],
getEnclosingClass());
String donorFileName = adviceMethod.getEnclosingClass().getInternalFileName();
String recipientFileName = getEnclosingClass().getInternalFileName();
// System.err.println("donor " + donorFileName);
// System.err.println("recip " + recipientFileName);
if (! donorFileName.equals(recipientFileName)) {
localAdviceMethod.fromFilename = donorFileName;
getEnclosingClass().addInlinedSourceFileInfo(
donorFileName,
adviceMethod.highestLineNumber);
}
getEnclosingClass().addMethodGen(localAdviceMethod);
// create a map that will move all slots in advice method forward by extraParamOffset
// in order to make room for the new proceed-required arguments that are added at
// the beginning of the parameter list
int nVars = adviceMethod.getMaxLocals() + extraParamOffset;
IntMap varMap = IntMap.idMap(nVars);
for (int i=extraParamOffset; i < nVars; i++) {
varMap.put(i-extraParamOffset, i);
}
localAdviceMethod.getBody().insert(
BcelClassWeaver.genInlineInstructions(adviceMethod,
localAdviceMethod, varMap, fact, true));
localAdviceMethod.setMaxLocals(nVars);
//System.err.println(localAdviceMethod);
// the shadow is now empty. First, create a correct call
// to the around advice. This includes both the call (which may involve
// value conversion of the advice arguments) and the return
// (which may involve value conversion of the return value). Right now
// we push a null for the unused closure. It's sad, but there it is.
InstructionList advice = new InstructionList();
// InstructionHandle adviceMethodInvocation;
{
for (Iterator i = argVarList.iterator(); i.hasNext(); ) {
BcelVar var = (BcelVar)i.next();
var.appendLoad(advice, fact);
}
// ??? we don't actually need to push NULL for the closure if we take care
advice.append(
munger.getAdviceArgSetup(
this,
null,
(munger.getConcreteAspect().isAnnotationStyleAspect() && munger.getDeclaringAspect()!=null && munger.getDeclaringAspect().resolve(world).isAnnotationStyleAspect())?
this.loadThisJoinPoint():
new InstructionList(InstructionConstants.ACONST_NULL)));
// adviceMethodInvocation =
advice.append(
Utility.createInvoke(fact, localAdviceMethod)); //(fact, getWorld(), munger.getSignature()));
advice.append(
Utility.createConversion(
getFactory(),
BcelWorld.makeBcelType(mungerSig.getReturnType()),
extractedMethod.getReturnType(),world.isInJava5Mode()));
if (! isFallsThrough()) {
advice.append(InstructionFactory.createReturn(extractedMethod.getReturnType()));
}
}
// now, situate the call inside the possible dynamic tests,
// and actually add the whole mess to the shadow
if (! hasDynamicTest) {
range.append(advice);
} else {
InstructionList afterThingie = new InstructionList(InstructionConstants.NOP);
InstructionList callback = makeCallToCallback(extractedMethod);
if (terminatesWithReturn()) {
callback.append(
InstructionFactory.createReturn(extractedMethod.getReturnType()));
} else {
//InstructionHandle endNop = range.insert(fact.NOP, Range.InsideAfter);
advice.append(
InstructionFactory.createBranchInstruction(
Constants.GOTO,
afterThingie.getStart()));
}
range.append(
munger.getTestInstructions(
this,
advice.getStart(),
callback.getStart(),
advice.getStart()));
range.append(advice);
range.append(callback);
range.append(afterThingie);
}
// now search through the advice, looking for a call to PROCEED.
// Then we replace the call to proceed with some argument setup, and a
// call to the extracted method.
// inlining support for code style aspects
if (!munger.getConcreteAspect().isAnnotationStyleAspect()) {
String proceedName =
NameMangler.proceedMethodName(munger.getSignature().getName());
InstructionHandle curr = localAdviceMethod.getBody().getStart();
InstructionHandle end = localAdviceMethod.getBody().getEnd();
ConstantPoolGen cpg = localAdviceMethod.getEnclosingClass().getConstantPoolGen();
while (curr != end) {
InstructionHandle next = curr.getNext();
Instruction inst = curr.getInstruction();
if ((inst instanceof INVOKESTATIC)
&& proceedName.equals(((INVOKESTATIC) inst).getMethodName(cpg))) {
localAdviceMethod.getBody().append(
curr,
getRedoneProceedCall(
fact,
extractedMethod,
munger,
localAdviceMethod,
proceedVarList));
Utility.deleteInstruction(curr, localAdviceMethod);
}
curr = next;
}
// and that's it.
} else {
//ATAJ inlining support for @AJ aspects
// [TODO document @AJ code rule: don't manipulate 2 jps proceed at the same time.. in an advice body]
InstructionHandle curr = localAdviceMethod.getBody().getStart();
InstructionHandle end = localAdviceMethod.getBody().getEnd();
ConstantPoolGen cpg = localAdviceMethod.getEnclosingClass().getConstantPoolGen();
while (curr != end) {
InstructionHandle next = curr.getNext();
Instruction inst = curr.getInstruction();
if ((inst instanceof INVOKEINTERFACE)
&& "proceed".equals(((INVOKEINTERFACE) inst).getMethodName(cpg))) {
final boolean isProceedWithArgs;
if (((INVOKEINTERFACE) inst).getArgumentTypes(cpg).length == 1) {
// proceed with args as a boxed Object[]
isProceedWithArgs = true;
} else {
isProceedWithArgs = false;
}
InstructionList insteadProceedIl = getRedoneProceedCallForAnnotationStyle(
fact,
extractedMethod,
munger,
localAdviceMethod,
proceedVarList,
isProceedWithArgs
);
localAdviceMethod.getBody().append(curr, insteadProceedIl);
Utility.deleteInstruction(curr, localAdviceMethod);
}
curr = next;
}
}
}
private InstructionList getRedoneProceedCall(
InstructionFactory fact,
LazyMethodGen callbackMethod,
BcelAdvice munger,
LazyMethodGen localAdviceMethod,
List argVarList)
{
InstructionList ret = new InstructionList();
// we have on stack all the arguments for the ADVICE call.
// we have in frame somewhere all the arguments for the non-advice call.
BcelVar[] adviceVars = munger.getExposedStateAsBcelVars(true);
IntMap proceedMap = makeProceedArgumentMap(adviceVars);
// System.out.println(proceedMap + " for " + this);
// System.out.println(argVarList);
ResolvedType[] proceedParamTypes =
world.resolve(munger.getSignature().getParameterTypes());
// remove this*JoinPoint* as arguments to proceed
if (munger.getBaseParameterCount()+1 < proceedParamTypes.length) {
int len = munger.getBaseParameterCount()+1;
ResolvedType[] newTypes = new ResolvedType[len];
System.arraycopy(proceedParamTypes, 0, newTypes, 0, len);
proceedParamTypes = newTypes;
}
//System.out.println("stateTypes: " + Arrays.asList(stateTypes));
BcelVar[] proceedVars =
Utility.pushAndReturnArrayOfVars(proceedParamTypes, ret, fact, localAdviceMethod);
Type[] stateTypes = callbackMethod.getArgumentTypes();
// System.out.println("stateTypes: " + Arrays.asList(stateTypes));
for (int i=0, len=stateTypes.length; i < len; i++) {
Type stateType = stateTypes[i];
ResolvedType stateTypeX = BcelWorld.fromBcel(stateType).resolve(world);
if (proceedMap.hasKey(i)) {
//throw new RuntimeException("unimplemented");
proceedVars[proceedMap.get(i)].appendLoadAndConvert(ret, fact, stateTypeX);
} else {
((BcelVar) argVarList.get(i)).appendLoad(ret, fact);
}
}
ret.append(Utility.createInvoke(fact, callbackMethod));
ret.append(Utility.createConversion(fact, callbackMethod.getReturnType(),
BcelWorld.makeBcelType(munger.getSignature().getReturnType())));
return ret;
}
private static boolean bindsThisOrTarget(Pointcut pointcut) {
ThisTargetFinder visitor = new ThisTargetFinder();
pointcut.accept(visitor, null);
return visitor.bindsThisOrTarget;
}
private static class ThisTargetFinder extends IdentityPointcutVisitor {
boolean bindsThisOrTarget = false;
public Object visit(ThisOrTargetPointcut node, Object data) {
if (node.isBinding()) {
bindsThisOrTarget = true;
}
return node;
}
public Object visit(AndPointcut node, Object data) {
if (!bindsThisOrTarget) node.getLeft().accept(this, data);
if (!bindsThisOrTarget) node.getRight().accept(this, data);
return node;
}
public Object visit(NotPointcut node, Object data) {
if (!bindsThisOrTarget) node.getNegatedPointcut().accept(this, data);
return node;
}
public Object visit(OrPointcut node, Object data) {
if (!bindsThisOrTarget) node.getLeft().accept(this, data);
if (!bindsThisOrTarget) node.getRight().accept(this, data);
return node;
}
}
/**
* ATAJ Handle the inlining for @AJ aspects
*
*/
private InstructionList getRedoneProceedCallForAnnotationStyle(
InstructionFactory fact,
LazyMethodGen callbackMethod,
BcelAdvice munger,
LazyMethodGen localAdviceMethod,
List argVarList,
boolean isProceedWithArgs)
{
// Notes:
// proceedingjp is on stack (since user was calling pjp.proceed(...)
// new Object[]{new Integer(argAdvice1-1)};// arg of proceed
// call to proceed(..) is NOT made
// instead we do
// itar callback args i
// get from array i, convert it to the callback arg i
// if ask for JP, push the one we got on the stack
// invoke callback, create conversion back to Object/Integer
// rest of method -- (hence all those conversions)
// intValue() from original code
// int res = .. from original code
//Note: we just don't care about the proceed map etc
// (we would need to care if we allow repositioning of arguments in advice signature)
InstructionList ret = new InstructionList();
// store the Object[] array on stack if proceed with args
if (isProceedWithArgs) {
// STORE the Object[] into a local variable
Type objectArrayType = Type.getType("[Ljava/lang/Object;");
int localProceedArgArray = localAdviceMethod.allocateLocal(objectArrayType);
ret.append(InstructionFactory.createStore(objectArrayType, localProceedArgArray));
// STORE the ProceedingJoinPoint instance into a local variable
Type proceedingJpType = Type.getType("Lorg/aspectj/lang/ProceedingJoinPoint;");
int localJp = localAdviceMethod.allocateLocal(proceedingJpType);
ret.append(InstructionFactory.createStore(proceedingJpType, localJp));
// push on stack each element of the object array
// that is assumed to be consistent with the callback argument (ie munger args)
// TODO do we want to try catch ClassCast and AOOBE exception ?
// special logic when withincode is static or not
// This next bit of code probably makes more sense if you read its implementation for
// weaveAroundClosure() - see JoinPointImpl.proceed(Object[]). Basically depending
// on whether the join point has a this/target and whether the pointcut binds this/target
// then the arguments to the 'new' proceed call need to be reorganized. (pr126167)
boolean relatedPointcutBindsThis = bindsThis(munger);
boolean relatedPointcutBindsTarget = bindsTarget(munger);
boolean targetIsSameAsThis = getKind().isTargetSameAsThis();
// two numbers can differ because a pointcut may bind both this/target and yet at the
// join point this and target are the same (eg. call)
int indexIntoObjectArrayForArguments=0;
int indexIntoCallbackMethodForArguments = 0;
if (hasThis()) {
if (relatedPointcutBindsThis) {
if (!(relatedPointcutBindsTarget && targetIsSameAsThis)) {
// they have supplied new this as first entry in object array
ret.append(InstructionFactory.createLoad(objectArrayType, localProceedArgArray));
ret.append(Utility.createConstant(fact, 0));
ret.append(InstructionFactory.createArrayLoad(Type.OBJECT));
ret.append(Utility.createConversion(fact,Type.OBJECT,callbackMethod.getArgumentTypes()[0]));
indexIntoCallbackMethodForArguments++;
}
indexIntoObjectArrayForArguments=1;
} else {
// use local variable 0 (which is 'this' for a non-static method)
ret.append(new ALOAD(0));
indexIntoCallbackMethodForArguments++;
}
}
if (hasTarget()) {
if (relatedPointcutBindsTarget) {
if (getKind().isTargetSameAsThis()) {
ret.append(InstructionFactory.createLoad(objectArrayType, localProceedArgArray));
ret.append(Utility.createConstant(fact, relatedPointcutBindsThis?1:0));
ret.append(InstructionFactory.createArrayLoad(Type.OBJECT));
ret.append(Utility.createConversion(fact,Type.OBJECT,callbackMethod.getArgumentTypes()[0]));
indexIntoObjectArrayForArguments++;
indexIntoCallbackMethodForArguments++;
} else {
int position =(hasThis()&& relatedPointcutBindsThis?1:0);
ret.append(InstructionFactory.createLoad(objectArrayType, localProceedArgArray));
ret.append(Utility.createConstant(fact, position));
ret.append(InstructionFactory.createArrayLoad(Type.OBJECT));
ret.append(Utility.createConversion(fact,Type.OBJECT,callbackMethod.getArgumentTypes()[position]));
indexIntoObjectArrayForArguments=position+1;
indexIntoCallbackMethodForArguments++;
}
} else {
if (getKind().isTargetSameAsThis()) {
//ret.append(new ALOAD(0));
} else {
ret.append(InstructionFactory.createLoad(localAdviceMethod.getArgumentTypes()[0],hasThis()?1:0));
indexIntoCallbackMethodForArguments++;
}
}
}
for (int i = indexIntoCallbackMethodForArguments, len=callbackMethod.getArgumentTypes().length; i < len; i++) {
Type stateType = callbackMethod.getArgumentTypes()[i];
BcelWorld.fromBcel(stateType).resolve(world);
if ("Lorg/aspectj/lang/JoinPoint;".equals(stateType.getSignature())) {
ret.append(new ALOAD(localJp));// from localAdvice signature
} else {
ret.append(InstructionFactory.createLoad(objectArrayType, localProceedArgArray));
ret.append(Utility.createConstant(fact, i-indexIntoCallbackMethodForArguments +indexIntoObjectArrayForArguments));
ret.append(InstructionFactory.createArrayLoad(Type.OBJECT));
ret.append(Utility.createConversion(
fact,
Type.OBJECT,
stateType
));
}
}
} else {
Type proceedingJpType = Type.getType("Lorg/aspectj/lang/ProceedingJoinPoint;");
int localJp = localAdviceMethod.allocateLocal(proceedingJpType);
ret.append(InstructionFactory.createStore(proceedingJpType, localJp));
for (int i = 0, len=callbackMethod.getArgumentTypes().length; i < len; i++) {
Type stateType = callbackMethod.getArgumentTypes()[i];
/*ResolvedType stateTypeX =*/
BcelWorld.fromBcel(stateType).resolve(world);
if ("Lorg/aspectj/lang/JoinPoint;".equals(stateType.getSignature())) {
ret.append(new ALOAD(localJp));// from localAdvice signature
// } else if ("Lorg/aspectj/lang/ProceedingJoinPoint;".equals(stateType.getSignature())) {
// //FIXME ALEX?
// ret.append(new ALOAD(localJp));// from localAdvice signature
//// ret.append(fact.createCheckCast(
//// (ReferenceType) BcelWorld.makeBcelType(stateTypeX)
//// ));
// // cast ?
//
} else {
ret.append(InstructionFactory.createLoad(stateType, i));
}
}
}
// do the callback invoke
ret.append(Utility.createInvoke(fact, callbackMethod));
// box it again. Handles cases where around advice does return something else than Object
if (!UnresolvedType.OBJECT.equals(munger.getSignature().getReturnType())) {
ret.append(Utility.createConversion(
fact,
callbackMethod.getReturnType(),
Type.OBJECT
));
}
ret.append(Utility.createConversion(
fact,
callbackMethod.getReturnType(),
BcelWorld.makeBcelType(munger.getSignature().getReturnType())
));
return ret;
//
//
//
// if (proceedMap.hasKey(i)) {
// ret.append(new ALOAD(i));
// //throw new RuntimeException("unimplemented");
// //proceedVars[proceedMap.get(i)].appendLoadAndConvert(ret, fact, stateTypeX);
// } else {
// //((BcelVar) argVarList.get(i)).appendLoad(ret, fact);
// //ret.append(new ALOAD(i));
// if ("Lorg/aspectj/lang/JoinPoint;".equals(stateType.getSignature())) {
// ret.append(new ALOAD(i));
// } else {
// ret.append(new ALOAD(i));
// }
// }
// }
//
// ret.append(Utility.createInvoke(fact, callbackMethod));
// ret.append(Utility.createConversion(fact, callbackMethod.getReturnType(),
// BcelWorld.makeBcelType(munger.getSignature().getReturnType())));
//
// //ret.append(new ACONST_NULL());//will be POPed
// if (true) return ret;
//
//
//
// // we have on stack all the arguments for the ADVICE call.
// // we have in frame somewhere all the arguments for the non-advice call.
//
// BcelVar[] adviceVars = munger.getExposedStateAsBcelVars();
// IntMap proceedMap = makeProceedArgumentMap(adviceVars);
//
// System.out.println(proceedMap + " for " + this);
// System.out.println(argVarList);
//
// ResolvedType[] proceedParamTypes =
// world.resolve(munger.getSignature().getParameterTypes());
// // remove this*JoinPoint* as arguments to proceed
// if (munger.getBaseParameterCount()+1 < proceedParamTypes.length) {
// int len = munger.getBaseParameterCount()+1;
// ResolvedType[] newTypes = new ResolvedType[len];
// System.arraycopy(proceedParamTypes, 0, newTypes, 0, len);
// proceedParamTypes = newTypes;
// }
//
// //System.out.println("stateTypes: " + Arrays.asList(stateTypes));
// BcelVar[] proceedVars =
// Utility.pushAndReturnArrayOfVars(proceedParamTypes, ret, fact, localAdviceMethod);
//
// Type[] stateTypes = callbackMethod.getArgumentTypes();
//// System.out.println("stateTypes: " + Arrays.asList(stateTypes));
//
// for (int i=0, len=stateTypes.length; i < len; i++) {
// Type stateType = stateTypes[i];
// ResolvedType stateTypeX = BcelWorld.fromBcel(stateType).resolve(world);
// if (proceedMap.hasKey(i)) {
// //throw new RuntimeException("unimplemented");
// proceedVars[proceedMap.get(i)].appendLoadAndConvert(ret, fact, stateTypeX);
// } else {
// ((BcelVar) argVarList.get(i)).appendLoad(ret, fact);
// }
// }
//
// ret.append(Utility.createInvoke(fact, callbackMethod));
// ret.append(Utility.createConversion(fact, callbackMethod.getReturnType(),
// BcelWorld.makeBcelType(munger.getSignature().getReturnType())));
// return ret;
}
private boolean bindsThis(BcelAdvice munger) {
UsesThisVisitor utv = new UsesThisVisitor();
munger.getPointcut().accept(utv, null);
return utv.usesThis;
}
private boolean bindsTarget(BcelAdvice munger) {
UsesTargetVisitor utv = new UsesTargetVisitor();
munger.getPointcut().accept(utv, null);
return utv.usesTarget;
}
private static class UsesThisVisitor extends IdentityPointcutVisitor {
boolean usesThis = false;
public Object visit(ThisOrTargetPointcut node, Object data) {
if (node.isThis() && node.isBinding()) usesThis=true;
return node;
}
public Object visit(AndPointcut node, Object data) {
if (!usesThis) node.getLeft().accept(this, data);
if (!usesThis) node.getRight().accept(this, data);
return node;
}
public Object visit(NotPointcut node, Object data) {
if (!usesThis) node.getNegatedPointcut().accept(this, data);
return node;
}
public Object visit(OrPointcut node, Object data) {
if (!usesThis) node.getLeft().accept(this, data);
if (!usesThis) node.getRight().accept(this, data);
return node;
}
}
private static class UsesTargetVisitor extends IdentityPointcutVisitor {
boolean usesTarget = false;
public Object visit(ThisOrTargetPointcut node, Object data) {
if (!node.isThis() && node.isBinding()) usesTarget=true;
return node;
}
public Object visit(AndPointcut node, Object data) {
if (!usesTarget) node.getLeft().accept(this, data);
if (!usesTarget) node.getRight().accept(this, data);
return node;
}
public Object visit(NotPointcut node, Object data) {
if (!usesTarget) node.getNegatedPointcut().accept(this, data);
return node;
}
public Object visit(OrPointcut node, Object data) {
if (!usesTarget) node.getLeft().accept(this, data);
if (!usesTarget) node.getRight().accept(this, data);
return node;
}
}
public void weaveAroundClosure(BcelAdvice munger, boolean hasDynamicTest) {
InstructionFactory fact = getFactory();
enclosingMethod.setCanInline(false);
// MOVE OUT ALL THE INSTRUCTIONS IN MY SHADOW INTO ANOTHER METHOD!
LazyMethodGen callbackMethod =
extractMethod(
NameMangler.aroundCallbackMethodName(
getSignature(),
getEnclosingClass()),
0,
munger);
BcelVar[] adviceVars = munger.getExposedStateAsBcelVars(true);
String closureClassName =
NameMangler.makeClosureClassName(
getEnclosingClass().getType(),
getEnclosingClass().getNewGeneratedNameTag());
Member constructorSig = new MemberImpl(Member.CONSTRUCTOR,
UnresolvedType.forName(closureClassName), 0, "<init>",
"([Ljava/lang/Object;)V");
BcelVar closureHolder = null;
// This is not being used currently since getKind() == preinitializaiton
// cannot happen in around advice
if (getKind() == PreInitialization) {
closureHolder = genTempVar(AjcMemberMaker.AROUND_CLOSURE_TYPE);
}
InstructionList closureInstantiation =
makeClosureInstantiation(constructorSig, closureHolder);
/*LazyMethodGen constructor = */
makeClosureClassAndReturnConstructor(
closureClassName,
callbackMethod,
makeProceedArgumentMap(adviceVars)
);
InstructionList returnConversionCode;
if (getKind() == PreInitialization) {
returnConversionCode = new InstructionList();
BcelVar stateTempVar = genTempVar(UnresolvedType.OBJECTARRAY);
closureHolder.appendLoad(returnConversionCode, fact);
returnConversionCode.append(
Utility.createInvoke(
fact,
world,
AjcMemberMaker.aroundClosurePreInitializationGetter()));
stateTempVar.appendStore(returnConversionCode, fact);
Type[] stateTypes = getSuperConstructorParameterTypes();
returnConversionCode.append(InstructionConstants.ALOAD_0); // put "this" back on the stack
for (int i = 0, len = stateTypes.length; i < len; i++) {
UnresolvedType bcelTX = BcelWorld.fromBcel(stateTypes[i]);
ResolvedType stateRTX = world.resolve(bcelTX,true);
if (stateRTX.isMissing()) {
world.getLint().cantFindType.signal(
new String[] {WeaverMessages.format(WeaverMessages.CANT_FIND_TYPE_DURING_AROUND_WEAVE_PREINIT,bcelTX.getClassName())},
getSourceLocation(),
new ISourceLocation[]{ munger.getSourceLocation()}
);
// IMessage msg = new Message(
// WeaverMessages.format(WeaverMessages.CANT_FIND_TYPE_DURING_AROUND_WEAVE_PREINIT,bcelTX.getClassName()),
// "",IMessage.ERROR,getSourceLocation(),null,
// new ISourceLocation[]{ munger.getSourceLocation()});
// world.getMessageHandler().handleMessage(msg);
}
stateTempVar.appendConvertableArrayLoad(
returnConversionCode,
fact,
i,
stateRTX);
}
} else {
returnConversionCode =
Utility.createConversion(
getFactory(),
BcelWorld.makeBcelType(munger.getSignature().getReturnType()),
callbackMethod.getReturnType(),world.isInJava5Mode());
if (!isFallsThrough()) {
returnConversionCode.append(
InstructionFactory.createReturn(callbackMethod.getReturnType()));
}
}
// initialize the bit flags for this shadow
int bitflags =0x000000;
if (getKind().isTargetSameAsThis()) bitflags|=0x010000;
if (hasThis()) bitflags|=0x001000;
if (bindsThis(munger)) bitflags|=0x000100;
if (hasTarget()) bitflags|=0x000010;
if (bindsTarget(munger)) bitflags|=0x000001;
// ATAJ for @AJ aspect we need to link the closure with the joinpoint instance
if (munger.getConcreteAspect()!=null && munger.getConcreteAspect().isAnnotationStyleAspect()
&& munger.getDeclaringAspect()!=null && munger.getDeclaringAspect().resolve(world).isAnnotationStyleAspect()) {
// stick the bitflags on the stack and call the variant of linkClosureAndJoinPoint that takes an int
closureInstantiation.append(fact.createConstant(new Integer(bitflags)));
closureInstantiation.append(Utility.createInvoke(
getFactory(),
getWorld(),
new MemberImpl(
Member.METHOD,
UnresolvedType.forName("org.aspectj.runtime.internal.AroundClosure"),
Modifier.PUBLIC,
"linkClosureAndJoinPoint",
"(I)Lorg/aspectj/lang/ProceedingJoinPoint;"
)
));
}
InstructionList advice = new InstructionList();
advice.append(munger.getAdviceArgSetup(this, null, closureInstantiation));
// invoke the advice
advice.append(munger.getNonTestAdviceInstructions(this));
advice.append(returnConversionCode);
if (!hasDynamicTest) {
range.append(advice);
} else {
InstructionList callback = makeCallToCallback(callbackMethod);
InstructionList postCallback = new InstructionList();
if (terminatesWithReturn()) {
callback.append(
InstructionFactory.createReturn(callbackMethod.getReturnType()));
} else {
advice.append(
InstructionFactory.createBranchInstruction(
Constants.GOTO,
postCallback.append(InstructionConstants.NOP)));
}
range.append(
munger.getTestInstructions(
this,
advice.getStart(),
callback.getStart(),
advice.getStart()));
range.append(advice);
range.append(callback);
range.append(postCallback);
}
}
// exposed for testing
InstructionList makeCallToCallback(LazyMethodGen callbackMethod) {
InstructionFactory fact = getFactory();
InstructionList callback = new InstructionList();
if (thisVar != null) {
callback.append(InstructionConstants.ALOAD_0);
}
if (targetVar != null && targetVar != thisVar) {
callback.append(BcelRenderer.renderExpr(fact, world, targetVar));
}
callback.append(BcelRenderer.renderExprs(fact, world, argVars));
// remember to render tjps
if (thisJoinPointVar != null) {
callback.append(BcelRenderer.renderExpr(fact, world, thisJoinPointVar));
}
callback.append(Utility.createInvoke(fact, callbackMethod));
return callback;
}
/** side-effect-free */
private InstructionList makeClosureInstantiation(Member constructor, BcelVar holder) {
// LazyMethodGen constructor) {
InstructionFactory fact = getFactory();
BcelVar arrayVar = genTempVar(UnresolvedType.OBJECTARRAY);
//final Type objectArrayType = new ArrayType(Type.OBJECT, 1);
final InstructionList il = new InstructionList();
int alen = getArgCount() + (thisVar == null ? 0 : 1) +
((targetVar != null && targetVar != thisVar) ? 1 : 0) +
(thisJoinPointVar == null ? 0 : 1);
il.append(Utility.createConstant(fact, alen));
il.append((Instruction)fact.createNewArray(Type.OBJECT, (short)1));
arrayVar.appendStore(il, fact);
int stateIndex = 0;
if (thisVar != null) {
arrayVar.appendConvertableArrayStore(il, fact, stateIndex, thisVar);
thisVar.setPositionInAroundState(stateIndex);
stateIndex++;
}
if (targetVar != null && targetVar != thisVar) {
arrayVar.appendConvertableArrayStore(il, fact, stateIndex, targetVar);
targetVar.setPositionInAroundState(stateIndex);
stateIndex++;
}
for (int i = 0, len = getArgCount(); i<len; i++) {
arrayVar.appendConvertableArrayStore(il, fact, stateIndex, argVars[i]);
argVars[i].setPositionInAroundState(stateIndex);
stateIndex++;
}
if (thisJoinPointVar != null) {
arrayVar.appendConvertableArrayStore(il, fact, stateIndex, thisJoinPointVar);
thisJoinPointVar.setPositionInAroundState(stateIndex);
stateIndex++;
}
il.append(fact.createNew(new ObjectType(constructor.getDeclaringType().getName())));
il.append(new DUP());
arrayVar.appendLoad(il, fact);
il.append(Utility.createInvoke(fact, world, constructor));
if (getKind() == PreInitialization) {
il.append(InstructionConstants.DUP);
holder.appendStore(il, fact);
}
return il;
}
private IntMap makeProceedArgumentMap(BcelVar[] adviceArgs) {
//System.err.println("coming in with " + Arrays.asList(adviceArgs));
IntMap ret = new IntMap();
for(int i = 0, len = adviceArgs.length; i < len; i++) {
BcelVar v = (BcelVar) adviceArgs[i];
if (v == null) continue; // XXX we don't know why this is required
int pos = v.getPositionInAroundState();
if (pos >= 0) { // need this test to avoid args bound via cflow
ret.put(pos, i);
}
}
//System.err.println("returning " + ret);
return ret;
}
/**
*
*
* @param callbackMethod the method we will call back to when our run method gets called.
*
* @param proceedMap A map from state position to proceed argument position. May be
* non covering on state position.
*/
private LazyMethodGen makeClosureClassAndReturnConstructor(
String closureClassName,
LazyMethodGen callbackMethod,
IntMap proceedMap)
{
String superClassName = "org.aspectj.runtime.internal.AroundClosure";
Type objectArrayType = new ArrayType(Type.OBJECT, 1);
LazyClassGen closureClass = new LazyClassGen(closureClassName,
superClassName,
getEnclosingClass().getFileName(),
Modifier.PUBLIC,
new String[] {},
getWorld());
InstructionFactory fact = new InstructionFactory(closureClass.getConstantPoolGen());
// constructor
LazyMethodGen constructor = new LazyMethodGen(Modifier.PUBLIC,
Type.VOID,
"<init>",
new Type[] {objectArrayType},
new String[] {},
closureClass);
InstructionList cbody = constructor.getBody();
cbody.append(InstructionFactory.createLoad(Type.OBJECT, 0));
cbody.append(InstructionFactory.createLoad(objectArrayType, 1));
cbody.append(fact.createInvoke(superClassName, "<init>", Type.VOID,
new Type[] {objectArrayType}, Constants.INVOKESPECIAL));
cbody.append(InstructionFactory.createReturn(Type.VOID));
closureClass.addMethodGen(constructor);
// method
LazyMethodGen runMethod = new LazyMethodGen(Modifier.PUBLIC,
Type.OBJECT,
"run",
new Type[] {objectArrayType},
new String[] {},
closureClass);
InstructionList mbody = runMethod.getBody();
BcelVar proceedVar = new BcelVar(UnresolvedType.OBJECTARRAY.resolve(world), 1);
// int proceedVarIndex = 1;
BcelVar stateVar =
new BcelVar(UnresolvedType.OBJECTARRAY.resolve(world), runMethod.allocateLocal(1));
// int stateVarIndex = runMethod.allocateLocal(1);
mbody.append(InstructionFactory.createThis());
mbody.append(fact.createGetField(superClassName, "state", objectArrayType));
mbody.append(stateVar.createStore(fact));
// mbody.append(fact.createStore(objectArrayType, stateVarIndex));
Type[] stateTypes = callbackMethod.getArgumentTypes();
for (int i=0, len=stateTypes.length; i < len; i++) {
Type stateType = stateTypes[i];
ResolvedType stateTypeX = BcelWorld.fromBcel(stateType).resolve(world);
if (proceedMap.hasKey(i)) {
mbody.append(
proceedVar.createConvertableArrayLoad(fact, proceedMap.get(i),
stateTypeX));
} else {
mbody.append(
stateVar.createConvertableArrayLoad(fact, i,
stateTypeX));
}
}
mbody.append(Utility.createInvoke(fact, callbackMethod));
if (getKind() == PreInitialization) {
mbody.append(Utility.createSet(
fact,
AjcMemberMaker.aroundClosurePreInitializationField()));
mbody.append(InstructionConstants.ACONST_NULL);
} else {
mbody.append(
Utility.createConversion(
fact,
callbackMethod.getReturnType(),
Type.OBJECT));
}
mbody.append(InstructionFactory.createReturn(Type.OBJECT));
closureClass.addMethodGen(runMethod);
// class
getEnclosingClass().addGeneratedInner(closureClass);
return constructor;
}
// ---- extraction methods
public LazyMethodGen extractMethod(String newMethodName, int visibilityModifier, ShadowMunger munger) {
LazyMethodGen.assertGoodBody(range.getBody(), newMethodName);
if (!getKind().allowsExtraction()) throw new BCException("Attempt to extract method from a shadow kind that does not support this operation (" + getKind() + ")");
LazyMethodGen freshMethod = createMethodGen(newMethodName,visibilityModifier);
// System.err.println("******");
// System.err.println("ABOUT TO EXTRACT METHOD for" + this);
// enclosingMethod.print(System.err);
// System.err.println("INTO");
// freshMethod.print(System.err);
// System.err.println("WITH REMAP");
// System.err.println(makeRemap());
range.extractInstructionsInto(freshMethod, makeRemap(),
(getKind() != PreInitialization) &&
isFallsThrough());
if (getKind() == PreInitialization) {
addPreInitializationReturnCode(
freshMethod,
getSuperConstructorParameterTypes());
}
getEnclosingClass().addMethodGen(freshMethod,munger.getSourceLocation());
return freshMethod;
}
private void addPreInitializationReturnCode(
LazyMethodGen extractedMethod,
Type[] superConstructorTypes)
{
InstructionList body = extractedMethod.getBody();
final InstructionFactory fact = getFactory();
BcelVar arrayVar = new BcelVar(
world.getCoreType(UnresolvedType.OBJECTARRAY),
extractedMethod.allocateLocal(1));
int len = superConstructorTypes.length;
body.append(Utility.createConstant(fact, len));
body.append((Instruction)fact.createNewArray(Type.OBJECT, (short)1));
arrayVar.appendStore(body, fact);
for (int i = len - 1; i >= 0; i++) {
// convert thing on top of stack to object
body.append(
Utility.createConversion(fact, superConstructorTypes[i], Type.OBJECT));
// push object array
arrayVar.appendLoad(body, fact);
// swap
body.append(InstructionConstants.SWAP);
// do object array store.
body.append(Utility.createConstant(fact, i));
body.append(InstructionConstants.SWAP);
body.append(InstructionFactory.createArrayStore(Type.OBJECT));
}
arrayVar.appendLoad(body, fact);
body.append(InstructionConstants.ARETURN);
}
private Type[] getSuperConstructorParameterTypes() {
// assert getKind() == PreInitialization
InstructionHandle superCallHandle = getRange().getEnd().getNext();
InvokeInstruction superCallInstruction =
(InvokeInstruction) superCallHandle.getInstruction();
return superCallInstruction.getArgumentTypes(
getEnclosingClass().getConstantPoolGen());
}
/** make a map from old frame location to new frame location. Any unkeyed frame
* location picks out a copied local */
private IntMap makeRemap() {
IntMap ret = new IntMap(5);
int reti = 0;
if (thisVar != null) {
ret.put(0, reti++); // thisVar guaranteed to be 0
}
if (targetVar != null && targetVar != thisVar) {
ret.put(targetVar.getSlot(), reti++);
}
for (int i = 0, len = argVars.length; i < len; i++) {
ret.put(argVars[i].getSlot(), reti);
reti += argVars[i].getType().getSize();
}
if (thisJoinPointVar != null) {
ret.put(thisJoinPointVar.getSlot(), reti++);
}
// we not only need to put the arguments, we also need to remap their
// aliases, which we so helpfully put into temps at the beginning of this join
// point.
if (! getKind().argsOnStack()) {
int oldi = 0;
int newi = 0;
// if we're passing in a this and we're not argsOnStack we're always
// passing in a target too
if (arg0HoldsThis()) { ret.put(0, 0); oldi++; newi+=1; }
//assert targetVar == thisVar
for (int i = 0; i < getArgCount(); i++) {
UnresolvedType type = getArgType(i);
ret.put(oldi, newi);
oldi += type.getSize();
newi += type.getSize();
}
}
// System.err.println("making remap for : " + this);
// if (targetVar != null) System.err.println("target slot : " + targetVar.getSlot());
// if (thisVar != null) System.err.println(" this slot : " + thisVar.getSlot());
// System.err.println(ret);
return ret;
}
/**
* The new method always static.
* It may take some extra arguments: this, target.
* If it's argsOnStack, then it must take both this/target
* If it's argsOnFrame, it shares this and target.
* ??? rewrite this to do less array munging, please
*/
private LazyMethodGen createMethodGen(String newMethodName, int visibilityModifier) {
Type[] parameterTypes = BcelWorld.makeBcelTypes(getArgTypes());
int modifiers = Modifier.FINAL | visibilityModifier;
// XXX some bug
// if (! isExpressionKind() && getSignature().isStrict(world)) {
// modifiers |= Modifier.STRICT;
// }
modifiers |= Modifier.STATIC;
if (targetVar != null && targetVar != thisVar) {
UnresolvedType targetType = getTargetType();
targetType = ensureTargetTypeIsCorrect(targetType);
// see pr109728 - this fixes the case when the declaring class is sometype 'X' but the getfield
// in the bytecode refers to a subtype of 'X'. This makes sure we use the type originally
// mentioned in the fieldget instruction as the method parameter and *not* the type upon which the
// field is declared because when the instructions are extracted into the new around body,
// they will still refer to the subtype.
if (getKind()==FieldGet && getActualTargetType()!=null &&
!getActualTargetType().equals(targetType.getName())) {
targetType = UnresolvedType.forName(getActualTargetType()).resolve(world);
}
ResolvedMember resolvedMember = getSignature().resolve(world);
if (resolvedMember != null && Modifier.isProtected(resolvedMember.getModifiers()) &&
!samePackage(targetType.getPackageName(), getEnclosingType().getPackageName()) &&
!resolvedMember.getName().equals("clone"))
{
if (!targetType.resolve(world).isAssignableFrom(getThisType().resolve(world))) {
throw new BCException("bad bytecode");
}
targetType = getThisType();
}
parameterTypes = addType(BcelWorld.makeBcelType(targetType), parameterTypes);
}
if (thisVar != null) {
UnresolvedType thisType = getThisType();
parameterTypes = addType(BcelWorld.makeBcelType(thisType), parameterTypes);
}
// We always want to pass down thisJoinPoint in case we have already woven
// some advice in here. If we only have a single piece of around advice on a
// join point, it is unnecessary to accept (and pass) tjp.
if (thisJoinPointVar != null) {
parameterTypes = addTypeToEnd(LazyClassGen.tjpType, parameterTypes);
//FIXME ALEX? which one
//parameterTypes = addTypeToEnd(LazyClassGen.proceedingTjpType, parameterTypes);
}
UnresolvedType returnType;
if (getKind() == PreInitialization) {
returnType = UnresolvedType.OBJECTARRAY;
} else {
if (getKind() == ConstructorCall) returnType = getSignature().getDeclaringType();
else if (getKind() == FieldSet) returnType = ResolvedType.VOID;
else returnType = getSignature().getReturnType().resolve(world);
// returnType = getReturnType(); // for this and above lines, see pr137496
}
return
new LazyMethodGen(
modifiers,
BcelWorld.makeBcelType(returnType),
newMethodName,
parameterTypes,
new String[0],
// XXX again, we need to look up methods!
// UnresolvedType.getNames(getSignature().getExceptions(world)),
getEnclosingClass());
}
private boolean samePackage(String p1, String p2) {
if (p1 == null) return p2 == null;
if (p2 == null) return false;
return p1.equals(p2);
}
private Type[] addType(Type type, Type[] types) {
int len = types.length;
Type[] ret = new Type[len+1];
ret[0] = type;
System.arraycopy(types, 0, ret, 1, len);
return ret;
}
private Type[] addTypeToEnd(Type type, Type[] types) {
int len = types.length;
Type[] ret = new Type[len+1];
ret[len] = type;
System.arraycopy(types, 0, ret, 0, len);
return ret;
}
public BcelVar genTempVar(UnresolvedType typeX) {
return new BcelVar(typeX.resolve(world), genTempVarIndex(typeX.getSize()));
}
// public static final boolean CREATE_TEMP_NAMES = true;
public BcelVar genTempVar(UnresolvedType typeX, String localName) {
BcelVar tv = genTempVar(typeX);
// if (CREATE_TEMP_NAMES) {
// for (InstructionHandle ih = range.getStart(); ih != range.getEnd(); ih = ih.getNext()) {
// if (Range.isRangeHandle(ih)) continue;
// ih.addTargeter(new LocalVariableTag(typeX, localName, tv.getSlot()));
// }
// }
return tv;
}
// eh doesn't think we need to garbage collect these (64K is a big number...)
private int genTempVarIndex(int size) {
return enclosingMethod.allocateLocal(size);
}
public InstructionFactory getFactory() {
return getEnclosingClass().getFactory();
}
public ISourceLocation getSourceLocation() {
int sourceLine = getSourceLine();
if (sourceLine == 0 || sourceLine == -1) {
// Thread.currentThread().dumpStack();
// System.err.println(this + ": " + range);
return getEnclosingClass().getType().getSourceLocation();
} else {
// For staticinitialization, if we have a nice offset, don't build a new source loc
if (getKind()==Shadow.StaticInitialization && getEnclosingClass().getType().getSourceLocation().getOffset()!=0) {
return getEnclosingClass().getType().getSourceLocation();
} else {
int offset = 0;
Kind kind = getKind();
if ( (kind == MethodExecution) ||
(kind == ConstructorExecution) ||
(kind == AdviceExecution) ||
(kind == StaticInitialization) ||
(kind == PreInitialization) ||
(kind == Initialization)) {
if (getEnclosingMethod().hasDeclaredLineNumberInfo()) {
offset = getEnclosingMethod().getDeclarationOffset();
}
}
return getEnclosingClass().getType().getSourceContext().makeSourceLocation(sourceLine, offset);
}
}
}
public Shadow getEnclosingShadow() {
return enclosingShadow;
}
public LazyMethodGen getEnclosingMethod() {
return enclosingMethod;
}
public boolean isFallsThrough() {
return !terminatesWithReturn(); //fallsThrough;
}
public void setActualTargetType(String className) {
this.actualInstructionTargetType = className;
}
public String getActualTargetType() {
return actualInstructionTargetType;
}
}
|
151,978 |
Bug 151978 [3.2compiler] Generics program fails to compile
|
generics problem, reported on newsgroup by Thomas Darimont //package de.tutorials.aspectj; public interface IMessage { void publish(); } interface IErrorMessage extends IMessage{ StackTraceElement[] getStackTrace(); } interface IObjectFactory<E> { public <T extends E> T create(Class<T> theObjectType, Object[] theParameters); } class MessageFactory implements IObjectFactory<IMessage>{ public <T extends IMessage> T create(Class<T> theObjectType, Object[] theParameters) { return null; } } class Main { public static void main(String[] args) { IErrorMessage message = new MessageFactory().create(IErrorMessage.class, new Object[]{"Foo","Bar"}); } }
|
resolved fixed
|
68c36e3
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-07-28T13:17:57Z | 2006-07-27T11:33:20Z |
tests/bugs153/pr151978/IMessage.java
| |
151,978 |
Bug 151978 [3.2compiler] Generics program fails to compile
|
generics problem, reported on newsgroup by Thomas Darimont //package de.tutorials.aspectj; public interface IMessage { void publish(); } interface IErrorMessage extends IMessage{ StackTraceElement[] getStackTrace(); } interface IObjectFactory<E> { public <T extends E> T create(Class<T> theObjectType, Object[] theParameters); } class MessageFactory implements IObjectFactory<IMessage>{ public <T extends IMessage> T create(Class<T> theObjectType, Object[] theParameters) { return null; } } class Main { public static void main(String[] args) { IErrorMessage message = new MessageFactory().create(IErrorMessage.class, new Object[]{"Foo","Bar"}); } }
|
resolved fixed
|
68c36e3
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-07-28T13:17:57Z | 2006-07-27T11:33:20Z |
tests/src/org/aspectj/systemtest/ajc153/Ajc153Tests.java
|
/*******************************************************************************
* Copyright (c) 2006 IBM
* 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.ajc153;
import java.io.File;
import junit.framework.Test;
import org.aspectj.testing.Utils;
import org.aspectj.testing.XMLBasedAjcTestCase;
public class Ajc153Tests extends org.aspectj.testing.XMLBasedAjcTestCase {
public void testMissingLineNumbersInStacktraceBefore_pr145442() { runTest("missing line numbers in stacktrace before");}
public void testMissingLineNumbersInStacktraceAfter_pr145442() { runTest("missing line numbers in stacktrace after");}
public void testMissingLineNumbersInStacktraceAround_pr145442() { runTest("missing line numbers in stacktrace around");}
// public void testArgnamesAndJavac_pr148381() { runTest("argNames and javac");}
// public void testCFlowXMLAspectLTW_pr149096() { runTest("cflow xml concrete aspect"); }
// public void testAmbiguousBinding_pr121805() { runTest("ambiguous binding");}
public void testGenericInheritanceDecp_pr150095() { runTest("generics, inheritance and decp");}
public void testIllegalStateException_pr148737() { runTest("illegalstateexception for non generic type");}
public void testAtajInheritance_pr149305_1() { runTest("ataj inheritance - 1");}
public void testAtajInheritance_pr149305_2() { runTest("ataj inheritance - 2");}
public void testAtajInheritance_pr149305_3() { runTest("ataj inheritance - 3");}
public void testVerificationFailureForAspectOf_pr148693() {
runTest("verification problem"); // build the code
Utils.verifyClass(ajc,"mypackage.MyAspect"); // verify it <<< BRAND NEW VERIFY UTILITY FOR EVERYONE TO TRY ;)
}
public void testIncorrectAnnotationValue_pr148537() { runTest("incorrect annotation value");}
public void testVerifyErrNoTypeCflowField_pr145693_1() { runTest("verifyErrNoTypeCflowField"); }
public void testVerifyErrInpathNoTypeCflowField_pr145693_2() { runTest("verifyErrInpathNoTypeCflowField"); }
public void testCpathNoTypeCflowField_pr145693_3() { runTest("cpathNoTypeCflowField"); }
// public void testVisibilityProblem_pr149071() { runTest("visibility problem");}
// public void testAdviceNotWovenAspectPath_pr147841() { runTest("advice not woven on aspectpath");}
public void testGenericSignatures_pr148409() { runTest("generic signature problem"); }
// public void testBrokenIfArgsCflowAtAj_pr145018() { runTest("ataj crashing with cflow, if and args");}
public void testCantFindType_pr149322_01() {runTest("can't find type on interface call 1");}
public void testCantFindType_pr149322_02() {runTest("can't find type on interface call 2");}
public void testCantFindType_pr149322_03() {runTest("can't find type on interface call 3");}
public void testMatchVolatileField_pr150671() {runTest("match volatile field");};
/////////////////////////////////////////
public static Test suite() {
return XMLBasedAjcTestCase.loadSuite(Ajc153Tests.class);
}
protected File getSpecFile() {
return new File("../tests/src/org/aspectj/systemtest/ajc153/ajc153.xml");
}
}
|
151,938 |
Bug 151938 Handle Duplicate -javaagent entries more gracefully
|
If you start a java 5 VM with AspectJ's load-time weaver specified more than once using the -javaagent flag, if there is an aop.xml file defined, it chokes badly: it tries to reweave the woven AspectJ code and emits massive amounts of bytecode. It would be better if AspectJ detected that it was specified more than once and gave a warning then disabled all but one of the agents. Failing that, it would be better to fail and give an error message than emit the bytecode. This issue came up for our automated installer, which adds a -javaagent flag to VM startup commands. If the script is wrapped twice, it can generate a duplicate. We are making our scripts more intelligent to avoid this issue, but we are probably not the only people who will hit this issue (e.g., if someone manually edits both setclasspath.bat and catalina.bat to add the flag for a Tomcat instance...)
|
resolved fixed
|
bebb364
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-08-01T20:41:52Z | 2006-07-27T00:26:40Z |
loadtime5/java5-src/org/aspectj/weaver/loadtime/Agent.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.instrument.Instrumentation;
import java.lang.instrument.ClassFileTransformer;
/**
* Java 1.5 preMain agent to hook in the class pre processor
* Can be used with -javaagent:aspectjweaver.jar
*
* @author <a href="mailto:[email protected]">Alexandre Vasseur</a>
*/
public class Agent {
/**
* The instrumentation instance
*/
private static Instrumentation s_instrumentation;
/**
* The ClassFileTransformer wrapping the weaver
*/
private static ClassFileTransformer s_transformer = new ClassPreProcessorAgentAdapter();
/**
* JSR-163 preMain Agent entry method
*
* @param options
* @param instrumentation
*/
public static void premain(String options, Instrumentation instrumentation) {
s_instrumentation = instrumentation;
s_instrumentation.addTransformer(s_transformer);
}
/**
* Returns the Instrumentation system level instance
*/
public static Instrumentation getInstrumentation() {
if (s_instrumentation == null) {
throw new UnsupportedOperationException("Java 5 was not started with preMain -javaagent for AspectJ");
}
return s_instrumentation;
}
}
|
151,938 |
Bug 151938 Handle Duplicate -javaagent entries more gracefully
|
If you start a java 5 VM with AspectJ's load-time weaver specified more than once using the -javaagent flag, if there is an aop.xml file defined, it chokes badly: it tries to reweave the woven AspectJ code and emits massive amounts of bytecode. It would be better if AspectJ detected that it was specified more than once and gave a warning then disabled all but one of the agents. Failing that, it would be better to fail and give an error message than emit the bytecode. This issue came up for our automated installer, which adds a -javaagent flag to VM startup commands. If the script is wrapped twice, it can generate a duplicate. We are making our scripts more intelligent to avoid this issue, but we are probably not the only people who will hit this issue (e.g., if someone manually edits both setclasspath.bat and catalina.bat to add the flag for a Tomcat instance...)
|
resolved fixed
|
bebb364
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-08-01T20:41:52Z | 2006-07-27T00:26:40Z |
tests/java5/ataspectj/HelloWorld.java
| |
151,938 |
Bug 151938 Handle Duplicate -javaagent entries more gracefully
|
If you start a java 5 VM with AspectJ's load-time weaver specified more than once using the -javaagent flag, if there is an aop.xml file defined, it chokes badly: it tries to reweave the woven AspectJ code and emits massive amounts of bytecode. It would be better if AspectJ detected that it was specified more than once and gave a warning then disabled all but one of the agents. Failing that, it would be better to fail and give an error message than emit the bytecode. This issue came up for our automated installer, which adds a -javaagent flag to VM startup commands. If the script is wrapped twice, it can generate a duplicate. We are making our scripts more intelligent to avoid this issue, but we are probably not the only people who will hit this issue (e.g., if someone manually edits both setclasspath.bat and catalina.bat to add the flag for a Tomcat instance...)
|
resolved fixed
|
bebb364
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-08-01T20:41:52Z | 2006-07-27T00:26:40Z |
tests/java5/ataspectj/MessageHandler.java
| |
151,938 |
Bug 151938 Handle Duplicate -javaagent entries more gracefully
|
If you start a java 5 VM with AspectJ's load-time weaver specified more than once using the -javaagent flag, if there is an aop.xml file defined, it chokes badly: it tries to reweave the woven AspectJ code and emits massive amounts of bytecode. It would be better if AspectJ detected that it was specified more than once and gave a warning then disabled all but one of the agents. Failing that, it would be better to fail and give an error message than emit the bytecode. This issue came up for our automated installer, which adds a -javaagent flag to VM startup commands. If the script is wrapped twice, it can generate a duplicate. We are making our scripts more intelligent to avoid this issue, but we are probably not the only people who will hit this issue (e.g., if someone manually edits both setclasspath.bat and catalina.bat to add the flag for a Tomcat instance...)
|
resolved fixed
|
bebb364
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-08-01T20:41:52Z | 2006-07-27T00:26:40Z |
tests/src/org/aspectj/systemtest/ajc153/Ajc153Tests.java
|
/*******************************************************************************
* Copyright (c) 2006 IBM
* 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.ajc153;
import java.io.File;
import junit.framework.Test;
import org.aspectj.testing.Utils;
import org.aspectj.testing.XMLBasedAjcTestCase;
public class Ajc153Tests extends org.aspectj.testing.XMLBasedAjcTestCase {
//public void testGenericsProblem_pr151978() { runTest("generics problem");}
//public void testMissingLineNumbersInStacktraceBefore_pr145442() { runTest("missing line numbers in stacktrace before");}
//public void testMissingLineNumbersInStacktraceAfter_pr145442() { runTest("missing line numbers in stacktrace after");}
//public void testMissingLineNumbersInStacktraceAround_pr145442() { runTest("missing line numbers in stacktrace around");}
// public void testArgnamesAndJavac_pr148381() { runTest("argNames and javac");}
// public void testCFlowXMLAspectLTW_pr149096() { runTest("cflow xml concrete aspect"); }
// public void testAmbiguousBinding_pr121805() { runTest("ambiguous binding");}
public void testGenericInheritanceDecp_pr150095() { runTest("generics, inheritance and decp");}
public void testIllegalStateException_pr148737() { runTest("illegalstateexception for non generic type");}
public void testAtajInheritance_pr149305_1() { runTest("ataj inheritance - 1");}
public void testAtajInheritance_pr149305_2() { runTest("ataj inheritance - 2");}
public void testAtajInheritance_pr149305_3() { runTest("ataj inheritance - 3");}
public void testVerificationFailureForAspectOf_pr148693() {
runTest("verification problem"); // build the code
Utils.verifyClass(ajc,"mypackage.MyAspect"); // verify it <<< BRAND NEW VERIFY UTILITY FOR EVERYONE TO TRY ;)
}
public void testIncorrectAnnotationValue_pr148537() { runTest("incorrect annotation value");}
public void testVerifyErrNoTypeCflowField_pr145693_1() { runTest("verifyErrNoTypeCflowField"); }
public void testVerifyErrInpathNoTypeCflowField_pr145693_2() { runTest("verifyErrInpathNoTypeCflowField"); }
public void testCpathNoTypeCflowField_pr145693_3() { runTest("cpathNoTypeCflowField"); }
// public void testVisibilityProblem_pr149071() { runTest("visibility problem");}
// public void testAdviceNotWovenAspectPath_pr147841() { runTest("advice not woven on aspectpath");}
public void testGenericSignatures_pr148409() { runTest("generic signature problem"); }
// public void testBrokenIfArgsCflowAtAj_pr145018() { runTest("ataj crashing with cflow, if and args");}
public void testCantFindType_pr149322_01() {runTest("can't find type on interface call 1");}
public void testCantFindType_pr149322_02() {runTest("can't find type on interface call 2");}
public void testCantFindType_pr149322_03() {runTest("can't find type on interface call 3");}
public void testMatchVolatileField_pr150671() {runTest("match volatile field");};
/////////////////////////////////////////
public static Test suite() {
return XMLBasedAjcTestCase.loadSuite(Ajc153Tests.class);
}
protected File getSpecFile() {
return new File("../tests/src/org/aspectj/systemtest/ajc153/ajc153.xml");
}
}
|
152,589 |
Bug 152589 [pipeline] adding a whitespace results in adviceDidNotMatch warning
| null |
resolved fixed
|
9664058
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-08-03T07:23:55Z | 2006-08-02T14:46:40Z |
org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/compiler/AjPipeliningCompilerAdapter.java
|
/*******************************************************************************
* Copyright (c) 2006 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:
* Andy Clement - initial implementation 26Jul06
*******************************************************************************/
package org.aspectj.ajdt.internal.compiler;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.aspectj.ajdt.internal.compiler.ast.AddAtAspectJAnnotationsVisitor;
import org.aspectj.ajdt.internal.compiler.ast.AspectDeclaration;
import org.aspectj.ajdt.internal.compiler.ast.ValidateAtAspectJAnnotationsVisitor;
import org.aspectj.ajdt.internal.compiler.lookup.EclipseFactory;
import org.aspectj.ajdt.internal.core.builder.AjState;
import org.aspectj.bridge.IMessage;
import org.aspectj.bridge.IMessageHandler;
import org.aspectj.bridge.IProgressListener;
import org.aspectj.bridge.context.CompilationAndWeavingContext;
import org.aspectj.bridge.context.ContextToken;
import org.aspectj.org.eclipse.jdt.internal.compiler.CompilationResult;
import org.aspectj.org.eclipse.jdt.internal.compiler.Compiler;
import org.aspectj.org.eclipse.jdt.internal.compiler.ast.Annotation;
import org.aspectj.org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration;
import org.aspectj.org.eclipse.jdt.internal.compiler.ast.TypeDeclaration;
import org.aspectj.org.eclipse.jdt.internal.compiler.env.ICompilationUnit;
import org.aspectj.org.eclipse.jdt.internal.compiler.impl.CompilerOptions;
import org.aspectj.org.eclipse.jdt.internal.compiler.problem.AbortCompilation;
import org.aspectj.util.CharOperation;
import org.aspectj.weaver.bcel.BcelWeaver;
import org.aspectj.weaver.bcel.BcelWorld;
import org.aspectj.weaver.patterns.CflowPointcut;
/**
* Adapts standard JDT Compiler to add in AspectJ specific behaviours.
* This version implements pipelining - where files are compiled and then
* woven immediately, unlike AjCompilerAdapter which compiles everything
* then weaves everything. (One small note: because all aspects have to
* be known before weaving can take place, the weaving pipeline is 'stalled'
* until all aspects have been compiled).
*
* The basic strategy is this:
*
* 1. diet parse all input source files
* - this is enough for us to implement ITD matching
* - this enables us to determine which are aspects
* 2. sort the input files, aspects first
* - keep a note of how many files contain aspects
* 3. if there are aspects, mark the pipeline as 'stalled'
* 3. repeat
* 3a. compile a file
* 3b. have we now compiled all aspects?
* NO - put file in a weave pending queue
* YES- unstall the 'pipeline'
* 3c. is the pipeline stalled?
* NO - weave all pending files and this one
* YES- do nothing
*
* Complexities arise because of:
* - what does -XterminateAfterCompilation mean? since there is no stage
* where everything is compiled and nothing is woven
*
*
* Here is the compiler loop difference when pipelining.
*
* the old way:
* Finished diet parsing [C:\temp\ajcSandbox\aspectjhead\ajcTest23160.tmp\ClassOne.java]
* Finished diet parsing [C:\temp\ajcSandbox\aspectjhead\ajcTest23160.tmp\ClassTwo.java]
* > AjLookupEnvironment.completeTypeBindings()
* < AjLookupEnvironment.completeTypeBindings()
* compiling C:\temp\ajcSandbox\aspectjhead\ajcTest23160.tmp\ClassOne.java
* >Compiler.process(C:\temp\ajcSandbox\aspectjhead\ajcTest23160.tmp\ClassOne.java)
* <Compiler.process(C:\temp\ajcSandbox\aspectjhead\ajcTest23160.tmp\ClassOne.java)
* compiling C:\temp\ajcSandbox\aspectjhead\ajcTest23160.tmp\ClassTwo.java
* >Compiler.process(C:\temp\ajcSandbox\aspectjhead\ajcTest23160.tmp\ClassTwo.java)
* <Compiler.process(C:\temp\ajcSandbox\aspectjhead\ajcTest23160.tmp\ClassTwo.java)
* >AjCompilerAdapter.weave()
* >BcelWeaver.prepareForWeave
* <BcelWeaver.prepareForWeave
* woven class ClassOne (from C:\temp\ajcSandbox\aspectjhead\ajcTest23160.tmp\ClassOne.java)
* woven class ClassTwo (from C:\temp\ajcSandbox\aspectjhead\ajcTest23160.tmp\ClassTwo.java)
* <AjCompilerAdapter.weave()
*
* the new way (see the compiling/weaving mixed up):
* Finished diet parsing [C:\temp\ajcSandbox\aspectjhead\ajcTest23160.tmp\ClassOne.java]
* Finished diet parsing [C:\temp\ajcSandbox\aspectjhead\ajcTest23160.tmp\ClassTwo.java]
* >AjLookupEnvironment.completeTypeBindings()
* <AjLookupEnvironment.completeTypeBindings()
* compiling C:\temp\ajcSandbox\aspectjhead\ajcTest23160.tmp\ClassOne.java
* >Compiler.process(C:\temp\ajcSandbox\aspectjhead\ajcTest23160.tmp\ClassOne.java)
* <Compiler.process(C:\temp\ajcSandbox\aspectjhead\ajcTest23160.tmp\ClassOne.java)
* >AjCompilerAdapter.weave()
* >BcelWeaver.prepareForWeave
* <BcelWeaver.prepareForWeave
* woven class ClassOne (from C:\temp\ajcSandbox\aspectjhead\ajcTest23160.tmp\ClassOne.java)
* <AjCompilerAdapter.weave()
* compiling C:\temp\ajcSandbox\aspectjhead\ajcTest23160.tmp\ClassTwo.java
* >Compiler.process(C:\temp\ajcSandbox\aspectjhead\ajcTest23160.tmp\ClassTwo.java)
* <Compiler.process(C:\temp\ajcSandbox\aspectjhead\ajcTest23160.tmp\ClassTwo.java)
* >AjCompilerAdapter.weave()
* woven class ClassTwo (from C:\temp\ajcSandbox\aspectjhead\ajcTest23160.tmp\ClassTwo.java)
* <AjCompilerAdapter.weave()
*
*
*/
public class AjPipeliningCompilerAdapter extends AbstractCompilerAdapter {
private Compiler compiler;
private BcelWeaver weaver;
private EclipseFactory eWorld;
private boolean isBatchCompile;
private boolean reportedErrors;
private boolean isXTerminateAfterCompilation;
private boolean proceedOnError;
private boolean inJava5Mode;
private boolean noAtAspectJAnnotationProcessing;
private IIntermediateResultsRequestor intermediateResultsRequestor;
private IProgressListener progressListener;
private IOutputClassFileNameProvider outputFileNameProvider;
private IBinarySourceProvider binarySourceProvider;
private WeaverMessageHandler weaverMessageHandler;
private Map /* fileName > List<UnwovenClassFile> */ binarySourceSetForFullWeave = new HashMap();
private ContextToken processingToken = null;
private ContextToken resolvingToken = null;
private ContextToken analysingToken = null;
private ContextToken generatingToken = null;
private AjState incrementalCompilationState;
// Maintains a list of whats weaving - whilst the pipeline is stalled, this accumulates aspects.
List /*InterimResult*/ resultsPendingWeave = new ArrayList();
// pipelining info
private boolean pipelineStalled = true;
private boolean weaverInitialized = false;
private int toWaitFor;
/**
* Create an adapter, and tell it everything it needs to now to drive the AspectJ
* parts of a compile cycle.
* @param compiler the JDT compiler that produces class files from source
* @param isBatchCompile true if this is a full build (non-incremental)
* @param world the bcelWorld used for type resolution during weaving
* @param weaver the weaver
* @param intRequestor recipient of interim compilation results from compiler (pre-weave)
* @param outputFileNameProvider implementor of a strategy providing output file names for results
* @param binarySourceEntries binary source that we didn't compile, but that we need to weave
* @param resultSetForFullWeave if we are doing an incremental build, and the weaver determines
* that we need to weave the world, this is the set of intermediate
* results that will be passed to the weaver.
*/
public AjPipeliningCompilerAdapter(Compiler compiler,
boolean isBatchCompile,
BcelWorld world,
BcelWeaver weaver,
EclipseFactory eFactory,
IIntermediateResultsRequestor intRequestor,
IProgressListener progressListener,
IOutputClassFileNameProvider outputFileNameProvider,
IBinarySourceProvider binarySourceProvider,
Map fullBinarySourceEntries, /* fileName |-> List<UnwovenClassFile> */
boolean isXterminateAfterCompilation,
boolean proceedOnError,
boolean noAtAspectJProcessing,
AjState incrementalCompilationState) {
this.compiler = compiler;
this.isBatchCompile = isBatchCompile;
this.weaver = weaver;
this.intermediateResultsRequestor = intRequestor;
this.progressListener = progressListener;
this.outputFileNameProvider = outputFileNameProvider;
this.binarySourceProvider = binarySourceProvider;
this.isXTerminateAfterCompilation = isXterminateAfterCompilation;
this.proceedOnError = proceedOnError;
this.binarySourceSetForFullWeave = fullBinarySourceEntries;
this.eWorld = eFactory;
this.inJava5Mode = false;
this.noAtAspectJAnnotationProcessing = noAtAspectJProcessing;
this.incrementalCompilationState = incrementalCompilationState;
if (compiler.options.complianceLevel == CompilerOptions.JDK1_5) inJava5Mode = true;
IMessageHandler msgHandler = world.getMessageHandler();
// Do we need to reset the message handler or create a new one? (This saves a ton of memory lost on incremental compiles...)
if (msgHandler instanceof WeaverMessageHandler) {
((WeaverMessageHandler)msgHandler).resetCompiler(compiler);
weaverMessageHandler = (WeaverMessageHandler)msgHandler;
} else {
weaverMessageHandler = new WeaverMessageHandler(msgHandler, compiler);
world.setMessageHandler(weaverMessageHandler);
}
}
// the compilation lifecycle methods below are called in order as compilation progresses...
/**
* In a pipelining compilation system, we need to ensure aspects are through the pipeline first. Only
* when they are all through (and therefore we know about all static/dynamic crosscutting) can be
* proceed to weave anything. Effectively the weaving part of the pipeline stalls until all the
* aspects have been fully compiled. This method sorts the compilation units such that any containing
* aspects are fully compiled first and it keeps a note on how long it should stall the pipeline before
* commencing weaving.
*/
public void afterDietParsing(CompilationUnitDeclaration[] units) {
if (debugPipeline) System.err.println("> afterDietParsing: there are "+(units==null?0:units.length)+" units to sort");
if (!reportedErrors && units!=null) {
for (int i = 0; i < units.length; i++) {
if (units[i]!=null && units[i].compilationResult!=null && units[i].compilationResult.hasErrors()) {
reportedErrors = true;
break; // TODO break or exit here?
}
}
}
// Break the units into two lists...
List aspects = new ArrayList();
List nonaspects = new ArrayList();
for (int i=0;i<units.length;i++) {
if (containsAnAspect(units[i])) aspects.add(units[i]); else nonaspects.add(units[i]);
}
if (units == null) return; // what does this mean?
// ...and put them back together, aspects first
int posn = 0;
for (Iterator iter = aspects.iterator(); iter.hasNext();) {
units[posn++] = (CompilationUnitDeclaration) iter.next();
}
for (Iterator iter = nonaspects.iterator(); iter.hasNext();) {
units[posn++] = (CompilationUnitDeclaration) iter.next();
}
// Work out how long to stall the pipeline
toWaitFor = aspects.size();
if (debugPipeline) System.err.println("< afterDietParsing: stalling pipeline for "+toWaitFor+" source files");
// TESTING
if (pipelineTesting) {
if (pipelineOutput ==null) pipelineOutput = new Hashtable();
pipelineOutput.put("filesContainingAspects", new Integer(toWaitFor).toString());
StringBuffer order = new StringBuffer();
order.append("[");
for (int i = 0; i < units.length; i++) {
if (i!=0) order.append(",");
CompilationUnitDeclaration declaration = units[i];
String filename = new String(declaration.getFileName());
int idx = filename.lastIndexOf('/');
if (idx>0) filename=filename.substring(idx+1);
idx = filename.lastIndexOf('\\');
if (idx>0) filename=filename.substring(idx+1);
order.append(filename);
}
order.append("]");
pipelineOutput.put("weaveOrder", order.toString());
}
}
public void beforeCompiling(ICompilationUnit[] sourceUnits) {
resultsPendingWeave = new ArrayList();
reportedErrors = false;
}
public void beforeProcessing(CompilationUnitDeclaration unit) {
if (debugPipeline) System.err.println("compiling " + new String(unit.getFileName()));
eWorld.showMessage(IMessage.INFO, "compiling " + new String(unit.getFileName()), null, null);
processingToken = CompilationAndWeavingContext.enteringPhase(CompilationAndWeavingContext.PROCESSING_COMPILATION_UNIT,unit.getFileName());
if (inJava5Mode && !noAtAspectJAnnotationProcessing) {
ContextToken tok = CompilationAndWeavingContext.enteringPhase(CompilationAndWeavingContext.ADDING_AT_ASPECTJ_ANNOTATIONS, unit.getFileName());
AddAtAspectJAnnotationsVisitor atAspectJVisitor = new AddAtAspectJAnnotationsVisitor(unit);
unit.traverse(atAspectJVisitor, unit.scope);
CompilationAndWeavingContext.leavingPhase(tok);
}
}
public void beforeResolving(CompilationUnitDeclaration unit) {
resolvingToken = CompilationAndWeavingContext.enteringPhase(CompilationAndWeavingContext.RESOLVING_COMPILATION_UNIT, unit.getFileName());
}
public void afterResolving(CompilationUnitDeclaration unit) {
if (resolvingToken != null)
CompilationAndWeavingContext.leavingPhase(resolvingToken);
}
public void beforeAnalysing(CompilationUnitDeclaration unit) {
analysingToken = CompilationAndWeavingContext.enteringPhase(CompilationAndWeavingContext.ANALYSING_COMPILATION_UNIT, unit.getFileName());
if (inJava5Mode && !noAtAspectJAnnotationProcessing) {
ValidateAtAspectJAnnotationsVisitor atAspectJVisitor = new ValidateAtAspectJAnnotationsVisitor(unit);
unit.traverse(atAspectJVisitor, unit.scope);
}
}
public void afterAnalysing(CompilationUnitDeclaration unit) {
if (analysingToken != null)
CompilationAndWeavingContext.leavingPhase(analysingToken);
}
public void beforeGenerating(CompilationUnitDeclaration unit) {
generatingToken = CompilationAndWeavingContext.enteringPhase(CompilationAndWeavingContext.GENERATING_UNWOVEN_CODE_FOR_COMPILATION_UNIT, unit.getFileName());
}
public void afterGenerating(CompilationUnitDeclaration unit) {
if (generatingToken != null)
CompilationAndWeavingContext.leavingPhase(generatingToken);
}
public void afterCompiling(CompilationUnitDeclaration[] units) {
this.eWorld.cleanup();
if (!weaverInitialized) { // nothing got compiled, doesnt mean there is nothing to do... (binary weaving)
if (!(isXTerminateAfterCompilation || (reportedErrors && !proceedOnError))) {
// acceptResult(unit.compilationResult);
// } else {
try {
weaveQueuedEntries();
} catch (IOException ex) {
AbortCompilation ac = new AbortCompilation(null,ex);
throw ac;
}
}
}
postWeave();
try {
// not great ... but one more check before we continue, see pr132314
if (!reportedErrors && units!=null) {
for (int i = 0; i < units.length; i++) {
if (units[i]!=null && units[i].compilationResult!=null && units[i].compilationResult.hasErrors()) {
reportedErrors = true;
break;
}
}
}
if (isXTerminateAfterCompilation || (reportedErrors && !proceedOnError)) {
// no point weaving... just tell the requestor we're done
notifyRequestor();
} else {
// weave(); // notification happens as weave progresses...
// weaver.getWorld().flush(); // pr152257
}
// } catch (IOException ex) {
// AbortCompilation ac = new AbortCompilation(null,ex);
// throw ac;
} catch (RuntimeException rEx) {
if (rEx instanceof AbortCompilation) throw rEx; // Don't wrap AbortCompilation exceptions!
// This will be unwrapped in Compiler.handleInternalException() and the nested
// RuntimeException thrown back to the original caller - which is AspectJ
// which will then then log it as a compiler problem.
throw new AbortCompilation(true,rEx);
}
}
public void afterProcessing(CompilationUnitDeclaration unit, int unitIndex) {
CompilationAndWeavingContext.leavingPhase(processingToken);
eWorld.finishedCompilationUnit(unit);
InterimCompilationResult intRes = new InterimCompilationResult(unit.compilationResult,outputFileNameProvider);
if (unit.compilationResult.hasErrors()) reportedErrors = true;
if (intermediateResultsRequestor != null) {
intermediateResultsRequestor.acceptResult(intRes);
}
if (isXTerminateAfterCompilation || (reportedErrors && !proceedOnError)) {
acceptResult(unit.compilationResult);
} else {
queueForWeaving(intRes);
}
}
private void queueForWeaving(InterimCompilationResult intRes) {
resultsPendingWeave.add(intRes);
if (pipelineStalled) {
if (resultsPendingWeave.size()>=toWaitFor) pipelineStalled = false;
}
if (pipelineStalled) return;
try {
weaveQueuedEntries();
} catch (IOException ex) {
AbortCompilation ac = new AbortCompilation(null,ex);
throw ac;
}
}
/*
* Called from the weaverAdapter once it has finished weaving the class files
* associated with a given compilation result.
*/
public void acceptResult(CompilationResult result) {
compiler.requestor.acceptResult(result.tagAsAccepted());
if (compiler.unitsToProcess != null) {
for (int i = 0; i < compiler.unitsToProcess.length; i++) {
if (compiler.unitsToProcess[i] != null) {
if (compiler.unitsToProcess[i].compilationResult == result) {
compiler.unitsToProcess[i].cleanUp();
compiler.unitsToProcess[i] = null;
}
}
}
}
}
// helper methods...
// ==================================================================================
private List getBinarySourcesFrom(Map binarySourceEntries) {
// Map is fileName |-> List<UnwovenClassFile>
List ret = new ArrayList();
for (Iterator binIter = binarySourceEntries.keySet().iterator(); binIter.hasNext();) {
String sourceFileName = (String) binIter.next();
List unwovenClassFiles = (List) binarySourceEntries.get(sourceFileName);
// XXX - see bugs 57432,58679 - final parameter on next call should be "compiler.options.maxProblemsPerUnit"
CompilationResult result = new CompilationResult(sourceFileName.toCharArray(),0,0,Integer.MAX_VALUE);
result.noSourceAvailable();
InterimCompilationResult binarySource =
new InterimCompilationResult(result,unwovenClassFiles);
ret.add(binarySource);
}
return ret;
}
private void notifyRequestor() {
for (Iterator iter = resultsPendingWeave.iterator(); iter.hasNext();) {
InterimCompilationResult iresult = (InterimCompilationResult) iter.next();
compiler.requestor.acceptResult(iresult.result().tagAsAccepted());
}
}
private void weaveQueuedEntries() throws IOException {
if (debugPipeline)System.err.println(">.weaveQueuedEntries()");
for (Iterator iter = resultsPendingWeave.iterator(); iter.hasNext();) {
InterimCompilationResult iresult = (InterimCompilationResult) iter.next();
for (int i = 0; i < iresult.unwovenClassFiles().length; i++) {
weaver.addClassFile(iresult.unwovenClassFiles()[i]);
}
}
ensureWeaverInitialized(); // by doing this only once, are we saying needToReweaveWorld can't change once the aspects have been stuffed into the weaver?
if (weaver.needToReweaveWorld() && !isBatchCompile) return;
weaver.weave(new WeaverAdapter(this,weaverMessageHandler,progressListener));
resultsPendingWeave.clear(); // dont need to do those again
this.eWorld.minicleanup();
if (debugPipeline)System.err.println("<.weaveQueuedEntries()");
}
private void ensureWeaverInitialized() {
if (weaverInitialized) return;
weaverInitialized=true;
weaver.setIsBatchWeave(isBatchCompile);
weaver.prepareForWeave();
if (weaver.needToReweaveWorld()) {
if (!isBatchCompile) {
//force full recompilation from source
this.incrementalCompilationState.forceBatchBuildNextTimeAround();
return;
}
resultsPendingWeave.addAll(getBinarySourcesFrom(binarySourceSetForFullWeave));
} else {
Map binarySourcesToAdd = binarySourceProvider.getBinarySourcesForThisWeave();
resultsPendingWeave.addAll(getBinarySourcesFrom(binarySourcesToAdd));
}
}
private void weave() throws IOException {
if (debugPipeline)System.err.println("> weave()");
// ensure weaver state is set up correctly
for (Iterator iter = resultsPendingWeave.iterator(); iter.hasNext();) {
InterimCompilationResult iresult = (InterimCompilationResult) iter.next();
for (int i = 0; i < iresult.unwovenClassFiles().length; i++) {
weaver.addClassFile(iresult.unwovenClassFiles()[i]);
}
}
weaver.setIsBatchWeave(isBatchCompile);
weaver.prepareForWeave();
if (weaver.needToReweaveWorld()) {
if (!isBatchCompile) {
//force full recompilation from source
this.incrementalCompilationState.forceBatchBuildNextTimeAround();
return;
}
resultsPendingWeave.addAll(getBinarySourcesFrom(binarySourceSetForFullWeave));
} else {
Map binarySourcesToAdd = binarySourceProvider.getBinarySourcesForThisWeave();
resultsPendingWeave.addAll(getBinarySourcesFrom(binarySourcesToAdd));
}
try {
weaver.weave(new WeaverAdapter(this,weaverMessageHandler,progressListener));
} finally {
CflowPointcut.clearCaches();
weaver.tidyUp();
IMessageHandler imh = weaver.getWorld().getMessageHandler();
if (imh instanceof WeaverMessageHandler)
((WeaverMessageHandler)imh).resetCompiler(null);
}
if (debugPipeline)System.err.println("< weave()");
}
private void postWeave() {
if (debugPipeline)System.err.println("> postWeave()");
IMessageHandler imh = weaver.getWorld().getMessageHandler();
CflowPointcut.clearCaches();
if (imh instanceof WeaverMessageHandler)
((WeaverMessageHandler)imh).setCurrentResult(null);
weaver.allWeavingComplete();
weaver.tidyUp();
if (imh instanceof WeaverMessageHandler)
((WeaverMessageHandler)imh).resetCompiler(null);
if (debugPipeline)System.err.println("< postWeave()");
}
/**
* Return true if the compilation unit declaration contains an aspect declaration (either code style
* or annotation style). It must inspect the multiple types that may be in a compilation
* unit declaration and any inner types.
*/
private boolean containsAnAspect(CompilationUnitDeclaration cud) {
TypeDeclaration[] typeDecls = cud.types;
if (typeDecls!=null) {
for (int i = 0; i < typeDecls.length; i++) { // loop through top level types in the file
TypeDeclaration declaration = typeDecls[i];
if (isAspect(declaration)) return true;
if (declaration.memberTypes!=null) {
TypeDeclaration[] memberTypes = declaration.memberTypes;
for (int j = 0; j < memberTypes.length; j++) { // loop through inner types
if (containsAnAspect(memberTypes[j])) return true;
}
}
}
}
return false;
}
private boolean containsAnAspect(TypeDeclaration tDecl) {
if (isAspect(tDecl)) return true;
if (tDecl.memberTypes!=null) {
TypeDeclaration[] memberTypes = tDecl.memberTypes;
for (int j = 0; j < memberTypes.length; j++) { // loop through inner types
if (containsAnAspect(memberTypes[j])) return true;
}
}
return false;
}
private static final char[] aspectSig = "Lorg/aspectj/lang/annotation/Aspect;".toCharArray();
private boolean isAspect(TypeDeclaration declaration) {
if (declaration instanceof AspectDeclaration) return true; // code style
else if (declaration.annotations!=null) { // check for annotation style
for (int index = 0; index < declaration.annotations.length; index++) {
TypeDeclaration.resolveAnnotations(declaration.staticInitializerScope, declaration.annotations, declaration.binding); // force annotation resolution
Annotation a = declaration.annotations[index];
if (CharOperation.equals(a.resolvedType.signature(),aspectSig)) return true;
}
}
return false;
}
// ---
/**
* SECRET: FOR TESTING - this can be used to collect information that tests can verify.
*/
public static boolean pipelineTesting = false;
public static Hashtable pipelineOutput = null;
// Keys into pipelineOutput:
// compileOrder "[XXX,YYY]" a list of the order in which files will be woven (aspects should be first)
// filesContainingAspects "NNN" how many input source files have aspects inside
//
public static String getPipelineDebugOutput(String key) {
if (pipelineOutput==null) return "";
return (String)pipelineOutput.get(key);
}
private final boolean debugPipeline = false;
public List getResultsPendingWeave() { return resultsPendingWeave;}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.