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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
117,614 |
Bug 117614 ajc crashes on common-logging-1.0.4.jar
|
--- Dump Properties --- Dump file: ajcore.20051122.152749.326.txt Dump reason: org.aspectj.weaver.BCException Dump on exception: true Dump at exit condition: abort ---- Exception Information --- org.aspectj.weaver.BCException: bad resolve of void org.apache.log4j.Category.log(java.lang.String, org.apache.log4j.Level, java.lang.Object, java.lang.Throwable) at org.aspectj.weaver.World.getModifiers(World.java:216) at org.aspectj.weaver.Member.getModifiers(Member.java:406) at org.aspectj.weaver.patterns.KindedPointcut.warnOnConfusingSig(KindedPointcut.java:109) at org.aspectj.weaver.patterns.KindedPointcut.match(KindedPointcut.java:69) at org.aspectj.weaver.patterns.OrPointcut.match(OrPointcut.java:44) at org.aspectj.weaver.patterns.AndPointcut.match(AndPointcut.java:43) at org.aspectj.weaver.patterns.AndPointcut.match(AndPointcut.java:43) at org.aspectj.weaver.ShadowMunger.match(ShadowMunger.java:62) at org.aspectj.weaver.Advice.match(Advice.java:91) at org.aspectj.weaver.bcel.BcelClassWeaver.match(BcelClassWeaver.java:1126) at org.aspectj.weaver.bcel.BcelClassWeaver.matchInvokeInstruction(BcelClassWeaver.java:1115) at org.aspectj.weaver.bcel.BcelClassWeaver.match(BcelClassWeaver.java:987) at org.aspectj.weaver.bcel.BcelClassWeaver.match(BcelClassWeaver.java:827) at org.aspectj.weaver.bcel.BcelClassWeaver.weave(BcelClassWeaver.java:348) at org.aspectj.weaver.bcel.BcelClassWeaver.weave(BcelClassWeaver.java:83) at org.aspectj.weaver.bcel.BcelWeaver.weave(BcelWeaver.java:742) at org.aspectj.weaver.bcel.BcelWeaver.weaveWithoutDump(BcelWeaver.java:707) at org.aspectj.weaver.bcel.BcelWeaver.weaveAndNotify(BcelWeaver.java:634) at org.aspectj.weaver.bcel.BcelWeaver.weave(BcelWeaver.java:577) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.weave(AjCompilerAdapter.java:243) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.afterCompiling(AjCompilerAdapter.java:118) at org.aspectj.org.eclipse.jdt.internal.compiler.Compiler.compile(Compiler.java:383) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.performCompilation(AjBuildManager.java:680) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.doBuild(AjBuildManager.java:168) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.batchBuild(AjBuildManager.java:102) at org.aspectj.ajdt.ajc.AjdtCommand.doCommand(AjdtCommand.java:109) at org.aspectj.ajdt.ajc.AjdtCommand.runCommand(AjdtCommand.java:60) at org.aspectj.tools.ajc.Main.run(Main.java:291)
|
resolved fixed
|
6eb77c5
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2005-11-24T14:28:27Z | 2005-11-23T01:40:00Z |
weaver/src/org/aspectj/weaver/patterns/WithinPointcut.java
|
/* *******************************************************************
* Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC).
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* PARC initial implementation
* ******************************************************************/
package org.aspectj.weaver.patterns;
import java.io.DataOutputStream;
import java.io.IOException;
import java.util.Map;
import java.util.Set;
import org.aspectj.bridge.IMessage;
import org.aspectj.bridge.ISourceLocation;
import org.aspectj.bridge.Message;
import org.aspectj.bridge.MessageUtil;
import org.aspectj.util.FuzzyBoolean;
import org.aspectj.weaver.ISourceContext;
import org.aspectj.weaver.IntMap;
import org.aspectj.weaver.ResolvedType;
import org.aspectj.weaver.Shadow;
import org.aspectj.weaver.VersionedDataInputStream;
import org.aspectj.weaver.WeaverMessages;
import org.aspectj.weaver.ast.Literal;
import org.aspectj.weaver.ast.Test;
public class WithinPointcut extends Pointcut {
private TypePattern typePattern;
public WithinPointcut(TypePattern type) {
this.typePattern = type;
this.pointcutKind = WITHIN;
}
public TypePattern getTypePattern() {
return typePattern;
}
private FuzzyBoolean isWithinType(ResolvedType type) {
while (type != null) {
if (typePattern.matchesStatically(type)) {
return FuzzyBoolean.YES;
}
type = type.getDeclaringType();
}
return FuzzyBoolean.NO;
}
public Set couldMatchKinds() {
return Shadow.ALL_SHADOW_KINDS;
}
public Pointcut parameterizeWith(Map typeVariableMap) {
WithinPointcut ret = new WithinPointcut(this.typePattern.parameterizeWith(typeVariableMap));
ret.copyLocationFrom(this);
return ret;
}
public FuzzyBoolean fastMatch(FastMatchInfo info) {
if (typePattern.annotationPattern instanceof AnyAnnotationTypePattern) {
return isWithinType(info.getType());
}
return FuzzyBoolean.MAYBE;
}
protected FuzzyBoolean matchInternal(Shadow shadow) {
ResolvedType enclosingType = shadow.getIWorld().resolve(shadow.getEnclosingType(),true);
if (enclosingType == ResolvedType.MISSING) {
IMessage msg = new Message(
WeaverMessages.format(WeaverMessages.CANT_FIND_TYPE_WITHINPCD,
shadow.getEnclosingType().getName()),
shadow.getSourceLocation(),true,new ISourceLocation[]{getSourceLocation()});
shadow.getIWorld().getMessageHandler().handleMessage(msg);
}
typePattern.resolve(shadow.getIWorld());
return isWithinType(enclosingType);
}
public void write(DataOutputStream s) throws IOException {
s.writeByte(Pointcut.WITHIN);
typePattern.write(s);
writeLocation(s);
}
public static Pointcut read(VersionedDataInputStream s, ISourceContext context) throws IOException {
TypePattern type = TypePattern.read(s, context);
WithinPointcut ret = new WithinPointcut(type);
ret.readLocation(context, s);
return ret;
}
public void resolveBindings(IScope scope, Bindings bindings) {
typePattern = typePattern.resolveBindings(scope, bindings, false, false);
// look for parameterized type patterns which are not supported...
HasThisTypePatternTriedToSneakInSomeGenericOrParameterizedTypePatternMatchingStuffAnywhereVisitor
visitor = new HasThisTypePatternTriedToSneakInSomeGenericOrParameterizedTypePatternMatchingStuffAnywhereVisitor();
typePattern.traverse(visitor, null);
if (visitor.wellHasItThen/*?*/()) {
scope.message(MessageUtil.error(WeaverMessages.format(WeaverMessages.WITHIN_PCD_DOESNT_SUPPORT_PARAMETERS),
getSourceLocation()));
}
}
public void postRead(ResolvedType enclosingType) {
typePattern.postRead(enclosingType);
}
public boolean couldEverMatchSameJoinPointsAs(WithinPointcut other) {
return typePattern.couldEverMatchSameTypesAs(other.typePattern);
}
public boolean equals(Object other) {
if (!(other instanceof WithinPointcut)) return false;
WithinPointcut o = (WithinPointcut)other;
return o.typePattern.equals(this.typePattern);
}
public int hashCode() {
int result = 43;
result = 37*result + typePattern.hashCode();
return result;
}
public String toString() {
return "within(" + typePattern + ")";
}
protected Test findResidueInternal(Shadow shadow, ExposedState state) {
return match(shadow).alwaysTrue() ? Literal.TRUE : Literal.FALSE;
}
public Pointcut concretize1(ResolvedType inAspect, ResolvedType declaringType, IntMap bindings) {
Pointcut ret = new WithinPointcut(typePattern);
ret.copyLocationFrom(this);
return ret;
}
public Object accept(PatternNodeVisitor visitor, Object data) {
return visitor.visit(this, data);
}
}
|
11,280 |
Bug 11280 [View Mgmt] Switching perspectives loses view maximized state
|
1. Open the CVS repository view in the Java perspective. 2. Double click the title bar to maximize it 3. Switch to the resource perspective. 4. Come back to the Java perspective. The CVS repository view is no longer maximized. A view that is maximized should stay maximized.
|
resolved wontfix
|
508dbcb
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2005-11-28T12:08:29Z | 2002-03-13T17:20:00Z |
tests/src/org/aspectj/systemtest/ajc150/Ajc150Tests.java
|
/*******************************************************************************
* Copyright (c) 2004 IBM
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* Andy Clement - initial API and implementation
*******************************************************************************/
package org.aspectj.systemtest.ajc150;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.List;
import junit.framework.Test;
import org.aspectj.apache.bcel.classfile.JavaClass;
import org.aspectj.apache.bcel.classfile.Method;
import org.aspectj.apache.bcel.classfile.Signature;
import org.aspectj.apache.bcel.util.ClassPath;
import org.aspectj.apache.bcel.util.SyntheticRepository;
import org.aspectj.asm.AsmManager;
import org.aspectj.asm.IHierarchy;
import org.aspectj.asm.IProgramElement;
import org.aspectj.asm.IRelationship;
import org.aspectj.asm.internal.Relationship;
import org.aspectj.testing.XMLBasedAjcTestCase;
import org.aspectj.util.LangUtil;
public class Ajc150Tests extends org.aspectj.testing.XMLBasedAjcTestCase {
public static Test suite() {
return XMLBasedAjcTestCase.loadSuite(Ajc150Tests.class);
}
protected File getSpecFile() {
return new File("../tests/src/org/aspectj/systemtest/ajc150/ajc150.xml");
}
/*
public void testBrokenDispatchByITD_pr72834() { runTest("broken dispatch");}
public void testMissingAccessor_pr73856() { runTest("missing accessor");}
public void testCunningDeclareParents_pr92311() { runTest("cunning declare parents");}
public void testGenericITDsAndAbstractMethodError_pr102357() { runTest("generic itds and abstract method error");}
*/
public void testAtDeclareParents_pr117681() { runTest("at declare parents");}
public void testPrivilegeProblem_pr87525() { runTest("privilege problem with switch");}
public void testGenericAspects_pr115237() { runTest("aspectOf and generic aspects");}
public void testClassFormatError_pr114436() { runTest("ClassFormatError binary weaving perthis");}
public void testParserException_pr115788() { runTest("parser exception");}
public void testPossibleStaticImports_pr113066_1() { runTest("possible static imports bug - 1");}
public void testPossibleStaticImports_pr113066_2() { runTest("possible static imports bug - 2");}
public void testPossibleStaticImports_pr113066_3() { runTest("possible static imports bug - 3");}
public void testITDCtor_pr112783() { runTest("Problem with constructor ITDs");}
public void testAnnotatedITDFs_pr114005_1() { runTest("Annotated ITDFs - 1");}
public void testAnnotatedITDFs_pr114005_2() { runTest("Annotated ITDFs - 2");}
public void testCantCallSuperMethods_pr90143() { runTest("cant call super methods");}
public void testBrokenDecp_pr112476() { runTest("binary weaving decp broken");}
public void testUnboundFormal_pr112027() { runTest("unexpected error unboundFormalInPC");}
public void testNPEScopeSetup_pr115038() { runTest("NPE in ensureScopeSetup");}
public void testCCEGenerics_pr113445() { runTest("Generics ClassCastException");}
public void testMatthewsAspect_pr113947_1() { runTest("maws generic aspect - 1");}
public void testMatthewsAspect_pr113947_2() { runTest("maws generic aspect - 2");}
public void testFieldGet_pr114343() { runTest("field-get, generics and around advice");}
public void testFieldGet_pr114343_2() { runTest("field-get, generics and around advice - 2");}
public void testFieldGet_pr114343_3() { runTest("field-get, generics and around advice - 3");}
public void testCaptureBinding_pr114744() { runTest("capturebinding wildcard problem");}
public void testBadDecp_pr110788_1() { runTest("bad generic decp - 1");}
public void testBadDecp_pr110788_2() { runTest("bad generic decp - 2");}
public void testBadDecp_pr110788_3() { runTest("bad generic decp - 3");}
public void testBadDecp_pr110788_4() { runTest("bad generic decp - 4");}
public void testVarargsITD_pr110906() { runTest("ITD varargs problem");}
public void testBadRenderer_pr86903() { runTest("bcelrenderer bad");}
public void testIncompatibleClassChangeError_pr113630_1() {runTest("IncompatibleClassChangeError - errorscenario");}
public void testIncompatibleClassChangeError_pr113630_2() {runTest("IncompatibleClassChangeError - workingscenario");}
public void testFieldGetProblemWithGenericField_pr113861() {runTest("field-get problems with generic field");}
public void testDeclareAnnotationOnNonExistentType_pr99191_1() { runTest("declare annotation on non existent type - 1");}
public void testDeclareAnnotationOnNonExistentType_pr99191_2() { runTest("declare annotation on non existent type - 2");}
public void testDeclareAnnotationOnNonExistentType_pr99191_3() { runTest("declare annotation on non existent type - 3");}
public void testDeclareAnnotationOnNonExistentType_pr99191_4() { runTest("declare annotation on non existent type - 4");}
public void testDeclareAnnotationOnNonExistentType_pr99191_5() { runTest("declare annotation on non existent type - 5");}
public void testBadGenericSigAttribute_pr110927() {
runTest("cant create signature attribute");
Signature sig = GenericsTests.getClassSignature(ajc,"I");
if (sig==null) fail("Couldn't find signature attribute for type I");
String sigString = sig.getSignature();
if (!(sigString.equals("Ljava/lang/Object;LIE2;LIE1<Ljava/lang/String;>;") ||
sigString.equals("Ljava/lang/Object;LIE1<Ljava/lang/String;>;LIE2;"))) {
fail("Signature was "+sigString+" when should have been something like Ljava/lang/Object;LIE1<Ljava/lang/String;>;LIE2;");
}
}
public void test_typeProcessingOrderWhenDeclareParents() {
runTest("Order of types passed to compiler determines weaving behavior");
}
public void test_aroundMethod() {
runTest("method called around in class");
}
public void test_aroundMethodAspect() {
runTest("method called around in aspect");
}
public void test_ambiguousBindingsDetection() {
runTest("Various kinds of ambiguous bindings");
}
public void test_ambiguousArgsDetection() {
runTest("ambiguous args");
}
public void testIncorrectExceptionTableWhenBreakInMethod_pr78021() {
runTest("Injecting exception into while loop with break statement causes catch block to be ignored");
}
public void testIncorrectExceptionTableWhenReturnInMethod_pr79554() {
runTest("Return in try-block disables catch-block if final-block is present");
}
public void testMissingDebugInfoForGeneratedMethods_pr82570() throws ClassNotFoundException {
runTest("Weaved code does not include debug lines");
boolean f = false;
JavaClass jc = getClassFrom(ajc.getSandboxDirectory(),"PR82570_1");
Method[] meths = jc.getMethods();
for (int i = 0; i < meths.length; i++) {
Method method = meths[i];
if (f) System.err.println("Line number table for "+method.getName()+method.getSignature()+" = "+method.getLineNumberTable());
assertTrue("Didn't find a line number table for method "+method.getName()+method.getSignature(),
method.getLineNumberTable()!=null);
}
// This test would determine the info isn't there if you pass -g:none ...
// cR = ajc(baseDir,new String[]{"PR82570_1.java","-g:none"});
// assertTrue("Expected no compile problem:"+cR,!cR.hasErrorMessages());
// System.err.println(cR.getStandardError());
// jc = getClassFrom(ajc.getSandboxDirectory(),"PR82570_1");
// meths = jc.getMethods();
// for (int i = 0; i < meths.length; i++) {
// Method method = meths[i];
// assertTrue("Found a line number table for method "+method.getName(),
// method.getLineNumberTable()==null);
// }
}
public void testCanOverrideProtectedMethodsViaITDandDecp_pr83303() {
runTest("compiler error when mixing inheritance, overriding and polymorphism");
}
public void testPerTypeWithin_pr106554() {runTest("Problem in staticinitialization with pertypewithin aspect");}
public void testPerTypeWithinMissesNamedInnerTypes() {
runTest("pertypewithin() handing of inner classes (1)");
}
public void testPerTypeWithinMissesAnonymousInnerTypes() {
runTest("pertypewithin() handing of inner classes (2)");
}
public void testPerTypeWithinIncorrectlyMatchingInterfaces() {
runTest("pertypewithin({interface}) illegal field modifier");
}
public void test051_arrayCloningInJava5() {
runTest("AJC possible bug with static nested classes");
}
public void testBadASMforEnums() throws IOException {
runTest("bad asm for enums");
if (LangUtil.is15VMOrGreater()) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
PrintWriter pw = new PrintWriter(baos);
AsmManager.dumptree(pw,AsmManager.getDefault().getHierarchy().getRoot(),0);
pw.flush();
String tree = baos.toString();
assertTrue("Expected 'Red [enumvalue]' somewhere in here:"+tree,tree.indexOf("Red [enumvalue]")!=-1);
}
}
public void npeOnTypeNotFound() {
runTest("structure model npe on type not found");
}
public void testNoRuntimeExceptionSoftening() {
runTest("declare soft of runtime exception");
}
public void testRuntimeNoSoftenWithHandler() {
runTest("declare soft w. catch block");
}
public void testSyntaxError() {
runTest("invalid cons syntax");
}
public void testVarargsInConsBug() {
runTest("varargs in constructor sig");
}
public void testAspectpathdirs() {
runTest("dirs on aspectpath");
}
public void testIntroSample() {
runTest("introduction sample");
}
public void testPTWInterface() {
runTest("pertypewithin({interface}) illegal field modifier");
}
public void testEnumCalledEnumEtc() {
runTest("enum called Enum, annotation called Annotation, etc");
}
public void testInternalCompilerError_pr86832() {
runTest("Internal compiler error");
}
public void testCloneMethod_pr83311() {
runTest("overriding/polymorphism error on interface method introduction");
}
// IfPointcut.findResidueInternal() was modified to make this test complete in a short amount
// of time - if you see it hanging, someone has messed with the optimization.
public void testIfEvaluationExplosion_pr94086() {
runTest("Exploding compile time with if() statements in pointcut");
}
public void testReflectNPE_pr94167() {runTest("NPE in reflect implementation");}
public void testStaticImports_pr84260() {runTest("static import failures");}
public void testGenerics_pr99089() {runTest("ArrayIndexOutOfBoundsException - Generics in privileged aspects");}
public void testGenerics_pr95993() {runTest("NPE at ClassScope.java:660 when compiling generic class");}
public void testItdGenerics_pr99228() {runTest("ITD of a field into a generic class");}
public void testItdGenerics_pr98320() {runTest("intertype with nested generic type");}
public void testItdGenerics_pr100227() {runTest("inner class with generic enclosing class");}
public void testItdGenerics_pr100260() {runTest("methods inherited from a generic parent");}
public void testSyntaxErrorNPE_pr103266() {runTest("NPE on syntax error");}
public void testFinalAbstractClass_pr109486() { runTest("Internal compiler error (ClassParser.java:242)");}
public void testComplexBinding_pr102210() { runTest("NullPointerException trying to compile");}
public void testIllegalStateExceptionOnNestedParameterizedType_pr106634() {
runTest("IllegalStateException unpacking signature of nested parameterized type");
}
public void testParseErrorOnAnnotationStarPlusPattern() {
runTest("(@Foo *)+ type pattern parse error");
}
public void test_pr106130_tooManyLocals() {
runTest("test weaving with > 256 locals");
}
public void testMissingNamePattern_pr106461() { runTest("missing name pattern"); }
public void testMissingNamePattern_pr107059() {
runTest("parser crashes on call(void (@a *)(..)");
}
public void testIntermediateAnnotationMatching() {
runTest("intermediate annotation matching");
}
public void testBadRuntimeTestGeneration() {
runTest("target(@Foo *)");
}
public void testErrorMessageOnITDWithTypePatterns() {
runTest("clear error message on itd with type pattern");
}
public void testAjKeywordsAsIdentifiers() {
runTest("before and after are valid identifiers in classes");
}
public void testAjKeywordsAsIdentifiers2() {
runTest("before and after are valid identifiers in classes, part 2");
}
public void testNoBeforeReturningAdvice() {
runTest("before returning advice not allowed!");
}
public void testDetectVoidFieldType() {
runTest("void field type in pointcut expression");
}
public void testPointcutOverriding() {
runTest("overriding final pointcut from super-aspect");
}
public void testAtSuppressWarnings() {
runTest("@SuppressWarnings should suppress");
}
public void testDEOWWithBindingPointcut() {
runTest("declare warning : foo(str) : ...;");
}
public void testAroundAdviceAndInterfaceInitializer() {
runTest("around advice on interface initializer");
}
public void testGoodErrorMessageOnUnmatchedMemberSyntax() {
runTest("good error message for unmatched member syntax");
}
public void testITDWithNoExceptionAndIntermediary() {
runTest("itd override with no exception clause");
}
public void testAnonymousInnerClasses() {
runTest("anonymous inner classes");
}
public void testMultipleAnonymousInnerClasses() {
runTest("multiple anonymous inner classes");
}
public void testPrivilegedMethodAccessorsGetRightExceptions_pr82989() {
runTest("Compiler error due to a wrong exception check in try blocks");
}
public void testAnonymousInnerClassWithMethodReturningTypeParameter_pr107898() {
runTest("anonymous inner class with method returning type parameter");
}
public void testMatchingOfObjectArray() {
runTest("matching against Object[]");
}
public void testMultipleAnonymousInnerClasses_pr108104() {
runTest("multiple anonymous inner classes 2");
}
public void testSignatureMatchingInMultipleOverrideScenario() {
runTest("signature matching in override scenario");
}
public void testWildcardAnnotationMatching_pr108245() {
runTest("wildcard annotation matching - pr108245");
}
public void testInnerTypesAndTypeVariables() {
runTest("inner types and type variables");
}
public void testAtAfterThrowingWithNoFormal() {
runTest("@AfterThrowing with no formal specified");
}
public void testParameterizedVarArgsMatch() {
runTest("varargs with type variable");
}
public void testFieldAccessInsideITDM() {
runTest("itd field access inside itd method");
}
public void testTypeVarWithTypeVarBound() {
runTest("type variable with type variable bound");
}
public void testEnumSwitchInITD() {
runTest("switch on enum inside ITD method");
}
public void testInnerTypeOfGeneric() {
runTest("inner type of generic interface reference from parameterized type");
}
public void testDeclareParentsIntroducingCovariantReturnType() {
runTest("declare parents introducing override with covariance");
}
public void testInnerClassPassedToVarargs() {
runTest("inner class passed as argument to varargs method");
}
public void testInlinedFieldAccessInProceedCall() {
runTest("inlined field access in proceed call");
}
public void testVisibiltyInSignatureMatchingWithOverridesPart1() {
runTest("visibility in signature matching with overrides - 1");
}
public void testVisibiltyInSignatureMatchingWithOverridesPart2() {
runTest("visibility in signature matching with overrides - 2");
}
public void testVisibiltyInSignatureMatchingWithOverridesPart3() {
runTest("visibility in signature matching with overrides - 3");
}
public void testArgsGeneratedCorrectlyForAdviceExecution() {
runTest("args generated correctly for advice execution join point");
}
public void testNoUnusedWarningsOnAspectTypes() {
runTest("no unused warnings on aspect types");
}
public void testSyntheticArgumentsOnITDConstructorsNotUsedInMatching() {
runTest("synthetic arguments on itd cons are not used in matching");
}
public void testParsingOfGenericTypeSignature() {
runTest("parse generic type signature with parameterized type in interface");
}
public void testOverrideAndCovarianceWithDecPRuntime() {
runTest("override and covariance with decp - runtime");
}
public void testOverrideAndCovarianceWithDecPRuntimeMultiFiles() {
runTest("override and covariance with decp - runtime separate files");
}
public void testOverrideAndCovarianceWithDecPRuntimeMultiFilesBinaryWeaving() {
runTest("override and covariance with decp - binary weaving");
}
public void testAbstractSynchronizedITDMethods() {
runTest("abstract synchronized itdms not detected");
}
public void testSynchronizedITDInterfaceMethods() {
runTest("synchronized itd interface methods");
}
public void testNoWarningOnUnusedPointcut() {
runTest("unused private pointcuts");
}
public void testITDOnInterfaceWithExistingMember() {
runTest("itd interface method already existing on interface");
}
public void testFinalITDMOnInterface() {
runTest("final itd methods on interfaces");
}
public void testPrivatePointcutOverriding() {
runTest("can't override private pointcut in abstract aspect");
}
public void testAdviceOnCflow() {
runTest("advising cflow advice execution");
}
public void testNoTypeMismatchOnSameGenericTypes() {
runTest("no type mismatch on generic types in itds");
}
public void testSuperCallInITD() {
runTest("super call in ITD");
}
public void testSuperCallInITDPart2() {
runTest("super call in ITD - part 2");
}
public void testAtAnnotationBadTest_pr103740() {
runTest("Compiler failure on at_annotation");
}
public void testNoUnusedParameterWarningsForSyntheticAdviceArgs() {
runTest("no unused parameter warnings for synthetic advice args");
}
public void testNoVerifyErrorWithSetOnInnerType() {
runTest("no verify error with set on inner type");
}
public void testCantFindTypeErrorWithGenericReturnTypeOrParameter() {
runTest("cant find type error with generic return type or parameter");
}
public void testNoVerifyErrorOnGenericCollectionMemberAccess() {
runTest("no verify error on generic collection member access");
}
public void testRawAndGenericTypeConversionITDCons() {
runTest("raw and generic type conversion with itd cons");
}
public void testAtAnnotationBindingWithAround() {
runTest("@annotation binding with around advice");
}
public void testUnableToBuildShadows_pr109728() { runTest("Unable to build shadows");}
public void testMessageOnMissingTypeInDecP() {
runTest("declare parents on a missing type");
}
public void testParameterizedGenericMethods() {
runTest("parameterized generic methods");
}
public void testIllegalChangeToPointcutDeclaration_pr111915() {
runTest("test illegal change to pointcut declaration");
}
public void testCantProvideDefaultImplViaITD_pr110307_1() {runTest("Cant provide default implementation via ITD - 1");}
public void testCantProvideDefaultImplViaITD_pr110307_2() {runTest("Cant provide default implementation via ITD - 2");}
public void testCantProvideDefaultImplViaITD_pr110307_3() {runTest("Cant provide default implementation via ITD - 3");}
public void testCantProvideDefaultImplViaITD_pr110307_4() {runTest("Cant provide default implementation via ITD - 4");}
public void testCantProvideDefaultImplViaITD_pr110307_5() {runTest("Cant provide default implementation via ITD - 5");}
// Needs a change in the compiler so that getType() can be overridden in the intertype scope - thats
// where we can police whether a type variable has been used without being specified appropriately.
//public void testCantProvideDefaultImplViaITD_pr110307_6() {runTest("Cant provide default implementation via ITD - 6");}
public void testCantProvideDefaultImplViaITD_pr110307_7() {runTest("Cant provide default implementation via ITD - 7");}
public void testCallJoinPointsInAnonymousInnerClasses() {
runTest("call join points in anonymous inner classes");
}
public void testNoRequirementForUnwovenTypesToBeExposedToWeaver() {
runTest("default impl of Runnable");
}
public void testArrayCloneCallJoinPoints() {
runTest("array clone call join points in 1.4 vs 1.3");
}
public void testDebugInfoForAroundAdvice() {
runTest("debug info in around advice inlining");
}
public void testCCEWithGenericWildcard_pr112602() {
runTest("ClassCastException with generic wildcard");
}
public void testAdviceInStructureModelWithAnonymousInnerClass_pr77269() {
//AsmManager.setReporting("c:/debug.txt",true,true,true,true);
runTest("advice in structure model with anonymous inner class");
IHierarchy top = AsmManager.getDefault().getHierarchy();
// checking that the run() method inside anonymous inner class is in
// the structure model
IProgramElement anonRunMethodIPE = top.findElementForLabel(top.getRoot(),
IProgramElement.Kind.METHOD,"run()");
assertNotNull("Couldn't find 'run()' element in the tree",anonRunMethodIPE);
List l = AsmManager.getDefault().getRelationshipMap().get(anonRunMethodIPE);
assertNotNull("Should have some relationships but does not",l);
assertTrue("Should have one relationship but has " + l.size(),l.size()==1);
Relationship rel = (Relationship)l.get(0);
List targets = rel.getTargets();
assertTrue("Should have one target but has" + targets.size(),
targets.size()==1);
IProgramElement target = AsmManager.getDefault().getHierarchy().findElementForHandle((String)targets.get(0));
assertEquals("target of relationship should be 'before(): p..' but is "
+ target.toLabelString(),"before(): p..",target.toLabelString());
IProgramElement adviceIPE = top.findElementForLabel(top.getRoot(),
IProgramElement.Kind.ADVICE,"before(): p..");
assertNotNull("Couldn't find 'before(): p..' element in the tree",adviceIPE);
l = AsmManager.getDefault().getRelationshipMap().get(adviceIPE);
assertNotNull("Should have some relationships but does not",l);
assertTrue("Should have a relationship but does not ",l.size()>0);
for (Iterator iter = l.iterator(); iter.hasNext();) {
IRelationship element = (IRelationship) iter.next();
if (element.getName().equals("advises")) {
rel = (Relationship) element;
break;
}
}
targets = rel.getTargets();
assertTrue("Should have one target but has" + targets.size(),
targets.size()==1);
target = AsmManager.getDefault().getHierarchy().findElementForHandle((String)targets.get(0));
assertEquals("target of relationship should be 'run()' but is "
+ target.toLabelString(),"run()",target.toLabelString());
}
public void testAdviceInStructureModelWithNamedInnerClass_pr77269() {
//AsmManager.setReporting("c:/debug.txt",true,true,true,true);
runTest("advice in structure model with named inner class");
IHierarchy top = AsmManager.getDefault().getHierarchy();
// checking that the m() method inside named inner class is in
// the structure model
IProgramElement namedMethodIPE = top.findElementForLabel(top.getRoot(),
IProgramElement.Kind.METHOD,"m()");
assertNotNull("Couldn't find 'm()' element in the tree",namedMethodIPE);
List l = AsmManager.getDefault().getRelationshipMap().get(namedMethodIPE);
assertNotNull("Should have some relationships but does not",l);
assertTrue("Should have one relationship but has " + l.size(),l.size()==1);
Relationship rel = (Relationship)l.get(0);
List targets = rel.getTargets();
assertTrue("Should have one target but has" + targets.size(),
targets.size()==1);
IProgramElement target = AsmManager.getDefault().getHierarchy().findElementForHandle((String)targets.get(0));
assertEquals("target of relationship should be 'before(): p..' but is "
+ target.toLabelString(),"before(): p..",target.toLabelString());
IProgramElement adviceIPE = top.findElementForLabel(top.getRoot(),
IProgramElement.Kind.ADVICE,"before(): p..");
assertNotNull("Couldn't find 'before(): p..' element in the tree",adviceIPE);
l = AsmManager.getDefault().getRelationshipMap().get(adviceIPE);
assertNotNull("Should have some relationships but does not",l);
assertTrue("Should have a relationship but does not ",l.size()>0);
for (Iterator iter = l.iterator(); iter.hasNext();) {
IRelationship element = (IRelationship) iter.next();
if (element.getName().equals("advises")) {
rel = (Relationship) element;
break;
}
}
targets = rel.getTargets();
assertTrue("Should have one target but has" + targets.size(),
targets.size()==1);
target = AsmManager.getDefault().getHierarchy().findElementForHandle((String)targets.get(0));
assertEquals("target of relationship should be 'm()' but is "
+ target.toLabelString(),"m()",target.toLabelString());
}
public void testDWInStructureModelWithAnonymousInnerClass_pr77269() {
// AsmManager.setReporting("c:/debug.txt",true,true,true,true);
runTest("declare warning in structure model with anonymous inner class");
IHierarchy top = AsmManager.getDefault().getHierarchy();
IProgramElement pe = top.findElementForLabel(top.getRoot(),
IProgramElement.Kind.CODE,"method-call(void pack.Test.someMethod())");
assertNotNull("Couldn't find 'method-call(void pack.Test.someMethod())' element in the tree",pe);
}
public void testVarArgsIITDInConstructor() {
runTest("ITD varargs in constructor");
}
public void testWeaveInfoMessageForDeclareAtMethodOnITDdMethod() {
runTest("weaveinfo message for declare at method on an ITDd method");
}
public void testITDCWithNoExplicitConsCall() {
runTest("ITDC with no explicit cons call");
}
public void testJava5SpecificFeaturesUsedAtJava14OrLower() {
runTest("java 5 pointcuts and declares at pre-java 5 compliance levels");
}
public void testAnonymousTypes() {
runTest("Anonymous types and nome matching");
}
public void testAdviceExecutionJPToStringForms() {
runTest("adviceexecution join point toString forms");
}
public void testAssertWithinPointcutExpression() {
runTest("pointcut expression containing 'assert'");
}
public void testNoVerifyErrorWithTwoThisPCDs_pr113447() {
runTest("no verify error with two this pcds");
}
public void testNoVerifyErrorWithTwoAtThisPCDs_pr113447() {
runTest("no verify error with two at this pcds");
}
public void testNoVerifyErrorWithAtWithinPCDs_pr113447() {
runTest("no verify error with at within pcds");
}
public void testNoVerifyErrorWithAtWithincodePCDs_pr113447() {
runTest("no verify error with at withincode pcds");
}
public void testNoVerifyErrorWithAtAnnotationPCDs_pr113447() {
runTest("no verify error with at annotation pcds");
}
public void testNoVerifyErrorWithTwoArgsPCDs_pr113447() {
runTest("no verify error with two args pcds");
}
public void testNoStackOverflowWithCircularPCDInGenericAspect() {
runTest("no StackOverflowError with circular pcd in generic aspect");
}
public void testNoStackOverflowWithCircularPCDInGenericAspect2() {
runTest("no StackOverflowError with circular pcd in generic aspect - 2");
}
public void testNPEInThisJoinPointStaticPart() {
runTest("thisJoinPointStaticPart in if test");
}
public void testPointcutParsingOfCompiledPointcuts() {
runTest("pointcut parsing with ajc compiled pointcut references");
}
public void testReflectionOfAbstractITDs() {
runTest("reflection on abstract ITDs (Billing example)");
}
public void testDeclareSoftWithAdviceExecution() {
runTest("declare soft and adviceexecution");
}
public void testDeclareSoftWithExclusions() {
runTest("declare soft and exclusions");
}
public void testReturningObjectBinding() {
runTest("returning(Object) binding");
}
public void testPerTargetAndNegation() {
runTest("pertarget and negated pointcut");
}
public void testParameterizedPointcutAndAdvice() {
runTest("parameterized pointcut and advice");
}
/*
* Load-time weaving bugs
*/
public void testNPEinWeavingAdaptor_pr116626() { runTest("NPE in WeavingAdaptor");}
public void testXlintMessageForImproperAnnotationType_pr115252_Exact() {runTest("xlint message for improper exact annotation type");}
public void testXlintMessageForImproperAnnotationType_pr115252_OR() {runTest("xlint message for improper annotation type inside OR");}
public void testXlintMessageForImproperAnnotationType_pr115252_AND() {runTest("xlint message for improper annotation type inside AND");}
public void testXlintMessageForImproperAnnotationType_pr115252_Return() {runTest("xlint message for improper annotated return type");}
public void testXlintMessageForImproperAnnotationType_pr115252_Declaring() {runTest("xlint message for improper annotated declaring type");}
public void testXlintMessageForImproperAnnotationType_pr115252_Parameter() {runTest("xlint message for improper annotated parameter type");}
public void testXlintMessageForImproperAnnotationType_pr115252_Throws() {runTest("xlint message for improper annotated throws pattern");}
public void testXlintMessageForImproperAnnotationType_pr115252_MoreThanOne() {runTest("xlint message for more than one improper annotated parameter type");}
public void testDeclareAtTypeInStructureModel_pr115607() {
AsmManager.setReporting("c:/debug.txt",true,true,true,true);
runTest("declare at type appears correctly in structure model");
IHierarchy top = AsmManager.getDefault().getHierarchy();
IProgramElement pe = top.findElementForLabel(top.getRoot(),
IProgramElement.Kind.DECLARE_ANNOTATION_AT_TYPE,"declare @type: Simple : @I");
assertNotNull("Couldn't find 'declare @type: Simple : @I' element in the tree",pe);
List l = AsmManager.getDefault().getRelationshipMap().get(pe);
assertNotNull("Should have some relationships but does not",l);
}
// helper methods.....
public SyntheticRepository createRepos(File cpentry) {
ClassPath cp = new ClassPath(cpentry+File.pathSeparator+System.getProperty("java.class.path"));
return SyntheticRepository.getInstance(cp);
}
protected JavaClass getClassFrom(File where,String clazzname) throws ClassNotFoundException {
SyntheticRepository repos = createRepos(where);
return repos.loadClass(clazzname);
}
}
|
11,280 |
Bug 11280 [View Mgmt] Switching perspectives loses view maximized state
|
1. Open the CVS repository view in the Java perspective. 2. Double click the title bar to maximize it 3. Switch to the resource perspective. 4. Come back to the Java perspective. The CVS repository view is no longer maximized. A view that is maximized should stay maximized.
|
resolved wontfix
|
508dbcb
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2005-11-28T12:08:29Z | 2002-03-13T17:20:00Z |
weaver/src/org/aspectj/weaver/reflect/ReflectionBasedReferenceTypeDelegateFactory.java
|
/* *******************************************************************
* Copyright (c) 2005 Contributors.
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Eclipse Public License v1.0
* which accompanies this distribution and is available at
* http://eclipse.org/legal/epl-v10.html
*
* Contributors:
* Adrian Colyer Initial implementation
* ******************************************************************/
package org.aspectj.weaver.reflect;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Member;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import org.aspectj.util.LangUtil;
import org.aspectj.weaver.ReferenceType;
import org.aspectj.weaver.ResolvedMember;
import org.aspectj.weaver.ResolvedMemberImpl;
import org.aspectj.weaver.ResolvedType;
import org.aspectj.weaver.UnresolvedType;
import org.aspectj.weaver.World;
/**
* @author colyer
* Creates the appropriate ReflectionBasedReferenceTypeDelegate according to
* the VM level we are running at. Uses reflection to avoid 1.5 dependencies in
* 1.4 and 1.3 code base.
*/
public class ReflectionBasedReferenceTypeDelegateFactory {
public static ReflectionBasedReferenceTypeDelegate
createDelegate(ReferenceType forReferenceType, World inWorld, ClassLoader usingClassLoader) {
try {
Class c = Class.forName(forReferenceType.getName(),false,usingClassLoader);
if (LangUtil.is15VMOrGreater()) {
ReflectionBasedReferenceTypeDelegate rbrtd = create15Delegate(forReferenceType,c,usingClassLoader,inWorld);
if (rbrtd!=null) return rbrtd; // can be null if we didn't find the class the delegate logic loads
}
return new ReflectionBasedReferenceTypeDelegate(c,usingClassLoader,inWorld,forReferenceType);
} catch (ClassNotFoundException cnfEx) {
return null;
}
}
private static ReflectionBasedReferenceTypeDelegate create15Delegate(ReferenceType forReferenceType, Class forClass, ClassLoader usingClassLoader, World inWorld) {
try {
// important that we use *our own* classloader for the next call...
Class delegateClass = Class.forName("org.aspectj.weaver.reflect.Java15ReflectionBasedReferenceTypeDelegate",false,ReflectionBasedReferenceTypeDelegate.class.getClassLoader());
ReflectionBasedReferenceTypeDelegate ret = (ReflectionBasedReferenceTypeDelegate) delegateClass.newInstance();
ret.initialize(forReferenceType,forClass,usingClassLoader,inWorld);
return ret;
} catch (ClassNotFoundException cnfEx) {
return null;
} catch (InstantiationException insEx) {
return null;
} catch (IllegalAccessException illAccEx) {
return null;
}
}
/**
* convert a java.lang.reflect.Member into a resolved member in the world
* @param reflectMember
* @param inWorld
* @return
*/
public static ResolvedMember createResolvedMember(Member reflectMember, World inWorld) {
if (reflectMember instanceof Method) {
return createResolvedMethod((Method)reflectMember,inWorld);
} else if (reflectMember instanceof Constructor) {
return createResolvedConstructor((Constructor)reflectMember,inWorld);
} else {
return createResolvedField((Field)reflectMember,inWorld);
}
}
public static ResolvedMember createResolvedMethod(Method aMethod, World inWorld) {
ReflectionBasedResolvedMemberImpl ret = new ReflectionBasedResolvedMemberImpl(org.aspectj.weaver.Member.METHOD,
toResolvedType(aMethod.getDeclaringClass(),(ReflectionWorld)inWorld),
aMethod.getModifiers(),
toResolvedType(aMethod.getReturnType(),(ReflectionWorld)inWorld),
aMethod.getName(),
toResolvedTypeArray(aMethod.getParameterTypes(),inWorld),
toResolvedTypeArray(aMethod.getExceptionTypes(),inWorld),
aMethod
);
if (inWorld instanceof ReflectionWorld) {
ret.setAnnotationFinder(((ReflectionWorld)inWorld).getAnnotationFinder());
}
return ret;
}
public static ResolvedMember createResolvedAdviceMember(Method aMethod, World inWorld) {
ReflectionBasedResolvedMemberImpl ret =
new ReflectionBasedResolvedMemberImpl(org.aspectj.weaver.Member.ADVICE,
toResolvedType(aMethod.getDeclaringClass(),(ReflectionWorld)inWorld),
aMethod.getModifiers(),
toResolvedType(aMethod.getReturnType(),(ReflectionWorld)inWorld),
aMethod.getName(),
toResolvedTypeArray(aMethod.getParameterTypes(),inWorld),
toResolvedTypeArray(aMethod.getExceptionTypes(),inWorld),
aMethod
);
if (inWorld instanceof ReflectionWorld) {
ret.setAnnotationFinder(((ReflectionWorld)inWorld).getAnnotationFinder());
}
return ret;
}
public static ResolvedMember createStaticInitMember(Class forType, World inWorld) {
return new ResolvedMemberImpl(org.aspectj.weaver.Member.STATIC_INITIALIZATION,
toResolvedType(forType,(ReflectionWorld)inWorld),
Modifier.STATIC,
ResolvedType.VOID,
"<clinit>",
new UnresolvedType[0],
new UnresolvedType[0]
);
}
public static ResolvedMember createResolvedConstructor(Constructor aConstructor, World inWorld) {
ReflectionBasedResolvedMemberImpl ret =
new ReflectionBasedResolvedMemberImpl(org.aspectj.weaver.Member.CONSTRUCTOR,
toResolvedType(aConstructor.getDeclaringClass(),(ReflectionWorld)inWorld),
aConstructor.getModifiers(),
toResolvedType(aConstructor.getDeclaringClass(),(ReflectionWorld)inWorld),
"init",
toResolvedTypeArray(aConstructor.getParameterTypes(),inWorld),
toResolvedTypeArray(aConstructor.getExceptionTypes(),inWorld),
aConstructor
);
if (inWorld instanceof ReflectionWorld) {
ret.setAnnotationFinder(((ReflectionWorld)inWorld).getAnnotationFinder());
}
return ret;
}
public static ResolvedMember createResolvedField(Field aField, World inWorld) {
ReflectionBasedResolvedMemberImpl ret =
new ReflectionBasedResolvedMemberImpl(org.aspectj.weaver.Member.FIELD,
toResolvedType(aField.getDeclaringClass(),(ReflectionWorld)inWorld),
aField.getModifiers(),
toResolvedType(aField.getType(),(ReflectionWorld)inWorld),
aField.getName(),
new UnresolvedType[0],
aField);
if (inWorld instanceof ReflectionWorld) {
ret.setAnnotationFinder(((ReflectionWorld)inWorld).getAnnotationFinder());
}
return ret;
}
public static ResolvedMember createHandlerMember(Class exceptionType, Class inType,World inWorld) {
return new ResolvedMemberImpl(
org.aspectj.weaver.Member.HANDLER,
toResolvedType(inType,(ReflectionWorld)inWorld),
Modifier.STATIC,
"<catch>",
"(" + inWorld.resolve(exceptionType.getName()).getSignature() + ")V");
}
public static ResolvedType resolveTypeInWorld(Class aClass, World aWorld) {
// classes that represent arrays return a class name that is the signature of the array type, ho-hum...
String className = aClass.getName();
if (aClass.isArray()) {
return aWorld.resolve(UnresolvedType.forSignature(className));
}
else{
return aWorld.resolve(className);
}
}
private static ResolvedType toResolvedType(Class aClass, ReflectionWorld aWorld) {
return aWorld.resolve(aClass);
}
private static ResolvedType[] toResolvedTypeArray(Class[] classes, World inWorld) {
ResolvedType[] ret = new ResolvedType[classes.length];
for (int i = 0; i < ret.length; i++) {
ret[i] = ((ReflectionWorld)inWorld).resolve(classes[i]);
}
return ret;
}
}
|
118,337 |
Bug 118337 Use weaver's ClassLoader not the usingClassLoader in 1.5 factory
|
In ReflectionBasedReferenceTypeDelegateFactory this line (44) of code is breaking my use of the weaver for looking up bootstrap classes (where the classloader is null and the AspectJ weaver isn't accessible to the bootstrap loader). The commented out code works just fine for me. Is there a real need to resolve the AspectJ runtime from a different classloader than the one that was already used to load this class from the AspectJ runtime? Class delegateClass = Class.forName("org.aspectj.weaver.reflect.Java15ReflectionBasedReferenceTypeDelegate",false,usingClassLoader);//ReflectionBasedReferenceTypeDelegate.class.getClassLoader());
|
resolved fixed
|
d1a295c
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2005-11-29T19:35:57Z | 2005-11-29T02:06:40Z |
weaver/src/org/aspectj/weaver/reflect/ReflectionBasedReferenceTypeDelegateFactory.java
|
/* *******************************************************************
* Copyright (c) 2005 Contributors.
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Eclipse Public License v1.0
* which accompanies this distribution and is available at
* http://eclipse.org/legal/epl-v10.html
*
* Contributors:
* Adrian Colyer Initial implementation
* ******************************************************************/
package org.aspectj.weaver.reflect;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Member;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import org.aspectj.util.LangUtil;
import org.aspectj.weaver.ReferenceType;
import org.aspectj.weaver.ResolvedMember;
import org.aspectj.weaver.ResolvedMemberImpl;
import org.aspectj.weaver.ResolvedType;
import org.aspectj.weaver.UnresolvedType;
import org.aspectj.weaver.World;
/**
* @author colyer
* Creates the appropriate ReflectionBasedReferenceTypeDelegate according to
* the VM level we are running at. Uses reflection to avoid 1.5 dependencies in
* 1.4 and 1.3 code base.
*/
public class ReflectionBasedReferenceTypeDelegateFactory {
public static ReflectionBasedReferenceTypeDelegate
createDelegate(ReferenceType forReferenceType, World inWorld, ClassLoader usingClassLoader) {
try {
Class c = Class.forName(forReferenceType.getName(),false,usingClassLoader);
if (LangUtil.is15VMOrGreater()) {
ReflectionBasedReferenceTypeDelegate rbrtd = create15Delegate(forReferenceType,c,usingClassLoader,inWorld);
if (rbrtd!=null) return rbrtd; // can be null if we didn't find the class the delegate logic loads
}
return new ReflectionBasedReferenceTypeDelegate(c,usingClassLoader,inWorld,forReferenceType);
} catch (ClassNotFoundException cnfEx) {
return null;
}
}
private static ReflectionBasedReferenceTypeDelegate create15Delegate(ReferenceType forReferenceType, Class forClass, ClassLoader usingClassLoader, World inWorld) {
try {
Class delegateClass = Class.forName("org.aspectj.weaver.reflect.Java15ReflectionBasedReferenceTypeDelegate",false,usingClassLoader);//ReflectionBasedReferenceTypeDelegate.class.getClassLoader());
ReflectionBasedReferenceTypeDelegate ret = (ReflectionBasedReferenceTypeDelegate) delegateClass.newInstance();
ret.initialize(forReferenceType,forClass,usingClassLoader,inWorld);
return ret;
} catch (ClassNotFoundException cnfEx) {
throw new IllegalStateException("Attempted to create Java 1.5 reflection based delegate but org.aspectj.weaver.reflect.Java15ReflectionBasedReferenceTypeDelegate was not found on classpath");
} catch (InstantiationException insEx) {
throw new IllegalStateException("Attempted to create Java 1.5 reflection based delegate but InstantiationException: " + insEx + " occured");
} catch (IllegalAccessException illAccEx) {
throw new IllegalStateException("Attempted to create Java 1.5 reflection based delegate but IllegalAccessException: " + illAccEx + " occured");
}
}
/**
* convert a java.lang.reflect.Member into a resolved member in the world
* @param reflectMember
* @param inWorld
* @return
*/
public static ResolvedMember createResolvedMember(Member reflectMember, World inWorld) {
if (reflectMember instanceof Method) {
return createResolvedMethod((Method)reflectMember,inWorld);
} else if (reflectMember instanceof Constructor) {
return createResolvedConstructor((Constructor)reflectMember,inWorld);
} else {
return createResolvedField((Field)reflectMember,inWorld);
}
}
public static ResolvedMember createResolvedMethod(Method aMethod, World inWorld) {
ReflectionBasedResolvedMemberImpl ret = new ReflectionBasedResolvedMemberImpl(org.aspectj.weaver.Member.METHOD,
toResolvedType(aMethod.getDeclaringClass(),(ReflectionWorld)inWorld),
aMethod.getModifiers(),
toResolvedType(aMethod.getReturnType(),(ReflectionWorld)inWorld),
aMethod.getName(),
toResolvedTypeArray(aMethod.getParameterTypes(),inWorld),
toResolvedTypeArray(aMethod.getExceptionTypes(),inWorld),
aMethod
);
if (inWorld instanceof ReflectionWorld) {
ret.setAnnotationFinder(((ReflectionWorld)inWorld).getAnnotationFinder());
}
return ret;
}
public static ResolvedMember createResolvedAdviceMember(Method aMethod, World inWorld) {
ReflectionBasedResolvedMemberImpl ret =
new ReflectionBasedResolvedMemberImpl(org.aspectj.weaver.Member.ADVICE,
toResolvedType(aMethod.getDeclaringClass(),(ReflectionWorld)inWorld),
aMethod.getModifiers(),
toResolvedType(aMethod.getReturnType(),(ReflectionWorld)inWorld),
aMethod.getName(),
toResolvedTypeArray(aMethod.getParameterTypes(),inWorld),
toResolvedTypeArray(aMethod.getExceptionTypes(),inWorld),
aMethod
);
if (inWorld instanceof ReflectionWorld) {
ret.setAnnotationFinder(((ReflectionWorld)inWorld).getAnnotationFinder());
}
return ret;
}
public static ResolvedMember createStaticInitMember(Class forType, World inWorld) {
return new ResolvedMemberImpl(org.aspectj.weaver.Member.STATIC_INITIALIZATION,
toResolvedType(forType,(ReflectionWorld)inWorld),
Modifier.STATIC,
ResolvedType.VOID,
"<clinit>",
new UnresolvedType[0],
new UnresolvedType[0]
);
}
public static ResolvedMember createResolvedConstructor(Constructor aConstructor, World inWorld) {
ReflectionBasedResolvedMemberImpl ret =
new ReflectionBasedResolvedMemberImpl(org.aspectj.weaver.Member.CONSTRUCTOR,
toResolvedType(aConstructor.getDeclaringClass(),(ReflectionWorld)inWorld),
aConstructor.getModifiers(),
toResolvedType(aConstructor.getDeclaringClass(),(ReflectionWorld)inWorld),
"init",
toResolvedTypeArray(aConstructor.getParameterTypes(),inWorld),
toResolvedTypeArray(aConstructor.getExceptionTypes(),inWorld),
aConstructor
);
if (inWorld instanceof ReflectionWorld) {
ret.setAnnotationFinder(((ReflectionWorld)inWorld).getAnnotationFinder());
}
return ret;
}
public static ResolvedMember createResolvedField(Field aField, World inWorld) {
ReflectionBasedResolvedMemberImpl ret =
new ReflectionBasedResolvedMemberImpl(org.aspectj.weaver.Member.FIELD,
toResolvedType(aField.getDeclaringClass(),(ReflectionWorld)inWorld),
aField.getModifiers(),
toResolvedType(aField.getType(),(ReflectionWorld)inWorld),
aField.getName(),
new UnresolvedType[0],
aField);
if (inWorld instanceof ReflectionWorld) {
ret.setAnnotationFinder(((ReflectionWorld)inWorld).getAnnotationFinder());
}
return ret;
}
public static ResolvedMember createHandlerMember(Class exceptionType, Class inType,World inWorld) {
return new ResolvedMemberImpl(
org.aspectj.weaver.Member.HANDLER,
toResolvedType(inType,(ReflectionWorld)inWorld),
Modifier.STATIC,
"<catch>",
"(" + inWorld.resolve(exceptionType.getName()).getSignature() + ")V");
}
public static ResolvedType resolveTypeInWorld(Class aClass, World aWorld) {
// classes that represent arrays return a class name that is the signature of the array type, ho-hum...
String className = aClass.getName();
if (aClass.isArray()) {
return aWorld.resolve(UnresolvedType.forSignature(className));
}
else{
return aWorld.resolve(className);
}
}
private static ResolvedType toResolvedType(Class aClass, ReflectionWorld aWorld) {
return aWorld.resolve(aClass);
}
private static ResolvedType[] toResolvedTypeArray(Class[] classes, World inWorld) {
ResolvedType[] ret = new ResolvedType[classes.length];
for (int i = 0; i < ret.length; i++) {
ret[i] = ((ReflectionWorld)inWorld).resolve(classes[i]);
}
return ret;
}
}
|
111,667 |
Bug 111667 Produce a compile warning when default advice precedence is applied
|
I propose that the compiler spit out a warning anytime that it has to apply the default advice precedence. Also, it should spit out the recommendation that default ordering is not guaranteed from release to release of the compiler. You can see the thread on aspectj-dev titled "change in runtime execution order" and the one on aspectj-users titled "AJDT 1.3 and aspectj" for the reasoning behind why this is a good thing.
|
resolved fixed
|
2c81907
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2005-11-30T17:23:35Z | 2005-10-05T19:20:00Z |
tests/src/org/aspectj/systemtest/ajc150/Ajc150Tests.java
|
/*******************************************************************************
* Copyright (c) 2004 IBM
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* Andy Clement - initial API and implementation
*******************************************************************************/
package org.aspectj.systemtest.ajc150;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.List;
import junit.framework.Test;
import org.aspectj.apache.bcel.classfile.JavaClass;
import org.aspectj.apache.bcel.classfile.Method;
import org.aspectj.apache.bcel.classfile.Signature;
import org.aspectj.apache.bcel.util.ClassPath;
import org.aspectj.apache.bcel.util.SyntheticRepository;
import org.aspectj.asm.AsmManager;
import org.aspectj.asm.IHierarchy;
import org.aspectj.asm.IProgramElement;
import org.aspectj.asm.IRelationship;
import org.aspectj.asm.internal.Relationship;
import org.aspectj.testing.XMLBasedAjcTestCase;
import org.aspectj.util.LangUtil;
public class Ajc150Tests extends org.aspectj.testing.XMLBasedAjcTestCase {
public static Test suite() {
return XMLBasedAjcTestCase.loadSuite(Ajc150Tests.class);
}
protected File getSpecFile() {
return new File("../tests/src/org/aspectj/systemtest/ajc150/ajc150.xml");
}
/*
public void testBrokenDispatchByITD_pr72834() { runTest("broken dispatch");}
public void testMissingAccessor_pr73856() { runTest("missing accessor");}
public void testCunningDeclareParents_pr92311() { runTest("cunning declare parents");}
public void testGenericITDsAndAbstractMethodError_pr102357() { runTest("generic itds and abstract method error");}
*/
public void testGeneratingCodeForAnOldRuntime_pr116679_1() { runTest("generating code for a 1.2.1 runtime - 1");}
public void testGeneratingCodeForAnOldRuntime_pr116679_2() { runTest("generating code for a 1.2.1 runtime - 2");}
public void testAtDeclareParents_pr117681() { runTest("at declare parents");}
public void testPrivilegeProblem_pr87525() { runTest("privilege problem with switch");}
public void testGenericAspects_pr115237() { runTest("aspectOf and generic aspects");}
public void testClassFormatError_pr114436() { runTest("ClassFormatError binary weaving perthis");}
public void testParserException_pr115788() { runTest("parser exception");}
public void testPossibleStaticImports_pr113066_1() { runTest("possible static imports bug - 1");}
public void testPossibleStaticImports_pr113066_2() { runTest("possible static imports bug - 2");}
public void testPossibleStaticImports_pr113066_3() { runTest("possible static imports bug - 3");}
public void testITDCtor_pr112783() { runTest("Problem with constructor ITDs");}
public void testAnnotatedITDFs_pr114005_1() { runTest("Annotated ITDFs - 1");}
public void testAnnotatedITDFs_pr114005_2() { runTest("Annotated ITDFs - 2");}
public void testCantCallSuperMethods_pr90143() { runTest("cant call super methods");}
public void testBrokenDecp_pr112476() { runTest("binary weaving decp broken");}
public void testUnboundFormal_pr112027() { runTest("unexpected error unboundFormalInPC");}
public void testNPEScopeSetup_pr115038() { runTest("NPE in ensureScopeSetup");}
public void testCCEGenerics_pr113445() { runTest("Generics ClassCastException");}
public void testMatthewsAspect_pr113947_1() { runTest("maws generic aspect - 1");}
public void testMatthewsAspect_pr113947_2() { runTest("maws generic aspect - 2");}
public void testFieldGet_pr114343() { runTest("field-get, generics and around advice");}
public void testFieldGet_pr114343_2() { runTest("field-get, generics and around advice - 2");}
public void testFieldGet_pr114343_3() { runTest("field-get, generics and around advice - 3");}
public void testCaptureBinding_pr114744() { runTest("capturebinding wildcard problem");}
public void testBadDecp_pr110788_1() { runTest("bad generic decp - 1");}
public void testBadDecp_pr110788_2() { runTest("bad generic decp - 2");}
public void testBadDecp_pr110788_3() { runTest("bad generic decp - 3");}
public void testBadDecp_pr110788_4() { runTest("bad generic decp - 4");}
public void testVarargsITD_pr110906() { runTest("ITD varargs problem");}
public void testBadRenderer_pr86903() { runTest("bcelrenderer bad");}
//public void testLintForAdviceSorting_pr111667() { runTest("lint for advice sorting");}
public void testIncompatibleClassChangeError_pr113630_1() {runTest("IncompatibleClassChangeError - errorscenario");}
public void testIncompatibleClassChangeError_pr113630_2() {runTest("IncompatibleClassChangeError - workingscenario");}
public void testFieldGetProblemWithGenericField_pr113861() {runTest("field-get problems with generic field");}
public void testDeclareAnnotationOnNonExistentType_pr99191_1() { runTest("declare annotation on non existent type - 1");}
public void testDeclareAnnotationOnNonExistentType_pr99191_2() { runTest("declare annotation on non existent type - 2");}
public void testDeclareAnnotationOnNonExistentType_pr99191_3() { runTest("declare annotation on non existent type - 3");}
public void testDeclareAnnotationOnNonExistentType_pr99191_4() { runTest("declare annotation on non existent type - 4");}
public void testDeclareAnnotationOnNonExistentType_pr99191_5() { runTest("declare annotation on non existent type - 5");}
public void testBadGenericSigAttribute_pr110927() {
runTest("cant create signature attribute");
Signature sig = GenericsTests.getClassSignature(ajc,"I");
if (sig==null) fail("Couldn't find signature attribute for type I");
String sigString = sig.getSignature();
if (!(sigString.equals("Ljava/lang/Object;LIE2;LIE1<Ljava/lang/String;>;") ||
sigString.equals("Ljava/lang/Object;LIE1<Ljava/lang/String;>;LIE2;"))) {
fail("Signature was "+sigString+" when should have been something like Ljava/lang/Object;LIE1<Ljava/lang/String;>;LIE2;");
}
}
public void test_typeProcessingOrderWhenDeclareParents() {
runTest("Order of types passed to compiler determines weaving behavior");
}
public void test_aroundMethod() {
runTest("method called around in class");
}
public void test_aroundMethodAspect() {
runTest("method called around in aspect");
}
public void test_ambiguousBindingsDetection() {
runTest("Various kinds of ambiguous bindings");
}
public void test_ambiguousArgsDetection() {
runTest("ambiguous args");
}
public void testIncorrectExceptionTableWhenBreakInMethod_pr78021() {
runTest("Injecting exception into while loop with break statement causes catch block to be ignored");
}
public void testIncorrectExceptionTableWhenReturnInMethod_pr79554() {
runTest("Return in try-block disables catch-block if final-block is present");
}
public void testMissingDebugInfoForGeneratedMethods_pr82570() throws ClassNotFoundException {
runTest("Weaved code does not include debug lines");
boolean f = false;
JavaClass jc = getClassFrom(ajc.getSandboxDirectory(),"PR82570_1");
Method[] meths = jc.getMethods();
for (int i = 0; i < meths.length; i++) {
Method method = meths[i];
if (f) System.err.println("Line number table for "+method.getName()+method.getSignature()+" = "+method.getLineNumberTable());
assertTrue("Didn't find a line number table for method "+method.getName()+method.getSignature(),
method.getLineNumberTable()!=null);
}
// This test would determine the info isn't there if you pass -g:none ...
// cR = ajc(baseDir,new String[]{"PR82570_1.java","-g:none"});
// assertTrue("Expected no compile problem:"+cR,!cR.hasErrorMessages());
// System.err.println(cR.getStandardError());
// jc = getClassFrom(ajc.getSandboxDirectory(),"PR82570_1");
// meths = jc.getMethods();
// for (int i = 0; i < meths.length; i++) {
// Method method = meths[i];
// assertTrue("Found a line number table for method "+method.getName(),
// method.getLineNumberTable()==null);
// }
}
public void testCanOverrideProtectedMethodsViaITDandDecp_pr83303() {
runTest("compiler error when mixing inheritance, overriding and polymorphism");
}
public void testPerTypeWithin_pr106554() {runTest("Problem in staticinitialization with pertypewithin aspect");}
public void testPerTypeWithinMissesNamedInnerTypes() {
runTest("pertypewithin() handing of inner classes (1)");
}
public void testPerTypeWithinMissesAnonymousInnerTypes() {
runTest("pertypewithin() handing of inner classes (2)");
}
public void testPerTypeWithinIncorrectlyMatchingInterfaces() {
runTest("pertypewithin({interface}) illegal field modifier");
}
public void test051_arrayCloningInJava5() {
runTest("AJC possible bug with static nested classes");
}
public void testBadASMforEnums() throws IOException {
runTest("bad asm for enums");
if (LangUtil.is15VMOrGreater()) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
PrintWriter pw = new PrintWriter(baos);
AsmManager.dumptree(pw,AsmManager.getDefault().getHierarchy().getRoot(),0);
pw.flush();
String tree = baos.toString();
assertTrue("Expected 'Red [enumvalue]' somewhere in here:"+tree,tree.indexOf("Red [enumvalue]")!=-1);
}
}
public void npeOnTypeNotFound() {
runTest("structure model npe on type not found");
}
public void testNoRuntimeExceptionSoftening() {
runTest("declare soft of runtime exception");
}
public void testRuntimeNoSoftenWithHandler() {
runTest("declare soft w. catch block");
}
public void testSyntaxError() {
runTest("invalid cons syntax");
}
public void testVarargsInConsBug() {
runTest("varargs in constructor sig");
}
public void testAspectpathdirs() {
runTest("dirs on aspectpath");
}
public void testIntroSample() {
runTest("introduction sample");
}
public void testPTWInterface() {
runTest("pertypewithin({interface}) illegal field modifier");
}
public void testEnumCalledEnumEtc() {
runTest("enum called Enum, annotation called Annotation, etc");
}
public void testInternalCompilerError_pr86832() {
runTest("Internal compiler error");
}
public void testCloneMethod_pr83311() {
runTest("overriding/polymorphism error on interface method introduction");
}
// IfPointcut.findResidueInternal() was modified to make this test complete in a short amount
// of time - if you see it hanging, someone has messed with the optimization.
public void testIfEvaluationExplosion_pr94086() {
runTest("Exploding compile time with if() statements in pointcut");
}
public void testReflectNPE_pr94167() {runTest("NPE in reflect implementation");}
public void testStaticImports_pr84260() {runTest("static import failures");}
public void testGenerics_pr99089() {runTest("ArrayIndexOutOfBoundsException - Generics in privileged aspects");}
public void testGenerics_pr95993() {runTest("NPE at ClassScope.java:660 when compiling generic class");}
public void testItdGenerics_pr99228() {runTest("ITD of a field into a generic class");}
public void testItdGenerics_pr98320() {runTest("intertype with nested generic type");}
public void testItdGenerics_pr100227() {runTest("inner class with generic enclosing class");}
public void testItdGenerics_pr100260() {runTest("methods inherited from a generic parent");}
public void testSyntaxErrorNPE_pr103266() {runTest("NPE on syntax error");}
public void testFinalAbstractClass_pr109486() { runTest("Internal compiler error (ClassParser.java:242)");}
public void testComplexBinding_pr102210() { runTest("NullPointerException trying to compile");}
public void testIllegalStateExceptionOnNestedParameterizedType_pr106634() {
runTest("IllegalStateException unpacking signature of nested parameterized type");
}
public void testParseErrorOnAnnotationStarPlusPattern() {
runTest("(@Foo *)+ type pattern parse error");
}
public void test_pr106130_tooManyLocals() {
runTest("test weaving with > 256 locals");
}
public void testMissingNamePattern_pr106461() { runTest("missing name pattern"); }
public void testMissingNamePattern_pr107059() {
runTest("parser crashes on call(void (@a *)(..)");
}
public void testIntermediateAnnotationMatching() {
runTest("intermediate annotation matching");
}
public void testBadRuntimeTestGeneration() {
runTest("target(@Foo *)");
}
public void testErrorMessageOnITDWithTypePatterns() {
runTest("clear error message on itd with type pattern");
}
public void testAjKeywordsAsIdentifiers() {
runTest("before and after are valid identifiers in classes");
}
public void testAjKeywordsAsIdentifiers2() {
runTest("before and after are valid identifiers in classes, part 2");
}
public void testNoBeforeReturningAdvice() {
runTest("before returning advice not allowed!");
}
public void testDetectVoidFieldType() {
runTest("void field type in pointcut expression");
}
public void testPointcutOverriding() {
runTest("overriding final pointcut from super-aspect");
}
public void testAtSuppressWarnings() {
runTest("@SuppressWarnings should suppress");
}
public void testDEOWWithBindingPointcut() {
runTest("declare warning : foo(str) : ...;");
}
public void testAroundAdviceAndInterfaceInitializer() {
runTest("around advice on interface initializer");
}
public void testGoodErrorMessageOnUnmatchedMemberSyntax() {
runTest("good error message for unmatched member syntax");
}
public void testITDWithNoExceptionAndIntermediary() {
runTest("itd override with no exception clause");
}
public void testAnonymousInnerClasses() {
runTest("anonymous inner classes");
}
public void testMultipleAnonymousInnerClasses() {
runTest("multiple anonymous inner classes");
}
public void testPrivilegedMethodAccessorsGetRightExceptions_pr82989() {
runTest("Compiler error due to a wrong exception check in try blocks");
}
public void testAnonymousInnerClassWithMethodReturningTypeParameter_pr107898() {
runTest("anonymous inner class with method returning type parameter");
}
public void testMatchingOfObjectArray() {
runTest("matching against Object[]");
}
public void testMultipleAnonymousInnerClasses_pr108104() {
runTest("multiple anonymous inner classes 2");
}
public void testSignatureMatchingInMultipleOverrideScenario() {
runTest("signature matching in override scenario");
}
public void testWildcardAnnotationMatching_pr108245() {
runTest("wildcard annotation matching - pr108245");
}
public void testInnerTypesAndTypeVariables() {
runTest("inner types and type variables");
}
public void testAtAfterThrowingWithNoFormal() {
runTest("@AfterThrowing with no formal specified");
}
public void testParameterizedVarArgsMatch() {
runTest("varargs with type variable");
}
public void testFieldAccessInsideITDM() {
runTest("itd field access inside itd method");
}
public void testTypeVarWithTypeVarBound() {
runTest("type variable with type variable bound");
}
public void testEnumSwitchInITD() {
runTest("switch on enum inside ITD method");
}
public void testInnerTypeOfGeneric() {
runTest("inner type of generic interface reference from parameterized type");
}
public void testDeclareParentsIntroducingCovariantReturnType() {
runTest("declare parents introducing override with covariance");
}
public void testInnerClassPassedToVarargs() {
runTest("inner class passed as argument to varargs method");
}
public void testInlinedFieldAccessInProceedCall() {
runTest("inlined field access in proceed call");
}
public void testVisibiltyInSignatureMatchingWithOverridesPart1() {
runTest("visibility in signature matching with overrides - 1");
}
public void testVisibiltyInSignatureMatchingWithOverridesPart2() {
runTest("visibility in signature matching with overrides - 2");
}
public void testVisibiltyInSignatureMatchingWithOverridesPart3() {
runTest("visibility in signature matching with overrides - 3");
}
public void testArgsGeneratedCorrectlyForAdviceExecution() {
runTest("args generated correctly for advice execution join point");
}
public void testNoUnusedWarningsOnAspectTypes() {
runTest("no unused warnings on aspect types");
}
public void testSyntheticArgumentsOnITDConstructorsNotUsedInMatching() {
runTest("synthetic arguments on itd cons are not used in matching");
}
public void testParsingOfGenericTypeSignature() {
runTest("parse generic type signature with parameterized type in interface");
}
public void testOverrideAndCovarianceWithDecPRuntime() {
runTest("override and covariance with decp - runtime");
}
public void testOverrideAndCovarianceWithDecPRuntimeMultiFiles() {
runTest("override and covariance with decp - runtime separate files");
}
public void testOverrideAndCovarianceWithDecPRuntimeMultiFilesBinaryWeaving() {
runTest("override and covariance with decp - binary weaving");
}
public void testAbstractSynchronizedITDMethods() {
runTest("abstract synchronized itdms not detected");
}
public void testSynchronizedITDInterfaceMethods() {
runTest("synchronized itd interface methods");
}
public void testNoWarningOnUnusedPointcut() {
runTest("unused private pointcuts");
}
public void testITDOnInterfaceWithExistingMember() {
runTest("itd interface method already existing on interface");
}
public void testFinalITDMOnInterface() {
runTest("final itd methods on interfaces");
}
public void testPrivatePointcutOverriding() {
runTest("can't override private pointcut in abstract aspect");
}
public void testAdviceOnCflow() {
runTest("advising cflow advice execution");
}
public void testNoTypeMismatchOnSameGenericTypes() {
runTest("no type mismatch on generic types in itds");
}
public void testSuperCallInITD() {
runTest("super call in ITD");
}
public void testSuperCallInITDPart2() {
runTest("super call in ITD - part 2");
}
public void testAtAnnotationBadTest_pr103740() {
runTest("Compiler failure on at_annotation");
}
public void testNoUnusedParameterWarningsForSyntheticAdviceArgs() {
runTest("no unused parameter warnings for synthetic advice args");
}
public void testNoVerifyErrorWithSetOnInnerType() {
runTest("no verify error with set on inner type");
}
public void testCantFindTypeErrorWithGenericReturnTypeOrParameter() {
runTest("cant find type error with generic return type or parameter");
}
public void testNoVerifyErrorOnGenericCollectionMemberAccess() {
runTest("no verify error on generic collection member access");
}
public void testRawAndGenericTypeConversionITDCons() {
runTest("raw and generic type conversion with itd cons");
}
public void testAtAnnotationBindingWithAround() {
runTest("@annotation binding with around advice");
}
public void testUnableToBuildShadows_pr109728() { runTest("Unable to build shadows");}
public void testMessageOnMissingTypeInDecP() {
runTest("declare parents on a missing type");
}
public void testParameterizedGenericMethods() {
runTest("parameterized generic methods");
}
public void testIllegalChangeToPointcutDeclaration_pr111915() {
runTest("test illegal change to pointcut declaration");
}
public void testCantProvideDefaultImplViaITD_pr110307_1() {runTest("Cant provide default implementation via ITD - 1");}
public void testCantProvideDefaultImplViaITD_pr110307_2() {runTest("Cant provide default implementation via ITD - 2");}
public void testCantProvideDefaultImplViaITD_pr110307_3() {runTest("Cant provide default implementation via ITD - 3");}
public void testCantProvideDefaultImplViaITD_pr110307_4() {runTest("Cant provide default implementation via ITD - 4");}
public void testCantProvideDefaultImplViaITD_pr110307_5() {runTest("Cant provide default implementation via ITD - 5");}
// Needs a change in the compiler so that getType() can be overridden in the intertype scope - thats
// where we can police whether a type variable has been used without being specified appropriately.
//public void testCantProvideDefaultImplViaITD_pr110307_6() {runTest("Cant provide default implementation via ITD - 6");}
public void testCantProvideDefaultImplViaITD_pr110307_7() {runTest("Cant provide default implementation via ITD - 7");}
public void testCallJoinPointsInAnonymousInnerClasses() {
runTest("call join points in anonymous inner classes");
}
public void testNoRequirementForUnwovenTypesToBeExposedToWeaver() {
runTest("default impl of Runnable");
}
public void testArrayCloneCallJoinPoints() {
runTest("array clone call join points in 1.4 vs 1.3");
}
public void testDebugInfoForAroundAdvice() {
runTest("debug info in around advice inlining");
}
public void testCCEWithGenericWildcard_pr112602() {
runTest("ClassCastException with generic wildcard");
}
public void testAdviceInStructureModelWithAnonymousInnerClass_pr77269() {
//AsmManager.setReporting("c:/debug.txt",true,true,true,true);
runTest("advice in structure model with anonymous inner class");
IHierarchy top = AsmManager.getDefault().getHierarchy();
// checking that the run() method inside anonymous inner class is in
// the structure model
IProgramElement anonRunMethodIPE = top.findElementForLabel(top.getRoot(),
IProgramElement.Kind.METHOD,"run()");
assertNotNull("Couldn't find 'run()' element in the tree",anonRunMethodIPE);
List l = AsmManager.getDefault().getRelationshipMap().get(anonRunMethodIPE);
assertNotNull("Should have some relationships but does not",l);
assertTrue("Should have one relationship but has " + l.size(),l.size()==1);
Relationship rel = (Relationship)l.get(0);
List targets = rel.getTargets();
assertTrue("Should have one target but has" + targets.size(),
targets.size()==1);
IProgramElement target = AsmManager.getDefault().getHierarchy().findElementForHandle((String)targets.get(0));
assertEquals("target of relationship should be 'before(): p..' but is "
+ target.toLabelString(),"before(): p..",target.toLabelString());
IProgramElement adviceIPE = top.findElementForLabel(top.getRoot(),
IProgramElement.Kind.ADVICE,"before(): p..");
assertNotNull("Couldn't find 'before(): p..' element in the tree",adviceIPE);
l = AsmManager.getDefault().getRelationshipMap().get(adviceIPE);
assertNotNull("Should have some relationships but does not",l);
assertTrue("Should have a relationship but does not ",l.size()>0);
for (Iterator iter = l.iterator(); iter.hasNext();) {
IRelationship element = (IRelationship) iter.next();
if (element.getName().equals("advises")) {
rel = (Relationship) element;
break;
}
}
targets = rel.getTargets();
assertTrue("Should have one target but has" + targets.size(),
targets.size()==1);
target = AsmManager.getDefault().getHierarchy().findElementForHandle((String)targets.get(0));
assertEquals("target of relationship should be 'run()' but is "
+ target.toLabelString(),"run()",target.toLabelString());
}
public void testAdviceInStructureModelWithNamedInnerClass_pr77269() {
//AsmManager.setReporting("c:/debug.txt",true,true,true,true);
runTest("advice in structure model with named inner class");
IHierarchy top = AsmManager.getDefault().getHierarchy();
// checking that the m() method inside named inner class is in
// the structure model
IProgramElement namedMethodIPE = top.findElementForLabel(top.getRoot(),
IProgramElement.Kind.METHOD,"m()");
assertNotNull("Couldn't find 'm()' element in the tree",namedMethodIPE);
List l = AsmManager.getDefault().getRelationshipMap().get(namedMethodIPE);
assertNotNull("Should have some relationships but does not",l);
assertTrue("Should have one relationship but has " + l.size(),l.size()==1);
Relationship rel = (Relationship)l.get(0);
List targets = rel.getTargets();
assertTrue("Should have one target but has" + targets.size(),
targets.size()==1);
IProgramElement target = AsmManager.getDefault().getHierarchy().findElementForHandle((String)targets.get(0));
assertEquals("target of relationship should be 'before(): p..' but is "
+ target.toLabelString(),"before(): p..",target.toLabelString());
IProgramElement adviceIPE = top.findElementForLabel(top.getRoot(),
IProgramElement.Kind.ADVICE,"before(): p..");
assertNotNull("Couldn't find 'before(): p..' element in the tree",adviceIPE);
l = AsmManager.getDefault().getRelationshipMap().get(adviceIPE);
assertNotNull("Should have some relationships but does not",l);
assertTrue("Should have a relationship but does not ",l.size()>0);
for (Iterator iter = l.iterator(); iter.hasNext();) {
IRelationship element = (IRelationship) iter.next();
if (element.getName().equals("advises")) {
rel = (Relationship) element;
break;
}
}
targets = rel.getTargets();
assertTrue("Should have one target but has" + targets.size(),
targets.size()==1);
target = AsmManager.getDefault().getHierarchy().findElementForHandle((String)targets.get(0));
assertEquals("target of relationship should be 'm()' but is "
+ target.toLabelString(),"m()",target.toLabelString());
}
public void testDWInStructureModelWithAnonymousInnerClass_pr77269() {
// AsmManager.setReporting("c:/debug.txt",true,true,true,true);
runTest("declare warning in structure model with anonymous inner class");
IHierarchy top = AsmManager.getDefault().getHierarchy();
IProgramElement pe = top.findElementForLabel(top.getRoot(),
IProgramElement.Kind.CODE,"method-call(void pack.Test.someMethod())");
assertNotNull("Couldn't find 'method-call(void pack.Test.someMethod())' element in the tree",pe);
}
public void testVarArgsIITDInConstructor() {
runTest("ITD varargs in constructor");
}
public void testWeaveInfoMessageForDeclareAtMethodOnITDdMethod() {
runTest("weaveinfo message for declare at method on an ITDd method");
}
public void testITDCWithNoExplicitConsCall() {
runTest("ITDC with no explicit cons call");
}
public void testJava5SpecificFeaturesUsedAtJava14OrLower() {
runTest("java 5 pointcuts and declares at pre-java 5 compliance levels");
}
public void testAnonymousTypes() {
runTest("Anonymous types and nome matching");
}
public void testAdviceExecutionJPToStringForms() {
runTest("adviceexecution join point toString forms");
}
public void testAssertWithinPointcutExpression() {
runTest("pointcut expression containing 'assert'");
}
public void testNoVerifyErrorWithTwoThisPCDs_pr113447() {
runTest("no verify error with two this pcds");
}
public void testNoVerifyErrorWithTwoAtThisPCDs_pr113447() {
runTest("no verify error with two at this pcds");
}
public void testNoVerifyErrorWithAtWithinPCDs_pr113447() {
runTest("no verify error with at within pcds");
}
public void testNoVerifyErrorWithAtWithincodePCDs_pr113447() {
runTest("no verify error with at withincode pcds");
}
public void testNoVerifyErrorWithAtAnnotationPCDs_pr113447() {
runTest("no verify error with at annotation pcds");
}
public void testNoVerifyErrorWithTwoArgsPCDs_pr113447() {
runTest("no verify error with two args pcds");
}
public void testNoStackOverflowWithCircularPCDInGenericAspect() {
runTest("no StackOverflowError with circular pcd in generic aspect");
}
public void testNoStackOverflowWithCircularPCDInGenericAspect2() {
runTest("no StackOverflowError with circular pcd in generic aspect - 2");
}
public void testNPEInThisJoinPointStaticPart() {
runTest("thisJoinPointStaticPart in if test");
}
public void testPointcutParsingOfCompiledPointcuts() {
runTest("pointcut parsing with ajc compiled pointcut references");
}
public void testReflectionOfAbstractITDs() {
runTest("reflection on abstract ITDs (Billing example)");
}
public void testDeclareSoftWithAdviceExecution() {
runTest("declare soft and adviceexecution");
}
public void testDeclareSoftWithExclusions() {
runTest("declare soft and exclusions");
}
public void testReturningObjectBinding() {
runTest("returning(Object) binding");
}
public void testPerTargetAndNegation() {
runTest("pertarget and negated pointcut");
}
public void testParameterizedPointcutAndAdvice() {
runTest("parameterized pointcut and advice");
}
public void testDoublyParameterizedAbstractType() {
runTest("double parameter generic abstract type");
}
public void testArgNamesInAdviceAnnotations() {
runTest("arg names in advice annotations");
}
/*
* Load-time weaving bugs
*/
public void testNPEinWeavingAdaptor_pr116626() { runTest("NPE in WeavingAdaptor");}
public void testXlintMessageForImproperAnnotationType_pr115252_Exact() {runTest("xlint message for improper exact annotation type");}
public void testXlintMessageForImproperAnnotationType_pr115252_OR() {runTest("xlint message for improper annotation type inside OR");}
public void testXlintMessageForImproperAnnotationType_pr115252_AND() {runTest("xlint message for improper annotation type inside AND");}
public void testXlintMessageForImproperAnnotationType_pr115252_Return() {runTest("xlint message for improper annotated return type");}
public void testXlintMessageForImproperAnnotationType_pr115252_Declaring() {runTest("xlint message for improper annotated declaring type");}
public void testXlintMessageForImproperAnnotationType_pr115252_Parameter() {runTest("xlint message for improper annotated parameter type");}
public void testXlintMessageForImproperAnnotationType_pr115252_Throws() {runTest("xlint message for improper annotated throws pattern");}
public void testXlintMessageForImproperAnnotationType_pr115252_MoreThanOne() {runTest("xlint message for more than one improper annotated parameter type");}
public void testDeclareAtTypeInStructureModel_pr115607() {
AsmManager.setReporting("c:/debug.txt",true,true,true,true);
runTest("declare at type appears correctly in structure model");
IHierarchy top = AsmManager.getDefault().getHierarchy();
IProgramElement pe = top.findElementForLabel(top.getRoot(),
IProgramElement.Kind.DECLARE_ANNOTATION_AT_TYPE,"declare @type: Simple : @I");
assertNotNull("Couldn't find 'declare @type: Simple : @I' element in the tree",pe);
List l = AsmManager.getDefault().getRelationshipMap().get(pe);
assertNotNull("Should have some relationships but does not",l);
}
// helper methods.....
public SyntheticRepository createRepos(File cpentry) {
ClassPath cp = new ClassPath(cpentry+File.pathSeparator+System.getProperty("java.class.path"));
return SyntheticRepository.getInstance(cp);
}
protected JavaClass getClassFrom(File where,String clazzname) throws ClassNotFoundException {
SyntheticRepository repos = createRepos(where);
return repos.loadClass(clazzname);
}
}
|
111,667 |
Bug 111667 Produce a compile warning when default advice precedence is applied
|
I propose that the compiler spit out a warning anytime that it has to apply the default advice precedence. Also, it should spit out the recommendation that default ordering is not guaranteed from release to release of the compiler. You can see the thread on aspectj-dev titled "change in runtime execution order" and the one on aspectj-users titled "AJDT 1.3 and aspectj" for the reasoning behind why this is a good thing.
|
resolved fixed
|
2c81907
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2005-11-30T17:23:35Z | 2005-10-05T19:20:00Z |
weaver/src/org/aspectj/weaver/Lint.java
|
/* *******************************************************************
* Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC).
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* PARC initial implementation
* ******************************************************************/
package org.aspectj.weaver;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.MessageFormat;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Properties;
import org.aspectj.bridge.IMessage;
import org.aspectj.bridge.ISourceLocation;
import org.aspectj.bridge.Message;
import org.aspectj.bridge.MessageUtil;
public class Lint {
/* private */ Map kinds = new HashMap();
/* private */ World world;
public final Kind invalidAbsoluteTypeName =
new Kind("invalidAbsoluteTypeName", "no match for this type name: {0}");
public final Kind invalidWildcardTypeName =
new Kind("invalidWildcardTypeName", "no match for this type pattern: {0}");
public final Kind unresolvableMember =
new Kind("unresolvableMember", "can not resolve this member: {0}");
public final Kind typeNotExposedToWeaver =
new Kind("typeNotExposedToWeaver", "this affected type is not exposed to the weaver: {0}");
public final Kind shadowNotInStructure =
new Kind("shadowNotInStructure", "the shadow for this join point is not exposed in the structure model: {0}");
public final Kind unmatchedSuperTypeInCall =
new Kind("unmatchedSuperTypeInCall", "does not match because declaring type is {0}, if match desired use target({1})");
public final Kind unmatchedTargetKind =
new Kind("unmatchedTargetKind", "does not match because annotation {0} has @Target{1}");
public final Kind canNotImplementLazyTjp =
new Kind("canNotImplementLazyTjp", "can not implement lazyTjp on this joinpoint {0} because around advice is used");
public final Kind multipleAdviceStoppingLazyTjp =
new Kind("multipleAdviceStoppingLazyTjp", "can not implement lazyTjp at joinpoint {0} because of advice conflicts, see secondary locations to find conflicting advice");
public final Kind needsSerialVersionUIDField =
new Kind("needsSerialVersionUIDField", "serialVersionUID of type {0} needs to be set because of {1}");
public final Kind serialVersionUIDBroken =
new Kind("brokeSerialVersionCompatibility", "serialVersionUID of type {0} is broken because of added field {1}");
public final Kind noInterfaceCtorJoinpoint =
new Kind("noInterfaceCtorJoinpoint","no interface constructor-execution join point - use {0}+ for implementing classes");
public final Kind noJoinpointsForBridgeMethods =
new Kind("noJoinpointsForBridgeMethods","pointcut did not match on the method call to a bridge method. Bridge methods are generated by the compiler and have no join points");
public final Kind enumAsTargetForDecpIgnored =
new Kind("enumAsTargetForDecpIgnored","enum type {0} matches a declare parents type pattern but is being ignored");
public final Kind annotationAsTargetForDecpIgnored =
new Kind("annotationAsTargetForDecpIgnored","annotation type {0} matches a declare parents type pattern but is being ignored");
public final Kind cantMatchArrayTypeOnVarargs =
new Kind("cantMatchArrayTypeOnVarargs","an array type as the last parameter in a signature does not match on the varargs declared method: {0}");
public final Kind adviceDidNotMatch =
new Kind("adviceDidNotMatch","advice defined in {0} has not been applied");
public final Kind invalidTargetForAnnotation =
new Kind("invalidTargetForAnnotation","{0} is not a valid target for annotation {1}, this annotation can only be applied to {2}");
public final Kind elementAlreadyAnnotated =
new Kind("elementAlreadyAnnotated","{0} - already has an annotation of type {1}, cannot add a second instance");
public final Kind runtimeExceptionNotSoftened =
new Kind("runtimeExceptionNotSoftened","{0} will not be softened as it is already a RuntimeException");
public final Kind uncheckedArgument =
new Kind("uncheckedArgument","unchecked match of {0} with {1} when argument is an instance of {2} at join point {3}");
public final Kind uncheckedAdviceConversion =
new Kind("uncheckedAdviceConversion","unchecked conversion when advice applied at shadow {0}, expected {1} but advice uses {2}");
public final Kind noGuardForLazyTjp =
new Kind("noGuardForLazyTjp","can not build thisJoinPoint lazily for this advice since it has no suitable guard. The advice applies at {0}");
public final Kind noExplicitConstructorCall =
new Kind("noExplicitConstructorCall","inter-type constructor does not contain explicit constructor call: field initializers in the target type will not be executed");
public final Kind aspectExcludedByConfiguration =
new Kind("aspectExcludedByConfiguration","aspect {0} exluded for class loader {1}");
// there are a lot of messages in the cant find type family - I'm defining an umbrella lint warning that
// allows a user to control their severity (for e.g. ltw or binary weaving)
public final Kind cantFindType =
new Kind("cantFindType","{0}");
public final Kind cantFindTypeAffectingJoinPointMatch = new Kind("cantFindTypeAffectingJPMatch","{0}");
public Lint(World world) {
this.world = world;
}
public void setAll(String messageKind) {
setAll(getMessageKind(messageKind));
}
private void setAll(IMessage.Kind messageKind) {
for (Iterator i = kinds.values().iterator(); i.hasNext(); ) {
Kind kind = (Kind)i.next();
kind.setKind(messageKind);
}
}
public void setFromProperties(File file) {
try {
InputStream s = new FileInputStream(file);
setFromProperties(s);
} catch (IOException ioe) {
MessageUtil.error(world.getMessageHandler(),
WeaverMessages.format(WeaverMessages.XLINT_LOAD_ERROR,file.getPath(),ioe.getMessage()));
}
}
public void loadDefaultProperties() {
InputStream s = getClass().getResourceAsStream("XlintDefault.properties");
if (s == null) {
MessageUtil.warn(world.getMessageHandler(),
WeaverMessages.format(WeaverMessages.XLINTDEFAULT_LOAD_ERROR));
return;
}
try {
setFromProperties(s);
} catch (IOException ioe) {
MessageUtil.error(world.getMessageHandler(),
WeaverMessages.format(WeaverMessages.XLINTDEFAULT_LOAD_PROBLEM,ioe.getMessage()));
}
}
private void setFromProperties(InputStream s) throws IOException {
Properties p = new Properties();
p.load(s);
setFromProperties(p);
}
public void setFromProperties(Properties properties) {
for (Iterator i = properties.entrySet().iterator(); i.hasNext(); ) {
Map.Entry entry = (Map.Entry)i.next();
Kind kind = (Kind)kinds.get(entry.getKey());
if (kind == null) {
MessageUtil.error(world.getMessageHandler(),
WeaverMessages.format(WeaverMessages.XLINT_KEY_ERROR,entry.getKey()));
} else {
kind.setKind(getMessageKind((String)entry.getValue()));
}
}
}
public Collection allKinds() {
return kinds.values();
}
public Kind getLintKind(String name) {
return (Kind) kinds.get(name);
}
// temporarily suppress the given lint messages
public void suppressKinds(Collection lintKind) {
for (Iterator iter = lintKind.iterator(); iter.hasNext();) {
Kind k = (Kind) iter.next();
k.setSuppressed(true);
}
}
// remove any suppression of lint warnings in place
public void clearSuppressions() {
for (Iterator iter = kinds.values().iterator(); iter.hasNext();) {
Kind k = (Kind) iter.next();
k.setSuppressed(false);
}
}
private IMessage.Kind getMessageKind(String v) {
if (v.equals("ignore")) return null;
else if (v.equals("warning")) return IMessage.WARNING;
else if (v.equals("error")) return IMessage.ERROR;
MessageUtil.error(world.getMessageHandler(),
WeaverMessages.format(WeaverMessages.XLINT_VALUE_ERROR,v));
return null;
}
public class Kind {
private String name;
private String message;
private IMessage.Kind kind = IMessage.WARNING;
private boolean isSupressed = false; // by SuppressAjWarnings
public Kind(String name, String message) {
this.name = name;
this.message = message;
kinds.put(this.name, this);
}
public void setSuppressed(boolean shouldBeSuppressed) {
this.isSupressed = shouldBeSuppressed;
}
public boolean isEnabled() {
return (kind != null) && !isSupressed();
}
private boolean isSupressed() {
// can't suppress errors!
return isSupressed && (kind != IMessage.ERROR);
}
public String getName() {
return name;
}
public IMessage.Kind getKind() {
return kind;
}
public void setKind(IMessage.Kind kind) {
this.kind = kind;
}
public void signal(String info, ISourceLocation location) {
if (kind == null) return;
String text = MessageFormat.format(message, new Object[] {info} );
text += " [Xlint:" + name + "]";
world.getMessageHandler().handleMessage(new Message(text, kind, null, location));
}
public void signal(String[] infos, ISourceLocation location, ISourceLocation[] extraLocations) {
if (kind == null) return;
String text = MessageFormat.format(message, infos );
text += " [Xlint:" + name + "]";
world.getMessageHandler().handleMessage(
new Message(text, "", kind, location, null, extraLocations));
}
}
}
|
111,667 |
Bug 111667 Produce a compile warning when default advice precedence is applied
|
I propose that the compiler spit out a warning anytime that it has to apply the default advice precedence. Also, it should spit out the recommendation that default ordering is not guaranteed from release to release of the compiler. You can see the thread on aspectj-dev titled "change in runtime execution order" and the one on aspectj-users titled "AJDT 1.3 and aspectj" for the reasoning behind why this is a good thing.
|
resolved fixed
|
2c81907
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2005-11-30T17:23:35Z | 2005-10-05T19:20:00Z |
weaver/src/org/aspectj/weaver/Shadow.java
|
/* *******************************************************************
* Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC).
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* PARC initial implementation
* ******************************************************************/
package org.aspectj.weaver;
import java.io.DataInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import org.aspectj.asm.IRelationship;
import org.aspectj.bridge.IMessage;
import org.aspectj.bridge.ISourceLocation;
import org.aspectj.bridge.Message;
import org.aspectj.bridge.MessageUtil;
import org.aspectj.bridge.WeaveMessage;
import org.aspectj.lang.JoinPoint;
import org.aspectj.util.PartialOrder;
import org.aspectj.util.TypeSafeEnum;
import org.aspectj.weaver.ast.Var;
import org.aspectj.weaver.bcel.BcelAdvice;
/*
* The superclass of anything representing a the shadow of a join point. A shadow represents
* some bit of code, and encompasses both entry and exit from that code. All shadows have a kind
* and a signature.
*/
public abstract class Shadow {
// every Shadow has a unique id, doesn't matter if it wraps...
private static int nextShadowID = 100; // easier to spot than zero.
private final Kind kind;
private final Member signature;
private Member matchingSignature;
private ResolvedMember resolvedSignature;
protected final Shadow enclosingShadow;
protected List mungers = new ArrayList(1);
public int shadowId = nextShadowID++; // every time we build a shadow, it gets a new id
// ----
protected Shadow(Kind kind, Member signature, Shadow enclosingShadow) {
this.kind = kind;
this.signature = signature;
this.enclosingShadow = enclosingShadow;
}
// ----
public abstract World getIWorld();
public List /*ShadowMunger*/ getMungers() {
return mungers;
}
/**
* could this(*) pcd ever match
*/
public final boolean hasThis() {
if (getKind().neverHasThis()) {
return false;
} else if (getKind().isEnclosingKind()) {
return !getSignature().isStatic();
} else if (enclosingShadow == null) {
return false;
} else {
return enclosingShadow.hasThis();
}
}
/**
* the type of the this object here
*
* @throws IllegalStateException if there is no this here
*/
public final UnresolvedType getThisType() {
if (!hasThis()) throw new IllegalStateException("no this");
if (getKind().isEnclosingKind()) {
return getSignature().getDeclaringType();
} else {
return enclosingShadow.getThisType();
}
}
/**
* a var referencing this
*
* @throws IllegalStateException if there is no target here
*/
public abstract Var getThisVar();
/**
* could target(*) pcd ever match
*/
public final boolean hasTarget() {
if (getKind().neverHasTarget()) {
return false;
} else if (getKind().isTargetSameAsThis()) {
return hasThis();
} else {
return !getSignature().isStatic();
}
}
/**
* the type of the target object here
*
* @throws IllegalStateException if there is no target here
*/
public final UnresolvedType getTargetType() {
if (!hasTarget()) throw new IllegalStateException("no target");
return getSignature().getDeclaringType();
}
/**
* a var referencing the target
*
* @throws IllegalStateException if there is no target here
*/
public abstract Var getTargetVar();
public UnresolvedType[] getArgTypes() {
if (getKind() == FieldSet) return new UnresolvedType[] { getSignature().getReturnType() };
return getSignature().getParameterTypes();
}
public UnresolvedType[] getGenericArgTypes() {
if (getKind() == FieldSet) return new UnresolvedType[] { getResolvedSignature().getGenericReturnType() };
return getResolvedSignature().getGenericParameterTypes();
}
public UnresolvedType getArgType(int arg) {
if (getKind() == FieldSet) return getSignature().getReturnType();
return getSignature().getParameterTypes()[arg];
}
public int getArgCount() {
if (getKind() == FieldSet) return 1;
return getSignature()
.getParameterTypes().length;
}
public abstract UnresolvedType getEnclosingType();
public abstract Var getArgVar(int i);
public abstract Var getThisJoinPointVar();
public abstract Var getThisJoinPointStaticPartVar();
public abstract Var getThisEnclosingJoinPointStaticPartVar();
// annotation variables
public abstract Var getKindedAnnotationVar(UnresolvedType forAnnotationType);
public abstract Var getWithinAnnotationVar(UnresolvedType forAnnotationType);
public abstract Var getWithinCodeAnnotationVar(UnresolvedType forAnnotationType);
public abstract Var getThisAnnotationVar(UnresolvedType forAnnotationType);
public abstract Var getTargetAnnotationVar(UnresolvedType forAnnotationType);
public abstract Var getArgAnnotationVar(int i, UnresolvedType forAnnotationType);
public abstract Member getEnclosingCodeSignature();
/** returns the kind of shadow this is, representing what happens under this shadow
*/
public Kind getKind() {
return kind;
}
/** returns the signature of the thing under this shadow
*/
public Member getSignature() {
return signature;
}
/**
* returns the signature of the thing under this shadow, with
* any synthetic arguments removed
*/
public Member getMatchingSignature() {
return matchingSignature != null ? matchingSignature : signature;
}
public void setMatchingSignature(Member member) {
this.matchingSignature = member;
}
/**
* returns the resolved signature of the thing under this shadow
*
*/
public ResolvedMember getResolvedSignature() {
if (resolvedSignature == null) {
resolvedSignature = signature.resolve(getIWorld());
}
return resolvedSignature;
}
public UnresolvedType getReturnType() {
if (kind == ConstructorCall) return getSignature().getDeclaringType();
else if (kind == FieldSet) return ResolvedType.VOID;
return getResolvedSignature().getGenericReturnType();
}
/**
* These names are the ones that will be returned by thisJoinPoint.getKind()
* Those need to be documented somewhere
*/
public static final Kind MethodCall = new Kind(JoinPoint.METHOD_CALL, 1, true);
public static final Kind ConstructorCall = new Kind(JoinPoint.CONSTRUCTOR_CALL, 2, true);
public static final Kind MethodExecution = new Kind(JoinPoint.METHOD_EXECUTION, 3, false);
public static final Kind ConstructorExecution = new Kind(JoinPoint.CONSTRUCTOR_EXECUTION, 4, false);
public static final Kind FieldGet = new Kind(JoinPoint.FIELD_GET, 5, true);
public static final Kind FieldSet = new Kind(JoinPoint.FIELD_SET, 6, true);
public static final Kind StaticInitialization = new Kind(JoinPoint.STATICINITIALIZATION, 7, false);
public static final Kind PreInitialization = new Kind(JoinPoint.PREINTIALIZATION, 8, false);
public static final Kind AdviceExecution = new Kind(JoinPoint.ADVICE_EXECUTION, 9, false);
public static final Kind Initialization = new Kind(JoinPoint.INITIALIZATION, 10, false);
public static final Kind ExceptionHandler = new Kind(JoinPoint.EXCEPTION_HANDLER, 11, true);
public static final int MAX_SHADOW_KIND = 11;
public static final Kind[] SHADOW_KINDS = new Kind[] {
MethodCall, ConstructorCall, MethodExecution, ConstructorExecution,
FieldGet, FieldSet, StaticInitialization, PreInitialization,
AdviceExecution, Initialization, ExceptionHandler,
};
public static final Set ALL_SHADOW_KINDS;
static {
HashSet aSet = new HashSet();
for (int i = 0; i < SHADOW_KINDS.length; i++) {
aSet.add(SHADOW_KINDS[i]);
}
ALL_SHADOW_KINDS = Collections.unmodifiableSet(aSet);
}
/** A type-safe enum representing the kind of shadows
*/
public static final class Kind extends TypeSafeEnum {
// private boolean argsOnStack; //XXX unused
public Kind(String name, int key, boolean argsOnStack) {
super(name, key);
// this.argsOnStack = argsOnStack;
}
public String toLegalJavaIdentifier() {
return getName().replace('-', '_');
}
public boolean argsOnStack() {
return !isTargetSameAsThis();
}
// !!! this is false for handlers!
public boolean allowsExtraction() {
return true;
}
// XXX revisit along with removal of priorities
public boolean hasHighPriorityExceptions() {
return !isTargetSameAsThis();
}
/**
* These shadow kinds have return values that can be bound in
* after returning(Dooberry doo) advice.
* @return
*/
public boolean hasReturnValue() {
return
this == MethodCall ||
this == ConstructorCall ||
this == MethodExecution ||
this == FieldGet ||
this == AdviceExecution;
}
/**
* These are all the shadows that contains other shadows within them and
* are often directly associated with methods.
*/
public boolean isEnclosingKind() {
return this == MethodExecution || this == ConstructorExecution ||
this == AdviceExecution || this == StaticInitialization
|| this == Initialization;
}
public boolean isTargetSameAsThis() {
return this == MethodExecution
|| this == ConstructorExecution
|| this == StaticInitialization
|| this == PreInitialization
|| this == AdviceExecution
|| this == Initialization;
}
public boolean neverHasTarget() {
return this == ConstructorCall
|| this == ExceptionHandler
|| this == PreInitialization
|| this == StaticInitialization;
}
public boolean neverHasThis() {
return this == PreInitialization
|| this == StaticInitialization;
}
public String getSimpleName() {
int dash = getName().lastIndexOf('-');
if (dash == -1) return getName();
else return getName().substring(dash+1);
}
public static Kind read(DataInputStream s) throws IOException {
int key = s.readByte();
switch(key) {
case 1: return MethodCall;
case 2: return ConstructorCall;
case 3: return MethodExecution;
case 4: return ConstructorExecution;
case 5: return FieldGet;
case 6: return FieldSet;
case 7: return StaticInitialization;
case 8: return PreInitialization;
case 9: return AdviceExecution;
case 10: return Initialization;
case 11: return ExceptionHandler;
}
throw new BCException("unknown kind: " + key);
}
}
/**
* Only does the check if the munger requires it (@AJ aspects don't)
*
* @param munger
* @return
*/
protected boolean checkMunger(ShadowMunger munger) {
if (munger.mustCheckExceptions()) {
for (Iterator i = munger.getThrownExceptions().iterator(); i.hasNext(); ) {
if (!checkCanThrow(munger, (ResolvedType)i.next() )) return false;
}
}
return true;
}
protected boolean checkCanThrow(ShadowMunger munger, ResolvedType resolvedTypeX) {
if (getKind() == ExceptionHandler) {
//XXX much too lenient rules here, need to walk up exception handlers
return true;
}
if (!isDeclaredException(resolvedTypeX, getSignature())) {
getIWorld().showMessage(IMessage.ERROR,
WeaverMessages.format(WeaverMessages.CANT_THROW_CHECKED,resolvedTypeX,this), // from advice in \'" + munger. + "\'",
getSourceLocation(), munger.getSourceLocation());
}
return true;
}
private boolean isDeclaredException(
ResolvedType resolvedTypeX,
Member member)
{
ResolvedType[] excs = getIWorld().resolve(member.getExceptions(getIWorld()));
for (int i=0, len=excs.length; i < len; i++) {
if (excs[i].isAssignableFrom(resolvedTypeX)) return true;
}
return false;
}
public void addMunger(ShadowMunger munger) {
if (checkMunger(munger)) this.mungers.add(munger);
}
public final void implement() {
sortMungers();
if (mungers == null) return;
prepareForMungers();
implementMungers();
}
private void sortMungers() {
List sorted = PartialOrder.sort(mungers);
if (sorted == null) {
// this means that we have circular dependencies
for (Iterator i = mungers.iterator(); i.hasNext(); ) {
ShadowMunger m = (ShadowMunger)i.next();
getIWorld().getMessageHandler().handleMessage(
MessageUtil.error(
WeaverMessages.format(WeaverMessages.CIRCULAR_DEPENDENCY,this), m.getSourceLocation()));
}
}
mungers = sorted;
}
/** Prepare the shadow for implementation. After this is done, the shadow
* should be in such a position that each munger simply needs to be implemented.
*/
protected void prepareForMungers() {
throw new RuntimeException("Generic shadows cannot be prepared");
}
/*
* Ensure we report a nice source location - particular in the case
* where the source info is missing (binary weave).
*/
private String beautifyLocation(ISourceLocation isl) {
StringBuffer nice = new StringBuffer();
if (isl==null || isl.getSourceFile()==null || isl.getSourceFile().getName().indexOf("no debug info available")!=-1) {
nice.append("no debug info available");
} else {
// can't use File.getName() as this fails when a Linux box encounters a path created on Windows and vice-versa
int takeFrom = isl.getSourceFile().getPath().lastIndexOf('/');
if (takeFrom == -1) {
takeFrom = isl.getSourceFile().getPath().lastIndexOf('\\');
}
nice.append(isl.getSourceFile().getPath().substring(takeFrom +1));
if (isl.getLine()!=0) nice.append(":").append(isl.getLine());
}
return nice.toString();
}
/*
* Report a message about the advice weave that has occurred. Some messing about
* to make it pretty ! This code is just asking for an NPE to occur ...
*/
private void reportWeavingMessage(ShadowMunger munger) {
Advice advice = (Advice)munger;
AdviceKind aKind = advice.getKind();
// Only report on interesting advice kinds ...
if (aKind == null || advice.getConcreteAspect()==null) {
// We suspect someone is programmatically driving the weaver
// (e.g. IdWeaveTestCase in the weaver testcases)
return;
}
if (!( aKind.equals(AdviceKind.Before) ||
aKind.equals(AdviceKind.After) ||
aKind.equals(AdviceKind.AfterReturning) ||
aKind.equals(AdviceKind.AfterThrowing) ||
aKind.equals(AdviceKind.Around) ||
aKind.equals(AdviceKind.Softener))) return;
String description = advice.getKind().toString();
String advisedType = this.getEnclosingType().getName();
String advisingType= advice.getConcreteAspect().getName();
Message msg = null;
if (advice.getKind().equals(AdviceKind.Softener)) {
msg = WeaveMessage.constructWeavingMessage(
WeaveMessage.WEAVEMESSAGE_SOFTENS,
new String[]{advisedType,beautifyLocation(getSourceLocation()),
advisingType,beautifyLocation(munger.getSourceLocation())},
advisedType,
advisingType);
} else {
boolean runtimeTest = ((BcelAdvice)advice).hasDynamicTests();
String joinPointDescription = this.toString();
msg = WeaveMessage.constructWeavingMessage(WeaveMessage.WEAVEMESSAGE_ADVISES,
new String[]{ joinPointDescription, advisedType, beautifyLocation(getSourceLocation()),
description,
advisingType,beautifyLocation(munger.getSourceLocation()),
(runtimeTest?" [with runtime test]":"")},
advisedType,
advisingType);
// Boolean.toString(runtimeTest)});
}
getIWorld().getMessageHandler().handleMessage(msg);
}
public IRelationship.Kind determineRelKind(ShadowMunger munger) {
AdviceKind ak = ((Advice)munger).getKind();
if (ak.getKey()==AdviceKind.Before.getKey())
return IRelationship.Kind.ADVICE_BEFORE;
else if (ak.getKey()==AdviceKind.After.getKey())
return IRelationship.Kind.ADVICE_AFTER;
else if (ak.getKey()==AdviceKind.AfterThrowing.getKey())
return IRelationship.Kind.ADVICE_AFTERTHROWING;
else if (ak.getKey()==AdviceKind.AfterReturning.getKey())
return IRelationship.Kind.ADVICE_AFTERRETURNING;
else if (ak.getKey()==AdviceKind.Around.getKey())
return IRelationship.Kind.ADVICE_AROUND;
else if (ak.getKey()==AdviceKind.CflowEntry.getKey() ||
ak.getKey()==AdviceKind.CflowBelowEntry.getKey() ||
ak.getKey()==AdviceKind.InterInitializer.getKey() ||
ak.getKey()==AdviceKind.PerCflowEntry.getKey() ||
ak.getKey()==AdviceKind.PerCflowBelowEntry.getKey() ||
ak.getKey()==AdviceKind.PerThisEntry.getKey() ||
ak.getKey()==AdviceKind.PerTargetEntry.getKey() ||
ak.getKey()==AdviceKind.Softener.getKey() ||
ak.getKey()==AdviceKind.PerTypeWithinEntry.getKey()) {
//System.err.println("Dont want a message about this: "+ak);
return null;
}
throw new RuntimeException("Shadow.determineRelKind: What the hell is it? "+ak);
}
/** Actually implement the (non-empty) mungers associated with this shadow */
private void implementMungers() {
World world = getIWorld();
for (Iterator iter = mungers.iterator(); iter.hasNext();) {
ShadowMunger munger = (ShadowMunger) iter.next();
munger.implementOn(this);
if (world.getCrossReferenceHandler() != null) {
world.getCrossReferenceHandler().addCrossReference(
munger.getSourceLocation(), // What is being applied
this.getSourceLocation(), // Where is it being applied
determineRelKind(munger), // What kind of advice?
((BcelAdvice)munger).hasDynamicTests() // Is a runtime test being stuffed in the code?
);
}
// TAG: WeavingMessage
if (!getIWorld().getMessageHandler().isIgnoring(IMessage.WEAVEINFO)) {
reportWeavingMessage(munger);
}
if (world.getModel() != null) {
//System.err.println("munger: " + munger + " on " + this);
AsmRelationshipProvider.getDefault().adviceMunger(world.getModel(), this, munger);
}
}
}
public String makeReflectiveFactoryString() {
return null; //XXX
}
public abstract ISourceLocation getSourceLocation();
// ---- utility
public String toString() {
return getKind() + "(" + getSignature() + ")"; // + getSourceLines();
}
public String toResolvedString(World world) {
return getKind() + "(" + world.resolve(getSignature()).toGenericString() + ")";
}
}
|
111,667 |
Bug 111667 Produce a compile warning when default advice precedence is applied
|
I propose that the compiler spit out a warning anytime that it has to apply the default advice precedence. Also, it should spit out the recommendation that default ordering is not guaranteed from release to release of the compiler. You can see the thread on aspectj-dev titled "change in runtime execution order" and the one on aspectj-users titled "AJDT 1.3 and aspectj" for the reasoning behind why this is a good thing.
|
resolved fixed
|
2c81907
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2005-11-30T17:23:35Z | 2005-10-05T19:20:00Z |
weaver/src/org/aspectj/weaver/World.java
|
/* *******************************************************************
* Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC).
* 2005 Contributors
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* PARC initial implementation
* Adrian Colyer, Andy Clement, overhaul for generics
* ******************************************************************/
package org.aspectj.weaver;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.WeakHashMap;
import org.aspectj.asm.IHierarchy;
import org.aspectj.bridge.IMessageHandler;
import org.aspectj.bridge.ISourceLocation;
import org.aspectj.bridge.Message;
import org.aspectj.bridge.MessageUtil;
import org.aspectj.bridge.IMessage.Kind;
import org.aspectj.bridge.context.PinpointingMessageHandler;
import org.aspectj.weaver.UnresolvedType.TypeKind;
import org.aspectj.weaver.patterns.DeclarePrecedence;
import org.aspectj.weaver.patterns.PerClause;
import org.aspectj.weaver.patterns.Pointcut;
/**
* A World is a collection of known types and crosscutting members.
*/
public abstract class World implements Dump.INode {
/** handler for any messages produced during resolution etc. */
private IMessageHandler messageHandler = IMessageHandler.SYSTEM_ERR;
/** handler for cross-reference information produced during the weaving process */
private ICrossReferenceHandler xrefHandler = null;
/** Currently 'active' scope in which to lookup (resolve) typevariable references */
private TypeVariableDeclaringElement typeVariableLookupScope;
/** The heart of the world, a map from type signatures to resolved types */
protected TypeMap typeMap = new TypeMap(); // Signature to ResolvedType
/** Calculator for working out aspect precedence */
private AspectPrecedenceCalculator precedenceCalculator;
/** All of the type and shadow mungers known to us */
private CrosscuttingMembersSet crosscuttingMembersSet =
new CrosscuttingMembersSet(this);
/** Model holds ASM relationships */
private IHierarchy model = null;
/** for processing Xlint messages */
private Lint lint = new Lint(this);
/** XnoInline option setting passed down to weaver */
private boolean XnoInline;
/** XlazyTjp option setting passed down to weaver */
private boolean XlazyTjp;
/** XhasMember option setting passed down to weaver */
private boolean XhasMember = false;
/** Xpinpoint controls whether we put out developer info showing the source of messages */
private boolean Xpinpoint = false;
/** When behaving in a Java 5 way autoboxing is considered */
private boolean behaveInJava5Way = false;
/** The level of the aspectjrt.jar the code we generate needs to run on */
private String targetAspectjRuntimeLevel = Constants.RUNTIME_LEVEL_DEFAULT;
/**
* A list of RuntimeExceptions containing full stack information for every
* type we couldn't find.
*/
private List dumpState_cantFindTypeExceptions = null;
/**
* Play God.
* On the first day, God created the primitive types and put them in the type
* map.
*/
protected World() {
super();
Dump.registerNode(this.getClass(),this);
typeMap.put("B", ResolvedType.BYTE);
typeMap.put("S", ResolvedType.SHORT);
typeMap.put("I", ResolvedType.INT);
typeMap.put("J", ResolvedType.LONG);
typeMap.put("F", ResolvedType.FLOAT);
typeMap.put("D", ResolvedType.DOUBLE);
typeMap.put("C", ResolvedType.CHAR);
typeMap.put("Z", ResolvedType.BOOLEAN);
typeMap.put("V", ResolvedType.VOID);
precedenceCalculator = new AspectPrecedenceCalculator(this);
}
/**
* Dump processing when a fatal error occurs
*/
public void accept (Dump.IVisitor visitor) {
visitor.visitString("Shadow mungers:");
visitor.visitList(crosscuttingMembersSet.getShadowMungers());
visitor.visitString("Type mungers:");
visitor.visitList(crosscuttingMembersSet.getTypeMungers());
visitor.visitString("Late Type mungers:");
visitor.visitList(crosscuttingMembersSet.getLateTypeMungers());
if (dumpState_cantFindTypeExceptions!=null) {
visitor.visitString("Cant find type problems:");
visitor.visitList(dumpState_cantFindTypeExceptions);
dumpState_cantFindTypeExceptions = null;
}
}
// =============================================================================
// T Y P E R E S O L U T I O N
// =============================================================================
/**
* Resolve a type that we require to be present in the world
*/
public ResolvedType resolve(UnresolvedType ty) {
return resolve(ty, false);
}
/**
* Attempt to resolve a type - the source location gives you some context in which
* resolution is taking place. In the case of an error where we can't find the
* type - we can then at least report why (source location) we were trying to resolve it.
*/
public ResolvedType resolve(UnresolvedType ty,ISourceLocation isl) {
ResolvedType ret = resolve(ty,true);
if (ty == ResolvedType.MISSING) {
//IMessage msg = null;
getLint().cantFindType.signal(WeaverMessages.format(WeaverMessages.CANT_FIND_TYPE,ty.getName()),isl);
//if (isl!=null) {
//msg = MessageUtil.error(WeaverMessages.format(WeaverMessages.CANT_FIND_TYPE,ty.getName()),isl);
//} else {
//msg = MessageUtil.error(WeaverMessages.format(WeaverMessages.CANT_FIND_TYPE,ty.getName()));
//}
//messageHandler.handleMessage(msg);
}
return ret;
}
/**
* Convenience method for resolving an array of unresolved types
* in one hit. Useful for e.g. resolving type parameters in signatures.
*/
public ResolvedType[] resolve(UnresolvedType[] types) {
if (types == null) return new ResolvedType[0];
ResolvedType[] ret = new ResolvedType[types.length];
for (int i=0; i<types.length; i++) {
ret[i] = resolve(types[i]);
}
return ret;
}
/**
* Resolve a type. This the hub of type resolution. The resolved type is added
* to the type map by signature.
*/
public ResolvedType resolve(UnresolvedType ty, boolean allowMissing) {
// special resolution processing for already resolved types.
if (ty instanceof ResolvedType) {
ResolvedType rty = (ResolvedType) ty;
rty = resolve(rty);
return rty;
}
// dispatch back to the type variable reference to resolve its constituent parts
// don't do this for other unresolved types otherwise you'll end up in a loop
if (ty.isTypeVariableReference()) {
return ty.resolve(this);
}
// if we've already got a resolved type for the signature, just return it
// after updating the world
String signature = ty.getSignature();
ResolvedType ret = typeMap.get(signature);
if (ret != null) {
ret.world = this; // Set the world for the RTX
return ret;
} else if ( signature.equals("?") || signature.equals("*")) {
// might be a problem here, not sure '?' should make it to here as a signature, the
// proper signature for wildcard '?' is '*'
// fault in generic wildcard, can't be done earlier because of init issues
ResolvedType something = new BoundedReferenceType("?",this);
typeMap.put("?",something);
return something;
}
// no existing resolved type, create one
if (ty.isArray()) {
ResolvedType componentType = resolve(ty.getComponentType(),allowMissing);
String brackets = signature.substring(0,signature.lastIndexOf("[")+1);
ret = new ResolvedType.Array(signature, brackets+componentType.getErasureSignature(),
this,
componentType);
} else {
ret = resolveToReferenceType(ty);
if (!allowMissing && ret == ResolvedType.MISSING) {
ret = handleRequiredMissingTypeDuringResolution(ty);
}
}
// Pulling in the type may have already put the right entry in the map
if (typeMap.get(signature)==null && ret != ResolvedType.MISSING) {
typeMap.put(signature, ret);
}
return ret;
}
/**
* We tried to resolve a type and couldn't find it...
*/
private ResolvedType handleRequiredMissingTypeDuringResolution(UnresolvedType ty) {
// defer the message until someone asks a question of the type that we can't answer
// just from the signature.
// MessageUtil.error(messageHandler,
// WeaverMessages.format(WeaverMessages.CANT_FIND_TYPE,ty.getName()));
if (dumpState_cantFindTypeExceptions==null) {
dumpState_cantFindTypeExceptions = new ArrayList();
}
dumpState_cantFindTypeExceptions.add(new RuntimeException("Can't find type "+ty.getName()));
return new MissingResolvedTypeWithKnownSignature(ty.getSignature(),this);
}
/**
* Some TypeFactory operations create resolved types directly, but these won't be
* in the typeMap - this resolution process puts them there. Resolved types are
* also told their world which is needed for the special autoboxing resolved types.
*/
public ResolvedType resolve(ResolvedType ty) {
if (ty.isTypeVariableReference()) return ty; // until type variables have proper sigs...
ResolvedType resolved = typeMap.get(ty.getSignature());
if (resolved == null) {
typeMap.put(ty.getSignature(), ty);
resolved = ty;
}
resolved.world = this;
return resolved;
}
/**
* Convenience method for finding a type by name and resolving it in one step.
*/
public ResolvedType resolve(String name) {
return resolve(UnresolvedType.forName(name));
}
public ResolvedType resolve(String name,boolean allowMissing) {
return resolve(UnresolvedType.forName(name),allowMissing);
}
private ResolvedType currentlyResolvingBaseType;
/**
* Resolve to a ReferenceType - simple, raw, parameterized, or generic.
* Raw, parameterized, and generic versions of a type share a delegate.
*/
private final ResolvedType resolveToReferenceType(UnresolvedType ty) {
if (ty.isParameterizedType()) {
// ======= parameterized types ================
ReferenceType genericType = (ReferenceType)resolveGenericTypeFor(ty,false);
currentlyResolvingBaseType = genericType;
ReferenceType parameterizedType =
TypeFactory.createParameterizedType(genericType, ty.typeParameters, this);
currentlyResolvingBaseType = null;
return parameterizedType;
} else if (ty.isGenericType()) {
// ======= generic types ======================
ReferenceType genericType = (ReferenceType)resolveGenericTypeFor(ty,false);
return genericType;
} else if (ty.isGenericWildcard()) {
// ======= generic wildcard types =============
return resolveGenericWildcardFor(ty);
} else {
// ======= simple and raw types ===============
String erasedSignature = ty.getErasureSignature();
ReferenceType simpleOrRawType = new ReferenceType(erasedSignature, this);
ReferenceTypeDelegate delegate = resolveDelegate(simpleOrRawType);
if (delegate == null) return ResolvedType.MISSING;
if (delegate.isGeneric() && behaveInJava5Way) {
// ======== raw type ===========
simpleOrRawType.typeKind = TypeKind.RAW;
ReferenceType genericType = makeGenericTypeFrom(delegate,simpleOrRawType);
// name = ReferenceType.fromTypeX(UnresolvedType.forRawTypeNames(ty.getName()),this);
simpleOrRawType.setDelegate(delegate);
genericType.setDelegate(delegate);
simpleOrRawType.setGenericType(genericType);
return simpleOrRawType;
} else {
// ======== simple type =========
simpleOrRawType.setDelegate(delegate);
return simpleOrRawType;
}
}
}
/**
* Attempt to resolve a type that should be a generic type.
*/
public ResolvedType resolveGenericTypeFor(UnresolvedType anUnresolvedType, boolean allowMissing) {
// Look up the raw type by signature
String rawSignature = anUnresolvedType.getRawType().getSignature();
ResolvedType rawType = (ResolvedType) typeMap.get(rawSignature);
if (rawType==null) {
rawType = resolve(UnresolvedType.forSignature(rawSignature),false);
typeMap.put(rawSignature,rawType);
}
// Does the raw type know its generic form? (It will if we created the
// raw type from a source type, it won't if its been created just through
// being referenced, e.g. java.util.List
ResolvedType genericType = rawType.getGenericType();
// There is a special case to consider here (testGenericsBang_pr95993 highlights it)
// You may have an unresolvedType for a parameterized type but it
// is backed by a simple type rather than a generic type. This occurs for
// inner types of generic types that inherit their enclosing types
// type variables.
if (rawType.isSimpleType() && (anUnresolvedType.typeParameters==null || anUnresolvedType.typeParameters.length==0)) {
rawType.world = this;
return rawType;
}
if (genericType != null) {
genericType.world = this;
return genericType;
} else {
// Fault in the generic that underpins the raw type ;)
ReferenceTypeDelegate delegate = resolveDelegate((ReferenceType)rawType);
ReferenceType genericRefType = makeGenericTypeFrom(delegate,((ReferenceType)rawType));
((ReferenceType)rawType).setGenericType(genericRefType);
genericRefType.setDelegate(delegate);
((ReferenceType)rawType).setDelegate(delegate);
return genericRefType;
}
}
private ReferenceType makeGenericTypeFrom(ReferenceTypeDelegate delegate, ReferenceType rawType) {
String genericSig = delegate.getDeclaredGenericSignature();
if (genericSig != null) {
return new ReferenceType(
UnresolvedType.forGenericTypeSignature(rawType.getSignature(),delegate.getDeclaredGenericSignature()),this);
} else {
return new ReferenceType(
UnresolvedType.forGenericTypeVariables(rawType.getSignature(), delegate.getTypeVariables()),this);
}
}
/**
* Go from an unresolved generic wildcard (represented by UnresolvedType) to a resolved version (BoundedReferenceType).
*/
private ReferenceType resolveGenericWildcardFor(UnresolvedType aType) {
BoundedReferenceType ret = null;
// FIXME asc doesnt take account of additional interface bounds (e.g. ? super R & Serializable - can you do that?)
if (aType.isExtends()) {
ReferenceType upperBound = (ReferenceType)resolve(aType.getUpperBound());
ret = new BoundedReferenceType(upperBound,true,this);
} else if (aType.isSuper()) {
ReferenceType lowerBound = (ReferenceType) resolve(aType.getLowerBound());
ret = new BoundedReferenceType(lowerBound,false,this);
} else {
// must be ? on its own!
}
return ret;
}
/**
* Find the ReferenceTypeDelegate behind this reference type so that it can
* fulfill its contract.
*/
protected abstract ReferenceTypeDelegate resolveDelegate(ReferenceType ty);
/**
* Special resolution for "core" types like OBJECT. These are resolved just like
* any other type, but if they are not found it is more serious and we issue an
* error message immediately.
*/
public ResolvedType getCoreType(UnresolvedType tx) {
ResolvedType coreTy = resolve(tx,true);
if (coreTy == ResolvedType.MISSING) {
MessageUtil.error(messageHandler,
WeaverMessages.format(WeaverMessages.CANT_FIND_CORE_TYPE,tx.getName()));
}
return coreTy;
}
/**
* Lookup a type by signature, if not found then build one and put it in the
* map.
*/
public ReferenceType lookupOrCreateName(UnresolvedType ty) {
String signature = ty.getSignature();
ReferenceType ret = lookupBySignature(signature);
if (ret == null) {
ret = ReferenceType.fromTypeX(ty, this);
typeMap.put(signature, ret);
}
return ret;
}
/**
* Lookup a reference type in the world by its signature. Returns
* null if not found.
*/
public ReferenceType lookupBySignature(String signature) {
return (ReferenceType) typeMap.get(signature);
}
// =============================================================================
// T Y P E R E S O L U T I O N -- E N D
// =============================================================================
/**
* Member resolution is achieved by resolving the declaring type and then
* looking up the member in the resolved declaring type.
*/
public ResolvedMember resolve(Member member) {
ResolvedType declaring = member.getDeclaringType().resolve(this);
if (declaring.isRawType()) declaring = declaring.getGenericType();
ResolvedMember ret;
if (member.getKind() == Member.FIELD) {
ret = declaring.lookupField(member);
} else {
ret = declaring.lookupMethod(member);
}
if (ret != null) return ret;
return declaring.lookupSyntheticMember(member);
}
// Methods for creating various cross-cutting members...
// ===========================================================
/**
* Create an advice shadow munger from the given advice attribute
*/
public abstract Advice createAdviceMunger(
AjAttribute.AdviceAttribute attribute,
Pointcut pointcut,
Member signature);
/**
* Create an advice shadow munger for the given advice kind
*/
public final Advice createAdviceMunger(
AdviceKind kind,
Pointcut p,
Member signature,
int extraParameterFlags,
IHasSourceLocation loc)
{
AjAttribute.AdviceAttribute attribute =
new AjAttribute.AdviceAttribute(kind, p, extraParameterFlags, loc.getStart(), loc.getEnd(), loc.getSourceContext());
return createAdviceMunger(attribute, p, signature);
}
public abstract ConcreteTypeMunger makeCflowStackFieldAdder(ResolvedMember cflowField);
public abstract ConcreteTypeMunger makeCflowCounterFieldAdder(ResolvedMember cflowField);
/**
* Register a munger for perclause @AJ aspect so that we add aspectOf(..) to them as needed
* @see org.aspectj.weaver.bcel.BcelWorld#makePerClauseAspect(ResolvedType, org.aspectj.weaver.patterns.PerClause.Kind)
*/
public abstract ConcreteTypeMunger makePerClauseAspect(ResolvedType aspect, PerClause.Kind kind);
public abstract ConcreteTypeMunger concreteTypeMunger(ResolvedTypeMunger munger, ResolvedType aspectType);
/**
* Same signature as org.aspectj.util.PartialOrder.PartialComparable.compareTo
*/
public int compareByPrecedence(ResolvedType aspect1, ResolvedType aspect2) {
return precedenceCalculator.compareByPrecedence(aspect1, aspect2);
}
/**
* compares by precedence with the additional rule that a super-aspect is
* sorted before its sub-aspects
*/
public int compareByPrecedenceAndHierarchy(ResolvedType aspect1, ResolvedType aspect2) {
return precedenceCalculator.compareByPrecedenceAndHierarchy(aspect1, aspect2);
}
// simple property getter and setters
// ===========================================================
/**
* Nobody should hold onto a copy of this message handler, or setMessageHandler won't
* work right.
*/
public IMessageHandler getMessageHandler() {
return messageHandler;
}
public void setMessageHandler(IMessageHandler messageHandler) {
if (this.isInPinpointMode()) {
this.messageHandler = new PinpointingMessageHandler(messageHandler);
} else {
this.messageHandler = messageHandler;
}
}
/**
* convenenience method for creating and issuing messages via the message handler -
* if you supply two locations you will get two messages.
*/
public void showMessage(
Kind kind,
String message,
ISourceLocation loc1,
ISourceLocation loc2)
{
if (loc1 != null) {
messageHandler.handleMessage(new Message(message, kind, null, loc1));
if (loc2 != null) {
messageHandler.handleMessage(new Message(message, kind, null, loc2));
}
} else {
messageHandler.handleMessage(new Message(message, kind, null, loc2));
}
}
public void setCrossReferenceHandler(ICrossReferenceHandler xrefHandler) {
this.xrefHandler = xrefHandler;
}
/**
* Get the cross-reference handler for the world, may be null.
*/
public ICrossReferenceHandler getCrossReferenceHandler() {
return this.xrefHandler;
}
public void setTypeVariableLookupScope(TypeVariableDeclaringElement scope) {
this.typeVariableLookupScope = scope;
}
public TypeVariableDeclaringElement getTypeVariableLookupScope() {
return typeVariableLookupScope;
}
public List getDeclareParents() {
return crosscuttingMembersSet.getDeclareParents();
}
public List getDeclareAnnotationOnTypes() {
return crosscuttingMembersSet.getDeclareAnnotationOnTypes();
}
public List getDeclareAnnotationOnFields() {
return crosscuttingMembersSet.getDeclareAnnotationOnFields();
}
public List getDeclareAnnotationOnMethods() {
return crosscuttingMembersSet.getDeclareAnnotationOnMethods();
}
public List getDeclareSoft() {
return crosscuttingMembersSet.getDeclareSofts();
}
public CrosscuttingMembersSet getCrosscuttingMembersSet() {
return crosscuttingMembersSet;
}
public IHierarchy getModel() {
return model;
}
public void setModel(IHierarchy model) {
this.model = model;
}
public Lint getLint() {
return lint;
}
public void setLint(Lint lint) {
this.lint = lint;
}
public boolean isXnoInline() {
return XnoInline;
}
public void setXnoInline(boolean xnoInline) {
XnoInline = xnoInline;
}
public boolean isXlazyTjp() {
return XlazyTjp;
}
public void setXlazyTjp(boolean b) {
XlazyTjp = b;
}
public boolean isHasMemberSupportEnabled() {
return XhasMember;
}
public void setXHasMemberSupportEnabled(boolean b) {
XhasMember = b;
}
public boolean isInPinpointMode() {
return Xpinpoint;
}
public void setPinpointMode(boolean b) {
this.Xpinpoint = b;
}
public void setBehaveInJava5Way(boolean b) {
behaveInJava5Way = b;
}
public boolean isInJava5Mode() {
return behaveInJava5Way;
}
public void setTargetAspectjRuntimeLevel(String s) {
targetAspectjRuntimeLevel = s;
}
public String getTargetAspectjRuntimeLevel() {
return targetAspectjRuntimeLevel;
}
public boolean isTargettingAspectJRuntime12() {
return getTargetAspectjRuntimeLevel().equals(org.aspectj.weaver.Constants.RUNTIME_LEVEL_12);
}
/*
* Map of types in the world, with soft links to expendable ones.
* An expendable type is a reference type that is not exposed to the weaver (ie
* just pulled in for type resolution purposes).
*/
protected static class TypeMap {
/** Map of types that never get thrown away */
private Map tMap = new HashMap();
/** Map of types that may be ejected from the cache if we need space */
private Map expendableMap = new WeakHashMap();
private static final boolean debug = false;
/**
* Add a new type into the map, the key is the type signature.
* Some types do *not* go in the map, these are ones involving
* *member* type variables. The reason is that when all you have is the
* signature which gives you a type variable name, you cannot
* guarantee you are using the type variable in the same way
* as someone previously working with a similarly
* named type variable. So, these do not go into the map:
* - TypeVariableReferenceType.
* - ParameterizedType where a member type variable is involved.
* - BoundedReferenceType when one of the bounds is a type variable.
*
* definition: "member type variables" - a tvar declared on a generic
* method/ctor as opposed to those you see declared on a generic type.
*/
public ResolvedType put(String key, ResolvedType type) {
if (type.isParameterizedType() && type.isParameterizedWithAMemberTypeVariable()) {
if (debug)
System.err.println("Not putting a parameterized type that utilises member declared type variables into the typemap: key="+key+" type="+type);
return type;
}
if (type.isTypeVariableReference()) {
if (debug)
System.err.println("Not putting a type variable reference type into the typemap: key="+key+" type="+type);
return type;
}
// this test should be improved - only avoid putting them in if one of the
// bounds is a member type variable
if (type instanceof BoundedReferenceType) {
if (debug)
System.err.println("Not putting a bounded reference type into the typemap: key="+key+" type="+type);
return type;
}
if (type instanceof MissingResolvedTypeWithKnownSignature) {
if (debug)
System.err.println("Not putting a missing type into the typemap: key="+key+" type="+type);
return type;
}
if (isExpendable(type)) {
return (ResolvedType) expendableMap.put(key,type);
} else {
return (ResolvedType) tMap.put(key,type);
}
}
/** Lookup a type by its signature */
public ResolvedType get(String key) {
ResolvedType ret = (ResolvedType) tMap.get(key);
if (ret == null) ret = (ResolvedType) expendableMap.get(key);
return ret;
}
/** Remove a type from the map */
public ResolvedType remove(String key) {
ResolvedType ret = (ResolvedType) tMap.remove(key);
if (ret == null) ret = (ResolvedType) expendableMap.remove(key);
return ret;
}
/** Reference types we don't intend to weave may be ejected from
* the cache if we need the space.
*/
private boolean isExpendable(ResolvedType type) {
return (
(type != null) &&
(!type.isExposedToWeaver()) &&
(!type.isPrimitiveType())
);
}
public String toString() {
StringBuffer sb = new StringBuffer();
sb.append("types:\n");
sb.append(dumpthem(tMap));
sb.append("expendables:\n");
sb.append(dumpthem(expendableMap));
return sb.toString();
}
private String dumpthem(Map m) {
StringBuffer sb = new StringBuffer();
Set keys = m.keySet();
for (Iterator iter = keys.iterator(); iter.hasNext();) {
String k = (String) iter.next();
sb.append(k+"="+m.get(k)).append("\n");
}
return sb.toString();
}
}
/**
* This class is used to compute and store precedence relationships between
* aspects.
*/
private static class AspectPrecedenceCalculator {
private World world;
private Map cachedResults;
public AspectPrecedenceCalculator(World forSomeWorld) {
this.world = forSomeWorld;
this.cachedResults = new HashMap();
}
/**
* Ask every declare precedence in the world to order the two aspects.
* If more than one declare precedence gives an ordering, and the orderings
* conflict, then that's an error.
*/
public int compareByPrecedence(ResolvedType firstAspect, ResolvedType secondAspect) {
PrecedenceCacheKey key = new PrecedenceCacheKey(firstAspect,secondAspect);
if (cachedResults.containsKey(key)) {
return ((Integer) cachedResults.get(key)).intValue();
} else {
int order = 0;
DeclarePrecedence orderer = null; // Records the declare precedence statement that gives the first ordering
for (Iterator i = world.getCrosscuttingMembersSet().getDeclareDominates().iterator(); i.hasNext(); ) {
DeclarePrecedence d = (DeclarePrecedence)i.next();
int thisOrder = d.compare(firstAspect, secondAspect);
if (thisOrder != 0) {
if (orderer==null) orderer = d;
if (order != 0 && order != thisOrder) {
ISourceLocation[] isls = new ISourceLocation[2];
isls[0]=orderer.getSourceLocation();
isls[1]=d.getSourceLocation();
Message m =
new Message("conflicting declare precedence orderings for aspects: "+
firstAspect.getName()+" and "+secondAspect.getName(),null,true,isls);
world.getMessageHandler().handleMessage(m);
} else {
order = thisOrder;
}
}
}
cachedResults.put(key, new Integer(order));
return order;
}
}
public int compareByPrecedenceAndHierarchy(ResolvedType firstAspect, ResolvedType secondAspect) {
if (firstAspect.equals(secondAspect)) return 0;
int ret = compareByPrecedence(firstAspect, secondAspect);
if (ret != 0) return ret;
if (firstAspect.isAssignableFrom(secondAspect)) return -1;
else if (secondAspect.isAssignableFrom(firstAspect)) return +1;
return 0;
}
private static class PrecedenceCacheKey {
public ResolvedType aspect1;
public ResolvedType aspect2;
public PrecedenceCacheKey(ResolvedType a1, ResolvedType a2) {
this.aspect1 = a1;
this.aspect2 = a2;
}
public boolean equals(Object obj) {
if (!(obj instanceof PrecedenceCacheKey)) return false;
PrecedenceCacheKey other = (PrecedenceCacheKey) obj;
return (aspect1 == other.aspect1 && aspect2 == other.aspect2);
}
public int hashCode() {
return aspect1.hashCode() + aspect2.hashCode();
}
}
}
public void validateType(UnresolvedType type) { }
// --- 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);
}
// ---
}
|
117,209 |
Bug 117209 Runtime error - Stack size too large, Bug#69706 related.
| null |
resolved fixed
|
551b9ca
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2005-11-30T19:51:24Z | 2005-11-20T07:00:00Z |
org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/core/builder/AjBuildConfig.java
|
/* *******************************************************************
* Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC).
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* PARC initial implementation
* Adrian Colyer added constructor to populate javaOptions with
* default settings - 01.20.2003
* Bugzilla #29768, 29769
* ******************************************************************/
package org.aspectj.ajdt.internal.core.builder;
import java.io.File;
import java.io.FileFilter;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.aspectj.util.FileUtil;
/**
* All configuration information needed to run the AspectJ compiler.
* Compiler options (as opposed to path information) are held in an AjCompilerOptions instance
*/
public class AjBuildConfig {
private boolean shouldProceed = true;
public static final String AJLINT_IGNORE = "ignore";
public static final String AJLINT_WARN = "warn";
public static final String AJLINT_ERROR = "error";
public static final String AJLINT_DEFAULT = "default";
private File outputDir;
private File outputJar;
private String outxmlName;
private List/*File*/ sourceRoots = new ArrayList();
private List/*File*/ files = new ArrayList();
private List /*File*/ binaryFiles = new ArrayList(); // .class files in indirs...
private List/*File*/ inJars = new ArrayList();
private List/*File*/ inPath = new ArrayList();
private Map/*String->File*/ sourcePathResources = new HashMap();
private List/*File*/ aspectpath = new ArrayList();
private List/*String*/ classpath = new ArrayList();
private List/*String*/ bootclasspath = new ArrayList();
private File configFile;
private String lintMode = AJLINT_DEFAULT;
private File lintSpecFile = null;
private AjCompilerOptions options;
/** if true, then global values override local when joining */
private boolean override = true;
// incremental variants handled by the compiler client, but parsed here
private boolean incrementalMode;
private File incrementalFile;
public String toString() {
StringBuffer sb = new StringBuffer();
sb.append("BuildConfig["+(configFile==null?"null":configFile.getAbsoluteFile().toString())+"] #Files="+files.size());
return sb.toString();
}
public static class BinarySourceFile {
public BinarySourceFile(File dir, File src) {
this.fromInPathDirectory = dir;
this.binSrc = src;
}
public File fromInPathDirectory;
public File binSrc;
public boolean equals(Object obj) {
if ((obj instanceof BinarySourceFile) &&
(obj != null)) {
BinarySourceFile other = (BinarySourceFile)obj;
return(binSrc.equals(other.binSrc));
}
return false;
}
public int hashCode() {
return binSrc != null ? binSrc.hashCode() : 0;
}
}
/**
* Intialises the javaOptions Map to hold the default
* JDT Compiler settings. Added by AMC 01.20.2003 in reponse
* to bug #29768 and enh. 29769.
* The settings here are duplicated from those set in
* org.eclipse.jdt.internal.compiler.batch.Main, but I've elected to
* copy them rather than refactor the JDT class since this keeps
* integration with future JDT releases easier (?).
*/
public AjBuildConfig( ) {
options = new AjCompilerOptions();
}
/**
* returned files includes <ul>
* <li>files explicitly listed on command-line</li>
* <li>files listed by reference in argument list files</li>
* <li>files contained in sourceRootDir if that exists</li>
* </ul>
*
* @return all source files that should be compiled.
*/
public List/*File*/ getFiles() {
return files;
}
/**
* returned files includes all .class files found in
* a directory on the inpath, but does not include
* .class files contained within jars.
*/
public List/*BinarySourceFile*/ getBinaryFiles() {
return binaryFiles;
}
public File getOutputDir() {
return outputDir;
}
public void setFiles(List files) {
this.files = files;
}
public void setOutputDir(File outputDir) {
this.outputDir = outputDir;
}
public AjCompilerOptions getOptions() {
return options;
}
/**
* This does not include -bootclasspath but includes -extdirs and -classpath
*/
public List getClasspath() { // XXX setters don't respect javadoc contract...
return classpath;
}
public void setClasspath(List classpath) {
this.classpath = classpath;
}
public List getBootclasspath() {
return bootclasspath;
}
public void setBootclasspath(List bootclasspath) {
this.bootclasspath = bootclasspath;
}
public File getOutputJar() {
return outputJar;
}
public String getOutxmlName() {
return outxmlName;
}
public List/*File*/ getInpath() {
// Elements of the list are either archives (jars/zips) or directories
return inPath;
}
public List/*File*/ getInJars() {
return inJars;
}
public Map getSourcePathResources() {
return sourcePathResources;
}
public void setOutputJar(File outputJar) {
this.outputJar = outputJar;
}
public void setOutxmlName(String name) {
this.outxmlName = name;
}
public void setInJars(List sourceJars) {
this.inJars = sourceJars;
}
public void setInPath(List dirsOrJars) {
inPath = dirsOrJars;
// remember all the class files in directories on the inpath
binaryFiles = new ArrayList();
FileFilter filter = new FileFilter() {
public boolean accept(File pathname) {
return pathname.getPath().endsWith(".class");
}};
for (Iterator iter = dirsOrJars.iterator(); iter.hasNext();) {
File inpathElement = (File) iter.next();
if (inpathElement.isDirectory()) {
File[] files = FileUtil.listFiles(inpathElement, filter);
for (int i = 0; i < files.length; i++) {
binaryFiles.add(new BinarySourceFile(inpathElement,files[i]));
}
}
}
}
public List getSourceRoots() {
return sourceRoots;
}
public void setSourceRoots(List sourceRootDir) {
this.sourceRoots = sourceRootDir;
}
public File getConfigFile() {
return configFile;
}
public void setConfigFile(File configFile) {
this.configFile = configFile;
}
public void setIncrementalMode(boolean incrementalMode) {
this.incrementalMode = incrementalMode;
}
public boolean isIncrementalMode() {
return incrementalMode;
}
public void setIncrementalFile(File incrementalFile) {
this.incrementalFile = incrementalFile;
}
public boolean isIncrementalFileMode() {
return (null != incrementalFile);
}
/**
* @return List (String) classpath of bootclasspath, injars, inpath, aspectpath
* entries, specified classpath (extdirs, and classpath), and output dir or jar
*/
public List getFullClasspath() {
List full = new ArrayList();
full.addAll(getBootclasspath()); // XXX Is it OK that boot classpath overrides inpath/injars/aspectpath?
for (Iterator i = inJars.iterator(); i.hasNext(); ) {
full.add(((File)i.next()).getAbsolutePath());
}
for (Iterator i = inPath.iterator();i.hasNext();) {
full.add(((File)i.next()).getAbsolutePath());
}
for (Iterator i = aspectpath.iterator(); i.hasNext(); ) {
full.add(((File)i.next()).getAbsolutePath());
}
full.addAll(getClasspath());
// if (null != outputDir) {
// full.add(outputDir.getAbsolutePath());
// } else if (null != outputJar) {
// full.add(outputJar.getAbsolutePath());
// }
return full;
}
public File getLintSpecFile() {
return lintSpecFile;
}
public void setLintSpecFile(File lintSpecFile) {
this.lintSpecFile = lintSpecFile;
}
public List getAspectpath() {
return aspectpath;
}
public void setAspectpath(List aspectpath) {
this.aspectpath = aspectpath;
}
/** @return true if any config file, sourceroots, sourcefiles, injars or inpath */
public boolean hasSources() {
return ((null != configFile)
|| (0 < sourceRoots.size())
|| (0 < files.size())
|| (0 < inJars.size())
|| (0 < inPath.size())
);
}
// /** @return null if no errors, String errors otherwise */
// public String configErrors() {
// StringBuffer result = new StringBuffer();
// // ok, permit both. sigh.
//// if ((null != outputDir) && (null != outputJar)) {
//// result.append("specified both outputDir and outputJar");
//// }
// // incremental => only sourceroots
// //
// return (0 == result.length() ? null : result.toString());
// }
/**
* Install global values into local config
* unless values conflict:
* <ul>
* <li>Collections are unioned</li>
* <li>values takes local value unless default and global set</li>
* <li>this only sets one of outputDir and outputJar as needed</li>
* <ul>
* This also configures super if javaOptions change.
* @param global the AjBuildConfig to read globals from
*/
public void installGlobals(AjBuildConfig global) { // XXX relies on default values
// don't join the options - they already have defaults taken care of.
// Map optionsMap = options.getMap();
// join(optionsMap,global.getOptions().getMap());
// options.set(optionsMap);
join(aspectpath, global.aspectpath);
join(classpath, global.classpath);
if (null == configFile) {
configFile = global.configFile; // XXX correct?
}
if (!isEmacsSymMode() && global.isEmacsSymMode()) {
setEmacsSymMode(true);
}
join(files, global.files);
if (!isGenerateModelMode() && global.isGenerateModelMode()) {
setGenerateModelMode(true);
}
if (null == incrementalFile) {
incrementalFile = global.incrementalFile;
}
if (!incrementalMode && global.incrementalMode) {
incrementalMode = true;
}
join(inJars, global.inJars);
join(inPath, global.inPath);
if ((null == lintMode)
|| (AJLINT_DEFAULT.equals(lintMode))) {
setLintMode(global.lintMode);
}
if (null == lintSpecFile) {
lintSpecFile = global.lintSpecFile;
}
if (!isNoWeave() && global.isNoWeave()) {
setNoWeave(true);
}
if ((null == outputDir) && (null == outputJar)) {
if (null != global.outputDir) {
outputDir = global.outputDir;
}
if (null != global.outputJar) {
outputJar = global.outputJar;
}
}
join(sourceRoots, global.sourceRoots);
if (!isXnoInline() && global.isXnoInline()) {
setXnoInline(true);
}
if (!isXserializableAspects() && global.isXserializableAspects()) {
setXserializableAspects(true);
}
if (!isXlazyTjp() && global.isXlazyTjp()) {
setXlazyTjp(true);
}
if (!isXHasMemberEnabled() && global.isXHasMemberEnabled()) {
setXHasMemberSupport(true);
}
if (!isXNotReweavable() && global.isXNotReweavable()) {
setXnotReweavable(true);
}
}
void join(Collection local, Collection global) {
for (Iterator iter = global.iterator(); iter.hasNext();) {
Object next = iter.next();
if (!local.contains(next)) {
local.add(next);
}
}
}
void join(Map local, Map global) {
for (Iterator iter = global.keySet().iterator(); iter.hasNext();) {
Object key = iter.next();
if (override || (null == local.get(key))) { //
Object value = global.get(key);
if (null != value) {
local.put(key, value);
}
}
}
}
public void setSourcePathResources(Map map) {
sourcePathResources = map;
}
/**
* used to indicate whether to proceed after parsing config
*/
public boolean shouldProceed() {
return shouldProceed;
}
public void doNotProceed() {
shouldProceed = false;
}
public String getLintMode() {
return lintMode;
}
// options...
public void setLintMode(String lintMode) {
this.lintMode = lintMode;
String lintValue = null;
if (AJLINT_IGNORE.equals(lintMode)) {
lintValue = AjCompilerOptions.IGNORE;
} else if (AJLINT_WARN.equals(lintMode)) {
lintValue = AjCompilerOptions.WARNING;
} else if (AJLINT_ERROR.equals(lintMode)) {
lintValue = AjCompilerOptions.ERROR;
}
if (lintValue != null) {
Map lintOptions = new HashMap();
lintOptions.put(AjCompilerOptions.OPTION_ReportInvalidAbsoluteTypeName,lintValue);
lintOptions.put(AjCompilerOptions.OPTION_ReportInvalidWildcardTypeName,lintValue);
lintOptions.put(AjCompilerOptions.OPTION_ReportUnresolvableMember,lintValue);
lintOptions.put(AjCompilerOptions.OPTION_ReportTypeNotExposedToWeaver,lintValue);
lintOptions.put(AjCompilerOptions.OPTION_ReportShadowNotInStructure,lintValue);
lintOptions.put(AjCompilerOptions.OPTION_ReportUnmatchedSuperTypeInCall,lintValue);
lintOptions.put(AjCompilerOptions.OPTION_ReportCannotImplementLazyTJP,lintValue);
lintOptions.put(AjCompilerOptions.OPTION_ReportNeedSerialVersionUIDField,lintValue);
lintOptions.put(AjCompilerOptions.OPTION_ReportIncompatibleSerialVersion,lintValue);
options.set(lintOptions);
}
}
public boolean isNoWeave() {
return options.noWeave;
}
public void setNoWeave(boolean noWeave) {
options.noWeave = noWeave;
}
public boolean isXserializableAspects() {
return options.xSerializableAspects;
}
public void setXserializableAspects(boolean xserializableAspects) {
options.xSerializableAspects = xserializableAspects;
}
public boolean isXnoInline() {
return options.xNoInline;
}
public void setXnoInline(boolean xnoInline) {
options.xNoInline = xnoInline;
}
public boolean isXlazyTjp() {
return options.xLazyThisJoinPoint;
}
public void setXlazyTjp(boolean b) {
options.xLazyThisJoinPoint = b;
}
public void setXnotReweavable(boolean b) {
options.xNotReweavable = b;
}
public void setXHasMemberSupport(boolean enabled) {
options.xHasMember = enabled;
}
public boolean isXHasMemberEnabled() {
return options.xHasMember;
}
public void setXdevPinpointMode(boolean enabled) {
options.xdevPinpoint = enabled;
}
public boolean isXdevPinpoint() {
return options.xdevPinpoint;
}
public boolean isXNotReweavable() {
return options.xNotReweavable;
}
public boolean isGenerateJavadocsInModelMode() {
return options.generateJavaDocsInModel;
}
public void setGenerateJavadocsInModelMode(
boolean generateJavadocsInModelMode) {
options.generateJavaDocsInModel = generateJavadocsInModelMode;
}
public boolean isGenerateCrossRefsMode() {
return options.generateCrossRefs;
}
public void setGenerateCrossRefsMode(boolean on) {
options.generateCrossRefs = on;
}
public boolean isEmacsSymMode() {
return options.generateEmacsSymFiles;
}
public void setEmacsSymMode(boolean emacsSymMode) {
options.generateEmacsSymFiles = emacsSymMode;
}
public boolean isGenerateModelMode() {
return options.generateModel;
}
public void setGenerateModelMode(boolean structureModelMode) {
options.generateModel = structureModelMode;
}
public boolean isNoAtAspectJAnnotationProcessing() {
return options.noAtAspectJProcessing;
}
public void setNoAtAspectJAnnotationProcessing(boolean noProcess) {
options.noAtAspectJProcessing = noProcess;
}
public void setShowWeavingInformation(boolean b) {
options.showWeavingInformation = true;
}
public boolean getShowWeavingInformation() {
return options.showWeavingInformation;
}
public void setProceedOnError(boolean b) {
options.proceedOnError = b;
}
public boolean getProceedOnError() {
return options.proceedOnError;
}
public void setBehaveInJava5Way(boolean b) {
options.behaveInJava5Way = b;
}
public boolean getBehaveInJava5Way() {
return options.behaveInJava5Way;
}
public void setTargetAspectjRuntimeLevel(String level) {
options.targetAspectjRuntimeLevel = level;
}
public String getTargetAspectjRuntimeLevel() {
return options.targetAspectjRuntimeLevel;
}
}
|
117,209 |
Bug 117209 Runtime error - Stack size too large, Bug#69706 related.
| null |
resolved fixed
|
551b9ca
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2005-11-30T19:51:24Z | 2005-11-20T07:00:00Z |
tests/multiIncremental/pr117209/base/src/Aspect.java
| |
117,209 |
Bug 117209 Runtime error - Stack size too large, Bug#69706 related.
| null |
resolved fixed
|
551b9ca
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2005-11-30T19:51:24Z | 2005-11-20T07:00:00Z |
tests/multiIncremental/pr117209/base/src/Broken.java
| |
117,209 |
Bug 117209 Runtime error - Stack size too large, Bug#69706 related.
| null |
resolved fixed
|
551b9ca
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2005-11-30T19:51:24Z | 2005-11-20T07:00:00Z |
tests/multiIncremental/pr117209/base/src/DefaultInterfaceImplementationRecipe.java
| |
117,209 |
Bug 117209 Runtime error - Stack size too large, Bug#69706 related.
| null |
resolved fixed
|
551b9ca
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2005-11-30T19:51:24Z | 2005-11-20T07:00:00Z |
tests/multiIncremental/pr117209/base/src/MyClass_ch16.java
| |
117,209 |
Bug 117209 Runtime error - Stack size too large, Bug#69706 related.
| null |
resolved fixed
|
551b9ca
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2005-11-30T19:51:24Z | 2005-11-20T07:00:00Z |
tests/multiIncremental/pr117209/base/src/MyInterface_ch16.java
| |
117,209 |
Bug 117209 Runtime error - Stack size too large, Bug#69706 related.
| null |
resolved fixed
|
551b9ca
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2005-11-30T19:51:24Z | 2005-11-20T07:00:00Z |
tests/multiIncremental/pr117209/base/src/P.java
| |
117,209 |
Bug 117209 Runtime error - Stack size too large, Bug#69706 related.
| null |
resolved fixed
|
551b9ca
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2005-11-30T19:51:24Z | 2005-11-20T07:00:00Z |
tests/src/org/aspectj/systemtest/incremental/tools/AjdeInteractionTestbed.java
|
/* *******************************************************************
* Copyright (c) 2005 Contributors.
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Eclipse Public License v1.0
* which accompanies this distribution and is available at
* http://eclipse.org/legal/epl-v10.html
*
* Contributors:
* Andy Clement initial implementation
* ******************************************************************/
package org.aspectj.systemtest.incremental.tools;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import junit.framework.AssertionFailedError;
import junit.framework.TestCase;
import org.aspectj.ajde.Ajde;
import org.aspectj.ajde.BuildOptionsAdapter;
import org.aspectj.ajde.BuildProgressMonitor;
import org.aspectj.ajde.ErrorHandler;
import org.aspectj.ajde.ProjectPropertiesAdapter;
import org.aspectj.ajde.TaskListManager;
import org.aspectj.ajdt.internal.core.builder.AbstractStateListener;
import org.aspectj.ajdt.internal.core.builder.AjState;
import org.aspectj.ajdt.internal.core.builder.IncrementalStateManager;
import org.aspectj.asm.AsmManager;
import org.aspectj.bridge.IMessage;
import org.aspectj.bridge.ISourceLocation;
import org.aspectj.bridge.IMessage.Kind;
/**
* This class uses Ajde in the same way that an IDE (e.g. AJDT) does.
*
* The build is driven through 'build(projectName,configFile)' but the
* build can be configured by the methods beginning 'configure***'.
* Information about what happened during a build is accessible
* through the get*, was*, print* public methods...
*
* There are many methods across the multiple listeners that communicate
* info with Ajde - not all are implemented. Those that are are
* task tagged DOESSOMETHING :)
*/
public class AjdeInteractionTestbed extends TestCase {
public static boolean VERBOSE = false; // do you want the gory details?
public final static String testdataSrcDir = "../tests/multiIncremental";
protected static File sandboxDir;
private static final String SANDBOX_NAME = "ajcSandbox";
private static boolean buildModel;
// Methods for configuring the build
public static void configureBuildStructureModel(boolean b) { buildModel = b;}
public static void configureNewProjectDependency(String fromProject, String projectItDependsOn) {
MyProjectPropertiesAdapter.addDependancy(fromProject,projectItDependsOn);
}
// End of methods for configuring the build
protected File getWorkingDir() { return sandboxDir; }
protected void setUp() throws Exception {
super.setUp();
MyStateListener.reset();
MyBuildProgressMonitor.reset();
MyTaskListManager.reset();
// Create a sandbox in which to work
createEmptySandbox();
}
/** Drives a build */
public boolean build(String projectName,String configFile) {
return AjdeManager.build(projectName,configFile);
}
/** Looks after communicating with the singleton Ajde instance */
public static class AjdeManager {
static {
Ajde.init(null,
MyTaskListManager.getInstance(),
MyBuildProgressMonitor.getInstance(),
MyProjectPropertiesAdapter.getInstance(),
MyBuildOptionsAdapter.getInstance(),
null,null,
MyErrorHandler.getInstance());
MyStateListener sl = MyStateListener.getInstance();
AjState.stateListener = sl;
}
/**
* Builds a specified project using a specified config file. Subsequent
* calls to build the same project should result in incremental builds.
*/
private static boolean build(String projectName,String configFile) {
pause(1000); // delay to allow previous runs build stamps to be OK
lognoln("Building project '"+projectName+"'");
// Ajde.getDefault().enableLogging(System.out);
//Ajde.getDefault().getBuildManager().setReportInfoMessages(true);
// Configure the necessary providers and listeners for this compile
MyBuildProgressMonitor.reset();
MyTaskListManager.reset();
MyStateListener.reset();
MyProjectPropertiesAdapter.setActiveProject(projectName);
AsmManager.attemptIncrementalModelRepairs=true;
IncrementalStateManager.recordIncrementalStates=true;
Ajde.getDefault().getBuildManager().setBuildModelMode(buildModel);
// Do the compile
Ajde.getDefault().getBuildManager().build(getFile(projectName,configFile));
// Wait for it to complete
while (!MyBuildProgressMonitor.hasFinished()) {
lognoln(".");
pause(100);
}
log("");
// What happened?
if (MyTaskListManager.hasErrorMessages()) {
System.err.println("Build errors:");
for (Iterator iter = MyTaskListManager.getErrorMessages().iterator(); iter.hasNext();) {
IMessage element = (IMessage) iter.next();
System.err.println(element);
}
System.err.println("---------");
}
log("Build finished, time taken = "+MyBuildProgressMonitor.getTimeTaken()+"ms");
return true;
}
private static void pause(int millis) {
try {
Thread.sleep(millis);
} catch (InterruptedException ie) {}
}
// public static boolean lastCompileDefaultedToBatch() {
// return MyTaskListManager.defaultedToBatch();
// }
}
// Methods for querying what happened during a build and accessing information
// about the build:
/**
* Helper method for dumping info about which files were compiled and
* woven during the last build.
*/
public String printCompiledAndWovenFiles() {
StringBuffer sb = new StringBuffer();
if (getCompiledFiles().size()==0 && getWovenClasses().size()==0)
sb.append("No files were compiled or woven\n");
for (Iterator iter = getCompiledFiles().iterator(); iter.hasNext();) {
Object element = (Object) iter.next();
sb.append("compiled: "+element+"\n");
}
for (Iterator iter = getWovenClasses().iterator(); iter.hasNext();) {
Object element = (Object) iter.next();
sb.append("woven: "+element+"\n");
}
return sb.toString();
}
/**
* Summary report on what happened in the most recent build
*/
public void printBuildReport() {
System.out.println("\n============== BUILD REPORT =================");
System.out.println("Build took: "+getTimeTakenForBuild()+"ms");
List compiled=getCompiledFiles();
System.out.println("Compiled: "+compiled.size()+" files");
for (Iterator iter = compiled.iterator(); iter.hasNext();) {
System.out.println(" :"+iter.next());
}
List woven=getWovenClasses();
System.out.println("Wove: "+woven.size()+" files");
for (Iterator iter = woven.iterator(); iter.hasNext();) {
System.out.println(" :"+iter.next());
}
if (wasFullBuild()) System.out.println("It was a batch (full) build");
System.out.println("=============================================");
}
public boolean wasFullBuild() {
return MyStateListener.wasFullBuild();
}
public long getTimeTakenForBuild() {
return MyBuildProgressMonitor.getTimeTaken();
}
public List getCompiledFiles() {
return MyBuildProgressMonitor.getCompiledFiles();
}
public List getWovenClasses() {
return MyBuildProgressMonitor.getWovenClasses();
}
// Infrastructure below here
private void createEmptySandbox() {
String os = System.getProperty("os.name");
File tempDir = null;
// AMC - I did this rather than use the JDK default as I hate having to go look
// in c:\documents and settings\......... for the results of a failed test.
if (os.startsWith("Windows")) {
//Alex: try D first since NTFS on mine while FAT leads to failure..
tempDir = new File("D:\\temp");
if (!tempDir.exists()) {
tempDir = new File("C:\\temp");
if (!tempDir.exists()) {
tempDir.mkdir();
}
}
} else {
tempDir = new File("/tmp");
}
File sandboxRoot = new File(tempDir,SANDBOX_NAME);
if (!sandboxRoot.exists()) {
sandboxRoot.mkdir();
}
org.aspectj.util.FileUtil.deleteContents(sandboxRoot);
try {
sandboxDir = File.createTempFile("ajcTest",".tmp",sandboxRoot);
sandboxDir.delete();
sandboxDir.mkdir();
} catch (IOException ioEx) {
throw new AssertionFailedError("Unable to create sandbox directory for test");
}
}
private static void log(String msg) {
if (VERBOSE) System.out.println(msg);
}
private static void lognoln(String msg) {
if (VERBOSE) System.out.print(msg);
}
/** Return the *full* path to this file which is taken relative to the project dir*/
protected static String getFile(String projectName, String path) {
return new File(sandboxDir,projectName+File.separatorChar + path).getAbsolutePath();
}
// Helper classes that communicate with Ajde
static class MyErrorHandler implements ErrorHandler {
static MyErrorHandler _instance = new MyErrorHandler();
private List errorMessages = new ArrayList();
private MyErrorHandler() {}
public static ErrorHandler getInstance() {
return _instance;
}
public void handleWarning(String message) {
log("ErrorHandler.handleWarning("+message+")");
}
public void handleError(String message) {
log("ErrorHandler.handleWarning("+message+")");
errorMessages.add(message);
}
public void handleError(String message, Throwable t) {
log("ErrorHandler.handleError("+message+","+t+")");
if (VERBOSE) t.printStackTrace();
errorMessages.add(message+","+t+")");
}
public static List/*String*/ getErrorMessages() {
return _instance.errorMessages;
}
}
// -----------------
static class MyProjectPropertiesAdapter implements ProjectPropertiesAdapter {
private final static boolean VERBOSE = false;
static MyProjectPropertiesAdapter _instance = new MyProjectPropertiesAdapter();
private MyProjectPropertiesAdapter() {}
public static ProjectPropertiesAdapter getInstance() {
return _instance;
}
private String projectName = null;
public static void setActiveProject(String n) {
_instance.projectName = n;
}
private static Hashtable dependants = new Hashtable();
public static void addDependancy(String project, String projectItDependsOn) {
List l = (List)dependants.get(project);
if (l == null) {
List ps = new ArrayList();
ps.add(projectItDependsOn);
dependants.put(project,ps);
} else {
l.add(projectItDependsOn);
}
}
// interface impl below
// DOESSOMETHING
public String getProjectName() {
log("MyProjectProperties.getProjectName() [returning "+projectName+"]");
return projectName;
}
// DOESSOMETHING
public String getRootProjectDir() {
String dir = testdataSrcDir+File.separatorChar+projectName;
log("MyProjectProperties.getRootProjectDir() [returning "+dir+"]");
return dir;
}
public List getBuildConfigFiles() {
log("MyProjectProperties.getBuildConfigFiles()");
return null;
}
public String getDefaultBuildConfigFile() {
log("MyProjectProperties.getDefaultBuildConfigFile()");
return null;
}
public String getLastActiveBuildConfigFile() {
log("MyProjectProperties.getLastActiveBuildConfigFile()");
return null;
}
public List getProjectSourceFiles() {
log("MyProjectProperties.getProjectSourceFiles()");
return null;
}
public String getProjectSourcePath() {
log("MyProjectProperties.getProjectSourcePath()");
return null;
}
// DOESSOMETHING
public String getClasspath() {
log("MyProjectProperties.getClasspath()");
String cp =
new File(testdataSrcDir) + File.pathSeparator +
System.getProperty("sun.boot.class.path") +
File.pathSeparator + "../runtime/bin" +
File.pathSeparator + System.getProperty("aspectjrt.path") +
File.pathSeparator+".."+File.separator+"lib" + File.separator+"test"+File.separator+"aspectjrt.jar";
// look at dependant projects
List projects = (List)dependants.get(projectName);
if (projects!=null) {
for (Iterator iter = projects.iterator(); iter.hasNext();) {
cp = getFile((String)iter.next(),"bin")+File.pathSeparator+cp;
}
}
//System.err.println("For project "+projectName+" getClasspath() returning "+cp);
return cp;
}
public String getOutputPath() {
String dir = getFile(projectName,"bin");
log("MyProjectProperties.getOutputPath() [returning "+dir+"]");
return dir;
}
public String getBootClasspath() {
log("MyProjectProperties.getBootClasspath()");
return null;
}
public String getClassToExecute() {
log("MyProjectProperties.getClassToExecute()");
return null;
}
public String getExecutionArgs() {
log("MyProjectProperties.getExecutionArgs()");
return null;
}
public String getVmArgs() {
log("MyProjectProperties.getVmArgs()");
return null;
}
public Set getInJars() {
log("MyProjectProperties.getInJars()");
return null;
}
public Set getInpath() {
log("MyProjectProperties.getInPath()");
return null;
}
public Map getSourcePathResources() {
log("MyProjectProperties.getSourcePathResources()");
return null;
}
public String getOutJar() {
log("MyProjectProperties.getOutJar()");
return null;
}
public Set getSourceRoots() {
log("MyProjectProperties.getSourceRoots()");
return null;
}
public Set getAspectPath() {
log("MyProjectProperties.getAspectPath()");
return null;
}
public static void log(String s) {
if (VERBOSE) System.out.println(s);
}
}
// -----------------------
static class MyBuildProgressMonitor implements BuildProgressMonitor {
public static boolean VERBOSE = false;
private static MyBuildProgressMonitor _instance = new MyBuildProgressMonitor();
private MyBuildProgressMonitor() {}
private List compiledFiles=new ArrayList();
private List wovenClasses=new ArrayList();
public static BuildProgressMonitor getInstance() {
return _instance;
}
public static void reset() {
_instance.finished = false;
_instance.compiledFiles.clear();
_instance.wovenClasses.clear();
}
public static boolean hasFinished() {
return _instance.finished;
}
public static List getCompiledFiles() { return _instance.compiledFiles;}
public static List getWovenClasses() { return _instance.wovenClasses; }
//---
private long starttime = 0;
private long totaltimetaken = 0;
private boolean finished = false;
public void start(String configFile) {
starttime = System.currentTimeMillis();
log("BuildProgressMonitor.start("+configFile+")");
}
public void setProgressText(String text) {
log("BuildProgressMonitor.setProgressText("+text+")");
if (text.startsWith("compiled: ")) {
compiledFiles.add(text.substring(10));
} else if (text.startsWith("woven class ")) {
wovenClasses.add(text.substring(12));
} else if (text.startsWith("woven aspect ")) {
wovenClasses.add(text.substring(13));
}
}
public void setProgressBarVal(int newVal) {
log("BuildProgressMonitor.setProgressBarVal("+newVal+")");
}
public void incrementProgressBarVal() {
log("BuildProgressMonitor.incrementProgressBarVal()");
}
public void setProgressBarMax(int maxVal) {
log("BuildProgressMonitor.setProgressBarMax("+maxVal+")");
}
public int getProgressBarMax() {
log("BuildProgressMonitor.getProgressBarMax() [returns 100]");
return 100;
}
public void finish() {
log("BuildProgressMonitor.finish()");
_instance.finished=true;
_instance.totaltimetaken=(System.currentTimeMillis()-starttime);
}
public static long getTimeTaken() {
return _instance.totaltimetaken;
}
public static void log(String s) {
if (VERBOSE) System.out.println(s);
}
}
// ----
static class MyTaskListManager implements TaskListManager {
private static final String CANT_BUILD_INCREMENTAL_INDICATION = "Unable to perform incremental build";
private static final String DOING_BATCH_BUILD_INDICATION = "Performing batch build for config";
private final static boolean VERBOSE = false;
static MyTaskListManager _instance = new MyTaskListManager();
private MyTaskListManager() {}
private boolean receivedNonIncrementalBuildMessage = false;
private boolean receivedBatchBuildMessage = false;
private List errorMessages = new ArrayList();
public static void reset() {
_instance.receivedNonIncrementalBuildMessage=false;
_instance.receivedBatchBuildMessage=false;
_instance.errorMessages.clear();
}
// public static boolean defaultedToBatch() {
// return _instance.receivedNonIncrementalBuildMessage;
// }
//
// public static boolean didBatchBuild() {
// return _instance.receivedBatchBuildMessage;
// }
public static boolean hasErrorMessages() {
return !_instance.errorMessages.isEmpty();
}
public static List/*IMessage*/ getErrorMessages() {
return _instance.errorMessages;
}
public static TaskListManager getInstance() {
return _instance;
}
public void addSourcelineTask(String message, ISourceLocation sourceLocation, Kind kind) {
log("TaskListManager.addSourcelineTask("+message+","+sourceLocation+","+kind+")");
}
// DOESSOMETHING
public void addSourcelineTask(IMessage message) {
// if (message.getKind()==IMessage.INFO) {
// if (message.getMessage().startsWith(CANT_BUILD_INCREMENTAL_INDICATION)) _instance.receivedNonIncrementalBuildMessage=true;
// if (message.getMessage().startsWith(DOING_BATCH_BUILD_INDICATION)) _instance.receivedBatchBuildMessage=true;
// }
if (message.getKind()==IMessage.ERROR) {
errorMessages.add(message);
}
log("TaskListManager.addSourcelineTask("+message+")");
}
public boolean hasWarning() {
log("TaskListManager.hasWarning() [returning false]");
return false;
}
public void addProjectTask(String message, Kind kind) {
log("TaskListManager.addProjectTask("+message+","+kind+")");
}
public void clearTasks() {
log("TaskListManager.clearTasks()");
}
public static void log(String s) {
if (VERBOSE) System.out.println(s);
}
}
// ----
static class MyBuildOptionsAdapter implements BuildOptionsAdapter {
static MyBuildOptionsAdapter _instance = new MyBuildOptionsAdapter();
private MyBuildOptionsAdapter() {}
public static BuildOptionsAdapter getInstance() {
return _instance;
}
public Map getJavaOptionsMap() {
return null;
}
public boolean getUseJavacMode() {
return false;
}
public String getWorkingOutputPath() {
return null;
}
public boolean getPreprocessMode() {
return false;
}
public String getCharacterEncoding() {
return null;
}
public boolean getSourceOnePointFourMode() {
return false;
}
// DOESSOMETHING
public boolean getIncrementalMode() {
return true;
}
public boolean getLenientSpecMode() {
return false;
}
public boolean getStrictSpecMode() {
return false;
}
public boolean getPortingMode() {
return false;
}
public String getNonStandardOptions() {
return null;
}
public String getComplianceLevel() {
return null;
}
public String getSourceCompatibilityLevel() {
return "1.5";
}
public Set getWarnings() {
return null;
}
public Set getDebugLevel() {
return null;
}
public boolean getNoImportError() {
return false;
}
public boolean getPreserveAllLocals() {
return false;
}
}
static class MyStateListener extends AbstractStateListener {
private static MyStateListener _instance = new MyStateListener();
private MyStateListener() {reset();}
public static MyStateListener getInstance() { return _instance;}
public static boolean informedAboutKindOfBuild;
public static boolean fullBuildOccurred;
public static List detectedDeletions = new ArrayList();
public static void reset() {
informedAboutKindOfBuild=false;
fullBuildOccurred=false;
if (detectedDeletions!=null) detectedDeletions.clear();
}
public boolean pathChange = false;
public void pathChangeDetected() {pathChange = true;}
public void aboutToCompareClasspaths(List oldClasspath, List newClasspath) {}
public void detectedClassChangeInThisDir(File f) {}
public void detectedAspectDeleted(File f) {
detectedDeletions.add(f.toString());
}
public void buildSuccessful(boolean wasFullBuild) {
informedAboutKindOfBuild= true;
fullBuildOccurred=wasFullBuild;
}
public static boolean wasFullBuild() {
if (!informedAboutKindOfBuild) throw new RuntimeException("I never heard about what kind of build it was!!");
return fullBuildOccurred;
}
};
}
|
117,209 |
Bug 117209 Runtime error - Stack size too large, Bug#69706 related.
| null |
resolved fixed
|
551b9ca
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2005-11-30T19:51:24Z | 2005-11-20T07:00:00Z |
tests/src/org/aspectj/systemtest/incremental/tools/MultiProjectIncrementalTests.java
|
/* *******************************************************************
* Copyright (c) 2005 Contributors.
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Eclipse Public License v1.0
* which accompanies this distribution and is available at
* http://eclipse.org/legal/epl-v10.html
*
* Contributors:
* Andy Clement initial implementation
* ******************************************************************/
package org.aspectj.systemtest.incremental.tools;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.aspectj.ajdt.internal.core.builder.AjState;
import org.aspectj.ajdt.internal.core.builder.IncrementalStateManager;
import org.aspectj.asm.AsmManager;
import org.aspectj.asm.IProgramElement;
import org.aspectj.bridge.IMessage;
import org.aspectj.testing.util.FileUtil;
/**
* The superclass knows all about talking through Ajde to the compiler.
* The superclass isn't in charge of knowing how to simulate overlays
* for incremental builds, that is in here. As is the ability to
* generate valid build configs based on a directory structure. To
* support this we just need access to a sandbox directory - this
* sandbox is managed by the superclass (it only assumes all builds occur
* in <sandboxDir>/<projectName>/ )
*
* The idea is you can initialize multiple projects in the sandbox and
* they can all be built independently, hopefully exploiting
* incremental compilation. Between builds you can alter the contents
* of a project using the alter() method that overlays some set of
* new files onto the current set (adding new files/changing existing
* ones) - you can then drive a new build and check it behaves as
* expected.
*/
public class MultiProjectIncrementalTests extends AjdeInteractionTestbed {
private static boolean VERBOSE = false;
protected void setUp() throws Exception {
super.setUp();
AjdeInteractionTestbed.VERBOSE = VERBOSE;
}
// Compile a single simple project
public void testTheBasics() {
initialiseProject("P1");
build("P1"); // This first build will be batch
build("P1");
checkWasntFullBuild();
checkCompileWeaveCount(0,0);
}
// Make simple changes to a project, adding a class
public void testSimpleChanges() {
initialiseProject("P1");
build("P1"); // This first build will be batch
alter("P1","inc1"); // adds a single class
build("P1");
checkCompileWeaveCount(1,-1);
build("P1");
checkCompileWeaveCount(0,-1);
}
// Make simple changes to a project, adding a class and an aspect
public void testAddingAnAspect() {
initialiseProject("P1");
build("P1");
alter("P1","inc1"); // adds a class
alter("P1","inc2"); // adds an aspect
build("P1");
long timeTakenForFullBuildAndWeave = getTimeTakenForBuild();
checkWasntFullBuild();
checkCompileWeaveCount(2,3);
build("P1");
long timeTakenForSimpleIncBuild = getTimeTakenForBuild();
// I don't think this test will have timing issues as the times should be *RADICALLY* different
// On my config, first build time is 2093ms and the second is 30ms
assertTrue("Should not take longer for the trivial incremental build! first="+timeTakenForFullBuildAndWeave+
"ms second="+timeTakenForSimpleIncBuild+"ms",
timeTakenForSimpleIncBuild<timeTakenForFullBuildAndWeave);
}
public void testBuildingTwoProjectsInTurns() {
configureBuildStructureModel(true);
initialiseProject("P1");
initialiseProject("P2");
build("P1");
build("P2");
build("P1");
checkWasntFullBuild();
build("P2");
checkWasntFullBuild();
}
/**
* In order for this next test to run, I had to move the weaver/world pair we keep in the
* AjBuildManager instance down into the state object - this makes perfect sense - otherwise
* when reusing the state for another project we'd not be switching to the right weaver/world
* for that project.
*/
public void testBuildingTwoProjectsMakingSmallChanges() {
configureBuildStructureModel(true);
initialiseProject("P1");
initialiseProject("P2");
build("P1");
build("P2");
build("P1");
checkWasntFullBuild();
build("P2");
checkWasntFullBuild();
alter("P1","inc1"); // adds a class
alter("P1","inc2"); // adds an aspect
build("P1");
checkWasntFullBuild();
}
/**
* Setup up two simple projects and build them in turn - check the
* structure model is right after each build
*/
public void testBuildingTwoProjectsAndVerifyingModel() {
configureBuildStructureModel(true);
initialiseProject("P1");
initialiseProject("P2");
build("P1");
checkForNode("pkg","C",true);
build("P2");
checkForNode("pkg","C",false);
build("P1");
checkForNode("pkg","C",true);
build("P2");
checkForNode("pkg","C",false);
}
// Setup up two simple projects and build them in turn - check the
// structure model is right after each build
public void testBuildingTwoProjectsAndVerifyingStuff() {
configureBuildStructureModel(true);
initialiseProject("P1");
initialiseProject("P2");
build("P1");
checkForNode("pkg","C",true);
build("P2");
checkForNode("pkg","C",false);
build("P1");
checkForNode("pkg","C",true);
build("P2");
checkForNode("pkg","C",false);
}
/**
* Complex. Here we are testing that a state object records structural changes since
* the last full build correctly. We build a simple project from scratch - this will
* be a full build and so the structural changes since last build count should be 0.
* We then alter a class, adding a new method and check structural changes is 1.
*/
public void testStateManagement1() {
File binDirectoryForP1 = new File(getFile("P1","bin"));
initialiseProject("P1");
build("P1"); // full build
AjState ajs = IncrementalStateManager.findStateManagingOutputLocation(binDirectoryForP1);
assertTrue("There should be a state object for project P1",ajs!=null);
assertTrue("Should be no structural changes as it was a full build but found: "+
ajs.getNumberOfStructuralChangesSinceLastFullBuild(),
ajs.getNumberOfStructuralChangesSinceLastFullBuild()==0);
alter("P1","inc3"); // adds a method to the class C.java
build("P1");
checkWasntFullBuild();
ajs = IncrementalStateManager.findStateManagingOutputLocation(new File(getFile("P1","bin")));
assertTrue("There should be state for project P1",ajs!=null);
checkWasntFullBuild();
assertTrue("Should be one structural changes as it was a full build but found: "+
ajs.getNumberOfStructuralChangesSinceLastFullBuild(),
ajs.getNumberOfStructuralChangesSinceLastFullBuild()==1);
}
/**
* Complex. Here we are testing that a state object records structural changes since
* the last full build correctly. We build a simple project from scratch - this will
* be a full build and so the structural changes since last build count should be 0.
* We then alter a class, changing body of a method, not the structure and
* check struc changes is still 0.
*/
public void testStateManagement2() {
File binDirectoryForP1 = new File(getFile("P1","bin"));
initialiseProject("P1");
alter("P1","inc3"); // need this change in here so 'inc4' can be applied without making
// it a structural change
build("P1"); // full build
AjState ajs = IncrementalStateManager.findStateManagingOutputLocation(binDirectoryForP1);
assertTrue("There should be state for project P1",ajs!=null);
assertTrue("Should be no struc changes as its a full build: "+
ajs.getNumberOfStructuralChangesSinceLastFullBuild(),
ajs.getNumberOfStructuralChangesSinceLastFullBuild()==0);
alter("P1","inc4"); // changes body of main() method but does *not* change the structure of C.java
build("P1");
checkWasntFullBuild();
ajs = IncrementalStateManager.findStateManagingOutputLocation(new File(getFile("P1","bin")));
assertTrue("There should be state for project P1",ajs!=null);
checkWasntFullBuild();
assertTrue("Shouldn't be any structural changes but there were "+
ajs.getNumberOfStructuralChangesSinceLastFullBuild(),
ajs.getNumberOfStructuralChangesSinceLastFullBuild()==0);
}
/**
* Now the most complex test. Create a dependancy between two projects. Building
* one may affect whether the other does an incremental or full build. The
* structural information recorded in the state object should be getting used
* to control whether a full build is necessary...
*/
public void testBuildingDependantProjects() {
initialiseProject("P1");
initialiseProject("P2");
configureNewProjectDependency("P2","P1");
build("P1");
build("P2"); // now everything is consistent and compiled
alter("P1","inc1"); // adds a second class
build("P1");
build("P2"); // although a second class was added - P2 can't be using it, so we don't full build here :)
checkWasntFullBuild();
alter("P1","inc3"); // structurally changes one of the classes
build("P1");
build("P2"); // build notices the structural change
checkWasFullBuild();
alter("P1","inc4");
build("P1");
build("P2"); // build sees a change but works out its not structural
checkWasntFullBuild();
}
public void testPr85132() {
initialiseProject("PR85132");
build("PR85132");
alter("PR85132","inc1");
build("PR85132");
}
public void testPr92837() {
initialiseProject("PR92837");
build("PR92837");
alter("PR92837","inc1");
build("PR92837");
}
public void testPr114875() {
initialiseProject("pr114875");
build("pr114875");
alter("pr114875","inc1");
build("pr114875");
checkWasntFullBuild();
alter("pr114875","inc2");
build("pr114875");
checkWasntFullBuild();
}
public void testPr115251() {
//AjdeInteractionTestbed.VERBOSE=true;
initialiseProject("PR115251");
build("PR115251");
checkWasFullBuild();
alter("PR115251","inc1");
build("PR115251");
checkWasntFullBuild();
}
/* public void testPr111779() {
super.VERBOSE=true;
initialiseProject("PR111779");
build("PR111779");
alter("PR111779","inc1");
build("PR111779");
}
*/
public void testPr93310_1() {
initialiseProject("PR93310_1");
build("PR93310_1");
checkWasFullBuild();
String fileC2 = getWorkingDir().getAbsolutePath() + File.separatorChar + "PR93310_1" + File.separatorChar + "src" + File.separatorChar + "pack" + File.separatorChar + "C2.java";
(new File(fileC2)).delete();
alter("PR93310_1","inc1");
build("PR93310_1");
checkWasFullBuild();
int l = AjdeInteractionTestbed.MyStateListener.detectedDeletions.size();
assertTrue("Expected one deleted file to be noticed, but detected: "+l,l==1);
String name = (String)AjdeInteractionTestbed.MyStateListener.detectedDeletions.get(0);
assertTrue("Should end with C2.java but is "+name,name.endsWith("C2.java"));
}
public void testPr93310_2() {
initialiseProject("PR93310_2");
build("PR93310_2");
checkWasFullBuild();
String fileC2 = getWorkingDir().getAbsolutePath() + File.separatorChar + "PR93310_2" + File.separatorChar + "src" + File.separatorChar + "pack" + File.separatorChar + "C2.java";
(new File(fileC2)).delete();
alter("PR93310_2","inc1");
build("PR93310_2");
checkWasFullBuild();
int l = AjdeInteractionTestbed.MyStateListener.detectedDeletions.size();
assertTrue("Expected one deleted file to be noticed, but detected: "+l,l==1);
String name = (String)AjdeInteractionTestbed.MyStateListener.detectedDeletions.get(0);
assertTrue("Should end with C2.java but is "+name,name.endsWith("C2.java"));
}
// Stage1: Compile two files, pack.A and pack.A1 - A1 sets a protected field in A.
// Stage2: make the field private in class A > gives compile error
// Stage3: Add a new aspect whilst there is a compile error !
public void testPr113531() {
initialiseProject("PR113531");
build("PR113531");
assertFalse("build should have compiled ok",
MyTaskListManager.hasErrorMessages());
alter("PR113531","inc1");
build("PR113531");
assertEquals("error message should be 'foo cannot be resolved' ",
"foo cannot be resolved",
((IMessage)MyTaskListManager.getErrorMessages().get(0))
.getMessage());
alter("PR113531","inc2");
build("PR113531");
assertTrue("There should be no exceptions handled:\n"+MyErrorHandler.getErrorMessages(),
MyErrorHandler.getErrorMessages().isEmpty());
assertEquals("error message should be 'foo cannot be resolved' ",
"foo cannot be resolved",
((IMessage)MyTaskListManager.getErrorMessages().get(0))
.getMessage());
}
public void testPr112736() {
AjdeInteractionTestbed.VERBOSE = true;
initialiseProject("PR112736");
build("PR112736");
checkWasFullBuild();
String fileC2 = getWorkingDir().getAbsolutePath() + File.separatorChar + "PR112736" + File.separatorChar + "src" + File.separatorChar + "pack" + File.separatorChar + "A.java";
(new File(fileC2)).delete();
alter("PR112736","inc1");
build("PR112736");
checkWasFullBuild();
}
// other possible tests:
// - memory usage (freemem calls?)
// - relationship map
// ---------------------------------------------------------------------------------------------------
/**
* Check we compiled/wove the right number of files, passing '-1' indicates you don't care about
* that number.
*/
private void checkCompileWeaveCount(int expCompile,int expWoven) {
if (expCompile!=-1 && getCompiledFiles().size()!=expCompile)
fail("Expected compilation of "+expCompile+" files but compiled "+getCompiledFiles().size()+
"\n"+printCompiledAndWovenFiles());
if (expWoven!=-1 && getWovenClasses().size()!=expWoven)
fail("Expected weaving of "+expWoven+" files but wove "+getWovenClasses().size()+
"\n"+printCompiledAndWovenFiles());
}
private void checkWasntFullBuild() {
assertTrue("Shouldn't have been a full (batch) build",!wasFullBuild());
}
private void checkWasFullBuild() {
assertTrue("Should have been a full (batch) build",wasFullBuild());
}
private void checkForNode(String packageName,String typeName,boolean shouldBeFound) {
IProgramElement ipe = AsmManager.getDefault().getHierarchy().findElementForType(packageName,typeName);
if (shouldBeFound) {
if (ipe==null) printModel();
assertTrue("Should have been able to find '"+packageName+"."+typeName+"' in the asm",ipe!=null);
} else {
if (ipe!=null) printModel();
assertTrue("Should have NOT been able to find '"+packageName+"."+typeName+"' in the asm",ipe==null);
}
}
private void printModel() {
try {
AsmManager.dumptree(AsmManager.getDefault().getHierarchy().getRoot(),0);
} catch (IOException e) {
e.printStackTrace();
}
}
public void build(String projectName) {
constructUpToDateLstFile(projectName,"build.lst");
build(projectName,"build.lst");
if (AjdeInteractionTestbed.VERBOSE) printBuildReport();
}
private void constructUpToDateLstFile(String pname,String configname) {
File projectBase = new File(sandboxDir,pname);
File toConstruct = new File(projectBase,configname);
List filesForCompilation = new ArrayList();
collectUpFiles(projectBase,projectBase,filesForCompilation);
try {
FileOutputStream fos = new FileOutputStream(toConstruct);
DataOutputStream dos = new DataOutputStream(fos);
for (Iterator iter = filesForCompilation.iterator(); iter.hasNext();) {
String file = (String) iter.next();
dos.writeBytes(file+"\n");
}
dos.close();
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
private void collectUpFiles(File location,File base,List collectionPoint) {
String contents[] = location.list();
if (contents==null) return;
for (int i = 0; i < contents.length; i++) {
String string = contents[i];
File f = new File(location,string);
if (f.isDirectory()) {
collectUpFiles(f,base,collectionPoint);
} else if (f.isFile() && (f.getName().endsWith(".aj") || f.getName().endsWith(".java"))) {
String fileFound;
try {
fileFound = f.getCanonicalPath();
String toRemove = base.getCanonicalPath();
if (!fileFound.startsWith(toRemove)) throw new RuntimeException("eh? "+fileFound+" "+toRemove);
collectionPoint.add(fileFound.substring(toRemove.length()+1));//+1 captures extra separator
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
/**
* Fill in the working directory with the project base files,
* from the 'base' folder.
*/
private 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);
}
}
|
118,781 |
Bug 118781 [waiting-on-build]VerifyError in AspectJ
|
I'm fairly new to AspectJ, so this is probably not going to be well explained. I've started working on a project that was working fine. Then I added methods to classes that take a 2-dimensional string array parameter and suddenly I'm getting a VerifyError exception. java.lang.VerifyError: (class: com/drkw/cpds/obligor/facades/version_1_00/ObligorDetailFacade_1_00, method: searchForObligorSummariesByGroup_aroundBody24 signature: (Lcom/drkw/cpds/obligor/facades/version_1_00/ObligorDetailFacade_1_00;[[[Ljava/lang/String;Ljava/lang/String;LjavaA(‚ at com.drkw.cpds.obligor.facades.version_1_00.obligor.ObligorManager.<clinit>(ObligorManager.java:48) at com.drkw.cpds.obligor.integration.version_1_00.obligor.GetObligorDetailsGroupingTest.testGetObligorDetailsUsingGroups(GetObligorDetailsGroupingTest.java:45) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
|
resolved fixed
|
a75b7fa
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2005-12-01T15:00:22Z | 2005-12-01T09:40:00Z |
tests/bugs150/pr118781/MyAspect.java
| |
118,781 |
Bug 118781 [waiting-on-build]VerifyError in AspectJ
|
I'm fairly new to AspectJ, so this is probably not going to be well explained. I've started working on a project that was working fine. Then I added methods to classes that take a 2-dimensional string array parameter and suddenly I'm getting a VerifyError exception. java.lang.VerifyError: (class: com/drkw/cpds/obligor/facades/version_1_00/ObligorDetailFacade_1_00, method: searchForObligorSummariesByGroup_aroundBody24 signature: (Lcom/drkw/cpds/obligor/facades/version_1_00/ObligorDetailFacade_1_00;[[[Ljava/lang/String;Ljava/lang/String;LjavaA(‚ at com.drkw.cpds.obligor.facades.version_1_00.obligor.ObligorManager.<clinit>(ObligorManager.java:48) at com.drkw.cpds.obligor.integration.version_1_00.obligor.GetObligorDetailsGroupingTest.testGetObligorDetailsUsingGroups(GetObligorDetailsGroupingTest.java:45) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
|
resolved fixed
|
a75b7fa
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2005-12-01T15:00:22Z | 2005-12-01T09:40:00Z |
tests/bugs150/pr118781/MyClass.java
| |
118,781 |
Bug 118781 [waiting-on-build]VerifyError in AspectJ
|
I'm fairly new to AspectJ, so this is probably not going to be well explained. I've started working on a project that was working fine. Then I added methods to classes that take a 2-dimensional string array parameter and suddenly I'm getting a VerifyError exception. java.lang.VerifyError: (class: com/drkw/cpds/obligor/facades/version_1_00/ObligorDetailFacade_1_00, method: searchForObligorSummariesByGroup_aroundBody24 signature: (Lcom/drkw/cpds/obligor/facades/version_1_00/ObligorDetailFacade_1_00;[[[Ljava/lang/String;Ljava/lang/String;LjavaA(‚ at com.drkw.cpds.obligor.facades.version_1_00.obligor.ObligorManager.<clinit>(ObligorManager.java:48) at com.drkw.cpds.obligor.integration.version_1_00.obligor.GetObligorDetailsGroupingTest.testGetObligorDetailsUsingGroups(GetObligorDetailsGroupingTest.java:45) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
|
resolved fixed
|
a75b7fa
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2005-12-01T15:00:22Z | 2005-12-01T09:40:00Z |
tests/bugs150/pr118781/MyMain.java
| |
118,781 |
Bug 118781 [waiting-on-build]VerifyError in AspectJ
|
I'm fairly new to AspectJ, so this is probably not going to be well explained. I've started working on a project that was working fine. Then I added methods to classes that take a 2-dimensional string array parameter and suddenly I'm getting a VerifyError exception. java.lang.VerifyError: (class: com/drkw/cpds/obligor/facades/version_1_00/ObligorDetailFacade_1_00, method: searchForObligorSummariesByGroup_aroundBody24 signature: (Lcom/drkw/cpds/obligor/facades/version_1_00/ObligorDetailFacade_1_00;[[[Ljava/lang/String;Ljava/lang/String;LjavaA(‚ at com.drkw.cpds.obligor.facades.version_1_00.obligor.ObligorManager.<clinit>(ObligorManager.java:48) at com.drkw.cpds.obligor.integration.version_1_00.obligor.GetObligorDetailsGroupingTest.testGetObligorDetailsUsingGroups(GetObligorDetailsGroupingTest.java:45) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
|
resolved fixed
|
a75b7fa
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2005-12-01T15:00:22Z | 2005-12-01T09:40:00Z |
tests/src/org/aspectj/systemtest/ajc150/Ajc150Tests.java
|
/*******************************************************************************
* Copyright (c) 2004 IBM
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* Andy Clement - initial API and implementation
*******************************************************************************/
package org.aspectj.systemtest.ajc150;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.List;
import junit.framework.Test;
import org.aspectj.apache.bcel.classfile.JavaClass;
import org.aspectj.apache.bcel.classfile.Method;
import org.aspectj.apache.bcel.classfile.Signature;
import org.aspectj.apache.bcel.util.ClassPath;
import org.aspectj.apache.bcel.util.SyntheticRepository;
import org.aspectj.asm.AsmManager;
import org.aspectj.asm.IHierarchy;
import org.aspectj.asm.IProgramElement;
import org.aspectj.asm.IRelationship;
import org.aspectj.asm.internal.Relationship;
import org.aspectj.testing.XMLBasedAjcTestCase;
import org.aspectj.util.LangUtil;
public class Ajc150Tests extends org.aspectj.testing.XMLBasedAjcTestCase {
public static Test suite() {
return XMLBasedAjcTestCase.loadSuite(Ajc150Tests.class);
}
protected File getSpecFile() {
return new File("../tests/src/org/aspectj/systemtest/ajc150/ajc150.xml");
}
/*
public void testBrokenDispatchByITD_pr72834() { runTest("broken dispatch");}
public void testMissingAccessor_pr73856() { runTest("missing accessor");}
public void testCunningDeclareParents_pr92311() { runTest("cunning declare parents");}
public void testGenericITDsAndAbstractMethodError_pr102357() { runTest("generic itds and abstract method error");}
*/
public void testGeneratingCodeForAnOldRuntime_pr116679_1() { runTest("generating code for a 1.2.1 runtime - 1");}
public void testGeneratingCodeForAnOldRuntime_pr116679_2() { runTest("generating code for a 1.2.1 runtime - 2");}
public void testAmbiguousMethod_pr118599_1() { runTest("ambiguous method when binary weaving - 1");}
public void testAmbiguousMethod_pr118599_2() { runTest("ambiguous method when binary weaving - 2");}
public void testAtDeclareParents_pr117681() { runTest("at declare parents");}
public void testPrivilegeProblem_pr87525() { runTest("privilege problem with switch");}
public void testGenericAspects_pr115237() { runTest("aspectOf and generic aspects");}
public void testClassFormatError_pr114436() { runTest("ClassFormatError binary weaving perthis");}
public void testParserException_pr115788() { runTest("parser exception");}
public void testPossibleStaticImports_pr113066_1() { runTest("possible static imports bug - 1");}
public void testPossibleStaticImports_pr113066_2() { runTest("possible static imports bug - 2");}
public void testPossibleStaticImports_pr113066_3() { runTest("possible static imports bug - 3");}
public void testITDCtor_pr112783() { runTest("Problem with constructor ITDs");}
public void testAnnotatedITDFs_pr114005_1() { runTest("Annotated ITDFs - 1");}
public void testAnnotatedITDFs_pr114005_2() { runTest("Annotated ITDFs - 2");}
public void testCantCallSuperMethods_pr90143() { runTest("cant call super methods");}
public void testBrokenDecp_pr112476() { runTest("binary weaving decp broken");}
public void testUnboundFormal_pr112027() { runTest("unexpected error unboundFormalInPC");}
public void testNPEScopeSetup_pr115038() { runTest("NPE in ensureScopeSetup");}
public void testCCEGenerics_pr113445() { runTest("Generics ClassCastException");}
public void testMatthewsAspect_pr113947_1() { runTest("maws generic aspect - 1");}
public void testMatthewsAspect_pr113947_2() { runTest("maws generic aspect - 2");}
public void testFieldGet_pr114343() { runTest("field-get, generics and around advice");}
public void testFieldGet_pr114343_2() { runTest("field-get, generics and around advice - 2");}
public void testFieldGet_pr114343_3() { runTest("field-get, generics and around advice - 3");}
public void testCaptureBinding_pr114744() { runTest("capturebinding wildcard problem");}
public void testBadDecp_pr110788_1() { runTest("bad generic decp - 1");}
public void testBadDecp_pr110788_2() { runTest("bad generic decp - 2");}
public void testBadDecp_pr110788_3() { runTest("bad generic decp - 3");}
public void testBadDecp_pr110788_4() { runTest("bad generic decp - 4");}
public void testVarargsITD_pr110906() { runTest("ITD varargs problem");}
public void testBadRenderer_pr86903() { runTest("bcelrenderer bad");}
// public void testIllegalInitialization_pr118326_1() { runTest("illegal initialization - 1");}
// public void testIllegalInitialization_pr118326_2() { runTest("illegal initialization - 2");}
public void testLintForAdviceSorting_pr111667() { runTest("lint for advice sorting");}
public void testIncompatibleClassChangeError_pr113630_1() {runTest("IncompatibleClassChangeError - errorscenario");}
public void testIncompatibleClassChangeError_pr113630_2() {runTest("IncompatibleClassChangeError - workingscenario");}
public void testFieldGetProblemWithGenericField_pr113861() {runTest("field-get problems with generic field");}
public void testDeclareAnnotationOnNonExistentType_pr99191_1() { runTest("declare annotation on non existent type - 1");}
public void testDeclareAnnotationOnNonExistentType_pr99191_2() { runTest("declare annotation on non existent type - 2");}
public void testDeclareAnnotationOnNonExistentType_pr99191_3() { runTest("declare annotation on non existent type - 3");}
public void testDeclareAnnotationOnNonExistentType_pr99191_4() { runTest("declare annotation on non existent type - 4");}
public void testDeclareAnnotationOnNonExistentType_pr99191_5() { runTest("declare annotation on non existent type - 5");}
public void testBadGenericSigAttribute_pr110927() {
runTest("cant create signature attribute");
Signature sig = GenericsTests.getClassSignature(ajc,"I");
if (sig==null) fail("Couldn't find signature attribute for type I");
String sigString = sig.getSignature();
if (!(sigString.equals("Ljava/lang/Object;LIE2;LIE1<Ljava/lang/String;>;") ||
sigString.equals("Ljava/lang/Object;LIE1<Ljava/lang/String;>;LIE2;"))) {
fail("Signature was "+sigString+" when should have been something like Ljava/lang/Object;LIE1<Ljava/lang/String;>;LIE2;");
}
}
public void test_typeProcessingOrderWhenDeclareParents() {
runTest("Order of types passed to compiler determines weaving behavior");
}
public void test_aroundMethod() {
runTest("method called around in class");
}
public void test_aroundMethodAspect() {
runTest("method called around in aspect");
}
public void test_ambiguousBindingsDetection() {
runTest("Various kinds of ambiguous bindings");
}
public void test_ambiguousArgsDetection() {
runTest("ambiguous args");
}
public void testIncorrectExceptionTableWhenBreakInMethod_pr78021() {
runTest("Injecting exception into while loop with break statement causes catch block to be ignored");
}
public void testIncorrectExceptionTableWhenReturnInMethod_pr79554() {
runTest("Return in try-block disables catch-block if final-block is present");
}
public void testMissingDebugInfoForGeneratedMethods_pr82570() throws ClassNotFoundException {
runTest("Weaved code does not include debug lines");
boolean f = false;
JavaClass jc = getClassFrom(ajc.getSandboxDirectory(),"PR82570_1");
Method[] meths = jc.getMethods();
for (int i = 0; i < meths.length; i++) {
Method method = meths[i];
if (f) System.err.println("Line number table for "+method.getName()+method.getSignature()+" = "+method.getLineNumberTable());
assertTrue("Didn't find a line number table for method "+method.getName()+method.getSignature(),
method.getLineNumberTable()!=null);
}
// This test would determine the info isn't there if you pass -g:none ...
// cR = ajc(baseDir,new String[]{"PR82570_1.java","-g:none"});
// assertTrue("Expected no compile problem:"+cR,!cR.hasErrorMessages());
// System.err.println(cR.getStandardError());
// jc = getClassFrom(ajc.getSandboxDirectory(),"PR82570_1");
// meths = jc.getMethods();
// for (int i = 0; i < meths.length; i++) {
// Method method = meths[i];
// assertTrue("Found a line number table for method "+method.getName(),
// method.getLineNumberTable()==null);
// }
}
public void testCanOverrideProtectedMethodsViaITDandDecp_pr83303() {
runTest("compiler error when mixing inheritance, overriding and polymorphism");
}
public void testPerTypeWithin_pr106554() {runTest("Problem in staticinitialization with pertypewithin aspect");}
public void testPerTypeWithinMissesNamedInnerTypes() {
runTest("pertypewithin() handing of inner classes (1)");
}
public void testPerTypeWithinMissesAnonymousInnerTypes() {
runTest("pertypewithin() handing of inner classes (2)");
}
public void testPerTypeWithinIncorrectlyMatchingInterfaces() {
runTest("pertypewithin({interface}) illegal field modifier");
}
public void test051_arrayCloningInJava5() {
runTest("AJC possible bug with static nested classes");
}
public void testBadASMforEnums() throws IOException {
runTest("bad asm for enums");
if (LangUtil.is15VMOrGreater()) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
PrintWriter pw = new PrintWriter(baos);
AsmManager.dumptree(pw,AsmManager.getDefault().getHierarchy().getRoot(),0);
pw.flush();
String tree = baos.toString();
assertTrue("Expected 'Red [enumvalue]' somewhere in here:"+tree,tree.indexOf("Red [enumvalue]")!=-1);
}
}
public void npeOnTypeNotFound() {
runTest("structure model npe on type not found");
}
public void testNoRuntimeExceptionSoftening() {
runTest("declare soft of runtime exception");
}
public void testRuntimeNoSoftenWithHandler() {
runTest("declare soft w. catch block");
}
public void testSyntaxError() {
runTest("invalid cons syntax");
}
public void testVarargsInConsBug() {
runTest("varargs in constructor sig");
}
public void testAspectpathdirs() {
runTest("dirs on aspectpath");
}
public void testIntroSample() {
runTest("introduction sample");
}
public void testPTWInterface() {
runTest("pertypewithin({interface}) illegal field modifier");
}
public void testEnumCalledEnumEtc() {
runTest("enum called Enum, annotation called Annotation, etc");
}
public void testInternalCompilerError_pr86832() {
runTest("Internal compiler error");
}
public void testCloneMethod_pr83311() {
runTest("overriding/polymorphism error on interface method introduction");
}
// IfPointcut.findResidueInternal() was modified to make this test complete in a short amount
// of time - if you see it hanging, someone has messed with the optimization.
public void testIfEvaluationExplosion_pr94086() {
runTest("Exploding compile time with if() statements in pointcut");
}
public void testReflectNPE_pr94167() {runTest("NPE in reflect implementation");}
public void testStaticImports_pr84260() {runTest("static import failures");}
public void testGenerics_pr99089() {runTest("ArrayIndexOutOfBoundsException - Generics in privileged aspects");}
public void testGenerics_pr95993() {runTest("NPE at ClassScope.java:660 when compiling generic class");}
public void testItdGenerics_pr99228() {runTest("ITD of a field into a generic class");}
public void testItdGenerics_pr98320() {runTest("intertype with nested generic type");}
public void testItdGenerics_pr100227() {runTest("inner class with generic enclosing class");}
public void testItdGenerics_pr100260() {runTest("methods inherited from a generic parent");}
public void testSyntaxErrorNPE_pr103266() {runTest("NPE on syntax error");}
public void testFinalAbstractClass_pr109486() { runTest("Internal compiler error (ClassParser.java:242)");}
public void testComplexBinding_pr102210() { runTest("NullPointerException trying to compile");}
public void testIllegalStateExceptionOnNestedParameterizedType_pr106634() {
runTest("IllegalStateException unpacking signature of nested parameterized type");
}
public void testParseErrorOnAnnotationStarPlusPattern() {
runTest("(@Foo *)+ type pattern parse error");
}
public void test_pr106130_tooManyLocals() {
runTest("test weaving with > 256 locals");
}
public void testMissingNamePattern_pr106461() { runTest("missing name pattern"); }
public void testMissingNamePattern_pr107059() {
runTest("parser crashes on call(void (@a *)(..)");
}
public void testIntermediateAnnotationMatching() {
runTest("intermediate annotation matching");
}
public void testBadRuntimeTestGeneration() {
runTest("target(@Foo *)");
}
public void testErrorMessageOnITDWithTypePatterns() {
runTest("clear error message on itd with type pattern");
}
public void testAjKeywordsAsIdentifiers() {
runTest("before and after are valid identifiers in classes");
}
public void testAjKeywordsAsIdentifiers2() {
runTest("before and after are valid identifiers in classes, part 2");
}
public void testNoBeforeReturningAdvice() {
runTest("before returning advice not allowed!");
}
public void testDetectVoidFieldType() {
runTest("void field type in pointcut expression");
}
public void testPointcutOverriding() {
runTest("overriding final pointcut from super-aspect");
}
public void testAtSuppressWarnings() {
runTest("@SuppressWarnings should suppress");
}
public void testDEOWWithBindingPointcut() {
runTest("declare warning : foo(str) : ...;");
}
public void testAroundAdviceAndInterfaceInitializer() {
runTest("around advice on interface initializer");
}
public void testGoodErrorMessageOnUnmatchedMemberSyntax() {
runTest("good error message for unmatched member syntax");
}
public void testITDWithNoExceptionAndIntermediary() {
runTest("itd override with no exception clause");
}
public void testAnonymousInnerClasses() {
runTest("anonymous inner classes");
}
public void testMultipleAnonymousInnerClasses() {
runTest("multiple anonymous inner classes");
}
public void testPrivilegedMethodAccessorsGetRightExceptions_pr82989() {
runTest("Compiler error due to a wrong exception check in try blocks");
}
public void testAnonymousInnerClassWithMethodReturningTypeParameter_pr107898() {
runTest("anonymous inner class with method returning type parameter");
}
public void testMatchingOfObjectArray() {
runTest("matching against Object[]");
}
public void testMultipleAnonymousInnerClasses_pr108104() {
runTest("multiple anonymous inner classes 2");
}
public void testSignatureMatchingInMultipleOverrideScenario() {
runTest("signature matching in override scenario");
}
public void testWildcardAnnotationMatching_pr108245() {
runTest("wildcard annotation matching - pr108245");
}
public void testInnerTypesAndTypeVariables() {
runTest("inner types and type variables");
}
public void testAtAfterThrowingWithNoFormal() {
runTest("@AfterThrowing with no formal specified");
}
public void testParameterizedVarArgsMatch() {
runTest("varargs with type variable");
}
public void testFieldAccessInsideITDM() {
runTest("itd field access inside itd method");
}
public void testTypeVarWithTypeVarBound() {
runTest("type variable with type variable bound");
}
public void testEnumSwitchInITD() {
runTest("switch on enum inside ITD method");
}
public void testInnerTypeOfGeneric() {
runTest("inner type of generic interface reference from parameterized type");
}
public void testDeclareParentsIntroducingCovariantReturnType() {
runTest("declare parents introducing override with covariance");
}
public void testInnerClassPassedToVarargs() {
runTest("inner class passed as argument to varargs method");
}
public void testInlinedFieldAccessInProceedCall() {
runTest("inlined field access in proceed call");
}
public void testVisibiltyInSignatureMatchingWithOverridesPart1() {
runTest("visibility in signature matching with overrides - 1");
}
public void testVisibiltyInSignatureMatchingWithOverridesPart2() {
runTest("visibility in signature matching with overrides - 2");
}
public void testVisibiltyInSignatureMatchingWithOverridesPart3() {
runTest("visibility in signature matching with overrides - 3");
}
public void testArgsGeneratedCorrectlyForAdviceExecution() {
runTest("args generated correctly for advice execution join point");
}
public void testNoUnusedWarningsOnAspectTypes() {
runTest("no unused warnings on aspect types");
}
public void testSyntheticArgumentsOnITDConstructorsNotUsedInMatching() {
runTest("synthetic arguments on itd cons are not used in matching");
}
public void testParsingOfGenericTypeSignature() {
runTest("parse generic type signature with parameterized type in interface");
}
public void testOverrideAndCovarianceWithDecPRuntime() {
runTest("override and covariance with decp - runtime");
}
public void testOverrideAndCovarianceWithDecPRuntimeMultiFiles() {
runTest("override and covariance with decp - runtime separate files");
}
public void testOverrideAndCovarianceWithDecPRuntimeMultiFilesBinaryWeaving() {
runTest("override and covariance with decp - binary weaving");
}
public void testAbstractSynchronizedITDMethods() {
runTest("abstract synchronized itdms not detected");
}
public void testSynchronizedITDInterfaceMethods() {
runTest("synchronized itd interface methods");
}
public void testNoWarningOnUnusedPointcut() {
runTest("unused private pointcuts");
}
public void testITDOnInterfaceWithExistingMember() {
runTest("itd interface method already existing on interface");
}
public void testFinalITDMOnInterface() {
runTest("final itd methods on interfaces");
}
public void testPrivatePointcutOverriding() {
runTest("can't override private pointcut in abstract aspect");
}
public void testAdviceOnCflow() {
runTest("advising cflow advice execution");
}
public void testNoTypeMismatchOnSameGenericTypes() {
runTest("no type mismatch on generic types in itds");
}
public void testSuperCallInITD() {
runTest("super call in ITD");
}
public void testSuperCallInITDPart2() {
runTest("super call in ITD - part 2");
}
public void testAtAnnotationBadTest_pr103740() {
runTest("Compiler failure on at_annotation");
}
public void testNoUnusedParameterWarningsForSyntheticAdviceArgs() {
runTest("no unused parameter warnings for synthetic advice args");
}
public void testNoVerifyErrorWithSetOnInnerType() {
runTest("no verify error with set on inner type");
}
public void testCantFindTypeErrorWithGenericReturnTypeOrParameter() {
runTest("cant find type error with generic return type or parameter");
}
public void testNoVerifyErrorOnGenericCollectionMemberAccess() {
runTest("no verify error on generic collection member access");
}
public void testRawAndGenericTypeConversionITDCons() {
runTest("raw and generic type conversion with itd cons");
}
public void testAtAnnotationBindingWithAround() {
runTest("@annotation binding with around advice");
}
public void testUnableToBuildShadows_pr109728() { runTest("Unable to build shadows");}
public void testMessageOnMissingTypeInDecP() {
runTest("declare parents on a missing type");
}
public void testParameterizedGenericMethods() {
runTest("parameterized generic methods");
}
public void testIllegalChangeToPointcutDeclaration_pr111915() {
runTest("test illegal change to pointcut declaration");
}
public void testCantProvideDefaultImplViaITD_pr110307_1() {runTest("Cant provide default implementation via ITD - 1");}
public void testCantProvideDefaultImplViaITD_pr110307_2() {runTest("Cant provide default implementation via ITD - 2");}
public void testCantProvideDefaultImplViaITD_pr110307_3() {runTest("Cant provide default implementation via ITD - 3");}
public void testCantProvideDefaultImplViaITD_pr110307_4() {runTest("Cant provide default implementation via ITD - 4");}
public void testCantProvideDefaultImplViaITD_pr110307_5() {runTest("Cant provide default implementation via ITD - 5");}
// Needs a change in the compiler so that getType() can be overridden in the intertype scope - thats
// where we can police whether a type variable has been used without being specified appropriately.
//public void testCantProvideDefaultImplViaITD_pr110307_6() {runTest("Cant provide default implementation via ITD - 6");}
public void testCantProvideDefaultImplViaITD_pr110307_7() {runTest("Cant provide default implementation via ITD - 7");}
public void testCallJoinPointsInAnonymousInnerClasses() {
runTest("call join points in anonymous inner classes");
}
public void testNoRequirementForUnwovenTypesToBeExposedToWeaver() {
runTest("default impl of Runnable");
}
public void testArrayCloneCallJoinPoints() {
runTest("array clone call join points in 1.4 vs 1.3");
}
public void testDebugInfoForAroundAdvice() {
runTest("debug info in around advice inlining");
}
public void testCCEWithGenericWildcard_pr112602() {
runTest("ClassCastException with generic wildcard");
}
public void testAdviceInStructureModelWithAnonymousInnerClass_pr77269() {
//AsmManager.setReporting("c:/debug.txt",true,true,true,true);
runTest("advice in structure model with anonymous inner class");
IHierarchy top = AsmManager.getDefault().getHierarchy();
// checking that the run() method inside anonymous inner class is in
// the structure model
IProgramElement anonRunMethodIPE = top.findElementForLabel(top.getRoot(),
IProgramElement.Kind.METHOD,"run()");
assertNotNull("Couldn't find 'run()' element in the tree",anonRunMethodIPE);
List l = AsmManager.getDefault().getRelationshipMap().get(anonRunMethodIPE);
assertNotNull("Should have some relationships but does not",l);
assertTrue("Should have one relationship but has " + l.size(),l.size()==1);
Relationship rel = (Relationship)l.get(0);
List targets = rel.getTargets();
assertTrue("Should have one target but has" + targets.size(),
targets.size()==1);
IProgramElement target = AsmManager.getDefault().getHierarchy().findElementForHandle((String)targets.get(0));
assertEquals("target of relationship should be 'before(): p..' but is "
+ target.toLabelString(),"before(): p..",target.toLabelString());
IProgramElement adviceIPE = top.findElementForLabel(top.getRoot(),
IProgramElement.Kind.ADVICE,"before(): p..");
assertNotNull("Couldn't find 'before(): p..' element in the tree",adviceIPE);
l = AsmManager.getDefault().getRelationshipMap().get(adviceIPE);
assertNotNull("Should have some relationships but does not",l);
assertTrue("Should have a relationship but does not ",l.size()>0);
for (Iterator iter = l.iterator(); iter.hasNext();) {
IRelationship element = (IRelationship) iter.next();
if (element.getName().equals("advises")) {
rel = (Relationship) element;
break;
}
}
targets = rel.getTargets();
assertTrue("Should have one target but has" + targets.size(),
targets.size()==1);
target = AsmManager.getDefault().getHierarchy().findElementForHandle((String)targets.get(0));
assertEquals("target of relationship should be 'run()' but is "
+ target.toLabelString(),"run()",target.toLabelString());
}
public void testAdviceInStructureModelWithNamedInnerClass_pr77269() {
//AsmManager.setReporting("c:/debug.txt",true,true,true,true);
runTest("advice in structure model with named inner class");
IHierarchy top = AsmManager.getDefault().getHierarchy();
// checking that the m() method inside named inner class is in
// the structure model
IProgramElement namedMethodIPE = top.findElementForLabel(top.getRoot(),
IProgramElement.Kind.METHOD,"m()");
assertNotNull("Couldn't find 'm()' element in the tree",namedMethodIPE);
List l = AsmManager.getDefault().getRelationshipMap().get(namedMethodIPE);
assertNotNull("Should have some relationships but does not",l);
assertTrue("Should have one relationship but has " + l.size(),l.size()==1);
Relationship rel = (Relationship)l.get(0);
List targets = rel.getTargets();
assertTrue("Should have one target but has" + targets.size(),
targets.size()==1);
IProgramElement target = AsmManager.getDefault().getHierarchy().findElementForHandle((String)targets.get(0));
assertEquals("target of relationship should be 'before(): p..' but is "
+ target.toLabelString(),"before(): p..",target.toLabelString());
IProgramElement adviceIPE = top.findElementForLabel(top.getRoot(),
IProgramElement.Kind.ADVICE,"before(): p..");
assertNotNull("Couldn't find 'before(): p..' element in the tree",adviceIPE);
l = AsmManager.getDefault().getRelationshipMap().get(adviceIPE);
assertNotNull("Should have some relationships but does not",l);
assertTrue("Should have a relationship but does not ",l.size()>0);
for (Iterator iter = l.iterator(); iter.hasNext();) {
IRelationship element = (IRelationship) iter.next();
if (element.getName().equals("advises")) {
rel = (Relationship) element;
break;
}
}
targets = rel.getTargets();
assertTrue("Should have one target but has" + targets.size(),
targets.size()==1);
target = AsmManager.getDefault().getHierarchy().findElementForHandle((String)targets.get(0));
assertEquals("target of relationship should be 'm()' but is "
+ target.toLabelString(),"m()",target.toLabelString());
}
public void testDWInStructureModelWithAnonymousInnerClass_pr77269() {
// AsmManager.setReporting("c:/debug.txt",true,true,true,true);
runTest("declare warning in structure model with anonymous inner class");
IHierarchy top = AsmManager.getDefault().getHierarchy();
IProgramElement pe = top.findElementForLabel(top.getRoot(),
IProgramElement.Kind.CODE,"method-call(void pack.Test.someMethod())");
assertNotNull("Couldn't find 'method-call(void pack.Test.someMethod())' element in the tree",pe);
}
public void testVarArgsIITDInConstructor() {
runTest("ITD varargs in constructor");
}
public void testWeaveInfoMessageForDeclareAtMethodOnITDdMethod() {
runTest("weaveinfo message for declare at method on an ITDd method");
}
public void testITDCWithNoExplicitConsCall() {
runTest("ITDC with no explicit cons call");
}
public void testJava5SpecificFeaturesUsedAtJava14OrLower() {
runTest("java 5 pointcuts and declares at pre-java 5 compliance levels");
}
public void testAnonymousTypes() {
runTest("Anonymous types and nome matching");
}
public void testAdviceExecutionJPToStringForms() {
runTest("adviceexecution join point toString forms");
}
public void testAssertWithinPointcutExpression() {
runTest("pointcut expression containing 'assert'");
}
public void testNoVerifyErrorWithTwoThisPCDs_pr113447() {
runTest("no verify error with two this pcds");
}
public void testNoVerifyErrorWithTwoAtThisPCDs_pr113447() {
runTest("no verify error with two at this pcds");
}
public void testNoVerifyErrorWithAtWithinPCDs_pr113447() {
runTest("no verify error with at within pcds");
}
public void testNoVerifyErrorWithAtWithincodePCDs_pr113447() {
runTest("no verify error with at withincode pcds");
}
public void testNoVerifyErrorWithAtAnnotationPCDs_pr113447() {
runTest("no verify error with at annotation pcds");
}
public void testNoVerifyErrorWithTwoArgsPCDs_pr113447() {
runTest("no verify error with two args pcds");
}
public void testNoStackOverflowWithCircularPCDInGenericAspect() {
runTest("no StackOverflowError with circular pcd in generic aspect");
}
public void testNoStackOverflowWithCircularPCDInGenericAspect2() {
runTest("no StackOverflowError with circular pcd in generic aspect - 2");
}
public void testNPEInThisJoinPointStaticPart() {
runTest("thisJoinPointStaticPart in if test");
}
public void testPointcutParsingOfCompiledPointcuts() {
runTest("pointcut parsing with ajc compiled pointcut references");
}
public void testReflectionOfAbstractITDs() {
runTest("reflection on abstract ITDs (Billing example)");
}
public void testDeclareSoftWithAdviceExecution() {
runTest("declare soft and adviceexecution");
}
public void testDeclareSoftWithExclusions() {
runTest("declare soft and exclusions");
}
public void testReturningObjectBinding() {
runTest("returning(Object) binding");
}
public void testPerTargetAndNegation() {
runTest("pertarget and negated pointcut");
}
public void testParameterizedPointcutAndAdvice() {
runTest("parameterized pointcut and advice");
}
public void testDoublyParameterizedAbstractType() {
runTest("double parameter generic abstract type");
}
public void testArgNamesInAdviceAnnotations() {
runTest("arg names in advice annotations");
}
/*
* Load-time weaving bugs
*/
public void testNPEinWeavingAdaptor_pr116626() { runTest("NPE in WeavingAdaptor");}
public void testXlintMessageForImproperAnnotationType_pr115252_Exact() {runTest("xlint message for improper exact annotation type");}
public void testXlintMessageForImproperAnnotationType_pr115252_OR() {runTest("xlint message for improper annotation type inside OR");}
public void testXlintMessageForImproperAnnotationType_pr115252_AND() {runTest("xlint message for improper annotation type inside AND");}
public void testXlintMessageForImproperAnnotationType_pr115252_Return() {runTest("xlint message for improper annotated return type");}
public void testXlintMessageForImproperAnnotationType_pr115252_Declaring() {runTest("xlint message for improper annotated declaring type");}
public void testXlintMessageForImproperAnnotationType_pr115252_Parameter() {runTest("xlint message for improper annotated parameter type");}
public void testXlintMessageForImproperAnnotationType_pr115252_Throws() {runTest("xlint message for improper annotated throws pattern");}
public void testXlintMessageForImproperAnnotationType_pr115252_MoreThanOne() {runTest("xlint message for more than one improper annotated parameter type");}
public void testDeclareAtTypeInStructureModel_pr115607() {
AsmManager.setReporting("c:/debug.txt",true,true,true,true);
runTest("declare at type appears correctly in structure model");
IHierarchy top = AsmManager.getDefault().getHierarchy();
IProgramElement pe = top.findElementForLabel(top.getRoot(),
IProgramElement.Kind.DECLARE_ANNOTATION_AT_TYPE,"declare @type: Simple : @I");
assertNotNull("Couldn't find 'declare @type: Simple : @I' element in the tree",pe);
List l = AsmManager.getDefault().getRelationshipMap().get(pe);
assertNotNull("Should have some relationships but does not",l);
}
// helper methods.....
public SyntheticRepository createRepos(File cpentry) {
ClassPath cp = new ClassPath(cpentry+File.pathSeparator+System.getProperty("java.class.path"));
return SyntheticRepository.getInstance(cp);
}
protected JavaClass getClassFrom(File where,String clazzname) throws ClassNotFoundException {
SyntheticRepository repos = createRepos(where);
return repos.loadClass(clazzname);
}
}
|
118,781 |
Bug 118781 [waiting-on-build]VerifyError in AspectJ
|
I'm fairly new to AspectJ, so this is probably not going to be well explained. I've started working on a project that was working fine. Then I added methods to classes that take a 2-dimensional string array parameter and suddenly I'm getting a VerifyError exception. java.lang.VerifyError: (class: com/drkw/cpds/obligor/facades/version_1_00/ObligorDetailFacade_1_00, method: searchForObligorSummariesByGroup_aroundBody24 signature: (Lcom/drkw/cpds/obligor/facades/version_1_00/ObligorDetailFacade_1_00;[[[Ljava/lang/String;Ljava/lang/String;LjavaA(‚ at com.drkw.cpds.obligor.facades.version_1_00.obligor.ObligorManager.<clinit>(ObligorManager.java:48) at com.drkw.cpds.obligor.integration.version_1_00.obligor.GetObligorDetailsGroupingTest.testGetObligorDetailsUsingGroups(GetObligorDetailsGroupingTest.java:45) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
|
resolved fixed
|
a75b7fa
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2005-12-01T15:00:22Z | 2005-12-01T09:40:00Z |
weaver/src/org/aspectj/weaver/World.java
|
/* *******************************************************************
* Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC).
* 2005 Contributors
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* PARC initial implementation
* Adrian Colyer, Andy Clement, overhaul for generics
* ******************************************************************/
package org.aspectj.weaver;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.WeakHashMap;
import org.aspectj.asm.IHierarchy;
import org.aspectj.bridge.IMessageHandler;
import org.aspectj.bridge.ISourceLocation;
import org.aspectj.bridge.Message;
import org.aspectj.bridge.MessageUtil;
import org.aspectj.bridge.IMessage.Kind;
import org.aspectj.bridge.context.PinpointingMessageHandler;
import org.aspectj.weaver.UnresolvedType.TypeKind;
import org.aspectj.weaver.patterns.DeclarePrecedence;
import org.aspectj.weaver.patterns.PerClause;
import org.aspectj.weaver.patterns.Pointcut;
/**
* A World is a collection of known types and crosscutting members.
*/
public abstract class World implements Dump.INode {
/** handler for any messages produced during resolution etc. */
private IMessageHandler messageHandler = IMessageHandler.SYSTEM_ERR;
/** handler for cross-reference information produced during the weaving process */
private ICrossReferenceHandler xrefHandler = null;
/** Currently 'active' scope in which to lookup (resolve) typevariable references */
private TypeVariableDeclaringElement typeVariableLookupScope;
/** The heart of the world, a map from type signatures to resolved types */
protected TypeMap typeMap = new TypeMap(); // Signature to ResolvedType
/** Calculator for working out aspect precedence */
private AspectPrecedenceCalculator precedenceCalculator;
/** All of the type and shadow mungers known to us */
private CrosscuttingMembersSet crosscuttingMembersSet =
new CrosscuttingMembersSet(this);
/** Model holds ASM relationships */
private IHierarchy model = null;
/** for processing Xlint messages */
private Lint lint = new Lint(this);
/** XnoInline option setting passed down to weaver */
private boolean XnoInline;
/** XlazyTjp option setting passed down to weaver */
private boolean XlazyTjp;
/** XhasMember option setting passed down to weaver */
private boolean XhasMember = false;
/** Xpinpoint controls whether we put out developer info showing the source of messages */
private boolean Xpinpoint = false;
/** When behaving in a Java 5 way autoboxing is considered */
private boolean behaveInJava5Way = false;
/** The level of the aspectjrt.jar the code we generate needs to run on */
private String targetAspectjRuntimeLevel = Constants.RUNTIME_LEVEL_DEFAULT;
/**
* A list of RuntimeExceptions containing full stack information for every
* type we couldn't find.
*/
private List dumpState_cantFindTypeExceptions = null;
/**
* Play God.
* On the first day, God created the primitive types and put them in the type
* map.
*/
protected World() {
super();
Dump.registerNode(this.getClass(),this);
typeMap.put("B", ResolvedType.BYTE);
typeMap.put("S", ResolvedType.SHORT);
typeMap.put("I", ResolvedType.INT);
typeMap.put("J", ResolvedType.LONG);
typeMap.put("F", ResolvedType.FLOAT);
typeMap.put("D", ResolvedType.DOUBLE);
typeMap.put("C", ResolvedType.CHAR);
typeMap.put("Z", ResolvedType.BOOLEAN);
typeMap.put("V", ResolvedType.VOID);
precedenceCalculator = new AspectPrecedenceCalculator(this);
}
/**
* Dump processing when a fatal error occurs
*/
public void accept (Dump.IVisitor visitor) {
visitor.visitString("Shadow mungers:");
visitor.visitList(crosscuttingMembersSet.getShadowMungers());
visitor.visitString("Type mungers:");
visitor.visitList(crosscuttingMembersSet.getTypeMungers());
visitor.visitString("Late Type mungers:");
visitor.visitList(crosscuttingMembersSet.getLateTypeMungers());
if (dumpState_cantFindTypeExceptions!=null) {
visitor.visitString("Cant find type problems:");
visitor.visitList(dumpState_cantFindTypeExceptions);
dumpState_cantFindTypeExceptions = null;
}
}
// =============================================================================
// T Y P E R E S O L U T I O N
// =============================================================================
/**
* Resolve a type that we require to be present in the world
*/
public ResolvedType resolve(UnresolvedType ty) {
return resolve(ty, false);
}
/**
* Attempt to resolve a type - the source location gives you some context in which
* resolution is taking place. In the case of an error where we can't find the
* type - we can then at least report why (source location) we were trying to resolve it.
*/
public ResolvedType resolve(UnresolvedType ty,ISourceLocation isl) {
ResolvedType ret = resolve(ty,true);
if (ty == ResolvedType.MISSING) {
//IMessage msg = null;
getLint().cantFindType.signal(WeaverMessages.format(WeaverMessages.CANT_FIND_TYPE,ty.getName()),isl);
//if (isl!=null) {
//msg = MessageUtil.error(WeaverMessages.format(WeaverMessages.CANT_FIND_TYPE,ty.getName()),isl);
//} else {
//msg = MessageUtil.error(WeaverMessages.format(WeaverMessages.CANT_FIND_TYPE,ty.getName()));
//}
//messageHandler.handleMessage(msg);
}
return ret;
}
/**
* Convenience method for resolving an array of unresolved types
* in one hit. Useful for e.g. resolving type parameters in signatures.
*/
public ResolvedType[] resolve(UnresolvedType[] types) {
if (types == null) return new ResolvedType[0];
ResolvedType[] ret = new ResolvedType[types.length];
for (int i=0; i<types.length; i++) {
ret[i] = resolve(types[i]);
}
return ret;
}
/**
* Resolve a type. This the hub of type resolution. The resolved type is added
* to the type map by signature.
*/
public ResolvedType resolve(UnresolvedType ty, boolean allowMissing) {
// special resolution processing for already resolved types.
if (ty instanceof ResolvedType) {
ResolvedType rty = (ResolvedType) ty;
rty = resolve(rty);
return rty;
}
// dispatch back to the type variable reference to resolve its constituent parts
// don't do this for other unresolved types otherwise you'll end up in a loop
if (ty.isTypeVariableReference()) {
return ty.resolve(this);
}
// if we've already got a resolved type for the signature, just return it
// after updating the world
String signature = ty.getSignature();
ResolvedType ret = typeMap.get(signature);
if (ret != null) {
ret.world = this; // Set the world for the RTX
return ret;
} else if ( signature.equals("?") || signature.equals("*")) {
// might be a problem here, not sure '?' should make it to here as a signature, the
// proper signature for wildcard '?' is '*'
// fault in generic wildcard, can't be done earlier because of init issues
ResolvedType something = new BoundedReferenceType("?",this);
typeMap.put("?",something);
return something;
}
// no existing resolved type, create one
if (ty.isArray()) {
ResolvedType componentType = resolve(ty.getComponentType(),allowMissing);
String brackets = signature.substring(0,signature.lastIndexOf("[")+1);
ret = new ResolvedType.Array(signature, brackets+componentType.getErasureSignature(),
this,
componentType);
} else {
ret = resolveToReferenceType(ty);
if (!allowMissing && ret == ResolvedType.MISSING) {
ret = handleRequiredMissingTypeDuringResolution(ty);
}
}
// Pulling in the type may have already put the right entry in the map
if (typeMap.get(signature)==null && ret != ResolvedType.MISSING) {
typeMap.put(signature, ret);
}
return ret;
}
/**
* We tried to resolve a type and couldn't find it...
*/
private ResolvedType handleRequiredMissingTypeDuringResolution(UnresolvedType ty) {
// defer the message until someone asks a question of the type that we can't answer
// just from the signature.
// MessageUtil.error(messageHandler,
// WeaverMessages.format(WeaverMessages.CANT_FIND_TYPE,ty.getName()));
if (dumpState_cantFindTypeExceptions==null) {
dumpState_cantFindTypeExceptions = new ArrayList();
}
dumpState_cantFindTypeExceptions.add(new RuntimeException("Can't find type "+ty.getName()));
return new MissingResolvedTypeWithKnownSignature(ty.getSignature(),this);
}
/**
* Some TypeFactory operations create resolved types directly, but these won't be
* in the typeMap - this resolution process puts them there. Resolved types are
* also told their world which is needed for the special autoboxing resolved types.
*/
public ResolvedType resolve(ResolvedType ty) {
if (ty.isTypeVariableReference()) return ty; // until type variables have proper sigs...
ResolvedType resolved = typeMap.get(ty.getSignature());
if (resolved == null) {
typeMap.put(ty.getSignature(), ty);
resolved = ty;
}
resolved.world = this;
return resolved;
}
/**
* Convenience method for finding a type by name and resolving it in one step.
*/
public ResolvedType resolve(String name) {
return resolve(UnresolvedType.forName(name));
}
public ResolvedType resolve(String name,boolean allowMissing) {
return resolve(UnresolvedType.forName(name),allowMissing);
}
private ResolvedType currentlyResolvingBaseType;
/**
* Resolve to a ReferenceType - simple, raw, parameterized, or generic.
* Raw, parameterized, and generic versions of a type share a delegate.
*/
private final ResolvedType resolveToReferenceType(UnresolvedType ty) {
if (ty.isParameterizedType()) {
// ======= parameterized types ================
ReferenceType genericType = (ReferenceType)resolveGenericTypeFor(ty,false);
currentlyResolvingBaseType = genericType;
ReferenceType parameterizedType =
TypeFactory.createParameterizedType(genericType, ty.typeParameters, this);
currentlyResolvingBaseType = null;
return parameterizedType;
} else if (ty.isGenericType()) {
// ======= generic types ======================
ReferenceType genericType = (ReferenceType)resolveGenericTypeFor(ty,false);
return genericType;
} else if (ty.isGenericWildcard()) {
// ======= generic wildcard types =============
return resolveGenericWildcardFor(ty);
} else {
// ======= simple and raw types ===============
String erasedSignature = ty.getErasureSignature();
ReferenceType simpleOrRawType = new ReferenceType(erasedSignature, this);
ReferenceTypeDelegate delegate = resolveDelegate(simpleOrRawType);
if (delegate == null) return ResolvedType.MISSING;
if (delegate.isGeneric() && behaveInJava5Way) {
// ======== raw type ===========
simpleOrRawType.typeKind = TypeKind.RAW;
ReferenceType genericType = makeGenericTypeFrom(delegate,simpleOrRawType);
// name = ReferenceType.fromTypeX(UnresolvedType.forRawTypeNames(ty.getName()),this);
simpleOrRawType.setDelegate(delegate);
genericType.setDelegate(delegate);
simpleOrRawType.setGenericType(genericType);
return simpleOrRawType;
} else {
// ======== simple type =========
simpleOrRawType.setDelegate(delegate);
return simpleOrRawType;
}
}
}
/**
* Attempt to resolve a type that should be a generic type.
*/
public ResolvedType resolveGenericTypeFor(UnresolvedType anUnresolvedType, boolean allowMissing) {
// Look up the raw type by signature
String rawSignature = anUnresolvedType.getRawType().getSignature();
ResolvedType rawType = (ResolvedType) typeMap.get(rawSignature);
if (rawType==null) {
rawType = resolve(UnresolvedType.forSignature(rawSignature),false);
typeMap.put(rawSignature,rawType);
}
// Does the raw type know its generic form? (It will if we created the
// raw type from a source type, it won't if its been created just through
// being referenced, e.g. java.util.List
ResolvedType genericType = rawType.getGenericType();
// There is a special case to consider here (testGenericsBang_pr95993 highlights it)
// You may have an unresolvedType for a parameterized type but it
// is backed by a simple type rather than a generic type. This occurs for
// inner types of generic types that inherit their enclosing types
// type variables.
if (rawType.isSimpleType() && (anUnresolvedType.typeParameters==null || anUnresolvedType.typeParameters.length==0)) {
rawType.world = this;
return rawType;
}
if (genericType != null) {
genericType.world = this;
return genericType;
} else {
// Fault in the generic that underpins the raw type ;)
ReferenceTypeDelegate delegate = resolveDelegate((ReferenceType)rawType);
ReferenceType genericRefType = makeGenericTypeFrom(delegate,((ReferenceType)rawType));
((ReferenceType)rawType).setGenericType(genericRefType);
genericRefType.setDelegate(delegate);
((ReferenceType)rawType).setDelegate(delegate);
return genericRefType;
}
}
private ReferenceType makeGenericTypeFrom(ReferenceTypeDelegate delegate, ReferenceType rawType) {
String genericSig = delegate.getDeclaredGenericSignature();
if (genericSig != null) {
return new ReferenceType(
UnresolvedType.forGenericTypeSignature(rawType.getSignature(),delegate.getDeclaredGenericSignature()),this);
} else {
return new ReferenceType(
UnresolvedType.forGenericTypeVariables(rawType.getSignature(), delegate.getTypeVariables()),this);
}
}
/**
* Go from an unresolved generic wildcard (represented by UnresolvedType) to a resolved version (BoundedReferenceType).
*/
private ReferenceType resolveGenericWildcardFor(UnresolvedType aType) {
BoundedReferenceType ret = null;
// FIXME asc doesnt take account of additional interface bounds (e.g. ? super R & Serializable - can you do that?)
if (aType.isExtends()) {
ReferenceType upperBound = (ReferenceType)resolve(aType.getUpperBound());
ret = new BoundedReferenceType(upperBound,true,this);
} else if (aType.isSuper()) {
ReferenceType lowerBound = (ReferenceType) resolve(aType.getLowerBound());
ret = new BoundedReferenceType(lowerBound,false,this);
} else {
// must be ? on its own!
}
return ret;
}
/**
* Find the ReferenceTypeDelegate behind this reference type so that it can
* fulfill its contract.
*/
protected abstract ReferenceTypeDelegate resolveDelegate(ReferenceType ty);
/**
* Special resolution for "core" types like OBJECT. These are resolved just like
* any other type, but if they are not found it is more serious and we issue an
* error message immediately.
*/
public ResolvedType getCoreType(UnresolvedType tx) {
ResolvedType coreTy = resolve(tx,true);
if (coreTy == ResolvedType.MISSING) {
MessageUtil.error(messageHandler,
WeaverMessages.format(WeaverMessages.CANT_FIND_CORE_TYPE,tx.getName()));
}
return coreTy;
}
/**
* Lookup a type by signature, if not found then build one and put it in the
* map.
*/
public ReferenceType lookupOrCreateName(UnresolvedType ty) {
String signature = ty.getSignature();
ReferenceType ret = lookupBySignature(signature);
if (ret == null) {
ret = ReferenceType.fromTypeX(ty, this);
typeMap.put(signature, ret);
}
return ret;
}
/**
* Lookup a reference type in the world by its signature. Returns
* null if not found.
*/
public ReferenceType lookupBySignature(String signature) {
return (ReferenceType) typeMap.get(signature);
}
// =============================================================================
// T Y P E R E S O L U T I O N -- E N D
// =============================================================================
/**
* Member resolution is achieved by resolving the declaring type and then
* looking up the member in the resolved declaring type.
*/
public ResolvedMember resolve(Member member) {
ResolvedType declaring = member.getDeclaringType().resolve(this);
if (declaring.isRawType()) declaring = declaring.getGenericType();
ResolvedMember ret;
if (member.getKind() == Member.FIELD) {
ret = declaring.lookupField(member);
} else {
ret = declaring.lookupMethod(member);
}
if (ret != null) return ret;
return declaring.lookupSyntheticMember(member);
}
// Methods for creating various cross-cutting members...
// ===========================================================
/**
* Create an advice shadow munger from the given advice attribute
*/
public abstract Advice createAdviceMunger(
AjAttribute.AdviceAttribute attribute,
Pointcut pointcut,
Member signature);
/**
* Create an advice shadow munger for the given advice kind
*/
public final Advice createAdviceMunger(
AdviceKind kind,
Pointcut p,
Member signature,
int extraParameterFlags,
IHasSourceLocation loc)
{
AjAttribute.AdviceAttribute attribute =
new AjAttribute.AdviceAttribute(kind, p, extraParameterFlags, loc.getStart(), loc.getEnd(), loc.getSourceContext());
return createAdviceMunger(attribute, p, signature);
}
public abstract ConcreteTypeMunger makeCflowStackFieldAdder(ResolvedMember cflowField);
public abstract ConcreteTypeMunger makeCflowCounterFieldAdder(ResolvedMember cflowField);
/**
* Register a munger for perclause @AJ aspect so that we add aspectOf(..) to them as needed
* @see org.aspectj.weaver.bcel.BcelWorld#makePerClauseAspect(ResolvedType, org.aspectj.weaver.patterns.PerClause.Kind)
*/
public abstract ConcreteTypeMunger makePerClauseAspect(ResolvedType aspect, PerClause.Kind kind);
public abstract ConcreteTypeMunger concreteTypeMunger(ResolvedTypeMunger munger, ResolvedType aspectType);
/**
* Same signature as org.aspectj.util.PartialOrder.PartialComparable.compareTo
*/
public int compareByPrecedence(ResolvedType aspect1, ResolvedType aspect2) {
return precedenceCalculator.compareByPrecedence(aspect1, aspect2);
}
public Integer getPrecedenceIfAny(ResolvedType aspect1, ResolvedType aspect2) {
return precedenceCalculator.getPrecedenceIfAny(aspect1, aspect2);
}
/**
* compares by precedence with the additional rule that a super-aspect is
* sorted before its sub-aspects
*/
public int compareByPrecedenceAndHierarchy(ResolvedType aspect1, ResolvedType aspect2) {
return precedenceCalculator.compareByPrecedenceAndHierarchy(aspect1, aspect2);
}
// simple property getter and setters
// ===========================================================
/**
* Nobody should hold onto a copy of this message handler, or setMessageHandler won't
* work right.
*/
public IMessageHandler getMessageHandler() {
return messageHandler;
}
public void setMessageHandler(IMessageHandler messageHandler) {
if (this.isInPinpointMode()) {
this.messageHandler = new PinpointingMessageHandler(messageHandler);
} else {
this.messageHandler = messageHandler;
}
}
/**
* convenenience method for creating and issuing messages via the message handler -
* if you supply two locations you will get two messages.
*/
public void showMessage(
Kind kind,
String message,
ISourceLocation loc1,
ISourceLocation loc2)
{
if (loc1 != null) {
messageHandler.handleMessage(new Message(message, kind, null, loc1));
if (loc2 != null) {
messageHandler.handleMessage(new Message(message, kind, null, loc2));
}
} else {
messageHandler.handleMessage(new Message(message, kind, null, loc2));
}
}
public void setCrossReferenceHandler(ICrossReferenceHandler xrefHandler) {
this.xrefHandler = xrefHandler;
}
/**
* Get the cross-reference handler for the world, may be null.
*/
public ICrossReferenceHandler getCrossReferenceHandler() {
return this.xrefHandler;
}
public void setTypeVariableLookupScope(TypeVariableDeclaringElement scope) {
this.typeVariableLookupScope = scope;
}
public TypeVariableDeclaringElement getTypeVariableLookupScope() {
return typeVariableLookupScope;
}
public List getDeclareParents() {
return crosscuttingMembersSet.getDeclareParents();
}
public List getDeclareAnnotationOnTypes() {
return crosscuttingMembersSet.getDeclareAnnotationOnTypes();
}
public List getDeclareAnnotationOnFields() {
return crosscuttingMembersSet.getDeclareAnnotationOnFields();
}
public List getDeclareAnnotationOnMethods() {
return crosscuttingMembersSet.getDeclareAnnotationOnMethods();
}
public List getDeclareSoft() {
return crosscuttingMembersSet.getDeclareSofts();
}
public CrosscuttingMembersSet getCrosscuttingMembersSet() {
return crosscuttingMembersSet;
}
public IHierarchy getModel() {
return model;
}
public void setModel(IHierarchy model) {
this.model = model;
}
public Lint getLint() {
return lint;
}
public void setLint(Lint lint) {
this.lint = lint;
}
public boolean isXnoInline() {
return XnoInline;
}
public void setXnoInline(boolean xnoInline) {
XnoInline = xnoInline;
}
public boolean isXlazyTjp() {
return XlazyTjp;
}
public void setXlazyTjp(boolean b) {
XlazyTjp = b;
}
public boolean isHasMemberSupportEnabled() {
return XhasMember;
}
public void setXHasMemberSupportEnabled(boolean b) {
XhasMember = b;
}
public boolean isInPinpointMode() {
return Xpinpoint;
}
public void setPinpointMode(boolean b) {
this.Xpinpoint = b;
}
public void setBehaveInJava5Way(boolean b) {
behaveInJava5Way = b;
}
public boolean isInJava5Mode() {
return behaveInJava5Way;
}
public void setTargetAspectjRuntimeLevel(String s) {
targetAspectjRuntimeLevel = s;
}
public String getTargetAspectjRuntimeLevel() {
return targetAspectjRuntimeLevel;
}
public boolean isTargettingAspectJRuntime12() {
return getTargetAspectjRuntimeLevel().equals(org.aspectj.weaver.Constants.RUNTIME_LEVEL_12);
}
/*
* Map of types in the world, with soft links to expendable ones.
* An expendable type is a reference type that is not exposed to the weaver (ie
* just pulled in for type resolution purposes).
*/
protected static class TypeMap {
/** Map of types that never get thrown away */
private Map tMap = new HashMap();
/** Map of types that may be ejected from the cache if we need space */
private Map expendableMap = new WeakHashMap();
private static final boolean debug = false;
/**
* Add a new type into the map, the key is the type signature.
* Some types do *not* go in the map, these are ones involving
* *member* type variables. The reason is that when all you have is the
* signature which gives you a type variable name, you cannot
* guarantee you are using the type variable in the same way
* as someone previously working with a similarly
* named type variable. So, these do not go into the map:
* - TypeVariableReferenceType.
* - ParameterizedType where a member type variable is involved.
* - BoundedReferenceType when one of the bounds is a type variable.
*
* definition: "member type variables" - a tvar declared on a generic
* method/ctor as opposed to those you see declared on a generic type.
*/
public ResolvedType put(String key, ResolvedType type) {
if (type.isParameterizedType() && type.isParameterizedWithAMemberTypeVariable()) {
if (debug)
System.err.println("Not putting a parameterized type that utilises member declared type variables into the typemap: key="+key+" type="+type);
return type;
}
if (type.isTypeVariableReference()) {
if (debug)
System.err.println("Not putting a type variable reference type into the typemap: key="+key+" type="+type);
return type;
}
// this test should be improved - only avoid putting them in if one of the
// bounds is a member type variable
if (type instanceof BoundedReferenceType) {
if (debug)
System.err.println("Not putting a bounded reference type into the typemap: key="+key+" type="+type);
return type;
}
if (type instanceof MissingResolvedTypeWithKnownSignature) {
if (debug)
System.err.println("Not putting a missing type into the typemap: key="+key+" type="+type);
return type;
}
if (isExpendable(type)) {
return (ResolvedType) expendableMap.put(key,type);
} else {
return (ResolvedType) tMap.put(key,type);
}
}
/** Lookup a type by its signature */
public ResolvedType get(String key) {
ResolvedType ret = (ResolvedType) tMap.get(key);
if (ret == null) ret = (ResolvedType) expendableMap.get(key);
return ret;
}
/** Remove a type from the map */
public ResolvedType remove(String key) {
ResolvedType ret = (ResolvedType) tMap.remove(key);
if (ret == null) ret = (ResolvedType) expendableMap.remove(key);
return ret;
}
/** Reference types we don't intend to weave may be ejected from
* the cache if we need the space.
*/
private boolean isExpendable(ResolvedType type) {
return (
(type != null) &&
(!type.isExposedToWeaver()) &&
(!type.isPrimitiveType())
);
}
public String toString() {
StringBuffer sb = new StringBuffer();
sb.append("types:\n");
sb.append(dumpthem(tMap));
sb.append("expendables:\n");
sb.append(dumpthem(expendableMap));
return sb.toString();
}
private String dumpthem(Map m) {
StringBuffer sb = new StringBuffer();
Set keys = m.keySet();
for (Iterator iter = keys.iterator(); iter.hasNext();) {
String k = (String) iter.next();
sb.append(k+"="+m.get(k)).append("\n");
}
return sb.toString();
}
}
/**
* This class is used to compute and store precedence relationships between
* aspects.
*/
private static class AspectPrecedenceCalculator {
private World world;
private Map cachedResults;
public AspectPrecedenceCalculator(World forSomeWorld) {
this.world = forSomeWorld;
this.cachedResults = new HashMap();
}
/**
* Ask every declare precedence in the world to order the two aspects.
* If more than one declare precedence gives an ordering, and the orderings
* conflict, then that's an error.
*/
public int compareByPrecedence(ResolvedType firstAspect, ResolvedType secondAspect) {
PrecedenceCacheKey key = new PrecedenceCacheKey(firstAspect,secondAspect);
if (cachedResults.containsKey(key)) {
return ((Integer) cachedResults.get(key)).intValue();
} else {
int order = 0;
DeclarePrecedence orderer = null; // Records the declare precedence statement that gives the first ordering
for (Iterator i = world.getCrosscuttingMembersSet().getDeclareDominates().iterator(); i.hasNext(); ) {
DeclarePrecedence d = (DeclarePrecedence)i.next();
int thisOrder = d.compare(firstAspect, secondAspect);
if (thisOrder != 0) {
if (orderer==null) orderer = d;
if (order != 0 && order != thisOrder) {
ISourceLocation[] isls = new ISourceLocation[2];
isls[0]=orderer.getSourceLocation();
isls[1]=d.getSourceLocation();
Message m =
new Message("conflicting declare precedence orderings for aspects: "+
firstAspect.getName()+" and "+secondAspect.getName(),null,true,isls);
world.getMessageHandler().handleMessage(m);
} else {
order = thisOrder;
}
}
}
cachedResults.put(key, new Integer(order));
return order;
}
}
public Integer getPrecedenceIfAny(ResolvedType aspect1,ResolvedType aspect2) {
return (Integer)cachedResults.get(new PrecedenceCacheKey(aspect1,aspect2));
}
public int compareByPrecedenceAndHierarchy(ResolvedType firstAspect, ResolvedType secondAspect) {
if (firstAspect.equals(secondAspect)) return 0;
int ret = compareByPrecedence(firstAspect, secondAspect);
if (ret != 0) return ret;
if (firstAspect.isAssignableFrom(secondAspect)) return -1;
else if (secondAspect.isAssignableFrom(firstAspect)) return +1;
return 0;
}
private static class PrecedenceCacheKey {
public ResolvedType aspect1;
public ResolvedType aspect2;
public PrecedenceCacheKey(ResolvedType a1, ResolvedType a2) {
this.aspect1 = a1;
this.aspect2 = a2;
}
public boolean equals(Object obj) {
if (!(obj instanceof PrecedenceCacheKey)) return false;
PrecedenceCacheKey other = (PrecedenceCacheKey) obj;
return (aspect1 == other.aspect1 && aspect2 == other.aspect2);
}
public int hashCode() {
return aspect1.hashCode() + aspect2.hashCode();
}
}
}
public void validateType(UnresolvedType type) { }
// --- with java5 we can get into a recursive mess if we aren't careful when resolving types (*cough* java.lang.Enum) ---
// --- this first map is for java15 delegates which may try and recursively access the same type variables.
// --- I would rather stash this against a reference type - but we don't guarantee referencetypes are unique for
// so we can't :(
private Map workInProgress1 = new HashMap();
public TypeVariable[] getTypeVariablesCurrentlyBeingProcessed(Class baseClass) {
return (TypeVariable[])workInProgress1.get(baseClass);
}
public void recordTypeVariablesCurrentlyBeingProcessed(Class baseClass, TypeVariable[] typeVariables) {
workInProgress1.put(baseClass,typeVariables);
}
public void forgetTypeVariablesCurrentlyBeingProcessed(Class baseClass) {
workInProgress1.remove(baseClass);
}
// ---
}
|
118,698 |
Bug 118698 Not Allowing Access to Private ITD inside Nested Type
|
AspectJ is failing to allow access to a private ITD field from a type nested inside the aspect, which is inconsistent with Java's access rules. Here is the source. See also the follow up patch to tests that integrates it into the ajc150 test suite. public aspect prUnknown { private static interface Marker {} private class Foo implements Marker { public Foo() { bar = null; // allowed listener = null; // should also be allowed this.listener = null; // so should this Marker.this.listener = null; // and this ((Marker)this).listener = null; // and this } } private Object Marker.listener; private Object bar; }
|
resolved fixed
|
6d94d09
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2005-12-02T11:06:37Z | 2005-11-30T19:46:40Z |
org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/compiler/lookup/InterTypeFieldBinding.java
|
/* *******************************************************************
* Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC).
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* PARC initial implementation
* ******************************************************************/
package org.aspectj.ajdt.internal.compiler.lookup;
import org.aspectj.weaver.AjcMemberMaker;
import org.aspectj.weaver.ResolvedTypeMunger;
import org.aspectj.weaver.UnresolvedType;
import org.aspectj.org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration;
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.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.SyntheticMethodBinding;
import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.TypeBinding;
public class InterTypeFieldBinding extends FieldBinding {
public ReferenceBinding targetType;
public SyntheticMethodBinding reader;
public SyntheticMethodBinding writer;
public AbstractMethodDeclaration sourceMethod;
public InterTypeFieldBinding(EclipseFactory world, ResolvedTypeMunger munger, UnresolvedType withinType,
AbstractMethodDeclaration sourceMethod)
{
super(world.makeFieldBinding(munger.getSignature(),munger.getTypeVariableAliases()), null);
this.sourceMethod = sourceMethod;
targetType = (ReferenceBinding)world.makeTypeBinding(munger.getSignature().getDeclaringType());
this.declaringClass = (ReferenceBinding)world.makeTypeBinding(withinType);
reader = new SimpleSyntheticAccessMethodBinding(
world.makeMethodBinding(
AjcMemberMaker.interFieldGetDispatcher(munger.getSignature(), withinType)
));
writer = new SimpleSyntheticAccessMethodBinding(world.makeMethodBinding(
AjcMemberMaker.interFieldSetDispatcher(munger.getSignature(), withinType)
));
}
public boolean canBeSeenBy(TypeBinding receiverType, InvocationSite invocationSite, Scope scope) {
scope.compilationUnitScope().recordTypeReference(declaringClass);
//System.err.println("canBeSeenBy: " + this + ", " + isPublic());
if (isPublic()) return true;
SourceTypeBinding invocationType = scope.invocationType();
//System.out.println("receiver: " + receiverType + ", " + invocationType);
ReferenceBinding declaringType = declaringClass;
// FIXME asc what about parameterized types and private ITD generic fields on interfaces?
// Don't work with a raw type, work with the generic type
if (declaringClass.isRawType())
declaringType = ((RawTypeBinding)declaringClass).type;
if (invocationType == declaringType) return true;
// if (invocationType.isPrivileged) {
// System.out.println("privileged access to: " + this);
// return true;
// }
if (isProtected()) {
throw new RuntimeException("unimplemented");
}
//XXX make sure this walks correctly
if (isPrivate()) {
// answer true if the receiverType is the declaringClass
// AND the invocationType and the declaringClass have a common enclosingType
if (receiverType != declaringType) return false;
if (invocationType != declaringType) {
ReferenceBinding outerInvocationType = invocationType;
ReferenceBinding temp = outerInvocationType.enclosingType();
while (temp != null) {
outerInvocationType = temp;
temp = temp.enclosingType();
}
ReferenceBinding outerDeclaringClass = declaringType;
temp = outerDeclaringClass.enclosingType();
while (temp != null) {
outerDeclaringClass = temp;
temp = temp.enclosingType();
}
if (outerInvocationType != outerDeclaringClass) return false;
}
return true;
}
// isDefault()
if (invocationType.fPackage == declaringClass.fPackage) return true;
return false;
}
public SyntheticMethodBinding getAccessMethod(boolean isReadAccess) {
if (isReadAccess) return reader;
else return writer;
}
public boolean alwaysNeedsAccessMethod(boolean isReadAccess) { return true; }
public ReferenceBinding getTargetType() {
return targetType;
}
// overrides ITD'd method in FieldBinding...
public ReferenceBinding getOwningClass() {
return targetType;
}
}
|
118,698 |
Bug 118698 Not Allowing Access to Private ITD inside Nested Type
|
AspectJ is failing to allow access to a private ITD field from a type nested inside the aspect, which is inconsistent with Java's access rules. Here is the source. See also the follow up patch to tests that integrates it into the ajc150 test suite. public aspect prUnknown { private static interface Marker {} private class Foo implements Marker { public Foo() { bar = null; // allowed listener = null; // should also be allowed this.listener = null; // so should this Marker.this.listener = null; // and this ((Marker)this).listener = null; // and this } } private Object Marker.listener; private Object bar; }
|
resolved fixed
|
6d94d09
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2005-12-02T11:06:37Z | 2005-11-30T19:46:40Z |
tests/src/org/aspectj/systemtest/ajc150/Ajc150Tests.java
|
/*******************************************************************************
* Copyright (c) 2004 IBM
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* Andy Clement - initial API and implementation
*******************************************************************************/
package org.aspectj.systemtest.ajc150;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.List;
import junit.framework.Test;
import org.aspectj.apache.bcel.classfile.JavaClass;
import org.aspectj.apache.bcel.classfile.Method;
import org.aspectj.apache.bcel.classfile.Signature;
import org.aspectj.apache.bcel.util.ClassPath;
import org.aspectj.apache.bcel.util.SyntheticRepository;
import org.aspectj.asm.AsmManager;
import org.aspectj.asm.IHierarchy;
import org.aspectj.asm.IProgramElement;
import org.aspectj.asm.IRelationship;
import org.aspectj.asm.internal.Relationship;
import org.aspectj.testing.XMLBasedAjcTestCase;
import org.aspectj.util.LangUtil;
public class Ajc150Tests extends org.aspectj.testing.XMLBasedAjcTestCase {
public static Test suite() {
return XMLBasedAjcTestCase.loadSuite(Ajc150Tests.class);
}
protected File getSpecFile() {
return new File("../tests/src/org/aspectj/systemtest/ajc150/ajc150.xml");
}
/*
public void testBrokenDispatchByITD_pr72834() { runTest("broken dispatch");}
public void testMissingAccessor_pr73856() { runTest("missing accessor");}
public void testCunningDeclareParents_pr92311() { runTest("cunning declare parents");}
public void testGenericITDsAndAbstractMethodError_pr102357() { runTest("generic itds and abstract method error");}
*/
public void testGeneratingCodeForAnOldRuntime_pr116679_1() { runTest("generating code for a 1.2.1 runtime - 1");}
public void testGeneratingCodeForAnOldRuntime_pr116679_2() { runTest("generating code for a 1.2.1 runtime - 2");}
public void testAmbiguousMethod_pr118599_1() { runTest("ambiguous method when binary weaving - 1");}
public void testAmbiguousMethod_pr118599_2() { runTest("ambiguous method when binary weaving - 2");}
public void testAroundAdviceArrayAdviceSigs_pr118781() { runTest("verify error with around advice array sigs");}
public void testAtDeclareParents_pr117681() { runTest("at declare parents");}
public void testPrivilegeProblem_pr87525() { runTest("privilege problem with switch");}
public void testGenericAspects_pr115237() { runTest("aspectOf and generic aspects");}
public void testClassFormatError_pr114436() { runTest("ClassFormatError binary weaving perthis");}
public void testParserException_pr115788() { runTest("parser exception");}
public void testPossibleStaticImports_pr113066_1() { runTest("possible static imports bug - 1");}
public void testPossibleStaticImports_pr113066_2() { runTest("possible static imports bug - 2");}
public void testPossibleStaticImports_pr113066_3() { runTest("possible static imports bug - 3");}
public void testITDCtor_pr112783() { runTest("Problem with constructor ITDs");}
public void testAnnotatedITDFs_pr114005_1() { runTest("Annotated ITDFs - 1");}
public void testAnnotatedITDFs_pr114005_2() { runTest("Annotated ITDFs - 2");}
public void testCantCallSuperMethods_pr90143() { runTest("cant call super methods");}
public void testBrokenDecp_pr112476() { runTest("binary weaving decp broken");}
public void testUnboundFormal_pr112027() { runTest("unexpected error unboundFormalInPC");}
public void testNPEScopeSetup_pr115038() { runTest("NPE in ensureScopeSetup");}
public void testCCEGenerics_pr113445() { runTest("Generics ClassCastException");}
public void testMatthewsAspect_pr113947_1() { runTest("maws generic aspect - 1");}
public void testMatthewsAspect_pr113947_2() { runTest("maws generic aspect - 2");}
public void testFieldGet_pr114343() { runTest("field-get, generics and around advice");}
public void testFieldGet_pr114343_2() { runTest("field-get, generics and around advice - 2");}
public void testFieldGet_pr114343_3() { runTest("field-get, generics and around advice - 3");}
public void testCaptureBinding_pr114744() { runTest("capturebinding wildcard problem");}
public void testBadDecp_pr110788_1() { runTest("bad generic decp - 1");}
public void testBadDecp_pr110788_2() { runTest("bad generic decp - 2");}
public void testBadDecp_pr110788_3() { runTest("bad generic decp - 3");}
public void testBadDecp_pr110788_4() { runTest("bad generic decp - 4");}
public void testVarargsITD_pr110906() { runTest("ITD varargs problem");}
public void testBadRenderer_pr86903() { runTest("bcelrenderer bad");}
// public void testIllegalInitialization_pr118326_1() { runTest("illegal initialization - 1");}
// public void testIllegalInitialization_pr118326_2() { runTest("illegal initialization - 2");}
public void testLintForAdviceSorting_pr111667() { runTest("lint for advice sorting");}
public void testIncompatibleClassChangeError_pr113630_1() {runTest("IncompatibleClassChangeError - errorscenario");}
public void testIncompatibleClassChangeError_pr113630_2() {runTest("IncompatibleClassChangeError - workingscenario");}
public void testFieldGetProblemWithGenericField_pr113861() {runTest("field-get problems with generic field");}
public void testDeclareAnnotationOnNonExistentType_pr99191_1() { runTest("declare annotation on non existent type - 1");}
public void testDeclareAnnotationOnNonExistentType_pr99191_2() { runTest("declare annotation on non existent type - 2");}
public void testDeclareAnnotationOnNonExistentType_pr99191_3() { runTest("declare annotation on non existent type - 3");}
public void testDeclareAnnotationOnNonExistentType_pr99191_4() { runTest("declare annotation on non existent type - 4");}
public void testDeclareAnnotationOnNonExistentType_pr99191_5() { runTest("declare annotation on non existent type - 5");}
public void testBadGenericSigAttribute_pr110927() {
runTest("cant create signature attribute");
Signature sig = GenericsTests.getClassSignature(ajc,"I");
if (sig==null) fail("Couldn't find signature attribute for type I");
String sigString = sig.getSignature();
if (!(sigString.equals("Ljava/lang/Object;LIE2;LIE1<Ljava/lang/String;>;") ||
sigString.equals("Ljava/lang/Object;LIE1<Ljava/lang/String;>;LIE2;"))) {
fail("Signature was "+sigString+" when should have been something like Ljava/lang/Object;LIE1<Ljava/lang/String;>;LIE2;");
}
}
public void test_typeProcessingOrderWhenDeclareParents() {
runTest("Order of types passed to compiler determines weaving behavior");
}
public void test_aroundMethod() {
runTest("method called around in class");
}
public void test_aroundMethodAspect() {
runTest("method called around in aspect");
}
public void test_ambiguousBindingsDetection() {
runTest("Various kinds of ambiguous bindings");
}
public void test_ambiguousArgsDetection() {
runTest("ambiguous args");
}
public void testIncorrectExceptionTableWhenBreakInMethod_pr78021() {
runTest("Injecting exception into while loop with break statement causes catch block to be ignored");
}
public void testIncorrectExceptionTableWhenReturnInMethod_pr79554() {
runTest("Return in try-block disables catch-block if final-block is present");
}
public void testMissingDebugInfoForGeneratedMethods_pr82570() throws ClassNotFoundException {
runTest("Weaved code does not include debug lines");
boolean f = false;
JavaClass jc = getClassFrom(ajc.getSandboxDirectory(),"PR82570_1");
Method[] meths = jc.getMethods();
for (int i = 0; i < meths.length; i++) {
Method method = meths[i];
if (f) System.err.println("Line number table for "+method.getName()+method.getSignature()+" = "+method.getLineNumberTable());
assertTrue("Didn't find a line number table for method "+method.getName()+method.getSignature(),
method.getLineNumberTable()!=null);
}
// This test would determine the info isn't there if you pass -g:none ...
// cR = ajc(baseDir,new String[]{"PR82570_1.java","-g:none"});
// assertTrue("Expected no compile problem:"+cR,!cR.hasErrorMessages());
// System.err.println(cR.getStandardError());
// jc = getClassFrom(ajc.getSandboxDirectory(),"PR82570_1");
// meths = jc.getMethods();
// for (int i = 0; i < meths.length; i++) {
// Method method = meths[i];
// assertTrue("Found a line number table for method "+method.getName(),
// method.getLineNumberTable()==null);
// }
}
public void testCanOverrideProtectedMethodsViaITDandDecp_pr83303() {
runTest("compiler error when mixing inheritance, overriding and polymorphism");
}
public void testPerTypeWithin_pr106554() {runTest("Problem in staticinitialization with pertypewithin aspect");}
public void testPerTypeWithinMissesNamedInnerTypes() {
runTest("pertypewithin() handing of inner classes (1)");
}
public void testPerTypeWithinMissesAnonymousInnerTypes() {
runTest("pertypewithin() handing of inner classes (2)");
}
public void testPerTypeWithinIncorrectlyMatchingInterfaces() {
runTest("pertypewithin({interface}) illegal field modifier");
}
public void test051_arrayCloningInJava5() {
runTest("AJC possible bug with static nested classes");
}
public void testBadASMforEnums() throws IOException {
runTest("bad asm for enums");
if (LangUtil.is15VMOrGreater()) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
PrintWriter pw = new PrintWriter(baos);
AsmManager.dumptree(pw,AsmManager.getDefault().getHierarchy().getRoot(),0);
pw.flush();
String tree = baos.toString();
assertTrue("Expected 'Red [enumvalue]' somewhere in here:"+tree,tree.indexOf("Red [enumvalue]")!=-1);
}
}
public void npeOnTypeNotFound() {
runTest("structure model npe on type not found");
}
public void testNoRuntimeExceptionSoftening() {
runTest("declare soft of runtime exception");
}
public void testRuntimeNoSoftenWithHandler() {
runTest("declare soft w. catch block");
}
public void testSyntaxError() {
runTest("invalid cons syntax");
}
public void testVarargsInConsBug() {
runTest("varargs in constructor sig");
}
public void testAspectpathdirs() {
runTest("dirs on aspectpath");
}
public void testIntroSample() {
runTest("introduction sample");
}
public void testPTWInterface() {
runTest("pertypewithin({interface}) illegal field modifier");
}
public void testEnumCalledEnumEtc() {
runTest("enum called Enum, annotation called Annotation, etc");
}
public void testInternalCompilerError_pr86832() {
runTest("Internal compiler error");
}
public void testCloneMethod_pr83311() {
runTest("overriding/polymorphism error on interface method introduction");
}
// IfPointcut.findResidueInternal() was modified to make this test complete in a short amount
// of time - if you see it hanging, someone has messed with the optimization.
public void testIfEvaluationExplosion_pr94086() {
runTest("Exploding compile time with if() statements in pointcut");
}
public void testReflectNPE_pr94167() {runTest("NPE in reflect implementation");}
public void testStaticImports_pr84260() {runTest("static import failures");}
public void testGenerics_pr99089() {runTest("ArrayIndexOutOfBoundsException - Generics in privileged aspects");}
public void testGenerics_pr95993() {runTest("NPE at ClassScope.java:660 when compiling generic class");}
public void testItdGenerics_pr99228() {runTest("ITD of a field into a generic class");}
public void testItdGenerics_pr98320() {runTest("intertype with nested generic type");}
public void testItdGenerics_pr100227() {runTest("inner class with generic enclosing class");}
public void testItdGenerics_pr100260() {runTest("methods inherited from a generic parent");}
public void testSyntaxErrorNPE_pr103266() {runTest("NPE on syntax error");}
public void testFinalAbstractClass_pr109486() { runTest("Internal compiler error (ClassParser.java:242)");}
public void testComplexBinding_pr102210() { runTest("NullPointerException trying to compile");}
public void testIllegalStateExceptionOnNestedParameterizedType_pr106634() {
runTest("IllegalStateException unpacking signature of nested parameterized type");
}
public void testParseErrorOnAnnotationStarPlusPattern() {
runTest("(@Foo *)+ type pattern parse error");
}
public void test_pr106130_tooManyLocals() {
runTest("test weaving with > 256 locals");
}
public void testMissingNamePattern_pr106461() { runTest("missing name pattern"); }
public void testMissingNamePattern_pr107059() {
runTest("parser crashes on call(void (@a *)(..)");
}
public void testIntermediateAnnotationMatching() {
runTest("intermediate annotation matching");
}
public void testBadRuntimeTestGeneration() {
runTest("target(@Foo *)");
}
public void testErrorMessageOnITDWithTypePatterns() {
runTest("clear error message on itd with type pattern");
}
public void testAjKeywordsAsIdentifiers() {
runTest("before and after are valid identifiers in classes");
}
public void testAjKeywordsAsIdentifiers2() {
runTest("before and after are valid identifiers in classes, part 2");
}
public void testNoBeforeReturningAdvice() {
runTest("before returning advice not allowed!");
}
public void testDetectVoidFieldType() {
runTest("void field type in pointcut expression");
}
public void testPointcutOverriding() {
runTest("overriding final pointcut from super-aspect");
}
public void testAtSuppressWarnings() {
runTest("@SuppressWarnings should suppress");
}
public void testDEOWWithBindingPointcut() {
runTest("declare warning : foo(str) : ...;");
}
public void testAroundAdviceAndInterfaceInitializer() {
runTest("around advice on interface initializer");
}
public void testGoodErrorMessageOnUnmatchedMemberSyntax() {
runTest("good error message for unmatched member syntax");
}
public void testITDWithNoExceptionAndIntermediary() {
runTest("itd override with no exception clause");
}
public void testAnonymousInnerClasses() {
runTest("anonymous inner classes");
}
public void testMultipleAnonymousInnerClasses() {
runTest("multiple anonymous inner classes");
}
public void testPrivilegedMethodAccessorsGetRightExceptions_pr82989() {
runTest("Compiler error due to a wrong exception check in try blocks");
}
public void testAnonymousInnerClassWithMethodReturningTypeParameter_pr107898() {
runTest("anonymous inner class with method returning type parameter");
}
public void testMatchingOfObjectArray() {
runTest("matching against Object[]");
}
public void testMultipleAnonymousInnerClasses_pr108104() {
runTest("multiple anonymous inner classes 2");
}
public void testSignatureMatchingInMultipleOverrideScenario() {
runTest("signature matching in override scenario");
}
public void testWildcardAnnotationMatching_pr108245() {
runTest("wildcard annotation matching - pr108245");
}
public void testInnerTypesAndTypeVariables() {
runTest("inner types and type variables");
}
public void testAtAfterThrowingWithNoFormal() {
runTest("@AfterThrowing with no formal specified");
}
public void testParameterizedVarArgsMatch() {
runTest("varargs with type variable");
}
public void testFieldAccessInsideITDM() {
runTest("itd field access inside itd method");
}
public void testTypeVarWithTypeVarBound() {
runTest("type variable with type variable bound");
}
public void testEnumSwitchInITD() {
runTest("switch on enum inside ITD method");
}
public void testInnerTypeOfGeneric() {
runTest("inner type of generic interface reference from parameterized type");
}
public void testDeclareParentsIntroducingCovariantReturnType() {
runTest("declare parents introducing override with covariance");
}
public void testInnerClassPassedToVarargs() {
runTest("inner class passed as argument to varargs method");
}
public void testInlinedFieldAccessInProceedCall() {
runTest("inlined field access in proceed call");
}
public void testVisibiltyInSignatureMatchingWithOverridesPart1() {
runTest("visibility in signature matching with overrides - 1");
}
public void testVisibiltyInSignatureMatchingWithOverridesPart2() {
runTest("visibility in signature matching with overrides - 2");
}
public void testVisibiltyInSignatureMatchingWithOverridesPart3() {
runTest("visibility in signature matching with overrides - 3");
}
public void testArgsGeneratedCorrectlyForAdviceExecution() {
runTest("args generated correctly for advice execution join point");
}
public void testNoUnusedWarningsOnAspectTypes() {
runTest("no unused warnings on aspect types");
}
public void testSyntheticArgumentsOnITDConstructorsNotUsedInMatching() {
runTest("synthetic arguments on itd cons are not used in matching");
}
public void testParsingOfGenericTypeSignature() {
runTest("parse generic type signature with parameterized type in interface");
}
public void testOverrideAndCovarianceWithDecPRuntime() {
runTest("override and covariance with decp - runtime");
}
public void testOverrideAndCovarianceWithDecPRuntimeMultiFiles() {
runTest("override and covariance with decp - runtime separate files");
}
public void testOverrideAndCovarianceWithDecPRuntimeMultiFilesBinaryWeaving() {
runTest("override and covariance with decp - binary weaving");
}
public void testAbstractSynchronizedITDMethods() {
runTest("abstract synchronized itdms not detected");
}
public void testSynchronizedITDInterfaceMethods() {
runTest("synchronized itd interface methods");
}
public void testNoWarningOnUnusedPointcut() {
runTest("unused private pointcuts");
}
public void testITDOnInterfaceWithExistingMember() {
runTest("itd interface method already existing on interface");
}
public void testFinalITDMOnInterface() {
runTest("final itd methods on interfaces");
}
public void testPrivatePointcutOverriding() {
runTest("can't override private pointcut in abstract aspect");
}
public void testAdviceOnCflow() {
runTest("advising cflow advice execution");
}
public void testNoTypeMismatchOnSameGenericTypes() {
runTest("no type mismatch on generic types in itds");
}
public void testSuperCallInITD() {
runTest("super call in ITD");
}
public void testSuperCallInITDPart2() {
runTest("super call in ITD - part 2");
}
public void testAtAnnotationBadTest_pr103740() {
runTest("Compiler failure on at_annotation");
}
public void testNoUnusedParameterWarningsForSyntheticAdviceArgs() {
runTest("no unused parameter warnings for synthetic advice args");
}
public void testNoVerifyErrorWithSetOnInnerType() {
runTest("no verify error with set on inner type");
}
public void testCantFindTypeErrorWithGenericReturnTypeOrParameter() {
runTest("cant find type error with generic return type or parameter");
}
public void testNoVerifyErrorOnGenericCollectionMemberAccess() {
runTest("no verify error on generic collection member access");
}
public void testRawAndGenericTypeConversionITDCons() {
runTest("raw and generic type conversion with itd cons");
}
public void testAtAnnotationBindingWithAround() {
runTest("@annotation binding with around advice");
}
public void testUnableToBuildShadows_pr109728() { runTest("Unable to build shadows");}
public void testMessageOnMissingTypeInDecP() {
runTest("declare parents on a missing type");
}
public void testParameterizedGenericMethods() {
runTest("parameterized generic methods");
}
public void testIllegalChangeToPointcutDeclaration_pr111915() {
runTest("test illegal change to pointcut declaration");
}
public void testCantProvideDefaultImplViaITD_pr110307_1() {runTest("Cant provide default implementation via ITD - 1");}
public void testCantProvideDefaultImplViaITD_pr110307_2() {runTest("Cant provide default implementation via ITD - 2");}
public void testCantProvideDefaultImplViaITD_pr110307_3() {runTest("Cant provide default implementation via ITD - 3");}
public void testCantProvideDefaultImplViaITD_pr110307_4() {runTest("Cant provide default implementation via ITD - 4");}
public void testCantProvideDefaultImplViaITD_pr110307_5() {runTest("Cant provide default implementation via ITD - 5");}
// Needs a change in the compiler so that getType() can be overridden in the intertype scope - thats
// where we can police whether a type variable has been used without being specified appropriately.
//public void testCantProvideDefaultImplViaITD_pr110307_6() {runTest("Cant provide default implementation via ITD - 6");}
public void testCantProvideDefaultImplViaITD_pr110307_7() {runTest("Cant provide default implementation via ITD - 7");}
public void testCallJoinPointsInAnonymousInnerClasses() {
runTest("call join points in anonymous inner classes");
}
public void testNoRequirementForUnwovenTypesToBeExposedToWeaver() {
runTest("default impl of Runnable");
}
public void testArrayCloneCallJoinPoints() {
runTest("array clone call join points in 1.4 vs 1.3");
}
public void testDebugInfoForAroundAdvice() {
runTest("debug info in around advice inlining");
}
public void testCCEWithGenericWildcard_pr112602() {
runTest("ClassCastException with generic wildcard");
}
public void testAdviceInStructureModelWithAnonymousInnerClass_pr77269() {
//AsmManager.setReporting("c:/debug.txt",true,true,true,true);
runTest("advice in structure model with anonymous inner class");
IHierarchy top = AsmManager.getDefault().getHierarchy();
// checking that the run() method inside anonymous inner class is in
// the structure model
IProgramElement anonRunMethodIPE = top.findElementForLabel(top.getRoot(),
IProgramElement.Kind.METHOD,"run()");
assertNotNull("Couldn't find 'run()' element in the tree",anonRunMethodIPE);
List l = AsmManager.getDefault().getRelationshipMap().get(anonRunMethodIPE);
assertNotNull("Should have some relationships but does not",l);
assertTrue("Should have one relationship but has " + l.size(),l.size()==1);
Relationship rel = (Relationship)l.get(0);
List targets = rel.getTargets();
assertTrue("Should have one target but has" + targets.size(),
targets.size()==1);
IProgramElement target = AsmManager.getDefault().getHierarchy().findElementForHandle((String)targets.get(0));
assertEquals("target of relationship should be 'before(): p..' but is "
+ target.toLabelString(),"before(): p..",target.toLabelString());
IProgramElement adviceIPE = top.findElementForLabel(top.getRoot(),
IProgramElement.Kind.ADVICE,"before(): p..");
assertNotNull("Couldn't find 'before(): p..' element in the tree",adviceIPE);
l = AsmManager.getDefault().getRelationshipMap().get(adviceIPE);
assertNotNull("Should have some relationships but does not",l);
assertTrue("Should have a relationship but does not ",l.size()>0);
for (Iterator iter = l.iterator(); iter.hasNext();) {
IRelationship element = (IRelationship) iter.next();
if (element.getName().equals("advises")) {
rel = (Relationship) element;
break;
}
}
targets = rel.getTargets();
assertTrue("Should have one target but has" + targets.size(),
targets.size()==1);
target = AsmManager.getDefault().getHierarchy().findElementForHandle((String)targets.get(0));
assertEquals("target of relationship should be 'run()' but is "
+ target.toLabelString(),"run()",target.toLabelString());
}
public void testAdviceInStructureModelWithNamedInnerClass_pr77269() {
//AsmManager.setReporting("c:/debug.txt",true,true,true,true);
runTest("advice in structure model with named inner class");
IHierarchy top = AsmManager.getDefault().getHierarchy();
// checking that the m() method inside named inner class is in
// the structure model
IProgramElement namedMethodIPE = top.findElementForLabel(top.getRoot(),
IProgramElement.Kind.METHOD,"m()");
assertNotNull("Couldn't find 'm()' element in the tree",namedMethodIPE);
List l = AsmManager.getDefault().getRelationshipMap().get(namedMethodIPE);
assertNotNull("Should have some relationships but does not",l);
assertTrue("Should have one relationship but has " + l.size(),l.size()==1);
Relationship rel = (Relationship)l.get(0);
List targets = rel.getTargets();
assertTrue("Should have one target but has" + targets.size(),
targets.size()==1);
IProgramElement target = AsmManager.getDefault().getHierarchy().findElementForHandle((String)targets.get(0));
assertEquals("target of relationship should be 'before(): p..' but is "
+ target.toLabelString(),"before(): p..",target.toLabelString());
IProgramElement adviceIPE = top.findElementForLabel(top.getRoot(),
IProgramElement.Kind.ADVICE,"before(): p..");
assertNotNull("Couldn't find 'before(): p..' element in the tree",adviceIPE);
l = AsmManager.getDefault().getRelationshipMap().get(adviceIPE);
assertNotNull("Should have some relationships but does not",l);
assertTrue("Should have a relationship but does not ",l.size()>0);
for (Iterator iter = l.iterator(); iter.hasNext();) {
IRelationship element = (IRelationship) iter.next();
if (element.getName().equals("advises")) {
rel = (Relationship) element;
break;
}
}
targets = rel.getTargets();
assertTrue("Should have one target but has" + targets.size(),
targets.size()==1);
target = AsmManager.getDefault().getHierarchy().findElementForHandle((String)targets.get(0));
assertEquals("target of relationship should be 'm()' but is "
+ target.toLabelString(),"m()",target.toLabelString());
}
public void testDWInStructureModelWithAnonymousInnerClass_pr77269() {
// AsmManager.setReporting("c:/debug.txt",true,true,true,true);
runTest("declare warning in structure model with anonymous inner class");
IHierarchy top = AsmManager.getDefault().getHierarchy();
IProgramElement pe = top.findElementForLabel(top.getRoot(),
IProgramElement.Kind.CODE,"method-call(void pack.Test.someMethod())");
assertNotNull("Couldn't find 'method-call(void pack.Test.someMethod())' element in the tree",pe);
}
public void testVarArgsIITDInConstructor() {
runTest("ITD varargs in constructor");
}
public void testWeaveInfoMessageForDeclareAtMethodOnITDdMethod() {
runTest("weaveinfo message for declare at method on an ITDd method");
}
public void testITDCWithNoExplicitConsCall() {
runTest("ITDC with no explicit cons call");
}
public void testJava5SpecificFeaturesUsedAtJava14OrLower() {
runTest("java 5 pointcuts and declares at pre-java 5 compliance levels");
}
public void testAnonymousTypes() {
runTest("Anonymous types and nome matching");
}
public void testAdviceExecutionJPToStringForms() {
runTest("adviceexecution join point toString forms");
}
public void testAssertWithinPointcutExpression() {
runTest("pointcut expression containing 'assert'");
}
public void testNoVerifyErrorWithTwoThisPCDs_pr113447() {
runTest("no verify error with two this pcds");
}
public void testNoVerifyErrorWithTwoAtThisPCDs_pr113447() {
runTest("no verify error with two at this pcds");
}
public void testNoVerifyErrorWithAtWithinPCDs_pr113447() {
runTest("no verify error with at within pcds");
}
public void testNoVerifyErrorWithAtWithincodePCDs_pr113447() {
runTest("no verify error with at withincode pcds");
}
public void testNoVerifyErrorWithAtAnnotationPCDs_pr113447() {
runTest("no verify error with at annotation pcds");
}
public void testNoVerifyErrorWithTwoArgsPCDs_pr113447() {
runTest("no verify error with two args pcds");
}
public void testNoStackOverflowWithCircularPCDInGenericAspect() {
runTest("no StackOverflowError with circular pcd in generic aspect");
}
public void testNoStackOverflowWithCircularPCDInGenericAspect2() {
runTest("no StackOverflowError with circular pcd in generic aspect - 2");
}
public void testNPEInThisJoinPointStaticPart() {
runTest("thisJoinPointStaticPart in if test");
}
public void testPointcutParsingOfCompiledPointcuts() {
runTest("pointcut parsing with ajc compiled pointcut references");
}
public void testReflectionOfAbstractITDs() {
runTest("reflection on abstract ITDs (Billing example)");
}
public void testDeclareSoftWithAdviceExecution() {
runTest("declare soft and adviceexecution");
}
public void testDeclareSoftWithExclusions() {
runTest("declare soft and exclusions");
}
public void testReturningObjectBinding() {
runTest("returning(Object) binding");
}
public void testPerTargetAndNegation() {
runTest("pertarget and negated pointcut");
}
public void testParameterizedPointcutAndAdvice() {
runTest("parameterized pointcut and advice");
}
public void testDoublyParameterizedAbstractType() {
runTest("double parameter generic abstract type");
}
public void testArgNamesInAdviceAnnotations() {
runTest("arg names in advice annotations");
}
/*
* Load-time weaving bugs
*/
public void testNPEinWeavingAdaptor_pr116626() { runTest("NPE in WeavingAdaptor");}
public void testXlintMessageForImproperAnnotationType_pr115252_Exact() {runTest("xlint message for improper exact annotation type");}
public void testXlintMessageForImproperAnnotationType_pr115252_OR() {runTest("xlint message for improper annotation type inside OR");}
public void testXlintMessageForImproperAnnotationType_pr115252_AND() {runTest("xlint message for improper annotation type inside AND");}
public void testXlintMessageForImproperAnnotationType_pr115252_Return() {runTest("xlint message for improper annotated return type");}
public void testXlintMessageForImproperAnnotationType_pr115252_Declaring() {runTest("xlint message for improper annotated declaring type");}
public void testXlintMessageForImproperAnnotationType_pr115252_Parameter() {runTest("xlint message for improper annotated parameter type");}
public void testXlintMessageForImproperAnnotationType_pr115252_Throws() {runTest("xlint message for improper annotated throws pattern");}
public void testXlintMessageForImproperAnnotationType_pr115252_MoreThanOne() {runTest("xlint message for more than one improper annotated parameter type");}
public void testDeclareAtTypeInStructureModel_pr115607() {
AsmManager.setReporting("c:/debug.txt",true,true,true,true);
runTest("declare at type appears correctly in structure model");
IHierarchy top = AsmManager.getDefault().getHierarchy();
IProgramElement pe = top.findElementForLabel(top.getRoot(),
IProgramElement.Kind.DECLARE_ANNOTATION_AT_TYPE,"declare @type: Simple : @I");
assertNotNull("Couldn't find 'declare @type: Simple : @I' element in the tree",pe);
List l = AsmManager.getDefault().getRelationshipMap().get(pe);
assertNotNull("Should have some relationships but does not",l);
}
// helper methods.....
public SyntheticRepository createRepos(File cpentry) {
ClassPath cp = new ClassPath(cpentry+File.pathSeparator+System.getProperty("java.class.path"));
return SyntheticRepository.getInstance(cp);
}
protected JavaClass getClassFrom(File where,String clazzname) throws ClassNotFoundException {
SyntheticRepository repos = createRepos(where);
return repos.loadClass(clazzname);
}
}
|
118,149 |
Bug 118149 AspectJ compiler crahses possibly due to poincut context binding issue
|
I am using the latest version of AJDT (1.3.0.20051125115230). The reason is not entirely clear, but I have a pointcut of form public pointcut realPC(Common entity) : pc1(entity) || pc2(entity); Just a few hours back, I used to get an error regarding incompatible binding of entity in the || poincut. When I got that error, Eclipse was frozen to the point that clicking "Details" on exception report made Eclipse hang and had to kill it using the task manager. So I modified the program to avoid || expression in pointcut, after unsuccessfully trying various ways to express the pointcut. It was an ugly thing to do, since I essentially had to duplicate the advice for both pointcuts. Anyway... Then I tried to reproduce on a smaller project to provide a minimal program to reproduced the bug. However, it worked just fine on that project (and I couldn't see any material difference in the pointcuts or the classes involved). Encouraged by this, I retried the or-ed version of the pointcut on the real project. This time, I get the crash and can acccess the stack trace. java.lang.NullPointerException at org.aspectj.weaver.ast.Test.makeInstanceof(Test.java:78) at org.aspectj.weaver.patterns.IfPointcut.findResidueInternal(IfPointcut.java:181) at org.aspectj.weaver.patterns.Pointcut.findResidue(Pointcut.java:267) at org.aspectj.weaver.patterns.AndPointcut.findResidueInternal(AndPointcut.java:97) at org.aspectj.weaver.patterns.Pointcut.findResidue(Pointcut.java:267) at org.aspectj.weaver.patterns.AndPointcut.findResidueInternal(AndPointcut.java:97) at org.aspectj.weaver.patterns.Pointcut.findResidue(Pointcut.java:267) at org.aspectj.weaver.patterns.OrPointcut.findResidueInternal(OrPointcut.java:99) at org.aspectj.weaver.patterns.Pointcut.findResidue(Pointcut.java:267) at org.aspectj.weaver.patterns.OrPointcut.findResidueInternal(OrPointcut.java:99) at org.aspectj.weaver.patterns.Pointcut.findResidue(Pointcut.java:267) at org.aspectj.weaver.bcel.BcelAdvice.specializeOn(BcelAdvice.java:133) at org.aspectj.weaver.bcel.BcelShadow.prepareForMungers(BcelShadow.java:308) at org.aspectj.weaver.Shadow.implement(Shadow.java:404) at org.aspectj.weaver.bcel.BcelClassWeaver.implement(BcelClassWeaver.java:2146) at org.aspectj.weaver.bcel.BcelClassWeaver.weave(BcelClassWeaver.java:467) at org.aspectj.weaver.bcel.BcelClassWeaver.weave(BcelClassWeaver.java:102) at org.aspectj.weaver.bcel.BcelWeaver.weave(BcelWeaver.java:1534) at org.aspectj.weaver.bcel.BcelWeaver.weaveWithoutDump(BcelWeaver.java:1485) at org.aspectj.weaver.bcel.BcelWeaver.weaveAndNotify(BcelWeaver.java:1266) at org.aspectj.weaver.bcel.BcelWeaver.weave(BcelWeaver.java:1088) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.weave(AjCompilerAdapter.java:300) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.afterCompiling(AjCompilerAdapter.java:178) at org.aspectj.ajdt.internal.compiler.CompilerAdapter.ajc$afterReturning$org_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:809) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.doBuild(AjBuildManager.java:230) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.batchBuild(AjBuildManager.java:156) at org.aspectj.ajde.internal.CompilerAdapter.compile(CompilerAdapter.java:122) at org.aspectj.ajde.internal.AspectJBuildManager$CompilerThread.run(AspectJBuildManager.java:191) trouble in: public abstract class com.aspectivity.mgmt.web.entity.ManageEntity extends com.aspectivity.mgmt.web.TemplatePage: public void <init>(com.aspectivity.mgmt.model.Entity, boolean, String, String, String, String, String) org.aspectj.weaver.MethodDeclarationLineNumber: 19:557 : ALOAD_0 // com.aspectivity.mgmt.web.entity.ManageEntity this (line 19) INVOKESPECIAL com.aspectivity.mgmt.web.TemplatePage.<init> ()V ALOAD_1 ASTORE 9 ILOAD_2 ISTORE 10 ALOAD_3 ASTORE 11 ALOAD 4 ASTORE 12 ALOAD 5 ASTORE 13 ALOAD 6 ASTORE 14 ALOAD 7 ASTORE 15 constructor-execution(void com.aspectivity.mgmt.web.entity.ManageEntity.<init>(com.aspectivity.mgmt.model.Entity, boolean, java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String)) | ALOAD_0 // com.aspectivity.mgmt.web.entity.ManageEntity this (line 23) | ALOAD_3 // java.lang.String pageTitle | INVOKEVIRTUAL com.aspectivity.mgmt.web.entity.ManageEntity.setPageTitle (Ljava/lang/String;)V | ALOAD_0 // com.aspectivity.mgmt.web.entity.ManageEntity this (line 25) | ALOAD_0 // com.aspectivity.mgmt.web.entity.ManageEntity this | ALOAD_1 // com.aspectivity.mgmt.model.Entity entity | ALOAD 5 // java.lang.String addEntityLinkText | INVOKEVIRTUAL com.aspectivity.mgmt.web.entity.ManageEntity.getEntitiesListView (Lcom/aspectivity/mgmt/model/Entity;Ljava/lang/String;)Lwicket/markup/html/list/ListView; | INVOKEVIRTUAL com.aspectivity.mgmt.web.entity.ManageEntity.add (Lwicket/Component;)Lwicket/MarkupContainer; | POP | ALOAD_0 // com.aspectivity.mgmt.web.entity.ManageEntity this (line 27) | LDC "addEntityLink" | ACONST_NULL | INVOKEVIRTUAL com.aspectivity.mgmt.web.entity.ManageEntity.getEditLink (Ljava/lang/String;Lcom/aspectivity/mgmt/model/Entity;)Lwicket/markup/html/link/Link; | ASTORE 8 | ALOAD_0 // com.aspectivity.mgmt.web.entity.ManageEntity this (line 28) | ALOAD 8 // wicket.markup.html.link.Link addEntityLink | INVOKEVIRTUAL com.aspectivity.mgmt.web.entity.ManageEntity.add (Lwicket/Component;)Lwicket/MarkupContainer; | POP | ALOAD 8 // wicket.markup.html.link.Link addEntityLink (line 29) | NEW wicket.markup.html.basic.Label | DUP | LDC "addEntityLinkText" | ALOAD 5 // java.lang.String addEntityLinkText | INVOKESPECIAL wicket.markup.html.basic.Label.<init> (Ljava/lang/String;Ljava/lang/String;)V | INVOKEVIRTUAL wicket.markup.html.link.Link.add (Lwicket/Component;)Lwicket/MarkupContainer; | POP | ILOAD_2 // boolean isInitialView (line 31) | IFEQ L0 | ALOAD_0 // com.aspectivity.mgmt.web.entity.ManageEntity this (line 32) | NEW wicket.markup.html.basic.Label | DUP | LDC "editEntity" | LDC "" | INVOKESPECIAL wicket.markup.html.basic.Label.<init> (Ljava/lang/String;Ljava/lang/String;)V | INVOKEVIRTUAL com.aspectivity.mgmt.web.entity.ManageEntity.add (Lwicket/Component;)Lwicket/MarkupContainer; | POP | GOTO L1 | L0: ALOAD_0 // com.aspectivity.mgmt.web.entity.ManageEntity this (line 34) | ALOAD_0 // com.aspectivity.mgmt.web.entity.ManageEntity this | ALOAD_1 // com.aspectivity.mgmt.model.Entity entity | ILOAD_2 // boolean isInitialView | ALOAD 6 // java.lang.String addPanelTtile | ALOAD 7 // java.lang.String editPanelTitle | INVOKESPECIAL com.aspectivity.mgmt.web.entity.ManageEntity.getEditPanel (Lcom/aspectivity/mgmt/model/Entity;ZLjava/lang/String;Ljava/lang/String;)Lwicket/Component; | INVOKEVIRTUAL com.aspectivity.mgmt.web.entity.ManageEntity.add (Lwicket/Component;)Lwicket/MarkupContainer; | POP | L1: ALOAD_0 // com.aspectivity.mgmt.web.entity.ManageEntity this (line 37) | NEW wicket.markup.html.basic.Label | DUP | LDC "listViewTitle" | ALOAD 4 // java.lang.String listViewTitle | INVOKESPECIAL wicket.markup.html.basic.Label.<init> (Ljava/lang/String;Ljava/lang/String;)V | INVOKEVIRTUAL com.aspectivity.mgmt.web.entity.ManageEntity.add (Lwicket/Component;)Lwicket/MarkupContainer; | POP | RETURN (line 38) constructor-execution(void com.aspectivity.mgmt.web.entity.ManageEntity.<init>(com.aspectivity.mgmt.model.Entity, boolean, java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String)) end public void <init>(com.aspectivity.mgmt.model.Entity, boolean, String, String, String, String, String) protected abstract com.aspectivity.mgmt.model.Entity createNewEntity() org.aspectj.weaver.MethodDeclarationLineNumber: 40:1233 ; protected abstract void removeEntity(com.aspectivity.mgmt.model.Entity) org.aspectj.weaver.MethodDeclarationLineNumber: 41:1278 ; protected abstract java.util.List getAllEntities() org.aspectj.weaver.MethodDeclarationLineNumber: 42:1351 ; protected abstract com.aspectivity.mgmt.web.entity.ManageEntity createNewPage(com.aspectivity.mgmt.model.Entity, boolean) org.aspectj.weaver.MethodDeclarationLineNumber: 44:1406 ; protected abstract wicket.Component createEditPanel(String, String, com.aspectivity.mgmt.model.Entity) org.aspectj.weaver.MethodDeclarationLineNumber: 45:1490 ; protected wicket.markup.html.list.ListView getEntitiesListView(com.aspectivity.mgmt.model.Entity, String) org.aspectj.weaver.MethodDeclarationLineNumber: 47:1581 : NEW com.aspectivity.mgmt.web.entity.EntityListView (line 48) DUP ALOAD_0 // com.aspectivity.mgmt.web.entity.ManageEntity this LDC "entityList" ALOAD_0 // com.aspectivity.mgmt.web.entity.ManageEntity this INVOKEVIRTUAL com.aspectivity.mgmt.web.entity.ManageEntity.getAllEntities ()Ljava/util/List; ALOAD_1 // com.aspectivity.mgmt.model.Entity entity INVOKESPECIAL com.aspectivity.mgmt.web.entity.EntityListView.<init> (Lcom/aspectivity/mgmt/web/entity/ManageEntity;Ljava/lang/String;Ljava/util/List;Lcom/aspectivity/mgmt/model/Entity;)V ARETURN end protected wicket.markup.html.list.ListView getEntitiesListView(com.aspectivity.mgmt.model.Entity, String) protected wicket.markup.html.link.Link getEditLink(String, com.aspectivity.mgmt.model.Entity) org.aspectj.weaver.MethodDeclarationLineNumber: 51:1743 : NEW wicket.markup.html.link.PageLink (line 52) DUP ALOAD_1 // java.lang.String name NEW com.aspectivity.mgmt.web.entity.ManageEntity$1 DUP ALOAD_0 // com.aspectivity.mgmt.web.entity.ManageEntity this ALOAD_2 // com.aspectivity.mgmt.model.Entity entity INVOKESPECIAL com.aspectivity.mgmt.web.entity.ManageEntity$1.<init> (Lcom/aspectivity/mgmt/web/entity/ManageEntity;Lcom/aspectivity/mgmt/model/Entity;)V INVOKESPECIAL wicket.markup.html.link.PageLink.<init> (Ljava/lang/String;Lwicket/markup/html/link/IPageLink;)V ARETURN end protected wicket.markup.html.link.Link getEditLink(String, com.aspectivity.mgmt.model.Entity) protected wicket.markup.html.link.Link getRemoveLink(String, wicket.markup.html.list.ListItem) org.aspectj.weaver.MethodDeclarationLineNumber: 63:2013 : NEW com.aspectivity.mgmt.web.entity.ManageEntity$2 (line 64) DUP ALOAD_0 // com.aspectivity.mgmt.web.entity.ManageEntity this ALOAD_1 // java.lang.String id ALOAD_2 // wicket.markup.html.list.ListItem item INVOKESPECIAL com.aspectivity.mgmt.web.entity.ManageEntity$2.<init> (Lcom/aspectivity/mgmt/web/entity/ManageEntity;Ljava/lang/String;Lwicket/markup/html/list/ListItem;)V ARETURN end protected wicket.markup.html.link.Link getRemoveLink(String, wicket.markup.html.list.ListItem) private wicket.Component getEditPanel(com.aspectivity.mgmt.model.Entity, boolean, String, String) org.aspectj.weaver.MethodDeclarationLineNumber: 75:2376 : ALOAD_1 // com.aspectivity.mgmt.model.Entity entity (line 77) IFNONNULL L0 ALOAD_3 // java.lang.String addPanelTtile GOTO L1 L0: ALOAD 4 // java.lang.String editPanelTitle L1: ASTORE 5 ALOAD_1 // com.aspectivity.mgmt.model.Entity entity (line 78) IFNONNULL L2 ALOAD_0 // com.aspectivity.mgmt.web.entity.ManageEntity this (line 79) INVOKEVIRTUAL com.aspectivity.mgmt.web.entity.ManageEntity.createNewEntity ()Lcom/aspectivity/mgmt/model/Entity; ASTORE_1 // com.aspectivity.mgmt.model.Entity entity L2: ALOAD_0 // com.aspectivity.mgmt.web.entity.ManageEntity this (line 81) LDC "editEntity" ALOAD 5 // java.lang.String panelTitle ALOAD_1 // com.aspectivity.mgmt.model.Entity entity INVOKEVIRTUAL com.aspectivity.mgmt.web.entity.ManageEntity.createEditPanel (Ljava/lang/String;Ljava/lang/String;Lcom/aspectivity/mgmt/model/Entity;)Lwicket/Component; ARETURN end private wicket.Component getEditPanel(com.aspectivity.mgmt.model.Entity, boolean, String, String) end public abstract class com.aspectivity.mgmt.web.entity.ManageEntity when implementing on shadow constructor-execution(void com.aspectivity.mgmt.web.entity.ManageEntity.<init>(com.aspectivity.mgmt.model.Entity, boolean, java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String)) when weaving type com.aspectivity.mgmt.web.entity.ManageEntity when weaving classes when weaving when batch building BuildConfig[C:\work\projects\workspace\.metadata\.plugins\org.eclipse.ajdt.core\Aspectivity.generated.lst] #Files=87
|
resolved fixed
|
d43e74b
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2005-12-06T03:20:59Z | 2005-11-27T05:40:00Z |
tests/src/org/aspectj/systemtest/ajc150/Ajc150Tests.java
|
/*******************************************************************************
* Copyright (c) 2004 IBM
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* Andy Clement - initial API and implementation
*******************************************************************************/
package org.aspectj.systemtest.ajc150;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.List;
import junit.framework.Test;
import org.aspectj.apache.bcel.classfile.JavaClass;
import org.aspectj.apache.bcel.classfile.Method;
import org.aspectj.apache.bcel.classfile.Signature;
import org.aspectj.apache.bcel.util.ClassPath;
import org.aspectj.apache.bcel.util.SyntheticRepository;
import org.aspectj.asm.AsmManager;
import org.aspectj.asm.IHierarchy;
import org.aspectj.asm.IProgramElement;
import org.aspectj.asm.IRelationship;
import org.aspectj.asm.internal.Relationship;
import org.aspectj.testing.XMLBasedAjcTestCase;
import org.aspectj.util.LangUtil;
public class Ajc150Tests extends org.aspectj.testing.XMLBasedAjcTestCase {
public static Test suite() {
return XMLBasedAjcTestCase.loadSuite(Ajc150Tests.class);
}
protected File getSpecFile() {
return new File("../tests/src/org/aspectj/systemtest/ajc150/ajc150.xml");
}
/*
public void testBrokenDispatchByITD_pr72834() { runTest("broken dispatch");}
public void testMissingAccessor_pr73856() { runTest("missing accessor");}
public void testCunningDeclareParents_pr92311() { runTest("cunning declare parents");}
public void testGenericITDsAndAbstractMethodError_pr102357() { runTest("generic itds and abstract method error");}
*/
public void testGeneratingCodeForAnOldRuntime_pr116679_1() { runTest("generating code for a 1.2.1 runtime - 1");}
public void testGeneratingCodeForAnOldRuntime_pr116679_2() { runTest("generating code for a 1.2.1 runtime - 2");}
public void testAmbiguousMethod_pr118599_1() { runTest("ambiguous method when binary weaving - 1");}
public void testAmbiguousMethod_pr118599_2() { runTest("ambiguous method when binary weaving - 2");}
public void testAroundAdviceArrayAdviceSigs_pr118781() { runTest("verify error with around advice array sigs");}
public void testAtDeclareParents_pr117681() { runTest("at declare parents");}
public void testPrivilegeProblem_pr87525() { runTest("privilege problem with switch");}
public void testGenericAspects_pr115237() { runTest("aspectOf and generic aspects");}
public void testClassFormatError_pr114436() { runTest("ClassFormatError binary weaving perthis");}
public void testParserException_pr115788() { runTest("parser exception");}
public void testPossibleStaticImports_pr113066_1() { runTest("possible static imports bug - 1");}
public void testPossibleStaticImports_pr113066_2() { runTest("possible static imports bug - 2");}
public void testPossibleStaticImports_pr113066_3() { runTest("possible static imports bug - 3");}
public void testITDCtor_pr112783() { runTest("Problem with constructor ITDs");}
public void testAnnotatedITDFs_pr114005_1() { runTest("Annotated ITDFs - 1");}
public void testAnnotatedITDFs_pr114005_2() { runTest("Annotated ITDFs - 2");}
public void testCantCallSuperMethods_pr90143() { runTest("cant call super methods");}
public void testBrokenDecp_pr112476() { runTest("binary weaving decp broken");}
public void testUnboundFormal_pr112027() { runTest("unexpected error unboundFormalInPC");}
public void testNPEScopeSetup_pr115038() { runTest("NPE in ensureScopeSetup");}
public void testCCEGenerics_pr113445() { runTest("Generics ClassCastException");}
public void testMatthewsAspect_pr113947_1() { runTest("maws generic aspect - 1");}
public void testMatthewsAspect_pr113947_2() { runTest("maws generic aspect - 2");}
public void testFieldGet_pr114343() { runTest("field-get, generics and around advice");}
public void testFieldGet_pr114343_2() { runTest("field-get, generics and around advice - 2");}
public void testFieldGet_pr114343_3() { runTest("field-get, generics and around advice - 3");}
public void testCaptureBinding_pr114744() { runTest("capturebinding wildcard problem");}
public void testBadDecp_pr110788_1() { runTest("bad generic decp - 1");}
public void testBadDecp_pr110788_2() { runTest("bad generic decp - 2");}
public void testBadDecp_pr110788_3() { runTest("bad generic decp - 3");}
public void testBadDecp_pr110788_4() { runTest("bad generic decp - 4");}
public void testVarargsITD_pr110906() { runTest("ITD varargs problem");}
public void testBadRenderer_pr86903() { runTest("bcelrenderer bad");}
//public void testIllegalInitialization_pr118326_1() { runTest("illegal initialization - 1");}
//public void testIllegalInitialization_pr118326_2() { runTest("illegal initialization - 2");}
public void testLintForAdviceSorting_pr111667() { runTest("lint for advice sorting");}
public void testIncompatibleClassChangeError_pr113630_1() {runTest("IncompatibleClassChangeError - errorscenario");}
public void testIncompatibleClassChangeError_pr113630_2() {runTest("IncompatibleClassChangeError - workingscenario");}
public void testFieldGetProblemWithGenericField_pr113861() {runTest("field-get problems with generic field");}
public void testAccesstoPrivateITDInNested_pr118698() { runTest("access to private ITD from nested type");}
public void testDeclareAnnotationOnNonExistentType_pr99191_1() { runTest("declare annotation on non existent type - 1");}
public void testDeclareAnnotationOnNonExistentType_pr99191_2() { runTest("declare annotation on non existent type - 2");}
public void testDeclareAnnotationOnNonExistentType_pr99191_3() { runTest("declare annotation on non existent type - 3");}
public void testDeclareAnnotationOnNonExistentType_pr99191_4() { runTest("declare annotation on non existent type - 4");}
public void testDeclareAnnotationOnNonExistentType_pr99191_5() { runTest("declare annotation on non existent type - 5");}
public void testBadGenericSigAttribute_pr110927() {
runTest("cant create signature attribute");
Signature sig = GenericsTests.getClassSignature(ajc,"I");
if (sig==null) fail("Couldn't find signature attribute for type I");
String sigString = sig.getSignature();
if (!(sigString.equals("Ljava/lang/Object;LIE2;LIE1<Ljava/lang/String;>;") ||
sigString.equals("Ljava/lang/Object;LIE1<Ljava/lang/String;>;LIE2;"))) {
fail("Signature was "+sigString+" when should have been something like Ljava/lang/Object;LIE1<Ljava/lang/String;>;LIE2;");
}
}
public void test_typeProcessingOrderWhenDeclareParents() {
runTest("Order of types passed to compiler determines weaving behavior");
}
public void test_aroundMethod() {
runTest("method called around in class");
}
public void test_aroundMethodAspect() {
runTest("method called around in aspect");
}
public void test_ambiguousBindingsDetection() {
runTest("Various kinds of ambiguous bindings");
}
public void test_ambiguousArgsDetection() {
runTest("ambiguous args");
}
public void testIncorrectExceptionTableWhenBreakInMethod_pr78021() {
runTest("Injecting exception into while loop with break statement causes catch block to be ignored");
}
public void testIncorrectExceptionTableWhenReturnInMethod_pr79554() {
runTest("Return in try-block disables catch-block if final-block is present");
}
public void testMissingDebugInfoForGeneratedMethods_pr82570() throws ClassNotFoundException {
runTest("Weaved code does not include debug lines");
boolean f = false;
JavaClass jc = getClassFrom(ajc.getSandboxDirectory(),"PR82570_1");
Method[] meths = jc.getMethods();
for (int i = 0; i < meths.length; i++) {
Method method = meths[i];
if (f) System.err.println("Line number table for "+method.getName()+method.getSignature()+" = "+method.getLineNumberTable());
assertTrue("Didn't find a line number table for method "+method.getName()+method.getSignature(),
method.getLineNumberTable()!=null);
}
// This test would determine the info isn't there if you pass -g:none ...
// cR = ajc(baseDir,new String[]{"PR82570_1.java","-g:none"});
// assertTrue("Expected no compile problem:"+cR,!cR.hasErrorMessages());
// System.err.println(cR.getStandardError());
// jc = getClassFrom(ajc.getSandboxDirectory(),"PR82570_1");
// meths = jc.getMethods();
// for (int i = 0; i < meths.length; i++) {
// Method method = meths[i];
// assertTrue("Found a line number table for method "+method.getName(),
// method.getLineNumberTable()==null);
// }
}
public void testCanOverrideProtectedMethodsViaITDandDecp_pr83303() {
runTest("compiler error when mixing inheritance, overriding and polymorphism");
}
public void testPerTypeWithin_pr106554() {runTest("Problem in staticinitialization with pertypewithin aspect");}
public void testPerTypeWithinMissesNamedInnerTypes() {
runTest("pertypewithin() handing of inner classes (1)");
}
public void testPerTypeWithinMissesAnonymousInnerTypes() {
runTest("pertypewithin() handing of inner classes (2)");
}
public void testPerTypeWithinIncorrectlyMatchingInterfaces() {
runTest("pertypewithin({interface}) illegal field modifier");
}
public void test051_arrayCloningInJava5() {
runTest("AJC possible bug with static nested classes");
}
public void testBadASMforEnums() throws IOException {
runTest("bad asm for enums");
if (LangUtil.is15VMOrGreater()) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
PrintWriter pw = new PrintWriter(baos);
AsmManager.dumptree(pw,AsmManager.getDefault().getHierarchy().getRoot(),0);
pw.flush();
String tree = baos.toString();
assertTrue("Expected 'Red [enumvalue]' somewhere in here:"+tree,tree.indexOf("Red [enumvalue]")!=-1);
}
}
public void npeOnTypeNotFound() {
runTest("structure model npe on type not found");
}
public void testNoRuntimeExceptionSoftening() {
runTest("declare soft of runtime exception");
}
public void testRuntimeNoSoftenWithHandler() {
runTest("declare soft w. catch block");
}
public void testSyntaxError() {
runTest("invalid cons syntax");
}
public void testVarargsInConsBug() {
runTest("varargs in constructor sig");
}
public void testAspectpathdirs() {
runTest("dirs on aspectpath");
}
public void testIntroSample() {
runTest("introduction sample");
}
public void testPTWInterface() {
runTest("pertypewithin({interface}) illegal field modifier");
}
public void testEnumCalledEnumEtc() {
runTest("enum called Enum, annotation called Annotation, etc");
}
public void testInternalCompilerError_pr86832() {
runTest("Internal compiler error");
}
public void testCloneMethod_pr83311() {
runTest("overriding/polymorphism error on interface method introduction");
}
// IfPointcut.findResidueInternal() was modified to make this test complete in a short amount
// of time - if you see it hanging, someone has messed with the optimization.
public void testIfEvaluationExplosion_pr94086() {
runTest("Exploding compile time with if() statements in pointcut");
}
public void testReflectNPE_pr94167() {runTest("NPE in reflect implementation");}
public void testStaticImports_pr84260() {runTest("static import failures");}
public void testGenerics_pr99089() {runTest("ArrayIndexOutOfBoundsException - Generics in privileged aspects");}
public void testGenerics_pr95993() {runTest("NPE at ClassScope.java:660 when compiling generic class");}
public void testItdGenerics_pr99228() {runTest("ITD of a field into a generic class");}
public void testItdGenerics_pr98320() {runTest("intertype with nested generic type");}
public void testItdGenerics_pr100227() {runTest("inner class with generic enclosing class");}
public void testItdGenerics_pr100260() {runTest("methods inherited from a generic parent");}
public void testSyntaxErrorNPE_pr103266() {runTest("NPE on syntax error");}
public void testFinalAbstractClass_pr109486() { runTest("Internal compiler error (ClassParser.java:242)");}
public void testComplexBinding_pr102210() { runTest("NullPointerException trying to compile");}
public void testIllegalStateExceptionOnNestedParameterizedType_pr106634() {
runTest("IllegalStateException unpacking signature of nested parameterized type");
}
public void testParseErrorOnAnnotationStarPlusPattern() {
runTest("(@Foo *)+ type pattern parse error");
}
public void test_pr106130_tooManyLocals() {
runTest("test weaving with > 256 locals");
}
public void testMissingNamePattern_pr106461() { runTest("missing name pattern"); }
public void testMissingNamePattern_pr107059() {
runTest("parser crashes on call(void (@a *)(..)");
}
public void testIntermediateAnnotationMatching() {
runTest("intermediate annotation matching");
}
public void testBadRuntimeTestGeneration() {
runTest("target(@Foo *)");
}
public void testErrorMessageOnITDWithTypePatterns() {
runTest("clear error message on itd with type pattern");
}
public void testAjKeywordsAsIdentifiers() {
runTest("before and after are valid identifiers in classes");
}
public void testAjKeywordsAsIdentifiers2() {
runTest("before and after are valid identifiers in classes, part 2");
}
public void testNoBeforeReturningAdvice() {
runTest("before returning advice not allowed!");
}
public void testDetectVoidFieldType() {
runTest("void field type in pointcut expression");
}
public void testPointcutOverriding() {
runTest("overriding final pointcut from super-aspect");
}
public void testAtSuppressWarnings() {
runTest("@SuppressWarnings should suppress");
}
public void testDEOWWithBindingPointcut() {
runTest("declare warning : foo(str) : ...;");
}
public void testAroundAdviceAndInterfaceInitializer() {
runTest("around advice on interface initializer");
}
public void testGoodErrorMessageOnUnmatchedMemberSyntax() {
runTest("good error message for unmatched member syntax");
}
public void testITDWithNoExceptionAndIntermediary() {
runTest("itd override with no exception clause");
}
public void testAnonymousInnerClasses() {
runTest("anonymous inner classes");
}
public void testMultipleAnonymousInnerClasses() {
runTest("multiple anonymous inner classes");
}
public void testPrivilegedMethodAccessorsGetRightExceptions_pr82989() {
runTest("Compiler error due to a wrong exception check in try blocks");
}
public void testAnonymousInnerClassWithMethodReturningTypeParameter_pr107898() {
runTest("anonymous inner class with method returning type parameter");
}
public void testMatchingOfObjectArray() {
runTest("matching against Object[]");
}
public void testMultipleAnonymousInnerClasses_pr108104() {
runTest("multiple anonymous inner classes 2");
}
public void testSignatureMatchingInMultipleOverrideScenario() {
runTest("signature matching in override scenario");
}
public void testWildcardAnnotationMatching_pr108245() {
runTest("wildcard annotation matching - pr108245");
}
public void testInnerTypesAndTypeVariables() {
runTest("inner types and type variables");
}
public void testAtAfterThrowingWithNoFormal() {
runTest("@AfterThrowing with no formal specified");
}
public void testParameterizedVarArgsMatch() {
runTest("varargs with type variable");
}
public void testFieldAccessInsideITDM() {
runTest("itd field access inside itd method");
}
public void testTypeVarWithTypeVarBound() {
runTest("type variable with type variable bound");
}
public void testEnumSwitchInITD() {
runTest("switch on enum inside ITD method");
}
public void testInnerTypeOfGeneric() {
runTest("inner type of generic interface reference from parameterized type");
}
public void testDeclareParentsIntroducingCovariantReturnType() {
runTest("declare parents introducing override with covariance");
}
public void testInnerClassPassedToVarargs() {
runTest("inner class passed as argument to varargs method");
}
public void testInlinedFieldAccessInProceedCall() {
runTest("inlined field access in proceed call");
}
public void testVisibiltyInSignatureMatchingWithOverridesPart1() {
runTest("visibility in signature matching with overrides - 1");
}
public void testVisibiltyInSignatureMatchingWithOverridesPart2() {
runTest("visibility in signature matching with overrides - 2");
}
public void testVisibiltyInSignatureMatchingWithOverridesPart3() {
runTest("visibility in signature matching with overrides - 3");
}
public void testArgsGeneratedCorrectlyForAdviceExecution() {
runTest("args generated correctly for advice execution join point");
}
public void testNoUnusedWarningsOnAspectTypes() {
runTest("no unused warnings on aspect types");
}
public void testSyntheticArgumentsOnITDConstructorsNotUsedInMatching() {
runTest("synthetic arguments on itd cons are not used in matching");
}
public void testParsingOfGenericTypeSignature() {
runTest("parse generic type signature with parameterized type in interface");
}
public void testOverrideAndCovarianceWithDecPRuntime() {
runTest("override and covariance with decp - runtime");
}
public void testOverrideAndCovarianceWithDecPRuntimeMultiFiles() {
runTest("override and covariance with decp - runtime separate files");
}
public void testOverrideAndCovarianceWithDecPRuntimeMultiFilesBinaryWeaving() {
runTest("override and covariance with decp - binary weaving");
}
public void testAbstractSynchronizedITDMethods() {
runTest("abstract synchronized itdms not detected");
}
public void testSynchronizedITDInterfaceMethods() {
runTest("synchronized itd interface methods");
}
public void testNoWarningOnUnusedPointcut() {
runTest("unused private pointcuts");
}
public void testITDOnInterfaceWithExistingMember() {
runTest("itd interface method already existing on interface");
}
public void testFinalITDMOnInterface() {
runTest("final itd methods on interfaces");
}
public void testPrivatePointcutOverriding() {
runTest("can't override private pointcut in abstract aspect");
}
public void testAdviceOnCflow() {
runTest("advising cflow advice execution");
}
public void testNoTypeMismatchOnSameGenericTypes() {
runTest("no type mismatch on generic types in itds");
}
public void testSuperCallInITD() {
runTest("super call in ITD");
}
public void testSuperCallInITDPart2() {
runTest("super call in ITD - part 2");
}
public void testAtAnnotationBadTest_pr103740() {
runTest("Compiler failure on at_annotation");
}
public void testNoUnusedParameterWarningsForSyntheticAdviceArgs() {
runTest("no unused parameter warnings for synthetic advice args");
}
public void testNoVerifyErrorWithSetOnInnerType() {
runTest("no verify error with set on inner type");
}
public void testCantFindTypeErrorWithGenericReturnTypeOrParameter() {
runTest("cant find type error with generic return type or parameter");
}
public void testNoVerifyErrorOnGenericCollectionMemberAccess() {
runTest("no verify error on generic collection member access");
}
public void testRawAndGenericTypeConversionITDCons() {
runTest("raw and generic type conversion with itd cons");
}
public void testAtAnnotationBindingWithAround() {
runTest("@annotation binding with around advice");
}
public void testUnableToBuildShadows_pr109728() { runTest("Unable to build shadows");}
public void testMessageOnMissingTypeInDecP() {
runTest("declare parents on a missing type");
}
public void testParameterizedGenericMethods() {
runTest("parameterized generic methods");
}
public void testIllegalChangeToPointcutDeclaration_pr111915() {
runTest("test illegal change to pointcut declaration");
}
public void testCantProvideDefaultImplViaITD_pr110307_1() {runTest("Cant provide default implementation via ITD - 1");}
public void testCantProvideDefaultImplViaITD_pr110307_2() {runTest("Cant provide default implementation via ITD - 2");}
public void testCantProvideDefaultImplViaITD_pr110307_3() {runTest("Cant provide default implementation via ITD - 3");}
public void testCantProvideDefaultImplViaITD_pr110307_4() {runTest("Cant provide default implementation via ITD - 4");}
public void testCantProvideDefaultImplViaITD_pr110307_5() {runTest("Cant provide default implementation via ITD - 5");}
// Needs a change in the compiler so that getType() can be overridden in the intertype scope - thats
// where we can police whether a type variable has been used without being specified appropriately.
//public void testCantProvideDefaultImplViaITD_pr110307_6() {runTest("Cant provide default implementation via ITD - 6");}
public void testCantProvideDefaultImplViaITD_pr110307_7() {runTest("Cant provide default implementation via ITD - 7");}
public void testCallJoinPointsInAnonymousInnerClasses() {
runTest("call join points in anonymous inner classes");
}
public void testNoRequirementForUnwovenTypesToBeExposedToWeaver() {
runTest("default impl of Runnable");
}
public void testArrayCloneCallJoinPoints() {
runTest("array clone call join points in 1.4 vs 1.3");
}
public void testDebugInfoForAroundAdvice() {
runTest("debug info in around advice inlining");
}
public void testCCEWithGenericWildcard_pr112602() {
runTest("ClassCastException with generic wildcard");
}
public void testAdviceInStructureModelWithAnonymousInnerClass_pr77269() {
//AsmManager.setReporting("c:/debug.txt",true,true,true,true);
runTest("advice in structure model with anonymous inner class");
IHierarchy top = AsmManager.getDefault().getHierarchy();
// checking that the run() method inside anonymous inner class is in
// the structure model
IProgramElement anonRunMethodIPE = top.findElementForLabel(top.getRoot(),
IProgramElement.Kind.METHOD,"run()");
assertNotNull("Couldn't find 'run()' element in the tree",anonRunMethodIPE);
List l = AsmManager.getDefault().getRelationshipMap().get(anonRunMethodIPE);
assertNotNull("Should have some relationships but does not",l);
assertTrue("Should have one relationship but has " + l.size(),l.size()==1);
Relationship rel = (Relationship)l.get(0);
List targets = rel.getTargets();
assertTrue("Should have one target but has" + targets.size(),
targets.size()==1);
IProgramElement target = AsmManager.getDefault().getHierarchy().findElementForHandle((String)targets.get(0));
assertEquals("target of relationship should be 'before(): p..' but is "
+ target.toLabelString(),"before(): p..",target.toLabelString());
IProgramElement adviceIPE = top.findElementForLabel(top.getRoot(),
IProgramElement.Kind.ADVICE,"before(): p..");
assertNotNull("Couldn't find 'before(): p..' element in the tree",adviceIPE);
l = AsmManager.getDefault().getRelationshipMap().get(adviceIPE);
assertNotNull("Should have some relationships but does not",l);
assertTrue("Should have a relationship but does not ",l.size()>0);
for (Iterator iter = l.iterator(); iter.hasNext();) {
IRelationship element = (IRelationship) iter.next();
if (element.getName().equals("advises")) {
rel = (Relationship) element;
break;
}
}
targets = rel.getTargets();
assertTrue("Should have one target but has" + targets.size(),
targets.size()==1);
target = AsmManager.getDefault().getHierarchy().findElementForHandle((String)targets.get(0));
assertEquals("target of relationship should be 'run()' but is "
+ target.toLabelString(),"run()",target.toLabelString());
}
public void testAdviceInStructureModelWithNamedInnerClass_pr77269() {
//AsmManager.setReporting("c:/debug.txt",true,true,true,true);
runTest("advice in structure model with named inner class");
IHierarchy top = AsmManager.getDefault().getHierarchy();
// checking that the m() method inside named inner class is in
// the structure model
IProgramElement namedMethodIPE = top.findElementForLabel(top.getRoot(),
IProgramElement.Kind.METHOD,"m()");
assertNotNull("Couldn't find 'm()' element in the tree",namedMethodIPE);
List l = AsmManager.getDefault().getRelationshipMap().get(namedMethodIPE);
assertNotNull("Should have some relationships but does not",l);
assertTrue("Should have one relationship but has " + l.size(),l.size()==1);
Relationship rel = (Relationship)l.get(0);
List targets = rel.getTargets();
assertTrue("Should have one target but has" + targets.size(),
targets.size()==1);
IProgramElement target = AsmManager.getDefault().getHierarchy().findElementForHandle((String)targets.get(0));
assertEquals("target of relationship should be 'before(): p..' but is "
+ target.toLabelString(),"before(): p..",target.toLabelString());
IProgramElement adviceIPE = top.findElementForLabel(top.getRoot(),
IProgramElement.Kind.ADVICE,"before(): p..");
assertNotNull("Couldn't find 'before(): p..' element in the tree",adviceIPE);
l = AsmManager.getDefault().getRelationshipMap().get(adviceIPE);
assertNotNull("Should have some relationships but does not",l);
assertTrue("Should have a relationship but does not ",l.size()>0);
for (Iterator iter = l.iterator(); iter.hasNext();) {
IRelationship element = (IRelationship) iter.next();
if (element.getName().equals("advises")) {
rel = (Relationship) element;
break;
}
}
targets = rel.getTargets();
assertTrue("Should have one target but has" + targets.size(),
targets.size()==1);
target = AsmManager.getDefault().getHierarchy().findElementForHandle((String)targets.get(0));
assertEquals("target of relationship should be 'm()' but is "
+ target.toLabelString(),"m()",target.toLabelString());
}
public void testDWInStructureModelWithAnonymousInnerClass_pr77269() {
// AsmManager.setReporting("c:/debug.txt",true,true,true,true);
runTest("declare warning in structure model with anonymous inner class");
IHierarchy top = AsmManager.getDefault().getHierarchy();
IProgramElement pe = top.findElementForLabel(top.getRoot(),
IProgramElement.Kind.CODE,"method-call(void pack.Test.someMethod())");
assertNotNull("Couldn't find 'method-call(void pack.Test.someMethod())' element in the tree",pe);
}
public void testVarArgsIITDInConstructor() {
runTest("ITD varargs in constructor");
}
public void testWeaveInfoMessageForDeclareAtMethodOnITDdMethod() {
runTest("weaveinfo message for declare at method on an ITDd method");
}
public void testITDCWithNoExplicitConsCall() {
runTest("ITDC with no explicit cons call");
}
public void testJava5SpecificFeaturesUsedAtJava14OrLower() {
runTest("java 5 pointcuts and declares at pre-java 5 compliance levels");
}
public void testAnonymousTypes() {
runTest("Anonymous types and nome matching");
}
public void testAdviceExecutionJPToStringForms() {
runTest("adviceexecution join point toString forms");
}
public void testAssertWithinPointcutExpression() {
runTest("pointcut expression containing 'assert'");
}
public void testNoVerifyErrorWithTwoThisPCDs_pr113447() {
runTest("no verify error with two this pcds");
}
public void testNoVerifyErrorWithTwoAtThisPCDs_pr113447() {
runTest("no verify error with two at this pcds");
}
public void testNoVerifyErrorWithAtWithinPCDs_pr113447() {
runTest("no verify error with at within pcds");
}
public void testNoVerifyErrorWithAtWithincodePCDs_pr113447() {
runTest("no verify error with at withincode pcds");
}
public void testNoVerifyErrorWithAtAnnotationPCDs_pr113447() {
runTest("no verify error with at annotation pcds");
}
public void testNoVerifyErrorWithTwoArgsPCDs_pr113447() {
runTest("no verify error with two args pcds");
}
public void testNoStackOverflowWithCircularPCDInGenericAspect() {
runTest("no StackOverflowError with circular pcd in generic aspect");
}
public void testNoStackOverflowWithCircularPCDInGenericAspect2() {
runTest("no StackOverflowError with circular pcd in generic aspect - 2");
}
public void testNPEInThisJoinPointStaticPart() {
runTest("thisJoinPointStaticPart in if test");
}
public void testPointcutParsingOfCompiledPointcuts() {
runTest("pointcut parsing with ajc compiled pointcut references");
}
public void testReflectionOfAbstractITDs() {
runTest("reflection on abstract ITDs (Billing example)");
}
public void testDeclareSoftWithAdviceExecution() {
runTest("declare soft and adviceexecution");
}
public void testDeclareSoftWithExclusions() {
runTest("declare soft and exclusions");
}
public void testReturningObjectBinding() {
runTest("returning(Object) binding");
}
public void testPerTargetAndNegation() {
runTest("pertarget and negated pointcut");
}
public void testParameterizedPointcutAndAdvice() {
runTest("parameterized pointcut and advice");
}
public void testDoublyParameterizedAbstractType() {
runTest("double parameter generic abstract type");
}
public void testArgNamesInAdviceAnnotations() {
runTest("arg names in advice annotations");
}
/*
* Load-time weaving bugs
*/
public void testNPEinWeavingAdaptor_pr116626() { runTest("NPE in WeavingAdaptor");}
public void testXlintMessageForImproperAnnotationType_pr115252_Exact() {runTest("xlint message for improper exact annotation type");}
public void testXlintMessageForImproperAnnotationType_pr115252_OR() {runTest("xlint message for improper annotation type inside OR");}
public void testXlintMessageForImproperAnnotationType_pr115252_AND() {runTest("xlint message for improper annotation type inside AND");}
public void testXlintMessageForImproperAnnotationType_pr115252_Return() {runTest("xlint message for improper annotated return type");}
public void testXlintMessageForImproperAnnotationType_pr115252_Declaring() {runTest("xlint message for improper annotated declaring type");}
public void testXlintMessageForImproperAnnotationType_pr115252_Parameter() {runTest("xlint message for improper annotated parameter type");}
public void testXlintMessageForImproperAnnotationType_pr115252_Throws() {runTest("xlint message for improper annotated throws pattern");}
public void testXlintMessageForImproperAnnotationType_pr115252_MoreThanOne() {runTest("xlint message for more than one improper annotated parameter type");}
public void testDeclareAtTypeInStructureModel_pr115607() {
AsmManager.setReporting("c:/debug.txt",true,true,true,true);
runTest("declare at type appears correctly in structure model");
IHierarchy top = AsmManager.getDefault().getHierarchy();
IProgramElement pe = top.findElementForLabel(top.getRoot(),
IProgramElement.Kind.DECLARE_ANNOTATION_AT_TYPE,"declare @type: Simple : @I");
assertNotNull("Couldn't find 'declare @type: Simple : @I' element in the tree",pe);
List l = AsmManager.getDefault().getRelationshipMap().get(pe);
assertNotNull("Should have some relationships but does not",l);
}
public void testNoNPEWhenInaccessibleMethodIsCalledWithinITD_pr119019() {
runTest("no NPE when inaccessible method is called within itd");
}
// helper methods.....
public SyntheticRepository createRepos(File cpentry) {
ClassPath cp = new ClassPath(cpentry+File.pathSeparator+System.getProperty("java.class.path"));
return SyntheticRepository.getInstance(cp);
}
protected JavaClass getClassFrom(File where,String clazzname) throws ClassNotFoundException {
SyntheticRepository repos = createRepos(where);
return repos.loadClass(clazzname);
}
}
|
118,149 |
Bug 118149 AspectJ compiler crahses possibly due to poincut context binding issue
|
I am using the latest version of AJDT (1.3.0.20051125115230). The reason is not entirely clear, but I have a pointcut of form public pointcut realPC(Common entity) : pc1(entity) || pc2(entity); Just a few hours back, I used to get an error regarding incompatible binding of entity in the || poincut. When I got that error, Eclipse was frozen to the point that clicking "Details" on exception report made Eclipse hang and had to kill it using the task manager. So I modified the program to avoid || expression in pointcut, after unsuccessfully trying various ways to express the pointcut. It was an ugly thing to do, since I essentially had to duplicate the advice for both pointcuts. Anyway... Then I tried to reproduce on a smaller project to provide a minimal program to reproduced the bug. However, it worked just fine on that project (and I couldn't see any material difference in the pointcuts or the classes involved). Encouraged by this, I retried the or-ed version of the pointcut on the real project. This time, I get the crash and can acccess the stack trace. java.lang.NullPointerException at org.aspectj.weaver.ast.Test.makeInstanceof(Test.java:78) at org.aspectj.weaver.patterns.IfPointcut.findResidueInternal(IfPointcut.java:181) at org.aspectj.weaver.patterns.Pointcut.findResidue(Pointcut.java:267) at org.aspectj.weaver.patterns.AndPointcut.findResidueInternal(AndPointcut.java:97) at org.aspectj.weaver.patterns.Pointcut.findResidue(Pointcut.java:267) at org.aspectj.weaver.patterns.AndPointcut.findResidueInternal(AndPointcut.java:97) at org.aspectj.weaver.patterns.Pointcut.findResidue(Pointcut.java:267) at org.aspectj.weaver.patterns.OrPointcut.findResidueInternal(OrPointcut.java:99) at org.aspectj.weaver.patterns.Pointcut.findResidue(Pointcut.java:267) at org.aspectj.weaver.patterns.OrPointcut.findResidueInternal(OrPointcut.java:99) at org.aspectj.weaver.patterns.Pointcut.findResidue(Pointcut.java:267) at org.aspectj.weaver.bcel.BcelAdvice.specializeOn(BcelAdvice.java:133) at org.aspectj.weaver.bcel.BcelShadow.prepareForMungers(BcelShadow.java:308) at org.aspectj.weaver.Shadow.implement(Shadow.java:404) at org.aspectj.weaver.bcel.BcelClassWeaver.implement(BcelClassWeaver.java:2146) at org.aspectj.weaver.bcel.BcelClassWeaver.weave(BcelClassWeaver.java:467) at org.aspectj.weaver.bcel.BcelClassWeaver.weave(BcelClassWeaver.java:102) at org.aspectj.weaver.bcel.BcelWeaver.weave(BcelWeaver.java:1534) at org.aspectj.weaver.bcel.BcelWeaver.weaveWithoutDump(BcelWeaver.java:1485) at org.aspectj.weaver.bcel.BcelWeaver.weaveAndNotify(BcelWeaver.java:1266) at org.aspectj.weaver.bcel.BcelWeaver.weave(BcelWeaver.java:1088) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.weave(AjCompilerAdapter.java:300) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.afterCompiling(AjCompilerAdapter.java:178) at org.aspectj.ajdt.internal.compiler.CompilerAdapter.ajc$afterReturning$org_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:809) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.doBuild(AjBuildManager.java:230) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.batchBuild(AjBuildManager.java:156) at org.aspectj.ajde.internal.CompilerAdapter.compile(CompilerAdapter.java:122) at org.aspectj.ajde.internal.AspectJBuildManager$CompilerThread.run(AspectJBuildManager.java:191) trouble in: public abstract class com.aspectivity.mgmt.web.entity.ManageEntity extends com.aspectivity.mgmt.web.TemplatePage: public void <init>(com.aspectivity.mgmt.model.Entity, boolean, String, String, String, String, String) org.aspectj.weaver.MethodDeclarationLineNumber: 19:557 : ALOAD_0 // com.aspectivity.mgmt.web.entity.ManageEntity this (line 19) INVOKESPECIAL com.aspectivity.mgmt.web.TemplatePage.<init> ()V ALOAD_1 ASTORE 9 ILOAD_2 ISTORE 10 ALOAD_3 ASTORE 11 ALOAD 4 ASTORE 12 ALOAD 5 ASTORE 13 ALOAD 6 ASTORE 14 ALOAD 7 ASTORE 15 constructor-execution(void com.aspectivity.mgmt.web.entity.ManageEntity.<init>(com.aspectivity.mgmt.model.Entity, boolean, java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String)) | ALOAD_0 // com.aspectivity.mgmt.web.entity.ManageEntity this (line 23) | ALOAD_3 // java.lang.String pageTitle | INVOKEVIRTUAL com.aspectivity.mgmt.web.entity.ManageEntity.setPageTitle (Ljava/lang/String;)V | ALOAD_0 // com.aspectivity.mgmt.web.entity.ManageEntity this (line 25) | ALOAD_0 // com.aspectivity.mgmt.web.entity.ManageEntity this | ALOAD_1 // com.aspectivity.mgmt.model.Entity entity | ALOAD 5 // java.lang.String addEntityLinkText | INVOKEVIRTUAL com.aspectivity.mgmt.web.entity.ManageEntity.getEntitiesListView (Lcom/aspectivity/mgmt/model/Entity;Ljava/lang/String;)Lwicket/markup/html/list/ListView; | INVOKEVIRTUAL com.aspectivity.mgmt.web.entity.ManageEntity.add (Lwicket/Component;)Lwicket/MarkupContainer; | POP | ALOAD_0 // com.aspectivity.mgmt.web.entity.ManageEntity this (line 27) | LDC "addEntityLink" | ACONST_NULL | INVOKEVIRTUAL com.aspectivity.mgmt.web.entity.ManageEntity.getEditLink (Ljava/lang/String;Lcom/aspectivity/mgmt/model/Entity;)Lwicket/markup/html/link/Link; | ASTORE 8 | ALOAD_0 // com.aspectivity.mgmt.web.entity.ManageEntity this (line 28) | ALOAD 8 // wicket.markup.html.link.Link addEntityLink | INVOKEVIRTUAL com.aspectivity.mgmt.web.entity.ManageEntity.add (Lwicket/Component;)Lwicket/MarkupContainer; | POP | ALOAD 8 // wicket.markup.html.link.Link addEntityLink (line 29) | NEW wicket.markup.html.basic.Label | DUP | LDC "addEntityLinkText" | ALOAD 5 // java.lang.String addEntityLinkText | INVOKESPECIAL wicket.markup.html.basic.Label.<init> (Ljava/lang/String;Ljava/lang/String;)V | INVOKEVIRTUAL wicket.markup.html.link.Link.add (Lwicket/Component;)Lwicket/MarkupContainer; | POP | ILOAD_2 // boolean isInitialView (line 31) | IFEQ L0 | ALOAD_0 // com.aspectivity.mgmt.web.entity.ManageEntity this (line 32) | NEW wicket.markup.html.basic.Label | DUP | LDC "editEntity" | LDC "" | INVOKESPECIAL wicket.markup.html.basic.Label.<init> (Ljava/lang/String;Ljava/lang/String;)V | INVOKEVIRTUAL com.aspectivity.mgmt.web.entity.ManageEntity.add (Lwicket/Component;)Lwicket/MarkupContainer; | POP | GOTO L1 | L0: ALOAD_0 // com.aspectivity.mgmt.web.entity.ManageEntity this (line 34) | ALOAD_0 // com.aspectivity.mgmt.web.entity.ManageEntity this | ALOAD_1 // com.aspectivity.mgmt.model.Entity entity | ILOAD_2 // boolean isInitialView | ALOAD 6 // java.lang.String addPanelTtile | ALOAD 7 // java.lang.String editPanelTitle | INVOKESPECIAL com.aspectivity.mgmt.web.entity.ManageEntity.getEditPanel (Lcom/aspectivity/mgmt/model/Entity;ZLjava/lang/String;Ljava/lang/String;)Lwicket/Component; | INVOKEVIRTUAL com.aspectivity.mgmt.web.entity.ManageEntity.add (Lwicket/Component;)Lwicket/MarkupContainer; | POP | L1: ALOAD_0 // com.aspectivity.mgmt.web.entity.ManageEntity this (line 37) | NEW wicket.markup.html.basic.Label | DUP | LDC "listViewTitle" | ALOAD 4 // java.lang.String listViewTitle | INVOKESPECIAL wicket.markup.html.basic.Label.<init> (Ljava/lang/String;Ljava/lang/String;)V | INVOKEVIRTUAL com.aspectivity.mgmt.web.entity.ManageEntity.add (Lwicket/Component;)Lwicket/MarkupContainer; | POP | RETURN (line 38) constructor-execution(void com.aspectivity.mgmt.web.entity.ManageEntity.<init>(com.aspectivity.mgmt.model.Entity, boolean, java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String)) end public void <init>(com.aspectivity.mgmt.model.Entity, boolean, String, String, String, String, String) protected abstract com.aspectivity.mgmt.model.Entity createNewEntity() org.aspectj.weaver.MethodDeclarationLineNumber: 40:1233 ; protected abstract void removeEntity(com.aspectivity.mgmt.model.Entity) org.aspectj.weaver.MethodDeclarationLineNumber: 41:1278 ; protected abstract java.util.List getAllEntities() org.aspectj.weaver.MethodDeclarationLineNumber: 42:1351 ; protected abstract com.aspectivity.mgmt.web.entity.ManageEntity createNewPage(com.aspectivity.mgmt.model.Entity, boolean) org.aspectj.weaver.MethodDeclarationLineNumber: 44:1406 ; protected abstract wicket.Component createEditPanel(String, String, com.aspectivity.mgmt.model.Entity) org.aspectj.weaver.MethodDeclarationLineNumber: 45:1490 ; protected wicket.markup.html.list.ListView getEntitiesListView(com.aspectivity.mgmt.model.Entity, String) org.aspectj.weaver.MethodDeclarationLineNumber: 47:1581 : NEW com.aspectivity.mgmt.web.entity.EntityListView (line 48) DUP ALOAD_0 // com.aspectivity.mgmt.web.entity.ManageEntity this LDC "entityList" ALOAD_0 // com.aspectivity.mgmt.web.entity.ManageEntity this INVOKEVIRTUAL com.aspectivity.mgmt.web.entity.ManageEntity.getAllEntities ()Ljava/util/List; ALOAD_1 // com.aspectivity.mgmt.model.Entity entity INVOKESPECIAL com.aspectivity.mgmt.web.entity.EntityListView.<init> (Lcom/aspectivity/mgmt/web/entity/ManageEntity;Ljava/lang/String;Ljava/util/List;Lcom/aspectivity/mgmt/model/Entity;)V ARETURN end protected wicket.markup.html.list.ListView getEntitiesListView(com.aspectivity.mgmt.model.Entity, String) protected wicket.markup.html.link.Link getEditLink(String, com.aspectivity.mgmt.model.Entity) org.aspectj.weaver.MethodDeclarationLineNumber: 51:1743 : NEW wicket.markup.html.link.PageLink (line 52) DUP ALOAD_1 // java.lang.String name NEW com.aspectivity.mgmt.web.entity.ManageEntity$1 DUP ALOAD_0 // com.aspectivity.mgmt.web.entity.ManageEntity this ALOAD_2 // com.aspectivity.mgmt.model.Entity entity INVOKESPECIAL com.aspectivity.mgmt.web.entity.ManageEntity$1.<init> (Lcom/aspectivity/mgmt/web/entity/ManageEntity;Lcom/aspectivity/mgmt/model/Entity;)V INVOKESPECIAL wicket.markup.html.link.PageLink.<init> (Ljava/lang/String;Lwicket/markup/html/link/IPageLink;)V ARETURN end protected wicket.markup.html.link.Link getEditLink(String, com.aspectivity.mgmt.model.Entity) protected wicket.markup.html.link.Link getRemoveLink(String, wicket.markup.html.list.ListItem) org.aspectj.weaver.MethodDeclarationLineNumber: 63:2013 : NEW com.aspectivity.mgmt.web.entity.ManageEntity$2 (line 64) DUP ALOAD_0 // com.aspectivity.mgmt.web.entity.ManageEntity this ALOAD_1 // java.lang.String id ALOAD_2 // wicket.markup.html.list.ListItem item INVOKESPECIAL com.aspectivity.mgmt.web.entity.ManageEntity$2.<init> (Lcom/aspectivity/mgmt/web/entity/ManageEntity;Ljava/lang/String;Lwicket/markup/html/list/ListItem;)V ARETURN end protected wicket.markup.html.link.Link getRemoveLink(String, wicket.markup.html.list.ListItem) private wicket.Component getEditPanel(com.aspectivity.mgmt.model.Entity, boolean, String, String) org.aspectj.weaver.MethodDeclarationLineNumber: 75:2376 : ALOAD_1 // com.aspectivity.mgmt.model.Entity entity (line 77) IFNONNULL L0 ALOAD_3 // java.lang.String addPanelTtile GOTO L1 L0: ALOAD 4 // java.lang.String editPanelTitle L1: ASTORE 5 ALOAD_1 // com.aspectivity.mgmt.model.Entity entity (line 78) IFNONNULL L2 ALOAD_0 // com.aspectivity.mgmt.web.entity.ManageEntity this (line 79) INVOKEVIRTUAL com.aspectivity.mgmt.web.entity.ManageEntity.createNewEntity ()Lcom/aspectivity/mgmt/model/Entity; ASTORE_1 // com.aspectivity.mgmt.model.Entity entity L2: ALOAD_0 // com.aspectivity.mgmt.web.entity.ManageEntity this (line 81) LDC "editEntity" ALOAD 5 // java.lang.String panelTitle ALOAD_1 // com.aspectivity.mgmt.model.Entity entity INVOKEVIRTUAL com.aspectivity.mgmt.web.entity.ManageEntity.createEditPanel (Ljava/lang/String;Ljava/lang/String;Lcom/aspectivity/mgmt/model/Entity;)Lwicket/Component; ARETURN end private wicket.Component getEditPanel(com.aspectivity.mgmt.model.Entity, boolean, String, String) end public abstract class com.aspectivity.mgmt.web.entity.ManageEntity when implementing on shadow constructor-execution(void com.aspectivity.mgmt.web.entity.ManageEntity.<init>(com.aspectivity.mgmt.model.Entity, boolean, java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String)) when weaving type com.aspectivity.mgmt.web.entity.ManageEntity when weaving classes when weaving when batch building BuildConfig[C:\work\projects\workspace\.metadata\.plugins\org.eclipse.ajdt.core\Aspectivity.generated.lst] #Files=87
|
resolved fixed
|
d43e74b
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2005-12-06T03:20:59Z | 2005-11-27T05:40:00Z |
weaver/src/org/aspectj/weaver/patterns/IfPointcut.java
|
/* *******************************************************************
* Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC).
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* PARC initial implementation
* Alexandre Vasseur if() implementation for @AJ style
* ******************************************************************/
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 java.util.Set;
import org.aspectj.bridge.IMessage;
import org.aspectj.lang.JoinPoint;
import org.aspectj.util.FuzzyBoolean;
import org.aspectj.weaver.Advice;
import org.aspectj.weaver.AjcMemberMaker;
import org.aspectj.weaver.ISourceContext;
import org.aspectj.weaver.IntMap;
import org.aspectj.weaver.ResolvedMember;
import org.aspectj.weaver.ResolvedMemberImpl;
import org.aspectj.weaver.ResolvedPointcutDefinition;
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.Expr;
import org.aspectj.weaver.ast.Literal;
import org.aspectj.weaver.ast.Test;
import org.aspectj.weaver.ast.Var;
public class IfPointcut extends Pointcut {
public ResolvedMember testMethod;
public int extraParameterFlags;
/**
* A token source dump that looks like a pointcut (but is NOT parseable at all - just here to help debugging etc)
*/
private String enclosingPointcutHint;
public Pointcut residueSource;
int baseArgsCount;
//XXX some way to compute args
public IfPointcut(ResolvedMember testMethod, int extraParameterFlags) {
this.testMethod = testMethod;
this.extraParameterFlags = extraParameterFlags;
this.pointcutKind = IF;
this.enclosingPointcutHint = null;
}
/**
* No-arg constructor for @AJ style, where the if() body is actually the @Pointcut annotated method
*/
public IfPointcut(String enclosingPointcutHint) {
this.pointcutKind = IF;
this.enclosingPointcutHint = enclosingPointcutHint;
this.testMethod = null;// resolved during concretize
this.extraParameterFlags = -1;//allows to keep track of the @Aj style
}
public Set couldMatchKinds() {
return Shadow.ALL_SHADOW_KINDS;
}
public FuzzyBoolean fastMatch(FastMatchInfo type) {
return FuzzyBoolean.MAYBE;
}
protected FuzzyBoolean matchInternal(Shadow shadow) {
//??? this is not maximally efficient
return FuzzyBoolean.MAYBE;
}
public boolean alwaysFalse() {
return false;
}
public boolean alwaysTrue() {
return false;
}
// enh 76055
public Pointcut getResidueSource() {
return residueSource;
}
public void write(DataOutputStream s) throws IOException {
s.writeByte(Pointcut.IF);
s.writeBoolean(testMethod != null); // do we have a test method?
if (testMethod != null) testMethod.write(s);
s.writeByte(extraParameterFlags);
writeLocation(s);
}
public static Pointcut read(VersionedDataInputStream s, ISourceContext context) throws IOException {
boolean hasTestMethod = s.readBoolean();
ResolvedMember resolvedTestMethod = null;
if (hasTestMethod) { // should always have a test method unless @AJ style
resolvedTestMethod = ResolvedMemberImpl.readResolvedMember(s, context);
}
IfPointcut ret = new IfPointcut(resolvedTestMethod, s.readByte());
ret.readLocation(context, s);
return ret;
}
public void resolveBindings(IScope scope, Bindings bindings) {
//??? all we need is good error messages in here in cflow contexts
}
public boolean equals(Object other) {
if (!(other instanceof IfPointcut)) return false;
IfPointcut o = (IfPointcut)other;
if (o.testMethod==null) return (this.testMethod==null);
return o.testMethod.equals(this.testMethod);
}
public int hashCode() {
int result = 17;
result = 37*result + testMethod.hashCode();
return result;
}
public String toString() {
if (extraParameterFlags < 0) {
//@AJ style
return "if()";
} else {
return "if(" + testMethod + ")";//FIXME AV - bad, this makes it unparsable. Perhaps we can use if() for code style behind the scene!
}
}
//??? The implementation of name binding and type checking in if PCDs is very convoluted
// There has to be a better way...
private boolean findingResidue = false;
// Similar to lastMatchedShadowId - but only for if PCDs.
private int ifLastMatchedShadowId;
private Test ifLastMatchedShadowResidue;
/**
* At each shadow that matched, the residue can be different.
*/
protected Test findResidueInternal(Shadow shadow, ExposedState state) {
if (findingResidue) return Literal.TRUE;
findingResidue = true;
try {
// Have we already been asked this question?
if (shadow.shadowId == ifLastMatchedShadowId) return ifLastMatchedShadowResidue;
Test ret = Literal.TRUE;
List args = new ArrayList();
// code style
if (extraParameterFlags >= 0) {
// If there are no args to sort out, don't bother with the recursive call
if (baseArgsCount > 0) {
ExposedState myState = new ExposedState(baseArgsCount);
//??? we throw out the test that comes from this walk. All we want here
// is bindings for the arguments
residueSource.findResidue(shadow, myState);
for (int i=0; i < baseArgsCount; i++) {
Var v = myState.get(i);
args.add(v);
ret = Test.makeAnd(ret,
Test.makeInstanceof(v,
testMethod.getParameterTypes()[i].resolve(shadow.getIWorld())));
}
}
// handle thisJoinPoint parameters
if ((extraParameterFlags & Advice.ThisJoinPoint) != 0) {
args.add(shadow.getThisJoinPointVar());
}
if ((extraParameterFlags & Advice.ThisJoinPointStaticPart) != 0) {
args.add(shadow.getThisJoinPointStaticPartVar());
}
if ((extraParameterFlags & Advice.ThisEnclosingJoinPointStaticPart) != 0) {
args.add(shadow.getThisEnclosingJoinPointStaticPartVar());
}
} else {
// @style is slightly different
int currentStateIndex = 0;
//FIXME AV - "args(jp)" test(jp, thejp) will fail here
for (int i = 0; i < testMethod.getParameterTypes().length; i++) {
String argSignature = testMethod.getParameterTypes()[i].getSignature();
if (AjcMemberMaker.TYPEX_JOINPOINT.getSignature().equals(argSignature)) {
args.add(shadow.getThisJoinPointVar());
} else if (AjcMemberMaker.TYPEX_PROCEEDINGJOINPOINT.getSignature().equals(argSignature)) {
args.add(shadow.getThisJoinPointVar());
} else if (AjcMemberMaker.TYPEX_STATICJOINPOINT.getSignature().equals(argSignature)) {
args.add(shadow.getThisJoinPointStaticPartVar());
} else if (AjcMemberMaker.TYPEX_ENCLOSINGSTATICJOINPOINT.getSignature().equals(argSignature)) {
args.add(shadow.getThisEnclosingJoinPointStaticPartVar());
} else {
// we don't use i as JoinPoint.* can be anywhere in the signature in @style
Var v = state.get(currentStateIndex++);
args.add(v);
ret = Test.makeAnd(ret,
Test.makeInstanceof(v,
testMethod.getParameterTypes()[i].resolve(shadow.getIWorld())));
}
}
}
ret = Test.makeAnd(ret, Test.makeCall(testMethod, (Expr[])args.toArray(new Expr[args.size()])));
// Remember...
ifLastMatchedShadowId = shadow.shadowId;
ifLastMatchedShadowResidue = ret;
return ret;
} finally {
findingResidue = false;
}
}
// amc - the only reason this override seems to be here is to stop the copy, but
// that can be prevented by overriding shouldCopyLocationForConcretization,
// allowing me to make the method final in Pointcut.
// public Pointcut concretize(ResolvedType inAspect, IntMap bindings) {
// return this.concretize1(inAspect, bindings);
// }
protected boolean shouldCopyLocationForConcretize() {
return false;
}
private IfPointcut partiallyConcretized = null;
public Pointcut concretize1(ResolvedType inAspect, ResolvedType declaringType, IntMap bindings) {
//System.err.println("concretize: " + this + " already: " + partiallyConcretized);
if (isDeclare(bindings.getEnclosingAdvice())) {
// Enforce rule about which designators are supported in declare
inAspect.getWorld().showMessage(IMessage.ERROR,
WeaverMessages.format(WeaverMessages.IF_IN_DECLARE),
bindings.getEnclosingAdvice().getSourceLocation(),
null);
return Pointcut.makeMatchesNothing(Pointcut.CONCRETE);
}
if (partiallyConcretized != null) {
return partiallyConcretized;
}
final IfPointcut ret;
if (extraParameterFlags < 0 && testMethod == null) {
// @AJ style, we need to find the testMethod in the aspect defining the "if()" enclosing pointcut
ResolvedPointcutDefinition def = bindings.peekEnclosingDefinition();
if (def != null) {
ResolvedType aspect = inAspect.getWorld().resolve(def.getDeclaringType());
for (Iterator memberIter = aspect.getMethods(); memberIter.hasNext();) {
ResolvedMember method = (ResolvedMember) memberIter.next();
if (def.getName().equals(method.getName())
&& def.getParameterTypes().length == method.getParameterTypes().length) {
boolean sameSig = true;
for (int j = 0; j < method.getParameterTypes().length; j++) {
UnresolvedType argJ = method.getParameterTypes()[j];
if (!argJ.equals(def.getParameterTypes()[j])) {
sameSig = false;
break;
}
}
if (sameSig) {
testMethod = method;
break;
}
}
}
if (testMethod == null) {
inAspect.getWorld().showMessage(
IMessage.ERROR,
"Cannot find if() body from '" + def.toString() + "' for '" + enclosingPointcutHint + "'",
this.getSourceLocation(),
null
);
return Pointcut.makeMatchesNothing(Pointcut.CONCRETE);
}
} else {
testMethod = inAspect.getWorld().resolve(bindings.getAdviceSignature());
}
ret = new IfPointcut(enclosingPointcutHint);
ret.testMethod = testMethod;
} else {
ret = new IfPointcut(testMethod, extraParameterFlags);
}
ret.copyLocationFrom(this);
partiallyConcretized = ret;
// It is possible to directly code your pointcut expression in a per clause
// rather than defining a pointcut declaration and referencing it in your
// per clause. If you do this, we have problems (bug #62458). For now,
// let's police that you are trying to code a pointcut in a per clause and
// put out a compiler error.
if (bindings.directlyInAdvice() && bindings.getEnclosingAdvice()==null) {
// Assumption: if() is in a per clause if we say we are directly in advice
// but we have no enclosing advice.
inAspect.getWorld().showMessage(IMessage.ERROR,
WeaverMessages.format(WeaverMessages.IF_IN_PERCLAUSE),
this.getSourceLocation(),null);
return Pointcut.makeMatchesNothing(Pointcut.CONCRETE);
}
if (bindings.directlyInAdvice()) {
ShadowMunger advice = bindings.getEnclosingAdvice();
if (advice instanceof Advice) {
ret.baseArgsCount = ((Advice)advice).getBaseParameterCount();
} else {
ret.baseArgsCount = 0;
}
ret.residueSource = advice.getPointcut().concretize(inAspect, inAspect, ret.baseArgsCount, advice);
} else {
ResolvedPointcutDefinition def = bindings.peekEnclosingDefinition();
if (def == CflowPointcut.CFLOW_MARKER) {
inAspect.getWorld().showMessage(IMessage.ERROR,
WeaverMessages.format(WeaverMessages.IF_LEXICALLY_IN_CFLOW),
getSourceLocation(), null);
return Pointcut.makeMatchesNothing(Pointcut.CONCRETE);
}
ret.baseArgsCount = def.getParameterTypes().length;
// for @style, we have implicit binding for JoinPoint.* things
//FIXME AV - will lead to failure for "args(jp)" test(jp, thejp) / see args() implementation
if (ret.extraParameterFlags < 0) {
ret.baseArgsCount = 0;
for (int i = 0; i < testMethod.getParameterTypes().length; i++) {
String argSignature = testMethod.getParameterTypes()[i].getSignature();
if (AjcMemberMaker.TYPEX_JOINPOINT.getSignature().equals(argSignature)
|| AjcMemberMaker.TYPEX_PROCEEDINGJOINPOINT.getSignature().equals(argSignature)
|| AjcMemberMaker.TYPEX_STATICJOINPOINT.getSignature().equals(argSignature)
|| AjcMemberMaker.TYPEX_ENCLOSINGSTATICJOINPOINT.getSignature().equals(argSignature)) {
;
} else {
ret.baseArgsCount++;
}
}
}
IntMap newBindings = IntMap.idMap(ret.baseArgsCount);
newBindings.copyContext(bindings);
ret.residueSource = def.getPointcut().concretize(inAspect, declaringType, newBindings);
}
return ret;
}
// we can't touch "if" methods
public Pointcut parameterizeWith(Map typeVariableMap) {
return this;
}
// public static Pointcut MatchesNothing = new MatchesNothingPointcut();
// ??? there could possibly be some good optimizations to be done at this point
public static IfPointcut makeIfFalsePointcut(State state) {
IfPointcut ret = new IfFalsePointcut();
ret.state = state;
return ret;
}
public Object accept(PatternNodeVisitor visitor, Object data) {
return visitor.visit(this, data);
}
public static class IfFalsePointcut extends IfPointcut {
public IfFalsePointcut() {
super(null,0);
this.pointcutKind = Pointcut.IF_FALSE;
}
public Set couldMatchKinds() {
return Collections.EMPTY_SET;
}
public boolean alwaysFalse() {
return true;
}
protected Test findResidueInternal(Shadow shadow, ExposedState state) {
return Literal.FALSE; // can only get here if an earlier error occurred
}
public FuzzyBoolean fastMatch(FastMatchInfo type) {
return FuzzyBoolean.NO;
}
protected FuzzyBoolean matchInternal(Shadow shadow) {
return FuzzyBoolean.NO;
}
public FuzzyBoolean match(JoinPoint.StaticPart jpsp) {
return FuzzyBoolean.NO;
}
public void resolveBindings(IScope scope, Bindings bindings) {
}
public void postRead(ResolvedType enclosingType) {
}
public Pointcut concretize1(
ResolvedType inAspect,
ResolvedType declaringType,
IntMap bindings) {
if (isDeclare(bindings.getEnclosingAdvice())) {
// Enforce rule about which designators are supported in declare
inAspect.getWorld().showMessage(IMessage.ERROR,
WeaverMessages.format(WeaverMessages.IF_IN_DECLARE),
bindings.getEnclosingAdvice().getSourceLocation(),
null);
return Pointcut.makeMatchesNothing(Pointcut.CONCRETE);
}
return makeIfFalsePointcut(state);
}
public void write(DataOutputStream s) throws IOException {
s.writeByte(Pointcut.IF_FALSE);
}
public int hashCode() {
int result = 17;
return result;
}
public String toString() {
return "if(false)";
}
}
public static IfPointcut makeIfTruePointcut(State state) {
IfPointcut ret = new IfTruePointcut();
ret.state = state;
return ret;
}
public static class IfTruePointcut extends IfPointcut {
public IfTruePointcut() {
super(null,0);
this.pointcutKind = Pointcut.IF_TRUE;
}
public boolean alwaysTrue() {
return true;
}
protected Test findResidueInternal(Shadow shadow, ExposedState state) {
return Literal.TRUE; // can only get here if an earlier error occurred
}
public FuzzyBoolean fastMatch(FastMatchInfo type) {
return FuzzyBoolean.YES;
}
protected FuzzyBoolean matchInternal(Shadow shadow) {
return FuzzyBoolean.YES;
}
public FuzzyBoolean match(JoinPoint.StaticPart jpsp) {
return FuzzyBoolean.YES;
}
public void resolveBindings(IScope scope, Bindings bindings) {
}
public void postRead(ResolvedType enclosingType) {
}
public Pointcut concretize1(
ResolvedType inAspect,
ResolvedType declaringType,
IntMap bindings) {
if (isDeclare(bindings.getEnclosingAdvice())) {
// Enforce rule about which designators are supported in declare
inAspect.getWorld().showMessage(IMessage.ERROR,
WeaverMessages.format(WeaverMessages.IF_IN_DECLARE),
bindings.getEnclosingAdvice().getSourceLocation(),
null);
return Pointcut.makeMatchesNothing(Pointcut.CONCRETE);
}
return makeIfTruePointcut(state);
}
public void write(DataOutputStream s) throws IOException {
s.writeByte(IF_TRUE);
}
public int hashCode() {
int result = 37;
return result;
}
public String toString() {
return "if(true)";
}
}
}
|
118,715 |
Bug 118715 Load Time Weaving wipes out Xlint files if no Xlint values
|
In ClassLoaderWeavingAdaptor if weaverOption.lint is null, then a loaded Xlint properties file gets overwritten by the default Xlint properties. See attached patch to fix this problem.
|
resolved fixed
|
1e1bbb3
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2005-12-06T13:02:38Z | 2005-11-30T22:33:20Z |
loadtime/src/org/aspectj/weaver/loadtime/ClassLoaderWeavingAdaptor.java
|
/*******************************************************************************
* Copyright (c) 2005 Contributors.
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Eclipse Public License v1.0
* which accompanies this distribution and is available at
* http://eclipse.org/legal/epl-v10.html
*
* Contributors:
* Alexandre Vasseur initial implementation
* David Knibb weaving context enhancments
*******************************************************************************/
package org.aspectj.weaver.loadtime;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
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.IMessage;
import org.aspectj.bridge.ISourceLocation;
import org.aspectj.bridge.Message;
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;
}
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();
}
Aj.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, messageHandler, new ICrossReferenceHandler() {
public void addCrossReference(ISourceLocation from, ISourceLocation to, IRelationship.Kind kind, boolean runtimeTest) {
;// for tools only
}
}
);
// //TODO this AJ code will call
// //org.aspectj.apache.bcel.Repository.setRepository(this);
// //ie set some static things
// //==> bogus as Bcel is expected to be
// org.aspectj.apache.bcel.Repository.setRepository(new ClassLoaderRepository(loader));
weaver = new BcelWeaver(bcelWorld);
// register the definitions
registerDefinitions(weaver, loader, definitions);
messageHandler = bcelWorld.getMessageHandler();
//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);
}
}
private String getClassLoaderName (ClassLoader loader) {
return weavingContext.getClassLoaderName();
}
/**
* Configure the weaver according to the option directives
* TODO av - don't know if it is that good to reuse, since we only allow a small subset of options in LTW
*
* @param weaver
* @param loader
* @param definitions
*/
private void registerOptions(final BcelWeaver weaver, final ClassLoader loader, final List definitions) {
StringBuffer allOptions = new StringBuffer();
for (Iterator iterator = definitions.iterator(); iterator.hasNext();) {
Definition definition = (Definition) iterator.next();
allOptions.append(definition.getWeaverOptions()).append(' ');
}
Options.WeaverOption weaverOption = Options.parse(allOptions.toString(), loader, messageHandler);
// configure the weaver and world
// AV - code duplicates AspectJBuilder.initWorldAndWeaver()
World world = weaver.getWorld();
world.setMessageHandler(weaverOption.messageHandler);
world.setXlazyTjp(weaverOption.lazyTjp);
world.setXHasMemberSupportEnabled(weaverOption.hasMember);
world.setPinpointMode(weaverOption.pinpoint);
weaver.setReweavableMode(weaverOption.notReWeavable);
world.setXnoInline(weaverOption.noInline);
// AMC - autodetect as per line below, needed for AtAjLTWTests.testLTWUnweavable
world.setBehaveInJava5Way(LangUtil.is15VMOrGreater());
//-Xlintfile: first so that lint wins
if (weaverOption.lintFile != null) {
InputStream resource = null;
try {
resource = loader.getResourceAsStream(weaverOption.lintFile);
Exception failure = null;
if (resource != null) {
try {
Properties properties = new Properties();
properties.load(resource);
world.getLint().setFromProperties(properties);
} catch (IOException e) {
failure = e;
}
}
if (failure != null || resource == null) {
world.getMessageHandler().handleMessage(new Message(
"Cannot access resource for -Xlintfile:"+weaverOption.lintFile,
IMessage.WARNING,
failure,
null));
}
} finally {
try { resource.close(); } catch (Throwable t) {;}
}
}
if (weaverOption.lint == null) {
bcelWorld.getLint().loadDefaultProperties();
bcelWorld.getLint().adviceDidNotMatch.setKind(IMessage.INFO);
} else {
if (weaverOption.lint.equals("default")) {//FIXME should be AjBuildConfig.AJLINT_DEFAULT but yetanother deps..
bcelWorld.getLint().loadDefaultProperties();
} else {
bcelWorld.getLint().setAll(weaverOption.lint);
}
}
//TODO proceedOnError option
}
private void registerAspectExclude(final BcelWeaver weaver, final ClassLoader loader, final List definitions) {
String fastMatchInfo = null;
for (Iterator iterator = definitions.iterator(); iterator.hasNext();) {
Definition definition = (Definition) iterator.next();
for (Iterator iterator1 = definition.getAspectExcludePatterns().iterator(); iterator1.hasNext();) {
String exclude = (String) iterator1.next();
TypePattern excludePattern = new PatternParser(exclude).parseTypePattern();
m_aspectExcludeTypePattern.add(excludePattern);
fastMatchInfo = looksLikeStartsWith(exclude);
if (fastMatchInfo != null) {
m_aspectExcludeStartsWith.add(fastMatchInfo);
}
}
}
}
private void registerAspectInclude(final BcelWeaver weaver, final ClassLoader loader, final List definitions) {
String fastMatchInfo = null;
for (Iterator iterator = definitions.iterator(); iterator.hasNext();) {
Definition definition = (Definition) iterator.next();
for (Iterator iterator1 = definition.getAspectIncludePatterns().iterator(); iterator1.hasNext();) {
String include = (String) iterator1.next();
TypePattern includePattern = new PatternParser(include).parseTypePattern();
m_aspectIncludeTypePattern.add(includePattern);
fastMatchInfo = looksLikeStartsWith(include);
if (fastMatchInfo != null) {
m_aspectIncludeStartsWith.add(fastMatchInfo);
}
}
}
}
protected void lint (String name, String[] infos) {
Lint lint = bcelWorld.getLint();
Kind kind = lint.getLintKind(name);
kind.signal(infos,null,null);
}
/**
* Register the aspect, following include / exclude rules
*
* @param weaver
* @param loader
* @param definitions
*/
private void registerAspects(final BcelWeaver weaver, final ClassLoader loader, final List definitions) {
//TODO: the exclude aspect allow to exclude aspect defined upper in the CL hierarchy - is it what we want ??
// if not, review the getResource so that we track which resource is defined by which CL
//iterate aspectClassNames
//exclude if in any of the exclude list
for (Iterator iterator = definitions.iterator(); iterator.hasNext();) {
Definition definition = (Definition) iterator.next();
for (Iterator aspects = definition.getAspectClassNames().iterator(); aspects.hasNext();) {
String aspectClassName = (String) aspects.next();
if (acceptAspect(aspectClassName)) {
info("register aspect " + aspectClassName);
/*ResolvedType aspect = */weaver.addLibraryAspect(aspectClassName);
//generate key for SC
if(namespace==null){
namespace=new StringBuffer(aspectClassName);
}else{
namespace = namespace.append(";"+aspectClassName);
}
}
else {
// warn("aspect excluded: " + aspectClassName);
lint("aspectExcludedByConfiguration", new String[] { aspectClassName, getClassLoaderName(loader) });
}
}
}
//iterate concreteAspects
//exclude if in any of the exclude list - note that the user defined name matters for that to happen
for (Iterator iterator = definitions.iterator(); iterator.hasNext();) {
Definition definition = (Definition) iterator.next();
for (Iterator aspects = definition.getConcreteAspects().iterator(); aspects.hasNext();) {
Definition.ConcreteAspect concreteAspect = (Definition.ConcreteAspect) aspects.next();
if (acceptAspect(concreteAspect.name)) {
ConcreteAspectCodeGen gen = new ConcreteAspectCodeGen(concreteAspect, weaver.getWorld());
if (!gen.validate()) {
error("Concrete-aspect '"+concreteAspect.name+"' could not be registered");
break;
}
this.generatedClassHandler.acceptClass(
concreteAspect.name,
gen.getBytes()
);
/*ResolvedType aspect = */weaver.addLibraryAspect(concreteAspect.name);
//generate key for SC
if(namespace==null){
namespace=new StringBuffer(concreteAspect.name);
}else{
namespace = namespace.append(";"+concreteAspect.name);
}
}
}
}
}
/**
* Register the include / exclude filters
* We duplicate simple patterns in startWith filters that will allow faster matching without ResolvedType
*
* @param weaver
* @param loader
* @param definitions
*/
private void registerIncludeExclude(final BcelWeaver weaver, final ClassLoader loader, final List definitions) {
String fastMatchInfo = null;
for (Iterator iterator = definitions.iterator(); iterator.hasNext();) {
Definition definition = (Definition) iterator.next();
for (Iterator iterator1 = definition.getIncludePatterns().iterator(); iterator1.hasNext();) {
String include = (String) iterator1.next();
TypePattern includePattern = new PatternParser(include).parseTypePattern();
m_includeTypePattern.add(includePattern);
fastMatchInfo = looksLikeStartsWith(include);
if (fastMatchInfo != null) {
m_includeStartsWith.add(fastMatchInfo);
}
}
for (Iterator iterator1 = definition.getExcludePatterns().iterator(); iterator1.hasNext();) {
String exclude = (String) iterator1.next();
TypePattern excludePattern = new PatternParser(exclude).parseTypePattern();
m_excludeTypePattern.add(excludePattern);
fastMatchInfo = looksLikeStartsWith(exclude);
if (fastMatchInfo != null) {
m_excludeStartsWith.add(fastMatchInfo);
}
}
}
}
/**
* Checks if the type pattern can be handled as a startswith check
*
* TODO AV - enhance to support "char.sss" ie FQN direclty (match iff equals)
* we could also add support for "*..*charss" endsWith style?
*
* @param typePattern
* @return null if not possible, or the startWith sequence to test against
*/
private String looksLikeStartsWith(String typePattern) {
if (typePattern.indexOf('@') >= 0
|| typePattern.indexOf('+') >= 0
|| typePattern.indexOf(' ') >= 0
|| typePattern.charAt(typePattern.length()-1) != '*') {
return null;
}
// now must looks like with "charsss..*" or "cha.rss..*" etc
// note that "*" and "*..*" won't be fast matched
// and that "charsss.*" will not neither
int length = typePattern.length();
if (typePattern.endsWith("..*") && length > 3) {
if (typePattern.indexOf("..") == length-3 // no ".." before last sequence
&& typePattern.indexOf('*') == length-1) { // no "*" before last sequence
return typePattern.substring(0, length-2).replace('$', '.');
// ie "charsss." or "char.rss." etc
}
}
return null;
}
/**
* Register the dump filter
*
* @param weaver
* @param loader
* @param definitions
*/
private void registerDump(final BcelWeaver weaver, final ClassLoader loader, final List definitions) {
for (Iterator iterator = definitions.iterator(); iterator.hasNext();) {
Definition definition = (Definition) iterator.next();
for (Iterator iterator1 = definition.getDumpPatterns().iterator(); iterator1.hasNext();) {
String dump = (String) iterator1.next();
TypePattern pattern = new PatternParser(dump).parseTypePattern();
m_dumpTypePattern.add(pattern);
}
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;
}
}
boolean fastAccept = false;//defaults to false if no fast include
for (int i = 0; i < m_includeStartsWith.size(); i++) {
fastAccept = fastClassName.startsWith((String)m_includeStartsWith.get(i));
if (fastAccept) {
break;
}
}
if (fastAccept) {
return true;
}
// needs further analysis
// TODO AV - needs refactoring
// during LTW this calling resolve at that stage is BAD as we do have the bytecode from the classloader hook
// but still go thru resolve that will do a getResourcesAsStream on disk
// this is also problematic for jit stub which are not on disk - as often underlying infra
// does returns null or some other info for getResourceAsStream (f.e. WLS 9 CR248491)
// Instead I parse the given bytecode. But this also means it will be parsed again in
// new WeavingClassFileProvider() from WeavingAdaptor.getWovenBytes()...
BcelObjectType bct = ((BcelWorld)weaver.getWorld()).addSourceObjectType(Utility.makeJavaClass(null, bytes));
ResolvedType classInfo = bct.getResolvedTypeX();//BAD: weaver.getWorld().resolve(UnresolvedType.forName(className), true);
//exclude are "AND"ed
for (Iterator iterator = m_excludeTypePattern.iterator(); iterator.hasNext();) {
TypePattern typePattern = (TypePattern) iterator.next();
if (typePattern.matchesStatically(classInfo)) {
// exclude match - skip
return false;
}
}
//include are "OR"ed
boolean accept = true;//defaults to true if no include
for (Iterator iterator = m_includeTypePattern.iterator(); iterator.hasNext();) {
TypePattern typePattern = (TypePattern) iterator.next();
accept = typePattern.matchesStatically(classInfo);
if (accept) {
break;
}
// goes on if this include did not match ("OR"ed)
}
return accept;
}
//FIXME we don't use include/exclude of others aop.xml
//this can be nice but very dangerous as well to change that
private boolean acceptAspect(String aspectClassName) {
// avoid ResolvedType if not needed
if (m_aspectExcludeTypePattern.isEmpty() && m_aspectIncludeTypePattern.isEmpty()) {
return true;
}
// still try to avoid ResolvedType if we have simple patterns
// EXCLUDE: if one match then reject
String fastClassName = aspectClassName.replace('/', '.').replace('.', '$');
for (int i = 0; i < m_aspectExcludeStartsWith.size(); i++) {
if (fastClassName.startsWith((String)m_aspectExcludeStartsWith.get(i))) {
return false;
}
}
//INCLUDE: if one match then accept
for (int i = 0; i < m_aspectIncludeStartsWith.size(); i++) {
if (fastClassName.startsWith((String)m_aspectIncludeStartsWith.get(i))) {
return true;
}
}
// needs further analysis
ResolvedType classInfo = weaver.getWorld().resolve(UnresolvedType.forName(aspectClassName), true);
//exclude are "AND"ed
for (Iterator iterator = m_aspectExcludeTypePattern.iterator(); iterator.hasNext();) {
TypePattern typePattern = (TypePattern) iterator.next();
if (typePattern.matchesStatically(classInfo)) {
// exclude match - skip
return false;
}
}
//include are "OR"ed
boolean accept = true;//defaults to true if no include
for (Iterator iterator = m_aspectIncludeTypePattern.iterator(); iterator.hasNext();) {
TypePattern typePattern = (TypePattern) iterator.next();
accept = typePattern.matchesStatically(classInfo);
if (accept) {
break;
}
// goes on if this include did not match ("OR"ed)
}
return accept;
}
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();
}
}
|
118,715 |
Bug 118715 Load Time Weaving wipes out Xlint files if no Xlint values
|
In ClassLoaderWeavingAdaptor if weaverOption.lint is null, then a loaded Xlint properties file gets overwritten by the default Xlint properties. See attached patch to fix this problem.
|
resolved fixed
|
1e1bbb3
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2005-12-06T13:02:38Z | 2005-11-30T22:33:20Z |
testing/newsrc/org/aspectj/testing/OutputSpec.java
|
/* *******************************************************************
* Copyright (c) 2005 IBM Corporation
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* Adrian Colyer,
* ******************************************************************/
package org.aspectj.testing;
import java.util.Iterator;
import java.util.List;
import java.util.ArrayList;
import java.util.StringTokenizer;
import org.aspectj.tools.ajc.AjcTestCase;
public class OutputSpec {
private List expectedOutputLines = new ArrayList();
public void addLine(OutputLine line) {
expectedOutputLines.add(line.getText());
}
public void matchAgainst(String output) {
boolean matches = false;
int lineNo = 0;
StringTokenizer strTok = new StringTokenizer(output,"\n");
if (strTok.countTokens() == expectedOutputLines.size()) {
matches = true;
for (Iterator iter = expectedOutputLines.iterator(); iter.hasNext();) {
String line = (String) iter.next();
lineNo++;
String outputLine = strTok.nextToken().trim();
if (!line.equals(outputLine)) {
matches = false;
break;
}
}
}
if (!matches) {
StringBuffer failMessage = new StringBuffer();
failMessage.append("Expecting output:\n");
for (Iterator iter = expectedOutputLines.iterator(); iter.hasNext();) {
String line = (String) iter.next();
failMessage.append(line);
failMessage.append("\n");
}
failMessage.append("But found output:\n");
failMessage.append(output);
failMessage.append("\n");
failMessage.append("First difference is on line " + lineNo);
failMessage.append("\n");
AjcTestCase.fail(failMessage.toString());
}
}
}
|
118,715 |
Bug 118715 Load Time Weaving wipes out Xlint files if no Xlint values
|
In ClassLoaderWeavingAdaptor if weaverOption.lint is null, then a loaded Xlint properties file gets overwritten by the default Xlint properties. See attached patch to fix this problem.
|
resolved fixed
|
1e1bbb3
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2005-12-06T13:02:38Z | 2005-11-30T22:33:20Z |
testing/newsrc/org/aspectj/testing/RunSpec.java
|
/* *******************************************************************
* Copyright (c) 2004 IBM Corporation
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* Adrian Colyer,
* ******************************************************************/
package org.aspectj.testing;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;
import org.aspectj.tools.ajc.AjcTestCase;
import org.aspectj.util.FileUtil;
/**
* @author colyer
*
* TODO To change the template for this generated type comment go to
* Window - Preferences - Java - Code Style - Code Templates
*/
public class RunSpec implements ITestStep {
private List expected = new ArrayList();
private String classToRun;
private String baseDir;
private String options;
private String cpath;
private AjcTest myTest;
private OutputSpec stdErrSpec;
private OutputSpec stdOutSpec;
private String ltwFile;
public RunSpec() {
}
/* (non-Javadoc)
* @see org.aspectj.testing.ITestStep#execute(org.aspectj.tools.ajc.AjcTestCase)
*/
public void execute(AjcTestCase inTestCase) {
if (!expected.isEmpty()) {
System.err.println("Warning, message spec for run command is currently ignored (org.aspectj.testing.RunSpec)");
}
String[] args = buildArgs();
// System.err.println("? execute() inTestCase='" + inTestCase + "', ltwFile=" + ltwFile);
boolean useLtw = copyLtwFile(inTestCase.getSandboxDirectory());
AjcTestCase.RunResult rr = inTestCase.run(getClassToRun(),args,getClasspath(),useLtw);
if (stdErrSpec != null) {
stdErrSpec.matchAgainst(rr.getStdErr());
}
if (stdOutSpec != null) {
stdOutSpec.matchAgainst(rr.getStdOut());
}
}
public void addExpectedMessage(ExpectedMessageSpec message) {
expected.add(message);
}
public void setBaseDir(String dir) {
this.baseDir = dir;
}
public void setTest(AjcTest test) {
this.myTest = test;
}
public String getOptions() {
return options;
}
public void setOptions(String options) {
this.options = options;
}
public String getClasspath() {
if (cpath == null) return null;
return this.cpath.replace('/', File.separatorChar);
}
public void setClasspath(String cpath) {
this.cpath = cpath;
}
public void addStdErrSpec(OutputSpec spec) {
this.stdErrSpec = spec;
}
public void addStdOutSpec(OutputSpec spec) {
this.stdOutSpec = spec;
}
/**
* @return Returns the classToRun.
*/
public String getClassToRun() {
return classToRun;
}
/**
* @param classToRun The classToRun to set.
*/
public void setClassToRun(String classToRun) {
this.classToRun = classToRun;
}
public String getLtwFile() {
return ltwFile;
}
public void setLtwFile(String ltwFile) {
this.ltwFile = ltwFile;
}
private String[] buildArgs() {
if (options == null) return new String[0];
StringTokenizer strTok = new StringTokenizer(options,",");
String[] ret = new String[strTok.countTokens()];
for (int i = 0; i < ret.length; i++) {
ret[i] = strTok.nextToken();
}
return ret;
}
private boolean copyLtwFile (File sandboxDirectory) {
boolean useLtw = false;
if (ltwFile != null) {
// TODO maw use flag rather than empty file name
if (ltwFile.trim().length() == 0) return true;
File from = new File(baseDir,ltwFile);
File to = new File(sandboxDirectory,"META-INF" + File.separator + "aop.xml");
// System.out.println("RunSpec.copyLtwFile() from=" + from.getAbsolutePath() + " to=" + to.getAbsolutePath());
try {
FileUtil.copyFile(from,to);
useLtw = true;
}
catch (IOException ex) {
AjcTestCase.fail(ex.toString());
}
}
return useLtw;
}
}
|
118,715 |
Bug 118715 Load Time Weaving wipes out Xlint files if no Xlint values
|
In ClassLoaderWeavingAdaptor if weaverOption.lint is null, then a loaded Xlint properties file gets overwritten by the default Xlint properties. See attached patch to fix this problem.
|
resolved fixed
|
1e1bbb3
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2005-12-06T13:02:38Z | 2005-11-30T22:33:20Z |
testing/newsrc/org/aspectj/testing/XMLBasedAjcTestCase.java
|
/* *******************************************************************
* Copyright (c) 2004 IBM Corporation
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* Adrian Colyer,
* ******************************************************************/
package org.aspectj.testing;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;
import java.util.Stack;
import junit.extensions.TestSetup;
import junit.framework.Test;
import junit.framework.TestSuite;
import org.apache.commons.digester.Digester;
import org.aspectj.tools.ajc.AjcTestCase;
import org.aspectj.tools.ajc.CompilationResult;
import org.aspectj.util.FileUtil;
/**
* Root class for all Test suites that are based on an AspectJ XML test suite
* file. Extends AjcTestCase allowing a mix of programmatic and spec-file
* driven testing. See org.aspectj.systemtest.incremental.IncrementalTests for
* an example of this mixed style.
* <p>The class org.aspectj.testing.MakeTestClass will generate a subclass of
* this class for you, given a suite spec. file as input...</p>
*/
public abstract class XMLBasedAjcTestCase extends AjcTestCase {
private static Map testMap = new HashMap();
private static boolean suiteLoaded = false;
private AjcTest currentTest = null;
private Stack clearTestAfterRun = new Stack();
public XMLBasedAjcTestCase() {
}
/**
* You must define a suite() method in subclasses, and return
* the result of calling this method. (Don't you hate static
* methods in programming models). For example:
* <pre>
* public static Test suite() {
* return XMLBasedAjcTestCase.loadSuite(MyTestCaseClass.class);
* }
* </pre>
* @param testCaseClass
* @return
*/
public static Test loadSuite(Class testCaseClass) {
TestSuite suite = new TestSuite(testCaseClass.getName());
suite.addTestSuite(testCaseClass);
TestSetup wrapper = new TestSetup(suite) {
/* (non-Javadoc)
* @see junit.extensions.TestSetup#setUp()
*/
protected void setUp() throws Exception {
super.setUp();
suiteLoaded = false;
}
/* (non-Javadoc)
* @see junit.extensions.TestSetup#tearDown()
*/
protected void tearDown() throws Exception {
super.tearDown();
suiteLoaded = false;
}
};
return wrapper;
}
/**
* The file containing the XML specification for the tests.
*/
protected abstract File getSpecFile();
/*
* Return a map from (String) test title -> AjcTest
*/
protected Map getSuiteTests() {
return testMap;
}
/**
* This helper method runs the test with the given title in the
* suite spec file. All tests steps in given ajc-test execute
* in the same sandbox.
*/
protected void runTest(String title) {
currentTest = (AjcTest) testMap.get(title);
final boolean clearTest = clearTestAfterRun();
if (currentTest == null) {
if (clearTest) {
System.err.println("test already run: " + title);
return;
} else {
fail("No test '" + title + "' in suite.");
}
}
ajc.setShouldEmptySandbox(true);
currentTest.runTest(this);
if (clearTest) {
testMap.remove(title);
}
}
/**
* Get the currently executing test. Useful for access to e.g.
* AjcTest.getTitle() etc..
*/
protected AjcTest getCurrentTest() {
return currentTest;
}
/**
* For use by the Digester. As the XML document is parsed, it creates instances
* of AjcTest objects, which are added to this TestCase by the Digester by
* calling this method.
*/
public void addTest(AjcTest test) {
testMap.put(test.getTitle(),test);
}
protected final void pushClearTestAfterRun(boolean val) {
clearTestAfterRun.push(val ? Boolean.FALSE: Boolean.TRUE);
}
protected final boolean popClearTestAfterRun() {
return clearTest(true);
}
protected final boolean clearTestAfterRun() {
return clearTest(false);
}
private boolean clearTest(boolean pop) {
if (clearTestAfterRun.isEmpty()) {
return false;
}
boolean result = ((Boolean) clearTestAfterRun.peek()).booleanValue();
if (pop) {
clearTestAfterRun.pop();
}
return result;
}
/*
* The rules for parsing a suite spec file. The Digester using bean properties to match attributes
* in the XML document to properties in the associated classes, so this simple implementation should
* be very easy to maintain and extend should you ever need to.
*/
protected Digester getDigester() {
Digester digester = new Digester();
digester.push(this);
digester.addObjectCreate("suite/ajc-test",AjcTest.class);
digester.addSetProperties("suite/ajc-test");
digester.addSetNext("suite/ajc-test","addTest","org.aspectj.testing.AjcTest");
digester.addObjectCreate("suite/ajc-test/compile",CompileSpec.class);
digester.addSetProperties("suite/ajc-test/compile");
digester.addSetNext("suite/ajc-test/compile","addTestStep","org.aspectj.testing.ITestStep");
digester.addObjectCreate("suite/ajc-test/run",RunSpec.class);
digester.addSetProperties("suite/ajc-test/run","class","classToRun");
digester.addSetProperties("suite/ajc-test/run","ltw","ltwFile");
digester.addSetNext("suite/ajc-test/run","addTestStep","org.aspectj.testing.ITestStep");
digester.addObjectCreate("*/message",ExpectedMessageSpec.class);
digester.addSetProperties("*/message");
digester.addSetNext("*/message","addExpectedMessage","org.aspectj.testing.ExpectedMessageSpec");
digester.addObjectCreate("suite/ajc-test/weave",WeaveSpec.class);
digester.addSetProperties("suite/ajc-test/weave");
digester.addSetNext("suite/ajc-test/weave","addTestStep","org.aspectj.testing.ITestStep");
digester.addObjectCreate("suite/ajc-test/ant",AntSpec.class);
digester.addSetProperties("suite/ajc-test/ant");
digester.addSetNext("suite/ajc-test/ant","addTestStep","org.aspectj.testing.ITestStep");
digester.addObjectCreate("suite/ajc-test/ant/stderr",OutputSpec.class);
digester.addSetProperties("suite/ajc-test/ant/stderr");
digester.addSetNext("suite/ajc-test/ant/stderr","addStdErrSpec","org.aspectj.testing.OutputSpec");
digester.addObjectCreate("suite/ajc-test/ant/stdout",OutputSpec.class);
digester.addSetProperties("suite/ajc-test/ant/stdout");
digester.addSetNext("suite/ajc-test/ant/stdout","addStdOutSpec","org.aspectj.testing.OutputSpec");
digester.addObjectCreate("suite/ajc-test/run/stderr",OutputSpec.class);
digester.addSetProperties("suite/ajc-test/run/stderr");
digester.addSetNext("suite/ajc-test/run/stderr","addStdErrSpec","org.aspectj.testing.OutputSpec");
digester.addObjectCreate("suite/ajc-test/run/stdout",OutputSpec.class);
digester.addSetProperties("suite/ajc-test/run/stdout");
digester.addSetNext("suite/ajc-test/run/stdout","addStdOutSpec","org.aspectj.testing.OutputSpec");
digester.addObjectCreate("*/line",OutputLine.class);
digester.addSetProperties("*/line");
digester.addSetNext("*/line","addLine","org.aspectj.testing.OutputLine");
return digester;
}
/* (non-Javadoc)
* @see org.aspectj.tools.ajc.AjcTestCase#setUp()
*/
protected void setUp() throws Exception {
super.setUp();
if (!suiteLoaded) {
testMap = new HashMap();
System.out.println("LOADING SUITE: " + getSpecFile().getPath());
Digester d = getDigester();
try {
InputStreamReader isr = new InputStreamReader(new FileInputStream(getSpecFile()));
d.parse(isr);
} catch (Exception ex) {
fail("Unable to load suite " + getSpecFile().getPath() + " : " + ex);
}
suiteLoaded = true;
}
}
protected long nextIncrement(boolean doWait) {
long time = System.currentTimeMillis();
if (doWait) {
try {
Thread.sleep(1000);
} catch (InterruptedException intEx) {}
}
return time;
}
protected void copyFile(String from, String to) throws Exception {
String dir = getCurrentTest().getDir();
FileUtil.copyFile(new File(dir + File.separator + from),
new File(ajc.getSandboxDirectory(),to));
}
protected void copyFileAndDoIncrementalBuild(String from, String to) throws Exception {
copyFile(from,to);
CompilationResult result = ajc.doIncrementalCompile();
assertNoMessages(result,"Expected clean compile from test '" + getCurrentTest().getTitle() + "'");
}
protected void copyFileAndDoIncrementalBuild(String from, String to, MessageSpec expectedResults) throws Exception {
String dir = getCurrentTest().getDir();
FileUtil.copyFile(new File(dir + File.separator + from),
new File(ajc.getSandboxDirectory(),to));
CompilationResult result = ajc.doIncrementalCompile();
assertMessages(result,"Test '" + getCurrentTest().getTitle() + "' did not produce expected messages",expectedResults);
}
protected void deleteFile(String file) {
new File(ajc.getSandboxDirectory(),file).delete();
}
protected void deleteFileAndDoIncrementalBuild(String file, MessageSpec expectedResult) throws Exception {
deleteFile(file);
CompilationResult result = ajc.doIncrementalCompile();
assertMessages(result,"Test '" + getCurrentTest().getTitle() + "' did not produce expected messages",expectedResult);
}
protected void deleteFileAndDoIncrementalBuild(String file) throws Exception {
deleteFileAndDoIncrementalBuild(file,MessageSpec.EMPTY_MESSAGE_SET);
}
protected void assertAdded(String file) {
assertTrue("File " + file + " should have been added",
new File(ajc.getSandboxDirectory(),file).exists());
}
protected void assertDeleted(String file) {
assertFalse("File " + file + " should have been deleted",
new File(ajc.getSandboxDirectory(),file).exists());
}
protected void assertUpdated(String file, long sinceTime) {
File f = new File(ajc.getSandboxDirectory(),file);
assertTrue("File " + file + " should have been updated",f.lastModified() > sinceTime);
}
}
|
118,715 |
Bug 118715 Load Time Weaving wipes out Xlint files if no Xlint values
|
In ClassLoaderWeavingAdaptor if weaverOption.lint is null, then a loaded Xlint properties file gets overwritten by the default Xlint properties. See attached patch to fix this problem.
|
resolved fixed
|
1e1bbb3
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2005-12-06T13:02:38Z | 2005-11-30T22:33:20Z |
tests/src/org/aspectj/systemtest/ajc150/ltw/LTWTests.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:
* Matthew Webster initial implementation
*******************************************************************************/
package org.aspectj.systemtest.ajc150.ltw;
import java.io.File;
import java.util.Enumeration;
import java.util.Properties;
import junit.framework.Test;
import org.aspectj.testing.XMLBasedAjcTestCase;
import org.aspectj.weaver.tools.WeavingAdaptor;
public class LTWTests extends org.aspectj.testing.XMLBasedAjcTestCase {
public static Test suite() {
return XMLBasedAjcTestCase.loadSuite(LTWTests.class);
}
protected File getSpecFile() {
return new File("../tests/src/org/aspectj/systemtest/ajc150/ltw/ltw.xml");
}
public void test001(){
runTest("Ensure 1st aspect is rewoven when weaving 2nd aspect");
}
public void testOutxmlFile (){
runTest("Ensure valid aop.xml file is generated");
}
public void testOutxmlJar (){
runTest("Ensure valid aop.xml is generated for -outjar");
}
public void testNoAopxml(){
setSystemProperty(WeavingAdaptor.WEAVING_ADAPTOR_VERBOSE,"true");
runTest("Ensure no weaving without visible aop.xml");
}
public void testDefineConcreteAspect(){
runTest("Define concrete sub-aspect using aop.xml");
}
public void testDeclareAbstractAspect(){
// setSystemProperty(WeavingAdaptor.WEAVING_ADAPTOR_VERBOSE,"true");
// setSystemProperty(WeavingAdaptor.SHOW_WEAVE_INFO_PROPERTY,"true");
runTest("Use abstract aspect for ITD using aop.xml");
}
public void testAspectsInclude () {
runTest("Ensure a subset of inherited aspects is used for weaving");
}
public void testAspectsIncludeWithLintWarning () {
runTest("Ensure weaver lint warning issued when an aspect is not used for weaving");
}
/*
* Allow system properties to be set and restored
* TODO maw move to XMLBasedAjcTestCase or RunSpec
*/
private final static String NULL = "null";
private Properties savedProperties;
protected void setSystemProperty (String key, String value) {
Properties systemProperties = System.getProperties();
copyProperty(key,systemProperties,savedProperties);
systemProperties.setProperty(key,value);
}
private static void copyProperty (String key, Properties from, Properties to) {
String value = from.getProperty(key,NULL);
to.setProperty(key,value);
}
protected void setUp() throws Exception {
super.setUp();
savedProperties = new Properties();
}
protected void tearDown() throws Exception {
super.tearDown();
/* Restore system properties */
Properties systemProperties = System.getProperties();
for (Enumeration enu = savedProperties.keys(); enu.hasMoreElements(); ) {
String key = (String)enu.nextElement();
String value = savedProperties.getProperty(key);
if (value == NULL) systemProperties.remove(key);
else systemProperties.setProperty(key,value);
}
}
}
|
118,715 |
Bug 118715 Load Time Weaving wipes out Xlint files if no Xlint values
|
In ClassLoaderWeavingAdaptor if weaverOption.lint is null, then a loaded Xlint properties file gets overwritten by the default Xlint properties. See attached patch to fix this problem.
|
resolved fixed
|
1e1bbb3
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2005-12-06T13:02:38Z | 2005-11-30T22:33:20Z |
weaver/src/org/aspectj/weaver/tools/WeavingAdaptor.java
|
/* *******************************************************************
* Copyright (c) 2004 IBM Corporation
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* Matthew Webster, Adrian Colyer,
* Martin Lippert initial implementation
* ******************************************************************/
package org.aspectj.weaver.tools;
import java.io.File;
import java.io.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.IMessage.Kind;
import org.aspectj.util.FileUtil;
import org.aspectj.util.LangUtil;
import org.aspectj.weaver.IClassFileProvider;
import org.aspectj.weaver.IWeaveRequestor;
import org.aspectj.weaver.bcel.BcelWeaver;
import org.aspectj.weaver.bcel.BcelWorld;
import org.aspectj.weaver.bcel.UnwovenClassFile;
/**
* This adaptor allows the AspectJ compiler to be embedded in an existing
* system to facilitate load-time weaving. It provides an interface for a
* weaving class loader to provide a classpath to be woven by a set of
* aspects. A callback is supplied to allow a class loader to define classes
* generated by the compiler during the weaving process.
* <p>
* A weaving class loader should create a <code>WeavingAdaptor</code> before
* any classes are defined, typically during construction. The set of aspects
* passed to the adaptor is fixed for the lifetime of the adaptor although the
* classpath can be augmented. A system property can be set to allow verbose
* weaving messages to be written to the console.
*
*/
public class WeavingAdaptor {
/**
* System property used to turn on verbose weaving messages
*/
public static final String WEAVING_ADAPTOR_VERBOSE = "aj.weaving.verbose";
public static final String SHOW_WEAVE_INFO_PROPERTY = "org.aspectj.weaver.showWeaveInfo";
protected boolean enabled = true;
protected boolean verbose = getVerbose();
protected BcelWorld bcelWorld = null;
protected BcelWeaver weaver = null;
protected IMessageHandler/*WeavingAdaptorMessageHandler*/ messageHandler = null;
protected GeneratedClassHandler generatedClassHandler;
protected Map generatedClasses = new HashMap(); /* String -> UnwovenClassFile */
protected WeavingAdaptor () {
createMessageHandler();
}
/**
* Construct a WeavingAdaptor with a reference to a weaving class loader. The
* adaptor will automatically search the class loader hierarchy to resolve
* classes. The adaptor will also search the hierarchy for WeavingClassLoader
* instances to determine the set of aspects to be used ofr weaving.
* @param loader instance of <code>ClassLoader</code>
*/
public WeavingAdaptor (WeavingClassLoader loader) {
// System.err.println("? WeavingAdaptor.<init>(" + loader +"," + aspectURLs.length + ")");
generatedClassHandler = loader;
init(getFullClassPath((ClassLoader)loader),getFullAspectPath((ClassLoader)loader/*,aspectURLs*/));
}
/**
* Construct a WeavingAdator with a reference to a
* <code>GeneratedClassHandler</code>, a full search path for resolving
* classes and a complete set of aspects. The search path must include
* classes loaded by the class loader constructing the WeavingAdaptor and
* all its parents in the hierarchy.
* @param handler <code>GeneratedClassHandler</code>
* @param classURLs the URLs from which to resolve classes
* @param aspectURLs the aspects used to weave classes defined by this class loader
*/
public WeavingAdaptor (GeneratedClassHandler handler, URL[] classURLs, URL[] aspectURLs) {
// System.err.println("? WeavingAdaptor.<init>()");
generatedClassHandler = handler;
init(FileUtil.makeClasspath(classURLs),FileUtil.makeClasspath(aspectURLs));
}
private List getFullClassPath (ClassLoader loader) {
List list = new LinkedList();
for (; loader != null; loader = loader.getParent()) {
if (loader instanceof URLClassLoader) {
URL[] urls = ((URLClassLoader)loader).getURLs();
list.addAll(0,FileUtil.makeClasspath(urls));
}
else {
warn("cannot determine classpath");
}
}
list.addAll(0,makeClasspath(System.getProperty("sun.boot.class.path")));
return list;
}
private List getFullAspectPath (ClassLoader loader) {
List list = new LinkedList();
for (; loader != null; loader = loader.getParent()) {
if (loader instanceof WeavingClassLoader) {
URL[] urls = ((WeavingClassLoader)loader).getAspectURLs();
list.addAll(0,FileUtil.makeClasspath(urls));
}
}
return list;
}
private static boolean getVerbose () {
return Boolean.getBoolean(WEAVING_ADAPTOR_VERBOSE);
}
private void init(List classPath, List aspectPath) {
createMessageHandler();
info("using classpath: " + classPath);
info("using aspectpath: " + aspectPath);
bcelWorld = new BcelWorld(classPath,messageHandler,null);
bcelWorld.setXnoInline(false);
bcelWorld.getLint().loadDefaultProperties();
if (LangUtil.is15VMOrGreater()) {
bcelWorld.setBehaveInJava5Way(true);
}
weaver = new BcelWeaver(bcelWorld);
registerAspectLibraries(aspectPath);
}
private void createMessageHandler() {
messageHandler = new WeavingAdaptorMessageHandler(new PrintWriter(System.err));
if (verbose) messageHandler.dontIgnore(IMessage.INFO);
if (Boolean.getBoolean(SHOW_WEAVE_INFO_PROPERTY)) messageHandler.dontIgnore(IMessage.WEAVEINFO);
}
/**
* Appends URL to path used by the WeavingAdptor to resolve classes
* @param url to be appended to search path
*/
public void addURL(URL url) {
File libFile = new File(url.getPath());
try {
weaver.addLibraryJarFile(libFile);
}
catch (IOException ex) {
warn("bad library: '" + libFile + "'");
}
}
/**
* Weave a class using aspects previously supplied to the adaptor.
* @param name the name of the class
* @param bytes the class bytes
* @return the woven bytes
* @exception IOException weave failed
*/
public byte[] weaveClass (String name, byte[] bytes) throws IOException {
if (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);
}
}
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) {
return !((/*(name.startsWith("org.apache.bcel.")//FIXME AV why ? bcel is wrapped in org.aspectj.
||*/ name.startsWith("org.aspectj.")
|| name.startsWith("java.")
|| name.startsWith("javax."))
//|| name.startsWith("$Proxy")//JDK proxies//FIXME AV is that 1.3 proxy ? fe. ataspect.$Proxy0 is a java5 proxy...
|| name.startsWith("sun.reflect."));//JDK reflect
}
/**
* We allow @AJ aspect weaving so that we can add aspectOf() as part of the weaving
* (and not part of the source compilation)
*
* @param name
* @param bytes bytecode (from classloader), allow to NOT lookup stuff on disk again during resolve
* @return true if @Aspect
*/
private boolean shouldWeaveAnnotationStyleAspect(String name, byte[] bytes) {
// AV: instead of doing resolve that would lookup stuff on disk thru BCEL ClassLoaderRepository
// we reuse bytes[] here to do a fast lookup for @Aspect annotation
return bcelWorld.isAnnotationStyleAspect(name, bytes);
}
/**
* Weave a set of bytes defining a class.
* @param name the name of the class being woven
* @param bytes the bytes that define the class
* @return byte[] the woven bytes for the class
* @throws IOException
*/
private byte[] getWovenBytes(String name, byte[] bytes) throws IOException {
WeavingClassFileProvider wcp = new WeavingClassFileProvider(name,bytes);
weaver.weave(wcp);
return wcp.getBytes();
}
/**
* Weave a set of bytes defining a class for only what is needed to turn @AspectJ aspect
* in a usefull form ie with aspectOf method - see #113587
* @param name the name of the class being woven
* @param bytes the bytes that define the class
* @return byte[] the woven bytes for the class
* @throws IOException
*/
private byte[] getAtAspectJAspectBytes(String name, byte[] bytes) throws IOException {
WeavingClassFileProvider wcp = new WeavingClassFileProvider(name,bytes);
wcp.setApplyAtAspectJMungersOnly();
weaver.weave(wcp);
return wcp.getBytes();
}
private void registerAspectLibraries(List aspectPath) {
// System.err.println("? WeavingAdaptor.registerAspectLibraries(" + aspectPath + ")");
for (Iterator i = aspectPath.iterator(); i.hasNext();) {
String libName = (String)i.next();
addAspectLibrary(libName);
}
weaver.prepareForWeave();
}
/*
* Register an aspect library with this classloader for use during
* weaving. This class loader will also return (unmodified) any of the
* classes in the library in response to a <code>findClass()</code> request.
* The library is not required to be on the weavingClasspath given when this
* classloader was constructed.
* @param aspectLibraryJarFile a jar file representing an aspect library
* @throws IOException
*/
private void addAspectLibrary(String aspectLibraryName) {
File aspectLibrary = new File(aspectLibraryName);
if (aspectLibrary.isDirectory()
|| (aspectLibrary.isFile()
&& FileUtil.hasZipSuffix(aspectLibraryName))) {
try {
info("adding aspect library: '" + aspectLibrary + "'");
weaver.addLibraryJarFile(aspectLibrary);
} catch (IOException ex) {
error("exception adding aspect library: '" + ex + "'");
}
} else {
error("bad aspect library: '" + aspectLibrary + "'");
}
}
private static List makeClasspath(String cp) {
List ret = new ArrayList();
if (cp != null) {
StringTokenizer tok = new StringTokenizer(cp,File.pathSeparator);
while (tok.hasMoreTokens()) {
ret.add(tok.nextToken());
}
}
return ret;
}
protected boolean info (String message) {
return MessageUtil.info(messageHandler,message);
}
protected boolean warn (String message) {
return MessageUtil.warn(messageHandler,message);
}
protected boolean warn (String message, Throwable th) {
return messageHandler.handleMessage(new Message("Register definition failed", IMessage.WARNING, th, null));
}
protected boolean error (String message) {
return MessageUtil.error(messageHandler,message);
}
/**
* 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 {
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;
public WeavingAdaptorMessageHandler (PrintWriter writer) {
super(writer,true);
ignore(IMessage.WEAVEINFO);
ignore(IMessage.INFO);
this.failKind = IMessage.ERROR;
}
public boolean handleMessage(IMessage message) throws AbortException {
boolean result = super.handleMessage(message);
if (0 <= message.getKind().compareTo(failKind)) {
throw new AbortException(message);
}
return true;
}
public boolean isIgnoring (Kind kind) {
return ((null != kind) && (ignoring.contains(kind)));
}
/**
* Set a message kind to be ignored from now on
*/
public void ignore (IMessage.Kind kind) {
if ((null != kind) && (!ignoring.contains(kind))) {
ignoring.add(kind);
}
}
/**
* Remove a message kind from the list of those ignored from now on.
*/
public void dontIgnore (IMessage.Kind kind) {
if (null != kind) {
ignoring.remove(kind);
}
}
}
private class WeavingClassFileProvider implements IClassFileProvider {
private UnwovenClassFile unwovenClass;
private List unwovenClasses = new ArrayList(); /* List<UnovenClassFile> */
private UnwovenClassFile wovenClass;
private boolean isApplyAtAspectJMungersOnly = false;
public WeavingClassFileProvider (String name, byte[] bytes) {
this.unwovenClass = new UnwovenClassFile(name,bytes);
this.unwovenClasses.add(unwovenClass);
if (shouldDump(name.replace('/', '.'),true)) {
dump(name, bytes, true);
}
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();
generatedClasses.put(className,result);
generatedClassHandler.acceptClass(className,result.getBytes());
}
}
public void processingReweavableState() { }
public void addingTypeMungers() {}
public void weavingAspects() {}
public void weavingClasses() {}
public void weaveCompleted() {}
};
}
}
}
|
118,715 |
Bug 118715 Load Time Weaving wipes out Xlint files if no Xlint values
|
In ClassLoaderWeavingAdaptor if weaverOption.lint is null, then a loaded Xlint properties file gets overwritten by the default Xlint properties. See attached patch to fix this problem.
|
resolved fixed
|
1e1bbb3
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2005-12-06T13:02:38Z | 2005-11-30T22:33:20Z |
weaver5/java5-src/org/aspectj/weaver/reflect/Java15ReflectionBasedReferenceTypeDelegate.java
|
/* *******************************************************************
* Copyright (c) 2005 Contributors.
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Eclipse Public License v1.0
* which accompanies this distribution and is available at
* http://eclipse.org/legal/epl-v10.html
*
* Contributors:
* Adrian Colyer Initial implementation
* ******************************************************************/
package org.aspectj.weaver.reflect;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.GenericArrayType;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.lang.reflect.WildcardType;
import java.util.HashMap;
import java.util.Map;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.AjType;
import org.aspectj.lang.reflect.AjTypeSystem;
import org.aspectj.lang.reflect.Pointcut;
import org.aspectj.weaver.AnnotationX;
import org.aspectj.weaver.BoundedReferenceType;
import org.aspectj.weaver.ReferenceType;
import org.aspectj.weaver.ResolvedMember;
import org.aspectj.weaver.ResolvedPointcutDefinition;
import org.aspectj.weaver.ResolvedType;
import org.aspectj.weaver.TypeFactory;
import org.aspectj.weaver.TypeVariable;
import org.aspectj.weaver.TypeVariableReferenceType;
import org.aspectj.weaver.UnresolvedType;
import org.aspectj.weaver.World;
import org.aspectj.weaver.internal.tools.PointcutExpressionImpl;
import org.aspectj.weaver.tools.PointcutParameter;
import org.aspectj.weaver.tools.PointcutParser;
/**
* @author colyer
* Provides Java 5 behaviour in reflection based delegates (overriding
* 1.4 behaviour from superclass where appropriate)
*/
public class Java15ReflectionBasedReferenceTypeDelegate extends
ReflectionBasedReferenceTypeDelegate {
private AjType<?> myType;
private ResolvedType[] annotations;
private ResolvedMember[] pointcuts;
private ResolvedMember[] methods;
private ResolvedMember[] fields;
private TypeVariable[] typeVariables;
private ResolvedType superclass;
private ResolvedType[] superInterfaces;
private String genericSignature = null;
private JavaLangTypeToResolvedTypeConverter typeConverter;
private Java15AnnotationFinder annotationFinder = 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();
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(),
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];
PointcutParser parser = PointcutParser.getPointcutParserSupportingAllPrimitivesAndUsingSpecifiedClassloaderForResolution(classLoader);
for (int i = 0; i < pcs.length; i++) {
AjType<?>[] ptypes = pcs[i].getParameterTypes();
String[] pnames = pcs[i].getParameterNames();
if (pnames.length != ptypes.length) {
throw new IllegalStateException("Required parameter names not available when parsing pointcut " + pcs[i].getName() + " in type " + getResolvedTypeX().getName());
}
PointcutParameter[] parameters = new PointcutParameter[ptypes.length];
for (int j = 0; j < parameters.length; j++) {
parameters[j] = parser.createPointcutParameter(pnames[j],ptypes[j].getJavaClass());
}
String pcExpr = pcs[i].getPointcutExpression().toString();
PointcutExpressionImpl pEx = (PointcutExpressionImpl) parser.parsePointcutExpression(pcExpr,getBaseClass(),parameters);
org.aspectj.weaver.patterns.Pointcut pc = pEx.getUnderlyingPointcut();
UnresolvedType[] weaverPTypes = new UnresolvedType[ptypes.length];
for (int j = 0; j < weaverPTypes.length; j++) {
weaverPTypes[j] = UnresolvedType.forName(ptypes[j].getName());
}
pointcuts[i] = new ResolvedPointcutDefinition(getResolvedTypeX(),pcs[i].getModifiers(),pcs[i].getName(),weaverPTypes,pc);
}
}
return pointcuts;
}
public boolean isAnnotation() {
return getBaseClass().isAnnotation();
}
public boolean isAnnotationStyleAspect() {
return getBaseClass().isAnnotationPresent(Aspect.class);
}
public boolean isAnnotationWithRuntimeRetention() {
if (!isAnnotation()) return false;
if (getBaseClass().isAnnotationPresent(Retention.class)) {
Retention retention = (Retention) getBaseClass().getAnnotation(Retention.class);
RetentionPolicy policy = retention.value();
return policy == RetentionPolicy.RUNTIME;
} else {
return false;
}
}
public boolean isAspect() {
return this.myType.isAspect();
}
public boolean isEnum() {
return getBaseClass().isEnum();
}
public boolean isGeneric() {
//return false; // for now
return getBaseClass().getTypeParameters().length > 0;
}
@Override
public boolean isAnonymous() {
return this.myClass.isAnonymousClass();
}
}
|
119,352 |
Bug 119352 AjType.getSupertype breaks for null
|
I ran into this while using reflection proxies with LTW... See attached patches for these test cases and my fix: public void testObjectSupertype() { AjType<?> objectSuper = AjTypeSystem.getAjType(Object.class).getSupertype(); assertNull(objectSuper); } public void testInterfaceSupertype() { AjType<?> serializableSuper = AjTypeSystem.getAjType(Serializable.class).getSupertype(); assertNull(serializableSuper); } public AjType<? super T> getSupertype() { Class<? super T> superclass = clazz.getSuperclass(); return superclass==null ? null : (AjType<? super T>) new AjTypeImpl(superclass); }
|
resolved fixed
|
6e8bf52
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2005-12-06T15:39:08Z | 2005-12-06T03:33:20Z |
aspectj5rt/java5-src/org/aspectj/internal/lang/reflect/AjTypeImpl.java
|
/* *******************************************************************
* Copyright (c) 2005 Contributors.
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Eclipse Public License v1.0
* which accompanies this distribution and is available at
* http://eclipse.org/legal/epl-v10.html
*
* Contributors:
* Adrian Colyer Initial implementation
* ******************************************************************/
package org.aspectj.internal.lang.reflect;
import java.lang.annotation.Annotation;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.lang.reflect.Type;
import java.lang.reflect.TypeVariable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.EnumSet;
import java.util.List;
import java.util.Set;
import org.aspectj.internal.lang.annotation.ajcDeclareAnnotation;
import org.aspectj.internal.lang.annotation.ajcDeclareEoW;
import org.aspectj.internal.lang.annotation.ajcDeclareParents;
import org.aspectj.internal.lang.annotation.ajcDeclarePrecedence;
import org.aspectj.internal.lang.annotation.ajcDeclareSoft;
import org.aspectj.internal.lang.annotation.ajcITD;
import org.aspectj.internal.lang.annotation.ajcPrivileged;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.DeclareError;
import org.aspectj.lang.annotation.DeclareWarning;
import org.aspectj.lang.reflect.Advice;
import org.aspectj.lang.reflect.AdviceKind;
import org.aspectj.lang.reflect.AjType;
import org.aspectj.lang.reflect.AjTypeSystem;
import org.aspectj.lang.reflect.DeclareAnnotation;
import org.aspectj.lang.reflect.DeclareErrorOrWarning;
import org.aspectj.lang.reflect.DeclareParents;
import org.aspectj.lang.reflect.DeclarePrecedence;
import org.aspectj.lang.reflect.DeclareSoft;
import org.aspectj.lang.reflect.InterTypeConstructorDeclaration;
import org.aspectj.lang.reflect.InterTypeFieldDeclaration;
import org.aspectj.lang.reflect.InterTypeMethodDeclaration;
import org.aspectj.lang.reflect.NoSuchAdviceException;
import org.aspectj.lang.reflect.NoSuchPointcutException;
import org.aspectj.lang.reflect.PerClause;
import org.aspectj.lang.reflect.PerClauseKind;
import org.aspectj.lang.reflect.Pointcut;
/**
* @author colyer
*
*/
public class AjTypeImpl<T> implements AjType<T> {
private static final String ajcMagic = "ajc$";
private Class<T> clazz;
private Pointcut[] declaredPointcuts = null;
private Pointcut[] pointcuts = null;
private Advice[] declaredAdvice = null;
private Advice[] advice = null;
private InterTypeMethodDeclaration[] declaredITDMethods = null;
private InterTypeMethodDeclaration[] itdMethods = null;
private InterTypeFieldDeclaration[] declaredITDFields = null;
private InterTypeFieldDeclaration[] itdFields = null;
private InterTypeConstructorDeclaration[] itdCons = null;
private InterTypeConstructorDeclaration[] declaredITDCons = null;
public AjTypeImpl(Class<T> fromClass) {
this.clazz = fromClass;
}
/* (non-Javadoc)
* @see org.aspectj.lang.reflect.AjType#getName()
*/
public String getName() {
return clazz.getName();
}
/* (non-Javadoc)
* @see org.aspectj.lang.reflect.AjType#getPackage()
*/
public Package getPackage() {
return clazz.getPackage();
}
/* (non-Javadoc)
* @see org.aspectj.lang.reflect.AjType#getInterfaces()
*/
public AjType<?>[] getInterfaces() {
Class<?>[] baseInterfaces = clazz.getInterfaces();
return toAjTypeArray(baseInterfaces);
}
/* (non-Javadoc)
* @see org.aspectj.lang.reflect.AjType#getModifiers()
*/
public int getModifiers() {
return clazz.getModifiers();
}
public Class<T> getJavaClass() {
return clazz;
}
/* (non-Javadoc)
* @see org.aspectj.lang.reflect.AjType#getSupertype()
*/
public AjType<? super T> getSupertype() {
Class<? super T> superclass = clazz.getSuperclass();
return (AjType<? super T>) new AjTypeImpl(superclass);
}
/* (non-Javadoc)
* @see org.aspectj.lang.reflect.AjType#getGenericSupertype()
*/
public Type getGenericSupertype() {
return clazz.getGenericSuperclass();
}
/* (non-Javadoc)
* @see org.aspectj.lang.reflect.AjType#getEnclosingMethod()
*/
public Method getEnclosingMethod() {
return clazz.getEnclosingMethod();
}
/* (non-Javadoc)
* @see org.aspectj.lang.reflect.AjType#getEnclosingConstructor()
*/
public Constructor getEnclosingConstructor() {
return clazz.getEnclosingConstructor();
}
/* (non-Javadoc)
* @see org.aspectj.lang.reflect.AjType#getEnclosingType()
*/
public AjType<?> getEnclosingType() {
Class<?> enc = clazz.getEnclosingClass();
return enc != null ? new AjTypeImpl(enc) : null;
}
/* (non-Javadoc)
* @see org.aspectj.lang.reflect.AjType#getDeclaringType()
*/
public AjType<?> getDeclaringType() {
Class dec = clazz.getDeclaringClass();
return dec != null ? new AjTypeImpl(dec) : null;
}
public PerClause getPerClause() {
if (isAspect()) {
Aspect aspectAnn = clazz.getAnnotation(Aspect.class);
String perClause = aspectAnn.value();
if (perClause.equals("")) {
if (getSupertype().isAspect()) {
return getSupertype().getPerClause();
}
return new PerClauseImpl(PerClauseKind.SINGLETON);
} else if (perClause.startsWith("perthis(")) {
return new PointcutBasedPerClauseImpl(PerClauseKind.PERTHIS,perClause.substring("perthis(".length(),perClause.length() - 1));
} else if (perClause.startsWith("pertarget(")) {
return new PointcutBasedPerClauseImpl(PerClauseKind.PERTARGET,perClause.substring("pertarget(".length(),perClause.length() - 1));
} else if (perClause.startsWith("percflow(")) {
return new PointcutBasedPerClauseImpl(PerClauseKind.PERCFLOW,perClause.substring("percflow(".length(),perClause.length() - 1));
} else if (perClause.startsWith("percflowbelow(")) {
return new PointcutBasedPerClauseImpl(PerClauseKind.PERCFLOWBELOW,perClause.substring("percflowbelow(".length(),perClause.length() - 1));
} else if (perClause.startsWith("pertypewithin")) {
return new TypePatternBasedPerClauseImpl(PerClauseKind.PERTYPEWITHIN,perClause.substring("pertypewithin(".length(),perClause.length() - 1));
} else {
throw new IllegalStateException("Per-clause not recognized: " + perClause);
}
} else {
return null;
}
}
/* (non-Javadoc)
* @see org.aspectj.lang.reflect.AjType#isAnnotationPresent(java.lang.Class)
*/
public boolean isAnnotationPresent(Class<? extends Annotation> annotationType) {
return clazz.isAnnotationPresent(annotationType);
}
public <A extends Annotation> A getAnnotation(Class<A> annotationType) {
return clazz.getAnnotation(annotationType);
}
/* (non-Javadoc)
* @see org.aspectj.lang.reflect.AjType#getAnnotations()
*/
public Annotation[] getAnnotations() {
return clazz.getAnnotations();
}
/* (non-Javadoc)
* @see org.aspectj.lang.reflect.AjType#getDeclaredAnnotations()
*/
public Annotation[] getDeclaredAnnotations() {
return clazz.getDeclaredAnnotations();
}
/* (non-Javadoc)
* @see org.aspectj.lang.reflect.AjType#getAspects()
*/
public AjType<?>[] getAjTypes() {
Class[] classes = clazz.getClasses();
return toAjTypeArray(classes);
}
/* (non-Javadoc)
* @see org.aspectj.lang.reflect.AjType#getDeclaredAspects()
*/
public AjType<?>[] getDeclaredAjTypes() {
Class[] classes = clazz.getDeclaredClasses();
return toAjTypeArray(classes);
}
/* (non-Javadoc)
* @see org.aspectj.lang.reflect.AjType#getConstructor(java.lang.Class...)
*/
public Constructor getConstructor(AjType<?>... parameterTypes) throws NoSuchMethodException {
return clazz.getConstructor(toClassArray(parameterTypes));
}
/* (non-Javadoc)
* @see org.aspectj.lang.reflect.AjType#getConstructors()
*/
public Constructor[] getConstructors() {
return clazz.getConstructors();
}
/* (non-Javadoc)
* @see org.aspectj.lang.reflect.AjType#getDeclaredConstructor(java.lang.Class...)
*/
public Constructor getDeclaredConstructor(AjType<?>... parameterTypes) throws NoSuchMethodException {
return clazz.getDeclaredConstructor(toClassArray(parameterTypes));
}
/* (non-Javadoc)
* @see org.aspectj.lang.reflect.AjType#getDeclaredConstructors()
*/
public Constructor[] getDeclaredConstructors() {
return clazz.getDeclaredConstructors();
}
/* (non-Javadoc)
* @see org.aspectj.lang.reflect.AjType#getDeclaredField(java.lang.String)
*/
public Field getDeclaredField(String name) throws NoSuchFieldException {
Field f = clazz.getDeclaredField(name);
if (f.getName().startsWith(ajcMagic)) throw new NoSuchFieldException(name);
return f;
}
/* (non-Javadoc)
* @see org.aspectj.lang.reflect.AjType#getDeclaredFields()
*/
public Field[] getDeclaredFields() {
Field[] fields = clazz.getDeclaredFields();
List<Field> filteredFields = new ArrayList<Field>();
for (Field field : fields)
if (!field.getName().startsWith(ajcMagic)
&& !field.isAnnotationPresent(DeclareWarning.class)
&& !field.isAnnotationPresent(DeclareError.class)) {
filteredFields.add(field);
}
Field[] ret = new Field[filteredFields.size()];
filteredFields.toArray(ret);
return ret;
}
/* (non-Javadoc)
* @see org.aspectj.lang.reflect.AjType#getField(java.lang.String)
*/
public Field getField(String name) throws NoSuchFieldException {
Field f = clazz.getField(name);
if (f.getName().startsWith(ajcMagic)) throw new NoSuchFieldException(name);
return f;
}
/* (non-Javadoc)
* @see org.aspectj.lang.reflect.AjType#getFields()
*/
public Field[] getFields() {
Field[] fields = clazz.getFields();
List<Field> filteredFields = new ArrayList<Field>();
for (Field field : fields)
if (!field.getName().startsWith(ajcMagic)
&& !field.isAnnotationPresent(DeclareWarning.class)
&& !field.isAnnotationPresent(DeclareError.class)) {
filteredFields.add(field);
}
Field[] ret = new Field[filteredFields.size()];
filteredFields.toArray(ret);
return ret;
}
/* (non-Javadoc)
* @see org.aspectj.lang.reflect.AjType#getDeclaredMethod(java.lang.String, java.lang.Class...)
*/
public Method getDeclaredMethod(String name, AjType<?>... parameterTypes) throws NoSuchMethodException {
Method m = clazz.getDeclaredMethod(name,toClassArray(parameterTypes));
if (!isReallyAMethod(m)) throw new NoSuchMethodException(name);
return m;
}
/* (non-Javadoc)
* @see org.aspectj.lang.reflect.AjType#getMethod(java.lang.String, java.lang.Class...)
*/
public Method getMethod(String name, AjType<?>... parameterTypes) throws NoSuchMethodException {
Method m = clazz.getMethod(name,toClassArray(parameterTypes));
if (!isReallyAMethod(m)) throw new NoSuchMethodException(name);
return m;
}
/* (non-Javadoc)
* @see org.aspectj.lang.reflect.AjType#getDeclaredMethods()
*/
public Method[] getDeclaredMethods() {
Method[] methods = clazz.getDeclaredMethods();
List<Method> filteredMethods = new ArrayList<Method>();
for (Method method : methods) {
if (isReallyAMethod(method)) filteredMethods.add(method);
}
Method[] ret = new Method[filteredMethods.size()];
filteredMethods.toArray(ret);
return ret;
}
/* (non-Javadoc)
* @see org.aspectj.lang.reflect.AjType#getMethods()
*/
public Method[] getMethods() {
Method[] methods = clazz.getMethods();
List<Method> filteredMethods = new ArrayList<Method>();
for (Method method : methods) {
if (isReallyAMethod(method)) filteredMethods.add(method);
}
Method[] ret = new Method[filteredMethods.size()];
filteredMethods.toArray(ret);
return ret;
}
private boolean isReallyAMethod(Method method) {
if (method.getName().startsWith(ajcMagic)) return false;
if (method.isAnnotationPresent(org.aspectj.lang.annotation.Pointcut.class)) return false;
if (method.isAnnotationPresent(Before.class)) return false;
if (method.isAnnotationPresent(After.class)) return false;
if (method.isAnnotationPresent(AfterReturning.class)) return false;
if (method.isAnnotationPresent(AfterThrowing.class)) return false;
if (method.isAnnotationPresent(Around.class)) return false;
return true;
}
/* (non-Javadoc)
* @see org.aspectj.lang.reflect.AjType#getDeclaredPointcut(java.lang.String)
*/
public Pointcut getDeclaredPointcut(String name) throws NoSuchPointcutException {
Pointcut[] pcs = getDeclaredPointcuts();
for (Pointcut pc : pcs)
if (pc.getName().equals(name)) return pc;
throw new NoSuchPointcutException(name);
}
/* (non-Javadoc)
* @see org.aspectj.lang.reflect.AjType#getPointcut(java.lang.String)
*/
public Pointcut getPointcut(String name) throws NoSuchPointcutException {
Pointcut[] pcs = getPointcuts();
for (Pointcut pc : pcs)
if (pc.getName().equals(name)) return pc;
throw new NoSuchPointcutException(name);
}
/* (non-Javadoc)
* @see org.aspectj.lang.reflect.AjType#getDeclaredPointcuts()
*/
public Pointcut[] getDeclaredPointcuts() {
if (declaredPointcuts != null) return declaredPointcuts;
List<Pointcut> pointcuts = new ArrayList<Pointcut>();
Method[] methods = clazz.getDeclaredMethods();
for (Method method : methods) {
Pointcut pc = asPointcut(method);
if (pc != null) pointcuts.add(pc);
}
Pointcut[] ret = new Pointcut[pointcuts.size()];
pointcuts.toArray(ret);
declaredPointcuts = ret;
return ret;
}
/* (non-Javadoc)
* @see org.aspectj.lang.reflect.AjType#getPointcuts()
*/
public Pointcut[] getPointcuts() {
if (pointcuts != null) return pointcuts;
List<Pointcut> pcuts = new ArrayList<Pointcut>();
Method[] methods = clazz.getMethods();
for (Method method : methods) {
Pointcut pc = asPointcut(method);
if (pc != null) pcuts.add(pc);
}
Pointcut[] ret = new Pointcut[pcuts.size()];
pcuts.toArray(ret);
pointcuts = ret;
return ret;
}
private Pointcut asPointcut(Method method) {
org.aspectj.lang.annotation.Pointcut pcAnn = method.getAnnotation(org.aspectj.lang.annotation.Pointcut.class);
if (pcAnn != null) {
String name = method.getName();
if (name.startsWith(ajcMagic)) {
// extract real name
int nameStart = name.indexOf("$$");
name = name.substring(nameStart +2,name.length());
int nextDollar = name.indexOf("$");
if (nextDollar != -1) name = name.substring(0,nextDollar);
}
return new PointcutImpl(name,pcAnn.value(),method,AjTypeSystem.getAjType(method.getDeclaringClass()),pcAnn.argNames());
} else {
return null;
}
}
public Advice[] getDeclaredAdvice(AdviceKind... ofType) {
Set<AdviceKind> types;
if (ofType.length == 0) {
types = EnumSet.allOf(AdviceKind.class);
} else {
types = EnumSet.noneOf(AdviceKind.class);
types.addAll(Arrays.asList(ofType));
}
return getDeclaredAdvice(types);
}
public Advice[] getAdvice(AdviceKind... ofType) {
Set<AdviceKind> types;
if (ofType.length == 0) {
types = EnumSet.allOf(AdviceKind.class);
} else {
types = EnumSet.noneOf(AdviceKind.class);
types.addAll(Arrays.asList(ofType));
}
return getAdvice(types);
}
/* (non-Javadoc)
* @see org.aspectj.lang.reflect.AjType#getDeclaredAdvice(org.aspectj.lang.reflect.AdviceType)
*/
private Advice[] getDeclaredAdvice(Set ofAdviceTypes) {
if (declaredAdvice == null) initDeclaredAdvice();
List<Advice> adviceList = new ArrayList<Advice>();
for (Advice a : declaredAdvice) {
if (ofAdviceTypes.contains(a.getKind())) adviceList.add(a);
}
Advice[] ret = new Advice[adviceList.size()];
adviceList.toArray(ret);
return ret;
}
private void initDeclaredAdvice() {
Method[] methods = clazz.getDeclaredMethods();
List<Advice> adviceList = new ArrayList<Advice>();
for (Method method : methods) {
Advice advice = asAdvice(method);
if (advice != null) adviceList.add(advice);
}
declaredAdvice = new Advice[adviceList.size()];
adviceList.toArray(declaredAdvice);
}
/* (non-Javadoc)
* @see org.aspectj.lang.reflect.AjType#getDeclaredAdvice(org.aspectj.lang.reflect.AdviceType)
*/
private Advice[] getAdvice(Set ofAdviceTypes) {
if (advice == null) initAdvice();
List<Advice> adviceList = new ArrayList<Advice>();
for (Advice a : advice) {
if (ofAdviceTypes.contains(a.getKind())) adviceList.add(a);
}
Advice[] ret = new Advice[adviceList.size()];
adviceList.toArray(ret);
return ret;
}
private void initAdvice() {
Method[] methods = clazz.getMethods();
List<Advice> adviceList = new ArrayList<Advice>();
for (Method method : methods) {
Advice advice = asAdvice(method);
if (advice != null) adviceList.add(advice);
}
advice = new Advice[adviceList.size()];
adviceList.toArray(advice);
}
public Advice getAdvice(String name) throws NoSuchAdviceException {
if (name.equals("")) throw new IllegalArgumentException("use getAdvice(AdviceType...) instead for un-named advice");
if (advice == null) initAdvice();
for (Advice a : advice) {
if (a.getName().equals(name)) return a;
}
throw new NoSuchAdviceException(name);
}
public Advice getDeclaredAdvice(String name) throws NoSuchAdviceException {
if (name.equals("")) throw new IllegalArgumentException("use getAdvice(AdviceType...) instead for un-named advice");
if (declaredAdvice == null) initDeclaredAdvice();
for (Advice a : declaredAdvice) {
if (a.getName().equals(name)) return a;
}
throw new NoSuchAdviceException(name);
}
private Advice asAdvice(Method method) {
if (method.getAnnotations().length == 0) return null;
Before beforeAnn = method.getAnnotation(Before.class);
if (beforeAnn != null) return new AdviceImpl(method,beforeAnn.value(),AdviceKind.BEFORE);
After afterAnn = method.getAnnotation(After.class);
if (afterAnn != null) return new AdviceImpl(method,afterAnn.value(),AdviceKind.AFTER);
AfterReturning afterReturningAnn = method.getAnnotation(AfterReturning.class);
if (afterReturningAnn != null) {
String pcExpr = afterReturningAnn.pointcut();
if (pcExpr.equals("")) pcExpr = afterReturningAnn.value();
return new AdviceImpl(method,pcExpr,AdviceKind.AFTER_RETURNING,afterReturningAnn.returning());
}
AfterThrowing afterThrowingAnn = method.getAnnotation(AfterThrowing.class);
if (afterThrowingAnn != null) {
String pcExpr = afterThrowingAnn.pointcut();
if (pcExpr == null) pcExpr = afterThrowingAnn.value();
return new AdviceImpl(method,pcExpr,AdviceKind.AFTER_THROWING,afterThrowingAnn.throwing());
}
Around aroundAnn = method.getAnnotation(Around.class);
if (aroundAnn != null) return new AdviceImpl(method,aroundAnn.value(),AdviceKind.AROUND);
return null;
}
/* (non-Javadoc)
* @see org.aspectj.lang.reflect.AjType#getDeclaredITDMethod(java.lang.String, java.lang.Class, java.lang.Class...)
*/
public InterTypeMethodDeclaration getDeclaredITDMethod(String name,
AjType<?> target, AjType<?>... parameterTypes) throws NoSuchMethodException {
InterTypeMethodDeclaration[] itdms = getDeclaredITDMethods();
outer: for (InterTypeMethodDeclaration itdm : itdms) {
try {
if (!itdm.getName().equals(name)) continue;
AjType<?> itdTarget = itdm.getTargetType();
if (itdTarget.equals(target)) {
AjType<?>[] ptypes = itdm.getParameterTypes();
if (ptypes.length == parameterTypes.length) {
for (int i = 0; i < ptypes.length; i++) {
if (!ptypes[i].equals(parameterTypes[i]))
continue outer;
}
return itdm;
}
}
} catch (ClassNotFoundException cnf) {
// just move on to the next one
}
}
throw new NoSuchMethodException(name);
}
/* (non-Javadoc)
* @see org.aspectj.lang.reflect.AjType#getDeclaredITDMethods()
*/
public InterTypeMethodDeclaration[] getDeclaredITDMethods() {
if (this.declaredITDMethods == null) {
List<InterTypeMethodDeclaration> itdms = new ArrayList<InterTypeMethodDeclaration>();
Method[] baseMethods = clazz.getDeclaredMethods();
for (Method m : baseMethods) {
if (!m.getName().contains("ajc$interMethodDispatch1$")) continue;
if (m.isAnnotationPresent(ajcITD.class)) {
ajcITD ann = m.getAnnotation(ajcITD.class);
InterTypeMethodDeclaration itdm =
new InterTypeMethodDeclarationImpl(
this,ann.targetType(),ann.modifiers(),
ann.name(),m);
itdms.add(itdm);
}
}
addAnnotationStyleITDMethods(itdms,false);
this.declaredITDMethods = new InterTypeMethodDeclaration[itdms.size()];
itdms.toArray(this.declaredITDMethods);
}
return this.declaredITDMethods;
}
/* (non-Javadoc)
* @see org.aspectj.lang.reflect.AjType#getITDMethod(java.lang.String, java.lang.Class, java.lang.Class...)
*/
public InterTypeMethodDeclaration getITDMethod(String name, AjType<?> target,
AjType<?>... parameterTypes)
throws NoSuchMethodException {
InterTypeMethodDeclaration[] itdms = getITDMethods();
outer: for (InterTypeMethodDeclaration itdm : itdms) {
try {
if (!itdm.getName().equals(name)) continue;
AjType<?> itdTarget = itdm.getTargetType();
if (itdTarget.equals(target)) {
AjType<?>[] ptypes = itdm.getParameterTypes();
if (ptypes.length == parameterTypes.length) {
for (int i = 0; i < ptypes.length; i++) {
if (!ptypes[i].equals(parameterTypes[i]))
continue outer;
}
return itdm;
}
}
} catch (ClassNotFoundException cnf) {
// just move on to the next one
}
}
throw new NoSuchMethodException(name);
}
/* (non-Javadoc)
* @see org.aspectj.lang.reflect.AjType#getITDMethods()
*/
public InterTypeMethodDeclaration[] getITDMethods() {
if (this.itdMethods == null) {
List<InterTypeMethodDeclaration> itdms = new ArrayList<InterTypeMethodDeclaration>();
Method[] baseMethods = clazz.getDeclaredMethods();
for (Method m : baseMethods) {
if (!m.getName().contains("ajc$interMethod$")) continue;
if (m.isAnnotationPresent(ajcITD.class)) {
ajcITD ann = m.getAnnotation(ajcITD.class);
if (!Modifier.isPublic(ann.modifiers())) continue;
InterTypeMethodDeclaration itdm =
new InterTypeMethodDeclarationImpl(
this,ann.targetType(),ann.modifiers(),
ann.name(),m);
itdms.add(itdm);
}
}
addAnnotationStyleITDMethods(itdms,true);
this.itdMethods = new InterTypeMethodDeclaration[itdms.size()];
itdms.toArray(this.itdMethods);
}
return this.itdMethods;
}
private void addAnnotationStyleITDMethods(List<InterTypeMethodDeclaration> toList, boolean publicOnly) {
if (isAspect()) {
for (Field f : clazz.getDeclaredFields()) {
if (!f.getType().isInterface()) continue;
if (!Modifier.isPublic(f.getModifiers()) || !Modifier.isStatic(f.getModifiers())) continue;
if (f.isAnnotationPresent(org.aspectj.lang.annotation.DeclareParents.class)) {
for (Method itdM : f.getType().getDeclaredMethods()) {
if (!Modifier.isPublic(itdM.getModifiers()) && publicOnly) continue;
InterTypeMethodDeclaration itdm = new InterTypeMethodDeclarationImpl(
this, AjTypeSystem.getAjType(f.getType()), itdM
);
toList.add(itdm);
}
}
}
}
}
private void addAnnotationStyleITDFields(List<InterTypeFieldDeclaration> toList, boolean publicOnly) {
return;
//AV: I think it is meaningless
//@AJ decp is interface driven ie no field
}
/* (non-Javadoc)
* @see org.aspectj.lang.reflect.AjType#getDeclaredITDConstructor(java.lang.Class, java.lang.Class...)
*/
public InterTypeConstructorDeclaration getDeclaredITDConstructor(
AjType<?> target, AjType<?>... parameterTypes) throws NoSuchMethodException {
InterTypeConstructorDeclaration[] itdcs = getDeclaredITDConstructors();
outer: for (InterTypeConstructorDeclaration itdc : itdcs) {
try {
AjType<?> itdTarget = itdc.getTargetType();
if (itdTarget.equals(target)) {
AjType<?>[] ptypes = itdc.getParameterTypes();
if (ptypes.length == parameterTypes.length) {
for (int i = 0; i < ptypes.length; i++) {
if (!ptypes[i].equals(parameterTypes[i]))
continue outer;
}
return itdc;
}
}
} catch (ClassNotFoundException cnf) {
// just move on to the next one
}
}
throw new NoSuchMethodException();
}
/* (non-Javadoc)
* @see org.aspectj.lang.reflect.AjType#getDeclaredITDConstructors()
*/
public InterTypeConstructorDeclaration[] getDeclaredITDConstructors() {
if (this.declaredITDCons == null) {
List<InterTypeConstructorDeclaration> itdcs = new ArrayList<InterTypeConstructorDeclaration>();
Method[] baseMethods = clazz.getDeclaredMethods();
for (Method m : baseMethods) {
if (!m.getName().contains("ajc$postInterConstructor")) continue;
if (m.isAnnotationPresent(ajcITD.class)) {
ajcITD ann = m.getAnnotation(ajcITD.class);
InterTypeConstructorDeclaration itdc =
new InterTypeConstructorDeclarationImpl(this,ann.targetType(),ann.modifiers(),m);
itdcs.add(itdc);
}
}
this.declaredITDCons = new InterTypeConstructorDeclaration[itdcs.size()];
itdcs.toArray(this.declaredITDCons);
}
return this.declaredITDCons;
}
/* (non-Javadoc)
* @see org.aspectj.lang.reflect.AjType#getITDConstructor(java.lang.Class, java.lang.Class...)
*/
public InterTypeConstructorDeclaration getITDConstructor(AjType<?> target,
AjType<?>... parameterTypes) throws NoSuchMethodException {
InterTypeConstructorDeclaration[] itdcs = getITDConstructors();
outer: for (InterTypeConstructorDeclaration itdc : itdcs) {
try {
AjType<?> itdTarget = itdc.getTargetType();
if (itdTarget.equals(target)) {
AjType<?>[] ptypes = itdc.getParameterTypes();
if (ptypes.length == parameterTypes.length) {
for (int i = 0; i < ptypes.length; i++) {
if (!ptypes[i].equals(parameterTypes[i]))
continue outer;
}
return itdc;
}
}
} catch (ClassNotFoundException cnf) {
// just move on to the next one
}
}
throw new NoSuchMethodException();
}
/* (non-Javadoc)
* @see org.aspectj.lang.reflect.AjType#getITDConstructors()
*/
public InterTypeConstructorDeclaration[] getITDConstructors() {
if (this.itdCons == null) {
List<InterTypeConstructorDeclaration> itdcs = new ArrayList<InterTypeConstructorDeclaration>();
Method[] baseMethods = clazz.getMethods();
for (Method m : baseMethods) {
if (!m.getName().contains("ajc$postInterConstructor")) continue;
if (m.isAnnotationPresent(ajcITD.class)) {
ajcITD ann = m.getAnnotation(ajcITD.class);
if (!Modifier.isPublic(ann.modifiers())) continue;
InterTypeConstructorDeclaration itdc =
new InterTypeConstructorDeclarationImpl(this,ann.targetType(),ann.modifiers(),m);
itdcs.add(itdc);
}
}
this.itdCons = new InterTypeConstructorDeclaration[itdcs.size()];
itdcs.toArray(this.itdCons);
}
return this.itdCons; }
/* (non-Javadoc)
* @see org.aspectj.lang.reflect.AjType#getDeclaredITDField(java.lang.String, java.lang.Class)
*/
public InterTypeFieldDeclaration getDeclaredITDField(String name,
AjType<?> target) throws NoSuchFieldException {
InterTypeFieldDeclaration[] itdfs = getDeclaredITDFields();
for (InterTypeFieldDeclaration itdf : itdfs) {
if (itdf.getName().equals(name)) {
try {
AjType<?> itdTarget = itdf.getTargetType();
if (itdTarget.equals(target)) return itdf;
} catch (ClassNotFoundException cnfEx) {
// move on to next field
}
}
}
throw new NoSuchFieldException(name);
}
/* (non-Javadoc)
* @see org.aspectj.lang.reflect.AjType#getDeclaredITDFields()
*/
public InterTypeFieldDeclaration[] getDeclaredITDFields() {
List<InterTypeFieldDeclaration> itdfs = new ArrayList<InterTypeFieldDeclaration>();
if (this.declaredITDFields == null) {
Method[] baseMethods = clazz.getDeclaredMethods();
for(Method m : baseMethods) {
if (m.isAnnotationPresent(ajcITD.class)) {
if (!m.getName().contains("ajc$interFieldInit")) continue;
ajcITD ann = m.getAnnotation(ajcITD.class);
String interFieldInitMethodName = m.getName();
String interFieldGetDispatchMethodName =
interFieldInitMethodName.replace("FieldInit","FieldGetDispatch");
try {
Method dispatch = clazz.getDeclaredMethod(interFieldGetDispatchMethodName, m.getParameterTypes());
InterTypeFieldDeclaration itdf = new InterTypeFieldDeclarationImpl(
this,ann.targetType(),ann.modifiers(),ann.name(),
AjTypeSystem.getAjType(dispatch.getReturnType()),
dispatch.getGenericReturnType());
itdfs.add(itdf);
} catch (NoSuchMethodException nsmEx) {
throw new IllegalStateException("Can't find field get dispatch method for " + m.getName());
}
}
}
addAnnotationStyleITDFields(itdfs, false);
this.declaredITDFields = new InterTypeFieldDeclaration[itdfs.size()];
itdfs.toArray(this.declaredITDFields);
}
return this.declaredITDFields;
}
/* (non-Javadoc)
* @see org.aspectj.lang.reflect.AjType#getITDField(java.lang.String, java.lang.Class)
*/
public InterTypeFieldDeclaration getITDField(String name, AjType<?> target)
throws NoSuchFieldException {
InterTypeFieldDeclaration[] itdfs = getITDFields();
for (InterTypeFieldDeclaration itdf : itdfs) {
if (itdf.getName().equals(name)) {
try {
AjType<?> itdTarget = itdf.getTargetType();
if (itdTarget.equals(target)) return itdf;
} catch (ClassNotFoundException cnfEx) {
// move on to next field
}
}
}
throw new NoSuchFieldException(name);
}
/* (non-Javadoc)
* @see org.aspectj.lang.reflect.AjType#getITDFields()
*/
public InterTypeFieldDeclaration[] getITDFields() {
List<InterTypeFieldDeclaration> itdfs = new ArrayList<InterTypeFieldDeclaration>();
if (this.itdFields == null) {
Method[] baseMethods = clazz.getMethods();
for(Method m : baseMethods) {
if (m.isAnnotationPresent(ajcITD.class)) {
ajcITD ann = m.getAnnotation(ajcITD.class);
if (!m.getName().contains("ajc$interFieldInit")) continue;
if (!Modifier.isPublic(ann.modifiers())) continue;
String interFieldInitMethodName = m.getName();
String interFieldGetDispatchMethodName =
interFieldInitMethodName.replace("FieldInit","FieldGetDispatch");
try {
Method dispatch = m.getDeclaringClass().getDeclaredMethod(interFieldGetDispatchMethodName, m.getParameterTypes());
InterTypeFieldDeclaration itdf = new InterTypeFieldDeclarationImpl(
this,ann.targetType(),ann.modifiers(),ann.name(),
AjTypeSystem.getAjType(dispatch.getReturnType()),
dispatch.getGenericReturnType());
itdfs.add(itdf);
} catch (NoSuchMethodException nsmEx) {
throw new IllegalStateException("Can't find field get dispatch method for " + m.getName());
}
}
}
addAnnotationStyleITDFields(itdfs, true);
this.itdFields = new InterTypeFieldDeclaration[itdfs.size()];
itdfs.toArray(this.itdFields);
}
return this.itdFields;
}
/* (non-Javadoc)
* @see org.aspectj.lang.reflect.AjType#getDeclareErrorOrWarnings()
*/
public DeclareErrorOrWarning[] getDeclareErrorOrWarnings() {
List<DeclareErrorOrWarning> deows = new ArrayList<DeclareErrorOrWarning>();
for (Field field : clazz.getDeclaredFields()) {
try {
if (field.isAnnotationPresent(DeclareWarning.class)) {
DeclareWarning dw = field.getAnnotation(DeclareWarning.class);
if (Modifier.isPublic(field.getModifiers()) && Modifier.isStatic(field.getModifiers())) {
String message = (String) field.get(null);
DeclareErrorOrWarningImpl deow = new DeclareErrorOrWarningImpl(dw.value(),message,false,this);
deows.add(deow);
}
} else if (field.isAnnotationPresent(DeclareError.class)) {
DeclareError de = field.getAnnotation(DeclareError.class);
if (Modifier.isPublic(field.getModifiers()) && Modifier.isStatic(field.getModifiers())) {
String message = (String) field.get(null);
DeclareErrorOrWarningImpl deow = new DeclareErrorOrWarningImpl(de.value(),message,true,this);
deows.add(deow);
}
}
} catch (IllegalArgumentException e) {
// just move on to the next field
} catch (IllegalAccessException e) {
// just move on to the next field
}
}
for (Method method : clazz.getDeclaredMethods()) {
if (method.isAnnotationPresent(ajcDeclareEoW.class)) {
ajcDeclareEoW deowAnn = method.getAnnotation(ajcDeclareEoW.class);
DeclareErrorOrWarning deow = new DeclareErrorOrWarningImpl(deowAnn.pointcut(),deowAnn.message(),deowAnn.isError(),this);
deows.add(deow);
}
}
DeclareErrorOrWarning[] ret = new DeclareErrorOrWarning[deows.size()];
deows.toArray(ret);
return ret;
}
/* (non-Javadoc)
* @see org.aspectj.lang.reflect.AjType#getDeclareParents()
*/
public DeclareParents[] getDeclareParents() {
List<DeclareParents> decps = new ArrayList<DeclareParents>();
for (Method method : clazz.getDeclaredMethods()) {
if (method.isAnnotationPresent(ajcDeclareParents.class)) {
ajcDeclareParents decPAnn = method.getAnnotation(ajcDeclareParents.class);
DeclareParentsImpl decp = new DeclareParentsImpl(
decPAnn.targetTypePattern(),
decPAnn.parentTypes(),
decPAnn.isExtends(),
this
);
decps.add(decp);
}
}
addAnnotationStyleDeclareParents(decps);
if (getSupertype().isAspect()) {
decps.addAll(Arrays.asList(getSupertype().getDeclareParents()));
}
DeclareParents[] ret = new DeclareParents[decps.size()];
decps.toArray(ret);
return ret;
}
private void addAnnotationStyleDeclareParents(List<DeclareParents> toList) {
for (Field f : clazz.getDeclaredFields()) {
if (f.isAnnotationPresent(org.aspectj.lang.annotation.DeclareImplements.class)) {
if (!f.getType().isInterface()) continue;
org.aspectj.lang.annotation.DeclareImplements ann = f.getAnnotation(org.aspectj.lang.annotation.DeclareImplements.class);
String parentType = f.getType().getName();
DeclareParentsImpl decp = new DeclareParentsImpl(
ann.value(),
parentType,
false,
this
);
toList.add(decp);
}
if (f.isAnnotationPresent(org.aspectj.lang.annotation.DeclareParents.class)
&& Modifier.isStatic(f.getModifiers())
&& Modifier.isPublic(f.getModifiers())) {
if (!f.getType().isInterface()) continue;
org.aspectj.lang.annotation.DeclareParents ann = f.getAnnotation(org.aspectj.lang.annotation.DeclareParents.class);
String parentType = f.getType().getName();
DeclareParentsImpl decp = new DeclareParentsImpl(
ann.value(),
parentType,
false,
this
);
toList.add(decp);
}
}
}
/* (non-Javadoc)
* @see org.aspectj.lang.reflect.AjType#getDeclareSofts()
*/
public DeclareSoft[] getDeclareSofts() {
List<DeclareSoft> decs = new ArrayList<DeclareSoft>();
for (Method method : clazz.getDeclaredMethods()) {
if (method.isAnnotationPresent(ajcDeclareSoft.class)) {
ajcDeclareSoft decSAnn = method.getAnnotation(ajcDeclareSoft.class);
DeclareSoftImpl ds = new DeclareSoftImpl(
this,
decSAnn.pointcut(),
decSAnn.exceptionType()
);
decs.add(ds);
}
}
if (getSupertype().isAspect()) {
decs.addAll(Arrays.asList(getSupertype().getDeclareSofts()));
}
DeclareSoft[] ret = new DeclareSoft[decs.size()];
decs.toArray(ret);
return ret;
}
/* (non-Javadoc)
* @see org.aspectj.lang.reflect.AjType#getDeclareAnnotations()
*/
public DeclareAnnotation[] getDeclareAnnotations() {
List<DeclareAnnotation> decAs = new ArrayList<DeclareAnnotation>();
for (Method method : clazz.getDeclaredMethods()) {
if (method.isAnnotationPresent(ajcDeclareAnnotation.class)) {
ajcDeclareAnnotation decAnn = method.getAnnotation(ajcDeclareAnnotation.class);
// the target annotation is on this method...
Annotation targetAnnotation = null;
Annotation[] anns = method.getAnnotations();
for (Annotation ann: anns) {
if (ann.annotationType() != ajcDeclareAnnotation.class) {
// this must be the one...
targetAnnotation = ann;
break;
}
}
DeclareAnnotationImpl da = new DeclareAnnotationImpl(
this,
decAnn.kind(),
decAnn.pattern(),
targetAnnotation,
decAnn.annotation()
);
decAs.add(da);
}
}
if (getSupertype().isAspect()) {
decAs.addAll(Arrays.asList(getSupertype().getDeclareAnnotations()));
}
DeclareAnnotation[] ret = new DeclareAnnotation[decAs.size()];
decAs.toArray(ret);
return ret;
}
/* (non-Javadoc)
* @see org.aspectj.lang.reflect.AjType#getDeclarePrecedence()
*/
public DeclarePrecedence[] getDeclarePrecedence() {
List<DeclarePrecedence> decps = new ArrayList<DeclarePrecedence>();
// @AspectJ Style
if (clazz.isAnnotationPresent(org.aspectj.lang.annotation.DeclarePrecedence.class)) {
org.aspectj.lang.annotation.DeclarePrecedence ann =
clazz.getAnnotation(org.aspectj.lang.annotation.DeclarePrecedence.class);
DeclarePrecedenceImpl decp = new DeclarePrecedenceImpl(
ann.value(),
this
);
decps.add(decp);
}
// annotated code-style
for (Method method : clazz.getDeclaredMethods()) {
if (method.isAnnotationPresent(ajcDeclarePrecedence.class)) {
ajcDeclarePrecedence decPAnn = method.getAnnotation(ajcDeclarePrecedence.class);
DeclarePrecedenceImpl decp = new DeclarePrecedenceImpl(
decPAnn.value(),
this
);
decps.add(decp);
}
}
if (getSupertype().isAspect()) {
decps.addAll(Arrays.asList(getSupertype().getDeclarePrecedence()));
}
DeclarePrecedence[] ret = new DeclarePrecedence[decps.size()];
decps.toArray(ret);
return ret;
}
/* (non-Javadoc)
* @see org.aspectj.lang.reflect.AjType#getEnumConstants()
*/
public T[] getEnumConstants() {
return clazz.getEnumConstants();
}
/* (non-Javadoc)
* @see org.aspectj.lang.reflect.AjType#getTypeParameters()
*/
public TypeVariable<Class<T>>[] getTypeParameters() {
return clazz.getTypeParameters();
}
/* (non-Javadoc)
* @see org.aspectj.lang.reflect.AjType#isEnum()
*/
public boolean isEnum() {
return clazz.isEnum();
}
/* (non-Javadoc)
* @see org.aspectj.lang.reflect.AjType#isInstance(java.lang.Object)
*/
public boolean isInstance(Object o) {
return clazz.isInstance(o);
}
/* (non-Javadoc)
* @see org.aspectj.lang.reflect.AjType#isInterface()
*/
public boolean isInterface() {
return clazz.isInterface();
}
/* (non-Javadoc)
* @see org.aspectj.lang.reflect.AjType#isLocalClass()
*/
public boolean isLocalClass() {
return clazz.isLocalClass() && !isAspect();
}
/* (non-Javadoc)
* @see org.aspectj.lang.reflect.AjType#isMemberClass()
*/
public boolean isMemberClass() {
return clazz.isMemberClass() && !isAspect();
}
/* (non-Javadoc)
* @see org.aspectj.lang.reflect.AjType#isArray()
*/
public boolean isArray() {
return clazz.isArray();
}
/* (non-Javadoc)
* @see org.aspectj.lang.reflect.AjType#isPrimitive()
*/
public boolean isPrimitive() {
return clazz.isPrimitive();
}
/* (non-Javadoc)
* @see org.aspectj.lang.reflect.AjType#isAspect()
*/
public boolean isAspect() {
return clazz.getAnnotation(Aspect.class) != null;
}
/* (non-Javadoc)
* @see org.aspectj.lang.reflect.AjType#isMemberAspect()
*/
public boolean isMemberAspect() {
return clazz.isMemberClass() && isAspect();
}
public boolean isPrivileged() {
return isAspect() && clazz.isAnnotationPresent(ajcPrivileged.class);
}
@Override
public boolean equals(Object obj) {
if (!(obj instanceof AjTypeImpl)) return false;
AjTypeImpl other = (AjTypeImpl) obj;
return other.clazz.equals(clazz);
}
@Override
public int hashCode() {
return clazz.hashCode();
}
private AjType<?>[] toAjTypeArray(Class<?>[] classes) {
AjType<?>[] ajtypes = new AjType<?>[classes.length];
for (int i = 0; i < ajtypes.length; i++) {
ajtypes[i] = AjTypeSystem.getAjType(classes[i]);
}
return ajtypes;
}
private Class<?>[] toClassArray(AjType<?>[] ajTypes) {
Class<?>[] classes = new Class<?>[ajTypes.length];
for (int i = 0; i < classes.length; i++) {
classes[i] = ajTypes[i].getJavaClass();
}
return classes;
}
public String toString() { return getName(); }
}
|
119,352 |
Bug 119352 AjType.getSupertype breaks for null
|
I ran into this while using reflection proxies with LTW... See attached patches for these test cases and my fix: public void testObjectSupertype() { AjType<?> objectSuper = AjTypeSystem.getAjType(Object.class).getSupertype(); assertNull(objectSuper); } public void testInterfaceSupertype() { AjType<?> serializableSuper = AjTypeSystem.getAjType(Serializable.class).getSupertype(); assertNull(serializableSuper); } public AjType<? super T> getSupertype() { Class<? super T> superclass = clazz.getSuperclass(); return superclass==null ? null : (AjType<? super T>) new AjTypeImpl(superclass); }
|
resolved fixed
|
6e8bf52
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2005-12-06T15:39:08Z | 2005-12-06T03:33:20Z |
aspectj5rt/java5-testsrc/org/aspectj/internal/lang/reflect/AjTypeTests.java
|
/* *******************************************************************
* Copyright (c) 2005 Contributors.
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Eclipse Public License v1.0
* which accompanies this distribution and is available at
* http://eclipse.org/legal/epl-v10.html
*
* Contributors:
* Adrian Colyer initial implementation
* ******************************************************************/
package org.aspectj.internal.lang.reflect;
import java.io.Serializable;
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 java.lang.reflect.TypeVariable;
import junit.framework.TestCase;
import org.aspectj.lang.reflect.AjType;
import org.aspectj.lang.reflect.AjTypeSystem;
public class AjTypeTests extends TestCase {
private AjType<String> stringType;
@Override
protected void setUp() throws Exception {
super.setUp();
stringType = AjTypeSystem.getAjType(String.class);
}
public void testCreateAjType() {
assertNotNull("should find type",stringType);
}
public void testGetName() {
assertEquals(String.class.getName(),stringType.getName());
}
public void testGetPackage() {
assertEquals(String.class.getPackage(),stringType.getPackage());
}
public void testGetInterfaces() {
Class[] i1 = String.class.getInterfaces();
AjType<?>[] i2 = stringType.getInterfaces();
assertEquals(i1.length,i2.length);
for (int i = 0; i < i1.length; i++)
assertEquals(i1[i],i2[i].getJavaClass());
}
public void testGetModifiers() {
assertEquals(String.class.getModifiers(),stringType.getModifiers());
}
public void testGetSupertype() {
Class<?> stringSuper = String.class.getSuperclass();
AjType ajSuper = stringType.getSupertype();
assertEquals(AjTypeSystem.getAjType(stringSuper),ajSuper);
}
public void testGetGenericSupertype() {
Type t = AjTypeSystem.getAjType(Goo.class).getGenericSupertype();
assertEquals(Foo.class,t);
}
public void testGetEnclosingMethod() {
new Goo().foo();
}
public void testGetEnclosingConstructor() {
new Goo();
}
public void testGetEnclosingType() {
AjType t = AjTypeSystem.getAjType(Foo.Z.class);
assertEquals("org.aspectj.internal.lang.reflect.Foo",t.getEnclosingType().getName());
}
public void testGetDeclaringType() {
AjType t = AjTypeSystem.getAjType(Foo.Z.class);
assertEquals("org.aspectj.internal.lang.reflect.Foo",t.getDeclaringType().getName());
}
public void testIsAnnotationPresent() {
AjType<Foo> foo = AjTypeSystem.getAjType(Foo.class);
AjType<Goo> goo = AjTypeSystem.getAjType(Goo.class);
assertTrue(foo.isAnnotationPresent(SomeAnn.class));
assertFalse(goo.isAnnotationPresent(SomeAnn.class));
}
public void testGetAnnotation() {
AjType<Foo> foo = AjTypeSystem.getAjType(Foo.class);
AjType<Goo> goo = AjTypeSystem.getAjType(Goo.class);
assertNotNull(foo.getAnnotation(SomeAnn.class));
assertNull(goo.getAnnotation(SomeAnn.class));
}
public void testGetAnnotations() {
AjType<Foo> foo = AjTypeSystem.getAjType(Foo.class);
AjType<Goo> goo = AjTypeSystem.getAjType(Goo.class);
assertEquals(1,foo.getAnnotations().length);
assertEquals(0,goo.getAnnotations().length);
}
public void testGetDeclaredAnnotations() {
AjType<Foo> foo = AjTypeSystem.getAjType(Foo.class);
AjType<Goo> goo = AjTypeSystem.getAjType(Goo.class);
assertEquals(0,goo.getDeclaredAnnotations().length);
assertEquals(1,foo.getDeclaredAnnotations().length);
}
public void testGetAjTypes() {
AjType<Foo> foo = AjTypeSystem.getAjType(Foo.class);
AjType[] fooTypes = foo.getAjTypes();
assertEquals(1,fooTypes.length);
assertEquals("org.aspectj.internal.lang.reflect.Foo$Z",fooTypes[0].getName());
}
public void testGetDeclaredAjTypes() {
AjType<Foo> foo = AjTypeSystem.getAjType(Foo.class);
AjType[] fooTypes = foo.getDeclaredAjTypes();
assertEquals(2,fooTypes.length);
// Alex -> Adrian: looks like you can not make assumption on the ordering
String s = " " + fooTypes[0].getName() + " " + fooTypes[1].getName();
assertTrue(s.indexOf(" org.aspectj.internal.lang.reflect.Foo$Z") >= 0);
assertTrue(s.indexOf(" org.aspectj.internal.lang.reflect.Foo$XX") >= 0);
}
public void testGetConstructor() throws Exception {
Constructor c1 = String.class.getConstructor(String.class);
Constructor c2 = stringType.getConstructor(stringType);
assertEquals(c1,c2);
}
public void testGetConstructors() {
Constructor[] c1 = String.class.getConstructors();
Constructor[] c2 = stringType.getConstructors();
assertEquals(c1.length,c2.length);
for (int i = 0; i < c1.length; i++)
assertEquals(c1[i],c2[i]);
}
public void testGetDeclaredConstructor() throws Exception {
Constructor c1 = String.class.getDeclaredConstructor(String.class);
Constructor c2 = stringType.getDeclaredConstructor(stringType);
assertEquals(c1,c2);
}
public void testGetDeclaredConstructors() {
Constructor[] c1 = String.class.getDeclaredConstructors();
Constructor[] c2 = stringType.getDeclaredConstructors();
assertEquals(c1.length,c2.length);
for (int i = 0; i < c1.length; i++)
assertEquals(c1[i],c2[i]);
}
public void testGetDeclaredField() throws Exception {
Field f1 = String.class.getDeclaredField("value");
Field f2 = stringType.getDeclaredField("value");
assertEquals(f1,f2);
}
public void testGetDeclaredFields() {
Field[] f1 = String.class.getDeclaredFields();
Field[] f2 = stringType.getDeclaredFields();
assertEquals(f1.length,f2.length);
for (int i = 0; i < f1.length; i++)
assertEquals(f1[i],f2[i]);
}
public void testGetField() throws Exception {
AjType<Goo> goo = AjTypeSystem.getAjType(Goo.class);
assertEquals("g",goo.getField("g").getName());
}
public void testGetFields() {
AjType<Goo> goo = AjTypeSystem.getAjType(Goo.class);
Field[] fields = goo.getFields();
assertEquals(1,fields.length);
assertEquals("g",fields[0].getName());
}
public void testGetDeclaredMethod() throws Exception {
Method m1 = String.class.getDeclaredMethod("toUpperCase");
Method m2 = stringType.getDeclaredMethod("toUpperCase");
assertEquals(m1,m2);
}
public void testGetMethod() throws Exception {
Method m1 = String.class.getMethod("toUpperCase");
Method m2 = stringType.getMethod("toUpperCase");
assertEquals(m1,m2);
}
public void testGetDeclaredMethods() {
Method[] m1 = String.class.getDeclaredMethods();
Method[] m2 = stringType.getDeclaredMethods();
assertEquals(m1.length,m2.length);
for (int i = 0; i < m1.length; i++)
assertEquals(m1[i],m2[i]);
}
public void testGetMethods() {
Method[] m1 = String.class.getMethods();
Method[] m2 = stringType.getMethods();
assertEquals(m1.length,m2.length);
for (int i = 0; i < m1.length; i++)
assertEquals(m1[i],m2[i]);
}
public void testGetEnumConstants() {
AjType e = AjTypeSystem.getAjType(E.class);
Object[] consts = e.getEnumConstants();
assertEquals(3,consts.length);
}
public void testGetTypeParameters() {
AjType<Foo> foo = AjTypeSystem.getAjType(Foo.class);
TypeVariable<Class<Foo>>[] tvs = foo.getTypeParameters();
assertEquals(1,tvs.length);
assertEquals("T",tvs[0].getName());
}
public void testIsEnum() {
assertFalse(stringType.isEnum());
}
public void testIsInstance() {
assertTrue(stringType.isInstance("I am"));
}
public void testIsInterface() {
assertFalse(stringType.isInterface());
assertTrue(AjTypeSystem.getAjType(Serializable.class).isInterface());
}
public void testIsLocalClass() {
assertFalse(stringType.isLocalClass());
}
public void testIsArray() {
assertFalse(stringType.isArray());
assertTrue(AjTypeSystem.getAjType(Integer[].class).isArray());
}
public void testIsPrimitive() {
assertFalse(stringType.isPrimitive());
assertTrue(AjTypeSystem.getAjType(boolean.class).isPrimitive());
}
public void testIsAspect() {
assertFalse(stringType.isAspect());
}
public void testIsMemberAspect() {
assertFalse(stringType.isMemberAspect());
}
public void testIsPrivileged() {
assertFalse(stringType.isPrivileged());
}
public void testEquals() {
AjType stringTypeTwo = AjTypeSystem.getAjType(String.class);
assertTrue(stringType.equals(stringTypeTwo));
}
public void testHashCode() {
AjType stringTypeTwo = AjTypeSystem.getAjType(String.class);
assertEquals(stringType.hashCode(),stringTypeTwo.hashCode());
}
}
@Retention(RetentionPolicy.RUNTIME)
@interface SomeAnn {}
@SomeAnn
class Foo<T> {
public Foo() {
class Y { int y; }
AjType t = AjTypeSystem.getAjType(Y.class);
Constructor c = t.getEnclosingConstructor();
if (!c.getName().equals("org.aspectj.internal.lang.reflect.Foo")) throw new RuntimeException("should have been Foo");
}
public void foo() {
class X { int x; }
AjType t = AjTypeSystem.getAjType(X.class);
Method m = t.getEnclosingMethod();
if (!m.getName().equals("foo")) throw new RuntimeException("should have been foo");
}
public class Z { int z; }
class XX { int xx; }
}
class Goo extends Foo {
@interface IX {}
public Goo() {
super();
}
public int g;
int g2;
}
enum E { A,B,C; }
|
109,614 |
Bug 109614 [waiting-on-build] [iajc.task] java.lang.RuntimeException: Ranges must be updated with an enclosing instructionList
| null |
resolved fixed
|
94159f9
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2005-12-08T11:43:16Z | 2005-09-15T13:13:20Z |
tests/bugs150/pr109614.java
| |
109,614 |
Bug 109614 [waiting-on-build] [iajc.task] java.lang.RuntimeException: Ranges must be updated with an enclosing instructionList
| null |
resolved fixed
|
94159f9
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2005-12-08T11:43:16Z | 2005-09-15T13:13:20Z |
tests/src/org/aspectj/systemtest/ajc150/Ajc150Tests.java
|
/*******************************************************************************
* Copyright (c) 2004 IBM
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* Andy Clement - initial API and implementation
*******************************************************************************/
package org.aspectj.systemtest.ajc150;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.List;
import junit.framework.Test;
import org.aspectj.apache.bcel.classfile.JavaClass;
import org.aspectj.apache.bcel.classfile.Method;
import org.aspectj.apache.bcel.classfile.Signature;
import org.aspectj.apache.bcel.util.ClassPath;
import org.aspectj.apache.bcel.util.SyntheticRepository;
import org.aspectj.asm.AsmManager;
import org.aspectj.asm.IHierarchy;
import org.aspectj.asm.IProgramElement;
import org.aspectj.asm.IRelationship;
import org.aspectj.asm.internal.Relationship;
import org.aspectj.testing.XMLBasedAjcTestCase;
import org.aspectj.util.LangUtil;
public class Ajc150Tests extends org.aspectj.testing.XMLBasedAjcTestCase {
public static Test suite() {
return XMLBasedAjcTestCase.loadSuite(Ajc150Tests.class);
}
protected File getSpecFile() {
return new File("../tests/src/org/aspectj/systemtest/ajc150/ajc150.xml");
}
// public void testGenericPTW_pr119539_1() { runTest("generic pertypewithin aspect - 1");}
//public void testGenericPTW_pr119539_2() { runTest("generic pertypewithin aspect - 2");}
//public void testGenericPTW_pr119539_3() { runTest("generic pertypewithin aspect - 3");}
/*
public void testBrokenDispatchByITD_pr72834() { runTest("broken dispatch");}
public void testMissingAccessor_pr73856() { runTest("missing accessor");}
public void testCunningDeclareParents_pr92311() { runTest("cunning declare parents");}
public void testGenericITDsAndAbstractMethodError_pr102357() { runTest("generic itds and abstract method error");}
*/
public void testGeneratingCodeForAnOldRuntime_pr116679_1() { runTest("generating code for a 1.2.1 runtime - 1");}
public void testGeneratingCodeForAnOldRuntime_pr116679_2() { runTest("generating code for a 1.2.1 runtime - 2");}
public void testAmbiguousMethod_pr118599_1() { runTest("ambiguous method when binary weaving - 1");}
public void testAmbiguousMethod_pr118599_2() { runTest("ambiguous method when binary weaving - 2");}
public void testAroundAdviceArrayAdviceSigs_pr118781() { runTest("verify error with around advice array sigs");}
public void testAtDeclareParents_pr117681() { runTest("at declare parents");}
public void testPrivilegeProblem_pr87525() { runTest("privilege problem with switch");}
public void testGenericAspects_pr115237() { runTest("aspectOf and generic aspects");}
public void testClassFormatError_pr114436() { runTest("ClassFormatError binary weaving perthis");}
public void testParserException_pr115788() { runTest("parser exception");}
public void testPossibleStaticImports_pr113066_1() { runTest("possible static imports bug - 1");}
public void testPossibleStaticImports_pr113066_2() { runTest("possible static imports bug - 2");}
public void testPossibleStaticImports_pr113066_3() { runTest("possible static imports bug - 3");}
public void testITDCtor_pr112783() { runTest("Problem with constructor ITDs");}
public void testAnnotatedITDFs_pr114005_1() { runTest("Annotated ITDFs - 1");}
public void testAnnotatedITDFs_pr114005_2() { runTest("Annotated ITDFs - 2");}
public void testCantCallSuperMethods_pr90143() { runTest("cant call super methods");}
public void testBrokenDecp_pr112476() { runTest("binary weaving decp broken");}
public void testUnboundFormal_pr112027() { runTest("unexpected error unboundFormalInPC");}
public void testNPEScopeSetup_pr115038() { runTest("NPE in ensureScopeSetup");}
public void testCCEGenerics_pr113445() { runTest("Generics ClassCastException");}
public void testMatthewsAspect_pr113947_1() { runTest("maws generic aspect - 1");}
public void testMatthewsAspect_pr113947_2() { runTest("maws generic aspect - 2");}
public void testFieldGet_pr114343() { runTest("field-get, generics and around advice");}
public void testFieldGet_pr114343_2() { runTest("field-get, generics and around advice - 2");}
public void testFieldGet_pr114343_3() { runTest("field-get, generics and around advice - 3");}
public void testCaptureBinding_pr114744() { runTest("capturebinding wildcard problem");}
public void testBadDecp_pr110788_1() { runTest("bad generic decp - 1");}
public void testBadDecp_pr110788_2() { runTest("bad generic decp - 2");}
public void testBadDecp_pr110788_3() { runTest("bad generic decp - 3");}
public void testBadDecp_pr110788_4() { runTest("bad generic decp - 4");}
public void testBrokenSwitch_pr117854() { runTest("broken switch transform");}
public void testVarargsITD_pr110906() { runTest("ITD varargs problem");}
public void testBadRenderer_pr86903() { runTest("bcelrenderer bad");}
//public void testIllegalInitialization_pr118326_1() { runTest("illegal initialization - 1");}
//public void testIllegalInitialization_pr118326_2() { runTest("illegal initialization - 2");}
public void testLintForAdviceSorting_pr111667() { runTest("lint for advice sorting");}
public void testIncompatibleClassChangeError_pr113630_1() {runTest("IncompatibleClassChangeError - errorscenario");}
public void testIncompatibleClassChangeError_pr113630_2() {runTest("IncompatibleClassChangeError - workingscenario");}
public void testFieldGetProblemWithGenericField_pr113861() {runTest("field-get problems with generic field");}
public void testAccesstoPrivateITDInNested_pr118698() { runTest("access to private ITD from nested type");}
public void testDeclareAnnotationOnNonExistentType_pr99191_1() { runTest("declare annotation on non existent type - 1");}
public void testDeclareAnnotationOnNonExistentType_pr99191_2() { runTest("declare annotation on non existent type - 2");}
public void testDeclareAnnotationOnNonExistentType_pr99191_3() { runTest("declare annotation on non existent type - 3");}
public void testDeclareAnnotationOnNonExistentType_pr99191_4() { runTest("declare annotation on non existent type - 4");}
public void testDeclareAnnotationOnNonExistentType_pr99191_5() { runTest("declare annotation on non existent type - 5");}
public void testBadGenericSigAttribute_pr110927() {
runTest("cant create signature attribute");
Signature sig = GenericsTests.getClassSignature(ajc,"I");
if (sig==null) fail("Couldn't find signature attribute for type I");
String sigString = sig.getSignature();
if (!(sigString.equals("Ljava/lang/Object;LIE2;LIE1<Ljava/lang/String;>;") ||
sigString.equals("Ljava/lang/Object;LIE1<Ljava/lang/String;>;LIE2;"))) {
fail("Signature was "+sigString+" when should have been something like Ljava/lang/Object;LIE1<Ljava/lang/String;>;LIE2;");
}
}
public void test_typeProcessingOrderWhenDeclareParents() {
runTest("Order of types passed to compiler determines weaving behavior");
}
public void test_aroundMethod() {
runTest("method called around in class");
}
public void test_aroundMethodAspect() {
runTest("method called around in aspect");
}
public void test_ambiguousBindingsDetection() {
runTest("Various kinds of ambiguous bindings");
}
public void test_ambiguousArgsDetection() {
runTest("ambiguous args");
}
public void testIncorrectExceptionTableWhenBreakInMethod_pr78021() {
runTest("Injecting exception into while loop with break statement causes catch block to be ignored");
}
public void testIncorrectExceptionTableWhenReturnInMethod_pr79554() {
runTest("Return in try-block disables catch-block if final-block is present");
}
public void testMissingDebugInfoForGeneratedMethods_pr82570() throws ClassNotFoundException {
runTest("Weaved code does not include debug lines");
boolean f = false;
JavaClass jc = getClassFrom(ajc.getSandboxDirectory(),"PR82570_1");
Method[] meths = jc.getMethods();
for (int i = 0; i < meths.length; i++) {
Method method = meths[i];
if (f) System.err.println("Line number table for "+method.getName()+method.getSignature()+" = "+method.getLineNumberTable());
assertTrue("Didn't find a line number table for method "+method.getName()+method.getSignature(),
method.getLineNumberTable()!=null);
}
// This test would determine the info isn't there if you pass -g:none ...
// cR = ajc(baseDir,new String[]{"PR82570_1.java","-g:none"});
// assertTrue("Expected no compile problem:"+cR,!cR.hasErrorMessages());
// System.err.println(cR.getStandardError());
// jc = getClassFrom(ajc.getSandboxDirectory(),"PR82570_1");
// meths = jc.getMethods();
// for (int i = 0; i < meths.length; i++) {
// Method method = meths[i];
// assertTrue("Found a line number table for method "+method.getName(),
// method.getLineNumberTable()==null);
// }
}
public void testCanOverrideProtectedMethodsViaITDandDecp_pr83303() {
runTest("compiler error when mixing inheritance, overriding and polymorphism");
}
public void testPerTypeWithin_pr106554() {runTest("Problem in staticinitialization with pertypewithin aspect");}
public void testPerTypeWithinMissesNamedInnerTypes() {
runTest("pertypewithin() handing of inner classes (1)");
}
public void testPerTypeWithinMissesAnonymousInnerTypes() {
runTest("pertypewithin() handing of inner classes (2)");
}
public void testPerTypeWithinIncorrectlyMatchingInterfaces() {
runTest("pertypewithin({interface}) illegal field modifier");
}
public void test051_arrayCloningInJava5() {
runTest("AJC possible bug with static nested classes");
}
public void testBadASMforEnums() throws IOException {
runTest("bad asm for enums");
if (LangUtil.is15VMOrGreater()) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
PrintWriter pw = new PrintWriter(baos);
AsmManager.dumptree(pw,AsmManager.getDefault().getHierarchy().getRoot(),0);
pw.flush();
String tree = baos.toString();
assertTrue("Expected 'Red [enumvalue]' somewhere in here:"+tree,tree.indexOf("Red [enumvalue]")!=-1);
}
}
public void npeOnTypeNotFound() {
runTest("structure model npe on type not found");
}
public void testNoRuntimeExceptionSoftening() {
runTest("declare soft of runtime exception");
}
public void testRuntimeNoSoftenWithHandler() {
runTest("declare soft w. catch block");
}
public void testSyntaxError() {
runTest("invalid cons syntax");
}
public void testVarargsInConsBug() {
runTest("varargs in constructor sig");
}
public void testAspectpathdirs() {
runTest("dirs on aspectpath");
}
public void testIntroSample() {
runTest("introduction sample");
}
public void testPTWInterface() {
runTest("pertypewithin({interface}) illegal field modifier");
}
public void testEnumCalledEnumEtc() {
runTest("enum called Enum, annotation called Annotation, etc");
}
public void testInternalCompilerError_pr86832() {
runTest("Internal compiler error");
}
public void testCloneMethod_pr83311() {
runTest("overriding/polymorphism error on interface method introduction");
}
// IfPointcut.findResidueInternal() was modified to make this test complete in a short amount
// of time - if you see it hanging, someone has messed with the optimization.
public void testIfEvaluationExplosion_pr94086() {
runTest("Exploding compile time with if() statements in pointcut");
}
public void testReflectNPE_pr94167() {runTest("NPE in reflect implementation");}
public void testStaticImports_pr84260() {runTest("static import failures");}
public void testGenerics_pr99089() {runTest("ArrayIndexOutOfBoundsException - Generics in privileged aspects");}
public void testGenerics_pr95993() {runTest("NPE at ClassScope.java:660 when compiling generic class");}
public void testItdGenerics_pr99228() {runTest("ITD of a field into a generic class");}
public void testItdGenerics_pr98320() {runTest("intertype with nested generic type");}
public void testItdGenerics_pr100227() {runTest("inner class with generic enclosing class");}
public void testItdGenerics_pr100260() {runTest("methods inherited from a generic parent");}
public void testSyntaxErrorNPE_pr103266() {runTest("NPE on syntax error");}
public void testFinalAbstractClass_pr109486() { runTest("Internal compiler error (ClassParser.java:242)");}
public void testComplexBinding_pr102210() { runTest("NullPointerException trying to compile");}
public void testIllegalStateExceptionOnNestedParameterizedType_pr106634() {
runTest("IllegalStateException unpacking signature of nested parameterized type");
}
public void testParseErrorOnAnnotationStarPlusPattern() {
runTest("(@Foo *)+ type pattern parse error");
}
public void test_pr106130_tooManyLocals() {
runTest("test weaving with > 256 locals");
}
public void testMissingNamePattern_pr106461() { runTest("missing name pattern"); }
public void testMissingNamePattern_pr107059() {
runTest("parser crashes on call(void (@a *)(..)");
}
public void testIntermediateAnnotationMatching() {
runTest("intermediate annotation matching");
}
public void testBadRuntimeTestGeneration() {
runTest("target(@Foo *)");
}
public void testErrorMessageOnITDWithTypePatterns() {
runTest("clear error message on itd with type pattern");
}
public void testAjKeywordsAsIdentifiers() {
runTest("before and after are valid identifiers in classes");
}
public void testAjKeywordsAsIdentifiers2() {
runTest("before and after are valid identifiers in classes, part 2");
}
public void testNoBeforeReturningAdvice() {
runTest("before returning advice not allowed!");
}
public void testDetectVoidFieldType() {
runTest("void field type in pointcut expression");
}
public void testPointcutOverriding() {
runTest("overriding final pointcut from super-aspect");
}
public void testAtSuppressWarnings() {
runTest("@SuppressWarnings should suppress");
}
public void testDEOWWithBindingPointcut() {
runTest("declare warning : foo(str) : ...;");
}
public void testAroundAdviceAndInterfaceInitializer() {
runTest("around advice on interface initializer");
}
public void testGoodErrorMessageOnUnmatchedMemberSyntax() {
runTest("good error message for unmatched member syntax");
}
public void testITDWithNoExceptionAndIntermediary() {
runTest("itd override with no exception clause");
}
public void testAnonymousInnerClasses() {
runTest("anonymous inner classes");
}
public void testMultipleAnonymousInnerClasses() {
runTest("multiple anonymous inner classes");
}
public void testPrivilegedMethodAccessorsGetRightExceptions_pr82989() {
runTest("Compiler error due to a wrong exception check in try blocks");
}
public void testAnonymousInnerClassWithMethodReturningTypeParameter_pr107898() {
runTest("anonymous inner class with method returning type parameter");
}
public void testMatchingOfObjectArray() {
runTest("matching against Object[]");
}
public void testMultipleAnonymousInnerClasses_pr108104() {
runTest("multiple anonymous inner classes 2");
}
public void testSignatureMatchingInMultipleOverrideScenario() {
runTest("signature matching in override scenario");
}
public void testWildcardAnnotationMatching_pr108245() {
runTest("wildcard annotation matching - pr108245");
}
public void testInnerTypesAndTypeVariables() {
runTest("inner types and type variables");
}
public void testAtAfterThrowingWithNoFormal() {
runTest("@AfterThrowing with no formal specified");
}
public void testParameterizedVarArgsMatch() {
runTest("varargs with type variable");
}
public void testFieldAccessInsideITDM() {
runTest("itd field access inside itd method");
}
public void testTypeVarWithTypeVarBound() {
runTest("type variable with type variable bound");
}
public void testEnumSwitchInITD() {
runTest("switch on enum inside ITD method");
}
public void testInnerTypeOfGeneric() {
runTest("inner type of generic interface reference from parameterized type");
}
public void testDeclareParentsIntroducingCovariantReturnType() {
runTest("declare parents introducing override with covariance");
}
public void testInnerClassPassedToVarargs() {
runTest("inner class passed as argument to varargs method");
}
public void testInlinedFieldAccessInProceedCall() {
runTest("inlined field access in proceed call");
}
public void testVisibiltyInSignatureMatchingWithOverridesPart1() {
runTest("visibility in signature matching with overrides - 1");
}
public void testVisibiltyInSignatureMatchingWithOverridesPart2() {
runTest("visibility in signature matching with overrides - 2");
}
public void testVisibiltyInSignatureMatchingWithOverridesPart3() {
runTest("visibility in signature matching with overrides - 3");
}
public void testArgsGeneratedCorrectlyForAdviceExecution() {
runTest("args generated correctly for advice execution join point");
}
public void testNoUnusedWarningsOnAspectTypes() {
runTest("no unused warnings on aspect types");
}
public void testSyntheticArgumentsOnITDConstructorsNotUsedInMatching() {
runTest("synthetic arguments on itd cons are not used in matching");
}
public void testParsingOfGenericTypeSignature() {
runTest("parse generic type signature with parameterized type in interface");
}
public void testOverrideAndCovarianceWithDecPRuntime() {
runTest("override and covariance with decp - runtime");
}
public void testOverrideAndCovarianceWithDecPRuntimeMultiFiles() {
runTest("override and covariance with decp - runtime separate files");
}
public void testOverrideAndCovarianceWithDecPRuntimeMultiFilesBinaryWeaving() {
runTest("override and covariance with decp - binary weaving");
}
public void testAbstractSynchronizedITDMethods() {
runTest("abstract synchronized itdms not detected");
}
public void testSynchronizedITDInterfaceMethods() {
runTest("synchronized itd interface methods");
}
public void testNoWarningOnUnusedPointcut() {
runTest("unused private pointcuts");
}
public void testITDOnInterfaceWithExistingMember() {
runTest("itd interface method already existing on interface");
}
public void testFinalITDMOnInterface() {
runTest("final itd methods on interfaces");
}
public void testPrivatePointcutOverriding() {
runTest("can't override private pointcut in abstract aspect");
}
public void testAdviceOnCflow() {
runTest("advising cflow advice execution");
}
public void testNoTypeMismatchOnSameGenericTypes() {
runTest("no type mismatch on generic types in itds");
}
public void testSuperCallInITD() {
runTest("super call in ITD");
}
public void testSuperCallInITDPart2() {
runTest("super call in ITD - part 2");
}
public void testAtAnnotationBadTest_pr103740() {
runTest("Compiler failure on at_annotation");
}
public void testNoUnusedParameterWarningsForSyntheticAdviceArgs() {
runTest("no unused parameter warnings for synthetic advice args");
}
public void testNoVerifyErrorWithSetOnInnerType() {
runTest("no verify error with set on inner type");
}
public void testCantFindTypeErrorWithGenericReturnTypeOrParameter() {
runTest("cant find type error with generic return type or parameter");
}
public void testNoVerifyErrorOnGenericCollectionMemberAccess() {
runTest("no verify error on generic collection member access");
}
public void testRawAndGenericTypeConversionITDCons() {
runTest("raw and generic type conversion with itd cons");
}
public void testAtAnnotationBindingWithAround() {
runTest("@annotation binding with around advice");
}
public void testUnableToBuildShadows_pr109728() { runTest("Unable to build shadows");}
public void testMessageOnMissingTypeInDecP() {
runTest("declare parents on a missing type");
}
public void testParameterizedGenericMethods() {
runTest("parameterized generic methods");
}
public void testIllegalChangeToPointcutDeclaration_pr111915() {
runTest("test illegal change to pointcut declaration");
}
public void testCantProvideDefaultImplViaITD_pr110307_1() {runTest("Cant provide default implementation via ITD - 1");}
public void testCantProvideDefaultImplViaITD_pr110307_2() {runTest("Cant provide default implementation via ITD - 2");}
public void testCantProvideDefaultImplViaITD_pr110307_3() {runTest("Cant provide default implementation via ITD - 3");}
public void testCantProvideDefaultImplViaITD_pr110307_4() {runTest("Cant provide default implementation via ITD - 4");}
public void testCantProvideDefaultImplViaITD_pr110307_5() {runTest("Cant provide default implementation via ITD - 5");}
// Needs a change in the compiler so that getType() can be overridden in the intertype scope - thats
// where we can police whether a type variable has been used without being specified appropriately.
//public void testCantProvideDefaultImplViaITD_pr110307_6() {runTest("Cant provide default implementation via ITD - 6");}
public void testCantProvideDefaultImplViaITD_pr110307_7() {runTest("Cant provide default implementation via ITD - 7");}
public void testCallJoinPointsInAnonymousInnerClasses() {
runTest("call join points in anonymous inner classes");
}
public void testNoRequirementForUnwovenTypesToBeExposedToWeaver() {
runTest("default impl of Runnable");
}
public void testArrayCloneCallJoinPoints() {
runTest("array clone call join points in 1.4 vs 1.3");
}
public void testDebugInfoForAroundAdvice() {
runTest("debug info in around advice inlining");
}
public void testCCEWithGenericWildcard_pr112602() {
runTest("ClassCastException with generic wildcard");
}
public void testAdviceInStructureModelWithAnonymousInnerClass_pr77269() {
//AsmManager.setReporting("c:/debug.txt",true,true,true,true);
runTest("advice in structure model with anonymous inner class");
IHierarchy top = AsmManager.getDefault().getHierarchy();
// checking that the run() method inside anonymous inner class is in
// the structure model
IProgramElement anonRunMethodIPE = top.findElementForLabel(top.getRoot(),
IProgramElement.Kind.METHOD,"run()");
assertNotNull("Couldn't find 'run()' element in the tree",anonRunMethodIPE);
List l = AsmManager.getDefault().getRelationshipMap().get(anonRunMethodIPE);
assertNotNull("Should have some relationships but does not",l);
assertTrue("Should have one relationship but has " + l.size(),l.size()==1);
Relationship rel = (Relationship)l.get(0);
List targets = rel.getTargets();
assertTrue("Should have one target but has" + targets.size(),
targets.size()==1);
IProgramElement target = AsmManager.getDefault().getHierarchy().findElementForHandle((String)targets.get(0));
assertEquals("target of relationship should be 'before(): p..' but is "
+ target.toLabelString(),"before(): p..",target.toLabelString());
IProgramElement adviceIPE = top.findElementForLabel(top.getRoot(),
IProgramElement.Kind.ADVICE,"before(): p..");
assertNotNull("Couldn't find 'before(): p..' element in the tree",adviceIPE);
l = AsmManager.getDefault().getRelationshipMap().get(adviceIPE);
assertNotNull("Should have some relationships but does not",l);
assertTrue("Should have a relationship but does not ",l.size()>0);
for (Iterator iter = l.iterator(); iter.hasNext();) {
IRelationship element = (IRelationship) iter.next();
if (element.getName().equals("advises")) {
rel = (Relationship) element;
break;
}
}
targets = rel.getTargets();
assertTrue("Should have one target but has" + targets.size(),
targets.size()==1);
target = AsmManager.getDefault().getHierarchy().findElementForHandle((String)targets.get(0));
assertEquals("target of relationship should be 'run()' but is "
+ target.toLabelString(),"run()",target.toLabelString());
}
public void testAdviceInStructureModelWithNamedInnerClass_pr77269() {
//AsmManager.setReporting("c:/debug.txt",true,true,true,true);
runTest("advice in structure model with named inner class");
IHierarchy top = AsmManager.getDefault().getHierarchy();
// checking that the m() method inside named inner class is in
// the structure model
IProgramElement namedMethodIPE = top.findElementForLabel(top.getRoot(),
IProgramElement.Kind.METHOD,"m()");
assertNotNull("Couldn't find 'm()' element in the tree",namedMethodIPE);
List l = AsmManager.getDefault().getRelationshipMap().get(namedMethodIPE);
assertNotNull("Should have some relationships but does not",l);
assertTrue("Should have one relationship but has " + l.size(),l.size()==1);
Relationship rel = (Relationship)l.get(0);
List targets = rel.getTargets();
assertTrue("Should have one target but has" + targets.size(),
targets.size()==1);
IProgramElement target = AsmManager.getDefault().getHierarchy().findElementForHandle((String)targets.get(0));
assertEquals("target of relationship should be 'before(): p..' but is "
+ target.toLabelString(),"before(): p..",target.toLabelString());
IProgramElement adviceIPE = top.findElementForLabel(top.getRoot(),
IProgramElement.Kind.ADVICE,"before(): p..");
assertNotNull("Couldn't find 'before(): p..' element in the tree",adviceIPE);
l = AsmManager.getDefault().getRelationshipMap().get(adviceIPE);
assertNotNull("Should have some relationships but does not",l);
assertTrue("Should have a relationship but does not ",l.size()>0);
for (Iterator iter = l.iterator(); iter.hasNext();) {
IRelationship element = (IRelationship) iter.next();
if (element.getName().equals("advises")) {
rel = (Relationship) element;
break;
}
}
targets = rel.getTargets();
assertTrue("Should have one target but has" + targets.size(),
targets.size()==1);
target = AsmManager.getDefault().getHierarchy().findElementForHandle((String)targets.get(0));
assertEquals("target of relationship should be 'm()' but is "
+ target.toLabelString(),"m()",target.toLabelString());
}
public void testDWInStructureModelWithAnonymousInnerClass_pr77269() {
// AsmManager.setReporting("c:/debug.txt",true,true,true,true);
runTest("declare warning in structure model with anonymous inner class");
IHierarchy top = AsmManager.getDefault().getHierarchy();
IProgramElement pe = top.findElementForLabel(top.getRoot(),
IProgramElement.Kind.CODE,"method-call(void pack.Test.someMethod())");
assertNotNull("Couldn't find 'method-call(void pack.Test.someMethod())' element in the tree",pe);
}
public void testVarArgsIITDInConstructor() {
runTest("ITD varargs in constructor");
}
public void testWeaveInfoMessageForDeclareAtMethodOnITDdMethod() {
runTest("weaveinfo message for declare at method on an ITDd method");
}
public void testITDCWithNoExplicitConsCall() {
runTest("ITDC with no explicit cons call");
}
public void testJava5SpecificFeaturesUsedAtJava14OrLower() {
runTest("java 5 pointcuts and declares at pre-java 5 compliance levels");
}
public void testAnonymousTypes() {
runTest("Anonymous types and nome matching");
}
public void testAdviceExecutionJPToStringForms() {
runTest("adviceexecution join point toString forms");
}
public void testAssertWithinPointcutExpression() {
runTest("pointcut expression containing 'assert'");
}
public void testNoVerifyErrorWithTwoThisPCDs_pr113447() {
runTest("no verify error with two this pcds");
}
public void testNoVerifyErrorWithTwoAtThisPCDs_pr113447() {
runTest("no verify error with two at this pcds");
}
public void testNoVerifyErrorWithAtWithinPCDs_pr113447() {
runTest("no verify error with at within pcds");
}
public void testNoVerifyErrorWithAtWithincodePCDs_pr113447() {
runTest("no verify error with at withincode pcds");
}
public void testNoVerifyErrorWithAtAnnotationPCDs_pr113447() {
runTest("no verify error with at annotation pcds");
}
public void testNoVerifyErrorWithTwoArgsPCDs_pr113447() {
runTest("no verify error with two args pcds");
}
public void testNoStackOverflowWithCircularPCDInGenericAspect() {
runTest("no StackOverflowError with circular pcd in generic aspect");
}
public void testNoStackOverflowWithCircularPCDInGenericAspect2() {
runTest("no StackOverflowError with circular pcd in generic aspect - 2");
}
public void testNPEInThisJoinPointStaticPart() {
runTest("thisJoinPointStaticPart in if test");
}
public void testPointcutParsingOfCompiledPointcuts() {
runTest("pointcut parsing with ajc compiled pointcut references");
}
public void testReflectionOfAbstractITDs() {
runTest("reflection on abstract ITDs (Billing example)");
}
public void testDeclareSoftWithAdviceExecution() {
runTest("declare soft and adviceexecution");
}
public void testDeclareSoftWithExclusions() {
runTest("declare soft and exclusions");
}
public void testReturningObjectBinding() {
runTest("returning(Object) binding");
}
public void testPerTargetAndNegation() {
runTest("pertarget and negated pointcut");
}
public void testParameterizedPointcutAndAdvice() {
runTest("parameterized pointcut and advice");
}
public void testDoublyParameterizedAbstractType() {
runTest("double parameter generic abstract type");
}
public void testArgNamesInAdviceAnnotations() {
runTest("arg names in advice annotations");
}
/*
* Load-time weaving bugs
*/
public void testNPEinWeavingAdaptor_pr116626() { runTest("NPE in WeavingAdaptor");}
public void testXlintMessageForImproperAnnotationType_pr115252_Exact() {runTest("xlint message for improper exact annotation type");}
public void testXlintMessageForImproperAnnotationType_pr115252_OR() {runTest("xlint message for improper annotation type inside OR");}
public void testXlintMessageForImproperAnnotationType_pr115252_AND() {runTest("xlint message for improper annotation type inside AND");}
public void testXlintMessageForImproperAnnotationType_pr115252_Return() {runTest("xlint message for improper annotated return type");}
public void testXlintMessageForImproperAnnotationType_pr115252_Declaring() {runTest("xlint message for improper annotated declaring type");}
public void testXlintMessageForImproperAnnotationType_pr115252_Parameter() {runTest("xlint message for improper annotated parameter type");}
public void testXlintMessageForImproperAnnotationType_pr115252_Throws() {runTest("xlint message for improper annotated throws pattern");}
public void testXlintMessageForImproperAnnotationType_pr115252_MoreThanOne() {runTest("xlint message for more than one improper annotated parameter type");}
public void testDeclareAtTypeInStructureModel_pr115607() {
AsmManager.setReporting("c:/debug.txt",true,true,true,true);
runTest("declare at type appears correctly in structure model");
IHierarchy top = AsmManager.getDefault().getHierarchy();
IProgramElement pe = top.findElementForLabel(top.getRoot(),
IProgramElement.Kind.DECLARE_ANNOTATION_AT_TYPE,"declare @type: Simple : @I");
assertNotNull("Couldn't find 'declare @type: Simple : @I' element in the tree",pe);
List l = AsmManager.getDefault().getRelationshipMap().get(pe);
assertNotNull("Should have some relationships but does not",l);
}
public void testNoNPEWhenInaccessibleMethodIsCalledWithinITD_pr119019() {
runTest("no NPE when inaccessible method is called within itd");
}
public void testNoNPEWithOrPointcutAndMoreThanOneArgs_pr118149() {
runTest("no NPE with or pointcut and more than one args");
}
public void testNoSOBWithGenericInnerAspects_pr119543() {
runTest("no StringOutOfBoundsException with generic inner aspects");
}
// helper methods.....
public SyntheticRepository createRepos(File cpentry) {
ClassPath cp = new ClassPath(cpentry+File.pathSeparator+System.getProperty("java.class.path"));
return SyntheticRepository.getInstance(cp);
}
protected JavaClass getClassFrom(File where,String clazzname) throws ClassNotFoundException {
SyntheticRepository repos = createRepos(where);
return repos.loadClass(clazzname);
}
}
|
109,614 |
Bug 109614 [waiting-on-build] [iajc.task] java.lang.RuntimeException: Ranges must be updated with an enclosing instructionList
| null |
resolved fixed
|
94159f9
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2005-12-08T11:43:16Z | 2005-09-15T13:13:20Z |
weaver/src/org/aspectj/weaver/bcel/BcelShadow.java
|
/* *******************************************************************
* Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC).
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* PARC initial implementation
* Alexandre Vasseur support for @AJ aspects
* ******************************************************************/
package org.aspectj.weaver.bcel;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.aspectj.apache.bcel.Constants;
import org.aspectj.apache.bcel.classfile.Field;
import org.aspectj.apache.bcel.generic.ACONST_NULL;
import org.aspectj.apache.bcel.generic.ALOAD;
import org.aspectj.apache.bcel.generic.ANEWARRAY;
import org.aspectj.apache.bcel.generic.ArrayType;
import org.aspectj.apache.bcel.generic.BranchInstruction;
import org.aspectj.apache.bcel.generic.ConstantPoolGen;
import org.aspectj.apache.bcel.generic.DUP;
import org.aspectj.apache.bcel.generic.DUP_X1;
import org.aspectj.apache.bcel.generic.FieldInstruction;
import org.aspectj.apache.bcel.generic.INVOKEINTERFACE;
import org.aspectj.apache.bcel.generic.INVOKESPECIAL;
import org.aspectj.apache.bcel.generic.INVOKESTATIC;
import org.aspectj.apache.bcel.generic.Instruction;
import org.aspectj.apache.bcel.generic.InstructionConstants;
import org.aspectj.apache.bcel.generic.InstructionFactory;
import org.aspectj.apache.bcel.generic.InstructionHandle;
import org.aspectj.apache.bcel.generic.InstructionList;
import org.aspectj.apache.bcel.generic.InstructionTargeter;
import org.aspectj.apache.bcel.generic.InvokeInstruction;
import org.aspectj.apache.bcel.generic.LoadInstruction;
import org.aspectj.apache.bcel.generic.MULTIANEWARRAY;
import org.aspectj.apache.bcel.generic.NEW;
import org.aspectj.apache.bcel.generic.ObjectType;
import org.aspectj.apache.bcel.generic.PUSH;
import org.aspectj.apache.bcel.generic.ReturnInstruction;
import org.aspectj.apache.bcel.generic.SWAP;
import org.aspectj.apache.bcel.generic.StoreInstruction;
import org.aspectj.apache.bcel.generic.TargetLostException;
import org.aspectj.apache.bcel.generic.Type;
import org.aspectj.bridge.ISourceLocation;
import org.aspectj.weaver.Advice;
import org.aspectj.weaver.AdviceKind;
import org.aspectj.weaver.AjcMemberMaker;
import org.aspectj.weaver.BCException;
import org.aspectj.weaver.IntMap;
import org.aspectj.weaver.Member;
import org.aspectj.weaver.MemberImpl;
import org.aspectj.weaver.NameMangler;
import org.aspectj.weaver.NewConstructorTypeMunger;
import org.aspectj.weaver.NewFieldTypeMunger;
import org.aspectj.weaver.NewMethodTypeMunger;
import org.aspectj.weaver.ResolvedMember;
import org.aspectj.weaver.ResolvedMemberImpl;
import org.aspectj.weaver.ResolvedType;
import org.aspectj.weaver.Shadow;
import org.aspectj.weaver.ShadowMunger;
import org.aspectj.weaver.UnresolvedType;
import org.aspectj.weaver.WeaverMessages;
import org.aspectj.weaver.World;
import org.aspectj.weaver.ast.Var;
/*
* Some fun implementation stuff:
*
* * expressionKind advice is non-execution advice
* * may have a target.
* * if the body is extracted, it will be extracted into
* a static method. The first argument to the static
* method is the target
* * advice may expose a this object, but that's the advice's
* consideration, not ours. This object will NOT be cached in another
* local, but will always come from frame zero.
*
* * non-expressionKind advice is execution advice
* * may have a this.
* * target is same as this, and is exposed that way to advice
* (i.e., target will not be cached, will always come from frame zero)
* * if the body is extracted, it will be extracted into a method
* with same static/dynamic modifier as enclosing method. If non-static,
* target of callback call will be this.
*
* * because of these two facts, the setup of the actual arguments (including
* possible target) callback method is the same for both kinds of advice:
* push the targetVar, if it exists (it will not exist for advice on static
* things), then push all the argVars.
*
* Protected things:
*
* * the above is sufficient for non-expressionKind advice for protected things,
* since the target will always be this.
*
* * For expressionKind things, we have to modify the signature of the callback
* method slightly. For non-static expressionKind things, we modify
* the first argument of the callback method NOT to be the type specified
* by the method/field signature (the owner), but rather we type it to
* the currentlyEnclosing type. We are guaranteed this will be fine,
* since the verifier verifies that the target is a subtype of the currently
* enclosingType.
*
* Worries:
*
* * ConstructorCalls will be weirder than all of these, since they
* supposedly don't have a target (according to AspectJ), but they clearly
* do have a target of sorts, just one that needs to be pushed on the stack,
* dupped, and not touched otherwise until the constructor runs.
*
* @author Jim Hugunin
* @author Erik Hilsdale
*
*/
public class BcelShadow extends Shadow {
private ShadowRange range;
private final BcelWorld world;
private final LazyMethodGen enclosingMethod;
// private boolean fallsThrough; //XXX not used anymore
// SECRETAPI - for testing, this will tell us if the optimization succeeded *on the last shadow processed*
public static boolean appliedLazyTjpOptimization;
// Some instructions have a target type that will vary
// from the signature (pr109728) (1.4 declaring type issue)
private String actualInstructionTargetType;
// ---- initialization
/**
* This generates an unassociated shadow, rooted in a particular method but not rooted
* to any particular point in the code. It should be given to a rooted ShadowRange
* in the {@link ShadowRange#associateWithShadow(BcelShadow)} method.
*/
public BcelShadow(
BcelWorld world,
Kind kind,
Member signature,
LazyMethodGen enclosingMethod,
BcelShadow enclosingShadow)
{
super(kind, signature, enclosingShadow);
this.world = world;
this.enclosingMethod = enclosingMethod;
// fallsThrough = kind.argsOnStack();
}
// ---- copies all state, including Shadow's mungers...
public BcelShadow copyInto(LazyMethodGen recipient, BcelShadow enclosing) {
BcelShadow s = new BcelShadow(world, getKind(), getSignature(), recipient, enclosing);
List src = mungers;
List dest = s.mungers;
for (Iterator i = src.iterator(); i.hasNext(); ) {
dest.add(i.next());
}
return s;
}
// ---- overridden behaviour
public World getIWorld() {
return world;
}
private void deleteNewAndDup() {
final ConstantPoolGen cpg = getEnclosingClass().getConstantPoolGen();
int depth = 1;
InstructionHandle ih = range.getStart();
while (true) {
Instruction inst = ih.getInstruction();
if (inst instanceof INVOKESPECIAL
&& ((INVOKESPECIAL) inst).getName(cpg).equals("<init>")) {
depth++;
} else if (inst instanceof NEW) {
depth--;
if (depth == 0) break;
}
ih = ih.getPrev();
}
// now IH points to the NEW. We're followed by the DUP, and that is followed
// by the actual instruciton we care about.
InstructionHandle newHandle = ih;
InstructionHandle endHandle = newHandle.getNext();
InstructionHandle nextHandle;
if (endHandle.getInstruction() instanceof DUP) {
nextHandle = endHandle.getNext();
retargetFrom(newHandle, nextHandle);
retargetFrom(endHandle, nextHandle);
} else if (endHandle.getInstruction() instanceof DUP_X1) {
InstructionHandle dupHandle = endHandle;
endHandle = endHandle.getNext();
nextHandle = endHandle.getNext();
if (endHandle.getInstruction() instanceof SWAP) {}
else {
// XXX see next XXX comment
throw new RuntimeException("Unhandled kind of new " + endHandle);
}
retargetFrom(newHandle, nextHandle);
retargetFrom(dupHandle, nextHandle);
retargetFrom(endHandle, nextHandle);
} else {
endHandle = newHandle;
nextHandle = endHandle.getNext();
retargetFrom(newHandle, nextHandle);
// add a POP here... we found a NEW w/o a dup or anything else, so
// we must be in statement context.
getRange().insert(InstructionConstants.POP, Range.OutsideAfter);
}
// assert (dupHandle.getInstruction() instanceof DUP);
try {
range.getBody().delete(newHandle, endHandle);
} catch (TargetLostException e) {
throw new BCException("shouldn't happen");
}
}
private void retargetFrom(InstructionHandle old, InstructionHandle fresh) {
InstructionTargeter[] sources = old.getTargeters();
if (sources != null) {
for (int i = sources.length - 1; i >= 0; i--) {
sources[i].updateTarget(old, fresh);
}
}
}
// records advice that is stopping us doing the lazyTjp optimization
private List badAdvice = null;
public void addAdvicePreventingLazyTjp(BcelAdvice advice) {
if (badAdvice == null) badAdvice = new ArrayList();
badAdvice.add(advice);
}
protected void prepareForMungers() {
// if we're a constructor call, we need to remove the new:dup or the new:dup_x1:swap,
// and store all our
// arguments on the frame.
// ??? This is a bit of a hack (for the Java langauge). We do this because
// we sometime add code "outsideBefore" when dealing with weaving join points. We only
// do this for exposing state that is on the stack. It turns out to just work for
// everything except for constructor calls and exception handlers. If we were to clean
// this up, every ShadowRange would have three instructionHandle points, the start of
// the arg-setup code, the start of the running code, and the end of the running code.
if (getKind() == ConstructorCall) {
deleteNewAndDup();
initializeArgVars();
} else if (getKind() == PreInitialization) { // pr74952
ShadowRange range = getRange();
range.insert(InstructionConstants.NOP,Range.InsideAfter);
} else if (getKind() == ExceptionHandler) {
ShadowRange range = getRange();
InstructionList body = range.getBody();
InstructionHandle start = range.getStart();
// Create a store instruction to put the value from the top of the
// stack into a local variable slot. This is a trimmed version of
// what is in initializeArgVars() (since there is only one argument
// at a handler jp and only before advice is supported) (pr46298)
argVars = new BcelVar[1];
//int positionOffset = (hasTarget() ? 1 : 0) + ((hasThis() && !getKind().isTargetSameAsThis()) ? 1 : 0);
UnresolvedType tx = getArgType(0);
argVars[0] = genTempVar(tx, "ajc$arg0");
InstructionHandle insertedInstruction =
range.insert(argVars[0].createStore(getFactory()), Range.OutsideBefore);
// Now the exception range starts just after our new instruction.
// The next bit of code changes the exception range to point at
// the store instruction
InstructionTargeter[] targeters = start.getTargeters();
for (int i = 0; i < targeters.length; i++) {
InstructionTargeter t = targeters[i];
if (t instanceof ExceptionRange) {
ExceptionRange er = (ExceptionRange) t;
er.updateTarget(start, insertedInstruction, body);
}
}
}
// now we ask each munger to request our state
isThisJoinPointLazy = true;//world.isXlazyTjp(); // lazy is default now
badAdvice = null;
for (Iterator iter = mungers.iterator(); iter.hasNext();) {
ShadowMunger munger = (ShadowMunger) iter.next();
munger.specializeOn(this);
}
initializeThisJoinPoint();
if (thisJoinPointVar!=null && !isThisJoinPointLazy && badAdvice!=null && badAdvice.size()>1) {
// something stopped us making it a lazy tjp
// can't build tjp lazily, no suitable test...
int valid = 0;
for (Iterator iter = badAdvice.iterator(); iter.hasNext();) {
BcelAdvice element = (BcelAdvice) iter.next();
ISourceLocation sLoc = element.getSourceLocation();
if (sLoc!=null && sLoc.getLine()>0) valid++;
}
if (valid!=0) {
ISourceLocation[] badLocs = new ISourceLocation[valid];
int i = 0;
for (Iterator iter = badAdvice.iterator(); iter.hasNext();) {
BcelAdvice element = (BcelAdvice) iter.next();
ISourceLocation sLoc = element.getSourceLocation();
if (sLoc!=null) badLocs[i++]=sLoc;
}
world.getLint().multipleAdviceStoppingLazyTjp.signal(
new String[] {this.toString()},
getSourceLocation(),badLocs
);
}
}
badAdvice=null;
// If we are an expression kind, we require our target/arguments on the stack
// before we do our actual thing. However, they may have been removed
// from the stack as the shadowMungers have requested state.
// if any of our shadowMungers requested either the arguments or target,
// the munger will have added code
// to pop the target/arguments into temporary variables, represented by
// targetVar and argVars. In such a case, we must make sure to re-push the
// values.
// If we are nonExpressionKind, we don't expect arguments on the stack
// so this is moot. If our argVars happen to be null, then we know that
// no ShadowMunger has squirrelled away our arguments, so they're still
// on the stack.
InstructionFactory fact = getFactory();
if (getKind().argsOnStack() && argVars != null) {
// Special case first (pr46298). If we are an exception handler and the instruction
// just after the shadow is a POP then we should remove the pop. The code
// above which generated the store instruction has already cleared the stack.
// We also don't generate any code for the arguments in this case as it would be
// an incorrect aload.
if (getKind() == ExceptionHandler
&& range.getEnd().getNext().getInstruction().equals(InstructionConstants.POP)) {
// easier than deleting it ...
range.getEnd().getNext().setInstruction(InstructionConstants.NOP);
} else {
range.insert(
BcelRenderer.renderExprs(fact, world, argVars),
Range.InsideBefore);
if (targetVar != null) {
range.insert(
BcelRenderer.renderExpr(fact, world, targetVar),
Range.InsideBefore);
}
if (getKind() == ConstructorCall) {
range.insert((Instruction) InstructionFactory.createDup(1), Range.InsideBefore);
range.insert(
fact.createNew(
(ObjectType) BcelWorld.makeBcelType(
getSignature().getDeclaringType())),
Range.InsideBefore);
}
}
}
}
// ---- getters
public ShadowRange getRange() {
return range;
}
public void setRange(ShadowRange range) {
this.range = range;
}
public int getSourceLine() {
// if the kind of join point for which we are a shadow represents
// a method or constructor execution, then the best source line is
// the one from the enclosingMethod declarationLineNumber if available.
Kind kind = getKind();
if ( (kind == MethodExecution) ||
(kind == ConstructorExecution) ||
(kind == AdviceExecution) ||
(kind == StaticInitialization) ||
(kind == PreInitialization) ||
(kind == Initialization)) {
if (getEnclosingMethod().hasDeclaredLineNumberInfo()) {
return getEnclosingMethod().getDeclarationLineNumber();
}
}
if (range == null) {
if (getEnclosingMethod().hasBody()) {
return Utility.getSourceLine(getEnclosingMethod().getBody().getStart());
} else {
return 0;
}
}
int ret = Utility.getSourceLine(range.getStart());
if (ret < 0) return 0;
return ret;
}
// overrides
public UnresolvedType getEnclosingType() {
return getEnclosingClass().getType();
}
public LazyClassGen getEnclosingClass() {
return enclosingMethod.getEnclosingClass();
}
public BcelWorld getWorld() {
return world;
}
// ---- factory methods
public static BcelShadow makeConstructorExecution(
BcelWorld world,
LazyMethodGen enclosingMethod,
InstructionHandle justBeforeStart)
{
final InstructionList body = enclosingMethod.getBody();
BcelShadow s =
new BcelShadow(
world,
ConstructorExecution,
world.makeJoinPointSignature(enclosingMethod),
enclosingMethod,
null);
ShadowRange r = new ShadowRange(body);
r.associateWithShadow(s);
r.associateWithTargets(
Range.genStart(body, justBeforeStart.getNext()),
Range.genEnd(body));
return s;
}
public static BcelShadow makeStaticInitialization(
BcelWorld world,
LazyMethodGen enclosingMethod)
{
InstructionList body = enclosingMethod.getBody();
// move the start past ajc$preClinit
InstructionHandle clinitStart = body.getStart();
if (clinitStart.getInstruction() instanceof InvokeInstruction) {
InvokeInstruction ii = (InvokeInstruction)clinitStart.getInstruction();
if (ii
.getName(enclosingMethod.getEnclosingClass().getConstantPoolGen())
.equals(NameMangler.AJC_PRE_CLINIT_NAME)) {
clinitStart = clinitStart.getNext();
}
}
InstructionHandle clinitEnd = body.getEnd();
//XXX should move the end before the postClinit, but the return is then tricky...
// if (clinitEnd.getInstruction() instanceof InvokeInstruction) {
// InvokeInstruction ii = (InvokeInstruction)clinitEnd.getInstruction();
// if (ii.getName(enclosingMethod.getEnclosingClass().getConstantPoolGen()).equals(NameMangler.AJC_POST_CLINIT_NAME)) {
// clinitEnd = clinitEnd.getPrev();
// }
// }
BcelShadow s =
new BcelShadow(
world,
StaticInitialization,
world.makeJoinPointSignature(enclosingMethod),
enclosingMethod,
null);
ShadowRange r = new ShadowRange(body);
r.associateWithShadow(s);
r.associateWithTargets(
Range.genStart(body, clinitStart),
Range.genEnd(body, clinitEnd));
return s;
}
/** Make the shadow for an exception handler. Currently makes an empty shadow that
* only allows before advice to be woven into it.
*/
public static BcelShadow makeExceptionHandler(
BcelWorld world,
ExceptionRange exceptionRange,
LazyMethodGen enclosingMethod,
InstructionHandle startOfHandler,
BcelShadow enclosingShadow)
{
InstructionList body = enclosingMethod.getBody();
UnresolvedType catchType = exceptionRange.getCatchType();
UnresolvedType inType = enclosingMethod.getEnclosingClass().getType();
ResolvedMemberImpl sig = MemberImpl.makeExceptionHandlerSignature(inType, catchType);
sig.parameterNames = new String[] {findHandlerParamName(startOfHandler)};
BcelShadow s =
new BcelShadow(
world,
ExceptionHandler,
sig,
enclosingMethod,
enclosingShadow);
ShadowRange r = new ShadowRange(body);
r.associateWithShadow(s);
InstructionHandle start = Range.genStart(body, startOfHandler);
InstructionHandle end = Range.genEnd(body, start);
r.associateWithTargets(start, end);
exceptionRange.updateTarget(startOfHandler, start, body);
return s;
}
private static String findHandlerParamName(InstructionHandle startOfHandler) {
if (startOfHandler.getInstruction() instanceof StoreInstruction &&
startOfHandler.getNext() != null)
{
int slot = ((StoreInstruction)startOfHandler.getInstruction()).getIndex();
//System.out.println("got store: " + startOfHandler.getInstruction() + ", " + index);
InstructionTargeter[] targeters = startOfHandler.getNext().getTargeters();
if (targeters!=null) {
for (int i=targeters.length-1; i >= 0; i--) {
if (targeters[i] instanceof LocalVariableTag) {
LocalVariableTag t = (LocalVariableTag)targeters[i];
if (t.getSlot() == slot) {
return t.getName();
}
//System.out.println("tag: " + targeters[i]);
}
}
}
}
return "<missing>";
}
/** create an init join point associated w/ an interface in the body of a constructor */
public static BcelShadow makeIfaceInitialization(
BcelWorld world,
LazyMethodGen constructor,
Member interfaceConstructorSignature)
{
// 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 makeMethodCall(
BcelWorld world,
LazyMethodGen enclosingMethod,
InstructionHandle callHandle,
BcelShadow enclosingShadow)
{
final InstructionList body = enclosingMethod.getBody();
BcelShadow s =
new BcelShadow(
world,
MethodCall,
world.makeJoinPointSignatureForMethodInvocation(
enclosingMethod.getEnclosingClass(),
(InvokeInstruction) callHandle.getInstruction()),
enclosingMethod,
enclosingShadow);
ShadowRange r = new ShadowRange(body);
r.associateWithShadow(s);
r.associateWithTargets(
Range.genStart(body, callHandle),
Range.genEnd(body, callHandle));
retargetAllBranches(callHandle, r.getStart());
return s;
}
public static BcelShadow makeShadowForMethodCall(
BcelWorld world,
LazyMethodGen enclosingMethod,
InstructionHandle callHandle,
BcelShadow enclosingShadow,
Kind kind,
ResolvedMember sig)
{
final InstructionList body = enclosingMethod.getBody();
BcelShadow s =
new BcelShadow(
world,
kind,
sig,
enclosingMethod,
enclosingShadow);
ShadowRange r = new ShadowRange(body);
r.associateWithShadow(s);
r.associateWithTargets(
Range.genStart(body, callHandle),
Range.genEnd(body, callHandle));
retargetAllBranches(callHandle, r.getStart());
return s;
}
public static BcelShadow makeFieldGet(
BcelWorld world,
ResolvedMember field,
LazyMethodGen enclosingMethod,
InstructionHandle getHandle,
BcelShadow enclosingShadow)
{
final InstructionList body = enclosingMethod.getBody();
BcelShadow s =
new BcelShadow(
world,
FieldGet,
field,
// BcelWorld.makeFieldSignature(
// enclosingMethod.getEnclosingClass(),
// (FieldInstruction) getHandle.getInstruction()),
enclosingMethod,
enclosingShadow);
ShadowRange r = new ShadowRange(body);
r.associateWithShadow(s);
r.associateWithTargets(
Range.genStart(body, getHandle),
Range.genEnd(body, getHandle));
retargetAllBranches(getHandle, r.getStart());
return s;
}
public static BcelShadow makeFieldSet(
BcelWorld world,
LazyMethodGen enclosingMethod,
InstructionHandle setHandle,
BcelShadow enclosingShadow)
{
final InstructionList body = enclosingMethod.getBody();
BcelShadow s =
new BcelShadow(
world,
FieldSet,
BcelWorld.makeFieldJoinPointSignature(
enclosingMethod.getEnclosingClass(),
(FieldInstruction) setHandle.getInstruction()),
enclosingMethod,
enclosingShadow);
ShadowRange r = new ShadowRange(body);
r.associateWithShadow(s);
r.associateWithTargets(
Range.genStart(body, setHandle),
Range.genEnd(body, setHandle));
retargetAllBranches(setHandle, r.getStart());
return s;
}
public static void retargetAllBranches(InstructionHandle from, InstructionHandle to) {
InstructionTargeter[] sources = from.getTargeters();
if (sources != null) {
for (int i = sources.length - 1; i >= 0; i--) {
InstructionTargeter source = sources[i];
if (source instanceof BranchInstruction) {
source.updateTarget(from, to);
}
}
}
}
// // ---- type access methods
// private ObjectType getTargetBcelType() {
// return (ObjectType) BcelWorld.makeBcelType(getTargetType());
// }
// private Type getArgBcelType(int arg) {
// return BcelWorld.makeBcelType(getArgType(arg));
// }
// ---- kinding
/**
* If the end of my range has no real instructions following then
* my context needs a return at the end.
*/
public boolean terminatesWithReturn() {
return getRange().getRealNext() == null;
}
/**
* Is arg0 occupied with the value of this
*/
public boolean arg0HoldsThis() {
if (getKind().isEnclosingKind()) {
return !getSignature().isStatic();
} else if (enclosingShadow == null) {
//XXX this is mostly right
// this doesn't do the right thing for calls in the pre part of introduced constructors.
return !enclosingMethod.isStatic();
} else {
return ((BcelShadow)enclosingShadow).arg0HoldsThis();
}
}
// ---- argument getting methods
private BcelVar thisVar = null;
private BcelVar targetVar = null;
private BcelVar[] argVars = null;
private Map/*<UnresolvedType,BcelVar>*/ kindedAnnotationVars = null;
private Map/*<UnresolvedType,BcelVar>*/ thisAnnotationVars = null;
private Map/*<UnresolvedType,BcelVar>*/ targetAnnotationVars = null;
private Map/*<UnresolvedType,BcelVar>*/[] argAnnotationVars = null;
private Map/*<UnresolvedType,BcelVar>*/ withinAnnotationVars = null;
private Map/*<UnresolvedType,BcelVar>*/ withincodeAnnotationVars = null;
public Var getThisVar() {
if (!hasThis()) {
throw new IllegalStateException("no this");
}
initializeThisVar();
return thisVar;
}
public Var getThisAnnotationVar(UnresolvedType forAnnotationType) {
if (!hasThis()) {
throw new IllegalStateException("no this");
}
initializeThisAnnotationVars(); // FIXME asc Why bother with this if we always return one?
// Even if we can't find one, we have to return one as we might have this annotation at runtime
Var v = (Var) thisAnnotationVars.get(forAnnotationType);
if (v==null)
v = new TypeAnnotationAccessVar(forAnnotationType.resolve(world),(BcelVar)getThisVar());
return v;
}
public Var getTargetVar() {
if (!hasTarget()) {
throw new IllegalStateException("no target");
}
initializeTargetVar();
return targetVar;
}
public Var getTargetAnnotationVar(UnresolvedType forAnnotationType) {
if (!hasTarget()) {
throw new IllegalStateException("no target");
}
initializeTargetAnnotationVars(); // FIXME asc why bother with this if we always return one?
Var v =(Var) targetAnnotationVars.get(forAnnotationType);
// Even if we can't find one, we have to return one as we might have this annotation at runtime
if (v==null)
v = new TypeAnnotationAccessVar(forAnnotationType.resolve(world),(BcelVar)getTargetVar());
return v;
}
public Var getArgVar(int i) {
initializeArgVars();
return argVars[i];
}
public Var getArgAnnotationVar(int i,UnresolvedType forAnnotationType) {
initializeArgAnnotationVars();
Var v= (Var) argAnnotationVars[i].get(forAnnotationType);
if (v==null)
v = new TypeAnnotationAccessVar(forAnnotationType.resolve(world),(BcelVar)getArgVar(i));
return v;
}
public Var getKindedAnnotationVar(UnresolvedType forAnnotationType) {
initializeKindedAnnotationVars();
return (Var) kindedAnnotationVars.get(forAnnotationType);
}
public Var getWithinAnnotationVar(UnresolvedType forAnnotationType) {
initializeWithinAnnotationVars();
return (Var) withinAnnotationVars.get(forAnnotationType);
}
public Var getWithinCodeAnnotationVar(UnresolvedType forAnnotationType) {
initializeWithinCodeAnnotationVars();
return (Var) withincodeAnnotationVars.get(forAnnotationType);
}
// reflective thisJoinPoint support
private BcelVar thisJoinPointVar = null;
private boolean isThisJoinPointLazy;
private int lazyTjpConsumers = 0;
private BcelVar thisJoinPointStaticPartVar = null;
// private BcelVar thisEnclosingJoinPointStaticPartVar = null;
public final Var getThisJoinPointStaticPartVar() {
return getThisJoinPointStaticPartBcelVar();
}
public final Var getThisEnclosingJoinPointStaticPartVar() {
return getThisEnclosingJoinPointStaticPartBcelVar();
}
public void requireThisJoinPoint(boolean hasGuardTest, boolean isAround) {
if (!isAround){
if (!hasGuardTest) {
isThisJoinPointLazy = false;
} else {
lazyTjpConsumers++;
}
}
// if (!hasGuardTest) {
// isThisJoinPointLazy = false;
// } else {
// lazyTjpConsumers++;
// }
if (thisJoinPointVar == null) {
thisJoinPointVar = genTempVar(UnresolvedType.forName("org.aspectj.lang.JoinPoint"));
}
}
public Var getThisJoinPointVar() {
requireThisJoinPoint(false,false);
return thisJoinPointVar;
}
void initializeThisJoinPoint() {
if (thisJoinPointVar == null) return;
if (isThisJoinPointLazy) {
isThisJoinPointLazy = checkLazyTjp();
}
if (isThisJoinPointLazy) {
appliedLazyTjpOptimization = true;
createThisJoinPoint(); // make sure any state needed is initialized, but throw the instructions out
if (lazyTjpConsumers == 1) return; // special case only one lazyTjpUser
InstructionFactory fact = getFactory();
InstructionList il = new InstructionList();
il.append(InstructionConstants.ACONST_NULL);
il.append(thisJoinPointVar.createStore(fact));
range.insert(il, Range.OutsideBefore);
} else {
appliedLazyTjpOptimization = false;
InstructionFactory fact = getFactory();
InstructionList il = createThisJoinPoint();
il.append(thisJoinPointVar.createStore(fact));
range.insert(il, Range.OutsideBefore);
}
}
private boolean checkLazyTjp() {
// check for around advice
for (Iterator i = mungers.iterator(); i.hasNext();) {
ShadowMunger munger = (ShadowMunger) i.next();
if (munger instanceof Advice) {
if ( ((Advice)munger).getKind() == AdviceKind.Around) {
if (munger.getSourceLocation()!=null) { // do we know enough to bother reporting?
world.getLint().canNotImplementLazyTjp.signal(
new String[] {toString()},
getSourceLocation(),
new ISourceLocation[] { munger.getSourceLocation() }
);
}
return false;
}
}
}
return true;
}
InstructionList loadThisJoinPoint() {
InstructionFactory fact = getFactory();
InstructionList il = new InstructionList();
if (isThisJoinPointLazy) {
// If we're lazy, build the join point right here.
il.append(createThisJoinPoint());
// Does someone else need it? If so, store it for later retrieval
if (lazyTjpConsumers > 1) {
il.append(thisJoinPointVar.createStore(fact));
InstructionHandle end = il.append(thisJoinPointVar.createLoad(fact));
il.insert(InstructionFactory.createBranchInstruction(Constants.IFNONNULL, end));
il.insert(thisJoinPointVar.createLoad(fact));
}
} else {
// If not lazy, its already been built and stored, just retrieve it
thisJoinPointVar.appendLoad(il, fact);
}
return il;
}
InstructionList createThisJoinPoint() {
InstructionFactory fact = getFactory();
InstructionList il = new InstructionList();
BcelVar staticPart = getThisJoinPointStaticPartBcelVar();
staticPart.appendLoad(il, fact);
if (hasThis()) {
((BcelVar)getThisVar()).appendLoad(il, fact);
} else {
il.append(new ACONST_NULL());
}
if (hasTarget()) {
((BcelVar)getTargetVar()).appendLoad(il, fact);
} else {
il.append(new ACONST_NULL());
}
switch(getArgCount()) {
case 0:
il.append(fact.createInvoke("org.aspectj.runtime.reflect.Factory",
"makeJP", LazyClassGen.tjpType,
new Type[] { LazyClassGen.staticTjpType,
Type.OBJECT, Type.OBJECT},
Constants.INVOKESTATIC));
break;
case 1:
((BcelVar)getArgVar(0)).appendLoadAndConvert(il, fact, world.getCoreType(ResolvedType.OBJECT));
il.append(fact.createInvoke("org.aspectj.runtime.reflect.Factory",
"makeJP", LazyClassGen.tjpType,
new Type[] { LazyClassGen.staticTjpType,
Type.OBJECT, Type.OBJECT, Type.OBJECT},
Constants.INVOKESTATIC));
break;
case 2:
((BcelVar)getArgVar(0)).appendLoadAndConvert(il, fact, world.getCoreType(ResolvedType.OBJECT));
((BcelVar)getArgVar(1)).appendLoadAndConvert(il, fact, world.getCoreType(ResolvedType.OBJECT));
il.append(fact.createInvoke("org.aspectj.runtime.reflect.Factory",
"makeJP", LazyClassGen.tjpType,
new Type[] { LazyClassGen.staticTjpType,
Type.OBJECT, Type.OBJECT, Type.OBJECT, Type.OBJECT},
Constants.INVOKESTATIC));
break;
default:
il.append(makeArgsObjectArray());
il.append(fact.createInvoke("org.aspectj.runtime.reflect.Factory",
"makeJP", LazyClassGen.tjpType,
new Type[] { LazyClassGen.staticTjpType,
Type.OBJECT, Type.OBJECT, new ArrayType(Type.OBJECT, 1)},
Constants.INVOKESTATIC));
break;
}
return il;
}
/**
* Get the Var for the jpStaticPart
* @return
*/
public BcelVar getThisJoinPointStaticPartBcelVar() {
return getThisJoinPointStaticPartBcelVar(false);
}
/**
* Get the Var for the xxxxJpStaticPart, xxx = this or enclosing
* @param isEnclosingJp true to have the enclosingJpStaticPart
* @return
*/
public BcelVar getThisJoinPointStaticPartBcelVar(final boolean isEnclosingJp) {
if (thisJoinPointStaticPartVar == null) {
Field field = getEnclosingClass().getTjpField(this, isEnclosingJp);
ResolvedType sjpType = null;
if (world.isTargettingAspectJRuntime12()) { // TAG:SUPPORTING12: We didn't have different jpsp types in 1.2
sjpType = world.getCoreType(UnresolvedType.forName("org.aspectj.lang.JoinPoint$StaticPart"));
} else {
sjpType = isEnclosingJp?
world.getCoreType(UnresolvedType.forName("org.aspectj.lang.JoinPoint$EnclosingStaticPart")):
world.getCoreType(UnresolvedType.forName("org.aspectj.lang.JoinPoint$StaticPart"));
}
thisJoinPointStaticPartVar = new BcelFieldRef(
sjpType,
getEnclosingClass().getClassName(),
field.getName());
// getEnclosingClass().warnOnAddedStaticInitializer(this,munger.getSourceLocation());
}
return thisJoinPointStaticPartVar;
}
/**
* Get the Var for the enclosingJpStaticPart
* @return
*/
public BcelVar getThisEnclosingJoinPointStaticPartBcelVar() {
if (enclosingShadow == null) {
// the enclosing of an execution is itself
return getThisJoinPointStaticPartBcelVar(true);
} else {
return ((BcelShadow)enclosingShadow).getThisJoinPointStaticPartBcelVar(true);
}
}
//??? need to better understand all the enclosing variants
public Member getEnclosingCodeSignature() {
if (getKind().isEnclosingKind()) {
return getSignature();
} else if (getKind() == Shadow.PreInitialization) {
// PreInit doesn't enclose code but its signature
// is correctly the signature of the ctor.
return getSignature();
} else if (enclosingShadow == null) {
return getEnclosingMethod().getMemberView();
} else {
return enclosingShadow.getSignature();
}
}
private InstructionList makeArgsObjectArray() {
InstructionFactory fact = getFactory();
BcelVar arrayVar = genTempVar(UnresolvedType.OBJECTARRAY);
final InstructionList il = new InstructionList();
int alen = getArgCount() ;
il.append(Utility.createConstant(fact, alen));
il.append((Instruction)fact.createNewArray(Type.OBJECT, (short)1));
arrayVar.appendStore(il, fact);
int stateIndex = 0;
for (int i = 0, len = getArgCount(); i<len; i++) {
arrayVar.appendConvertableArrayStore(il, fact, stateIndex, (BcelVar)getArgVar(i));
stateIndex++;
}
arrayVar.appendLoad(il, fact);
return il;
}
// ---- initializing var tables
/* initializing this is doesn't do anything, because this
* is protected from side-effects, so we don't need to copy its location
*/
private void initializeThisVar() {
if (thisVar != null) return;
thisVar = new BcelVar(getThisType().resolve(world), 0);
thisVar.setPositionInAroundState(0);
}
public void initializeTargetVar() {
InstructionFactory fact = getFactory();
if (targetVar != null) return;
if (getKind().isTargetSameAsThis()) {
if (hasThis()) initializeThisVar();
targetVar = thisVar;
} else {
initializeArgVars(); // gotta pop off the args before we find the target
UnresolvedType type = getTargetType();
type = ensureTargetTypeIsCorrect(type);
targetVar = genTempVar(type, "ajc$target");
range.insert(targetVar.createStore(fact), Range.OutsideBefore);
targetVar.setPositionInAroundState(hasThis() ? 1 : 0);
}
}
/* PR 72528
* This method double checks the target type under certain conditions. The Java 1.4
* compilers seem to take calls to clone methods on array types and create bytecode that
* looks like clone is being called on Object. If we advise a clone call with around
* advice we extract the call into a helper method which we can then refer to. Because the
* type in the bytecode for the call to clone is Object we create a helper method with
* an Object parameter - this is not correct as we have lost the fact that the actual
* type is an array type. If we don't do the check below we will create code that fails
* java verification. This method checks for the peculiar set of conditions and if they
* are true, it has a sneak peek at the code before the call to see what is on the stack.
*/
public UnresolvedType ensureTargetTypeIsCorrect(UnresolvedType tx) {
if (tx.equals(ResolvedType.OBJECT) && getKind() == MethodCall &&
getSignature().getReturnType().equals(ResolvedType.OBJECT) &&
getSignature().getArity()==0 &&
getSignature().getName().charAt(0) == 'c' &&
getSignature().getName().equals("clone")) {
// Lets go back through the code from the start of the shadow
InstructionHandle searchPtr = range.getStart().getPrev();
while (Range.isRangeHandle(searchPtr) ||
searchPtr.getInstruction() instanceof StoreInstruction) { // ignore this instruction - it doesnt give us the info we want
searchPtr = searchPtr.getPrev();
}
// A load instruction may tell us the real type of what the clone() call is on
if (searchPtr.getInstruction() instanceof LoadInstruction) {
LoadInstruction li = (LoadInstruction)searchPtr.getInstruction();
li.getIndex();
LocalVariableTag lvt = LazyMethodGen.getLocalVariableTag(searchPtr,li.getIndex());
return lvt.getType();
}
// A field access instruction may tell us the real type of what the clone() call is on
if (searchPtr.getInstruction() instanceof FieldInstruction) {
FieldInstruction si = (FieldInstruction)searchPtr.getInstruction();
Type t = si.getFieldType(getEnclosingClass().getConstantPoolGen());
return BcelWorld.fromBcel(t);
}
// A new array instruction obviously tells us it is an array type !
if (searchPtr.getInstruction() instanceof ANEWARRAY) {
//ANEWARRAY ana = (ANEWARRAY)searchPoint.getInstruction();
//Type t = ana.getType(getEnclosingClass().getConstantPoolGen());
// Just use a standard java.lang.object array - that will work fine
return BcelWorld.fromBcel(new ArrayType(Type.OBJECT,1));
}
// A multi new array instruction obviously tells us it is an array type !
if (searchPtr.getInstruction() instanceof MULTIANEWARRAY) {
MULTIANEWARRAY ana = (MULTIANEWARRAY)searchPtr.getInstruction();
// Type t = ana.getType(getEnclosingClass().getConstantPoolGen());
// t = new ArrayType(t,ana.getDimensions());
// Just use a standard java.lang.object array - that will work fine
return BcelWorld.fromBcel(new ArrayType(Type.OBJECT,ana.getDimensions()));
}
throw new BCException("Can't determine real target of clone() when processing instruction "+
searchPtr.getInstruction());
}
return tx;
}
public void initializeArgVars() {
if (argVars != null) return;
InstructionFactory fact = getFactory();
int len = getArgCount();
argVars = new BcelVar[len];
int positionOffset = (hasTarget() ? 1 : 0) +
((hasThis() && !getKind().isTargetSameAsThis()) ? 1 : 0);
if (getKind().argsOnStack()) {
// we move backwards because we're popping off the stack
for (int i = len - 1; i >= 0; i--) {
UnresolvedType type = getArgType(i);
BcelVar tmp = genTempVar(type, "ajc$arg" + i);
range.insert(tmp.createStore(getFactory()), Range.OutsideBefore);
int position = i;
position += positionOffset;
tmp.setPositionInAroundState(position);
argVars[i] = tmp;
}
} else {
int index = 0;
if (arg0HoldsThis()) index++;
for (int i = 0; i < len; i++) {
UnresolvedType type = getArgType(i);
BcelVar tmp = genTempVar(type, "ajc$arg" + i);
range.insert(tmp.createCopyFrom(fact, index), Range.OutsideBefore);
argVars[i] = tmp;
int position = i;
position += positionOffset;
// System.out.println("set position: " + tmp + ", " + position + " in " + this);
// System.out.println(" hasThis: " + hasThis() + ", hasTarget: " + hasTarget());
tmp.setPositionInAroundState(position);
index += type.getSize();
}
}
}
public void initializeForAroundClosure() {
initializeArgVars();
if (hasTarget()) initializeTargetVar();
if (hasThis()) initializeThisVar();
// System.out.println("initialized: " + this + " thisVar = " + thisVar);
}
public void initializeThisAnnotationVars() {
if (thisAnnotationVars != null) return;
thisAnnotationVars = new HashMap();
// populate..
}
public void initializeTargetAnnotationVars() {
if (targetAnnotationVars != null) return;
if (getKind().isTargetSameAsThis()) {
if (hasThis()) initializeThisAnnotationVars();
targetAnnotationVars = thisAnnotationVars;
} else {
targetAnnotationVars = new HashMap();
ResolvedType[] rtx = this.getTargetType().resolve(world).getAnnotationTypes(); // what about annotations we havent gotten yet but we will get in subclasses?
for (int i = 0; i < rtx.length; i++) {
ResolvedType typeX = rtx[i];
targetAnnotationVars.put(typeX,new TypeAnnotationAccessVar(typeX,(BcelVar)getTargetVar()));
}
// populate.
}
}
public void initializeArgAnnotationVars() {
if (argAnnotationVars != null) return;
int numArgs = getArgCount();
argAnnotationVars = new Map[numArgs];
for (int i = 0; i < argAnnotationVars.length; i++) {
argAnnotationVars[i] = new HashMap();
//FIXME asc just delete this logic - we always build the Var on demand, as we don't know at weave time
// what the full set of annotations could be (due to static/dynamic type differences...)
}
}
protected Member getRelevantMember(Member foundMember, Member relevantMember, ResolvedType relevantType){
if (foundMember != null){
return foundMember;
}
foundMember = getSignature().resolve(world);
if (foundMember == null && relevantMember != null) {
foundMember = relevantType.lookupMemberWithSupersAndITDs(relevantMember);
}
// check the ITD'd dooberries
List mungers = relevantType.resolve(world).getInterTypeMungers();
for (Iterator iter = mungers.iterator(); iter.hasNext();) {
BcelTypeMunger typeMunger = (BcelTypeMunger) iter.next();
if (typeMunger.getMunger() instanceof NewMethodTypeMunger ||
typeMunger.getMunger() instanceof NewConstructorTypeMunger) {
ResolvedMember fakerm = typeMunger.getSignature();
if (fakerm.getName().equals(getSignature().getName()) &&
fakerm.getParameterSignature().equals(getSignature().getParameterSignature())){
if (foundMember.getKind()==ResolvedMember.CONSTRUCTOR){
foundMember = AjcMemberMaker.interConstructor(
relevantType,
(ResolvedMember)foundMember,
typeMunger.getAspectType());
} else {
foundMember = AjcMemberMaker.interMethod((ResolvedMember)foundMember,
typeMunger.getAspectType(), false);
}
// in the above.. what about if it's on an Interface? Can that happen?
// then the last arg of the above should be true
return foundMember;
}
}
}
return foundMember;
}
protected ResolvedType [] getAnnotations(Member foundMember, Member relevantMember, ResolvedType relevantType){
if (foundMember == null){
// check the ITD'd dooberries
List mungers = relevantType.resolve(world).getInterTypeMungers();
for (Iterator iter = mungers.iterator(); iter.hasNext();) {
BcelTypeMunger typeMunger = (BcelTypeMunger) iter.next();
if (typeMunger.getMunger() instanceof NewMethodTypeMunger ||
typeMunger.getMunger() instanceof NewConstructorTypeMunger) {
ResolvedMember fakerm = typeMunger.getSignature();
//if (fakerm.hasAnnotations())
ResolvedMember ajcMethod = (getSignature().getKind()==ResolvedMember.CONSTRUCTOR?
AjcMemberMaker.postIntroducedConstructor(typeMunger.getAspectType(),fakerm.getDeclaringType(),fakerm.getParameterTypes()):
AjcMemberMaker.interMethodDispatcher(fakerm,typeMunger.getAspectType()));
//AjcMemberMaker.interMethodBody(fakerm,typeMunger.getAspectType()));
ResolvedMember rmm = findMethod(typeMunger.getAspectType(),ajcMethod);
if (fakerm.getName().equals(getSignature().getName()) &&
fakerm.getParameterSignature().equals(getSignature().getParameterSignature())) {
relevantType = typeMunger.getAspectType();
foundMember = rmm;
return foundMember.getAnnotationTypes();
}
}
}
// didn't find in ITDs, look in supers
foundMember = relevantType.lookupMemberWithSupersAndITDs(relevantMember);
if (foundMember == null) {
throw new IllegalStateException("Couldn't find member " + relevantMember + " for type " + relevantType);
}
}
return foundMember.getAnnotationTypes();
}
public void initializeKindedAnnotationVars() {
if (kindedAnnotationVars != null) return;
kindedAnnotationVars = new HashMap();
// by determining what "kind" of shadow we are, we can find out the
// annotations on the appropriate element (method, field, constructor, type).
// Then create one BcelVar entry in the map for each annotation, keyed by
// annotation type (UnresolvedType).
// FIXME asc Refactor this code, there is duplication
ResolvedType[] annotations = null;
Member relevantMember = getSignature();
ResolvedType relevantType = relevantMember.getDeclaringType().resolve(world);
if (getKind() == Shadow.StaticInitialization) {
annotations = relevantType.resolve(world).getAnnotationTypes();
} else if (getKind() == Shadow.MethodCall || getKind() == Shadow.ConstructorCall) {
Member foundMember = findMethod2(relevantType.resolve(world).getDeclaredMethods(),getSignature());
annotations = getAnnotations(foundMember, relevantMember, relevantType);
relevantMember = getRelevantMember(foundMember,relevantMember,relevantType);
relevantType = relevantMember.getDeclaringType().resolve(world);
} else if (getKind() == Shadow.FieldSet || getKind() == Shadow.FieldGet) {
relevantMember = findField(relevantType.getDeclaredFields(),getSignature());
if (relevantMember==null) {
// check the ITD'd dooberries
List mungers = relevantType.resolve(world).getInterTypeMungers();
for (Iterator iter = mungers.iterator(); iter.hasNext();) {
BcelTypeMunger typeMunger = (BcelTypeMunger) iter.next();
if (typeMunger.getMunger() instanceof NewFieldTypeMunger) {
ResolvedMember fakerm = typeMunger.getSignature();
//if (fakerm.hasAnnotations())
ResolvedMember ajcMethod = AjcMemberMaker.interFieldInitializer(fakerm,typeMunger.getAspectType());
ResolvedMember rmm = findMethod(typeMunger.getAspectType(),ajcMethod);
if (fakerm.equals(getSignature())) {
relevantType = typeMunger.getAspectType();
relevantMember = rmm;
}
}
}
}
annotations = relevantMember.getAnnotationTypes();
} else if (getKind() == Shadow.MethodExecution || getKind() == Shadow.ConstructorExecution ||
getKind() == Shadow.AdviceExecution) {
//ResolvedMember rm[] = relevantType.getDeclaredMethods();
Member foundMember = findMethod2(relevantType.getDeclaredMethods(),getSignature());
annotations = getAnnotations(foundMember, relevantMember,relevantType);
relevantMember = foundMember;
relevantMember = getRelevantMember(foundMember, relevantMember,relevantType);
} else if (getKind() == Shadow.ExceptionHandler) {
relevantType = getSignature().getParameterTypes()[0].resolve(world);
annotations = relevantType.getAnnotationTypes();
} else if (getKind() == Shadow.PreInitialization || getKind() == Shadow.Initialization) {
ResolvedMember found = findMethod2(relevantType.getDeclaredMethods(),getSignature());
annotations = found.getAnnotationTypes();
}
if (annotations == null) {
// We can't have recognized the shadow - should blow up now to be on the safe side
throw new BCException("Couldn't discover annotations for shadow: "+getKind());
}
for (int i = 0; i < annotations.length; i++) {
ResolvedType aTX = annotations[i];
KindedAnnotationAccessVar kaav = new KindedAnnotationAccessVar(getKind(),aTX.resolve(world),relevantType,relevantMember);
kindedAnnotationVars.put(aTX,kaav);
}
}
//FIXME asc whats the real diff between this one and the version in findMethod()?
ResolvedMember findMethod2(ResolvedMember rm[], Member sig) {
ResolvedMember found = null;
// String searchString = getSignature().getName()+getSignature().getParameterSignature();
for (int i = 0; i < rm.length && found==null; i++) {
ResolvedMember member = rm[i];
if (member.getName().equals(sig.getName()) && member.getParameterSignature().equals(sig.getParameterSignature()))
found = member;
}
return found;
}
private ResolvedMember findMethod(ResolvedType aspectType, ResolvedMember ajcMethod) {
ResolvedMember decMethods[] = aspectType.getDeclaredMethods();
for (int i = 0; i < decMethods.length; i++) {
ResolvedMember member = decMethods[i];
if (member.equals(ajcMethod)) return member;
}
return null;
}
private ResolvedMember findField(ResolvedMember[] members,Member lookingFor) {
for (int i = 0; i < members.length; i++) {
ResolvedMember member = members[i];
if ( member.getName().equals(getSignature().getName()) &&
member.getType().equals(getSignature().getType())) {
return member;
}
}
return null;
}
public void initializeWithinAnnotationVars() {
if (withinAnnotationVars != null) return;
withinAnnotationVars = new HashMap();
ResolvedType[] annotations = getEnclosingType().resolve(world).getAnnotationTypes();
for (int i = 0; i < annotations.length; i++) {
ResolvedType ann = annotations[i];
Kind k = Shadow.StaticInitialization;
withinAnnotationVars.put(ann,new KindedAnnotationAccessVar(k,ann,getEnclosingType(),null));
}
}
public void initializeWithinCodeAnnotationVars() {
if (withincodeAnnotationVars != null) return;
withincodeAnnotationVars = new HashMap();
// For some shadow we are interested in annotations on the method containing that shadow.
ResolvedType[] annotations = getEnclosingMethod().getMemberView().getAnnotationTypes();
for (int i = 0; i < annotations.length; i++) {
ResolvedType ann = annotations[i];
Kind k = (getEnclosingMethod().getMemberView().getKind()==Member.CONSTRUCTOR?
Shadow.ConstructorExecution:Shadow.MethodExecution);
withincodeAnnotationVars.put(ann,
new KindedAnnotationAccessVar(k,ann,getEnclosingType(),getEnclosingCodeSignature()));
}
}
// ---- weave methods
void weaveBefore(BcelAdvice munger) {
range.insert(
munger.getAdviceInstructions(this, null, range.getRealStart()),
Range.InsideBefore);
}
public void weaveAfter(BcelAdvice munger) {
weaveAfterThrowing(munger, UnresolvedType.THROWABLE);
weaveAfterReturning(munger);
}
/**
* We guarantee that the return value is on the top of the stack when
* munger.getAdviceInstructions() will be run
* (Unless we have a void return type in which case there's nothing)
*/
public void weaveAfterReturning(BcelAdvice munger) {
// InstructionFactory fact = getFactory();
List returns = new ArrayList();
Instruction ret = null;
for (InstructionHandle ih = range.getStart(); ih != range.getEnd(); ih = ih.getNext()) {
if (ih.getInstruction() instanceof ReturnInstruction) {
returns.add(ih);
ret = Utility.copyInstruction(ih.getInstruction());
}
}
InstructionList retList;
InstructionHandle afterAdvice;
if (ret != null) {
retList = new InstructionList(ret);
afterAdvice = retList.getStart();
} else /* if (munger.hasDynamicTests()) */ {
/*
*
27: getstatic #72; //Field ajc$cflowCounter$0:Lorg/aspectj/runtime/internal/CFlowCounter;
30: invokevirtual #87; //Method org/aspectj/runtime/internal/CFlowCounter.dec:()V
33: aload 6
35: athrow
36: nop
37: getstatic #72; //Field ajc$cflowCounter$0:Lorg/aspectj/runtime/internal/CFlowCounter;
40: invokevirtual #87; //Method org/aspectj/runtime/internal/CFlowCounter.dec:()V
43: d2i
44: invokespecial #23; //Method java/lang/Object."<init>":()V
*/
retList = new InstructionList(InstructionConstants.NOP);
afterAdvice = retList.getStart();
// } else {
// retList = new InstructionList();
// afterAdvice = null;
}
InstructionList advice = new InstructionList();
BcelVar tempVar = null;
if (munger.hasExtraParameter()) {
UnresolvedType tempVarType = getReturnType();
if (tempVarType.equals(ResolvedType.VOID)) {
tempVar = genTempVar(UnresolvedType.OBJECT);
advice.append(InstructionConstants.ACONST_NULL);
tempVar.appendStore(advice, getFactory());
} else {
tempVar = genTempVar(tempVarType);
advice.append(InstructionFactory.createDup(tempVarType.getSize()));
tempVar.appendStore(advice, getFactory());
}
}
advice.append(munger.getAdviceInstructions(this, tempVar, afterAdvice));
if (ret != null) {
InstructionHandle gotoTarget = advice.getStart();
for (Iterator i = returns.iterator(); i.hasNext();) {
InstructionHandle ih = (InstructionHandle) i.next();
Utility.replaceInstruction(
ih,
InstructionFactory.createBranchInstruction(
Constants.GOTO,
gotoTarget),
enclosingMethod);
}
range.append(advice);
range.append(retList);
} else {
range.append(advice);
range.append(retList);
}
}
public void weaveAfterThrowing(BcelAdvice munger, UnresolvedType catchType) {
// a good optimization would be not to generate anything here
// if the shadow is GUARANTEED empty (i.e., there's NOTHING, not even
// a shadow, inside me).
if (getRange().getStart().getNext() == getRange().getEnd()) return;
InstructionFactory fact = getFactory();
InstructionList handler = new InstructionList();
BcelVar exceptionVar = genTempVar(catchType);
exceptionVar.appendStore(handler, fact);
// pr62642
// I will now jump through some firey BCEL hoops to generate a trivial bit of code:
// if (exc instanceof ExceptionInInitializerError)
// throw (ExceptionInInitializerError)exc;
if (this.getEnclosingMethod().getName().equals("<clinit>")) {
ResolvedType eiieType = world.resolve("java.lang.ExceptionInInitializerError");
ObjectType eiieBcelType = (ObjectType)BcelWorld.makeBcelType(eiieType);
InstructionList ih = new InstructionList(InstructionConstants.NOP);
handler.append(exceptionVar.createLoad(fact));
handler.append(fact.createInstanceOf(eiieBcelType));
BranchInstruction bi =
InstructionFactory.createBranchInstruction(Constants.IFEQ,ih.getStart());
handler.append(bi);
handler.append(exceptionVar.createLoad(fact));
handler.append(fact.createCheckCast(eiieBcelType));
handler.append(InstructionConstants.ATHROW);
handler.append(ih);
}
InstructionList endHandler = new InstructionList(
exceptionVar.createLoad(fact));
handler.append(munger.getAdviceInstructions(this, exceptionVar, endHandler.getStart()));
handler.append(endHandler);
handler.append(InstructionConstants.ATHROW);
InstructionHandle handlerStart = handler.getStart();
if (isFallsThrough()) {
InstructionHandle jumpTarget = handler.append(InstructionConstants.NOP);
handler.insert(InstructionFactory.createBranchInstruction(Constants.GOTO, jumpTarget));
}
InstructionHandle protectedEnd = handler.getStart();
range.insert(handler, Range.InsideAfter);
enclosingMethod.addExceptionHandler(range.getStart().getNext(), protectedEnd.getPrev(),
handlerStart, (ObjectType)BcelWorld.makeBcelType(catchType), //???Type.THROWABLE,
// high priority if our args are on the stack
getKind().hasHighPriorityExceptions());
}
//??? this shares a lot of code with the above weaveAfterThrowing
//??? would be nice to abstract that to say things only once
public void weaveSoftener(BcelAdvice munger, UnresolvedType catchType) {
// a good optimization would be not to generate anything here
// if the shadow is GUARANTEED empty (i.e., there's NOTHING, not even
// a shadow, inside me).
if (getRange().getStart().getNext() == getRange().getEnd()) return;
InstructionFactory fact = getFactory();
InstructionList handler = new InstructionList();
InstructionList rtExHandler = new InstructionList();
BcelVar exceptionVar = genTempVar(catchType);
handler.append(fact.createNew(NameMangler.SOFT_EXCEPTION_TYPE));
handler.append(InstructionFactory.createDup(1));
handler.append(exceptionVar.createLoad(fact));
handler.append(fact.createInvoke(NameMangler.SOFT_EXCEPTION_TYPE, "<init>",
Type.VOID, new Type[] { Type.THROWABLE }, Constants.INVOKESPECIAL)); //??? special
handler.append(InstructionConstants.ATHROW);
// ENH 42737
exceptionVar.appendStore(rtExHandler, fact);
// aload_1
rtExHandler.append(exceptionVar.createLoad(fact));
// instanceof class java/lang/RuntimeException
rtExHandler.append(fact.createInstanceOf(new ObjectType("java.lang.RuntimeException")));
// ifeq go to new SOFT_EXCEPTION_TYPE instruction
rtExHandler.append(InstructionFactory.createBranchInstruction(Constants.IFEQ,handler.getStart()));
// aload_1
rtExHandler.append(exceptionVar.createLoad(fact));
// athrow
rtExHandler.append(InstructionFactory.ATHROW);
InstructionHandle handlerStart = rtExHandler.getStart();
if (isFallsThrough()) {
InstructionHandle jumpTarget = range.getEnd();//handler.append(fact.NOP);
rtExHandler.insert(InstructionFactory.createBranchInstruction(Constants.GOTO, jumpTarget));
}
rtExHandler.append(handler);
InstructionHandle protectedEnd = rtExHandler.getStart();
range.insert(rtExHandler, Range.InsideAfter);
enclosingMethod.addExceptionHandler(range.getStart().getNext(), protectedEnd.getPrev(),
handlerStart, (ObjectType)BcelWorld.makeBcelType(catchType),
// high priority if our args are on the stack
getKind().hasHighPriorityExceptions());
}
public void weavePerObjectEntry(final BcelAdvice munger, final BcelVar onVar) {
final InstructionFactory fact = getFactory();
InstructionList entryInstructions = new InstructionList();
InstructionList entrySuccessInstructions = new InstructionList();
onVar.appendLoad(entrySuccessInstructions, fact);
entrySuccessInstructions.append(
Utility.createInvoke(fact, world,
AjcMemberMaker.perObjectBind(munger.getConcreteAspect())));
InstructionList testInstructions =
munger.getTestInstructions(this, entrySuccessInstructions.getStart(),
range.getRealStart(),
entrySuccessInstructions.getStart());
entryInstructions.append(testInstructions);
entryInstructions.append(entrySuccessInstructions);
range.insert(entryInstructions, Range.InsideBefore);
}
// PTWIMPL Create static initializer to call the aspect factory
/**
* Causes the aspect instance to be *set* for later retrievable through localAspectof()/aspectOf()
*/
public void weavePerTypeWithinAspectInitialization(final BcelAdvice munger,UnresolvedType t) {
if (t.resolve(world).isInterface()) return; // Don't initialize statics in
final InstructionFactory fact = getFactory();
InstructionList entryInstructions = new InstructionList();
InstructionList entrySuccessInstructions = new InstructionList();
BcelWorld.getBcelObjectType(munger.getConcreteAspect());
String aspectname = munger.getConcreteAspect().getName();
String ptwField = NameMangler.perTypeWithinFieldForTarget(munger.getConcreteAspect());
entrySuccessInstructions.append(new PUSH(fact.getConstantPool(),t.getName()));
entrySuccessInstructions.append(fact.createInvoke(aspectname,"ajc$createAspectInstance",new ObjectType(aspectname),
new Type[]{new ObjectType("java.lang.String")},Constants.INVOKESTATIC));
entrySuccessInstructions.append(fact.createPutStatic(t.getName(),ptwField,
new ObjectType(aspectname)));
entryInstructions.append(entrySuccessInstructions);
range.insert(entryInstructions, Range.InsideBefore);
}
public void weaveCflowEntry(final BcelAdvice munger, final Member cflowField) {
final boolean isPer = munger.getKind() == AdviceKind.PerCflowBelowEntry ||
munger.getKind() == AdviceKind.PerCflowEntry;
final Type objectArrayType = new ArrayType(Type.OBJECT, 1);
final InstructionFactory fact = getFactory();
final BcelVar testResult = genTempVar(ResolvedType.BOOLEAN);
InstructionList entryInstructions = new InstructionList();
{
InstructionList entrySuccessInstructions = new InstructionList();
if (munger.hasDynamicTests()) {
entryInstructions.append(Utility.createConstant(fact, 0));
testResult.appendStore(entryInstructions, fact);
entrySuccessInstructions.append(Utility.createConstant(fact, 1));
testResult.appendStore(entrySuccessInstructions, fact);
}
if (isPer) {
entrySuccessInstructions.append(
fact.createInvoke(munger.getConcreteAspect().getName(),
NameMangler.PERCFLOW_PUSH_METHOD,
Type.VOID,
new Type[] { },
Constants.INVOKESTATIC));
} else {
BcelVar[] cflowStateVars = munger.getExposedStateAsBcelVars();
if (cflowStateVars.length == 0) {
// This should be getting managed by a counter - lets make sure.
if (!cflowField.getType().getName().endsWith("CFlowCounter"))
throw new RuntimeException("Incorrectly attempting counter operation on stacked cflow");
entrySuccessInstructions.append(
Utility.createGet(fact, cflowField));
//arrayVar.appendLoad(entrySuccessInstructions, fact);
entrySuccessInstructions.append(fact.createInvoke(NameMangler.CFLOW_COUNTER_TYPE,"inc",Type.VOID,new Type[] { },Constants.INVOKEVIRTUAL));
} else {
BcelVar arrayVar = genTempVar(UnresolvedType.OBJECTARRAY);
int alen = cflowStateVars.length;
entrySuccessInstructions.append(Utility.createConstant(fact, alen));
entrySuccessInstructions.append(
(Instruction) fact.createNewArray(Type.OBJECT, (short) 1));
arrayVar.appendStore(entrySuccessInstructions, fact);
for (int i = 0; i < alen; i++) {
arrayVar.appendConvertableArrayStore(
entrySuccessInstructions,
fact,
i,
cflowStateVars[i]);
}
entrySuccessInstructions.append(
Utility.createGet(fact, cflowField));
arrayVar.appendLoad(entrySuccessInstructions, fact);
entrySuccessInstructions.append(
fact.createInvoke(NameMangler.CFLOW_STACK_TYPE, "push", Type.VOID,
new Type[] { objectArrayType },
Constants.INVOKEVIRTUAL));
}
}
InstructionList testInstructions =
munger.getTestInstructions(this, entrySuccessInstructions.getStart(),
range.getRealStart(),
entrySuccessInstructions.getStart());
entryInstructions.append(testInstructions);
entryInstructions.append(entrySuccessInstructions);
}
// this is the same for both per and non-per
weaveAfter(new BcelAdvice(null, null, null, 0, 0, 0, null, null) {
public InstructionList getAdviceInstructions(
BcelShadow s,
BcelVar extraArgVar,
InstructionHandle ifNoAdvice) {
InstructionList exitInstructions = new InstructionList();
if (munger.hasDynamicTests()) {
testResult.appendLoad(exitInstructions, fact);
exitInstructions.append(
InstructionFactory.createBranchInstruction(
Constants.IFEQ,
ifNoAdvice));
}
exitInstructions.append(Utility.createGet(fact, cflowField));
if (munger.getKind() != AdviceKind.PerCflowEntry &&
munger.getKind() != AdviceKind.PerCflowBelowEntry &&
munger.getExposedStateAsBcelVars().length==0) {
exitInstructions
.append(
fact
.createInvoke(
NameMangler.CFLOW_COUNTER_TYPE,
"dec",
Type.VOID,
new Type[] {
}, Constants.INVOKEVIRTUAL));
} else {
exitInstructions
.append(
fact
.createInvoke(
NameMangler.CFLOW_STACK_TYPE,
"pop",
Type.VOID,
new Type[] {
}, Constants.INVOKEVIRTUAL));
}
return exitInstructions;
}
});
range.insert(entryInstructions, Range.InsideBefore);
}
public void weaveAroundInline(
BcelAdvice munger,
boolean hasDynamicTest)
{
/* Implementation notes:
*
* AroundInline still extracts the instructions of the original shadow into
* an extracted method. This allows inlining of even that advice that doesn't
* call proceed or calls proceed more than once.
*
* It extracts the instructions of the original shadow into a method.
*
* Then it extracts the instructions of the advice into a new method defined on
* this enclosing class. This new method can then be specialized as below.
*
* Then it searches in the instructions of the advice for any call to the
* proceed method.
*
* At such a call, there is stuff on the stack representing the arguments to
* proceed. Pop these into the frame.
*
* Now build the stack for the call to the extracted method, taking values
* either from the join point state or from the new frame locs from proceed.
* Now call the extracted method. The right return value should be on the
* stack, so no cast is necessary.
*
* If only one call to proceed is made, we can re-inline the original shadow.
* We are not doing that presently.
*
* If the body of the advice can be determined to not alter the stack, or if
* this shadow doesn't care about the stack, i.e. method-execution, then the
* new method for the advice can also be re-lined. We are not doing that
* presently.
*/
// !!! THIS BLOCK OF CODE SHOULD BE IN A METHOD CALLED weaveAround(...);
Member mungerSig = munger.getSignature();
//Member originalSig = mungerSig; // If mungerSig is on a parameterized type, originalSig is the member on the generic type
if (mungerSig instanceof ResolvedMember) {
ResolvedMember rm = (ResolvedMember)mungerSig;
if (rm.hasBackingGenericMember()) mungerSig = rm.getBackingGenericMember();
}
ResolvedType declaringType = world.resolve(mungerSig.getDeclaringType(),true);
if (declaringType == ResolvedType.MISSING) {
world.getLint().cantFindType.signal(
new String[] {WeaverMessages.format(WeaverMessages.CANT_FIND_TYPE_DURING_AROUND_WEAVE,declaringType.getClassName())},
getSourceLocation(),
new ISourceLocation[]{ munger.getSourceLocation()}
);
// IMessage msg = new Message(
// WeaverMessages.format(WeaverMessages.CANT_FIND_TYPE_DURING_AROUND_WEAVE,declaringType.getClassName()),
// "",IMessage.ERROR,getSourceLocation(),null,
// new ISourceLocation[]{ munger.getSourceLocation()});
// world.getMessageHandler().handleMessage(msg);
}
//??? might want some checks here to give better errors
BcelObjectType ot = BcelWorld.getBcelObjectType((declaringType.isParameterizedType()?declaringType.getGenericType():declaringType));
LazyMethodGen adviceMethod = ot.getLazyClassGen().getLazyMethodGen(mungerSig);
if (!adviceMethod.getCanInline()) {
weaveAroundClosure(munger, hasDynamicTest);
return;
}
// specific test for @AJ proceedInInners
if (munger.getConcreteAspect().isAnnotationStyleAspect()) {
// if we can't find one proceed()
// we suspect that the call is happening in an inner class
// so we don't inline it.
// Note: for code style, this is done at Aspect compilation time.
boolean canSeeProceedPassedToOther = false;
InstructionHandle curr = adviceMethod.getBody().getStart();
InstructionHandle end = adviceMethod.getBody().getEnd();
ConstantPoolGen cpg = adviceMethod.getEnclosingClass().getConstantPoolGen();
while (curr != end) {
InstructionHandle next = curr.getNext();
Instruction inst = curr.getInstruction();
if ((inst instanceof InvokeInstruction)
&& ((InvokeInstruction)inst).getSignature(cpg).indexOf("Lorg/aspectj/lang/ProceedingJoinPoint;") > 0) {
// we may want to refine to exclude stuff returning jp ?
// does code style skip inline if i write dump(thisJoinPoint) ?
canSeeProceedPassedToOther = true;// we see one pjp passed around - dangerous
break;
}
curr = next;
}
if (canSeeProceedPassedToOther) {
// remember this decision to avoid re-analysis
adviceMethod.setCanInline(false);
weaveAroundClosure(munger, hasDynamicTest);
return;
}
}
// We can't inline around methods if they have around advice on them, this
// is because the weaving will extract the body and hence the proceed call.
//??? should consider optimizations to recognize simple cases that don't require body extraction
enclosingMethod.setCanInline(false);
// start by exposing various useful things into the frame
final InstructionFactory fact = getFactory();
// now generate the aroundBody method
LazyMethodGen extractedMethod =
extractMethod(
NameMangler.aroundCallbackMethodName(
getSignature(),
getEnclosingClass()),
Modifier.PRIVATE,
munger
);
// now extract the advice into its own method
String adviceMethodName =
NameMangler.aroundCallbackMethodName(
getSignature(),
getEnclosingClass()) + "$advice";
List argVarList = new ArrayList();
List proceedVarList = new ArrayList();
int extraParamOffset = 0;
// Create the extra parameters that are needed for passing to proceed
// This code is very similar to that found in makeCallToCallback and should
// be rationalized in the future
if (thisVar != null) {
argVarList.add(thisVar);
proceedVarList.add(new BcelVar(thisVar.getType(), extraParamOffset));
extraParamOffset += thisVar.getType().getSize();
}
if (targetVar != null && targetVar != thisVar) {
argVarList.add(targetVar);
proceedVarList.add(new BcelVar(targetVar.getType(), extraParamOffset));
extraParamOffset += targetVar.getType().getSize();
}
for (int i = 0, len = getArgCount(); i < len; i++) {
argVarList.add(argVars[i]);
proceedVarList.add(new BcelVar(argVars[i].getType(), extraParamOffset));
extraParamOffset += argVars[i].getType().getSize();
}
if (thisJoinPointVar != null) {
argVarList.add(thisJoinPointVar);
proceedVarList.add(new BcelVar(thisJoinPointVar.getType(), extraParamOffset));
extraParamOffset += thisJoinPointVar.getType().getSize();
}
Type[] adviceParameterTypes = adviceMethod.getArgumentTypes();
Type[] extractedMethodParameterTypes = extractedMethod.getArgumentTypes();
Type[] parameterTypes =
new Type[extractedMethodParameterTypes.length
+ adviceParameterTypes.length
+ 1];
int parameterIndex = 0;
System.arraycopy(
extractedMethodParameterTypes,
0,
parameterTypes,
parameterIndex,
extractedMethodParameterTypes.length);
parameterIndex += extractedMethodParameterTypes.length;
parameterTypes[parameterIndex++] =
BcelWorld.makeBcelType(adviceMethod.getEnclosingClass().getType());
System.arraycopy(
adviceParameterTypes,
0,
parameterTypes,
parameterIndex,
adviceParameterTypes.length);
LazyMethodGen localAdviceMethod =
new LazyMethodGen(
Modifier.PRIVATE | Modifier.FINAL | Modifier.STATIC,
BcelWorld.makeBcelType(mungerSig.getReturnType()),
adviceMethodName,
parameterTypes,
new String[0],
getEnclosingClass());
String donorFileName = adviceMethod.getEnclosingClass().getInternalFileName();
String recipientFileName = getEnclosingClass().getInternalFileName();
// System.err.println("donor " + donorFileName);
// System.err.println("recip " + recipientFileName);
if (! donorFileName.equals(recipientFileName)) {
localAdviceMethod.fromFilename = donorFileName;
getEnclosingClass().addInlinedSourceFileInfo(
donorFileName,
adviceMethod.highestLineNumber);
}
getEnclosingClass().addMethodGen(localAdviceMethod);
// create a map that will move all slots in advice method forward by extraParamOffset
// in order to make room for the new proceed-required arguments that are added at
// the beginning of the parameter list
int nVars = adviceMethod.getMaxLocals() + extraParamOffset;
IntMap varMap = IntMap.idMap(nVars);
for (int i=extraParamOffset; i < nVars; i++) {
varMap.put(i-extraParamOffset, i);
}
localAdviceMethod.getBody().insert(
BcelClassWeaver.genInlineInstructions(adviceMethod,
localAdviceMethod, varMap, fact, true));
localAdviceMethod.setMaxLocals(nVars);
//System.err.println(localAdviceMethod);
// the shadow is now empty. First, create a correct call
// to the around advice. This includes both the call (which may involve
// value conversion of the advice arguments) and the return
// (which may involve value conversion of the return value). Right now
// we push a null for the unused closure. It's sad, but there it is.
InstructionList advice = new InstructionList();
// InstructionHandle adviceMethodInvocation;
{
for (Iterator i = argVarList.iterator(); i.hasNext(); ) {
BcelVar var = (BcelVar)i.next();
var.appendLoad(advice, fact);
}
// ??? we don't actually need to push NULL for the closure if we take care
advice.append(
munger.getAdviceArgSetup(
this,
null,
(munger.getConcreteAspect().isAnnotationStyleAspect())?
this.loadThisJoinPoint():
new InstructionList(InstructionConstants.ACONST_NULL)));
// adviceMethodInvocation =
advice.append(
Utility.createInvoke(fact, localAdviceMethod)); //(fact, getWorld(), munger.getSignature()));
advice.append(
Utility.createConversion(
getFactory(),
BcelWorld.makeBcelType(mungerSig.getReturnType()),
extractedMethod.getReturnType()));
if (! isFallsThrough()) {
advice.append(InstructionFactory.createReturn(extractedMethod.getReturnType()));
}
}
// now, situate the call inside the possible dynamic tests,
// and actually add the whole mess to the shadow
if (! hasDynamicTest) {
range.append(advice);
} else {
InstructionList afterThingie = new InstructionList(InstructionConstants.NOP);
InstructionList callback = makeCallToCallback(extractedMethod);
if (terminatesWithReturn()) {
callback.append(
InstructionFactory.createReturn(extractedMethod.getReturnType()));
} else {
//InstructionHandle endNop = range.insert(fact.NOP, Range.InsideAfter);
advice.append(
InstructionFactory.createBranchInstruction(
Constants.GOTO,
afterThingie.getStart()));
}
range.append(
munger.getTestInstructions(
this,
advice.getStart(),
callback.getStart(),
advice.getStart()));
range.append(advice);
range.append(callback);
range.append(afterThingie);
}
// now search through the advice, looking for a call to PROCEED.
// Then we replace the call to proceed with some argument setup, and a
// call to the extracted method.
// inlining support for code style aspects
if (!munger.getConcreteAspect().isAnnotationStyleAspect()) {
String proceedName =
NameMangler.proceedMethodName(munger.getSignature().getName());
InstructionHandle curr = localAdviceMethod.getBody().getStart();
InstructionHandle end = localAdviceMethod.getBody().getEnd();
ConstantPoolGen cpg = localAdviceMethod.getEnclosingClass().getConstantPoolGen();
while (curr != end) {
InstructionHandle next = curr.getNext();
Instruction inst = curr.getInstruction();
if ((inst instanceof INVOKESTATIC)
&& proceedName.equals(((INVOKESTATIC) inst).getMethodName(cpg))) {
localAdviceMethod.getBody().append(
curr,
getRedoneProceedCall(
fact,
extractedMethod,
munger,
localAdviceMethod,
proceedVarList));
Utility.deleteInstruction(curr, localAdviceMethod);
}
curr = next;
}
// and that's it.
} else {
//ATAJ inlining support for @AJ aspects
// [TODO document @AJ code rule: don't manipulate 2 jps proceed at the same time.. in an advice body]
InstructionHandle curr = localAdviceMethod.getBody().getStart();
InstructionHandle end = localAdviceMethod.getBody().getEnd();
ConstantPoolGen cpg = localAdviceMethod.getEnclosingClass().getConstantPoolGen();
while (curr != end) {
InstructionHandle next = curr.getNext();
Instruction inst = curr.getInstruction();
if ((inst instanceof INVOKEINTERFACE)
&& "proceed".equals(((INVOKEINTERFACE) inst).getMethodName(cpg))) {
final boolean isProceedWithArgs;
if (((INVOKEINTERFACE) inst).getArgumentTypes(cpg).length == 1) {
// proceed with args as a boxed Object[]
isProceedWithArgs = true;
} else {
isProceedWithArgs = false;
}
InstructionList insteadProceedIl = getRedoneProceedCallForAnnotationStyle(
fact,
extractedMethod,
munger,
localAdviceMethod,
proceedVarList,
isProceedWithArgs
);
localAdviceMethod.getBody().append(curr, insteadProceedIl);
Utility.deleteInstruction(curr, localAdviceMethod);
}
curr = next;
}
}
}
private InstructionList getRedoneProceedCall(
InstructionFactory fact,
LazyMethodGen callbackMethod,
BcelAdvice munger,
LazyMethodGen localAdviceMethod,
List argVarList)
{
InstructionList ret = new InstructionList();
// we have on stack all the arguments for the ADVICE call.
// we have in frame somewhere all the arguments for the non-advice call.
BcelVar[] adviceVars = munger.getExposedStateAsBcelVars();
IntMap proceedMap = makeProceedArgumentMap(adviceVars);
// System.out.println(proceedMap + " for " + this);
// System.out.println(argVarList);
ResolvedType[] proceedParamTypes =
world.resolve(munger.getSignature().getParameterTypes());
// remove this*JoinPoint* as arguments to proceed
if (munger.getBaseParameterCount()+1 < proceedParamTypes.length) {
int len = munger.getBaseParameterCount()+1;
ResolvedType[] newTypes = new ResolvedType[len];
System.arraycopy(proceedParamTypes, 0, newTypes, 0, len);
proceedParamTypes = newTypes;
}
//System.out.println("stateTypes: " + Arrays.asList(stateTypes));
BcelVar[] proceedVars =
Utility.pushAndReturnArrayOfVars(proceedParamTypes, ret, fact, localAdviceMethod);
Type[] stateTypes = callbackMethod.getArgumentTypes();
// System.out.println("stateTypes: " + Arrays.asList(stateTypes));
for (int i=0, len=stateTypes.length; i < len; i++) {
Type stateType = stateTypes[i];
ResolvedType stateTypeX = BcelWorld.fromBcel(stateType).resolve(world);
if (proceedMap.hasKey(i)) {
//throw new RuntimeException("unimplemented");
proceedVars[proceedMap.get(i)].appendLoadAndConvert(ret, fact, stateTypeX);
} else {
((BcelVar) argVarList.get(i)).appendLoad(ret, fact);
}
}
ret.append(Utility.createInvoke(fact, callbackMethod));
ret.append(Utility.createConversion(fact, callbackMethod.getReturnType(),
BcelWorld.makeBcelType(munger.getSignature().getReturnType())));
return ret;
}
/**
* ATAJ Handle the inlining for @AJ aspects
*
* @param fact
* @param callbackMethod
* @param munger
* @param localAdviceMethod
* @param argVarList
* @param isProceedWithArgs
* @return
*/
private InstructionList getRedoneProceedCallForAnnotationStyle(
InstructionFactory fact,
LazyMethodGen callbackMethod,
BcelAdvice munger,
LazyMethodGen localAdviceMethod,
List argVarList,
boolean isProceedWithArgs)
{
// Notes:
// proceedingjp is on stack (since user was calling pjp.proceed(...)
// the boxed args to proceed() are on stack as well (Object[]) unless
// the call is to pjp.proceed(<noarg>)
// new Object[]{new Integer(argAdvice1-1)};// arg of proceed
// call to proceed(..) is NOT made
// instead we do
// itar callback args i
// get from array i, convert it to the callback arg i
// if ask for JP, push the one we got on the stack
// invoke callback, create conversion back to Object/Integer
// rest of method -- (hence all those conversions)
// intValue() from original code
// int res = .. from original code
//Note: we just don't care about the proceed map etc
InstructionList ret = new InstructionList();
// store the Object[] array on stack if proceed with args
if (isProceedWithArgs) {
Type objectArrayType = Type.getType("[Ljava/lang/Object;");
int localProceedArgArray = localAdviceMethod.allocateLocal(objectArrayType);
ret.append(InstructionFactory.createStore(objectArrayType, localProceedArgArray));
Type proceedingJpType = Type.getType("Lorg/aspectj/lang/ProceedingJoinPoint;");
int localJp = localAdviceMethod.allocateLocal(proceedingJpType);
ret.append(InstructionFactory.createStore(proceedingJpType, localJp));
// push on stack each element of the object array
// that is assumed to be consistent with the callback argument (ie munger args)
// TODO do we want to try catch ClassCast and AOOBE exception ?
// special logic when withincode is static or not
int startIndex = 0;
if (thisVar != null) {
startIndex = 1;
//TODO this logic is actually depending on target as well - test me
ret.append(new ALOAD(0));//thisVar
}
for (int i = startIndex, len=callbackMethod.getArgumentTypes().length; i < len; i++) {
Type stateType = callbackMethod.getArgumentTypes()[i];
BcelWorld.fromBcel(stateType).resolve(world);
if ("Lorg/aspectj/lang/JoinPoint;".equals(stateType.getSignature())) {
ret.append(new ALOAD(localJp));// from localAdvice signature
} else {
ret.append(InstructionFactory.createLoad(objectArrayType, localProceedArgArray));
ret.append(Utility.createConstant(fact, i-startIndex));
ret.append(InstructionFactory.createArrayLoad(Type.OBJECT));
ret.append(Utility.createConversion(
fact,
Type.OBJECT,
stateType
));
}
}
} else {
Type proceedingJpType = Type.getType("Lorg/aspectj/lang/ProceedingJoinPoint;");
int localJp = localAdviceMethod.allocateLocal(proceedingJpType);
ret.append(InstructionFactory.createStore(proceedingJpType, localJp));
for (int i = 0, len=callbackMethod.getArgumentTypes().length; i < len; i++) {
Type stateType = callbackMethod.getArgumentTypes()[i];
/*ResolvedType stateTypeX =*/
BcelWorld.fromBcel(stateType).resolve(world);
if ("Lorg/aspectj/lang/JoinPoint;".equals(stateType.getSignature())) {
ret.append(new ALOAD(localJp));// from localAdvice signature
// } else if ("Lorg/aspectj/lang/ProceedingJoinPoint;".equals(stateType.getSignature())) {
// //FIXME ALEX?
// ret.append(new ALOAD(localJp));// from localAdvice signature
//// ret.append(fact.createCheckCast(
//// (ReferenceType) BcelWorld.makeBcelType(stateTypeX)
//// ));
// // cast ?
//
} else {
ret.append(InstructionFactory.createLoad(stateType, i));
}
}
}
// do the callback invoke
ret.append(Utility.createInvoke(fact, callbackMethod));
// box it again. Handles cases where around advice does return something else than Object
if (!UnresolvedType.OBJECT.equals(munger.getSignature().getReturnType())) {
ret.append(Utility.createConversion(
fact,
callbackMethod.getReturnType(),
Type.OBJECT
));
}
ret.append(Utility.createConversion(
fact,
callbackMethod.getReturnType(),
BcelWorld.makeBcelType(munger.getSignature().getReturnType())
));
return ret;
//
//
//
// if (proceedMap.hasKey(i)) {
// ret.append(new ALOAD(i));
// //throw new RuntimeException("unimplemented");
// //proceedVars[proceedMap.get(i)].appendLoadAndConvert(ret, fact, stateTypeX);
// } else {
// //((BcelVar) argVarList.get(i)).appendLoad(ret, fact);
// //ret.append(new ALOAD(i));
// if ("Lorg/aspectj/lang/JoinPoint;".equals(stateType.getSignature())) {
// ret.append(new ALOAD(i));
// } else {
// ret.append(new ALOAD(i));
// }
// }
// }
//
// ret.append(Utility.createInvoke(fact, callbackMethod));
// ret.append(Utility.createConversion(fact, callbackMethod.getReturnType(),
// BcelWorld.makeBcelType(munger.getSignature().getReturnType())));
//
// //ret.append(new ACONST_NULL());//will be POPed
// if (true) return ret;
//
//
//
// // we have on stack all the arguments for the ADVICE call.
// // we have in frame somewhere all the arguments for the non-advice call.
//
// BcelVar[] adviceVars = munger.getExposedStateAsBcelVars();
// IntMap proceedMap = makeProceedArgumentMap(adviceVars);
//
// System.out.println(proceedMap + " for " + this);
// System.out.println(argVarList);
//
// ResolvedType[] proceedParamTypes =
// world.resolve(munger.getSignature().getParameterTypes());
// // remove this*JoinPoint* as arguments to proceed
// if (munger.getBaseParameterCount()+1 < proceedParamTypes.length) {
// int len = munger.getBaseParameterCount()+1;
// ResolvedType[] newTypes = new ResolvedType[len];
// System.arraycopy(proceedParamTypes, 0, newTypes, 0, len);
// proceedParamTypes = newTypes;
// }
//
// //System.out.println("stateTypes: " + Arrays.asList(stateTypes));
// BcelVar[] proceedVars =
// Utility.pushAndReturnArrayOfVars(proceedParamTypes, ret, fact, localAdviceMethod);
//
// Type[] stateTypes = callbackMethod.getArgumentTypes();
//// System.out.println("stateTypes: " + Arrays.asList(stateTypes));
//
// for (int i=0, len=stateTypes.length; i < len; i++) {
// Type stateType = stateTypes[i];
// ResolvedType stateTypeX = BcelWorld.fromBcel(stateType).resolve(world);
// if (proceedMap.hasKey(i)) {
// //throw new RuntimeException("unimplemented");
// proceedVars[proceedMap.get(i)].appendLoadAndConvert(ret, fact, stateTypeX);
// } else {
// ((BcelVar) argVarList.get(i)).appendLoad(ret, fact);
// }
// }
//
// ret.append(Utility.createInvoke(fact, callbackMethod));
// ret.append(Utility.createConversion(fact, callbackMethod.getReturnType(),
// BcelWorld.makeBcelType(munger.getSignature().getReturnType())));
// return ret;
}
public void weaveAroundClosure(BcelAdvice munger, boolean hasDynamicTest) {
InstructionFactory fact = getFactory();
enclosingMethod.setCanInline(false);
// MOVE OUT ALL THE INSTRUCTIONS IN MY SHADOW INTO ANOTHER METHOD!
LazyMethodGen callbackMethod =
extractMethod(
NameMangler.aroundCallbackMethodName(
getSignature(),
getEnclosingClass()),
0,
munger);
BcelVar[] adviceVars = munger.getExposedStateAsBcelVars();
String closureClassName =
NameMangler.makeClosureClassName(
getEnclosingClass().getType(),
getEnclosingClass().getNewGeneratedNameTag());
Member constructorSig = new MemberImpl(Member.CONSTRUCTOR,
UnresolvedType.forName(closureClassName), 0, "<init>",
"([Ljava/lang/Object;)V");
BcelVar closureHolder = null;
// This is not being used currently since getKind() == preinitializaiton
// cannot happen in around advice
if (getKind() == PreInitialization) {
closureHolder = genTempVar(AjcMemberMaker.AROUND_CLOSURE_TYPE);
}
InstructionList closureInstantiation =
makeClosureInstantiation(constructorSig, closureHolder);
/*LazyMethodGen constructor = */
makeClosureClassAndReturnConstructor(
closureClassName,
callbackMethod,
makeProceedArgumentMap(adviceVars)
);
InstructionList returnConversionCode;
if (getKind() == PreInitialization) {
returnConversionCode = new InstructionList();
BcelVar stateTempVar = genTempVar(UnresolvedType.OBJECTARRAY);
closureHolder.appendLoad(returnConversionCode, fact);
returnConversionCode.append(
Utility.createInvoke(
fact,
world,
AjcMemberMaker.aroundClosurePreInitializationGetter()));
stateTempVar.appendStore(returnConversionCode, fact);
Type[] stateTypes = getSuperConstructorParameterTypes();
returnConversionCode.append(InstructionConstants.ALOAD_0); // put "this" back on the stack
for (int i = 0, len = stateTypes.length; i < len; i++) {
UnresolvedType bcelTX = BcelWorld.fromBcel(stateTypes[i]);
ResolvedType stateRTX = world.resolve(bcelTX,true);
if (stateRTX == ResolvedType.MISSING) {
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());
if (!isFallsThrough()) {
returnConversionCode.append(
InstructionFactory.createReturn(callbackMethod.getReturnType()));
}
}
// ATAJ for @AJ aspect we need to link the closure with the joinpoint instance
if (munger.getConcreteAspect()!=null && munger.getConcreteAspect().isAnnotationStyleAspect()) {
closureInstantiation.append(Utility.createInvoke(
getFactory(),
getWorld(),
new MemberImpl(
Member.METHOD,
UnresolvedType.forName("org.aspectj.runtime.internal.AroundClosure"),
Modifier.PUBLIC,
"linkClosureAndJoinPoint",
"()Lorg/aspectj/lang/ProceedingJoinPoint;"
)
));
}
InstructionList advice = new InstructionList();
advice.append(munger.getAdviceArgSetup(this, null, closureInstantiation));
// invoke the advice
advice.append(munger.getNonTestAdviceInstructions(this));
advice.append(returnConversionCode);
if (!hasDynamicTest) {
range.append(advice);
} else {
InstructionList callback = makeCallToCallback(callbackMethod);
InstructionList postCallback = new InstructionList();
if (terminatesWithReturn()) {
callback.append(
InstructionFactory.createReturn(callbackMethod.getReturnType()));
} else {
advice.append(
InstructionFactory.createBranchInstruction(
Constants.GOTO,
postCallback.append(InstructionConstants.NOP)));
}
range.append(
munger.getTestInstructions(
this,
advice.getStart(),
callback.getStart(),
advice.getStart()));
range.append(advice);
range.append(callback);
range.append(postCallback);
}
}
// exposed for testing
InstructionList makeCallToCallback(LazyMethodGen callbackMethod) {
InstructionFactory fact = getFactory();
InstructionList callback = new InstructionList();
if (thisVar != null) {
callback.append(InstructionConstants.ALOAD_0);
}
if (targetVar != null && targetVar != thisVar) {
callback.append(BcelRenderer.renderExpr(fact, world, targetVar));
}
callback.append(BcelRenderer.renderExprs(fact, world, argVars));
// remember to render tjps
if (thisJoinPointVar != null) {
callback.append(BcelRenderer.renderExpr(fact, world, thisJoinPointVar));
}
callback.append(Utility.createInvoke(fact, callbackMethod));
return callback;
}
/** side-effect-free */
private InstructionList makeClosureInstantiation(Member constructor, BcelVar holder) {
// LazyMethodGen constructor) {
InstructionFactory fact = getFactory();
BcelVar arrayVar = genTempVar(UnresolvedType.OBJECTARRAY);
//final Type objectArrayType = new ArrayType(Type.OBJECT, 1);
final InstructionList il = new InstructionList();
int alen = getArgCount() + (thisVar == null ? 0 : 1) +
((targetVar != null && targetVar != thisVar) ? 1 : 0) +
(thisJoinPointVar == null ? 0 : 1);
il.append(Utility.createConstant(fact, alen));
il.append((Instruction)fact.createNewArray(Type.OBJECT, (short)1));
arrayVar.appendStore(il, fact);
int stateIndex = 0;
if (thisVar != null) {
arrayVar.appendConvertableArrayStore(il, fact, stateIndex, thisVar);
thisVar.setPositionInAroundState(stateIndex);
stateIndex++;
}
if (targetVar != null && targetVar != thisVar) {
arrayVar.appendConvertableArrayStore(il, fact, stateIndex, targetVar);
targetVar.setPositionInAroundState(stateIndex);
stateIndex++;
}
for (int i = 0, len = getArgCount(); i<len; i++) {
arrayVar.appendConvertableArrayStore(il, fact, stateIndex, argVars[i]);
argVars[i].setPositionInAroundState(stateIndex);
stateIndex++;
}
if (thisJoinPointVar != null) {
arrayVar.appendConvertableArrayStore(il, fact, stateIndex, thisJoinPointVar);
thisJoinPointVar.setPositionInAroundState(stateIndex);
stateIndex++;
}
il.append(fact.createNew(new ObjectType(constructor.getDeclaringType().getName())));
il.append(new DUP());
arrayVar.appendLoad(il, fact);
il.append(Utility.createInvoke(fact, world, constructor));
if (getKind() == PreInitialization) {
il.append(InstructionConstants.DUP);
holder.appendStore(il, fact);
}
return il;
}
private IntMap makeProceedArgumentMap(BcelVar[] adviceArgs) {
//System.err.println("coming in with " + Arrays.asList(adviceArgs));
IntMap ret = new IntMap();
for(int i = 0, len = adviceArgs.length; i < len; i++) {
BcelVar v = (BcelVar) adviceArgs[i];
if (v == null) continue; // XXX we don't know why this is required
int pos = v.getPositionInAroundState();
if (pos >= 0) { // need this test to avoid args bound via cflow
ret.put(pos, i);
}
}
//System.err.println("returning " + ret);
return ret;
}
/**
*
*
* @param callbackMethod the method we will call back to when our run method gets called.
*
* @param proceedMap A map from state position to proceed argument position. May be
* non covering on state position.
*/
private LazyMethodGen makeClosureClassAndReturnConstructor(
String closureClassName,
LazyMethodGen callbackMethod,
IntMap proceedMap)
{
String superClassName = "org.aspectj.runtime.internal.AroundClosure";
Type objectArrayType = new ArrayType(Type.OBJECT, 1);
LazyClassGen closureClass = new LazyClassGen(closureClassName,
superClassName,
getEnclosingClass().getFileName(),
Modifier.PUBLIC,
new String[] {},
getWorld());
InstructionFactory fact = new InstructionFactory(closureClass.getConstantPoolGen());
// constructor
LazyMethodGen constructor = new LazyMethodGen(Modifier.PUBLIC,
Type.VOID,
"<init>",
new Type[] {objectArrayType},
new String[] {},
closureClass);
InstructionList cbody = constructor.getBody();
cbody.append(InstructionFactory.createLoad(Type.OBJECT, 0));
cbody.append(InstructionFactory.createLoad(objectArrayType, 1));
cbody.append(fact.createInvoke(superClassName, "<init>", Type.VOID,
new Type[] {objectArrayType}, Constants.INVOKESPECIAL));
cbody.append(InstructionFactory.createReturn(Type.VOID));
closureClass.addMethodGen(constructor);
// method
LazyMethodGen runMethod = new LazyMethodGen(Modifier.PUBLIC,
Type.OBJECT,
"run",
new Type[] {objectArrayType},
new String[] {},
closureClass);
InstructionList mbody = runMethod.getBody();
BcelVar proceedVar = new BcelVar(UnresolvedType.OBJECTARRAY.resolve(world), 1);
// int proceedVarIndex = 1;
BcelVar stateVar =
new BcelVar(UnresolvedType.OBJECTARRAY.resolve(world), runMethod.allocateLocal(1));
// int stateVarIndex = runMethod.allocateLocal(1);
mbody.append(InstructionFactory.createThis());
mbody.append(fact.createGetField(superClassName, "state", objectArrayType));
mbody.append(stateVar.createStore(fact));
// mbody.append(fact.createStore(objectArrayType, stateVarIndex));
Type[] stateTypes = callbackMethod.getArgumentTypes();
for (int i=0, len=stateTypes.length; i < len; i++) {
Type stateType = stateTypes[i];
ResolvedType stateTypeX = BcelWorld.fromBcel(stateType).resolve(world);
if (proceedMap.hasKey(i)) {
mbody.append(
proceedVar.createConvertableArrayLoad(fact, proceedMap.get(i),
stateTypeX));
} else {
mbody.append(
stateVar.createConvertableArrayLoad(fact, i,
stateTypeX));
}
}
mbody.append(Utility.createInvoke(fact, callbackMethod));
if (getKind() == PreInitialization) {
mbody.append(Utility.createSet(
fact,
AjcMemberMaker.aroundClosurePreInitializationField()));
mbody.append(InstructionConstants.ACONST_NULL);
} else {
mbody.append(
Utility.createConversion(
fact,
callbackMethod.getReturnType(),
Type.OBJECT));
}
mbody.append(InstructionFactory.createReturn(Type.OBJECT));
closureClass.addMethodGen(runMethod);
// class
getEnclosingClass().addGeneratedInner(closureClass);
return constructor;
}
// ---- extraction methods
public LazyMethodGen extractMethod(String newMethodName, int visibilityModifier, ShadowMunger munger) {
LazyMethodGen.assertGoodBody(range.getBody(), newMethodName);
if (!getKind().allowsExtraction()) throw new BCException("Attempt to extract method from a shadow kind that does not support this operation (" + getKind() + ")");
LazyMethodGen freshMethod = createMethodGen(newMethodName,visibilityModifier);
// System.err.println("******");
// System.err.println("ABOUT TO EXTRACT METHOD for" + this);
// enclosingMethod.print(System.err);
// System.err.println("INTO");
// freshMethod.print(System.err);
// System.err.println("WITH REMAP");
// System.err.println(makeRemap());
range.extractInstructionsInto(freshMethod, makeRemap(),
(getKind() != PreInitialization) &&
isFallsThrough());
if (getKind() == PreInitialization) {
addPreInitializationReturnCode(
freshMethod,
getSuperConstructorParameterTypes());
}
getEnclosingClass().addMethodGen(freshMethod,munger.getSourceLocation());
return freshMethod;
}
private void addPreInitializationReturnCode(
LazyMethodGen extractedMethod,
Type[] superConstructorTypes)
{
InstructionList body = extractedMethod.getBody();
final InstructionFactory fact = getFactory();
BcelVar arrayVar = new BcelVar(
world.getCoreType(UnresolvedType.OBJECTARRAY),
extractedMethod.allocateLocal(1));
int len = superConstructorTypes.length;
body.append(Utility.createConstant(fact, len));
body.append((Instruction)fact.createNewArray(Type.OBJECT, (short)1));
arrayVar.appendStore(body, fact);
for (int i = len - 1; i >= 0; i++) {
// convert thing on top of stack to object
body.append(
Utility.createConversion(fact, superConstructorTypes[i], Type.OBJECT));
// push object array
arrayVar.appendLoad(body, fact);
// swap
body.append(InstructionConstants.SWAP);
// do object array store.
body.append(Utility.createConstant(fact, i));
body.append(InstructionConstants.SWAP);
body.append(InstructionFactory.createArrayStore(Type.OBJECT));
}
arrayVar.appendLoad(body, fact);
body.append(InstructionConstants.ARETURN);
}
private Type[] getSuperConstructorParameterTypes() {
// assert getKind() == PreInitialization
InstructionHandle superCallHandle = getRange().getEnd().getNext();
InvokeInstruction superCallInstruction =
(InvokeInstruction) superCallHandle.getInstruction();
return superCallInstruction.getArgumentTypes(
getEnclosingClass().getConstantPoolGen());
}
/** make a map from old frame location to new frame location. Any unkeyed frame
* location picks out a copied local */
private IntMap makeRemap() {
IntMap ret = new IntMap(5);
int reti = 0;
if (thisVar != null) {
ret.put(0, reti++); // thisVar guaranteed to be 0
}
if (targetVar != null && targetVar != thisVar) {
ret.put(targetVar.getSlot(), reti++);
}
for (int i = 0, len = argVars.length; i < len; i++) {
ret.put(argVars[i].getSlot(), reti);
reti += argVars[i].getType().getSize();
}
if (thisJoinPointVar != null) {
ret.put(thisJoinPointVar.getSlot(), reti++);
}
// we not only need to put the arguments, we also need to remap their
// aliases, which we so helpfully put into temps at the beginning of this join
// point.
if (! getKind().argsOnStack()) {
int oldi = 0;
int newi = 0;
// if we're passing in a this and we're not argsOnStack we're always
// passing in a target too
if (arg0HoldsThis()) { ret.put(0, 0); oldi++; newi+=1; }
//assert targetVar == thisVar
for (int i = 0; i < getArgCount(); i++) {
UnresolvedType type = getArgType(i);
ret.put(oldi, newi);
oldi += type.getSize();
newi += type.getSize();
}
}
// System.err.println("making remap for : " + this);
// if (targetVar != null) System.err.println("target slot : " + targetVar.getSlot());
// if (thisVar != null) System.err.println(" this slot : " + thisVar.getSlot());
// System.err.println(ret);
return ret;
}
/**
* The new method always static.
* It may take some extra arguments: this, target.
* If it's argsOnStack, then it must take both this/target
* If it's argsOnFrame, it shares this and target.
* ??? rewrite this to do less array munging, please
*/
private LazyMethodGen createMethodGen(String newMethodName, int visibilityModifier) {
Type[] parameterTypes = BcelWorld.makeBcelTypes(getArgTypes());
int modifiers = Modifier.FINAL | visibilityModifier;
// XXX some bug
// if (! isExpressionKind() && getSignature().isStrict(world)) {
// modifiers |= Modifier.STRICT;
// }
modifiers |= Modifier.STATIC;
if (targetVar != null && targetVar != thisVar) {
UnresolvedType targetType = getTargetType();
targetType = ensureTargetTypeIsCorrect(targetType);
// see pr109728 - this fixes the case when the declaring class is sometype 'X' but the getfield
// in the bytecode refers to a subtype of 'X'. This makes sure we use the type originally
// mentioned in the fieldget instruction as the method parameter and *not* the type upon which the
// field is declared because when the instructions are extracted into the new around body,
// they will still refer to the subtype.
if (getKind()==FieldGet && getActualTargetType()!=null &&
!getActualTargetType().equals(targetType.getName())) {
targetType = UnresolvedType.forName(getActualTargetType()).resolve(world);
}
ResolvedMember resolvedMember = getSignature().resolve(world);
if (resolvedMember != null && Modifier.isProtected(resolvedMember.getModifiers()) &&
!samePackage(targetType.getPackageName(), getEnclosingType().getPackageName()) &&
!resolvedMember.getName().equals("clone"))
{
if (!targetType.resolve(world).isAssignableFrom(getThisType().resolve(world))) {
throw new BCException("bad bytecode");
}
targetType = getThisType();
}
parameterTypes = addType(BcelWorld.makeBcelType(targetType), parameterTypes);
}
if (thisVar != null) {
UnresolvedType thisType = getThisType();
parameterTypes = addType(BcelWorld.makeBcelType(thisType), parameterTypes);
}
// We always want to pass down thisJoinPoint in case we have already woven
// some advice in here. If we only have a single piece of around advice on a
// join point, it is unnecessary to accept (and pass) tjp.
if (thisJoinPointVar != null) {
parameterTypes = addTypeToEnd(LazyClassGen.tjpType, parameterTypes);
//FIXME ALEX? which one
//parameterTypes = addTypeToEnd(LazyClassGen.proceedingTjpType, parameterTypes);
}
UnresolvedType returnType;
if (getKind() == PreInitialization) {
returnType = UnresolvedType.OBJECTARRAY;
} else {
returnType = getReturnType();
}
return
new LazyMethodGen(
modifiers,
BcelWorld.makeBcelType(returnType),
newMethodName,
parameterTypes,
new String[0],
// XXX again, we need to look up methods!
// UnresolvedType.getNames(getSignature().getExceptions(world)),
getEnclosingClass());
}
private boolean samePackage(String p1, String p2) {
if (p1 == null) return p2 == null;
if (p2 == null) return false;
return p1.equals(p2);
}
private Type[] addType(Type type, Type[] types) {
int len = types.length;
Type[] ret = new Type[len+1];
ret[0] = type;
System.arraycopy(types, 0, ret, 1, len);
return ret;
}
private Type[] addTypeToEnd(Type type, Type[] types) {
int len = types.length;
Type[] ret = new Type[len+1];
ret[len] = type;
System.arraycopy(types, 0, ret, 0, len);
return ret;
}
public BcelVar genTempVar(UnresolvedType typeX) {
return new BcelVar(typeX.resolve(world), genTempVarIndex(typeX.getSize()));
}
// public static final boolean CREATE_TEMP_NAMES = true;
public BcelVar genTempVar(UnresolvedType typeX, String localName) {
BcelVar tv = genTempVar(typeX);
// if (CREATE_TEMP_NAMES) {
// for (InstructionHandle ih = range.getStart(); ih != range.getEnd(); ih = ih.getNext()) {
// if (Range.isRangeHandle(ih)) continue;
// ih.addTargeter(new LocalVariableTag(typeX, localName, tv.getSlot()));
// }
// }
return tv;
}
// eh doesn't think we need to garbage collect these (64K is a big number...)
private int genTempVarIndex(int size) {
return enclosingMethod.allocateLocal(size);
}
public InstructionFactory getFactory() {
return getEnclosingClass().getFactory();
}
public ISourceLocation getSourceLocation() {
int sourceLine = getSourceLine();
if (sourceLine == 0 || sourceLine == -1) {
// Thread.currentThread().dumpStack();
// System.err.println(this + ": " + range);
return getEnclosingClass().getType().getSourceLocation();
} else {
// For staticinitialization, if we have a nice offset, don't build a new source loc
if (getKind()==Shadow.StaticInitialization && getEnclosingClass().getType().getSourceLocation().getOffset()!=0) {
return getEnclosingClass().getType().getSourceLocation();
} else {
int offset = 0;
Kind kind = getKind();
if ( (kind == MethodExecution) ||
(kind == ConstructorExecution) ||
(kind == AdviceExecution) ||
(kind == StaticInitialization) ||
(kind == PreInitialization) ||
(kind == Initialization)) {
if (getEnclosingMethod().hasDeclaredLineNumberInfo()) {
offset = getEnclosingMethod().getDeclarationOffset();
}
}
return getEnclosingClass().getType().getSourceContext().makeSourceLocation(sourceLine, offset);
}
}
}
public Shadow getEnclosingShadow() {
return enclosingShadow;
}
public LazyMethodGen getEnclosingMethod() {
return enclosingMethod;
}
public boolean isFallsThrough() {
return !terminatesWithReturn(); //fallsThrough;
}
public void setActualTargetType(String className) {
this.actualInstructionTargetType = className;
}
public String getActualTargetType() {
return actualInstructionTargetType;
}
}
|
119,353 |
Bug 119353 Inconsistent Implementations of ReferenceType.getDeclaredMethods()
|
I am running into a problem in load-time weaving when I use reflection delegates because the weaver is generating an incorrect bridge method when I perform an inter-type declaration on Struts.ActionServlet for the init method. On investigation, the BCEL world is recognizing this as an overriding method, because its version of getDeclaredMethods is returning the declared methods for all ancestor superclasses. However, the reflection world is returning only the declared methods for this one class. It therefore appears that the weaver expects getDeclaredMethods to return all of them (making the name quite misleading). I think previously the method was being implemented inconsistently between 1.5 reflection and <1.5 reflection delegates. But it looks like it needs to be handled consistently to include all superclass methods. However, I dont know what other places (e.g., the MAP) are really expecting getDeclaredMethods and its siblings to behave like Java reflection's version... I started work on adding a getAllDeclaredMethods method to ReferenceType and delegates, as an alternative to provide the weaver the ability to check method overriding as in this case, but it's a little bit involved and I wanted to flag the issue first. Here's a test that fails and illustrates the issue: Index: ReflectionBasedReferenceTypeDelegateTest.java =================================================================== RCS file: /home/technology/org.aspectj/modules/weaver/testsrc/org/aspectj/weaver/reflect/ReflectionBasedReferenceTypeDelegateTest.java,v retrieving revision 1.5 diff -u -r1.5 ReflectionBasedReferenceTypeDelegateTest.java --- ReflectionBasedReferenceTypeDelegateTest.java 28 Nov 2005 17:44:40 -0000 1.5 +++ ReflectionBasedReferenceTypeDelegateTest.java 6 Dec 2005 04:11:41 -0000 @@ -238,6 +238,18 @@ assertTrue("Superclass for Map generic type should be Object but was "+rt2,rt2.equals(UnresolvedType.OBJECT)); } + public void testCompareSubclassDelegates() { + world.setBehaveInJava5Way(true); + + BcelWorld bcelWorld = new BcelWorld(); + bcelWorld.setBehaveInJava5Way(true); + UnresolvedType javaUtilHashMap = UnresolvedType.forName("java.util.HashMap"); + ReferenceType rawType = (ReferenceType)bcelWorld.resolve(javaUtilHashMap ); + + ReferenceType rawReflectType = (ReferenceType)world.resolve(javaUtilHashMap ); + assertEquals(rawType.getDelegate().getDeclaredMethods().length, rawReflectType.getDelegate().getDeclaredMethods().length); + } + // todo: array of int protected void setUp() throws Exception { This results in: junit.framework.AssertionFailedError: expected:<41> but was:<29> at junit.framework.Assert.fail(Assert.java:47) at junit.framework.Assert.failNotEquals(Assert.java:282) at junit.framework.Assert.assertEquals(Assert.java:64) at junit.framework.Assert.assertEquals(Assert.java:201) at junit.framework.Assert.assertEquals(Assert.java:207) at org.aspectj.weaver.reflect.ReflectionBasedReferenceTypeDelegateTest.testCompareSubclassDelegates(ReflectionBasedReferenceTypeDelegateTest.java:250) at java.lang.reflect.Method.invoke(Native Method) 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 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
|
b52515f
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2005-12-09T08:40:12Z | 2005-12-06T03:33:20Z |
weaver/src/org/aspectj/weaver/reflect/ReflectionBasedReferenceTypeDelegateFactory.java
|
/* *******************************************************************
* Copyright (c) 2005 Contributors.
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Eclipse Public License v1.0
* which accompanies this distribution and is available at
* http://eclipse.org/legal/epl-v10.html
*
* Contributors:
* Adrian Colyer Initial implementation
* ******************************************************************/
package org.aspectj.weaver.reflect;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Member;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import org.aspectj.util.LangUtil;
import org.aspectj.weaver.ReferenceType;
import org.aspectj.weaver.ResolvedMember;
import org.aspectj.weaver.ResolvedMemberImpl;
import org.aspectj.weaver.ResolvedType;
import org.aspectj.weaver.UnresolvedType;
import org.aspectj.weaver.World;
/**
* @author colyer
* Creates the appropriate ReflectionBasedReferenceTypeDelegate according to
* the VM level we are running at. Uses reflection to avoid 1.5 dependencies in
* 1.4 and 1.3 code base.
*/
public class ReflectionBasedReferenceTypeDelegateFactory {
public static ReflectionBasedReferenceTypeDelegate
createDelegate(ReferenceType forReferenceType, World inWorld, ClassLoader usingClassLoader) {
try {
Class c = Class.forName(forReferenceType.getName(),false,usingClassLoader);
if (LangUtil.is15VMOrGreater()) {
ReflectionBasedReferenceTypeDelegate rbrtd = create15Delegate(forReferenceType,c,usingClassLoader,inWorld);
if (rbrtd!=null) return rbrtd; // can be null if we didn't find the class the delegate logic loads
}
return new ReflectionBasedReferenceTypeDelegate(c,usingClassLoader,inWorld,forReferenceType);
} catch (ClassNotFoundException cnfEx) {
return null;
}
}
private static ReflectionBasedReferenceTypeDelegate create15Delegate(ReferenceType forReferenceType, Class forClass, ClassLoader usingClassLoader, World inWorld) {
try {
Class delegateClass = Class.forName("org.aspectj.weaver.reflect.Java15ReflectionBasedReferenceTypeDelegate");//,false,usingClassLoader);//ReflectionBasedReferenceTypeDelegate.class.getClassLoader());
ReflectionBasedReferenceTypeDelegate ret = (ReflectionBasedReferenceTypeDelegate) delegateClass.newInstance();
ret.initialize(forReferenceType,forClass,usingClassLoader,inWorld);
return ret;
} catch (ClassNotFoundException cnfEx) {
throw new IllegalStateException("Attempted to create Java 1.5 reflection based delegate but org.aspectj.weaver.reflect.Java15ReflectionBasedReferenceTypeDelegate was not found on classpath");
} catch (InstantiationException insEx) {
throw new IllegalStateException("Attempted to create Java 1.5 reflection based delegate but InstantiationException: " + insEx + " occured");
} catch (IllegalAccessException illAccEx) {
throw new IllegalStateException("Attempted to create Java 1.5 reflection based delegate but IllegalAccessException: " + illAccEx + " occured");
}
}
private static GenericSignatureInformationProvider createGenericSignatureProvider(World inWorld) {
if (LangUtil.is15VMOrGreater()) {
try {
Class providerClass = Class.forName("org.aspectj.weaver.reflect.Java15GenericSignatureInformationProvider");
Constructor cons = providerClass.getConstructor(new Class[] {World.class});
GenericSignatureInformationProvider ret = (GenericSignatureInformationProvider) cons.newInstance(new Object[] {inWorld});
return ret;
} catch (ClassNotFoundException cnfEx) {
throw new IllegalStateException("Attempted to create Java 1.5 generic signature provider but org.aspectj.weaver.reflect.Java15GenericSignatureInformationProvider was not found on classpath");
} catch (NoSuchMethodException nsmEx) {
throw new IllegalStateException("Attempted to create Java 1.5 generic signature provider but: " + nsmEx + " occured");
} catch (InstantiationException insEx) {
throw new IllegalStateException("Attempted to create Java 1.5 generic signature provider but: " + insEx + " occured");
} catch (InvocationTargetException invEx) {
throw new IllegalStateException("Attempted to create Java 1.5 generic signature provider but: " + invEx + " occured");
} catch (IllegalAccessException illAcc) {
throw new IllegalStateException("Attempted to create Java 1.5 generic signature provider but: " + illAcc + " occured");
}
} else {
return new Java14GenericSignatureInformationProvider();
}
}
/**
* convert a java.lang.reflect.Member into a resolved member in the world
* @param reflectMember
* @param inWorld
* @return
*/
public static ResolvedMember createResolvedMember(Member reflectMember, World inWorld) {
if (reflectMember instanceof Method) {
return createResolvedMethod((Method)reflectMember,inWorld);
} else if (reflectMember instanceof Constructor) {
return createResolvedConstructor((Constructor)reflectMember,inWorld);
} else {
return createResolvedField((Field)reflectMember,inWorld);
}
}
public static ResolvedMember createResolvedMethod(Method aMethod, World inWorld) {
ReflectionBasedResolvedMemberImpl ret = new ReflectionBasedResolvedMemberImpl(org.aspectj.weaver.Member.METHOD,
toResolvedType(aMethod.getDeclaringClass(),(ReflectionWorld)inWorld),
aMethod.getModifiers(),
toResolvedType(aMethod.getReturnType(),(ReflectionWorld)inWorld),
aMethod.getName(),
toResolvedTypeArray(aMethod.getParameterTypes(),inWorld),
toResolvedTypeArray(aMethod.getExceptionTypes(),inWorld),
aMethod
);
if (inWorld instanceof ReflectionWorld) {
ret.setAnnotationFinder(((ReflectionWorld)inWorld).getAnnotationFinder());
}
ret.setGenericSignatureInformationProvider(createGenericSignatureProvider(inWorld));
return ret;
}
public static ResolvedMember createResolvedAdviceMember(Method aMethod, World inWorld) {
ReflectionBasedResolvedMemberImpl ret =
new ReflectionBasedResolvedMemberImpl(org.aspectj.weaver.Member.ADVICE,
toResolvedType(aMethod.getDeclaringClass(),(ReflectionWorld)inWorld),
aMethod.getModifiers(),
toResolvedType(aMethod.getReturnType(),(ReflectionWorld)inWorld),
aMethod.getName(),
toResolvedTypeArray(aMethod.getParameterTypes(),inWorld),
toResolvedTypeArray(aMethod.getExceptionTypes(),inWorld),
aMethod
);
if (inWorld instanceof ReflectionWorld) {
ret.setAnnotationFinder(((ReflectionWorld)inWorld).getAnnotationFinder());
}
ret.setGenericSignatureInformationProvider(createGenericSignatureProvider(inWorld));
return ret;
}
public static ResolvedMember createStaticInitMember(Class forType, World inWorld) {
return new ResolvedMemberImpl(org.aspectj.weaver.Member.STATIC_INITIALIZATION,
toResolvedType(forType,(ReflectionWorld)inWorld),
Modifier.STATIC,
ResolvedType.VOID,
"<clinit>",
new UnresolvedType[0],
new UnresolvedType[0]
);
}
public static ResolvedMember createResolvedConstructor(Constructor aConstructor, World inWorld) {
ReflectionBasedResolvedMemberImpl ret =
new ReflectionBasedResolvedMemberImpl(org.aspectj.weaver.Member.CONSTRUCTOR,
toResolvedType(aConstructor.getDeclaringClass(),(ReflectionWorld)inWorld),
aConstructor.getModifiers(),
toResolvedType(aConstructor.getDeclaringClass(),(ReflectionWorld)inWorld),
"init",
toResolvedTypeArray(aConstructor.getParameterTypes(),inWorld),
toResolvedTypeArray(aConstructor.getExceptionTypes(),inWorld),
aConstructor
);
if (inWorld instanceof ReflectionWorld) {
ret.setAnnotationFinder(((ReflectionWorld)inWorld).getAnnotationFinder());
}
ret.setGenericSignatureInformationProvider(createGenericSignatureProvider(inWorld));
return ret;
}
public static ResolvedMember createResolvedField(Field aField, World inWorld) {
ReflectionBasedResolvedMemberImpl ret =
new ReflectionBasedResolvedMemberImpl(org.aspectj.weaver.Member.FIELD,
toResolvedType(aField.getDeclaringClass(),(ReflectionWorld)inWorld),
aField.getModifiers(),
toResolvedType(aField.getType(),(ReflectionWorld)inWorld),
aField.getName(),
new UnresolvedType[0],
aField);
if (inWorld instanceof ReflectionWorld) {
ret.setAnnotationFinder(((ReflectionWorld)inWorld).getAnnotationFinder());
}
ret.setGenericSignatureInformationProvider(createGenericSignatureProvider(inWorld));
return ret;
}
public static ResolvedMember createHandlerMember(Class exceptionType, Class inType,World inWorld) {
return new ResolvedMemberImpl(
org.aspectj.weaver.Member.HANDLER,
toResolvedType(inType,(ReflectionWorld)inWorld),
Modifier.STATIC,
"<catch>",
"(" + inWorld.resolve(exceptionType.getName()).getSignature() + ")V");
}
public static ResolvedType resolveTypeInWorld(Class aClass, World aWorld) {
// classes that represent arrays return a class name that is the signature of the array type, ho-hum...
String className = aClass.getName();
if (aClass.isArray()) {
return aWorld.resolve(UnresolvedType.forSignature(className.replace('.','/')));
}
else{
return aWorld.resolve(className);
}
}
private static ResolvedType toResolvedType(Class aClass, ReflectionWorld aWorld) {
return aWorld.resolve(aClass);
}
private static ResolvedType[] toResolvedTypeArray(Class[] classes, World inWorld) {
ResolvedType[] ret = new ResolvedType[classes.length];
for (int i = 0; i < ret.length; i++) {
ret[i] = ((ReflectionWorld)inWorld).resolve(classes[i]);
}
return ret;
}
}
|
119,353 |
Bug 119353 Inconsistent Implementations of ReferenceType.getDeclaredMethods()
|
I am running into a problem in load-time weaving when I use reflection delegates because the weaver is generating an incorrect bridge method when I perform an inter-type declaration on Struts.ActionServlet for the init method. On investigation, the BCEL world is recognizing this as an overriding method, because its version of getDeclaredMethods is returning the declared methods for all ancestor superclasses. However, the reflection world is returning only the declared methods for this one class. It therefore appears that the weaver expects getDeclaredMethods to return all of them (making the name quite misleading). I think previously the method was being implemented inconsistently between 1.5 reflection and <1.5 reflection delegates. But it looks like it needs to be handled consistently to include all superclass methods. However, I dont know what other places (e.g., the MAP) are really expecting getDeclaredMethods and its siblings to behave like Java reflection's version... I started work on adding a getAllDeclaredMethods method to ReferenceType and delegates, as an alternative to provide the weaver the ability to check method overriding as in this case, but it's a little bit involved and I wanted to flag the issue first. Here's a test that fails and illustrates the issue: Index: ReflectionBasedReferenceTypeDelegateTest.java =================================================================== RCS file: /home/technology/org.aspectj/modules/weaver/testsrc/org/aspectj/weaver/reflect/ReflectionBasedReferenceTypeDelegateTest.java,v retrieving revision 1.5 diff -u -r1.5 ReflectionBasedReferenceTypeDelegateTest.java --- ReflectionBasedReferenceTypeDelegateTest.java 28 Nov 2005 17:44:40 -0000 1.5 +++ ReflectionBasedReferenceTypeDelegateTest.java 6 Dec 2005 04:11:41 -0000 @@ -238,6 +238,18 @@ assertTrue("Superclass for Map generic type should be Object but was "+rt2,rt2.equals(UnresolvedType.OBJECT)); } + public void testCompareSubclassDelegates() { + world.setBehaveInJava5Way(true); + + BcelWorld bcelWorld = new BcelWorld(); + bcelWorld.setBehaveInJava5Way(true); + UnresolvedType javaUtilHashMap = UnresolvedType.forName("java.util.HashMap"); + ReferenceType rawType = (ReferenceType)bcelWorld.resolve(javaUtilHashMap ); + + ReferenceType rawReflectType = (ReferenceType)world.resolve(javaUtilHashMap ); + assertEquals(rawType.getDelegate().getDeclaredMethods().length, rawReflectType.getDelegate().getDeclaredMethods().length); + } + // todo: array of int protected void setUp() throws Exception { This results in: junit.framework.AssertionFailedError: expected:<41> but was:<29> at junit.framework.Assert.fail(Assert.java:47) at junit.framework.Assert.failNotEquals(Assert.java:282) at junit.framework.Assert.assertEquals(Assert.java:64) at junit.framework.Assert.assertEquals(Assert.java:201) at junit.framework.Assert.assertEquals(Assert.java:207) at org.aspectj.weaver.reflect.ReflectionBasedReferenceTypeDelegateTest.testCompareSubclassDelegates(ReflectionBasedReferenceTypeDelegateTest.java:250) at java.lang.reflect.Method.invoke(Native Method) 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 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
|
b52515f
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2005-12-09T08:40:12Z | 2005-12-06T03:33:20Z |
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 junit.framework.TestCase;
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));
}
// todo: array of int
protected void setUp() throws Exception {
world = new ReflectionWorld();
objectType = world.resolve("java.lang.Object");
}
}
|
119,353 |
Bug 119353 Inconsistent Implementations of ReferenceType.getDeclaredMethods()
|
I am running into a problem in load-time weaving when I use reflection delegates because the weaver is generating an incorrect bridge method when I perform an inter-type declaration on Struts.ActionServlet for the init method. On investigation, the BCEL world is recognizing this as an overriding method, because its version of getDeclaredMethods is returning the declared methods for all ancestor superclasses. However, the reflection world is returning only the declared methods for this one class. It therefore appears that the weaver expects getDeclaredMethods to return all of them (making the name quite misleading). I think previously the method was being implemented inconsistently between 1.5 reflection and <1.5 reflection delegates. But it looks like it needs to be handled consistently to include all superclass methods. However, I dont know what other places (e.g., the MAP) are really expecting getDeclaredMethods and its siblings to behave like Java reflection's version... I started work on adding a getAllDeclaredMethods method to ReferenceType and delegates, as an alternative to provide the weaver the ability to check method overriding as in this case, but it's a little bit involved and I wanted to flag the issue first. Here's a test that fails and illustrates the issue: Index: ReflectionBasedReferenceTypeDelegateTest.java =================================================================== RCS file: /home/technology/org.aspectj/modules/weaver/testsrc/org/aspectj/weaver/reflect/ReflectionBasedReferenceTypeDelegateTest.java,v retrieving revision 1.5 diff -u -r1.5 ReflectionBasedReferenceTypeDelegateTest.java --- ReflectionBasedReferenceTypeDelegateTest.java 28 Nov 2005 17:44:40 -0000 1.5 +++ ReflectionBasedReferenceTypeDelegateTest.java 6 Dec 2005 04:11:41 -0000 @@ -238,6 +238,18 @@ assertTrue("Superclass for Map generic type should be Object but was "+rt2,rt2.equals(UnresolvedType.OBJECT)); } + public void testCompareSubclassDelegates() { + world.setBehaveInJava5Way(true); + + BcelWorld bcelWorld = new BcelWorld(); + bcelWorld.setBehaveInJava5Way(true); + UnresolvedType javaUtilHashMap = UnresolvedType.forName("java.util.HashMap"); + ReferenceType rawType = (ReferenceType)bcelWorld.resolve(javaUtilHashMap ); + + ReferenceType rawReflectType = (ReferenceType)world.resolve(javaUtilHashMap ); + assertEquals(rawType.getDelegate().getDeclaredMethods().length, rawReflectType.getDelegate().getDeclaredMethods().length); + } + // todo: array of int protected void setUp() throws Exception { This results in: junit.framework.AssertionFailedError: expected:<41> but was:<29> at junit.framework.Assert.fail(Assert.java:47) at junit.framework.Assert.failNotEquals(Assert.java:282) at junit.framework.Assert.assertEquals(Assert.java:64) at junit.framework.Assert.assertEquals(Assert.java:201) at junit.framework.Assert.assertEquals(Assert.java:207) at org.aspectj.weaver.reflect.ReflectionBasedReferenceTypeDelegateTest.testCompareSubclassDelegates(ReflectionBasedReferenceTypeDelegateTest.java:250) at java.lang.reflect.Method.invoke(Native Method) 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 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
|
b52515f
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2005-12-09T08:40:12Z | 2005-12-06T03:33:20Z |
weaver5/java5-src/org/aspectj/weaver/reflect/Java15ReflectionBasedReferenceTypeDelegate.java
|
/* *******************************************************************
* Copyright (c) 2005 Contributors.
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Eclipse Public License v1.0
* which accompanies this distribution and is available at
* http://eclipse.org/legal/epl-v10.html
*
* Contributors:
* Adrian Colyer Initial implementation
* ******************************************************************/
package org.aspectj.weaver.reflect;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.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.internal.tools.PointcutExpressionImpl;
import org.aspectj.weaver.tools.PointcutParameter;
import org.aspectj.weaver.tools.PointcutParser;
/**
* @author colyer
* Provides Java 5 behaviour in reflection based delegates (overriding
* 1.4 behaviour from superclass where appropriate)
*/
public class Java15ReflectionBasedReferenceTypeDelegate extends
ReflectionBasedReferenceTypeDelegate {
private AjType<?> myType;
private ResolvedType[] annotations;
private ResolvedMember[] pointcuts;
private ResolvedMember[] methods;
private ResolvedMember[] fields;
private TypeVariable[] typeVariables;
private ResolvedType superclass;
private ResolvedType[] superInterfaces;
private String genericSignature = null;
private JavaLangTypeToResolvedTypeConverter typeConverter;
private Java15AnnotationFinder annotationFinder = 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();
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(),
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];
PointcutParser parser = PointcutParser.getPointcutParserSupportingAllPrimitivesAndUsingSpecifiedClassloaderForResolution(classLoader);
for (int i = 0; i < pcs.length; i++) {
AjType<?>[] ptypes = pcs[i].getParameterTypes();
String[] pnames = pcs[i].getParameterNames();
if (pnames.length != ptypes.length) {
throw new IllegalStateException("Required parameter names not available when parsing pointcut " + pcs[i].getName() + " in type " + getResolvedTypeX().getName());
}
PointcutParameter[] parameters = new PointcutParameter[ptypes.length];
for (int j = 0; j < parameters.length; j++) {
parameters[j] = parser.createPointcutParameter(pnames[j],ptypes[j].getJavaClass());
}
String pcExpr = pcs[i].getPointcutExpression().toString();
PointcutExpressionImpl pEx = (PointcutExpressionImpl) parser.parsePointcutExpression(pcExpr,getBaseClass(),parameters);
org.aspectj.weaver.patterns.Pointcut pc = pEx.getUnderlyingPointcut();
UnresolvedType[] weaverPTypes = new UnresolvedType[ptypes.length];
for (int j = 0; j < weaverPTypes.length; j++) {
weaverPTypes[j] = UnresolvedType.forName(ptypes[j].getName());
}
pointcuts[i] = new ResolvedPointcutDefinition(getResolvedTypeX(),pcs[i].getModifiers(),pcs[i].getName(),weaverPTypes,pc);
}
}
return pointcuts;
}
public boolean isAnnotation() {
return getBaseClass().isAnnotation();
}
public boolean isAnnotationStyleAspect() {
return getBaseClass().isAnnotationPresent(Aspect.class);
}
public boolean isAnnotationWithRuntimeRetention() {
if (!isAnnotation()) return false;
if (getBaseClass().isAnnotationPresent(Retention.class)) {
Retention retention = (Retention) getBaseClass().getAnnotation(Retention.class);
RetentionPolicy policy = retention.value();
return policy == RetentionPolicy.RUNTIME;
} else {
return false;
}
}
public boolean isAspect() {
return this.myType.isAspect();
}
public boolean isEnum() {
return getBaseClass().isEnum();
}
public boolean isGeneric() {
//return false; // for now
return getBaseClass().getTypeParameters().length > 0;
}
@Override
public boolean isAnonymous() {
return this.myClass.isAnonymousClass();
}
}
|
119,451 |
Bug 119451 AJDoc produces incorrect warning for package accessed aspects
| null |
resolved fixed
|
5f8d2cd
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2005-12-09T10:32:57Z | 2005-12-06T17:26:40Z |
ajde/testsrc/org/aspectj/ajde/AsmDeclarationsTest.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
*
* ******************************************************************/
package org.aspectj.ajde;
import org.aspectj.asm.*;
/**
* @author Mik Kersten
*/
public class AsmDeclarationsTest extends AjdeTestCase {
private IHierarchy model = null;
// TODO-path
private static final String CONFIG_FILE_PATH = "../examples/coverage/coverage.lst";
public AsmDeclarationsTest(String name) {
super(name);
}
public void testRoot() {
IProgramElement root = (IProgramElement)model.getRoot();
assertNotNull(root);
assertEquals(root.toLabelString(), "coverage.lst");
}
public void testAspectAccessibility() {
IProgramElement packageAspect = AsmManager.getDefault().getHierarchy().findElementForType(null, "AdviceNamingCoverage");
assertNotNull(packageAspect);
assertEquals(IProgramElement.Accessibility.PACKAGE, packageAspect.getAccessibility());
}
public void testStaticModifiers() {
IProgramElement aspect = AsmManager.getDefault().getHierarchy().findElementForType(null, "ModifiersCoverage");
assertNotNull(aspect);
IProgramElement staticA = model.findElementForSignature(aspect, IProgramElement.Kind.FIELD, "staticA");
assertTrue(staticA.getModifiers().contains(IProgramElement.Modifiers.STATIC));
IProgramElement finalA = model.findElementForSignature(aspect, IProgramElement.Kind.FIELD, "finalA");
assertTrue(!finalA.getModifiers().contains(IProgramElement.Modifiers.STATIC));
assertTrue(finalA.getModifiers().contains(IProgramElement.Modifiers.FINAL));
}
public void testFileInPackageAndDefaultPackage() {
IProgramElement root = model.getRoot();
assertEquals(root.toLabelString(), "coverage.lst");
IProgramElement pkg = (IProgramElement)root.getChildren().get(1);
assertEquals(pkg.toLabelString(), "pkg");
assertEquals(((IProgramElement)pkg.getChildren().get(0)).toLabelString(), "InPackage.java");
assertEquals(((IProgramElement)root.getChildren().get(0)).toLabelString(), "ModelCoverage.java");
}
public void testDeclares() {
IProgramElement node = (IProgramElement)model.getRoot();
assertNotNull(node);
IProgramElement aspect = AsmManager.getDefault().getHierarchy().findElementForType(null, "DeclareCoverage");
assertNotNull(aspect);
String label = "declare error: \"Illegal construct..\"";
IProgramElement decErrNode = model.findElementForSignature(aspect, IProgramElement.Kind.DECLARE_ERROR, "declare error");
assertNotNull(decErrNode);
assertEquals(decErrNode.toLabelString(), label);
String decWarnMessage = "declare warning: \"Illegal call.\"";
IProgramElement decWarnNode = model.findElementForSignature(aspect, IProgramElement.Kind.DECLARE_WARNING, "declare warning");
assertNotNull(decWarnNode);
assertEquals(decWarnNode.toLabelString(), decWarnMessage);
String decParentsMessage = "declare parents: implements Serializable";
IProgramElement decParentsNode = model.findElementForSignature(aspect, IProgramElement.Kind.DECLARE_PARENTS, "declare parents");
assertNotNull(decParentsNode);
assertEquals(decParentsNode.toLabelString(), decParentsMessage);
// check the next two relative to this one
int declareIndex = decParentsNode.getParent().getChildren().indexOf(decParentsNode);
String decParentsPtnMessage = "declare parents: extends Observable";
assertEquals(decParentsPtnMessage,((IProgramElement)aspect.getChildren().get(declareIndex+1)).toLabelString());
String decParentsTPMessage = "declare parents: extends Observable";
assertEquals(decParentsTPMessage,((IProgramElement)aspect.getChildren().get(declareIndex+2)).toLabelString());
String decSoftMessage = "declare soft: SizeException";
IProgramElement decSoftNode = model.findElementForSignature(aspect, IProgramElement.Kind.DECLARE_SOFT, "declare soft");
assertNotNull(decSoftNode);
assertEquals(decSoftNode.toLabelString(), decSoftMessage);
String decPrecMessage = "declare precedence: AdviceCoverage, InterTypeDecCoverage, <type pattern>";
IProgramElement decPrecNode = model.findElementForSignature(aspect, IProgramElement.Kind.DECLARE_PRECEDENCE, "declare precedence");
assertNotNull(decPrecNode);
assertEquals(decPrecNode.toLabelString(), decPrecMessage);
}
public void testInterTypeMemberDeclares() {
IProgramElement node = (IProgramElement)model.getRoot();
assertNotNull(node);
IProgramElement aspect = AsmManager.getDefault().getHierarchy().findElementForType(null, "InterTypeDecCoverage");
assertNotNull(aspect);
String fieldMsg = "Point.xxx";
IProgramElement fieldNode = model.findElementForLabel(aspect, IProgramElement.Kind.INTER_TYPE_FIELD, fieldMsg);
assertNotNull(fieldNode);
assertEquals(fieldNode.toLabelString(), fieldMsg);
String methodMsg = "Point.check(int, Line)";
IProgramElement methodNode = model.findElementForLabel(aspect, IProgramElement.Kind.INTER_TYPE_METHOD, methodMsg);
assertNotNull(methodNode);
assertEquals(methodNode.toLabelString(), methodMsg);
// TODO: enable
// String constructorMsg = "Point.new(int, int, int)";
// ProgramElementNode constructorNode = model.findNode(aspect, ProgramElementNode.Kind.INTER_TYPE_CONSTRUCTOR, constructorMsg);
// assertNotNull(constructorNode);
// assertEquals(constructorNode.toLabelString(), constructorMsg);
}
public void testPointcuts() {
IProgramElement node = (IProgramElement)model.getRoot();
assertNotNull(node);
IProgramElement aspect = AsmManager.getDefault().getHierarchy().findElementForType(null, "AdviceNamingCoverage");
assertNotNull(aspect);
String ptct = "named()";
IProgramElement ptctNode = model.findElementForSignature(aspect, IProgramElement.Kind.POINTCUT, ptct);
assertNotNull(ptctNode);
assertEquals(ptctNode.toLabelString(), ptct);
String params = "namedWithArgs(int, int)";
IProgramElement paramsNode = model.findElementForSignature(aspect, IProgramElement.Kind.POINTCUT, params);
assertNotNull(paramsNode);
assertEquals(paramsNode.toLabelString(), params);
}
public void testAbstract() {
IProgramElement node = (IProgramElement)model.getRoot();
assertNotNull(node);
IProgramElement aspect = AsmManager.getDefault().getHierarchy().findElementForType(null, "AbstractAspect");
assertNotNull(aspect);
String abst = "abPtct()";
IProgramElement abstNode = model.findElementForSignature(aspect, IProgramElement.Kind.POINTCUT, abst);
assertNotNull(abstNode);
assertEquals(abstNode.toLabelString(), abst);
}
public void testAdvice() {
IProgramElement node = (IProgramElement)model.getRoot();
assertNotNull(node);
IProgramElement aspect = AsmManager.getDefault().getHierarchy().findElementForType(null, "AdviceNamingCoverage");
assertNotNull(aspect);
String anon = "before(): <anonymous pointcut>";
IProgramElement anonNode = model.findElementForLabel(aspect, IProgramElement.Kind.ADVICE, anon);
assertNotNull(anonNode);
assertEquals(anonNode.toLabelString(), anon);
String named = "before(): named..";
IProgramElement namedNode = model.findElementForLabel(aspect, IProgramElement.Kind.ADVICE, named);
assertNotNull(namedNode);
assertEquals(namedNode.toLabelString(), named);
String namedWithOneArg = "around(int): namedWithOneArg..";
IProgramElement namedWithOneArgNode = model.findElementForLabel(aspect, IProgramElement.Kind.ADVICE, namedWithOneArg);
assertNotNull(namedWithOneArgNode);
assertEquals(namedWithOneArgNode.toLabelString(), namedWithOneArg);
String afterReturning = "afterReturning(int, int): namedWithArgs..";
IProgramElement afterReturningNode = model.findElementForLabel(aspect, IProgramElement.Kind.ADVICE, afterReturning);
assertNotNull(afterReturningNode);
assertEquals(afterReturningNode.toLabelString(), afterReturning);
String around = "around(int): namedWithOneArg..";
IProgramElement aroundNode = model.findElementForLabel(aspect, IProgramElement.Kind.ADVICE, around);
assertNotNull(aroundNode);
assertEquals(aroundNode.toLabelString(), around);
String compAnon = "before(int): <anonymous pointcut>..";
IProgramElement compAnonNode = model.findElementForLabel(aspect, IProgramElement.Kind.ADVICE, compAnon);
assertNotNull(compAnonNode);
assertEquals(compAnonNode.toLabelString(), compAnon);
String compNamed = "before(int): named()..";
IProgramElement compNamedNode = model.findElementForLabel(aspect, IProgramElement.Kind.ADVICE, compNamed);
assertNotNull(compNamedNode);
assertEquals(compNamedNode.toLabelString(), compNamed);
}
protected void setUp() throws Exception {
super.setUp("examples");
assertTrue("build success", doSynchronousBuild(CONFIG_FILE_PATH));
model = AsmManager.getDefault().getHierarchy();
}
protected void tearDown() throws Exception {
super.tearDown();
}
}
|
119,451 |
Bug 119451 AJDoc produces incorrect warning for package accessed aspects
| null |
resolved fixed
|
5f8d2cd
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2005-12-09T10:32:57Z | 2005-12-06T17:26:40Z |
ajdoc/src/org/aspectj/tools/ajdoc/StubFileGenerator.java
|
/* *******************************************************************
* Copyright (c) 1999-2001 Xerox Corporation,
* 2002 Palo Alto Research Center, Incorporated (PARC).
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* Xerox/PARC initial implementation
* Mik Kersten port to AspectJ 1.1+ code base
* ******************************************************************/
package org.aspectj.tools.ajdoc;
import java.io.*;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import org.aspectj.asm.AsmManager;
import org.aspectj.asm.IProgramElement;
/**
* @author Mik Kersten
*/
class StubFileGenerator{
static Hashtable declIDTable = null;
static void doFiles (Hashtable table,
SymbolManager symbolManager,
File[] inputFiles,
File[] signatureFiles) throws DocException {
declIDTable = table;
for (int i = 0; i < inputFiles.length; i++) {
processFile(symbolManager, inputFiles[i], signatureFiles[i]);
}
}
static void processFile(SymbolManager symbolManager, File inputFile, File signatureFile) throws DocException {
try {
String path = StructureUtil.translateAjPathName(signatureFile.getCanonicalPath());
PrintWriter writer = new PrintWriter(new BufferedWriter(new FileWriter(path)));
String packageName = StructureUtil.getPackageDeclarationFromFile(inputFile);
if (packageName != null && packageName != "") {
writer.println( "package " + packageName + ";" );
}
IProgramElement fileNode = (IProgramElement)AsmManager.getDefault().getHierarchy().findElementForSourceFile(inputFile.getAbsolutePath());
for (Iterator it = fileNode.getChildren().iterator(); it.hasNext(); ) {
IProgramElement node = (IProgramElement)it.next();
if (node.getKind().equals(IProgramElement.Kind.IMPORT_REFERENCE)) {
processImportDeclaration(node, writer);
} else {
try {
processTypeDeclaration(node, writer);
} catch (DocException d){
throw new DocException("File name invalid: " + inputFile.toString());
}
}
}
// if we got an error we don't want the contents of the file
writer.close();
} catch (IOException e) {
System.err.println(e.getMessage());
e.printStackTrace();
}
}
private static void processImportDeclaration(IProgramElement node, PrintWriter writer) throws IOException {
List imports = node.getChildren();
for (Iterator i = imports.iterator(); i.hasNext();) {
IProgramElement importNode = (IProgramElement) i.next();
writer.print("import ");
writer.print(importNode.getName());
writer.println(';');
}
}
private static void processTypeDeclaration(IProgramElement classNode, PrintWriter writer) throws DocException {
String formalComment = addDeclID(classNode, classNode.getFormalComment());
writer.println(formalComment);
String signature = genSourceSignature(classNode);// StructureUtil.genSignature(classNode);
if (signature == null){
throw new DocException("The java file is invalid");
}
// System.err.println("######" + signature + ", " + classNode.getName());
if (!StructureUtil.isAnonymous(classNode) && !classNode.getName().equals("<undefined>")) {
writer.println(signature + " {" );
processMembers(classNode.getChildren(), writer, classNode.getKind().equals(IProgramElement.Kind.INTERFACE));
writer.println();
writer.println("}");
}
}
private static void processMembers(List/*IProgramElement*/ members, PrintWriter writer, boolean declaringTypeIsInterface) throws DocException {
for (Iterator it = members.iterator(); it.hasNext();) {
IProgramElement member = (IProgramElement) it.next();
if (member.getKind().isType()) {
if (!member.getParent().getKind().equals(IProgramElement.Kind.METHOD)
&& !StructureUtil.isAnonymous(member)) {// don't print anonymous types
// System.err.println(">>>>>>>>>>>>>" + member.getName() + "<<<<" + member.getParent());
processTypeDeclaration(member, writer);
}
} else {
String formalComment = addDeclID(member, member.getFormalComment());;
writer.println(formalComment);
String signature = "";
if (!member.getKind().equals(IProgramElement.Kind.POINTCUT)
&& !member.getKind().equals(IProgramElement.Kind.ADVICE)) {
signature = member.getSourceSignature();//StructureUtil.genSignature(member);
if (member.getKind().equals(IProgramElement.Kind.ENUM_VALUE)){
if (((IProgramElement)members.get(members.indexOf(member)+1)).getKind().equals(IProgramElement.Kind.ENUM_VALUE)){
// if the next member is also an ENUM_VALUE:
signature = signature + ",";
} else {
signature = signature + ";";
}
}
}
if (member.getKind().isDeclare()) {
// System.err.println("> Skipping declare (ajdoc limitation): " + member.toLabelString());
} else if (signature != null &&
signature != "" &&
!member.getKind().isInterTypeMember() &&
!member.getKind().equals(IProgramElement.Kind.INITIALIZER) &&
!StructureUtil.isAnonymous(member)) {
writer.print(signature);
} else {
// System.err.println(">> skipping: " + member.getKind());
}
if (member.getKind().equals(IProgramElement.Kind.METHOD) ||
member.getKind().equals(IProgramElement.Kind.CONSTRUCTOR)) {
if (member.getParent().getKind().equals(IProgramElement.Kind.INTERFACE) ||
signature.indexOf("abstract ") != -1) {
writer.println(";");
} else {
writer.println(" { }");
}
} else if (member.getKind().equals(IProgramElement.Kind.FIELD)) {
// writer.println(";");
}
}
}
}
/**
* Translates "aspect" to "class", as long as its not ".aspect"
*/
private static String genSourceSignature(IProgramElement classNode) {
String signature = classNode.getSourceSignature();
if (signature != null){
int index = signature.indexOf("aspect");
if (index != -1 && signature.charAt(index-1) != '.') {
signature = signature.substring(0, index) +
"class " +
signature.substring(index + 6, signature.length());
}
}
return signature;
}
static int nextDeclID = 0;
static String addDeclID(IProgramElement decl, String formalComment) {
String declID = "" + ++nextDeclID;
declIDTable.put(declID, decl);
return addToFormal(formalComment, Config.DECL_ID_STRING + declID + Config.DECL_ID_TERMINATOR);
}
/**
* We want to go:
* just before the first period
* just before the first @
* just before the end of the comment
*
* Adds a place holder for the period ('#') if one will need to be
* replaced.
*/
static String addToFormal(String formalComment, String string) {
boolean appendPeriod = true;
if ( (formalComment == null) || formalComment.equals("")) {
//formalComment = "/**\n * . \n */\n";
formalComment = "/**\n * \n */\n";
appendPeriod = false;
}
formalComment = formalComment.trim();
int atsignPos = formalComment.indexOf('@');
int endPos = formalComment.indexOf("*/");
int periodPos = formalComment.indexOf("/**")+2;
int position = 0;
String periodPlaceHolder = "";
if ( periodPos != -1 ) {
position = periodPos+1;
}
else if ( atsignPos != -1 ) {
string = string + "\n * ";
position = atsignPos;
}
else if ( endPos != -1 ) {
string = "* " + string + "\n";
position = endPos;
}
else {
// !!! perhaps this error should not be silent
throw new Error("Failed to append to formal comment for comment: " +
formalComment );
}
return
formalComment.substring(0, position) + periodPlaceHolder +
string +
formalComment.substring(position);
}
}
|
119,451 |
Bug 119451 AJDoc produces incorrect warning for package accessed aspects
| null |
resolved fixed
|
5f8d2cd
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2005-12-09T10:32:57Z | 2005-12-06T17:26:40Z |
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 Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* PARC initial implementation
* ******************************************************************/
package org.aspectj.ajdt.internal.compiler.ast;
import java.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 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);
world.addTypeBinding(interfaceType);
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
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.addTypeBinding(interfaceType);
interfaceType.addMethod(world, AjcMemberMaker.perObjectInterfaceGet(typeX));
interfaceType.addMethod(world, AjcMemberMaker.perObjectInterfaceSet(typeX));
interfaceType.generateClass(compilationResult, classFile);
return interfaceType;
}
// 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());
} 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) {
printModifiers(this.modifiers, 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;
}
}
|
120,351 |
Bug 120351 cflowbelow issue when binding, in @AJ
| null |
resolved fixed
|
979124d
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2005-12-12T10:48:46Z | 2005-12-12T09:33:20Z |
tests/java5/ataspectj/ataspectj/bugs/CflowBelowStackTest.java
| |
120,351 |
Bug 120351 cflowbelow issue when binding, in @AJ
| null |
resolved fixed
|
979124d
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2005-12-12T10:48:46Z | 2005-12-12T09:33:20Z |
tests/src/org/aspectj/systemtest/ajc150/ataspectj/AtAjLTWTests.java
|
/*******************************************************************************
* Copyright (c) 2005 Contributors.
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Eclipse Public License v1.0
* which accompanies this distribution and is available at
* http://eclipse.org/legal/epl-v10.html
*
* Contributors:
* Alexandre Vasseur initial implementation
*******************************************************************************/
package org.aspectj.systemtest.ajc150.ataspectj;
import java.io.File;
import java.io.FilenameFilter;
import junit.framework.Test;
import org.aspectj.testing.XMLBasedAjcTestCase;
import org.aspectj.util.FileUtil;
/**
* @author <a href="mailto:alex AT gnilux DOT com">Alexandre Vasseur</a>
*/
public class AtAjLTWTests extends XMLBasedAjcTestCase {
public static Test suite() {
return XMLBasedAjcTestCase.loadSuite(org.aspectj.systemtest.ajc150.ataspectj.AtAjLTWTests.class);
}
protected File getSpecFile() {
return new File("../tests/src/org/aspectj/systemtest/ajc150/ataspectj/ltw.xml");
}
public void testRunThemAllWithJavacCompiledAndLTW() {
runTest("RunThemAllWithJavacCompiledAndLTW");
}
public void testAjcLTWPerClauseTest_XnoWeave() {
runTest("AjcLTW PerClauseTest -XnoWeave");
}
public void testAjcLTWPerClauseTest_Xreweavable() {
runTest("AjcLTW PerClauseTest -Xreweavable");
}
public void testJavaCAjcLTWPerClauseTest() {
runTest("JavaCAjcLTW PerClauseTest");
}
public void testAjcLTWAroundInlineMungerTest_XnoWeave() {
runTest("AjcLTW AroundInlineMungerTest -XnoWeave");
}
public void testAjcLTWAroundInlineMungerTest_Xreweavable() {
runTest("AjcLTW AroundInlineMungerTest");
}
public void testAjcLTWAroundInlineMungerTest() {
runTest("AjcLTW AroundInlineMungerTest");
}
public void testAjcLTWAroundInlineMungerTest_XnoInline_Xreweavable() {
runTest("AjcLTW AroundInlineMungerTest -XnoInline -Xreweavable");
}
public void testAjcLTWAroundInlineMungerTest2() {
runTest("AjcLTW AroundInlineMungerTest2");
}
public void testLTWDumpNone() {
runTest("LTW DumpTest none");
File f = new File("_ajdump/ataspectj/DumpTest.class");
assertFalse(f.exists());
f = new File("_ajdump/_before/ataspectj/DumpTestTheDump.class");
assertFalse(f.exists());
f = new File("_ajdump/ataspectj/DumpTestTheDump.class");
assertFalse(f.exists());
}
public void testLTWDump() {
runTest("LTW DumpTest");
File f = new File("_ajdump/ataspectj/DumpTest.class");
assertFalse(f.exists());
f = new File("_ajdump/_before/ataspectj/DumpTestTheDump.class");
assertFalse(f.exists());
f = new File("_ajdump/ataspectj/DumpTestTheDump.class");
assertTrue(f.exists());
// tidy up...
f = new File("_ajdump");
FileUtil.deleteContents(f);
f.delete();
}
public void testLTWDumpBeforeAndAfter() {
runTest("LTW DumpTest before and after");
File f = new File("_ajdump/_before/ataspectj/Test$$EnhancerByCGLIB$$12345.class");
assertTrue(f.exists());
f = new File("_ajdump/ataspectj/Test$$EnhancerByCGLIB$$12345.class");
assertTrue(f.exists());
// tidy up...
f = new File("_ajdump");
FileUtil.deleteContents(f);
f.delete();
}
public void testLTWDumpClosure() {
runTest("LTW DumpTest closure");
File f = new File("_ajdump/ataspectj/DumpTestTheDump$AjcClosure1.class");
assertTrue("Missing dump file " + f.getAbsolutePath(),f.exists());
// tidy up...
f = new File("_ajdump");
FileUtil.deleteContents(f);
f.delete();
}
public void testLTWDumpProxy() {
runTest("LTW DumpTest proxy");
// The working directory is different because this test must be forked
File dir = new File("../tests/java5/ataspectj");
File f = new File(dir,"_ajdump/_before");
System.out.println("AtAjLTWTests.testLTWDumpProxy() f=" + f.getAbsolutePath());
CountingFilenameFilter cff = new CountingFilenameFilter();
f.listFiles(cff);
assertEquals("Expected dump file in " + f.getAbsolutePath(),1,cff.getCount());
f = new File(dir,"_ajdump");
System.out.println("AtAjLTWTests.testLTWDumpProxy() f=" + f.getAbsolutePath());
cff = new CountingFilenameFilter();
f.listFiles(cff);
assertEquals(1,cff.getCount());
// tidy up...
f = new File(dir,"_ajdump");
FileUtil.deleteContents(f);
f.delete();
}
public void testAjcAspect1LTWAspect2_Xreweavable() {
runTest("Ajc Aspect1 LTW Aspect2 -Xreweavable");
}
public void testLTWLogSilent() {
runTest("LTW Log silent");
}
public void testLTWLogVerbose() {
runTest("LTW Log verbose");
}
public void testLTWLogVerboseAndShow() {
runTest("LTW Log verbose and showWeaveInfo");
}
public void testLTWLogMessageHandlerClass() {
runTest("LTW Log messageHandlerClass");
}
public void testLTWUnweavable() {
// actually test that we do LTW proxy and jit classes
runTest("LTW Unweavable");
}
public void testLTWDecp() {
runTest("LTW Decp");
}
public void testLTWDecp2() {
runTest("LTW Decp2");
}
public void testCompileTimeAspectsDeclaredToLTWWeaver() {
runTest("Compile time aspects declared to ltw weaver");
}
public void testConcreteAtAspect() {
runTest("Concrete@Aspect");
}
public void testConcreteAspect() {
runTest("ConcreteAspect");
}
public void testConcretePrecedenceAspect() {
runTest("ConcretePrecedenceAspect");
}
public void testAspectOfWhenAspectNotInInclude() {
runTest("AspectOfWhenAspectNotInInclude");
}
public void testAppContainer() {
runTest("AppContainer");
}
private static class CountingFilenameFilter implements FilenameFilter {
private int count;
public boolean accept(File dir, String name) {
if (name.endsWith(".class")) count++;
return false;
}
public int getCount() {
return count;
}
}
}
|
120,351 |
Bug 120351 cflowbelow issue when binding, in @AJ
| null |
resolved fixed
|
979124d
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2005-12-12T10:48:46Z | 2005-12-12T09:33:20Z |
weaver/src/org/aspectj/weaver/bcel/BcelAdvice.java
|
/* *******************************************************************
* Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC).
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* PARC initial implementation
* Alexandre Vasseur support for @AJ aspects
* ******************************************************************/
package org.aspectj.weaver.bcel;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Map;
import org.aspectj.apache.bcel.generic.InstructionConstants;
import org.aspectj.apache.bcel.generic.InstructionFactory;
import org.aspectj.apache.bcel.generic.InstructionHandle;
import org.aspectj.apache.bcel.generic.InstructionList;
import org.aspectj.bridge.ISourceLocation;
import org.aspectj.bridge.Message;
import org.aspectj.weaver.Advice;
import org.aspectj.weaver.AdviceKind;
import org.aspectj.weaver.AjAttribute;
import org.aspectj.weaver.BCException;
import org.aspectj.weaver.ISourceContext;
import org.aspectj.weaver.Member;
import org.aspectj.weaver.ResolvedMember;
import org.aspectj.weaver.ResolvedType;
import org.aspectj.weaver.Shadow;
import org.aspectj.weaver.ShadowMunger;
import org.aspectj.weaver.UnresolvedType;
import org.aspectj.weaver.WeaverMessages;
import org.aspectj.weaver.World;
import org.aspectj.weaver.ast.Literal;
import org.aspectj.weaver.ast.Test;
import org.aspectj.weaver.patterns.ExactTypePattern;
import org.aspectj.weaver.patterns.ExposedState;
import org.aspectj.weaver.patterns.PerClause;
import org.aspectj.weaver.patterns.Pointcut;
/**
* Advice implemented for bcel.
*
* @author Erik Hilsdale
* @author Jim Hugunin
*/
public class BcelAdvice extends Advice {
private Test pointcutTest;
private ExposedState exposedState;
private boolean hasMatchedAtLeastOnce = false;
public BcelAdvice(
AjAttribute.AdviceAttribute attribute,
Pointcut pointcut,
Member signature,
ResolvedType concreteAspect)
{
super(attribute, pointcut, signature);
this.concreteAspect = concreteAspect;
}
// !!! must only be used for testing
public BcelAdvice(AdviceKind kind, Pointcut pointcut, Member signature,
int extraArgumentFlags,
int start, int end, ISourceContext sourceContext, ResolvedType concreteAspect)
{
this(new AjAttribute.AdviceAttribute(kind, pointcut, extraArgumentFlags, start, end, sourceContext),
pointcut, signature, concreteAspect);
thrownExceptions = Collections.EMPTY_LIST; //!!! interaction with unit tests
}
// ---- implementations of ShadowMunger's methods
public ShadowMunger concretize(ResolvedType fromType, World world, PerClause clause) {
suppressLintWarnings(world);
ShadowMunger ret = super.concretize(fromType, world, clause);
clearLintSuppressions(world);
return ret;
}
public ShadowMunger parameterizeWith(ResolvedType declaringType,Map typeVariableMap) {
Pointcut pc = getPointcut().parameterizeWith(typeVariableMap);
BcelAdvice ret = null;
Member adviceSignature = signature;
// allows for around advice where the return value is a type variable (see pr115250)
if (signature instanceof ResolvedMember && signature.getDeclaringType().isGenericType()) {
adviceSignature = ((ResolvedMember)signature).parameterizedWith(declaringType.getTypeParameters(),declaringType,declaringType.isParameterizedType());
}
ret = new BcelAdvice(this.attribute,pc,adviceSignature,this.concreteAspect);
return ret;
}
public boolean match(Shadow shadow, World world) {
suppressLintWarnings(world);
boolean ret = super.match(shadow, world);
clearLintSuppressions(world);
return ret;
}
public void specializeOn(Shadow shadow) {
if (getKind() == AdviceKind.Around) {
((BcelShadow)shadow).initializeForAroundClosure();
}
//XXX this case is just here for supporting lazy test code
if (getKind() == null) {
exposedState = new ExposedState(0);
return;
}
if (getKind().isPerEntry()) {
exposedState = new ExposedState(0);
} else if (getKind().isCflow()) {
exposedState = new ExposedState(nFreeVars);
} else if (getSignature() != null) {
exposedState = new ExposedState(getSignature());
} else {
exposedState = new ExposedState(0);
return; //XXX this case is just here for supporting lazy test code
}
World world = shadow.getIWorld();
suppressLintWarnings(world);
pointcutTest = getPointcut().findResidue(shadow, exposedState);
clearLintSuppressions(world);
// these initializations won't be performed by findResidue, but need to be
// so that the joinpoint is primed for weaving
if (getKind() == AdviceKind.PerThisEntry) {
shadow.getThisVar();
} else if (getKind() == AdviceKind.PerTargetEntry) {
shadow.getTargetVar();
}
// make sure thisJoinPoint parameters are initialized
if ((getExtraParameterFlags() & ThisJoinPointStaticPart) != 0) {
((BcelShadow)shadow).getThisJoinPointStaticPartVar();
((BcelShadow)shadow).getEnclosingClass().warnOnAddedStaticInitializer(shadow,getSourceLocation());
}
if ((getExtraParameterFlags() & ThisJoinPoint) != 0) {
boolean hasGuardTest = pointcutTest != Literal.TRUE && getKind() != AdviceKind.Around;
boolean isAround = getKind() == AdviceKind.Around;
((BcelShadow)shadow).requireThisJoinPoint(hasGuardTest,isAround);
((BcelShadow)shadow).getEnclosingClass().warnOnAddedStaticInitializer(shadow,getSourceLocation());
if (!hasGuardTest && world.getLint().multipleAdviceStoppingLazyTjp.isEnabled()) {
// collect up the problematic advice
((BcelShadow)shadow).addAdvicePreventingLazyTjp(this);
}
if (!isAround && !hasGuardTest && world.getLint().noGuardForLazyTjp.isEnabled()) {
// can't build tjp lazily, no suitable test...
world.getLint().noGuardForLazyTjp.signal(
new String[] {shadow.toString()},
getSourceLocation(),
new ISourceLocation[] { ((BcelShadow)shadow).getSourceLocation() }
);
}
}
if ((getExtraParameterFlags() & ThisEnclosingJoinPointStaticPart) != 0) {
((BcelShadow)shadow).getThisEnclosingJoinPointStaticPartVar();
((BcelShadow)shadow).getEnclosingClass().warnOnAddedStaticInitializer(shadow,getSourceLocation());
}
}
private boolean canInline(Shadow s) {
if (attribute.isProceedInInners()) return false;
//XXX this guard seems to only be needed for bad test cases
if (concreteAspect == null || concreteAspect.isMissing()) return false;
if (concreteAspect.getWorld().isXnoInline()) return false;
//System.err.println("isWoven? " + ((BcelObjectType)concreteAspect).getLazyClassGen().getWeaverState());
return BcelWorld.getBcelObjectType(concreteAspect).getLazyClassGen().isWoven();
}
public void implementOn(Shadow s) {
hasMatchedAtLeastOnce=true;
BcelShadow shadow = (BcelShadow) s;
//FIXME AV - see #75442, this logic is not enough so for now comment it out until we fix the bug
// // callback for perObject AJC MightHaveAspect postMunge (#75442)
// if (getConcreteAspect() != null
// && getConcreteAspect().getPerClause() != null
// && PerClause.PEROBJECT.equals(getConcreteAspect().getPerClause().getKind())) {
// final PerObject clause;
// if (getConcreteAspect().getPerClause() instanceof PerFromSuper) {
// clause = (PerObject)((PerFromSuper) getConcreteAspect().getPerClause()).lookupConcretePerClause(getConcreteAspect());
// } else {
// clause = (PerObject) getConcreteAspect().getPerClause();
// }
// if (clause.isThis()) {
// PerObjectInterfaceTypeMunger.registerAsAdvisedBy(s.getThisVar().getType(), getConcreteAspect());
// } else {
// PerObjectInterfaceTypeMunger.registerAsAdvisedBy(s.getTargetVar().getType(), getConcreteAspect());
// }
// }
if (getKind() == AdviceKind.Before) {
shadow.weaveBefore(this);
} else if (getKind() == AdviceKind.AfterReturning) {
shadow.weaveAfterReturning(this);
} else if (getKind() == AdviceKind.AfterThrowing) {
UnresolvedType catchType =
hasExtraParameter()
? getExtraParameterType()
: UnresolvedType.THROWABLE;
shadow.weaveAfterThrowing(this, catchType);
} else if (getKind() == AdviceKind.After) {
shadow.weaveAfter(this);
} else if (getKind() == AdviceKind.Around) {
// Note: under regular LTW the aspect is usually loaded after the first use of any class affecteted by it
// This means that as long as the aspect has not been thru the LTW, it's woven state is unknown
// and thus canInline(s) will return false.
// To force inlining (test), ones can do Class aspect = FQNAspect.class in the clinit of the target class
// FIXME AV : for AJC compiled @AJ aspect (or any code style aspect), the woven state can never be known
// if the aspect belongs to a parent classloader. In that case the aspect will never be inlined.
// It might be dangerous to change that especially for @AJ aspect non compiled with AJC since if those
// are not weaved (f.e. use of some limiteed LTW etc) then they cannot be prepared for inlining.
// One solution would be to flag @AJ aspect with an annotation as "prepared" and query that one.
if (!canInline(s)) {
shadow.weaveAroundClosure(this, hasDynamicTests());
} else {
shadow.weaveAroundInline(this, hasDynamicTests());
}
} else if (getKind() == AdviceKind.InterInitializer) {
shadow.weaveAfterReturning(this);
} else if (getKind().isCflow()) {
shadow.weaveCflowEntry(this, getSignature());
} else if (getKind() == AdviceKind.PerThisEntry) {
shadow.weavePerObjectEntry(this, (BcelVar)shadow.getThisVar());
} else if (getKind() == AdviceKind.PerTargetEntry) {
shadow.weavePerObjectEntry(this, (BcelVar)shadow.getTargetVar());
} else if (getKind() == AdviceKind.Softener) {
shadow.weaveSoftener(this, ((ExactTypePattern)exceptionType).getType());
} else if (getKind() == AdviceKind.PerTypeWithinEntry) {
// PTWIMPL Entry to ptw is the static initialization of a type that matched the ptw type pattern
shadow.weavePerTypeWithinAspectInitialization(this,shadow.getEnclosingType());
} else {
throw new BCException("unimplemented kind: " + getKind());
}
}
// ---- implementations
private Collection collectCheckedExceptions(UnresolvedType[] excs) {
if (excs == null || excs.length == 0) return Collections.EMPTY_LIST;
Collection ret = new ArrayList();
World world = concreteAspect.getWorld();
ResolvedType runtimeException = world.getCoreType(UnresolvedType.RUNTIME_EXCEPTION);
ResolvedType error = world.getCoreType(UnresolvedType.ERROR);
for (int i=0, len=excs.length; i < len; i++) {
ResolvedType t = world.resolve(excs[i],true);
if (t.isMissing()) {
world.getLint().cantFindType.signal(
WeaverMessages.format(WeaverMessages.CANT_FIND_TYPE_EXCEPTION_TYPE,excs[i].getName()),
getSourceLocation()
);
// IMessage msg = new Message(
// WeaverMessages.format(WeaverMessages.CANT_FIND_TYPE_EXCEPTION_TYPE,excs[i].getName()),
// "",IMessage.ERROR,getSourceLocation(),null,null);
// world.getMessageHandler().handleMessage(msg);
}
if (!(runtimeException.isAssignableFrom(t) || error.isAssignableFrom(t))) {
ret.add(t);
}
}
return ret;
}
private Collection thrownExceptions = null;
public Collection getThrownExceptions() {
if (thrownExceptions == null) {
//??? can we really lump in Around here, how does this interact with Throwable
if (concreteAspect != null && concreteAspect.getWorld() != null && // null tests for test harness
(getKind().isAfter() || getKind() == AdviceKind.Before || getKind() == AdviceKind.Around))
{
World world = concreteAspect.getWorld();
ResolvedMember m = world.resolve(signature);
if (m == null) {
thrownExceptions = Collections.EMPTY_LIST;
} else {
thrownExceptions = collectCheckedExceptions(m.getExceptions());
}
} else {
thrownExceptions = Collections.EMPTY_LIST;
}
}
return thrownExceptions;
}
/**
* The munger must not check for the advice exceptions to be declared by the shadow in the case
* of @AJ aspects so that around can throws Throwable
*
* @return
*/
public boolean mustCheckExceptions() {
if (getConcreteAspect() == null) {
return true;
}
return !getConcreteAspect().isAnnotationStyleAspect();
}
// only call me after prepare has been called
public boolean hasDynamicTests() {
// if (hasExtraParameter() && getKind() == AdviceKind.AfterReturning) {
// UnresolvedType extraParameterType = getExtraParameterType();
// if (! extraParameterType.equals(UnresolvedType.OBJECT)
// && ! extraParameterType.isPrimitive())
// return true;
// }
return pointcutTest != null &&
!(pointcutTest == Literal.TRUE);// || pointcutTest == Literal.NO_TEST);
}
/**
* get the instruction list for the really simple version of this advice.
* Is broken apart
* for other advice, but if you want it in one block, this is the method to call.
*
* @param s The shadow around which these instructions will eventually live.
* @param extraArgVar The var that will hold the return value or thrown exception
* for afterX advice
* @param ifNoAdvice The instructionHandle to jump to if the dynamic
* tests for this munger fails.
*/
InstructionList getAdviceInstructions(
BcelShadow s,
BcelVar extraArgVar,
InstructionHandle ifNoAdvice)
{
BcelShadow shadow = (BcelShadow) s;
InstructionFactory fact = shadow.getFactory();
BcelWorld world = shadow.getWorld();
InstructionList il = new InstructionList();
// we test to see if we have the right kind of thing...
// after throwing does this just by the exception mechanism.
if (hasExtraParameter() && getKind() == AdviceKind.AfterReturning) {
UnresolvedType extraParameterType = getExtraParameterType();
if (! extraParameterType.equals(UnresolvedType.OBJECT)
&& ! extraParameterType.isPrimitiveType()) {
il.append(
BcelRenderer.renderTest(
fact,
world,
Test.makeInstanceof(
extraArgVar, getExtraParameterType().resolve(world)),
null,
ifNoAdvice,
null));
}
}
il.append(getAdviceArgSetup(shadow, extraArgVar, null));
il.append(getNonTestAdviceInstructions(shadow));
InstructionHandle ifYesAdvice = il.getStart();
il.insert(getTestInstructions(shadow, ifYesAdvice, ifNoAdvice, ifYesAdvice));
return il;
}
public InstructionList getAdviceArgSetup(
BcelShadow shadow,
BcelVar extraVar,
InstructionList closureInstantiation)
{
InstructionFactory fact = shadow.getFactory();
BcelWorld world = shadow.getWorld();
InstructionList il = new InstructionList();
// if (targetAspectField != null) {
// il.append(fact.createFieldAccess(
// targetAspectField.getDeclaringType().getName(),
// targetAspectField.getName(),
// BcelWorld.makeBcelType(targetAspectField.getType()),
// Constants.GETSTATIC));
// }
//
//System.err.println("BcelAdvice: " + exposedState);
if (exposedState.getAspectInstance() != null) {
il.append(BcelRenderer.renderExpr(fact, world, exposedState.getAspectInstance()));
}
final boolean isAnnotationStyleAspect = getConcreteAspect()!=null && getConcreteAspect().isAnnotationStyleAspect();
boolean previousIsClosure = false;
for (int i = 0, len = exposedState.size(); i < len; i++) {
if (exposedState.isErroneousVar(i)) continue; // Erroneous vars have already had error msgs reported!
BcelVar v = (BcelVar) exposedState.get(i);
if (v == null) {
// if not @AJ aspect, go on with the regular binding handling
if (!isAnnotationStyleAspect) {
;
} else {
// ATAJ: for @AJ aspects, handle implicit binding of xxJoinPoint
//if (getKind() == AdviceKind.Around) {
// previousIsClosure = true;
// il.append(closureInstantiation);
if ("Lorg/aspectj/lang/ProceedingJoinPoint;".equals(getSignature().getParameterTypes()[i].getSignature())) {
//make sure we are in an around, since we deal with the closure, not the arg here
if (getKind() != AdviceKind.Around) {
previousIsClosure = false;
getConcreteAspect().getWorld().getMessageHandler().handleMessage(
new Message(
"use of ProceedingJoinPoint is allowed only on around advice ("
+ "arg " + i + " in " + toString() + ")",
this.getSourceLocation(),
true
)
);
// try to avoid verify error and pass in null
il.append(InstructionConstants.ACONST_NULL);
} else {
if (previousIsClosure) {
il.append(InstructionConstants.DUP);
} else {
previousIsClosure = true;
il.append(closureInstantiation.copy());
}
}
} else if ("Lorg/aspectj/lang/JoinPoint$StaticPart;".equals(getSignature().getParameterTypes()[i].getSignature())) {
previousIsClosure = false;
if ((getExtraParameterFlags() & ThisJoinPointStaticPart) != 0) {
shadow.getThisJoinPointStaticPartBcelVar().appendLoad(il, fact);
}
} else if ("Lorg/aspectj/lang/JoinPoint;".equals(getSignature().getParameterTypes()[i].getSignature())) {
previousIsClosure = false;
if ((getExtraParameterFlags() & ThisJoinPoint) != 0) {
il.append(shadow.loadThisJoinPoint());
}
} else if ("Lorg/aspectj/lang/JoinPoint$EnclosingStaticPart;".equals(getSignature().getParameterTypes()[i].getSignature())) {
previousIsClosure = false;
if ((getExtraParameterFlags() & ThisEnclosingJoinPointStaticPart) != 0) {
shadow.getThisEnclosingJoinPointStaticPartBcelVar().appendLoad(il, fact);
}
} else if (hasExtraParameter()) {
previousIsClosure = false;
extraVar.appendLoadAndConvert(
il,
fact,
getExtraParameterType().resolve(world));
} else {
previousIsClosure = false;
getConcreteAspect().getWorld().getMessageHandler().handleMessage(
new Message(
"use of ProceedingJoinPoint is allowed only on around advice ("
+ "arg " + i + " in " + toString() + ")",
this.getSourceLocation(),
true
)
);
// try to avoid verify error and pass in null
il.append(InstructionConstants.ACONST_NULL);
}
}
} else {
UnresolvedType desiredTy = getBindingParameterTypes()[i];
v.appendLoadAndConvert(il, fact, desiredTy.resolve(world));
}
}
// ATAJ: for code style aspect, handles the extraFlag as usual ie not
// in the middle of the formal bindings but at the end, in a rock solid ordering
if (!isAnnotationStyleAspect) {
if (getKind() == AdviceKind.Around) {
il.append(closureInstantiation);
} else if (hasExtraParameter()) {
extraVar.appendLoadAndConvert(
il,
fact,
getExtraParameterType().resolve(world));
}
// handle thisJoinPoint parameters
// these need to be in that same order as parameters in
// org.aspectj.ajdt.internal.compiler.ast.AdviceDeclaration
if ((getExtraParameterFlags() & ThisJoinPointStaticPart) != 0) {
shadow.getThisJoinPointStaticPartBcelVar().appendLoad(il, fact);
}
if ((getExtraParameterFlags() & ThisJoinPoint) != 0) {
il.append(shadow.loadThisJoinPoint());
}
if ((getExtraParameterFlags() & ThisEnclosingJoinPointStaticPart) != 0) {
shadow.getThisEnclosingJoinPointStaticPartBcelVar().appendLoad(il, fact);
}
}
return il;
}
public InstructionList getNonTestAdviceInstructions(BcelShadow shadow) {
return new InstructionList(
Utility.createInvoke(shadow.getFactory(), shadow.getWorld(), getOriginalSignature()));
}
public Member getOriginalSignature() {
Member sig = getSignature();
if (sig instanceof ResolvedMember) {
ResolvedMember rsig = (ResolvedMember)sig;
if (rsig.hasBackingGenericMember()) return rsig.getBackingGenericMember();
}
return sig;
}
public InstructionList getTestInstructions(
BcelShadow shadow,
InstructionHandle sk,
InstructionHandle fk,
InstructionHandle next)
{
//System.err.println("test: " + pointcutTest);
return BcelRenderer.renderTest(
shadow.getFactory(),
shadow.getWorld(),
pointcutTest,
sk,
fk,
next);
}
public int compareTo(Object other) {
if (!(other instanceof BcelAdvice)) return 0;
BcelAdvice o = (BcelAdvice)other;
//System.err.println("compareTo: " + this + ", " + o);
if (kind.getPrecedence() != o.kind.getPrecedence()) {
if (kind.getPrecedence() > o.kind.getPrecedence()) return +1;
else return -1;
}
if (kind.isCflow()) {
// System.err.println("sort: " + this + " innerCflowEntries " + innerCflowEntries);
// System.err.println(" " + o + " innerCflowEntries " + o.innerCflowEntries);
boolean isBelow = (kind == AdviceKind.CflowBelowEntry);
if (this.innerCflowEntries.contains(o)) return isBelow ? +1 : -1;
else if (o.innerCflowEntries.contains(this)) return isBelow ? -1 : +1;
else return 0;
}
if (kind.isPerEntry() || kind == AdviceKind.Softener) {
return 0;
}
//System.out.println("compare: " + this + " with " + other);
World world = concreteAspect.getWorld();
int ret =
concreteAspect.getWorld().compareByPrecedence(
concreteAspect,
o.concreteAspect);
if (ret != 0) return ret;
ResolvedType declaringAspect = getDeclaringAspect().resolve(world);
ResolvedType o_declaringAspect = o.getDeclaringAspect().resolve(world);
if (declaringAspect == o_declaringAspect) {
if (kind.isAfter() || o.kind.isAfter()) {
return this.getStart() < o.getStart() ? -1: +1;
} else {
return this.getStart()< o.getStart() ? +1: -1;
}
} else if (declaringAspect.isAssignableFrom(o_declaringAspect)) {
return -1;
} else if (o_declaringAspect.isAssignableFrom(declaringAspect)) {
return +1;
} else {
return 0;
}
}
public BcelVar[] getExposedStateAsBcelVars() {
// ATAJ aspect
// the closure instantiation has the same mapping as the extracted method from wich it is called
if (getConcreteAspect()!= null && getConcreteAspect().isAnnotationStyleAspect()) {
return BcelVar.NONE;
}
//System.out.println("vars: " + Arrays.asList(exposedState.vars));
if (exposedState == null) return BcelVar.NONE;
int len = exposedState.vars.length;
BcelVar[] ret = new BcelVar[len];
for (int i=0; i < len; i++) {
ret[i] = (BcelVar)exposedState.vars[i];
}
return ret; //(BcelVar[]) exposedState.vars;
}
public boolean hasMatchedSomething() {
return hasMatchedAtLeastOnce;
}
protected void suppressLintWarnings(World inWorld) {
if (suppressedLintKinds == null) {
if (signature instanceof BcelMethod) {
this.suppressedLintKinds = Utility.getSuppressedWarnings(signature.getAnnotations(), inWorld.getLint());
} else {
this.suppressedLintKinds = Collections.EMPTY_LIST;
}
}
inWorld.getLint().suppressKinds(suppressedLintKinds);
}
protected void clearLintSuppressions(World inWorld) {
inWorld.getLint().clearSuppressions();
}
}
|
120,351 |
Bug 120351 cflowbelow issue when binding, in @AJ
| null |
resolved fixed
|
979124d
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2005-12-12T10:48:46Z | 2005-12-12T09:33:20Z |
weaver/src/org/aspectj/weaver/bcel/BcelShadow.java
|
/* *******************************************************************
* Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC).
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* PARC initial implementation
* Alexandre Vasseur support for @AJ aspects
* ******************************************************************/
package org.aspectj.weaver.bcel;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.aspectj.apache.bcel.Constants;
import org.aspectj.apache.bcel.classfile.Field;
import org.aspectj.apache.bcel.generic.ACONST_NULL;
import org.aspectj.apache.bcel.generic.ALOAD;
import org.aspectj.apache.bcel.generic.ANEWARRAY;
import org.aspectj.apache.bcel.generic.ArrayType;
import org.aspectj.apache.bcel.generic.BranchInstruction;
import org.aspectj.apache.bcel.generic.ConstantPoolGen;
import org.aspectj.apache.bcel.generic.DUP;
import org.aspectj.apache.bcel.generic.DUP_X1;
import org.aspectj.apache.bcel.generic.FieldInstruction;
import org.aspectj.apache.bcel.generic.INVOKEINTERFACE;
import org.aspectj.apache.bcel.generic.INVOKESPECIAL;
import org.aspectj.apache.bcel.generic.INVOKESTATIC;
import org.aspectj.apache.bcel.generic.Instruction;
import org.aspectj.apache.bcel.generic.InstructionConstants;
import org.aspectj.apache.bcel.generic.InstructionFactory;
import org.aspectj.apache.bcel.generic.InstructionHandle;
import org.aspectj.apache.bcel.generic.InstructionList;
import org.aspectj.apache.bcel.generic.InstructionTargeter;
import org.aspectj.apache.bcel.generic.InvokeInstruction;
import org.aspectj.apache.bcel.generic.LoadInstruction;
import org.aspectj.apache.bcel.generic.MULTIANEWARRAY;
import org.aspectj.apache.bcel.generic.NEW;
import org.aspectj.apache.bcel.generic.ObjectType;
import org.aspectj.apache.bcel.generic.PUSH;
import org.aspectj.apache.bcel.generic.ReturnInstruction;
import org.aspectj.apache.bcel.generic.SWAP;
import org.aspectj.apache.bcel.generic.StoreInstruction;
import org.aspectj.apache.bcel.generic.TargetLostException;
import org.aspectj.apache.bcel.generic.Type;
import org.aspectj.bridge.ISourceLocation;
import org.aspectj.weaver.Advice;
import org.aspectj.weaver.AdviceKind;
import org.aspectj.weaver.AjcMemberMaker;
import org.aspectj.weaver.BCException;
import org.aspectj.weaver.IntMap;
import org.aspectj.weaver.Member;
import org.aspectj.weaver.MemberImpl;
import org.aspectj.weaver.NameMangler;
import org.aspectj.weaver.NewConstructorTypeMunger;
import org.aspectj.weaver.NewFieldTypeMunger;
import org.aspectj.weaver.NewMethodTypeMunger;
import org.aspectj.weaver.ResolvedMember;
import org.aspectj.weaver.ResolvedMemberImpl;
import org.aspectj.weaver.ResolvedType;
import org.aspectj.weaver.Shadow;
import org.aspectj.weaver.ShadowMunger;
import org.aspectj.weaver.UnresolvedType;
import org.aspectj.weaver.WeaverMessages;
import org.aspectj.weaver.World;
import org.aspectj.weaver.ast.Var;
/*
* Some fun implementation stuff:
*
* * expressionKind advice is non-execution advice
* * may have a target.
* * if the body is extracted, it will be extracted into
* a static method. The first argument to the static
* method is the target
* * advice may expose a this object, but that's the advice's
* consideration, not ours. This object will NOT be cached in another
* local, but will always come from frame zero.
*
* * non-expressionKind advice is execution advice
* * may have a this.
* * target is same as this, and is exposed that way to advice
* (i.e., target will not be cached, will always come from frame zero)
* * if the body is extracted, it will be extracted into a method
* with same static/dynamic modifier as enclosing method. If non-static,
* target of callback call will be this.
*
* * because of these two facts, the setup of the actual arguments (including
* possible target) callback method is the same for both kinds of advice:
* push the targetVar, if it exists (it will not exist for advice on static
* things), then push all the argVars.
*
* Protected things:
*
* * the above is sufficient for non-expressionKind advice for protected things,
* since the target will always be this.
*
* * For expressionKind things, we have to modify the signature of the callback
* method slightly. For non-static expressionKind things, we modify
* the first argument of the callback method NOT to be the type specified
* by the method/field signature (the owner), but rather we type it to
* the currentlyEnclosing type. We are guaranteed this will be fine,
* since the verifier verifies that the target is a subtype of the currently
* enclosingType.
*
* Worries:
*
* * ConstructorCalls will be weirder than all of these, since they
* supposedly don't have a target (according to AspectJ), but they clearly
* do have a target of sorts, just one that needs to be pushed on the stack,
* dupped, and not touched otherwise until the constructor runs.
*
* @author Jim Hugunin
* @author Erik Hilsdale
*
*/
public class BcelShadow extends Shadow {
private ShadowRange range;
private final BcelWorld world;
private final LazyMethodGen enclosingMethod;
// private boolean fallsThrough; //XXX not used anymore
// SECRETAPI - for testing, this will tell us if the optimization succeeded *on the last shadow processed*
public static boolean appliedLazyTjpOptimization;
// Some instructions have a target type that will vary
// from the signature (pr109728) (1.4 declaring type issue)
private String actualInstructionTargetType;
// ---- initialization
/**
* This generates an unassociated shadow, rooted in a particular method but not rooted
* to any particular point in the code. It should be given to a rooted ShadowRange
* in the {@link ShadowRange#associateWithShadow(BcelShadow)} method.
*/
public BcelShadow(
BcelWorld world,
Kind kind,
Member signature,
LazyMethodGen enclosingMethod,
BcelShadow enclosingShadow)
{
super(kind, signature, enclosingShadow);
this.world = world;
this.enclosingMethod = enclosingMethod;
// fallsThrough = kind.argsOnStack();
}
// ---- copies all state, including Shadow's mungers...
public BcelShadow copyInto(LazyMethodGen recipient, BcelShadow enclosing) {
BcelShadow s = new BcelShadow(world, getKind(), getSignature(), recipient, enclosing);
List src = mungers;
List dest = s.mungers;
for (Iterator i = src.iterator(); i.hasNext(); ) {
dest.add(i.next());
}
return s;
}
// ---- overridden behaviour
public World getIWorld() {
return world;
}
private void deleteNewAndDup() {
final ConstantPoolGen cpg = getEnclosingClass().getConstantPoolGen();
int depth = 1;
InstructionHandle ih = range.getStart();
while (true) {
Instruction inst = ih.getInstruction();
if (inst instanceof INVOKESPECIAL
&& ((INVOKESPECIAL) inst).getName(cpg).equals("<init>")) {
depth++;
} else if (inst instanceof NEW) {
depth--;
if (depth == 0) break;
}
ih = ih.getPrev();
}
// now IH points to the NEW. We're followed by the DUP, and that is followed
// by the actual instruction we care about.
InstructionHandle newHandle = ih;
InstructionHandle endHandle = newHandle.getNext();
InstructionHandle nextHandle;
if (endHandle.getInstruction() instanceof DUP) {
nextHandle = endHandle.getNext();
retargetFrom(newHandle, nextHandle);
retargetFrom(endHandle, nextHandle);
} else if (endHandle.getInstruction() instanceof DUP_X1) {
InstructionHandle dupHandle = endHandle;
endHandle = endHandle.getNext();
nextHandle = endHandle.getNext();
if (endHandle.getInstruction() instanceof SWAP) {}
else {
// XXX see next XXX comment
throw new RuntimeException("Unhandled kind of new " + endHandle);
}
// Now make any jumps to the 'new', the 'dup' or the 'end' now target the nextHandle
retargetFrom(newHandle, nextHandle);
retargetFrom(dupHandle, nextHandle);
retargetFrom(endHandle, nextHandle);
} else {
endHandle = newHandle;
nextHandle = endHandle.getNext();
retargetFrom(newHandle, nextHandle);
// add a POP here... we found a NEW w/o a dup or anything else, so
// we must be in statement context.
getRange().insert(InstructionConstants.POP, Range.OutsideAfter);
}
// assert (dupHandle.getInstruction() instanceof DUP);
try {
range.getBody().delete(newHandle, endHandle);
} catch (TargetLostException e) {
throw new BCException("shouldn't happen");
}
}
private void retargetFrom(InstructionHandle old, InstructionHandle fresh) {
InstructionTargeter[] sources = old.getTargeters();
if (sources != null) {
for (int i = sources.length - 1; i >= 0; i--) {
if (sources[i] instanceof ExceptionRange) {
ExceptionRange it = (ExceptionRange)sources[i];
System.err.println("...");
it.updateTarget(old,fresh,it.getBody());
} else {
sources[i].updateTarget(old, fresh);
}
}
}
}
// records advice that is stopping us doing the lazyTjp optimization
private List badAdvice = null;
public void addAdvicePreventingLazyTjp(BcelAdvice advice) {
if (badAdvice == null) badAdvice = new ArrayList();
badAdvice.add(advice);
}
protected void prepareForMungers() {
// if we're a constructor call, we need to remove the new:dup or the new:dup_x1:swap,
// and store all our
// arguments on the frame.
// ??? This is a bit of a hack (for the Java langauge). We do this because
// we sometime add code "outsideBefore" when dealing with weaving join points. We only
// do this for exposing state that is on the stack. It turns out to just work for
// everything except for constructor calls and exception handlers. If we were to clean
// this up, every ShadowRange would have three instructionHandle points, the start of
// the arg-setup code, the start of the running code, and the end of the running code.
if (getKind() == ConstructorCall) {
deleteNewAndDup();
initializeArgVars();
} else if (getKind() == PreInitialization) { // pr74952
ShadowRange range = getRange();
range.insert(InstructionConstants.NOP,Range.InsideAfter);
} else if (getKind() == ExceptionHandler) {
ShadowRange range = getRange();
InstructionList body = range.getBody();
InstructionHandle start = range.getStart();
// Create a store instruction to put the value from the top of the
// stack into a local variable slot. This is a trimmed version of
// what is in initializeArgVars() (since there is only one argument
// at a handler jp and only before advice is supported) (pr46298)
argVars = new BcelVar[1];
//int positionOffset = (hasTarget() ? 1 : 0) + ((hasThis() && !getKind().isTargetSameAsThis()) ? 1 : 0);
UnresolvedType tx = getArgType(0);
argVars[0] = genTempVar(tx, "ajc$arg0");
InstructionHandle insertedInstruction =
range.insert(argVars[0].createStore(getFactory()), Range.OutsideBefore);
// Now the exception range starts just after our new instruction.
// The next bit of code changes the exception range to point at
// the store instruction
InstructionTargeter[] targeters = start.getTargeters();
for (int i = 0; i < targeters.length; i++) {
InstructionTargeter t = targeters[i];
if (t instanceof ExceptionRange) {
ExceptionRange er = (ExceptionRange) t;
er.updateTarget(start, insertedInstruction, body);
}
}
}
// now we ask each munger to request our state
isThisJoinPointLazy = true;//world.isXlazyTjp(); // lazy is default now
badAdvice = null;
for (Iterator iter = mungers.iterator(); iter.hasNext();) {
ShadowMunger munger = (ShadowMunger) iter.next();
munger.specializeOn(this);
}
initializeThisJoinPoint();
if (thisJoinPointVar!=null && !isThisJoinPointLazy && badAdvice!=null && badAdvice.size()>1) {
// something stopped us making it a lazy tjp
// can't build tjp lazily, no suitable test...
int valid = 0;
for (Iterator iter = badAdvice.iterator(); iter.hasNext();) {
BcelAdvice element = (BcelAdvice) iter.next();
ISourceLocation sLoc = element.getSourceLocation();
if (sLoc!=null && sLoc.getLine()>0) valid++;
}
if (valid!=0) {
ISourceLocation[] badLocs = new ISourceLocation[valid];
int i = 0;
for (Iterator iter = badAdvice.iterator(); iter.hasNext();) {
BcelAdvice element = (BcelAdvice) iter.next();
ISourceLocation sLoc = element.getSourceLocation();
if (sLoc!=null) badLocs[i++]=sLoc;
}
world.getLint().multipleAdviceStoppingLazyTjp.signal(
new String[] {this.toString()},
getSourceLocation(),badLocs
);
}
}
badAdvice=null;
// If we are an expression kind, we require our target/arguments on the stack
// before we do our actual thing. However, they may have been removed
// from the stack as the shadowMungers have requested state.
// if any of our shadowMungers requested either the arguments or target,
// the munger will have added code
// to pop the target/arguments into temporary variables, represented by
// targetVar and argVars. In such a case, we must make sure to re-push the
// values.
// If we are nonExpressionKind, we don't expect arguments on the stack
// so this is moot. If our argVars happen to be null, then we know that
// no ShadowMunger has squirrelled away our arguments, so they're still
// on the stack.
InstructionFactory fact = getFactory();
if (getKind().argsOnStack() && argVars != null) {
// Special case first (pr46298). If we are an exception handler and the instruction
// just after the shadow is a POP then we should remove the pop. The code
// above which generated the store instruction has already cleared the stack.
// We also don't generate any code for the arguments in this case as it would be
// an incorrect aload.
if (getKind() == ExceptionHandler
&& range.getEnd().getNext().getInstruction().equals(InstructionConstants.POP)) {
// easier than deleting it ...
range.getEnd().getNext().setInstruction(InstructionConstants.NOP);
} else {
range.insert(
BcelRenderer.renderExprs(fact, world, argVars),
Range.InsideBefore);
if (targetVar != null) {
range.insert(
BcelRenderer.renderExpr(fact, world, targetVar),
Range.InsideBefore);
}
if (getKind() == ConstructorCall) {
range.insert((Instruction) InstructionFactory.createDup(1), Range.InsideBefore);
range.insert(
fact.createNew(
(ObjectType) BcelWorld.makeBcelType(
getSignature().getDeclaringType())),
Range.InsideBefore);
}
}
}
}
// ---- getters
public ShadowRange getRange() {
return range;
}
public void setRange(ShadowRange range) {
this.range = range;
}
public int getSourceLine() {
// if the kind of join point for which we are a shadow represents
// a method or constructor execution, then the best source line is
// the one from the enclosingMethod declarationLineNumber if available.
Kind kind = getKind();
if ( (kind == MethodExecution) ||
(kind == ConstructorExecution) ||
(kind == AdviceExecution) ||
(kind == StaticInitialization) ||
(kind == PreInitialization) ||
(kind == Initialization)) {
if (getEnclosingMethod().hasDeclaredLineNumberInfo()) {
return getEnclosingMethod().getDeclarationLineNumber();
}
}
if (range == null) {
if (getEnclosingMethod().hasBody()) {
return Utility.getSourceLine(getEnclosingMethod().getBody().getStart());
} else {
return 0;
}
}
int ret = Utility.getSourceLine(range.getStart());
if (ret < 0) return 0;
return ret;
}
// overrides
public UnresolvedType getEnclosingType() {
return getEnclosingClass().getType();
}
public LazyClassGen getEnclosingClass() {
return enclosingMethod.getEnclosingClass();
}
public BcelWorld getWorld() {
return world;
}
// ---- factory methods
public static BcelShadow makeConstructorExecution(
BcelWorld world,
LazyMethodGen enclosingMethod,
InstructionHandle justBeforeStart)
{
final InstructionList body = enclosingMethod.getBody();
BcelShadow s =
new BcelShadow(
world,
ConstructorExecution,
world.makeJoinPointSignature(enclosingMethod),
enclosingMethod,
null);
ShadowRange r = new ShadowRange(body);
r.associateWithShadow(s);
r.associateWithTargets(
Range.genStart(body, justBeforeStart.getNext()),
Range.genEnd(body));
return s;
}
public static BcelShadow makeStaticInitialization(
BcelWorld world,
LazyMethodGen enclosingMethod)
{
InstructionList body = enclosingMethod.getBody();
// move the start past ajc$preClinit
InstructionHandle clinitStart = body.getStart();
if (clinitStart.getInstruction() instanceof InvokeInstruction) {
InvokeInstruction ii = (InvokeInstruction)clinitStart.getInstruction();
if (ii
.getName(enclosingMethod.getEnclosingClass().getConstantPoolGen())
.equals(NameMangler.AJC_PRE_CLINIT_NAME)) {
clinitStart = clinitStart.getNext();
}
}
InstructionHandle clinitEnd = body.getEnd();
//XXX should move the end before the postClinit, but the return is then tricky...
// if (clinitEnd.getInstruction() instanceof InvokeInstruction) {
// InvokeInstruction ii = (InvokeInstruction)clinitEnd.getInstruction();
// if (ii.getName(enclosingMethod.getEnclosingClass().getConstantPoolGen()).equals(NameMangler.AJC_POST_CLINIT_NAME)) {
// clinitEnd = clinitEnd.getPrev();
// }
// }
BcelShadow s =
new BcelShadow(
world,
StaticInitialization,
world.makeJoinPointSignature(enclosingMethod),
enclosingMethod,
null);
ShadowRange r = new ShadowRange(body);
r.associateWithShadow(s);
r.associateWithTargets(
Range.genStart(body, clinitStart),
Range.genEnd(body, clinitEnd));
return s;
}
/** Make the shadow for an exception handler. Currently makes an empty shadow that
* only allows before advice to be woven into it.
*/
public static BcelShadow makeExceptionHandler(
BcelWorld world,
ExceptionRange exceptionRange,
LazyMethodGen enclosingMethod,
InstructionHandle startOfHandler,
BcelShadow enclosingShadow)
{
InstructionList body = enclosingMethod.getBody();
UnresolvedType catchType = exceptionRange.getCatchType();
UnresolvedType inType = enclosingMethod.getEnclosingClass().getType();
ResolvedMemberImpl sig = MemberImpl.makeExceptionHandlerSignature(inType, catchType);
sig.parameterNames = new String[] {findHandlerParamName(startOfHandler)};
BcelShadow s =
new BcelShadow(
world,
ExceptionHandler,
sig,
enclosingMethod,
enclosingShadow);
ShadowRange r = new ShadowRange(body);
r.associateWithShadow(s);
InstructionHandle start = Range.genStart(body, startOfHandler);
InstructionHandle end = Range.genEnd(body, start);
r.associateWithTargets(start, end);
exceptionRange.updateTarget(startOfHandler, start, body);
return s;
}
private static String findHandlerParamName(InstructionHandle startOfHandler) {
if (startOfHandler.getInstruction() instanceof StoreInstruction &&
startOfHandler.getNext() != null)
{
int slot = ((StoreInstruction)startOfHandler.getInstruction()).getIndex();
//System.out.println("got store: " + startOfHandler.getInstruction() + ", " + index);
InstructionTargeter[] targeters = startOfHandler.getNext().getTargeters();
if (targeters!=null) {
for (int i=targeters.length-1; i >= 0; i--) {
if (targeters[i] instanceof LocalVariableTag) {
LocalVariableTag t = (LocalVariableTag)targeters[i];
if (t.getSlot() == slot) {
return t.getName();
}
//System.out.println("tag: " + targeters[i]);
}
}
}
}
return "<missing>";
}
/** create an init join point associated w/ an interface in the body of a constructor */
public static BcelShadow makeIfaceInitialization(
BcelWorld world,
LazyMethodGen constructor,
Member interfaceConstructorSignature)
{
// 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 makeMethodCall(
BcelWorld world,
LazyMethodGen enclosingMethod,
InstructionHandle callHandle,
BcelShadow enclosingShadow)
{
final InstructionList body = enclosingMethod.getBody();
BcelShadow s =
new BcelShadow(
world,
MethodCall,
world.makeJoinPointSignatureForMethodInvocation(
enclosingMethod.getEnclosingClass(),
(InvokeInstruction) callHandle.getInstruction()),
enclosingMethod,
enclosingShadow);
ShadowRange r = new ShadowRange(body);
r.associateWithShadow(s);
r.associateWithTargets(
Range.genStart(body, callHandle),
Range.genEnd(body, callHandle));
retargetAllBranches(callHandle, r.getStart());
return s;
}
public static BcelShadow makeShadowForMethodCall(
BcelWorld world,
LazyMethodGen enclosingMethod,
InstructionHandle callHandle,
BcelShadow enclosingShadow,
Kind kind,
ResolvedMember sig)
{
final InstructionList body = enclosingMethod.getBody();
BcelShadow s =
new BcelShadow(
world,
kind,
sig,
enclosingMethod,
enclosingShadow);
ShadowRange r = new ShadowRange(body);
r.associateWithShadow(s);
r.associateWithTargets(
Range.genStart(body, callHandle),
Range.genEnd(body, callHandle));
retargetAllBranches(callHandle, r.getStart());
return s;
}
public static BcelShadow makeFieldGet(
BcelWorld world,
ResolvedMember field,
LazyMethodGen enclosingMethod,
InstructionHandle getHandle,
BcelShadow enclosingShadow)
{
final InstructionList body = enclosingMethod.getBody();
BcelShadow s =
new BcelShadow(
world,
FieldGet,
field,
// BcelWorld.makeFieldSignature(
// enclosingMethod.getEnclosingClass(),
// (FieldInstruction) getHandle.getInstruction()),
enclosingMethod,
enclosingShadow);
ShadowRange r = new ShadowRange(body);
r.associateWithShadow(s);
r.associateWithTargets(
Range.genStart(body, getHandle),
Range.genEnd(body, getHandle));
retargetAllBranches(getHandle, r.getStart());
return s;
}
public static BcelShadow makeFieldSet(
BcelWorld world,
LazyMethodGen enclosingMethod,
InstructionHandle setHandle,
BcelShadow enclosingShadow)
{
final InstructionList body = enclosingMethod.getBody();
BcelShadow s =
new BcelShadow(
world,
FieldSet,
BcelWorld.makeFieldJoinPointSignature(
enclosingMethod.getEnclosingClass(),
(FieldInstruction) setHandle.getInstruction()),
enclosingMethod,
enclosingShadow);
ShadowRange r = new ShadowRange(body);
r.associateWithShadow(s);
r.associateWithTargets(
Range.genStart(body, setHandle),
Range.genEnd(body, setHandle));
retargetAllBranches(setHandle, r.getStart());
return s;
}
public static void retargetAllBranches(InstructionHandle from, InstructionHandle to) {
InstructionTargeter[] sources = from.getTargeters();
if (sources != null) {
for (int i = sources.length - 1; i >= 0; i--) {
InstructionTargeter source = sources[i];
if (source instanceof BranchInstruction) {
source.updateTarget(from, to);
}
}
}
}
// // ---- type access methods
// private ObjectType getTargetBcelType() {
// return (ObjectType) BcelWorld.makeBcelType(getTargetType());
// }
// private Type getArgBcelType(int arg) {
// return BcelWorld.makeBcelType(getArgType(arg));
// }
// ---- kinding
/**
* If the end of my range has no real instructions following then
* my context needs a return at the end.
*/
public boolean terminatesWithReturn() {
return getRange().getRealNext() == null;
}
/**
* Is arg0 occupied with the value of this
*/
public boolean arg0HoldsThis() {
if (getKind().isEnclosingKind()) {
return !getSignature().isStatic();
} else if (enclosingShadow == null) {
//XXX this is mostly right
// this doesn't do the right thing for calls in the pre part of introduced constructors.
return !enclosingMethod.isStatic();
} else {
return ((BcelShadow)enclosingShadow).arg0HoldsThis();
}
}
// ---- argument getting methods
private BcelVar thisVar = null;
private BcelVar targetVar = null;
private BcelVar[] argVars = null;
private Map/*<UnresolvedType,BcelVar>*/ kindedAnnotationVars = null;
private Map/*<UnresolvedType,BcelVar>*/ thisAnnotationVars = null;
private Map/*<UnresolvedType,BcelVar>*/ targetAnnotationVars = null;
private Map/*<UnresolvedType,BcelVar>*/[] argAnnotationVars = null;
private Map/*<UnresolvedType,BcelVar>*/ withinAnnotationVars = null;
private Map/*<UnresolvedType,BcelVar>*/ withincodeAnnotationVars = null;
public Var getThisVar() {
if (!hasThis()) {
throw new IllegalStateException("no this");
}
initializeThisVar();
return thisVar;
}
public Var getThisAnnotationVar(UnresolvedType forAnnotationType) {
if (!hasThis()) {
throw new IllegalStateException("no this");
}
initializeThisAnnotationVars(); // FIXME asc Why bother with this if we always return one?
// Even if we can't find one, we have to return one as we might have this annotation at runtime
Var v = (Var) thisAnnotationVars.get(forAnnotationType);
if (v==null)
v = new TypeAnnotationAccessVar(forAnnotationType.resolve(world),(BcelVar)getThisVar());
return v;
}
public Var getTargetVar() {
if (!hasTarget()) {
throw new IllegalStateException("no target");
}
initializeTargetVar();
return targetVar;
}
public Var getTargetAnnotationVar(UnresolvedType forAnnotationType) {
if (!hasTarget()) {
throw new IllegalStateException("no target");
}
initializeTargetAnnotationVars(); // FIXME asc why bother with this if we always return one?
Var v =(Var) targetAnnotationVars.get(forAnnotationType);
// Even if we can't find one, we have to return one as we might have this annotation at runtime
if (v==null)
v = new TypeAnnotationAccessVar(forAnnotationType.resolve(world),(BcelVar)getTargetVar());
return v;
}
public Var getArgVar(int i) {
initializeArgVars();
return argVars[i];
}
public Var getArgAnnotationVar(int i,UnresolvedType forAnnotationType) {
initializeArgAnnotationVars();
Var v= (Var) argAnnotationVars[i].get(forAnnotationType);
if (v==null)
v = new TypeAnnotationAccessVar(forAnnotationType.resolve(world),(BcelVar)getArgVar(i));
return v;
}
public Var getKindedAnnotationVar(UnresolvedType forAnnotationType) {
initializeKindedAnnotationVars();
return (Var) kindedAnnotationVars.get(forAnnotationType);
}
public Var getWithinAnnotationVar(UnresolvedType forAnnotationType) {
initializeWithinAnnotationVars();
return (Var) withinAnnotationVars.get(forAnnotationType);
}
public Var getWithinCodeAnnotationVar(UnresolvedType forAnnotationType) {
initializeWithinCodeAnnotationVars();
return (Var) withincodeAnnotationVars.get(forAnnotationType);
}
// reflective thisJoinPoint support
private BcelVar thisJoinPointVar = null;
private boolean isThisJoinPointLazy;
private int lazyTjpConsumers = 0;
private BcelVar thisJoinPointStaticPartVar = null;
// private BcelVar thisEnclosingJoinPointStaticPartVar = null;
public final Var getThisJoinPointStaticPartVar() {
return getThisJoinPointStaticPartBcelVar();
}
public final Var getThisEnclosingJoinPointStaticPartVar() {
return getThisEnclosingJoinPointStaticPartBcelVar();
}
public void requireThisJoinPoint(boolean hasGuardTest, boolean isAround) {
if (!isAround){
if (!hasGuardTest) {
isThisJoinPointLazy = false;
} else {
lazyTjpConsumers++;
}
}
// if (!hasGuardTest) {
// isThisJoinPointLazy = false;
// } else {
// lazyTjpConsumers++;
// }
if (thisJoinPointVar == null) {
thisJoinPointVar = genTempVar(UnresolvedType.forName("org.aspectj.lang.JoinPoint"));
}
}
public Var getThisJoinPointVar() {
requireThisJoinPoint(false,false);
return thisJoinPointVar;
}
void initializeThisJoinPoint() {
if (thisJoinPointVar == null) return;
if (isThisJoinPointLazy) {
isThisJoinPointLazy = checkLazyTjp();
}
if (isThisJoinPointLazy) {
appliedLazyTjpOptimization = true;
createThisJoinPoint(); // make sure any state needed is initialized, but throw the instructions out
if (lazyTjpConsumers == 1) return; // special case only one lazyTjpUser
InstructionFactory fact = getFactory();
InstructionList il = new InstructionList();
il.append(InstructionConstants.ACONST_NULL);
il.append(thisJoinPointVar.createStore(fact));
range.insert(il, Range.OutsideBefore);
} else {
appliedLazyTjpOptimization = false;
InstructionFactory fact = getFactory();
InstructionList il = createThisJoinPoint();
il.append(thisJoinPointVar.createStore(fact));
range.insert(il, Range.OutsideBefore);
}
}
private boolean checkLazyTjp() {
// check for around advice
for (Iterator i = mungers.iterator(); i.hasNext();) {
ShadowMunger munger = (ShadowMunger) i.next();
if (munger instanceof Advice) {
if ( ((Advice)munger).getKind() == AdviceKind.Around) {
if (munger.getSourceLocation()!=null) { // do we know enough to bother reporting?
world.getLint().canNotImplementLazyTjp.signal(
new String[] {toString()},
getSourceLocation(),
new ISourceLocation[] { munger.getSourceLocation() }
);
}
return false;
}
}
}
return true;
}
InstructionList loadThisJoinPoint() {
InstructionFactory fact = getFactory();
InstructionList il = new InstructionList();
if (isThisJoinPointLazy) {
// If we're lazy, build the join point right here.
il.append(createThisJoinPoint());
// Does someone else need it? If so, store it for later retrieval
if (lazyTjpConsumers > 1) {
il.append(thisJoinPointVar.createStore(fact));
InstructionHandle end = il.append(thisJoinPointVar.createLoad(fact));
il.insert(InstructionFactory.createBranchInstruction(Constants.IFNONNULL, end));
il.insert(thisJoinPointVar.createLoad(fact));
}
} else {
// If not lazy, its already been built and stored, just retrieve it
thisJoinPointVar.appendLoad(il, fact);
}
return il;
}
InstructionList createThisJoinPoint() {
InstructionFactory fact = getFactory();
InstructionList il = new InstructionList();
BcelVar staticPart = getThisJoinPointStaticPartBcelVar();
staticPart.appendLoad(il, fact);
if (hasThis()) {
((BcelVar)getThisVar()).appendLoad(il, fact);
} else {
il.append(new ACONST_NULL());
}
if (hasTarget()) {
((BcelVar)getTargetVar()).appendLoad(il, fact);
} else {
il.append(new ACONST_NULL());
}
switch(getArgCount()) {
case 0:
il.append(fact.createInvoke("org.aspectj.runtime.reflect.Factory",
"makeJP", LazyClassGen.tjpType,
new Type[] { LazyClassGen.staticTjpType,
Type.OBJECT, Type.OBJECT},
Constants.INVOKESTATIC));
break;
case 1:
((BcelVar)getArgVar(0)).appendLoadAndConvert(il, fact, world.getCoreType(ResolvedType.OBJECT));
il.append(fact.createInvoke("org.aspectj.runtime.reflect.Factory",
"makeJP", LazyClassGen.tjpType,
new Type[] { LazyClassGen.staticTjpType,
Type.OBJECT, Type.OBJECT, Type.OBJECT},
Constants.INVOKESTATIC));
break;
case 2:
((BcelVar)getArgVar(0)).appendLoadAndConvert(il, fact, world.getCoreType(ResolvedType.OBJECT));
((BcelVar)getArgVar(1)).appendLoadAndConvert(il, fact, world.getCoreType(ResolvedType.OBJECT));
il.append(fact.createInvoke("org.aspectj.runtime.reflect.Factory",
"makeJP", LazyClassGen.tjpType,
new Type[] { LazyClassGen.staticTjpType,
Type.OBJECT, Type.OBJECT, Type.OBJECT, Type.OBJECT},
Constants.INVOKESTATIC));
break;
default:
il.append(makeArgsObjectArray());
il.append(fact.createInvoke("org.aspectj.runtime.reflect.Factory",
"makeJP", LazyClassGen.tjpType,
new Type[] { LazyClassGen.staticTjpType,
Type.OBJECT, Type.OBJECT, new ArrayType(Type.OBJECT, 1)},
Constants.INVOKESTATIC));
break;
}
return il;
}
/**
* Get the Var for the jpStaticPart
* @return
*/
public BcelVar getThisJoinPointStaticPartBcelVar() {
return getThisJoinPointStaticPartBcelVar(false);
}
/**
* Get the Var for the xxxxJpStaticPart, xxx = this or enclosing
* @param isEnclosingJp true to have the enclosingJpStaticPart
* @return
*/
public BcelVar getThisJoinPointStaticPartBcelVar(final boolean isEnclosingJp) {
if (thisJoinPointStaticPartVar == null) {
Field field = getEnclosingClass().getTjpField(this, isEnclosingJp);
ResolvedType sjpType = null;
if (world.isTargettingAspectJRuntime12()) { // TAG:SUPPORTING12: We didn't have different jpsp types in 1.2
sjpType = world.getCoreType(UnresolvedType.forName("org.aspectj.lang.JoinPoint$StaticPart"));
} else {
sjpType = isEnclosingJp?
world.getCoreType(UnresolvedType.forName("org.aspectj.lang.JoinPoint$EnclosingStaticPart")):
world.getCoreType(UnresolvedType.forName("org.aspectj.lang.JoinPoint$StaticPart"));
}
thisJoinPointStaticPartVar = new BcelFieldRef(
sjpType,
getEnclosingClass().getClassName(),
field.getName());
// getEnclosingClass().warnOnAddedStaticInitializer(this,munger.getSourceLocation());
}
return thisJoinPointStaticPartVar;
}
/**
* Get the Var for the enclosingJpStaticPart
* @return
*/
public BcelVar getThisEnclosingJoinPointStaticPartBcelVar() {
if (enclosingShadow == null) {
// the enclosing of an execution is itself
return getThisJoinPointStaticPartBcelVar(true);
} else {
return ((BcelShadow)enclosingShadow).getThisJoinPointStaticPartBcelVar(true);
}
}
//??? need to better understand all the enclosing variants
public Member getEnclosingCodeSignature() {
if (getKind().isEnclosingKind()) {
return getSignature();
} else if (getKind() == Shadow.PreInitialization) {
// PreInit doesn't enclose code but its signature
// is correctly the signature of the ctor.
return getSignature();
} else if (enclosingShadow == null) {
return getEnclosingMethod().getMemberView();
} else {
return enclosingShadow.getSignature();
}
}
private InstructionList makeArgsObjectArray() {
InstructionFactory fact = getFactory();
BcelVar arrayVar = genTempVar(UnresolvedType.OBJECTARRAY);
final InstructionList il = new InstructionList();
int alen = getArgCount() ;
il.append(Utility.createConstant(fact, alen));
il.append((Instruction)fact.createNewArray(Type.OBJECT, (short)1));
arrayVar.appendStore(il, fact);
int stateIndex = 0;
for (int i = 0, len = getArgCount(); i<len; i++) {
arrayVar.appendConvertableArrayStore(il, fact, stateIndex, (BcelVar)getArgVar(i));
stateIndex++;
}
arrayVar.appendLoad(il, fact);
return il;
}
// ---- initializing var tables
/* initializing this is doesn't do anything, because this
* is protected from side-effects, so we don't need to copy its location
*/
private void initializeThisVar() {
if (thisVar != null) return;
thisVar = new BcelVar(getThisType().resolve(world), 0);
thisVar.setPositionInAroundState(0);
}
public void initializeTargetVar() {
InstructionFactory fact = getFactory();
if (targetVar != null) return;
if (getKind().isTargetSameAsThis()) {
if (hasThis()) initializeThisVar();
targetVar = thisVar;
} else {
initializeArgVars(); // gotta pop off the args before we find the target
UnresolvedType type = getTargetType();
type = ensureTargetTypeIsCorrect(type);
targetVar = genTempVar(type, "ajc$target");
range.insert(targetVar.createStore(fact), Range.OutsideBefore);
targetVar.setPositionInAroundState(hasThis() ? 1 : 0);
}
}
/* PR 72528
* This method double checks the target type under certain conditions. The Java 1.4
* compilers seem to take calls to clone methods on array types and create bytecode that
* looks like clone is being called on Object. If we advise a clone call with around
* advice we extract the call into a helper method which we can then refer to. Because the
* type in the bytecode for the call to clone is Object we create a helper method with
* an Object parameter - this is not correct as we have lost the fact that the actual
* type is an array type. If we don't do the check below we will create code that fails
* java verification. This method checks for the peculiar set of conditions and if they
* are true, it has a sneak peek at the code before the call to see what is on the stack.
*/
public UnresolvedType ensureTargetTypeIsCorrect(UnresolvedType tx) {
if (tx.equals(ResolvedType.OBJECT) && getKind() == MethodCall &&
getSignature().getReturnType().equals(ResolvedType.OBJECT) &&
getSignature().getArity()==0 &&
getSignature().getName().charAt(0) == 'c' &&
getSignature().getName().equals("clone")) {
// Lets go back through the code from the start of the shadow
InstructionHandle searchPtr = range.getStart().getPrev();
while (Range.isRangeHandle(searchPtr) ||
searchPtr.getInstruction() instanceof StoreInstruction) { // ignore this instruction - it doesnt give us the info we want
searchPtr = searchPtr.getPrev();
}
// A load instruction may tell us the real type of what the clone() call is on
if (searchPtr.getInstruction() instanceof LoadInstruction) {
LoadInstruction li = (LoadInstruction)searchPtr.getInstruction();
li.getIndex();
LocalVariableTag lvt = LazyMethodGen.getLocalVariableTag(searchPtr,li.getIndex());
return lvt.getType();
}
// A field access instruction may tell us the real type of what the clone() call is on
if (searchPtr.getInstruction() instanceof FieldInstruction) {
FieldInstruction si = (FieldInstruction)searchPtr.getInstruction();
Type t = si.getFieldType(getEnclosingClass().getConstantPoolGen());
return BcelWorld.fromBcel(t);
}
// A new array instruction obviously tells us it is an array type !
if (searchPtr.getInstruction() instanceof ANEWARRAY) {
//ANEWARRAY ana = (ANEWARRAY)searchPoint.getInstruction();
//Type t = ana.getType(getEnclosingClass().getConstantPoolGen());
// Just use a standard java.lang.object array - that will work fine
return BcelWorld.fromBcel(new ArrayType(Type.OBJECT,1));
}
// A multi new array instruction obviously tells us it is an array type !
if (searchPtr.getInstruction() instanceof MULTIANEWARRAY) {
MULTIANEWARRAY ana = (MULTIANEWARRAY)searchPtr.getInstruction();
// Type t = ana.getType(getEnclosingClass().getConstantPoolGen());
// t = new ArrayType(t,ana.getDimensions());
// Just use a standard java.lang.object array - that will work fine
return BcelWorld.fromBcel(new ArrayType(Type.OBJECT,ana.getDimensions()));
}
throw new BCException("Can't determine real target of clone() when processing instruction "+
searchPtr.getInstruction());
}
return tx;
}
public void initializeArgVars() {
if (argVars != null) return;
InstructionFactory fact = getFactory();
int len = getArgCount();
argVars = new BcelVar[len];
int positionOffset = (hasTarget() ? 1 : 0) +
((hasThis() && !getKind().isTargetSameAsThis()) ? 1 : 0);
if (getKind().argsOnStack()) {
// we move backwards because we're popping off the stack
for (int i = len - 1; i >= 0; i--) {
UnresolvedType type = getArgType(i);
BcelVar tmp = genTempVar(type, "ajc$arg" + i);
range.insert(tmp.createStore(getFactory()), Range.OutsideBefore);
int position = i;
position += positionOffset;
tmp.setPositionInAroundState(position);
argVars[i] = tmp;
}
} else {
int index = 0;
if (arg0HoldsThis()) index++;
for (int i = 0; i < len; i++) {
UnresolvedType type = getArgType(i);
BcelVar tmp = genTempVar(type, "ajc$arg" + i);
range.insert(tmp.createCopyFrom(fact, index), Range.OutsideBefore);
argVars[i] = tmp;
int position = i;
position += positionOffset;
// System.out.println("set position: " + tmp + ", " + position + " in " + this);
// System.out.println(" hasThis: " + hasThis() + ", hasTarget: " + hasTarget());
tmp.setPositionInAroundState(position);
index += type.getSize();
}
}
}
public void initializeForAroundClosure() {
initializeArgVars();
if (hasTarget()) initializeTargetVar();
if (hasThis()) initializeThisVar();
// System.out.println("initialized: " + this + " thisVar = " + thisVar);
}
public void initializeThisAnnotationVars() {
if (thisAnnotationVars != null) return;
thisAnnotationVars = new HashMap();
// populate..
}
public void initializeTargetAnnotationVars() {
if (targetAnnotationVars != null) return;
if (getKind().isTargetSameAsThis()) {
if (hasThis()) initializeThisAnnotationVars();
targetAnnotationVars = thisAnnotationVars;
} else {
targetAnnotationVars = new HashMap();
ResolvedType[] rtx = this.getTargetType().resolve(world).getAnnotationTypes(); // what about annotations we havent gotten yet but we will get in subclasses?
for (int i = 0; i < rtx.length; i++) {
ResolvedType typeX = rtx[i];
targetAnnotationVars.put(typeX,new TypeAnnotationAccessVar(typeX,(BcelVar)getTargetVar()));
}
// populate.
}
}
public void initializeArgAnnotationVars() {
if (argAnnotationVars != null) return;
int numArgs = getArgCount();
argAnnotationVars = new Map[numArgs];
for (int i = 0; i < argAnnotationVars.length; i++) {
argAnnotationVars[i] = new HashMap();
//FIXME asc just delete this logic - we always build the Var on demand, as we don't know at weave time
// what the full set of annotations could be (due to static/dynamic type differences...)
}
}
protected Member getRelevantMember(Member foundMember, Member relevantMember, ResolvedType relevantType){
if (foundMember != null){
return foundMember;
}
foundMember = getSignature().resolve(world);
if (foundMember == null && relevantMember != null) {
foundMember = relevantType.lookupMemberWithSupersAndITDs(relevantMember);
}
// check the ITD'd dooberries
List mungers = relevantType.resolve(world).getInterTypeMungers();
for (Iterator iter = mungers.iterator(); iter.hasNext();) {
BcelTypeMunger typeMunger = (BcelTypeMunger) iter.next();
if (typeMunger.getMunger() instanceof NewMethodTypeMunger ||
typeMunger.getMunger() instanceof NewConstructorTypeMunger) {
ResolvedMember fakerm = typeMunger.getSignature();
if (fakerm.getName().equals(getSignature().getName()) &&
fakerm.getParameterSignature().equals(getSignature().getParameterSignature())){
if (foundMember.getKind()==ResolvedMember.CONSTRUCTOR){
foundMember = AjcMemberMaker.interConstructor(
relevantType,
(ResolvedMember)foundMember,
typeMunger.getAspectType());
} else {
foundMember = AjcMemberMaker.interMethod((ResolvedMember)foundMember,
typeMunger.getAspectType(), false);
}
// in the above.. what about if it's on an Interface? Can that happen?
// then the last arg of the above should be true
return foundMember;
}
}
}
return foundMember;
}
protected ResolvedType [] getAnnotations(Member foundMember, Member relevantMember, ResolvedType relevantType){
if (foundMember == null){
// check the ITD'd dooberries
List mungers = relevantType.resolve(world).getInterTypeMungers();
for (Iterator iter = mungers.iterator(); iter.hasNext();) {
BcelTypeMunger typeMunger = (BcelTypeMunger) iter.next();
if (typeMunger.getMunger() instanceof NewMethodTypeMunger ||
typeMunger.getMunger() instanceof NewConstructorTypeMunger) {
ResolvedMember fakerm = typeMunger.getSignature();
//if (fakerm.hasAnnotations())
ResolvedMember ajcMethod = (getSignature().getKind()==ResolvedMember.CONSTRUCTOR?
AjcMemberMaker.postIntroducedConstructor(typeMunger.getAspectType(),fakerm.getDeclaringType(),fakerm.getParameterTypes()):
AjcMemberMaker.interMethodDispatcher(fakerm,typeMunger.getAspectType()));
//AjcMemberMaker.interMethodBody(fakerm,typeMunger.getAspectType()));
ResolvedMember rmm = findMethod(typeMunger.getAspectType(),ajcMethod);
if (fakerm.getName().equals(getSignature().getName()) &&
fakerm.getParameterSignature().equals(getSignature().getParameterSignature())) {
relevantType = typeMunger.getAspectType();
foundMember = rmm;
return foundMember.getAnnotationTypes();
}
}
}
// didn't find in ITDs, look in supers
foundMember = relevantType.lookupMemberWithSupersAndITDs(relevantMember);
if (foundMember == null) {
throw new IllegalStateException("Couldn't find member " + relevantMember + " for type " + relevantType);
}
}
return foundMember.getAnnotationTypes();
}
public void initializeKindedAnnotationVars() {
if (kindedAnnotationVars != null) return;
kindedAnnotationVars = new HashMap();
// by determining what "kind" of shadow we are, we can find out the
// annotations on the appropriate element (method, field, constructor, type).
// Then create one BcelVar entry in the map for each annotation, keyed by
// annotation type (UnresolvedType).
// FIXME asc Refactor this code, there is duplication
ResolvedType[] annotations = null;
Member relevantMember = getSignature();
ResolvedType relevantType = relevantMember.getDeclaringType().resolve(world);
if (getKind() == Shadow.StaticInitialization) {
annotations = relevantType.resolve(world).getAnnotationTypes();
} else if (getKind() == Shadow.MethodCall || getKind() == Shadow.ConstructorCall) {
Member foundMember = findMethod2(relevantType.resolve(world).getDeclaredMethods(),getSignature());
annotations = getAnnotations(foundMember, relevantMember, relevantType);
relevantMember = getRelevantMember(foundMember,relevantMember,relevantType);
relevantType = relevantMember.getDeclaringType().resolve(world);
} else if (getKind() == Shadow.FieldSet || getKind() == Shadow.FieldGet) {
relevantMember = findField(relevantType.getDeclaredFields(),getSignature());
if (relevantMember==null) {
// check the ITD'd dooberries
List mungers = relevantType.resolve(world).getInterTypeMungers();
for (Iterator iter = mungers.iterator(); iter.hasNext();) {
BcelTypeMunger typeMunger = (BcelTypeMunger) iter.next();
if (typeMunger.getMunger() instanceof NewFieldTypeMunger) {
ResolvedMember fakerm = typeMunger.getSignature();
//if (fakerm.hasAnnotations())
ResolvedMember ajcMethod = AjcMemberMaker.interFieldInitializer(fakerm,typeMunger.getAspectType());
ResolvedMember rmm = findMethod(typeMunger.getAspectType(),ajcMethod);
if (fakerm.equals(getSignature())) {
relevantType = typeMunger.getAspectType();
relevantMember = rmm;
}
}
}
}
annotations = relevantMember.getAnnotationTypes();
} else if (getKind() == Shadow.MethodExecution || getKind() == Shadow.ConstructorExecution ||
getKind() == Shadow.AdviceExecution) {
//ResolvedMember rm[] = relevantType.getDeclaredMethods();
Member foundMember = findMethod2(relevantType.getDeclaredMethods(),getSignature());
annotations = getAnnotations(foundMember, relevantMember,relevantType);
relevantMember = foundMember;
relevantMember = getRelevantMember(foundMember, relevantMember,relevantType);
} else if (getKind() == Shadow.ExceptionHandler) {
relevantType = getSignature().getParameterTypes()[0].resolve(world);
annotations = relevantType.getAnnotationTypes();
} else if (getKind() == Shadow.PreInitialization || getKind() == Shadow.Initialization) {
ResolvedMember found = findMethod2(relevantType.getDeclaredMethods(),getSignature());
annotations = found.getAnnotationTypes();
}
if (annotations == null) {
// We can't have recognized the shadow - should blow up now to be on the safe side
throw new BCException("Couldn't discover annotations for shadow: "+getKind());
}
for (int i = 0; i < annotations.length; i++) {
ResolvedType aTX = annotations[i];
KindedAnnotationAccessVar kaav = new KindedAnnotationAccessVar(getKind(),aTX.resolve(world),relevantType,relevantMember);
kindedAnnotationVars.put(aTX,kaav);
}
}
//FIXME asc whats the real diff between this one and the version in findMethod()?
ResolvedMember findMethod2(ResolvedMember rm[], Member sig) {
ResolvedMember found = null;
// String searchString = getSignature().getName()+getSignature().getParameterSignature();
for (int i = 0; i < rm.length && found==null; i++) {
ResolvedMember member = rm[i];
if (member.getName().equals(sig.getName()) && member.getParameterSignature().equals(sig.getParameterSignature()))
found = member;
}
return found;
}
private ResolvedMember findMethod(ResolvedType aspectType, ResolvedMember ajcMethod) {
ResolvedMember decMethods[] = aspectType.getDeclaredMethods();
for (int i = 0; i < decMethods.length; i++) {
ResolvedMember member = decMethods[i];
if (member.equals(ajcMethod)) return member;
}
return null;
}
private ResolvedMember findField(ResolvedMember[] members,Member lookingFor) {
for (int i = 0; i < members.length; i++) {
ResolvedMember member = members[i];
if ( member.getName().equals(getSignature().getName()) &&
member.getType().equals(getSignature().getType())) {
return member;
}
}
return null;
}
public void initializeWithinAnnotationVars() {
if (withinAnnotationVars != null) return;
withinAnnotationVars = new HashMap();
ResolvedType[] annotations = getEnclosingType().resolve(world).getAnnotationTypes();
for (int i = 0; i < annotations.length; i++) {
ResolvedType ann = annotations[i];
Kind k = Shadow.StaticInitialization;
withinAnnotationVars.put(ann,new KindedAnnotationAccessVar(k,ann,getEnclosingType(),null));
}
}
public void initializeWithinCodeAnnotationVars() {
if (withincodeAnnotationVars != null) return;
withincodeAnnotationVars = new HashMap();
// For some shadow we are interested in annotations on the method containing that shadow.
ResolvedType[] annotations = getEnclosingMethod().getMemberView().getAnnotationTypes();
for (int i = 0; i < annotations.length; i++) {
ResolvedType ann = annotations[i];
Kind k = (getEnclosingMethod().getMemberView().getKind()==Member.CONSTRUCTOR?
Shadow.ConstructorExecution:Shadow.MethodExecution);
withincodeAnnotationVars.put(ann,
new KindedAnnotationAccessVar(k,ann,getEnclosingType(),getEnclosingCodeSignature()));
}
}
// ---- weave methods
void weaveBefore(BcelAdvice munger) {
range.insert(
munger.getAdviceInstructions(this, null, range.getRealStart()),
Range.InsideBefore);
}
public void weaveAfter(BcelAdvice munger) {
weaveAfterThrowing(munger, UnresolvedType.THROWABLE);
weaveAfterReturning(munger);
}
/**
* We guarantee that the return value is on the top of the stack when
* munger.getAdviceInstructions() will be run
* (Unless we have a void return type in which case there's nothing)
*/
public void weaveAfterReturning(BcelAdvice munger) {
// InstructionFactory fact = getFactory();
List returns = new ArrayList();
Instruction ret = null;
for (InstructionHandle ih = range.getStart(); ih != range.getEnd(); ih = ih.getNext()) {
if (ih.getInstruction() instanceof ReturnInstruction) {
returns.add(ih);
ret = Utility.copyInstruction(ih.getInstruction());
}
}
InstructionList retList;
InstructionHandle afterAdvice;
if (ret != null) {
retList = new InstructionList(ret);
afterAdvice = retList.getStart();
} else /* if (munger.hasDynamicTests()) */ {
/*
*
27: getstatic #72; //Field ajc$cflowCounter$0:Lorg/aspectj/runtime/internal/CFlowCounter;
30: invokevirtual #87; //Method org/aspectj/runtime/internal/CFlowCounter.dec:()V
33: aload 6
35: athrow
36: nop
37: getstatic #72; //Field ajc$cflowCounter$0:Lorg/aspectj/runtime/internal/CFlowCounter;
40: invokevirtual #87; //Method org/aspectj/runtime/internal/CFlowCounter.dec:()V
43: d2i
44: invokespecial #23; //Method java/lang/Object."<init>":()V
*/
retList = new InstructionList(InstructionConstants.NOP);
afterAdvice = retList.getStart();
// } else {
// retList = new InstructionList();
// afterAdvice = null;
}
InstructionList advice = new InstructionList();
BcelVar tempVar = null;
if (munger.hasExtraParameter()) {
UnresolvedType tempVarType = getReturnType();
if (tempVarType.equals(ResolvedType.VOID)) {
tempVar = genTempVar(UnresolvedType.OBJECT);
advice.append(InstructionConstants.ACONST_NULL);
tempVar.appendStore(advice, getFactory());
} else {
tempVar = genTempVar(tempVarType);
advice.append(InstructionFactory.createDup(tempVarType.getSize()));
tempVar.appendStore(advice, getFactory());
}
}
advice.append(munger.getAdviceInstructions(this, tempVar, afterAdvice));
if (ret != null) {
InstructionHandle gotoTarget = advice.getStart();
for (Iterator i = returns.iterator(); i.hasNext();) {
InstructionHandle ih = (InstructionHandle) i.next();
Utility.replaceInstruction(
ih,
InstructionFactory.createBranchInstruction(
Constants.GOTO,
gotoTarget),
enclosingMethod);
}
range.append(advice);
range.append(retList);
} else {
range.append(advice);
range.append(retList);
}
}
public void weaveAfterThrowing(BcelAdvice munger, UnresolvedType catchType) {
// a good optimization would be not to generate anything here
// if the shadow is GUARANTEED empty (i.e., there's NOTHING, not even
// a shadow, inside me).
if (getRange().getStart().getNext() == getRange().getEnd()) return;
InstructionFactory fact = getFactory();
InstructionList handler = new InstructionList();
BcelVar exceptionVar = genTempVar(catchType);
exceptionVar.appendStore(handler, fact);
// pr62642
// I will now jump through some firey BCEL hoops to generate a trivial bit of code:
// if (exc instanceof ExceptionInInitializerError)
// throw (ExceptionInInitializerError)exc;
if (this.getEnclosingMethod().getName().equals("<clinit>")) {
ResolvedType eiieType = world.resolve("java.lang.ExceptionInInitializerError");
ObjectType eiieBcelType = (ObjectType)BcelWorld.makeBcelType(eiieType);
InstructionList ih = new InstructionList(InstructionConstants.NOP);
handler.append(exceptionVar.createLoad(fact));
handler.append(fact.createInstanceOf(eiieBcelType));
BranchInstruction bi =
InstructionFactory.createBranchInstruction(Constants.IFEQ,ih.getStart());
handler.append(bi);
handler.append(exceptionVar.createLoad(fact));
handler.append(fact.createCheckCast(eiieBcelType));
handler.append(InstructionConstants.ATHROW);
handler.append(ih);
}
InstructionList endHandler = new InstructionList(
exceptionVar.createLoad(fact));
handler.append(munger.getAdviceInstructions(this, exceptionVar, endHandler.getStart()));
handler.append(endHandler);
handler.append(InstructionConstants.ATHROW);
InstructionHandle handlerStart = handler.getStart();
if (isFallsThrough()) {
InstructionHandle jumpTarget = handler.append(InstructionConstants.NOP);
handler.insert(InstructionFactory.createBranchInstruction(Constants.GOTO, jumpTarget));
}
InstructionHandle protectedEnd = handler.getStart();
range.insert(handler, Range.InsideAfter);
enclosingMethod.addExceptionHandler(range.getStart().getNext(), protectedEnd.getPrev(),
handlerStart, (ObjectType)BcelWorld.makeBcelType(catchType), //???Type.THROWABLE,
// high priority if our args are on the stack
getKind().hasHighPriorityExceptions());
}
//??? this shares a lot of code with the above weaveAfterThrowing
//??? would be nice to abstract that to say things only once
public void weaveSoftener(BcelAdvice munger, UnresolvedType catchType) {
// a good optimization would be not to generate anything here
// if the shadow is GUARANTEED empty (i.e., there's NOTHING, not even
// a shadow, inside me).
if (getRange().getStart().getNext() == getRange().getEnd()) return;
InstructionFactory fact = getFactory();
InstructionList handler = new InstructionList();
InstructionList rtExHandler = new InstructionList();
BcelVar exceptionVar = genTempVar(catchType);
handler.append(fact.createNew(NameMangler.SOFT_EXCEPTION_TYPE));
handler.append(InstructionFactory.createDup(1));
handler.append(exceptionVar.createLoad(fact));
handler.append(fact.createInvoke(NameMangler.SOFT_EXCEPTION_TYPE, "<init>",
Type.VOID, new Type[] { Type.THROWABLE }, Constants.INVOKESPECIAL)); //??? special
handler.append(InstructionConstants.ATHROW);
// ENH 42737
exceptionVar.appendStore(rtExHandler, fact);
// aload_1
rtExHandler.append(exceptionVar.createLoad(fact));
// instanceof class java/lang/RuntimeException
rtExHandler.append(fact.createInstanceOf(new ObjectType("java.lang.RuntimeException")));
// ifeq go to new SOFT_EXCEPTION_TYPE instruction
rtExHandler.append(InstructionFactory.createBranchInstruction(Constants.IFEQ,handler.getStart()));
// aload_1
rtExHandler.append(exceptionVar.createLoad(fact));
// athrow
rtExHandler.append(InstructionFactory.ATHROW);
InstructionHandle handlerStart = rtExHandler.getStart();
if (isFallsThrough()) {
InstructionHandle jumpTarget = range.getEnd();//handler.append(fact.NOP);
rtExHandler.insert(InstructionFactory.createBranchInstruction(Constants.GOTO, jumpTarget));
}
rtExHandler.append(handler);
InstructionHandle protectedEnd = rtExHandler.getStart();
range.insert(rtExHandler, Range.InsideAfter);
enclosingMethod.addExceptionHandler(range.getStart().getNext(), protectedEnd.getPrev(),
handlerStart, (ObjectType)BcelWorld.makeBcelType(catchType),
// high priority if our args are on the stack
getKind().hasHighPriorityExceptions());
}
public void weavePerObjectEntry(final BcelAdvice munger, final BcelVar onVar) {
final InstructionFactory fact = getFactory();
InstructionList entryInstructions = new InstructionList();
InstructionList entrySuccessInstructions = new InstructionList();
onVar.appendLoad(entrySuccessInstructions, fact);
entrySuccessInstructions.append(
Utility.createInvoke(fact, world,
AjcMemberMaker.perObjectBind(munger.getConcreteAspect())));
InstructionList testInstructions =
munger.getTestInstructions(this, entrySuccessInstructions.getStart(),
range.getRealStart(),
entrySuccessInstructions.getStart());
entryInstructions.append(testInstructions);
entryInstructions.append(entrySuccessInstructions);
range.insert(entryInstructions, Range.InsideBefore);
}
// PTWIMPL Create static initializer to call the aspect factory
/**
* Causes the aspect instance to be *set* for later retrievable through localAspectof()/aspectOf()
*/
public void weavePerTypeWithinAspectInitialization(final BcelAdvice munger,UnresolvedType t) {
if (t.resolve(world).isInterface()) return; // Don't initialize statics in
final InstructionFactory fact = getFactory();
InstructionList entryInstructions = new InstructionList();
InstructionList entrySuccessInstructions = new InstructionList();
BcelWorld.getBcelObjectType(munger.getConcreteAspect());
String aspectname = munger.getConcreteAspect().getName();
String ptwField = NameMangler.perTypeWithinFieldForTarget(munger.getConcreteAspect());
entrySuccessInstructions.append(new PUSH(fact.getConstantPool(),t.getName()));
entrySuccessInstructions.append(fact.createInvoke(aspectname,"ajc$createAspectInstance",new ObjectType(aspectname),
new Type[]{new ObjectType("java.lang.String")},Constants.INVOKESTATIC));
entrySuccessInstructions.append(fact.createPutStatic(t.getName(),ptwField,
new ObjectType(aspectname)));
entryInstructions.append(entrySuccessInstructions);
range.insert(entryInstructions, Range.InsideBefore);
}
public void weaveCflowEntry(final BcelAdvice munger, final Member cflowField) {
final boolean isPer = munger.getKind() == AdviceKind.PerCflowBelowEntry ||
munger.getKind() == AdviceKind.PerCflowEntry;
final Type objectArrayType = new ArrayType(Type.OBJECT, 1);
final InstructionFactory fact = getFactory();
final BcelVar testResult = genTempVar(ResolvedType.BOOLEAN);
InstructionList entryInstructions = new InstructionList();
{
InstructionList entrySuccessInstructions = new InstructionList();
if (munger.hasDynamicTests()) {
entryInstructions.append(Utility.createConstant(fact, 0));
testResult.appendStore(entryInstructions, fact);
entrySuccessInstructions.append(Utility.createConstant(fact, 1));
testResult.appendStore(entrySuccessInstructions, fact);
}
if (isPer) {
entrySuccessInstructions.append(
fact.createInvoke(munger.getConcreteAspect().getName(),
NameMangler.PERCFLOW_PUSH_METHOD,
Type.VOID,
new Type[] { },
Constants.INVOKESTATIC));
} else {
BcelVar[] cflowStateVars = munger.getExposedStateAsBcelVars();
if (cflowStateVars.length == 0) {
// This should be getting managed by a counter - lets make sure.
if (!cflowField.getType().getName().endsWith("CFlowCounter"))
throw new RuntimeException("Incorrectly attempting counter operation on stacked cflow");
entrySuccessInstructions.append(
Utility.createGet(fact, cflowField));
//arrayVar.appendLoad(entrySuccessInstructions, fact);
entrySuccessInstructions.append(fact.createInvoke(NameMangler.CFLOW_COUNTER_TYPE,"inc",Type.VOID,new Type[] { },Constants.INVOKEVIRTUAL));
} else {
BcelVar arrayVar = genTempVar(UnresolvedType.OBJECTARRAY);
int alen = cflowStateVars.length;
entrySuccessInstructions.append(Utility.createConstant(fact, alen));
entrySuccessInstructions.append(
(Instruction) fact.createNewArray(Type.OBJECT, (short) 1));
arrayVar.appendStore(entrySuccessInstructions, fact);
for (int i = 0; i < alen; i++) {
arrayVar.appendConvertableArrayStore(
entrySuccessInstructions,
fact,
i,
cflowStateVars[i]);
}
entrySuccessInstructions.append(
Utility.createGet(fact, cflowField));
arrayVar.appendLoad(entrySuccessInstructions, fact);
entrySuccessInstructions.append(
fact.createInvoke(NameMangler.CFLOW_STACK_TYPE, "push", Type.VOID,
new Type[] { objectArrayType },
Constants.INVOKEVIRTUAL));
}
}
InstructionList testInstructions =
munger.getTestInstructions(this, entrySuccessInstructions.getStart(),
range.getRealStart(),
entrySuccessInstructions.getStart());
entryInstructions.append(testInstructions);
entryInstructions.append(entrySuccessInstructions);
}
// this is the same for both per and non-per
weaveAfter(new BcelAdvice(null, null, null, 0, 0, 0, null, null) {
public InstructionList getAdviceInstructions(
BcelShadow s,
BcelVar extraArgVar,
InstructionHandle ifNoAdvice) {
InstructionList exitInstructions = new InstructionList();
if (munger.hasDynamicTests()) {
testResult.appendLoad(exitInstructions, fact);
exitInstructions.append(
InstructionFactory.createBranchInstruction(
Constants.IFEQ,
ifNoAdvice));
}
exitInstructions.append(Utility.createGet(fact, cflowField));
if (munger.getKind() != AdviceKind.PerCflowEntry &&
munger.getKind() != AdviceKind.PerCflowBelowEntry &&
munger.getExposedStateAsBcelVars().length==0) {
exitInstructions
.append(
fact
.createInvoke(
NameMangler.CFLOW_COUNTER_TYPE,
"dec",
Type.VOID,
new Type[] {
}, Constants.INVOKEVIRTUAL));
} else {
exitInstructions
.append(
fact
.createInvoke(
NameMangler.CFLOW_STACK_TYPE,
"pop",
Type.VOID,
new Type[] {
}, Constants.INVOKEVIRTUAL));
}
return exitInstructions;
}
});
range.insert(entryInstructions, Range.InsideBefore);
}
public void weaveAroundInline(
BcelAdvice munger,
boolean hasDynamicTest)
{
/* Implementation notes:
*
* AroundInline still extracts the instructions of the original shadow into
* an extracted method. This allows inlining of even that advice that doesn't
* call proceed or calls proceed more than once.
*
* It extracts the instructions of the original shadow into a method.
*
* Then it extracts the instructions of the advice into a new method defined on
* this enclosing class. This new method can then be specialized as below.
*
* Then it searches in the instructions of the advice for any call to the
* proceed method.
*
* At such a call, there is stuff on the stack representing the arguments to
* proceed. Pop these into the frame.
*
* Now build the stack for the call to the extracted method, taking values
* either from the join point state or from the new frame locs from proceed.
* Now call the extracted method. The right return value should be on the
* stack, so no cast is necessary.
*
* If only one call to proceed is made, we can re-inline the original shadow.
* We are not doing that presently.
*
* If the body of the advice can be determined to not alter the stack, or if
* this shadow doesn't care about the stack, i.e. method-execution, then the
* new method for the advice can also be re-lined. We are not doing that
* presently.
*/
// !!! THIS BLOCK OF CODE SHOULD BE IN A METHOD CALLED weaveAround(...);
Member mungerSig = munger.getSignature();
//Member originalSig = mungerSig; // If mungerSig is on a parameterized type, originalSig is the member on the generic type
if (mungerSig instanceof ResolvedMember) {
ResolvedMember rm = (ResolvedMember)mungerSig;
if (rm.hasBackingGenericMember()) mungerSig = rm.getBackingGenericMember();
}
ResolvedType declaringType = world.resolve(mungerSig.getDeclaringType(),true);
if (declaringType.isMissing()) {
world.getLint().cantFindType.signal(
new String[] {WeaverMessages.format(WeaverMessages.CANT_FIND_TYPE_DURING_AROUND_WEAVE,declaringType.getClassName())},
getSourceLocation(),
new ISourceLocation[]{ munger.getSourceLocation()}
);
// IMessage msg = new Message(
// WeaverMessages.format(WeaverMessages.CANT_FIND_TYPE_DURING_AROUND_WEAVE,declaringType.getClassName()),
// "",IMessage.ERROR,getSourceLocation(),null,
// new ISourceLocation[]{ munger.getSourceLocation()});
// world.getMessageHandler().handleMessage(msg);
}
//??? might want some checks here to give better errors
BcelObjectType ot = BcelWorld.getBcelObjectType((declaringType.isParameterizedType()?declaringType.getGenericType():declaringType));
LazyMethodGen adviceMethod = ot.getLazyClassGen().getLazyMethodGen(mungerSig);
if (!adviceMethod.getCanInline()) {
weaveAroundClosure(munger, hasDynamicTest);
return;
}
// specific test for @AJ proceedInInners
if (munger.getConcreteAspect().isAnnotationStyleAspect()) {
// if we can't find one proceed()
// we suspect that the call is happening in an inner class
// so we don't inline it.
// Note: for code style, this is done at Aspect compilation time.
boolean canSeeProceedPassedToOther = false;
InstructionHandle curr = adviceMethod.getBody().getStart();
InstructionHandle end = adviceMethod.getBody().getEnd();
ConstantPoolGen cpg = adviceMethod.getEnclosingClass().getConstantPoolGen();
while (curr != end) {
InstructionHandle next = curr.getNext();
Instruction inst = curr.getInstruction();
if ((inst instanceof InvokeInstruction)
&& ((InvokeInstruction)inst).getSignature(cpg).indexOf("Lorg/aspectj/lang/ProceedingJoinPoint;") > 0) {
// we may want to refine to exclude stuff returning jp ?
// does code style skip inline if i write dump(thisJoinPoint) ?
canSeeProceedPassedToOther = true;// we see one pjp passed around - dangerous
break;
}
curr = next;
}
if (canSeeProceedPassedToOther) {
// remember this decision to avoid re-analysis
adviceMethod.setCanInline(false);
weaveAroundClosure(munger, hasDynamicTest);
return;
}
}
// We can't inline around methods if they have around advice on them, this
// is because the weaving will extract the body and hence the proceed call.
//??? should consider optimizations to recognize simple cases that don't require body extraction
enclosingMethod.setCanInline(false);
// start by exposing various useful things into the frame
final InstructionFactory fact = getFactory();
// now generate the aroundBody method
LazyMethodGen extractedMethod =
extractMethod(
NameMangler.aroundCallbackMethodName(
getSignature(),
getEnclosingClass()),
Modifier.PRIVATE,
munger
);
// now extract the advice into its own method
String adviceMethodName =
NameMangler.aroundCallbackMethodName(
getSignature(),
getEnclosingClass()) + "$advice";
List argVarList = new ArrayList();
List proceedVarList = new ArrayList();
int extraParamOffset = 0;
// Create the extra parameters that are needed for passing to proceed
// This code is very similar to that found in makeCallToCallback and should
// be rationalized in the future
if (thisVar != null) {
argVarList.add(thisVar);
proceedVarList.add(new BcelVar(thisVar.getType(), extraParamOffset));
extraParamOffset += thisVar.getType().getSize();
}
if (targetVar != null && targetVar != thisVar) {
argVarList.add(targetVar);
proceedVarList.add(new BcelVar(targetVar.getType(), extraParamOffset));
extraParamOffset += targetVar.getType().getSize();
}
for (int i = 0, len = getArgCount(); i < len; i++) {
argVarList.add(argVars[i]);
proceedVarList.add(new BcelVar(argVars[i].getType(), extraParamOffset));
extraParamOffset += argVars[i].getType().getSize();
}
if (thisJoinPointVar != null) {
argVarList.add(thisJoinPointVar);
proceedVarList.add(new BcelVar(thisJoinPointVar.getType(), extraParamOffset));
extraParamOffset += thisJoinPointVar.getType().getSize();
}
Type[] adviceParameterTypes = adviceMethod.getArgumentTypes();
Type[] extractedMethodParameterTypes = extractedMethod.getArgumentTypes();
Type[] parameterTypes =
new Type[extractedMethodParameterTypes.length
+ adviceParameterTypes.length
+ 1];
int parameterIndex = 0;
System.arraycopy(
extractedMethodParameterTypes,
0,
parameterTypes,
parameterIndex,
extractedMethodParameterTypes.length);
parameterIndex += extractedMethodParameterTypes.length;
parameterTypes[parameterIndex++] =
BcelWorld.makeBcelType(adviceMethod.getEnclosingClass().getType());
System.arraycopy(
adviceParameterTypes,
0,
parameterTypes,
parameterIndex,
adviceParameterTypes.length);
LazyMethodGen localAdviceMethod =
new LazyMethodGen(
Modifier.PRIVATE | Modifier.FINAL | Modifier.STATIC,
BcelWorld.makeBcelType(mungerSig.getReturnType()),
adviceMethodName,
parameterTypes,
new String[0],
getEnclosingClass());
String donorFileName = adviceMethod.getEnclosingClass().getInternalFileName();
String recipientFileName = getEnclosingClass().getInternalFileName();
// System.err.println("donor " + donorFileName);
// System.err.println("recip " + recipientFileName);
if (! donorFileName.equals(recipientFileName)) {
localAdviceMethod.fromFilename = donorFileName;
getEnclosingClass().addInlinedSourceFileInfo(
donorFileName,
adviceMethod.highestLineNumber);
}
getEnclosingClass().addMethodGen(localAdviceMethod);
// create a map that will move all slots in advice method forward by extraParamOffset
// in order to make room for the new proceed-required arguments that are added at
// the beginning of the parameter list
int nVars = adviceMethod.getMaxLocals() + extraParamOffset;
IntMap varMap = IntMap.idMap(nVars);
for (int i=extraParamOffset; i < nVars; i++) {
varMap.put(i-extraParamOffset, i);
}
localAdviceMethod.getBody().insert(
BcelClassWeaver.genInlineInstructions(adviceMethod,
localAdviceMethod, varMap, fact, true));
localAdviceMethod.setMaxLocals(nVars);
//System.err.println(localAdviceMethod);
// the shadow is now empty. First, create a correct call
// to the around advice. This includes both the call (which may involve
// value conversion of the advice arguments) and the return
// (which may involve value conversion of the return value). Right now
// we push a null for the unused closure. It's sad, but there it is.
InstructionList advice = new InstructionList();
// InstructionHandle adviceMethodInvocation;
{
for (Iterator i = argVarList.iterator(); i.hasNext(); ) {
BcelVar var = (BcelVar)i.next();
var.appendLoad(advice, fact);
}
// ??? we don't actually need to push NULL for the closure if we take care
advice.append(
munger.getAdviceArgSetup(
this,
null,
(munger.getConcreteAspect().isAnnotationStyleAspect())?
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();
IntMap proceedMap = makeProceedArgumentMap(adviceVars);
// System.out.println(proceedMap + " for " + this);
// System.out.println(argVarList);
ResolvedType[] proceedParamTypes =
world.resolve(munger.getSignature().getParameterTypes());
// remove this*JoinPoint* as arguments to proceed
if (munger.getBaseParameterCount()+1 < proceedParamTypes.length) {
int len = munger.getBaseParameterCount()+1;
ResolvedType[] newTypes = new ResolvedType[len];
System.arraycopy(proceedParamTypes, 0, newTypes, 0, len);
proceedParamTypes = newTypes;
}
//System.out.println("stateTypes: " + Arrays.asList(stateTypes));
BcelVar[] proceedVars =
Utility.pushAndReturnArrayOfVars(proceedParamTypes, ret, fact, localAdviceMethod);
Type[] stateTypes = callbackMethod.getArgumentTypes();
// System.out.println("stateTypes: " + Arrays.asList(stateTypes));
for (int i=0, len=stateTypes.length; i < len; i++) {
Type stateType = stateTypes[i];
ResolvedType stateTypeX = BcelWorld.fromBcel(stateType).resolve(world);
if (proceedMap.hasKey(i)) {
//throw new RuntimeException("unimplemented");
proceedVars[proceedMap.get(i)].appendLoadAndConvert(ret, fact, stateTypeX);
} else {
((BcelVar) argVarList.get(i)).appendLoad(ret, fact);
}
}
ret.append(Utility.createInvoke(fact, callbackMethod));
ret.append(Utility.createConversion(fact, callbackMethod.getReturnType(),
BcelWorld.makeBcelType(munger.getSignature().getReturnType())));
return ret;
}
/**
* ATAJ Handle the inlining for @AJ aspects
*
* @param fact
* @param callbackMethod
* @param munger
* @param localAdviceMethod
* @param argVarList
* @param isProceedWithArgs
* @return
*/
private InstructionList getRedoneProceedCallForAnnotationStyle(
InstructionFactory fact,
LazyMethodGen callbackMethod,
BcelAdvice munger,
LazyMethodGen localAdviceMethod,
List argVarList,
boolean isProceedWithArgs)
{
// Notes:
// proceedingjp is on stack (since user was calling pjp.proceed(...)
// the boxed args to proceed() are on stack as well (Object[]) unless
// the call is to pjp.proceed(<noarg>)
// new Object[]{new Integer(argAdvice1-1)};// arg of proceed
// call to proceed(..) is NOT made
// instead we do
// itar callback args i
// get from array i, convert it to the callback arg i
// if ask for JP, push the one we got on the stack
// invoke callback, create conversion back to Object/Integer
// rest of method -- (hence all those conversions)
// intValue() from original code
// int res = .. from original code
//Note: we just don't care about the proceed map etc
InstructionList ret = new InstructionList();
// store the Object[] array on stack if proceed with args
if (isProceedWithArgs) {
Type objectArrayType = Type.getType("[Ljava/lang/Object;");
int localProceedArgArray = localAdviceMethod.allocateLocal(objectArrayType);
ret.append(InstructionFactory.createStore(objectArrayType, localProceedArgArray));
Type proceedingJpType = Type.getType("Lorg/aspectj/lang/ProceedingJoinPoint;");
int localJp = localAdviceMethod.allocateLocal(proceedingJpType);
ret.append(InstructionFactory.createStore(proceedingJpType, localJp));
// push on stack each element of the object array
// that is assumed to be consistent with the callback argument (ie munger args)
// TODO do we want to try catch ClassCast and AOOBE exception ?
// special logic when withincode is static or not
int startIndex = 0;
if (thisVar != null) {
startIndex = 1;
//TODO this logic is actually depending on target as well - test me
ret.append(new ALOAD(0));//thisVar
}
for (int i = startIndex, len=callbackMethod.getArgumentTypes().length; i < len; i++) {
Type stateType = callbackMethod.getArgumentTypes()[i];
BcelWorld.fromBcel(stateType).resolve(world);
if ("Lorg/aspectj/lang/JoinPoint;".equals(stateType.getSignature())) {
ret.append(new ALOAD(localJp));// from localAdvice signature
} else {
ret.append(InstructionFactory.createLoad(objectArrayType, localProceedArgArray));
ret.append(Utility.createConstant(fact, i-startIndex));
ret.append(InstructionFactory.createArrayLoad(Type.OBJECT));
ret.append(Utility.createConversion(
fact,
Type.OBJECT,
stateType
));
}
}
} else {
Type proceedingJpType = Type.getType("Lorg/aspectj/lang/ProceedingJoinPoint;");
int localJp = localAdviceMethod.allocateLocal(proceedingJpType);
ret.append(InstructionFactory.createStore(proceedingJpType, localJp));
for (int i = 0, len=callbackMethod.getArgumentTypes().length; i < len; i++) {
Type stateType = callbackMethod.getArgumentTypes()[i];
/*ResolvedType stateTypeX =*/
BcelWorld.fromBcel(stateType).resolve(world);
if ("Lorg/aspectj/lang/JoinPoint;".equals(stateType.getSignature())) {
ret.append(new ALOAD(localJp));// from localAdvice signature
// } else if ("Lorg/aspectj/lang/ProceedingJoinPoint;".equals(stateType.getSignature())) {
// //FIXME ALEX?
// ret.append(new ALOAD(localJp));// from localAdvice signature
//// ret.append(fact.createCheckCast(
//// (ReferenceType) BcelWorld.makeBcelType(stateTypeX)
//// ));
// // cast ?
//
} else {
ret.append(InstructionFactory.createLoad(stateType, i));
}
}
}
// do the callback invoke
ret.append(Utility.createInvoke(fact, callbackMethod));
// box it again. Handles cases where around advice does return something else than Object
if (!UnresolvedType.OBJECT.equals(munger.getSignature().getReturnType())) {
ret.append(Utility.createConversion(
fact,
callbackMethod.getReturnType(),
Type.OBJECT
));
}
ret.append(Utility.createConversion(
fact,
callbackMethod.getReturnType(),
BcelWorld.makeBcelType(munger.getSignature().getReturnType())
));
return ret;
//
//
//
// if (proceedMap.hasKey(i)) {
// ret.append(new ALOAD(i));
// //throw new RuntimeException("unimplemented");
// //proceedVars[proceedMap.get(i)].appendLoadAndConvert(ret, fact, stateTypeX);
// } else {
// //((BcelVar) argVarList.get(i)).appendLoad(ret, fact);
// //ret.append(new ALOAD(i));
// if ("Lorg/aspectj/lang/JoinPoint;".equals(stateType.getSignature())) {
// ret.append(new ALOAD(i));
// } else {
// ret.append(new ALOAD(i));
// }
// }
// }
//
// ret.append(Utility.createInvoke(fact, callbackMethod));
// ret.append(Utility.createConversion(fact, callbackMethod.getReturnType(),
// BcelWorld.makeBcelType(munger.getSignature().getReturnType())));
//
// //ret.append(new ACONST_NULL());//will be POPed
// if (true) return ret;
//
//
//
// // we have on stack all the arguments for the ADVICE call.
// // we have in frame somewhere all the arguments for the non-advice call.
//
// BcelVar[] adviceVars = munger.getExposedStateAsBcelVars();
// IntMap proceedMap = makeProceedArgumentMap(adviceVars);
//
// System.out.println(proceedMap + " for " + this);
// System.out.println(argVarList);
//
// ResolvedType[] proceedParamTypes =
// world.resolve(munger.getSignature().getParameterTypes());
// // remove this*JoinPoint* as arguments to proceed
// if (munger.getBaseParameterCount()+1 < proceedParamTypes.length) {
// int len = munger.getBaseParameterCount()+1;
// ResolvedType[] newTypes = new ResolvedType[len];
// System.arraycopy(proceedParamTypes, 0, newTypes, 0, len);
// proceedParamTypes = newTypes;
// }
//
// //System.out.println("stateTypes: " + Arrays.asList(stateTypes));
// BcelVar[] proceedVars =
// Utility.pushAndReturnArrayOfVars(proceedParamTypes, ret, fact, localAdviceMethod);
//
// Type[] stateTypes = callbackMethod.getArgumentTypes();
//// System.out.println("stateTypes: " + Arrays.asList(stateTypes));
//
// for (int i=0, len=stateTypes.length; i < len; i++) {
// Type stateType = stateTypes[i];
// ResolvedType stateTypeX = BcelWorld.fromBcel(stateType).resolve(world);
// if (proceedMap.hasKey(i)) {
// //throw new RuntimeException("unimplemented");
// proceedVars[proceedMap.get(i)].appendLoadAndConvert(ret, fact, stateTypeX);
// } else {
// ((BcelVar) argVarList.get(i)).appendLoad(ret, fact);
// }
// }
//
// ret.append(Utility.createInvoke(fact, callbackMethod));
// ret.append(Utility.createConversion(fact, callbackMethod.getReturnType(),
// BcelWorld.makeBcelType(munger.getSignature().getReturnType())));
// return ret;
}
public void weaveAroundClosure(BcelAdvice munger, boolean hasDynamicTest) {
InstructionFactory fact = getFactory();
enclosingMethod.setCanInline(false);
// MOVE OUT ALL THE INSTRUCTIONS IN MY SHADOW INTO ANOTHER METHOD!
LazyMethodGen callbackMethod =
extractMethod(
NameMangler.aroundCallbackMethodName(
getSignature(),
getEnclosingClass()),
0,
munger);
BcelVar[] adviceVars = munger.getExposedStateAsBcelVars();
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()) {
closureInstantiation.append(Utility.createInvoke(
getFactory(),
getWorld(),
new MemberImpl(
Member.METHOD,
UnresolvedType.forName("org.aspectj.runtime.internal.AroundClosure"),
Modifier.PUBLIC,
"linkClosureAndJoinPoint",
"()Lorg/aspectj/lang/ProceedingJoinPoint;"
)
));
}
InstructionList advice = new InstructionList();
advice.append(munger.getAdviceArgSetup(this, null, closureInstantiation));
// invoke the advice
advice.append(munger.getNonTestAdviceInstructions(this));
advice.append(returnConversionCode);
if (!hasDynamicTest) {
range.append(advice);
} else {
InstructionList callback = makeCallToCallback(callbackMethod);
InstructionList postCallback = new InstructionList();
if (terminatesWithReturn()) {
callback.append(
InstructionFactory.createReturn(callbackMethod.getReturnType()));
} else {
advice.append(
InstructionFactory.createBranchInstruction(
Constants.GOTO,
postCallback.append(InstructionConstants.NOP)));
}
range.append(
munger.getTestInstructions(
this,
advice.getStart(),
callback.getStart(),
advice.getStart()));
range.append(advice);
range.append(callback);
range.append(postCallback);
}
}
// exposed for testing
InstructionList makeCallToCallback(LazyMethodGen callbackMethod) {
InstructionFactory fact = getFactory();
InstructionList callback = new InstructionList();
if (thisVar != null) {
callback.append(InstructionConstants.ALOAD_0);
}
if (targetVar != null && targetVar != thisVar) {
callback.append(BcelRenderer.renderExpr(fact, world, targetVar));
}
callback.append(BcelRenderer.renderExprs(fact, world, argVars));
// remember to render tjps
if (thisJoinPointVar != null) {
callback.append(BcelRenderer.renderExpr(fact, world, thisJoinPointVar));
}
callback.append(Utility.createInvoke(fact, callbackMethod));
return callback;
}
/** side-effect-free */
private InstructionList makeClosureInstantiation(Member constructor, BcelVar holder) {
// LazyMethodGen constructor) {
InstructionFactory fact = getFactory();
BcelVar arrayVar = genTempVar(UnresolvedType.OBJECTARRAY);
//final Type objectArrayType = new ArrayType(Type.OBJECT, 1);
final InstructionList il = new InstructionList();
int alen = getArgCount() + (thisVar == null ? 0 : 1) +
((targetVar != null && targetVar != thisVar) ? 1 : 0) +
(thisJoinPointVar == null ? 0 : 1);
il.append(Utility.createConstant(fact, alen));
il.append((Instruction)fact.createNewArray(Type.OBJECT, (short)1));
arrayVar.appendStore(il, fact);
int stateIndex = 0;
if (thisVar != null) {
arrayVar.appendConvertableArrayStore(il, fact, stateIndex, thisVar);
thisVar.setPositionInAroundState(stateIndex);
stateIndex++;
}
if (targetVar != null && targetVar != thisVar) {
arrayVar.appendConvertableArrayStore(il, fact, stateIndex, targetVar);
targetVar.setPositionInAroundState(stateIndex);
stateIndex++;
}
for (int i = 0, len = getArgCount(); i<len; i++) {
arrayVar.appendConvertableArrayStore(il, fact, stateIndex, argVars[i]);
argVars[i].setPositionInAroundState(stateIndex);
stateIndex++;
}
if (thisJoinPointVar != null) {
arrayVar.appendConvertableArrayStore(il, fact, stateIndex, thisJoinPointVar);
thisJoinPointVar.setPositionInAroundState(stateIndex);
stateIndex++;
}
il.append(fact.createNew(new ObjectType(constructor.getDeclaringType().getName())));
il.append(new DUP());
arrayVar.appendLoad(il, fact);
il.append(Utility.createInvoke(fact, world, constructor));
if (getKind() == PreInitialization) {
il.append(InstructionConstants.DUP);
holder.appendStore(il, fact);
}
return il;
}
private IntMap makeProceedArgumentMap(BcelVar[] adviceArgs) {
//System.err.println("coming in with " + Arrays.asList(adviceArgs));
IntMap ret = new IntMap();
for(int i = 0, len = adviceArgs.length; i < len; i++) {
BcelVar v = (BcelVar) adviceArgs[i];
if (v == null) continue; // XXX we don't know why this is required
int pos = v.getPositionInAroundState();
if (pos >= 0) { // need this test to avoid args bound via cflow
ret.put(pos, i);
}
}
//System.err.println("returning " + ret);
return ret;
}
/**
*
*
* @param callbackMethod the method we will call back to when our run method gets called.
*
* @param proceedMap A map from state position to proceed argument position. May be
* non covering on state position.
*/
private LazyMethodGen makeClosureClassAndReturnConstructor(
String closureClassName,
LazyMethodGen callbackMethod,
IntMap proceedMap)
{
String superClassName = "org.aspectj.runtime.internal.AroundClosure";
Type objectArrayType = new ArrayType(Type.OBJECT, 1);
LazyClassGen closureClass = new LazyClassGen(closureClassName,
superClassName,
getEnclosingClass().getFileName(),
Modifier.PUBLIC,
new String[] {},
getWorld());
InstructionFactory fact = new InstructionFactory(closureClass.getConstantPoolGen());
// constructor
LazyMethodGen constructor = new LazyMethodGen(Modifier.PUBLIC,
Type.VOID,
"<init>",
new Type[] {objectArrayType},
new String[] {},
closureClass);
InstructionList cbody = constructor.getBody();
cbody.append(InstructionFactory.createLoad(Type.OBJECT, 0));
cbody.append(InstructionFactory.createLoad(objectArrayType, 1));
cbody.append(fact.createInvoke(superClassName, "<init>", Type.VOID,
new Type[] {objectArrayType}, Constants.INVOKESPECIAL));
cbody.append(InstructionFactory.createReturn(Type.VOID));
closureClass.addMethodGen(constructor);
// method
LazyMethodGen runMethod = new LazyMethodGen(Modifier.PUBLIC,
Type.OBJECT,
"run",
new Type[] {objectArrayType},
new String[] {},
closureClass);
InstructionList mbody = runMethod.getBody();
BcelVar proceedVar = new BcelVar(UnresolvedType.OBJECTARRAY.resolve(world), 1);
// int proceedVarIndex = 1;
BcelVar stateVar =
new BcelVar(UnresolvedType.OBJECTARRAY.resolve(world), runMethod.allocateLocal(1));
// int stateVarIndex = runMethod.allocateLocal(1);
mbody.append(InstructionFactory.createThis());
mbody.append(fact.createGetField(superClassName, "state", objectArrayType));
mbody.append(stateVar.createStore(fact));
// mbody.append(fact.createStore(objectArrayType, stateVarIndex));
Type[] stateTypes = callbackMethod.getArgumentTypes();
for (int i=0, len=stateTypes.length; i < len; i++) {
Type stateType = stateTypes[i];
ResolvedType stateTypeX = BcelWorld.fromBcel(stateType).resolve(world);
if (proceedMap.hasKey(i)) {
mbody.append(
proceedVar.createConvertableArrayLoad(fact, proceedMap.get(i),
stateTypeX));
} else {
mbody.append(
stateVar.createConvertableArrayLoad(fact, i,
stateTypeX));
}
}
mbody.append(Utility.createInvoke(fact, callbackMethod));
if (getKind() == PreInitialization) {
mbody.append(Utility.createSet(
fact,
AjcMemberMaker.aroundClosurePreInitializationField()));
mbody.append(InstructionConstants.ACONST_NULL);
} else {
mbody.append(
Utility.createConversion(
fact,
callbackMethod.getReturnType(),
Type.OBJECT));
}
mbody.append(InstructionFactory.createReturn(Type.OBJECT));
closureClass.addMethodGen(runMethod);
// class
getEnclosingClass().addGeneratedInner(closureClass);
return constructor;
}
// ---- extraction methods
public LazyMethodGen extractMethod(String newMethodName, int visibilityModifier, ShadowMunger munger) {
LazyMethodGen.assertGoodBody(range.getBody(), newMethodName);
if (!getKind().allowsExtraction()) throw new BCException("Attempt to extract method from a shadow kind that does not support this operation (" + getKind() + ")");
LazyMethodGen freshMethod = createMethodGen(newMethodName,visibilityModifier);
// System.err.println("******");
// System.err.println("ABOUT TO EXTRACT METHOD for" + this);
// enclosingMethod.print(System.err);
// System.err.println("INTO");
// freshMethod.print(System.err);
// System.err.println("WITH REMAP");
// System.err.println(makeRemap());
range.extractInstructionsInto(freshMethod, makeRemap(),
(getKind() != PreInitialization) &&
isFallsThrough());
if (getKind() == PreInitialization) {
addPreInitializationReturnCode(
freshMethod,
getSuperConstructorParameterTypes());
}
getEnclosingClass().addMethodGen(freshMethod,munger.getSourceLocation());
return freshMethod;
}
private void addPreInitializationReturnCode(
LazyMethodGen extractedMethod,
Type[] superConstructorTypes)
{
InstructionList body = extractedMethod.getBody();
final InstructionFactory fact = getFactory();
BcelVar arrayVar = new BcelVar(
world.getCoreType(UnresolvedType.OBJECTARRAY),
extractedMethod.allocateLocal(1));
int len = superConstructorTypes.length;
body.append(Utility.createConstant(fact, len));
body.append((Instruction)fact.createNewArray(Type.OBJECT, (short)1));
arrayVar.appendStore(body, fact);
for (int i = len - 1; i >= 0; i++) {
// convert thing on top of stack to object
body.append(
Utility.createConversion(fact, superConstructorTypes[i], Type.OBJECT));
// push object array
arrayVar.appendLoad(body, fact);
// swap
body.append(InstructionConstants.SWAP);
// do object array store.
body.append(Utility.createConstant(fact, i));
body.append(InstructionConstants.SWAP);
body.append(InstructionFactory.createArrayStore(Type.OBJECT));
}
arrayVar.appendLoad(body, fact);
body.append(InstructionConstants.ARETURN);
}
private Type[] getSuperConstructorParameterTypes() {
// assert getKind() == PreInitialization
InstructionHandle superCallHandle = getRange().getEnd().getNext();
InvokeInstruction superCallInstruction =
(InvokeInstruction) superCallHandle.getInstruction();
return superCallInstruction.getArgumentTypes(
getEnclosingClass().getConstantPoolGen());
}
/** make a map from old frame location to new frame location. Any unkeyed frame
* location picks out a copied local */
private IntMap makeRemap() {
IntMap ret = new IntMap(5);
int reti = 0;
if (thisVar != null) {
ret.put(0, reti++); // thisVar guaranteed to be 0
}
if (targetVar != null && targetVar != thisVar) {
ret.put(targetVar.getSlot(), reti++);
}
for (int i = 0, len = argVars.length; i < len; i++) {
ret.put(argVars[i].getSlot(), reti);
reti += argVars[i].getType().getSize();
}
if (thisJoinPointVar != null) {
ret.put(thisJoinPointVar.getSlot(), reti++);
}
// we not only need to put the arguments, we also need to remap their
// aliases, which we so helpfully put into temps at the beginning of this join
// point.
if (! getKind().argsOnStack()) {
int oldi = 0;
int newi = 0;
// if we're passing in a this and we're not argsOnStack we're always
// passing in a target too
if (arg0HoldsThis()) { ret.put(0, 0); oldi++; newi+=1; }
//assert targetVar == thisVar
for (int i = 0; i < getArgCount(); i++) {
UnresolvedType type = getArgType(i);
ret.put(oldi, newi);
oldi += type.getSize();
newi += type.getSize();
}
}
// System.err.println("making remap for : " + this);
// if (targetVar != null) System.err.println("target slot : " + targetVar.getSlot());
// if (thisVar != null) System.err.println(" this slot : " + thisVar.getSlot());
// System.err.println(ret);
return ret;
}
/**
* The new method always static.
* It may take some extra arguments: this, target.
* If it's argsOnStack, then it must take both this/target
* If it's argsOnFrame, it shares this and target.
* ??? rewrite this to do less array munging, please
*/
private LazyMethodGen createMethodGen(String newMethodName, int visibilityModifier) {
Type[] parameterTypes = BcelWorld.makeBcelTypes(getArgTypes());
int modifiers = Modifier.FINAL | visibilityModifier;
// XXX some bug
// if (! isExpressionKind() && getSignature().isStrict(world)) {
// modifiers |= Modifier.STRICT;
// }
modifiers |= Modifier.STATIC;
if (targetVar != null && targetVar != thisVar) {
UnresolvedType targetType = getTargetType();
targetType = ensureTargetTypeIsCorrect(targetType);
// see pr109728 - this fixes the case when the declaring class is sometype 'X' but the getfield
// in the bytecode refers to a subtype of 'X'. This makes sure we use the type originally
// mentioned in the fieldget instruction as the method parameter and *not* the type upon which the
// field is declared because when the instructions are extracted into the new around body,
// they will still refer to the subtype.
if (getKind()==FieldGet && getActualTargetType()!=null &&
!getActualTargetType().equals(targetType.getName())) {
targetType = UnresolvedType.forName(getActualTargetType()).resolve(world);
}
ResolvedMember resolvedMember = getSignature().resolve(world);
if (resolvedMember != null && Modifier.isProtected(resolvedMember.getModifiers()) &&
!samePackage(targetType.getPackageName(), getEnclosingType().getPackageName()) &&
!resolvedMember.getName().equals("clone"))
{
if (!targetType.resolve(world).isAssignableFrom(getThisType().resolve(world))) {
throw new BCException("bad bytecode");
}
targetType = getThisType();
}
parameterTypes = addType(BcelWorld.makeBcelType(targetType), parameterTypes);
}
if (thisVar != null) {
UnresolvedType thisType = getThisType();
parameterTypes = addType(BcelWorld.makeBcelType(thisType), parameterTypes);
}
// We always want to pass down thisJoinPoint in case we have already woven
// some advice in here. If we only have a single piece of around advice on a
// join point, it is unnecessary to accept (and pass) tjp.
if (thisJoinPointVar != null) {
parameterTypes = addTypeToEnd(LazyClassGen.tjpType, parameterTypes);
//FIXME ALEX? which one
//parameterTypes = addTypeToEnd(LazyClassGen.proceedingTjpType, parameterTypes);
}
UnresolvedType returnType;
if (getKind() == PreInitialization) {
returnType = UnresolvedType.OBJECTARRAY;
} else {
returnType = getReturnType();
}
return
new LazyMethodGen(
modifiers,
BcelWorld.makeBcelType(returnType),
newMethodName,
parameterTypes,
new String[0],
// XXX again, we need to look up methods!
// UnresolvedType.getNames(getSignature().getExceptions(world)),
getEnclosingClass());
}
private boolean samePackage(String p1, String p2) {
if (p1 == null) return p2 == null;
if (p2 == null) return false;
return p1.equals(p2);
}
private Type[] addType(Type type, Type[] types) {
int len = types.length;
Type[] ret = new Type[len+1];
ret[0] = type;
System.arraycopy(types, 0, ret, 1, len);
return ret;
}
private Type[] addTypeToEnd(Type type, Type[] types) {
int len = types.length;
Type[] ret = new Type[len+1];
ret[len] = type;
System.arraycopy(types, 0, ret, 0, len);
return ret;
}
public BcelVar genTempVar(UnresolvedType typeX) {
return new BcelVar(typeX.resolve(world), genTempVarIndex(typeX.getSize()));
}
// public static final boolean CREATE_TEMP_NAMES = true;
public BcelVar genTempVar(UnresolvedType typeX, String localName) {
BcelVar tv = genTempVar(typeX);
// if (CREATE_TEMP_NAMES) {
// for (InstructionHandle ih = range.getStart(); ih != range.getEnd(); ih = ih.getNext()) {
// if (Range.isRangeHandle(ih)) continue;
// ih.addTargeter(new LocalVariableTag(typeX, localName, tv.getSlot()));
// }
// }
return tv;
}
// eh doesn't think we need to garbage collect these (64K is a big number...)
private int genTempVarIndex(int size) {
return enclosingMethod.allocateLocal(size);
}
public InstructionFactory getFactory() {
return getEnclosingClass().getFactory();
}
public ISourceLocation getSourceLocation() {
int sourceLine = getSourceLine();
if (sourceLine == 0 || sourceLine == -1) {
// Thread.currentThread().dumpStack();
// System.err.println(this + ": " + range);
return getEnclosingClass().getType().getSourceLocation();
} else {
// For staticinitialization, if we have a nice offset, don't build a new source loc
if (getKind()==Shadow.StaticInitialization && getEnclosingClass().getType().getSourceLocation().getOffset()!=0) {
return getEnclosingClass().getType().getSourceLocation();
} else {
int offset = 0;
Kind kind = getKind();
if ( (kind == MethodExecution) ||
(kind == ConstructorExecution) ||
(kind == AdviceExecution) ||
(kind == StaticInitialization) ||
(kind == PreInitialization) ||
(kind == Initialization)) {
if (getEnclosingMethod().hasDeclaredLineNumberInfo()) {
offset = getEnclosingMethod().getDeclarationOffset();
}
}
return getEnclosingClass().getType().getSourceContext().makeSourceLocation(sourceLine, offset);
}
}
}
public Shadow getEnclosingShadow() {
return enclosingShadow;
}
public LazyMethodGen getEnclosingMethod() {
return enclosingMethod;
}
public boolean isFallsThrough() {
return !terminatesWithReturn(); //fallsThrough;
}
public void setActualTargetType(String className) {
this.actualInstructionTargetType = className;
}
public String getActualTargetType() {
return actualInstructionTargetType;
}
}
|
120,363 |
Bug 120363 LTW weaver include and exclude does not behave correctly
| null |
resolved fixed
|
9edb4b6
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2005-12-12T15:42:19Z | 2005-12-12T15:06:40Z |
loadtime/src/org/aspectj/weaver/loadtime/ClassLoaderWeavingAdaptor.java
|
/*******************************************************************************
* Copyright (c) 2005 Contributors.
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Eclipse Public License v1.0
* which accompanies this distribution and is available at
* http://eclipse.org/legal/epl-v10.html
*
* Contributors:
* Alexandre Vasseur initial implementation
* David Knibb weaving context enhancments
*******************************************************************************/
package org.aspectj.weaver.loadtime;
import 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.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;
}
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, messageHandler, new ICrossReferenceHandler() {
public void addCrossReference(ISourceLocation from, ISourceLocation to, IRelationship.Kind kind, boolean runtimeTest) {
;// for tools only
}
}
);
// //TODO this AJ code will call
// //org.aspectj.apache.bcel.Repository.setRepository(this);
// //ie set some static things
// //==> bogus as Bcel is expected to be
// org.aspectj.apache.bcel.Repository.setRepository(new ClassLoaderRepository(loader));
weaver = new BcelWeaver(bcelWorld);
// register the definitions
registerDefinitions(weaver, loader, definitions);
messageHandler = bcelWorld.getMessageHandler();
//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);
}
}
private String getClassLoaderName (ClassLoader loader) {
return weavingContext.getClassLoaderName();
}
/**
* Configure the weaver according to the option directives
* TODO av - don't know if it is that good to reuse, since we only allow a small subset of options in LTW
*
* @param weaver
* @param loader
* @param definitions
*/
private void registerOptions(final BcelWeaver weaver, final ClassLoader loader, final List definitions) {
StringBuffer allOptions = new StringBuffer();
for (Iterator iterator = definitions.iterator(); iterator.hasNext();) {
Definition definition = (Definition) iterator.next();
allOptions.append(definition.getWeaverOptions()).append(' ');
}
Options.WeaverOption weaverOption = Options.parse(allOptions.toString(), loader, messageHandler);
// configure the weaver and world
// AV - code duplicates AspectJBuilder.initWorldAndWeaver()
World world = weaver.getWorld();
world.setMessageHandler(weaverOption.messageHandler);
world.setXlazyTjp(weaverOption.lazyTjp);
world.setXHasMemberSupportEnabled(weaverOption.hasMember);
world.setPinpointMode(weaverOption.pinpoint);
weaver.setReweavableMode(weaverOption.notReWeavable);
world.setXnoInline(weaverOption.noInline);
// AMC - autodetect as per line below, needed for AtAjLTWTests.testLTWUnweavable
world.setBehaveInJava5Way(LangUtil.is15VMOrGreater());
/* 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;
}
}
boolean fastAccept = false;//defaults to false if no fast include
for (int i = 0; i < m_includeStartsWith.size(); i++) {
fastAccept = fastClassName.startsWith((String)m_includeStartsWith.get(i));
if (fastAccept) {
break;
}
}
if (fastAccept) {
return true;
}
// needs further analysis
// TODO AV - needs refactoring
// during LTW this calling resolve at that stage is BAD as we do have the bytecode from the classloader hook
// but still go thru resolve that will do a getResourcesAsStream on disk
// this is also problematic for jit stub which are not on disk - as often underlying infra
// does returns null or some other info for getResourceAsStream (f.e. WLS 9 CR248491)
// Instead I parse the given bytecode. But this also means it will be parsed again in
// new WeavingClassFileProvider() from WeavingAdaptor.getWovenBytes()...
BcelObjectType bct = ((BcelWorld)weaver.getWorld()).addSourceObjectType(Utility.makeJavaClass(null, bytes));
ResolvedType classInfo = bct.getResolvedTypeX();//BAD: weaver.getWorld().resolve(UnresolvedType.forName(className), true);
//exclude are "AND"ed
for (Iterator iterator = m_excludeTypePattern.iterator(); iterator.hasNext();) {
TypePattern typePattern = (TypePattern) iterator.next();
if (typePattern.matchesStatically(classInfo)) {
// exclude match - skip
return false;
}
}
//include are "OR"ed
boolean accept = true;//defaults to true if no include
for (Iterator iterator = m_includeTypePattern.iterator(); iterator.hasNext();) {
TypePattern typePattern = (TypePattern) iterator.next();
accept = typePattern.matchesStatically(classInfo);
if (accept) {
break;
}
// goes on if this include did not match ("OR"ed)
}
return accept;
}
//FIXME we don't use include/exclude of others aop.xml
//this can be nice but very dangerous as well to change that
private boolean acceptAspect(String aspectClassName) {
// avoid ResolvedType if not needed
if (m_aspectExcludeTypePattern.isEmpty() && m_aspectIncludeTypePattern.isEmpty()) {
return true;
}
// still try to avoid ResolvedType if we have simple patterns
// EXCLUDE: if one match then reject
String fastClassName = aspectClassName.replace('/', '.').replace('.', '$');
for (int i = 0; i < m_aspectExcludeStartsWith.size(); i++) {
if (fastClassName.startsWith((String)m_aspectExcludeStartsWith.get(i))) {
return false;
}
}
//INCLUDE: if one match then accept
for (int i = 0; i < m_aspectIncludeStartsWith.size(); i++) {
if (fastClassName.startsWith((String)m_aspectIncludeStartsWith.get(i))) {
return true;
}
}
// needs further analysis
ResolvedType classInfo = weaver.getWorld().resolve(UnresolvedType.forName(aspectClassName), true);
//exclude are "AND"ed
for (Iterator iterator = m_aspectExcludeTypePattern.iterator(); iterator.hasNext();) {
TypePattern typePattern = (TypePattern) iterator.next();
if (typePattern.matchesStatically(classInfo)) {
// exclude match - skip
return false;
}
}
//include are "OR"ed
boolean accept = true;//defaults to true if no include
for (Iterator iterator = m_aspectIncludeTypePattern.iterator(); iterator.hasNext();) {
TypePattern typePattern = (TypePattern) iterator.next();
accept = typePattern.matchesStatically(classInfo);
if (accept) {
break;
}
// goes on if this include did not match ("OR"ed)
}
return accept;
}
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,363 |
Bug 120363 LTW weaver include and exclude does not behave correctly
| null |
resolved fixed
|
9edb4b6
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2005-12-12T15:42:19Z | 2005-12-12T15:06:40Z |
tests/java5/ataspectj/ataspectj/Test$$EnhancerByCGLIB$$12345.java
|
/*******************************************************************************
* Copyright (c) 2005 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:
* Matthew Webster - initial implementation
*******************************************************************************/
package ataspectj;
public class Test$$EnhancerByCGLIB$$12345 {
public static void main(String[] args) {
System.out.println("Test$$EnhancerByCGLIB$$12345.main()");
}
}
|
120,363 |
Bug 120363 LTW weaver include and exclude does not behave correctly
| null |
resolved fixed
|
9edb4b6
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2005-12-12T15:42:19Z | 2005-12-12T15:06:40Z |
tests/java5/ataspectj/com/foo/bar/Test$$EnhancerByCGLIB$$12345.java
| |
120,363 |
Bug 120363 LTW weaver include and exclude does not behave correctly
| null |
resolved fixed
|
9edb4b6
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2005-12-12T15:42:19Z | 2005-12-12T15:06:40Z |
tests/java5/ataspectj/com/foo/bar/Test.java
| |
120,363 |
Bug 120363 LTW weaver include and exclude does not behave correctly
| null |
resolved fixed
|
9edb4b6
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2005-12-12T15:42:19Z | 2005-12-12T15:06:40Z |
tests/src/org/aspectj/systemtest/ajc150/ataspectj/AtAjLTWTests.java
|
/*******************************************************************************
* Copyright (c) 2005 Contributors.
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Eclipse Public License v1.0
* which accompanies this distribution and is available at
* http://eclipse.org/legal/epl-v10.html
*
* Contributors:
* Alexandre Vasseur initial implementation
*******************************************************************************/
package org.aspectj.systemtest.ajc150.ataspectj;
import java.io.File;
import java.io.FilenameFilter;
import junit.framework.Test;
import org.aspectj.testing.XMLBasedAjcTestCase;
import org.aspectj.util.FileUtil;
/**
* @author <a href="mailto:alex AT gnilux DOT com">Alexandre Vasseur</a>
*/
public class AtAjLTWTests extends XMLBasedAjcTestCase {
public static Test suite() {
return XMLBasedAjcTestCase.loadSuite(org.aspectj.systemtest.ajc150.ataspectj.AtAjLTWTests.class);
}
protected File getSpecFile() {
return new File("../tests/src/org/aspectj/systemtest/ajc150/ataspectj/ltw.xml");
}
public void testRunThemAllWithJavacCompiledAndLTW() {
runTest("RunThemAllWithJavacCompiledAndLTW");
}
public void testAjcLTWPerClauseTest_XnoWeave() {
runTest("AjcLTW PerClauseTest -XnoWeave");
}
public void testAjcLTWPerClauseTest_Xreweavable() {
runTest("AjcLTW PerClauseTest -Xreweavable");
}
public void testJavaCAjcLTWPerClauseTest() {
runTest("JavaCAjcLTW PerClauseTest");
}
public void testAjcLTWAroundInlineMungerTest_XnoWeave() {
runTest("AjcLTW AroundInlineMungerTest -XnoWeave");
}
public void testAjcLTWAroundInlineMungerTest_Xreweavable() {
runTest("AjcLTW AroundInlineMungerTest");
}
public void testAjcLTWAroundInlineMungerTest() {
runTest("AjcLTW AroundInlineMungerTest");
}
public void testAjcLTWAroundInlineMungerTest_XnoInline_Xreweavable() {
runTest("AjcLTW AroundInlineMungerTest -XnoInline -Xreweavable");
}
public void testAjcLTWAroundInlineMungerTest2() {
runTest("AjcLTW AroundInlineMungerTest2");
}
public void testLTWDumpNone() {
runTest("LTW DumpTest none");
File f = new File("_ajdump/ataspectj/DumpTest.class");
assertFalse(f.exists());
f = new File("_ajdump/_before/ataspectj/DumpTestTheDump.class");
assertFalse(f.exists());
f = new File("_ajdump/ataspectj/DumpTestTheDump.class");
assertFalse(f.exists());
}
public void testLTWDump() {
runTest("LTW DumpTest");
File f = new File("_ajdump/ataspectj/DumpTest.class");
assertFalse(f.exists());
f = new File("_ajdump/_before/ataspectj/DumpTestTheDump.class");
assertFalse(f.exists());
f = new File("_ajdump/ataspectj/DumpTestTheDump.class");
assertTrue(f.exists());
// tidy up...
f = new File("_ajdump");
FileUtil.deleteContents(f);
f.delete();
}
public void testLTWDumpBeforeAndAfter() {
runTest("LTW DumpTest before and after");
File f = new File("_ajdump/_before/ataspectj/Test$$EnhancerByCGLIB$$12345.class");
assertTrue(f.exists());
f = new File("_ajdump/ataspectj/Test$$EnhancerByCGLIB$$12345.class");
assertTrue(f.exists());
// tidy up...
f = new File("_ajdump");
FileUtil.deleteContents(f);
f.delete();
}
public void testLTWDumpClosure() {
runTest("LTW DumpTest closure");
File f = new File("_ajdump/ataspectj/DumpTestTheDump$AjcClosure1.class");
assertTrue("Missing dump file " + f.getAbsolutePath(),f.exists());
// tidy up...
f = new File("_ajdump");
FileUtil.deleteContents(f);
f.delete();
}
public void testLTWDumpProxy() {
runTest("LTW DumpTest proxy");
// The working directory is different because this test must be forked
File dir = new File("../tests/java5/ataspectj");
File f = new File(dir,"_ajdump/_before");
System.out.println("AtAjLTWTests.testLTWDumpProxy() f=" + f.getAbsolutePath());
CountingFilenameFilter cff = new CountingFilenameFilter();
f.listFiles(cff);
assertEquals("Expected dump file in " + f.getAbsolutePath(),1,cff.getCount());
f = new File(dir,"_ajdump");
System.out.println("AtAjLTWTests.testLTWDumpProxy() f=" + f.getAbsolutePath());
cff = new CountingFilenameFilter();
f.listFiles(cff);
assertEquals(1,cff.getCount());
// tidy up...
f = new File(dir,"_ajdump");
FileUtil.deleteContents(f);
f.delete();
}
public void testAjcAspect1LTWAspect2_Xreweavable() {
runTest("Ajc Aspect1 LTW Aspect2 -Xreweavable");
}
public void testLTWLogSilent() {
runTest("LTW Log silent");
}
public void testLTWLogVerbose() {
runTest("LTW Log verbose");
}
public void testLTWLogVerboseAndShow() {
runTest("LTW Log verbose and showWeaveInfo");
}
public void testLTWLogMessageHandlerClass() {
runTest("LTW Log messageHandlerClass");
}
public void testLTWUnweavable() {
// actually test that we do LTW proxy and jit classes
runTest("LTW Unweavable");
}
public void testLTWDecp() {
runTest("LTW Decp");
}
public void testLTWDecp2() {
runTest("LTW Decp2");
}
public void testCompileTimeAspectsDeclaredToLTWWeaver() {
runTest("Compile time aspects declared to ltw weaver");
}
public void testConcreteAtAspect() {
runTest("Concrete@Aspect");
}
public void testConcreteAspect() {
runTest("ConcreteAspect");
}
public void testConcretePrecedenceAspect() {
runTest("ConcretePrecedenceAspect");
}
public void testAspectOfWhenAspectNotInInclude() {
runTest("AspectOfWhenAspectNotInInclude");
}
public void testAppContainer() {
runTest("AppContainer");
}
public void testCflowBelowStack() {
runTest("CflowBelowStack");
}
private static class CountingFilenameFilter implements FilenameFilter {
private int count;
public boolean accept(File dir, String name) {
if (name.endsWith(".class")) count++;
return false;
}
public int getCount() {
return count;
}
}
}
|
120,401 |
Bug 120401 add signature to UnresolvedType.parameterize(..) exception
|
I keep getting UnresolvedType UnsupportedOperationException unhelpful message "resolve this type first," so I'm adding the signature to the message (without permission, hence the bug as notice). throw new UnsupportedOperationException("unable to parameterize unresolved type: " + signature); ------------------------------- java.lang.UnsupportedOperationException at org.aspectj.weaver.UnresolvedType.parameterize(UnresolvedType.java:218) at org.aspectj.weaver.patterns.ExactTypePattern.parameterizeWith(ExactTypePattern.java:242) at org.aspectj.weaver.patterns.TypePatternList.parameterizeWith(TypePatternList.java:195) at org.aspectj.weaver.patterns.DeclareParents.parameterizeWith(DeclareParents.java:77) at org.aspectj.weaver.ReferenceType.getDeclares(ReferenceType.java:484) at org.aspectj.weaver.ResolvedType.collectDeclares(ResolvedType.java:523) at org.aspectj.weaver.ResolvedType.collectCrosscuttingMembers(ResolvedType.java:488) at org.aspectj.weaver.CrosscuttingMembersSet.addOrReplaceAspect(CrosscuttingMembersSet.java:60) at org.aspectj.ajdt.internal.compiler.lookup.AjLookupEnvironment.addCrosscuttingStructures(AjLookupEnvironment.java:378) at org.aspectj.ajdt.internal.compiler.lookup.AjLookupEnvironment.addCrosscuttingStructures(AjLookupEnvironment.java:388) at org.aspectj.ajdt.internal.compiler.lookup.AjLookupEnvironment.collectAllITDsAndDeclares(AjLookupEnvironment.java:314) at org.aspectj.ajdt.internal.compiler.lookup.AjLookupEnvironment.completeTypeBindings(AjLookupEnvironment.java:168) at org.aspectj.org.eclipse.jdt.internal.compiler.Compiler.beginToCompile(Compiler.java:301) at org.aspectj.org.eclipse.jdt.internal.compiler.Compiler.compile(Compiler.java:315) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.performCompilation(AjBuildManager.java:811) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.doBuild(AjBuildManager.java:230) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.doBuild(AjBuildManager.java:185) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.incrementalBuild(AjBuildManager.java:163) at org.aspectj.ajde.internal.CompilerAdapter.compile(CompilerAdapter.java:117) at org.aspectj.ajde.internal.AspectJBuildManager$CompilerThread.run(AspectJBuildManager.java:191) UnsupportedOperationException thrown: resolve this type first
|
resolved fixed
|
3ac4627
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2005-12-12T17:13:35Z | 2005-12-12T17:53:20Z |
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 Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* PARC initial implementation
* Andy Clement 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_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("?");
// 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("resolve this type first");
}
/**
* 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;
}
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();
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;
}
}
|
120,521 |
Bug 120521 named pointcut not resolved in pertarget pointcut
|
Get incorrect error "can't find pointcut ..." when declaring pertarget pointcut using pointcut declared outside the aspect. True of HEAD right now. Not true of pointcuts declared inside the aspect or issingleton aspects. I thought this was reported and fixed, but I couldn't find the bug. Sorry if it is a duplicate. ------------------------------------------------- package bugs; public class PerTargetSubaspectError { public static void main(String[] args) { C.run(); } static class C { static void run() {} } pointcut doit() : execution(void C.run()); // no error if not pertarget static aspect CPT pertarget(pc()){ // no error if doit() defined in CPT protected pointcut pc() : doit(); // unexpected CE before() : doit() {} // no CE } }
|
resolved fixed
|
ae500c6
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2005-12-13T09:25:38Z | 2005-12-13T07:46:40Z |
tests/bugs150/pr120521/PerTargetSubaspectError.java
| |
120,521 |
Bug 120521 named pointcut not resolved in pertarget pointcut
|
Get incorrect error "can't find pointcut ..." when declaring pertarget pointcut using pointcut declared outside the aspect. True of HEAD right now. Not true of pointcuts declared inside the aspect or issingleton aspects. I thought this was reported and fixed, but I couldn't find the bug. Sorry if it is a duplicate. ------------------------------------------------- package bugs; public class PerTargetSubaspectError { public static void main(String[] args) { C.run(); } static class C { static void run() {} } pointcut doit() : execution(void C.run()); // no error if not pertarget static aspect CPT pertarget(pc()){ // no error if doit() defined in CPT protected pointcut pc() : doit(); // unexpected CE before() : doit() {} // no CE } }
|
resolved fixed
|
ae500c6
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2005-12-13T09:25:38Z | 2005-12-13T07:46:40Z |
tests/src/org/aspectj/systemtest/ajc150/Ajc150Tests.java
|
/*******************************************************************************
* Copyright (c) 2004 IBM
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* Andy Clement - initial API and implementation
*******************************************************************************/
package org.aspectj.systemtest.ajc150;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.List;
import junit.framework.Test;
import org.aspectj.apache.bcel.classfile.JavaClass;
import org.aspectj.apache.bcel.classfile.Method;
import org.aspectj.apache.bcel.classfile.Signature;
import org.aspectj.apache.bcel.util.ClassPath;
import org.aspectj.apache.bcel.util.SyntheticRepository;
import org.aspectj.asm.AsmManager;
import org.aspectj.asm.IHierarchy;
import org.aspectj.asm.IProgramElement;
import org.aspectj.asm.IRelationship;
import org.aspectj.asm.internal.Relationship;
import org.aspectj.testing.XMLBasedAjcTestCase;
import org.aspectj.util.LangUtil;
public class Ajc150Tests extends org.aspectj.testing.XMLBasedAjcTestCase {
public static Test suite() {
return XMLBasedAjcTestCase.loadSuite(Ajc150Tests.class);
}
protected File getSpecFile() {
return new File("../tests/src/org/aspectj/systemtest/ajc150/ajc150.xml");
}
public void testDollarClasses_pr120474() { runTest("Dollar classes");}
public void testGenericPTW_pr119539_1() { runTest("generic pertypewithin aspect - 1");}
public void testGenericPTW_pr119539_2() { runTest("generic pertypewithin aspect - 2");}
public void testGenericPTW_pr119539_3() { runTest("generic pertypewithin aspect - 3");}
/*
public void testBrokenDispatchByITD_pr72834() { runTest("broken dispatch");}
public void testMissingAccessor_pr73856() { runTest("missing accessor");}
public void testCunningDeclareParents_pr92311() { runTest("cunning declare parents");}
public void testGenericITDsAndAbstractMethodError_pr102357() { runTest("generic itds and abstract method error");}
*/
//public void testIncorrectSignatureMatchingWithExceptions_pr119749() { runTest("incorrect exception signature matching");}
public void testGeneratingCodeForAnOldRuntime_pr116679_1() { runTest("generating code for a 1.2.1 runtime - 1");}
public void testGeneratingCodeForAnOldRuntime_pr116679_2() { runTest("generating code for a 1.2.1 runtime - 2");}
public void testAmbiguousMethod_pr118599_1() { runTest("ambiguous method when binary weaving - 1");}
public void testAmbiguousMethod_pr118599_2() { runTest("ambiguous method when binary weaving - 2");}
public void testAroundAdviceArrayAdviceSigs_pr118781() { runTest("verify error with around advice array sigs");}
public void testAtDeclareParents_pr117681() { runTest("at declare parents");}
public void testPrivilegeProblem_pr87525() { runTest("privilege problem with switch");}
public void testRangeProblem_pr109614() { runTest("Range problem");}
public void testGenericAspects_pr115237() { runTest("aspectOf and generic aspects");}
public void testClassFormatError_pr114436() { runTest("ClassFormatError binary weaving perthis");}
public void testParserException_pr115788() { runTest("parser exception");}
public void testPossibleStaticImports_pr113066_1() { runTest("possible static imports bug - 1");}
public void testPossibleStaticImports_pr113066_2() { runTest("possible static imports bug - 2");}
public void testPossibleStaticImports_pr113066_3() { runTest("possible static imports bug - 3");}
public void testITDCtor_pr112783() { runTest("Problem with constructor ITDs");}
public void testAnnotatedITDFs_pr114005_1() { runTest("Annotated ITDFs - 1");}
public void testAnnotatedITDFs_pr114005_2() { runTest("Annotated ITDFs - 2");}
public void testCantCallSuperMethods_pr90143() { runTest("cant call super methods");}
public void testBrokenDecp_pr112476() { runTest("binary weaving decp broken");}
public void testUnboundFormal_pr112027() { runTest("unexpected error unboundFormalInPC");}
public void testNPEScopeSetup_pr115038() { runTest("NPE in ensureScopeSetup");}
public void testCCEGenerics_pr113445() { runTest("Generics ClassCastException");}
public void testMatthewsAspect_pr113947_1() { runTest("maws generic aspect - 1");}
public void testMatthewsAspect_pr113947_2() { runTest("maws generic aspect - 2");}
public void testFieldGet_pr114343() { runTest("field-get, generics and around advice");}
public void testFieldGet_pr114343_2() { runTest("field-get, generics and around advice - 2");}
public void testFieldGet_pr114343_3() { runTest("field-get, generics and around advice - 3");}
public void testCaptureBinding_pr114744() { runTest("capturebinding wildcard problem");}
public void testAutoboxingAroundAdvice_pr119210_1() { runTest("autoboxing around advice - 1");}
public void testAutoboxingAroundAdvice_pr119210_2() { runTest("autoboxing around advice - 2");}
public void testAutoboxingAroundAdvice_pr119210_3() { runTest("autoboxing around advice - 3");}
public void testBadDecp_pr110788_1() { runTest("bad generic decp - 1");}
public void testBadDecp_pr110788_2() { runTest("bad generic decp - 2");}
public void testBadDecp_pr110788_3() { runTest("bad generic decp - 3");}
public void testBadDecp_pr110788_4() { runTest("bad generic decp - 4");}
public void testSpuriousOverrideMethodWarning_pr119570_1() { runTest("spurious override method warning");}
public void testSpuriousOverrideMethodWarning_pr119570_2() { runTest("spurious override method warning - 2");}
public void testBrokenSwitch_pr117854() { runTest("broken switch transform");}
public void testVarargsITD_pr110906() { runTest("ITD varargs problem");}
public void testBadRenderer_pr86903() { runTest("bcelrenderer bad");}
//public void testIllegalInitialization_pr118326_1() { runTest("illegal initialization - 1");}
//public void testIllegalInitialization_pr118326_2() { runTest("illegal initialization - 2");}
public void testLintForAdviceSorting_pr111667() { runTest("lint for advice sorting");}
public void testIncompatibleClassChangeError_pr113630_1() {runTest("IncompatibleClassChangeError - errorscenario");}
public void testIncompatibleClassChangeError_pr113630_2() {runTest("IncompatibleClassChangeError - workingscenario");}
public void testFieldGetProblemWithGenericField_pr113861() {runTest("field-get problems with generic field");}
public void testAccesstoPrivateITDInNested_pr118698() { runTest("access to private ITD from nested type");}
public void testDeclareAnnotationOnNonExistentType_pr99191_1() { runTest("declare annotation on non existent type - 1");}
public void testDeclareAnnotationOnNonExistentType_pr99191_2() { runTest("declare annotation on non existent type - 2");}
public void testDeclareAnnotationOnNonExistentType_pr99191_3() { runTest("declare annotation on non existent type - 3");}
public void testDeclareAnnotationOnNonExistentType_pr99191_4() { runTest("declare annotation on non existent type - 4");}
public void testDeclareAnnotationOnNonExistentType_pr99191_5() { runTest("declare annotation on non existent type - 5");}
public void testBadGenericSigAttribute_pr110927() {
runTest("cant create signature attribute");
Signature sig = GenericsTests.getClassSignature(ajc,"I");
if (sig==null) fail("Couldn't find signature attribute for type I");
String sigString = sig.getSignature();
if (!(sigString.equals("Ljava/lang/Object;LIE2;LIE1<Ljava/lang/String;>;") ||
sigString.equals("Ljava/lang/Object;LIE1<Ljava/lang/String;>;LIE2;"))) {
fail("Signature was "+sigString+" when should have been something like Ljava/lang/Object;LIE1<Ljava/lang/String;>;LIE2;");
}
}
public void test_typeProcessingOrderWhenDeclareParents() {
runTest("Order of types passed to compiler determines weaving behavior");
}
public void test_aroundMethod() {
runTest("method called around in class");
}
public void test_aroundMethodAspect() {
runTest("method called around in aspect");
}
public void test_ambiguousBindingsDetection() {
runTest("Various kinds of ambiguous bindings");
}
public void test_ambiguousArgsDetection() {
runTest("ambiguous args");
}
public void testIncorrectExceptionTableWhenBreakInMethod_pr78021() {
runTest("Injecting exception into while loop with break statement causes catch block to be ignored");
}
public void testIncorrectExceptionTableWhenReturnInMethod_pr79554() {
runTest("Return in try-block disables catch-block if final-block is present");
}
public void testMissingDebugInfoForGeneratedMethods_pr82570() throws ClassNotFoundException {
runTest("Weaved code does not include debug lines");
boolean f = false;
JavaClass jc = getClassFrom(ajc.getSandboxDirectory(),"PR82570_1");
Method[] meths = jc.getMethods();
for (int i = 0; i < meths.length; i++) {
Method method = meths[i];
if (f) System.err.println("Line number table for "+method.getName()+method.getSignature()+" = "+method.getLineNumberTable());
assertTrue("Didn't find a line number table for method "+method.getName()+method.getSignature(),
method.getLineNumberTable()!=null);
}
// This test would determine the info isn't there if you pass -g:none ...
// cR = ajc(baseDir,new String[]{"PR82570_1.java","-g:none"});
// assertTrue("Expected no compile problem:"+cR,!cR.hasErrorMessages());
// System.err.println(cR.getStandardError());
// jc = getClassFrom(ajc.getSandboxDirectory(),"PR82570_1");
// meths = jc.getMethods();
// for (int i = 0; i < meths.length; i++) {
// Method method = meths[i];
// assertTrue("Found a line number table for method "+method.getName(),
// method.getLineNumberTable()==null);
// }
}
public void testCanOverrideProtectedMethodsViaITDandDecp_pr83303() {
runTest("compiler error when mixing inheritance, overriding and polymorphism");
}
public void testPerTypeWithin_pr106554() {runTest("Problem in staticinitialization with pertypewithin aspect");}
public void testPerTypeWithinMissesNamedInnerTypes() {
runTest("pertypewithin() handing of inner classes (1)");
}
public void testPerTypeWithinMissesAnonymousInnerTypes() {
runTest("pertypewithin() handing of inner classes (2)");
}
public void testPerTypeWithinIncorrectlyMatchingInterfaces() {
runTest("pertypewithin({interface}) illegal field modifier");
}
public void test051_arrayCloningInJava5() {
runTest("AJC possible bug with static nested classes");
}
public void testBadASMforEnums() throws IOException {
runTest("bad asm for enums");
if (LangUtil.is15VMOrGreater()) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
PrintWriter pw = new PrintWriter(baos);
AsmManager.dumptree(pw,AsmManager.getDefault().getHierarchy().getRoot(),0);
pw.flush();
String tree = baos.toString();
assertTrue("Expected 'Red [enumvalue]' somewhere in here:"+tree,tree.indexOf("Red [enumvalue]")!=-1);
}
}
public void npeOnTypeNotFound() {
runTest("structure model npe on type not found");
}
public void testNoRuntimeExceptionSoftening() {
runTest("declare soft of runtime exception");
}
public void testRuntimeNoSoftenWithHandler() {
runTest("declare soft w. catch block");
}
public void testSyntaxError() {
runTest("invalid cons syntax");
}
public void testVarargsInConsBug() {
runTest("varargs in constructor sig");
}
public void testAspectpathdirs() {
runTest("dirs on aspectpath");
}
public void testIntroSample() {
runTest("introduction sample");
}
public void testPTWInterface() {
runTest("pertypewithin({interface}) illegal field modifier");
}
public void testEnumCalledEnumEtc() {
runTest("enum called Enum, annotation called Annotation, etc");
}
public void testInternalCompilerError_pr86832() {
runTest("Internal compiler error");
}
public void testCloneMethod_pr83311() {
runTest("overriding/polymorphism error on interface method introduction");
}
// IfPointcut.findResidueInternal() was modified to make this test complete in a short amount
// of time - if you see it hanging, someone has messed with the optimization.
public void testIfEvaluationExplosion_pr94086() {
runTest("Exploding compile time with if() statements in pointcut");
}
public void testReflectNPE_pr94167() {runTest("NPE in reflect implementation");}
public void testStaticImports_pr84260() {runTest("static import failures");}
public void testGenerics_pr99089() {runTest("ArrayIndexOutOfBoundsException - Generics in privileged aspects");}
public void testGenerics_pr95993() {runTest("NPE at ClassScope.java:660 when compiling generic class");}
public void testItdGenerics_pr99228() {runTest("ITD of a field into a generic class");}
public void testItdGenerics_pr98320() {runTest("intertype with nested generic type");}
public void testItdGenerics_pr100227() {runTest("inner class with generic enclosing class");}
public void testItdGenerics_pr100260() {runTest("methods inherited from a generic parent");}
public void testSyntaxErrorNPE_pr103266() {runTest("NPE on syntax error");}
public void testFinalAbstractClass_pr109486() { runTest("Internal compiler error (ClassParser.java:242)");}
public void testComplexBinding_pr102210() { runTest("NullPointerException trying to compile");}
public void testIllegalStateExceptionOnNestedParameterizedType_pr106634() {
runTest("IllegalStateException unpacking signature of nested parameterized type");
}
public void testParseErrorOnAnnotationStarPlusPattern() {
runTest("(@Foo *)+ type pattern parse error");
}
public void test_pr106130_tooManyLocals() {
runTest("test weaving with > 256 locals");
}
public void testMissingNamePattern_pr106461() { runTest("missing name pattern"); }
public void testMissingNamePattern_pr107059() {
runTest("parser crashes on call(void (@a *)(..)");
}
public void testIntermediateAnnotationMatching() {
runTest("intermediate annotation matching");
}
public void testBadRuntimeTestGeneration() {
runTest("target(@Foo *)");
}
public void testErrorMessageOnITDWithTypePatterns() {
runTest("clear error message on itd with type pattern");
}
public void testAjKeywordsAsIdentifiers() {
runTest("before and after are valid identifiers in classes");
}
public void testAjKeywordsAsIdentifiers2() {
runTest("before and after are valid identifiers in classes, part 2");
}
public void testNoBeforeReturningAdvice() {
runTest("before returning advice not allowed!");
}
public void testDetectVoidFieldType() {
runTest("void field type in pointcut expression");
}
public void testPointcutOverriding() {
runTest("overriding final pointcut from super-aspect");
}
public void testAtSuppressWarnings() {
runTest("@SuppressWarnings should suppress");
}
public void testDEOWWithBindingPointcut() {
runTest("declare warning : foo(str) : ...;");
}
public void testAroundAdviceAndInterfaceInitializer() {
runTest("around advice on interface initializer");
}
public void testGoodErrorMessageOnUnmatchedMemberSyntax() {
runTest("good error message for unmatched member syntax");
}
public void testITDWithNoExceptionAndIntermediary() {
runTest("itd override with no exception clause");
}
public void testAnonymousInnerClasses() {
runTest("anonymous inner classes");
}
public void testMultipleAnonymousInnerClasses() {
runTest("multiple anonymous inner classes");
}
public void testPrivilegedMethodAccessorsGetRightExceptions_pr82989() {
runTest("Compiler error due to a wrong exception check in try blocks");
}
public void testAnonymousInnerClassWithMethodReturningTypeParameter_pr107898() {
runTest("anonymous inner class with method returning type parameter");
}
public void testMatchingOfObjectArray() {
runTest("matching against Object[]");
}
public void testMultipleAnonymousInnerClasses_pr108104() {
runTest("multiple anonymous inner classes 2");
}
public void testSignatureMatchingInMultipleOverrideScenario() {
runTest("signature matching in override scenario");
}
public void testWildcardAnnotationMatching_pr108245() {
runTest("wildcard annotation matching - pr108245");
}
public void testInnerTypesAndTypeVariables() {
runTest("inner types and type variables");
}
public void testAtAfterThrowingWithNoFormal() {
runTest("@AfterThrowing with no formal specified");
}
public void testParameterizedVarArgsMatch() {
runTest("varargs with type variable");
}
public void testFieldAccessInsideITDM() {
runTest("itd field access inside itd method");
}
public void testTypeVarWithTypeVarBound() {
runTest("type variable with type variable bound");
}
public void testEnumSwitchInITD() {
runTest("switch on enum inside ITD method");
}
public void testInnerTypeOfGeneric() {
runTest("inner type of generic interface reference from parameterized type");
}
public void testDeclareParentsIntroducingCovariantReturnType() {
runTest("declare parents introducing override with covariance");
}
public void testInnerClassPassedToVarargs() {
runTest("inner class passed as argument to varargs method");
}
public void testInlinedFieldAccessInProceedCall() {
runTest("inlined field access in proceed call");
}
public void testVisibiltyInSignatureMatchingWithOverridesPart1() {
runTest("visibility in signature matching with overrides - 1");
}
public void testVisibiltyInSignatureMatchingWithOverridesPart2() {
runTest("visibility in signature matching with overrides - 2");
}
public void testVisibiltyInSignatureMatchingWithOverridesPart3() {
runTest("visibility in signature matching with overrides - 3");
}
public void testArgsGeneratedCorrectlyForAdviceExecution() {
runTest("args generated correctly for advice execution join point");
}
public void testNoUnusedWarningsOnAspectTypes() {
runTest("no unused warnings on aspect types");
}
public void testSyntheticArgumentsOnITDConstructorsNotUsedInMatching() {
runTest("synthetic arguments on itd cons are not used in matching");
}
public void testParsingOfGenericTypeSignature() {
runTest("parse generic type signature with parameterized type in interface");
}
public void testOverrideAndCovarianceWithDecPRuntime() {
runTest("override and covariance with decp - runtime");
}
public void testOverrideAndCovarianceWithDecPRuntimeMultiFiles() {
runTest("override and covariance with decp - runtime separate files");
}
public void testOverrideAndCovarianceWithDecPRuntimeMultiFilesBinaryWeaving() {
runTest("override and covariance with decp - binary weaving");
}
public void testAbstractSynchronizedITDMethods() {
runTest("abstract synchronized itdms not detected");
}
public void testSynchronizedITDInterfaceMethods() {
runTest("synchronized itd interface methods");
}
public void testNoWarningOnUnusedPointcut() {
runTest("unused private pointcuts");
}
public void testITDOnInterfaceWithExistingMember() {
runTest("itd interface method already existing on interface");
}
public void testFinalITDMOnInterface() {
runTest("final itd methods on interfaces");
}
public void testPrivatePointcutOverriding() {
runTest("can't override private pointcut in abstract aspect");
}
public void testAdviceOnCflow() {
runTest("advising cflow advice execution");
}
public void testNoTypeMismatchOnSameGenericTypes() {
runTest("no type mismatch on generic types in itds");
}
public void testSuperCallInITD() {
runTest("super call in ITD");
}
public void testSuperCallInITDPart2() {
runTest("super call in ITD - part 2");
}
public void testAtAnnotationBadTest_pr103740() {
runTest("Compiler failure on at_annotation");
}
public void testNoUnusedParameterWarningsForSyntheticAdviceArgs() {
runTest("no unused parameter warnings for synthetic advice args");
}
public void testNoVerifyErrorWithSetOnInnerType() {
runTest("no verify error with set on inner type");
}
public void testCantFindTypeErrorWithGenericReturnTypeOrParameter() {
runTest("cant find type error with generic return type or parameter");
}
public void testNoVerifyErrorOnGenericCollectionMemberAccess() {
runTest("no verify error on generic collection member access");
}
public void testRawAndGenericTypeConversionITDCons() {
runTest("raw and generic type conversion with itd cons");
}
public void testAtAnnotationBindingWithAround() {
runTest("@annotation binding with around advice");
}
public void testUnableToBuildShadows_pr109728() { runTest("Unable to build shadows");}
public void testMessageOnMissingTypeInDecP() {
runTest("declare parents on a missing type");
}
public void testParameterizedGenericMethods() {
runTest("parameterized generic methods");
}
public void testIllegalChangeToPointcutDeclaration_pr111915() {
runTest("test illegal change to pointcut declaration");
}
public void testCantProvideDefaultImplViaITD_pr110307_1() {runTest("Cant provide default implementation via ITD - 1");}
public void testCantProvideDefaultImplViaITD_pr110307_2() {runTest("Cant provide default implementation via ITD - 2");}
public void testCantProvideDefaultImplViaITD_pr110307_3() {runTest("Cant provide default implementation via ITD - 3");}
public void testCantProvideDefaultImplViaITD_pr110307_4() {runTest("Cant provide default implementation via ITD - 4");}
public void testCantProvideDefaultImplViaITD_pr110307_5() {runTest("Cant provide default implementation via ITD - 5");}
// Needs a change in the compiler so that getType() can be overridden in the intertype scope - thats
// where we can police whether a type variable has been used without being specified appropriately.
//public void testCantProvideDefaultImplViaITD_pr110307_6() {runTest("Cant provide default implementation via ITD - 6");}
public void testCantProvideDefaultImplViaITD_pr110307_7() {runTest("Cant provide default implementation via ITD - 7");}
public void testCallJoinPointsInAnonymousInnerClasses() {
runTest("call join points in anonymous inner classes");
}
public void testNoRequirementForUnwovenTypesToBeExposedToWeaver() {
runTest("default impl of Runnable");
}
public void testArrayCloneCallJoinPoints() {
runTest("array clone call join points in 1.4 vs 1.3");
}
public void testDebugInfoForAroundAdvice() {
runTest("debug info in around advice inlining");
}
public void testCCEWithGenericWildcard_pr112602() {
runTest("ClassCastException with generic wildcard");
}
public void testAdviceInStructureModelWithAnonymousInnerClass_pr77269() {
//AsmManager.setReporting("c:/debug.txt",true,true,true,true);
runTest("advice in structure model with anonymous inner class");
IHierarchy top = AsmManager.getDefault().getHierarchy();
// checking that the run() method inside anonymous inner class is in
// the structure model
IProgramElement anonRunMethodIPE = top.findElementForLabel(top.getRoot(),
IProgramElement.Kind.METHOD,"run()");
assertNotNull("Couldn't find 'run()' element in the tree",anonRunMethodIPE);
List l = AsmManager.getDefault().getRelationshipMap().get(anonRunMethodIPE);
assertNotNull("Should have some relationships but does not",l);
assertTrue("Should have one relationship but has " + l.size(),l.size()==1);
Relationship rel = (Relationship)l.get(0);
List targets = rel.getTargets();
assertTrue("Should have one target but has" + targets.size(),
targets.size()==1);
IProgramElement target = AsmManager.getDefault().getHierarchy().findElementForHandle((String)targets.get(0));
assertEquals("target of relationship should be 'before(): p..' but is "
+ target.toLabelString(),"before(): p..",target.toLabelString());
IProgramElement adviceIPE = top.findElementForLabel(top.getRoot(),
IProgramElement.Kind.ADVICE,"before(): p..");
assertNotNull("Couldn't find 'before(): p..' element in the tree",adviceIPE);
l = AsmManager.getDefault().getRelationshipMap().get(adviceIPE);
assertNotNull("Should have some relationships but does not",l);
assertTrue("Should have a relationship but does not ",l.size()>0);
for (Iterator iter = l.iterator(); iter.hasNext();) {
IRelationship element = (IRelationship) iter.next();
if (element.getName().equals("advises")) {
rel = (Relationship) element;
break;
}
}
targets = rel.getTargets();
assertTrue("Should have one target but has" + targets.size(),
targets.size()==1);
target = AsmManager.getDefault().getHierarchy().findElementForHandle((String)targets.get(0));
assertEquals("target of relationship should be 'run()' but is "
+ target.toLabelString(),"run()",target.toLabelString());
}
public void testAdviceInStructureModelWithNamedInnerClass_pr77269() {
//AsmManager.setReporting("c:/debug.txt",true,true,true,true);
runTest("advice in structure model with named inner class");
IHierarchy top = AsmManager.getDefault().getHierarchy();
// checking that the m() method inside named inner class is in
// the structure model
IProgramElement namedMethodIPE = top.findElementForLabel(top.getRoot(),
IProgramElement.Kind.METHOD,"m()");
assertNotNull("Couldn't find 'm()' element in the tree",namedMethodIPE);
List l = AsmManager.getDefault().getRelationshipMap().get(namedMethodIPE);
assertNotNull("Should have some relationships but does not",l);
assertTrue("Should have one relationship but has " + l.size(),l.size()==1);
Relationship rel = (Relationship)l.get(0);
List targets = rel.getTargets();
assertTrue("Should have one target but has" + targets.size(),
targets.size()==1);
IProgramElement target = AsmManager.getDefault().getHierarchy().findElementForHandle((String)targets.get(0));
assertEquals("target of relationship should be 'before(): p..' but is "
+ target.toLabelString(),"before(): p..",target.toLabelString());
IProgramElement adviceIPE = top.findElementForLabel(top.getRoot(),
IProgramElement.Kind.ADVICE,"before(): p..");
assertNotNull("Couldn't find 'before(): p..' element in the tree",adviceIPE);
l = AsmManager.getDefault().getRelationshipMap().get(adviceIPE);
assertNotNull("Should have some relationships but does not",l);
assertTrue("Should have a relationship but does not ",l.size()>0);
for (Iterator iter = l.iterator(); iter.hasNext();) {
IRelationship element = (IRelationship) iter.next();
if (element.getName().equals("advises")) {
rel = (Relationship) element;
break;
}
}
targets = rel.getTargets();
assertTrue("Should have one target but has" + targets.size(),
targets.size()==1);
target = AsmManager.getDefault().getHierarchy().findElementForHandle((String)targets.get(0));
assertEquals("target of relationship should be 'm()' but is "
+ target.toLabelString(),"m()",target.toLabelString());
}
public void testDWInStructureModelWithAnonymousInnerClass_pr77269() {
// AsmManager.setReporting("c:/debug.txt",true,true,true,true);
runTest("declare warning in structure model with anonymous inner class");
IHierarchy top = AsmManager.getDefault().getHierarchy();
IProgramElement pe = top.findElementForLabel(top.getRoot(),
IProgramElement.Kind.CODE,"method-call(void pack.Test.someMethod())");
assertNotNull("Couldn't find 'method-call(void pack.Test.someMethod())' element in the tree",pe);
}
public void testVarArgsIITDInConstructor() {
runTest("ITD varargs in constructor");
}
public void testWeaveInfoMessageForDeclareAtMethodOnITDdMethod() {
runTest("weaveinfo message for declare at method on an ITDd method");
}
public void testITDCWithNoExplicitConsCall() {
runTest("ITDC with no explicit cons call");
}
public void testJava5SpecificFeaturesUsedAtJava14OrLower() {
runTest("java 5 pointcuts and declares at pre-java 5 compliance levels");
}
public void testAnonymousTypes() {
runTest("Anonymous types and nome matching");
}
public void testAdviceExecutionJPToStringForms() {
runTest("adviceexecution join point toString forms");
}
public void testAssertWithinPointcutExpression() {
runTest("pointcut expression containing 'assert'");
}
public void testNoVerifyErrorWithTwoThisPCDs_pr113447() {
runTest("no verify error with two this pcds");
}
public void testNoVerifyErrorWithTwoAtThisPCDs_pr113447() {
runTest("no verify error with two at this pcds");
}
public void testNoVerifyErrorWithAtWithinPCDs_pr113447() {
runTest("no verify error with at within pcds");
}
public void testNoVerifyErrorWithAtWithincodePCDs_pr113447() {
runTest("no verify error with at withincode pcds");
}
public void testNoVerifyErrorWithAtAnnotationPCDs_pr113447() {
runTest("no verify error with at annotation pcds");
}
public void testNoVerifyErrorWithTwoArgsPCDs_pr113447() {
runTest("no verify error with two args pcds");
}
public void testNoStackOverflowWithCircularPCDInGenericAspect() {
runTest("no StackOverflowError with circular pcd in generic aspect");
}
public void testNoStackOverflowWithCircularPCDInGenericAspect2() {
runTest("no StackOverflowError with circular pcd in generic aspect - 2");
}
public void testNPEInThisJoinPointStaticPart() {
runTest("thisJoinPointStaticPart in if test");
}
public void testPointcutParsingOfCompiledPointcuts() {
runTest("pointcut parsing with ajc compiled pointcut references");
}
public void testReflectionOfAbstractITDs() {
runTest("reflection on abstract ITDs (Billing example)");
}
public void testDeclareSoftWithAdviceExecution() {
runTest("declare soft and adviceexecution");
}
public void testDeclareSoftWithExclusions() {
runTest("declare soft and exclusions");
}
public void testReturningObjectBinding() {
runTest("returning(Object) binding");
}
public void testPerTargetAndNegation() {
runTest("pertarget and negated pointcut");
}
public void testParameterizedPointcutAndAdvice() {
runTest("parameterized pointcut and advice");
}
public void testDoublyParameterizedAbstractType() {
runTest("double parameter generic abstract type");
}
public void testArgNamesInAdviceAnnotations() {
runTest("arg names in advice annotations");
}
/*
* Load-time weaving bugs
*/
public void testNPEinWeavingAdaptor_pr116626() { runTest("NPE in WeavingAdaptor");}
public void testXlintMessageForImproperAnnotationType_pr115252_Exact() {runTest("xlint message for improper exact annotation type");}
public void testXlintMessageForImproperAnnotationType_pr115252_OR() {runTest("xlint message for improper annotation type inside OR");}
public void testXlintMessageForImproperAnnotationType_pr115252_AND() {runTest("xlint message for improper annotation type inside AND");}
public void testXlintMessageForImproperAnnotationType_pr115252_Return() {runTest("xlint message for improper annotated return type");}
public void testXlintMessageForImproperAnnotationType_pr115252_Declaring() {runTest("xlint message for improper annotated declaring type");}
public void testXlintMessageForImproperAnnotationType_pr115252_Parameter() {runTest("xlint message for improper annotated parameter type");}
public void testXlintMessageForImproperAnnotationType_pr115252_Throws() {runTest("xlint message for improper annotated throws pattern");}
public void testXlintMessageForImproperAnnotationType_pr115252_MoreThanOne() {runTest("xlint message for more than one improper annotated parameter type");}
public void testDeclareAtTypeInStructureModel_pr115607() {
AsmManager.setReporting("c:/debug.txt",true,true,true,true);
runTest("declare at type appears correctly in structure model");
IHierarchy top = AsmManager.getDefault().getHierarchy();
IProgramElement pe = top.findElementForLabel(top.getRoot(),
IProgramElement.Kind.DECLARE_ANNOTATION_AT_TYPE,"declare @type: Simple : @I");
assertNotNull("Couldn't find 'declare @type: Simple : @I' element in the tree",pe);
List l = AsmManager.getDefault().getRelationshipMap().get(pe);
assertNotNull("Should have some relationships but does not",l);
}
public void testNoNPEWhenInaccessibleMethodIsCalledWithinITD_pr119019() {
runTest("no NPE when inaccessible method is called within itd");
}
public void testNoNPEWithOrPointcutAndMoreThanOneArgs_pr118149() {
runTest("no NPE with or pointcut and more than one args");
}
public void testNoSOBWithGenericInnerAspects_pr119543() {
runTest("no StringOutOfBoundsException with generic inner aspects");
}
public void testIllegalAccessErrorWithAroundAdvice_pr119657() {
runTest("IllegalAccessError with around advice on interface method call");
}
public void testIllegalAccessErrorWithAroundAdviceNotSelf_pr119657() {
runTest("IllegalAccessError with around advice on interface method call not self");
}
public void testIllegalAccessErrorWithAroundAdviceNoWeaveLTW_pr119657() {
runTest("IllegalAccessError with around advice on interface method call using -XnoWeave and LTW");
}
public void testIllegalAccessErrorWithAroundAdviceLTW_pr119657() {
runTest("IllegalAccessError with around advice on interface method call using LTW");
}
public void testIllegalAccessErrorWithAroundAdviceNotSelfLTW_pr119657() {
runTest("IllegalAccessError with around advice on interface method call not self using LTW");
}
public void testIllegalAccessErrorWithAroundAdviceSelfAndNotSelfLTW_pr119657() {
runTest("IllegalAccessError with around advice on interface method call self and not self using LTW");
}
public void testIllegalAccessErrorWithAroundAdviceLTWNoInline_pr119657() {
runTest("IllegalAccessError with around advice on interface method call using LTW and -XnoInline");
}
// helper methods.....
public SyntheticRepository createRepos(File cpentry) {
ClassPath cp = new ClassPath(cpentry+File.pathSeparator+System.getProperty("java.class.path"));
return SyntheticRepository.getInstance(cp);
}
protected JavaClass getClassFrom(File where,String clazzname) throws ClassNotFoundException {
SyntheticRepository repos = createRepos(where);
return repos.loadClass(clazzname);
}
}
|
120,543 |
Bug 120543 Issue version message during load-time weaving
|
It would be very useful to know exactly which version of the weaver is being used for LTW. An informational message could be issued when each WeavingAdaptor instance is created (it is possible to have multiple versions of AspectJ in a system). This message could be similar to the that issued by "ajc -version".
|
resolved fixed
|
9d32b76
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2005-12-13T14:03:53Z | 2005-12-13T10:33:20Z |
weaver/src/org/aspectj/weaver/tools/WeavingAdaptor.java
|
/* *******************************************************************
* Copyright (c) 2004 IBM Corporation
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* Matthew Webster, Adrian Colyer,
* Martin Lippert initial implementation
* ******************************************************************/
package org.aspectj.weaver.tools;
import java.io.File;
import java.io.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.IMessage.Kind;
import org.aspectj.util.FileUtil;
import org.aspectj.util.LangUtil;
import org.aspectj.weaver.IClassFileProvider;
import org.aspectj.weaver.IWeaveRequestor;
import org.aspectj.weaver.bcel.BcelWeaver;
import org.aspectj.weaver.bcel.BcelWorld;
import org.aspectj.weaver.bcel.UnwovenClassFile;
/**
* This adaptor allows the AspectJ compiler to be embedded in an existing
* system to facilitate load-time weaving. It provides an interface for a
* weaving class loader to provide a classpath to be woven by a set of
* aspects. A callback is supplied to allow a class loader to define classes
* generated by the compiler during the weaving process.
* <p>
* A weaving class loader should create a <code>WeavingAdaptor</code> before
* any classes are defined, typically during construction. The set of aspects
* passed to the adaptor is fixed for the lifetime of the adaptor although the
* classpath can be augmented. A system property can be set to allow verbose
* weaving messages to be written to the console.
*
*/
public class WeavingAdaptor {
/**
* System property used to turn on verbose weaving messages
*/
public static final String WEAVING_ADAPTOR_VERBOSE = "aj.weaving.verbose";
public static final String SHOW_WEAVE_INFO_PROPERTY = "org.aspectj.weaver.showWeaveInfo";
protected boolean enabled = true;
protected boolean verbose = getVerbose();
protected BcelWorld bcelWorld = null;
protected BcelWeaver weaver = null;
protected IMessageHandler/*WeavingAdaptorMessageHandler*/ messageHandler = null;
protected GeneratedClassHandler generatedClassHandler;
protected Map generatedClasses = new HashMap(); /* String -> UnwovenClassFile */
protected WeavingAdaptor () {
createMessageHandler();
}
/**
* Construct a WeavingAdaptor with a reference to a weaving class loader. The
* adaptor will automatically search the class loader hierarchy to resolve
* classes. The adaptor will also search the hierarchy for WeavingClassLoader
* instances to determine the set of aspects to be used ofr weaving.
* @param loader instance of <code>ClassLoader</code>
*/
public WeavingAdaptor (WeavingClassLoader loader) {
// System.err.println("? WeavingAdaptor.<init>(" + loader +"," + aspectURLs.length + ")");
generatedClassHandler = loader;
init(getFullClassPath((ClassLoader)loader),getFullAspectPath((ClassLoader)loader/*,aspectURLs*/));
}
/**
* Construct a WeavingAdator with a reference to a
* <code>GeneratedClassHandler</code>, a full search path for resolving
* classes and a complete set of aspects. The search path must include
* classes loaded by the class loader constructing the WeavingAdaptor and
* all its parents in the hierarchy.
* @param handler <code>GeneratedClassHandler</code>
* @param classURLs the URLs from which to resolve classes
* @param aspectURLs the aspects used to weave classes defined by this class loader
*/
public WeavingAdaptor (GeneratedClassHandler handler, URL[] classURLs, URL[] aspectURLs) {
// System.err.println("? WeavingAdaptor.<init>()");
generatedClassHandler = handler;
init(FileUtil.makeClasspath(classURLs),FileUtil.makeClasspath(aspectURLs));
}
private List getFullClassPath (ClassLoader loader) {
List list = new LinkedList();
for (; loader != null; loader = loader.getParent()) {
if (loader instanceof URLClassLoader) {
URL[] urls = ((URLClassLoader)loader).getURLs();
list.addAll(0,FileUtil.makeClasspath(urls));
}
else {
warn("cannot determine classpath");
}
}
list.addAll(0,makeClasspath(System.getProperty("sun.boot.class.path")));
return list;
}
private List getFullAspectPath (ClassLoader loader) {
List list = new LinkedList();
for (; loader != null; loader = loader.getParent()) {
if (loader instanceof WeavingClassLoader) {
URL[] urls = ((WeavingClassLoader)loader).getAspectURLs();
list.addAll(0,FileUtil.makeClasspath(urls));
}
}
return list;
}
private static boolean getVerbose () {
return Boolean.getBoolean(WEAVING_ADAPTOR_VERBOSE);
}
private void init(List classPath, List aspectPath) {
createMessageHandler();
info("using classpath: " + classPath);
info("using aspectpath: " + aspectPath);
bcelWorld = new BcelWorld(classPath,messageHandler,null);
bcelWorld.setXnoInline(false);
bcelWorld.getLint().loadDefaultProperties();
if (LangUtil.is15VMOrGreater()) {
bcelWorld.setBehaveInJava5Way(true);
}
weaver = new BcelWeaver(bcelWorld);
registerAspectLibraries(aspectPath);
}
private void createMessageHandler() {
messageHandler = new WeavingAdaptorMessageHandler(new PrintWriter(System.err));
if (verbose) messageHandler.dontIgnore(IMessage.INFO);
if (Boolean.getBoolean(SHOW_WEAVE_INFO_PROPERTY)) messageHandler.dontIgnore(IMessage.WEAVEINFO);
}
/**
* Appends URL to path used by the WeavingAdptor to resolve classes
* @param url to be appended to search path
*/
public void addURL(URL url) {
File libFile = new File(url.getPath());
try {
weaver.addLibraryJarFile(libFile);
}
catch (IOException ex) {
warn("bad library: '" + libFile + "'");
}
}
/**
* Weave a class using aspects previously supplied to the adaptor.
* @param name the name of the class
* @param bytes the class bytes
* @return the woven bytes
* @exception IOException weave failed
*/
public byte[] weaveClass (String name, byte[] bytes) throws IOException {
if (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);
}
}
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) {
return !((/*(name.startsWith("org.apache.bcel.")//FIXME AV why ? bcel is wrapped in org.aspectj.
||*/ name.startsWith("org.aspectj.")
|| name.startsWith("java.")
|| name.startsWith("javax."))
//|| name.startsWith("$Proxy")//JDK proxies//FIXME AV is that 1.3 proxy ? fe. ataspect.$Proxy0 is a java5 proxy...
|| name.startsWith("sun.reflect."));//JDK reflect
}
/**
* We allow @AJ aspect weaving so that we can add aspectOf() as part of the weaving
* (and not part of the source compilation)
*
* @param name
* @param bytes bytecode (from classloader), allow to NOT lookup stuff on disk again during resolve
* @return true if @Aspect
*/
private boolean shouldWeaveAnnotationStyleAspect(String name, byte[] bytes) {
// AV: instead of doing resolve that would lookup stuff on disk thru BCEL ClassLoaderRepository
// we reuse bytes[] here to do a fast lookup for @Aspect annotation
return bcelWorld.isAnnotationStyleAspect(name, bytes);
}
/**
* Weave a set of bytes defining a class.
* @param name the name of the class being woven
* @param bytes the bytes that define the class
* @return byte[] the woven bytes for the class
* @throws IOException
*/
private byte[] getWovenBytes(String name, byte[] bytes) throws IOException {
WeavingClassFileProvider wcp = new WeavingClassFileProvider(name,bytes);
weaver.weave(wcp);
return wcp.getBytes();
}
/**
* Weave a set of bytes defining a class for only what is needed to turn @AspectJ aspect
* in a usefull form ie with aspectOf method - see #113587
* @param name the name of the class being woven
* @param bytes the bytes that define the class
* @return byte[] the woven bytes for the class
* @throws IOException
*/
private byte[] getAtAspectJAspectBytes(String name, byte[] bytes) throws IOException {
WeavingClassFileProvider wcp = new WeavingClassFileProvider(name,bytes);
wcp.setApplyAtAspectJMungersOnly();
weaver.weave(wcp);
return wcp.getBytes();
}
private void registerAspectLibraries(List aspectPath) {
// System.err.println("? WeavingAdaptor.registerAspectLibraries(" + aspectPath + ")");
for (Iterator i = aspectPath.iterator(); i.hasNext();) {
String libName = (String)i.next();
addAspectLibrary(libName);
}
weaver.prepareForWeave();
}
/*
* Register an aspect library with this classloader for use during
* weaving. This class loader will also return (unmodified) any of the
* classes in the library in response to a <code>findClass()</code> request.
* The library is not required to be on the weavingClasspath given when this
* classloader was constructed.
* @param aspectLibraryJarFile a jar file representing an aspect library
* @throws IOException
*/
private void addAspectLibrary(String aspectLibraryName) {
File aspectLibrary = new File(aspectLibraryName);
if (aspectLibrary.isDirectory()
|| (aspectLibrary.isFile()
&& FileUtil.hasZipSuffix(aspectLibraryName))) {
try {
info("adding aspect library: '" + aspectLibrary + "'");
weaver.addLibraryJarFile(aspectLibrary);
} catch (IOException ex) {
error("exception adding aspect library: '" + ex + "'");
}
} else {
error("bad aspect library: '" + aspectLibrary + "'");
}
}
private static List makeClasspath(String cp) {
List ret = new ArrayList();
if (cp != null) {
StringTokenizer tok = new StringTokenizer(cp,File.pathSeparator);
while (tok.hasMoreTokens()) {
ret.add(tok.nextToken());
}
}
return ret;
}
protected boolean info (String message) {
return MessageUtil.info(messageHandler,message);
}
protected boolean warn (String message) {
return MessageUtil.warn(messageHandler,message);
}
protected boolean warn (String message, Throwable th) {
return messageHandler.handleMessage(new Message(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;
public WeavingAdaptorMessageHandler (PrintWriter writer) {
super(writer,true);
ignore(IMessage.WEAVEINFO);
ignore(IMessage.INFO);
this.failKind = IMessage.ERROR;
}
public boolean handleMessage(IMessage message) throws AbortException {
boolean result = super.handleMessage(message);
if (0 <= message.getKind().compareTo(failKind)) {
throw new AbortException(message);
}
return true;
}
public boolean isIgnoring (Kind kind) {
return ((null != kind) && (ignoring.contains(kind)));
}
/**
* Set a message kind to be ignored from now on
*/
public void ignore (IMessage.Kind kind) {
if ((null != kind) && (!ignoring.contains(kind))) {
ignoring.add(kind);
}
}
/**
* Remove a message kind from the list of those ignored from now on.
*/
public void dontIgnore (IMessage.Kind kind) {
if (null != kind) {
ignoring.remove(kind);
}
}
}
private class WeavingClassFileProvider implements IClassFileProvider {
private UnwovenClassFile unwovenClass;
private List unwovenClasses = new ArrayList(); /* List<UnovenClassFile> */
private UnwovenClassFile wovenClass;
private boolean isApplyAtAspectJMungersOnly = false;
public WeavingClassFileProvider (String name, byte[] bytes) {
this.unwovenClass = new UnwovenClassFile(name,bytes);
this.unwovenClasses.add(unwovenClass);
if (shouldDump(name.replace('/', '.'),true)) {
dump(name, bytes, true);
}
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();
generatedClasses.put(className,result);
generatedClassHandler.acceptClass(className,result.getBytes());
}
}
public void processingReweavableState() { }
public void addingTypeMungers() {}
public void weavingAspects() {}
public void weavingClasses() {}
public void weaveCompleted() {}
};
}
}
}
|
120,693 |
Bug 120693 Contribution: More Efficient Lint Warnings: ~15% Performance Increase
|
In profiling a load-time weaving configuration from HEAD, I found that 9% of total time (over 10% of weaving time) is spent in org.aspectj.weaver.Lint.clearSuppressions(), mostly from use inside BcelClassWeaver.match I made a small change in the parts of BcelAdvice that clear suppressions to save the list that was cleared and to only clear these. This alone saves about 15% of total CPU time in start up on my sample configuration.
|
resolved fixed
|
bdafe31
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2005-12-13T21:04:36Z | 2005-12-13T18:53:20Z |
weaver/src/org/aspectj/weaver/Lint.java
|
/* *******************************************************************
* Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC).
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* PARC initial implementation
* ******************************************************************/
package org.aspectj.weaver;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.MessageFormat;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Properties;
import org.aspectj.bridge.IMessage;
import org.aspectj.bridge.ISourceLocation;
import org.aspectj.bridge.Message;
import org.aspectj.bridge.MessageUtil;
public class Lint {
/* private */ Map kinds = new HashMap();
/* private */ World world;
public final Kind invalidAbsoluteTypeName =
new Kind("invalidAbsoluteTypeName", "no match for this type name: {0}");
public final Kind invalidWildcardTypeName =
new Kind("invalidWildcardTypeName", "no match for this type pattern: {0}");
public final Kind unresolvableMember =
new Kind("unresolvableMember", "can not resolve this member: {0}");
public final Kind typeNotExposedToWeaver =
new Kind("typeNotExposedToWeaver", "this affected type is not exposed to the weaver: {0}");
public final Kind shadowNotInStructure =
new Kind("shadowNotInStructure", "the shadow for this join point is not exposed in the structure model: {0}");
public final Kind unmatchedSuperTypeInCall =
new Kind("unmatchedSuperTypeInCall", "does not match because declaring type is {0}, if match desired use target({1})");
public final Kind unmatchedTargetKind =
new Kind("unmatchedTargetKind", "does not match because annotation {0} has @Target{1}");
public final Kind canNotImplementLazyTjp =
new Kind("canNotImplementLazyTjp", "can not implement lazyTjp on this joinpoint {0} because around advice is used");
public final Kind multipleAdviceStoppingLazyTjp =
new Kind("multipleAdviceStoppingLazyTjp", "can not implement lazyTjp at joinpoint {0} because of advice conflicts, see secondary locations to find conflicting advice");
public final Kind needsSerialVersionUIDField =
new Kind("needsSerialVersionUIDField", "serialVersionUID of type {0} needs to be set because of {1}");
public final Kind serialVersionUIDBroken =
new Kind("brokeSerialVersionCompatibility", "serialVersionUID of type {0} is broken because of added field {1}");
public final Kind noInterfaceCtorJoinpoint =
new Kind("noInterfaceCtorJoinpoint","no interface constructor-execution join point - use {0}+ for implementing classes");
public final Kind noJoinpointsForBridgeMethods =
new Kind("noJoinpointsForBridgeMethods","pointcut did not match on the method call to a bridge method. Bridge methods are generated by the compiler and have no join points");
public final Kind enumAsTargetForDecpIgnored =
new Kind("enumAsTargetForDecpIgnored","enum type {0} matches a declare parents type pattern but is being ignored");
public final Kind annotationAsTargetForDecpIgnored =
new Kind("annotationAsTargetForDecpIgnored","annotation type {0} matches a declare parents type pattern but is being ignored");
public final Kind cantMatchArrayTypeOnVarargs =
new Kind("cantMatchArrayTypeOnVarargs","an array type as the last parameter in a signature does not match on the varargs declared method: {0}");
public final Kind adviceDidNotMatch =
new Kind("adviceDidNotMatch","advice defined in {0} has not been applied");
public final Kind invalidTargetForAnnotation =
new Kind("invalidTargetForAnnotation","{0} is not a valid target for annotation {1}, this annotation can only be applied to {2}");
public final Kind elementAlreadyAnnotated =
new Kind("elementAlreadyAnnotated","{0} - already has an annotation of type {1}, cannot add a second instance");
public final Kind runtimeExceptionNotSoftened =
new Kind("runtimeExceptionNotSoftened","{0} will not be softened as it is already a RuntimeException");
public final Kind uncheckedArgument =
new Kind("uncheckedArgument","unchecked match of {0} with {1} when argument is an instance of {2} at join point {3}");
public final Kind uncheckedAdviceConversion =
new Kind("uncheckedAdviceConversion","unchecked conversion when advice applied at shadow {0}, expected {1} but advice uses {2}");
public final Kind noGuardForLazyTjp =
new Kind("noGuardForLazyTjp","can not build thisJoinPoint lazily for this advice since it has no suitable guard. The advice applies at {0}");
public final Kind noExplicitConstructorCall =
new Kind("noExplicitConstructorCall","inter-type constructor does not contain explicit constructor call: field initializers in the target type will not be executed");
public final Kind aspectExcludedByConfiguration =
new Kind("aspectExcludedByConfiguration","aspect {0} exluded for class loader {1}");
public final Kind unorderedAdviceAtShadow =
new Kind("unorderedAdviceAtShadow","at this shadow {0} no precedence is specified between advice applying from aspect {1} and aspect {2}");
// there are a lot of messages in the cant find type family - I'm defining an umbrella lint warning that
// allows a user to control their severity (for e.g. ltw or binary weaving)
public final Kind cantFindType =
new Kind("cantFindType","{0}");
public final Kind cantFindTypeAffectingJoinPointMatch = new Kind("cantFindTypeAffectingJPMatch","{0}");
public Lint(World world) {
this.world = world;
}
public void setAll(String messageKind) {
setAll(getMessageKind(messageKind));
}
private void setAll(IMessage.Kind messageKind) {
for (Iterator i = kinds.values().iterator(); i.hasNext(); ) {
Kind kind = (Kind)i.next();
kind.setKind(messageKind);
}
}
public void setFromProperties(File file) {
try {
InputStream s = new FileInputStream(file);
setFromProperties(s);
} catch (IOException ioe) {
MessageUtil.error(world.getMessageHandler(),
WeaverMessages.format(WeaverMessages.XLINT_LOAD_ERROR,file.getPath(),ioe.getMessage()));
}
}
public void loadDefaultProperties() {
InputStream s = getClass().getResourceAsStream("XlintDefault.properties");
if (s == null) {
MessageUtil.warn(world.getMessageHandler(),
WeaverMessages.format(WeaverMessages.XLINTDEFAULT_LOAD_ERROR));
return;
}
try {
setFromProperties(s);
} catch (IOException ioe) {
MessageUtil.error(world.getMessageHandler(),
WeaverMessages.format(WeaverMessages.XLINTDEFAULT_LOAD_PROBLEM,ioe.getMessage()));
}
}
private void setFromProperties(InputStream s) throws IOException {
Properties p = new Properties();
p.load(s);
setFromProperties(p);
}
public void setFromProperties(Properties properties) {
for (Iterator i = properties.entrySet().iterator(); i.hasNext(); ) {
Map.Entry entry = (Map.Entry)i.next();
Kind kind = (Kind)kinds.get(entry.getKey());
if (kind == null) {
MessageUtil.error(world.getMessageHandler(),
WeaverMessages.format(WeaverMessages.XLINT_KEY_ERROR,entry.getKey()));
} else {
kind.setKind(getMessageKind((String)entry.getValue()));
}
}
}
public Collection allKinds() {
return kinds.values();
}
public Kind getLintKind(String name) {
return (Kind) kinds.get(name);
}
// temporarily suppress the given lint messages
public void suppressKinds(Collection lintKind) {
for (Iterator iter = lintKind.iterator(); iter.hasNext();) {
Kind k = (Kind) iter.next();
k.setSuppressed(true);
}
}
// remove any suppression of lint warnings in place
public void clearSuppressions() {
for (Iterator iter = kinds.values().iterator(); iter.hasNext();) {
Kind k = (Kind) iter.next();
k.setSuppressed(false);
}
}
private IMessage.Kind getMessageKind(String v) {
if (v.equals("ignore")) return null;
else if (v.equals("warning")) return IMessage.WARNING;
else if (v.equals("error")) return IMessage.ERROR;
MessageUtil.error(world.getMessageHandler(),
WeaverMessages.format(WeaverMessages.XLINT_VALUE_ERROR,v));
return null;
}
public class Kind {
private String name;
private String message;
private IMessage.Kind kind = IMessage.WARNING;
private boolean isSupressed = false; // by SuppressAjWarnings
public Kind(String name, String message) {
this.name = name;
this.message = message;
kinds.put(this.name, this);
}
public void setSuppressed(boolean shouldBeSuppressed) {
this.isSupressed = shouldBeSuppressed;
}
public boolean isEnabled() {
return (kind != null) && !isSupressed();
}
private boolean isSupressed() {
// can't suppress errors!
return isSupressed && (kind != IMessage.ERROR);
}
public String getName() {
return name;
}
public IMessage.Kind getKind() {
return kind;
}
public void setKind(IMessage.Kind kind) {
this.kind = kind;
}
public void signal(String info, ISourceLocation location) {
if (kind == null) return;
String text = MessageFormat.format(message, new Object[] {info} );
text += " [Xlint:" + name + "]";
world.getMessageHandler().handleMessage(new Message(text, kind, null, location));
}
public void signal(String[] infos, ISourceLocation location, ISourceLocation[] extraLocations) {
if (kind == null) return;
String text = MessageFormat.format(message, infos );
text += " [Xlint:" + name + "]";
world.getMessageHandler().handleMessage(
new Message(text, "", kind, location, null, extraLocations));
}
}
}
|
120,693 |
Bug 120693 Contribution: More Efficient Lint Warnings: ~15% Performance Increase
|
In profiling a load-time weaving configuration from HEAD, I found that 9% of total time (over 10% of weaving time) is spent in org.aspectj.weaver.Lint.clearSuppressions(), mostly from use inside BcelClassWeaver.match I made a small change in the parts of BcelAdvice that clear suppressions to save the list that was cleared and to only clear these. This alone saves about 15% of total CPU time in start up on my sample configuration.
|
resolved fixed
|
bdafe31
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2005-12-13T21:04:36Z | 2005-12-13T18:53:20Z |
weaver/src/org/aspectj/weaver/bcel/BcelAdvice.java
|
/* *******************************************************************
* Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC).
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* PARC initial implementation
* Alexandre Vasseur support for @AJ aspects
* ******************************************************************/
package org.aspectj.weaver.bcel;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Map;
import org.aspectj.apache.bcel.generic.InstructionConstants;
import org.aspectj.apache.bcel.generic.InstructionFactory;
import org.aspectj.apache.bcel.generic.InstructionHandle;
import org.aspectj.apache.bcel.generic.InstructionList;
import org.aspectj.bridge.ISourceLocation;
import org.aspectj.bridge.Message;
import org.aspectj.weaver.Advice;
import org.aspectj.weaver.AdviceKind;
import org.aspectj.weaver.AjAttribute;
import org.aspectj.weaver.BCException;
import org.aspectj.weaver.ISourceContext;
import org.aspectj.weaver.Member;
import org.aspectj.weaver.ResolvedMember;
import org.aspectj.weaver.ResolvedType;
import org.aspectj.weaver.Shadow;
import org.aspectj.weaver.ShadowMunger;
import org.aspectj.weaver.UnresolvedType;
import org.aspectj.weaver.WeaverMessages;
import org.aspectj.weaver.World;
import org.aspectj.weaver.ast.Literal;
import org.aspectj.weaver.ast.Test;
import org.aspectj.weaver.patterns.ExactTypePattern;
import org.aspectj.weaver.patterns.ExposedState;
import org.aspectj.weaver.patterns.PerClause;
import org.aspectj.weaver.patterns.Pointcut;
/**
* Advice implemented for bcel.
*
* @author Erik Hilsdale
* @author Jim Hugunin
*/
public class BcelAdvice extends Advice {
private Test pointcutTest;
private ExposedState exposedState;
private boolean hasMatchedAtLeastOnce = false;
public BcelAdvice(
AjAttribute.AdviceAttribute attribute,
Pointcut pointcut,
Member signature,
ResolvedType concreteAspect)
{
super(attribute, pointcut, signature);
this.concreteAspect = concreteAspect;
}
// !!! must only be used for testing
public BcelAdvice(AdviceKind kind, Pointcut pointcut, Member signature,
int extraArgumentFlags,
int start, int end, ISourceContext sourceContext, ResolvedType concreteAspect)
{
this(new AjAttribute.AdviceAttribute(kind, pointcut, extraArgumentFlags, start, end, sourceContext),
pointcut, signature, concreteAspect);
thrownExceptions = Collections.EMPTY_LIST; //!!! interaction with unit tests
}
// ---- implementations of ShadowMunger's methods
public ShadowMunger concretize(ResolvedType fromType, World world, PerClause clause) {
suppressLintWarnings(world);
ShadowMunger ret = super.concretize(fromType, world, clause);
clearLintSuppressions(world);
return ret;
}
public ShadowMunger parameterizeWith(ResolvedType declaringType,Map typeVariableMap) {
Pointcut pc = getPointcut().parameterizeWith(typeVariableMap);
BcelAdvice ret = null;
Member adviceSignature = signature;
// allows for around advice where the return value is a type variable (see pr115250)
if (signature instanceof ResolvedMember && signature.getDeclaringType().isGenericType()) {
adviceSignature = ((ResolvedMember)signature).parameterizedWith(declaringType.getTypeParameters(),declaringType,declaringType.isParameterizedType());
}
ret = new BcelAdvice(this.attribute,pc,adviceSignature,this.concreteAspect);
return ret;
}
public boolean match(Shadow shadow, World world) {
suppressLintWarnings(world);
boolean ret = super.match(shadow, world);
clearLintSuppressions(world);
return ret;
}
public void specializeOn(Shadow shadow) {
if (getKind() == AdviceKind.Around) {
((BcelShadow)shadow).initializeForAroundClosure();
}
//XXX this case is just here for supporting lazy test code
if (getKind() == null) {
exposedState = new ExposedState(0);
return;
}
if (getKind().isPerEntry()) {
exposedState = new ExposedState(0);
} else if (getKind().isCflow()) {
exposedState = new ExposedState(nFreeVars);
} else if (getSignature() != null) {
exposedState = new ExposedState(getSignature());
} else {
exposedState = new ExposedState(0);
return; //XXX this case is just here for supporting lazy test code
}
World world = shadow.getIWorld();
suppressLintWarnings(world);
pointcutTest = getPointcut().findResidue(shadow, exposedState);
clearLintSuppressions(world);
// these initializations won't be performed by findResidue, but need to be
// so that the joinpoint is primed for weaving
if (getKind() == AdviceKind.PerThisEntry) {
shadow.getThisVar();
} else if (getKind() == AdviceKind.PerTargetEntry) {
shadow.getTargetVar();
}
// make sure thisJoinPoint parameters are initialized
if ((getExtraParameterFlags() & ThisJoinPointStaticPart) != 0) {
((BcelShadow)shadow).getThisJoinPointStaticPartVar();
((BcelShadow)shadow).getEnclosingClass().warnOnAddedStaticInitializer(shadow,getSourceLocation());
}
if ((getExtraParameterFlags() & ThisJoinPoint) != 0) {
boolean hasGuardTest = pointcutTest != Literal.TRUE && getKind() != AdviceKind.Around;
boolean isAround = getKind() == AdviceKind.Around;
((BcelShadow)shadow).requireThisJoinPoint(hasGuardTest,isAround);
((BcelShadow)shadow).getEnclosingClass().warnOnAddedStaticInitializer(shadow,getSourceLocation());
if (!hasGuardTest && world.getLint().multipleAdviceStoppingLazyTjp.isEnabled()) {
// collect up the problematic advice
((BcelShadow)shadow).addAdvicePreventingLazyTjp(this);
}
if (!isAround && !hasGuardTest && world.getLint().noGuardForLazyTjp.isEnabled()) {
// can't build tjp lazily, no suitable test...
world.getLint().noGuardForLazyTjp.signal(
new String[] {shadow.toString()},
getSourceLocation(),
new ISourceLocation[] { ((BcelShadow)shadow).getSourceLocation() }
);
}
}
if ((getExtraParameterFlags() & ThisEnclosingJoinPointStaticPart) != 0) {
((BcelShadow)shadow).getThisEnclosingJoinPointStaticPartVar();
((BcelShadow)shadow).getEnclosingClass().warnOnAddedStaticInitializer(shadow,getSourceLocation());
}
}
private boolean canInline(Shadow s) {
if (attribute.isProceedInInners()) return false;
//XXX this guard seems to only be needed for bad test cases
if (concreteAspect == null || concreteAspect.isMissing()) return false;
if (concreteAspect.getWorld().isXnoInline()) return false;
//System.err.println("isWoven? " + ((BcelObjectType)concreteAspect).getLazyClassGen().getWeaverState());
return BcelWorld.getBcelObjectType(concreteAspect).getLazyClassGen().isWoven();
}
public void implementOn(Shadow s) {
hasMatchedAtLeastOnce=true;
BcelShadow shadow = (BcelShadow) s;
//FIXME AV - see #75442, this logic is not enough so for now comment it out until we fix the bug
// // callback for perObject AJC MightHaveAspect postMunge (#75442)
// if (getConcreteAspect() != null
// && getConcreteAspect().getPerClause() != null
// && PerClause.PEROBJECT.equals(getConcreteAspect().getPerClause().getKind())) {
// final PerObject clause;
// if (getConcreteAspect().getPerClause() instanceof PerFromSuper) {
// clause = (PerObject)((PerFromSuper) getConcreteAspect().getPerClause()).lookupConcretePerClause(getConcreteAspect());
// } else {
// clause = (PerObject) getConcreteAspect().getPerClause();
// }
// if (clause.isThis()) {
// PerObjectInterfaceTypeMunger.registerAsAdvisedBy(s.getThisVar().getType(), getConcreteAspect());
// } else {
// PerObjectInterfaceTypeMunger.registerAsAdvisedBy(s.getTargetVar().getType(), getConcreteAspect());
// }
// }
if (getKind() == AdviceKind.Before) {
shadow.weaveBefore(this);
} else if (getKind() == AdviceKind.AfterReturning) {
shadow.weaveAfterReturning(this);
} else if (getKind() == AdviceKind.AfterThrowing) {
UnresolvedType catchType =
hasExtraParameter()
? getExtraParameterType()
: UnresolvedType.THROWABLE;
shadow.weaveAfterThrowing(this, catchType);
} else if (getKind() == AdviceKind.After) {
shadow.weaveAfter(this);
} else if (getKind() == AdviceKind.Around) {
// Note: under regular LTW the aspect is usually loaded after the first use of any class affecteted by it
// This means that as long as the aspect has not been thru the LTW, it's woven state is unknown
// and thus canInline(s) will return false.
// To force inlining (test), ones can do Class aspect = FQNAspect.class in the clinit of the target class
// FIXME AV : for AJC compiled @AJ aspect (or any code style aspect), the woven state can never be known
// if the aspect belongs to a parent classloader. In that case the aspect will never be inlined.
// It might be dangerous to change that especially for @AJ aspect non compiled with AJC since if those
// are not weaved (f.e. use of some limiteed LTW etc) then they cannot be prepared for inlining.
// One solution would be to flag @AJ aspect with an annotation as "prepared" and query that one.
if (!canInline(s)) {
shadow.weaveAroundClosure(this, hasDynamicTests());
} else {
shadow.weaveAroundInline(this, hasDynamicTests());
}
} else if (getKind() == AdviceKind.InterInitializer) {
shadow.weaveAfterReturning(this);
} else if (getKind().isCflow()) {
shadow.weaveCflowEntry(this, getSignature());
} else if (getKind() == AdviceKind.PerThisEntry) {
shadow.weavePerObjectEntry(this, (BcelVar)shadow.getThisVar());
} else if (getKind() == AdviceKind.PerTargetEntry) {
shadow.weavePerObjectEntry(this, (BcelVar)shadow.getTargetVar());
} else if (getKind() == AdviceKind.Softener) {
shadow.weaveSoftener(this, ((ExactTypePattern)exceptionType).getType());
} else if (getKind() == AdviceKind.PerTypeWithinEntry) {
// PTWIMPL Entry to ptw is the static initialization of a type that matched the ptw type pattern
shadow.weavePerTypeWithinAspectInitialization(this,shadow.getEnclosingType());
} else {
throw new BCException("unimplemented kind: " + getKind());
}
}
// ---- implementations
private Collection collectCheckedExceptions(UnresolvedType[] excs) {
if (excs == null || excs.length == 0) return Collections.EMPTY_LIST;
Collection ret = new ArrayList();
World world = concreteAspect.getWorld();
ResolvedType runtimeException = world.getCoreType(UnresolvedType.RUNTIME_EXCEPTION);
ResolvedType error = world.getCoreType(UnresolvedType.ERROR);
for (int i=0, len=excs.length; i < len; i++) {
ResolvedType t = world.resolve(excs[i],true);
if (t.isMissing()) {
world.getLint().cantFindType.signal(
WeaverMessages.format(WeaverMessages.CANT_FIND_TYPE_EXCEPTION_TYPE,excs[i].getName()),
getSourceLocation()
);
// IMessage msg = new Message(
// WeaverMessages.format(WeaverMessages.CANT_FIND_TYPE_EXCEPTION_TYPE,excs[i].getName()),
// "",IMessage.ERROR,getSourceLocation(),null,null);
// world.getMessageHandler().handleMessage(msg);
}
if (!(runtimeException.isAssignableFrom(t) || error.isAssignableFrom(t))) {
ret.add(t);
}
}
return ret;
}
private Collection thrownExceptions = null;
public Collection getThrownExceptions() {
if (thrownExceptions == null) {
//??? can we really lump in Around here, how does this interact with Throwable
if (concreteAspect != null && concreteAspect.getWorld() != null && // null tests for test harness
(getKind().isAfter() || getKind() == AdviceKind.Before || getKind() == AdviceKind.Around))
{
World world = concreteAspect.getWorld();
ResolvedMember m = world.resolve(signature);
if (m == null) {
thrownExceptions = Collections.EMPTY_LIST;
} else {
thrownExceptions = collectCheckedExceptions(m.getExceptions());
}
} else {
thrownExceptions = Collections.EMPTY_LIST;
}
}
return thrownExceptions;
}
/**
* The munger must not check for the advice exceptions to be declared by the shadow in the case
* of @AJ aspects so that around can throws Throwable
*
* @return
*/
public boolean mustCheckExceptions() {
if (getConcreteAspect() == null) {
return true;
}
return !getConcreteAspect().isAnnotationStyleAspect();
}
// only call me after prepare has been called
public boolean hasDynamicTests() {
// if (hasExtraParameter() && getKind() == AdviceKind.AfterReturning) {
// UnresolvedType extraParameterType = getExtraParameterType();
// if (! extraParameterType.equals(UnresolvedType.OBJECT)
// && ! extraParameterType.isPrimitive())
// return true;
// }
return pointcutTest != null &&
!(pointcutTest == Literal.TRUE);// || pointcutTest == Literal.NO_TEST);
}
/**
* get the instruction list for the really simple version of this advice.
* Is broken apart
* for other advice, but if you want it in one block, this is the method to call.
*
* @param s The shadow around which these instructions will eventually live.
* @param extraArgVar The var that will hold the return value or thrown exception
* for afterX advice
* @param ifNoAdvice The instructionHandle to jump to if the dynamic
* tests for this munger fails.
*/
InstructionList getAdviceInstructions(
BcelShadow s,
BcelVar extraArgVar,
InstructionHandle ifNoAdvice)
{
BcelShadow shadow = (BcelShadow) s;
InstructionFactory fact = shadow.getFactory();
BcelWorld world = shadow.getWorld();
InstructionList il = new InstructionList();
// we test to see if we have the right kind of thing...
// after throwing does this just by the exception mechanism.
if (hasExtraParameter() && getKind() == AdviceKind.AfterReturning) {
UnresolvedType extraParameterType = getExtraParameterType();
if (! extraParameterType.equals(UnresolvedType.OBJECT)
&& ! extraParameterType.isPrimitiveType()) {
il.append(
BcelRenderer.renderTest(
fact,
world,
Test.makeInstanceof(
extraArgVar, getExtraParameterType().resolve(world)),
null,
ifNoAdvice,
null));
}
}
il.append(getAdviceArgSetup(shadow, extraArgVar, null));
il.append(getNonTestAdviceInstructions(shadow));
InstructionHandle ifYesAdvice = il.getStart();
il.insert(getTestInstructions(shadow, ifYesAdvice, ifNoAdvice, ifYesAdvice));
return il;
}
public InstructionList getAdviceArgSetup(
BcelShadow shadow,
BcelVar extraVar,
InstructionList closureInstantiation)
{
InstructionFactory fact = shadow.getFactory();
BcelWorld world = shadow.getWorld();
InstructionList il = new InstructionList();
// if (targetAspectField != null) {
// il.append(fact.createFieldAccess(
// targetAspectField.getDeclaringType().getName(),
// targetAspectField.getName(),
// BcelWorld.makeBcelType(targetAspectField.getType()),
// Constants.GETSTATIC));
// }
//
//System.err.println("BcelAdvice: " + exposedState);
if (exposedState.getAspectInstance() != null) {
il.append(BcelRenderer.renderExpr(fact, world, exposedState.getAspectInstance()));
}
final boolean isAnnotationStyleAspect = getConcreteAspect()!=null && getConcreteAspect().isAnnotationStyleAspect();
boolean previousIsClosure = false;
for (int i = 0, len = exposedState.size(); i < len; i++) {
if (exposedState.isErroneousVar(i)) continue; // Erroneous vars have already had error msgs reported!
BcelVar v = (BcelVar) exposedState.get(i);
if (v == null) {
// if not @AJ aspect, go on with the regular binding handling
if (!isAnnotationStyleAspect) {
;
} else {
// ATAJ: for @AJ aspects, handle implicit binding of xxJoinPoint
//if (getKind() == AdviceKind.Around) {
// previousIsClosure = true;
// il.append(closureInstantiation);
if ("Lorg/aspectj/lang/ProceedingJoinPoint;".equals(getSignature().getParameterTypes()[i].getSignature())) {
//make sure we are in an around, since we deal with the closure, not the arg here
if (getKind() != AdviceKind.Around) {
previousIsClosure = false;
getConcreteAspect().getWorld().getMessageHandler().handleMessage(
new Message(
"use of ProceedingJoinPoint is allowed only on around advice ("
+ "arg " + i + " in " + toString() + ")",
this.getSourceLocation(),
true
)
);
// try to avoid verify error and pass in null
il.append(InstructionConstants.ACONST_NULL);
} else {
if (previousIsClosure) {
il.append(InstructionConstants.DUP);
} else {
previousIsClosure = true;
il.append(closureInstantiation.copy());
}
}
} else if ("Lorg/aspectj/lang/JoinPoint$StaticPart;".equals(getSignature().getParameterTypes()[i].getSignature())) {
previousIsClosure = false;
if ((getExtraParameterFlags() & ThisJoinPointStaticPart) != 0) {
shadow.getThisJoinPointStaticPartBcelVar().appendLoad(il, fact);
}
} else if ("Lorg/aspectj/lang/JoinPoint;".equals(getSignature().getParameterTypes()[i].getSignature())) {
previousIsClosure = false;
if ((getExtraParameterFlags() & ThisJoinPoint) != 0) {
il.append(shadow.loadThisJoinPoint());
}
} else if ("Lorg/aspectj/lang/JoinPoint$EnclosingStaticPart;".equals(getSignature().getParameterTypes()[i].getSignature())) {
previousIsClosure = false;
if ((getExtraParameterFlags() & ThisEnclosingJoinPointStaticPart) != 0) {
shadow.getThisEnclosingJoinPointStaticPartBcelVar().appendLoad(il, fact);
}
} else if (hasExtraParameter()) {
previousIsClosure = false;
extraVar.appendLoadAndConvert(
il,
fact,
getExtraParameterType().resolve(world));
} else {
previousIsClosure = false;
getConcreteAspect().getWorld().getMessageHandler().handleMessage(
new Message(
"use of ProceedingJoinPoint is allowed only on around advice ("
+ "arg " + i + " in " + toString() + ")",
this.getSourceLocation(),
true
)
);
// try to avoid verify error and pass in null
il.append(InstructionConstants.ACONST_NULL);
}
}
} else {
UnresolvedType desiredTy = getBindingParameterTypes()[i];
v.appendLoadAndConvert(il, fact, desiredTy.resolve(world));
}
}
// ATAJ: for code style aspect, handles the extraFlag as usual ie not
// in the middle of the formal bindings but at the end, in a rock solid ordering
if (!isAnnotationStyleAspect) {
if (getKind() == AdviceKind.Around) {
il.append(closureInstantiation);
} else if (hasExtraParameter()) {
extraVar.appendLoadAndConvert(
il,
fact,
getExtraParameterType().resolve(world));
}
// handle thisJoinPoint parameters
// these need to be in that same order as parameters in
// org.aspectj.ajdt.internal.compiler.ast.AdviceDeclaration
if ((getExtraParameterFlags() & ThisJoinPointStaticPart) != 0) {
shadow.getThisJoinPointStaticPartBcelVar().appendLoad(il, fact);
}
if ((getExtraParameterFlags() & ThisJoinPoint) != 0) {
il.append(shadow.loadThisJoinPoint());
}
if ((getExtraParameterFlags() & ThisEnclosingJoinPointStaticPart) != 0) {
shadow.getThisEnclosingJoinPointStaticPartBcelVar().appendLoad(il, fact);
}
}
return il;
}
public InstructionList getNonTestAdviceInstructions(BcelShadow shadow) {
return new InstructionList(
Utility.createInvoke(shadow.getFactory(), shadow.getWorld(), getOriginalSignature()));
}
public Member getOriginalSignature() {
Member sig = getSignature();
if (sig instanceof ResolvedMember) {
ResolvedMember rsig = (ResolvedMember)sig;
if (rsig.hasBackingGenericMember()) return rsig.getBackingGenericMember();
}
return sig;
}
public InstructionList getTestInstructions(
BcelShadow shadow,
InstructionHandle sk,
InstructionHandle fk,
InstructionHandle next)
{
//System.err.println("test: " + pointcutTest);
return BcelRenderer.renderTest(
shadow.getFactory(),
shadow.getWorld(),
pointcutTest,
sk,
fk,
next);
}
public int compareTo(Object other) {
if (!(other instanceof BcelAdvice)) return 0;
BcelAdvice o = (BcelAdvice)other;
//System.err.println("compareTo: " + this + ", " + o);
if (kind.getPrecedence() != o.kind.getPrecedence()) {
if (kind.getPrecedence() > o.kind.getPrecedence()) return +1;
else return -1;
}
if (kind.isCflow()) {
// System.err.println("sort: " + this + " innerCflowEntries " + innerCflowEntries);
// System.err.println(" " + o + " innerCflowEntries " + o.innerCflowEntries);
boolean isBelow = (kind == AdviceKind.CflowBelowEntry);
if (this.innerCflowEntries.contains(o)) return isBelow ? +1 : -1;
else if (o.innerCflowEntries.contains(this)) return isBelow ? -1 : +1;
else return 0;
}
if (kind.isPerEntry() || kind == AdviceKind.Softener) {
return 0;
}
//System.out.println("compare: " + this + " with " + other);
World world = concreteAspect.getWorld();
int ret =
concreteAspect.getWorld().compareByPrecedence(
concreteAspect,
o.concreteAspect);
if (ret != 0) return ret;
ResolvedType declaringAspect = getDeclaringAspect().resolve(world);
ResolvedType o_declaringAspect = o.getDeclaringAspect().resolve(world);
if (declaringAspect == o_declaringAspect) {
if (kind.isAfter() || o.kind.isAfter()) {
return this.getStart() < o.getStart() ? -1: +1;
} else {
return this.getStart()< o.getStart() ? +1: -1;
}
} else if (declaringAspect.isAssignableFrom(o_declaringAspect)) {
return -1;
} else if (o_declaringAspect.isAssignableFrom(declaringAspect)) {
return +1;
} else {
return 0;
}
}
public BcelVar[] getExposedStateAsBcelVars(boolean isAround) {
// ATAJ aspect
if (isAround) {
// the closure instantiation has the same mapping as the extracted method from wich it is called
if (getConcreteAspect()!= null && getConcreteAspect().isAnnotationStyleAspect()) {
return BcelVar.NONE;
}
}
//System.out.println("vars: " + Arrays.asList(exposedState.vars));
if (exposedState == null) return BcelVar.NONE;
int len = exposedState.vars.length;
BcelVar[] ret = new BcelVar[len];
for (int i=0; i < len; i++) {
ret[i] = (BcelVar)exposedState.vars[i];
}
return ret; //(BcelVar[]) exposedState.vars;
}
public boolean hasMatchedSomething() {
return hasMatchedAtLeastOnce;
}
protected void suppressLintWarnings(World inWorld) {
if (suppressedLintKinds == null) {
if (signature instanceof BcelMethod) {
this.suppressedLintKinds = Utility.getSuppressedWarnings(signature.getAnnotations(), inWorld.getLint());
} else {
this.suppressedLintKinds = Collections.EMPTY_LIST;
}
}
inWorld.getLint().suppressKinds(suppressedLintKinds);
}
protected void clearLintSuppressions(World inWorld) {
inWorld.getLint().clearSuppressions();
}
}
|
120,743 |
Bug 120743 Improvements to define new server wizard page
|
On the panel where the server location and button to install the server is shown, a couple of usability improvements could be made... (1) If I choose browse and choose a location. Then hit install server, the fs browser should not be brought back up since I have already hitten browse and selected a location. (2) If (1) and the location chosen contains no server, and the server is downlodable, classpath validation errors should not show, but a message stating that no server is found but can be installed by selecting the install server button.
|
closed wontfix
|
588e7b9
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2005-12-13T22:23:24Z | 2005-12-13T21:40: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);
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) {
// 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();
}
}
|
120,909 |
Bug 120909 Test failures using IBM Java 5
|
1. ReflectionBasedReferenceTypeDelegateTest.testCompareSubclassDelegates() junit.framework.AssertionFailedError: Errors:Couldn't find void java.util.HashMap.onEntry() in the bcel set Couldn't find void java.util.HashMap.onExit() in the bcel set Couldn't find void java.util.HashMap.transfer0(java.util.HashMap$Entry[]) in the bcel set at junit.framework.Assert.fail(Assert.java:47) at junit.framework.Assert.assertTrue(Assert.java:20) at org.aspectj.weaver.reflect.ReflectionBasedReferenceTypeDelegateTest.testCompareSubclassDelegates(ReflectionBasedReferenceTypeDelegateTest.java:278) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:64) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:615) 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 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) This failure occures because when we compare BeclWorld with ReflectionWorld we are still picking up the default (Sun) version of HashMap in JRE15_LIB for BCEL. The solution is to create both worlds with the same class loader. 2. Ajc150Tests.testModifierOverrides() junit.framework.AssertionFailedError: Expecting output: execution(void pr119749.C.m()): execMe[@pr119749$Me()] execution(void pr119749.C.m()): execEx But found output: execution(void pr119749.C.m()): execMe[@pr119749.Me()] execution(void pr119749.C.m()): execEx First difference is on line 1 at junit.framework.Assert.fail(Assert.java:47) at org.aspectj.testing.OutputSpec.matchAgainst(OutputSpec.java:58) at org.aspectj.testing.RunSpec.execute(RunSpec.java:61) at org.aspectj.testing.AjcTest.runTest(AjcTest.java:68) at org.aspectj.testing.XMLBasedAjcTestCase.runTest(XMLBasedAjcTestCase.java:111) at org.aspectj.systemtest.ajc150.Ajc150Tests.testModifierOverrides(Ajc150Tests.java:852) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:64) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:615) 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 junit.extensions.TestDecorator.basicRun(TestDecorator.java:22) at junit.extensions.TestSetup$1.protect(TestSetup.java:19) at junit.framework.TestResult.runProtected(TestResult.java:124) at junit.extensions.TestSetup.run(TestSetup.java:23) 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 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) This failure is due a difference between JDKs in the implementation of toString() for annotations.
|
resolved fixed
|
9abfc40
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2005-12-15T15:57:36Z | 2005-12-14T17:06:40Z |
loadtime/src/org/aspectj/weaver/loadtime/DefaultWeavingContext.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:
* David Knibb initial implementation
*******************************************************************************/
package org.aspectj.weaver.loadtime;
import java.io.IOException;
import java.net.URL;
import java.util.Enumeration;
/**
* Use in non-OSGi environment
*
* @author David Knibb
*/
public class DefaultWeavingContext implements IWeavingContext {
protected ClassLoader loader;
public DefaultWeavingContext(){
loader = getClass().getClassLoader();
}
/**
* Construct a new WeavingContext to use the specifed ClassLoader
* This is the constructor which should be used.
* @param loader
*/
public DefaultWeavingContext(ClassLoader loader) {
this.loader = loader;
}
/**
* Same as ClassLoader.getResources()
*/
public Enumeration getResources(String name) throws IOException {
return loader.getResources(name);
}
/**
* @return null as we are not in an OSGi environment (therefore no bundles)
*/
public String getBundleIdFromURL(URL url) {
return null;
}
/**
* @return classname@hashcode
*/
public String getClassLoaderName() {
return ((loader!=null)?loader.getClass().getName()+"@"+loader.hashCode():"null");
}
}
|
120,909 |
Bug 120909 Test failures using IBM Java 5
|
1. ReflectionBasedReferenceTypeDelegateTest.testCompareSubclassDelegates() junit.framework.AssertionFailedError: Errors:Couldn't find void java.util.HashMap.onEntry() in the bcel set Couldn't find void java.util.HashMap.onExit() in the bcel set Couldn't find void java.util.HashMap.transfer0(java.util.HashMap$Entry[]) in the bcel set at junit.framework.Assert.fail(Assert.java:47) at junit.framework.Assert.assertTrue(Assert.java:20) at org.aspectj.weaver.reflect.ReflectionBasedReferenceTypeDelegateTest.testCompareSubclassDelegates(ReflectionBasedReferenceTypeDelegateTest.java:278) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:64) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:615) 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 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) This failure occures because when we compare BeclWorld with ReflectionWorld we are still picking up the default (Sun) version of HashMap in JRE15_LIB for BCEL. The solution is to create both worlds with the same class loader. 2. Ajc150Tests.testModifierOverrides() junit.framework.AssertionFailedError: Expecting output: execution(void pr119749.C.m()): execMe[@pr119749$Me()] execution(void pr119749.C.m()): execEx But found output: execution(void pr119749.C.m()): execMe[@pr119749.Me()] execution(void pr119749.C.m()): execEx First difference is on line 1 at junit.framework.Assert.fail(Assert.java:47) at org.aspectj.testing.OutputSpec.matchAgainst(OutputSpec.java:58) at org.aspectj.testing.RunSpec.execute(RunSpec.java:61) at org.aspectj.testing.AjcTest.runTest(AjcTest.java:68) at org.aspectj.testing.XMLBasedAjcTestCase.runTest(XMLBasedAjcTestCase.java:111) at org.aspectj.systemtest.ajc150.Ajc150Tests.testModifierOverrides(Ajc150Tests.java:852) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:64) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:615) 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 junit.extensions.TestDecorator.basicRun(TestDecorator.java:22) at junit.extensions.TestSetup$1.protect(TestSetup.java:19) at junit.framework.TestResult.runProtected(TestResult.java:124) at junit.extensions.TestSetup.run(TestSetup.java:23) 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 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) This failure is due a difference between JDKs in the implementation of toString() for annotations.
|
resolved fixed
|
9abfc40
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2005-12-15T15:57:36Z | 2005-12-14T17:06:40Z |
weaver/src/org/aspectj/weaver/reflect/ReflectionWorld.java
|
/* *******************************************************************
* Copyright (c) 2005 Contributors.
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Eclipse Public License v1.0
* which accompanies this distribution and is available at
* http://eclipse.org/legal/epl-v10.html
*
* Contributors:
* Adrian Colyer Initial implementation
* ******************************************************************/
package org.aspectj.weaver.reflect;
import org.aspectj.bridge.AbortException;
import org.aspectj.bridge.IMessage;
import org.aspectj.bridge.IMessageHandler;
import org.aspectj.util.LangUtil;
import org.aspectj.weaver.Advice;
import org.aspectj.weaver.BCException;
import org.aspectj.weaver.ConcreteTypeMunger;
import org.aspectj.weaver.Member;
import org.aspectj.weaver.ReferenceType;
import org.aspectj.weaver.ReferenceTypeDelegate;
import org.aspectj.weaver.ResolvedMember;
import org.aspectj.weaver.ResolvedType;
import org.aspectj.weaver.ResolvedTypeMunger;
import org.aspectj.weaver.UnresolvedType;
import org.aspectj.weaver.World;
import org.aspectj.weaver.AjAttribute.AdviceAttribute;
import org.aspectj.weaver.patterns.Pointcut;
import org.aspectj.weaver.patterns.PerClause.Kind;
/**
* A ReflectionWorld is used solely for purposes of type resolution based on
* the runtime classpath (java.lang.reflect). It does not support weaving operations
* (creation of mungers etc..).
*
*/
public class ReflectionWorld extends World {
private ClassLoader classLoader;
private AnnotationFinder annotationFinder;
public ReflectionWorld() {
super();
this.setMessageHandler(new ExceptionBasedMessageHandler());
setBehaveInJava5Way(LangUtil.is15VMOrGreater());
this.classLoader = ReflectionWorld.class.getClassLoader();
if (LangUtil.is15VMOrGreater()) {
initializeAnnotationFinder(this.classLoader);
}
}
public ReflectionWorld(ClassLoader aClassLoader) {
super();
this.setMessageHandler(new ExceptionBasedMessageHandler());
setBehaveInJava5Way(LangUtil.is15VMOrGreater());
this.classLoader = aClassLoader;
if (LangUtil.is15VMOrGreater()) {
initializeAnnotationFinder(this.classLoader);
}
}
private void initializeAnnotationFinder(ClassLoader loader) {
try {
Class java15AnnotationFinder = Class.forName("org.aspectj.weaver.reflect.Java15AnnotationFinder");
this.annotationFinder = (AnnotationFinder) java15AnnotationFinder.newInstance();
this.annotationFinder.setClassLoader(loader);
this.annotationFinder.setWorld(this);
} catch(ClassNotFoundException ex) {
// must be on 1.4 or earlier
} catch(IllegalAccessException ex) {
// not so good
throw new BCException("AspectJ internal error",ex);
} catch(InstantiationException ex) {
throw new BCException("AspectJ internal error",ex);
}
}
public ClassLoader getClassLoader() {
return this.classLoader;
}
public AnnotationFinder getAnnotationFinder() {
return this.annotationFinder;
}
public ResolvedType resolve(Class aClass) {
// classes that represent arrays return a class name that is the signature of the array type, ho-hum...
String className = aClass.getName();
if (aClass.isArray()) {
return resolve(UnresolvedType.forSignature(className));
}
else{
return resolve(className);
}
}
/* (non-Javadoc)
* @see org.aspectj.weaver.World#resolveDelegate(org.aspectj.weaver.ReferenceType)
*/
protected ReferenceTypeDelegate resolveDelegate(ReferenceType ty) {
return ReflectionBasedReferenceTypeDelegateFactory.createDelegate(ty, this, this.classLoader);
}
/* (non-Javadoc)
* @see org.aspectj.weaver.World#createAdviceMunger(org.aspectj.weaver.AjAttribute.AdviceAttribute, org.aspectj.weaver.patterns.Pointcut, org.aspectj.weaver.Member)
*/
public Advice createAdviceMunger(AdviceAttribute attribute,
Pointcut pointcut, Member signature) {
throw new UnsupportedOperationException("Cannot create advice munger in ReflectionWorld");
}
/* (non-Javadoc)
* @see org.aspectj.weaver.World#makeCflowStackFieldAdder(org.aspectj.weaver.ResolvedMember)
*/
public ConcreteTypeMunger makeCflowStackFieldAdder(ResolvedMember cflowField) {
throw new UnsupportedOperationException("Cannot create cflow stack in ReflectionWorld");
}
/* (non-Javadoc)
* @see org.aspectj.weaver.World#makeCflowCounterFieldAdder(org.aspectj.weaver.ResolvedMember)
*/
public ConcreteTypeMunger makeCflowCounterFieldAdder(
ResolvedMember cflowField) {
throw new UnsupportedOperationException("Cannot create cflow counter in ReflectionWorld");
}
/* (non-Javadoc)
* @see org.aspectj.weaver.World#makePerClauseAspect(org.aspectj.weaver.ResolvedType, org.aspectj.weaver.patterns.PerClause.Kind)
*/
public ConcreteTypeMunger makePerClauseAspect(ResolvedType aspect, Kind kind) {
throw new UnsupportedOperationException("Cannot create per clause in ReflectionWorld");
}
/* (non-Javadoc)
* @see org.aspectj.weaver.World#concreteTypeMunger(org.aspectj.weaver.ResolvedTypeMunger, org.aspectj.weaver.ResolvedType)
*/
public ConcreteTypeMunger concreteTypeMunger(ResolvedTypeMunger munger,
ResolvedType aspectType) {
throw new UnsupportedOperationException("Cannot create type munger in ReflectionWorld");
}
public static class ReflectionWorldException extends RuntimeException {
private static final long serialVersionUID = -3432261918302793005L;
public ReflectionWorldException(String message) {
super(message);
}
}
private static class ExceptionBasedMessageHandler implements IMessageHandler {
public boolean handleMessage(IMessage message) throws AbortException {
throw new ReflectionWorldException(message.toString());
}
public boolean isIgnoring(org.aspectj.bridge.IMessage.Kind kind) {
if (kind == IMessage.INFO) {
return true;
} else {
return false;
}
}
public void dontIgnore(org.aspectj.bridge.IMessage.Kind kind) {
// empty
}
}
}
|
120,909 |
Bug 120909 Test failures using IBM Java 5
|
1. ReflectionBasedReferenceTypeDelegateTest.testCompareSubclassDelegates() junit.framework.AssertionFailedError: Errors:Couldn't find void java.util.HashMap.onEntry() in the bcel set Couldn't find void java.util.HashMap.onExit() in the bcel set Couldn't find void java.util.HashMap.transfer0(java.util.HashMap$Entry[]) in the bcel set at junit.framework.Assert.fail(Assert.java:47) at junit.framework.Assert.assertTrue(Assert.java:20) at org.aspectj.weaver.reflect.ReflectionBasedReferenceTypeDelegateTest.testCompareSubclassDelegates(ReflectionBasedReferenceTypeDelegateTest.java:278) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:64) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:615) 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 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) This failure occures because when we compare BeclWorld with ReflectionWorld we are still picking up the default (Sun) version of HashMap in JRE15_LIB for BCEL. The solution is to create both worlds with the same class loader. 2. Ajc150Tests.testModifierOverrides() junit.framework.AssertionFailedError: Expecting output: execution(void pr119749.C.m()): execMe[@pr119749$Me()] execution(void pr119749.C.m()): execEx But found output: execution(void pr119749.C.m()): execMe[@pr119749.Me()] execution(void pr119749.C.m()): execEx First difference is on line 1 at junit.framework.Assert.fail(Assert.java:47) at org.aspectj.testing.OutputSpec.matchAgainst(OutputSpec.java:58) at org.aspectj.testing.RunSpec.execute(RunSpec.java:61) at org.aspectj.testing.AjcTest.runTest(AjcTest.java:68) at org.aspectj.testing.XMLBasedAjcTestCase.runTest(XMLBasedAjcTestCase.java:111) at org.aspectj.systemtest.ajc150.Ajc150Tests.testModifierOverrides(Ajc150Tests.java:852) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:64) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:615) 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 junit.extensions.TestDecorator.basicRun(TestDecorator.java:22) at junit.extensions.TestSetup$1.protect(TestSetup.java:19) at junit.framework.TestResult.runProtected(TestResult.java:124) at junit.extensions.TestSetup.run(TestSetup.java:23) 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 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) This failure is due a difference between JDKs in the implementation of toString() for annotations.
|
resolved fixed
|
9abfc40
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2005-12-15T15:57:36Z | 2005-12-14T17:06:40Z |
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.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();
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();
objectType = world.resolve("java.lang.Object");
}
}
|
120,909 |
Bug 120909 Test failures using IBM Java 5
|
1. ReflectionBasedReferenceTypeDelegateTest.testCompareSubclassDelegates() junit.framework.AssertionFailedError: Errors:Couldn't find void java.util.HashMap.onEntry() in the bcel set Couldn't find void java.util.HashMap.onExit() in the bcel set Couldn't find void java.util.HashMap.transfer0(java.util.HashMap$Entry[]) in the bcel set at junit.framework.Assert.fail(Assert.java:47) at junit.framework.Assert.assertTrue(Assert.java:20) at org.aspectj.weaver.reflect.ReflectionBasedReferenceTypeDelegateTest.testCompareSubclassDelegates(ReflectionBasedReferenceTypeDelegateTest.java:278) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:64) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:615) 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 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) This failure occures because when we compare BeclWorld with ReflectionWorld we are still picking up the default (Sun) version of HashMap in JRE15_LIB for BCEL. The solution is to create both worlds with the same class loader. 2. Ajc150Tests.testModifierOverrides() junit.framework.AssertionFailedError: Expecting output: execution(void pr119749.C.m()): execMe[@pr119749$Me()] execution(void pr119749.C.m()): execEx But found output: execution(void pr119749.C.m()): execMe[@pr119749.Me()] execution(void pr119749.C.m()): execEx First difference is on line 1 at junit.framework.Assert.fail(Assert.java:47) at org.aspectj.testing.OutputSpec.matchAgainst(OutputSpec.java:58) at org.aspectj.testing.RunSpec.execute(RunSpec.java:61) at org.aspectj.testing.AjcTest.runTest(AjcTest.java:68) at org.aspectj.testing.XMLBasedAjcTestCase.runTest(XMLBasedAjcTestCase.java:111) at org.aspectj.systemtest.ajc150.Ajc150Tests.testModifierOverrides(Ajc150Tests.java:852) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:64) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:615) 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 junit.extensions.TestDecorator.basicRun(TestDecorator.java:22) at junit.extensions.TestSetup$1.protect(TestSetup.java:19) at junit.framework.TestResult.runProtected(TestResult.java:124) at junit.extensions.TestSetup.run(TestSetup.java:23) 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 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) This failure is due a difference between JDKs in the implementation of toString() for annotations.
|
resolved fixed
|
9abfc40
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2005-12-15T15:57:36Z | 2005-12-14T17:06:40Z |
weaver/testsrc/org/aspectj/weaver/reflect/ReflectionWorldTest.java
|
/* *******************************************************************
* Copyright (c) 2005 Contributors.
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Eclipse Public License v1.0
* which accompanies this distribution and is available at
* http://eclipse.org/legal/epl-v10.html
*
* Contributors:
* Adrian Colyer Initial implementation
* ******************************************************************/
package org.aspectj.weaver.reflect;
import junit.framework.TestCase;
import org.aspectj.weaver.ResolvedType;
import org.aspectj.weaver.World;
public class ReflectionWorldTest extends TestCase {
public void testDelegateCreation() {
World world = new ReflectionWorld();
ResolvedType rt = world.resolve("java.lang.Object");
assertNotNull(rt);
assertEquals("Ljava/lang/Object;",rt.getSignature());
}
public void testArrayTypes() {
ReflectionWorld world = new ReflectionWorld();
String[] strArray = new String[1];
ResolvedType rt = world.resolve(strArray.getClass());
assertTrue(rt.isArray());
}
public void testPrimitiveTypes() {
ReflectionWorld world = new ReflectionWorld();
assertEquals("int",ResolvedType.INT,world.resolve(int.class));
assertEquals("void",ResolvedType.VOID,world.resolve(void.class));
}
}
|
58,520 |
Bug 58520 ajdoc doesn't navigate to target details in some cases
|
When a file is advised, javadoc uses the following naming convention for setting its "A NAME": convertCheckedException(java.lang.Throwable) However, ajdoc uses the unqualified name for the argument, resuting in the follwing in-file anchor link: <class-name>.html#convertCheckedException(Throwable) Which fails to navigate to the anchor within the file, although it does always go to the right file.
|
resolved fixed
|
bbdd496
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2005-12-21T10:37:43Z | 2004-04-14T16:26:40Z |
ajdoc/testdata/pr119453/src/pack/C.java
|
package pack;
public class C {
public int x = 2;
void method() {
}
public String method1() {
return "";
}
private String method2(){
return "";
}
}
|
58,520 |
Bug 58520 ajdoc doesn't navigate to target details in some cases
|
When a file is advised, javadoc uses the following naming convention for setting its "A NAME": convertCheckedException(java.lang.Throwable) However, ajdoc uses the unqualified name for the argument, resuting in the follwing in-file anchor link: <class-name>.html#convertCheckedException(Throwable) Which fails to navigate to the anchor within the file, although it does always go to the right file.
|
resolved fixed
|
bbdd496
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2005-12-21T10:37:43Z | 2004-04-14T16:26:40Z |
ajdoc/testsrc/org/aspectj/tools/ajdoc/AjdocTests.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:
* Wes Isberg initial implementation
* ******************************************************************/
package org.aspectj.tools.ajdoc;
import java.io.File;
import org.aspectj.util.FileUtil;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
public class AjdocTests extends TestCase {
public static File ASPECTJRT_PATH;
static {
String[] paths = { "sp:aspectjrt.path", "sp:aspectjrt.jar",
"../lib/test/aspectjrt.jar", "../aj-build/jars/aspectj5rt-all.jar",
"../aj-build/jars/runtime.jar",
"../runtime/bin"};
ASPECTJRT_PATH = FileUtil.getBestFile(paths);
}
public static Test suite() {
TestSuite suite = new TestSuite(AjdocTests.class.getName());
//$JUnit-BEGIN$
suite.addTestSuite(DeclareFormsTest.class);
suite.addTestSuite(SpacewarTestCase.class);
suite.addTestSuite(PatternsTestCase.class);
suite.addTestSuite(CoverageTestCase.class);
suite.addTestSuite(ITDTest.class);
suite.addTestSuite(ExecutionTestCase.class);// !!! must be last because it exists
//$JUnit-END$
return suite;
}
}
|
58,520 |
Bug 58520 ajdoc doesn't navigate to target details in some cases
|
When a file is advised, javadoc uses the following naming convention for setting its "A NAME": convertCheckedException(java.lang.Throwable) However, ajdoc uses the unqualified name for the argument, resuting in the follwing in-file anchor link: <class-name>.html#convertCheckedException(Throwable) Which fails to navigate to the anchor within the file, although it does always go to the right file.
|
resolved fixed
|
bbdd496
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2005-12-21T10:37:43Z | 2004-04-14T16:26:40Z |
ajdoc/testsrc/org/aspectj/tools/ajdoc/FullyQualifiedArgumentTest.java
| |
58,520 |
Bug 58520 ajdoc doesn't navigate to target details in some cases
|
When a file is advised, javadoc uses the following naming convention for setting its "A NAME": convertCheckedException(java.lang.Throwable) However, ajdoc uses the unqualified name for the argument, resuting in the follwing in-file anchor link: <class-name>.html#convertCheckedException(Throwable) Which fails to navigate to the anchor within the file, although it does always go to the right file.
|
resolved fixed
|
bbdd496
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2005-12-21T10:37:43Z | 2004-04-14T16:26:40Z |
org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/core/builder/AsmElementFormatter.java
|
/* *******************************************************************
* Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC).
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* PARC initial implementation
* Alexandre Vasseur support for @AJ style
* ******************************************************************/
package org.aspectj.ajdt.internal.core.builder;
import java.util.ArrayList;
import java.util.List;
import org.aspectj.ajdt.internal.compiler.ast.AdviceDeclaration;
import org.aspectj.ajdt.internal.compiler.ast.DeclareDeclaration;
import org.aspectj.ajdt.internal.compiler.ast.InterTypeConstructorDeclaration;
import org.aspectj.ajdt.internal.compiler.ast.InterTypeDeclaration;
import org.aspectj.ajdt.internal.compiler.ast.InterTypeFieldDeclaration;
import org.aspectj.ajdt.internal.compiler.ast.InterTypeMethodDeclaration;
import org.aspectj.ajdt.internal.compiler.ast.PointcutDeclaration;
import org.aspectj.ajdt.internal.compiler.lookup.AjLookupEnvironment;
import org.aspectj.asm.IProgramElement;
import org.aspectj.weaver.AdviceKind;
import org.aspectj.weaver.ResolvedType;
import org.aspectj.weaver.UnresolvedType;
import org.aspectj.weaver.patterns.AndPointcut;
import org.aspectj.weaver.patterns.DeclareAnnotation;
import org.aspectj.weaver.patterns.DeclareErrorOrWarning;
import org.aspectj.weaver.patterns.DeclareParents;
import org.aspectj.weaver.patterns.DeclarePrecedence;
import org.aspectj.weaver.patterns.DeclareSoft;
import org.aspectj.weaver.patterns.OrPointcut;
import org.aspectj.weaver.patterns.ReferencePointcut;
import org.aspectj.weaver.patterns.TypePattern;
import org.aspectj.weaver.patterns.TypePatternList;
import org.aspectj.org.eclipse.jdt.internal.compiler.ast.Argument;
import org.aspectj.org.eclipse.jdt.internal.compiler.ast.MethodDeclaration;
import org.aspectj.org.eclipse.jdt.internal.compiler.ast.Annotation;
/**
* @author Mik Kersten
*/
public class AsmElementFormatter {
public static final String DECLARE_PRECEDENCE = "precedence";
public static final String DECLARE_SOFT = "soft";
public static final String DECLARE_PARENTS = "parents";
public static final String DECLARE_WARNING = "warning";
public static final String DECLARE_ERROR = "error";
public static final String DECLARE_UNKNONWN = "<unknown declare>";
public static final String POINTCUT_ABSTRACT = "<abstract pointcut>";
public static final String POINTCUT_ANONYMOUS = "<anonymous pointcut>";
public static final int MAX_MESSAGE_LENGTH = 18;
public static final String DEC_LABEL = "declare";
public void genLabelAndKind(MethodDeclaration methodDeclaration, IProgramElement node) {
if (methodDeclaration instanceof AdviceDeclaration) {
AdviceDeclaration ad = (AdviceDeclaration)methodDeclaration;
node.setKind(IProgramElement.Kind.ADVICE);
if (ad.kind == AdviceKind.Around) {
node.setCorrespondingType(ad.returnType.toString()); //returnTypeToString(0));
}
String details = "";
if (ad.pointcutDesignator != null) {
if (ad.pointcutDesignator.getPointcut() instanceof ReferencePointcut) {
ReferencePointcut rp = (ReferencePointcut)ad.pointcutDesignator.getPointcut();
details += rp.name + "..";
} else if (ad.pointcutDesignator.getPointcut() instanceof AndPointcut) {
AndPointcut ap = (AndPointcut)ad.pointcutDesignator.getPointcut();
if (ap.getLeft() instanceof ReferencePointcut) {
details += ap.getLeft().toString() + "..";
} else {
details += POINTCUT_ANONYMOUS + "..";
}
} else if (ad.pointcutDesignator.getPointcut() instanceof OrPointcut) {
OrPointcut op = (OrPointcut)ad.pointcutDesignator.getPointcut();
if (op.getLeft() instanceof ReferencePointcut) {
details += op.getLeft().toString() + "..";
} else {
details += POINTCUT_ANONYMOUS + "..";
}
} else {
details += POINTCUT_ANONYMOUS;
}
} else {
details += POINTCUT_ABSTRACT;
}
node.setName(ad.kind.toString());
node.setDetails(details);
setParameters(methodDeclaration, node);
} else if (methodDeclaration instanceof PointcutDeclaration) {
PointcutDeclaration pd = (PointcutDeclaration)methodDeclaration;
node.setKind(IProgramElement.Kind.POINTCUT);
node.setName(translatePointcutName(new String(methodDeclaration.selector)));
setParameters(methodDeclaration, node);
} else if (methodDeclaration instanceof DeclareDeclaration) {
DeclareDeclaration declare = (DeclareDeclaration)methodDeclaration;
String name = DEC_LABEL + " ";
if (declare.declareDecl instanceof DeclareErrorOrWarning) {
DeclareErrorOrWarning deow = (DeclareErrorOrWarning)declare.declareDecl;
if (deow.isError()) {
node.setKind( IProgramElement.Kind.DECLARE_ERROR);
name += DECLARE_ERROR;
} else {
node.setKind( IProgramElement.Kind.DECLARE_WARNING);
name += DECLARE_WARNING;
}
node.setName(name) ;
node.setDetails("\"" + genDeclareMessage(deow.getMessage()) + "\"");
} else if (declare.declareDecl instanceof DeclareParents) {
node.setKind( IProgramElement.Kind.DECLARE_PARENTS);
DeclareParents dp = (DeclareParents)declare.declareDecl;
node.setName(name + DECLARE_PARENTS);
String kindOfDP = null;
StringBuffer details = new StringBuffer("");
TypePattern[] newParents = dp.getParents().getTypePatterns();
for (int i = 0; i < newParents.length; i++) {
TypePattern tp = newParents[i];
UnresolvedType tx = tp.getExactType();
if (kindOfDP == null) {
kindOfDP = "implements ";
try {
ResolvedType rtx = tx.resolve(((AjLookupEnvironment)declare.scope.environment()).factory.getWorld());
if (!rtx.isInterface()) kindOfDP = "extends ";
} catch (Throwable t) {
// What can go wrong???? who knows!
}
}
String typename= tp.toString();
if (typename.lastIndexOf(".")!=-1) {
typename=typename.substring(typename.lastIndexOf(".")+1);
}
details.append(typename);
if ((i+1)<newParents.length) details.append(",");
}
node.setDetails(kindOfDP+details.toString());
} else if (declare.declareDecl instanceof DeclareSoft) {
node.setKind( IProgramElement.Kind.DECLARE_SOFT);
DeclareSoft ds = (DeclareSoft)declare.declareDecl;
node.setName(name + DECLARE_SOFT);
node.setDetails(genTypePatternLabel(ds.getException()));
} else if (declare.declareDecl instanceof DeclarePrecedence) {
node.setKind( IProgramElement.Kind.DECLARE_PRECEDENCE);
DeclarePrecedence ds = (DeclarePrecedence)declare.declareDecl;
node.setName(name + DECLARE_PRECEDENCE);
node.setDetails(genPrecedenceListLabel(ds.getPatterns()));
} else if (declare.declareDecl instanceof DeclareAnnotation) {
DeclareAnnotation deca = (DeclareAnnotation)declare.declareDecl;
String thekind = deca.getKind().toString();
node.setName(name+"@"+thekind.substring(3));
if (deca.getKind()==DeclareAnnotation.AT_CONSTRUCTOR) {
node.setKind(IProgramElement.Kind.DECLARE_ANNOTATION_AT_CONSTRUCTOR);
} else if (deca.getKind()==DeclareAnnotation.AT_FIELD) {
node.setKind(IProgramElement.Kind.DECLARE_ANNOTATION_AT_FIELD);
} else if (deca.getKind()==DeclareAnnotation.AT_METHOD) {
node.setKind(IProgramElement.Kind.DECLARE_ANNOTATION_AT_METHOD);
} else if (deca.getKind()==DeclareAnnotation.AT_TYPE) {
node.setKind(IProgramElement.Kind.DECLARE_ANNOTATION_AT_TYPE);
}
node.setDetails(genDecaLabel(deca));
} else {
node.setKind(IProgramElement.Kind.ERROR);
node.setName(DECLARE_UNKNONWN);
}
} else if (methodDeclaration instanceof InterTypeDeclaration) {
InterTypeDeclaration itd = (InterTypeDeclaration)methodDeclaration;
String name = itd.getOnType().toString() + "." + new String(itd.getDeclaredSelector());
if (methodDeclaration instanceof InterTypeFieldDeclaration) {
node.setKind(IProgramElement.Kind.INTER_TYPE_FIELD);
node.setName(name);
} else if (methodDeclaration instanceof InterTypeMethodDeclaration) {
node.setKind(IProgramElement.Kind.INTER_TYPE_METHOD);
node.setName(name);
} else if (methodDeclaration instanceof InterTypeConstructorDeclaration) {
node.setKind(IProgramElement.Kind.INTER_TYPE_CONSTRUCTOR);
// StringBuffer argumentsSignature = new StringBuffer("fubar");
// argumentsSignature.append("(");
// if (methodDeclaration.arguments!=null && methodDeclaration.arguments.length>1) {
//
// for (int i = 1;i<methodDeclaration.arguments.length;i++) {
// argumentsSignature.append(methodDeclaration.arguments[i]);
// if (i+1<methodDeclaration.arguments.length) argumentsSignature.append(",");
// }
// }
// argumentsSignature.append(")");
// InterTypeConstructorDeclaration itcd = (InterTypeConstructorDeclaration)methodDeclaration;
node.setName(itd.getOnType().toString() + "." + itd.getOnType().toString()/*+argumentsSignature.toString()*/);
} else {
node.setKind(IProgramElement.Kind.ERROR);
node.setName(name);
}
node.setCorrespondingType(itd.returnType.toString());
if (node.getKind() != IProgramElement.Kind.INTER_TYPE_FIELD) {
setParameters(methodDeclaration, node);
}
} else {
if (methodDeclaration.isConstructor()) {
node.setKind(IProgramElement.Kind.CONSTRUCTOR);
} else {
node.setKind(IProgramElement.Kind.METHOD);
//TODO AV - could speed up if we could dig only for @Aspect declaring types (or aspect if mixed style allowed)
//??? how to : node.getParent().getKind().equals(IProgramElement.Kind.ASPECT)) {
if (true && methodDeclaration.annotations != null) {
for (int i = 0; i < methodDeclaration.annotations.length; i++) {
//Note: AV: implicit single advice type support here (should be enforced somewhere as well (APT etc))
Annotation annotation = methodDeclaration.annotations[i];
String annotationSig = new String(annotation.type.getTypeBindingPublic(methodDeclaration.scope).signature());
if ("Lorg/aspectj/lang/annotation/Pointcut;".equals(annotationSig)) {
node.setKind(IProgramElement.Kind.POINTCUT);
break;
} else if ("Lorg/aspectj/lang/annotation/Before;".equals(annotationSig)
|| "Lorg/aspectj/lang/annotation/After;".equals(annotationSig)
|| "Lorg/aspectj/lang/annotation/AfterReturning;".equals(annotationSig)
|| "Lorg/aspectj/lang/annotation/AfterThrowing;".equals(annotationSig)
|| "Lorg/aspectj/lang/annotation/Around;".equals(annotationSig)) {
node.setKind(IProgramElement.Kind.ADVICE);
//TODO AV - all are considered anonymous - is that ok?
node.setDetails(POINTCUT_ANONYMOUS);
break;
}
}
}
}
node.setName(new String(methodDeclaration.selector));
setParameters(methodDeclaration, node);
}
}
private String genDecaLabel(DeclareAnnotation deca) {
StringBuffer sb = new StringBuffer("");
sb.append(deca.getPatternAsString());
sb.append(" : ");
sb.append(deca.getAnnotationString());
return sb.toString();
}
private String genPrecedenceListLabel(TypePatternList list) {
String tpList = "";
for (int i = 0; i < list.size(); i++) {
tpList += genTypePatternLabel(list.get(i));
if (i < list.size()-1) tpList += ", ";
}
return tpList;
}
// private String genArguments(MethodDeclaration md) {
// String args = "";
// Argument[] argArray = md.arguments;
// if (argArray == null) return args;
// for (int i = 0; i < argArray.length; i++) {
// String argName = new String(argArray[i].name);
// String argType = argArray[i].type.toString();
// if (acceptArgument(argName, argType)) {
// args += argType + ", ";
// }
// }
// int lastSepIndex = args.lastIndexOf(',');
// if (lastSepIndex != -1 && args.endsWith(", ")) args = args.substring(0, lastSepIndex);
// return args;
// }
private void setParameters(MethodDeclaration md, IProgramElement pe) {
Argument[] argArray = md.arguments;
List names = new ArrayList();
List types = new ArrayList();
pe.setParameterNames(names);
pe.setParameterTypes(types);
if (argArray == null) return;
for (int i = 0; i < argArray.length; i++) {
String argName = new String(argArray[i].name);
String argType = argArray[i].type.toString();
if (acceptArgument(argName, argType)) {
names.add(argName);
types.add(argType);
}
}
}
// TODO: fix this way of determing ajc-added arguments, make subtype of Argument with extra info
private boolean acceptArgument(String name, String type) {
return !name.startsWith("ajc$this_")
&& !type.equals("org.aspectj.lang.JoinPoint.StaticPart")
&& !type.equals("org.aspectj.lang.JoinPoint")
&& !type.equals("org.aspectj.runtime.internal.AroundClosure");
}
public String genTypePatternLabel(TypePattern tp) {
final String TYPE_PATTERN_LITERAL = "<type pattern>";
String label;
UnresolvedType typeX = tp.getExactType();
if (!ResolvedType.isMissing(typeX)) {
label = typeX.getName();
if (tp.isIncludeSubtypes()) label += "+";
} else {
label = TYPE_PATTERN_LITERAL;
}
return label;
}
public String genDeclareMessage(String message) {
int length = message.length();
if (length < MAX_MESSAGE_LENGTH) {
return message;
} else {
return message.substring(0, MAX_MESSAGE_LENGTH-1) + "..";
}
}
// // TODO:
// private String translateAdviceName(String label) {
// if (label.indexOf("before") != -1) return "before";
// if (label.indexOf("returning") != -1) return "after returning";
// if (label.indexOf("after") != -1) return "after";
// if (label.indexOf("around") != -1) return "around";
// else return "<advice>";
// }
// // !!! move or replace
// private String translateDeclareName(String name) {
// int colonIndex = name.indexOf(":");
// if (colonIndex != -1) {
// return name.substring(0, colonIndex);
// } else {
// return name;
// }
// }
// !!! move or replace
// private String translateInterTypeDecName(String name) {
// int index = name.lastIndexOf('$');
// if (index != -1) {
// return name.substring(index+1);
// } else {
// return name;
// }
// }
// !!! move or replace
private String translatePointcutName(String name) {
int index = name.indexOf("$$")+2;
int endIndex = name.lastIndexOf('$');
if (index != -1 && endIndex != -1) {
return name.substring(index, endIndex);
} else {
return name;
}
}
}
|
58,520 |
Bug 58520 ajdoc doesn't navigate to target details in some cases
|
When a file is advised, javadoc uses the following naming convention for setting its "A NAME": convertCheckedException(java.lang.Throwable) However, ajdoc uses the unqualified name for the argument, resuting in the follwing in-file anchor link: <class-name>.html#convertCheckedException(Throwable) Which fails to navigate to the anchor within the file, although it does always go to the right file.
|
resolved fixed
|
bbdd496
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2005-12-21T10:37:43Z | 2004-04-14T16:26:40Z |
org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/core/builder/AsmHierarchyBuilder.java
|
/* *******************************************************************
* Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC).
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* PARC initial implementation
* Mik Kersten revisions, added additional relationships
* 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();
/**
* Reset for every compilation unit.
*/
protected AjBuildConfig buildConfig;
/**
* Reset for every compilation unit.
*/
protected Stack stack;
/**
* Reset for every compilation unit.
*/
private CompilationResult currCompilationResult;
/**
*
* @param cuDeclaration
* @param buildConfig
* @param structureModel hiearchy to add this unit's declarations to
*/
public void buildStructureForCompilationUnit(CompilationUnitDeclaration cuDeclaration, IHierarchy structureModel, AjBuildConfig buildConfig) {
currCompilationResult = cuDeclaration.compilationResult();
LangUtil.throwIaxIfNull(currCompilationResult, "result");
stack = new Stack();
this.buildConfig = buildConfig;
internalBuild(cuDeclaration, structureModel);
// throw new RuntimeException("not implemented");
}
private void internalBuild(CompilationUnitDeclaration unit, IHierarchy structureModel) {
LangUtil.throwIaxIfNull(structureModel, "structureModel");
if (!currCompilationResult.equals(unit.compilationResult())) {
throw new IllegalArgumentException("invalid unit: " + unit);
}
// ---- summary
// add unit to package (or root if no package),
// first removing any duplicate (XXX? removes children if 3 classes in same file?)
// push the node on the stack
// and traverse
// -- create node to add
final File file = new File(new String(unit.getFileName()));
final IProgramElement cuNode;
{
// AMC - use the source start and end from the compilation unit decl
int startLine = getStartLine(unit);
int endLine = getEndLine(unit);
SourceLocation sourceLocation
= new SourceLocation(file, startLine, endLine);
sourceLocation.setOffset(unit.sourceStart);
cuNode = new ProgramElement(
new String(file.getName()),
IProgramElement.Kind.FILE_JAVA,
sourceLocation,
0,
"",
new ArrayList());
}
cuNode.addChild(new ProgramElement(
"import declarations",
IProgramElement.Kind.IMPORT_REFERENCE,
null,
0,
"",
new ArrayList()));
final IProgramElement addToNode = genAddToNode(unit, structureModel);
// -- remove duplicates before adding (XXX use them instead?)
if (addToNode!=null && addToNode.getChildren()!=null) {
for (ListIterator itt = addToNode.getChildren().listIterator(); itt.hasNext(); ) {
IProgramElement child = (IProgramElement)itt.next();
ISourceLocation childLoc = child.getSourceLocation();
if (null == childLoc) {
// XXX ok, packages have null source locations
// signal others?
} else if (childLoc.getSourceFile().equals(file)) {
itt.remove();
}
}
}
// -- add and traverse
addToNode.addChild(cuNode);
stack.push(cuNode);
unit.traverse(this, unit.scope);
// -- update file map (XXX do this before traversal?)
try {
structureModel.addToFileMap(file.getCanonicalPath(), cuNode);
} catch (IOException e) {
System.err.println("IOException " + e.getMessage()
+ " creating path for " + file );
// XXX signal IOException when canonicalizing file path
}
}
/**
* Get/create the node (package or root) to add to.
*/
private IProgramElement genAddToNode(
CompilationUnitDeclaration unit,
IHierarchy structureModel) {
final IProgramElement addToNode;
{
ImportReference currentPackage = unit.currentPackage;
if (null == currentPackage) {
addToNode = structureModel.getRoot();
} else {
String pkgName;
{
StringBuffer nameBuffer = new StringBuffer();
final char[][] importName = currentPackage.getImportName();
final int last = importName.length-1;
for (int i = 0; i < importName.length; i++) {
nameBuffer.append(new String(importName[i]));
if (i < last) {
nameBuffer.append('.');
}
}
pkgName = nameBuffer.toString();
}
IProgramElement pkgNode = null;
if (structureModel!=null && structureModel.getRoot()!=null && structureModel.getRoot().getChildren()!=null) {
for (Iterator it = structureModel.getRoot().getChildren().iterator();
it.hasNext(); ) {
IProgramElement currNode = (IProgramElement)it.next();
if (pkgName.equals(currNode.getName())) {
pkgNode = currNode;
break;
}
}
}
if (pkgNode == null) {
// note packages themselves have no source location
pkgNode = new ProgramElement(
pkgName,
IProgramElement.Kind.PACKAGE,
new ArrayList()
);
structureModel.getRoot().addChild(pkgNode);
}
addToNode = pkgNode;
}
}
return addToNode;
}
public boolean visit(TypeDeclaration typeDeclaration, CompilationUnitScope scope) {
String name = new String(typeDeclaration.name);
IProgramElement.Kind kind = IProgramElement.Kind.CLASS;
if (typeDeclaration instanceof AspectDeclaration) kind = IProgramElement.Kind.ASPECT;
else if (typeDeclaration.kind() == IGenericType.INTERFACE_DECL) kind = IProgramElement.Kind.INTERFACE;
else if (typeDeclaration.kind() == IGenericType.ENUM_DECL) kind = IProgramElement.Kind.ENUM;
else if (typeDeclaration.kind() == IGenericType.ANNOTATION_TYPE_DECL) kind = IProgramElement.Kind.ANNOTATION;
//@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,
"",
new ArrayList());
peNode.setSourceSignature(genSourceSignature(typeDeclaration));
peNode.setFormalComment(generateJavadocComment(typeDeclaration));
((IProgramElement)stack.peek()).addChild(peNode);
stack.push(peNode);
return true;
}
public void endVisit(TypeDeclaration typeDeclaration, CompilationUnitScope scope) {
stack.pop();
}
// ??? share impl with visit(TypeDeclaration, ..) ?
public boolean visit(TypeDeclaration memberTypeDeclaration, ClassScope scope) {
String name = new String(memberTypeDeclaration.name);
IProgramElement.Kind kind = IProgramElement.Kind.CLASS;
if (memberTypeDeclaration instanceof AspectDeclaration) kind = IProgramElement.Kind.ASPECT;
else if (memberTypeDeclaration.kind() == IGenericType.INTERFACE_DECL) kind = IProgramElement.Kind.INTERFACE;
else if (memberTypeDeclaration.kind() == IGenericType.ENUM_DECL) kind = IProgramElement.Kind.ENUM;
else if (memberTypeDeclaration.kind() == IGenericType.ANNOTATION_TYPE_DECL) kind = IProgramElement.Kind.ANNOTATION;
//@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,
"",
new ArrayList());
peNode.setSourceSignature(genSourceSignature(memberTypeDeclaration));
peNode.setFormalComment(generateJavadocComment(memberTypeDeclaration));
((IProgramElement)stack.peek()).addChild(peNode);
stack.push(peNode);
return true;
}
public void endVisit(TypeDeclaration memberTypeDeclaration, ClassScope scope) {
stack.pop();
}
public boolean visit(TypeDeclaration memberTypeDeclaration, BlockScope scope) {
String fullName = "<undefined>";
if (memberTypeDeclaration.allocation != null
&& memberTypeDeclaration.allocation.type != null) {
// Create a name something like 'new Runnable() {..}'
fullName = "new "+memberTypeDeclaration.allocation.type.toString()+"() {..}";
} else if (memberTypeDeclaration.binding != null
&& memberTypeDeclaration.binding.constantPoolName() != null) {
// If we couldn't find a nice name like 'new Runnable() {..}' then use the number after the $
fullName = new String(memberTypeDeclaration.binding.constantPoolName());
int dollar = fullName.indexOf('$');
fullName = fullName.substring(dollar+1);
}
IProgramElement.Kind kind = IProgramElement.Kind.CLASS;
if (memberTypeDeclaration.kind() == IGenericType.INTERFACE_DECL) kind = IProgramElement.Kind.INTERFACE;
else if (memberTypeDeclaration.kind() == IGenericType.ENUM_DECL) kind = IProgramElement.Kind.ENUM;
else if (memberTypeDeclaration.kind() == IGenericType.ANNOTATION_TYPE_DECL) kind = IProgramElement.Kind.ANNOTATION;
//@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,
"",
new ArrayList());
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(
"",
IProgramElement.Kind.ERROR,
makeLocation(methodDeclaration),
(sig!=null?sig.getModifiers():0),
"",
new ArrayList());
} else {
peNode = new ProgramElement(
"",
IProgramElement.Kind.ERROR,
makeLocation(methodDeclaration),
methodDeclaration.modifiers,
"",
new ArrayList());
}
formatter.genLabelAndKind(methodDeclaration, peNode);
genBytecodeInfo(methodDeclaration, peNode);
List namedPointcuts = genNamedPointcuts(methodDeclaration);
addUsesPointcutRelationsForNode(peNode, namedPointcuts, methodDeclaration);
if (methodDeclaration.returnType!=null) {
// 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 {
peNode.setCorrespondingType(methodDeclaration.returnType.resolvedType.debugName());
}
} else {
peNode.setCorrespondingType(null);
}
peNode.setSourceSignature(genSourceSignature(methodDeclaration));
peNode.setFormalComment(generateJavadocComment(methodDeclaration));
// TODO: add return type test
if (peNode.getKind().equals(IProgramElement.Kind.METHOD)) {
if (peNode.toLabelString().equals("main(String[])")
&& peNode.getModifiers().contains(IProgramElement.Modifiers.STATIC)
&& peNode.getAccessibility().equals(IProgramElement.Accessibility.PUBLIC)) {
((IProgramElement)stack.peek()).setRunnable(true);
}
}
stack.push(peNode);
return true;
}
private void addUsesPointcutRelationsForNode(IProgramElement peNode, List namedPointcuts, MethodDeclaration declaration) {
for (Iterator it = namedPointcuts.iterator(); it.hasNext();) {
ReferencePointcut rp = (ReferencePointcut) it.next();
ResolvedMember member = getPointcutDeclaration(rp, declaration);
if (member != null) {
IRelationship foreward = AsmManager.getDefault().getRelationshipMap().get(peNode.getHandleIdentifier(), IRelationship.Kind.USES_POINTCUT, "uses pointcut", false, true);
foreward.addTarget(AsmManager.getDefault().getHandleProvider().createHandleIdentifier(member.getSourceLocation()));
IRelationship back = AsmManager.getDefault().getRelationshipMap().get(AsmManager.getDefault().getHandleProvider().createHandleIdentifier(member.getSourceLocation()), IRelationship.Kind.USES_POINTCUT, "pointcut used by", false, true);
back.addTarget(peNode.getHandleIdentifier());
}
}
}
private ResolvedMember getPointcutDeclaration(ReferencePointcut rp, MethodDeclaration declaration) {
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);
}
public void endVisit(MethodDeclaration methodDeclaration, ClassScope scope) {
stack.pop();
}
public boolean visit(ImportReference importRef, CompilationUnitScope scope) {
int dotIndex = importRef.toString().lastIndexOf('.');
String currPackageImport = "";
if (dotIndex != -1) {
currPackageImport = importRef.toString().substring(0, dotIndex);
}
if (!((ProgramElement)stack.peek()).getPackageName().equals(currPackageImport)) {
IProgramElement peNode = new ProgramElement(
new String(importRef.toString()),
IProgramElement.Kind.IMPORT_REFERENCE,
makeLocation(importRef),
0,
"",
new ArrayList());
ProgramElement imports = (ProgramElement)((ProgramElement)stack.peek()).getChildren().get(0);
imports.addChild(0, peNode);
stack.push(peNode);
}
return true;
}
public void endVisit(ImportReference importRef, CompilationUnitScope scope) {
int dotIndex = importRef.toString().lastIndexOf('.');
String currPackageImport = "";
if (dotIndex != -1) {
currPackageImport = importRef.toString().substring(0, dotIndex);
}
if (!((ProgramElement)stack.peek()).getPackageName().equals(currPackageImport)) {
stack.pop();
}
}
public boolean visit(FieldDeclaration fieldDeclaration, MethodScope scope) {
IProgramElement peNode = null;
if (fieldDeclaration.type == null) { // The field represents an enum value
peNode = new ProgramElement(
new String(fieldDeclaration.name),IProgramElement.Kind.ENUM_VALUE,
makeLocation(fieldDeclaration), fieldDeclaration.modifiers,
"", new ArrayList());
peNode.setCorrespondingType(fieldDeclaration.binding.type.debugName());
} else {
peNode = new ProgramElement(
new String(fieldDeclaration.name),IProgramElement.Kind.FIELD,
makeLocation(fieldDeclaration), fieldDeclaration.modifiers,
"", new ArrayList());
peNode.setCorrespondingType(fieldDeclaration.type.toString());
}
peNode.setSourceSignature(genSourceSignature(fieldDeclaration));
peNode.setFormalComment(generateJavadocComment(fieldDeclaration));
((IProgramElement)stack.peek()).addChild(peNode);
stack.push(peNode);
return true;
}
public void endVisit(FieldDeclaration fieldDeclaration, MethodScope scope) {
stack.pop();
}
/**
* Checks if comments should be added to the model before generating.
*/
protected String generateJavadocComment(ASTNode astNode) {
if (buildConfig != null && !buildConfig.isGenerateJavadocsInModelMode()) return null;
StringBuffer sb = new StringBuffer(); // !!! specify length?
boolean completed = false;
int startIndex = -1;
if (astNode instanceof MethodDeclaration) {
startIndex = ((MethodDeclaration)astNode).declarationSourceStart;
} else if (astNode instanceof FieldDeclaration) {
startIndex = ((FieldDeclaration)astNode).declarationSourceStart;
} else if (astNode instanceof TypeDeclaration) {
startIndex = ((TypeDeclaration)astNode).declarationSourceStart;
}
if (startIndex == -1) {
return null;
} else if (currCompilationResult.compilationUnit.getContents()[startIndex] == '/' // look for /**
&& currCompilationResult.compilationUnit.getContents()[startIndex+1] == '*'
&& currCompilationResult.compilationUnit.getContents()[startIndex+2] == '*') {
for (int i = startIndex; i < astNode.sourceStart && !completed; i++) {
char curr = currCompilationResult.compilationUnit.getContents()[i];
if (curr == '/' && sb.length() > 2 && sb.charAt(sb.length()-1) == '*') completed = true; // found */
sb.append(currCompilationResult.compilationUnit.getContents()[i]);
}
return sb.toString();
} else {
return null;
}
}
/**
* Doesn't print qualified allocation expressions.
*/
protected String genSourceSignature(FieldDeclaration fieldDeclaration) {
StringBuffer output = new StringBuffer();
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,
"",
new ArrayList());
peNode.setModifiers(constructorDeclaration.modifiers);
peNode.setSourceSignature(genSourceSignature(constructorDeclaration));
// Fix to enable us to anchor things from ctor nodes
if (constructorDeclaration.binding != null) {
String memberName = "";
String memberBytecodeSignature = "";
try {
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,
"",
new ArrayList());
((IProgramElement)stack.peek()).addChild(peNode);
stack.push(peNode);
initializer.block.traverse(this, scope);
stack.pop();
return false;
}
// ??? handle non-existant files
protected ISourceLocation makeLocation(ASTNode node) {
String fileName = "";
if (currCompilationResult.getFileName() != null) {
fileName = new String(currCompilationResult.getFileName());
}
// AMC - different strategies based on node kind
int startLine = getStartLine(node);
int endLine = getEndLine(node);
SourceLocation loc = null;
if ( startLine <= endLine ) {
// found a valid end line for this node...
loc = new SourceLocation(new File(fileName), startLine, endLine);
loc.setOffset(node.sourceStart);
} else {
loc = new SourceLocation(new File(fileName), startLine);
loc.setOffset(node.sourceStart);
}
return loc;
}
// AMC - overloaded set of methods to get start and end lines for
// various ASTNode types. They have no common ancestor in the
// hierarchy!!
protected int getStartLine( ASTNode n){
// if ( n instanceof AbstractVariableDeclaration ) return getStartLine( (AbstractVariableDeclaration)n);
// if ( n instanceof AbstractMethodDeclaration ) return getStartLine( (AbstractMethodDeclaration)n);
// if ( n instanceof TypeDeclaration ) return getStartLine( (TypeDeclaration)n);
return ProblemHandler.searchLineNumber(
currCompilationResult.lineSeparatorPositions,
n.sourceStart);
}
// AMC - overloaded set of methods to get start and end lines for
// various ASTNode types. They have no common ancestor in the
// hierarchy!!
protected int getEndLine( ASTNode n){
if ( n instanceof AbstractVariableDeclaration ) return getEndLine( (AbstractVariableDeclaration)n);
if ( n instanceof AbstractMethodDeclaration ) return getEndLine( (AbstractMethodDeclaration)n);
if ( n instanceof TypeDeclaration ) return getEndLine( (TypeDeclaration)n);
return ProblemHandler.searchLineNumber(
currCompilationResult.lineSeparatorPositions,
n.sourceEnd);
}
// AMC - overloaded set of methods to get start and end lines for
// various ASTNode types. They have no common ancestor in the
// hierarchy!!
// private int getStartLine( AbstractVariableDeclaration avd ) {
// return ProblemHandler.searchLineNumber(
// currCompilationResult.lineSeparatorPositions,
// avd.declarationSourceStart);
// }
// AMC - overloaded set of methods to get start and end lines for
// various ASTNode types. They have no common ancestor in the
// hierarchy!!
private int getEndLine( AbstractVariableDeclaration avd ){
return ProblemHandler.searchLineNumber(
currCompilationResult.lineSeparatorPositions,
avd.declarationSourceEnd);
}
// AMC - overloaded set of methods to get start and end lines for
// various ASTNode types. They have no common ancestor in the
// hierarchy!!
// private int getStartLine( AbstractMethodDeclaration amd ){
// return ProblemHandler.searchLineNumber(
// currCompilationResult.lineSeparatorPositions,
// amd.declarationSourceStart);
// }
// AMC - overloaded set of methods to get start and end lines for
// various ASTNode types. They have no common ancestor in the
// hierarchy!!
private int getEndLine( AbstractMethodDeclaration amd) {
return ProblemHandler.searchLineNumber(
currCompilationResult.lineSeparatorPositions,
amd.declarationSourceEnd);
}
// AMC - overloaded set of methods to get start and end lines for
// various ASTNode types. They have no common ancestor in the
// hierarchy!!
// private int getStartLine( TypeDeclaration td ){
// return ProblemHandler.searchLineNumber(
// currCompilationResult.lineSeparatorPositions,
// td.declarationSourceStart);
// }
// AMC - overloaded set of methods to get start and end lines for
// various ASTNode types. They have no common ancestor in the
// hierarchy!!
private int getEndLine( TypeDeclaration td){
return ProblemHandler.searchLineNumber(
currCompilationResult.lineSeparatorPositions,
td.declarationSourceEnd);
}
}
|
121,385 |
Bug 121385 around advice does not work when LTW
|
I defined a aop.xml and a aspect, I have already copy aspectjweaver.jar D:\work\BTM\lib\aspectjweaver.jar, and added -javaagent:D:\work\BTM\lib\aspectjweaver.jar option to the JVM in Eclipse, it works fine if there are before and after advice in aspect, but it will be wrong once I used around advice. if I use compile-time weaving, this around advice works fine. my Eclipse env: eclipse 3.0.2 + AJDT 1.2.1 RC1 release + Sun JDK 1.5.0. aspect file: import org.aspectj.lang.Signature; import org.aspectj.lang.JoinPoint; public abstract aspect World { //private Object result; pointcut greeting() : execution(* Hello.sayWorld(..)); Object around(): greeting() { System.out.println("around start!"); Object result = proceed(); System.out.println("around end!"); return result; } // before() : greeting() { // Signature signature = thisJoinPoint.getSignature(); // System.out.println("before " + signature.getName()); // } // after() returning () : greeting() { // Signature signature = thisJoinPoint.getSignature(); // System.out.println("after " + signature.getName()); // } } aop.xml file: <?xml version="1.0" encoding="UTF-8"?> <aspectj> <aspects> <aspect name="World"/> <concrete-aspect name="World1" extends="World"> <pointcut name="greeting" expression="execution(* Hello.sayWorld(..)) || execution(* Hello.sayHello(..))"/> </concrete-aspect> </aspects> <weaver options="-Xreweavable -verbose -XlazyTjp -showWeaveInfo"> <include within="Hello"/> </weaver> </aspectj> around advice error message in eclipse console as below: info register aspect World info generating class 'World1' info weaving 'Hello' info weaver operating in reweavable mode. Need to verify any required types exist. abort trouble in: public class Hello extends java.lang.Object: public void <init>(): ALOAD_0 // Hello this (line 2) INVOKESPECIAL java.lang.Object.<init> ()V constructor-execution(void Hello.<init>()) | RETURN constructor-execution(void Hello.<init>()) end public void <init>() public static void main(String[]) org.aspectj.weaver.MethodDeclarationLineNumber: 7:75 : INVOKESTATIC Hello.sayHello ()V (line 9) RETURN (line 10) end public static void main(String[]) public static void sayHello() org.aspectj.weaver.MethodDeclarationLineNumber: 12:180 : end public static void sayHello() public static int sayWorld() org.aspectj.weaver.MethodDeclarationLineNumber: 17:268 : method-execution(int Hello.sayWorld()) | GETSTATIC java.lang.System.out Ljava/io/PrintStream; (line 18) | LDC "World" | INVOKEVIRTUAL java.io.PrintStream.println (Ljava/lang/String;)V | ICONST_0 (line 19) | IRETURN method-execution(int Hello.sayWorld()) end public static int sayWorld() static final void sayHello_aroundBody0(): GETSTATIC java.lang.System.out Ljava/io/PrintStream; (line 13) LDC "Hello" INVOKEVIRTUAL java.io.PrintStream.println (Ljava/lang/String;)V INVOKESTATIC Hello.sayWorld ()I (line 14) POP RETURN (line 15) end static final void sayHello_aroundBody0() end public class Hello public class Hello$AjcClosure1 extends org.aspectj.runtime.internal.AroundClosure: public void <init>(Object[]): ALOAD_0 ALOAD_1 INVOKESPECIAL org.aspectj.runtime.internal.AroundClosure.<init> ([Ljava/lang/Object;)V RETURN end public void <init>(Object[]) public Object run(Object[]): ALOAD_0 GETFIELD org.aspectj.runtime.internal.AroundClosure.state [Ljava/lang/Object; ASTORE_2 INVOKESTATIC Hello.sayHello_aroundBody0 ()V ACONST_NULL ARETURN end public Object run(Object[]) end public class Hello$AjcClosure1 -- (NullPointerException) null null java.lang.NullPointerException at org.aspectj.weaver.bcel.BcelAdvice.getAdviceArgSetup(BcelAdvice.java:457) at org.aspectj.weaver.bcel.BcelShadow.weaveAroundClosure(BcelShadow.java:2685) at org.aspectj.weaver.bcel.BcelAdvice.implementOn(BcelAdvice.java:230) at org.aspectj.weaver.Shadow.implementMungers(Shadow.java:588) at org.aspectj.weaver.Shadow.implement(Shadow.java:405) at org.aspectj.weaver.bcel.BcelClassWeaver.implement(BcelClassWeaver.java:2146) at org.aspectj.weaver.bcel.BcelClassWeaver.weave(BcelClassWeaver.java:467) at org.aspectj.weaver.bcel.BcelClassWeaver.weave(BcelClassWeaver.java:102) at org.aspectj.weaver.bcel.BcelWeaver.weave(BcelWeaver.java:1543) at org.aspectj.weaver.bcel.BcelWeaver.weaveWithoutDump(BcelWeaver.java:1494) at org.aspectj.weaver.bcel.BcelWeaver.weaveAndNotify(BcelWeaver.java:1275) at org.aspectj.weaver.bcel.BcelWeaver.weave(BcelWeaver.java:1097) at org.aspectj.weaver.tools.WeavingAdaptor.getWovenBytes(WeavingAdaptor.java:263) at org.aspectj.weaver.tools.WeavingAdaptor.weaveClass(WeavingAdaptor.java:196) at org.aspectj.weaver.loadtime.Aj.preProcess(Aj.java:65) at org.aspectj.weaver.loadtime.ClassPreProcessorAgentAdapter.transform(ClassPreProcessorAgentAdapter.java:52) at sun.instrument.TransformerManager.transform(TransformerManager.java:122) at sun.instrument.InstrumentationImpl.transform(InstrumentationImpl.java:155) at java.lang.ClassLoader.defineClass1(Native Method) at java.lang.ClassLoader.defineClass(ClassLoader.java:620) at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:124) at java.net.URLClassLoader.defineClass(URLClassLoader.java:260) at java.net.URLClassLoader.access$100(URLClassLoader.java:56) at java.net.URLClassLoader$1.run(URLClassLoader.java:195) at java.security.AccessController.doPrivileged(Native Method) at java.net.URLClassLoader.findClass(URLClassLoader.java:188) at java.lang.ClassLoader.loadClass(ClassLoader.java:306) at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:268) at java.lang.ClassLoader.loadClass(ClassLoader.java:251) at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:319) Message: abort trouble in: public class Hello extends java.lang.Object: public void <init>(): ALOAD_0 // Hello this (line 2) INVOKESPECIAL java.lang.Object.<init> ()V constructor-execution(void Hello.<init>()) | RETURN constructor-execution(void Hello.<init>()) end public void <init>() public static void main(String[]) org.aspectj.weaver.MethodDeclarationLineNumber: 7:75 : INVOKESTATIC Hello.sayHello ()V (line 9) RETURN (line 10) end public static void main(String[]) public static void sayHello() org.aspectj.weaver.MethodDeclarationLineNumber: 12:180 : end public static void sayHello() public static int sayWorld() org.aspectj.weaver.MethodDeclarationLineNumber: 17:268 : method-execution(int Hello.sayWorld()) | GETSTATIC java.lang.System.out Ljava/io/PrintStream; (line 18) | LDC "World" | INVOKEVIRTUAL java.io.PrintStream.println (Ljava/lang/String;)V | ICONST_0 (line 19) | IRETURN method-execution(int Hello.sayWorld()) end public static int sayWorld() static final void sayHello_aroundBody0(): GETSTATIC java.lang.System.out Ljava/io/PrintStream; (line 13) LDC "Hello" INVOKEVIRTUAL java.io.PrintStream.println (Ljava/lang/String;)V INVOKESTATIC Hello.sayWorld ()I (line 14) POP RETURN (line 15) end static final void sayHello_aroundBody0() end public class Hello public class Hello$AjcClosure1 extends org.aspectj.runtime.internal.AroundClosure: public void <init>(Object[]): ALOAD_0 ALOAD_1 INVOKESPECIAL org.aspectj.runtime.internal.AroundClosure.<init> ([Ljava/lang/Object;)V RETURN end public void <init>(Object[]) public Object run(Object[]): ALOAD_0 GETFIELD org.aspectj.runtime.internal.AroundClosure.state [Ljava/lang/Object; ASTORE_2 INVOKESTATIC Hello.sayHello_aroundBody0 ()V ACONST_NULL ARETURN end public Object run(Object[]) end public class Hello$AjcClosure1 -- (NullPointerException) null null java.lang.NullPointerException at org.aspectj.weaver.bcel.BcelAdvice.getAdviceArgSetup(BcelAdvice.java:457) at org.aspectj.weaver.bcel.BcelShadow.weaveAroundClosure(BcelShadow.java:2685) at org.aspectj.weaver.bcel.BcelAdvice.implementOn(BcelAdvice.java:230) at org.aspectj.weaver.Shadow.implementMungers(Shadow.java:588) at org.aspectj.weaver.Shadow.implement(Shadow.java:405) at org.aspectj.weaver.bcel.BcelClassWeaver.implement(BcelClassWeaver.java:2146) at org.aspectj.weaver.bcel.BcelClassWeaver.weave(BcelClassWeaver.java:467) at org.aspectj.weaver.bcel.BcelClassWeaver.weave(BcelClassWeaver.java:102) at org.aspectj.weaver.bcel.BcelWeaver.weave(BcelWeaver.java:1543) at org.aspectj.weaver.bcel.BcelWeaver.weaveWithoutDump(BcelWeaver.java:1494) at org.aspectj.weaver.bcel.BcelWeaver.weaveAndNotify(BcelWeaver.java:1275) at org.aspectj.weaver.bcel.BcelWeaver.weave(BcelWeaver.java:1097) at org.aspectj.weaver.tools.WeavingAdaptor.getWovenBytes(WeavingAdaptor.java:263) at org.aspectj.weaver.tools.WeavingAdaptor.weaveClass(WeavingAdaptor.java:196) at org.aspectj.weaver.loadtime.Aj.preProcess(Aj.java:65) at org.aspectj.weaver.loadtime.ClassPreProcessorAgentAdapter.transform(ClassPreProcessorAgentAdapter.java:52) at sun.instrument.TransformerManager.transform(TransformerManager.java:122) at sun.instrument.InstrumentationImpl.transform(InstrumentationImpl.java:155) at java.lang.ClassLoader.defineClass1(Native Method) at java.lang.ClassLoader.defineClass(ClassLoader.java:620) at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:124) at java.net.URLClassLoader.defineClass(URLClassLoader.java:260) at java.net.URLClassLoader.access$100(URLClassLoader.java:56) at java.net.URLClassLoader$1.run(URLClassLoader.java:195) at java.security.AccessController.doPrivileged(Native Method) at java.net.URLClassLoader.findClass(URLClassLoader.java:188) at java.lang.ClassLoader.loadClass(ClassLoader.java:306) at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:268) at java.lang.ClassLoader.loadClass(ClassLoader.java:251) at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:319) org.aspectj.bridge.AbortException: trouble in: public class Hello extends java.lang.Object: public void <init>(): ALOAD_0 // Hello this (line 2) INVOKESPECIAL java.lang.Object.<init> ()V constructor-execution(void Hello.<init>()) | RETURN constructor-execution(void Hello.<init>()) end public void <init>() public static void main(String[]) org.aspectj.weaver.MethodDeclarationLineNumber: 7:75 : INVOKESTATIC Hello.sayHello ()V (line 9) RETURN (line 10) end public static void main(String[]) public static void sayHello() org.aspectj.weaver.MethodDeclarationLineNumber: 12:180 : end public static void sayHello() public static int sayWorld() org.aspectj.weaver.MethodDeclarationLineNumber: 17:268 : method-execution(int Hello.sayWorld()) | GETSTATIC java.lang.System.out Ljava/io/PrintStream; (line 18) | LDC "World" | INVOKEVIRTUAL java.io.PrintStream.println (Ljava/lang/String;)V | ICONST_0 (line 19) | IRETURN method-execution(int Hello.sayWorld()) end public static int sayWorld() static final void sayHello_aroundBody0(): GETSTATIC java.lang.System.out Ljava/io/PrintStream; (line 13) LDC "Hello" INVOKEVIRTUAL java.io.PrintStream.println (Ljava/lang/String;)V INVOKESTATIC Hello.sayWorld ()I (line 14) POP RETURN (line 15) end static final void sayHello_aroundBody0() end public class Hello public class Hello$AjcClosure1 extends org.aspectj.runtime.internal.AroundClosure: public void <init>(Object[]): ALOAD_0 ALOAD_1 INVOKESPECIAL org.aspectj.runtime.internal.AroundClosure.<init> ([Ljava/lang/Object;)V RETURN end public void <init>(Object[]) public Object run(Object[]): ALOAD_0 GETFIELD org.aspectj.runtime.internal.AroundClosure.state [Ljava/lang/Object; ASTORE_2 INVOKESTATIC Hello.sayHello_aroundBody0 ()V ACONST_NULL ARETURN end public Object run(Object[]) end public class Hello$AjcClosure1 at org.aspectj.bridge.MessageWriter.handleMessage(MessageWriter.java:47) at org.aspectj.weaver.tools.WeavingAdaptor$WeavingAdaptorMessageHandler.handleMessage(WeavingAdaptor.java:395) at org.aspectj.weaver.bcel.BcelWeaver.weave(BcelWeaver.java:1554) at org.aspectj.weaver.bcel.BcelWeaver.weaveWithoutDump(BcelWeaver.java:1494) at org.aspectj.weaver.bcel.BcelWeaver.weaveAndNotify(BcelWeaver.java:1275) at org.aspectj.weaver.bcel.BcelWeaver.weave(BcelWeaver.java:1097) at org.aspectj.weaver.tools.WeavingAdaptor.getWovenBytes(WeavingAdaptor.java:263) at org.aspectj.weaver.tools.WeavingAdaptor.weaveClass(WeavingAdaptor.java:196) at org.aspectj.weaver.loadtime.Aj.preProcess(Aj.java:65) at org.aspectj.weaver.loadtime.ClassPreProcessorAgentAdapter.transform(ClassPreProcessorAgentAdapter.java:52) at sun.instrument.TransformerManager.transform(TransformerManager.java:122) at sun.instrument.InstrumentationImpl.transform(InstrumentationImpl.java:155) at java.lang.ClassLoader.defineClass1(Native Method) at java.lang.ClassLoader.defineClass(ClassLoader.java:620) at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:124) at java.net.URLClassLoader.defineClass(URLClassLoader.java:260) at java.net.URLClassLoader.access$100(URLClassLoader.java:56) at java.net.URLClassLoader$1.run(URLClassLoader.java:195) at java.security.AccessController.doPrivileged(Native Method) at java.net.URLClassLoader.findClass(URLClassLoader.java:188) at java.lang.ClassLoader.loadClass(ClassLoader.java:306) at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:268) at java.lang.ClassLoader.loadClass(ClassLoader.java:251) at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:319) Hello World
|
resolved fixed
|
a778ac4
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2005-12-21T17:21:57Z | 2005-12-19T11:00:00Z |
tests/bugs150/pr121385/A.java
| |
121,385 |
Bug 121385 around advice does not work when LTW
|
I defined a aop.xml and a aspect, I have already copy aspectjweaver.jar D:\work\BTM\lib\aspectjweaver.jar, and added -javaagent:D:\work\BTM\lib\aspectjweaver.jar option to the JVM in Eclipse, it works fine if there are before and after advice in aspect, but it will be wrong once I used around advice. if I use compile-time weaving, this around advice works fine. my Eclipse env: eclipse 3.0.2 + AJDT 1.2.1 RC1 release + Sun JDK 1.5.0. aspect file: import org.aspectj.lang.Signature; import org.aspectj.lang.JoinPoint; public abstract aspect World { //private Object result; pointcut greeting() : execution(* Hello.sayWorld(..)); Object around(): greeting() { System.out.println("around start!"); Object result = proceed(); System.out.println("around end!"); return result; } // before() : greeting() { // Signature signature = thisJoinPoint.getSignature(); // System.out.println("before " + signature.getName()); // } // after() returning () : greeting() { // Signature signature = thisJoinPoint.getSignature(); // System.out.println("after " + signature.getName()); // } } aop.xml file: <?xml version="1.0" encoding="UTF-8"?> <aspectj> <aspects> <aspect name="World"/> <concrete-aspect name="World1" extends="World"> <pointcut name="greeting" expression="execution(* Hello.sayWorld(..)) || execution(* Hello.sayHello(..))"/> </concrete-aspect> </aspects> <weaver options="-Xreweavable -verbose -XlazyTjp -showWeaveInfo"> <include within="Hello"/> </weaver> </aspectj> around advice error message in eclipse console as below: info register aspect World info generating class 'World1' info weaving 'Hello' info weaver operating in reweavable mode. Need to verify any required types exist. abort trouble in: public class Hello extends java.lang.Object: public void <init>(): ALOAD_0 // Hello this (line 2) INVOKESPECIAL java.lang.Object.<init> ()V constructor-execution(void Hello.<init>()) | RETURN constructor-execution(void Hello.<init>()) end public void <init>() public static void main(String[]) org.aspectj.weaver.MethodDeclarationLineNumber: 7:75 : INVOKESTATIC Hello.sayHello ()V (line 9) RETURN (line 10) end public static void main(String[]) public static void sayHello() org.aspectj.weaver.MethodDeclarationLineNumber: 12:180 : end public static void sayHello() public static int sayWorld() org.aspectj.weaver.MethodDeclarationLineNumber: 17:268 : method-execution(int Hello.sayWorld()) | GETSTATIC java.lang.System.out Ljava/io/PrintStream; (line 18) | LDC "World" | INVOKEVIRTUAL java.io.PrintStream.println (Ljava/lang/String;)V | ICONST_0 (line 19) | IRETURN method-execution(int Hello.sayWorld()) end public static int sayWorld() static final void sayHello_aroundBody0(): GETSTATIC java.lang.System.out Ljava/io/PrintStream; (line 13) LDC "Hello" INVOKEVIRTUAL java.io.PrintStream.println (Ljava/lang/String;)V INVOKESTATIC Hello.sayWorld ()I (line 14) POP RETURN (line 15) end static final void sayHello_aroundBody0() end public class Hello public class Hello$AjcClosure1 extends org.aspectj.runtime.internal.AroundClosure: public void <init>(Object[]): ALOAD_0 ALOAD_1 INVOKESPECIAL org.aspectj.runtime.internal.AroundClosure.<init> ([Ljava/lang/Object;)V RETURN end public void <init>(Object[]) public Object run(Object[]): ALOAD_0 GETFIELD org.aspectj.runtime.internal.AroundClosure.state [Ljava/lang/Object; ASTORE_2 INVOKESTATIC Hello.sayHello_aroundBody0 ()V ACONST_NULL ARETURN end public Object run(Object[]) end public class Hello$AjcClosure1 -- (NullPointerException) null null java.lang.NullPointerException at org.aspectj.weaver.bcel.BcelAdvice.getAdviceArgSetup(BcelAdvice.java:457) at org.aspectj.weaver.bcel.BcelShadow.weaveAroundClosure(BcelShadow.java:2685) at org.aspectj.weaver.bcel.BcelAdvice.implementOn(BcelAdvice.java:230) at org.aspectj.weaver.Shadow.implementMungers(Shadow.java:588) at org.aspectj.weaver.Shadow.implement(Shadow.java:405) at org.aspectj.weaver.bcel.BcelClassWeaver.implement(BcelClassWeaver.java:2146) at org.aspectj.weaver.bcel.BcelClassWeaver.weave(BcelClassWeaver.java:467) at org.aspectj.weaver.bcel.BcelClassWeaver.weave(BcelClassWeaver.java:102) at org.aspectj.weaver.bcel.BcelWeaver.weave(BcelWeaver.java:1543) at org.aspectj.weaver.bcel.BcelWeaver.weaveWithoutDump(BcelWeaver.java:1494) at org.aspectj.weaver.bcel.BcelWeaver.weaveAndNotify(BcelWeaver.java:1275) at org.aspectj.weaver.bcel.BcelWeaver.weave(BcelWeaver.java:1097) at org.aspectj.weaver.tools.WeavingAdaptor.getWovenBytes(WeavingAdaptor.java:263) at org.aspectj.weaver.tools.WeavingAdaptor.weaveClass(WeavingAdaptor.java:196) at org.aspectj.weaver.loadtime.Aj.preProcess(Aj.java:65) at org.aspectj.weaver.loadtime.ClassPreProcessorAgentAdapter.transform(ClassPreProcessorAgentAdapter.java:52) at sun.instrument.TransformerManager.transform(TransformerManager.java:122) at sun.instrument.InstrumentationImpl.transform(InstrumentationImpl.java:155) at java.lang.ClassLoader.defineClass1(Native Method) at java.lang.ClassLoader.defineClass(ClassLoader.java:620) at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:124) at java.net.URLClassLoader.defineClass(URLClassLoader.java:260) at java.net.URLClassLoader.access$100(URLClassLoader.java:56) at java.net.URLClassLoader$1.run(URLClassLoader.java:195) at java.security.AccessController.doPrivileged(Native Method) at java.net.URLClassLoader.findClass(URLClassLoader.java:188) at java.lang.ClassLoader.loadClass(ClassLoader.java:306) at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:268) at java.lang.ClassLoader.loadClass(ClassLoader.java:251) at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:319) Message: abort trouble in: public class Hello extends java.lang.Object: public void <init>(): ALOAD_0 // Hello this (line 2) INVOKESPECIAL java.lang.Object.<init> ()V constructor-execution(void Hello.<init>()) | RETURN constructor-execution(void Hello.<init>()) end public void <init>() public static void main(String[]) org.aspectj.weaver.MethodDeclarationLineNumber: 7:75 : INVOKESTATIC Hello.sayHello ()V (line 9) RETURN (line 10) end public static void main(String[]) public static void sayHello() org.aspectj.weaver.MethodDeclarationLineNumber: 12:180 : end public static void sayHello() public static int sayWorld() org.aspectj.weaver.MethodDeclarationLineNumber: 17:268 : method-execution(int Hello.sayWorld()) | GETSTATIC java.lang.System.out Ljava/io/PrintStream; (line 18) | LDC "World" | INVOKEVIRTUAL java.io.PrintStream.println (Ljava/lang/String;)V | ICONST_0 (line 19) | IRETURN method-execution(int Hello.sayWorld()) end public static int sayWorld() static final void sayHello_aroundBody0(): GETSTATIC java.lang.System.out Ljava/io/PrintStream; (line 13) LDC "Hello" INVOKEVIRTUAL java.io.PrintStream.println (Ljava/lang/String;)V INVOKESTATIC Hello.sayWorld ()I (line 14) POP RETURN (line 15) end static final void sayHello_aroundBody0() end public class Hello public class Hello$AjcClosure1 extends org.aspectj.runtime.internal.AroundClosure: public void <init>(Object[]): ALOAD_0 ALOAD_1 INVOKESPECIAL org.aspectj.runtime.internal.AroundClosure.<init> ([Ljava/lang/Object;)V RETURN end public void <init>(Object[]) public Object run(Object[]): ALOAD_0 GETFIELD org.aspectj.runtime.internal.AroundClosure.state [Ljava/lang/Object; ASTORE_2 INVOKESTATIC Hello.sayHello_aroundBody0 ()V ACONST_NULL ARETURN end public Object run(Object[]) end public class Hello$AjcClosure1 -- (NullPointerException) null null java.lang.NullPointerException at org.aspectj.weaver.bcel.BcelAdvice.getAdviceArgSetup(BcelAdvice.java:457) at org.aspectj.weaver.bcel.BcelShadow.weaveAroundClosure(BcelShadow.java:2685) at org.aspectj.weaver.bcel.BcelAdvice.implementOn(BcelAdvice.java:230) at org.aspectj.weaver.Shadow.implementMungers(Shadow.java:588) at org.aspectj.weaver.Shadow.implement(Shadow.java:405) at org.aspectj.weaver.bcel.BcelClassWeaver.implement(BcelClassWeaver.java:2146) at org.aspectj.weaver.bcel.BcelClassWeaver.weave(BcelClassWeaver.java:467) at org.aspectj.weaver.bcel.BcelClassWeaver.weave(BcelClassWeaver.java:102) at org.aspectj.weaver.bcel.BcelWeaver.weave(BcelWeaver.java:1543) at org.aspectj.weaver.bcel.BcelWeaver.weaveWithoutDump(BcelWeaver.java:1494) at org.aspectj.weaver.bcel.BcelWeaver.weaveAndNotify(BcelWeaver.java:1275) at org.aspectj.weaver.bcel.BcelWeaver.weave(BcelWeaver.java:1097) at org.aspectj.weaver.tools.WeavingAdaptor.getWovenBytes(WeavingAdaptor.java:263) at org.aspectj.weaver.tools.WeavingAdaptor.weaveClass(WeavingAdaptor.java:196) at org.aspectj.weaver.loadtime.Aj.preProcess(Aj.java:65) at org.aspectj.weaver.loadtime.ClassPreProcessorAgentAdapter.transform(ClassPreProcessorAgentAdapter.java:52) at sun.instrument.TransformerManager.transform(TransformerManager.java:122) at sun.instrument.InstrumentationImpl.transform(InstrumentationImpl.java:155) at java.lang.ClassLoader.defineClass1(Native Method) at java.lang.ClassLoader.defineClass(ClassLoader.java:620) at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:124) at java.net.URLClassLoader.defineClass(URLClassLoader.java:260) at java.net.URLClassLoader.access$100(URLClassLoader.java:56) at java.net.URLClassLoader$1.run(URLClassLoader.java:195) at java.security.AccessController.doPrivileged(Native Method) at java.net.URLClassLoader.findClass(URLClassLoader.java:188) at java.lang.ClassLoader.loadClass(ClassLoader.java:306) at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:268) at java.lang.ClassLoader.loadClass(ClassLoader.java:251) at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:319) org.aspectj.bridge.AbortException: trouble in: public class Hello extends java.lang.Object: public void <init>(): ALOAD_0 // Hello this (line 2) INVOKESPECIAL java.lang.Object.<init> ()V constructor-execution(void Hello.<init>()) | RETURN constructor-execution(void Hello.<init>()) end public void <init>() public static void main(String[]) org.aspectj.weaver.MethodDeclarationLineNumber: 7:75 : INVOKESTATIC Hello.sayHello ()V (line 9) RETURN (line 10) end public static void main(String[]) public static void sayHello() org.aspectj.weaver.MethodDeclarationLineNumber: 12:180 : end public static void sayHello() public static int sayWorld() org.aspectj.weaver.MethodDeclarationLineNumber: 17:268 : method-execution(int Hello.sayWorld()) | GETSTATIC java.lang.System.out Ljava/io/PrintStream; (line 18) | LDC "World" | INVOKEVIRTUAL java.io.PrintStream.println (Ljava/lang/String;)V | ICONST_0 (line 19) | IRETURN method-execution(int Hello.sayWorld()) end public static int sayWorld() static final void sayHello_aroundBody0(): GETSTATIC java.lang.System.out Ljava/io/PrintStream; (line 13) LDC "Hello" INVOKEVIRTUAL java.io.PrintStream.println (Ljava/lang/String;)V INVOKESTATIC Hello.sayWorld ()I (line 14) POP RETURN (line 15) end static final void sayHello_aroundBody0() end public class Hello public class Hello$AjcClosure1 extends org.aspectj.runtime.internal.AroundClosure: public void <init>(Object[]): ALOAD_0 ALOAD_1 INVOKESPECIAL org.aspectj.runtime.internal.AroundClosure.<init> ([Ljava/lang/Object;)V RETURN end public void <init>(Object[]) public Object run(Object[]): ALOAD_0 GETFIELD org.aspectj.runtime.internal.AroundClosure.state [Ljava/lang/Object; ASTORE_2 INVOKESTATIC Hello.sayHello_aroundBody0 ()V ACONST_NULL ARETURN end public Object run(Object[]) end public class Hello$AjcClosure1 at org.aspectj.bridge.MessageWriter.handleMessage(MessageWriter.java:47) at org.aspectj.weaver.tools.WeavingAdaptor$WeavingAdaptorMessageHandler.handleMessage(WeavingAdaptor.java:395) at org.aspectj.weaver.bcel.BcelWeaver.weave(BcelWeaver.java:1554) at org.aspectj.weaver.bcel.BcelWeaver.weaveWithoutDump(BcelWeaver.java:1494) at org.aspectj.weaver.bcel.BcelWeaver.weaveAndNotify(BcelWeaver.java:1275) at org.aspectj.weaver.bcel.BcelWeaver.weave(BcelWeaver.java:1097) at org.aspectj.weaver.tools.WeavingAdaptor.getWovenBytes(WeavingAdaptor.java:263) at org.aspectj.weaver.tools.WeavingAdaptor.weaveClass(WeavingAdaptor.java:196) at org.aspectj.weaver.loadtime.Aj.preProcess(Aj.java:65) at org.aspectj.weaver.loadtime.ClassPreProcessorAgentAdapter.transform(ClassPreProcessorAgentAdapter.java:52) at sun.instrument.TransformerManager.transform(TransformerManager.java:122) at sun.instrument.InstrumentationImpl.transform(InstrumentationImpl.java:155) at java.lang.ClassLoader.defineClass1(Native Method) at java.lang.ClassLoader.defineClass(ClassLoader.java:620) at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:124) at java.net.URLClassLoader.defineClass(URLClassLoader.java:260) at java.net.URLClassLoader.access$100(URLClassLoader.java:56) at java.net.URLClassLoader$1.run(URLClassLoader.java:195) at java.security.AccessController.doPrivileged(Native Method) at java.net.URLClassLoader.findClass(URLClassLoader.java:188) at java.lang.ClassLoader.loadClass(ClassLoader.java:306) at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:268) at java.lang.ClassLoader.loadClass(ClassLoader.java:251) at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:319) Hello World
|
resolved fixed
|
a778ac4
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2005-12-21T17:21:57Z | 2005-12-19T11:00:00Z |
tests/bugs150/pr121385/Hello.java
| |
121,385 |
Bug 121385 around advice does not work when LTW
|
I defined a aop.xml and a aspect, I have already copy aspectjweaver.jar D:\work\BTM\lib\aspectjweaver.jar, and added -javaagent:D:\work\BTM\lib\aspectjweaver.jar option to the JVM in Eclipse, it works fine if there are before and after advice in aspect, but it will be wrong once I used around advice. if I use compile-time weaving, this around advice works fine. my Eclipse env: eclipse 3.0.2 + AJDT 1.2.1 RC1 release + Sun JDK 1.5.0. aspect file: import org.aspectj.lang.Signature; import org.aspectj.lang.JoinPoint; public abstract aspect World { //private Object result; pointcut greeting() : execution(* Hello.sayWorld(..)); Object around(): greeting() { System.out.println("around start!"); Object result = proceed(); System.out.println("around end!"); return result; } // before() : greeting() { // Signature signature = thisJoinPoint.getSignature(); // System.out.println("before " + signature.getName()); // } // after() returning () : greeting() { // Signature signature = thisJoinPoint.getSignature(); // System.out.println("after " + signature.getName()); // } } aop.xml file: <?xml version="1.0" encoding="UTF-8"?> <aspectj> <aspects> <aspect name="World"/> <concrete-aspect name="World1" extends="World"> <pointcut name="greeting" expression="execution(* Hello.sayWorld(..)) || execution(* Hello.sayHello(..))"/> </concrete-aspect> </aspects> <weaver options="-Xreweavable -verbose -XlazyTjp -showWeaveInfo"> <include within="Hello"/> </weaver> </aspectj> around advice error message in eclipse console as below: info register aspect World info generating class 'World1' info weaving 'Hello' info weaver operating in reweavable mode. Need to verify any required types exist. abort trouble in: public class Hello extends java.lang.Object: public void <init>(): ALOAD_0 // Hello this (line 2) INVOKESPECIAL java.lang.Object.<init> ()V constructor-execution(void Hello.<init>()) | RETURN constructor-execution(void Hello.<init>()) end public void <init>() public static void main(String[]) org.aspectj.weaver.MethodDeclarationLineNumber: 7:75 : INVOKESTATIC Hello.sayHello ()V (line 9) RETURN (line 10) end public static void main(String[]) public static void sayHello() org.aspectj.weaver.MethodDeclarationLineNumber: 12:180 : end public static void sayHello() public static int sayWorld() org.aspectj.weaver.MethodDeclarationLineNumber: 17:268 : method-execution(int Hello.sayWorld()) | GETSTATIC java.lang.System.out Ljava/io/PrintStream; (line 18) | LDC "World" | INVOKEVIRTUAL java.io.PrintStream.println (Ljava/lang/String;)V | ICONST_0 (line 19) | IRETURN method-execution(int Hello.sayWorld()) end public static int sayWorld() static final void sayHello_aroundBody0(): GETSTATIC java.lang.System.out Ljava/io/PrintStream; (line 13) LDC "Hello" INVOKEVIRTUAL java.io.PrintStream.println (Ljava/lang/String;)V INVOKESTATIC Hello.sayWorld ()I (line 14) POP RETURN (line 15) end static final void sayHello_aroundBody0() end public class Hello public class Hello$AjcClosure1 extends org.aspectj.runtime.internal.AroundClosure: public void <init>(Object[]): ALOAD_0 ALOAD_1 INVOKESPECIAL org.aspectj.runtime.internal.AroundClosure.<init> ([Ljava/lang/Object;)V RETURN end public void <init>(Object[]) public Object run(Object[]): ALOAD_0 GETFIELD org.aspectj.runtime.internal.AroundClosure.state [Ljava/lang/Object; ASTORE_2 INVOKESTATIC Hello.sayHello_aroundBody0 ()V ACONST_NULL ARETURN end public Object run(Object[]) end public class Hello$AjcClosure1 -- (NullPointerException) null null java.lang.NullPointerException at org.aspectj.weaver.bcel.BcelAdvice.getAdviceArgSetup(BcelAdvice.java:457) at org.aspectj.weaver.bcel.BcelShadow.weaveAroundClosure(BcelShadow.java:2685) at org.aspectj.weaver.bcel.BcelAdvice.implementOn(BcelAdvice.java:230) at org.aspectj.weaver.Shadow.implementMungers(Shadow.java:588) at org.aspectj.weaver.Shadow.implement(Shadow.java:405) at org.aspectj.weaver.bcel.BcelClassWeaver.implement(BcelClassWeaver.java:2146) at org.aspectj.weaver.bcel.BcelClassWeaver.weave(BcelClassWeaver.java:467) at org.aspectj.weaver.bcel.BcelClassWeaver.weave(BcelClassWeaver.java:102) at org.aspectj.weaver.bcel.BcelWeaver.weave(BcelWeaver.java:1543) at org.aspectj.weaver.bcel.BcelWeaver.weaveWithoutDump(BcelWeaver.java:1494) at org.aspectj.weaver.bcel.BcelWeaver.weaveAndNotify(BcelWeaver.java:1275) at org.aspectj.weaver.bcel.BcelWeaver.weave(BcelWeaver.java:1097) at org.aspectj.weaver.tools.WeavingAdaptor.getWovenBytes(WeavingAdaptor.java:263) at org.aspectj.weaver.tools.WeavingAdaptor.weaveClass(WeavingAdaptor.java:196) at org.aspectj.weaver.loadtime.Aj.preProcess(Aj.java:65) at org.aspectj.weaver.loadtime.ClassPreProcessorAgentAdapter.transform(ClassPreProcessorAgentAdapter.java:52) at sun.instrument.TransformerManager.transform(TransformerManager.java:122) at sun.instrument.InstrumentationImpl.transform(InstrumentationImpl.java:155) at java.lang.ClassLoader.defineClass1(Native Method) at java.lang.ClassLoader.defineClass(ClassLoader.java:620) at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:124) at java.net.URLClassLoader.defineClass(URLClassLoader.java:260) at java.net.URLClassLoader.access$100(URLClassLoader.java:56) at java.net.URLClassLoader$1.run(URLClassLoader.java:195) at java.security.AccessController.doPrivileged(Native Method) at java.net.URLClassLoader.findClass(URLClassLoader.java:188) at java.lang.ClassLoader.loadClass(ClassLoader.java:306) at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:268) at java.lang.ClassLoader.loadClass(ClassLoader.java:251) at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:319) Message: abort trouble in: public class Hello extends java.lang.Object: public void <init>(): ALOAD_0 // Hello this (line 2) INVOKESPECIAL java.lang.Object.<init> ()V constructor-execution(void Hello.<init>()) | RETURN constructor-execution(void Hello.<init>()) end public void <init>() public static void main(String[]) org.aspectj.weaver.MethodDeclarationLineNumber: 7:75 : INVOKESTATIC Hello.sayHello ()V (line 9) RETURN (line 10) end public static void main(String[]) public static void sayHello() org.aspectj.weaver.MethodDeclarationLineNumber: 12:180 : end public static void sayHello() public static int sayWorld() org.aspectj.weaver.MethodDeclarationLineNumber: 17:268 : method-execution(int Hello.sayWorld()) | GETSTATIC java.lang.System.out Ljava/io/PrintStream; (line 18) | LDC "World" | INVOKEVIRTUAL java.io.PrintStream.println (Ljava/lang/String;)V | ICONST_0 (line 19) | IRETURN method-execution(int Hello.sayWorld()) end public static int sayWorld() static final void sayHello_aroundBody0(): GETSTATIC java.lang.System.out Ljava/io/PrintStream; (line 13) LDC "Hello" INVOKEVIRTUAL java.io.PrintStream.println (Ljava/lang/String;)V INVOKESTATIC Hello.sayWorld ()I (line 14) POP RETURN (line 15) end static final void sayHello_aroundBody0() end public class Hello public class Hello$AjcClosure1 extends org.aspectj.runtime.internal.AroundClosure: public void <init>(Object[]): ALOAD_0 ALOAD_1 INVOKESPECIAL org.aspectj.runtime.internal.AroundClosure.<init> ([Ljava/lang/Object;)V RETURN end public void <init>(Object[]) public Object run(Object[]): ALOAD_0 GETFIELD org.aspectj.runtime.internal.AroundClosure.state [Ljava/lang/Object; ASTORE_2 INVOKESTATIC Hello.sayHello_aroundBody0 ()V ACONST_NULL ARETURN end public Object run(Object[]) end public class Hello$AjcClosure1 -- (NullPointerException) null null java.lang.NullPointerException at org.aspectj.weaver.bcel.BcelAdvice.getAdviceArgSetup(BcelAdvice.java:457) at org.aspectj.weaver.bcel.BcelShadow.weaveAroundClosure(BcelShadow.java:2685) at org.aspectj.weaver.bcel.BcelAdvice.implementOn(BcelAdvice.java:230) at org.aspectj.weaver.Shadow.implementMungers(Shadow.java:588) at org.aspectj.weaver.Shadow.implement(Shadow.java:405) at org.aspectj.weaver.bcel.BcelClassWeaver.implement(BcelClassWeaver.java:2146) at org.aspectj.weaver.bcel.BcelClassWeaver.weave(BcelClassWeaver.java:467) at org.aspectj.weaver.bcel.BcelClassWeaver.weave(BcelClassWeaver.java:102) at org.aspectj.weaver.bcel.BcelWeaver.weave(BcelWeaver.java:1543) at org.aspectj.weaver.bcel.BcelWeaver.weaveWithoutDump(BcelWeaver.java:1494) at org.aspectj.weaver.bcel.BcelWeaver.weaveAndNotify(BcelWeaver.java:1275) at org.aspectj.weaver.bcel.BcelWeaver.weave(BcelWeaver.java:1097) at org.aspectj.weaver.tools.WeavingAdaptor.getWovenBytes(WeavingAdaptor.java:263) at org.aspectj.weaver.tools.WeavingAdaptor.weaveClass(WeavingAdaptor.java:196) at org.aspectj.weaver.loadtime.Aj.preProcess(Aj.java:65) at org.aspectj.weaver.loadtime.ClassPreProcessorAgentAdapter.transform(ClassPreProcessorAgentAdapter.java:52) at sun.instrument.TransformerManager.transform(TransformerManager.java:122) at sun.instrument.InstrumentationImpl.transform(InstrumentationImpl.java:155) at java.lang.ClassLoader.defineClass1(Native Method) at java.lang.ClassLoader.defineClass(ClassLoader.java:620) at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:124) at java.net.URLClassLoader.defineClass(URLClassLoader.java:260) at java.net.URLClassLoader.access$100(URLClassLoader.java:56) at java.net.URLClassLoader$1.run(URLClassLoader.java:195) at java.security.AccessController.doPrivileged(Native Method) at java.net.URLClassLoader.findClass(URLClassLoader.java:188) at java.lang.ClassLoader.loadClass(ClassLoader.java:306) at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:268) at java.lang.ClassLoader.loadClass(ClassLoader.java:251) at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:319) org.aspectj.bridge.AbortException: trouble in: public class Hello extends java.lang.Object: public void <init>(): ALOAD_0 // Hello this (line 2) INVOKESPECIAL java.lang.Object.<init> ()V constructor-execution(void Hello.<init>()) | RETURN constructor-execution(void Hello.<init>()) end public void <init>() public static void main(String[]) org.aspectj.weaver.MethodDeclarationLineNumber: 7:75 : INVOKESTATIC Hello.sayHello ()V (line 9) RETURN (line 10) end public static void main(String[]) public static void sayHello() org.aspectj.weaver.MethodDeclarationLineNumber: 12:180 : end public static void sayHello() public static int sayWorld() org.aspectj.weaver.MethodDeclarationLineNumber: 17:268 : method-execution(int Hello.sayWorld()) | GETSTATIC java.lang.System.out Ljava/io/PrintStream; (line 18) | LDC "World" | INVOKEVIRTUAL java.io.PrintStream.println (Ljava/lang/String;)V | ICONST_0 (line 19) | IRETURN method-execution(int Hello.sayWorld()) end public static int sayWorld() static final void sayHello_aroundBody0(): GETSTATIC java.lang.System.out Ljava/io/PrintStream; (line 13) LDC "Hello" INVOKEVIRTUAL java.io.PrintStream.println (Ljava/lang/String;)V INVOKESTATIC Hello.sayWorld ()I (line 14) POP RETURN (line 15) end static final void sayHello_aroundBody0() end public class Hello public class Hello$AjcClosure1 extends org.aspectj.runtime.internal.AroundClosure: public void <init>(Object[]): ALOAD_0 ALOAD_1 INVOKESPECIAL org.aspectj.runtime.internal.AroundClosure.<init> ([Ljava/lang/Object;)V RETURN end public void <init>(Object[]) public Object run(Object[]): ALOAD_0 GETFIELD org.aspectj.runtime.internal.AroundClosure.state [Ljava/lang/Object; ASTORE_2 INVOKESTATIC Hello.sayHello_aroundBody0 ()V ACONST_NULL ARETURN end public Object run(Object[]) end public class Hello$AjcClosure1 at org.aspectj.bridge.MessageWriter.handleMessage(MessageWriter.java:47) at org.aspectj.weaver.tools.WeavingAdaptor$WeavingAdaptorMessageHandler.handleMessage(WeavingAdaptor.java:395) at org.aspectj.weaver.bcel.BcelWeaver.weave(BcelWeaver.java:1554) at org.aspectj.weaver.bcel.BcelWeaver.weaveWithoutDump(BcelWeaver.java:1494) at org.aspectj.weaver.bcel.BcelWeaver.weaveAndNotify(BcelWeaver.java:1275) at org.aspectj.weaver.bcel.BcelWeaver.weave(BcelWeaver.java:1097) at org.aspectj.weaver.tools.WeavingAdaptor.getWovenBytes(WeavingAdaptor.java:263) at org.aspectj.weaver.tools.WeavingAdaptor.weaveClass(WeavingAdaptor.java:196) at org.aspectj.weaver.loadtime.Aj.preProcess(Aj.java:65) at org.aspectj.weaver.loadtime.ClassPreProcessorAgentAdapter.transform(ClassPreProcessorAgentAdapter.java:52) at sun.instrument.TransformerManager.transform(TransformerManager.java:122) at sun.instrument.InstrumentationImpl.transform(InstrumentationImpl.java:155) at java.lang.ClassLoader.defineClass1(Native Method) at java.lang.ClassLoader.defineClass(ClassLoader.java:620) at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:124) at java.net.URLClassLoader.defineClass(URLClassLoader.java:260) at java.net.URLClassLoader.access$100(URLClassLoader.java:56) at java.net.URLClassLoader$1.run(URLClassLoader.java:195) at java.security.AccessController.doPrivileged(Native Method) at java.net.URLClassLoader.findClass(URLClassLoader.java:188) at java.lang.ClassLoader.loadClass(ClassLoader.java:306) at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:268) at java.lang.ClassLoader.loadClass(ClassLoader.java:251) at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:319) Hello World
|
resolved fixed
|
a778ac4
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2005-12-21T17:21:57Z | 2005-12-19T11:00:00Z |
tests/bugs150/pr121385/WorldAt.java
| |
121,385 |
Bug 121385 around advice does not work when LTW
|
I defined a aop.xml and a aspect, I have already copy aspectjweaver.jar D:\work\BTM\lib\aspectjweaver.jar, and added -javaagent:D:\work\BTM\lib\aspectjweaver.jar option to the JVM in Eclipse, it works fine if there are before and after advice in aspect, but it will be wrong once I used around advice. if I use compile-time weaving, this around advice works fine. my Eclipse env: eclipse 3.0.2 + AJDT 1.2.1 RC1 release + Sun JDK 1.5.0. aspect file: import org.aspectj.lang.Signature; import org.aspectj.lang.JoinPoint; public abstract aspect World { //private Object result; pointcut greeting() : execution(* Hello.sayWorld(..)); Object around(): greeting() { System.out.println("around start!"); Object result = proceed(); System.out.println("around end!"); return result; } // before() : greeting() { // Signature signature = thisJoinPoint.getSignature(); // System.out.println("before " + signature.getName()); // } // after() returning () : greeting() { // Signature signature = thisJoinPoint.getSignature(); // System.out.println("after " + signature.getName()); // } } aop.xml file: <?xml version="1.0" encoding="UTF-8"?> <aspectj> <aspects> <aspect name="World"/> <concrete-aspect name="World1" extends="World"> <pointcut name="greeting" expression="execution(* Hello.sayWorld(..)) || execution(* Hello.sayHello(..))"/> </concrete-aspect> </aspects> <weaver options="-Xreweavable -verbose -XlazyTjp -showWeaveInfo"> <include within="Hello"/> </weaver> </aspectj> around advice error message in eclipse console as below: info register aspect World info generating class 'World1' info weaving 'Hello' info weaver operating in reweavable mode. Need to verify any required types exist. abort trouble in: public class Hello extends java.lang.Object: public void <init>(): ALOAD_0 // Hello this (line 2) INVOKESPECIAL java.lang.Object.<init> ()V constructor-execution(void Hello.<init>()) | RETURN constructor-execution(void Hello.<init>()) end public void <init>() public static void main(String[]) org.aspectj.weaver.MethodDeclarationLineNumber: 7:75 : INVOKESTATIC Hello.sayHello ()V (line 9) RETURN (line 10) end public static void main(String[]) public static void sayHello() org.aspectj.weaver.MethodDeclarationLineNumber: 12:180 : end public static void sayHello() public static int sayWorld() org.aspectj.weaver.MethodDeclarationLineNumber: 17:268 : method-execution(int Hello.sayWorld()) | GETSTATIC java.lang.System.out Ljava/io/PrintStream; (line 18) | LDC "World" | INVOKEVIRTUAL java.io.PrintStream.println (Ljava/lang/String;)V | ICONST_0 (line 19) | IRETURN method-execution(int Hello.sayWorld()) end public static int sayWorld() static final void sayHello_aroundBody0(): GETSTATIC java.lang.System.out Ljava/io/PrintStream; (line 13) LDC "Hello" INVOKEVIRTUAL java.io.PrintStream.println (Ljava/lang/String;)V INVOKESTATIC Hello.sayWorld ()I (line 14) POP RETURN (line 15) end static final void sayHello_aroundBody0() end public class Hello public class Hello$AjcClosure1 extends org.aspectj.runtime.internal.AroundClosure: public void <init>(Object[]): ALOAD_0 ALOAD_1 INVOKESPECIAL org.aspectj.runtime.internal.AroundClosure.<init> ([Ljava/lang/Object;)V RETURN end public void <init>(Object[]) public Object run(Object[]): ALOAD_0 GETFIELD org.aspectj.runtime.internal.AroundClosure.state [Ljava/lang/Object; ASTORE_2 INVOKESTATIC Hello.sayHello_aroundBody0 ()V ACONST_NULL ARETURN end public Object run(Object[]) end public class Hello$AjcClosure1 -- (NullPointerException) null null java.lang.NullPointerException at org.aspectj.weaver.bcel.BcelAdvice.getAdviceArgSetup(BcelAdvice.java:457) at org.aspectj.weaver.bcel.BcelShadow.weaveAroundClosure(BcelShadow.java:2685) at org.aspectj.weaver.bcel.BcelAdvice.implementOn(BcelAdvice.java:230) at org.aspectj.weaver.Shadow.implementMungers(Shadow.java:588) at org.aspectj.weaver.Shadow.implement(Shadow.java:405) at org.aspectj.weaver.bcel.BcelClassWeaver.implement(BcelClassWeaver.java:2146) at org.aspectj.weaver.bcel.BcelClassWeaver.weave(BcelClassWeaver.java:467) at org.aspectj.weaver.bcel.BcelClassWeaver.weave(BcelClassWeaver.java:102) at org.aspectj.weaver.bcel.BcelWeaver.weave(BcelWeaver.java:1543) at org.aspectj.weaver.bcel.BcelWeaver.weaveWithoutDump(BcelWeaver.java:1494) at org.aspectj.weaver.bcel.BcelWeaver.weaveAndNotify(BcelWeaver.java:1275) at org.aspectj.weaver.bcel.BcelWeaver.weave(BcelWeaver.java:1097) at org.aspectj.weaver.tools.WeavingAdaptor.getWovenBytes(WeavingAdaptor.java:263) at org.aspectj.weaver.tools.WeavingAdaptor.weaveClass(WeavingAdaptor.java:196) at org.aspectj.weaver.loadtime.Aj.preProcess(Aj.java:65) at org.aspectj.weaver.loadtime.ClassPreProcessorAgentAdapter.transform(ClassPreProcessorAgentAdapter.java:52) at sun.instrument.TransformerManager.transform(TransformerManager.java:122) at sun.instrument.InstrumentationImpl.transform(InstrumentationImpl.java:155) at java.lang.ClassLoader.defineClass1(Native Method) at java.lang.ClassLoader.defineClass(ClassLoader.java:620) at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:124) at java.net.URLClassLoader.defineClass(URLClassLoader.java:260) at java.net.URLClassLoader.access$100(URLClassLoader.java:56) at java.net.URLClassLoader$1.run(URLClassLoader.java:195) at java.security.AccessController.doPrivileged(Native Method) at java.net.URLClassLoader.findClass(URLClassLoader.java:188) at java.lang.ClassLoader.loadClass(ClassLoader.java:306) at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:268) at java.lang.ClassLoader.loadClass(ClassLoader.java:251) at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:319) Message: abort trouble in: public class Hello extends java.lang.Object: public void <init>(): ALOAD_0 // Hello this (line 2) INVOKESPECIAL java.lang.Object.<init> ()V constructor-execution(void Hello.<init>()) | RETURN constructor-execution(void Hello.<init>()) end public void <init>() public static void main(String[]) org.aspectj.weaver.MethodDeclarationLineNumber: 7:75 : INVOKESTATIC Hello.sayHello ()V (line 9) RETURN (line 10) end public static void main(String[]) public static void sayHello() org.aspectj.weaver.MethodDeclarationLineNumber: 12:180 : end public static void sayHello() public static int sayWorld() org.aspectj.weaver.MethodDeclarationLineNumber: 17:268 : method-execution(int Hello.sayWorld()) | GETSTATIC java.lang.System.out Ljava/io/PrintStream; (line 18) | LDC "World" | INVOKEVIRTUAL java.io.PrintStream.println (Ljava/lang/String;)V | ICONST_0 (line 19) | IRETURN method-execution(int Hello.sayWorld()) end public static int sayWorld() static final void sayHello_aroundBody0(): GETSTATIC java.lang.System.out Ljava/io/PrintStream; (line 13) LDC "Hello" INVOKEVIRTUAL java.io.PrintStream.println (Ljava/lang/String;)V INVOKESTATIC Hello.sayWorld ()I (line 14) POP RETURN (line 15) end static final void sayHello_aroundBody0() end public class Hello public class Hello$AjcClosure1 extends org.aspectj.runtime.internal.AroundClosure: public void <init>(Object[]): ALOAD_0 ALOAD_1 INVOKESPECIAL org.aspectj.runtime.internal.AroundClosure.<init> ([Ljava/lang/Object;)V RETURN end public void <init>(Object[]) public Object run(Object[]): ALOAD_0 GETFIELD org.aspectj.runtime.internal.AroundClosure.state [Ljava/lang/Object; ASTORE_2 INVOKESTATIC Hello.sayHello_aroundBody0 ()V ACONST_NULL ARETURN end public Object run(Object[]) end public class Hello$AjcClosure1 -- (NullPointerException) null null java.lang.NullPointerException at org.aspectj.weaver.bcel.BcelAdvice.getAdviceArgSetup(BcelAdvice.java:457) at org.aspectj.weaver.bcel.BcelShadow.weaveAroundClosure(BcelShadow.java:2685) at org.aspectj.weaver.bcel.BcelAdvice.implementOn(BcelAdvice.java:230) at org.aspectj.weaver.Shadow.implementMungers(Shadow.java:588) at org.aspectj.weaver.Shadow.implement(Shadow.java:405) at org.aspectj.weaver.bcel.BcelClassWeaver.implement(BcelClassWeaver.java:2146) at org.aspectj.weaver.bcel.BcelClassWeaver.weave(BcelClassWeaver.java:467) at org.aspectj.weaver.bcel.BcelClassWeaver.weave(BcelClassWeaver.java:102) at org.aspectj.weaver.bcel.BcelWeaver.weave(BcelWeaver.java:1543) at org.aspectj.weaver.bcel.BcelWeaver.weaveWithoutDump(BcelWeaver.java:1494) at org.aspectj.weaver.bcel.BcelWeaver.weaveAndNotify(BcelWeaver.java:1275) at org.aspectj.weaver.bcel.BcelWeaver.weave(BcelWeaver.java:1097) at org.aspectj.weaver.tools.WeavingAdaptor.getWovenBytes(WeavingAdaptor.java:263) at org.aspectj.weaver.tools.WeavingAdaptor.weaveClass(WeavingAdaptor.java:196) at org.aspectj.weaver.loadtime.Aj.preProcess(Aj.java:65) at org.aspectj.weaver.loadtime.ClassPreProcessorAgentAdapter.transform(ClassPreProcessorAgentAdapter.java:52) at sun.instrument.TransformerManager.transform(TransformerManager.java:122) at sun.instrument.InstrumentationImpl.transform(InstrumentationImpl.java:155) at java.lang.ClassLoader.defineClass1(Native Method) at java.lang.ClassLoader.defineClass(ClassLoader.java:620) at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:124) at java.net.URLClassLoader.defineClass(URLClassLoader.java:260) at java.net.URLClassLoader.access$100(URLClassLoader.java:56) at java.net.URLClassLoader$1.run(URLClassLoader.java:195) at java.security.AccessController.doPrivileged(Native Method) at java.net.URLClassLoader.findClass(URLClassLoader.java:188) at java.lang.ClassLoader.loadClass(ClassLoader.java:306) at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:268) at java.lang.ClassLoader.loadClass(ClassLoader.java:251) at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:319) org.aspectj.bridge.AbortException: trouble in: public class Hello extends java.lang.Object: public void <init>(): ALOAD_0 // Hello this (line 2) INVOKESPECIAL java.lang.Object.<init> ()V constructor-execution(void Hello.<init>()) | RETURN constructor-execution(void Hello.<init>()) end public void <init>() public static void main(String[]) org.aspectj.weaver.MethodDeclarationLineNumber: 7:75 : INVOKESTATIC Hello.sayHello ()V (line 9) RETURN (line 10) end public static void main(String[]) public static void sayHello() org.aspectj.weaver.MethodDeclarationLineNumber: 12:180 : end public static void sayHello() public static int sayWorld() org.aspectj.weaver.MethodDeclarationLineNumber: 17:268 : method-execution(int Hello.sayWorld()) | GETSTATIC java.lang.System.out Ljava/io/PrintStream; (line 18) | LDC "World" | INVOKEVIRTUAL java.io.PrintStream.println (Ljava/lang/String;)V | ICONST_0 (line 19) | IRETURN method-execution(int Hello.sayWorld()) end public static int sayWorld() static final void sayHello_aroundBody0(): GETSTATIC java.lang.System.out Ljava/io/PrintStream; (line 13) LDC "Hello" INVOKEVIRTUAL java.io.PrintStream.println (Ljava/lang/String;)V INVOKESTATIC Hello.sayWorld ()I (line 14) POP RETURN (line 15) end static final void sayHello_aroundBody0() end public class Hello public class Hello$AjcClosure1 extends org.aspectj.runtime.internal.AroundClosure: public void <init>(Object[]): ALOAD_0 ALOAD_1 INVOKESPECIAL org.aspectj.runtime.internal.AroundClosure.<init> ([Ljava/lang/Object;)V RETURN end public void <init>(Object[]) public Object run(Object[]): ALOAD_0 GETFIELD org.aspectj.runtime.internal.AroundClosure.state [Ljava/lang/Object; ASTORE_2 INVOKESTATIC Hello.sayHello_aroundBody0 ()V ACONST_NULL ARETURN end public Object run(Object[]) end public class Hello$AjcClosure1 at org.aspectj.bridge.MessageWriter.handleMessage(MessageWriter.java:47) at org.aspectj.weaver.tools.WeavingAdaptor$WeavingAdaptorMessageHandler.handleMessage(WeavingAdaptor.java:395) at org.aspectj.weaver.bcel.BcelWeaver.weave(BcelWeaver.java:1554) at org.aspectj.weaver.bcel.BcelWeaver.weaveWithoutDump(BcelWeaver.java:1494) at org.aspectj.weaver.bcel.BcelWeaver.weaveAndNotify(BcelWeaver.java:1275) at org.aspectj.weaver.bcel.BcelWeaver.weave(BcelWeaver.java:1097) at org.aspectj.weaver.tools.WeavingAdaptor.getWovenBytes(WeavingAdaptor.java:263) at org.aspectj.weaver.tools.WeavingAdaptor.weaveClass(WeavingAdaptor.java:196) at org.aspectj.weaver.loadtime.Aj.preProcess(Aj.java:65) at org.aspectj.weaver.loadtime.ClassPreProcessorAgentAdapter.transform(ClassPreProcessorAgentAdapter.java:52) at sun.instrument.TransformerManager.transform(TransformerManager.java:122) at sun.instrument.InstrumentationImpl.transform(InstrumentationImpl.java:155) at java.lang.ClassLoader.defineClass1(Native Method) at java.lang.ClassLoader.defineClass(ClassLoader.java:620) at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:124) at java.net.URLClassLoader.defineClass(URLClassLoader.java:260) at java.net.URLClassLoader.access$100(URLClassLoader.java:56) at java.net.URLClassLoader$1.run(URLClassLoader.java:195) at java.security.AccessController.doPrivileged(Native Method) at java.net.URLClassLoader.findClass(URLClassLoader.java:188) at java.lang.ClassLoader.loadClass(ClassLoader.java:306) at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:268) at java.lang.ClassLoader.loadClass(ClassLoader.java:251) at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:319) Hello World
|
resolved fixed
|
a778ac4
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2005-12-21T17:21:57Z | 2005-12-19T11:00:00Z |
tests/src/org/aspectj/systemtest/ajc150/Ajc150Tests.java
|
/*******************************************************************************
* Copyright (c) 2004 IBM
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* Andy Clement - initial API and implementation
*******************************************************************************/
package org.aspectj.systemtest.ajc150;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.List;
import junit.framework.Test;
import org.aspectj.apache.bcel.classfile.JavaClass;
import org.aspectj.apache.bcel.classfile.Method;
import org.aspectj.apache.bcel.classfile.Signature;
import org.aspectj.apache.bcel.util.ClassPath;
import org.aspectj.apache.bcel.util.SyntheticRepository;
import org.aspectj.asm.AsmManager;
import org.aspectj.asm.IHierarchy;
import org.aspectj.asm.IProgramElement;
import org.aspectj.asm.IRelationship;
import org.aspectj.asm.internal.Relationship;
import org.aspectj.testing.XMLBasedAjcTestCase;
import org.aspectj.util.LangUtil;
public class Ajc150Tests extends org.aspectj.testing.XMLBasedAjcTestCase {
public static Test suite() {
return XMLBasedAjcTestCase.loadSuite(Ajc150Tests.class);
}
protected File getSpecFile() {
return new File("../tests/src/org/aspectj/systemtest/ajc150/ajc150.xml");
}
public void testTypeVars_pr121575() { runTest("different numbers of type vars");}
public void testTypeVars_pr121575_2() { runTest("different numbers of type vars - 2");}
public void testTypeVars_pr121575_3() { runTest("different numbers of type vars - 3");}
public void testTypeVars_pr121575_4() { runTest("different numbers of type vars - 4");}
public void testDecps1() { runTest("decps - 1"); }
public void testDecps1b() { runTest("decps - 1b"); }
public void testDecps2() { runTest("decps - 2"); }
public void testDecps2b() { runTest("decps - 2b"); }
public void testDecps3() { runTest("decps - 3"); }
public void testDecps3b() { runTest("decps - 3b"); }
public void testDecps3c() { runTest("decps - 3c"); }
public void testVarargsNPE_pr120826() { runTest("varargs NPE");}
public void testNamedPointcutPertarget_pr120521() { runTest("named pointcut not resolved in pertarget pointcut");}
public void testDollarClasses_pr120474() { runTest("Dollar classes");}
public void testGenericPTW_pr119539_1() { runTest("generic pertypewithin aspect - 1");}
public void testGenericPTW_pr119539_2() { runTest("generic pertypewithin aspect - 2");}
public void testGenericPTW_pr119539_3() { runTest("generic pertypewithin aspect - 3");}
/*
public void testBrokenDispatchByITD_pr72834() { runTest("broken dispatch");}
public void testMissingAccessor_pr73856() { runTest("missing accessor");}
public void testCunningDeclareParents_pr92311() { runTest("cunning declare parents");}
public void testGenericITDsAndAbstractMethodError_pr102357() { runTest("generic itds and abstract method error");}
*/
public void testIncorrectSignatureMatchingWithExceptions_pr119749() { runTest("incorrect exception signature matching");}
public void testGeneratingCodeForAnOldRuntime_pr116679_1() { runTest("generating code for a 1.2.1 runtime - 1");}
public void testGeneratingCodeForAnOldRuntime_pr116679_2() { runTest("generating code for a 1.2.1 runtime - 2");}
public void testAmbiguousMethod_pr118599_1() { runTest("ambiguous method when binary weaving - 1");}
public void testAmbiguousMethod_pr118599_2() { runTest("ambiguous method when binary weaving - 2");}
public void testAroundAdviceArrayAdviceSigs_pr118781() { runTest("verify error with around advice array sigs");}
public void testAtDeclareParents_pr117681() { runTest("at declare parents");}
public void testPrivilegeProblem_pr87525() { runTest("privilege problem with switch");}
public void testRangeProblem_pr109614() { runTest("Range problem");}
public void testGenericAspects_pr115237() { runTest("aspectOf and generic aspects");}
public void testClassFormatError_pr114436() { runTest("ClassFormatError binary weaving perthis");}
public void testParserException_pr115788() { runTest("parser exception");}
public void testPossibleStaticImports_pr113066_1() { runTest("possible static imports bug - 1");}
public void testPossibleStaticImports_pr113066_2() { runTest("possible static imports bug - 2");}
public void testPossibleStaticImports_pr113066_3() { runTest("possible static imports bug - 3");}
public void testITDCtor_pr112783() { runTest("Problem with constructor ITDs");}
public void testAnnotatedITDFs_pr114005_1() { runTest("Annotated ITDFs - 1");}
public void testAnnotatedITDFs_pr114005_2() { runTest("Annotated ITDFs - 2");}
public void testCantCallSuperMethods_pr90143() { runTest("cant call super methods");}
public void testBrokenDecp_pr112476() { runTest("binary weaving decp broken");}
public void testUnboundFormal_pr112027() { runTest("unexpected error unboundFormalInPC");}
public void testNPEScopeSetup_pr115038() { runTest("NPE in ensureScopeSetup");}
public void testCCEGenerics_pr113445() { runTest("Generics ClassCastException");}
public void testMatthewsAspect_pr113947_1() { runTest("maws generic aspect - 1");}
public void testMatthewsAspect_pr113947_2() { runTest("maws generic aspect - 2");}
public void testFieldGet_pr114343() { runTest("field-get, generics and around advice");}
public void testFieldGet_pr114343_2() { runTest("field-get, generics and around advice - 2");}
public void testFieldGet_pr114343_3() { runTest("field-get, generics and around advice - 3");}
public void testCaptureBinding_pr114744() { runTest("capturebinding wildcard problem");}
public void testAutoboxingAroundAdvice_pr119210_1() { runTest("autoboxing around advice - 1");}
public void testAutoboxingAroundAdvice_pr119210_2() { runTest("autoboxing around advice - 2");}
public void testAutoboxingAroundAdvice_pr119210_3() { runTest("autoboxing around advice - 3");}
public void testBadDecp_pr110788_1() { runTest("bad generic decp - 1");}
public void testBadDecp_pr110788_2() { runTest("bad generic decp - 2");}
public void testBadDecp_pr110788_3() { runTest("bad generic decp - 3");}
public void testBadDecp_pr110788_4() { runTest("bad generic decp - 4");}
public void testSpuriousOverrideMethodWarning_pr119570_1() { runTest("spurious override method warning");}
public void testSpuriousOverrideMethodWarning_pr119570_2() { runTest("spurious override method warning - 2");}
public void testBrokenSwitch_pr117854() { runTest("broken switch transform");}
public void testVarargsITD_pr110906() { runTest("ITD varargs problem");}
public void testBadRenderer_pr86903() { runTest("bcelrenderer bad");}
//public void testIllegalInitialization_pr118326_1() { runTest("illegal initialization - 1");}
//public void testIllegalInitialization_pr118326_2() { runTest("illegal initialization - 2");}
public void testLintForAdviceSorting_pr111667() { runTest("lint for advice sorting");}
public void testIncompatibleClassChangeError_pr113630_1() {runTest("IncompatibleClassChangeError - errorscenario");}
public void testIncompatibleClassChangeError_pr113630_2() {runTest("IncompatibleClassChangeError - workingscenario");}
public void testFieldGetProblemWithGenericField_pr113861() {runTest("field-get problems with generic field");}
public void testAccesstoPrivateITDInNested_pr118698() { runTest("access to private ITD from nested type");}
public void testDeclareAnnotationOnNonExistentType_pr99191_1() { runTest("declare annotation on non existent type - 1");}
public void testDeclareAnnotationOnNonExistentType_pr99191_2() { runTest("declare annotation on non existent type - 2");}
public void testDeclareAnnotationOnNonExistentType_pr99191_3() { runTest("declare annotation on non existent type - 3");}
public void testDeclareAnnotationOnNonExistentType_pr99191_4() { runTest("declare annotation on non existent type - 4");}
public void testDeclareAnnotationOnNonExistentType_pr99191_5() { runTest("declare annotation on non existent type - 5");}
public void testBadGenericSigAttribute_pr110927() {
runTest("cant create signature attribute");
Signature sig = GenericsTests.getClassSignature(ajc,"I");
if (sig==null) fail("Couldn't find signature attribute for type I");
String sigString = sig.getSignature();
if (!(sigString.equals("Ljava/lang/Object;LIE2;LIE1<Ljava/lang/String;>;") ||
sigString.equals("Ljava/lang/Object;LIE1<Ljava/lang/String;>;LIE2;"))) {
fail("Signature was "+sigString+" when should have been something like Ljava/lang/Object;LIE1<Ljava/lang/String;>;LIE2;");
}
}
public void test_typeProcessingOrderWhenDeclareParents() {
runTest("Order of types passed to compiler determines weaving behavior");
}
public void test_aroundMethod() {
runTest("method called around in class");
}
public void test_aroundMethodAspect() {
runTest("method called around in aspect");
}
public void test_ambiguousBindingsDetection() {
runTest("Various kinds of ambiguous bindings");
}
public void test_ambiguousArgsDetection() {
runTest("ambiguous args");
}
public void testIncorrectExceptionTableWhenBreakInMethod_pr78021() {
runTest("Injecting exception into while loop with break statement causes catch block to be ignored");
}
public void testIncorrectExceptionTableWhenReturnInMethod_pr79554() {
runTest("Return in try-block disables catch-block if final-block is present");
}
public void testMissingDebugInfoForGeneratedMethods_pr82570() throws ClassNotFoundException {
runTest("Weaved code does not include debug lines");
boolean f = false;
JavaClass jc = getClassFrom(ajc.getSandboxDirectory(),"PR82570_1");
Method[] meths = jc.getMethods();
for (int i = 0; i < meths.length; i++) {
Method method = meths[i];
if (f) System.err.println("Line number table for "+method.getName()+method.getSignature()+" = "+method.getLineNumberTable());
assertTrue("Didn't find a line number table for method "+method.getName()+method.getSignature(),
method.getLineNumberTable()!=null);
}
// This test would determine the info isn't there if you pass -g:none ...
// cR = ajc(baseDir,new String[]{"PR82570_1.java","-g:none"});
// assertTrue("Expected no compile problem:"+cR,!cR.hasErrorMessages());
// System.err.println(cR.getStandardError());
// jc = getClassFrom(ajc.getSandboxDirectory(),"PR82570_1");
// meths = jc.getMethods();
// for (int i = 0; i < meths.length; i++) {
// Method method = meths[i];
// assertTrue("Found a line number table for method "+method.getName(),
// method.getLineNumberTable()==null);
// }
}
public void testCanOverrideProtectedMethodsViaITDandDecp_pr83303() {
runTest("compiler error when mixing inheritance, overriding and polymorphism");
}
public void testPerTypeWithin_pr106554() {runTest("Problem in staticinitialization with pertypewithin aspect");}
public void testPerTypeWithinMissesNamedInnerTypes() {
runTest("pertypewithin() handing of inner classes (1)");
}
public void testPerTypeWithinMissesAnonymousInnerTypes() {
runTest("pertypewithin() handing of inner classes (2)");
}
public void testPerTypeWithinIncorrectlyMatchingInterfaces() {
runTest("pertypewithin({interface}) illegal field modifier");
}
public void test051_arrayCloningInJava5() {
runTest("AJC possible bug with static nested classes");
}
public void testBadASMforEnums() throws IOException {
runTest("bad asm for enums");
if (LangUtil.is15VMOrGreater()) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
PrintWriter pw = new PrintWriter(baos);
AsmManager.dumptree(pw,AsmManager.getDefault().getHierarchy().getRoot(),0);
pw.flush();
String tree = baos.toString();
assertTrue("Expected 'Red [enumvalue]' somewhere in here:"+tree,tree.indexOf("Red [enumvalue]")!=-1);
}
}
public void npeOnTypeNotFound() {
runTest("structure model npe on type not found");
}
public void testNoRuntimeExceptionSoftening() {
runTest("declare soft of runtime exception");
}
public void testRuntimeNoSoftenWithHandler() {
runTest("declare soft w. catch block");
}
public void testSyntaxError() {
runTest("invalid cons syntax");
}
public void testVarargsInConsBug() {
runTest("varargs in constructor sig");
}
public void testAspectpathdirs() {
runTest("dirs on aspectpath");
}
public void testIntroSample() {
runTest("introduction sample");
}
public void testPTWInterface() {
runTest("pertypewithin({interface}) illegal field modifier");
}
public void testEnumCalledEnumEtc() {
runTest("enum called Enum, annotation called Annotation, etc");
}
public void testInternalCompilerError_pr86832() {
runTest("Internal compiler error");
}
public void testCloneMethod_pr83311() {
runTest("overriding/polymorphism error on interface method introduction");
}
// IfPointcut.findResidueInternal() was modified to make this test complete in a short amount
// of time - if you see it hanging, someone has messed with the optimization.
public void testIfEvaluationExplosion_pr94086() {
runTest("Exploding compile time with if() statements in pointcut");
}
public void testReflectNPE_pr94167() {runTest("NPE in reflect implementation");}
public void testStaticImports_pr84260() {runTest("static import failures");}
public void testGenerics_pr99089() {runTest("ArrayIndexOutOfBoundsException - Generics in privileged aspects");}
public void testGenerics_pr95993() {runTest("NPE at ClassScope.java:660 when compiling generic class");}
public void testItdGenerics_pr99228() {runTest("ITD of a field into a generic class");}
public void testItdGenerics_pr98320() {runTest("intertype with nested generic type");}
public void testItdGenerics_pr100227() {runTest("inner class with generic enclosing class");}
public void testItdGenerics_pr100260() {runTest("methods inherited from a generic parent");}
public void testSyntaxErrorNPE_pr103266() {runTest("NPE on syntax error");}
public void testFinalAbstractClass_pr109486() { runTest("Internal compiler error (ClassParser.java:242)");}
public void testComplexBinding_pr102210() { runTest("NullPointerException trying to compile");}
public void testIllegalStateExceptionOnNestedParameterizedType_pr106634() {
runTest("IllegalStateException unpacking signature of nested parameterized type");
}
public void testParseErrorOnAnnotationStarPlusPattern() {
runTest("(@Foo *)+ type pattern parse error");
}
public void test_pr106130_tooManyLocals() {
runTest("test weaving with > 256 locals");
}
public void testMissingNamePattern_pr106461() { runTest("missing name pattern"); }
public void testMissingNamePattern_pr107059() {
runTest("parser crashes on call(void (@a *)(..)");
}
public void testIntermediateAnnotationMatching() {
runTest("intermediate annotation matching");
}
public void testBadRuntimeTestGeneration() {
runTest("target(@Foo *)");
}
public void testErrorMessageOnITDWithTypePatterns() {
runTest("clear error message on itd with type pattern");
}
public void testAjKeywordsAsIdentifiers() {
runTest("before and after are valid identifiers in classes");
}
public void testAjKeywordsAsIdentifiers2() {
runTest("before and after are valid identifiers in classes, part 2");
}
public void testNoBeforeReturningAdvice() {
runTest("before returning advice not allowed!");
}
public void testDetectVoidFieldType() {
runTest("void field type in pointcut expression");
}
public void testPointcutOverriding() {
runTest("overriding final pointcut from super-aspect");
}
public void testAtSuppressWarnings() {
runTest("@SuppressWarnings should suppress");
}
public void testDEOWWithBindingPointcut() {
runTest("declare warning : foo(str) : ...;");
}
public void testAroundAdviceAndInterfaceInitializer() {
runTest("around advice on interface initializer");
}
public void testGoodErrorMessageOnUnmatchedMemberSyntax() {
runTest("good error message for unmatched member syntax");
}
public void testITDWithNoExceptionAndIntermediary() {
runTest("itd override with no exception clause");
}
public void testAnonymousInnerClasses() {
runTest("anonymous inner classes");
}
public void testMultipleAnonymousInnerClasses() {
runTest("multiple anonymous inner classes");
}
public void testPrivilegedMethodAccessorsGetRightExceptions_pr82989() {
runTest("Compiler error due to a wrong exception check in try blocks");
}
public void testAnonymousInnerClassWithMethodReturningTypeParameter_pr107898() {
runTest("anonymous inner class with method returning type parameter");
}
public void testMatchingOfObjectArray() {
runTest("matching against Object[]");
}
public void testMultipleAnonymousInnerClasses_pr108104() {
runTest("multiple anonymous inner classes 2");
}
public void testSignatureMatchingInMultipleOverrideScenario() {
runTest("signature matching in override scenario");
}
public void testWildcardAnnotationMatching_pr108245() {
runTest("wildcard annotation matching - pr108245");
}
public void testInnerTypesAndTypeVariables() {
runTest("inner types and type variables");
}
public void testAtAfterThrowingWithNoFormal() {
runTest("@AfterThrowing with no formal specified");
}
public void testParameterizedVarArgsMatch() {
runTest("varargs with type variable");
}
public void testFieldAccessInsideITDM() {
runTest("itd field access inside itd method");
}
public void testTypeVarWithTypeVarBound() {
runTest("type variable with type variable bound");
}
public void testEnumSwitchInITD() {
runTest("switch on enum inside ITD method");
}
public void testInnerTypeOfGeneric() {
runTest("inner type of generic interface reference from parameterized type");
}
public void testDeclareParentsIntroducingCovariantReturnType() {
runTest("declare parents introducing override with covariance");
}
public void testInnerClassPassedToVarargs() {
runTest("inner class passed as argument to varargs method");
}
public void testInlinedFieldAccessInProceedCall() {
runTest("inlined field access in proceed call");
}
public void testVisibiltyInSignatureMatchingWithOverridesPart1() {
runTest("visibility in signature matching with overrides - 1");
}
public void testVisibiltyInSignatureMatchingWithOverridesPart2() {
runTest("visibility in signature matching with overrides - 2");
}
public void testVisibiltyInSignatureMatchingWithOverridesPart3() {
runTest("visibility in signature matching with overrides - 3");
}
public void testArgsGeneratedCorrectlyForAdviceExecution() {
runTest("args generated correctly for advice execution join point");
}
public void testNoUnusedWarningsOnAspectTypes() {
runTest("no unused warnings on aspect types");
}
public void testSyntheticArgumentsOnITDConstructorsNotUsedInMatching() {
runTest("synthetic arguments on itd cons are not used in matching");
}
public void testParsingOfGenericTypeSignature() {
runTest("parse generic type signature with parameterized type in interface");
}
public void testOverrideAndCovarianceWithDecPRuntime() {
runTest("override and covariance with decp - runtime");
}
public void testOverrideAndCovarianceWithDecPRuntimeMultiFiles() {
runTest("override and covariance with decp - runtime separate files");
}
public void testOverrideAndCovarianceWithDecPRuntimeMultiFilesBinaryWeaving() {
runTest("override and covariance with decp - binary weaving");
}
public void testAbstractSynchronizedITDMethods() {
runTest("abstract synchronized itdms not detected");
}
public void testSynchronizedITDInterfaceMethods() {
runTest("synchronized itd interface methods");
}
public void testNoWarningOnUnusedPointcut() {
runTest("unused private pointcuts");
}
public void testITDOnInterfaceWithExistingMember() {
runTest("itd interface method already existing on interface");
}
public void testFinalITDMOnInterface() {
runTest("final itd methods on interfaces");
}
public void testPrivatePointcutOverriding() {
runTest("can't override private pointcut in abstract aspect");
}
public void testAdviceOnCflow() {
runTest("advising cflow advice execution");
}
public void testNoTypeMismatchOnSameGenericTypes() {
runTest("no type mismatch on generic types in itds");
}
public void testSuperCallInITD() {
runTest("super call in ITD");
}
public void testSuperCallInITDPart2() {
runTest("super call in ITD - part 2");
}
public void testAtAnnotationBadTest_pr103740() {
runTest("Compiler failure on at_annotation");
}
public void testNoUnusedParameterWarningsForSyntheticAdviceArgs() {
runTest("no unused parameter warnings for synthetic advice args");
}
public void testNoVerifyErrorWithSetOnInnerType() {
runTest("no verify error with set on inner type");
}
public void testCantFindTypeErrorWithGenericReturnTypeOrParameter() {
runTest("cant find type error with generic return type or parameter");
}
public void testNoVerifyErrorOnGenericCollectionMemberAccess() {
runTest("no verify error on generic collection member access");
}
public void testRawAndGenericTypeConversionITDCons() {
runTest("raw and generic type conversion with itd cons");
}
public void testAtAnnotationBindingWithAround() {
runTest("@annotation binding with around advice");
}
public void testUnableToBuildShadows_pr109728() { runTest("Unable to build shadows");}
public void testMessageOnMissingTypeInDecP() {
runTest("declare parents on a missing type");
}
public void testParameterizedGenericMethods() {
runTest("parameterized generic methods");
}
public void testIllegalChangeToPointcutDeclaration_pr111915() {
runTest("test illegal change to pointcut declaration");
}
public void testCantProvideDefaultImplViaITD_pr110307_1() {runTest("Cant provide default implementation via ITD - 1");}
public void testCantProvideDefaultImplViaITD_pr110307_2() {runTest("Cant provide default implementation via ITD - 2");}
public void testCantProvideDefaultImplViaITD_pr110307_3() {runTest("Cant provide default implementation via ITD - 3");}
public void testCantProvideDefaultImplViaITD_pr110307_4() {runTest("Cant provide default implementation via ITD - 4");}
public void testCantProvideDefaultImplViaITD_pr110307_5() {runTest("Cant provide default implementation via ITD - 5");}
// Needs a change in the compiler so that getType() can be overridden in the intertype scope - thats
// where we can police whether a type variable has been used without being specified appropriately.
//public void testCantProvideDefaultImplViaITD_pr110307_6() {runTest("Cant provide default implementation via ITD - 6");}
public void testCantProvideDefaultImplViaITD_pr110307_7() {runTest("Cant provide default implementation via ITD - 7");}
public void testCallJoinPointsInAnonymousInnerClasses() {
runTest("call join points in anonymous inner classes");
}
public void testNoRequirementForUnwovenTypesToBeExposedToWeaver() {
runTest("default impl of Runnable");
}
public void testArrayCloneCallJoinPoints() {
runTest("array clone call join points in 1.4 vs 1.3");
}
public void testDebugInfoForAroundAdvice() {
runTest("debug info in around advice inlining");
}
public void testCCEWithGenericWildcard_pr112602() {
runTest("ClassCastException with generic wildcard");
}
public void testAdviceInStructureModelWithAnonymousInnerClass_pr77269() {
//AsmManager.setReporting("c:/debug.txt",true,true,true,true);
runTest("advice in structure model with anonymous inner class");
IHierarchy top = AsmManager.getDefault().getHierarchy();
// checking that the run() method inside anonymous inner class is in
// the structure model
IProgramElement anonRunMethodIPE = top.findElementForLabel(top.getRoot(),
IProgramElement.Kind.METHOD,"run()");
assertNotNull("Couldn't find 'run()' element in the tree",anonRunMethodIPE);
List l = AsmManager.getDefault().getRelationshipMap().get(anonRunMethodIPE);
assertNotNull("Should have some relationships but does not",l);
assertTrue("Should have one relationship but has " + l.size(),l.size()==1);
Relationship rel = (Relationship)l.get(0);
List targets = rel.getTargets();
assertTrue("Should have one target but has" + targets.size(),
targets.size()==1);
IProgramElement target = AsmManager.getDefault().getHierarchy().findElementForHandle((String)targets.get(0));
assertEquals("target of relationship should be 'before(): p..' but is "
+ target.toLabelString(),"before(): p..",target.toLabelString());
IProgramElement adviceIPE = top.findElementForLabel(top.getRoot(),
IProgramElement.Kind.ADVICE,"before(): p..");
assertNotNull("Couldn't find 'before(): p..' element in the tree",adviceIPE);
l = AsmManager.getDefault().getRelationshipMap().get(adviceIPE);
assertNotNull("Should have some relationships but does not",l);
assertTrue("Should have a relationship but does not ",l.size()>0);
for (Iterator iter = l.iterator(); iter.hasNext();) {
IRelationship element = (IRelationship) iter.next();
if (element.getName().equals("advises")) {
rel = (Relationship) element;
break;
}
}
targets = rel.getTargets();
assertTrue("Should have one target but has" + targets.size(),
targets.size()==1);
target = AsmManager.getDefault().getHierarchy().findElementForHandle((String)targets.get(0));
assertEquals("target of relationship should be 'run()' but is "
+ target.toLabelString(),"run()",target.toLabelString());
}
public void testAdviceInStructureModelWithNamedInnerClass_pr77269() {
//AsmManager.setReporting("c:/debug.txt",true,true,true,true);
runTest("advice in structure model with named inner class");
IHierarchy top = AsmManager.getDefault().getHierarchy();
// checking that the m() method inside named inner class is in
// the structure model
IProgramElement namedMethodIPE = top.findElementForLabel(top.getRoot(),
IProgramElement.Kind.METHOD,"m()");
assertNotNull("Couldn't find 'm()' element in the tree",namedMethodIPE);
List l = AsmManager.getDefault().getRelationshipMap().get(namedMethodIPE);
assertNotNull("Should have some relationships but does not",l);
assertTrue("Should have one relationship but has " + l.size(),l.size()==1);
Relationship rel = (Relationship)l.get(0);
List targets = rel.getTargets();
assertTrue("Should have one target but has" + targets.size(),
targets.size()==1);
IProgramElement target = AsmManager.getDefault().getHierarchy().findElementForHandle((String)targets.get(0));
assertEquals("target of relationship should be 'before(): p..' but is "
+ target.toLabelString(),"before(): p..",target.toLabelString());
IProgramElement adviceIPE = top.findElementForLabel(top.getRoot(),
IProgramElement.Kind.ADVICE,"before(): p..");
assertNotNull("Couldn't find 'before(): p..' element in the tree",adviceIPE);
l = AsmManager.getDefault().getRelationshipMap().get(adviceIPE);
assertNotNull("Should have some relationships but does not",l);
assertTrue("Should have a relationship but does not ",l.size()>0);
for (Iterator iter = l.iterator(); iter.hasNext();) {
IRelationship element = (IRelationship) iter.next();
if (element.getName().equals("advises")) {
rel = (Relationship) element;
break;
}
}
targets = rel.getTargets();
assertTrue("Should have one target but has" + targets.size(),
targets.size()==1);
target = AsmManager.getDefault().getHierarchy().findElementForHandle((String)targets.get(0));
assertEquals("target of relationship should be 'm()' but is "
+ target.toLabelString(),"m()",target.toLabelString());
}
public void testDWInStructureModelWithAnonymousInnerClass_pr77269() {
// AsmManager.setReporting("c:/debug.txt",true,true,true,true);
runTest("declare warning in structure model with anonymous inner class");
IHierarchy top = AsmManager.getDefault().getHierarchy();
IProgramElement pe = top.findElementForLabel(top.getRoot(),
IProgramElement.Kind.CODE,"method-call(void pack.Test.someMethod())");
assertNotNull("Couldn't find 'method-call(void pack.Test.someMethod())' element in the tree",pe);
}
public void testVarArgsIITDInConstructor() {
runTest("ITD varargs in constructor");
}
public void testWeaveInfoMessageForDeclareAtMethodOnITDdMethod() {
runTest("weaveinfo message for declare at method on an ITDd method");
}
public void testITDCWithNoExplicitConsCall() {
runTest("ITDC with no explicit cons call");
}
public void testJava5SpecificFeaturesUsedAtJava14OrLower() {
runTest("java 5 pointcuts and declares at pre-java 5 compliance levels");
}
public void testAnonymousTypes() {
runTest("Anonymous types and nome matching");
}
public void testAdviceExecutionJPToStringForms() {
runTest("adviceexecution join point toString forms");
}
public void testAssertWithinPointcutExpression() {
runTest("pointcut expression containing 'assert'");
}
public void testNoVerifyErrorWithTwoThisPCDs_pr113447() {
runTest("no verify error with two this pcds");
}
public void testNoVerifyErrorWithTwoAtThisPCDs_pr113447() {
runTest("no verify error with two at this pcds");
}
public void testNoVerifyErrorWithAtWithinPCDs_pr113447() {
runTest("no verify error with at within pcds");
}
public void testNoVerifyErrorWithAtWithincodePCDs_pr113447() {
runTest("no verify error with at withincode pcds");
}
public void testNoVerifyErrorWithAtAnnotationPCDs_pr113447() {
runTest("no verify error with at annotation pcds");
}
public void testNoVerifyErrorWithTwoArgsPCDs_pr113447() {
runTest("no verify error with two args pcds");
}
public void testNoStackOverflowWithCircularPCDInGenericAspect() {
runTest("no StackOverflowError with circular pcd in generic aspect");
}
public void testNoStackOverflowWithCircularPCDInGenericAspect2() {
runTest("no StackOverflowError with circular pcd in generic aspect - 2");
}
public void testNPEInThisJoinPointStaticPart() {
runTest("thisJoinPointStaticPart in if test");
}
public void testPointcutParsingOfCompiledPointcuts() {
runTest("pointcut parsing with ajc compiled pointcut references");
}
public void testReflectionOfAbstractITDs() {
runTest("reflection on abstract ITDs (Billing example)");
}
public void testDeclareSoftWithAdviceExecution() {
runTest("declare soft and adviceexecution");
}
public void testDeclareSoftWithExclusions() {
runTest("declare soft and exclusions");
}
public void testReturningObjectBinding() {
runTest("returning(Object) binding");
}
public void testPerTargetAndNegation() {
runTest("pertarget and negated pointcut");
}
public void testParameterizedPointcutAndAdvice() {
runTest("parameterized pointcut and advice");
}
public void testDoublyParameterizedAbstractType() {
runTest("double parameter generic abstract type");
}
public void testArgNamesInAdviceAnnotations() {
runTest("arg names in advice annotations");
}
/*
* Load-time weaving bugs
*/
public void testNPEinWeavingAdaptor_pr116626() { runTest("NPE in WeavingAdaptor");}
public void testXlintMessageForImproperAnnotationType_pr115252_Exact() {runTest("xlint message for improper exact annotation type");}
public void testXlintMessageForImproperAnnotationType_pr115252_OR() {runTest("xlint message for improper annotation type inside OR");}
public void testXlintMessageForImproperAnnotationType_pr115252_AND() {runTest("xlint message for improper annotation type inside AND");}
public void testXlintMessageForImproperAnnotationType_pr115252_Return() {runTest("xlint message for improper annotated return type");}
public void testXlintMessageForImproperAnnotationType_pr115252_Declaring() {runTest("xlint message for improper annotated declaring type");}
public void testXlintMessageForImproperAnnotationType_pr115252_Parameter() {runTest("xlint message for improper annotated parameter type");}
public void testXlintMessageForImproperAnnotationType_pr115252_Throws() {runTest("xlint message for improper annotated throws pattern");}
public void testXlintMessageForImproperAnnotationType_pr115252_MoreThanOne() {runTest("xlint message for more than one improper annotated parameter type");}
public void testDeclareAtTypeInStructureModel_pr115607() {
AsmManager.setReporting("c:/debug.txt",true,true,true,true);
runTest("declare at type appears correctly in structure model");
IHierarchy top = AsmManager.getDefault().getHierarchy();
IProgramElement pe = top.findElementForLabel(top.getRoot(),
IProgramElement.Kind.DECLARE_ANNOTATION_AT_TYPE,"declare @type: Simple : @I");
assertNotNull("Couldn't find 'declare @type: Simple : @I' element in the tree",pe);
List l = AsmManager.getDefault().getRelationshipMap().get(pe);
assertNotNull("Should have some relationships but does not",l);
}
public void testNoNPEWhenInaccessibleMethodIsCalledWithinITD_pr119019() {
runTest("no NPE when inaccessible method is called within itd");
}
public void testNoNPEWithOrPointcutAndMoreThanOneArgs_pr118149() {
runTest("no NPE with or pointcut and more than one args");
}
public void testNoSOBWithGenericInnerAspects_pr119543() {
runTest("no StringOutOfBoundsException with generic inner aspects");
}
public void testIllegalAccessErrorWithAroundAdvice_pr119657() {
runTest("IllegalAccessError with around advice on interface method call");
}
public void testIllegalAccessErrorWithAroundAdviceNotSelf_pr119657() {
runTest("IllegalAccessError with around advice on interface method call not self");
}
public void testIllegalAccessErrorWithAroundAdviceNoWeaveLTW_pr119657() {
runTest("IllegalAccessError with around advice on interface method call using -XnoWeave and LTW");
}
public void testIllegalAccessErrorWithAroundAdviceLTW_pr119657() {
runTest("IllegalAccessError with around advice on interface method call using LTW");
}
public void testIllegalAccessErrorWithAroundAdviceNotSelfLTW_pr119657() {
runTest("IllegalAccessError with around advice on interface method call not self using LTW");
}
public void testIllegalAccessErrorWithAroundAdviceSelfAndNotSelfLTW_pr119657() {
runTest("IllegalAccessError with around advice on interface method call self and not self using LTW");
}
public void testIllegalAccessErrorWithAroundAdviceLTWNoInline_pr119657() {
runTest("IllegalAccessError with around advice on interface method call using LTW and -XnoInline");
}
public void testReflectOnCodeStyleITDs() {
runTest("reflection on itds");
}
public void testReflectOnAtAspectJDecP() {
runTest("reflection on @DeclareParents");
}
public void testModifierOverrides() {
runTest("modifier overrides");
}
public void testAbstractPerThisInAtAspectJ() {
runTest("abstract perthis in @AspectJ");
}
// helper methods.....
public SyntheticRepository createRepos(File cpentry) {
ClassPath cp = new ClassPath(cpentry+File.pathSeparator+System.getProperty("java.class.path"));
return SyntheticRepository.getInstance(cp);
}
protected JavaClass getClassFrom(File where,String clazzname) throws ClassNotFoundException {
SyntheticRepository repos = createRepos(where);
return repos.loadClass(clazzname);
}
}
|
121,385 |
Bug 121385 around advice does not work when LTW
|
I defined a aop.xml and a aspect, I have already copy aspectjweaver.jar D:\work\BTM\lib\aspectjweaver.jar, and added -javaagent:D:\work\BTM\lib\aspectjweaver.jar option to the JVM in Eclipse, it works fine if there are before and after advice in aspect, but it will be wrong once I used around advice. if I use compile-time weaving, this around advice works fine. my Eclipse env: eclipse 3.0.2 + AJDT 1.2.1 RC1 release + Sun JDK 1.5.0. aspect file: import org.aspectj.lang.Signature; import org.aspectj.lang.JoinPoint; public abstract aspect World { //private Object result; pointcut greeting() : execution(* Hello.sayWorld(..)); Object around(): greeting() { System.out.println("around start!"); Object result = proceed(); System.out.println("around end!"); return result; } // before() : greeting() { // Signature signature = thisJoinPoint.getSignature(); // System.out.println("before " + signature.getName()); // } // after() returning () : greeting() { // Signature signature = thisJoinPoint.getSignature(); // System.out.println("after " + signature.getName()); // } } aop.xml file: <?xml version="1.0" encoding="UTF-8"?> <aspectj> <aspects> <aspect name="World"/> <concrete-aspect name="World1" extends="World"> <pointcut name="greeting" expression="execution(* Hello.sayWorld(..)) || execution(* Hello.sayHello(..))"/> </concrete-aspect> </aspects> <weaver options="-Xreweavable -verbose -XlazyTjp -showWeaveInfo"> <include within="Hello"/> </weaver> </aspectj> around advice error message in eclipse console as below: info register aspect World info generating class 'World1' info weaving 'Hello' info weaver operating in reweavable mode. Need to verify any required types exist. abort trouble in: public class Hello extends java.lang.Object: public void <init>(): ALOAD_0 // Hello this (line 2) INVOKESPECIAL java.lang.Object.<init> ()V constructor-execution(void Hello.<init>()) | RETURN constructor-execution(void Hello.<init>()) end public void <init>() public static void main(String[]) org.aspectj.weaver.MethodDeclarationLineNumber: 7:75 : INVOKESTATIC Hello.sayHello ()V (line 9) RETURN (line 10) end public static void main(String[]) public static void sayHello() org.aspectj.weaver.MethodDeclarationLineNumber: 12:180 : end public static void sayHello() public static int sayWorld() org.aspectj.weaver.MethodDeclarationLineNumber: 17:268 : method-execution(int Hello.sayWorld()) | GETSTATIC java.lang.System.out Ljava/io/PrintStream; (line 18) | LDC "World" | INVOKEVIRTUAL java.io.PrintStream.println (Ljava/lang/String;)V | ICONST_0 (line 19) | IRETURN method-execution(int Hello.sayWorld()) end public static int sayWorld() static final void sayHello_aroundBody0(): GETSTATIC java.lang.System.out Ljava/io/PrintStream; (line 13) LDC "Hello" INVOKEVIRTUAL java.io.PrintStream.println (Ljava/lang/String;)V INVOKESTATIC Hello.sayWorld ()I (line 14) POP RETURN (line 15) end static final void sayHello_aroundBody0() end public class Hello public class Hello$AjcClosure1 extends org.aspectj.runtime.internal.AroundClosure: public void <init>(Object[]): ALOAD_0 ALOAD_1 INVOKESPECIAL org.aspectj.runtime.internal.AroundClosure.<init> ([Ljava/lang/Object;)V RETURN end public void <init>(Object[]) public Object run(Object[]): ALOAD_0 GETFIELD org.aspectj.runtime.internal.AroundClosure.state [Ljava/lang/Object; ASTORE_2 INVOKESTATIC Hello.sayHello_aroundBody0 ()V ACONST_NULL ARETURN end public Object run(Object[]) end public class Hello$AjcClosure1 -- (NullPointerException) null null java.lang.NullPointerException at org.aspectj.weaver.bcel.BcelAdvice.getAdviceArgSetup(BcelAdvice.java:457) at org.aspectj.weaver.bcel.BcelShadow.weaveAroundClosure(BcelShadow.java:2685) at org.aspectj.weaver.bcel.BcelAdvice.implementOn(BcelAdvice.java:230) at org.aspectj.weaver.Shadow.implementMungers(Shadow.java:588) at org.aspectj.weaver.Shadow.implement(Shadow.java:405) at org.aspectj.weaver.bcel.BcelClassWeaver.implement(BcelClassWeaver.java:2146) at org.aspectj.weaver.bcel.BcelClassWeaver.weave(BcelClassWeaver.java:467) at org.aspectj.weaver.bcel.BcelClassWeaver.weave(BcelClassWeaver.java:102) at org.aspectj.weaver.bcel.BcelWeaver.weave(BcelWeaver.java:1543) at org.aspectj.weaver.bcel.BcelWeaver.weaveWithoutDump(BcelWeaver.java:1494) at org.aspectj.weaver.bcel.BcelWeaver.weaveAndNotify(BcelWeaver.java:1275) at org.aspectj.weaver.bcel.BcelWeaver.weave(BcelWeaver.java:1097) at org.aspectj.weaver.tools.WeavingAdaptor.getWovenBytes(WeavingAdaptor.java:263) at org.aspectj.weaver.tools.WeavingAdaptor.weaveClass(WeavingAdaptor.java:196) at org.aspectj.weaver.loadtime.Aj.preProcess(Aj.java:65) at org.aspectj.weaver.loadtime.ClassPreProcessorAgentAdapter.transform(ClassPreProcessorAgentAdapter.java:52) at sun.instrument.TransformerManager.transform(TransformerManager.java:122) at sun.instrument.InstrumentationImpl.transform(InstrumentationImpl.java:155) at java.lang.ClassLoader.defineClass1(Native Method) at java.lang.ClassLoader.defineClass(ClassLoader.java:620) at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:124) at java.net.URLClassLoader.defineClass(URLClassLoader.java:260) at java.net.URLClassLoader.access$100(URLClassLoader.java:56) at java.net.URLClassLoader$1.run(URLClassLoader.java:195) at java.security.AccessController.doPrivileged(Native Method) at java.net.URLClassLoader.findClass(URLClassLoader.java:188) at java.lang.ClassLoader.loadClass(ClassLoader.java:306) at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:268) at java.lang.ClassLoader.loadClass(ClassLoader.java:251) at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:319) Message: abort trouble in: public class Hello extends java.lang.Object: public void <init>(): ALOAD_0 // Hello this (line 2) INVOKESPECIAL java.lang.Object.<init> ()V constructor-execution(void Hello.<init>()) | RETURN constructor-execution(void Hello.<init>()) end public void <init>() public static void main(String[]) org.aspectj.weaver.MethodDeclarationLineNumber: 7:75 : INVOKESTATIC Hello.sayHello ()V (line 9) RETURN (line 10) end public static void main(String[]) public static void sayHello() org.aspectj.weaver.MethodDeclarationLineNumber: 12:180 : end public static void sayHello() public static int sayWorld() org.aspectj.weaver.MethodDeclarationLineNumber: 17:268 : method-execution(int Hello.sayWorld()) | GETSTATIC java.lang.System.out Ljava/io/PrintStream; (line 18) | LDC "World" | INVOKEVIRTUAL java.io.PrintStream.println (Ljava/lang/String;)V | ICONST_0 (line 19) | IRETURN method-execution(int Hello.sayWorld()) end public static int sayWorld() static final void sayHello_aroundBody0(): GETSTATIC java.lang.System.out Ljava/io/PrintStream; (line 13) LDC "Hello" INVOKEVIRTUAL java.io.PrintStream.println (Ljava/lang/String;)V INVOKESTATIC Hello.sayWorld ()I (line 14) POP RETURN (line 15) end static final void sayHello_aroundBody0() end public class Hello public class Hello$AjcClosure1 extends org.aspectj.runtime.internal.AroundClosure: public void <init>(Object[]): ALOAD_0 ALOAD_1 INVOKESPECIAL org.aspectj.runtime.internal.AroundClosure.<init> ([Ljava/lang/Object;)V RETURN end public void <init>(Object[]) public Object run(Object[]): ALOAD_0 GETFIELD org.aspectj.runtime.internal.AroundClosure.state [Ljava/lang/Object; ASTORE_2 INVOKESTATIC Hello.sayHello_aroundBody0 ()V ACONST_NULL ARETURN end public Object run(Object[]) end public class Hello$AjcClosure1 -- (NullPointerException) null null java.lang.NullPointerException at org.aspectj.weaver.bcel.BcelAdvice.getAdviceArgSetup(BcelAdvice.java:457) at org.aspectj.weaver.bcel.BcelShadow.weaveAroundClosure(BcelShadow.java:2685) at org.aspectj.weaver.bcel.BcelAdvice.implementOn(BcelAdvice.java:230) at org.aspectj.weaver.Shadow.implementMungers(Shadow.java:588) at org.aspectj.weaver.Shadow.implement(Shadow.java:405) at org.aspectj.weaver.bcel.BcelClassWeaver.implement(BcelClassWeaver.java:2146) at org.aspectj.weaver.bcel.BcelClassWeaver.weave(BcelClassWeaver.java:467) at org.aspectj.weaver.bcel.BcelClassWeaver.weave(BcelClassWeaver.java:102) at org.aspectj.weaver.bcel.BcelWeaver.weave(BcelWeaver.java:1543) at org.aspectj.weaver.bcel.BcelWeaver.weaveWithoutDump(BcelWeaver.java:1494) at org.aspectj.weaver.bcel.BcelWeaver.weaveAndNotify(BcelWeaver.java:1275) at org.aspectj.weaver.bcel.BcelWeaver.weave(BcelWeaver.java:1097) at org.aspectj.weaver.tools.WeavingAdaptor.getWovenBytes(WeavingAdaptor.java:263) at org.aspectj.weaver.tools.WeavingAdaptor.weaveClass(WeavingAdaptor.java:196) at org.aspectj.weaver.loadtime.Aj.preProcess(Aj.java:65) at org.aspectj.weaver.loadtime.ClassPreProcessorAgentAdapter.transform(ClassPreProcessorAgentAdapter.java:52) at sun.instrument.TransformerManager.transform(TransformerManager.java:122) at sun.instrument.InstrumentationImpl.transform(InstrumentationImpl.java:155) at java.lang.ClassLoader.defineClass1(Native Method) at java.lang.ClassLoader.defineClass(ClassLoader.java:620) at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:124) at java.net.URLClassLoader.defineClass(URLClassLoader.java:260) at java.net.URLClassLoader.access$100(URLClassLoader.java:56) at java.net.URLClassLoader$1.run(URLClassLoader.java:195) at java.security.AccessController.doPrivileged(Native Method) at java.net.URLClassLoader.findClass(URLClassLoader.java:188) at java.lang.ClassLoader.loadClass(ClassLoader.java:306) at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:268) at java.lang.ClassLoader.loadClass(ClassLoader.java:251) at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:319) org.aspectj.bridge.AbortException: trouble in: public class Hello extends java.lang.Object: public void <init>(): ALOAD_0 // Hello this (line 2) INVOKESPECIAL java.lang.Object.<init> ()V constructor-execution(void Hello.<init>()) | RETURN constructor-execution(void Hello.<init>()) end public void <init>() public static void main(String[]) org.aspectj.weaver.MethodDeclarationLineNumber: 7:75 : INVOKESTATIC Hello.sayHello ()V (line 9) RETURN (line 10) end public static void main(String[]) public static void sayHello() org.aspectj.weaver.MethodDeclarationLineNumber: 12:180 : end public static void sayHello() public static int sayWorld() org.aspectj.weaver.MethodDeclarationLineNumber: 17:268 : method-execution(int Hello.sayWorld()) | GETSTATIC java.lang.System.out Ljava/io/PrintStream; (line 18) | LDC "World" | INVOKEVIRTUAL java.io.PrintStream.println (Ljava/lang/String;)V | ICONST_0 (line 19) | IRETURN method-execution(int Hello.sayWorld()) end public static int sayWorld() static final void sayHello_aroundBody0(): GETSTATIC java.lang.System.out Ljava/io/PrintStream; (line 13) LDC "Hello" INVOKEVIRTUAL java.io.PrintStream.println (Ljava/lang/String;)V INVOKESTATIC Hello.sayWorld ()I (line 14) POP RETURN (line 15) end static final void sayHello_aroundBody0() end public class Hello public class Hello$AjcClosure1 extends org.aspectj.runtime.internal.AroundClosure: public void <init>(Object[]): ALOAD_0 ALOAD_1 INVOKESPECIAL org.aspectj.runtime.internal.AroundClosure.<init> ([Ljava/lang/Object;)V RETURN end public void <init>(Object[]) public Object run(Object[]): ALOAD_0 GETFIELD org.aspectj.runtime.internal.AroundClosure.state [Ljava/lang/Object; ASTORE_2 INVOKESTATIC Hello.sayHello_aroundBody0 ()V ACONST_NULL ARETURN end public Object run(Object[]) end public class Hello$AjcClosure1 at org.aspectj.bridge.MessageWriter.handleMessage(MessageWriter.java:47) at org.aspectj.weaver.tools.WeavingAdaptor$WeavingAdaptorMessageHandler.handleMessage(WeavingAdaptor.java:395) at org.aspectj.weaver.bcel.BcelWeaver.weave(BcelWeaver.java:1554) at org.aspectj.weaver.bcel.BcelWeaver.weaveWithoutDump(BcelWeaver.java:1494) at org.aspectj.weaver.bcel.BcelWeaver.weaveAndNotify(BcelWeaver.java:1275) at org.aspectj.weaver.bcel.BcelWeaver.weave(BcelWeaver.java:1097) at org.aspectj.weaver.tools.WeavingAdaptor.getWovenBytes(WeavingAdaptor.java:263) at org.aspectj.weaver.tools.WeavingAdaptor.weaveClass(WeavingAdaptor.java:196) at org.aspectj.weaver.loadtime.Aj.preProcess(Aj.java:65) at org.aspectj.weaver.loadtime.ClassPreProcessorAgentAdapter.transform(ClassPreProcessorAgentAdapter.java:52) at sun.instrument.TransformerManager.transform(TransformerManager.java:122) at sun.instrument.InstrumentationImpl.transform(InstrumentationImpl.java:155) at java.lang.ClassLoader.defineClass1(Native Method) at java.lang.ClassLoader.defineClass(ClassLoader.java:620) at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:124) at java.net.URLClassLoader.defineClass(URLClassLoader.java:260) at java.net.URLClassLoader.access$100(URLClassLoader.java:56) at java.net.URLClassLoader$1.run(URLClassLoader.java:195) at java.security.AccessController.doPrivileged(Native Method) at java.net.URLClassLoader.findClass(URLClassLoader.java:188) at java.lang.ClassLoader.loadClass(ClassLoader.java:306) at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:268) at java.lang.ClassLoader.loadClass(ClassLoader.java:251) at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:319) Hello World
|
resolved fixed
|
a778ac4
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2005-12-21T17:21:57Z | 2005-12-19T11:00:00Z |
weaver/src/org/aspectj/weaver/bcel/BcelAdvice.java
|
/* *******************************************************************
* Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC).
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* PARC initial implementation
* Alexandre Vasseur support for @AJ aspects
* ******************************************************************/
package org.aspectj.weaver.bcel;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Map;
import org.aspectj.apache.bcel.generic.InstructionConstants;
import org.aspectj.apache.bcel.generic.InstructionFactory;
import org.aspectj.apache.bcel.generic.InstructionHandle;
import org.aspectj.apache.bcel.generic.InstructionList;
import org.aspectj.bridge.ISourceLocation;
import org.aspectj.bridge.Message;
import org.aspectj.weaver.Advice;
import org.aspectj.weaver.AdviceKind;
import org.aspectj.weaver.AjAttribute;
import org.aspectj.weaver.BCException;
import org.aspectj.weaver.ISourceContext;
import org.aspectj.weaver.Member;
import org.aspectj.weaver.ResolvedMember;
import org.aspectj.weaver.ResolvedType;
import org.aspectj.weaver.Shadow;
import org.aspectj.weaver.ShadowMunger;
import org.aspectj.weaver.UnresolvedType;
import org.aspectj.weaver.WeaverMessages;
import org.aspectj.weaver.World;
import org.aspectj.weaver.ast.Literal;
import org.aspectj.weaver.ast.Test;
import org.aspectj.weaver.patterns.ExactTypePattern;
import org.aspectj.weaver.patterns.ExposedState;
import org.aspectj.weaver.patterns.PerClause;
import org.aspectj.weaver.patterns.Pointcut;
/**
* Advice implemented for bcel.
*
* @author Erik Hilsdale
* @author Jim Hugunin
*/
public class BcelAdvice extends Advice {
private Test pointcutTest;
private ExposedState exposedState;
private boolean hasMatchedAtLeastOnce = false;
public BcelAdvice(
AjAttribute.AdviceAttribute attribute,
Pointcut pointcut,
Member signature,
ResolvedType concreteAspect)
{
super(attribute, pointcut, signature);
this.concreteAspect = concreteAspect;
}
// !!! must only be used for testing
public BcelAdvice(AdviceKind kind, Pointcut pointcut, Member signature,
int extraArgumentFlags,
int start, int end, ISourceContext sourceContext, ResolvedType concreteAspect)
{
this(new AjAttribute.AdviceAttribute(kind, pointcut, extraArgumentFlags, start, end, sourceContext),
pointcut, signature, concreteAspect);
thrownExceptions = Collections.EMPTY_LIST; //!!! interaction with unit tests
}
// ---- implementations of ShadowMunger's methods
public ShadowMunger concretize(ResolvedType fromType, World world, PerClause clause) {
suppressLintWarnings(world);
ShadowMunger ret = super.concretize(fromType, world, clause);
clearLintSuppressions(world,this.suppressedLintKinds);
return ret;
}
public ShadowMunger parameterizeWith(ResolvedType declaringType,Map typeVariableMap) {
Pointcut pc = getPointcut().parameterizeWith(typeVariableMap);
BcelAdvice ret = null;
Member adviceSignature = signature;
// allows for around advice where the return value is a type variable (see pr115250)
if (signature instanceof ResolvedMember && signature.getDeclaringType().isGenericType()) {
adviceSignature = ((ResolvedMember)signature).parameterizedWith(declaringType.getTypeParameters(),declaringType,declaringType.isParameterizedType());
}
ret = new BcelAdvice(this.attribute,pc,adviceSignature,this.concreteAspect);
return ret;
}
public boolean match(Shadow shadow, World world) {
suppressLintWarnings(world);
boolean ret = super.match(shadow, world);
clearLintSuppressions(world,this.suppressedLintKinds);
return ret;
}
public void specializeOn(Shadow shadow) {
if (getKind() == AdviceKind.Around) {
((BcelShadow)shadow).initializeForAroundClosure();
}
//XXX this case is just here for supporting lazy test code
if (getKind() == null) {
exposedState = new ExposedState(0);
return;
}
if (getKind().isPerEntry()) {
exposedState = new ExposedState(0);
} else if (getKind().isCflow()) {
exposedState = new ExposedState(nFreeVars);
} else if (getSignature() != null) {
exposedState = new ExposedState(getSignature());
} else {
exposedState = new ExposedState(0);
return; //XXX this case is just here for supporting lazy test code
}
World world = shadow.getIWorld();
suppressLintWarnings(world);
pointcutTest = getPointcut().findResidue(shadow, exposedState);
clearLintSuppressions(world,this.suppressedLintKinds);
// these initializations won't be performed by findResidue, but need to be
// so that the joinpoint is primed for weaving
if (getKind() == AdviceKind.PerThisEntry) {
shadow.getThisVar();
} else if (getKind() == AdviceKind.PerTargetEntry) {
shadow.getTargetVar();
}
// make sure thisJoinPoint parameters are initialized
if ((getExtraParameterFlags() & ThisJoinPointStaticPart) != 0) {
((BcelShadow)shadow).getThisJoinPointStaticPartVar();
((BcelShadow)shadow).getEnclosingClass().warnOnAddedStaticInitializer(shadow,getSourceLocation());
}
if ((getExtraParameterFlags() & ThisJoinPoint) != 0) {
boolean hasGuardTest = pointcutTest != Literal.TRUE && getKind() != AdviceKind.Around;
boolean isAround = getKind() == AdviceKind.Around;
((BcelShadow)shadow).requireThisJoinPoint(hasGuardTest,isAround);
((BcelShadow)shadow).getEnclosingClass().warnOnAddedStaticInitializer(shadow,getSourceLocation());
if (!hasGuardTest && world.getLint().multipleAdviceStoppingLazyTjp.isEnabled()) {
// collect up the problematic advice
((BcelShadow)shadow).addAdvicePreventingLazyTjp(this);
}
if (!isAround && !hasGuardTest && world.getLint().noGuardForLazyTjp.isEnabled()) {
// can't build tjp lazily, no suitable test...
world.getLint().noGuardForLazyTjp.signal(
new String[] {shadow.toString()},
getSourceLocation(),
new ISourceLocation[] { ((BcelShadow)shadow).getSourceLocation() }
);
}
}
if ((getExtraParameterFlags() & ThisEnclosingJoinPointStaticPart) != 0) {
((BcelShadow)shadow).getThisEnclosingJoinPointStaticPartVar();
((BcelShadow)shadow).getEnclosingClass().warnOnAddedStaticInitializer(shadow,getSourceLocation());
}
}
private boolean canInline(Shadow s) {
if (attribute.isProceedInInners()) return false;
//XXX this guard seems to only be needed for bad test cases
if (concreteAspect == null || concreteAspect.isMissing()) return false;
if (concreteAspect.getWorld().isXnoInline()) return false;
//System.err.println("isWoven? " + ((BcelObjectType)concreteAspect).getLazyClassGen().getWeaverState());
return BcelWorld.getBcelObjectType(concreteAspect).getLazyClassGen().isWoven();
}
public void implementOn(Shadow s) {
hasMatchedAtLeastOnce=true;
BcelShadow shadow = (BcelShadow) s;
//FIXME AV - see #75442, this logic is not enough so for now comment it out until we fix the bug
// // callback for perObject AJC MightHaveAspect postMunge (#75442)
// if (getConcreteAspect() != null
// && getConcreteAspect().getPerClause() != null
// && PerClause.PEROBJECT.equals(getConcreteAspect().getPerClause().getKind())) {
// final PerObject clause;
// if (getConcreteAspect().getPerClause() instanceof PerFromSuper) {
// clause = (PerObject)((PerFromSuper) getConcreteAspect().getPerClause()).lookupConcretePerClause(getConcreteAspect());
// } else {
// clause = (PerObject) getConcreteAspect().getPerClause();
// }
// if (clause.isThis()) {
// PerObjectInterfaceTypeMunger.registerAsAdvisedBy(s.getThisVar().getType(), getConcreteAspect());
// } else {
// PerObjectInterfaceTypeMunger.registerAsAdvisedBy(s.getTargetVar().getType(), getConcreteAspect());
// }
// }
if (getKind() == AdviceKind.Before) {
shadow.weaveBefore(this);
} else if (getKind() == AdviceKind.AfterReturning) {
shadow.weaveAfterReturning(this);
} else if (getKind() == AdviceKind.AfterThrowing) {
UnresolvedType catchType =
hasExtraParameter()
? getExtraParameterType()
: UnresolvedType.THROWABLE;
shadow.weaveAfterThrowing(this, catchType);
} else if (getKind() == AdviceKind.After) {
shadow.weaveAfter(this);
} else if (getKind() == AdviceKind.Around) {
// Note: under regular LTW the aspect is usually loaded after the first use of any class affecteted by it
// This means that as long as the aspect has not been thru the LTW, it's woven state is unknown
// and thus canInline(s) will return false.
// To force inlining (test), ones can do Class aspect = FQNAspect.class in the clinit of the target class
// FIXME AV : for AJC compiled @AJ aspect (or any code style aspect), the woven state can never be known
// if the aspect belongs to a parent classloader. In that case the aspect will never be inlined.
// It might be dangerous to change that especially for @AJ aspect non compiled with AJC since if those
// are not weaved (f.e. use of some limiteed LTW etc) then they cannot be prepared for inlining.
// One solution would be to flag @AJ aspect with an annotation as "prepared" and query that one.
if (!canInline(s)) {
shadow.weaveAroundClosure(this, hasDynamicTests());
} else {
shadow.weaveAroundInline(this, hasDynamicTests());
}
} else if (getKind() == AdviceKind.InterInitializer) {
shadow.weaveAfterReturning(this);
} else if (getKind().isCflow()) {
shadow.weaveCflowEntry(this, getSignature());
} else if (getKind() == AdviceKind.PerThisEntry) {
shadow.weavePerObjectEntry(this, (BcelVar)shadow.getThisVar());
} else if (getKind() == AdviceKind.PerTargetEntry) {
shadow.weavePerObjectEntry(this, (BcelVar)shadow.getTargetVar());
} else if (getKind() == AdviceKind.Softener) {
shadow.weaveSoftener(this, ((ExactTypePattern)exceptionType).getType());
} else if (getKind() == AdviceKind.PerTypeWithinEntry) {
// PTWIMPL Entry to ptw is the static initialization of a type that matched the ptw type pattern
shadow.weavePerTypeWithinAspectInitialization(this,shadow.getEnclosingType());
} else {
throw new BCException("unimplemented kind: " + getKind());
}
}
// ---- implementations
private Collection collectCheckedExceptions(UnresolvedType[] excs) {
if (excs == null || excs.length == 0) return Collections.EMPTY_LIST;
Collection ret = new ArrayList();
World world = concreteAspect.getWorld();
ResolvedType runtimeException = world.getCoreType(UnresolvedType.RUNTIME_EXCEPTION);
ResolvedType error = world.getCoreType(UnresolvedType.ERROR);
for (int i=0, len=excs.length; i < len; i++) {
ResolvedType t = world.resolve(excs[i],true);
if (t.isMissing()) {
world.getLint().cantFindType.signal(
WeaverMessages.format(WeaverMessages.CANT_FIND_TYPE_EXCEPTION_TYPE,excs[i].getName()),
getSourceLocation()
);
// IMessage msg = new Message(
// WeaverMessages.format(WeaverMessages.CANT_FIND_TYPE_EXCEPTION_TYPE,excs[i].getName()),
// "",IMessage.ERROR,getSourceLocation(),null,null);
// world.getMessageHandler().handleMessage(msg);
}
if (!(runtimeException.isAssignableFrom(t) || error.isAssignableFrom(t))) {
ret.add(t);
}
}
return ret;
}
private Collection thrownExceptions = null;
public Collection getThrownExceptions() {
if (thrownExceptions == null) {
//??? can we really lump in Around here, how does this interact with Throwable
if (concreteAspect != null && concreteAspect.getWorld() != null && // null tests for test harness
(getKind().isAfter() || getKind() == AdviceKind.Before || getKind() == AdviceKind.Around))
{
World world = concreteAspect.getWorld();
ResolvedMember m = world.resolve(signature);
if (m == null) {
thrownExceptions = Collections.EMPTY_LIST;
} else {
thrownExceptions = collectCheckedExceptions(m.getExceptions());
}
} else {
thrownExceptions = Collections.EMPTY_LIST;
}
}
return thrownExceptions;
}
/**
* The munger must not check for the advice exceptions to be declared by the shadow in the case
* of @AJ aspects so that around can throws Throwable
*
* @return
*/
public boolean mustCheckExceptions() {
if (getConcreteAspect() == null) {
return true;
}
return !getConcreteAspect().isAnnotationStyleAspect();
}
// only call me after prepare has been called
public boolean hasDynamicTests() {
// if (hasExtraParameter() && getKind() == AdviceKind.AfterReturning) {
// UnresolvedType extraParameterType = getExtraParameterType();
// if (! extraParameterType.equals(UnresolvedType.OBJECT)
// && ! extraParameterType.isPrimitive())
// return true;
// }
return pointcutTest != null &&
!(pointcutTest == Literal.TRUE);// || pointcutTest == Literal.NO_TEST);
}
/**
* get the instruction list for the really simple version of this advice.
* Is broken apart
* for other advice, but if you want it in one block, this is the method to call.
*
* @param s The shadow around which these instructions will eventually live.
* @param extraArgVar The var that will hold the return value or thrown exception
* for afterX advice
* @param ifNoAdvice The instructionHandle to jump to if the dynamic
* tests for this munger fails.
*/
InstructionList getAdviceInstructions(
BcelShadow s,
BcelVar extraArgVar,
InstructionHandle ifNoAdvice)
{
BcelShadow shadow = (BcelShadow) s;
InstructionFactory fact = shadow.getFactory();
BcelWorld world = shadow.getWorld();
InstructionList il = new InstructionList();
// we test to see if we have the right kind of thing...
// after throwing does this just by the exception mechanism.
if (hasExtraParameter() && getKind() == AdviceKind.AfterReturning) {
UnresolvedType extraParameterType = getExtraParameterType();
if (! extraParameterType.equals(UnresolvedType.OBJECT)
&& ! extraParameterType.isPrimitiveType()) {
il.append(
BcelRenderer.renderTest(
fact,
world,
Test.makeInstanceof(
extraArgVar, getExtraParameterType().resolve(world)),
null,
ifNoAdvice,
null));
}
}
il.append(getAdviceArgSetup(shadow, extraArgVar, null));
il.append(getNonTestAdviceInstructions(shadow));
InstructionHandle ifYesAdvice = il.getStart();
il.insert(getTestInstructions(shadow, ifYesAdvice, ifNoAdvice, ifYesAdvice));
return il;
}
public InstructionList getAdviceArgSetup(
BcelShadow shadow,
BcelVar extraVar,
InstructionList closureInstantiation)
{
InstructionFactory fact = shadow.getFactory();
BcelWorld world = shadow.getWorld();
InstructionList il = new InstructionList();
// if (targetAspectField != null) {
// il.append(fact.createFieldAccess(
// targetAspectField.getDeclaringType().getName(),
// targetAspectField.getName(),
// BcelWorld.makeBcelType(targetAspectField.getType()),
// Constants.GETSTATIC));
// }
//
//System.err.println("BcelAdvice: " + exposedState);
if (exposedState.getAspectInstance() != null) {
il.append(BcelRenderer.renderExpr(fact, world, exposedState.getAspectInstance()));
}
final boolean isAnnotationStyleAspect = getConcreteAspect()!=null && getConcreteAspect().isAnnotationStyleAspect();
boolean previousIsClosure = false;
for (int i = 0, len = exposedState.size(); i < len; i++) {
if (exposedState.isErroneousVar(i)) continue; // Erroneous vars have already had error msgs reported!
BcelVar v = (BcelVar) exposedState.get(i);
if (v == null) {
// if not @AJ aspect, go on with the regular binding handling
if (!isAnnotationStyleAspect) {
;
} else {
// ATAJ: for @AJ aspects, handle implicit binding of xxJoinPoint
//if (getKind() == AdviceKind.Around) {
// previousIsClosure = true;
// il.append(closureInstantiation);
if ("Lorg/aspectj/lang/ProceedingJoinPoint;".equals(getSignature().getParameterTypes()[i].getSignature())) {
//make sure we are in an around, since we deal with the closure, not the arg here
if (getKind() != AdviceKind.Around) {
previousIsClosure = false;
getConcreteAspect().getWorld().getMessageHandler().handleMessage(
new Message(
"use of ProceedingJoinPoint is allowed only on around advice ("
+ "arg " + i + " in " + toString() + ")",
this.getSourceLocation(),
true
)
);
// try to avoid verify error and pass in null
il.append(InstructionConstants.ACONST_NULL);
} else {
if (previousIsClosure) {
il.append(InstructionConstants.DUP);
} else {
previousIsClosure = true;
il.append(closureInstantiation.copy());
}
}
} else if ("Lorg/aspectj/lang/JoinPoint$StaticPart;".equals(getSignature().getParameterTypes()[i].getSignature())) {
previousIsClosure = false;
if ((getExtraParameterFlags() & ThisJoinPointStaticPart) != 0) {
shadow.getThisJoinPointStaticPartBcelVar().appendLoad(il, fact);
}
} else if ("Lorg/aspectj/lang/JoinPoint;".equals(getSignature().getParameterTypes()[i].getSignature())) {
previousIsClosure = false;
if ((getExtraParameterFlags() & ThisJoinPoint) != 0) {
il.append(shadow.loadThisJoinPoint());
}
} else if ("Lorg/aspectj/lang/JoinPoint$EnclosingStaticPart;".equals(getSignature().getParameterTypes()[i].getSignature())) {
previousIsClosure = false;
if ((getExtraParameterFlags() & ThisEnclosingJoinPointStaticPart) != 0) {
shadow.getThisEnclosingJoinPointStaticPartBcelVar().appendLoad(il, fact);
}
} else if (hasExtraParameter()) {
previousIsClosure = false;
//extra var can be null here (@Aj aspect extends abstract code style, advice in code style)
if (extraVar != null) {
extraVar.appendLoadAndConvert(
il,
fact,
getExtraParameterType().resolve(world));
}
} else {
previousIsClosure = false;
getConcreteAspect().getWorld().getMessageHandler().handleMessage(
new Message(
"use of ProceedingJoinPoint is allowed only on around advice ("
+ "arg " + i + " in " + toString() + ")",
this.getSourceLocation(),
true
)
);
// try to avoid verify error and pass in null
il.append(InstructionConstants.ACONST_NULL);
}
}
} else {
UnresolvedType desiredTy = getBindingParameterTypes()[i];
v.appendLoadAndConvert(il, fact, desiredTy.resolve(world));
}
}
// ATAJ: for code style aspect, handles the extraFlag as usual ie not
// in the middle of the formal bindings but at the end, in a rock solid ordering
if (!isAnnotationStyleAspect) {
if (getKind() == AdviceKind.Around) {
il.append(closureInstantiation);
} else if (hasExtraParameter()) {
extraVar.appendLoadAndConvert(
il,
fact,
getExtraParameterType().resolve(world));
}
// handle thisJoinPoint parameters
// these need to be in that same order as parameters in
// org.aspectj.ajdt.internal.compiler.ast.AdviceDeclaration
if ((getExtraParameterFlags() & ThisJoinPointStaticPart) != 0) {
shadow.getThisJoinPointStaticPartBcelVar().appendLoad(il, fact);
}
if ((getExtraParameterFlags() & ThisJoinPoint) != 0) {
il.append(shadow.loadThisJoinPoint());
}
if ((getExtraParameterFlags() & ThisEnclosingJoinPointStaticPart) != 0) {
shadow.getThisEnclosingJoinPointStaticPartBcelVar().appendLoad(il, fact);
}
}
return il;
}
public InstructionList getNonTestAdviceInstructions(BcelShadow shadow) {
return new InstructionList(
Utility.createInvoke(shadow.getFactory(), shadow.getWorld(), getOriginalSignature()));
}
public Member getOriginalSignature() {
Member sig = getSignature();
if (sig instanceof ResolvedMember) {
ResolvedMember rsig = (ResolvedMember)sig;
if (rsig.hasBackingGenericMember()) return rsig.getBackingGenericMember();
}
return sig;
}
public InstructionList getTestInstructions(
BcelShadow shadow,
InstructionHandle sk,
InstructionHandle fk,
InstructionHandle next)
{
//System.err.println("test: " + pointcutTest);
return BcelRenderer.renderTest(
shadow.getFactory(),
shadow.getWorld(),
pointcutTest,
sk,
fk,
next);
}
public int compareTo(Object other) {
if (!(other instanceof BcelAdvice)) return 0;
BcelAdvice o = (BcelAdvice)other;
//System.err.println("compareTo: " + this + ", " + o);
if (kind.getPrecedence() != o.kind.getPrecedence()) {
if (kind.getPrecedence() > o.kind.getPrecedence()) return +1;
else return -1;
}
if (kind.isCflow()) {
// System.err.println("sort: " + this + " innerCflowEntries " + innerCflowEntries);
// System.err.println(" " + o + " innerCflowEntries " + o.innerCflowEntries);
boolean isBelow = (kind == AdviceKind.CflowBelowEntry);
if (this.innerCflowEntries.contains(o)) return isBelow ? +1 : -1;
else if (o.innerCflowEntries.contains(this)) return isBelow ? -1 : +1;
else return 0;
}
if (kind.isPerEntry() || kind == AdviceKind.Softener) {
return 0;
}
//System.out.println("compare: " + this + " with " + other);
World world = concreteAspect.getWorld();
int ret =
concreteAspect.getWorld().compareByPrecedence(
concreteAspect,
o.concreteAspect);
if (ret != 0) return ret;
ResolvedType declaringAspect = getDeclaringAspect().resolve(world);
ResolvedType o_declaringAspect = o.getDeclaringAspect().resolve(world);
if (declaringAspect == o_declaringAspect) {
if (kind.isAfter() || o.kind.isAfter()) {
return this.getStart() < o.getStart() ? -1: +1;
} else {
return this.getStart()< o.getStart() ? +1: -1;
}
} else if (declaringAspect.isAssignableFrom(o_declaringAspect)) {
return -1;
} else if (o_declaringAspect.isAssignableFrom(declaringAspect)) {
return +1;
} else {
return 0;
}
}
public BcelVar[] getExposedStateAsBcelVars(boolean isAround) {
// ATAJ aspect
if (isAround) {
// the closure instantiation has the same mapping as the extracted method from wich it is called
if (getConcreteAspect()!= null && getConcreteAspect().isAnnotationStyleAspect()) {
return BcelVar.NONE;
}
}
//System.out.println("vars: " + Arrays.asList(exposedState.vars));
if (exposedState == null) return BcelVar.NONE;
int len = exposedState.vars.length;
BcelVar[] ret = new BcelVar[len];
for (int i=0; i < len; i++) {
ret[i] = (BcelVar)exposedState.vars[i];
}
return ret; //(BcelVar[]) exposedState.vars;
}
public boolean hasMatchedSomething() {
return hasMatchedAtLeastOnce;
}
protected void suppressLintWarnings(World inWorld) {
if (suppressedLintKinds == null) {
if (signature instanceof BcelMethod) {
this.suppressedLintKinds = Utility.getSuppressedWarnings(signature.getAnnotations(), inWorld.getLint());
} else {
this.suppressedLintKinds = Collections.EMPTY_LIST;
}
}
inWorld.getLint().suppressKinds(suppressedLintKinds);
}
protected void clearLintSuppressions(World inWorld,Collection toClear) {
inWorld.getLint().clearSuppressions(toClear);
}
}
|
121,385 |
Bug 121385 around advice does not work when LTW
|
I defined a aop.xml and a aspect, I have already copy aspectjweaver.jar D:\work\BTM\lib\aspectjweaver.jar, and added -javaagent:D:\work\BTM\lib\aspectjweaver.jar option to the JVM in Eclipse, it works fine if there are before and after advice in aspect, but it will be wrong once I used around advice. if I use compile-time weaving, this around advice works fine. my Eclipse env: eclipse 3.0.2 + AJDT 1.2.1 RC1 release + Sun JDK 1.5.0. aspect file: import org.aspectj.lang.Signature; import org.aspectj.lang.JoinPoint; public abstract aspect World { //private Object result; pointcut greeting() : execution(* Hello.sayWorld(..)); Object around(): greeting() { System.out.println("around start!"); Object result = proceed(); System.out.println("around end!"); return result; } // before() : greeting() { // Signature signature = thisJoinPoint.getSignature(); // System.out.println("before " + signature.getName()); // } // after() returning () : greeting() { // Signature signature = thisJoinPoint.getSignature(); // System.out.println("after " + signature.getName()); // } } aop.xml file: <?xml version="1.0" encoding="UTF-8"?> <aspectj> <aspects> <aspect name="World"/> <concrete-aspect name="World1" extends="World"> <pointcut name="greeting" expression="execution(* Hello.sayWorld(..)) || execution(* Hello.sayHello(..))"/> </concrete-aspect> </aspects> <weaver options="-Xreweavable -verbose -XlazyTjp -showWeaveInfo"> <include within="Hello"/> </weaver> </aspectj> around advice error message in eclipse console as below: info register aspect World info generating class 'World1' info weaving 'Hello' info weaver operating in reweavable mode. Need to verify any required types exist. abort trouble in: public class Hello extends java.lang.Object: public void <init>(): ALOAD_0 // Hello this (line 2) INVOKESPECIAL java.lang.Object.<init> ()V constructor-execution(void Hello.<init>()) | RETURN constructor-execution(void Hello.<init>()) end public void <init>() public static void main(String[]) org.aspectj.weaver.MethodDeclarationLineNumber: 7:75 : INVOKESTATIC Hello.sayHello ()V (line 9) RETURN (line 10) end public static void main(String[]) public static void sayHello() org.aspectj.weaver.MethodDeclarationLineNumber: 12:180 : end public static void sayHello() public static int sayWorld() org.aspectj.weaver.MethodDeclarationLineNumber: 17:268 : method-execution(int Hello.sayWorld()) | GETSTATIC java.lang.System.out Ljava/io/PrintStream; (line 18) | LDC "World" | INVOKEVIRTUAL java.io.PrintStream.println (Ljava/lang/String;)V | ICONST_0 (line 19) | IRETURN method-execution(int Hello.sayWorld()) end public static int sayWorld() static final void sayHello_aroundBody0(): GETSTATIC java.lang.System.out Ljava/io/PrintStream; (line 13) LDC "Hello" INVOKEVIRTUAL java.io.PrintStream.println (Ljava/lang/String;)V INVOKESTATIC Hello.sayWorld ()I (line 14) POP RETURN (line 15) end static final void sayHello_aroundBody0() end public class Hello public class Hello$AjcClosure1 extends org.aspectj.runtime.internal.AroundClosure: public void <init>(Object[]): ALOAD_0 ALOAD_1 INVOKESPECIAL org.aspectj.runtime.internal.AroundClosure.<init> ([Ljava/lang/Object;)V RETURN end public void <init>(Object[]) public Object run(Object[]): ALOAD_0 GETFIELD org.aspectj.runtime.internal.AroundClosure.state [Ljava/lang/Object; ASTORE_2 INVOKESTATIC Hello.sayHello_aroundBody0 ()V ACONST_NULL ARETURN end public Object run(Object[]) end public class Hello$AjcClosure1 -- (NullPointerException) null null java.lang.NullPointerException at org.aspectj.weaver.bcel.BcelAdvice.getAdviceArgSetup(BcelAdvice.java:457) at org.aspectj.weaver.bcel.BcelShadow.weaveAroundClosure(BcelShadow.java:2685) at org.aspectj.weaver.bcel.BcelAdvice.implementOn(BcelAdvice.java:230) at org.aspectj.weaver.Shadow.implementMungers(Shadow.java:588) at org.aspectj.weaver.Shadow.implement(Shadow.java:405) at org.aspectj.weaver.bcel.BcelClassWeaver.implement(BcelClassWeaver.java:2146) at org.aspectj.weaver.bcel.BcelClassWeaver.weave(BcelClassWeaver.java:467) at org.aspectj.weaver.bcel.BcelClassWeaver.weave(BcelClassWeaver.java:102) at org.aspectj.weaver.bcel.BcelWeaver.weave(BcelWeaver.java:1543) at org.aspectj.weaver.bcel.BcelWeaver.weaveWithoutDump(BcelWeaver.java:1494) at org.aspectj.weaver.bcel.BcelWeaver.weaveAndNotify(BcelWeaver.java:1275) at org.aspectj.weaver.bcel.BcelWeaver.weave(BcelWeaver.java:1097) at org.aspectj.weaver.tools.WeavingAdaptor.getWovenBytes(WeavingAdaptor.java:263) at org.aspectj.weaver.tools.WeavingAdaptor.weaveClass(WeavingAdaptor.java:196) at org.aspectj.weaver.loadtime.Aj.preProcess(Aj.java:65) at org.aspectj.weaver.loadtime.ClassPreProcessorAgentAdapter.transform(ClassPreProcessorAgentAdapter.java:52) at sun.instrument.TransformerManager.transform(TransformerManager.java:122) at sun.instrument.InstrumentationImpl.transform(InstrumentationImpl.java:155) at java.lang.ClassLoader.defineClass1(Native Method) at java.lang.ClassLoader.defineClass(ClassLoader.java:620) at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:124) at java.net.URLClassLoader.defineClass(URLClassLoader.java:260) at java.net.URLClassLoader.access$100(URLClassLoader.java:56) at java.net.URLClassLoader$1.run(URLClassLoader.java:195) at java.security.AccessController.doPrivileged(Native Method) at java.net.URLClassLoader.findClass(URLClassLoader.java:188) at java.lang.ClassLoader.loadClass(ClassLoader.java:306) at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:268) at java.lang.ClassLoader.loadClass(ClassLoader.java:251) at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:319) Message: abort trouble in: public class Hello extends java.lang.Object: public void <init>(): ALOAD_0 // Hello this (line 2) INVOKESPECIAL java.lang.Object.<init> ()V constructor-execution(void Hello.<init>()) | RETURN constructor-execution(void Hello.<init>()) end public void <init>() public static void main(String[]) org.aspectj.weaver.MethodDeclarationLineNumber: 7:75 : INVOKESTATIC Hello.sayHello ()V (line 9) RETURN (line 10) end public static void main(String[]) public static void sayHello() org.aspectj.weaver.MethodDeclarationLineNumber: 12:180 : end public static void sayHello() public static int sayWorld() org.aspectj.weaver.MethodDeclarationLineNumber: 17:268 : method-execution(int Hello.sayWorld()) | GETSTATIC java.lang.System.out Ljava/io/PrintStream; (line 18) | LDC "World" | INVOKEVIRTUAL java.io.PrintStream.println (Ljava/lang/String;)V | ICONST_0 (line 19) | IRETURN method-execution(int Hello.sayWorld()) end public static int sayWorld() static final void sayHello_aroundBody0(): GETSTATIC java.lang.System.out Ljava/io/PrintStream; (line 13) LDC "Hello" INVOKEVIRTUAL java.io.PrintStream.println (Ljava/lang/String;)V INVOKESTATIC Hello.sayWorld ()I (line 14) POP RETURN (line 15) end static final void sayHello_aroundBody0() end public class Hello public class Hello$AjcClosure1 extends org.aspectj.runtime.internal.AroundClosure: public void <init>(Object[]): ALOAD_0 ALOAD_1 INVOKESPECIAL org.aspectj.runtime.internal.AroundClosure.<init> ([Ljava/lang/Object;)V RETURN end public void <init>(Object[]) public Object run(Object[]): ALOAD_0 GETFIELD org.aspectj.runtime.internal.AroundClosure.state [Ljava/lang/Object; ASTORE_2 INVOKESTATIC Hello.sayHello_aroundBody0 ()V ACONST_NULL ARETURN end public Object run(Object[]) end public class Hello$AjcClosure1 -- (NullPointerException) null null java.lang.NullPointerException at org.aspectj.weaver.bcel.BcelAdvice.getAdviceArgSetup(BcelAdvice.java:457) at org.aspectj.weaver.bcel.BcelShadow.weaveAroundClosure(BcelShadow.java:2685) at org.aspectj.weaver.bcel.BcelAdvice.implementOn(BcelAdvice.java:230) at org.aspectj.weaver.Shadow.implementMungers(Shadow.java:588) at org.aspectj.weaver.Shadow.implement(Shadow.java:405) at org.aspectj.weaver.bcel.BcelClassWeaver.implement(BcelClassWeaver.java:2146) at org.aspectj.weaver.bcel.BcelClassWeaver.weave(BcelClassWeaver.java:467) at org.aspectj.weaver.bcel.BcelClassWeaver.weave(BcelClassWeaver.java:102) at org.aspectj.weaver.bcel.BcelWeaver.weave(BcelWeaver.java:1543) at org.aspectj.weaver.bcel.BcelWeaver.weaveWithoutDump(BcelWeaver.java:1494) at org.aspectj.weaver.bcel.BcelWeaver.weaveAndNotify(BcelWeaver.java:1275) at org.aspectj.weaver.bcel.BcelWeaver.weave(BcelWeaver.java:1097) at org.aspectj.weaver.tools.WeavingAdaptor.getWovenBytes(WeavingAdaptor.java:263) at org.aspectj.weaver.tools.WeavingAdaptor.weaveClass(WeavingAdaptor.java:196) at org.aspectj.weaver.loadtime.Aj.preProcess(Aj.java:65) at org.aspectj.weaver.loadtime.ClassPreProcessorAgentAdapter.transform(ClassPreProcessorAgentAdapter.java:52) at sun.instrument.TransformerManager.transform(TransformerManager.java:122) at sun.instrument.InstrumentationImpl.transform(InstrumentationImpl.java:155) at java.lang.ClassLoader.defineClass1(Native Method) at java.lang.ClassLoader.defineClass(ClassLoader.java:620) at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:124) at java.net.URLClassLoader.defineClass(URLClassLoader.java:260) at java.net.URLClassLoader.access$100(URLClassLoader.java:56) at java.net.URLClassLoader$1.run(URLClassLoader.java:195) at java.security.AccessController.doPrivileged(Native Method) at java.net.URLClassLoader.findClass(URLClassLoader.java:188) at java.lang.ClassLoader.loadClass(ClassLoader.java:306) at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:268) at java.lang.ClassLoader.loadClass(ClassLoader.java:251) at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:319) org.aspectj.bridge.AbortException: trouble in: public class Hello extends java.lang.Object: public void <init>(): ALOAD_0 // Hello this (line 2) INVOKESPECIAL java.lang.Object.<init> ()V constructor-execution(void Hello.<init>()) | RETURN constructor-execution(void Hello.<init>()) end public void <init>() public static void main(String[]) org.aspectj.weaver.MethodDeclarationLineNumber: 7:75 : INVOKESTATIC Hello.sayHello ()V (line 9) RETURN (line 10) end public static void main(String[]) public static void sayHello() org.aspectj.weaver.MethodDeclarationLineNumber: 12:180 : end public static void sayHello() public static int sayWorld() org.aspectj.weaver.MethodDeclarationLineNumber: 17:268 : method-execution(int Hello.sayWorld()) | GETSTATIC java.lang.System.out Ljava/io/PrintStream; (line 18) | LDC "World" | INVOKEVIRTUAL java.io.PrintStream.println (Ljava/lang/String;)V | ICONST_0 (line 19) | IRETURN method-execution(int Hello.sayWorld()) end public static int sayWorld() static final void sayHello_aroundBody0(): GETSTATIC java.lang.System.out Ljava/io/PrintStream; (line 13) LDC "Hello" INVOKEVIRTUAL java.io.PrintStream.println (Ljava/lang/String;)V INVOKESTATIC Hello.sayWorld ()I (line 14) POP RETURN (line 15) end static final void sayHello_aroundBody0() end public class Hello public class Hello$AjcClosure1 extends org.aspectj.runtime.internal.AroundClosure: public void <init>(Object[]): ALOAD_0 ALOAD_1 INVOKESPECIAL org.aspectj.runtime.internal.AroundClosure.<init> ([Ljava/lang/Object;)V RETURN end public void <init>(Object[]) public Object run(Object[]): ALOAD_0 GETFIELD org.aspectj.runtime.internal.AroundClosure.state [Ljava/lang/Object; ASTORE_2 INVOKESTATIC Hello.sayHello_aroundBody0 ()V ACONST_NULL ARETURN end public Object run(Object[]) end public class Hello$AjcClosure1 at org.aspectj.bridge.MessageWriter.handleMessage(MessageWriter.java:47) at org.aspectj.weaver.tools.WeavingAdaptor$WeavingAdaptorMessageHandler.handleMessage(WeavingAdaptor.java:395) at org.aspectj.weaver.bcel.BcelWeaver.weave(BcelWeaver.java:1554) at org.aspectj.weaver.bcel.BcelWeaver.weaveWithoutDump(BcelWeaver.java:1494) at org.aspectj.weaver.bcel.BcelWeaver.weaveAndNotify(BcelWeaver.java:1275) at org.aspectj.weaver.bcel.BcelWeaver.weave(BcelWeaver.java:1097) at org.aspectj.weaver.tools.WeavingAdaptor.getWovenBytes(WeavingAdaptor.java:263) at org.aspectj.weaver.tools.WeavingAdaptor.weaveClass(WeavingAdaptor.java:196) at org.aspectj.weaver.loadtime.Aj.preProcess(Aj.java:65) at org.aspectj.weaver.loadtime.ClassPreProcessorAgentAdapter.transform(ClassPreProcessorAgentAdapter.java:52) at sun.instrument.TransformerManager.transform(TransformerManager.java:122) at sun.instrument.InstrumentationImpl.transform(InstrumentationImpl.java:155) at java.lang.ClassLoader.defineClass1(Native Method) at java.lang.ClassLoader.defineClass(ClassLoader.java:620) at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:124) at java.net.URLClassLoader.defineClass(URLClassLoader.java:260) at java.net.URLClassLoader.access$100(URLClassLoader.java:56) at java.net.URLClassLoader$1.run(URLClassLoader.java:195) at java.security.AccessController.doPrivileged(Native Method) at java.net.URLClassLoader.findClass(URLClassLoader.java:188) at java.lang.ClassLoader.loadClass(ClassLoader.java:306) at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:268) at java.lang.ClassLoader.loadClass(ClassLoader.java:251) at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:319) Hello World
|
resolved fixed
|
a778ac4
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2005-12-21T17:21:57Z | 2005-12-19T11:00:00Z |
weaver/src/org/aspectj/weaver/bcel/BcelShadow.java
|
/* *******************************************************************
* Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC).
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* PARC initial implementation
* Alexandre Vasseur support for @AJ aspects
* ******************************************************************/
package org.aspectj.weaver.bcel;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.aspectj.apache.bcel.Constants;
import org.aspectj.apache.bcel.classfile.Field;
import org.aspectj.apache.bcel.generic.ACONST_NULL;
import org.aspectj.apache.bcel.generic.ALOAD;
import org.aspectj.apache.bcel.generic.ANEWARRAY;
import org.aspectj.apache.bcel.generic.ArrayType;
import org.aspectj.apache.bcel.generic.BranchInstruction;
import org.aspectj.apache.bcel.generic.ConstantPoolGen;
import org.aspectj.apache.bcel.generic.DUP;
import org.aspectj.apache.bcel.generic.DUP_X1;
import org.aspectj.apache.bcel.generic.FieldInstruction;
import org.aspectj.apache.bcel.generic.INVOKEINTERFACE;
import org.aspectj.apache.bcel.generic.INVOKESPECIAL;
import org.aspectj.apache.bcel.generic.INVOKESTATIC;
import org.aspectj.apache.bcel.generic.Instruction;
import org.aspectj.apache.bcel.generic.InstructionConstants;
import org.aspectj.apache.bcel.generic.InstructionFactory;
import org.aspectj.apache.bcel.generic.InstructionHandle;
import org.aspectj.apache.bcel.generic.InstructionList;
import org.aspectj.apache.bcel.generic.InstructionTargeter;
import org.aspectj.apache.bcel.generic.InvokeInstruction;
import org.aspectj.apache.bcel.generic.LoadInstruction;
import org.aspectj.apache.bcel.generic.MULTIANEWARRAY;
import org.aspectj.apache.bcel.generic.NEW;
import org.aspectj.apache.bcel.generic.ObjectType;
import org.aspectj.apache.bcel.generic.PUSH;
import org.aspectj.apache.bcel.generic.ReturnInstruction;
import org.aspectj.apache.bcel.generic.SWAP;
import org.aspectj.apache.bcel.generic.StoreInstruction;
import org.aspectj.apache.bcel.generic.TargetLostException;
import org.aspectj.apache.bcel.generic.Type;
import org.aspectj.bridge.ISourceLocation;
import org.aspectj.weaver.Advice;
import org.aspectj.weaver.AdviceKind;
import org.aspectj.weaver.AjcMemberMaker;
import org.aspectj.weaver.BCException;
import org.aspectj.weaver.IntMap;
import org.aspectj.weaver.Member;
import org.aspectj.weaver.MemberImpl;
import org.aspectj.weaver.NameMangler;
import org.aspectj.weaver.NewConstructorTypeMunger;
import org.aspectj.weaver.NewFieldTypeMunger;
import org.aspectj.weaver.NewMethodTypeMunger;
import org.aspectj.weaver.ResolvedMember;
import org.aspectj.weaver.ResolvedMemberImpl;
import org.aspectj.weaver.ResolvedType;
import org.aspectj.weaver.Shadow;
import org.aspectj.weaver.ShadowMunger;
import org.aspectj.weaver.UnresolvedType;
import org.aspectj.weaver.WeaverMessages;
import org.aspectj.weaver.World;
import org.aspectj.weaver.ast.Var;
/*
* Some fun implementation stuff:
*
* * expressionKind advice is non-execution advice
* * may have a target.
* * if the body is extracted, it will be extracted into
* a static method. The first argument to the static
* method is the target
* * advice may expose a this object, but that's the advice's
* consideration, not ours. This object will NOT be cached in another
* local, but will always come from frame zero.
*
* * non-expressionKind advice is execution advice
* * may have a this.
* * target is same as this, and is exposed that way to advice
* (i.e., target will not be cached, will always come from frame zero)
* * if the body is extracted, it will be extracted into a method
* with same static/dynamic modifier as enclosing method. If non-static,
* target of callback call will be this.
*
* * because of these two facts, the setup of the actual arguments (including
* possible target) callback method is the same for both kinds of advice:
* push the targetVar, if it exists (it will not exist for advice on static
* things), then push all the argVars.
*
* Protected things:
*
* * the above is sufficient for non-expressionKind advice for protected things,
* since the target will always be this.
*
* * For expressionKind things, we have to modify the signature of the callback
* method slightly. For non-static expressionKind things, we modify
* the first argument of the callback method NOT to be the type specified
* by the method/field signature (the owner), but rather we type it to
* the currentlyEnclosing type. We are guaranteed this will be fine,
* since the verifier verifies that the target is a subtype of the currently
* enclosingType.
*
* Worries:
*
* * ConstructorCalls will be weirder than all of these, since they
* supposedly don't have a target (according to AspectJ), but they clearly
* do have a target of sorts, just one that needs to be pushed on the stack,
* dupped, and not touched otherwise until the constructor runs.
*
* @author Jim Hugunin
* @author Erik Hilsdale
*
*/
public class BcelShadow extends Shadow {
private ShadowRange range;
private final BcelWorld world;
private final LazyMethodGen enclosingMethod;
// private boolean fallsThrough; //XXX not used anymore
// SECRETAPI - for testing, this will tell us if the optimization succeeded *on the last shadow processed*
public static boolean appliedLazyTjpOptimization;
// Some instructions have a target type that will vary
// from the signature (pr109728) (1.4 declaring type issue)
private String actualInstructionTargetType;
// ---- initialization
/**
* This generates an unassociated shadow, rooted in a particular method but not rooted
* to any particular point in the code. It should be given to a rooted ShadowRange
* in the {@link ShadowRange#associateWithShadow(BcelShadow)} method.
*/
public BcelShadow(
BcelWorld world,
Kind kind,
Member signature,
LazyMethodGen enclosingMethod,
BcelShadow enclosingShadow)
{
super(kind, signature, enclosingShadow);
this.world = world;
this.enclosingMethod = enclosingMethod;
// fallsThrough = kind.argsOnStack();
}
// ---- copies all state, including Shadow's mungers...
public BcelShadow copyInto(LazyMethodGen recipient, BcelShadow enclosing) {
BcelShadow s = new BcelShadow(world, getKind(), getSignature(), recipient, enclosing);
List src = mungers;
List dest = s.mungers;
for (Iterator i = src.iterator(); i.hasNext(); ) {
dest.add(i.next());
}
return s;
}
// ---- overridden behaviour
public World getIWorld() {
return world;
}
private void deleteNewAndDup() {
final ConstantPoolGen cpg = getEnclosingClass().getConstantPoolGen();
int depth = 1;
InstructionHandle ih = range.getStart();
while (true) {
Instruction inst = ih.getInstruction();
if (inst instanceof INVOKESPECIAL
&& ((INVOKESPECIAL) inst).getName(cpg).equals("<init>")) {
depth++;
} else if (inst instanceof NEW) {
depth--;
if (depth == 0) break;
}
ih = ih.getPrev();
}
// now IH points to the NEW. We're followed by the DUP, and that is followed
// by the actual instruction we care about.
InstructionHandle newHandle = ih;
InstructionHandle endHandle = newHandle.getNext();
InstructionHandle nextHandle;
if (endHandle.getInstruction() instanceof DUP) {
nextHandle = endHandle.getNext();
retargetFrom(newHandle, nextHandle);
retargetFrom(endHandle, nextHandle);
} else if (endHandle.getInstruction() instanceof DUP_X1) {
InstructionHandle dupHandle = endHandle;
endHandle = endHandle.getNext();
nextHandle = endHandle.getNext();
if (endHandle.getInstruction() instanceof SWAP) {}
else {
// XXX see next XXX comment
throw new RuntimeException("Unhandled kind of new " + endHandle);
}
// Now make any jumps to the 'new', the 'dup' or the 'end' now target the nextHandle
retargetFrom(newHandle, nextHandle);
retargetFrom(dupHandle, nextHandle);
retargetFrom(endHandle, nextHandle);
} else {
endHandle = newHandle;
nextHandle = endHandle.getNext();
retargetFrom(newHandle, nextHandle);
// add a POP here... we found a NEW w/o a dup or anything else, so
// we must be in statement context.
getRange().insert(InstructionConstants.POP, Range.OutsideAfter);
}
// assert (dupHandle.getInstruction() instanceof DUP);
try {
range.getBody().delete(newHandle, endHandle);
} catch (TargetLostException e) {
throw new BCException("shouldn't happen");
}
}
private void retargetFrom(InstructionHandle old, InstructionHandle fresh) {
InstructionTargeter[] sources = old.getTargeters();
if (sources != null) {
for (int i = sources.length - 1; i >= 0; i--) {
if (sources[i] instanceof ExceptionRange) {
ExceptionRange it = (ExceptionRange)sources[i];
System.err.println("...");
it.updateTarget(old,fresh,it.getBody());
} else {
sources[i].updateTarget(old, fresh);
}
}
}
}
// records advice that is stopping us doing the lazyTjp optimization
private List badAdvice = null;
public void addAdvicePreventingLazyTjp(BcelAdvice advice) {
if (badAdvice == null) badAdvice = new ArrayList();
badAdvice.add(advice);
}
protected void prepareForMungers() {
// if we're a constructor call, we need to remove the new:dup or the new:dup_x1:swap,
// and store all our
// arguments on the frame.
// ??? This is a bit of a hack (for the Java langauge). We do this because
// we sometime add code "outsideBefore" when dealing with weaving join points. We only
// do this for exposing state that is on the stack. It turns out to just work for
// everything except for constructor calls and exception handlers. If we were to clean
// this up, every ShadowRange would have three instructionHandle points, the start of
// the arg-setup code, the start of the running code, and the end of the running code.
if (getKind() == ConstructorCall) {
deleteNewAndDup();
initializeArgVars();
} else if (getKind() == PreInitialization) { // pr74952
ShadowRange range = getRange();
range.insert(InstructionConstants.NOP,Range.InsideAfter);
} else if (getKind() == ExceptionHandler) {
ShadowRange range = getRange();
InstructionList body = range.getBody();
InstructionHandle start = range.getStart();
// Create a store instruction to put the value from the top of the
// stack into a local variable slot. This is a trimmed version of
// what is in initializeArgVars() (since there is only one argument
// at a handler jp and only before advice is supported) (pr46298)
argVars = new BcelVar[1];
//int positionOffset = (hasTarget() ? 1 : 0) + ((hasThis() && !getKind().isTargetSameAsThis()) ? 1 : 0);
UnresolvedType tx = getArgType(0);
argVars[0] = genTempVar(tx, "ajc$arg0");
InstructionHandle insertedInstruction =
range.insert(argVars[0].createStore(getFactory()), Range.OutsideBefore);
// Now the exception range starts just after our new instruction.
// The next bit of code changes the exception range to point at
// the store instruction
InstructionTargeter[] targeters = start.getTargeters();
for (int i = 0; i < targeters.length; i++) {
InstructionTargeter t = targeters[i];
if (t instanceof ExceptionRange) {
ExceptionRange er = (ExceptionRange) t;
er.updateTarget(start, insertedInstruction, body);
}
}
}
// now we ask each munger to request our state
isThisJoinPointLazy = true;//world.isXlazyTjp(); // lazy is default now
badAdvice = null;
for (Iterator iter = mungers.iterator(); iter.hasNext();) {
ShadowMunger munger = (ShadowMunger) iter.next();
munger.specializeOn(this);
}
initializeThisJoinPoint();
if (thisJoinPointVar!=null && !isThisJoinPointLazy && badAdvice!=null && badAdvice.size()>1) {
// something stopped us making it a lazy tjp
// can't build tjp lazily, no suitable test...
int valid = 0;
for (Iterator iter = badAdvice.iterator(); iter.hasNext();) {
BcelAdvice element = (BcelAdvice) iter.next();
ISourceLocation sLoc = element.getSourceLocation();
if (sLoc!=null && sLoc.getLine()>0) valid++;
}
if (valid!=0) {
ISourceLocation[] badLocs = new ISourceLocation[valid];
int i = 0;
for (Iterator iter = badAdvice.iterator(); iter.hasNext();) {
BcelAdvice element = (BcelAdvice) iter.next();
ISourceLocation sLoc = element.getSourceLocation();
if (sLoc!=null) badLocs[i++]=sLoc;
}
world.getLint().multipleAdviceStoppingLazyTjp.signal(
new String[] {this.toString()},
getSourceLocation(),badLocs
);
}
}
badAdvice=null;
// If we are an expression kind, we require our target/arguments on the stack
// before we do our actual thing. However, they may have been removed
// from the stack as the shadowMungers have requested state.
// if any of our shadowMungers requested either the arguments or target,
// the munger will have added code
// to pop the target/arguments into temporary variables, represented by
// targetVar and argVars. In such a case, we must make sure to re-push the
// values.
// If we are nonExpressionKind, we don't expect arguments on the stack
// so this is moot. If our argVars happen to be null, then we know that
// no ShadowMunger has squirrelled away our arguments, so they're still
// on the stack.
InstructionFactory fact = getFactory();
if (getKind().argsOnStack() && argVars != null) {
// Special case first (pr46298). If we are an exception handler and the instruction
// just after the shadow is a POP then we should remove the pop. The code
// above which generated the store instruction has already cleared the stack.
// We also don't generate any code for the arguments in this case as it would be
// an incorrect aload.
if (getKind() == ExceptionHandler
&& range.getEnd().getNext().getInstruction().equals(InstructionConstants.POP)) {
// easier than deleting it ...
range.getEnd().getNext().setInstruction(InstructionConstants.NOP);
} else {
range.insert(
BcelRenderer.renderExprs(fact, world, argVars),
Range.InsideBefore);
if (targetVar != null) {
range.insert(
BcelRenderer.renderExpr(fact, world, targetVar),
Range.InsideBefore);
}
if (getKind() == ConstructorCall) {
range.insert((Instruction) InstructionFactory.createDup(1), Range.InsideBefore);
range.insert(
fact.createNew(
(ObjectType) BcelWorld.makeBcelType(
getSignature().getDeclaringType())),
Range.InsideBefore);
}
}
}
}
// ---- getters
public ShadowRange getRange() {
return range;
}
public void setRange(ShadowRange range) {
this.range = range;
}
public int getSourceLine() {
// if the kind of join point for which we are a shadow represents
// a method or constructor execution, then the best source line is
// the one from the enclosingMethod declarationLineNumber if available.
Kind kind = getKind();
if ( (kind == MethodExecution) ||
(kind == ConstructorExecution) ||
(kind == AdviceExecution) ||
(kind == StaticInitialization) ||
(kind == PreInitialization) ||
(kind == Initialization)) {
if (getEnclosingMethod().hasDeclaredLineNumberInfo()) {
return getEnclosingMethod().getDeclarationLineNumber();
}
}
if (range == null) {
if (getEnclosingMethod().hasBody()) {
return Utility.getSourceLine(getEnclosingMethod().getBody().getStart());
} else {
return 0;
}
}
int ret = Utility.getSourceLine(range.getStart());
if (ret < 0) return 0;
return ret;
}
// overrides
public UnresolvedType getEnclosingType() {
return getEnclosingClass().getType();
}
public LazyClassGen getEnclosingClass() {
return enclosingMethod.getEnclosingClass();
}
public BcelWorld getWorld() {
return world;
}
// ---- factory methods
public static BcelShadow makeConstructorExecution(
BcelWorld world,
LazyMethodGen enclosingMethod,
InstructionHandle justBeforeStart)
{
final InstructionList body = enclosingMethod.getBody();
BcelShadow s =
new BcelShadow(
world,
ConstructorExecution,
world.makeJoinPointSignature(enclosingMethod),
enclosingMethod,
null);
ShadowRange r = new ShadowRange(body);
r.associateWithShadow(s);
r.associateWithTargets(
Range.genStart(body, justBeforeStart.getNext()),
Range.genEnd(body));
return s;
}
public static BcelShadow makeStaticInitialization(
BcelWorld world,
LazyMethodGen enclosingMethod)
{
InstructionList body = enclosingMethod.getBody();
// move the start past ajc$preClinit
InstructionHandle clinitStart = body.getStart();
if (clinitStart.getInstruction() instanceof InvokeInstruction) {
InvokeInstruction ii = (InvokeInstruction)clinitStart.getInstruction();
if (ii
.getName(enclosingMethod.getEnclosingClass().getConstantPoolGen())
.equals(NameMangler.AJC_PRE_CLINIT_NAME)) {
clinitStart = clinitStart.getNext();
}
}
InstructionHandle clinitEnd = body.getEnd();
//XXX should move the end before the postClinit, but the return is then tricky...
// if (clinitEnd.getInstruction() instanceof InvokeInstruction) {
// InvokeInstruction ii = (InvokeInstruction)clinitEnd.getInstruction();
// if (ii.getName(enclosingMethod.getEnclosingClass().getConstantPoolGen()).equals(NameMangler.AJC_POST_CLINIT_NAME)) {
// clinitEnd = clinitEnd.getPrev();
// }
// }
BcelShadow s =
new BcelShadow(
world,
StaticInitialization,
world.makeJoinPointSignature(enclosingMethod),
enclosingMethod,
null);
ShadowRange r = new ShadowRange(body);
r.associateWithShadow(s);
r.associateWithTargets(
Range.genStart(body, clinitStart),
Range.genEnd(body, clinitEnd));
return s;
}
/** Make the shadow for an exception handler. Currently makes an empty shadow that
* only allows before advice to be woven into it.
*/
public static BcelShadow makeExceptionHandler(
BcelWorld world,
ExceptionRange exceptionRange,
LazyMethodGen enclosingMethod,
InstructionHandle startOfHandler,
BcelShadow enclosingShadow)
{
InstructionList body = enclosingMethod.getBody();
UnresolvedType catchType = exceptionRange.getCatchType();
UnresolvedType inType = enclosingMethod.getEnclosingClass().getType();
ResolvedMemberImpl sig = MemberImpl.makeExceptionHandlerSignature(inType, catchType);
sig.parameterNames = new String[] {findHandlerParamName(startOfHandler)};
BcelShadow s =
new BcelShadow(
world,
ExceptionHandler,
sig,
enclosingMethod,
enclosingShadow);
ShadowRange r = new ShadowRange(body);
r.associateWithShadow(s);
InstructionHandle start = Range.genStart(body, startOfHandler);
InstructionHandle end = Range.genEnd(body, start);
r.associateWithTargets(start, end);
exceptionRange.updateTarget(startOfHandler, start, body);
return s;
}
private static String findHandlerParamName(InstructionHandle startOfHandler) {
if (startOfHandler.getInstruction() instanceof StoreInstruction &&
startOfHandler.getNext() != null)
{
int slot = ((StoreInstruction)startOfHandler.getInstruction()).getIndex();
//System.out.println("got store: " + startOfHandler.getInstruction() + ", " + index);
InstructionTargeter[] targeters = startOfHandler.getNext().getTargeters();
if (targeters!=null) {
for (int i=targeters.length-1; i >= 0; i--) {
if (targeters[i] instanceof LocalVariableTag) {
LocalVariableTag t = (LocalVariableTag)targeters[i];
if (t.getSlot() == slot) {
return t.getName();
}
//System.out.println("tag: " + targeters[i]);
}
}
}
}
return "<missing>";
}
/** create an init join point associated w/ an interface in the body of a constructor */
public static BcelShadow makeIfaceInitialization(
BcelWorld world,
LazyMethodGen constructor,
Member interfaceConstructorSignature)
{
// 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 makeMethodCall(
BcelWorld world,
LazyMethodGen enclosingMethod,
InstructionHandle callHandle,
BcelShadow enclosingShadow)
{
final InstructionList body = enclosingMethod.getBody();
BcelShadow s =
new BcelShadow(
world,
MethodCall,
world.makeJoinPointSignatureForMethodInvocation(
enclosingMethod.getEnclosingClass(),
(InvokeInstruction) callHandle.getInstruction()),
enclosingMethod,
enclosingShadow);
ShadowRange r = new ShadowRange(body);
r.associateWithShadow(s);
r.associateWithTargets(
Range.genStart(body, callHandle),
Range.genEnd(body, callHandle));
retargetAllBranches(callHandle, r.getStart());
return s;
}
public static BcelShadow makeShadowForMethodCall(
BcelWorld world,
LazyMethodGen enclosingMethod,
InstructionHandle callHandle,
BcelShadow enclosingShadow,
Kind kind,
ResolvedMember sig)
{
final InstructionList body = enclosingMethod.getBody();
BcelShadow s =
new BcelShadow(
world,
kind,
sig,
enclosingMethod,
enclosingShadow);
ShadowRange r = new ShadowRange(body);
r.associateWithShadow(s);
r.associateWithTargets(
Range.genStart(body, callHandle),
Range.genEnd(body, callHandle));
retargetAllBranches(callHandle, r.getStart());
return s;
}
public static BcelShadow makeFieldGet(
BcelWorld world,
ResolvedMember field,
LazyMethodGen enclosingMethod,
InstructionHandle getHandle,
BcelShadow enclosingShadow)
{
final InstructionList body = enclosingMethod.getBody();
BcelShadow s =
new BcelShadow(
world,
FieldGet,
field,
// BcelWorld.makeFieldSignature(
// enclosingMethod.getEnclosingClass(),
// (FieldInstruction) getHandle.getInstruction()),
enclosingMethod,
enclosingShadow);
ShadowRange r = new ShadowRange(body);
r.associateWithShadow(s);
r.associateWithTargets(
Range.genStart(body, getHandle),
Range.genEnd(body, getHandle));
retargetAllBranches(getHandle, r.getStart());
return s;
}
public static BcelShadow makeFieldSet(
BcelWorld world,
LazyMethodGen enclosingMethod,
InstructionHandle setHandle,
BcelShadow enclosingShadow)
{
final InstructionList body = enclosingMethod.getBody();
BcelShadow s =
new BcelShadow(
world,
FieldSet,
BcelWorld.makeFieldJoinPointSignature(
enclosingMethod.getEnclosingClass(),
(FieldInstruction) setHandle.getInstruction()),
enclosingMethod,
enclosingShadow);
ShadowRange r = new ShadowRange(body);
r.associateWithShadow(s);
r.associateWithTargets(
Range.genStart(body, setHandle),
Range.genEnd(body, setHandle));
retargetAllBranches(setHandle, r.getStart());
return s;
}
public static void retargetAllBranches(InstructionHandle from, InstructionHandle to) {
InstructionTargeter[] sources = from.getTargeters();
if (sources != null) {
for (int i = sources.length - 1; i >= 0; i--) {
InstructionTargeter source = sources[i];
if (source instanceof BranchInstruction) {
source.updateTarget(from, to);
}
}
}
}
// // ---- type access methods
// private ObjectType getTargetBcelType() {
// return (ObjectType) BcelWorld.makeBcelType(getTargetType());
// }
// private Type getArgBcelType(int arg) {
// return BcelWorld.makeBcelType(getArgType(arg));
// }
// ---- kinding
/**
* If the end of my range has no real instructions following then
* my context needs a return at the end.
*/
public boolean terminatesWithReturn() {
return getRange().getRealNext() == null;
}
/**
* Is arg0 occupied with the value of this
*/
public boolean arg0HoldsThis() {
if (getKind().isEnclosingKind()) {
return !getSignature().isStatic();
} else if (enclosingShadow == null) {
//XXX this is mostly right
// this doesn't do the right thing for calls in the pre part of introduced constructors.
return !enclosingMethod.isStatic();
} else {
return ((BcelShadow)enclosingShadow).arg0HoldsThis();
}
}
// ---- argument getting methods
private BcelVar thisVar = null;
private BcelVar targetVar = null;
private BcelVar[] argVars = null;
private Map/*<UnresolvedType,BcelVar>*/ kindedAnnotationVars = null;
private Map/*<UnresolvedType,BcelVar>*/ thisAnnotationVars = null;
private Map/*<UnresolvedType,BcelVar>*/ targetAnnotationVars = null;
private Map/*<UnresolvedType,BcelVar>*/[] argAnnotationVars = null;
private Map/*<UnresolvedType,BcelVar>*/ withinAnnotationVars = null;
private Map/*<UnresolvedType,BcelVar>*/ withincodeAnnotationVars = null;
public Var getThisVar() {
if (!hasThis()) {
throw new IllegalStateException("no this");
}
initializeThisVar();
return thisVar;
}
public Var getThisAnnotationVar(UnresolvedType forAnnotationType) {
if (!hasThis()) {
throw new IllegalStateException("no this");
}
initializeThisAnnotationVars(); // FIXME asc Why bother with this if we always return one?
// Even if we can't find one, we have to return one as we might have this annotation at runtime
Var v = (Var) thisAnnotationVars.get(forAnnotationType);
if (v==null)
v = new TypeAnnotationAccessVar(forAnnotationType.resolve(world),(BcelVar)getThisVar());
return v;
}
public Var getTargetVar() {
if (!hasTarget()) {
throw new IllegalStateException("no target");
}
initializeTargetVar();
return targetVar;
}
public Var getTargetAnnotationVar(UnresolvedType forAnnotationType) {
if (!hasTarget()) {
throw new IllegalStateException("no target");
}
initializeTargetAnnotationVars(); // FIXME asc why bother with this if we always return one?
Var v =(Var) targetAnnotationVars.get(forAnnotationType);
// Even if we can't find one, we have to return one as we might have this annotation at runtime
if (v==null)
v = new TypeAnnotationAccessVar(forAnnotationType.resolve(world),(BcelVar)getTargetVar());
return v;
}
public Var getArgVar(int i) {
initializeArgVars();
return argVars[i];
}
public Var getArgAnnotationVar(int i,UnresolvedType forAnnotationType) {
initializeArgAnnotationVars();
Var v= (Var) argAnnotationVars[i].get(forAnnotationType);
if (v==null)
v = new TypeAnnotationAccessVar(forAnnotationType.resolve(world),(BcelVar)getArgVar(i));
return v;
}
public Var getKindedAnnotationVar(UnresolvedType forAnnotationType) {
initializeKindedAnnotationVars();
return (Var) kindedAnnotationVars.get(forAnnotationType);
}
public Var getWithinAnnotationVar(UnresolvedType forAnnotationType) {
initializeWithinAnnotationVars();
return (Var) withinAnnotationVars.get(forAnnotationType);
}
public Var getWithinCodeAnnotationVar(UnresolvedType forAnnotationType) {
initializeWithinCodeAnnotationVars();
return (Var) withincodeAnnotationVars.get(forAnnotationType);
}
// reflective thisJoinPoint support
private BcelVar thisJoinPointVar = null;
private boolean isThisJoinPointLazy;
private int lazyTjpConsumers = 0;
private BcelVar thisJoinPointStaticPartVar = null;
// private BcelVar thisEnclosingJoinPointStaticPartVar = null;
public final Var getThisJoinPointStaticPartVar() {
return getThisJoinPointStaticPartBcelVar();
}
public final Var getThisEnclosingJoinPointStaticPartVar() {
return getThisEnclosingJoinPointStaticPartBcelVar();
}
public void requireThisJoinPoint(boolean hasGuardTest, boolean isAround) {
if (!isAround){
if (!hasGuardTest) {
isThisJoinPointLazy = false;
} else {
lazyTjpConsumers++;
}
}
// if (!hasGuardTest) {
// isThisJoinPointLazy = false;
// } else {
// lazyTjpConsumers++;
// }
if (thisJoinPointVar == null) {
thisJoinPointVar = genTempVar(UnresolvedType.forName("org.aspectj.lang.JoinPoint"));
}
}
public Var getThisJoinPointVar() {
requireThisJoinPoint(false,false);
return thisJoinPointVar;
}
void initializeThisJoinPoint() {
if (thisJoinPointVar == null) return;
if (isThisJoinPointLazy) {
isThisJoinPointLazy = checkLazyTjp();
}
if (isThisJoinPointLazy) {
appliedLazyTjpOptimization = true;
createThisJoinPoint(); // make sure any state needed is initialized, but throw the instructions out
if (lazyTjpConsumers == 1) return; // special case only one lazyTjpUser
InstructionFactory fact = getFactory();
InstructionList il = new InstructionList();
il.append(InstructionConstants.ACONST_NULL);
il.append(thisJoinPointVar.createStore(fact));
range.insert(il, Range.OutsideBefore);
} else {
appliedLazyTjpOptimization = false;
InstructionFactory fact = getFactory();
InstructionList il = createThisJoinPoint();
il.append(thisJoinPointVar.createStore(fact));
range.insert(il, Range.OutsideBefore);
}
}
private boolean checkLazyTjp() {
// check for around advice
for (Iterator i = mungers.iterator(); i.hasNext();) {
ShadowMunger munger = (ShadowMunger) i.next();
if (munger instanceof Advice) {
if ( ((Advice)munger).getKind() == AdviceKind.Around) {
if (munger.getSourceLocation()!=null) { // do we know enough to bother reporting?
world.getLint().canNotImplementLazyTjp.signal(
new String[] {toString()},
getSourceLocation(),
new ISourceLocation[] { munger.getSourceLocation() }
);
}
return false;
}
}
}
return true;
}
InstructionList loadThisJoinPoint() {
InstructionFactory fact = getFactory();
InstructionList il = new InstructionList();
if (isThisJoinPointLazy) {
// If we're lazy, build the join point right here.
il.append(createThisJoinPoint());
// Does someone else need it? If so, store it for later retrieval
if (lazyTjpConsumers > 1) {
il.append(thisJoinPointVar.createStore(fact));
InstructionHandle end = il.append(thisJoinPointVar.createLoad(fact));
il.insert(InstructionFactory.createBranchInstruction(Constants.IFNONNULL, end));
il.insert(thisJoinPointVar.createLoad(fact));
}
} else {
// If not lazy, its already been built and stored, just retrieve it
thisJoinPointVar.appendLoad(il, fact);
}
return il;
}
InstructionList createThisJoinPoint() {
InstructionFactory fact = getFactory();
InstructionList il = new InstructionList();
BcelVar staticPart = getThisJoinPointStaticPartBcelVar();
staticPart.appendLoad(il, fact);
if (hasThis()) {
((BcelVar)getThisVar()).appendLoad(il, fact);
} else {
il.append(new ACONST_NULL());
}
if (hasTarget()) {
((BcelVar)getTargetVar()).appendLoad(il, fact);
} else {
il.append(new ACONST_NULL());
}
switch(getArgCount()) {
case 0:
il.append(fact.createInvoke("org.aspectj.runtime.reflect.Factory",
"makeJP", LazyClassGen.tjpType,
new Type[] { LazyClassGen.staticTjpType,
Type.OBJECT, Type.OBJECT},
Constants.INVOKESTATIC));
break;
case 1:
((BcelVar)getArgVar(0)).appendLoadAndConvert(il, fact, world.getCoreType(ResolvedType.OBJECT));
il.append(fact.createInvoke("org.aspectj.runtime.reflect.Factory",
"makeJP", LazyClassGen.tjpType,
new Type[] { LazyClassGen.staticTjpType,
Type.OBJECT, Type.OBJECT, Type.OBJECT},
Constants.INVOKESTATIC));
break;
case 2:
((BcelVar)getArgVar(0)).appendLoadAndConvert(il, fact, world.getCoreType(ResolvedType.OBJECT));
((BcelVar)getArgVar(1)).appendLoadAndConvert(il, fact, world.getCoreType(ResolvedType.OBJECT));
il.append(fact.createInvoke("org.aspectj.runtime.reflect.Factory",
"makeJP", LazyClassGen.tjpType,
new Type[] { LazyClassGen.staticTjpType,
Type.OBJECT, Type.OBJECT, Type.OBJECT, Type.OBJECT},
Constants.INVOKESTATIC));
break;
default:
il.append(makeArgsObjectArray());
il.append(fact.createInvoke("org.aspectj.runtime.reflect.Factory",
"makeJP", LazyClassGen.tjpType,
new Type[] { LazyClassGen.staticTjpType,
Type.OBJECT, Type.OBJECT, new ArrayType(Type.OBJECT, 1)},
Constants.INVOKESTATIC));
break;
}
return il;
}
/**
* Get the Var for the jpStaticPart
* @return
*/
public BcelVar getThisJoinPointStaticPartBcelVar() {
return getThisJoinPointStaticPartBcelVar(false);
}
/**
* Get the Var for the xxxxJpStaticPart, xxx = this or enclosing
* @param isEnclosingJp true to have the enclosingJpStaticPart
* @return
*/
public BcelVar getThisJoinPointStaticPartBcelVar(final boolean isEnclosingJp) {
if (thisJoinPointStaticPartVar == null) {
Field field = getEnclosingClass().getTjpField(this, isEnclosingJp);
ResolvedType sjpType = null;
if (world.isTargettingAspectJRuntime12()) { // TAG:SUPPORTING12: We didn't have different jpsp types in 1.2
sjpType = world.getCoreType(UnresolvedType.forName("org.aspectj.lang.JoinPoint$StaticPart"));
} else {
sjpType = isEnclosingJp?
world.getCoreType(UnresolvedType.forName("org.aspectj.lang.JoinPoint$EnclosingStaticPart")):
world.getCoreType(UnresolvedType.forName("org.aspectj.lang.JoinPoint$StaticPart"));
}
thisJoinPointStaticPartVar = new BcelFieldRef(
sjpType,
getEnclosingClass().getClassName(),
field.getName());
// getEnclosingClass().warnOnAddedStaticInitializer(this,munger.getSourceLocation());
}
return thisJoinPointStaticPartVar;
}
/**
* Get the Var for the enclosingJpStaticPart
* @return
*/
public BcelVar getThisEnclosingJoinPointStaticPartBcelVar() {
if (enclosingShadow == null) {
// the enclosing of an execution is itself
return getThisJoinPointStaticPartBcelVar(true);
} else {
return ((BcelShadow)enclosingShadow).getThisJoinPointStaticPartBcelVar(true);
}
}
//??? need to better understand all the enclosing variants
public Member getEnclosingCodeSignature() {
if (getKind().isEnclosingKind()) {
return getSignature();
} else if (getKind() == Shadow.PreInitialization) {
// PreInit doesn't enclose code but its signature
// is correctly the signature of the ctor.
return getSignature();
} else if (enclosingShadow == null) {
return getEnclosingMethod().getMemberView();
} else {
return enclosingShadow.getSignature();
}
}
private InstructionList makeArgsObjectArray() {
InstructionFactory fact = getFactory();
BcelVar arrayVar = genTempVar(UnresolvedType.OBJECTARRAY);
final InstructionList il = new InstructionList();
int alen = getArgCount() ;
il.append(Utility.createConstant(fact, alen));
il.append((Instruction)fact.createNewArray(Type.OBJECT, (short)1));
arrayVar.appendStore(il, fact);
int stateIndex = 0;
for (int i = 0, len = getArgCount(); i<len; i++) {
arrayVar.appendConvertableArrayStore(il, fact, stateIndex, (BcelVar)getArgVar(i));
stateIndex++;
}
arrayVar.appendLoad(il, fact);
return il;
}
// ---- initializing var tables
/* initializing this is doesn't do anything, because this
* is protected from side-effects, so we don't need to copy its location
*/
private void initializeThisVar() {
if (thisVar != null) return;
thisVar = new BcelVar(getThisType().resolve(world), 0);
thisVar.setPositionInAroundState(0);
}
public void initializeTargetVar() {
InstructionFactory fact = getFactory();
if (targetVar != null) return;
if (getKind().isTargetSameAsThis()) {
if (hasThis()) initializeThisVar();
targetVar = thisVar;
} else {
initializeArgVars(); // gotta pop off the args before we find the target
UnresolvedType type = getTargetType();
type = ensureTargetTypeIsCorrect(type);
targetVar = genTempVar(type, "ajc$target");
range.insert(targetVar.createStore(fact), Range.OutsideBefore);
targetVar.setPositionInAroundState(hasThis() ? 1 : 0);
}
}
/* PR 72528
* This method double checks the target type under certain conditions. The Java 1.4
* compilers seem to take calls to clone methods on array types and create bytecode that
* looks like clone is being called on Object. If we advise a clone call with around
* advice we extract the call into a helper method which we can then refer to. Because the
* type in the bytecode for the call to clone is Object we create a helper method with
* an Object parameter - this is not correct as we have lost the fact that the actual
* type is an array type. If we don't do the check below we will create code that fails
* java verification. This method checks for the peculiar set of conditions and if they
* are true, it has a sneak peek at the code before the call to see what is on the stack.
*/
public UnresolvedType ensureTargetTypeIsCorrect(UnresolvedType tx) {
if (tx.equals(ResolvedType.OBJECT) && getKind() == MethodCall &&
getSignature().getReturnType().equals(ResolvedType.OBJECT) &&
getSignature().getArity()==0 &&
getSignature().getName().charAt(0) == 'c' &&
getSignature().getName().equals("clone")) {
// Lets go back through the code from the start of the shadow
InstructionHandle searchPtr = range.getStart().getPrev();
while (Range.isRangeHandle(searchPtr) ||
searchPtr.getInstruction() instanceof StoreInstruction) { // ignore this instruction - it doesnt give us the info we want
searchPtr = searchPtr.getPrev();
}
// A load instruction may tell us the real type of what the clone() call is on
if (searchPtr.getInstruction() instanceof LoadInstruction) {
LoadInstruction li = (LoadInstruction)searchPtr.getInstruction();
li.getIndex();
LocalVariableTag lvt = LazyMethodGen.getLocalVariableTag(searchPtr,li.getIndex());
return lvt.getType();
}
// A field access instruction may tell us the real type of what the clone() call is on
if (searchPtr.getInstruction() instanceof FieldInstruction) {
FieldInstruction si = (FieldInstruction)searchPtr.getInstruction();
Type t = si.getFieldType(getEnclosingClass().getConstantPoolGen());
return BcelWorld.fromBcel(t);
}
// A new array instruction obviously tells us it is an array type !
if (searchPtr.getInstruction() instanceof ANEWARRAY) {
//ANEWARRAY ana = (ANEWARRAY)searchPoint.getInstruction();
//Type t = ana.getType(getEnclosingClass().getConstantPoolGen());
// Just use a standard java.lang.object array - that will work fine
return BcelWorld.fromBcel(new ArrayType(Type.OBJECT,1));
}
// A multi new array instruction obviously tells us it is an array type !
if (searchPtr.getInstruction() instanceof MULTIANEWARRAY) {
MULTIANEWARRAY ana = (MULTIANEWARRAY)searchPtr.getInstruction();
// Type t = ana.getType(getEnclosingClass().getConstantPoolGen());
// t = new ArrayType(t,ana.getDimensions());
// Just use a standard java.lang.object array - that will work fine
return BcelWorld.fromBcel(new ArrayType(Type.OBJECT,ana.getDimensions()));
}
throw new BCException("Can't determine real target of clone() when processing instruction "+
searchPtr.getInstruction());
}
return tx;
}
public void initializeArgVars() {
if (argVars != null) return;
InstructionFactory fact = getFactory();
int len = getArgCount();
argVars = new BcelVar[len];
int positionOffset = (hasTarget() ? 1 : 0) +
((hasThis() && !getKind().isTargetSameAsThis()) ? 1 : 0);
if (getKind().argsOnStack()) {
// we move backwards because we're popping off the stack
for (int i = len - 1; i >= 0; i--) {
UnresolvedType type = getArgType(i);
BcelVar tmp = genTempVar(type, "ajc$arg" + i);
range.insert(tmp.createStore(getFactory()), Range.OutsideBefore);
int position = i;
position += positionOffset;
tmp.setPositionInAroundState(position);
argVars[i] = tmp;
}
} else {
int index = 0;
if (arg0HoldsThis()) index++;
for (int i = 0; i < len; i++) {
UnresolvedType type = getArgType(i);
BcelVar tmp = genTempVar(type, "ajc$arg" + i);
range.insert(tmp.createCopyFrom(fact, index), Range.OutsideBefore);
argVars[i] = tmp;
int position = i;
position += positionOffset;
// System.out.println("set position: " + tmp + ", " + position + " in " + this);
// System.out.println(" hasThis: " + hasThis() + ", hasTarget: " + hasTarget());
tmp.setPositionInAroundState(position);
index += type.getSize();
}
}
}
public void initializeForAroundClosure() {
initializeArgVars();
if (hasTarget()) initializeTargetVar();
if (hasThis()) initializeThisVar();
// System.out.println("initialized: " + this + " thisVar = " + thisVar);
}
public void initializeThisAnnotationVars() {
if (thisAnnotationVars != null) return;
thisAnnotationVars = new HashMap();
// populate..
}
public void initializeTargetAnnotationVars() {
if (targetAnnotationVars != null) return;
if (getKind().isTargetSameAsThis()) {
if (hasThis()) initializeThisAnnotationVars();
targetAnnotationVars = thisAnnotationVars;
} else {
targetAnnotationVars = new HashMap();
ResolvedType[] rtx = this.getTargetType().resolve(world).getAnnotationTypes(); // what about annotations we havent gotten yet but we will get in subclasses?
for (int i = 0; i < rtx.length; i++) {
ResolvedType typeX = rtx[i];
targetAnnotationVars.put(typeX,new TypeAnnotationAccessVar(typeX,(BcelVar)getTargetVar()));
}
// populate.
}
}
public void initializeArgAnnotationVars() {
if (argAnnotationVars != null) return;
int numArgs = getArgCount();
argAnnotationVars = new Map[numArgs];
for (int i = 0; i < argAnnotationVars.length; i++) {
argAnnotationVars[i] = new HashMap();
//FIXME asc just delete this logic - we always build the Var on demand, as we don't know at weave time
// what the full set of annotations could be (due to static/dynamic type differences...)
}
}
protected Member getRelevantMember(Member foundMember, Member relevantMember, ResolvedType relevantType){
if (foundMember != null){
return foundMember;
}
foundMember = getSignature().resolve(world);
if (foundMember == null && relevantMember != null) {
foundMember = relevantType.lookupMemberWithSupersAndITDs(relevantMember);
}
// check the ITD'd dooberries
List mungers = relevantType.resolve(world).getInterTypeMungers();
for (Iterator iter = mungers.iterator(); iter.hasNext();) {
BcelTypeMunger typeMunger = (BcelTypeMunger) iter.next();
if (typeMunger.getMunger() instanceof NewMethodTypeMunger ||
typeMunger.getMunger() instanceof NewConstructorTypeMunger) {
ResolvedMember fakerm = typeMunger.getSignature();
if (fakerm.getName().equals(getSignature().getName()) &&
fakerm.getParameterSignature().equals(getSignature().getParameterSignature())){
if (foundMember.getKind()==ResolvedMember.CONSTRUCTOR){
foundMember = AjcMemberMaker.interConstructor(
relevantType,
(ResolvedMember)foundMember,
typeMunger.getAspectType());
} else {
foundMember = AjcMemberMaker.interMethod((ResolvedMember)foundMember,
typeMunger.getAspectType(), false);
}
// in the above.. what about if it's on an Interface? Can that happen?
// then the last arg of the above should be true
return foundMember;
}
}
}
return foundMember;
}
protected ResolvedType [] getAnnotations(Member foundMember, Member relevantMember, ResolvedType relevantType){
if (foundMember == null){
// check the ITD'd dooberries
List mungers = relevantType.resolve(world).getInterTypeMungers();
for (Iterator iter = mungers.iterator(); iter.hasNext();) {
BcelTypeMunger typeMunger = (BcelTypeMunger) iter.next();
if (typeMunger.getMunger() instanceof NewMethodTypeMunger ||
typeMunger.getMunger() instanceof NewConstructorTypeMunger) {
ResolvedMember fakerm = typeMunger.getSignature();
//if (fakerm.hasAnnotations())
ResolvedMember ajcMethod = (getSignature().getKind()==ResolvedMember.CONSTRUCTOR?
AjcMemberMaker.postIntroducedConstructor(typeMunger.getAspectType(),fakerm.getDeclaringType(),fakerm.getParameterTypes()):
AjcMemberMaker.interMethodDispatcher(fakerm,typeMunger.getAspectType()));
//AjcMemberMaker.interMethodBody(fakerm,typeMunger.getAspectType()));
ResolvedMember rmm = findMethod(typeMunger.getAspectType(),ajcMethod);
if (fakerm.getName().equals(getSignature().getName()) &&
fakerm.getParameterSignature().equals(getSignature().getParameterSignature())) {
relevantType = typeMunger.getAspectType();
foundMember = rmm;
return foundMember.getAnnotationTypes();
}
}
}
// didn't find in ITDs, look in supers
foundMember = relevantType.lookupMemberWithSupersAndITDs(relevantMember);
if (foundMember == null) {
throw new IllegalStateException("Couldn't find member " + relevantMember + " for type " + relevantType);
}
}
return foundMember.getAnnotationTypes();
}
public void initializeKindedAnnotationVars() {
if (kindedAnnotationVars != null) return;
kindedAnnotationVars = new HashMap();
// by determining what "kind" of shadow we are, we can find out the
// annotations on the appropriate element (method, field, constructor, type).
// Then create one BcelVar entry in the map for each annotation, keyed by
// annotation type (UnresolvedType).
// FIXME asc Refactor this code, there is duplication
ResolvedType[] annotations = null;
Member relevantMember = getSignature();
ResolvedType relevantType = relevantMember.getDeclaringType().resolve(world);
if (getKind() == Shadow.StaticInitialization) {
annotations = relevantType.resolve(world).getAnnotationTypes();
} else if (getKind() == Shadow.MethodCall || getKind() == Shadow.ConstructorCall) {
Member foundMember = findMethod2(relevantType.resolve(world).getDeclaredMethods(),getSignature());
annotations = getAnnotations(foundMember, relevantMember, relevantType);
relevantMember = getRelevantMember(foundMember,relevantMember,relevantType);
relevantType = relevantMember.getDeclaringType().resolve(world);
} else if (getKind() == Shadow.FieldSet || getKind() == Shadow.FieldGet) {
relevantMember = findField(relevantType.getDeclaredFields(),getSignature());
if (relevantMember==null) {
// check the ITD'd dooberries
List mungers = relevantType.resolve(world).getInterTypeMungers();
for (Iterator iter = mungers.iterator(); iter.hasNext();) {
BcelTypeMunger typeMunger = (BcelTypeMunger) iter.next();
if (typeMunger.getMunger() instanceof NewFieldTypeMunger) {
ResolvedMember fakerm = typeMunger.getSignature();
//if (fakerm.hasAnnotations())
ResolvedMember ajcMethod = AjcMemberMaker.interFieldInitializer(fakerm,typeMunger.getAspectType());
ResolvedMember rmm = findMethod(typeMunger.getAspectType(),ajcMethod);
if (fakerm.equals(getSignature())) {
relevantType = typeMunger.getAspectType();
relevantMember = rmm;
}
}
}
}
annotations = relevantMember.getAnnotationTypes();
} else if (getKind() == Shadow.MethodExecution || getKind() == Shadow.ConstructorExecution ||
getKind() == Shadow.AdviceExecution) {
//ResolvedMember rm[] = relevantType.getDeclaredMethods();
Member foundMember = findMethod2(relevantType.getDeclaredMethods(),getSignature());
annotations = getAnnotations(foundMember, relevantMember,relevantType);
relevantMember = foundMember;
relevantMember = getRelevantMember(foundMember, relevantMember,relevantType);
} else if (getKind() == Shadow.ExceptionHandler) {
relevantType = getSignature().getParameterTypes()[0].resolve(world);
annotations = relevantType.getAnnotationTypes();
} else if (getKind() == Shadow.PreInitialization || getKind() == Shadow.Initialization) {
ResolvedMember found = findMethod2(relevantType.getDeclaredMethods(),getSignature());
annotations = found.getAnnotationTypes();
}
if (annotations == null) {
// We can't have recognized the shadow - should blow up now to be on the safe side
throw new BCException("Couldn't discover annotations for shadow: "+getKind());
}
for (int i = 0; i < annotations.length; i++) {
ResolvedType aTX = annotations[i];
KindedAnnotationAccessVar kaav = new KindedAnnotationAccessVar(getKind(),aTX.resolve(world),relevantType,relevantMember);
kindedAnnotationVars.put(aTX,kaav);
}
}
//FIXME asc whats the real diff between this one and the version in findMethod()?
ResolvedMember findMethod2(ResolvedMember rm[], Member sig) {
ResolvedMember found = null;
// String searchString = getSignature().getName()+getSignature().getParameterSignature();
for (int i = 0; i < rm.length && found==null; i++) {
ResolvedMember member = rm[i];
if (member.getName().equals(sig.getName()) && member.getParameterSignature().equals(sig.getParameterSignature()))
found = member;
}
return found;
}
private ResolvedMember findMethod(ResolvedType aspectType, ResolvedMember ajcMethod) {
ResolvedMember decMethods[] = aspectType.getDeclaredMethods();
for (int i = 0; i < decMethods.length; i++) {
ResolvedMember member = decMethods[i];
if (member.equals(ajcMethod)) return member;
}
return null;
}
private ResolvedMember findField(ResolvedMember[] members,Member lookingFor) {
for (int i = 0; i < members.length; i++) {
ResolvedMember member = members[i];
if ( member.getName().equals(getSignature().getName()) &&
member.getType().equals(getSignature().getType())) {
return member;
}
}
return null;
}
public void initializeWithinAnnotationVars() {
if (withinAnnotationVars != null) return;
withinAnnotationVars = new HashMap();
ResolvedType[] annotations = getEnclosingType().resolve(world).getAnnotationTypes();
for (int i = 0; i < annotations.length; i++) {
ResolvedType ann = annotations[i];
Kind k = Shadow.StaticInitialization;
withinAnnotationVars.put(ann,new KindedAnnotationAccessVar(k,ann,getEnclosingType(),null));
}
}
public void initializeWithinCodeAnnotationVars() {
if (withincodeAnnotationVars != null) return;
withincodeAnnotationVars = new HashMap();
// For some shadow we are interested in annotations on the method containing that shadow.
ResolvedType[] annotations = getEnclosingMethod().getMemberView().getAnnotationTypes();
for (int i = 0; i < annotations.length; i++) {
ResolvedType ann = annotations[i];
Kind k = (getEnclosingMethod().getMemberView().getKind()==Member.CONSTRUCTOR?
Shadow.ConstructorExecution:Shadow.MethodExecution);
withincodeAnnotationVars.put(ann,
new KindedAnnotationAccessVar(k,ann,getEnclosingType(),getEnclosingCodeSignature()));
}
}
// ---- weave methods
void weaveBefore(BcelAdvice munger) {
range.insert(
munger.getAdviceInstructions(this, null, range.getRealStart()),
Range.InsideBefore);
}
public void weaveAfter(BcelAdvice munger) {
weaveAfterThrowing(munger, UnresolvedType.THROWABLE);
weaveAfterReturning(munger);
}
/**
* We guarantee that the return value is on the top of the stack when
* munger.getAdviceInstructions() will be run
* (Unless we have a void return type in which case there's nothing)
*/
public void weaveAfterReturning(BcelAdvice munger) {
// InstructionFactory fact = getFactory();
List returns = new ArrayList();
Instruction ret = null;
for (InstructionHandle ih = range.getStart(); ih != range.getEnd(); ih = ih.getNext()) {
if (ih.getInstruction() instanceof ReturnInstruction) {
returns.add(ih);
ret = Utility.copyInstruction(ih.getInstruction());
}
}
InstructionList retList;
InstructionHandle afterAdvice;
if (ret != null) {
retList = new InstructionList(ret);
afterAdvice = retList.getStart();
} else /* if (munger.hasDynamicTests()) */ {
/*
*
27: getstatic #72; //Field ajc$cflowCounter$0:Lorg/aspectj/runtime/internal/CFlowCounter;
30: invokevirtual #87; //Method org/aspectj/runtime/internal/CFlowCounter.dec:()V
33: aload 6
35: athrow
36: nop
37: getstatic #72; //Field ajc$cflowCounter$0:Lorg/aspectj/runtime/internal/CFlowCounter;
40: invokevirtual #87; //Method org/aspectj/runtime/internal/CFlowCounter.dec:()V
43: d2i
44: invokespecial #23; //Method java/lang/Object."<init>":()V
*/
retList = new InstructionList(InstructionConstants.NOP);
afterAdvice = retList.getStart();
// } else {
// retList = new InstructionList();
// afterAdvice = null;
}
InstructionList advice = new InstructionList();
BcelVar tempVar = null;
if (munger.hasExtraParameter()) {
UnresolvedType tempVarType = getReturnType();
if (tempVarType.equals(ResolvedType.VOID)) {
tempVar = genTempVar(UnresolvedType.OBJECT);
advice.append(InstructionConstants.ACONST_NULL);
tempVar.appendStore(advice, getFactory());
} else {
tempVar = genTempVar(tempVarType);
advice.append(InstructionFactory.createDup(tempVarType.getSize()));
tempVar.appendStore(advice, getFactory());
}
}
advice.append(munger.getAdviceInstructions(this, tempVar, afterAdvice));
if (ret != null) {
InstructionHandle gotoTarget = advice.getStart();
for (Iterator i = returns.iterator(); i.hasNext();) {
InstructionHandle ih = (InstructionHandle) i.next();
Utility.replaceInstruction(
ih,
InstructionFactory.createBranchInstruction(
Constants.GOTO,
gotoTarget),
enclosingMethod);
}
range.append(advice);
range.append(retList);
} else {
range.append(advice);
range.append(retList);
}
}
public void weaveAfterThrowing(BcelAdvice munger, UnresolvedType catchType) {
// a good optimization would be not to generate anything here
// if the shadow is GUARANTEED empty (i.e., there's NOTHING, not even
// a shadow, inside me).
if (getRange().getStart().getNext() == getRange().getEnd()) return;
InstructionFactory fact = getFactory();
InstructionList handler = new InstructionList();
BcelVar exceptionVar = genTempVar(catchType);
exceptionVar.appendStore(handler, fact);
// pr62642
// I will now jump through some firey BCEL hoops to generate a trivial bit of code:
// if (exc instanceof ExceptionInInitializerError)
// throw (ExceptionInInitializerError)exc;
if (this.getEnclosingMethod().getName().equals("<clinit>")) {
ResolvedType eiieType = world.resolve("java.lang.ExceptionInInitializerError");
ObjectType eiieBcelType = (ObjectType)BcelWorld.makeBcelType(eiieType);
InstructionList ih = new InstructionList(InstructionConstants.NOP);
handler.append(exceptionVar.createLoad(fact));
handler.append(fact.createInstanceOf(eiieBcelType));
BranchInstruction bi =
InstructionFactory.createBranchInstruction(Constants.IFEQ,ih.getStart());
handler.append(bi);
handler.append(exceptionVar.createLoad(fact));
handler.append(fact.createCheckCast(eiieBcelType));
handler.append(InstructionConstants.ATHROW);
handler.append(ih);
}
InstructionList endHandler = new InstructionList(
exceptionVar.createLoad(fact));
handler.append(munger.getAdviceInstructions(this, exceptionVar, endHandler.getStart()));
handler.append(endHandler);
handler.append(InstructionConstants.ATHROW);
InstructionHandle handlerStart = handler.getStart();
if (isFallsThrough()) {
InstructionHandle jumpTarget = handler.append(InstructionConstants.NOP);
handler.insert(InstructionFactory.createBranchInstruction(Constants.GOTO, jumpTarget));
}
InstructionHandle protectedEnd = handler.getStart();
range.insert(handler, Range.InsideAfter);
enclosingMethod.addExceptionHandler(range.getStart().getNext(), protectedEnd.getPrev(),
handlerStart, (ObjectType)BcelWorld.makeBcelType(catchType), //???Type.THROWABLE,
// high priority if our args are on the stack
getKind().hasHighPriorityExceptions());
}
//??? this shares a lot of code with the above weaveAfterThrowing
//??? would be nice to abstract that to say things only once
public void weaveSoftener(BcelAdvice munger, UnresolvedType catchType) {
// a good optimization would be not to generate anything here
// if the shadow is GUARANTEED empty (i.e., there's NOTHING, not even
// a shadow, inside me).
if (getRange().getStart().getNext() == getRange().getEnd()) return;
InstructionFactory fact = getFactory();
InstructionList handler = new InstructionList();
InstructionList rtExHandler = new InstructionList();
BcelVar exceptionVar = genTempVar(catchType);
handler.append(fact.createNew(NameMangler.SOFT_EXCEPTION_TYPE));
handler.append(InstructionFactory.createDup(1));
handler.append(exceptionVar.createLoad(fact));
handler.append(fact.createInvoke(NameMangler.SOFT_EXCEPTION_TYPE, "<init>",
Type.VOID, new Type[] { Type.THROWABLE }, Constants.INVOKESPECIAL)); //??? special
handler.append(InstructionConstants.ATHROW);
// ENH 42737
exceptionVar.appendStore(rtExHandler, fact);
// aload_1
rtExHandler.append(exceptionVar.createLoad(fact));
// instanceof class java/lang/RuntimeException
rtExHandler.append(fact.createInstanceOf(new ObjectType("java.lang.RuntimeException")));
// ifeq go to new SOFT_EXCEPTION_TYPE instruction
rtExHandler.append(InstructionFactory.createBranchInstruction(Constants.IFEQ,handler.getStart()));
// aload_1
rtExHandler.append(exceptionVar.createLoad(fact));
// athrow
rtExHandler.append(InstructionFactory.ATHROW);
InstructionHandle handlerStart = rtExHandler.getStart();
if (isFallsThrough()) {
InstructionHandle jumpTarget = range.getEnd();//handler.append(fact.NOP);
rtExHandler.insert(InstructionFactory.createBranchInstruction(Constants.GOTO, jumpTarget));
}
rtExHandler.append(handler);
InstructionHandle protectedEnd = rtExHandler.getStart();
range.insert(rtExHandler, Range.InsideAfter);
enclosingMethod.addExceptionHandler(range.getStart().getNext(), protectedEnd.getPrev(),
handlerStart, (ObjectType)BcelWorld.makeBcelType(catchType),
// high priority if our args are on the stack
getKind().hasHighPriorityExceptions());
}
public void weavePerObjectEntry(final BcelAdvice munger, final BcelVar onVar) {
final InstructionFactory fact = getFactory();
InstructionList entryInstructions = new InstructionList();
InstructionList entrySuccessInstructions = new InstructionList();
onVar.appendLoad(entrySuccessInstructions, fact);
entrySuccessInstructions.append(
Utility.createInvoke(fact, world,
AjcMemberMaker.perObjectBind(munger.getConcreteAspect())));
InstructionList testInstructions =
munger.getTestInstructions(this, entrySuccessInstructions.getStart(),
range.getRealStart(),
entrySuccessInstructions.getStart());
entryInstructions.append(testInstructions);
entryInstructions.append(entrySuccessInstructions);
range.insert(entryInstructions, Range.InsideBefore);
}
// PTWIMPL Create static initializer to call the aspect factory
/**
* Causes the aspect instance to be *set* for later retrievable through localAspectof()/aspectOf()
*/
public void weavePerTypeWithinAspectInitialization(final BcelAdvice munger,UnresolvedType t) {
if (t.resolve(world).isInterface()) return; // Don't initialize statics in
final InstructionFactory fact = getFactory();
InstructionList entryInstructions = new InstructionList();
InstructionList entrySuccessInstructions = new InstructionList();
BcelWorld.getBcelObjectType(munger.getConcreteAspect());
String aspectname = munger.getConcreteAspect().getName();
String ptwField = NameMangler.perTypeWithinFieldForTarget(munger.getConcreteAspect());
entrySuccessInstructions.append(new PUSH(fact.getConstantPool(),t.getName()));
entrySuccessInstructions.append(fact.createInvoke(aspectname,"ajc$createAspectInstance",new ObjectType(aspectname),
new Type[]{new ObjectType("java.lang.String")},Constants.INVOKESTATIC));
entrySuccessInstructions.append(fact.createPutStatic(t.getName(),ptwField,
new ObjectType(aspectname)));
entryInstructions.append(entrySuccessInstructions);
range.insert(entryInstructions, Range.InsideBefore);
}
public void weaveCflowEntry(final BcelAdvice munger, final Member cflowField) {
final boolean isPer = munger.getKind() == AdviceKind.PerCflowBelowEntry ||
munger.getKind() == AdviceKind.PerCflowEntry;
final Type objectArrayType = new ArrayType(Type.OBJECT, 1);
final InstructionFactory fact = getFactory();
final BcelVar testResult = genTempVar(ResolvedType.BOOLEAN);
InstructionList entryInstructions = new InstructionList();
{
InstructionList entrySuccessInstructions = new InstructionList();
if (munger.hasDynamicTests()) {
entryInstructions.append(Utility.createConstant(fact, 0));
testResult.appendStore(entryInstructions, fact);
entrySuccessInstructions.append(Utility.createConstant(fact, 1));
testResult.appendStore(entrySuccessInstructions, fact);
}
if (isPer) {
entrySuccessInstructions.append(
fact.createInvoke(munger.getConcreteAspect().getName(),
NameMangler.PERCFLOW_PUSH_METHOD,
Type.VOID,
new Type[] { },
Constants.INVOKESTATIC));
} else {
BcelVar[] cflowStateVars = munger.getExposedStateAsBcelVars(false);
if (cflowStateVars.length == 0) {
// This should be getting managed by a counter - lets make sure.
if (!cflowField.getType().getName().endsWith("CFlowCounter"))
throw new RuntimeException("Incorrectly attempting counter operation on stacked cflow");
entrySuccessInstructions.append(
Utility.createGet(fact, cflowField));
//arrayVar.appendLoad(entrySuccessInstructions, fact);
entrySuccessInstructions.append(fact.createInvoke(NameMangler.CFLOW_COUNTER_TYPE,"inc",Type.VOID,new Type[] { },Constants.INVOKEVIRTUAL));
} else {
BcelVar arrayVar = genTempVar(UnresolvedType.OBJECTARRAY);
int alen = cflowStateVars.length;
entrySuccessInstructions.append(Utility.createConstant(fact, alen));
entrySuccessInstructions.append(
(Instruction) fact.createNewArray(Type.OBJECT, (short) 1));
arrayVar.appendStore(entrySuccessInstructions, fact);
for (int i = 0; i < alen; i++) {
arrayVar.appendConvertableArrayStore(
entrySuccessInstructions,
fact,
i,
cflowStateVars[i]);
}
entrySuccessInstructions.append(
Utility.createGet(fact, cflowField));
arrayVar.appendLoad(entrySuccessInstructions, fact);
entrySuccessInstructions.append(
fact.createInvoke(NameMangler.CFLOW_STACK_TYPE, "push", Type.VOID,
new Type[] { objectArrayType },
Constants.INVOKEVIRTUAL));
}
}
InstructionList testInstructions =
munger.getTestInstructions(this, entrySuccessInstructions.getStart(),
range.getRealStart(),
entrySuccessInstructions.getStart());
entryInstructions.append(testInstructions);
entryInstructions.append(entrySuccessInstructions);
}
// this is the same for both per and non-per
weaveAfter(new BcelAdvice(null, null, null, 0, 0, 0, null, null) {
public InstructionList getAdviceInstructions(
BcelShadow s,
BcelVar extraArgVar,
InstructionHandle ifNoAdvice) {
InstructionList exitInstructions = new InstructionList();
if (munger.hasDynamicTests()) {
testResult.appendLoad(exitInstructions, fact);
exitInstructions.append(
InstructionFactory.createBranchInstruction(
Constants.IFEQ,
ifNoAdvice));
}
exitInstructions.append(Utility.createGet(fact, cflowField));
if (munger.getKind() != AdviceKind.PerCflowEntry &&
munger.getKind() != AdviceKind.PerCflowBelowEntry &&
munger.getExposedStateAsBcelVars(false).length==0) {
exitInstructions
.append(
fact
.createInvoke(
NameMangler.CFLOW_COUNTER_TYPE,
"dec",
Type.VOID,
new Type[] {
}, Constants.INVOKEVIRTUAL));
} else {
exitInstructions
.append(
fact
.createInvoke(
NameMangler.CFLOW_STACK_TYPE,
"pop",
Type.VOID,
new Type[] {
}, Constants.INVOKEVIRTUAL));
}
return exitInstructions;
}
});
range.insert(entryInstructions, Range.InsideBefore);
}
public void weaveAroundInline(
BcelAdvice munger,
boolean hasDynamicTest)
{
/* Implementation notes:
*
* AroundInline still extracts the instructions of the original shadow into
* an extracted method. This allows inlining of even that advice that doesn't
* call proceed or calls proceed more than once.
*
* It extracts the instructions of the original shadow into a method.
*
* Then it extracts the instructions of the advice into a new method defined on
* this enclosing class. This new method can then be specialized as below.
*
* Then it searches in the instructions of the advice for any call to the
* proceed method.
*
* At such a call, there is stuff on the stack representing the arguments to
* proceed. Pop these into the frame.
*
* Now build the stack for the call to the extracted method, taking values
* either from the join point state or from the new frame locs from proceed.
* Now call the extracted method. The right return value should be on the
* stack, so no cast is necessary.
*
* If only one call to proceed is made, we can re-inline the original shadow.
* We are not doing that presently.
*
* If the body of the advice can be determined to not alter the stack, or if
* this shadow doesn't care about the stack, i.e. method-execution, then the
* new method for the advice can also be re-lined. We are not doing that
* presently.
*/
// !!! THIS BLOCK OF CODE SHOULD BE IN A METHOD CALLED weaveAround(...);
Member mungerSig = munger.getSignature();
//Member originalSig = mungerSig; // If mungerSig is on a parameterized type, originalSig is the member on the generic type
if (mungerSig instanceof ResolvedMember) {
ResolvedMember rm = (ResolvedMember)mungerSig;
if (rm.hasBackingGenericMember()) mungerSig = rm.getBackingGenericMember();
}
ResolvedType declaringType = world.resolve(mungerSig.getDeclaringType(),true);
if (declaringType.isMissing()) {
world.getLint().cantFindType.signal(
new String[] {WeaverMessages.format(WeaverMessages.CANT_FIND_TYPE_DURING_AROUND_WEAVE,declaringType.getClassName())},
getSourceLocation(),
new ISourceLocation[]{ munger.getSourceLocation()}
);
// IMessage msg = new Message(
// WeaverMessages.format(WeaverMessages.CANT_FIND_TYPE_DURING_AROUND_WEAVE,declaringType.getClassName()),
// "",IMessage.ERROR,getSourceLocation(),null,
// new ISourceLocation[]{ munger.getSourceLocation()});
// world.getMessageHandler().handleMessage(msg);
}
//??? might want some checks here to give better errors
BcelObjectType ot = BcelWorld.getBcelObjectType((declaringType.isParameterizedType()?declaringType.getGenericType():declaringType));
LazyMethodGen adviceMethod = ot.getLazyClassGen().getLazyMethodGen(mungerSig);
if (!adviceMethod.getCanInline()) {
weaveAroundClosure(munger, hasDynamicTest);
return;
}
// specific test for @AJ proceedInInners
if (munger.getConcreteAspect().isAnnotationStyleAspect()) {
// if we can't find one proceed()
// we suspect that the call is happening in an inner class
// so we don't inline it.
// Note: for code style, this is done at Aspect compilation time.
boolean canSeeProceedPassedToOther = false;
InstructionHandle curr = adviceMethod.getBody().getStart();
InstructionHandle end = adviceMethod.getBody().getEnd();
ConstantPoolGen cpg = adviceMethod.getEnclosingClass().getConstantPoolGen();
while (curr != end) {
InstructionHandle next = curr.getNext();
Instruction inst = curr.getInstruction();
if ((inst instanceof InvokeInstruction)
&& ((InvokeInstruction)inst).getSignature(cpg).indexOf("Lorg/aspectj/lang/ProceedingJoinPoint;") > 0) {
// we may want to refine to exclude stuff returning jp ?
// does code style skip inline if i write dump(thisJoinPoint) ?
canSeeProceedPassedToOther = true;// we see one pjp passed around - dangerous
break;
}
curr = next;
}
if (canSeeProceedPassedToOther) {
// remember this decision to avoid re-analysis
adviceMethod.setCanInline(false);
weaveAroundClosure(munger, hasDynamicTest);
return;
}
}
// We can't inline around methods if they have around advice on them, this
// is because the weaving will extract the body and hence the proceed call.
//??? should consider optimizations to recognize simple cases that don't require body extraction
enclosingMethod.setCanInline(false);
// start by exposing various useful things into the frame
final InstructionFactory fact = getFactory();
// now generate the aroundBody method
LazyMethodGen extractedMethod =
extractMethod(
NameMangler.aroundCallbackMethodName(
getSignature(),
getEnclosingClass()),
Modifier.PRIVATE,
munger
);
// now extract the advice into its own method
String adviceMethodName =
NameMangler.aroundCallbackMethodName(
getSignature(),
getEnclosingClass()) + "$advice";
List argVarList = new ArrayList();
List proceedVarList = new ArrayList();
int extraParamOffset = 0;
// Create the extra parameters that are needed for passing to proceed
// This code is very similar to that found in makeCallToCallback and should
// be rationalized in the future
if (thisVar != null) {
argVarList.add(thisVar);
proceedVarList.add(new BcelVar(thisVar.getType(), extraParamOffset));
extraParamOffset += thisVar.getType().getSize();
}
if (targetVar != null && targetVar != thisVar) {
argVarList.add(targetVar);
proceedVarList.add(new BcelVar(targetVar.getType(), extraParamOffset));
extraParamOffset += targetVar.getType().getSize();
}
for (int i = 0, len = getArgCount(); i < len; i++) {
argVarList.add(argVars[i]);
proceedVarList.add(new BcelVar(argVars[i].getType(), extraParamOffset));
extraParamOffset += argVars[i].getType().getSize();
}
if (thisJoinPointVar != null) {
argVarList.add(thisJoinPointVar);
proceedVarList.add(new BcelVar(thisJoinPointVar.getType(), extraParamOffset));
extraParamOffset += thisJoinPointVar.getType().getSize();
}
Type[] adviceParameterTypes = adviceMethod.getArgumentTypes();
Type[] extractedMethodParameterTypes = extractedMethod.getArgumentTypes();
Type[] parameterTypes =
new Type[extractedMethodParameterTypes.length
+ adviceParameterTypes.length
+ 1];
int parameterIndex = 0;
System.arraycopy(
extractedMethodParameterTypes,
0,
parameterTypes,
parameterIndex,
extractedMethodParameterTypes.length);
parameterIndex += extractedMethodParameterTypes.length;
parameterTypes[parameterIndex++] =
BcelWorld.makeBcelType(adviceMethod.getEnclosingClass().getType());
System.arraycopy(
adviceParameterTypes,
0,
parameterTypes,
parameterIndex,
adviceParameterTypes.length);
LazyMethodGen localAdviceMethod =
new LazyMethodGen(
Modifier.PRIVATE | Modifier.FINAL | Modifier.STATIC,
BcelWorld.makeBcelType(mungerSig.getReturnType()),
adviceMethodName,
parameterTypes,
new String[0],
getEnclosingClass());
String donorFileName = adviceMethod.getEnclosingClass().getInternalFileName();
String recipientFileName = getEnclosingClass().getInternalFileName();
// System.err.println("donor " + donorFileName);
// System.err.println("recip " + recipientFileName);
if (! donorFileName.equals(recipientFileName)) {
localAdviceMethod.fromFilename = donorFileName;
getEnclosingClass().addInlinedSourceFileInfo(
donorFileName,
adviceMethod.highestLineNumber);
}
getEnclosingClass().addMethodGen(localAdviceMethod);
// create a map that will move all slots in advice method forward by extraParamOffset
// in order to make room for the new proceed-required arguments that are added at
// the beginning of the parameter list
int nVars = adviceMethod.getMaxLocals() + extraParamOffset;
IntMap varMap = IntMap.idMap(nVars);
for (int i=extraParamOffset; i < nVars; i++) {
varMap.put(i-extraParamOffset, i);
}
localAdviceMethod.getBody().insert(
BcelClassWeaver.genInlineInstructions(adviceMethod,
localAdviceMethod, varMap, fact, true));
localAdviceMethod.setMaxLocals(nVars);
//System.err.println(localAdviceMethod);
// the shadow is now empty. First, create a correct call
// to the around advice. This includes both the call (which may involve
// value conversion of the advice arguments) and the return
// (which may involve value conversion of the return value). Right now
// we push a null for the unused closure. It's sad, but there it is.
InstructionList advice = new InstructionList();
// InstructionHandle adviceMethodInvocation;
{
for (Iterator i = argVarList.iterator(); i.hasNext(); ) {
BcelVar var = (BcelVar)i.next();
var.appendLoad(advice, fact);
}
// ??? we don't actually need to push NULL for the closure if we take care
advice.append(
munger.getAdviceArgSetup(
this,
null,
(munger.getConcreteAspect().isAnnotationStyleAspect())?
this.loadThisJoinPoint():
new InstructionList(InstructionConstants.ACONST_NULL)));
// adviceMethodInvocation =
advice.append(
Utility.createInvoke(fact, localAdviceMethod)); //(fact, getWorld(), munger.getSignature()));
advice.append(
Utility.createConversion(
getFactory(),
BcelWorld.makeBcelType(mungerSig.getReturnType()),
extractedMethod.getReturnType(),world.isInJava5Mode()));
if (! isFallsThrough()) {
advice.append(InstructionFactory.createReturn(extractedMethod.getReturnType()));
}
}
// now, situate the call inside the possible dynamic tests,
// and actually add the whole mess to the shadow
if (! hasDynamicTest) {
range.append(advice);
} else {
InstructionList afterThingie = new InstructionList(InstructionConstants.NOP);
InstructionList callback = makeCallToCallback(extractedMethod);
if (terminatesWithReturn()) {
callback.append(
InstructionFactory.createReturn(extractedMethod.getReturnType()));
} else {
//InstructionHandle endNop = range.insert(fact.NOP, Range.InsideAfter);
advice.append(
InstructionFactory.createBranchInstruction(
Constants.GOTO,
afterThingie.getStart()));
}
range.append(
munger.getTestInstructions(
this,
advice.getStart(),
callback.getStart(),
advice.getStart()));
range.append(advice);
range.append(callback);
range.append(afterThingie);
}
// now search through the advice, looking for a call to PROCEED.
// Then we replace the call to proceed with some argument setup, and a
// call to the extracted method.
// inlining support for code style aspects
if (!munger.getConcreteAspect().isAnnotationStyleAspect()) {
String proceedName =
NameMangler.proceedMethodName(munger.getSignature().getName());
InstructionHandle curr = localAdviceMethod.getBody().getStart();
InstructionHandle end = localAdviceMethod.getBody().getEnd();
ConstantPoolGen cpg = localAdviceMethod.getEnclosingClass().getConstantPoolGen();
while (curr != end) {
InstructionHandle next = curr.getNext();
Instruction inst = curr.getInstruction();
if ((inst instanceof INVOKESTATIC)
&& proceedName.equals(((INVOKESTATIC) inst).getMethodName(cpg))) {
localAdviceMethod.getBody().append(
curr,
getRedoneProceedCall(
fact,
extractedMethod,
munger,
localAdviceMethod,
proceedVarList));
Utility.deleteInstruction(curr, localAdviceMethod);
}
curr = next;
}
// and that's it.
} else {
//ATAJ inlining support for @AJ aspects
// [TODO document @AJ code rule: don't manipulate 2 jps proceed at the same time.. in an advice body]
InstructionHandle curr = localAdviceMethod.getBody().getStart();
InstructionHandle end = localAdviceMethod.getBody().getEnd();
ConstantPoolGen cpg = localAdviceMethod.getEnclosingClass().getConstantPoolGen();
while (curr != end) {
InstructionHandle next = curr.getNext();
Instruction inst = curr.getInstruction();
if ((inst instanceof INVOKEINTERFACE)
&& "proceed".equals(((INVOKEINTERFACE) inst).getMethodName(cpg))) {
final boolean isProceedWithArgs;
if (((INVOKEINTERFACE) inst).getArgumentTypes(cpg).length == 1) {
// proceed with args as a boxed Object[]
isProceedWithArgs = true;
} else {
isProceedWithArgs = false;
}
InstructionList insteadProceedIl = getRedoneProceedCallForAnnotationStyle(
fact,
extractedMethod,
munger,
localAdviceMethod,
proceedVarList,
isProceedWithArgs
);
localAdviceMethod.getBody().append(curr, insteadProceedIl);
Utility.deleteInstruction(curr, localAdviceMethod);
}
curr = next;
}
}
}
private InstructionList getRedoneProceedCall(
InstructionFactory fact,
LazyMethodGen callbackMethod,
BcelAdvice munger,
LazyMethodGen localAdviceMethod,
List argVarList)
{
InstructionList ret = new InstructionList();
// we have on stack all the arguments for the ADVICE call.
// we have in frame somewhere all the arguments for the non-advice call.
BcelVar[] adviceVars = munger.getExposedStateAsBcelVars(true);
IntMap proceedMap = makeProceedArgumentMap(adviceVars);
// System.out.println(proceedMap + " for " + this);
// System.out.println(argVarList);
ResolvedType[] proceedParamTypes =
world.resolve(munger.getSignature().getParameterTypes());
// remove this*JoinPoint* as arguments to proceed
if (munger.getBaseParameterCount()+1 < proceedParamTypes.length) {
int len = munger.getBaseParameterCount()+1;
ResolvedType[] newTypes = new ResolvedType[len];
System.arraycopy(proceedParamTypes, 0, newTypes, 0, len);
proceedParamTypes = newTypes;
}
//System.out.println("stateTypes: " + Arrays.asList(stateTypes));
BcelVar[] proceedVars =
Utility.pushAndReturnArrayOfVars(proceedParamTypes, ret, fact, localAdviceMethod);
Type[] stateTypes = callbackMethod.getArgumentTypes();
// System.out.println("stateTypes: " + Arrays.asList(stateTypes));
for (int i=0, len=stateTypes.length; i < len; i++) {
Type stateType = stateTypes[i];
ResolvedType stateTypeX = BcelWorld.fromBcel(stateType).resolve(world);
if (proceedMap.hasKey(i)) {
//throw new RuntimeException("unimplemented");
proceedVars[proceedMap.get(i)].appendLoadAndConvert(ret, fact, stateTypeX);
} else {
((BcelVar) argVarList.get(i)).appendLoad(ret, fact);
}
}
ret.append(Utility.createInvoke(fact, callbackMethod));
ret.append(Utility.createConversion(fact, callbackMethod.getReturnType(),
BcelWorld.makeBcelType(munger.getSignature().getReturnType())));
return ret;
}
/**
* ATAJ Handle the inlining for @AJ aspects
*
* @param fact
* @param callbackMethod
* @param munger
* @param localAdviceMethod
* @param argVarList
* @param isProceedWithArgs
* @return
*/
private InstructionList getRedoneProceedCallForAnnotationStyle(
InstructionFactory fact,
LazyMethodGen callbackMethod,
BcelAdvice munger,
LazyMethodGen localAdviceMethod,
List argVarList,
boolean isProceedWithArgs)
{
// Notes:
// proceedingjp is on stack (since user was calling pjp.proceed(...)
// the boxed args to proceed() are on stack as well (Object[]) unless
// the call is to pjp.proceed(<noarg>)
// new Object[]{new Integer(argAdvice1-1)};// arg of proceed
// call to proceed(..) is NOT made
// instead we do
// itar callback args i
// get from array i, convert it to the callback arg i
// if ask for JP, push the one we got on the stack
// invoke callback, create conversion back to Object/Integer
// rest of method -- (hence all those conversions)
// intValue() from original code
// int res = .. from original code
//Note: we just don't care about the proceed map etc
InstructionList ret = new InstructionList();
// store the Object[] array on stack if proceed with args
if (isProceedWithArgs) {
Type objectArrayType = Type.getType("[Ljava/lang/Object;");
int localProceedArgArray = localAdviceMethod.allocateLocal(objectArrayType);
ret.append(InstructionFactory.createStore(objectArrayType, localProceedArgArray));
Type proceedingJpType = Type.getType("Lorg/aspectj/lang/ProceedingJoinPoint;");
int localJp = localAdviceMethod.allocateLocal(proceedingJpType);
ret.append(InstructionFactory.createStore(proceedingJpType, localJp));
// push on stack each element of the object array
// that is assumed to be consistent with the callback argument (ie munger args)
// TODO do we want to try catch ClassCast and AOOBE exception ?
// special logic when withincode is static or not
int startIndex = 0;
if (thisVar != null) {
startIndex = 1;
//TODO this logic is actually depending on target as well - test me
ret.append(new ALOAD(0));//thisVar
}
for (int i = startIndex, len=callbackMethod.getArgumentTypes().length; i < len; i++) {
Type stateType = callbackMethod.getArgumentTypes()[i];
BcelWorld.fromBcel(stateType).resolve(world);
if ("Lorg/aspectj/lang/JoinPoint;".equals(stateType.getSignature())) {
ret.append(new ALOAD(localJp));// from localAdvice signature
} else {
ret.append(InstructionFactory.createLoad(objectArrayType, localProceedArgArray));
ret.append(Utility.createConstant(fact, i-startIndex));
ret.append(InstructionFactory.createArrayLoad(Type.OBJECT));
ret.append(Utility.createConversion(
fact,
Type.OBJECT,
stateType
));
}
}
} else {
Type proceedingJpType = Type.getType("Lorg/aspectj/lang/ProceedingJoinPoint;");
int localJp = localAdviceMethod.allocateLocal(proceedingJpType);
ret.append(InstructionFactory.createStore(proceedingJpType, localJp));
for (int i = 0, len=callbackMethod.getArgumentTypes().length; i < len; i++) {
Type stateType = callbackMethod.getArgumentTypes()[i];
/*ResolvedType stateTypeX =*/
BcelWorld.fromBcel(stateType).resolve(world);
if ("Lorg/aspectj/lang/JoinPoint;".equals(stateType.getSignature())) {
ret.append(new ALOAD(localJp));// from localAdvice signature
// } else if ("Lorg/aspectj/lang/ProceedingJoinPoint;".equals(stateType.getSignature())) {
// //FIXME ALEX?
// ret.append(new ALOAD(localJp));// from localAdvice signature
//// ret.append(fact.createCheckCast(
//// (ReferenceType) BcelWorld.makeBcelType(stateTypeX)
//// ));
// // cast ?
//
} else {
ret.append(InstructionFactory.createLoad(stateType, i));
}
}
}
// do the callback invoke
ret.append(Utility.createInvoke(fact, callbackMethod));
// box it again. Handles cases where around advice does return something else than Object
if (!UnresolvedType.OBJECT.equals(munger.getSignature().getReturnType())) {
ret.append(Utility.createConversion(
fact,
callbackMethod.getReturnType(),
Type.OBJECT
));
}
ret.append(Utility.createConversion(
fact,
callbackMethod.getReturnType(),
BcelWorld.makeBcelType(munger.getSignature().getReturnType())
));
return ret;
//
//
//
// if (proceedMap.hasKey(i)) {
// ret.append(new ALOAD(i));
// //throw new RuntimeException("unimplemented");
// //proceedVars[proceedMap.get(i)].appendLoadAndConvert(ret, fact, stateTypeX);
// } else {
// //((BcelVar) argVarList.get(i)).appendLoad(ret, fact);
// //ret.append(new ALOAD(i));
// if ("Lorg/aspectj/lang/JoinPoint;".equals(stateType.getSignature())) {
// ret.append(new ALOAD(i));
// } else {
// ret.append(new ALOAD(i));
// }
// }
// }
//
// ret.append(Utility.createInvoke(fact, callbackMethod));
// ret.append(Utility.createConversion(fact, callbackMethod.getReturnType(),
// BcelWorld.makeBcelType(munger.getSignature().getReturnType())));
//
// //ret.append(new ACONST_NULL());//will be POPed
// if (true) return ret;
//
//
//
// // we have on stack all the arguments for the ADVICE call.
// // we have in frame somewhere all the arguments for the non-advice call.
//
// BcelVar[] adviceVars = munger.getExposedStateAsBcelVars();
// IntMap proceedMap = makeProceedArgumentMap(adviceVars);
//
// System.out.println(proceedMap + " for " + this);
// System.out.println(argVarList);
//
// ResolvedType[] proceedParamTypes =
// world.resolve(munger.getSignature().getParameterTypes());
// // remove this*JoinPoint* as arguments to proceed
// if (munger.getBaseParameterCount()+1 < proceedParamTypes.length) {
// int len = munger.getBaseParameterCount()+1;
// ResolvedType[] newTypes = new ResolvedType[len];
// System.arraycopy(proceedParamTypes, 0, newTypes, 0, len);
// proceedParamTypes = newTypes;
// }
//
// //System.out.println("stateTypes: " + Arrays.asList(stateTypes));
// BcelVar[] proceedVars =
// Utility.pushAndReturnArrayOfVars(proceedParamTypes, ret, fact, localAdviceMethod);
//
// Type[] stateTypes = callbackMethod.getArgumentTypes();
//// System.out.println("stateTypes: " + Arrays.asList(stateTypes));
//
// for (int i=0, len=stateTypes.length; i < len; i++) {
// Type stateType = stateTypes[i];
// ResolvedType stateTypeX = BcelWorld.fromBcel(stateType).resolve(world);
// if (proceedMap.hasKey(i)) {
// //throw new RuntimeException("unimplemented");
// proceedVars[proceedMap.get(i)].appendLoadAndConvert(ret, fact, stateTypeX);
// } else {
// ((BcelVar) argVarList.get(i)).appendLoad(ret, fact);
// }
// }
//
// ret.append(Utility.createInvoke(fact, callbackMethod));
// ret.append(Utility.createConversion(fact, callbackMethod.getReturnType(),
// BcelWorld.makeBcelType(munger.getSignature().getReturnType())));
// return ret;
}
public void weaveAroundClosure(BcelAdvice munger, boolean hasDynamicTest) {
InstructionFactory fact = getFactory();
enclosingMethod.setCanInline(false);
// MOVE OUT ALL THE INSTRUCTIONS IN MY SHADOW INTO ANOTHER METHOD!
LazyMethodGen callbackMethod =
extractMethod(
NameMangler.aroundCallbackMethodName(
getSignature(),
getEnclosingClass()),
0,
munger);
BcelVar[] adviceVars = munger.getExposedStateAsBcelVars(true);
String closureClassName =
NameMangler.makeClosureClassName(
getEnclosingClass().getType(),
getEnclosingClass().getNewGeneratedNameTag());
Member constructorSig = new MemberImpl(Member.CONSTRUCTOR,
UnresolvedType.forName(closureClassName), 0, "<init>",
"([Ljava/lang/Object;)V");
BcelVar closureHolder = null;
// This is not being used currently since getKind() == preinitializaiton
// cannot happen in around advice
if (getKind() == PreInitialization) {
closureHolder = genTempVar(AjcMemberMaker.AROUND_CLOSURE_TYPE);
}
InstructionList closureInstantiation =
makeClosureInstantiation(constructorSig, closureHolder);
/*LazyMethodGen constructor = */
makeClosureClassAndReturnConstructor(
closureClassName,
callbackMethod,
makeProceedArgumentMap(adviceVars)
);
InstructionList returnConversionCode;
if (getKind() == PreInitialization) {
returnConversionCode = new InstructionList();
BcelVar stateTempVar = genTempVar(UnresolvedType.OBJECTARRAY);
closureHolder.appendLoad(returnConversionCode, fact);
returnConversionCode.append(
Utility.createInvoke(
fact,
world,
AjcMemberMaker.aroundClosurePreInitializationGetter()));
stateTempVar.appendStore(returnConversionCode, fact);
Type[] stateTypes = getSuperConstructorParameterTypes();
returnConversionCode.append(InstructionConstants.ALOAD_0); // put "this" back on the stack
for (int i = 0, len = stateTypes.length; i < len; i++) {
UnresolvedType bcelTX = BcelWorld.fromBcel(stateTypes[i]);
ResolvedType stateRTX = world.resolve(bcelTX,true);
if (stateRTX.isMissing()) {
world.getLint().cantFindType.signal(
new String[] {WeaverMessages.format(WeaverMessages.CANT_FIND_TYPE_DURING_AROUND_WEAVE_PREINIT,bcelTX.getClassName())},
getSourceLocation(),
new ISourceLocation[]{ munger.getSourceLocation()}
);
// IMessage msg = new Message(
// WeaverMessages.format(WeaverMessages.CANT_FIND_TYPE_DURING_AROUND_WEAVE_PREINIT,bcelTX.getClassName()),
// "",IMessage.ERROR,getSourceLocation(),null,
// new ISourceLocation[]{ munger.getSourceLocation()});
// world.getMessageHandler().handleMessage(msg);
}
stateTempVar.appendConvertableArrayLoad(
returnConversionCode,
fact,
i,
stateRTX);
}
} else {
returnConversionCode =
Utility.createConversion(
getFactory(),
BcelWorld.makeBcelType(munger.getSignature().getReturnType()),
callbackMethod.getReturnType(),world.isInJava5Mode());
if (!isFallsThrough()) {
returnConversionCode.append(
InstructionFactory.createReturn(callbackMethod.getReturnType()));
}
}
// ATAJ for @AJ aspect we need to link the closure with the joinpoint instance
if (munger.getConcreteAspect()!=null && munger.getConcreteAspect().isAnnotationStyleAspect()) {
closureInstantiation.append(Utility.createInvoke(
getFactory(),
getWorld(),
new MemberImpl(
Member.METHOD,
UnresolvedType.forName("org.aspectj.runtime.internal.AroundClosure"),
Modifier.PUBLIC,
"linkClosureAndJoinPoint",
"()Lorg/aspectj/lang/ProceedingJoinPoint;"
)
));
}
InstructionList advice = new InstructionList();
advice.append(munger.getAdviceArgSetup(this, null, closureInstantiation));
// invoke the advice
advice.append(munger.getNonTestAdviceInstructions(this));
advice.append(returnConversionCode);
if (!hasDynamicTest) {
range.append(advice);
} else {
InstructionList callback = makeCallToCallback(callbackMethod);
InstructionList postCallback = new InstructionList();
if (terminatesWithReturn()) {
callback.append(
InstructionFactory.createReturn(callbackMethod.getReturnType()));
} else {
advice.append(
InstructionFactory.createBranchInstruction(
Constants.GOTO,
postCallback.append(InstructionConstants.NOP)));
}
range.append(
munger.getTestInstructions(
this,
advice.getStart(),
callback.getStart(),
advice.getStart()));
range.append(advice);
range.append(callback);
range.append(postCallback);
}
}
// exposed for testing
InstructionList makeCallToCallback(LazyMethodGen callbackMethod) {
InstructionFactory fact = getFactory();
InstructionList callback = new InstructionList();
if (thisVar != null) {
callback.append(InstructionConstants.ALOAD_0);
}
if (targetVar != null && targetVar != thisVar) {
callback.append(BcelRenderer.renderExpr(fact, world, targetVar));
}
callback.append(BcelRenderer.renderExprs(fact, world, argVars));
// remember to render tjps
if (thisJoinPointVar != null) {
callback.append(BcelRenderer.renderExpr(fact, world, thisJoinPointVar));
}
callback.append(Utility.createInvoke(fact, callbackMethod));
return callback;
}
/** side-effect-free */
private InstructionList makeClosureInstantiation(Member constructor, BcelVar holder) {
// LazyMethodGen constructor) {
InstructionFactory fact = getFactory();
BcelVar arrayVar = genTempVar(UnresolvedType.OBJECTARRAY);
//final Type objectArrayType = new ArrayType(Type.OBJECT, 1);
final InstructionList il = new InstructionList();
int alen = getArgCount() + (thisVar == null ? 0 : 1) +
((targetVar != null && targetVar != thisVar) ? 1 : 0) +
(thisJoinPointVar == null ? 0 : 1);
il.append(Utility.createConstant(fact, alen));
il.append((Instruction)fact.createNewArray(Type.OBJECT, (short)1));
arrayVar.appendStore(il, fact);
int stateIndex = 0;
if (thisVar != null) {
arrayVar.appendConvertableArrayStore(il, fact, stateIndex, thisVar);
thisVar.setPositionInAroundState(stateIndex);
stateIndex++;
}
if (targetVar != null && targetVar != thisVar) {
arrayVar.appendConvertableArrayStore(il, fact, stateIndex, targetVar);
targetVar.setPositionInAroundState(stateIndex);
stateIndex++;
}
for (int i = 0, len = getArgCount(); i<len; i++) {
arrayVar.appendConvertableArrayStore(il, fact, stateIndex, argVars[i]);
argVars[i].setPositionInAroundState(stateIndex);
stateIndex++;
}
if (thisJoinPointVar != null) {
arrayVar.appendConvertableArrayStore(il, fact, stateIndex, thisJoinPointVar);
thisJoinPointVar.setPositionInAroundState(stateIndex);
stateIndex++;
}
il.append(fact.createNew(new ObjectType(constructor.getDeclaringType().getName())));
il.append(new DUP());
arrayVar.appendLoad(il, fact);
il.append(Utility.createInvoke(fact, world, constructor));
if (getKind() == PreInitialization) {
il.append(InstructionConstants.DUP);
holder.appendStore(il, fact);
}
return il;
}
private IntMap makeProceedArgumentMap(BcelVar[] adviceArgs) {
//System.err.println("coming in with " + Arrays.asList(adviceArgs));
IntMap ret = new IntMap();
for(int i = 0, len = adviceArgs.length; i < len; i++) {
BcelVar v = (BcelVar) adviceArgs[i];
if (v == null) continue; // XXX we don't know why this is required
int pos = v.getPositionInAroundState();
if (pos >= 0) { // need this test to avoid args bound via cflow
ret.put(pos, i);
}
}
//System.err.println("returning " + ret);
return ret;
}
/**
*
*
* @param callbackMethod the method we will call back to when our run method gets called.
*
* @param proceedMap A map from state position to proceed argument position. May be
* non covering on state position.
*/
private LazyMethodGen makeClosureClassAndReturnConstructor(
String closureClassName,
LazyMethodGen callbackMethod,
IntMap proceedMap)
{
String superClassName = "org.aspectj.runtime.internal.AroundClosure";
Type objectArrayType = new ArrayType(Type.OBJECT, 1);
LazyClassGen closureClass = new LazyClassGen(closureClassName,
superClassName,
getEnclosingClass().getFileName(),
Modifier.PUBLIC,
new String[] {},
getWorld());
InstructionFactory fact = new InstructionFactory(closureClass.getConstantPoolGen());
// constructor
LazyMethodGen constructor = new LazyMethodGen(Modifier.PUBLIC,
Type.VOID,
"<init>",
new Type[] {objectArrayType},
new String[] {},
closureClass);
InstructionList cbody = constructor.getBody();
cbody.append(InstructionFactory.createLoad(Type.OBJECT, 0));
cbody.append(InstructionFactory.createLoad(objectArrayType, 1));
cbody.append(fact.createInvoke(superClassName, "<init>", Type.VOID,
new Type[] {objectArrayType}, Constants.INVOKESPECIAL));
cbody.append(InstructionFactory.createReturn(Type.VOID));
closureClass.addMethodGen(constructor);
// method
LazyMethodGen runMethod = new LazyMethodGen(Modifier.PUBLIC,
Type.OBJECT,
"run",
new Type[] {objectArrayType},
new String[] {},
closureClass);
InstructionList mbody = runMethod.getBody();
BcelVar proceedVar = new BcelVar(UnresolvedType.OBJECTARRAY.resolve(world), 1);
// int proceedVarIndex = 1;
BcelVar stateVar =
new BcelVar(UnresolvedType.OBJECTARRAY.resolve(world), runMethod.allocateLocal(1));
// int stateVarIndex = runMethod.allocateLocal(1);
mbody.append(InstructionFactory.createThis());
mbody.append(fact.createGetField(superClassName, "state", objectArrayType));
mbody.append(stateVar.createStore(fact));
// mbody.append(fact.createStore(objectArrayType, stateVarIndex));
Type[] stateTypes = callbackMethod.getArgumentTypes();
for (int i=0, len=stateTypes.length; i < len; i++) {
Type stateType = stateTypes[i];
ResolvedType stateTypeX = BcelWorld.fromBcel(stateType).resolve(world);
if (proceedMap.hasKey(i)) {
mbody.append(
proceedVar.createConvertableArrayLoad(fact, proceedMap.get(i),
stateTypeX));
} else {
mbody.append(
stateVar.createConvertableArrayLoad(fact, i,
stateTypeX));
}
}
mbody.append(Utility.createInvoke(fact, callbackMethod));
if (getKind() == PreInitialization) {
mbody.append(Utility.createSet(
fact,
AjcMemberMaker.aroundClosurePreInitializationField()));
mbody.append(InstructionConstants.ACONST_NULL);
} else {
mbody.append(
Utility.createConversion(
fact,
callbackMethod.getReturnType(),
Type.OBJECT));
}
mbody.append(InstructionFactory.createReturn(Type.OBJECT));
closureClass.addMethodGen(runMethod);
// class
getEnclosingClass().addGeneratedInner(closureClass);
return constructor;
}
// ---- extraction methods
public LazyMethodGen extractMethod(String newMethodName, int visibilityModifier, ShadowMunger munger) {
LazyMethodGen.assertGoodBody(range.getBody(), newMethodName);
if (!getKind().allowsExtraction()) throw new BCException("Attempt to extract method from a shadow kind that does not support this operation (" + getKind() + ")");
LazyMethodGen freshMethod = createMethodGen(newMethodName,visibilityModifier);
// System.err.println("******");
// System.err.println("ABOUT TO EXTRACT METHOD for" + this);
// enclosingMethod.print(System.err);
// System.err.println("INTO");
// freshMethod.print(System.err);
// System.err.println("WITH REMAP");
// System.err.println(makeRemap());
range.extractInstructionsInto(freshMethod, makeRemap(),
(getKind() != PreInitialization) &&
isFallsThrough());
if (getKind() == PreInitialization) {
addPreInitializationReturnCode(
freshMethod,
getSuperConstructorParameterTypes());
}
getEnclosingClass().addMethodGen(freshMethod,munger.getSourceLocation());
return freshMethod;
}
private void addPreInitializationReturnCode(
LazyMethodGen extractedMethod,
Type[] superConstructorTypes)
{
InstructionList body = extractedMethod.getBody();
final InstructionFactory fact = getFactory();
BcelVar arrayVar = new BcelVar(
world.getCoreType(UnresolvedType.OBJECTARRAY),
extractedMethod.allocateLocal(1));
int len = superConstructorTypes.length;
body.append(Utility.createConstant(fact, len));
body.append((Instruction)fact.createNewArray(Type.OBJECT, (short)1));
arrayVar.appendStore(body, fact);
for (int i = len - 1; i >= 0; i++) {
// convert thing on top of stack to object
body.append(
Utility.createConversion(fact, superConstructorTypes[i], Type.OBJECT));
// push object array
arrayVar.appendLoad(body, fact);
// swap
body.append(InstructionConstants.SWAP);
// do object array store.
body.append(Utility.createConstant(fact, i));
body.append(InstructionConstants.SWAP);
body.append(InstructionFactory.createArrayStore(Type.OBJECT));
}
arrayVar.appendLoad(body, fact);
body.append(InstructionConstants.ARETURN);
}
private Type[] getSuperConstructorParameterTypes() {
// assert getKind() == PreInitialization
InstructionHandle superCallHandle = getRange().getEnd().getNext();
InvokeInstruction superCallInstruction =
(InvokeInstruction) superCallHandle.getInstruction();
return superCallInstruction.getArgumentTypes(
getEnclosingClass().getConstantPoolGen());
}
/** make a map from old frame location to new frame location. Any unkeyed frame
* location picks out a copied local */
private IntMap makeRemap() {
IntMap ret = new IntMap(5);
int reti = 0;
if (thisVar != null) {
ret.put(0, reti++); // thisVar guaranteed to be 0
}
if (targetVar != null && targetVar != thisVar) {
ret.put(targetVar.getSlot(), reti++);
}
for (int i = 0, len = argVars.length; i < len; i++) {
ret.put(argVars[i].getSlot(), reti);
reti += argVars[i].getType().getSize();
}
if (thisJoinPointVar != null) {
ret.put(thisJoinPointVar.getSlot(), reti++);
}
// we not only need to put the arguments, we also need to remap their
// aliases, which we so helpfully put into temps at the beginning of this join
// point.
if (! getKind().argsOnStack()) {
int oldi = 0;
int newi = 0;
// if we're passing in a this and we're not argsOnStack we're always
// passing in a target too
if (arg0HoldsThis()) { ret.put(0, 0); oldi++; newi+=1; }
//assert targetVar == thisVar
for (int i = 0; i < getArgCount(); i++) {
UnresolvedType type = getArgType(i);
ret.put(oldi, newi);
oldi += type.getSize();
newi += type.getSize();
}
}
// System.err.println("making remap for : " + this);
// if (targetVar != null) System.err.println("target slot : " + targetVar.getSlot());
// if (thisVar != null) System.err.println(" this slot : " + thisVar.getSlot());
// System.err.println(ret);
return ret;
}
/**
* The new method always static.
* It may take some extra arguments: this, target.
* If it's argsOnStack, then it must take both this/target
* If it's argsOnFrame, it shares this and target.
* ??? rewrite this to do less array munging, please
*/
private LazyMethodGen createMethodGen(String newMethodName, int visibilityModifier) {
Type[] parameterTypes = BcelWorld.makeBcelTypes(getArgTypes());
int modifiers = Modifier.FINAL | visibilityModifier;
// XXX some bug
// if (! isExpressionKind() && getSignature().isStrict(world)) {
// modifiers |= Modifier.STRICT;
// }
modifiers |= Modifier.STATIC;
if (targetVar != null && targetVar != thisVar) {
UnresolvedType targetType = getTargetType();
targetType = ensureTargetTypeIsCorrect(targetType);
// see pr109728 - this fixes the case when the declaring class is sometype 'X' but the getfield
// in the bytecode refers to a subtype of 'X'. This makes sure we use the type originally
// mentioned in the fieldget instruction as the method parameter and *not* the type upon which the
// field is declared because when the instructions are extracted into the new around body,
// they will still refer to the subtype.
if (getKind()==FieldGet && getActualTargetType()!=null &&
!getActualTargetType().equals(targetType.getName())) {
targetType = UnresolvedType.forName(getActualTargetType()).resolve(world);
}
ResolvedMember resolvedMember = getSignature().resolve(world);
if (resolvedMember != null && Modifier.isProtected(resolvedMember.getModifiers()) &&
!samePackage(targetType.getPackageName(), getEnclosingType().getPackageName()) &&
!resolvedMember.getName().equals("clone"))
{
if (!targetType.resolve(world).isAssignableFrom(getThisType().resolve(world))) {
throw new BCException("bad bytecode");
}
targetType = getThisType();
}
parameterTypes = addType(BcelWorld.makeBcelType(targetType), parameterTypes);
}
if (thisVar != null) {
UnresolvedType thisType = getThisType();
parameterTypes = addType(BcelWorld.makeBcelType(thisType), parameterTypes);
}
// We always want to pass down thisJoinPoint in case we have already woven
// some advice in here. If we only have a single piece of around advice on a
// join point, it is unnecessary to accept (and pass) tjp.
if (thisJoinPointVar != null) {
parameterTypes = addTypeToEnd(LazyClassGen.tjpType, parameterTypes);
//FIXME ALEX? which one
//parameterTypes = addTypeToEnd(LazyClassGen.proceedingTjpType, parameterTypes);
}
UnresolvedType returnType;
if (getKind() == PreInitialization) {
returnType = UnresolvedType.OBJECTARRAY;
} else {
returnType = getReturnType();
}
return
new LazyMethodGen(
modifiers,
BcelWorld.makeBcelType(returnType),
newMethodName,
parameterTypes,
new String[0],
// XXX again, we need to look up methods!
// UnresolvedType.getNames(getSignature().getExceptions(world)),
getEnclosingClass());
}
private boolean samePackage(String p1, String p2) {
if (p1 == null) return p2 == null;
if (p2 == null) return false;
return p1.equals(p2);
}
private Type[] addType(Type type, Type[] types) {
int len = types.length;
Type[] ret = new Type[len+1];
ret[0] = type;
System.arraycopy(types, 0, ret, 1, len);
return ret;
}
private Type[] addTypeToEnd(Type type, Type[] types) {
int len = types.length;
Type[] ret = new Type[len+1];
ret[len] = type;
System.arraycopy(types, 0, ret, 0, len);
return ret;
}
public BcelVar genTempVar(UnresolvedType typeX) {
return new BcelVar(typeX.resolve(world), genTempVarIndex(typeX.getSize()));
}
// public static final boolean CREATE_TEMP_NAMES = true;
public BcelVar genTempVar(UnresolvedType typeX, String localName) {
BcelVar tv = genTempVar(typeX);
// if (CREATE_TEMP_NAMES) {
// for (InstructionHandle ih = range.getStart(); ih != range.getEnd(); ih = ih.getNext()) {
// if (Range.isRangeHandle(ih)) continue;
// ih.addTargeter(new LocalVariableTag(typeX, localName, tv.getSlot()));
// }
// }
return tv;
}
// eh doesn't think we need to garbage collect these (64K is a big number...)
private int genTempVarIndex(int size) {
return enclosingMethod.allocateLocal(size);
}
public InstructionFactory getFactory() {
return getEnclosingClass().getFactory();
}
public ISourceLocation getSourceLocation() {
int sourceLine = getSourceLine();
if (sourceLine == 0 || sourceLine == -1) {
// Thread.currentThread().dumpStack();
// System.err.println(this + ": " + range);
return getEnclosingClass().getType().getSourceLocation();
} else {
// For staticinitialization, if we have a nice offset, don't build a new source loc
if (getKind()==Shadow.StaticInitialization && getEnclosingClass().getType().getSourceLocation().getOffset()!=0) {
return getEnclosingClass().getType().getSourceLocation();
} else {
int offset = 0;
Kind kind = getKind();
if ( (kind == MethodExecution) ||
(kind == ConstructorExecution) ||
(kind == AdviceExecution) ||
(kind == StaticInitialization) ||
(kind == PreInitialization) ||
(kind == Initialization)) {
if (getEnclosingMethod().hasDeclaredLineNumberInfo()) {
offset = getEnclosingMethod().getDeclarationOffset();
}
}
return getEnclosingClass().getType().getSourceContext().makeSourceLocation(sourceLine, offset);
}
}
}
public Shadow getEnclosingShadow() {
return enclosingShadow;
}
public LazyMethodGen getEnclosingMethod() {
return enclosingMethod;
}
public boolean isFallsThrough() {
return !terminatesWithReturn(); //fallsThrough;
}
public void setActualTargetType(String className) {
this.actualInstructionTargetType = className;
}
public String getActualTargetType() {
return actualInstructionTargetType;
}
}
|
122,728 |
Bug 122728 ajdoc crashes
| null |
resolved fixed
|
d69ce9a
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-01-09T13:31:55Z | 2006-01-05T08:33:20Z |
ajdoc/src/org/aspectj/tools/ajdoc/StubFileGenerator.java
|
/* *******************************************************************
* Copyright (c) 1999-2001 Xerox Corporation,
* 2002 Palo Alto Research Center, Incorporated (PARC).
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* Xerox/PARC initial implementation
* Mik Kersten port to AspectJ 1.1+ code base
* ******************************************************************/
package org.aspectj.tools.ajdoc;
import java.io.*;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import org.aspectj.asm.AsmManager;
import org.aspectj.asm.IProgramElement;
/**
* @author Mik Kersten
*/
class StubFileGenerator{
static Hashtable declIDTable = null;
static void doFiles (Hashtable table,
SymbolManager symbolManager,
File[] inputFiles,
File[] signatureFiles) throws DocException {
declIDTable = table;
for (int i = 0; i < inputFiles.length; i++) {
processFile(symbolManager, inputFiles[i], signatureFiles[i]);
}
}
static void processFile(SymbolManager symbolManager, File inputFile, File signatureFile) throws DocException {
try {
String path = StructureUtil.translateAjPathName(signatureFile.getCanonicalPath());
PrintWriter writer = new PrintWriter(new BufferedWriter(new FileWriter(path)));
String packageName = StructureUtil.getPackageDeclarationFromFile(inputFile);
if (packageName != null && packageName != "") {
writer.println( "package " + packageName + ";" );
}
IProgramElement fileNode = (IProgramElement)AsmManager.getDefault().getHierarchy().findElementForSourceFile(inputFile.getAbsolutePath());
for (Iterator it = fileNode.getChildren().iterator(); it.hasNext(); ) {
IProgramElement node = (IProgramElement)it.next();
if (node.getKind().equals(IProgramElement.Kind.IMPORT_REFERENCE)) {
processImportDeclaration(node, writer);
} else {
try {
processTypeDeclaration(node, writer);
} catch (DocException d){
throw new DocException("File name invalid: " + inputFile.toString());
}
}
}
// if we got an error we don't want the contents of the file
writer.close();
} catch (IOException e) {
System.err.println(e.getMessage());
e.printStackTrace();
}
}
private static void processImportDeclaration(IProgramElement node, PrintWriter writer) throws IOException {
List imports = node.getChildren();
for (Iterator i = imports.iterator(); i.hasNext();) {
IProgramElement importNode = (IProgramElement) i.next();
writer.print("import ");
writer.print(importNode.getName());
writer.println(';');
}
}
private static void processTypeDeclaration(IProgramElement classNode, PrintWriter writer) throws DocException {
String formalComment = addDeclID(classNode, classNode.getFormalComment());
writer.println(formalComment);
String signature = genSourceSignature(classNode);// StructureUtil.genSignature(classNode);
if (signature == null){
throw new DocException("The java file is invalid");
}
// System.err.println("######" + signature + ", " + classNode.getName());
if (!StructureUtil.isAnonymous(classNode) && !classNode.getName().equals("<undefined>")) {
writer.println(signature + " {" );
processMembers(classNode.getChildren(), writer, classNode.getKind().equals(IProgramElement.Kind.INTERFACE));
writer.println();
writer.println("}");
}
}
private static void processMembers(List/*IProgramElement*/ members, PrintWriter writer, boolean declaringTypeIsInterface) throws DocException {
for (Iterator it = members.iterator(); it.hasNext();) {
IProgramElement member = (IProgramElement) it.next();
if (member.getKind().isType()) {
if (!member.getParent().getKind().equals(IProgramElement.Kind.METHOD)
&& !StructureUtil.isAnonymous(member)) {// don't print anonymous types
// System.err.println(">>>>>>>>>>>>>" + member.getName() + "<<<<" + member.getParent());
processTypeDeclaration(member, writer);
}
} else {
String formalComment = addDeclID(member, member.getFormalComment());;
writer.println(formalComment);
String signature = "";
if (!member.getKind().equals(IProgramElement.Kind.POINTCUT)
&& !member.getKind().equals(IProgramElement.Kind.ADVICE)) {
signature = member.getSourceSignature();//StructureUtil.genSignature(member);
if (member.getKind().equals(IProgramElement.Kind.ENUM_VALUE)){
if (((IProgramElement)members.get(members.indexOf(member)+1)).getKind().equals(IProgramElement.Kind.ENUM_VALUE)){
// if the next member is also an ENUM_VALUE:
signature = signature + ",";
} else {
signature = signature + ";";
}
}
}
if (member.getKind().isDeclare()) {
// System.err.println("> Skipping declare (ajdoc limitation): " + member.toLabelString());
} else if (signature != null &&
signature != "" &&
!member.getKind().isInterTypeMember() &&
!member.getKind().equals(IProgramElement.Kind.INITIALIZER) &&
!StructureUtil.isAnonymous(member)) {
writer.print(signature);
} else {
// System.err.println(">> skipping: " + member.getKind());
}
if (member.getKind().equals(IProgramElement.Kind.METHOD) ||
member.getKind().equals(IProgramElement.Kind.CONSTRUCTOR)) {
if (member.getParent().getKind().equals(IProgramElement.Kind.INTERFACE) ||
signature.indexOf("abstract ") != -1) {
writer.println(";");
} else {
writer.println(" { }");
}
} else if (member.getKind().equals(IProgramElement.Kind.FIELD)) {
// writer.println(";");
}
}
}
}
/**
* Translates "aspect" to "class", as long as its not ".aspect"
*/
private static String genSourceSignature(IProgramElement classNode) {
String signature = classNode.getSourceSignature();
if (signature != null){
int index = signature.indexOf("aspect");
if (index == 0 || (index != -1 && signature.charAt(index-1) != '.') ) {
signature = signature.substring(0, index) +
"class " +
signature.substring(index + 6, signature.length());
}
}
return signature;
}
static int nextDeclID = 0;
static String addDeclID(IProgramElement decl, String formalComment) {
String declID = "" + ++nextDeclID;
declIDTable.put(declID, decl);
return addToFormal(formalComment, Config.DECL_ID_STRING + declID + Config.DECL_ID_TERMINATOR);
}
/**
* We want to go:
* just before the first period
* just before the first @
* just before the end of the comment
*
* Adds a place holder for the period ('#') if one will need to be
* replaced.
*/
static String addToFormal(String formalComment, String string) {
boolean appendPeriod = true;
if ( (formalComment == null) || formalComment.equals("")) {
//formalComment = "/**\n * . \n */\n";
formalComment = "/**\n * \n */\n";
appendPeriod = false;
}
formalComment = formalComment.trim();
int atsignPos = formalComment.indexOf('@');
int endPos = formalComment.indexOf("*/");
int periodPos = formalComment.indexOf("/**")+2;
int position = 0;
String periodPlaceHolder = "";
if ( periodPos != -1 ) {
position = periodPos+1;
}
else if ( atsignPos != -1 ) {
string = string + "\n * ";
position = atsignPos;
}
else if ( endPos != -1 ) {
string = "* " + string + "\n";
position = endPos;
}
else {
// !!! perhaps this error should not be silent
throw new Error("Failed to append to formal comment for comment: " +
formalComment );
}
return
formalComment.substring(0, position) + periodPlaceHolder +
string +
formalComment.substring(position);
}
}
|
122,728 |
Bug 122728 ajdoc crashes
| null |
resolved fixed
|
d69ce9a
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-01-09T13:31:55Z | 2006-01-05T08:33:20Z |
ajdoc/testdata/pr122728/src/pack/ClassWithInnerEnum.java
| |
122,728 |
Bug 122728 ajdoc crashes
| null |
resolved fixed
|
d69ce9a
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-01-09T13:31:55Z | 2006-01-05T08:33:20Z |
ajdoc/testdata/pr122728/src/pack/EnumWithMethods.java
| |
122,728 |
Bug 122728 ajdoc crashes
| null |
resolved fixed
|
d69ce9a
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-01-09T13:31:55Z | 2006-01-05T08:33:20Z |
ajdoc/testdata/pr122728/src/pack/MyEnum.java
| |
122,728 |
Bug 122728 ajdoc crashes
| null |
resolved fixed
|
d69ce9a
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-01-09T13:31:55Z | 2006-01-05T08:33:20Z |
ajdoc/testsrc/org/aspectj/tools/ajdoc/AjdocTests.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:
* Wes Isberg initial implementation
* ******************************************************************/
package org.aspectj.tools.ajdoc;
import java.io.File;
import org.aspectj.util.FileUtil;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
public class AjdocTests extends TestCase {
public static File ASPECTJRT_PATH;
static {
String[] paths = { "sp:aspectjrt.path", "sp:aspectjrt.jar",
"../lib/test/aspectjrt.jar", "../aj-build/jars/aspectj5rt-all.jar",
"../aj-build/jars/runtime.jar",
"../runtime/bin"};
ASPECTJRT_PATH = FileUtil.getBestFile(paths);
}
public static Test suite() {
TestSuite suite = new TestSuite(AjdocTests.class.getName());
//$JUnit-BEGIN$
suite.addTestSuite(DeclareFormsTest.class);
suite.addTestSuite(SpacewarTestCase.class);
suite.addTestSuite(PatternsTestCase.class);
suite.addTestSuite(CoverageTestCase.class);
suite.addTestSuite(ITDTest.class);
suite.addTestSuite(FullyQualifiedArgumentTest.class);
suite.addTestSuite(ExecutionTestCase.class);// !!! must be last because it exists
//$JUnit-END$
return suite;
}
}
|
122,728 |
Bug 122728 ajdoc crashes
| null |
resolved fixed
|
d69ce9a
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-01-09T13:31:55Z | 2006-01-05T08:33:20Z |
ajdoc/testsrc/org/aspectj/tools/ajdoc/EnumTest.java
| |
112,458 |
Bug 112458 Property Editor still shows the properties of layout items when switch to Master page viewer.
|
Description: Property Editor still shows the properties of layout items when switch to Master page viewer. Steps to reproduce: 1. New a report and insert a label. 2. Select the label.(Property Editor shows label's properties) 3. Switch to Master Page. Expected result: Property Editor changs to reflect Master Page properties. Actual result: It still showed the label's properties. This will confuse customers if they thought it as Master Page Editor and set properties without click Master Page viewer at first.
|
closed fixed
|
53284da
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-01-10T09:44:47Z | 2005-10-13T10:40:00Z |
tests/src/org/aspectj/systemtest/AllTests15.java
|
/*
* Created on 19-01-2005
*/
package org.aspectj.systemtest;
import junit.framework.Test;
import junit.framework.TestSuite;
import org.aspectj.systemtest.ajc150.AllTestsAspectJ150;
import org.aspectj.systemtest.ajc150.ataspectj.AtAjAnnotationGenTests;
public class AllTests15 {
public static Test suite() {
TestSuite suite = new TestSuite("AspectJ System Test Suite - JDK 1.5");
//$JUnit-BEGIN$
suite.addTest(AllTests14.suite());
suite.addTest(AllTestsAspectJ150.suite());
suite.addTest(AtAjAnnotationGenTests.suite());
//$JUnit-END$
return suite;
}
}
|
112,458 |
Bug 112458 Property Editor still shows the properties of layout items when switch to Master page viewer.
|
Description: Property Editor still shows the properties of layout items when switch to Master page viewer. Steps to reproduce: 1. New a report and insert a label. 2. Select the label.(Property Editor shows label's properties) 3. Switch to Master Page. Expected result: Property Editor changs to reflect Master Page properties. Actual result: It still showed the label's properties. This will confuse customers if they thought it as Master Page Editor and set properties without click Master Page viewer at first.
|
closed fixed
|
53284da
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-01-10T09:44:47Z | 2005-10-13T10:40:00Z |
tests/src/org/aspectj/systemtest/ajc150/AllTestsAspectJ150.java
|
/*******************************************************************************
* Copyright (c) 2004 IBM
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* Andy Clement - initial API and implementation
*******************************************************************************/
package org.aspectj.systemtest.ajc150;
import org.aspectj.systemtest.ajc150.ataspectj.AtAjSyntaxTests;
import org.aspectj.systemtest.ajc150.ataspectj.AtAjMisuseTests;
import org.aspectj.systemtest.ajc150.ataspectj.AtAjLTWTests;
import org.aspectj.systemtest.ajc150.ltw.LTWTests;
import junit.framework.Test;
import junit.framework.TestSuite;
/**
* This pulls together tests we have written for AspectJ 1.5.0 that don't need Java 1.5 to run
*/
public class AllTestsAspectJ150 {
public static Test suite() {
TestSuite suite = new TestSuite("Java5/AspectJ5 tests");
//$JUnit-BEGIN$
suite.addTestSuite(MigrationTests.class);
suite.addTest(Ajc150Tests.suite());
suite.addTestSuite(SCCSFixTests.class);
suite.addTest(AccBridgeMethods.suite());
suite.addTestSuite(CovarianceTests.class);
suite.addTestSuite(Enums.class);
suite.addTest(AnnotationsBinaryWeaving.suite());
suite.addTest(AnnotationPointcutsTests.suite());
suite.addTestSuite(VarargsTests.class);
suite.addTestSuite(StaticImports.class);
suite.addTest(AnnotationRuntimeTests.suite());
suite.addTestSuite(PerTypeWithinTests.class);
suite.addTest(Autoboxing.suite());
suite.addTest(Annotations.suite());
suite.addTest(AnnotationBinding.suite());
suite.addTest(RuntimeAnnotations.suite());
suite.addTest(SuppressedWarnings.suite());
suite.addTest(DeclareAnnotationTests.suite());
suite.addTest(GenericsTests.suite());
suite.addTest(GenericITDsDesign.suite());
suite.addTest(AtAjSyntaxTests.suite());
suite.addTest(AtAjMisuseTests.suite());
suite.addTest(AtAjLTWTests.suite());
suite.addTest(HasMember.suite());
suite.addTestSuite(LTWTests.class);
//$JUnit-END$
return suite;
}
}
|
112,458 |
Bug 112458 Property Editor still shows the properties of layout items when switch to Master page viewer.
|
Description: Property Editor still shows the properties of layout items when switch to Master page viewer. Steps to reproduce: 1. New a report and insert a label. 2. Select the label.(Property Editor shows label's properties) 3. Switch to Master Page. Expected result: Property Editor changs to reflect Master Page properties. Actual result: It still showed the label's properties. This will confuse customers if they thought it as Master Page Editor and set properties without click Master Page viewer at first.
|
closed fixed
|
53284da
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-01-10T09:44:47Z | 2005-10-13T10:40:00Z |
tests/src/org/aspectj/systemtest/ajc151/Ajc151Tests.java
| |
112,458 |
Bug 112458 Property Editor still shows the properties of layout items when switch to Master page viewer.
|
Description: Property Editor still shows the properties of layout items when switch to Master page viewer. Steps to reproduce: 1. New a report and insert a label. 2. Select the label.(Property Editor shows label's properties) 3. Switch to Master Page. Expected result: Property Editor changs to reflect Master Page properties. Actual result: It still showed the label's properties. This will confuse customers if they thought it as Master Page Editor and set properties without click Master Page viewer at first.
|
closed fixed
|
53284da
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-01-10T09:44:47Z | 2005-10-13T10:40:00Z |
tests/src/org/aspectj/systemtest/ajc151/AllTestsAspectJ151.java
| |
112,458 |
Bug 112458 Property Editor still shows the properties of layout items when switch to Master page viewer.
|
Description: Property Editor still shows the properties of layout items when switch to Master page viewer. Steps to reproduce: 1. New a report and insert a label. 2. Select the label.(Property Editor shows label's properties) 3. Switch to Master Page. Expected result: Property Editor changs to reflect Master Page properties. Actual result: It still showed the label's properties. This will confuse customers if they thought it as Master Page Editor and set properties without click Master Page viewer at first.
|
closed fixed
|
53284da
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-01-10T09:44:47Z | 2005-10-13T10:40:00Z |
weaver/src/org/aspectj/weaver/TypeFactory.java
|
/* *******************************************************************
* Copyright (c) 2005 Contributors.
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Eclipse Public License v1.0
* which accompanies this distribution and is available at
* http://eclipse.org/legal/epl-v10.html
*
* Contributors:
* Adrian Colyer Initial implementation
* ******************************************************************/
package org.aspectj.weaver;
import java.util.ArrayList;
import java.util.List;
import org.aspectj.weaver.UnresolvedType.TypeKind;
/**
* @author colyer
*
*/
public class TypeFactory {
/**
* Create a parameterized version of a generic type.
* @param aGenericType
* @param someTypeParameters note, in the case of an inner type of a parameterized type,
* this parameter may legitimately be null
* @param inAWorld
* @return
*/
public static ReferenceType createParameterizedType(
ResolvedType aBaseType,
UnresolvedType[] someTypeParameters,
World inAWorld
) {
ResolvedType baseType = aBaseType;
if (!aBaseType.isGenericType()) {
// try and find the generic type...
if (someTypeParameters != null && someTypeParameters.length>0) {
if (!aBaseType.isRawType()) throw new IllegalStateException("Expecting raw type");
baseType = baseType.getGenericType();
if (baseType == null) throw new IllegalStateException("Raw type does not have generic type set");
} // else if someTypeParameters is null, then the base type is allowed to be non-generic, it's an inner
}
ResolvedType[] resolvedParameters = inAWorld.resolve(someTypeParameters);
ReferenceType pType = new ReferenceType(baseType,resolvedParameters,inAWorld);
pType.setSourceContext(aBaseType.getSourceContext());
return (ReferenceType) pType.resolve(inAWorld);
}
/**
* Create an *unresolved* parameterized version of a generic type.
*/
public static UnresolvedType createUnresolvedParameterizedType(String sig,String erasuresig,UnresolvedType[] arguments) {
return new UnresolvedType(sig,erasuresig,arguments);
}
public static ReferenceType createRawType(
ResolvedType aBaseType,
World inAWorld
) {
if (aBaseType.isRawType()) return (ReferenceType) aBaseType;
if (!aBaseType.isGenericType()) {
if (!aBaseType.isRawType()) throw new IllegalStateException("Expecting generic type");
}
ReferenceType rType = new ReferenceType(aBaseType,inAWorld);
rType.setSourceContext(aBaseType.getSourceContext());
return (ReferenceType) rType.resolve(inAWorld);
}
/**
* Used by UnresolvedType.read, creates a type from a full signature.
* @param signature
* @return
*/
public static UnresolvedType createTypeFromSignature(String signature) {
if (signature.equals(ResolvedType.MISSING_NAME)) return ResolvedType.MISSING;
if (signature.startsWith(ResolvedType.PARAMETERIZED_TYPE_IDENTIFIER)) {
// parameterized type, calculate signature erasure and type parameters
int startOfParams = signature.indexOf('<');
int endOfParams = signature.lastIndexOf('>');
String signatureErasure = "L" + signature.substring(1,startOfParams) + ";";
UnresolvedType[] typeParams = createTypeParams(signature.substring(startOfParams +1, endOfParams));
return new UnresolvedType(signature,signatureErasure,typeParams);
} else if (signature.equals("?")){
UnresolvedType ret = UnresolvedType.SOMETHING;
ret.typeKind = TypeKind.WILDCARD;
return ret;
} else if(signature.startsWith("+")) {
// ? extends ...
UnresolvedType bound = UnresolvedType.forSignature(signature.substring(1));
UnresolvedType ret = new UnresolvedType(signature);
ret.typeKind = TypeKind.WILDCARD;
ret.setUpperBound(bound);
return ret;
} else if (signature.startsWith("-")) {
// ? super ...
UnresolvedType bound = UnresolvedType.forSignature(signature.substring(1));
UnresolvedType ret = new UnresolvedType(signature);
ret.typeKind = TypeKind.WILDCARD;
ret.setLowerBound(bound);
return ret;
} else if (signature.startsWith("T")) {
String typeVariableName = signature.substring(1);
if (typeVariableName.endsWith(";")) {
typeVariableName = typeVariableName.substring(0, typeVariableName.length() -1);
}
return new UnresolvedTypeVariableReferenceType(new TypeVariable(typeVariableName));
} else if (signature.startsWith("[")) {
int dims = 0;
while (signature.charAt(dims)=='[') dims++;
UnresolvedType componentType = createTypeFromSignature(signature.substring(dims));
return new UnresolvedType(signature,
signature.substring(0,dims)+componentType.getErasureSignature());
} else if (signature.length()==1) { // could be a primitive
switch (signature.charAt(0)) {
case 'V': return ResolvedType.VOID;
case 'Z': return ResolvedType.BOOLEAN;
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 'S': return ResolvedType.SHORT;
}
}
return new UnresolvedType(signature);
}
private static UnresolvedType[] createTypeParams(String typeParameterSpecification) {
String remainingToProcess = typeParameterSpecification;
List types = new ArrayList();
while(!remainingToProcess.equals("")) {
int endOfSig = 0;
int anglies = 0;
boolean sigFound = false;
for (endOfSig = 0; (endOfSig < remainingToProcess.length()) && !sigFound; endOfSig++) {
char thisChar = remainingToProcess.charAt(endOfSig);
switch(thisChar) {
case '<' : anglies++; break;
case '>' : anglies--; break;
case ';' :
if (anglies == 0) {
sigFound = true;
break;
}
}
}
types.add(createTypeFromSignature(remainingToProcess.substring(0,endOfSig)));
remainingToProcess = remainingToProcess.substring(endOfSig);
}
UnresolvedType[] typeParams = new UnresolvedType[types.size()];
types.toArray(typeParams);
return typeParams;
}
}
|
122,458 |
Bug 122458 java.lang.StringIndexOutOfBoundsException when compiling (build no.: 20051220093604)
|
This exception occurs using the ajdt eclipse plugin when compiling a project the first time I add the ajdt nature. There are no aspects defined in the project. I suppose the exception occurs when compiling a class (sorry I can't post the entire source code) with this signature: public class FixedWidthParser<T> extends TabularDataParser<T> The only noticeable things about this class are the presence of an inherited type parameter (and redefined with same name) some custom annotations on methods and a varags on a method parameter, but all of this things are present on other classes in the same project that AspectJ apprently compiles well (I'm not sure about the fact it compiles them). Hope I helped you with this clues, here's the complete stacktrace. java.lang.StringIndexOutOfBoundsException at java.lang.String.substring(Unknown Source) at org.aspectj.weaver.TypeFactory.createTypeFromSignature(TypeFactory.java:86) at org.aspectj.weaver.TypeFactory.createTypeFromSignature(TypeFactory.java:116) at org.aspectj.weaver.UnresolvedType.forSignature(UnresolvedType.java:430) at org.aspectj.weaver.UnresolvedType.makeArray(UnresolvedType.java:286) at org.aspectj.ajdt.internal.compiler.lookup.EclipseFactory.fromBinding(EclipseFactory.java:214) at org.aspectj.ajdt.internal.compiler.lookup.EclipseFactory.makeResolvedMember(EclipseFactory.java:516) at org.aspectj.ajdt.internal.compiler.lookup.EclipseFactory.makeResolvedMember(EclipseFactory.java:494) at org.aspectj.ajdt.internal.compiler.lookup.EclipseFactory.makeResolvedMember(EclipseFactory.java:451) at org.aspectj.ajdt.internal.core.builder.AsmHierarchyBuilder.genBytecodeInfo(AsmHierarchyBuilder.java:525) at org.aspectj.ajdt.internal.core.builder.AsmHierarchyBuilder.visit(AsmHierarchyBuilder.java:400) 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: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:142) at org.aspectj.ajdt.internal.core.builder.AsmHierarchyBuilder.buildStructureForCompilationUnit(AsmHierarchyBuilder.java:82) at org.aspectj.ajdt.internal.compiler.lookup.EclipseFactory.finishedCompilationUnit(EclipseFactory.java:926) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.afterProcessing(AjCompilerAdapter.java:195) at org.aspectj.ajdt.internal.compiler.CompilerAdapter.ajc$afterReturning$org_aspectj_ajdt_internal_compiler_CompilerAdapter$4$6b855184(CompilerAdapter.aj:89) at org.aspectj.org.eclipse.jdt.internal.compiler.Compiler.process(Compiler.java:528) at org.aspectj.org.eclipse.jdt.internal.compiler.Compiler.compile(Compiler.java:329) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.performCompilation(AjBuildManager.java:811) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.doBuild(AjBuildManager.java:230) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.batchBuild(AjBuildManager.java:156) at org.aspectj.ajde.internal.CompilerAdapter.compile(CompilerAdapter.java:122) at org.aspectj.ajde.internal.AspectJBuildManager$CompilerThread.run(AspectJBuildManager.java:191) StringIndexOutOfBoundsException thrown: String index out of range: -2
|
resolved fixed
|
24a785f
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-01-10T09:47:15Z | 2006-01-02T16:40:00Z |
weaver/src/org/aspectj/weaver/TypeFactory.java
|
/* *******************************************************************
* Copyright (c) 2005 Contributors.
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Eclipse Public License v1.0
* which accompanies this distribution and is available at
* http://eclipse.org/legal/epl-v10.html
*
* Contributors:
* Adrian Colyer Initial implementation
* ******************************************************************/
package org.aspectj.weaver;
import java.util.ArrayList;
import java.util.List;
import org.aspectj.weaver.UnresolvedType.TypeKind;
/**
* @author colyer
*
*/
public class TypeFactory {
/**
* Create a parameterized version of a generic type.
* @param aGenericType
* @param someTypeParameters note, in the case of an inner type of a parameterized type,
* this parameter may legitimately be null
* @param inAWorld
* @return
*/
public static ReferenceType createParameterizedType(
ResolvedType aBaseType,
UnresolvedType[] someTypeParameters,
World inAWorld
) {
ResolvedType baseType = aBaseType;
if (!aBaseType.isGenericType()) {
// try and find the generic type...
if (someTypeParameters != null && someTypeParameters.length>0) {
if (!aBaseType.isRawType()) throw new IllegalStateException("Expecting raw type");
baseType = baseType.getGenericType();
if (baseType == null) throw new IllegalStateException("Raw type does not have generic type set");
} // else if someTypeParameters is null, then the base type is allowed to be non-generic, it's an inner
}
ResolvedType[] resolvedParameters = inAWorld.resolve(someTypeParameters);
ReferenceType pType = new ReferenceType(baseType,resolvedParameters,inAWorld);
pType.setSourceContext(aBaseType.getSourceContext());
return (ReferenceType) pType.resolve(inAWorld);
}
/**
* Create an *unresolved* parameterized version of a generic type.
*/
public static UnresolvedType createUnresolvedParameterizedType(String sig,String erasuresig,UnresolvedType[] arguments) {
return new UnresolvedType(sig,erasuresig,arguments);
}
public static ReferenceType createRawType(
ResolvedType aBaseType,
World inAWorld
) {
if (aBaseType.isRawType()) return (ReferenceType) aBaseType;
if (!aBaseType.isGenericType()) {
if (!aBaseType.isRawType()) throw new IllegalStateException("Expecting generic type");
}
ReferenceType rType = new ReferenceType(aBaseType,inAWorld);
rType.setSourceContext(aBaseType.getSourceContext());
return (ReferenceType) rType.resolve(inAWorld);
}
/**
* Used by UnresolvedType.read, creates a type from a full signature.
* @param signature
* @return
*/
public static UnresolvedType createTypeFromSignature(String signature) {
if (signature.equals(ResolvedType.MISSING_NAME)) return ResolvedType.MISSING;
if (signature.startsWith(ResolvedType.PARAMETERIZED_TYPE_IDENTIFIER)) {
// parameterized type, calculate signature erasure and type parameters
// (see pr112458) It is possible for a parameterized type to have *no* type parameters visible in its signature.
// This happens for an inner type of a parameterized type which simply inherits the type parameters
// of its parent. In this case it is parameterized but theres no < in the signature.
int startOfParams = signature.indexOf('<');
int endOfParams = signature.lastIndexOf('>');
if (startOfParams==-1) {
// Should be an inner type of a parameterized type - could assert there is a '$' in the signature....
String signatureErasure = "L" + signature.substring(1);
UnresolvedType[] typeParams = new UnresolvedType[0];
return new UnresolvedType(signature,signatureErasure,typeParams);
} else {
String signatureErasure = "L" + signature.substring(1,startOfParams) + ";";
UnresolvedType[] typeParams = createTypeParams(signature.substring(startOfParams +1, endOfParams));
return new UnresolvedType(signature,signatureErasure,typeParams);
}
} else if (signature.equals("?")){
UnresolvedType ret = UnresolvedType.SOMETHING;
ret.typeKind = TypeKind.WILDCARD;
return ret;
} else if(signature.startsWith("+")) {
// ? extends ...
UnresolvedType bound = UnresolvedType.forSignature(signature.substring(1));
UnresolvedType ret = new UnresolvedType(signature);
ret.typeKind = TypeKind.WILDCARD;
ret.setUpperBound(bound);
return ret;
} else if (signature.startsWith("-")) {
// ? super ...
UnresolvedType bound = UnresolvedType.forSignature(signature.substring(1));
UnresolvedType ret = new UnresolvedType(signature);
ret.typeKind = TypeKind.WILDCARD;
ret.setLowerBound(bound);
return ret;
} else if (signature.startsWith("T")) {
String typeVariableName = signature.substring(1);
if (typeVariableName.endsWith(";")) {
typeVariableName = typeVariableName.substring(0, typeVariableName.length() -1);
}
return new UnresolvedTypeVariableReferenceType(new TypeVariable(typeVariableName));
} else if (signature.startsWith("[")) {
int dims = 0;
while (signature.charAt(dims)=='[') dims++;
UnresolvedType componentType = createTypeFromSignature(signature.substring(dims));
return new UnresolvedType(signature,
signature.substring(0,dims)+componentType.getErasureSignature());
} else if (signature.length()==1) { // could be a primitive
switch (signature.charAt(0)) {
case 'V': return ResolvedType.VOID;
case 'Z': return ResolvedType.BOOLEAN;
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 'S': return ResolvedType.SHORT;
}
}
return new UnresolvedType(signature);
}
private static UnresolvedType[] createTypeParams(String typeParameterSpecification) {
String remainingToProcess = typeParameterSpecification;
List types = new ArrayList();
while(!remainingToProcess.equals("")) {
int endOfSig = 0;
int anglies = 0;
boolean sigFound = false;
for (endOfSig = 0; (endOfSig < remainingToProcess.length()) && !sigFound; endOfSig++) {
char thisChar = remainingToProcess.charAt(endOfSig);
switch(thisChar) {
case '<' : anglies++; break;
case '>' : anglies--; break;
case ';' :
if (anglies == 0) {
sigFound = true;
break;
}
}
}
types.add(createTypeFromSignature(remainingToProcess.substring(0,endOfSig)));
remainingToProcess = remainingToProcess.substring(endOfSig);
}
UnresolvedType[] typeParams = new UnresolvedType[types.size()];
types.toArray(typeParams);
return typeParams;
}
}
|
122,417 |
Bug 122417 [waiting-on-website-doc-refresh] Typo in org.aspectj.lang.JoinPoint String constant symbolic name
|
Methinks the n_a_m_e of the preinitialization constant is misspelled JoinPoint.PREINTIALIZATION is lacking an "I" between the N and the T JoinPoint.PREINITIALIZATION might be the correct version Note: The value of the constant ("preinitialization") is spelled correctly. Sorry for the inconvenience. Harald
|
resolved fixed
|
a9ef1b0
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-01-10T16:19:56Z | 2005-12-31T09:06:40Z |
runtime/src/org/aspectj/lang/JoinPoint.java
|
/* *******************************************************************
* Copyright (c) 1999-2001 Xerox Corporation,
* 2002 Palo Alto Research Center, Incorporated (PARC).
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* Xerox/PARC initial implementation
* ******************************************************************/
package org.aspectj.lang;
import org.aspectj.lang.reflect.SourceLocation;
/**
* <p>Provides reflective access to both the state available at a join point and
* static information about it. This information is available from the body
* of advice using the special form <code>thisJoinPoint</code>. The primary
* use of this reflective information is for tracing and logging applications.
* </p>
*
* <pre>
* aspect Logging {
* before(): within(com.bigboxco..*) && execution(public * *(..)) {
* System.err.println("entering: " + thisJoinPoint);
* System.err.println(" w/args: " + thisJoinPoint.getArgs());
* System.err.println(" at: " + thisJoinPoint.getSourceLocation());
* }
* }
* </pre>
*/
public interface JoinPoint {
String toString();
/**
* Returns an abbreviated string representation of the join point.
*/
String toShortString();
/**
* Returns an extended string representation of the join point.
*/
String toLongString();
/**
* <p> Returns the currently executing object. This will always be
* the same object as that matched by the <code>this</code> pointcut
* designator. Unless you specifically need this reflective access,
* you should use the <code>this</code> pointcut designator to
* get at this object for better static typing and performance.</p>
*
* <p> Returns null when there is no currently executing object available.
* This includes all join points that occur in a static context.</p>
*/
Object getThis();
/**
* <p> Returns the target object. This will always be
* the same object as that matched by the <code>target</code> pointcut
* designator. Unless you specifically need this reflective access,
* you should use the <code>target</code> pointcut designator to
* get at this object for better static typing and performance.</p>
*
* <p> Returns null when there is no target object.</p>
*/
Object getTarget();
/**
* <p>Returns the arguments at this join point.</p>
*/
Object[] getArgs();
/** Returns the signature at the join point.
*
* <code>getStaticPart().getSignature()</code> returns the same object
*/
Signature getSignature();
/** <p>Returns the source location corresponding to the join point.</p>
*
* <p>If there is no source location available, returns null.</p>
*
* <p>Returns the SourceLocation of the defining class for default constructors.</p>
*
* <p> <code>getStaticPart().getSourceLocation()</code> returns the same object. </p>
*/
SourceLocation getSourceLocation();
/** Returns a String representing the kind of join point. This
* String is guaranteed to be
* interned. <code>getStaticPart().getKind()</code> returns
* the same object.
*/
String getKind();
/**
* <p>This helper object contains only the static information about a join point.
* It is available from the <code>JoinPoint.getStaticPart()</code> method, and
* can be accessed separately within advice using the special form
* <code>thisJoinPointStaticPart</code>.</p>
*
* <p>If you are only interested in the static information about a join point,
* you should access it through this type for the best performance. This
* is particularly useful for library methods that want to do serious
* manipulations of this information, i.e.</p>
*
* <pre>
* public class LoggingUtils {
* public static void prettyPrint(JoinPoint.StaticPart jp) {
* ...
* }
* }
*
* aspect Logging {
* before(): ... { LoggingUtils.prettyPrint(thisJoinPointStaticPart); }
* }
* </pre>
*
* @see JoinPoint#getStaticPart()
*/
public interface StaticPart {
/** Returns the signature at the join point. */
Signature getSignature();
/** <p>Returns the source location corresponding to the join point.</p>
*
* <p>If there is no source location available, returns null.</p>
*
* <p>Returns the SourceLocation of the defining class for default constructors.</p>
*/
SourceLocation getSourceLocation();
/** <p> Returns a String representing the kind of join point. This String
* is guaranteed to be interned</p>
*/
String getKind();
String toString();
/**
* Returns an abbreviated string representation of the join point
*/
String toShortString();
/**
* Returns an extended string representation of the join point
*/
String toLongString();
}
public interface EnclosingStaticPart extends StaticPart {}
/**
* Returns an object that encapsulates the static parts of this join point.
*/
StaticPart getStaticPart();
/**
* The legal return values from getKind()
*/
static String METHOD_EXECUTION = "method-execution";
static String METHOD_CALL = "method-call";
static String CONSTRUCTOR_EXECUTION = "constructor-execution";
static String CONSTRUCTOR_CALL = "constructor-call";
static String FIELD_GET = "field-get";
static String FIELD_SET = "field-set";
static String STATICINITIALIZATION = "staticinitialization";
static String PREINTIALIZATION = "preinitialization";
static String INITIALIZATION = "initialization";
static String EXCEPTION_HANDLER = "exception-handler";
static String ADVICE_EXECUTION = "adviceexecution";
}
|
122,417 |
Bug 122417 [waiting-on-website-doc-refresh] Typo in org.aspectj.lang.JoinPoint String constant symbolic name
|
Methinks the n_a_m_e of the preinitialization constant is misspelled JoinPoint.PREINTIALIZATION is lacking an "I" between the N and the T JoinPoint.PREINITIALIZATION might be the correct version Note: The value of the constant ("preinitialization") is spelled correctly. Sorry for the inconvenience. Harald
|
resolved fixed
|
a9ef1b0
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-01-10T16:19:56Z | 2005-12-31T09:06:40Z |
weaver/src/org/aspectj/weaver/Shadow.java
|
/* *******************************************************************
* Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC).
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* PARC initial implementation
* ******************************************************************/
package org.aspectj.weaver;
import java.io.DataInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import org.aspectj.asm.IRelationship;
import org.aspectj.bridge.IMessage;
import org.aspectj.bridge.ISourceLocation;
import org.aspectj.bridge.Message;
import org.aspectj.bridge.MessageUtil;
import org.aspectj.bridge.WeaveMessage;
import org.aspectj.lang.JoinPoint;
import org.aspectj.util.PartialOrder;
import org.aspectj.util.TypeSafeEnum;
import org.aspectj.weaver.ast.Var;
import org.aspectj.weaver.bcel.BcelAdvice;
/*
* The superclass of anything representing a the shadow of a join point. A shadow represents
* some bit of code, and encompasses both entry and exit from that code. All shadows have a kind
* and a signature.
*/
public abstract class Shadow {
// every Shadow has a unique id, doesn't matter if it wraps...
private static int nextShadowID = 100; // easier to spot than zero.
private final Kind kind;
private final Member signature;
private Member matchingSignature;
private ResolvedMember resolvedSignature;
protected final Shadow enclosingShadow;
protected List mungers = new ArrayList(1);
public int shadowId = nextShadowID++; // every time we build a shadow, it gets a new id
// ----
protected Shadow(Kind kind, Member signature, Shadow enclosingShadow) {
this.kind = kind;
this.signature = signature;
this.enclosingShadow = enclosingShadow;
}
// ----
public abstract World getIWorld();
public List /*ShadowMunger*/ getMungers() {
return mungers;
}
/**
* could this(*) pcd ever match
*/
public final boolean hasThis() {
if (getKind().neverHasThis()) {
return false;
} else if (getKind().isEnclosingKind()) {
return !getSignature().isStatic();
} else if (enclosingShadow == null) {
return false;
} else {
return enclosingShadow.hasThis();
}
}
/**
* the type of the this object here
*
* @throws IllegalStateException if there is no this here
*/
public final UnresolvedType getThisType() {
if (!hasThis()) throw new IllegalStateException("no this");
if (getKind().isEnclosingKind()) {
return getSignature().getDeclaringType();
} else {
return enclosingShadow.getThisType();
}
}
/**
* a var referencing this
*
* @throws IllegalStateException if there is no target here
*/
public abstract Var getThisVar();
/**
* could target(*) pcd ever match
*/
public final boolean hasTarget() {
if (getKind().neverHasTarget()) {
return false;
} else if (getKind().isTargetSameAsThis()) {
return hasThis();
} else {
return !getSignature().isStatic();
}
}
/**
* the type of the target object here
*
* @throws IllegalStateException if there is no target here
*/
public final UnresolvedType getTargetType() {
if (!hasTarget()) throw new IllegalStateException("no target");
return getSignature().getDeclaringType();
}
/**
* a var referencing the target
*
* @throws IllegalStateException if there is no target here
*/
public abstract Var getTargetVar();
public UnresolvedType[] getArgTypes() {
if (getKind() == FieldSet) return new UnresolvedType[] { getSignature().getReturnType() };
return getSignature().getParameterTypes();
}
public UnresolvedType[] getGenericArgTypes() {
if (getKind() == FieldSet) return new UnresolvedType[] { getResolvedSignature().getGenericReturnType() };
return getResolvedSignature().getGenericParameterTypes();
}
public UnresolvedType getArgType(int arg) {
if (getKind() == FieldSet) return getSignature().getReturnType();
return getSignature().getParameterTypes()[arg];
}
public int getArgCount() {
if (getKind() == FieldSet) return 1;
return getSignature()
.getParameterTypes().length;
}
public abstract UnresolvedType getEnclosingType();
public abstract Var getArgVar(int i);
public abstract Var getThisJoinPointVar();
public abstract Var getThisJoinPointStaticPartVar();
public abstract Var getThisEnclosingJoinPointStaticPartVar();
// annotation variables
public abstract Var getKindedAnnotationVar(UnresolvedType forAnnotationType);
public abstract Var getWithinAnnotationVar(UnresolvedType forAnnotationType);
public abstract Var getWithinCodeAnnotationVar(UnresolvedType forAnnotationType);
public abstract Var getThisAnnotationVar(UnresolvedType forAnnotationType);
public abstract Var getTargetAnnotationVar(UnresolvedType forAnnotationType);
public abstract Var getArgAnnotationVar(int i, UnresolvedType forAnnotationType);
public abstract Member getEnclosingCodeSignature();
/** returns the kind of shadow this is, representing what happens under this shadow
*/
public Kind getKind() {
return kind;
}
/** returns the signature of the thing under this shadow
*/
public Member getSignature() {
return signature;
}
/**
* returns the signature of the thing under this shadow, with
* any synthetic arguments removed
*/
public Member getMatchingSignature() {
return matchingSignature != null ? matchingSignature : signature;
}
public void setMatchingSignature(Member member) {
this.matchingSignature = member;
}
/**
* returns the resolved signature of the thing under this shadow
*
*/
public ResolvedMember getResolvedSignature() {
if (resolvedSignature == null) {
resolvedSignature = signature.resolve(getIWorld());
}
return resolvedSignature;
}
public UnresolvedType getReturnType() {
if (kind == ConstructorCall) return getSignature().getDeclaringType();
else if (kind == FieldSet) return ResolvedType.VOID;
return getResolvedSignature().getGenericReturnType();
}
/**
* These names are the ones that will be returned by thisJoinPoint.getKind()
* Those need to be documented somewhere
*/
public static final Kind MethodCall = new Kind(JoinPoint.METHOD_CALL, 1, true);
public static final Kind ConstructorCall = new Kind(JoinPoint.CONSTRUCTOR_CALL, 2, true);
public static final Kind MethodExecution = new Kind(JoinPoint.METHOD_EXECUTION, 3, false);
public static final Kind ConstructorExecution = new Kind(JoinPoint.CONSTRUCTOR_EXECUTION, 4, false);
public static final Kind FieldGet = new Kind(JoinPoint.FIELD_GET, 5, true);
public static final Kind FieldSet = new Kind(JoinPoint.FIELD_SET, 6, true);
public static final Kind StaticInitialization = new Kind(JoinPoint.STATICINITIALIZATION, 7, false);
public static final Kind PreInitialization = new Kind(JoinPoint.PREINTIALIZATION, 8, false);
public static final Kind AdviceExecution = new Kind(JoinPoint.ADVICE_EXECUTION, 9, false);
public static final Kind Initialization = new Kind(JoinPoint.INITIALIZATION, 10, false);
public static final Kind ExceptionHandler = new Kind(JoinPoint.EXCEPTION_HANDLER, 11, true);
public static final int MAX_SHADOW_KIND = 11;
public static final Kind[] SHADOW_KINDS = new Kind[] {
MethodCall, ConstructorCall, MethodExecution, ConstructorExecution,
FieldGet, FieldSet, StaticInitialization, PreInitialization,
AdviceExecution, Initialization, ExceptionHandler,
};
public static final Set ALL_SHADOW_KINDS;
static {
HashSet aSet = new HashSet();
for (int i = 0; i < SHADOW_KINDS.length; i++) {
aSet.add(SHADOW_KINDS[i]);
}
ALL_SHADOW_KINDS = Collections.unmodifiableSet(aSet);
}
/** A type-safe enum representing the kind of shadows
*/
public static final class Kind extends TypeSafeEnum {
// private boolean argsOnStack; //XXX unused
public Kind(String name, int key, boolean argsOnStack) {
super(name, key);
// this.argsOnStack = argsOnStack;
}
public String toLegalJavaIdentifier() {
return getName().replace('-', '_');
}
public boolean argsOnStack() {
return !isTargetSameAsThis();
}
// !!! this is false for handlers!
public boolean allowsExtraction() {
return true;
}
// XXX revisit along with removal of priorities
public boolean hasHighPriorityExceptions() {
return !isTargetSameAsThis();
}
/**
* These shadow kinds have return values that can be bound in
* after returning(Dooberry doo) advice.
* @return
*/
public boolean hasReturnValue() {
return
this == MethodCall ||
this == ConstructorCall ||
this == MethodExecution ||
this == FieldGet ||
this == AdviceExecution;
}
/**
* These are all the shadows that contains other shadows within them and
* are often directly associated with methods.
*/
public boolean isEnclosingKind() {
return this == MethodExecution || this == ConstructorExecution ||
this == AdviceExecution || this == StaticInitialization
|| this == Initialization;
}
public boolean isTargetSameAsThis() {
return this == MethodExecution
|| this == ConstructorExecution
|| this == StaticInitialization
|| this == PreInitialization
|| this == AdviceExecution
|| this == Initialization;
}
public boolean neverHasTarget() {
return this == ConstructorCall
|| this == ExceptionHandler
|| this == PreInitialization
|| this == StaticInitialization;
}
public boolean neverHasThis() {
return this == PreInitialization
|| this == StaticInitialization;
}
public String getSimpleName() {
int dash = getName().lastIndexOf('-');
if (dash == -1) return getName();
else return getName().substring(dash+1);
}
public static Kind read(DataInputStream s) throws IOException {
int key = s.readByte();
switch(key) {
case 1: return MethodCall;
case 2: return ConstructorCall;
case 3: return MethodExecution;
case 4: return ConstructorExecution;
case 5: return FieldGet;
case 6: return FieldSet;
case 7: return StaticInitialization;
case 8: return PreInitialization;
case 9: return AdviceExecution;
case 10: return Initialization;
case 11: return ExceptionHandler;
}
throw new BCException("unknown kind: " + key);
}
}
/**
* Only does the check if the munger requires it (@AJ aspects don't)
*
* @param munger
* @return
*/
protected boolean checkMunger(ShadowMunger munger) {
if (munger.mustCheckExceptions()) {
for (Iterator i = munger.getThrownExceptions().iterator(); i.hasNext(); ) {
if (!checkCanThrow(munger, (ResolvedType)i.next() )) return false;
}
}
return true;
}
protected boolean checkCanThrow(ShadowMunger munger, ResolvedType resolvedTypeX) {
if (getKind() == ExceptionHandler) {
//XXX much too lenient rules here, need to walk up exception handlers
return true;
}
if (!isDeclaredException(resolvedTypeX, getSignature())) {
getIWorld().showMessage(IMessage.ERROR,
WeaverMessages.format(WeaverMessages.CANT_THROW_CHECKED,resolvedTypeX,this), // from advice in \'" + munger. + "\'",
getSourceLocation(), munger.getSourceLocation());
}
return true;
}
private boolean isDeclaredException(
ResolvedType resolvedTypeX,
Member member)
{
ResolvedType[] excs = getIWorld().resolve(member.getExceptions(getIWorld()));
for (int i=0, len=excs.length; i < len; i++) {
if (excs[i].isAssignableFrom(resolvedTypeX)) return true;
}
return false;
}
public void addMunger(ShadowMunger munger) {
if (checkMunger(munger)) this.mungers.add(munger);
}
public final void implement() {
sortMungers();
if (mungers == null) return;
prepareForMungers();
implementMungers();
}
private void sortMungers() {
List sorted = PartialOrder.sort(mungers);
// Bunch of code to work out whether to report xlints for advice that isn't ordered at this Joinpoint
possiblyReportUnorderedAdvice(sorted);
if (sorted == null) {
// this means that we have circular dependencies
for (Iterator i = mungers.iterator(); i.hasNext(); ) {
ShadowMunger m = (ShadowMunger)i.next();
getIWorld().getMessageHandler().handleMessage(
MessageUtil.error(
WeaverMessages.format(WeaverMessages.CIRCULAR_DEPENDENCY,this), m.getSourceLocation()));
}
}
mungers = sorted;
}
// not quite optimal... but the xlint is ignore by default
private void possiblyReportUnorderedAdvice(List sorted) {
if (sorted!=null && getIWorld().getLint().unorderedAdviceAtShadow.isEnabled() && mungers.size()>1) {
// Stores a set of strings of the form 'aspect1:aspect2' which indicates there is no
// precedence specified between the two aspects at this shadow.
Set clashingAspects = new HashSet();
int max = mungers.size();
// Compare every pair of advice mungers
for (int i = max-1; i >=0; i--) {
for (int j=0; j<i; j++) {
Object a = mungers.get(i);
Object b = mungers.get(j);
// Make sure they are the right type
if (a instanceof BcelAdvice && b instanceof BcelAdvice) {
BcelAdvice adviceA = (BcelAdvice)a;
BcelAdvice adviceB = (BcelAdvice)b;
if (!adviceA.concreteAspect.equals(adviceB.concreteAspect)) {
AdviceKind adviceKindA = adviceA.getKind();
AdviceKind adviceKindB = adviceB.getKind();
// make sure they are the nice ones (<6) and not any synthetic advice ones we
// create to support other features of the language.
if (adviceKindA.getKey()<(byte)6 && adviceKindB.getKey()<(byte)6 &&
adviceKindA.getPrecedence() == adviceKindB.getPrecedence()) {
// Ask the world if it knows about precedence between these
Integer order = getIWorld().getPrecedenceIfAny(
adviceA.concreteAspect,
adviceB.concreteAspect);
if (order!=null &&
order.equals(new Integer(0))) {
String key = adviceA.getDeclaringAspect()+":"+adviceB.getDeclaringAspect();
String possibleExistingKey = adviceB.getDeclaringAspect()+":"+adviceA.getDeclaringAspect();
if (!clashingAspects.contains(possibleExistingKey)) clashingAspects.add(key);
}
}
}
}
}
}
for (Iterator iter = clashingAspects.iterator(); iter.hasNext();) {
String element = (String) iter.next();
String aspect1 = element.substring(0,element.indexOf(":"));
String aspect2 = element.substring(element.indexOf(":")+1);
getIWorld().getLint().unorderedAdviceAtShadow.signal(
new String[]{this.toString(),aspect1,aspect2},
this.getSourceLocation(),null);
}
}
}
/** Prepare the shadow for implementation. After this is done, the shadow
* should be in such a position that each munger simply needs to be implemented.
*/
protected void prepareForMungers() {
throw new RuntimeException("Generic shadows cannot be prepared");
}
/*
* Ensure we report a nice source location - particular in the case
* where the source info is missing (binary weave).
*/
private String beautifyLocation(ISourceLocation isl) {
StringBuffer nice = new StringBuffer();
if (isl==null || isl.getSourceFile()==null || isl.getSourceFile().getName().indexOf("no debug info available")!=-1) {
nice.append("no debug info available");
} else {
// can't use File.getName() as this fails when a Linux box encounters a path created on Windows and vice-versa
int takeFrom = isl.getSourceFile().getPath().lastIndexOf('/');
if (takeFrom == -1) {
takeFrom = isl.getSourceFile().getPath().lastIndexOf('\\');
}
nice.append(isl.getSourceFile().getPath().substring(takeFrom +1));
if (isl.getLine()!=0) nice.append(":").append(isl.getLine());
}
return nice.toString();
}
/*
* Report a message about the advice weave that has occurred. Some messing about
* to make it pretty ! This code is just asking for an NPE to occur ...
*/
private void reportWeavingMessage(ShadowMunger munger) {
Advice advice = (Advice)munger;
AdviceKind aKind = advice.getKind();
// Only report on interesting advice kinds ...
if (aKind == null || advice.getConcreteAspect()==null) {
// We suspect someone is programmatically driving the weaver
// (e.g. IdWeaveTestCase in the weaver testcases)
return;
}
if (!( aKind.equals(AdviceKind.Before) ||
aKind.equals(AdviceKind.After) ||
aKind.equals(AdviceKind.AfterReturning) ||
aKind.equals(AdviceKind.AfterThrowing) ||
aKind.equals(AdviceKind.Around) ||
aKind.equals(AdviceKind.Softener))) return;
String description = advice.getKind().toString();
String advisedType = this.getEnclosingType().getName();
String advisingType= advice.getConcreteAspect().getName();
Message msg = null;
if (advice.getKind().equals(AdviceKind.Softener)) {
msg = WeaveMessage.constructWeavingMessage(
WeaveMessage.WEAVEMESSAGE_SOFTENS,
new String[]{advisedType,beautifyLocation(getSourceLocation()),
advisingType,beautifyLocation(munger.getSourceLocation())},
advisedType,
advisingType);
} else {
boolean runtimeTest = ((BcelAdvice)advice).hasDynamicTests();
String joinPointDescription = this.toString();
msg = WeaveMessage.constructWeavingMessage(WeaveMessage.WEAVEMESSAGE_ADVISES,
new String[]{ joinPointDescription, advisedType, beautifyLocation(getSourceLocation()),
description,
advisingType,beautifyLocation(munger.getSourceLocation()),
(runtimeTest?" [with runtime test]":"")},
advisedType,
advisingType);
// Boolean.toString(runtimeTest)});
}
getIWorld().getMessageHandler().handleMessage(msg);
}
public IRelationship.Kind determineRelKind(ShadowMunger munger) {
AdviceKind ak = ((Advice)munger).getKind();
if (ak.getKey()==AdviceKind.Before.getKey())
return IRelationship.Kind.ADVICE_BEFORE;
else if (ak.getKey()==AdviceKind.After.getKey())
return IRelationship.Kind.ADVICE_AFTER;
else if (ak.getKey()==AdviceKind.AfterThrowing.getKey())
return IRelationship.Kind.ADVICE_AFTERTHROWING;
else if (ak.getKey()==AdviceKind.AfterReturning.getKey())
return IRelationship.Kind.ADVICE_AFTERRETURNING;
else if (ak.getKey()==AdviceKind.Around.getKey())
return IRelationship.Kind.ADVICE_AROUND;
else if (ak.getKey()==AdviceKind.CflowEntry.getKey() ||
ak.getKey()==AdviceKind.CflowBelowEntry.getKey() ||
ak.getKey()==AdviceKind.InterInitializer.getKey() ||
ak.getKey()==AdviceKind.PerCflowEntry.getKey() ||
ak.getKey()==AdviceKind.PerCflowBelowEntry.getKey() ||
ak.getKey()==AdviceKind.PerThisEntry.getKey() ||
ak.getKey()==AdviceKind.PerTargetEntry.getKey() ||
ak.getKey()==AdviceKind.Softener.getKey() ||
ak.getKey()==AdviceKind.PerTypeWithinEntry.getKey()) {
//System.err.println("Dont want a message about this: "+ak);
return null;
}
throw new RuntimeException("Shadow.determineRelKind: What the hell is it? "+ak);
}
/** Actually implement the (non-empty) mungers associated with this shadow */
private void implementMungers() {
World world = getIWorld();
for (Iterator iter = mungers.iterator(); iter.hasNext();) {
ShadowMunger munger = (ShadowMunger) iter.next();
munger.implementOn(this);
if (world.getCrossReferenceHandler() != null) {
world.getCrossReferenceHandler().addCrossReference(
munger.getSourceLocation(), // What is being applied
this.getSourceLocation(), // Where is it being applied
determineRelKind(munger), // What kind of advice?
((BcelAdvice)munger).hasDynamicTests() // Is a runtime test being stuffed in the code?
);
}
// TAG: WeavingMessage
if (!getIWorld().getMessageHandler().isIgnoring(IMessage.WEAVEINFO)) {
reportWeavingMessage(munger);
}
if (world.getModel() != null) {
//System.err.println("munger: " + munger + " on " + this);
AsmRelationshipProvider.getDefault().adviceMunger(world.getModel(), this, munger);
}
}
}
public String makeReflectiveFactoryString() {
return null; //XXX
}
public abstract ISourceLocation getSourceLocation();
// ---- utility
public String toString() {
return getKind() + "(" + getSignature() + ")"; // + getSourceLines();
}
public String toResolvedString(World world) {
return getKind() + "(" + world.resolve(getSignature()).toGenericString() + ")";
}
}
|
122,248 |
Bug 122248 BUG for ajdt_1.3_for_eclipse_3.1.zip
|
Hi !! I use ajdt_1.3_for_eclipse_3.1.zip with eclipse 3.1.1 and fick this error when the eclipse try to make the workbrench: java.lang.IllegalStateException at org.aspectj.weaver.TypeFactory.createParameterizedType(TypeFactory.java:42) at org.aspectj.weaver.bcel.BcelGenericSignatureToTypeXConverter.classTypeSignature2TypeX(BcelGenericSignatureToTypeXConverter.java:82) at org.aspectj.weaver.bcel.BcelGenericSignatureToTypeXConverter.classTypeSignature2TypeX(BcelGenericSignatureToTypeXConverter.java:42) at org.aspectj.weaver.bcel.BcelObjectType.unpackGenericSignature(BcelObjectType.java:657) at org.aspectj.weaver.bcel.BcelObjectType.getSuperclass(BcelObjectType.java:181) at org.aspectj.weaver.ReferenceType.getSuperclass(ReferenceType.java:514) at org.aspectj.weaver.bcel.BcelWeaver.weaveParentsFor(BcelWeaver.java:1192) at org.aspectj.weaver.bcel.BcelWeaver.weave(BcelWeaver.java:1047) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.weave(AjCompilerAdapter.java:300) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.afterCompiling(AjCompilerAdapter.java:178) at org.aspectj.ajdt.internal.compiler.CompilerAdapter.ajc$afterReturning$org_aspectj_ajdt_internal_compiler_CompilerAdapter$2$f9cc9ca0(CompilerAdapter.aj:70) at org.aspectj.org.eclipse.jdt.internal.compiler.Compiler.compile(Compiler.java:367) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.performCompilation(AjBuildManager.java:811) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.doBuild(AjBuildManager.java:230) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.batchBuild(AjBuildManager.java:156) at org.aspectj.ajde.internal.CompilerAdapter.compile(CompilerAdapter.java:122) at org.aspectj.ajde.internal.AspectJBuildManager$CompilerThread.run(AspectJBuildManager.java:191) IllegalStateException thrown: Expecting raw type
|
resolved fixed
|
3f77e75
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-01-15T21:33:55Z | 2005-12-28T14:26:40Z |
weaver/src/org/aspectj/weaver/bcel/BcelField.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.util.HashSet;
import java.util.Iterator;
import java.util.List;
import org.aspectj.apache.bcel.classfile.Attribute;
import org.aspectj.apache.bcel.classfile.Field;
import org.aspectj.apache.bcel.classfile.GenericSignatureParser;
import org.aspectj.apache.bcel.classfile.Signature;
import org.aspectj.apache.bcel.classfile.Synthetic;
import org.aspectj.apache.bcel.classfile.annotation.Annotation;
import org.aspectj.weaver.AjAttribute;
import org.aspectj.weaver.AnnotationX;
import org.aspectj.weaver.BCException;
import org.aspectj.weaver.ResolvedMemberImpl;
import org.aspectj.weaver.ResolvedType;
import org.aspectj.weaver.UnresolvedType;
import org.aspectj.weaver.World;
import org.aspectj.weaver.bcel.BcelGenericSignatureToTypeXConverter.GenericSignatureFormatException;
final class BcelField extends ResolvedMemberImpl {
private static int AccSynthetic = 0x1000;
private Field field;
private boolean isAjSynthetic;
private boolean isSynthetic = false;
private AnnotationX[] annotations;
private World world;
private BcelObjectType bcelObjectType;
private UnresolvedType genericFieldType = null;
private boolean unpackedGenericSignature = false;
BcelField(BcelObjectType declaringType, Field field) {
super(
FIELD,
declaringType.getResolvedTypeX(),
field.getAccessFlags(),
field.getName(),
field.getSignature());
this.field = field;
this.world = declaringType.getResolvedTypeX().getWorld();
this.bcelObjectType = declaringType;
unpackAttributes(world);
checkedExceptions = UnresolvedType.NONE;
}
// ----
private void unpackAttributes(World world) {
Attribute[] attrs = field.getAttributes();
List as = BcelAttributes.readAjAttributes(getDeclaringType().getClassName(),attrs, getSourceContext(world),world.getMessageHandler(),bcelObjectType.getWeaverVersionAttribute());
as.addAll(AtAjAttributes.readAj5FieldAttributes(field, this, world.resolve(getDeclaringType()), getSourceContext(world), world.getMessageHandler()));
for (Iterator iter = as.iterator(); iter.hasNext();) {
AjAttribute a = (AjAttribute) iter.next();
if (a instanceof AjAttribute.AjSynthetic) {
isAjSynthetic = true;
} else {
throw new BCException("weird field attribute " + a);
}
}
isAjSynthetic = false;
for (int i = attrs.length - 1; i >= 0; i--) {
if (attrs[i] instanceof Synthetic) isSynthetic = true;
}
// in 1.5, synthetic is a modifier, not an attribute
if ((field.getModifiers() & AccSynthetic) != 0) {
isSynthetic = true;
}
}
public boolean isAjSynthetic() {
return isAjSynthetic; // || getName().startsWith(NameMangler.PREFIX);
}
public boolean isSynthetic() {
return isSynthetic;
}
public boolean hasAnnotation(UnresolvedType ofType) {
ensureAnnotationTypesRetrieved();
for (Iterator iter = annotationTypes.iterator(); iter.hasNext();) {
ResolvedType aType = (ResolvedType) iter.next();
if (aType.equals(ofType)) return true;
}
return false;
}
public ResolvedType[] getAnnotationTypes() {
ensureAnnotationTypesRetrieved();
ResolvedType[] ret = new ResolvedType[annotationTypes.size()];
annotationTypes.toArray(ret);
return ret;
}
private void ensureAnnotationTypesRetrieved() {
if (annotationTypes == null) {
Annotation annos[] = field.getAnnotations();
annotationTypes = new HashSet();
annotations = new AnnotationX[annos.length];
for (int i = 0; i < annos.length; i++) {
Annotation annotation = annos[i];
ResolvedType rtx = world.resolve(UnresolvedType.forName(annotation.getTypeName()));
annotationTypes.add(rtx);
annotations[i] = new AnnotationX(annotation,world);
}
}
}
public void addAnnotation(AnnotationX annotation) {
ensureAnnotationTypesRetrieved();
// Add it to the set of annotations
int len = annotations.length;
AnnotationX[] ret = new AnnotationX[len+1];
System.arraycopy(annotations, 0, ret, 0, len);
ret[len] = annotation;
annotations = ret;
// Add it to the set of annotation types
annotationTypes.add(UnresolvedType.forName(annotation.getTypeName()).resolve(world));
// FIXME asc this call here suggests we are managing the annotations at
// too many levels, here in BcelField we keep a set and in the lower 'field'
// object we keep a set - we should think about reducing this to one
// level??
field.addAnnotation(annotation.getBcelAnnotation());
}
/**
* Unpack the generic signature attribute if there is one and we haven't already
* done so, then find the true field type of this field (eg. List<String>).
*/
public UnresolvedType getGenericReturnType() {
unpackGenericSignature();
return genericFieldType;
}
private void unpackGenericSignature() {
if (unpackedGenericSignature)
return;
unpackedGenericSignature = true;
String gSig = field.getGenericSignature();
if (gSig != null) {
// get from generic
Signature.FieldTypeSignature fts = new GenericSignatureParser().parseAsFieldSignature(gSig);
Signature.ClassSignature genericTypeSig = bcelObjectType.getGenericClassTypeSignature();
Signature.FormalTypeParameter[] parentFormals = bcelObjectType.getAllFormals();
Signature.FormalTypeParameter[] typeVars =
((genericTypeSig == null) ? new Signature.FormalTypeParameter[0] : genericTypeSig.formalTypeParameters);
Signature.FormalTypeParameter[] formals =
new Signature.FormalTypeParameter[parentFormals.length + typeVars.length];
// put method formal in front of type formals for overriding in
// lookup
System.arraycopy(typeVars, 0, formals, 0, typeVars.length);
System.arraycopy(parentFormals, 0, formals, typeVars.length,parentFormals.length);
try {
genericFieldType = BcelGenericSignatureToTypeXConverter
.fieldTypeSignature2TypeX(fts, formals, world);
} catch (GenericSignatureFormatException e) {
// development bug, fail fast with good info
throw new IllegalStateException(
"While determing the generic field type of "
+ this.toString() + " with generic signature "
+ gSig + " the following error was detected: "
+ e.getMessage());
}
} else {
genericFieldType = getReturnType();
}
}
}
|
122,248 |
Bug 122248 BUG for ajdt_1.3_for_eclipse_3.1.zip
|
Hi !! I use ajdt_1.3_for_eclipse_3.1.zip with eclipse 3.1.1 and fick this error when the eclipse try to make the workbrench: java.lang.IllegalStateException at org.aspectj.weaver.TypeFactory.createParameterizedType(TypeFactory.java:42) at org.aspectj.weaver.bcel.BcelGenericSignatureToTypeXConverter.classTypeSignature2TypeX(BcelGenericSignatureToTypeXConverter.java:82) at org.aspectj.weaver.bcel.BcelGenericSignatureToTypeXConverter.classTypeSignature2TypeX(BcelGenericSignatureToTypeXConverter.java:42) at org.aspectj.weaver.bcel.BcelObjectType.unpackGenericSignature(BcelObjectType.java:657) at org.aspectj.weaver.bcel.BcelObjectType.getSuperclass(BcelObjectType.java:181) at org.aspectj.weaver.ReferenceType.getSuperclass(ReferenceType.java:514) at org.aspectj.weaver.bcel.BcelWeaver.weaveParentsFor(BcelWeaver.java:1192) at org.aspectj.weaver.bcel.BcelWeaver.weave(BcelWeaver.java:1047) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.weave(AjCompilerAdapter.java:300) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.afterCompiling(AjCompilerAdapter.java:178) at org.aspectj.ajdt.internal.compiler.CompilerAdapter.ajc$afterReturning$org_aspectj_ajdt_internal_compiler_CompilerAdapter$2$f9cc9ca0(CompilerAdapter.aj:70) at org.aspectj.org.eclipse.jdt.internal.compiler.Compiler.compile(Compiler.java:367) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.performCompilation(AjBuildManager.java:811) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.doBuild(AjBuildManager.java:230) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.batchBuild(AjBuildManager.java:156) at org.aspectj.ajde.internal.CompilerAdapter.compile(CompilerAdapter.java:122) at org.aspectj.ajde.internal.AspectJBuildManager$CompilerThread.run(AspectJBuildManager.java:191) IllegalStateException thrown: Expecting raw type
|
resolved fixed
|
3f77e75
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-01-15T21:33:55Z | 2005-12-28T14:26:40Z |
weaver/src/org/aspectj/weaver/bcel/BcelMethod.java
|
/* *******************************************************************
* Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC).
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* PARC initial implementation
* ******************************************************************/
package org.aspectj.weaver.bcel;
import java.lang.reflect.Modifier;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import org.aspectj.apache.bcel.classfile.ExceptionTable;
import org.aspectj.apache.bcel.classfile.GenericSignatureParser;
import org.aspectj.apache.bcel.classfile.LocalVariable;
import org.aspectj.apache.bcel.classfile.LocalVariableTable;
import org.aspectj.apache.bcel.classfile.Method;
import org.aspectj.apache.bcel.classfile.Signature;
import org.aspectj.apache.bcel.classfile.Signature.TypeVariableSignature;
import org.aspectj.apache.bcel.classfile.annotation.Annotation;
import org.aspectj.bridge.ISourceLocation;
import org.aspectj.bridge.SourceLocation;
import org.aspectj.weaver.AjAttribute;
import org.aspectj.weaver.AnnotationX;
import org.aspectj.weaver.BCException;
import org.aspectj.weaver.ISourceContext;
import org.aspectj.weaver.ResolvedMemberImpl;
import org.aspectj.weaver.ResolvedPointcutDefinition;
import org.aspectj.weaver.ResolvedType;
import org.aspectj.weaver.ShadowMunger;
import org.aspectj.weaver.UnresolvedType;
import org.aspectj.weaver.World;
import org.aspectj.weaver.bcel.BcelGenericSignatureToTypeXConverter.GenericSignatureFormatException;
final class BcelMethod extends ResolvedMemberImpl {
private Method method;
private boolean isAjSynthetic;
private ShadowMunger associatedShadowMunger;
private ResolvedPointcutDefinition preResolvedPointcut; // used when ajc has pre-resolved the pointcut of some @Advice
// private ResolvedType[] annotationTypes = null;
private AnnotationX[] annotations = null;
private AjAttribute.EffectiveSignatureAttribute effectiveSignature;
private AjAttribute.MethodDeclarationLineNumberAttribute declarationLineNumber;
private World world;
private BcelObjectType bcelObjectType;
BcelMethod(BcelObjectType declaringType, Method method) {
super(
method.getName().equals("<init>") ? CONSTRUCTOR :
(method.getName().equals("<clinit>") ? STATIC_INITIALIZATION : METHOD),
declaringType.getResolvedTypeX(),
declaringType.isInterface()
? method.getAccessFlags() | Modifier.INTERFACE
: method.getAccessFlags(),
method.getName(),
method.getSignature());
this.method = method;
this.sourceContext = declaringType.getResolvedTypeX().getSourceContext();
this.world = declaringType.getResolvedTypeX().getWorld();
this.bcelObjectType = declaringType;
unpackJavaAttributes();
unpackAjAttributes(world);
}
// ----
private void unpackJavaAttributes() {
ExceptionTable exnTable = method.getExceptionTable();
checkedExceptions = (exnTable == null)
? UnresolvedType.NONE
: UnresolvedType.forNames(exnTable.getExceptionNames());
LocalVariableTable varTable = method.getLocalVariableTable();
int len = getArity();
if (varTable == null) {
this.parameterNames = Utility.makeArgNames(len);
} else {
UnresolvedType[] paramTypes = getParameterTypes();
String[] paramNames = new String[len];
int index = isStatic() ? 0 : 1;
for (int i = 0; i < len; i++) {
LocalVariable lv = varTable.getLocalVariable(index);
if (lv == null) {
paramNames[i] = "arg" + i;
} else {
paramNames[i] = lv.getName();
}
index += paramTypes[i].getSize();
}
this.parameterNames = paramNames;
}
}
private void unpackAjAttributes(World world) {
associatedShadowMunger = null;
List as = BcelAttributes.readAjAttributes(getDeclaringType().getClassName(),method.getAttributes(), getSourceContext(world),world.getMessageHandler(),bcelObjectType.getWeaverVersionAttribute());
processAttributes(world, as);
as = AtAjAttributes.readAj5MethodAttributes(method, this, world.resolve(getDeclaringType()), preResolvedPointcut,getSourceContext(world), world.getMessageHandler());
processAttributes(world,as);
}
private void processAttributes(World world, List as) {
for (Iterator iter = as.iterator(); iter.hasNext();) {
AjAttribute a = (AjAttribute) iter.next();
if (a instanceof AjAttribute.MethodDeclarationLineNumberAttribute) {
declarationLineNumber = (AjAttribute.MethodDeclarationLineNumberAttribute)a;
} else if (a instanceof AjAttribute.AdviceAttribute) {
associatedShadowMunger = ((AjAttribute.AdviceAttribute)a).reify(this, world);
// return;
} else if (a instanceof AjAttribute.AjSynthetic) {
isAjSynthetic = true;
} else if (a instanceof AjAttribute.EffectiveSignatureAttribute) {
//System.out.println("found effective: " + this);
effectiveSignature = (AjAttribute.EffectiveSignatureAttribute)a;
} else if (a instanceof AjAttribute.PointcutDeclarationAttribute) {
// this is an @AspectJ annotated advice method, with pointcut pre-resolved by ajc
preResolvedPointcut = ((AjAttribute.PointcutDeclarationAttribute)a).reify();
} else {
throw new BCException("weird method attribute " + a);
}
}
}
public boolean isAjSynthetic() {
return isAjSynthetic; // || getName().startsWith(NameMangler.PREFIX);
}
//FIXME ??? needs an isSynthetic method
public ShadowMunger getAssociatedShadowMunger() {
return associatedShadowMunger;
}
public AjAttribute.EffectiveSignatureAttribute getEffectiveSignature() {
return effectiveSignature;
}
public boolean hasDeclarationLineNumberInfo() {
return declarationLineNumber != null;
}
public int getDeclarationLineNumber() {
if (declarationLineNumber != null) {
return declarationLineNumber.getLineNumber();
} else {
return -1;
}
}
public int getDeclarationOffset() {
if (declarationLineNumber != null) {
return declarationLineNumber.getOffset();
} else {
return -1;
}
}
public ISourceLocation getSourceLocation() {
ISourceLocation ret = super.getSourceLocation();
if ((ret == null || ret.getLine()==0) && hasDeclarationLineNumberInfo()) {
// lets see if we can do better
ISourceContext isc = getSourceContext();
if (isc !=null) ret = isc.makeSourceLocation(getDeclarationLineNumber(), getDeclarationOffset());
else ret = new SourceLocation(null,getDeclarationLineNumber());
}
return ret;
}
public Kind getKind() {
if (associatedShadowMunger != null) {
return ADVICE;
} else {
return super.getKind();
}
}
public boolean hasAnnotation(UnresolvedType ofType) {
ensureAnnotationTypesRetrieved();
for (Iterator iter = annotationTypes.iterator(); iter.hasNext();) {
ResolvedType aType = (ResolvedType) iter.next();
if (aType.equals(ofType)) return true;
}
return false;
}
public AnnotationX[] getAnnotations() {
ensureAnnotationTypesRetrieved();
return annotations;
}
public ResolvedType[] getAnnotationTypes() {
ensureAnnotationTypesRetrieved();
ResolvedType[] ret = new ResolvedType[annotationTypes.size()];
annotationTypes.toArray(ret);
return ret;
}
public void addAnnotation(AnnotationX annotation) {
ensureAnnotationTypesRetrieved();
// Add it to the set of annotations
int len = annotations.length;
AnnotationX[] ret = new AnnotationX[len+1];
System.arraycopy(annotations, 0, ret, 0, len);
ret[len] = annotation;
annotations = ret;
// Add it to the set of annotation types
annotationTypes.add(UnresolvedType.forName(annotation.getTypeName()).resolve(world));
// FIXME asc looks like we are managing two 'bunches' of annotations, one
// here and one in the real 'method' - should we reduce it to one layer?
method.addAnnotation(annotation.getBcelAnnotation());
}
private void ensureAnnotationTypesRetrieved() {
if (annotationTypes == null || method.getAnnotations().length!=annotations.length) { // sometimes the list changes underneath us!
Annotation annos[] = method.getAnnotations();
annotationTypes = new HashSet();
annotations = new AnnotationX[annos.length];
for (int i = 0; i < annos.length; i++) {
Annotation annotation = annos[i];
ResolvedType rtx = world.resolve(UnresolvedType.forName(annotation.getTypeName()));
annotationTypes.add(rtx);
annotations[i] = new AnnotationX(annotation,world);
}
}
}
private boolean canBeParameterized = false;
/**
* A method can be parameterized if it has one or more generic
* parameters. A generic parameter (type variable parameter) is
* identified by the prefix "T"
*/
public boolean canBeParameterized() {
unpackGenericSignature();
return canBeParameterized;
}
// genericized version of return and parameter types
private boolean unpackedGenericSignature = false;
private UnresolvedType genericReturnType = null;
private UnresolvedType[] genericParameterTypes = null;
public UnresolvedType[] getGenericParameterTypes() {
unpackGenericSignature();
return genericParameterTypes;
}
public UnresolvedType getGenericReturnType() {
unpackGenericSignature();
return genericReturnType;
}
private void unpackGenericSignature() {
if (unpackedGenericSignature) return;
unpackedGenericSignature = true;
String gSig = method.getGenericSignature();
if (gSig != null) {
Signature.MethodTypeSignature mSig = new GenericSignatureParser().parseAsMethodSignature(method.getGenericSignature());
if (mSig.formalTypeParameters.length > 0) {
// generic method declaration
canBeParameterized = true;
}
Signature.FormalTypeParameter[] parentFormals = bcelObjectType.getAllFormals();
Signature.FormalTypeParameter[] formals = new
Signature.FormalTypeParameter[parentFormals.length + mSig.formalTypeParameters.length];
// put method formal in front of type formals for overriding in lookup
System.arraycopy(mSig.formalTypeParameters,0,formals,0,mSig.formalTypeParameters.length);
System.arraycopy(parentFormals,0,formals,mSig.formalTypeParameters.length,parentFormals.length);
Signature.TypeSignature returnTypeSignature = mSig.returnType;
try {
genericReturnType = BcelGenericSignatureToTypeXConverter.typeSignature2TypeX(
returnTypeSignature, formals,
world);
} catch (GenericSignatureFormatException e) {
// development bug, fail fast with good info
throw new IllegalStateException(
"While determing the generic return type of " + this.toString()
+ " with generic signature " + gSig + " the following error was detected: "
+ e.getMessage());
}
Signature.TypeSignature[] paramTypeSigs = mSig.parameters;
genericParameterTypes = new UnresolvedType[paramTypeSigs.length];
for (int i = 0; i < paramTypeSigs.length; i++) {
try {
genericParameterTypes[i] =
BcelGenericSignatureToTypeXConverter.typeSignature2TypeX(
paramTypeSigs[i],formals,world);
} catch (GenericSignatureFormatException e) {
// development bug, fail fast with good info
throw new IllegalStateException(
"While determining the generic parameter types of " + this.toString()
+ " with generic signature " + gSig + " the following error was detected: "
+ e.getMessage());
}
if (paramTypeSigs[i] instanceof TypeVariableSignature) {
canBeParameterized = true;
}
}
} else {
genericReturnType = getReturnType();
genericParameterTypes = getParameterTypes();
}
}
}
|
122,248 |
Bug 122248 BUG for ajdt_1.3_for_eclipse_3.1.zip
|
Hi !! I use ajdt_1.3_for_eclipse_3.1.zip with eclipse 3.1.1 and fick this error when the eclipse try to make the workbrench: java.lang.IllegalStateException at org.aspectj.weaver.TypeFactory.createParameterizedType(TypeFactory.java:42) at org.aspectj.weaver.bcel.BcelGenericSignatureToTypeXConverter.classTypeSignature2TypeX(BcelGenericSignatureToTypeXConverter.java:82) at org.aspectj.weaver.bcel.BcelGenericSignatureToTypeXConverter.classTypeSignature2TypeX(BcelGenericSignatureToTypeXConverter.java:42) at org.aspectj.weaver.bcel.BcelObjectType.unpackGenericSignature(BcelObjectType.java:657) at org.aspectj.weaver.bcel.BcelObjectType.getSuperclass(BcelObjectType.java:181) at org.aspectj.weaver.ReferenceType.getSuperclass(ReferenceType.java:514) at org.aspectj.weaver.bcel.BcelWeaver.weaveParentsFor(BcelWeaver.java:1192) at org.aspectj.weaver.bcel.BcelWeaver.weave(BcelWeaver.java:1047) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.weave(AjCompilerAdapter.java:300) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.afterCompiling(AjCompilerAdapter.java:178) at org.aspectj.ajdt.internal.compiler.CompilerAdapter.ajc$afterReturning$org_aspectj_ajdt_internal_compiler_CompilerAdapter$2$f9cc9ca0(CompilerAdapter.aj:70) at org.aspectj.org.eclipse.jdt.internal.compiler.Compiler.compile(Compiler.java:367) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.performCompilation(AjBuildManager.java:811) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.doBuild(AjBuildManager.java:230) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.batchBuild(AjBuildManager.java:156) at org.aspectj.ajde.internal.CompilerAdapter.compile(CompilerAdapter.java:122) at org.aspectj.ajde.internal.AspectJBuildManager$CompilerThread.run(AspectJBuildManager.java:191) IllegalStateException thrown: Expecting raw type
|
resolved fixed
|
3f77e75
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-01-15T21:33:55Z | 2005-12-28T14:26:40Z |
weaver/src/org/aspectj/weaver/bcel/BcelObjectType.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.PrintStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import org.aspectj.apache.bcel.classfile.Attribute;
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.annotation.Annotation;
import org.aspectj.apache.bcel.classfile.annotation.ElementNameValuePair;
import org.aspectj.apache.bcel.classfile.annotation.ElementValue;
import org.aspectj.bridge.ISourceLocation;
import org.aspectj.weaver.AbstractReferenceTypeDelegate;
import org.aspectj.weaver.AjAttribute;
import org.aspectj.weaver.AjcMemberMaker;
import org.aspectj.weaver.AnnotationTargetKind;
import org.aspectj.weaver.AnnotationX;
import org.aspectj.weaver.BCException;
import org.aspectj.weaver.ReferenceType;
import org.aspectj.weaver.ReferenceTypeDelegate;
import org.aspectj.weaver.ResolvedMember;
import org.aspectj.weaver.ResolvedPointcutDefinition;
import org.aspectj.weaver.ResolvedType;
import org.aspectj.weaver.TypeVariable;
import org.aspectj.weaver.UnresolvedType;
import org.aspectj.weaver.WeaverStateInfo;
import org.aspectj.weaver.bcel.BcelGenericSignatureToTypeXConverter.GenericSignatureFormatException;
import org.aspectj.weaver.patterns.PerClause;
// ??? exposed for testing
public class BcelObjectType extends AbstractReferenceTypeDelegate {
private JavaClass javaClass;
private boolean isObject = false; // set upon construction
private LazyClassGen lazyClassGen = null; // set lazily if it's an aspect
// lazy, for no particular reason I can discern
private ResolvedType[] interfaces = null;
private ResolvedType superClass = null;
private ResolvedMember[] fields = null;
private ResolvedMember[] methods = null;
private ResolvedType[] annotationTypes = null;
private AnnotationX[] annotations = null;
private TypeVariable[] typeVars = null;
// track unpackAttribute. In some case (per clause inheritance) we encounter
// unpacked state when calling getPerClause
// this whole thing would require more clean up (AV)
private boolean isUnpacked = false;
// strangely non-lazy
private ResolvedPointcutDefinition[] pointcuts = null;
private PerClause perClause = null;
private WeaverStateInfo weaverState = null;
private AjAttribute.WeaverVersionInfo wvInfo = AjAttribute.WeaverVersionInfo.UNKNOWN;
private List typeMungers = Collections.EMPTY_LIST;
private List declares = Collections.EMPTY_LIST;
private ResolvedMember[] privilegedAccess = null;
private boolean discoveredWhetherAnnotationStyle = false;
private boolean isAnnotationStyleAspect = false;// set upon construction
private boolean isCodeStyleAspect = false; // not redundant with field above!
// TODO asc need soon but not just yet...
private boolean haveLookedForDeclaredSignature = false;
private String declaredSignature = null;
private boolean isGenericType = false;
private boolean discoveredRetentionPolicy = false;
private String retentionPolicy;
private boolean discoveredAnnotationTargetKinds = false;
private AnnotationTargetKind[] annotationTargetKinds;
/**
* A BcelObjectType is 'damaged' if it has been modified from what was original constructed from
* the bytecode. This currently happens if the parents are modified or an annotation is added -
* ideally BcelObjectType should be immutable but that's a bigger piece of work!!!!!!!!!! XXX
*/
private boolean damaged = false;
public Collection getTypeMungers() {
return typeMungers;
}
public Collection getDeclares() {
return declares;
}
public Collection getPrivilegedAccesses() {
if (privilegedAccess == null) return Collections.EMPTY_LIST;
return Arrays.asList(privilegedAccess);
}
// IMPORTANT! THIS DOESN'T do real work on the java class, just stores it away.
BcelObjectType(ReferenceType resolvedTypeX, JavaClass javaClass, boolean exposedToWeaver) {
super(resolvedTypeX, exposedToWeaver);
this.javaClass = javaClass;
//ATAJ: set the delegate right now for @AJ poincut, else it is done too late to lookup
// @AJ pc refs annotation in class hierarchy
resolvedTypeX.setDelegate(this);
if (resolvedTypeX.getSourceContext() == null) {
resolvedTypeX.setSourceContext(new BcelSourceContext(this));
}
// this should only ever be java.lang.Object which is
// the only class in Java-1.4 with no superclasses
isObject = (javaClass.getSuperclassNameIndex() == 0);
unpackAspectAttributes();
}
// repeat initialization
public void setJavaClass(JavaClass newclass) {
this.javaClass = newclass;
resetState();
}
public TypeVariable[] getTypeVariables() {
if (!isGeneric()) return new TypeVariable[0];
if (typeVars == null) {
Signature.ClassSignature classSig = javaClass.getGenericClassTypeSignature();
typeVars = new TypeVariable[classSig.formalTypeParameters.length];
for (int i = 0; i < typeVars.length; i++) {
Signature.FormalTypeParameter ftp = classSig.formalTypeParameters[i];
try {
typeVars[i] = BcelGenericSignatureToTypeXConverter.formalTypeParameter2TypeVariable(
ftp,
classSig.formalTypeParameters,
getResolvedTypeX().getWorld());
} catch (GenericSignatureFormatException e) {
// this is a development bug, so fail fast with good info
throw new IllegalStateException(
"While getting the type variables for type " + this.toString()
+ " with generic signature " + classSig +
" the following error condition was detected: " + e.getMessage());
}
}
}
return typeVars;
}
public int getModifiers() {
return javaClass.getAccessFlags();
}
/**
* Must take into account generic signature
*/
public ResolvedType getSuperclass() {
if (isObject) return null;
unpackGenericSignature();
if (superClass == null) {
superClass = getResolvedTypeX().getWorld().resolve(UnresolvedType.forName(javaClass.getSuperclassName()));
}
return superClass;
}
/**
* Retrieves the declared interfaces - this allows for the generic signature on a type. If specified
* then the generic signature is used to work out the types - this gets around the results of
* erasure when the class was originally compiled.
*/
public ResolvedType[] getDeclaredInterfaces() {
unpackGenericSignature();
if (interfaces == null) {
String[] ifaceNames = javaClass.getInterfaceNames();
interfaces = new ResolvedType[ifaceNames.length];
for (int i = 0, len = ifaceNames.length; i < len; i++) {
interfaces[i] = getResolvedTypeX().getWorld().resolve(UnresolvedType.forName(ifaceNames[i]));
}
}
return interfaces;
}
public ResolvedMember[] getDeclaredMethods() {
unpackGenericSignature();
if (methods == null) {
Method[] ms = javaClass.getMethods();
ResolvedMember[] ret = new ResolvedMember[ms.length];
for (int i = ms.length - 1; i >= 0; i--) {
ret[i] = new BcelMethod(this, ms[i]);
}
methods = ret;
}
return methods;
}
public ResolvedMember[] getDeclaredFields() {
unpackGenericSignature();
if (fields == null) {
Field[] fs = javaClass.getFields();
ResolvedMember[] ret = new ResolvedMember[fs.length];
for (int i = 0, len = fs.length; i < len; i++) {
ret[i] = new BcelField(this, fs[i]);
}
fields = ret;
}
return fields;
}
// ----
// fun based on the aj attributes
public ResolvedMember[] getDeclaredPointcuts() {
return pointcuts;
}
//??? method only used for testing
public void addPointcutDefinition(ResolvedPointcutDefinition d) {
damaged = true;
int len = pointcuts.length;
ResolvedPointcutDefinition[] ret = new ResolvedPointcutDefinition[len+1];
System.arraycopy(pointcuts, 0, ret, 0, len);
ret[len] = d;
pointcuts = ret;
}
public boolean isAspect() {
return perClause != null;
}
/**
* Check if the type is an @AJ aspect (no matter if used from an LTW point of view).
* Such aspects are annotated with @Aspect
*
* @return true for @AJ aspect
*/
public boolean isAnnotationStyleAspect() {
if (!discoveredWhetherAnnotationStyle) {
discoveredWhetherAnnotationStyle = true;
isAnnotationStyleAspect = !isCodeStyleAspect && hasAnnotation(AjcMemberMaker.ASPECT_ANNOTATION);
}
return isAnnotationStyleAspect;
}
private void unpackAspectAttributes() {
isUnpacked = true;
List pointcuts = new ArrayList();
typeMungers = new ArrayList();
declares = new ArrayList();
// Pass in empty list that can store things for readAj5 to process
List l = BcelAttributes.readAjAttributes(javaClass.getClassName(),javaClass.getAttributes(), getResolvedTypeX().getSourceContext(),getResolvedTypeX().getWorld().getMessageHandler(),AjAttribute.WeaverVersionInfo.UNKNOWN);
processAttributes(l,pointcuts,false);
l = AtAjAttributes.readAj5ClassAttributes(javaClass, getResolvedTypeX(), getResolvedTypeX().getSourceContext(), getResolvedTypeX().getWorld().getMessageHandler(),isCodeStyleAspect);
AjAttribute.Aspect deferredAspectAttribute = processAttributes(l,pointcuts,true);
this.pointcuts = (ResolvedPointcutDefinition[])
pointcuts.toArray(new ResolvedPointcutDefinition[pointcuts.size()]);
if (deferredAspectAttribute != null) {
// we can finally process the aspect and its associated perclause...
perClause = deferredAspectAttribute.reifyFromAtAspectJ(this.getResolvedTypeX());
}
}
private AjAttribute.Aspect processAttributes(List attributeList, List pointcuts, boolean fromAnnotations) {
AjAttribute.Aspect deferredAspectAttribute = null;
for (Iterator iter = attributeList.iterator(); iter.hasNext();) {
AjAttribute a = (AjAttribute) iter.next();
//System.err.println("unpacking: " + this + " and " + a);
if (a instanceof AjAttribute.Aspect) {
if (fromAnnotations) {
deferredAspectAttribute = (AjAttribute.Aspect) a;
} else {
perClause = ((AjAttribute.Aspect)a).reify(this.getResolvedTypeX());
isCodeStyleAspect = true;
}
} else if (a instanceof AjAttribute.PointcutDeclarationAttribute) {
pointcuts.add(((AjAttribute.PointcutDeclarationAttribute)a).reify());
} else if (a instanceof AjAttribute.WeaverState) {
weaverState = ((AjAttribute.WeaverState)a).reify();
} else if (a instanceof AjAttribute.TypeMunger) {
typeMungers.add(((AjAttribute.TypeMunger)a).reify(getResolvedTypeX().getWorld(), getResolvedTypeX()));
} else if (a instanceof AjAttribute.DeclareAttribute) {
declares.add(((AjAttribute.DeclareAttribute)a).getDeclare());
} else if (a instanceof AjAttribute.PrivilegedAttribute) {
privilegedAccess = ((AjAttribute.PrivilegedAttribute)a).getAccessedMembers();
} else if (a instanceof AjAttribute.SourceContextAttribute) {
if (getResolvedTypeX().getSourceContext() instanceof BcelSourceContext) {
((BcelSourceContext)getResolvedTypeX().getSourceContext()).addAttributeInfo((AjAttribute.SourceContextAttribute)a);
}
} else if (a instanceof AjAttribute.WeaverVersionInfo) {
wvInfo = (AjAttribute.WeaverVersionInfo)a; // Set the weaver version used to build this type
} else {
throw new BCException("bad attribute " + a);
}
}
return deferredAspectAttribute;
}
public PerClause getPerClause() {
if (!isUnpacked) {
unpackAspectAttributes();
}
return perClause;
}
JavaClass getJavaClass() {
return javaClass;
}
public void ensureDelegateConsistent() {
if (damaged) {resetState();damaged=false;}
}
public void resetState() {
this.interfaces = null;
this.superClass = null;
this.fields = null;
this.methods = null;
this.pointcuts = null;
this.perClause = null;
this.weaverState = null;
this.lazyClassGen = null;
this.annotations = null;
this.annotationTypes = null;
isObject = (javaClass.getSuperclassNameIndex() == 0);
unpackAspectAttributes();
discoveredWhetherAnnotationStyle = false;
isAnnotationStyleAspect=false;
}
public void finishedWith() {
// memory usage experiments....
// this.interfaces = null;
// this.superClass = null;
// this.fields = null;
// this.methods = null;
// this.pointcuts = null;
// this.perClause = null;
// this.weaverState = null;
// this.lazyClassGen = null;
// this next line frees up memory, but need to understand incremental implications
// before leaving it in.
// getResolvedTypeX().setSourceContext(null);
}
public WeaverStateInfo getWeaverState() {
return weaverState;
}
void setWeaverState(WeaverStateInfo weaverState) {
this.weaverState = weaverState;
}
public void printWackyStuff(PrintStream out) {
if (typeMungers.size() > 0) {
out.println(" TypeMungers: " + typeMungers);
}
if (declares.size() > 0) {
out.println(" declares: " + declares);
}
}
/**
* Return the lazyClassGen associated with this type. For aspect types, this
* value will be cached, since it is used to inline advice. For non-aspect
* types, this lazyClassGen is always newly constructed.
*/
public LazyClassGen getLazyClassGen() {
LazyClassGen ret = lazyClassGen;
if (ret == null) {
//System.err.println("creating lazy class gen for: " + this);
ret = new LazyClassGen(this);
//ret.print(System.err);
//System.err.println("made LCG from : " + this.getJavaClass().getSuperclassName() );
if (isAspect()) {
lazyClassGen = ret;
}
}
return ret;
}
public boolean isInterface() {
return javaClass.isInterface();
}
public boolean isEnum() {
return javaClass.isEnum();
}
public boolean isAnnotation() {
return javaClass.isAnnotation();
}
public boolean isAnonymous() {
return javaClass.isAnonymous();
}
public boolean isNested() {
return javaClass.isNested();
}
public void addAnnotation(AnnotationX annotation) {
damaged = true;
// Add it to the set of annotations
int len = annotations.length;
AnnotationX[] ret = new AnnotationX[len+1];
System.arraycopy(annotations, 0, ret, 0, len);
ret[len] = annotation;
annotations = ret;
// Add it to the set of annotation types
len = annotationTypes.length;
ResolvedType[] ret2 = new ResolvedType[len+1];
System.arraycopy(annotationTypes,0,ret2,0,len);
ret2[len] = getResolvedTypeX().getWorld().resolve(UnresolvedType.forName(annotation.getTypeName()));
annotationTypes = ret2;
}
public boolean isAnnotationWithRuntimeRetention() {
return getRetentionPolicy().equals("RUNTIME");
// if (!isAnnotation()) {
// return false;
// } else {
// Annotation[] annotationsOnThisType = javaClass.getAnnotations();
// for (int i = 0; i < annotationsOnThisType.length; i++) {
// Annotation a = annotationsOnThisType[i];
// if (a.getTypeName().equals(UnresolvedType.AT_RETENTION.getName())) {
// List values = a.getValues();
// boolean isRuntime = false;
// for (Iterator it = values.iterator(); it.hasNext();) {
// ElementNameValuePair element = (ElementNameValuePair) it.next();
// ElementValue v = element.getValue();
// isRuntime = v.stringifyValue().equals("RUNTIME");
// }
// return isRuntime;
// }
// }
// }
// return false;
}
public String getRetentionPolicy() {
if (discoveredRetentionPolicy) return retentionPolicy;
discoveredRetentionPolicy=true;
retentionPolicy=null; // null means we have no idea
if (isAnnotation()) {
Annotation[] annotationsOnThisType = javaClass.getAnnotations();
for (int i = 0; i < annotationsOnThisType.length; i++) {
Annotation a = annotationsOnThisType[i];
if (a.getTypeName().equals(UnresolvedType.AT_RETENTION.getName())) {
List values = a.getValues();
boolean isRuntime = false;
for (Iterator it = values.iterator(); it.hasNext();) {
ElementNameValuePair element = (ElementNameValuePair) it.next();
ElementValue v = element.getValue();
retentionPolicy = v.stringifyValue();
return retentionPolicy;
}
}
}
}
return retentionPolicy;
}
public boolean canAnnotationTargetType() {
AnnotationTargetKind[] targetKinds = getAnnotationTargetKinds();
if (targetKinds == null) return true;
for (int i = 0; i < targetKinds.length; i++) {
if (targetKinds[i].equals(AnnotationTargetKind.TYPE)) {
return true;
}
}
return false;
}
public AnnotationTargetKind[] getAnnotationTargetKinds() {
if (discoveredAnnotationTargetKinds) return annotationTargetKinds;
discoveredAnnotationTargetKinds = true;
annotationTargetKinds = null; // null means we have no idea or the @Target annotation hasn't been used
List targetKinds = new ArrayList();
if (isAnnotation()) {
Annotation[] annotationsOnThisType = javaClass.getAnnotations();
for (int i = 0; i < annotationsOnThisType.length; i++) {
Annotation a = annotationsOnThisType[i];
if (a.getTypeName().equals(UnresolvedType.AT_TARGET.getName())) {
List values = a.getValues();
for (Iterator it = values.iterator(); it.hasNext();) {
ElementNameValuePair element = (ElementNameValuePair) it.next();
ElementValue v = element.getValue();
String targetKind = v.stringifyValue();
if (targetKind.equals("ANNOTATION_TYPE")) {
targetKinds.add(AnnotationTargetKind.ANNOTATION_TYPE);
} else if (targetKind.equals("CONSTRUCTOR")) {
targetKinds.add(AnnotationTargetKind.CONSTRUCTOR);
} else if (targetKind.equals("FIELD")) {
targetKinds.add(AnnotationTargetKind.FIELD);
} else if (targetKind.equals("LOCAL_VARIABLE")) {
targetKinds.add(AnnotationTargetKind.LOCAL_VARIABLE);
} else if (targetKind.equals("METHOD")) {
targetKinds.add(AnnotationTargetKind.METHOD);
} else if (targetKind.equals("PACKAGE")) {
targetKinds.add(AnnotationTargetKind.PACKAGE);
} else if (targetKind.equals("PARAMETER")) {
targetKinds.add(AnnotationTargetKind.PARAMETER);
} else if (targetKind.equals("TYPE")) {
targetKinds.add(AnnotationTargetKind.TYPE);
}
}
}
}
if (!targetKinds.isEmpty()) {
annotationTargetKinds = new AnnotationTargetKind[targetKinds.size()];
return (AnnotationTargetKind[]) targetKinds.toArray(annotationTargetKinds);
}
}
return annotationTargetKinds;
}
public boolean isSynthetic() {
return getResolvedTypeX().isSynthetic();
}
public ISourceLocation getSourceLocation() {
return getResolvedTypeX().getSourceContext().makeSourceLocation(0, 0); //FIXME ??? we can do better than this
}
public AjAttribute.WeaverVersionInfo getWeaverVersionAttribute() {
return wvInfo;
}
public void addParent(ResolvedType newParent) {
damaged = true;
if (newParent.isClass()) {
superClass = newParent;
} else {
ResolvedType[] oldInterfaceNames = getDeclaredInterfaces();
int len = oldInterfaceNames.length;
ResolvedType[] newInterfaceNames = new ResolvedType[len+1];
System.arraycopy(oldInterfaceNames, 0, newInterfaceNames, 0, len);
newInterfaceNames[len] = newParent;
interfaces = newInterfaceNames;
}
//System.err.println("javaClass: " + Arrays.asList(javaClass.getInterfaceNames()) + " super " + javaClass.getSuperclassName());
//if (lazyClassGen != null) lazyClassGen.print();
}
public boolean hasAnnotation(UnresolvedType ofType) {
ensureAnnotationTypesRetrieved();
for (int i = 0; i < annotationTypes.length; i++) {
ResolvedType annX = annotationTypes[i];
if (annX.equals(ofType)) return true;
}
return false;
}
private void ensureAnnotationTypesRetrieved() {
if (annotationTypes == null) {
Annotation annos[] = javaClass.getAnnotations();
annotationTypes = new ResolvedType[annos.length];
annotations = new AnnotationX[annos.length];
for (int i = 0; i < annos.length; i++) {
Annotation annotation = annos[i];
ResolvedType rtx = getResolvedTypeX().getWorld().resolve(UnresolvedType.forName(annotation.getTypeName()));
annotationTypes[i] = rtx;
annotations[i] = new AnnotationX(annotation,getResolvedTypeX().getWorld());
}
}
}
public ResolvedType[] getAnnotationTypes() {
ensureAnnotationTypesRetrieved();
return annotationTypes;
}
/**
* Releases annotations wrapped in an annotationX
*/
public AnnotationX[] getAnnotations() {
ensureAnnotationTypesRetrieved();
return annotations;
}
public String getDeclaredGenericSignature() {
if (!haveLookedForDeclaredSignature) {
haveLookedForDeclaredSignature = true;
Attribute[] as = javaClass.getAttributes();
for (int i = 0; i < as.length && declaredSignature==null; i++) {
Attribute attribute = as[i];
if (attribute instanceof Signature) declaredSignature = ((Signature)attribute).getSignature();
}
if (declaredSignature!=null) isGenericType= (declaredSignature.charAt(0)=='<');
}
return declaredSignature;
}
Signature.ClassSignature getGenericClassTypeSignature() {
return javaClass.getGenericClassTypeSignature();
}
private boolean genericSignatureUnpacked = false;
private Signature.FormalTypeParameter[] formalsForResolution = null;
private void unpackGenericSignature() {
if (genericSignatureUnpacked) return;
genericSignatureUnpacked = true;
Signature.ClassSignature cSig = getGenericClassTypeSignature();
if (cSig != null) {
formalsForResolution = cSig.formalTypeParameters;
if (isNestedClass()) {
// we have to find any type variables from the outer type before proceeding with resolution.
Signature.FormalTypeParameter[] extraFormals = getFormalTypeParametersFromOuterClass();
if (extraFormals.length > 0) {
List allFormals = new ArrayList();
for (int i = 0; i < formalsForResolution.length; i++) {
allFormals.add(formalsForResolution[i]);
}
for (int i = 0; i < extraFormals.length; i++) {
allFormals.add(extraFormals[i]);
}
formalsForResolution = new Signature.FormalTypeParameter[allFormals.size()];
allFormals.toArray(formalsForResolution);
}
}
Signature.ClassTypeSignature superSig = cSig.superclassSignature;
try {
this.superClass =
BcelGenericSignatureToTypeXConverter.classTypeSignature2TypeX(
superSig, formalsForResolution, getResolvedTypeX().getWorld());
} catch (GenericSignatureFormatException e) {
// development bug, fail fast with good info
throw new IllegalStateException(
"While determing the generic superclass of " + this.javaClass.getClassName()
+ " with generic signature " + this.javaClass.getGenericSignature() + " the following error was detected: "
+ e.getMessage());
}
this.interfaces = new ResolvedType[cSig.superInterfaceSignatures.length];
for (int i = 0; i < cSig.superInterfaceSignatures.length; i++) {
try {
this.interfaces[i] =
BcelGenericSignatureToTypeXConverter.classTypeSignature2TypeX(
cSig.superInterfaceSignatures[i],
formalsForResolution,
getResolvedTypeX().getWorld());
} catch (GenericSignatureFormatException e) {
// development bug, fail fast with good info
throw new IllegalStateException(
"While determing the generic superinterfaces of " + this.javaClass.getClassName()
+ " with generic signature " + this.javaClass.getGenericSignature() + " the following error was detected: "
+ e.getMessage());
}
}
}
if (isGeneric()) {
// update resolved typex to point at generic type not raw type.
ReferenceType genericType = (ReferenceType) this.resolvedTypeX.getGenericType();
genericType.setSourceContext(this.resolvedTypeX.getSourceContext());
genericType.setStartPos(this.resolvedTypeX.getStartPos());
this.resolvedTypeX = genericType;
}
}
public Signature.FormalTypeParameter[] getAllFormals() {
unpackGenericSignature();
if (formalsForResolution == null) {
return new Signature.FormalTypeParameter[0];
} else {
return formalsForResolution;
}
}
private boolean isNestedClass() {
return javaClass.getClassName().indexOf('$') != -1;
}
private ReferenceType getOuterClass() {
if (!isNestedClass()) throw new IllegalStateException("Can't get the outer class of a non-nested type");
int lastDollar = javaClass.getClassName().lastIndexOf('$');
String superClassName = javaClass.getClassName().substring(0,lastDollar);
UnresolvedType outer = UnresolvedType.forName(superClassName);
return (ReferenceType) outer.resolve(getResolvedTypeX().getWorld());
}
private Signature.FormalTypeParameter[] getFormalTypeParametersFromOuterClass() {
List typeParameters = new ArrayList();
ReferenceType outer = getOuterClass();
ReferenceTypeDelegate outerDelegate = outer.getDelegate();
if (!(outerDelegate instanceof BcelObjectType)) {
throw new IllegalStateException("How come we're in BcelObjectType resolving an inner type of something that is NOT a BcelObjectType??");
}
BcelObjectType outerObjectType = (BcelObjectType) outerDelegate;
if (outerObjectType.isNestedClass()) {
Signature.FormalTypeParameter[] parentParams = outerObjectType.getFormalTypeParametersFromOuterClass();
for (int i = 0; i < parentParams.length; i++) {
typeParameters.add(parentParams[i]);
}
}
Signature.ClassSignature outerSig = outerObjectType.getGenericClassTypeSignature();
if (outerSig != null) {
for (int i = 0; i < outerSig.formalTypeParameters .length; i++) {
typeParameters.add(outerSig.formalTypeParameters[i]);
}
}
Signature.FormalTypeParameter[] ret = new Signature.FormalTypeParameter[typeParameters.size()];
typeParameters.toArray(ret);
return ret;
}
private void ensureGenericInfoProcessed() { getDeclaredGenericSignature();}
public boolean isGeneric() {
ensureGenericInfoProcessed();
return isGenericType;
}
public String toString() {
return (javaClass==null?"BcelObjectType":"BcelObjectTypeFor:"+javaClass.getClassName());
}
}
|
122,248 |
Bug 122248 BUG for ajdt_1.3_for_eclipse_3.1.zip
|
Hi !! I use ajdt_1.3_for_eclipse_3.1.zip with eclipse 3.1.1 and fick this error when the eclipse try to make the workbrench: java.lang.IllegalStateException at org.aspectj.weaver.TypeFactory.createParameterizedType(TypeFactory.java:42) at org.aspectj.weaver.bcel.BcelGenericSignatureToTypeXConverter.classTypeSignature2TypeX(BcelGenericSignatureToTypeXConverter.java:82) at org.aspectj.weaver.bcel.BcelGenericSignatureToTypeXConverter.classTypeSignature2TypeX(BcelGenericSignatureToTypeXConverter.java:42) at org.aspectj.weaver.bcel.BcelObjectType.unpackGenericSignature(BcelObjectType.java:657) at org.aspectj.weaver.bcel.BcelObjectType.getSuperclass(BcelObjectType.java:181) at org.aspectj.weaver.ReferenceType.getSuperclass(ReferenceType.java:514) at org.aspectj.weaver.bcel.BcelWeaver.weaveParentsFor(BcelWeaver.java:1192) at org.aspectj.weaver.bcel.BcelWeaver.weave(BcelWeaver.java:1047) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.weave(AjCompilerAdapter.java:300) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.afterCompiling(AjCompilerAdapter.java:178) at org.aspectj.ajdt.internal.compiler.CompilerAdapter.ajc$afterReturning$org_aspectj_ajdt_internal_compiler_CompilerAdapter$2$f9cc9ca0(CompilerAdapter.aj:70) at org.aspectj.org.eclipse.jdt.internal.compiler.Compiler.compile(Compiler.java:367) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.performCompilation(AjBuildManager.java:811) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.doBuild(AjBuildManager.java:230) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.batchBuild(AjBuildManager.java:156) at org.aspectj.ajde.internal.CompilerAdapter.compile(CompilerAdapter.java:122) at org.aspectj.ajde.internal.AspectJBuildManager$CompilerThread.run(AspectJBuildManager.java:191) IllegalStateException thrown: Expecting raw type
|
resolved fixed
|
3f77e75
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-01-15T21:33:55Z | 2005-12-28T14:26:40Z |
weaver/testsrc/org/aspectj/weaver/MemberTestCase15.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 org.aspectj.weaver.bcel.BcelWorld;
import junit.framework.TestCase;
/**
* @author colyer
*
*/
public class MemberTestCase15 extends TestCase {
public void testCanBeParameterizedRegularMethod() {
BcelWorld world = new BcelWorld();
ResolvedType javaLangClass = world.resolve(UnresolvedType.forName("java/lang/Class"));
ResolvedMember[] methods = javaLangClass.getDeclaredMethods();
ResolvedMember getAnnotations = null;
for (int i = 0; i < methods.length; i++) {
if (methods[i].getName().equals("getAnnotations")) {
getAnnotations = methods[i];
break;
}
}
if (getAnnotations != null) { // so can run on non-Java 5
// System.out.println("got it");
assertFalse(getAnnotations.canBeParameterized());
}
}
public void testCanBeParameterizedGenericMethod() {
BcelWorld world = new BcelWorld();
ResolvedType javaLangClass = world.resolve(UnresolvedType.forName("java.lang.Class"));
javaLangClass = javaLangClass.getGenericType();
if (javaLangClass == null) return; // for < 1.5
ResolvedMember[] methods = javaLangClass.getDeclaredMethods();
ResolvedMember asSubclass = null;
for (int i = 0; i < methods.length; i++) {
if (methods[i].getName().equals("asSubclass")) {
asSubclass = methods[i];
break;
}
}
if (asSubclass != null) { // so can run on non-Java 5
// System.out.println("got it");
assertTrue(asSubclass.canBeParameterized());
}
}
public void testCanBeParameterizedMethodInGenericType() {
BcelWorld world = new BcelWorld();
ResolvedType javaUtilList = world.resolve(UnresolvedType.forName("java.util.List"));
javaUtilList = javaUtilList.getGenericType();
if (javaUtilList == null) return; // for < 1.5
ResolvedMember[] methods = javaUtilList.getDeclaredMethods();
ResolvedMember add = null;
for (int i = 0; i < methods.length; i++) {
if (methods[i].getName().equals("add")) {
add = methods[i];
break;
}
}
if (add != null) { // so can run on non-Java 5
// System.out.println("got it");
assertTrue(add.canBeParameterized());
}
}
}
|
58,524 |
Bug 58524 ajdoc should not use the Declaration and SymbolManager classes
|
In order to speed up porting porting to the old HTML generation code ajdoc continues to use the following classes: org.aspectj.tools.ajdoc.Declaration org.aspectj.tools.ajdoc.SymbolManager These funtion only as a wrapper to the ASM, and are not needed. The next refactoring effort should get rid of them (and all those static methods as well!).
|
resolved fixed
|
f4c8bf9
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-01-16T16:46:54Z | 2004-04-14T16:26:40Z |
ajdoc/src/org/aspectj/tools/ajdoc/Declaration.java
|
/* *******************************************************************
* Copyright (c) 1999-2001 Xerox Corporation,
* 2002 Palo Alto Research Center, Incorporated (PARC).
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* Xerox/PARC initial implementation
* Mik Kersten port to AspectJ 1.1+ code base
* ******************************************************************/
package org.aspectj.tools.ajdoc;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import org.aspectj.asm.IProgramElement;
/**
* @author Mik Kersten
* @deprecated org.aspectj.asm.IProgramElement should be used instead
*/
public class Declaration implements Serializable {
private int beginLine;
private int endLine;
private int beginColumn;
private int endColumn;
private String modifiers;
private String fullSignature;
private String signature;
private String crosscutDesignator;
private String packageName;
private String kind;
private String declaringType;
private String filename;
private String formalComment;
private Declaration[] declarations;
private Handle crosscutDeclarationHandle;
private Handle[] pointedToByHandles;
private Handle[] pointsToHandles;
transient private Declaration crosscutDeclaration;
transient private Declaration[] pointedToBy = null;
transient private Declaration[] pointsTo = null;
private Declaration parentDeclaration = null;
private IProgramElement node;
public Declaration(int beginLine, int endLine, int beginColumn, int endColumn,
String modifiers, String signature, String fullSignature,
String crosscutDesignator,
String declaringType, String kind,
String filename, String formalComment,
String packageName,
IProgramElement node)
{
this.beginLine = beginLine;
this.endLine = endLine;
this.beginColumn = beginColumn;
this.endColumn = endColumn;
this.modifiers = modifiers;
this.signature = signature;
this.fullSignature = fullSignature;
this.crosscutDesignator = crosscutDesignator;
this.declaringType = declaringType;
this.kind = kind;
this.filename = filename;
this.formalComment = formalComment;
this.packageName = packageName;
this.pointedToByHandles = new Handle[0];
this.pointsToHandles = new Handle[0];
//???
this.declarations = new Declaration[0];
this.node = node;
}
public int getBeginLine() { return beginLine; }
public int getEndLine() { return endLine; }
public int getBeginColumn() { return beginColumn; }
public int getEndColumn() { return endColumn; }
public String getModifiers() { return modifiers; }
public String getFullSignature() { return fullSignature; }
public String getSignature() { return signature; }
public String getPackageName() { return packageName; }
public String getCrosscutDesignator() { return crosscutDesignator; }
public Declaration getParentDeclaration() { return parentDeclaration; }
public Declaration getCrosscutDeclaration() {
if (crosscutDeclaration == null && crosscutDeclarationHandle != null) {
crosscutDeclaration = crosscutDeclarationHandle.resolve();
}
return crosscutDeclaration;
}
public void setCrosscutDeclaration(Declaration _crosscutDeclaration) {
crosscutDeclaration = _crosscutDeclaration;
}
public String getDeclaringType() { return declaringType; }
public String getKind() {
if (kind.startsWith("introduced-")) {
return kind.substring(11);
} else {
return kind;
}
}
public String getFilename() { return filename; }
public String getFormalComment() { return formalComment; }
public Declaration[] getDeclarations() {
return declarations;
}
public void setDeclarations(Declaration[] decs) {
declarations = decs;
if (decs != null) {
for (int i = 0; i < decs.length; i++) {
decs[i].parentDeclaration = this;
}
}
}
public void setPointedToBy(Declaration[] decs) { pointedToBy = decs; }
public void setPointsTo(Declaration[] decs) { pointsTo = decs; }
public Declaration[] getPointedToBy() {
if (pointedToBy == null) {
pointedToBy = resolveHandles(pointedToByHandles);
}
return pointedToBy; //.elements();
}
public Declaration[] getPointsTo() {
if (pointsTo == null) {
pointsTo = resolveHandles(pointsToHandles);
}
return pointsTo; //.elements();
}
private Declaration[] filterTypes(Declaration[] a_decs) {
List decs = new LinkedList(Arrays.asList(a_decs));
for(Iterator i = decs.iterator(); i.hasNext(); ) {
Declaration dec = (Declaration)i.next();
if (!dec.isType()) i.remove();
}
return (Declaration[])decs.toArray(new Declaration[decs.size()]);
}
public Declaration[] getTargets() {
Declaration[] pointsTo = getPointsTo();
if (kind.equals("advice")) {
return pointsTo;
} else if (kind.equals("introduction")) {
return filterTypes(pointsTo);
} else {
return new Declaration[0];
}
}
// Handles are used to deal with dependencies between Declarations in different files
private Handle getHandle() {
return new Handle(filename, beginLine, beginColumn);
}
private Declaration[] resolveHandles(Handle[] handles) {
Declaration[] declarations = new Declaration[handles.length];
int missed = 0;
for(int i=0; i<handles.length; i++) {
//if (handles[i] == null) continue;
declarations[i] = handles[i].resolve();
if (declarations[i] == null) missed++;
}
if (missed > 0) {
Declaration[] decs = new Declaration[declarations.length - missed];
for (int i=0, j=0; i < declarations.length; i++) {
if (declarations[i] != null) decs[j++] = declarations[i];
}
declarations = decs;
}
return declarations;
}
private Handle[] getHandles(Declaration[] declarations) {
Handle[] handles = new Handle[declarations.length];
for(int i=0; i<declarations.length; i++) {
//if (declarations[i] == null) continue;
handles[i] = declarations[i].getHandle();
}
return handles;
}
// Make sure that all decs are convertted to handles before serialization
private void writeObject(ObjectOutputStream out) throws IOException {
pointedToByHandles = getHandles(getPointedToBy());
pointsToHandles = getHandles(getPointsTo());
if (crosscutDeclaration != null) {
crosscutDeclarationHandle = crosscutDeclaration.getHandle();
}
out.defaultWriteObject();
}
// support functions
public Declaration[] getCrosscutDeclarations() {
return getDeclarationsHelper("pointcut");
}
public Declaration[] getAdviceDeclarations() {
return getDeclarationsHelper("advice");
}
public Declaration[] getIntroductionDeclarations() {
return getDeclarationsHelper("introduction");
}
private Declaration[] getDeclarationsHelper(String kind) {
Declaration[] decls = getDeclarations();
List result = new ArrayList();
for ( int i = 0; i < decls.length; i++ ) {
Declaration decl = decls[i];
if ( decl.getKind().equals(kind) ) {
result.add(decl);
}
}
return (Declaration[])result.toArray(new Declaration[result.size()]);
}
public boolean isType() {
return getKind().equals("interface") || getKind().equals("class") || getKind().equals("aspect") || getKind().equals("enum");
}
public boolean hasBody() {
String kind = getKind();
return kind.equals("class") || kind.endsWith("constructor") ||
(kind.endsWith("method") && getModifiers().indexOf("abstract") == -1 &&
getModifiers().indexOf("native") == -1);
}
public boolean isIntroduced() {
return kind.startsWith("introduced-");
}
public boolean hasSignature() {
String kind = getKind();
if ( kind.equals( "class" ) ||
kind.equals( "interface" ) ||
kind.equals( "initializer" ) ||
kind.equals( "field" ) ||
kind.equals( "constructor" ) ||
kind.equals( "method" ) ) {
return true;
}
else {
return false;
}
}
private static class Handle implements Serializable {
public String filename;
public int line, column;
public Handle(String filename, int line, int column) {
this.filename = filename;
this.line = line;
this.column = column;
}
public Declaration resolve() {
SymbolManager manager = SymbolManager.getDefault();
return manager.getDeclarationAtPoint(filename, line, column);
}
}
public IProgramElement getNode() {
return node;
}
}
|
58,524 |
Bug 58524 ajdoc should not use the Declaration and SymbolManager classes
|
In order to speed up porting porting to the old HTML generation code ajdoc continues to use the following classes: org.aspectj.tools.ajdoc.Declaration org.aspectj.tools.ajdoc.SymbolManager These funtion only as a wrapper to the ASM, and are not needed. The next refactoring effort should get rid of them (and all those static methods as well!).
|
resolved fixed
|
f4c8bf9
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-01-16T16:46:54Z | 2004-04-14T16:26:40Z |
ajdoc/src/org/aspectj/tools/ajdoc/HtmlDecorator.java
|
/* *******************************************************************
* Copyright (c) 1999-2001 Xerox Corporation,
* 2002 Palo Alto Research Center, Incorporated (PARC).
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* Xerox/PARC initial implementation
* Mik Kersten port to AspectJ 1.1+ code base
* ******************************************************************/
package org.aspectj.tools.ajdoc;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import java.util.StringTokenizer;
import org.aspectj.asm.AsmManager;
import org.aspectj.asm.IProgramElement;
import org.aspectj.asm.IRelationship;
import org.aspectj.util.TypeSafeEnum;
/**
* @author Mik Kersten
*/
class HtmlDecorator {
private static final String POINTCUT_DETAIL = "Pointcut Detail";
private static final String ADVICE_DETAIL = "Advice Detail";
private static final String DECLARE_DETAIL = "Declare Detail";
private static final String ADVICE_SUMMARY = "Advice Summary";
private static final String POINTCUT_SUMMARY = "Pointcut Summary";
private static final String DECLARE_SUMMARY = "Declare Summary";
private static final String ITD_METHOD_SUMMARY = "Inter-Type Method Summary";
private static final String ITD_FIELD_SUMMARY = "Inter-Type Field Summary";
private static final String ITD_CONSTRUCTOR_SUMMARY = "Inter-Type Constructor Summary";
static List visibleFileList = new ArrayList();
static Hashtable declIDTable = null;
static SymbolManager symbolManager = null;
static File rootDir = null;
static String docVisibilityModifier;
static void decorateHTMLFromInputFiles(Hashtable table,
File newRootDir,
SymbolManager sm,
File[] inputFiles,
String docModifier ) throws IOException {
rootDir = newRootDir;
declIDTable = table;
symbolManager = sm;
docVisibilityModifier = docModifier;
for (int i = 0; i < inputFiles.length; i++) {
decorateHTMLFromDecls(symbolManager.getDeclarations(inputFiles[i].getCanonicalPath()),
rootDir.getCanonicalPath() + Config.DIR_SEP_CHAR,
docModifier,
false);
}
}
static void decorateHTMLFromDecls(Declaration[] decls, String base, String docModifier, boolean exceededNestingLevel) throws IOException {
if ( decls != null ) {
for (int i = 0; i < decls.length; i++) {
Declaration decl = decls[i];
decorateHTMLFromDecl(decl, base, docModifier, exceededNestingLevel);
}
}
}
/**
* Before attempting to decorate the HTML file we have to verify that it exists,
* which depends on the documentation visibility specified to c.
*
* Depending on docModifier, can document
* - public: only public
* - protected: protected and public (default)
* - package: package protected and public
* - private: everything
*/
static void decorateHTMLFromDecl(Declaration decl,
String base,
String docModifier,
boolean exceededNestingLevel ) throws IOException {
boolean nestedClass = false;
if ( decl.isType() ) {
boolean decorateFile = true;
if (isAboveVisibility(decl.getNode())) {
visibleFileList.add(decl.getSignature());
String packageName = decl.getPackageName();
String filename = "";
if ( packageName != null ) {
int index1 = base.lastIndexOf(Config.DIR_SEP_CHAR);
int index2 = base.lastIndexOf(".");
String currFileClass = "";
if (index1 > -1 && index2 > 0 && index1 < index2) {
currFileClass = base.substring(index1+1, index2);
}
// XXX only one level of nexting
if (currFileClass.equals(decl.getDeclaringType())) {
nestedClass = true;
packageName = packageName.replace( '.','/' );
String newBase = "";
if ( base.lastIndexOf(Config.DIR_SEP_CHAR) > 0 ) {
newBase = base.substring(0, base.lastIndexOf(Config.DIR_SEP_CHAR));
}
String signature = constructNestedTypeName(decl.getNode());
filename = newBase + Config.DIR_SEP_CHAR + packageName +
Config.DIR_SEP_CHAR + currFileClass + //"." +
signature + ".html";
} else {
packageName = packageName.replace( '.','/' );
filename = base + packageName + Config.DIR_SEP_CHAR + decl.getSignature() + ".html";
}
}
else {
filename = base + decl.getSignature() + ".html";
}
if (!exceededNestingLevel) {
decorateHTMLFile(new File(filename));
decorateHTMLFromDecls(decl.getDeclarations(),
base + decl.getSignature() + ".",
docModifier,
nestedClass);
}
else {
System.out.println("Warning: can not generate documentation for nested " +
"inner class: " + decl.getSignature() );
}
}
}
}
private static String constructNestedTypeName(IProgramElement node) {
if (node.getParent().getKind().isSourceFile()) {
return node.getName();
} else {
String nodeName = "";
if (node.getKind().isType()) nodeName += '.' + node.getName();
return constructNestedTypeName(node.getParent()) + nodeName;
}
}
/**
* Skips files that are public in the model but not public in the source,
* e.g. nested aspects.
*/
static void decorateHTMLFile(File file) throws IOException {
if (!file.exists()) return;
System.out.println( "> Decorating " + file.getCanonicalPath() + "..." );
BufferedReader reader = new BufferedReader(new FileReader(file));
StringBuffer fileContents = new StringBuffer();
String line = reader.readLine();
while( line != null ) {
fileContents.append(line + "\n");
line = reader.readLine();
}
boolean isSecond = false;
int index = 0;
IProgramElement decl;
while ( true ) {
//---this next part is an inlined procedure that returns two values---
//---the next declaration and the index at which that declaration's---
//---DeclID sits in the .html file ---
String contents = fileContents.toString();
int start = contents.indexOf( Config.DECL_ID_STRING, index);
int end = contents.indexOf( Config.DECL_ID_TERMINATOR, index );
if ( start == -1 )
decl = null;
else if ( end == -1 )
throw new Error("Malformed DeclID.");
else {
String tid = contents.substring(start + Config.DECL_ID_STRING.length(), end);
decl = (IProgramElement)declIDTable.get(tid);
index = start;
}
//--- ---
//--- ---
if ( decl == null ) break;
fileContents.delete(start, end + Config.DECL_ID_TERMINATOR.length());
if ( decl.getKind().isType() ) {
isSecond = true;
// addIntroductionDocumentation(decl, fileContents, index);
// addAdviceDocumentation(decl, fileContents, index);
// addPointcutDocumentation(decl, fileContents, index);
String fullname = "";
if (decl.getParent().getKind().equals(IProgramElement.Kind.ASPECT)
|| decl.getParent().getKind().equals(IProgramElement.Kind.CLASS)) {
fullname += decl.getParent().toSignatureString().concat(".").concat(decl.toSignatureString());
} else {
fullname += decl.toSignatureString();
}
// only add aspect documentation if we're in the correct
// file for the given IProgramElement
if (file.getName().indexOf(fullname + ".html") != -1) {
addAspectDocumentation(decl, fileContents, index);
}
}
else {
decorateMemberDocumentation(decl, fileContents, index);
}
// Change "Class" to "Aspect"
// moved this here because then can use the IProgramElement.Kind
// rather than checking to see if there's advice - this fixes
// the case with an inner aspect not having the title "Aspect"
if(decl.getKind().equals(IProgramElement.Kind.ASPECT)
&& file.getName().indexOf(decl.toSignatureString()) != -1) {
// only want to change "Class" to "Aspect" if we're in the
// file corresponding to the IProgramElement
String fullname = "";
if (decl.getParent().getKind().equals(IProgramElement.Kind.ASPECT)
|| decl.getParent().getKind().equals(IProgramElement.Kind.CLASS)) {
fullname += decl.getParent().toSignatureString().concat(".").concat(decl.toSignatureString());
} else {
fullname += decl.toSignatureString();
}
if (file.getName().indexOf(fullname + ".html") == -1) {
// we're still in the file for a parent IPE
continue;
}
boolean br = true;
int classStartIndex = fileContents.toString().indexOf("<BR>\nClass ");
if (classStartIndex == -1) {
classStartIndex = fileContents.toString().indexOf("<H2>\nClass ");
br = false;
}
if (classStartIndex != -1) {
int classEndIndex = fileContents.toString().indexOf("</H2>", classStartIndex);
if (classStartIndex != -1 && classEndIndex != -1) {
String classLine = fileContents.toString().substring(classStartIndex, classEndIndex);
String aspectLine = "";
if (br) {
aspectLine += "<BR>\n" + "Aspect " + classLine.substring(11, classLine.length());
} else {
aspectLine += "<H2>\n" + "Aspect " + classLine.substring(11, classLine.length());
}
fileContents.delete(classStartIndex, classEndIndex);
fileContents.insert(classStartIndex, aspectLine);
}
}
int secondClassStartIndex = fileContents.toString().indexOf("class <B>");
if (secondClassStartIndex != -1) {
String name = decl.toSignatureString();
int classEndIndex = fileContents.toString().indexOf(name + "</B><DT>");
if (secondClassStartIndex != -1 && classEndIndex != -1) {
StringBuffer sb = new StringBuffer(fileContents.toString().
substring(secondClassStartIndex,classEndIndex));
sb.replace(0,5,"aspect");
fileContents.delete(secondClassStartIndex, classEndIndex);
fileContents.insert(secondClassStartIndex, sb.toString());
}
}
}
}
file.delete();
FileOutputStream fos = new FileOutputStream( file );
fos.write( fileContents.toString().getBytes() );
reader.close();
fos.close();
}
static void addAspectDocumentation(IProgramElement node, StringBuffer fileBuffer, int index ) {
List pointcuts = new ArrayList();
List advice = new ArrayList();
List declares = new ArrayList();
List methodsDeclaredOn = StructureUtil.getDeclareInterTypeTargets(node, IProgramElement.Kind.INTER_TYPE_METHOD);
if (methodsDeclaredOn != null && !methodsDeclaredOn.isEmpty()) {
insertDeclarationsSummary(fileBuffer,methodsDeclaredOn,ITD_METHOD_SUMMARY,index);
}
List fieldsDeclaredOn = StructureUtil.getDeclareInterTypeTargets(node, IProgramElement.Kind.INTER_TYPE_FIELD);
if (fieldsDeclaredOn != null && !fieldsDeclaredOn.isEmpty()) {
insertDeclarationsSummary(fileBuffer,fieldsDeclaredOn,ITD_FIELD_SUMMARY,index);
}
List constDeclaredOn = StructureUtil.getDeclareInterTypeTargets(node, IProgramElement.Kind.INTER_TYPE_CONSTRUCTOR);
if (fieldsDeclaredOn != null && !constDeclaredOn.isEmpty()) {
insertDeclarationsSummary(fileBuffer,constDeclaredOn,ITD_CONSTRUCTOR_SUMMARY,index);
}
for (Iterator it = node.getChildren().iterator(); it.hasNext(); ) {
IProgramElement member = (IProgramElement)it.next();
if (member.getKind().equals(IProgramElement.Kind.POINTCUT)) {
pointcuts.add(member);
} else if (member.getKind().equals(IProgramElement.Kind.ADVICE)) {
advice.add(member);
} else if (member.getKind().isDeclare() || member.getKind().isInterTypeMember()) {
declares.add(member);
}
}
if (declares.size() > 0) {
insertDeclarationsDetails(fileBuffer, declares, DECLARE_DETAIL, index);
insertDeclarationsSummary(fileBuffer, declares, DECLARE_SUMMARY, index);
}
if (pointcuts.size() > 0) {
insertDeclarationsSummary(fileBuffer, pointcuts, POINTCUT_SUMMARY, index);
insertDeclarationsDetails(fileBuffer, pointcuts, POINTCUT_DETAIL, index);
}
if (advice.size() > 0) {
insertDeclarationsSummary(fileBuffer, advice, ADVICE_SUMMARY, index);
insertDeclarationsDetails(fileBuffer, advice, ADVICE_DETAIL, index);
}
// add the 'aspect declarations' information against the type
List parentsDeclaredOn = StructureUtil.getDeclareInterTypeTargets(node, IProgramElement.Kind.DECLARE_PARENTS);
if (parentsDeclaredOn != null && parentsDeclaredOn.size() > 0) {
decorateDocWithRel(node,fileBuffer,index,parentsDeclaredOn,HtmlRelationshipKind.ASPECT_DECLARATIONS);
}
// add the 'annotated by' information against the type
List annotatedBy = StructureUtil.getTargets(node,IRelationship.Kind.DECLARE_INTER_TYPE,"annotated by");
if (annotatedBy != null && annotatedBy.size() > 0) {
decorateDocWithRel(node,fileBuffer,index,annotatedBy,HtmlRelationshipKind.ANNOTATED_BY);
}
// add the 'advised by' information against the type
List advisedBy = StructureUtil.getTargets(node, IRelationship.Kind.ADVICE);
if (advisedBy != null && advisedBy.size() > 0) {
decorateDocWithRel(node,fileBuffer,index,advisedBy,HtmlRelationshipKind.ADVISED_BY);
}
}
// static void addIntroductionDocumentation(IProgramElement decl,
// StringBuffer fileBuffer,
// int index ) {
// Declaration[] introductions = decl.getIntroductionDeclarations();
// if ( introductions.length > 0 ) {
// insertDeclarationsSummary(fileBuffer,
// introductions,
// "Introduction Summary",
// index);
// insertDeclarationsDetails(fileBuffer,
// introductions,
// "Introduction Detail",
// index);
// }
// }
static void insertDeclarationsSummary(StringBuffer fileBuffer,
List decls,
String kind,
int index) {
if (!declsAboveVisibilityExist(decls)) return;
int insertIndex = findSummaryIndex(fileBuffer, index);
// insert the head of the table
String tableHead =
"<!-- ======== " + kind.toUpperCase() + " ======= -->\n\n" +
"<TABLE BORDER=\"1\" WIDTH=\"100%\" CELLPADDING=\"1\"" +
"CELLSPACING=\"0\"><TR><TD COLSPAN=2 BGCOLOR=\"#CCCCFF\">" +
"<FONT SIZE=\"+2\"><B>" + kind + "</B></FONT></TD></TR>\n";
fileBuffer.insert(insertIndex, tableHead);
insertIndex += tableHead.length();
// insert the body of the table
for ( int i = 0; i < decls.size(); i++ ) {
IProgramElement decl = (IProgramElement)decls.get(i);
if (isAboveVisibility(decl)) {
// insert the table row accordingly
String comment = generateSummaryComment(decl);
String entry = "";
if ( kind.equals( ADVICE_SUMMARY ) ) {
entry +=
"<TR><TD>" +
"<A HREF=\"#" + generateHREFName(decl) + "\">" +
"<TT>" + generateSignatures(decl) +
"</TT></A><BR> ";
if (!comment.equals("")) {
entry += comment + "<P>";
}
entry +=
generateAffects(decl) + "</TD>" +
"</TR><TD>\n";
}
else if ( kind.equals( POINTCUT_SUMMARY ) ) {
entry +=
"<TR><TD WIDTH=\"1%\">" +
"<FONT SIZE=-1><TT>" + genAccessibility(decl) + "</TT></FONT>" +
"</TD>\n" +
"<TD>" +
"<TT><A HREF=\"#" + generateHREFName(decl) + "\">" +
decl.toLabelString() + "</A></TT><BR> ";
if (!comment.equals("")) {
entry += comment + "<P>";
}
entry +=
"</TR></TD>\n";
}
else if ( kind.equals( DECLARE_SUMMARY ) ) {
entry +=
"<TR><TD WIDTH=\"1%\">" +
"<FONT SIZE=-1><TT>" +
generateModifierInformation(decl,false)
+ "</TT></FONT>" +
"</TD>" +
"<TD>" +
"<A HREF=\"#" + generateHREFName(decl) + "\">" +
"<TT>" + decl.toLabelString() + "</TT></A><P>" +
generateAffects(decl);
}
else if ( kind.equals( ITD_FIELD_SUMMARY )
|| kind.equals( ITD_METHOD_SUMMARY)) {
entry +=
"<TR><TD WIDTH=\"1%\">" +
"<FONT SIZE=-1><TT>" +
generateModifierInformation(decl,false) +
"</TT></FONT>" +
"</TD>" +
"<TD>" +
"<A HREF=\"#" + generateHREFName(decl) + "\">" +
"<TT>" + decl.toLabelString() + "</TT></A><P>"+
generateDeclaredBy(decl);
}
else if ( kind.equals( ITD_CONSTRUCTOR_SUMMARY ) ) {
entry +="<TD>" +
"<A HREF=\"#" + generateHREFName(decl) + "\">" +
"<TT>" + decl.toLabelString() + "</TT></A><P>"+
generateDeclaredBy(decl);
}
// insert the entry
fileBuffer.insert(insertIndex, entry);
insertIndex += entry.length();
}
}
// insert the end of the table
String tableTail = "</TABLE><P> \n";
fileBuffer.insert(insertIndex, tableTail);
insertIndex += tableTail.length();
}
private static boolean declsAboveVisibilityExist(List decls) {
boolean exist = false;
for (Iterator it = decls.iterator(); it.hasNext();) {
IProgramElement element = (IProgramElement) it.next();
if (isAboveVisibility(element)) exist = true;
}
return exist;
}
private static boolean isAboveVisibility(IProgramElement element) {
return
(docVisibilityModifier.equals("private")) || // everything
(docVisibilityModifier.equals("package") && element.getAccessibility().equals(IProgramElement.Accessibility.PACKAGE)) || // package
(docVisibilityModifier.equals("protected") && (element.getAccessibility().equals(IProgramElement.Accessibility.PROTECTED) ||
element.getAccessibility().equals(IProgramElement.Accessibility.PUBLIC))) ||
(docVisibilityModifier.equals("public") && element.getAccessibility().equals(IProgramElement.Accessibility.PUBLIC));
}
private static String genAccessibility(IProgramElement decl) {
if (decl.getAccessibility().equals(IProgramElement.Accessibility.PACKAGE)) {
return "(package private)";
} else {
return decl.getAccessibility().toString();
}
}
static void insertDeclarationsDetails(StringBuffer fileBuffer,
List decls,
String kind,
int index) {
if (!declsAboveVisibilityExist(decls)) return;
int insertIndex = findDetailsIndex(fileBuffer, index);
// insert the table heading
String detailsHeading
= "<P> \n" +
"<!-- ======== " + kind.toUpperCase() + " SUMMARY ======= -->\n\n" +
"<TABLE BORDER=\"1\" CELLPADDING=\"3\" CELLSPACING=\"0\" WIDTH=\"100%\">\n" +
"<TR BGCOLOR=\"#CCCCFF\" CLASS=\"TableHeadingColor\">\n" +
"<TD COLSPAN=1><FONT SIZE=\"+2\">\n" +
"<B>" + kind + "</B></FONT></TD>\n" +
"</TR>\n" +
"</TABLE>";
fileBuffer.insert(insertIndex, detailsHeading);
insertIndex += detailsHeading.length();
// insert the details
for ( int i = 0; i < decls.size(); i++ ) {
IProgramElement decl = (IProgramElement)decls.get(i);
if (isAboveVisibility(decl)) {
String entry = "";
// insert the table row accordingly
entry += "<A NAME=\"" + generateHREFName(decl) + "\"><!-- --></A>\n";
if ( kind.equals( ADVICE_DETAIL ) ) {
entry += "<H3>" + decl.getName() + "</H3><P>";
entry +=
"<TT>" +
generateSignatures(decl) + "</TT>\n" + "<P>" +
generateDetailsComment(decl) + "<P>" +
generateAffects(decl);
}
else if (kind.equals(POINTCUT_DETAIL)) {
entry +=
"<H3>" +
decl.toLabelString() +
"</H3><P>" +
generateDetailsComment(decl);
}
else if (kind.equals(DECLARE_DETAIL)) {
entry += "<H3>" + decl.toLabelString() +
"</H3><P>" +
generateModifierInformation(decl,true);
if (!decl.getKind().equals(IProgramElement.Kind.INTER_TYPE_CONSTRUCTOR)) {
entry += " ";
}
// if we're not a declare statement then we need to generate the signature.
// If we did this for declare statements we get two repeated lines
if (!decl.getKind().isDeclare()) {
entry += generateSignatures(decl) + "<P>";
}
entry += generateAffects(decl) +
generateDetailsComment(decl);
}
// insert the entry
if (i != decls.size()-1) {
entry += "<P><HR>\n";
}
else {
entry += "<P>";
}
fileBuffer.insert(insertIndex, entry);
insertIndex += entry.length();
}
}
}
/**
* TODO: don't place the summary first.
*/
static int findSummaryIndex(StringBuffer fileBuffer, int index) {
String fbs = fileBuffer.toString();
String MARKER_1 = "<!-- =========== FIELD SUMMARY =========== -->";
String MARKER_2 = "<!-- ======== CONSTRUCTOR SUMMARY ======== -->";
int index1 = fbs.indexOf(MARKER_1, index);
int index2 = fbs.indexOf(MARKER_2, index);
if (index1 < index2 && index1 != -1) {
return index1;
} else if (index2 != -1){
return index2;
} else {
return index;
}
}
static int findDetailsIndex(StringBuffer fileBuffer, int index) {
String fbs = fileBuffer.toString();
String MARKER_1 = "<!-- ========= CONSTRUCTOR DETAIL ======== -->";
String MARKER_2 = "<!-- ============ FIELD DETAIL =========== -->";
String MARKER_3 = "<!-- ============ METHOD DETAIL ========== -->";
int index1 = fbs.indexOf(MARKER_1, index);
int index2 = fbs.indexOf(MARKER_2, index);
int index3 = fbs.indexOf(MARKER_3, index);
if (index1 != -1 && index1 < index2 && index1 < index3) {
return index1;
} else if (index2 != -1 && index2 < index1 && index2 < index3) {
return index2;
} else if (index3 != -1) {
return index3;
} else {
return index;
}
}
static void decorateDocWithRel(
IProgramElement node,
StringBuffer fileContentsBuffer,
int index,
List targets,
HtmlRelationshipKind relKind) {
if (targets != null && !targets.isEmpty()) {
String adviceDoc = "<TABLE WIDTH=\"100%\" BGCOLOR=#FFFFFF><TR>" +
"<TD width=\"15%\" bgcolor=\"#FFD8B0\"><B><FONT COLOR=000000>" +
relKind.toString() +
"</font></b></td><td>";
String relativePackagePath =
getRelativePathFromHere(
node.getPackageName().replace('.', '/') + Config.DIR_SEP_CHAR);
List addedNames = new ArrayList();
for (Iterator it = targets.iterator(); it.hasNext(); ) {
Object o = it.next();
IProgramElement currDecl = null;
if (o instanceof String) {
String currHandle = (String)o;
currDecl = AsmManager.getDefault().getHierarchy().findElementForHandle(currHandle);
} else if (o instanceof IProgramElement){
currDecl = (IProgramElement)o;
} else {
return;
}
String packagePath = "";
if (currDecl.getPackageName() != null && !currDecl.getPackageName().equals("")) {
packagePath = currDecl.getPackageName().replace('.', '/') + Config.DIR_SEP_CHAR;
}
String hrefName = "";
String hrefLink = "";
// Start the hRefLink with the relative path based on where
// *this* type (i.e. the advised) is in the package structure.
hrefLink = relativePackagePath + packagePath;
if (currDecl.getPackageName() != null ) {
hrefName = currDecl.getPackageName().replace('.', '/');
// hrefLink = "";//+ currDecl.getPackageName() + Config.DIR_SEP_CHAR;
}
// in the case of nested classes, in order for the links to work,
// need to have the correct file name which is something of the
// form parentClass.nestedAspect.html
List names = new ArrayList();
IProgramElement parent = currDecl;
while (parent != null
&& parent.getParent() != null
&& (!parent.getParent().getKind().equals(IProgramElement.Kind.FILE_JAVA)
&& !parent.getParent().getKind().equals(IProgramElement.Kind.FILE_ASPECTJ))) {
parent = parent.getParent();
names.add(parent.toLinkLabelString());
}
StringBuffer sbuff = new StringBuffer();
for (int i = names.size() - 1; i >= 0; i--) {
String element = (String)names.get(i);
if (i == 0) {
sbuff.append(element);
} else {
sbuff.append(element + ".");
}
}
// use the currDecl.toLabelString rather than currDecl.getName()
// because two distinct advice blocks can have the same
// currDecl.getName() and wouldn't both appear in the ajdoc
hrefName += Config.DIR_SEP_CHAR +
sbuff.toString()
+ "." + currDecl.toLabelString();
// need to replace " with quot; otherwise the links wont work
// for 'matches declare' relationship
StringBuffer sb = new StringBuffer(currDecl.toLabelString());
int nextQuote = sb.toString().indexOf("\"");
while (nextQuote != -1) {
sb.deleteCharAt(nextQuote);
sb.insert(nextQuote,"quot;");
nextQuote = sb.toString().indexOf("\"");
}
hrefLink += sbuff.toString() + ".html" + "#" + sb.toString();
if (!addedNames.contains(hrefName)) {
adviceDoc = adviceDoc +
"<A HREF=\"" + hrefLink + "\"><tt>"
+ hrefName.replace('/', '.') + "</tt></A>";
if (it.hasNext()) adviceDoc += ", ";
addedNames.add(hrefName);
}
}
adviceDoc += "</TR></TD></TABLE>\n";
fileContentsBuffer.insert( index, adviceDoc );
}
}
static void decorateMemberDocumentation(IProgramElement node,
StringBuffer fileContentsBuffer,
int index ) {
List targets = StructureUtil.getTargets(node, IRelationship.Kind.ADVICE);
decorateDocWithRel(node,fileContentsBuffer,index,targets,HtmlRelationshipKind.ADVISED_BY);
List warnings = StructureUtil.getTargets(node,IRelationship.Kind.DECLARE,"matches declare");
decorateDocWithRel(node,fileContentsBuffer,index,warnings,HtmlRelationshipKind.MATCHES_DECLARE);
List softenedBy = StructureUtil.getTargets(node,IRelationship.Kind.DECLARE,"softened by");
decorateDocWithRel(node,fileContentsBuffer,index,softenedBy,HtmlRelationshipKind.SOFTENED_BY);
List annotatedBy = StructureUtil.getTargets(node,IRelationship.Kind.DECLARE_INTER_TYPE,"annotated by");
decorateDocWithRel(node,fileContentsBuffer,index,annotatedBy,HtmlRelationshipKind.ANNOTATED_BY);
}
/**
* pr119453 - adding "declared by" relationship
*/
static String generateDeclaredBy(IProgramElement decl) {
String entry = "<TABLE WIDTH=\"100%\" BGCOLOR=#FFFFFF><TR>" +
"<TD width=\"10%\" bgcolor=\"#FFD8B0\"><B><FONT COLOR=000000>" +
" Declared by:</b></font></td><td>";
String relativePackagePath =
getRelativePathFromHere(
decl.getPackageName().replace('.', '/') + Config.DIR_SEP_CHAR);
if (decl != null && !StructureUtil.isAnonymous(decl.getParent())) {
String packagePath = "";
if (decl.getPackageName() != null && !decl.getPackageName().equals("")) {
packagePath = decl.getPackageName().replace('.', '/') + Config.DIR_SEP_CHAR;
}
String typeSignature = constructNestedTypeName(decl);
String hrefName = packagePath + typeSignature;
// The hrefLink needs to just be the corresponding aspect
String hrefLink =
relativePackagePath
+ packagePath
+ typeSignature
+ ".html";
entry += "<A HREF=\"" + hrefLink +
"\"><tt>" + hrefName.replace('/', '.') + "</tt></A>"; // !!! don't replace
}
entry += "</B></FONT></TD></TR></TABLE>\n</TR></TD>\n";
return entry;
}
/**
* TODO: probably want to make this the same for intros and advice.
*/
static String generateAffects(IProgramElement decl) {
List targets = null;
if (decl.getKind().isDeclare() || decl.getKind().isInterTypeMember()) {
targets = StructureUtil.getDeclareTargets(decl);
} else {
targets = StructureUtil.getTargets(decl, IRelationship.Kind.ADVICE);
}
if (targets == null) return "";
String entry = "<TABLE WIDTH=\"100%\" BGCOLOR=#FFFFFF><TR>";
IProgramElement.Kind kind = decl.getKind();
if (kind.equals(IProgramElement.Kind.ADVICE)) {
entry += "<TD width=\"10%\" bgcolor=\"#FFD8B0\"><B><FONT COLOR=000000>" +
HtmlRelationshipKind.ADVISES.toString() +
"</b></font></td><td>";
} else if (kind.equals(IProgramElement.Kind.DECLARE_WARNING)
|| kind.equals(IProgramElement.Kind.DECLARE_ERROR)) {
entry += "<TD width=\"10%\" bgcolor=\"#FFD8B0\"><B><FONT COLOR=000000>" +
HtmlRelationshipKind.MATCHED_BY.toString() +
"</b></font></td><td>";
} else if (kind.isDeclareAnnotation()) {
entry += "<TD width=\"10%\" bgcolor=\"#FFD8B0\"><B><FONT COLOR=000000>" +
HtmlRelationshipKind.ANNOTATES.toString() +
"</b></font></td><td>";
} else if (kind.equals(IProgramElement.Kind.DECLARE_SOFT)) {
entry += "<TD width=\"10%\" bgcolor=\"#FFD8B0\"><B><FONT COLOR=000000>" +
HtmlRelationshipKind.SOFTENS.toString() +
"</b></font></td><td>";
} else {
entry += "<TD width=\"10%\" bgcolor=\"#FFD8B0\"><B><FONT COLOR=000000>" +
HtmlRelationshipKind.DECLARED_ON.toString() +
"</b></font></td><td>";
}
String relativePackagePath =
getRelativePathFromHere(
decl.getPackageName().replace('.', '/') + Config.DIR_SEP_CHAR);
List addedNames = new ArrayList(); // for ensuring that we don't add duplciates
for (Iterator it = targets.iterator(); it.hasNext(); ) {
String currHandle = (String)it.next();
IProgramElement currDecl = AsmManager.getDefault().getHierarchy().findElementForHandle(currHandle);
if (currDecl.getKind().equals(IProgramElement.Kind.CODE)) {
currDecl = currDecl.getParent(); // promote to enclosing
}
if (currDecl != null && !StructureUtil.isAnonymous(currDecl.getParent())) {
String packagePath = "";
if (currDecl.getPackageName() != null && !currDecl.getPackageName().equals("")) {
packagePath = currDecl.getPackageName().replace('.', '/') + Config.DIR_SEP_CHAR;
}
String typeSignature = constructNestedTypeName(currDecl);
String hrefName =
packagePath
+ typeSignature;
// Start the hRefLink with the relative path based on where
// *this* type (i.e. the advisor) is in the package structure.
String hrefLink =
relativePackagePath
+ packagePath
+ typeSignature
+ ".html";
if (!currDecl.getKind().isType()) {
hrefName += '.' + currDecl.getName();
hrefLink += "#" + currDecl.toLabelString();
}
if (!addedNames.contains(hrefName)) {
entry += "<A HREF=\"" + hrefLink +
"\"><tt>" + hrefName.replace('/', '.') + "</tt></A>"; // !!! don't replace
if (it.hasNext()) entry += ", ";
addedNames.add(hrefName);
}
}
}
entry += "</B></FONT></TD></TR></TABLE>\n</TR></TD>\n";
return entry;
}
/**
* Generates a relative directory path fragment that can be
* used to navigate "upwards" from the directory location
* implied by the argument.
* @param packagePath
* @return String consisting of multiple "../" parts, one for
* each component part of the input <code>packagePath</code>.
*/
private static String getRelativePathFromHere(String packagePath) {
StringBuffer result = new StringBuffer("");
if (packagePath != null && (packagePath.indexOf("/") != -1)) {
StringTokenizer sTok = new StringTokenizer(packagePath, "/", false);
while (sTok.hasMoreTokens()) {
sTok.nextToken(); // don't care about the token value
result.append(".." + Config.DIR_SEP_CHAR);
}// end while
}// end if
return result.toString();
}
/**
* Generate the "public int"-type information about the given IProgramElement.
* Used when dealing with ITDs. To mirror the behaviour of methods and fields
* in classes, if we're generating the summary information we don't want to
* include "public" if the accessibility of the IProgramElement is public.
*
*/
private static String generateModifierInformation(IProgramElement decl, boolean isDetails) {
String intro = "";
if (decl.getKind().isDeclare()) {
return intro + "</TT>";
}
if (isDetails ||
!decl.getAccessibility().equals(IProgramElement.Accessibility.PUBLIC)) {
intro += "<TT>" + decl.getAccessibility().toString() + " " ;
}
if (decl.getKind().equals(IProgramElement.Kind.INTER_TYPE_FIELD)) {
return intro + decl.getCorrespondingType() + "</TT>";
} else if (decl.getKind().equals(IProgramElement.Kind.INTER_TYPE_CONSTRUCTOR)
&& isDetails) {
return intro + "</TT>";
} else {
return intro + decl.getCorrespondingType(true) + "</TT>";
}
}
static String generateIntroductionSignatures(IProgramElement decl, boolean isDetails) {
return "<not implemented>";
// Declaration[] decls = decl.getDeclarations();
// String entry = "";
// for ( int j = 0; j < decls.length; j++ ) {
// Declaration currDecl = decls[j];
// if ( currDecl != null ) {
// entry +=
// "<TT><B>" +
// currDecl.getSignature() +
// "</B></TT><BR>";
// }
// if (isDetails) {
// entry += generateDetailsComment(currDecl) + "<P>";
// }
// else {
// entry += generateSummaryComment(currDecl) + "<P>";
// }
// }
// return entry;
}
static String generateSignatures(IProgramElement decl ) {
return "<B>" + decl.toLabelString() + "</B>";
}
static String generateSummaryComment(IProgramElement decl) {
String COMMENT_INDENT = " "; // !!!
String formattedComment = getFormattedComment(decl);
int periodIndex = formattedComment.indexOf( '.' );
if (formattedComment.equals("")) {
return "";
}
else if ( periodIndex != -1 ) {
return COMMENT_INDENT + formattedComment.substring( 0, periodIndex+1 ) ;
}
else {
return COMMENT_INDENT + formattedComment;
}
}
static String generateDetailsComment(IProgramElement decl) {
return getFormattedComment(decl);
}
static String generateHREFName(IProgramElement decl) {
//String hrefLink = decl.toLabelString().replace("\"", "quot;"); // !!!
StringBuffer hrefLinkBuffer = new StringBuffer();
char[] declChars = decl.toLabelString().toCharArray();
for (int i = 0; i < declChars.length; i++) {
if (declChars[i] == '"') {
hrefLinkBuffer.append("quot;");
} else {
hrefLinkBuffer.append(declChars[i]);
}
}
return hrefLinkBuffer.toString();
}
/**
* Figure out the link relative to the package.
*/
static String generateAffectsHREFLink(String declaringType) {
String link = rootDir.getAbsolutePath() + "/" + declaringType + ".html";
return link;
}
/**
* This formats a comment according to the rules in the Java Langauge Spec:
* <I>The text of a docuemntation comment consists of the characters between
* the /** that begins the comment and the 'star-slash' that ends it. The text is
* devided into one or more lines. On each of these lines, the leading *
* characters are ignored; for lines other than the first, blanks and
* tabs preceding the initial * characters are also discarded.</I>
*
* TODO: implement formatting or linking for tags.
*/
static String getFormattedComment(IProgramElement decl) {
String comment = decl.getFormalComment();
if (comment == null) return "";
String formattedComment = "";
// strip the comment markers
int startIndex = comment.indexOf("/**");
int endIndex = comment.indexOf("*/");
if ( startIndex == -1 ) {
startIndex = 0;
}
else {
startIndex += 3;
}
if ( endIndex == -1 ) {
endIndex = comment.length();
}
comment = comment.substring( startIndex, endIndex );
// string the leading whitespace and '*' characters at the beginning of each line
BufferedReader reader
= new BufferedReader( new StringReader( comment ) );
try {
for (String line = reader.readLine(); line != null; line = reader.readLine()) {
line = line.trim();
for (int i = 0; i < line.length(); i++ ) {
if ( line.charAt(0) == '*' ) {
line = line.substring(1, line.length());
}
else {
break;
}
}
// !!! remove any @see and @link tags from the line
//int seeIndex = line.indexOf("@see");
//int linkIndex = line.indexOf("@link");
//if ( seeIndex != -1 ) {
// line = line.substring(0, seeIndex) + line.substring(seeIndex);
//}
//if ( linkIndex != -1 ) {
// line = line.substring(0, linkIndex) + line.substring(linkIndex);
//}
formattedComment += line;
}
} catch ( IOException ioe ) {
throw new Error( "Couldn't format comment for declaration: " +
decl.getName() );
}
return formattedComment;
}
/**
* TypeSafeEnum for the entries which need to be put in the html doc
*/
public static class HtmlRelationshipKind extends TypeSafeEnum {
public HtmlRelationshipKind(String name, int key) {
super(name, key);
}
public static HtmlRelationshipKind read(DataInputStream s) throws IOException {
int key = s.readByte();
switch(key) {
case 1: return ADVISES;
case 2: return ADVISED_BY;
case 3: return MATCHED_BY;
case 4: return MATCHES_DECLARE;
case 5: return DECLARED_ON;
case 6: return ASPECT_DECLARATIONS;
case 7: return SOFTENS;
case 8: return SOFTENED_BY;
case 9: return ANNOTATES;
case 10: return ANNOTATED_BY;
case 11: return USES_POINTCUT;
case 12: return POINTCUT_USED_BY;
}
throw new Error("weird relationship kind " + key);
}
public static final HtmlRelationshipKind ADVISES = new HtmlRelationshipKind(" Advises:", 1);
public static final HtmlRelationshipKind ADVISED_BY = new HtmlRelationshipKind(" Advised by:", 2);
public static final HtmlRelationshipKind MATCHED_BY = new HtmlRelationshipKind(" Matched by:", 3);
public static final HtmlRelationshipKind MATCHES_DECLARE = new HtmlRelationshipKind(" Matches declare:", 4);
public static final HtmlRelationshipKind DECLARED_ON = new HtmlRelationshipKind(" Declared on:", 5);
public static final HtmlRelationshipKind ASPECT_DECLARATIONS = new HtmlRelationshipKind(" Aspect declarations:", 6);
public static final HtmlRelationshipKind SOFTENS = new HtmlRelationshipKind(" Softens:", 7);
public static final HtmlRelationshipKind SOFTENED_BY = new HtmlRelationshipKind(" Softened by:", 8);
public static final HtmlRelationshipKind ANNOTATES = new HtmlRelationshipKind(" Annotates:", 9);
public static final HtmlRelationshipKind ANNOTATED_BY = new HtmlRelationshipKind(" Annotated by:", 10);
public static final HtmlRelationshipKind USES_POINTCUT = new HtmlRelationshipKind(" Uses pointcut:", 11);
public static final HtmlRelationshipKind POINTCUT_USED_BY = new HtmlRelationshipKind(" Pointcut used by:", 12);
}
}
|
58,524 |
Bug 58524 ajdoc should not use the Declaration and SymbolManager classes
|
In order to speed up porting porting to the old HTML generation code ajdoc continues to use the following classes: org.aspectj.tools.ajdoc.Declaration org.aspectj.tools.ajdoc.SymbolManager These funtion only as a wrapper to the ASM, and are not needed. The next refactoring effort should get rid of them (and all those static methods as well!).
|
resolved fixed
|
f4c8bf9
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-01-16T16:46:54Z | 2004-04-14T16:26:40Z |
ajdoc/src/org/aspectj/tools/ajdoc/Main.java
|
/* *******************************************************************
* Copyright (c) 1999-2001 Xerox Corporation,
* 2002 Palo Alto Research Center, Incorporated (PARC).
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* Xerox/PARC initial implementation
* Mik Kersten port to AspectJ 1.1+ code base
* ******************************************************************/
package org.aspectj.tools.ajdoc;
import java.io.*;
import java.util.*;
import java.io.FileFilter;
import org.aspectj.bridge.Version;
import org.aspectj.util.FileUtil;
/**
* This is an old implementation of ajdoc that does not use an OO style. However, it
* does the job, and should serve to evolve a lightweight ajdoc implementation until
* we can make a properly extended javadoc implementation.
*
* @author Mik Kersten
*/
public class Main implements Config {
private static final String FAIL_MESSAGE = "> compile failed, exiting ajdoc";
static SymbolManager symbolManager = null;
/** Command line options. */
static Vector options;
/** Options to pass to ajc. */
static Vector ajcOptions;
/** All of the files to be processed by ajdoc. */
static Vector filenames;
/** List of files to pass to javadoc. */
static Vector fileList;
/** List of packages to pass to javadoc. */
static Vector packageList;
/** Default to package visiblity. */
static String docModifier = "package";
static Vector sourcepath;
static boolean verboseMode = false;
static boolean packageMode = false;
static boolean authorStandardDocletSwitch = false;
static boolean versionStandardDocletSwitch = false;
static File rootDir = null;
static Hashtable declIDTable = new Hashtable();
static String docDir = ".";
private static boolean deleteTempFilesOnExit = true;
private static boolean aborted = false;
// creating a local variable to enable us to create the ajdocworkingdir
// in a local sandbox during testing
private static String outputWorkingDir = Config.WORKING_DIR;
public static void clearState() {
symbolManager = null;
options = new Vector();
ajcOptions = new Vector();
filenames = new Vector();
fileList= new Vector();
packageList = new Vector();
docModifier = "package";
sourcepath = new Vector();
verboseMode = false;
packageMode = false;
rootDir = null;
declIDTable = new Hashtable();
docDir = ".";
aborted = false;
deleteTempFilesOnExit = true;
}
public static void main(String[] args) {
clearState();
if (!JavadocRunner.has14ToolsAvailable()) {
System.err.println("ajdoc requires a JDK 1.4 or later tools jar - exiting");
aborted = true;
return;
}
// STEP 1: parse the command line and do other global setup
sourcepath.addElement("."); // add the current directory to the classapth
parseCommandLine(args);
rootDir = getRootDir();
symbolManager = SymbolManager.getDefault();
File[] inputFiles = new File[filenames.size()];
File[] signatureFiles = new File[filenames.size()];
try {
// create the workingdir if it doesn't exist
if ( !(new File( outputWorkingDir ).isDirectory()) ) {
File dir = new File( outputWorkingDir );
dir.mkdir();
if (deleteTempFilesOnExit) dir.deleteOnExit();
}
for (int i = 0; i < filenames.size(); i++) {
inputFiles[i] = new File((String)filenames.elementAt(i));
//signatureFiles[i] = createSignatureFile(inputFiles[i]);
}
// PHASE 0: call ajc
ajcOptions.addElement("-noExit");
ajcOptions.addElement("-XjavadocsInModel"); // TODO: wrong option to force model gen
ajcOptions.addElement("-d");
ajcOptions.addElement(rootDir.getAbsolutePath());
String[] argsToCompiler = new String[ajcOptions.size() + inputFiles.length];
int i = 0;
for ( ; i < ajcOptions.size(); i++ ) {
argsToCompiler[i] = (String)ajcOptions.elementAt(i);
}
for ( int j = 0; j < inputFiles.length; j++) {
argsToCompiler[i] = inputFiles[j].getAbsolutePath();
//System.out.println(">> file to ajc: " + inputFiles[j].getAbsolutePath());
i++;
}
// System.out.println(Arrays.asList(argsToCompiler));
System.out.println( "> Calling ajc..." );
CompilerWrapper.main(argsToCompiler);
if (CompilerWrapper.hasErrors()) {
System.out.println(FAIL_MESSAGE);
aborted = true;
return;
}
/*
for (int ii = 0; ii < inputFiles.length; ii++) {
String tempFP = inputFiles[ii].getAbsolutePath();
tempFP = tempFP.substring(0, tempFP.length()-4);
tempFP += "ajsym";
System.out.println( ">> checking: " + tempFP);
File tempF = new File(tempFP);
if ( !tempF.exists() ) System.out.println( ">>> doesn't exist!" );
}
*/
for (int ii = 0; ii < filenames.size(); ii++) {
signatureFiles[ii] = createSignatureFile(inputFiles[ii]);
}
// PHASE 1: generate Signature files (Java with DeclIDs and no bodies).
System.out.println( "> Building signature files..." );
try{
StubFileGenerator.doFiles(declIDTable, symbolManager, inputFiles, signatureFiles);
} catch (DocException d){
System.err.println(d.getMessage());
// d.printStackTrace();
return;
}
// PHASE 2: let Javadoc generate HTML (with DeclIDs)
System.out.println( "> Calling javadoc..." );
String[] javadocargs = null;
if ( packageMode ) {
int numExtraArgs = 2;
if (authorStandardDocletSwitch) numExtraArgs++;
if (versionStandardDocletSwitch) numExtraArgs++;
javadocargs = new String[numExtraArgs + options.size() + packageList.size() +
fileList.size() ];
javadocargs[0] = "-sourcepath";
javadocargs[1] = outputWorkingDir;
int argIndex = 2;
if (authorStandardDocletSwitch) {
javadocargs[argIndex] = "-author";
argIndex++;
}
if (versionStandardDocletSwitch) {
javadocargs[argIndex] = "-version";
}
//javadocargs[1] = getSourcepathAsString();
for (int k = 0; k < options.size(); k++) {
javadocargs[numExtraArgs+k] = (String)options.elementAt(k);
}
for (int k = 0; k < packageList.size(); k++) {
javadocargs[numExtraArgs+options.size() + k] = (String)packageList.elementAt(k);
}
for (int k = 0; k < fileList.size(); k++) {
javadocargs[numExtraArgs+options.size() + packageList.size() + k] = (String)fileList.elementAt(k);
}
}
else {
javadocargs = new String[options.size() + signatureFiles.length];
for (int k = 0; k < options.size(); k++) {
javadocargs[k] = (String)options.elementAt(k);
}
for (int k = 0; k < signatureFiles.length; k++) {
javadocargs[options.size() + k] = StructureUtil.translateAjPathName(signatureFiles[k].getCanonicalPath());
}
}
JavadocRunner.callJavadoc(javadocargs);
//for ( int o = 0; o < inputFiles.length; o++ ) {
// System.out.println( "file: " + inputFiles[o] );
//}
// PHASE 3: add AspectDoc specific stuff to the HTML (and remove the DeclIDS).
/** We start with the known HTML files (the ones that correspond directly to the
* input files.) As we go along, we may learn that Javadoc split one .java file
* into multiple .html files to handle inner classes or local classes. The html
* file decorator picks that up.
*/
System.out.println( "> Decorating html files..." );
HtmlDecorator.decorateHTMLFromInputFiles(declIDTable,
rootDir,
symbolManager,
inputFiles,
docModifier);
System.out.println( "> Removing generated tags (this may take a while)..." );
removeDeclIDsFromFile("index-all.html", true);
removeDeclIDsFromFile("serialized-form.html", true);
if (packageList.size() > 0) {
for (int p = 0; p < packageList.size(); p++) {
removeDeclIDsFromFile(((String)packageList.elementAt(p)).replace('.','/') +
Config.DIR_SEP_CHAR +
"package-summary.html", true);
}
} else {
File[] files = rootDir.listFiles();
if (files == null){
System.err.println("Destination directory is not a directory: " + rootDir.toString());
return;
}
files = FileUtil.listFiles(rootDir, new FileFilter() {
public boolean accept(File f) {
return f.getName().equals("package-summary.html");
}
});
for (int j = 0; j < files.length; j++) {
removeDeclIDsFromFile(files[j].getAbsolutePath(), false);
}
}
System.out.println( "> Finished." );
} catch (Throwable e) {
handleInternalError(e);
exit(-2);
}
}
private static void removeDeclIDsFromFile(String filename, boolean relativePath) {
// Remove the decl ids from "index-all.html"
File indexFile;
if (relativePath) {
indexFile = new File(docDir + Config.DIR_SEP_CHAR + filename);
} else {
indexFile = new File(filename);
}
try {
if ( indexFile.exists() ) {
BufferedReader indexFileReader = new BufferedReader( new FileReader( indexFile ) );
String indexFileBuffer = "";
String line = indexFileReader.readLine();
while ( line != null ) {
int indexStart = line.indexOf( Config.DECL_ID_STRING );
int indexEnd = line.indexOf( Config.DECL_ID_TERMINATOR );
if ( indexStart != -1 && indexEnd != -1 ) {
line = line.substring( 0, indexStart ) +
line.substring( indexEnd+Config.DECL_ID_TERMINATOR.length() );
}
indexFileBuffer += line;
line = indexFileReader.readLine();
}
FileOutputStream fos = new FileOutputStream( indexFile );
fos.write( indexFileBuffer.getBytes() );
indexFileReader.close();
fos.close();
}
}
catch (IOException ioe) {
// be siltent
}
}
static Vector getSourcePath() {
Vector sourcePath = new Vector();
boolean found = false;
for ( int i = 0; i < options.size(); i++ ) {
String currOption = (String)options.elementAt(i);
if (found && !currOption.startsWith("-")) {
sourcePath.add(currOption);
}
if (currOption.equals("-sourcepath")) {
found = true;
}
}
return sourcePath;
}
static File getRootDir() {
File rootDir = new File( "." );
for ( int i = 0; i < options.size(); i++ ) {
if ( ((String)options.elementAt(i)).equals( "-d" ) ) {
rootDir = new File((String)options.elementAt(i+1));
if ( !rootDir.exists() ) {
rootDir.mkdir();
// System.out.println( "Destination directory not found: " +
// (String)options.elementAt(i+1) );
// System.exit( -1 );
}
}
}
return rootDir;
}
static File createSignatureFile(File inputFile) throws IOException {
String packageName = StructureUtil.getPackageDeclarationFromFile(inputFile);
String filename = "";
if ( packageName != null ) {
String pathName = outputWorkingDir + '/' + packageName.replace('.', '/');
File packageDir = new File(pathName);
if ( !packageDir.exists() ) {
packageDir.mkdirs();
if (deleteTempFilesOnExit) packageDir.deleteOnExit();
}
//verifyPackageDirExists(packageName, null);
packageName = packageName.replace( '.','/' ); // !!!
filename = outputWorkingDir + Config.DIR_SEP_CHAR + packageName +
Config.DIR_SEP_CHAR + inputFile.getName();
}
else {
filename = outputWorkingDir + Config.DIR_SEP_CHAR + inputFile.getName();
}
File signatureFile = new File( filename );
if (deleteTempFilesOnExit) signatureFile.deleteOnExit();
return signatureFile;
}
// static void verifyPackageDirExists( String packageName, String offset ) {
// System.err.println(">>> name: " + packageName + ", offset: " + offset);
// if ( packageName.indexOf( "." ) != -1 ) {
// File tempFile = new File("c:/aspectj-test/d1/d2/d3");
// tempFile.mkdirs();
// String currPkgDir = packageName.substring( 0, packageName.indexOf( "." ) );
// String remainingPkg = packageName.substring( packageName.indexOf( "." )+1 );
// String filePath = null;
// if ( offset != null ) {
// filePath = Config.WORKING_DIR + Config.DIR_SEP_CHAR +
// offset + Config.DIR_SEP_CHAR + currPkgDir ;
// }
// else {
// filePath = Config.WORKING_DIR + Config.DIR_SEP_CHAR + currPkgDir;
// }
// File packageDir = new File( filePath );
// if ( !packageDir.exists() ) {
// packageDir.mkdir();
// if (deleteTempFilesOnExit) packageDir.deleteOnExit();
// }
// if ( remainingPkg != "" ) {
// verifyPackageDirExists( remainingPkg, currPkgDir );
// }
// }
// else {
// String filePath = null;
// if ( offset != null ) {
// filePath = Config.WORKING_DIR + Config.DIR_SEP_CHAR + offset + Config.DIR_SEP_CHAR + packageName;
// }
// else {
// filePath = Config.WORKING_DIR + Config.DIR_SEP_CHAR + packageName;
// }
// File packageDir = new File( filePath );
// if ( !packageDir.exists() ) {
// packageDir.mkdir();
// if (deleteTempFilesOnExit) packageDir.deleteOnExit();
// }
// }
// }
/**
* Can read Eclipse-generated single-line arg
*/
static void parseCommandLine(String[] args) {
if (args.length == 0) {
displayHelpAndExit( null );
} else if (args.length == 1 && args[0].startsWith("@")) {
String argFile = args[0].substring(1);
System.out.println("> Using arg file: " + argFile);
BufferedReader br;
try {
br = new BufferedReader(new FileReader(argFile));
String line = "";
line = br.readLine();
StringTokenizer st = new StringTokenizer(line, " ");
List argList = new ArrayList();
while(st.hasMoreElements()) {
argList.add((String)st.nextElement());
}
//System.err.println(argList);
args = new String[argList.size()];
int counter = 0;
for (Iterator it = argList.iterator(); it.hasNext(); ) {
args[counter] = (String)it.next();
counter++;
}
} catch (FileNotFoundException e) {
System.err.println("> could not read arg file: " + argFile);
e.printStackTrace();
} catch (IOException ioe) {
System.err.println("> could not read arg file: " + argFile);
ioe.printStackTrace();
}
}
List vargs = new LinkedList(Arrays.asList(args));
parseArgs(vargs, new File( "." )); // !!!
if (filenames.size() == 0) {
displayHelpAndExit( "ajdoc: No packages or classes specified" );
}
}
static void setSourcepath(String arg) {
sourcepath.clear();
arg = arg + File.pathSeparator; // makes things easier for ourselves
StringTokenizer tokenizer = new StringTokenizer(arg, File.pathSeparator);
while (tokenizer.hasMoreElements()) {
sourcepath.addElement(tokenizer.nextElement());
}
}
static String getSourcepathAsString() {
String cPath = "";
for (int i = 0; i < sourcepath.size(); i++) {
cPath += (String)sourcepath.elementAt(i) + Config.DIR_SEP_CHAR + outputWorkingDir;
if (i != sourcepath.size()-1) {
cPath += File.pathSeparator;
}
}
return cPath;
}
static void parseArgs(List vargs, File currentWorkingDir) {
boolean addNextAsOption = false;
boolean addNextAsArgFile = false;
boolean addNextToAJCOptions = false;
boolean addNextAsDocDir = false;
boolean addNextAsClasspath = false;
boolean ignoreArg = false; // used for discrepancy betwen class/sourcepath in ajc/javadoc
boolean addNextAsSourcePath = false;
if ( vargs.size() == 0 ) {
displayHelpAndExit( null );
}
for (int i = 0; i < vargs.size() ; i++) {
String arg = (String)vargs.get(i);
ignoreArg = false;
if ( addNextToAJCOptions ) {
ajcOptions.addElement( arg );
addNextToAJCOptions = false;
}
if ( addNextAsDocDir ) {
docDir = arg;
addNextAsDocDir = false;
}
if ( addNextAsClasspath ) {
addNextAsClasspath = false;
}
if ( addNextAsSourcePath ) {
setSourcepath( arg );
addNextAsSourcePath = false;
ignoreArg = true;
}
if ( arg.startsWith("@") ) {
expandAtSignFile(arg.substring(1), currentWorkingDir);
}
else if ( arg.equals( "-argfile" ) ) {
addNextAsArgFile = true;
}
else if ( addNextAsArgFile ) {
expandAtSignFile(arg, currentWorkingDir);
addNextAsArgFile = false;
}
else if (arg.equals("-d") ) {
addNextAsOption = true;
options.addElement(arg);
addNextAsDocDir = true;
}
else if ( arg.equals( "-bootclasspath" ) ) {
addNextAsOption = true;
addNextToAJCOptions = true;
options.addElement( arg );
ajcOptions.addElement( arg );
}
else if ( arg.equals( "-source" ) ) {
addNextAsOption = true;
addNextToAJCOptions = true;
addNextAsClasspath = true;
options.addElement(arg);
ajcOptions.addElement(arg);
}
else if ( arg.equals( "-classpath" ) ) {
addNextAsOption = true;
addNextToAJCOptions = true;
addNextAsClasspath = true;
options.addElement( arg );
ajcOptions.addElement( arg );
}
else if ( arg.equals( "-encoding" ) ) {
addNextAsOption = true;
addNextToAJCOptions = false;
options.addElement( arg );
}
else if ( arg.equals( "-docencoding" ) ) {
addNextAsOption = true;
addNextToAJCOptions = false;
options.addElement( arg );
}
else if ( arg.equals( "-charset" ) ) {
addNextAsOption = true;
addNextToAJCOptions = false;
options.addElement( arg );
}
else if ( arg.equals( "-sourcepath" ) ) {
addNextAsSourcePath = true;
//options.addElement( arg );
//ajcOptions.addElement( arg );
}
else if (arg.equals("-XajdocDebug")) {
deleteTempFilesOnExit = false;
}
else if (arg.equals("-use")) {
System.out.println("> Ignoring unsupported option: -use");
}
else if (arg.equals("-splitindex")) {
// passed to javadoc
}
else if (arg.startsWith("-") || addNextAsOption) {
if ( arg.equals( "-private" ) ) {
docModifier = "private";
}else if ( arg.equals( "-package" ) ) {
docModifier = "package";
} else if ( arg.equals( "-protected" ) ) {
docModifier = "protected";
} else if ( arg.equals( "-public" ) ) {
docModifier = "public";
} else if ( arg.equals( "-verbose" ) ) {
verboseMode = true;
} else if ( arg.equals( "-author" ) ) {
authorStandardDocletSwitch = true;
} else if ( arg.equals( "-version" ) ) {
versionStandardDocletSwitch = true;
} else if ( arg.equals( "-v" ) ) {
System.out.println(getVersion());
exit(0);
} else if ( arg.equals( "-help" ) ) {
displayHelpAndExit( null );
} else if ( arg.equals( "-doclet" ) || arg.equals( "-docletpath" ) ) {
System.out.println( "The doclet and docletpath options are not currently supported \n" +
"since ajdoc makes assumptions about the behavior of the standard \n" +
"doclet. If you would find this option useful please email us at: \n" +
" \n" +
" [email protected] \n" +
" \n" );
exit(0);
} else if (arg.equals("-nonavbar")
|| arg.equals("-noindex")) {
// pass through
//System.err.println("> ignoring unsupported option: " + arg);
} else if ( addNextAsOption ) {
// pass through
} else {
System.err.println("> unrecognized argument: " + arg);
displayHelpAndExit( null );
}
options.addElement(arg);
addNextAsOption = false;
}
else {
// check if this is a file or a package
// System.err.println(">>>>>>>> " + );
String entryName = arg.substring(arg.lastIndexOf(File.separator)+1);
if (FileUtil.hasSourceSuffix(arg)
|| arg.endsWith(".lst")
&& arg != null ) {
File f = new File(arg);
if (f.isAbsolute()) {
filenames.addElement(arg);
}
else {
filenames.addElement( currentWorkingDir + Config.DIR_SEP_CHAR + arg );
}
fileList.addElement( arg );
}
// PACKAGE MODE STUFF
else if (!ignoreArg) {
packageMode = true;
packageList.addElement( arg );
arg = arg.replace( '.', '/' ); // !!!
// do this for every item in the classpath
for ( int c = 0; c < sourcepath.size(); c++ ) {
String path = (String)sourcepath.elementAt(c) + Config.DIR_SEP_CHAR + arg;
File pkg = new File(path);
if ( pkg.isDirectory() ) {
String[] files = pkg.list( new FilenameFilter() {
public boolean accept( File dir, String name ) {
int index1 = name.lastIndexOf( "." );
int index2 = name.length();
if ( (index1 >= 0 && index2 >= 0 ) &&
(name.substring(index1, index2).equals( ".java" )
|| name.substring(index1, index2).equals( ".aj" ))) {
return true;
}
else {
return false;
}
}
} );
for ( int j = 0; j < files.length; j++ ) {
filenames.addElement( (String)sourcepath.elementAt(c) +
Config.DIR_SEP_CHAR +
arg + Config.DIR_SEP_CHAR + files[j] );
}
}
else if (c == sourcepath.size() ) { // last element on classpath
System.out.println( "ajdoc: No package, class, or source file " +
"found named " + arg + "." );
}
else {
// didn't find it on that element of the classpath but that's ok
}
}
}
}
}
// set the default visibility as an option to javadoc option
if ( !options.contains( "-private" ) &&
!options.contains( "-package" ) &&
!options.contains( "-protected" ) &&
!options.contains( "-public" ) ) {
options.addElement( "-package" );
}
}
static void expandAtSignFile(String filename, File currentWorkingDir) {
List result = new LinkedList();
File atFile = qualifiedFile(filename, currentWorkingDir);
String atFileParent = atFile.getParent();
File myWorkingDir = null;
if (atFileParent != null) myWorkingDir = new File(atFileParent);
try {
BufferedReader stream = new BufferedReader(new FileReader(atFile));
String line = null;
while ( (line = stream.readLine()) != null) {
// strip out any comments of the form # to end of line
int commentStart = line.indexOf("//");
if (commentStart != -1) {
line = line.substring(0, commentStart);
}
// remove extra whitespace that might have crept in
line = line.trim();
// ignore blank lines
if (line.length() == 0) continue;
result.add(line);
}
} catch (IOException e) {
System.err.println("Error while reading the @ file " + atFile.getPath() + ".\n"
+ e);
System.exit( -1 );
}
parseArgs(result, myWorkingDir);
}
static File qualifiedFile(String name, File currentWorkingDir) {
name = name.replace('/', File.separatorChar);
File file = new File(name);
if (!file.isAbsolute() && currentWorkingDir != null) {
file = new File(currentWorkingDir, name);
}
return file;
}
static void displayHelpAndExit(String message) {
if (message != null) {
System.err.println(message);
System.err.println();
System.err.println(Config.USAGE);
} else {
System.out.println(Config.USAGE);
exit(0);
}
}
static protected void exit(int value) {
System.out.flush();
System.err.flush();
System.exit(value);
}
/* This section of code handles errors that occur during compilation */
static final String internalErrorMessage =
"Please copy the following text into an email message and send it,\n" +
"along with any additional information you can add to: \n" +
" \n" +
" [email protected] \n" +
" \n";
static public void handleInternalError(Throwable uncaughtThrowable) {
System.err.println("An internal error occured in ajdoc");
System.err.println(internalErrorMessage);
System.err.println(uncaughtThrowable.toString());
uncaughtThrowable.printStackTrace();
System.err.println();
}
static String getVersion() {
return "ajdoc version " + Version.text;
}
public static boolean hasAborted() {
return aborted;
}
/**
* Sets the output working dir to be <fullyQualifiedOutputDir>\ajdocworkingdir
* Useful in testing to redirect the ajdocworkingdir to the sandbox
*/
public static void setOutputWorkingDir(String fullyQulifiedOutputDir) {
if (fullyQulifiedOutputDir == null) {
resetOutputWorkingDir();
} else {
outputWorkingDir = fullyQulifiedOutputDir + File.separatorChar +
Config.WORKING_DIR;
}
}
/**
* Resets the output working dir to be the default which is
* <the current directory>\ajdocworkingdir
*/
public static void resetOutputWorkingDir() {
outputWorkingDir = Config.WORKING_DIR;
}
}
|
58,524 |
Bug 58524 ajdoc should not use the Declaration and SymbolManager classes
|
In order to speed up porting porting to the old HTML generation code ajdoc continues to use the following classes: org.aspectj.tools.ajdoc.Declaration org.aspectj.tools.ajdoc.SymbolManager These funtion only as a wrapper to the ASM, and are not needed. The next refactoring effort should get rid of them (and all those static methods as well!).
|
resolved fixed
|
f4c8bf9
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-01-16T16:46:54Z | 2004-04-14T16:26:40Z |
ajdoc/src/org/aspectj/tools/ajdoc/StubFileGenerator.java
|
/* *******************************************************************
* Copyright (c) 1999-2001 Xerox Corporation,
* 2002 Palo Alto Research Center, Incorporated (PARC).
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* Xerox/PARC initial implementation
* Mik Kersten port to AspectJ 1.1+ code base
* ******************************************************************/
package org.aspectj.tools.ajdoc;
import java.io.*;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import org.aspectj.asm.AsmManager;
import org.aspectj.asm.IProgramElement;
/**
* @author Mik Kersten
*/
class StubFileGenerator{
static Hashtable declIDTable = null;
static void doFiles (Hashtable table,
SymbolManager symbolManager,
File[] inputFiles,
File[] signatureFiles) throws DocException {
declIDTable = table;
for (int i = 0; i < inputFiles.length; i++) {
processFile(symbolManager, inputFiles[i], signatureFiles[i]);
}
}
static void processFile(SymbolManager symbolManager, File inputFile, File signatureFile) throws DocException {
try {
String path = StructureUtil.translateAjPathName(signatureFile.getCanonicalPath());
PrintWriter writer = new PrintWriter(new BufferedWriter(new FileWriter(path)));
String packageName = StructureUtil.getPackageDeclarationFromFile(inputFile);
if (packageName != null && packageName != "") {
writer.println( "package " + packageName + ";" );
}
IProgramElement fileNode = (IProgramElement)AsmManager.getDefault().getHierarchy().findElementForSourceFile(inputFile.getAbsolutePath());
for (Iterator it = fileNode.getChildren().iterator(); it.hasNext(); ) {
IProgramElement node = (IProgramElement)it.next();
if (node.getKind().equals(IProgramElement.Kind.IMPORT_REFERENCE)) {
processImportDeclaration(node, writer);
} else {
try {
processTypeDeclaration(node, writer);
} catch (DocException d){
throw new DocException("File name invalid: " + inputFile.toString());
}
}
}
// if we got an error we don't want the contents of the file
writer.close();
} catch (IOException e) {
System.err.println(e.getMessage());
e.printStackTrace();
}
}
private static void processImportDeclaration(IProgramElement node, PrintWriter writer) throws IOException {
List imports = node.getChildren();
for (Iterator i = imports.iterator(); i.hasNext();) {
IProgramElement importNode = (IProgramElement) i.next();
writer.print("import ");
writer.print(importNode.getName());
writer.println(';');
}
}
private static void processTypeDeclaration(IProgramElement classNode, PrintWriter writer) throws DocException {
String formalComment = addDeclID(classNode, classNode.getFormalComment());
writer.println(formalComment);
String signature = genSourceSignature(classNode);// StructureUtil.genSignature(classNode);
if (signature == null){
throw new DocException("The java file is invalid");
}
// System.err.println("######" + signature + ", " + classNode.getName());
if (!StructureUtil.isAnonymous(classNode) && !classNode.getName().equals("<undefined>")) {
writer.println(signature + " {" );
processMembers(classNode.getChildren(), writer, classNode.getKind().equals(IProgramElement.Kind.INTERFACE));
writer.println();
writer.println("}");
}
}
private static void processMembers(List/*IProgramElement*/ members, PrintWriter writer, boolean declaringTypeIsInterface) throws DocException {
for (Iterator it = members.iterator(); it.hasNext();) {
IProgramElement member = (IProgramElement) it.next();
if (member.getKind().isType()) {
if (!member.getParent().getKind().equals(IProgramElement.Kind.METHOD)
&& !StructureUtil.isAnonymous(member)) {// don't print anonymous types
// System.err.println(">>>>>>>>>>>>>" + member.getName() + "<<<<" + member.getParent());
processTypeDeclaration(member, writer);
}
} else {
String formalComment = addDeclID(member, member.getFormalComment());;
writer.println(formalComment);
String signature = "";
if (!member.getKind().equals(IProgramElement.Kind.POINTCUT)
&& !member.getKind().equals(IProgramElement.Kind.ADVICE)) {
signature = member.getSourceSignature();//StructureUtil.genSignature(member);
if (member.getKind().equals(IProgramElement.Kind.ENUM_VALUE)){
int index = members.indexOf(member);
if ((index + 1 < members.size()) &&
((IProgramElement)members.get(index+1)).getKind().equals(IProgramElement.Kind.ENUM_VALUE)){
// if the next member is also an ENUM_VALUE:
signature = signature + ",";
} else {
signature = signature + ";";
}
}
}
if (member.getKind().isDeclare()) {
// System.err.println("> Skipping declare (ajdoc limitation): " + member.toLabelString());
} else if (signature != null &&
signature != "" &&
!member.getKind().isInterTypeMember() &&
!member.getKind().equals(IProgramElement.Kind.INITIALIZER) &&
!StructureUtil.isAnonymous(member)) {
writer.print(signature);
} else {
// System.err.println(">> skipping: " + member.getKind());
}
if (member.getKind().equals(IProgramElement.Kind.METHOD) ||
member.getKind().equals(IProgramElement.Kind.CONSTRUCTOR)) {
if (member.getParent().getKind().equals(IProgramElement.Kind.INTERFACE) ||
signature.indexOf("abstract ") != -1) {
writer.println(";");
} else {
writer.println(" { }");
}
} else if (member.getKind().equals(IProgramElement.Kind.FIELD)) {
// writer.println(";");
}
}
}
}
/**
* Translates "aspect" to "class", as long as its not ".aspect"
*/
private static String genSourceSignature(IProgramElement classNode) {
String signature = classNode.getSourceSignature();
if (signature != null){
int index = signature.indexOf("aspect");
if (index == 0 || (index != -1 && signature.charAt(index-1) != '.') ) {
signature = signature.substring(0, index) +
"class " +
signature.substring(index + 6, signature.length());
}
}
return signature;
}
static int nextDeclID = 0;
static String addDeclID(IProgramElement decl, String formalComment) {
String declID = "" + ++nextDeclID;
declIDTable.put(declID, decl);
return addToFormal(formalComment, Config.DECL_ID_STRING + declID + Config.DECL_ID_TERMINATOR);
}
/**
* We want to go:
* just before the first period
* just before the first @
* just before the end of the comment
*
* Adds a place holder for the period ('#') if one will need to be
* replaced.
*/
static String addToFormal(String formalComment, String string) {
boolean appendPeriod = true;
if ( (formalComment == null) || formalComment.equals("")) {
//formalComment = "/**\n * . \n */\n";
formalComment = "/**\n * \n */\n";
appendPeriod = false;
}
formalComment = formalComment.trim();
int atsignPos = formalComment.indexOf('@');
int endPos = formalComment.indexOf("*/");
int periodPos = formalComment.indexOf("/**")+2;
int position = 0;
String periodPlaceHolder = "";
if ( periodPos != -1 ) {
position = periodPos+1;
}
else if ( atsignPos != -1 ) {
string = string + "\n * ";
position = atsignPos;
}
else if ( endPos != -1 ) {
string = "* " + string + "\n";
position = endPos;
}
else {
// !!! perhaps this error should not be silent
throw new Error("Failed to append to formal comment for comment: " +
formalComment );
}
return
formalComment.substring(0, position) + periodPlaceHolder +
string +
formalComment.substring(position);
}
}
|
58,524 |
Bug 58524 ajdoc should not use the Declaration and SymbolManager classes
|
In order to speed up porting porting to the old HTML generation code ajdoc continues to use the following classes: org.aspectj.tools.ajdoc.Declaration org.aspectj.tools.ajdoc.SymbolManager These funtion only as a wrapper to the ASM, and are not needed. The next refactoring effort should get rid of them (and all those static methods as well!).
|
resolved fixed
|
f4c8bf9
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-01-16T16:46:54Z | 2004-04-14T16:26:40Z |
ajdoc/src/org/aspectj/tools/ajdoc/SymbolManager.java
|
/* *******************************************************************
* Copyright (c) 1999-2001 Xerox Corporation,
* 2002 Palo Alto Research Center, Incorporated (PARC).
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* Xerox/PARC initial implementation
* Mik Kersten port to AspectJ 1.1+ code base
* ******************************************************************/
package org.aspectj.tools.ajdoc;
import java.util.*;
import org.aspectj.asm.*;
/**
* @author Mik Kersten
*/
public class SymbolManager {
private static SymbolManager INSTANCE = new SymbolManager();
public static SymbolManager getDefault() {
return INSTANCE;
}
/**
* TODO: only works for one class
*/
public Declaration[] getDeclarations(String filename) {
IProgramElement file = (IProgramElement)AsmManager.getDefault().getHierarchy().findElementForSourceFile(filename);
IProgramElement node = (IProgramElement)file.getChildren().get(0);
// Declaration[] decls = new Declaration[node.getChildren().size()+1];
final List nodes = new ArrayList();
HierarchyWalker walker = new HierarchyWalker() {
public void preProcess(IProgramElement node) {
IProgramElement p = (IProgramElement)node;
if (accept(node)) nodes.add(buildDecl(p));
}
};
file.walk(walker);
return (Declaration[])nodes.toArray(new Declaration[nodes.size()]);
}
/**
* Rejects anonymous kinds by checking if their name is an integer
*/
private boolean accept(IProgramElement node) {
if (node.getKind().isType()) {
boolean isAnonymous = StructureUtil.isAnonymous(node);
return !node.getParent().getKind().equals(IProgramElement.Kind.METHOD)
&& !isAnonymous;
} else {
return !node.getKind().equals(IProgramElement.Kind.IMPORT_REFERENCE);
}
// && !(node.getKind().isType() &&
// node.getParent().getKind().equals(IProgramElement.Kind.METHOD));
}
private Declaration buildDecl(IProgramElement node) {
String signature = "";
String accessibility = node.getAccessibility().toString();
if (!accessibility.equals("package")) signature = accessibility.toString() + " ";
String modifiers = "";
if (!node.getAccessibility().equals(IProgramElement.Accessibility.PACKAGE)) modifiers += node.getAccessibility() + " ";
for (Iterator modIt = node.getModifiers().iterator(); modIt.hasNext(); ) {
modifiers += modIt.next() + " ";
}
if (node.getKind().equals(IProgramElement.Kind.METHOD) ||
node.getKind().equals(IProgramElement.Kind.FIELD)) {
signature += node.getCorrespondingType() + " ";
}
if (node.getKind().equals(IProgramElement.Kind.CLASS) ||
node.getKind().equals(IProgramElement.Kind.METHOD)) {
signature += "class ";
} else if (node.getKind().equals(IProgramElement.Kind.INTERFACE) ||
node.getKind().equals(IProgramElement.Kind.METHOD)) {
signature += "interface ";
}
signature += node.toSignatureString();
String name = node.getName();
if (node.getKind().isType()) {
name = genPartiallyQualifiedName(node, node.getName());
}
String declaringType = node.getParent().getName();
// if (!node.getKind().isType()) {
// declaringType = node.getParent().getName();
// }
Declaration dec = new Declaration(
node.getSourceLocation().getLine(),
node.getSourceLocation().getEndLine(),
node.getSourceLocation().getColumn(),
-1,
modifiers,
name,
signature,
"", // crosscut designator
node.getDeclaringType(),
node.getKind().toString(),
node.getSourceLocation().getSourceFile().getAbsolutePath(),
node.getFormalComment(),
node.getPackageName(),
node
);
return dec;
}
// // In the unusual case that there are multiple declarations on a single line
// // This will return a random one
// public Declaration getDeclarationAtLine(String filename, int line) {
// return getDeclarationAtPoint(filename, line, -1);
// }
private String genPartiallyQualifiedName(IProgramElement node, String name) {
// if (node.getParent() != null) System.err.println("%%% " + node.getParent());
if (node.getParent() != null && node.getParent().getKind().isType()) {
name = node.getParent().getName() + '.' + name;
genPartiallyQualifiedName(node.getParent(), name);
}
return name;
}
public Declaration getDeclarationAtPoint(String filename, int line, int column) {
Declaration[] declarations = lookupDeclarations(filename);
//System.out.println("getting "+filename+", "+line+":"+column);
//System.out.println("decs: "+declarations);
return getDeclarationAtPoint(declarations, line, column);
}
public Declaration getDeclarationAtPoint(Declaration[] declarations, int line, int column) {
//!!! when we care about the performance of this method
//!!! these should be guaranteed to be sorted and a binary search used here
//!!! for now we use the simple (and reliable) linear search
if (declarations == null) return null;
for(int i=0; i<declarations.length; i++) {
Declaration dec = declarations[i];
if (dec.getBeginLine() == line) { // && dec.getEndLine() >= line) {
if (column == -1) return dec;
if (dec.getBeginColumn() == column) { // && dec.getEndColumn() >= column) {
return dec;
}
}
Declaration[] enclosedDecs = dec.getDeclarations();
if (enclosedDecs.length == 0) continue;
Declaration dec1 = getDeclarationAtPoint(enclosedDecs, line, column);
if (dec1 != null) return dec1;
}
//??? what should be returned for no declaration found
return null;
}
// private Hashtable symbolFileEntryCache = new Hashtable();
private Declaration[] lookupDeclarations(String filename) {
System.err.println("> looking up: " + filename);
return null;
// CorrFileEntry entry = lookup(filename, mapFilenameToSymbolFile(filename),
// symbolFileEntryCache);
// return (Declaration[])entry.data;
}
// private Hashtable sourceToOutputCache = new Hashtable();
// private Hashtable outputToSourceCache = new Hashtable();
// private Map lookupSourceToOutput(String filename) {
// CorrFileEntry entry = lookup(filename,
// getSourceToOutputFile(new File(filename).getParent()),
// sourceToOutputCache);
// return (Map)entry.data;
// }
// private Map lookupOutputToSource(String filename) {
// CorrFileEntry entry = lookup(filename,
// getOutputToSourceFile(new File(filename).getParent()),
// outputToSourceCache);
// return (Map)entry.data;
// }
/* generic code for dealing with correlation files, serialization, and caching */
// private static class CorrFileEntry {
// public long lastModified;
// public Object data;
//
// public CorrFileEntry(long lastModified, Object data) {
// this.lastModified = lastModified;
// this.data = data;
// }
// }
// private CorrFileEntry lookup(String filename, File file, Hashtable cache) {
// CorrFileEntry entry = (CorrFileEntry)cache.get(filename);
// if (entry != null && entry.lastModified == file.lastModified()) {
// return entry;
// }
//
// entry = createCorrFileEntry(file);
// cache.put(filename, entry);
// return entry;
// }
// private CorrFileEntry createCorrFileEntry(File file) {
// if (!file.exists()) {
// return new CorrFileEntry(0l, null);
// }
//
// try {
// long lastModified = file.lastModified();
// ObjectInputStream stream =
// new ObjectInputStream(new BufferedInputStream(new FileInputStream(file)));
// Object data = stream.readObject();
// stream.close();
// return new CorrFileEntry(lastModified, data);
// } catch (IOException ioe) {
// //System.err.println("ERROR!!!");
// //ioe.printStackTrace();
// return new CorrFileEntry(0l, null);
// } catch (ClassNotFoundException cce) {
// //System.err.println("ERROR!!!");
// //cce.printStackTrace();
// return new CorrFileEntry(0l, null);
// }
// }
/**
* @param methodName method name without type or parameter list
* @return method name with ajc-specific name mangling removed,
* unchanged if there's not ajc name mangling present
*/
public static String translateMethodName(String methodName) {
int firstDollar = methodName.indexOf('$');
if (firstDollar == -1) return methodName;
String baseName = methodName.substring(firstDollar);
if (methodName.indexOf("ajc") != -1) {
return "<" + baseName + " advice>";
} else {
return baseName;
}
}
/************************************************************************
The rest of the code in this file is just for testing purposes
************************************************************************/
// private static final void printIndentation(int indent, String prefix) {
// for(int i=0; i< indent; i++) System.out.print(" ");
// System.out.print(prefix);
// }
//
//
// private static final void printDeclaration(Declaration dec, int indent, String prefix) {
// printIndentation(indent, prefix);
// if (dec == null) {
// System.out.println("null");
// return;
// }
//
// System.out.println(dec.getKind()+": "+dec.getDeclaringType()+": "+
// dec.getModifiers()+": "+dec.getSignature()+": " +
// //dec.getFullSignature()+": "+
// dec.getCrosscutDesignator()+
// ": "+dec.isIntroduced()+": "+dec.getPackageName()+": "+dec.getBeginLine()+":"+dec.getBeginColumn()
// );
//
// //printIndentation(indent, "\"\"\"");
// //System.out.println(dec.getFormalComment());
// /*
// if (dec.getParentDeclaration() != null) {
// printDeclaration(dec.getParentDeclaration(), indent+INDENT, "PARENT ");
// }
// if (dec.getCrosscutDeclaration() != null) {
// printDeclaration(dec.getCrosscutDeclaration(), indent+INDENT, "XC ");
// }
// */
// if (prefix.equals("")) {
// printDeclarations(dec.getTargets(), indent+INDENT, "T> ");
// printDeclarations(dec.getPointsTo(), indent+INDENT, ">> ");
// printDeclarations(dec.getPointedToBy(), indent+INDENT, "<< ");
// printDeclarations(dec.getDeclarations(), indent+INDENT, "");
// }
// }
// private static final void printDeclarations(Declaration[] decs, int indent, String prefix) {
// for(int i=0; i<decs.length; i++) {
// printDeclaration(decs[i], indent, prefix);
// }
// }
// private static final int INDENT = 2;
// static void printLines(String filename, Map baseMap) throws IOException {
// if (baseMap == null) return;
//
// String fullName = new File(filename).getCanonicalPath();
// java.util.TreeMap map = new java.util.TreeMap();
//
// for (Iterator i = baseMap.entrySet().iterator(); i.hasNext(); ) {
// Map.Entry entry = (Map.Entry)i.next();
// SourceLine keyLine = (SourceLine)entry.getKey();
// if (!keyLine.filename.equals(fullName)) continue;
//
// map.put(new Integer(keyLine.line), entry.getValue());
// }
//
// for (java.util.Iterator j = map.entrySet().iterator(); j.hasNext(); ) {
// java.util.Map.Entry entry = (java.util.Map.Entry)j.next();
//
// System.out.println(entry.getKey() + ":\t" + entry.getValue());
// }
// }
// public static void main(String[] args) throws IOException {
// for(int i=0; i<args.length; i++) {
// String filename = args[i];
// System.out.println(filename);
//
// System.out.println("declaration mappings");
// System.out.println("kind: declaringType: modifiers: signature: fullSignature: crosscutDesignator: isIntroduced: packageName: parentDeclaration");
//
// Declaration[] declarations = getSymbolManager().getDeclarations(filename);
// if (declarations != null) {
// printDeclarations(declarations, INDENT, "");
// }
//
// System.out.println("source to output");
// printLines(filename, getSymbolManager().lookupSourceToOutput(filename));
// System.out.println("output to source");
// printLines(filename, getSymbolManager().lookupOutputToSource(filename));
// }
// }
}
|
123,612 |
Bug 123612 ArrayIndexOutOfBoundsException with incremental and declare @type
|
Given the following code: ------------------------------------------------- public aspect A { declare @type : C : @MyAnnotation; } @interface MyAnnotation { } class C { } ------------------------------------------------- if you comment out the declare @type statement and do an incremental build, then the following ArrayIndexOutOfBoundsException occurs: java.lang.ArrayIndexOutOfBoundsException: 0 at org.aspectj.ajdt.internal.compiler.lookup.AjLookupEnvironment.doDeclareAnnotations(AjLookupEnvironment.java:754) at org.aspectj.ajdt.internal.compiler.lookup.AjLookupEnvironment.weaveInterTypeDeclarations(AjLookupEnvironment.java:571) at org.aspectj.ajdt.internal.compiler.lookup.AjLookupEnvironment.weaveIntertypes(AjLookupEnvironment.java:357) at org.aspectj.ajdt.internal.compiler.lookup.AjLookupEnvironment.completeTypeBindings(AjLookupEnvironment.java:209) at org.aspectj.org.eclipse.jdt.internal.compiler.Compiler.beginToCompile(Compiler.java:301) at org.aspectj.org.eclipse.jdt.internal.compiler.Compiler.compile(Compiler.java:315) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.performCompilation(AjBuildManager.java:811) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.doBuild(AjBuildManager.java:254) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.incrementalBuild(AjBuildManager.java:163) at org.aspectj.ajde.internal.CompilerAdapter.compile(CompilerAdapter.java:117) at org.aspectj.ajde.internal.AspectJBuildManager$CompilerThread.run(AspectJBuildManager.java:191) This is against the latest code in HEAD.
|
resolved fixed
|
ab2f89b
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-01-17T15:32:20Z | 2006-01-12T15:33:20Z |
tests/src/org/aspectj/systemtest/incremental/tools/MultiProjectIncrementalTests.java
|
/* *******************************************************************
* Copyright (c) 2005 Contributors.
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Eclipse Public License v1.0
* which accompanies this distribution and is available at
* http://eclipse.org/legal/epl-v10.html
*
* Contributors:
* Andy Clement initial implementation
* ******************************************************************/
package org.aspectj.systemtest.incremental.tools;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.aspectj.ajdt.internal.core.builder.AjState;
import org.aspectj.ajdt.internal.core.builder.IncrementalStateManager;
import org.aspectj.asm.AsmManager;
import org.aspectj.asm.IProgramElement;
import org.aspectj.bridge.IMessage;
import org.aspectj.testing.util.FileUtil;
/**
* The superclass knows all about talking through Ajde to the compiler.
* The superclass isn't in charge of knowing how to simulate overlays
* for incremental builds, that is in here. As is the ability to
* generate valid build configs based on a directory structure. To
* support this we just need access to a sandbox directory - this
* sandbox is managed by the superclass (it only assumes all builds occur
* in <sandboxDir>/<projectName>/ )
*
* The idea is you can initialize multiple projects in the sandbox and
* they can all be built independently, hopefully exploiting
* incremental compilation. Between builds you can alter the contents
* of a project using the alter() method that overlays some set of
* new files onto the current set (adding new files/changing existing
* ones) - you can then drive a new build and check it behaves as
* expected.
*/
public class MultiProjectIncrementalTests extends AjdeInteractionTestbed {
private static boolean VERBOSE = false;
protected void setUp() throws Exception {
super.setUp();
AjdeInteractionTestbed.VERBOSE = VERBOSE;
}
// Compile a single simple project
public void testTheBasics() {
initialiseProject("P1");
build("P1"); // This first build will be batch
build("P1");
checkWasntFullBuild();
checkCompileWeaveCount(0,0);
}
// Make simple changes to a project, adding a class
public void testSimpleChanges() {
initialiseProject("P1");
build("P1"); // This first build will be batch
alter("P1","inc1"); // adds a single class
build("P1");
checkCompileWeaveCount(1,-1);
build("P1");
checkCompileWeaveCount(0,-1);
}
// Make simple changes to a project, adding a class and an aspect
public void testAddingAnAspect() {
initialiseProject("P1");
build("P1");
alter("P1","inc1"); // adds a class
alter("P1","inc2"); // adds an aspect
build("P1");
long timeTakenForFullBuildAndWeave = getTimeTakenForBuild();
checkWasntFullBuild();
checkCompileWeaveCount(2,3);
build("P1");
long timeTakenForSimpleIncBuild = getTimeTakenForBuild();
// I don't think this test will have timing issues as the times should be *RADICALLY* different
// On my config, first build time is 2093ms and the second is 30ms
assertTrue("Should not take longer for the trivial incremental build! first="+timeTakenForFullBuildAndWeave+
"ms second="+timeTakenForSimpleIncBuild+"ms",
timeTakenForSimpleIncBuild<timeTakenForFullBuildAndWeave);
}
public void testBuildingTwoProjectsInTurns() {
configureBuildStructureModel(true);
initialiseProject("P1");
initialiseProject("P2");
build("P1");
build("P2");
build("P1");
checkWasntFullBuild();
build("P2");
checkWasntFullBuild();
}
/**
* In order for this next test to run, I had to move the weaver/world pair we keep in the
* AjBuildManager instance down into the state object - this makes perfect sense - otherwise
* when reusing the state for another project we'd not be switching to the right weaver/world
* for that project.
*/
public void testBuildingTwoProjectsMakingSmallChanges() {
configureBuildStructureModel(true);
initialiseProject("P1");
initialiseProject("P2");
build("P1");
build("P2");
build("P1");
checkWasntFullBuild();
build("P2");
checkWasntFullBuild();
alter("P1","inc1"); // adds a class
alter("P1","inc2"); // adds an aspect
build("P1");
checkWasntFullBuild();
}
/**
* Setup up two simple projects and build them in turn - check the
* structure model is right after each build
*/
public void testBuildingTwoProjectsAndVerifyingModel() {
configureBuildStructureModel(true);
initialiseProject("P1");
initialiseProject("P2");
build("P1");
checkForNode("pkg","C",true);
build("P2");
checkForNode("pkg","C",false);
build("P1");
checkForNode("pkg","C",true);
build("P2");
checkForNode("pkg","C",false);
}
// Setup up two simple projects and build them in turn - check the
// structure model is right after each build
public void testBuildingTwoProjectsAndVerifyingStuff() {
configureBuildStructureModel(true);
initialiseProject("P1");
initialiseProject("P2");
build("P1");
checkForNode("pkg","C",true);
build("P2");
checkForNode("pkg","C",false);
build("P1");
checkForNode("pkg","C",true);
build("P2");
checkForNode("pkg","C",false);
}
/**
* Complex. Here we are testing that a state object records structural changes since
* the last full build correctly. We build a simple project from scratch - this will
* be a full build and so the structural changes since last build count should be 0.
* We then alter a class, adding a new method and check structural changes is 1.
*/
public void testStateManagement1() {
File binDirectoryForP1 = new File(getFile("P1","bin"));
initialiseProject("P1");
build("P1"); // full build
AjState ajs = IncrementalStateManager.findStateManagingOutputLocation(binDirectoryForP1);
assertTrue("There should be a state object for project P1",ajs!=null);
assertTrue("Should be no structural changes as it was a full build but found: "+
ajs.getNumberOfStructuralChangesSinceLastFullBuild(),
ajs.getNumberOfStructuralChangesSinceLastFullBuild()==0);
alter("P1","inc3"); // adds a method to the class C.java
build("P1");
checkWasntFullBuild();
ajs = IncrementalStateManager.findStateManagingOutputLocation(new File(getFile("P1","bin")));
assertTrue("There should be state for project P1",ajs!=null);
checkWasntFullBuild();
assertTrue("Should be one structural changes as it was a full build but found: "+
ajs.getNumberOfStructuralChangesSinceLastFullBuild(),
ajs.getNumberOfStructuralChangesSinceLastFullBuild()==1);
}
/**
* Complex. Here we are testing that a state object records structural changes since
* the last full build correctly. We build a simple project from scratch - this will
* be a full build and so the structural changes since last build count should be 0.
* We then alter a class, changing body of a method, not the structure and
* check struc changes is still 0.
*/
public void testStateManagement2() {
File binDirectoryForP1 = new File(getFile("P1","bin"));
initialiseProject("P1");
alter("P1","inc3"); // need this change in here so 'inc4' can be applied without making
// it a structural change
build("P1"); // full build
AjState ajs = IncrementalStateManager.findStateManagingOutputLocation(binDirectoryForP1);
assertTrue("There should be state for project P1",ajs!=null);
assertTrue("Should be no struc changes as its a full build: "+
ajs.getNumberOfStructuralChangesSinceLastFullBuild(),
ajs.getNumberOfStructuralChangesSinceLastFullBuild()==0);
alter("P1","inc4"); // changes body of main() method but does *not* change the structure of C.java
build("P1");
checkWasntFullBuild();
ajs = IncrementalStateManager.findStateManagingOutputLocation(new File(getFile("P1","bin")));
assertTrue("There should be state for project P1",ajs!=null);
checkWasntFullBuild();
assertTrue("Shouldn't be any structural changes but there were "+
ajs.getNumberOfStructuralChangesSinceLastFullBuild(),
ajs.getNumberOfStructuralChangesSinceLastFullBuild()==0);
}
/**
* Now the most complex test. Create a dependancy between two projects. Building
* one may affect whether the other does an incremental or full build. The
* structural information recorded in the state object should be getting used
* to control whether a full build is necessary...
*/
public void testBuildingDependantProjects() {
initialiseProject("P1");
initialiseProject("P2");
configureNewProjectDependency("P2","P1");
build("P1");
build("P2"); // now everything is consistent and compiled
alter("P1","inc1"); // adds a second class
build("P1");
build("P2"); // although a second class was added - P2 can't be using it, so we don't full build here :)
checkWasntFullBuild();
alter("P1","inc3"); // structurally changes one of the classes
build("P1");
build("P2"); // build notices the structural change
checkWasFullBuild();
alter("P1","inc4");
build("P1");
build("P2"); // build sees a change but works out its not structural
checkWasntFullBuild();
}
public void testPr85132() {
initialiseProject("PR85132");
build("PR85132");
alter("PR85132","inc1");
build("PR85132");
}
public void testPr92837() {
initialiseProject("PR92837");
build("PR92837");
alter("PR92837","inc1");
build("PR92837");
}
public void testPr119570() {
initialiseProject("PR119570");
build("PR119570");
assertTrue("Should be no errors, but got "+MyTaskListManager.getErrorMessages(),MyTaskListManager.getErrorMessages().size()==0);
}
public void testPr119570_2() {
initialiseProject("PR119570_2");
build("PR119570_2");
List l = MyTaskListManager.getWarningMessages();
assertTrue("Should be no warnings, but got "+l,l.size()==0);
}
// If you fiddle with the compiler options - you must manually reset the options at the end of the test
public void testPr117209() {
try {
initialiseProject("pr117209");
configureNonStandardCompileOptions("-proceedOnError");
build("pr117209");
checkCompileWeaveCount(6,6);
} finally {
MyBuildOptionsAdapter.reset();
}
}
public void testPr114875() {
initialiseProject("pr114875");
build("pr114875");
alter("pr114875","inc1");
build("pr114875");
checkWasntFullBuild();
alter("pr114875","inc2");
build("pr114875");
checkWasntFullBuild();
}
public void testPr117882() {
// AjdeInteractionTestbed.VERBOSE=true;
// AjdeInteractionTestbed.configureBuildStructureModel(true);
initialiseProject("PR117882");
build("PR117882");
checkWasFullBuild();
alter("PR117882","inc1");
build("PR117882");
checkWasntFullBuild();
// AjdeInteractionTestbed.VERBOSE=false;
// AjdeInteractionTestbed.configureBuildStructureModel(false);
}
public void testPr117882_2() {
// AjdeInteractionTestbed.VERBOSE=true;
// AjdeInteractionTestbed.configureBuildStructureModel(true);
initialiseProject("PR117882_2");
build("PR117882_2");
checkWasFullBuild();
alter("PR117882_2","inc1");
build("PR117882_2");
checkWasntFullBuild();
//checkCompileWeaveCount(1,4);
//fullBuild("PR117882_2");
//checkWasFullBuild();
// AjdeInteractionTestbed.VERBOSE=false;
// AjdeInteractionTestbed.configureBuildStructureModel(false);
}
public void testPr115251() {
//AjdeInteractionTestbed.VERBOSE=true;
initialiseProject("PR115251");
build("PR115251");
checkWasFullBuild();
alter("PR115251","inc1");
build("PR115251");
checkWasntFullBuild();
}
public void testPr121384() {
// AjdeInteractionTestbed.VERBOSE=true;
// AsmManager.setReporting("c:/foo.txt",true,true,true,false);
MyBuildOptionsAdapter.setNonStandardOptions("-showWeaveInfo");
configureBuildStructureModel(true);
initialiseProject("pr121384");
build("pr121384");
checkWasFullBuild();
alter("pr121384","inc1");
build("pr121384");
checkWasntFullBuild();
}
/* public void testPr111779() {
super.VERBOSE=true;
initialiseProject("PR111779");
build("PR111779");
alter("PR111779","inc1");
build("PR111779");
}
*/
public void testPr93310_1() {
initialiseProject("PR93310_1");
build("PR93310_1");
checkWasFullBuild();
String fileC2 = getWorkingDir().getAbsolutePath() + File.separatorChar + "PR93310_1" + File.separatorChar + "src" + File.separatorChar + "pack" + File.separatorChar + "C2.java";
(new File(fileC2)).delete();
alter("PR93310_1","inc1");
build("PR93310_1");
checkWasFullBuild();
int l = AjdeInteractionTestbed.MyStateListener.detectedDeletions.size();
assertTrue("Expected one deleted file to be noticed, but detected: "+l,l==1);
String name = (String)AjdeInteractionTestbed.MyStateListener.detectedDeletions.get(0);
assertTrue("Should end with C2.java but is "+name,name.endsWith("C2.java"));
}
public void testPr93310_2() {
initialiseProject("PR93310_2");
build("PR93310_2");
checkWasFullBuild();
String fileC2 = getWorkingDir().getAbsolutePath() + File.separatorChar + "PR93310_2" + File.separatorChar + "src" + File.separatorChar + "pack" + File.separatorChar + "C2.java";
(new File(fileC2)).delete();
alter("PR93310_2","inc1");
build("PR93310_2");
checkWasFullBuild();
int l = AjdeInteractionTestbed.MyStateListener.detectedDeletions.size();
assertTrue("Expected one deleted file to be noticed, but detected: "+l,l==1);
String name = (String)AjdeInteractionTestbed.MyStateListener.detectedDeletions.get(0);
assertTrue("Should end with C2.java but is "+name,name.endsWith("C2.java"));
}
// Stage1: Compile two files, pack.A and pack.A1 - A1 sets a protected field in A.
// Stage2: make the field private in class A > gives compile error
// Stage3: Add a new aspect whilst there is a compile error !
public void testPr113531() {
initialiseProject("PR113531");
build("PR113531");
assertFalse("build should have compiled ok",
MyTaskListManager.hasErrorMessages());
alter("PR113531","inc1");
build("PR113531");
assertEquals("error message should be 'foo cannot be resolved' ",
"foo cannot be resolved",
((IMessage)MyTaskListManager.getErrorMessages().get(0))
.getMessage());
alter("PR113531","inc2");
build("PR113531");
assertTrue("There should be no exceptions handled:\n"+MyErrorHandler.getErrorMessages(),
MyErrorHandler.getErrorMessages().isEmpty());
assertEquals("error message should be 'foo cannot be resolved' ",
"foo cannot be resolved",
((IMessage)MyTaskListManager.getErrorMessages().get(0))
.getMessage());
}
public void testPr112736() {
AjdeInteractionTestbed.VERBOSE = true;
initialiseProject("PR112736");
build("PR112736");
checkWasFullBuild();
String fileC2 = getWorkingDir().getAbsolutePath() + File.separatorChar + "PR112736" + File.separatorChar + "src" + File.separatorChar + "pack" + File.separatorChar + "A.java";
(new File(fileC2)).delete();
alter("PR112736","inc1");
build("PR112736");
checkWasFullBuild();
}
/**
* We have problems with multiple rewrites of a pointcut across incremental builds.
*/
public void testPr113257() {
initialiseProject("PR113257");
build("PR113257");
alter("PR113257","inc1");
build("PR113257");
checkWasntFullBuild();
alter("PR113257","inc1");
build("PR113257");
}
// other possible tests:
// - memory usage (freemem calls?)
// - relationship map
// ---------------------------------------------------------------------------------------------------
/**
* Check we compiled/wove the right number of files, passing '-1' indicates you don't care about
* that number.
*/
private void checkCompileWeaveCount(int expCompile,int expWoven) {
if (expCompile!=-1 && getCompiledFiles().size()!=expCompile)
fail("Expected compilation of "+expCompile+" files but compiled "+getCompiledFiles().size()+
"\n"+printCompiledAndWovenFiles());
if (expWoven!=-1 && getWovenClasses().size()!=expWoven)
fail("Expected weaving of "+expWoven+" files but wove "+getWovenClasses().size()+
"\n"+printCompiledAndWovenFiles());
}
private void checkWasntFullBuild() {
assertTrue("Shouldn't have been a full (batch) build",!wasFullBuild());
}
private void checkWasFullBuild() {
assertTrue("Should have been a full (batch) build",wasFullBuild());
}
private void checkForNode(String packageName,String typeName,boolean shouldBeFound) {
IProgramElement ipe = AsmManager.getDefault().getHierarchy().findElementForType(packageName,typeName);
if (shouldBeFound) {
if (ipe==null) printModel();
assertTrue("Should have been able to find '"+packageName+"."+typeName+"' in the asm",ipe!=null);
} else {
if (ipe!=null) printModel();
assertTrue("Should have NOT been able to find '"+packageName+"."+typeName+"' in the asm",ipe==null);
}
}
private void printModel() {
try {
AsmManager.dumptree(AsmManager.getDefault().getHierarchy().getRoot(),0);
} catch (IOException e) {
e.printStackTrace();
}
}
public void build(String projectName) {
constructUpToDateLstFile(projectName,"build.lst");
build(projectName,"build.lst");
if (AjdeInteractionTestbed.VERBOSE) printBuildReport();
}
public void fullBuild(String projectName) {
constructUpToDateLstFile(projectName,"build.lst");
fullBuild(projectName,"build.lst");
if (AjdeInteractionTestbed.VERBOSE) printBuildReport();
}
private void constructUpToDateLstFile(String pname,String configname) {
File projectBase = new File(sandboxDir,pname);
File toConstruct = new File(projectBase,configname);
List filesForCompilation = new ArrayList();
collectUpFiles(projectBase,projectBase,filesForCompilation);
try {
FileOutputStream fos = new FileOutputStream(toConstruct);
DataOutputStream dos = new DataOutputStream(fos);
for (Iterator iter = filesForCompilation.iterator(); iter.hasNext();) {
String file = (String) iter.next();
dos.writeBytes(file+"\n");
}
dos.close();
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
private void collectUpFiles(File location,File base,List collectionPoint) {
String contents[] = location.list();
if (contents==null) return;
for (int i = 0; i < contents.length; i++) {
String string = contents[i];
File f = new File(location,string);
if (f.isDirectory()) {
collectUpFiles(f,base,collectionPoint);
} else if (f.isFile() && (f.getName().endsWith(".aj") || f.getName().endsWith(".java"))) {
String fileFound;
try {
fileFound = f.getCanonicalPath();
String toRemove = base.getCanonicalPath();
if (!fileFound.startsWith(toRemove)) throw new RuntimeException("eh? "+fileFound+" "+toRemove);
collectionPoint.add(fileFound.substring(toRemove.length()+1));//+1 captures extra separator
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
/**
* Fill in the working directory with the project base files,
* from the 'base' folder.
*/
private void initialiseProject(String p) {
File projectSrc=new File(testdataSrcDir+File.separatorChar+p+File.separatorChar+"base");
File destination=new File(getWorkingDir(),p);
if (!destination.exists()) {destination.mkdir();}
copy(projectSrc,destination);//,false);
}
/*
* Applies an overlay onto the project being tested - copying
* the contents of the specified overlay directory.
*/
private void alter(String projectName,String overlayDirectory) {
File projectSrc =new File(testdataSrcDir+File.separatorChar+projectName+
File.separatorChar+overlayDirectory);
File destination=new File(getWorkingDir(),projectName);
copy(projectSrc,destination);
}
/**
* Copy the contents of some directory to another location - the
* copy is recursive.
*/
private void copy(File from, File to) {
String contents[] = from.list();
if (contents==null) return;
for (int i = 0; i < contents.length; i++) {
String string = contents[i];
File f = new File(from,string);
File t = new File(to,string);
if (f.isDirectory() && !f.getName().startsWith("inc")) {
t.mkdir();
copy(f,t);
} else if (f.isFile()) {
StringBuffer sb = new StringBuffer();
//if (VERBOSE) System.err.println("Copying "+f+" to "+t);
FileUtil.copyFile(f,t,sb);
if (sb.length()!=0) { System.err.println(sb.toString());}
}
}
}
private static void log(String msg) {
if (VERBOSE) System.out.println(msg);
}
}
|
123,612 |
Bug 123612 ArrayIndexOutOfBoundsException with incremental and declare @type
|
Given the following code: ------------------------------------------------- public aspect A { declare @type : C : @MyAnnotation; } @interface MyAnnotation { } class C { } ------------------------------------------------- if you comment out the declare @type statement and do an incremental build, then the following ArrayIndexOutOfBoundsException occurs: java.lang.ArrayIndexOutOfBoundsException: 0 at org.aspectj.ajdt.internal.compiler.lookup.AjLookupEnvironment.doDeclareAnnotations(AjLookupEnvironment.java:754) at org.aspectj.ajdt.internal.compiler.lookup.AjLookupEnvironment.weaveInterTypeDeclarations(AjLookupEnvironment.java:571) at org.aspectj.ajdt.internal.compiler.lookup.AjLookupEnvironment.weaveIntertypes(AjLookupEnvironment.java:357) at org.aspectj.ajdt.internal.compiler.lookup.AjLookupEnvironment.completeTypeBindings(AjLookupEnvironment.java:209) at org.aspectj.org.eclipse.jdt.internal.compiler.Compiler.beginToCompile(Compiler.java:301) at org.aspectj.org.eclipse.jdt.internal.compiler.Compiler.compile(Compiler.java:315) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.performCompilation(AjBuildManager.java:811) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.doBuild(AjBuildManager.java:254) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.incrementalBuild(AjBuildManager.java:163) at org.aspectj.ajde.internal.CompilerAdapter.compile(CompilerAdapter.java:117) at org.aspectj.ajde.internal.AspectJBuildManager$CompilerThread.run(AspectJBuildManager.java:191) This is against the latest code in HEAD.
|
resolved fixed
|
ab2f89b
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-01-17T15:32:20Z | 2006-01-12T15:33:20Z |
weaver/src/org/aspectj/weaver/CrosscuttingMembersSet.java
|
/* *******************************************************************
* Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC).
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* PARC initial implementation
* ******************************************************************/
package org.aspectj.weaver;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.aspectj.weaver.patterns.CflowPointcut;
import org.aspectj.weaver.patterns.DeclareParents;
/**
* This holds on to all CrosscuttingMembers for a world. It handles
* management of change.
*
* @author Jim Hugunin
*/
public class CrosscuttingMembersSet {
private World world;
//FIXME AV - ? we may need a sequencedHashMap there to ensure source based precedence for @AJ advice
private Map /* ResolvedType (the aspect) > CrosscuttingMembers */members = new HashMap();
private List shadowMungers = null;
private List typeMungers = null;
private List lateTypeMungers = null;
private List declareSofts = null;
private List declareParents = null;
private List declareAnnotationOnTypes = null;
private List declareAnnotationOnFields = null;
private List declareAnnotationOnMethods= null; // includes ctors
private List declareDominates = null;
public CrosscuttingMembersSet(World world) {
this.world = world;
}
/**
* @return whether or not that was a change to the global signature
* XXX for efficiency we will need a richer representation than this
*/
public boolean addOrReplaceAspect(ResolvedType aspectType) {
boolean change = false;
CrosscuttingMembers xcut = (CrosscuttingMembers)members.get(aspectType);
if (xcut == null) {
members.put(aspectType, aspectType.collectCrosscuttingMembers());
clearCaches();
CflowPointcut.clearCaches(aspectType);
change = true;
} else {
if (xcut.replaceWith(aspectType.collectCrosscuttingMembers())) {
clearCaches();
CflowPointcut.clearCaches(aspectType);
change = true;
} else {
change = false;
}
}
if (aspectType.isAbstract()) {
// we might have sub-aspects that need to re-collect their crosscutting members from us
boolean ancestorChange = addOrReplaceDescendantsOf(aspectType);
change = change || ancestorChange;
}
return change;
}
private boolean addOrReplaceDescendantsOf(ResolvedType aspectType) {
//System.err.println("Looking at descendants of "+aspectType.getName());
Set knownAspects = members.keySet();
Set toBeReplaced = new HashSet();
for(Iterator it = knownAspects.iterator(); it.hasNext(); ) {
ResolvedType candidateDescendant = (ResolvedType)it.next();
if ((candidateDescendant != aspectType) && (aspectType.isAssignableFrom(candidateDescendant))) {
toBeReplaced.add(candidateDescendant);
}
}
boolean change = false;
for (Iterator it = toBeReplaced.iterator(); it.hasNext(); ) {
ResolvedType next = (ResolvedType)it.next();
boolean thisChange = addOrReplaceAspect(next);
change = change || thisChange;
}
return change;
}
public void addAdviceLikeDeclares(ResolvedType aspectType) {
CrosscuttingMembers xcut = (CrosscuttingMembers)members.get(aspectType);
xcut.addDeclares(aspectType.collectDeclares(true));
}
public boolean deleteAspect(UnresolvedType aspectType) {
boolean isAspect = members.remove(aspectType) != null;
clearCaches();
return isAspect;
}
public boolean containsAspect(UnresolvedType aspectType) {
return members.containsKey(aspectType);
}
//XXX only for testing
public void addFixedCrosscuttingMembers(ResolvedType aspectType) {
members.put(aspectType, aspectType.crosscuttingMembers);
clearCaches();
}
private void clearCaches() {
shadowMungers = null;
typeMungers = null;
lateTypeMungers = null;
declareSofts = null;
declareParents = null;
declareDominates = null;
}
public List getShadowMungers() {
if (shadowMungers == null) {
ArrayList ret = new ArrayList();
for (Iterator i = members.values().iterator(); i.hasNext(); ) {
ret.addAll(((CrosscuttingMembers)i.next()).getShadowMungers());
}
shadowMungers = ret;
}
return shadowMungers;
}
public List getTypeMungers() {
if (typeMungers == null) {
ArrayList ret = new ArrayList();
for (Iterator i = members.values().iterator(); i.hasNext(); ) {
ret.addAll(((CrosscuttingMembers)i.next()).getTypeMungers());
}
typeMungers = ret;
}
return typeMungers;
}
public List getLateTypeMungers() {
if (lateTypeMungers == null) {
ArrayList ret = new ArrayList();
for (Iterator i = members.values().iterator(); i.hasNext(); ) {
ret.addAll(((CrosscuttingMembers)i.next()).getLateTypeMungers());
}
lateTypeMungers = ret;
}
return lateTypeMungers;
}
public List getDeclareSofts() {
if (declareSofts == null) {
Set ret = new HashSet();
for (Iterator i = members.values().iterator(); i.hasNext(); ) {
ret.addAll(((CrosscuttingMembers)i.next()).getDeclareSofts());
}
declareSofts = new ArrayList();
declareSofts.addAll(ret);
}
return declareSofts;
}
public List getDeclareParents() {
if (declareParents == null) {
Set ret = new HashSet();
for (Iterator i = members.values().iterator(); i.hasNext(); ) {
ret.addAll(((CrosscuttingMembers)i.next()).getDeclareParents());
}
declareParents = new ArrayList();
declareParents.addAll(ret);
}
return declareParents;
}
// DECAT Merge multiple together
public List getDeclareAnnotationOnTypes() {
if (declareAnnotationOnTypes == null) {
Set ret = new HashSet();
for (Iterator i = members.values().iterator(); i.hasNext(); ) {
ret.addAll(((CrosscuttingMembers)i.next()).getDeclareAnnotationOnTypes());
}
declareAnnotationOnTypes = new ArrayList();
declareAnnotationOnTypes.addAll(ret);
}
return declareAnnotationOnTypes;
}
public List getDeclareAnnotationOnFields() {
if (declareAnnotationOnFields == null) {
Set ret = new HashSet();
for (Iterator i = members.values().iterator(); i.hasNext(); ) {
ret.addAll(((CrosscuttingMembers)i.next()).getDeclareAnnotationOnFields());
}
declareAnnotationOnFields = new ArrayList();
declareAnnotationOnFields.addAll(ret);
}
return declareAnnotationOnFields;
}
/**
* Return an amalgamation of the declare @method/@constructor statements.
*/
public List getDeclareAnnotationOnMethods() {
if (declareAnnotationOnMethods == null) {
Set ret = new HashSet();
for (Iterator i = members.values().iterator(); i.hasNext(); ) {
ret.addAll(((CrosscuttingMembers)i.next()).getDeclareAnnotationOnMethods());
}
declareAnnotationOnMethods = new ArrayList();
declareAnnotationOnMethods.addAll(ret);
}
return declareAnnotationOnMethods;
}
public List getDeclareDominates() {
if (declareDominates == null) {
ArrayList ret = new ArrayList();
for (Iterator i = members.values().iterator(); i.hasNext(); ) {
ret.addAll(((CrosscuttingMembers)i.next()).getDeclareDominates());
}
declareDominates = ret;
}
return declareDominates;
}
public ResolvedType findAspectDeclaringParents(DeclareParents p) {
Set keys = this.members.keySet();
for (Iterator iter = keys.iterator(); iter.hasNext();) {
ResolvedType element = (ResolvedType) iter.next();
for (Iterator i = ((CrosscuttingMembers)members.get(element)).getDeclareParents().iterator(); i.hasNext(); ) {
DeclareParents dp = (DeclareParents)i.next();
if (dp.equals(p)) return element;
}
}
return null;
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.