issue_id
int64
2.03k
426k
title
stringlengths
9
251
body
stringlengths
1
32.8k
status
stringclasses
6 values
after_fix_sha
stringlengths
7
7
project_name
stringclasses
6 values
repo_url
stringclasses
6 values
repo_name
stringclasses
6 values
language
stringclasses
1 value
issue_url
null
before_fix_sha
null
pull_url
null
commit_datetime
unknown
report_datetime
unknown
updated_file
stringlengths
2
187
file_content
stringlengths
0
368k
382,189
Bug 382189 NPE in BcelTypeMunger.createBridgeMethod
Build Identifier: Since I updated to version AspectJ Development Tools 2.2.0.e37x-20120529-0900 I get during compile: java.lang.NullPointerException at org.aspectj.weaver.bcel.BcelTypeMunger.createBridgeMethod(BcelTypeMunger.java:1325) at org.aspectj.weaver.bcel.BcelTypeMunger.createAnyBridgeMethodsForCovariance(BcelTypeMunger.java:1272) at org.aspectj.weaver.bcel.BcelTypeMunger.mungeNewMethod(BcelTypeMunger.java:971) at org.aspectj.weaver.bcel.BcelTypeMunger.munge(BcelTypeMunger.java:108) at org.aspectj.weaver.bcel.BcelClassWeaver.weave(BcelClassWeave ... ) Before, I had AspectJ Development Tools 2.2.0.e37x-20120507-1400 and the same project compiled without that exception. Reproducible: Always
resolved fixed
a748303
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2012-06-16T00:42:25Z"
"2012-06-10T14:53:20Z"
tests/bugs170/pr382189/three/SuperA.java
382,189
Bug 382189 NPE in BcelTypeMunger.createBridgeMethod
Build Identifier: Since I updated to version AspectJ Development Tools 2.2.0.e37x-20120529-0900 I get during compile: java.lang.NullPointerException at org.aspectj.weaver.bcel.BcelTypeMunger.createBridgeMethod(BcelTypeMunger.java:1325) at org.aspectj.weaver.bcel.BcelTypeMunger.createAnyBridgeMethodsForCovariance(BcelTypeMunger.java:1272) at org.aspectj.weaver.bcel.BcelTypeMunger.mungeNewMethod(BcelTypeMunger.java:971) at org.aspectj.weaver.bcel.BcelTypeMunger.munge(BcelTypeMunger.java:108) at org.aspectj.weaver.bcel.BcelClassWeaver.weave(BcelClassWeave ... ) Before, I had AspectJ Development Tools 2.2.0.e37x-20120507-1400 and the same project compiled without that exception. Reproducible: Always
resolved fixed
a748303
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2012-06-16T00:42:25Z"
"2012-06-10T14:53:20Z"
tests/bugs170/pr382189/three/SuperB.java
382,189
Bug 382189 NPE in BcelTypeMunger.createBridgeMethod
Build Identifier: Since I updated to version AspectJ Development Tools 2.2.0.e37x-20120529-0900 I get during compile: java.lang.NullPointerException at org.aspectj.weaver.bcel.BcelTypeMunger.createBridgeMethod(BcelTypeMunger.java:1325) at org.aspectj.weaver.bcel.BcelTypeMunger.createAnyBridgeMethodsForCovariance(BcelTypeMunger.java:1272) at org.aspectj.weaver.bcel.BcelTypeMunger.mungeNewMethod(BcelTypeMunger.java:971) at org.aspectj.weaver.bcel.BcelTypeMunger.munge(BcelTypeMunger.java:108) at org.aspectj.weaver.bcel.BcelClassWeaver.weave(BcelClassWeave ... ) Before, I had AspectJ Development Tools 2.2.0.e37x-20120507-1400 and the same project compiled without that exception. Reproducible: Always
resolved fixed
a748303
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2012-06-16T00:42:25Z"
"2012-06-10T14:53:20Z"
tests/bugs170/pr382189/two/A.java
382,189
Bug 382189 NPE in BcelTypeMunger.createBridgeMethod
Build Identifier: Since I updated to version AspectJ Development Tools 2.2.0.e37x-20120529-0900 I get during compile: java.lang.NullPointerException at org.aspectj.weaver.bcel.BcelTypeMunger.createBridgeMethod(BcelTypeMunger.java:1325) at org.aspectj.weaver.bcel.BcelTypeMunger.createAnyBridgeMethodsForCovariance(BcelTypeMunger.java:1272) at org.aspectj.weaver.bcel.BcelTypeMunger.mungeNewMethod(BcelTypeMunger.java:971) at org.aspectj.weaver.bcel.BcelTypeMunger.munge(BcelTypeMunger.java:108) at org.aspectj.weaver.bcel.BcelClassWeaver.weave(BcelClassWeave ... ) Before, I had AspectJ Development Tools 2.2.0.e37x-20120507-1400 and the same project compiled without that exception. Reproducible: Always
resolved fixed
a748303
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2012-06-16T00:42:25Z"
"2012-06-10T14:53:20Z"
tests/bugs170/pr382189/two/B.java
382,189
Bug 382189 NPE in BcelTypeMunger.createBridgeMethod
Build Identifier: Since I updated to version AspectJ Development Tools 2.2.0.e37x-20120529-0900 I get during compile: java.lang.NullPointerException at org.aspectj.weaver.bcel.BcelTypeMunger.createBridgeMethod(BcelTypeMunger.java:1325) at org.aspectj.weaver.bcel.BcelTypeMunger.createAnyBridgeMethodsForCovariance(BcelTypeMunger.java:1272) at org.aspectj.weaver.bcel.BcelTypeMunger.mungeNewMethod(BcelTypeMunger.java:971) at org.aspectj.weaver.bcel.BcelTypeMunger.munge(BcelTypeMunger.java:108) at org.aspectj.weaver.bcel.BcelClassWeaver.weave(BcelClassWeave ... ) Before, I had AspectJ Development Tools 2.2.0.e37x-20120507-1400 and the same project compiled without that exception. Reproducible: Always
resolved fixed
a748303
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2012-06-16T00:42:25Z"
"2012-06-10T14:53:20Z"
tests/bugs170/pr382189/two/SuperA.java
382,189
Bug 382189 NPE in BcelTypeMunger.createBridgeMethod
Build Identifier: Since I updated to version AspectJ Development Tools 2.2.0.e37x-20120529-0900 I get during compile: java.lang.NullPointerException at org.aspectj.weaver.bcel.BcelTypeMunger.createBridgeMethod(BcelTypeMunger.java:1325) at org.aspectj.weaver.bcel.BcelTypeMunger.createAnyBridgeMethodsForCovariance(BcelTypeMunger.java:1272) at org.aspectj.weaver.bcel.BcelTypeMunger.mungeNewMethod(BcelTypeMunger.java:971) at org.aspectj.weaver.bcel.BcelTypeMunger.munge(BcelTypeMunger.java:108) at org.aspectj.weaver.bcel.BcelClassWeaver.weave(BcelClassWeave ... ) Before, I had AspectJ Development Tools 2.2.0.e37x-20120507-1400 and the same project compiled without that exception. Reproducible: Always
resolved fixed
a748303
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2012-06-16T00:42:25Z"
"2012-06-10T14:53:20Z"
tests/bugs170/pr382189/two/SuperB.java
382,189
Bug 382189 NPE in BcelTypeMunger.createBridgeMethod
Build Identifier: Since I updated to version AspectJ Development Tools 2.2.0.e37x-20120529-0900 I get during compile: java.lang.NullPointerException at org.aspectj.weaver.bcel.BcelTypeMunger.createBridgeMethod(BcelTypeMunger.java:1325) at org.aspectj.weaver.bcel.BcelTypeMunger.createAnyBridgeMethodsForCovariance(BcelTypeMunger.java:1272) at org.aspectj.weaver.bcel.BcelTypeMunger.mungeNewMethod(BcelTypeMunger.java:971) at org.aspectj.weaver.bcel.BcelTypeMunger.munge(BcelTypeMunger.java:108) at org.aspectj.weaver.bcel.BcelClassWeaver.weave(BcelClassWeave ... ) Before, I had AspectJ Development Tools 2.2.0.e37x-20120507-1400 and the same project compiled without that exception. Reproducible: Always
resolved fixed
a748303
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2012-06-16T00:42:25Z"
"2012-06-10T14:53:20Z"
tests/bugs170/pr382435/one/bug/A.java
382,189
Bug 382189 NPE in BcelTypeMunger.createBridgeMethod
Build Identifier: Since I updated to version AspectJ Development Tools 2.2.0.e37x-20120529-0900 I get during compile: java.lang.NullPointerException at org.aspectj.weaver.bcel.BcelTypeMunger.createBridgeMethod(BcelTypeMunger.java:1325) at org.aspectj.weaver.bcel.BcelTypeMunger.createAnyBridgeMethodsForCovariance(BcelTypeMunger.java:1272) at org.aspectj.weaver.bcel.BcelTypeMunger.mungeNewMethod(BcelTypeMunger.java:971) at org.aspectj.weaver.bcel.BcelTypeMunger.munge(BcelTypeMunger.java:108) at org.aspectj.weaver.bcel.BcelClassWeaver.weave(BcelClassWeave ... ) Before, I had AspectJ Development Tools 2.2.0.e37x-20120507-1400 and the same project compiled without that exception. Reproducible: Always
resolved fixed
a748303
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2012-06-16T00:42:25Z"
"2012-06-10T14:53:20Z"
tests/bugs170/pr382435/two/bug/A.java
382,189
Bug 382189 NPE in BcelTypeMunger.createBridgeMethod
Build Identifier: Since I updated to version AspectJ Development Tools 2.2.0.e37x-20120529-0900 I get during compile: java.lang.NullPointerException at org.aspectj.weaver.bcel.BcelTypeMunger.createBridgeMethod(BcelTypeMunger.java:1325) at org.aspectj.weaver.bcel.BcelTypeMunger.createAnyBridgeMethodsForCovariance(BcelTypeMunger.java:1272) at org.aspectj.weaver.bcel.BcelTypeMunger.mungeNewMethod(BcelTypeMunger.java:971) at org.aspectj.weaver.bcel.BcelTypeMunger.munge(BcelTypeMunger.java:108) at org.aspectj.weaver.bcel.BcelClassWeaver.weave(BcelClassWeave ... ) Before, I had AspectJ Development Tools 2.2.0.e37x-20120507-1400 and the same project compiled without that exception. Reproducible: Always
resolved fixed
a748303
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2012-06-16T00:42:25Z"
"2012-06-10T14:53:20Z"
tests/src/org/aspectj/systemtest/ajc170/Ajc170Tests.java
/******************************************************************************* * Copyright (c) 2008-2012 Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Andy Clement - initial API and implementation *******************************************************************************/ package org.aspectj.systemtest.ajc170; import java.io.File; import junit.framework.Test; import org.aspectj.apache.bcel.classfile.Field; import org.aspectj.apache.bcel.classfile.JavaClass; import org.aspectj.testing.XMLBasedAjcTestCase; import org.aspectj.weaver.TypeFactory; import org.aspectj.weaver.UnresolvedType; import org.aspectj.weaver.World; import org.aspectj.weaver.internal.tools.StandardPointcutExpressionImpl; import org.aspectj.weaver.patterns.Pointcut; import org.aspectj.weaver.patterns.PointcutRewriter; import org.aspectj.weaver.reflect.ReflectionWorld; import org.aspectj.weaver.tools.StandardPointcutParser; /** * @author Andy Clement */ public class Ajc170Tests extends org.aspectj.testing.XMLBasedAjcTestCase { // public void testLostAnnos_377130() { // runTest("missing annos on priv aspects"); // } // // public void testLostAnnos_377130_2() { // runTest("missing annos on priv aspects - 2"); // } public void testGenericAspectAround382723() { runTest("generic aspect"); } public void testGenericAspectAround382723_2() { runTest("generic aspect 2"); } public void testGenericAspectAround382723_3() { runTest("generic aspect 3"); } public void testGenericAspectAround382723_4() { runTest("generic aspect 4"); } // public void testCovariantGenericsItd382189() { // runTest("covariant generics"); // } public void testAttributeErrorJ7() { runTest("attribute issue with J7"); } public void testSwitchOnEnum() { runTest("switch on enum"); } public void testDecAtFieldOrderingLTW1() { runTest("dec at field ordering ltw 1"); } public void testDecAtFieldOrdering1() { runTest("dec at field ordering 1"); } // public void testDecAtFieldOrdering2() { // runTest("dec at field ordering 2"); // } public void testXmlDefsDeclareAnnoType() { runTest("xml defined dec anno - type"); } public void testXmlDefsDeclareAnnoMethod() { runTest("xml defined dec at method"); } // anno not runtime vis public void testXmlDefsDeclareAnnoMethod2() { runTest("xml defined dec at method 2"); } public void testXmlDefsDeclareAnnoField() { runTest("xml defined dec at field"); } public void testXmlDefsDeclareAnnoFieldVariants1() { runTest("xml defined dec anno - variants 1"); } public void testXmlDefsDeclareAnnoFieldVariants2() { runTest("xml defined dec anno - variants 2"); } public void testXmlDefsDeclareAnnoFieldMultipleValues() { runTest("xml defined dec anno - multiple values"); } public void testXmlDefsDeclareAnnoFieldMultipleValuesAndSpaces() { runTest("xml defined dec anno - multiple values and spaces"); } public void testPointcutExpense_374964() { // check a declaring type being specified causes the call() to be considered cheaper than this() World world = new ReflectionWorld(true, getClass().getClassLoader()); StandardPointcutParser pointcutParser = StandardPointcutParser.getPointcutParserSupportingAllPrimitives(world); StandardPointcutExpressionImpl pointcutExpression = (StandardPointcutExpressionImpl)pointcutParser.parsePointcutExpression("call(* *(..)) && this(Object)"); Pointcut pc = pointcutExpression.getUnderlyingPointcut(); Pointcut newp = new PointcutRewriter().rewrite(pc); // no declaring type so this() is considered cheaper assertEquals("(this(java.lang.Object) && call(* *(..)))",newp.toString()); pointcutExpression = (StandardPointcutExpressionImpl)pointcutParser.parsePointcutExpression("call(* String.*(..)) && this(Object)"); pc = pointcutExpression.getUnderlyingPointcut(); newp = new PointcutRewriter().rewrite(pc); // declaring type, so call() is cheaper assertEquals("(call(* java.lang.String.*(..)) && this(java.lang.Object))",newp.toString()); pointcutExpression = (StandardPointcutExpressionImpl)pointcutParser.parsePointcutExpression("this(Object) && call(* *(..)) && call(* String.*(..))"); pc = pointcutExpression.getUnderlyingPointcut(); newp = new PointcutRewriter().rewrite(pc); // more complex example, mix of them assertEquals("((call(* java.lang.String.*(..)) && this(java.lang.Object)) && call(* *(..)))",newp.toString()); } /* public void testPublicITDFs_pr73507_1() { runTest("public ITDfs - 1"); } public void testPublicITDFs_pr73507_2() { runTest("public ITDfs - 2"); } public void testPublicITDFs_pr73507_3() { runTest("public ITDfs - 3"); } public void testPublicITDFs_pr73507_4() { runTest("public ITDfs - 4"); } */ public void testBCExceptionAnnoDecp_371998() { runTest("BCException anno decp"); } public void testTransientTjpFields()throws Exception { runTest("transient tjp fields"); JavaClass jc = getClassFrom(ajc.getSandboxDirectory(), "Code"); Field[] fs = jc.getFields(); //private static final org.aspectj.lang.JoinPoint$StaticPart ajc$tjp_0 [Synthetic] //private static final org.aspectj.lang.JoinPoint$StaticPart ajc$tjp_1 [Synthetic] for (Field f: fs) { if (!f.isTransient()) { fail("Field should be transient: "+f); } } } public void testGenericsWithTwoTypeParamsOneWildcard() { UnresolvedType ut; ut = TypeFactory.createTypeFromSignature("LFoo<**>;"); assertEquals(2,ut.getTypeParameters().length); ut = TypeFactory.createTypeFromSignature("LFoo<***>;"); assertEquals(3,ut.getTypeParameters().length); ut = TypeFactory.createTypeFromSignature("LFoo<TP;*+Ljava/lang/String;>;"); assertEquals(2,ut.getTypeParameters().length); ut = TypeFactory.createTypeFromSignature("LFoo<*+Ljava/lang/String;TP;>;"); assertEquals(2,ut.getTypeParameters().length); ut = TypeFactory.createTypeFromSignature("LFoo<*+Ljava/lang/String;TP;>;"); assertEquals(2,ut.getTypeParameters().length); ut = TypeFactory.createTypeFromSignature("LFoo<*TT;>;"); assertEquals(2,ut.getTypeParameters().length); ut = TypeFactory.createTypeFromSignature("LFoo<[I>;"); assertEquals(1,ut.getTypeParameters().length); ut = TypeFactory.createTypeFromSignature("LFoo<[I[Z>;"); assertEquals(2,ut.getTypeParameters().length); } public void testPerThis() { runTest("perthis"); } public void testPerTarget() { runTest("pertarget"); } public void testPerCflow() { runTest("percflow"); } public void testPerTypeWithin() { runTest("pertypewithin"); } // not specifying -1.7 public void testDiamond1() { runTest("diamond 1"); } public void testDiamond2() { runTest("diamond 2"); } public void testDiamondItd1() { runTest("diamond itd 1"); } public void testLiterals1() { runTest("literals 1"); } public void testLiterals2() { runTest("literals 2"); } public void testLiteralsItd1() { runTest("literals itd 1"); } public void testStringSwitch1() { runTest("string switch 1"); } public void testStringSwitch2() { runTest("string switch 2"); } public void testMultiCatch1() { runTest("multi catch 1"); } public void testMultiCatch2() { runTest("multi catch 2"); } public void testMultiCatchWithHandler1() { runTest("multi catch with handler 1"); } public void testMultiCatchAspect1() { runTest("multi catch aspect 1"); } // public void testMultiCatchWithHandler2() { // runTest("multi catch with handler 2"); // } public void testSanity1() { runTest("sanity 1"); } public void testMissingImpl_363979() { runTest("missing impl"); } public void testMissingImpl_363979_2() { runTest("missing impl 2"); } public void testStackOverflow_364380() { runTest("stackoverflow"); } // public void testTryResources1() { // runTest("try resources 1"); // } // // public void testTryResources2() { // runTest("try resources 2"); // } // --- public static Test suite() { return XMLBasedAjcTestCase.loadSuite(Ajc170Tests.class); } @Override protected File getSpecFile() { return new File("../tests/src/org/aspectj/systemtest/ajc170/ajc170.xml"); } }
382,189
Bug 382189 NPE in BcelTypeMunger.createBridgeMethod
Build Identifier: Since I updated to version AspectJ Development Tools 2.2.0.e37x-20120529-0900 I get during compile: java.lang.NullPointerException at org.aspectj.weaver.bcel.BcelTypeMunger.createBridgeMethod(BcelTypeMunger.java:1325) at org.aspectj.weaver.bcel.BcelTypeMunger.createAnyBridgeMethodsForCovariance(BcelTypeMunger.java:1272) at org.aspectj.weaver.bcel.BcelTypeMunger.mungeNewMethod(BcelTypeMunger.java:971) at org.aspectj.weaver.bcel.BcelTypeMunger.munge(BcelTypeMunger.java:108) at org.aspectj.weaver.bcel.BcelClassWeaver.weave(BcelClassWeave ... ) Before, I had AspectJ Development Tools 2.2.0.e37x-20120507-1400 and the same project compiled without that exception. Reproducible: Always
resolved fixed
a748303
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2012-06-16T00:42:25Z"
"2012-06-10T14:53:20Z"
weaver/src/org/aspectj/weaver/bcel/BcelTypeMunger.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Eclipse Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * PARC initial implementation * Alexandre Vasseur @AspectJ ITDs * ******************************************************************/ package org.aspectj.weaver.bcel; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import org.aspectj.apache.bcel.Constants; import org.aspectj.apache.bcel.classfile.ClassFormatException; import org.aspectj.apache.bcel.classfile.ConstantPool; import org.aspectj.apache.bcel.classfile.Signature; import org.aspectj.apache.bcel.classfile.annotation.AnnotationGen; import org.aspectj.apache.bcel.generic.FieldGen; import org.aspectj.apache.bcel.generic.InstructionBranch; import org.aspectj.apache.bcel.generic.InstructionConstants; import org.aspectj.apache.bcel.generic.InstructionFactory; import org.aspectj.apache.bcel.generic.InstructionHandle; import org.aspectj.apache.bcel.generic.InstructionList; import org.aspectj.apache.bcel.generic.InvokeInstruction; import org.aspectj.apache.bcel.generic.Type; import org.aspectj.asm.AsmManager; import org.aspectj.asm.IProgramElement; import org.aspectj.bridge.IMessage; import org.aspectj.bridge.ISourceLocation; import org.aspectj.bridge.Message; import org.aspectj.bridge.MessageUtil; import org.aspectj.bridge.WeaveMessage; import org.aspectj.bridge.context.CompilationAndWeavingContext; import org.aspectj.bridge.context.ContextToken; import org.aspectj.weaver.AjcMemberMaker; import org.aspectj.weaver.AnnotationAJ; import org.aspectj.weaver.AnnotationOnTypeMunger; import org.aspectj.weaver.BCException; import org.aspectj.weaver.ConcreteTypeMunger; import org.aspectj.weaver.Member; import org.aspectj.weaver.MemberUtils; import org.aspectj.weaver.MethodDelegateTypeMunger; import org.aspectj.weaver.NameMangler; import org.aspectj.weaver.NewConstructorTypeMunger; import org.aspectj.weaver.NewFieldTypeMunger; import org.aspectj.weaver.NewMemberClassTypeMunger; import org.aspectj.weaver.NewMethodTypeMunger; import org.aspectj.weaver.NewParentTypeMunger; import org.aspectj.weaver.PerObjectInterfaceTypeMunger; import org.aspectj.weaver.PrivilegedAccessMunger; import org.aspectj.weaver.ResolvedMember; import org.aspectj.weaver.ResolvedMemberImpl; import org.aspectj.weaver.ResolvedType; import org.aspectj.weaver.ResolvedTypeMunger; import org.aspectj.weaver.Shadow; import org.aspectj.weaver.TypeVariableReference; import org.aspectj.weaver.UnresolvedType; import org.aspectj.weaver.WeaverMessages; import org.aspectj.weaver.WeaverStateInfo; import org.aspectj.weaver.World; import org.aspectj.weaver.model.AsmRelationshipProvider; import org.aspectj.weaver.patterns.DeclareAnnotation; import org.aspectj.weaver.patterns.Pointcut; public class BcelTypeMunger extends ConcreteTypeMunger { public BcelTypeMunger(ResolvedTypeMunger munger, ResolvedType aspectType) { super(munger, aspectType); } @Override public String toString() { return "(BcelTypeMunger " + getMunger() + ")"; } @Override public boolean shouldOverwrite() { return false; } public boolean munge(BcelClassWeaver weaver) { ContextToken tok = CompilationAndWeavingContext.enteringPhase(CompilationAndWeavingContext.MUNGING_WITH, this); boolean changed = false; boolean worthReporting = true; if (weaver.getWorld().isOverWeaving()) { WeaverStateInfo typeWeaverState = weaver.getLazyClassGen().getType().getWeaverState(); if (typeWeaverState != null && typeWeaverState.isAspectAlreadyApplied(getAspectType())) { return false; } } if (munger.getKind() == ResolvedTypeMunger.Field) { changed = mungeNewField(weaver, (NewFieldTypeMunger) munger); } else if (munger.getKind() == ResolvedTypeMunger.Method) { changed = mungeNewMethod(weaver, (NewMethodTypeMunger) munger); } else if (munger.getKind() == ResolvedTypeMunger.InnerClass) { changed = mungeNewMemberType(weaver, (NewMemberClassTypeMunger) munger); } else if (munger.getKind() == ResolvedTypeMunger.MethodDelegate2) { changed = mungeMethodDelegate(weaver, (MethodDelegateTypeMunger) munger); } else if (munger.getKind() == ResolvedTypeMunger.FieldHost) { changed = mungeFieldHost(weaver, (MethodDelegateTypeMunger.FieldHostTypeMunger) munger); } else if (munger.getKind() == ResolvedTypeMunger.PerObjectInterface) { changed = mungePerObjectInterface(weaver, (PerObjectInterfaceTypeMunger) munger); worthReporting = false; } else if (munger.getKind() == ResolvedTypeMunger.PerTypeWithinInterface) { // PTWIMPL Transform the target type (add the aspect instance field) changed = mungePerTypeWithinTransformer(weaver); worthReporting = false; } else if (munger.getKind() == ResolvedTypeMunger.PrivilegedAccess) { changed = mungePrivilegedAccess(weaver, (PrivilegedAccessMunger) munger); worthReporting = false; } else if (munger.getKind() == ResolvedTypeMunger.Constructor) { changed = mungeNewConstructor(weaver, (NewConstructorTypeMunger) munger); } else if (munger.getKind() == ResolvedTypeMunger.Parent) { changed = mungeNewParent(weaver, (NewParentTypeMunger) munger); } else if (munger.getKind() == ResolvedTypeMunger.AnnotationOnType) { changed = mungeNewAnnotationOnType(weaver, (AnnotationOnTypeMunger) munger); worthReporting = false; } else { throw new RuntimeException("unimplemented"); } if (changed && munger.changesPublicSignature()) { WeaverStateInfo info = weaver.getLazyClassGen().getOrCreateWeaverStateInfo(weaver.getReweavableMode()); info.addConcreteMunger(this); } if (changed && worthReporting) { ResolvedType declaringAspect = null; AsmManager model = ((BcelWorld) getWorld()).getModelAsAsmManager(); if (model != null) { if (munger instanceof NewParentTypeMunger) { NewParentTypeMunger nptMunger = (NewParentTypeMunger) munger; declaringAspect = nptMunger.getDeclaringType(); if (declaringAspect.isParameterizedOrGenericType()) { declaringAspect = declaringAspect.getRawType(); } ResolvedType thisAspect = getAspectType(); AsmRelationshipProvider.addRelationship(model, weaver.getLazyClassGen().getType(), munger, thisAspect); // Add a relationship on the actual declaring aspect too if (!thisAspect.equals(declaringAspect)) { // Might be the case the declaring aspect is generic and thisAspect is parameterizing it. In that case // record the actual parameterizations ResolvedType target = weaver.getLazyClassGen().getType(); ResolvedType newParent = nptMunger.getNewParent(); IProgramElement thisAspectNode = model.getHierarchy().findElementForType(thisAspect.getPackageName(), thisAspect.getClassName()); Map<String, List<String>> declareParentsMap = thisAspectNode.getDeclareParentsMap(); if (declareParentsMap == null) { declareParentsMap = new HashMap<String, List<String>>(); thisAspectNode.setDeclareParentsMap(declareParentsMap); } String tname = target.getName(); String pname = newParent.getName(); List<String> newparents = declareParentsMap.get(tname); if (newparents == null) { newparents = new ArrayList<String>(); declareParentsMap.put(tname, newparents); } newparents.add(pname); AsmRelationshipProvider.addRelationship(model, weaver.getLazyClassGen().getType(), munger, declaringAspect); } } else { declaringAspect = getAspectType(); AsmRelationshipProvider.addRelationship(model, weaver.getLazyClassGen().getType(), munger, declaringAspect); } } } // TAG: WeavingMessage if (changed && worthReporting && munger != null && !weaver.getWorld().getMessageHandler().isIgnoring(IMessage.WEAVEINFO)) { String tName = weaver.getLazyClassGen().getType().getSourceLocation().getSourceFile().getName(); if (tName.indexOf("no debug info available") != -1) { tName = "no debug info available"; } else { tName = getShortname(weaver.getLazyClassGen().getType().getSourceLocation().getSourceFile().getPath()); } String fName = getShortname(getAspectType().getSourceLocation().getSourceFile().getPath()); if (munger.getKind().equals(ResolvedTypeMunger.Parent)) { // This message could come out of AjLookupEnvironment.addParent // if doing parents munging at compile time only... NewParentTypeMunger parentTM = (NewParentTypeMunger) munger; if (parentTM.isMixin()) { weaver.getWorld() .getMessageHandler() .handleMessage( WeaveMessage.constructWeavingMessage(WeaveMessage.WEAVEMESSAGE_MIXIN, new String[] { parentTM.getNewParent().getName(), fName, weaver.getLazyClassGen().getType().getName(), tName }, weaver.getLazyClassGen().getClassName(), getAspectType().getName())); } else { if (parentTM.getNewParent().isInterface()) { weaver.getWorld() .getMessageHandler() .handleMessage( WeaveMessage.constructWeavingMessage(WeaveMessage.WEAVEMESSAGE_DECLAREPARENTSIMPLEMENTS, new String[] { weaver.getLazyClassGen().getType().getName(), tName, parentTM.getNewParent().getName(), fName }, weaver.getLazyClassGen() .getClassName(), getAspectType().getName())); } else { weaver.getWorld() .getMessageHandler() .handleMessage( WeaveMessage.constructWeavingMessage(WeaveMessage.WEAVEMESSAGE_DECLAREPARENTSEXTENDS, new String[] { weaver.getLazyClassGen().getType().getName(), tName, parentTM.getNewParent().getName(), fName })); // TAG: WeavingMessage DECLARE PARENTS: EXTENDS // reportDeclareParentsMessage(WeaveMessage. // WEAVEMESSAGE_DECLAREPARENTSEXTENDS,sourceType,parent); } } } else if (munger.getKind().equals(ResolvedTypeMunger.FieldHost)) { // hidden } else { ResolvedMember declaredSig = munger.getSignature(); String fromString = fName + ":'" + declaredSig + "'"; // if (declaredSig==null) declaredSig= munger.getSignature(); String kindString = munger.getKind().toString().toLowerCase(); if (kindString.equals("innerclass")) { kindString = "member class"; fromString = fName; } weaver.getWorld() .getMessageHandler() .handleMessage( WeaveMessage.constructWeavingMessage(WeaveMessage.WEAVEMESSAGE_ITD, new String[] { weaver.getLazyClassGen().getType().getName(), tName, kindString, getAspectType().getName(), fromString }, weaver.getLazyClassGen().getClassName(), getAspectType().getName())); } } CompilationAndWeavingContext.leavingPhase(tok); return changed; } private String getShortname(String path) { int takefrom = path.lastIndexOf('/'); if (takefrom == -1) { takefrom = path.lastIndexOf('\\'); } return path.substring(takefrom + 1); } private boolean mungeNewAnnotationOnType(BcelClassWeaver weaver, AnnotationOnTypeMunger munger) { // FIXME asc this has already been done up front, need to do it here too? try { BcelAnnotation anno = (BcelAnnotation) munger.getNewAnnotation(); weaver.getLazyClassGen().addAnnotation(anno.getBcelAnnotation()); } catch (ClassCastException cce) { throw new IllegalStateException("DiagnosticsFor318237: The typemunger "+munger+" contains an annotation of type "+ munger.getNewAnnotation().getClass().getName()+" when it should be a BcelAnnotation",cce); } return true; } /** * For a long time, AspectJ did not allow binary weaving of declare parents. This restriction is now lifted but could do with * more testing! */ private boolean mungeNewParent(BcelClassWeaver weaver, NewParentTypeMunger typeTransformer) { LazyClassGen newParentTarget = weaver.getLazyClassGen(); ResolvedType newParent = typeTransformer.getNewParent(); boolean performChange = true; performChange = enforceDecpRule1_abstractMethodsImplemented(weaver, typeTransformer.getSourceLocation(), newParentTarget, newParent); performChange = enforceDecpRule2_cantExtendFinalClass(weaver, typeTransformer.getSourceLocation(), newParentTarget, newParent) && performChange; List<ResolvedMember> methods = newParent.getMethodsWithoutIterator(false, true, false); for (ResolvedMember method : methods) { if (!method.getName().equals("<init>")) { LazyMethodGen subMethod = findMatchingMethod(newParentTarget, method); // FIXME asc is this safe for all bridge methods? if (subMethod != null && !subMethod.isBridgeMethod()) { if (!(subMethod.isSynthetic() && method.isSynthetic())) { if (!(subMethod.isStatic() && subMethod.getName().startsWith("access$"))) { // ignore generated accessors performChange = enforceDecpRule3_visibilityChanges(weaver, newParent, method, subMethod) && performChange; performChange = enforceDecpRule4_compatibleReturnTypes(weaver, method, subMethod) && performChange; performChange = enforceDecpRule5_cantChangeFromStaticToNonstatic(weaver, typeTransformer.getSourceLocation(), method, subMethod) && performChange; } } } } } if (!performChange) { // A rule was violated and an error message already reported return false; } if (newParent.isClass()) { // Changing the supertype if (!attemptToModifySuperCalls(weaver, newParentTarget, newParent)) { return false; } newParentTarget.setSuperClass(newParent); } else { // Add a new interface newParentTarget.addInterface(newParent, getSourceLocation()); } return true; } /** * Rule 1: For the declare parents to be allowed, the target type must override and implement inherited abstract methods (if the * type is not declared abstract) */ private boolean enforceDecpRule1_abstractMethodsImplemented(BcelClassWeaver weaver, ISourceLocation mungerLoc, LazyClassGen newParentTarget, ResolvedType newParent) { // Ignore abstract classes or interfaces if (newParentTarget.isAbstract() || newParentTarget.isInterface()) { return true; } boolean ruleCheckingSucceeded = true; List<ResolvedMember> newParentMethods = newParent.getMethodsWithoutIterator(false, true, false); for (ResolvedMember newParentMethod : newParentMethods) { String newParentMethodName = newParentMethod.getName(); // Ignore abstract ajc$interField prefixed methods if (newParentMethod.isAbstract() && !newParentMethodName.startsWith("ajc$interField")) { ResolvedMember discoveredImpl = null; List<ResolvedMember> targetMethods = newParentTarget.getType().getMethodsWithoutIterator(false, true, false); for (ResolvedMember targetMethod : targetMethods) { if (!targetMethod.isAbstract() && targetMethod.getName().equals(newParentMethodName)) { String newParentMethodSig = newParentMethod.getParameterSignature(); // ([TT;) String targetMethodSignature = targetMethod.getParameterSignature(); // ([Ljava/lang/Object;) // could be a match if (targetMethodSignature.equals(newParentMethodSig)) { discoveredImpl = targetMethod; } else { // Does the erasure match? In which case a bridge method will be created later to // satisfy the abstract method if (targetMethod.hasBackingGenericMember() && targetMethod.getBackingGenericMember().getParameterSignature().equals(newParentMethodSig)) { discoveredImpl = targetMethod; } else if (newParentMethod.hasBackingGenericMember()) { if (newParentMethod.getBackingGenericMember().getParameterSignature().equals(targetMethodSignature)) { discoveredImpl = targetMethod; } } } if (discoveredImpl != null) { break; } } } if (discoveredImpl == null) { // didnt find a valid implementation, lets check the // ITDs on this type to see if they satisfy it boolean satisfiedByITD = false; for (ConcreteTypeMunger m : newParentTarget.getType().getInterTypeMungersIncludingSupers()) { if (m.getMunger() != null && m.getMunger().getKind() == ResolvedTypeMunger.Method) { ResolvedMember sig = m.getSignature(); if (!Modifier.isAbstract(sig.getModifiers())) { // If the ITD shares a type variable with some target type, we need to tailor it // for that type if (m.isTargetTypeParameterized()) { ResolvedType genericOnType = getWorld().resolve(sig.getDeclaringType()).getGenericType(); m = m.parameterizedFor(newParent.discoverActualOccurrenceOfTypeInHierarchy(genericOnType)); // possible sig change when type parameters filled in sig = m.getSignature(); } if (ResolvedType.matches( AjcMemberMaker.interMethod(sig, m.getAspectType(), sig.getDeclaringType().resolve(weaver.getWorld()).isInterface()), newParentMethod)) { satisfiedByITD = true; } } } else if (m.getMunger() != null && m.getMunger().getKind() == ResolvedTypeMunger.MethodDelegate2) { // AV - that should be enough, no need to check more satisfiedByITD = true; } } if (!satisfiedByITD) { error(weaver, "The type " + newParentTarget.getName() + " must implement the inherited abstract method " + newParentMethod.getDeclaringType() + "." + newParentMethodName + newParentMethod.getParameterSignature(), newParentTarget.getType().getSourceLocation(), new ISourceLocation[] { newParentMethod.getSourceLocation(), mungerLoc }); ruleCheckingSucceeded = false; } } } } return ruleCheckingSucceeded; } /** * Rule 2. Can't extend final types */ private boolean enforceDecpRule2_cantExtendFinalClass(BcelClassWeaver weaver, ISourceLocation transformerLoc, LazyClassGen targetType, ResolvedType newParent) { if (newParent.isFinal()) { error(weaver, "Cannot make type " + targetType.getName() + " extend final class " + newParent.getName(), targetType .getType().getSourceLocation(), new ISourceLocation[] { transformerLoc }); return false; } return true; } /** * Rule 3. Can't narrow visibility of methods when overriding */ private boolean enforceDecpRule3_visibilityChanges(BcelClassWeaver weaver, ResolvedType newParent, ResolvedMember superMethod, LazyMethodGen subMethod) { boolean cont = true; if (Modifier.isPublic(superMethod.getModifiers())) { if (subMethod.isProtected() || subMethod.isDefault() || subMethod.isPrivate()) { weaver.getWorld() .getMessageHandler() .handleMessage( MessageUtil.error("Cannot reduce the visibility of the inherited method '" + superMethod + "' from " + newParent.getName(), superMethod.getSourceLocation())); cont = false; } } else if (Modifier.isProtected(superMethod.getModifiers())) { if (subMethod.isDefault() || subMethod.isPrivate()) { weaver.getWorld() .getMessageHandler() .handleMessage( MessageUtil.error("Cannot reduce the visibility of the inherited method '" + superMethod + "' from " + newParent.getName(), superMethod.getSourceLocation())); cont = false; } } else if (superMethod.isDefault()) { if (subMethod.isPrivate()) { weaver.getWorld() .getMessageHandler() .handleMessage( MessageUtil.error("Cannot reduce the visibility of the inherited method '" + superMethod + "' from " + newParent.getName(), superMethod.getSourceLocation())); cont = false; } } return cont; } /** * Rule 4. Can't have incompatible return types */ private boolean enforceDecpRule4_compatibleReturnTypes(BcelClassWeaver weaver, ResolvedMember superMethod, LazyMethodGen subMethod) { boolean cont = true; String superReturnTypeSig = superMethod.getGenericReturnType().getSignature(); // eg. Pjava/util/Collection<LFoo;> String subReturnTypeSig = subMethod.getGenericReturnTypeSignature(); superReturnTypeSig = superReturnTypeSig.replace('.', '/'); subReturnTypeSig = subReturnTypeSig.replace('.', '/'); if (!superReturnTypeSig.equals(subReturnTypeSig)) { // Check for covariance ResolvedType subType = weaver.getWorld().resolve(subMethod.getReturnType()); ResolvedType superType = weaver.getWorld().resolve(superMethod.getReturnType()); if (!superType.isAssignableFrom(subType)) { weaver.getWorld() .getMessageHandler() .handleMessage( MessageUtil.error("The return type is incompatible with " + superMethod.getDeclaringType() + "." + superMethod.getName() + superMethod.getParameterSignature(), subMethod.getSourceLocation())); // this just might be a better error message... // "The return type '"+subReturnTypeSig+ // "' is incompatible with the overridden method " // +superMethod.getDeclaringType()+"."+ // superMethod.getName()+superMethod.getParameterSignature()+ // " which returns '"+superReturnTypeSig+"'", cont = false; } } return cont; } /** * Rule5. Method overrides can't change the staticality (word?) - you can't override and make an instance method static or * override and make a static method an instance method. */ private boolean enforceDecpRule5_cantChangeFromStaticToNonstatic(BcelClassWeaver weaver, ISourceLocation mungerLoc, ResolvedMember superMethod, LazyMethodGen subMethod) { boolean superMethodStatic = Modifier.isStatic(superMethod.getModifiers()); if (superMethodStatic && !subMethod.isStatic()) { error(weaver, "This instance method " + subMethod.getName() + subMethod.getParameterSignature() + " cannot override the static method from " + superMethod.getDeclaringType().getName(), subMethod.getSourceLocation(), new ISourceLocation[] { mungerLoc }); return false; } else if (!superMethodStatic && subMethod.isStatic()) { error(weaver, "The static method " + subMethod.getName() + subMethod.getParameterSignature() + " cannot hide the instance method from " + superMethod.getDeclaringType().getName(), subMethod.getSourceLocation(), new ISourceLocation[] { mungerLoc }); return false; } return true; } public void error(BcelClassWeaver weaver, String text, ISourceLocation primaryLoc, ISourceLocation[] extraLocs) { IMessage msg = new Message(text, primaryLoc, true, extraLocs); weaver.getWorld().getMessageHandler().handleMessage(msg); } /** * Search the specified type for a particular method - do not use the return value in the comparison as it is not considered for * overriding. */ private LazyMethodGen findMatchingMethod(LazyClassGen type, ResolvedMember searchMethod) { String searchName = searchMethod.getName(); String searchSig = searchMethod.getParameterSignature(); for (LazyMethodGen method : type.getMethodGens()) { if (method.getName().equals(searchName) && method.getParameterSignature().equals(searchSig)) { return method; } } return null; } /** * The main part of implementing declare parents extends. Modify super ctor calls to target the new type. */ public boolean attemptToModifySuperCalls(BcelClassWeaver weaver, LazyClassGen newParentTarget, ResolvedType newParent) { ResolvedType currentParentType = newParentTarget.getSuperClass(); if (currentParentType.getGenericType() != null) { currentParentType = currentParentType.getGenericType(); } String currentParent = currentParentType.getName(); if (newParent.getGenericType() != null) { newParent = newParent.getGenericType(); // target new super calls at } // the generic type if its raw or parameterized List<LazyMethodGen> mgs = newParentTarget.getMethodGens(); // Look for ctors to modify for (LazyMethodGen aMethod : mgs) { if (LazyMethodGen.isConstructor(aMethod)) { InstructionList insList = aMethod.getBody(); InstructionHandle handle = insList.getStart(); while (handle != null) { if (handle.getInstruction().opcode == Constants.INVOKESPECIAL) { ConstantPool cpg = newParentTarget.getConstantPool(); InvokeInstruction invokeSpecial = (InvokeInstruction) handle.getInstruction(); if (invokeSpecial.getClassName(cpg).equals(currentParent) && invokeSpecial.getMethodName(cpg).equals("<init>")) { // System.err.println("Transforming super call '<init>" + invokeSpecial.getSignature(cpg) + "'"); // 1. Check there is a ctor in the new parent with // the same signature ResolvedMember newCtor = getConstructorWithSignature(newParent, invokeSpecial.getSignature(cpg)); if (newCtor == null) { // 2. Check ITDCs to see if the necessary ctor is provided that way boolean satisfiedByITDC = false; for (Iterator<ConcreteTypeMunger> ii = newParentTarget.getType() .getInterTypeMungersIncludingSupers().iterator(); ii.hasNext() && !satisfiedByITDC;) { ConcreteTypeMunger m = ii.next(); if (m.getMunger() instanceof NewConstructorTypeMunger) { if (m.getSignature().getSignature().equals(invokeSpecial.getSignature(cpg))) { satisfiedByITDC = true; } } } if (!satisfiedByITDC) { String csig = createReadableCtorSig(newParent, cpg, invokeSpecial); weaver.getWorld() .getMessageHandler() .handleMessage( MessageUtil.error( "Unable to modify hierarchy for " + newParentTarget.getClassName() + " - the constructor " + csig + " is missing", this.getSourceLocation())); return false; } } int idx = cpg.addMethodref(newParent.getName(), invokeSpecial.getMethodName(cpg), invokeSpecial.getSignature(cpg)); invokeSpecial.setIndex(idx); } } handle = handle.getNext(); } } } return true; } /** * Creates a nice signature for the ctor, something like "(int,Integer,String)" */ private String createReadableCtorSig(ResolvedType newParent, ConstantPool cpg, InvokeInstruction invokeSpecial) { StringBuffer sb = new StringBuffer(); Type[] ctorArgs = invokeSpecial.getArgumentTypes(cpg); sb.append(newParent.getClassName()); sb.append("("); for (int i = 0; i < ctorArgs.length; i++) { String argtype = ctorArgs[i].toString(); if (argtype.lastIndexOf(".") != -1) { sb.append(argtype.substring(argtype.lastIndexOf(".") + 1)); } else { sb.append(argtype); } if (i + 1 < ctorArgs.length) { sb.append(","); } } sb.append(")"); return sb.toString(); } private ResolvedMember getConstructorWithSignature(ResolvedType type, String searchSig) { for (ResolvedMember method : type.getDeclaredJavaMethods()) { if (MemberUtils.isConstructor(method)) { if (method.getSignature().equals(searchSig)) { return method; } } } return null; } private boolean mungePrivilegedAccess(BcelClassWeaver weaver, PrivilegedAccessMunger munger) { LazyClassGen gen = weaver.getLazyClassGen(); ResolvedMember member = munger.getMember(); ResolvedType onType = weaver.getWorld().resolve(member.getDeclaringType(), munger.getSourceLocation()); if (onType.isRawType()) { onType = onType.getGenericType(); } // System.out.println("munging: " + gen + " with " + member); if (onType.equals(gen.getType())) { if (member.getKind() == Member.FIELD) { // System.out.println("matched: " + gen); addFieldGetter(gen, member, AjcMemberMaker.privilegedAccessMethodForFieldGet(aspectType, member, munger.shortSyntax)); addFieldSetter(gen, member, AjcMemberMaker.privilegedAccessMethodForFieldSet(aspectType, member, munger.shortSyntax)); return true; } else if (member.getKind() == Member.METHOD) { addMethodDispatch(gen, member, AjcMemberMaker.privilegedAccessMethodForMethod(aspectType, member)); return true; } else if (member.getKind() == Member.CONSTRUCTOR) { for (Iterator<LazyMethodGen> i = gen.getMethodGens().iterator(); i.hasNext();) { LazyMethodGen m = i.next(); if (m.getMemberView() != null && m.getMemberView().getKind() == Member.CONSTRUCTOR) { // m.getMemberView().equals(member)) { m.forcePublic(); // return true; } } return true; // throw new BCException("no match for " + member + " in " + // gen); } else if (member.getKind() == Member.STATIC_INITIALIZATION) { gen.forcePublic(); return true; } else { throw new RuntimeException("unimplemented"); } } return false; } private void addFieldGetter(LazyClassGen gen, ResolvedMember field, ResolvedMember accessMethod) { LazyMethodGen mg = makeMethodGen(gen, accessMethod); InstructionList il = new InstructionList(); InstructionFactory fact = gen.getFactory(); if (Modifier.isStatic(field.getModifiers())) { il.append(fact.createFieldAccess(gen.getClassName(), field.getName(), BcelWorld.makeBcelType(field.getType()), Constants.GETSTATIC)); } else { il.append(InstructionConstants.ALOAD_0); il.append(fact.createFieldAccess(gen.getClassName(), field.getName(), BcelWorld.makeBcelType(field.getType()), Constants.GETFIELD)); } il.append(InstructionFactory.createReturn(BcelWorld.makeBcelType(field.getType()))); mg.getBody().insert(il); gen.addMethodGen(mg, getSignature().getSourceLocation()); } private void addFieldSetter(LazyClassGen gen, ResolvedMember field, ResolvedMember accessMethod) { LazyMethodGen mg = makeMethodGen(gen, accessMethod); InstructionList il = new InstructionList(); InstructionFactory fact = gen.getFactory(); Type fieldType = BcelWorld.makeBcelType(field.getType()); if (Modifier.isStatic(field.getModifiers())) { il.append(InstructionFactory.createLoad(fieldType, 0)); il.append(fact.createFieldAccess(gen.getClassName(), field.getName(), fieldType, Constants.PUTSTATIC)); } else { il.append(InstructionConstants.ALOAD_0); il.append(InstructionFactory.createLoad(fieldType, 1)); il.append(fact.createFieldAccess(gen.getClassName(), field.getName(), fieldType, Constants.PUTFIELD)); } il.append(InstructionFactory.createReturn(Type.VOID)); mg.getBody().insert(il); gen.addMethodGen(mg, getSignature().getSourceLocation()); } private void addMethodDispatch(LazyClassGen gen, ResolvedMember method, ResolvedMember accessMethod) { LazyMethodGen mg = makeMethodGen(gen, accessMethod); InstructionList il = new InstructionList(); InstructionFactory fact = gen.getFactory(); // Type fieldType = BcelWorld.makeBcelType(field.getType()); Type[] paramTypes = BcelWorld.makeBcelTypes(method.getParameterTypes()); int pos = 0; if (!Modifier.isStatic(method.getModifiers())) { il.append(InstructionConstants.ALOAD_0); pos++; } for (int i = 0, len = paramTypes.length; i < len; i++) { Type paramType = paramTypes[i]; il.append(InstructionFactory.createLoad(paramType, pos)); pos += paramType.getSize(); } il.append(Utility.createInvoke(fact, (BcelWorld) aspectType.getWorld(), method)); il.append(InstructionFactory.createReturn(BcelWorld.makeBcelType(method.getReturnType()))); mg.getBody().insert(il); gen.addMethodGen(mg); } protected LazyMethodGen makeMethodGen(LazyClassGen gen, ResolvedMember member) { try { Type returnType = BcelWorld.makeBcelType(member.getReturnType()); Type[] parameterTypes = BcelWorld.makeBcelTypes(member.getParameterTypes()); LazyMethodGen ret = new LazyMethodGen(member.getModifiers(), returnType, member.getName(), parameterTypes, UnresolvedType.getNames(member .getExceptions()), gen); // 43972 : Static crosscutting makes interfaces unusable for javac // ret.makeSynthetic(); return ret; } catch (ClassFormatException cfe) { throw new RuntimeException("Problem with makeMethodGen for method "+member.getName()+" in type "+gen.getName()+" ret="+member.getReturnType(),cfe); } } protected FieldGen makeFieldGen(LazyClassGen gen, ResolvedMember member) { return new FieldGen(member.getModifiers(), BcelWorld.makeBcelType(member.getReturnType()), member.getName(), gen.getConstantPool()); } private boolean mungePerObjectInterface(BcelClassWeaver weaver, PerObjectInterfaceTypeMunger munger) { // System.err.println("Munging perobject ["+munger+"] onto "+weaver. // getLazyClassGen().getClassName()); LazyClassGen gen = weaver.getLazyClassGen(); if (couldMatch(gen.getBcelObjectType(), munger.getTestPointcut())) { FieldGen fg = makeFieldGen(gen, AjcMemberMaker.perObjectField(gen.getType(), aspectType)); gen.addField(fg, getSourceLocation()); Type fieldType = BcelWorld.makeBcelType(aspectType); LazyMethodGen mg = new LazyMethodGen(Modifier.PUBLIC, fieldType, NameMangler.perObjectInterfaceGet(aspectType), new Type[0], new String[0], gen); InstructionList il = new InstructionList(); InstructionFactory fact = gen.getFactory(); il.append(InstructionConstants.ALOAD_0); il.append(fact.createFieldAccess(gen.getClassName(), fg.getName(), fieldType, Constants.GETFIELD)); il.append(InstructionFactory.createReturn(fieldType)); mg.getBody().insert(il); gen.addMethodGen(mg); LazyMethodGen mg1 = new LazyMethodGen(Modifier.PUBLIC, Type.VOID, NameMangler.perObjectInterfaceSet(aspectType), new Type[] { fieldType, }, new String[0], gen); InstructionList il1 = new InstructionList(); il1.append(InstructionConstants.ALOAD_0); il1.append(InstructionFactory.createLoad(fieldType, 1)); il1.append(fact.createFieldAccess(gen.getClassName(), fg.getName(), fieldType, Constants.PUTFIELD)); il1.append(InstructionFactory.createReturn(Type.VOID)); mg1.getBody().insert(il1); gen.addMethodGen(mg1); gen.addInterface(munger.getInterfaceType().resolve(weaver.getWorld()), getSourceLocation()); return true; } else { return false; } } // PTWIMPL Add field to hold aspect instance and an accessor private boolean mungePerTypeWithinTransformer(BcelClassWeaver weaver) { LazyClassGen gen = weaver.getLazyClassGen(); // if (couldMatch(gen.getBcelObjectType(), munger.getTestPointcut())) { // Add (to the target type) the field that will hold the aspect instance // e.g ajc$com_blah_SecurityAspect$ptwAspectInstance FieldGen fg = makeFieldGen(gen, AjcMemberMaker.perTypeWithinField(gen.getType(), aspectType)); gen.addField(fg, getSourceLocation()); // Add an accessor for this new field, the // ajc$<aspectname>$localAspectOf() method // e.g. // "public com_blah_SecurityAspect ajc$com_blah_SecurityAspect$localAspectOf()" Type fieldType = BcelWorld.makeBcelType(aspectType); LazyMethodGen mg = new LazyMethodGen(Modifier.PUBLIC | Modifier.STATIC, fieldType, NameMangler.perTypeWithinLocalAspectOf(aspectType), new Type[0], new String[0], gen); InstructionList il = new InstructionList(); // PTWIMPL ?? Should check if it is null and throw // NoAspectBoundException InstructionFactory fact = gen.getFactory(); il.append(fact.createFieldAccess(gen.getClassName(), fg.getName(), fieldType, Constants.GETSTATIC)); il.append(InstructionFactory.createReturn(fieldType)); mg.getBody().insert(il); gen.addMethodGen(mg); return true; // } else { // return false; // } } // ??? Why do we have this method? I thought by now we would know if it // matched or not private boolean couldMatch(BcelObjectType bcelObjectType, Pointcut pointcut) { return !bcelObjectType.isInterface(); } private boolean mungeNewMemberType(BcelClassWeaver classWeaver, NewMemberClassTypeMunger munger) { World world = classWeaver.getWorld(); ResolvedType onType = world.resolve(munger.getTargetType()); if (onType.isRawType()) { onType = onType.getGenericType(); } return onType.equals(classWeaver.getLazyClassGen().getType()); } private boolean mungeNewMethod(BcelClassWeaver classWeaver, NewMethodTypeMunger munger) { World world = classWeaver.getWorld(); // Resolving it will sort out the tvars ResolvedMember unMangledInterMethod = munger.getSignature().resolve(world); // do matching on the unMangled one, but actually add them to the mangled method ResolvedMember interMethodBody = munger.getDeclaredInterMethodBody(aspectType, world); ResolvedMember interMethodDispatcher = munger.getDeclaredInterMethodDispatcher(aspectType, world); ResolvedMember memberHoldingAnyAnnotations = interMethodDispatcher; LazyClassGen classGen = classWeaver.getLazyClassGen(); ResolvedType onType = world.resolve(unMangledInterMethod.getDeclaringType(), munger.getSourceLocation()); if (onType.isRawType()) { onType = onType.getGenericType(); } // Simple checks, can't ITD on annotations or enums if (onType.isAnnotation()) { signalError(WeaverMessages.ITDM_ON_ANNOTATION_NOT_ALLOWED, classWeaver, onType); return false; } if (onType.isEnum()) { signalError(WeaverMessages.ITDM_ON_ENUM_NOT_ALLOWED, classWeaver, onType); return false; } boolean mungingInterface = classGen.isInterface(); boolean onInterface = onType.isInterface(); if (onInterface && classGen.getLazyMethodGen(unMangledInterMethod.getName(), unMangledInterMethod.getSignature(), true) != null) { // this is ok, we could be providing the default implementation of a // method // that the target has already declared return false; } // If we are processing the intended ITD target type (might be an interface) if (onType.equals(classGen.getType())) { ResolvedMember mangledInterMethod = AjcMemberMaker.interMethod(unMangledInterMethod, aspectType, onInterface); LazyMethodGen newMethod = makeMethodGen(classGen, mangledInterMethod); if (mungingInterface) { // we want the modifiers of the ITD to be used for all *implementors* of the // interface, but the method itself we add to the interface must be public abstract newMethod.setAccessFlags(Modifier.PUBLIC | Modifier.ABSTRACT); } // pr98901 // For copying the annotations across, we have to discover the real // member in the aspect which is holding them. if (classWeaver.getWorld().isInJava5Mode()) { AnnotationAJ annotationsOnRealMember[] = null; ResolvedType toLookOn = aspectType; if (aspectType.isRawType()) { toLookOn = aspectType.getGenericType(); } ResolvedMember realMember = getRealMemberForITDFromAspect(toLookOn, memberHoldingAnyAnnotations, false); // 266602 - consider it missing to mean that the corresponding aspect had errors if (realMember == null) { // signalWarning("Unable to apply any annotations attached to " + munger.getSignature(), weaver); // throw new BCException("Couldn't find ITD init member '" + interMethodBody + "' on aspect " + aspectType); } else { annotationsOnRealMember = realMember.getAnnotations(); } Set<ResolvedType> addedAnnotations = new HashSet<ResolvedType>(); if (annotationsOnRealMember != null) { for (AnnotationAJ anno : annotationsOnRealMember) { AnnotationGen a = ((BcelAnnotation) anno).getBcelAnnotation(); AnnotationGen ag = new AnnotationGen(a, classGen.getConstantPool(), true); newMethod.addAnnotation(new BcelAnnotation(ag, classWeaver.getWorld())); addedAnnotations.add(anno.getType()); } } if (realMember != null) { copyOverParameterAnnotations(newMethod, realMember); } // the code below was originally added to cope with the case where an aspect declares an annotation on an ITD // declared within itself (an unusual situation). However, it also addresses the case where we may not find the // annotation on the real representation of the ITD. This can happen in a load-time weaving situation where // we couldn't add the annotation in time - and so here we recheck the declare annotations. Not quite ideal but // works. pr288635 List<DeclareAnnotation> allDecams = world.getDeclareAnnotationOnMethods(); for (DeclareAnnotation declareAnnotationMC : allDecams) { if (declareAnnotationMC.matches(unMangledInterMethod, world)) { // && newMethod.getEnclosingClass().getType() == aspectType) { AnnotationAJ annotation = declareAnnotationMC.getAnnotation(); if (!addedAnnotations.contains(annotation.getType())) { newMethod.addAnnotation(annotation); } } } } // If it doesn't target an interface and there is a body (i.e. it // isnt abstract) if (!onInterface && !Modifier.isAbstract(mangledInterMethod.getModifiers())) { InstructionList body = newMethod.getBody(); InstructionFactory fact = classGen.getFactory(); int pos = 0; if (!Modifier.isStatic(unMangledInterMethod.getModifiers())) { body.append(InstructionFactory.createThis()); pos++; } Type[] paramTypes = BcelWorld.makeBcelTypes(mangledInterMethod.getParameterTypes()); for (int i = 0, len = paramTypes.length; i < len; i++) { Type paramType = paramTypes[i]; body.append(InstructionFactory.createLoad(paramType, pos)); pos += paramType.getSize(); } body.append(Utility.createInvoke(fact, classWeaver.getWorld(), interMethodBody)); body.append(InstructionFactory.createReturn(BcelWorld.makeBcelType(mangledInterMethod.getReturnType()))); if (classWeaver.getWorld().isInJava5Mode()) { // Don't need bridge // methods if not in // 1.5 mode. createAnyBridgeMethodsForCovariance(classWeaver, munger, unMangledInterMethod, onType, classGen, paramTypes); } } else { // ??? this is okay // if (!(mg.getBody() == null)) throw new // RuntimeException("bas"); } if (world.isInJava5Mode()) { String basicSignature = mangledInterMethod.getSignature(); String genericSignature = ((ResolvedMemberImpl) mangledInterMethod).getSignatureForAttribute(); if (!basicSignature.equals(genericSignature)) { // Add a signature attribute to it newMethod.addAttribute(createSignatureAttribute(classGen.getConstantPool(), genericSignature)); } } // XXX make sure to check that we set exceptions properly on this // guy. classWeaver.addLazyMethodGen(newMethod); classWeaver.getLazyClassGen().warnOnAddedMethod(newMethod.getMethod(), getSignature().getSourceLocation()); addNeededSuperCallMethods(classWeaver, onType, munger.getSuperMethodsCalled()); return true; } else if (onInterface && !Modifier.isAbstract(unMangledInterMethod.getModifiers())) { // This means the 'gen' should be the top most implementor // - if it is *not* then something went wrong after we worked // out that it was the top most implementor (see pr49657) if (!classGen.getType().isTopmostImplementor(onType)) { ResolvedType rtx = classGen.getType().getTopmostImplementor(onType); if (rtx == null) { // pr302460 // null means there is something wrong with what we are looking at ResolvedType rt = classGen.getType(); if (rt.isInterface()) { ISourceLocation sloc = munger.getSourceLocation(); classWeaver .getWorld() .getMessageHandler() .handleMessage( MessageUtil.error( "ITD target " + rt.getName() + " is an interface but has been incorrectly determined to be the topmost implementor of " + onType.getName() + ". ITD is " + this.getSignature(), sloc)); } if (!onType.isAssignableFrom(rt)) { ISourceLocation sloc = munger.getSourceLocation(); classWeaver .getWorld() .getMessageHandler() .handleMessage( MessageUtil.error( "ITD target " + rt.getName() + " doesn't appear to implement " + onType.getName() + " why did we consider it the top most implementor? ITD is " + this.getSignature(), sloc)); } } else if (!rtx.isExposedToWeaver()) { ISourceLocation sLoc = munger.getSourceLocation(); classWeaver .getWorld() .getMessageHandler() .handleMessage( MessageUtil.error(WeaverMessages.format(WeaverMessages.ITD_NON_EXPOSED_IMPLEMENTOR, rtx, getAspectType().getName()), (sLoc == null ? getAspectType().getSourceLocation() : sLoc))); } else { // XXX what does this state mean? // We have incorrectly identified what is the top most // implementor and its not because // a type wasn't exposed to the weaver } return false; } else { ResolvedMember mangledInterMethod = AjcMemberMaker.interMethod(unMangledInterMethod, aspectType, false); LazyMethodGen mg = makeMethodGen(classGen, mangledInterMethod); // From 98901#29 - need to copy annotations across if (classWeaver.getWorld().isInJava5Mode()) { AnnotationAJ annotationsOnRealMember[] = null; ResolvedType toLookOn = aspectType; if (aspectType.isRawType()) { toLookOn = aspectType.getGenericType(); } ResolvedMember realMember = getRealMemberForITDFromAspect(toLookOn, memberHoldingAnyAnnotations, false); if (realMember == null) { throw new BCException("Couldn't find ITD holder member '" + memberHoldingAnyAnnotations + "' on aspect " + aspectType); } annotationsOnRealMember = realMember.getAnnotations(); if (annotationsOnRealMember != null) { for (AnnotationAJ annotationX : annotationsOnRealMember) { AnnotationGen a = ((BcelAnnotation) annotationX).getBcelAnnotation(); AnnotationGen ag = new AnnotationGen(a, classWeaver.getLazyClassGen().getConstantPool(), true); mg.addAnnotation(new BcelAnnotation(ag, classWeaver.getWorld())); } } copyOverParameterAnnotations(mg, realMember); } if (mungingInterface) { // we want the modifiers of the ITD to be used for all // *implementors* of the // interface, but the method itself we add to the interface // must be public abstract mg.setAccessFlags(Modifier.PUBLIC | Modifier.ABSTRACT); } Type[] paramTypes = BcelWorld.makeBcelTypes(mangledInterMethod.getParameterTypes()); Type returnType = BcelWorld.makeBcelType(mangledInterMethod.getReturnType()); InstructionList body = mg.getBody(); InstructionFactory fact = classGen.getFactory(); int pos = 0; if (!Modifier.isStatic(mangledInterMethod.getModifiers())) { body.append(InstructionFactory.createThis()); pos++; } for (int i = 0, len = paramTypes.length; i < len; i++) { Type paramType = paramTypes[i]; body.append(InstructionFactory.createLoad(paramType, pos)); pos += paramType.getSize(); } body.append(Utility.createInvoke(fact, classWeaver.getWorld(), interMethodBody)); Type t = BcelWorld.makeBcelType(interMethodBody.getReturnType()); if (!t.equals(returnType)) { body.append(fact.createCast(t, returnType)); } body.append(InstructionFactory.createReturn(returnType)); mg.definingType = onType; if (world.isInJava5Mode()) { String basicSignature = mangledInterMethod.getSignature(); String genericSignature = ((ResolvedMemberImpl) mangledInterMethod).getSignatureForAttribute(); if (!basicSignature.equals(genericSignature)) { // Add a signature attribute to it mg.addAttribute(createSignatureAttribute(classGen.getConstantPool(), genericSignature)); } } classWeaver.addOrReplaceLazyMethodGen(mg); addNeededSuperCallMethods(classWeaver, onType, munger.getSuperMethodsCalled()); // Work out if we need a bridge method for the new method added to the topmostimplementor. // Check if the munger being processed is a parameterized form of the original munger createBridgeIfNecessary(classWeaver, munger, unMangledInterMethod, classGen); return true; } } else { return false; } } private void createBridgeIfNecessary(BcelClassWeaver classWeaver, NewMethodTypeMunger munger, ResolvedMember unMangledInterMethod, LazyClassGen classGen) { if (munger.getDeclaredSignature() != null) { boolean needsbridging = false; ResolvedMember mungerSignature = munger.getSignature(); ResolvedMember toBridgeTo = munger.getDeclaredSignature().parameterizedWith(null, mungerSignature.getDeclaringType().resolve(getWorld()), false, munger.getTypeVariableAliases()); if (!toBridgeTo.getReturnType().getErasureSignature().equals(mungerSignature.getReturnType().getErasureSignature())) { needsbridging = true; } UnresolvedType[] originalParams = toBridgeTo.getParameterTypes(); UnresolvedType[] newParams = mungerSignature.getParameterTypes(); for (int ii = 0; ii < originalParams.length; ii++) { if (!originalParams[ii].getErasureSignature().equals(newParams[ii].getErasureSignature())) { needsbridging = true; } } if (needsbridging) { createBridge(classWeaver, unMangledInterMethod, classGen, toBridgeTo); } } } private void copyOverParameterAnnotations(LazyMethodGen receiverMethod, ResolvedMember donorMethod) { AnnotationAJ[][] pAnnos = donorMethod.getParameterAnnotations(); if (pAnnos != null) { int offset = receiverMethod.isStatic() ? 0 : 1; int param = 0; for (int i = offset; i < pAnnos.length; i++) { AnnotationAJ[] annosOnParam = pAnnos[i]; if (annosOnParam != null) { for (AnnotationAJ anno : annosOnParam) { receiverMethod.addParameterAnnotation(param, anno); } } param++; } } } private void createBridge(BcelClassWeaver weaver, ResolvedMember unMangledInterMethod, LazyClassGen classGen, ResolvedMember toBridgeTo) { Type[] paramTypes; Type returnType; InstructionList body; InstructionFactory fact; int pos; ResolvedMember bridgerMethod = AjcMemberMaker.bridgerToInterMethod(unMangledInterMethod, classGen.getType()); ResolvedMember bridgingSetter = AjcMemberMaker.interMethodBridger(toBridgeTo, aspectType, false); // pr250493 LazyMethodGen bridgeMethod = makeMethodGen(classGen, bridgingSetter); paramTypes = BcelWorld.makeBcelTypes(bridgingSetter.getParameterTypes()); Type[] bridgingToParms = BcelWorld.makeBcelTypes(unMangledInterMethod.getParameterTypes()); returnType = BcelWorld.makeBcelType(bridgingSetter.getReturnType()); body = bridgeMethod.getBody(); fact = classGen.getFactory(); pos = 0; if (!Modifier.isStatic(bridgingSetter.getModifiers())) { body.append(InstructionFactory.createThis()); pos++; } for (int i = 0, len = paramTypes.length; i < len; i++) { Type paramType = paramTypes[i]; body.append(InstructionFactory.createLoad(paramType, pos)); if (!bridgingSetter.getParameterTypes()[i].getErasureSignature().equals( unMangledInterMethod.getParameterTypes()[i].getErasureSignature())) { // System.err.println("Putting in cast from "+ // paramType+" to "+bridgingToParms[i]); body.append(fact.createCast(paramType, bridgingToParms[i])); } pos += paramType.getSize(); } body.append(Utility.createInvoke(fact, weaver.getWorld(), bridgerMethod)); body.append(InstructionFactory.createReturn(returnType)); classGen.addMethodGen(bridgeMethod); // mg.definingType = onType; } /** * Helper method to create a signature attribute based on a string signature: e.g. "Ljava/lang/Object;LI<Ljava/lang/Double;>;" */ private Signature createSignatureAttribute(ConstantPool cp, String signature) { int nameIndex = cp.addUtf8("Signature"); int sigIndex = cp.addUtf8(signature); return new Signature(nameIndex, 2, sigIndex, cp); } /** * Create any bridge method required because of covariant returns being used. This method is used in the case where an ITD is * applied to some type and it may be in an override relationship with a method from the supertype - but due to covariance there * is a mismatch in return values. Example of when required: Super defines: Object m(String s) Sub defines: String m(String s) * then we need a bridge method in Sub called 'Object m(String s)' that forwards to 'String m(String s)' */ private void createAnyBridgeMethodsForCovariance(BcelClassWeaver weaver, NewMethodTypeMunger munger, ResolvedMember unMangledInterMethod, ResolvedType onType, LazyClassGen gen, Type[] paramTypes) { // PERFORMANCE BOTTLENECK? Might need investigating, method analysis // between types in a hierarchy just seems expensive... // COVARIANCE BRIDGING // Algorithm: Step1. Check in this type - has someone already created // the bridge method? // Step2. Look above us - do we 'override' a method and yet differ in // return type (i.e. covariance) // Step3. Create a forwarding bridge method // ResolvedType superclass = onType.getSuperclass(); boolean quitRightNow = false; String localMethodName = unMangledInterMethod.getName(); String localParameterSig = unMangledInterMethod.getParameterSignature(); String localReturnTypeESig = unMangledInterMethod.getReturnType().getErasureSignature(); // Step1 boolean alreadyDone = false; // Compiler might have done it ResolvedMember[] localMethods = onType.getDeclaredMethods(); for (int i = 0; i < localMethods.length; i++) { ResolvedMember member = localMethods[i]; if (member.getName().equals(localMethodName)) { // Check the params if (member.getParameterSignature().equals(localParameterSig)) { alreadyDone = true; } } } // Step2 if (!alreadyDone) { // Use the iterator form of 'getMethods()' so we do as little work as necessary ResolvedType supertype = onType.getSuperclass(); if (supertype != null) { for (Iterator<ResolvedMember> iter = supertype.getMethods(true, true); iter.hasNext() && !quitRightNow;) { ResolvedMember aMethod = iter.next(); if (aMethod.getName().equals(localMethodName) && aMethod.getParameterSignature().equals(localParameterSig)) { // check the return types, if they are different we need a // bridging method. if (!aMethod.getReturnType().getErasureSignature().equals(localReturnTypeESig) && !Modifier.isPrivate(aMethod.getModifiers())) { // Step3 createBridgeMethod(weaver.getWorld(), munger, unMangledInterMethod, gen, paramTypes, aMethod); quitRightNow = true; } } } } } } /** * Create a bridge method for a particular munger. * * @param world * @param munger * @param unMangledInterMethod the method to bridge 'to' that we have already created in the 'subtype' * @param clazz the class in which to put the bridge method * @param paramTypes Parameter types for the bridge method, passed in as an optimization since the caller is likely to have * already created them. * @param theBridgeMethod */ private void createBridgeMethod(BcelWorld world, NewMethodTypeMunger munger, ResolvedMember unMangledInterMethod, LazyClassGen clazz, Type[] paramTypes, ResolvedMember theBridgeMethod) { InstructionList body; InstructionFactory fact; int pos = 0; LazyMethodGen bridgeMethod = makeMethodGen(clazz, theBridgeMethod); // The // bridge // method // in // this // type // will // have // the // same // signature // as // the // one // in // the // supertype bridgeMethod.setAccessFlags(bridgeMethod.getAccessFlags() | 0x00000040 /* * BRIDGE = 0x00000040 */); // UnresolvedType[] newParams = // munger.getSignature().getParameterTypes(); Type returnType = BcelWorld.makeBcelType(theBridgeMethod.getReturnType()); body = bridgeMethod.getBody(); fact = clazz.getFactory(); if (!Modifier.isStatic(unMangledInterMethod.getModifiers())) { body.append(InstructionFactory.createThis()); pos++; } for (int i = 0, len = paramTypes.length; i < len; i++) { Type paramType = paramTypes[i]; body.append(InstructionFactory.createLoad(paramType, pos)); // if (!bridgingSetter.getParameterTypes()[i].getErasureSignature(). // equals // (unMangledInterMethod.getParameterTypes()[i].getErasureSignature // ())) { // System.err.println("Putting in cast from "+paramType+" to "+ // bridgingToParms[i]); // body.append(fact.createCast(paramType,bridgingToParms[i])); // } pos += paramType.getSize(); } body.append(Utility.createInvoke(fact, world, unMangledInterMethod)); body.append(InstructionFactory.createReturn(returnType)); clazz.addMethodGen(bridgeMethod); } // Unlike toString() on a member, this does not include the declaring type private String stringifyMember(ResolvedMember member) { StringBuffer buf = new StringBuffer(); buf.append(member.getReturnType().getName()); buf.append(' '); buf.append(member.getName()); if (member.getKind() != Member.FIELD) { buf.append("("); UnresolvedType[] params = member.getParameterTypes(); if (params.length != 0) { buf.append(params[0]); for (int i = 1, len = params.length; i < len; i++) { buf.append(", "); buf.append(params[i].getName()); } } buf.append(")"); } return buf.toString(); } private boolean mungeMethodDelegate(BcelClassWeaver weaver, MethodDelegateTypeMunger munger) { World world = weaver.getWorld(); LazyClassGen gen = weaver.getLazyClassGen(); if (gen.getType().isAnnotation() || gen.getType().isEnum()) { // don't signal error as it could be a consequence of a wild type pattern return false; } ResolvedMember introduced = munger.getSignature(); ResolvedType fromType = world.resolve(introduced.getDeclaringType(), munger.getSourceLocation()); if (fromType.isRawType()) { fromType = fromType.getGenericType(); } boolean shouldApply = munger.matches(weaver.getLazyClassGen().getType(), aspectType); if (shouldApply) { Type bcelReturnType = BcelWorld.makeBcelType(introduced.getReturnType()); // If no implementation class was specified, the intention was that // the types matching the pattern // already implemented the interface, let's check that now! if (munger.getImplClassName() == null && !munger.specifiesDelegateFactoryMethod()) { boolean isOK = false; List<LazyMethodGen> existingMethods = gen.getMethodGens(); for (LazyMethodGen m : existingMethods) { if (m.getName().equals(introduced.getName()) && m.getParameterSignature().equals(introduced.getParameterSignature()) && m.getReturnType().equals(bcelReturnType)) { isOK = true; } } if (!isOK) { // the class does not implement this method, they needed to // supply a default impl class IMessage msg = new Message("@DeclareParents: No defaultImpl was specified but the type '" + gen.getName() + "' does not implement the method '" + stringifyMember(introduced) + "' defined on the interface '" + introduced.getDeclaringType() + "'", weaver.getLazyClassGen().getType().getSourceLocation(), true, new ISourceLocation[] { munger.getSourceLocation() }); weaver.getWorld().getMessageHandler().handleMessage(msg); return false; } return true; } LazyMethodGen mg = new LazyMethodGen(introduced.getModifiers() - Modifier.ABSTRACT, bcelReturnType, introduced.getName(), BcelWorld.makeBcelTypes(introduced.getParameterTypes()), BcelWorld.makeBcelTypesAsClassNames(introduced.getExceptions()), gen); // annotation copy from annotation on ITD interface if (weaver.getWorld().isInJava5Mode()) { AnnotationAJ annotationsOnRealMember[] = null; ResolvedType toLookOn = weaver.getWorld().lookupOrCreateName(introduced.getDeclaringType()); if (fromType.isRawType()) { toLookOn = fromType.getGenericType(); } // lookup the method ResolvedMember[] ms = toLookOn.getDeclaredJavaMethods(); for (ResolvedMember m : ms) { if (introduced.getName().equals(m.getName()) && introduced.getSignature().equals(m.getSignature())) { annotationsOnRealMember = m.getAnnotations(); break; } } if (annotationsOnRealMember != null) { for (AnnotationAJ anno : annotationsOnRealMember) { AnnotationGen a = ((BcelAnnotation) anno).getBcelAnnotation(); AnnotationGen ag = new AnnotationGen(a, weaver.getLazyClassGen().getConstantPool(), true); mg.addAnnotation(new BcelAnnotation(ag, weaver.getWorld())); } } } InstructionList body = new InstructionList(); InstructionFactory fact = gen.getFactory(); // getfield body.append(InstructionConstants.ALOAD_0); body.append(Utility.createGet(fact, munger.getDelegate(weaver.getLazyClassGen().getType()))); InstructionBranch ifNonNull = InstructionFactory.createBranchInstruction(Constants.IFNONNULL, null); body.append(ifNonNull); // Create and store a new instance body.append(InstructionConstants.ALOAD_0); // 'this' is where we'll store the field value // TODO for non-static case, call aspectOf() then call the factory method on the retval // TODO decide whether the value can really be cached // locate the aspect and call the static method in it if (munger.specifiesDelegateFactoryMethod()) { ResolvedMember rm = munger.getDelegateFactoryMethod(weaver.getWorld()); // Check the method parameter is compatible with the type of the instance to be passed if (rm.getArity() != 0) { ResolvedType parameterType = rm.getParameterTypes()[0].resolve(weaver.getWorld()); if (!parameterType.isAssignableFrom(weaver.getLazyClassGen().getType())) { signalError("For mixin factory method '" + rm + "': Instance type '" + weaver.getLazyClassGen().getType() + "' is not compatible with factory parameter type '" + parameterType + "'", weaver); return false; } } if (Modifier.isStatic(rm.getModifiers())) { if (rm.getArity() != 0) { body.append(InstructionConstants.ALOAD_0); } body.append(fact.createInvoke(rm.getDeclaringType().getName(), rm.getName(), rm.getSignature(), Constants.INVOKESTATIC)); body.append(Utility.createSet(fact, munger.getDelegate(weaver.getLazyClassGen().getType()))); } else { // Need to call aspectOf() to obtain the aspect instance then call the factory method upon that UnresolvedType theAspect = munger.getAspect(); body.append(fact.createInvoke(theAspect.getName(), "aspectOf", "()" + theAspect.getSignature(), Constants.INVOKESTATIC)); if (rm.getArity() != 0) { body.append(InstructionConstants.ALOAD_0); } body.append(fact.createInvoke(rm.getDeclaringType().getName(), rm.getName(), rm.getSignature(), Constants.INVOKEVIRTUAL)); body.append(Utility.createSet(fact, munger.getDelegate(weaver.getLazyClassGen().getType()))); } } else { body.append(fact.createNew(munger.getImplClassName())); body.append(InstructionConstants.DUP); body.append(fact.createInvoke(munger.getImplClassName(), "<init>", Type.VOID, Type.NO_ARGS, Constants.INVOKESPECIAL)); body.append(Utility.createSet(fact, munger.getDelegate(weaver.getLazyClassGen().getType()))); } // if not null use the instance we've got InstructionHandle ifNonNullElse = body.append(InstructionConstants.ALOAD_0); ifNonNull.setTarget(ifNonNullElse); body.append(Utility.createGet(fact, munger.getDelegate(weaver.getLazyClassGen().getType()))); // args int pos = 0; if (!Modifier.isStatic(introduced.getModifiers())) { // skip 'this' (?? can this really // happen) // body.append(InstructionFactory.createThis()); pos++; } Type[] paramTypes = BcelWorld.makeBcelTypes(introduced.getParameterTypes()); for (int i = 0, len = paramTypes.length; i < len; i++) { Type paramType = paramTypes[i]; body.append(InstructionFactory.createLoad(paramType, pos)); pos += paramType.getSize(); } body.append(Utility.createInvoke(fact, Constants.INVOKEINTERFACE, introduced)); body.append(InstructionFactory.createReturn(bcelReturnType)); mg.getBody().append(body); weaver.addLazyMethodGen(mg); weaver.getLazyClassGen().warnOnAddedMethod(mg.getMethod(), getSignature().getSourceLocation()); return true; } return false; } private boolean mungeFieldHost(BcelClassWeaver weaver, MethodDelegateTypeMunger.FieldHostTypeMunger munger) { LazyClassGen gen = weaver.getLazyClassGen(); if (gen.getType().isAnnotation() || gen.getType().isEnum()) { // don't signal error as it could be a consequence of a wild type // pattern return false; } // boolean shouldApply = munger.matches(weaver.getLazyClassGen().getType(), aspectType); // why // do // this? ResolvedMember host = AjcMemberMaker.itdAtDeclareParentsField(weaver.getLazyClassGen().getType(), munger.getSignature() .getType(), aspectType); FieldGen field = makeFieldGen(weaver.getLazyClassGen(), host); field.setModifiers(field.getModifiers() | BcelField.AccSynthetic); weaver.getLazyClassGen().addField(field, null); return true; } private ResolvedMember getRealMemberForITDFromAspect(ResolvedType aspectType, ResolvedMember lookingFor, boolean isCtorRelated) { World world = aspectType.getWorld(); boolean debug = false; if (debug) { System.err.println("Searching for a member on type: " + aspectType); System.err.println("Member we are looking for: " + lookingFor); } ResolvedMember aspectMethods[] = aspectType.getDeclaredMethods(); UnresolvedType[] lookingForParams = lookingFor.getParameterTypes(); ResolvedMember realMember = null; for (int i = 0; realMember == null && i < aspectMethods.length; i++) { ResolvedMember member = aspectMethods[i]; if (member.getName().equals(lookingFor.getName())) { UnresolvedType[] memberParams = member.getGenericParameterTypes(); if (memberParams.length == lookingForParams.length) { if (debug) { System.err.println("Reviewing potential candidates: " + member); } boolean matchOK = true; // If not related to a ctor ITD then the name is enough to // confirm we have the // right one. If it is ctor related we need to check the // params all match, although // only the erasure. if (isCtorRelated) { for (int j = 0; j < memberParams.length && matchOK; j++) { ResolvedType pMember = memberParams[j].resolve(world); ResolvedType pLookingFor = lookingForParams[j].resolve(world); if (pMember.isTypeVariableReference()) { pMember = ((TypeVariableReference) pMember).getTypeVariable().getFirstBound().resolve(world); } if (pMember.isParameterizedType() || pMember.isGenericType()) { pMember = pMember.getRawType().resolve(aspectType.getWorld()); } if (pLookingFor.isTypeVariableReference()) { pLookingFor = ((TypeVariableReference) pLookingFor).getTypeVariable().getFirstBound() .resolve(world); } if (pLookingFor.isParameterizedType() || pLookingFor.isGenericType()) { pLookingFor = pLookingFor.getRawType().resolve(world); } if (debug) { System.err.println("Comparing parameter " + j + " member=" + pMember + " lookingFor=" + pLookingFor); } if (!pMember.equals(pLookingFor)) { matchOK = false; } } } if (matchOK) { realMember = member; } } } } if (debug && realMember == null) { System.err.println("Didn't find a match"); } return realMember; } private void addNeededSuperCallMethods(BcelClassWeaver weaver, ResolvedType onType, Set<ResolvedMember> neededSuperCalls) { LazyClassGen gen = weaver.getLazyClassGen(); for (Iterator<ResolvedMember> iter = neededSuperCalls.iterator(); iter.hasNext();) { ResolvedMember superMethod = iter.next(); if (weaver.addDispatchTarget(superMethod)) { // System.err.println("super type: " + // superMethod.getDeclaringType() + ", " + gen.getType()); boolean isSuper = !superMethod.getDeclaringType().equals(gen.getType()); String dispatchName; if (isSuper) { dispatchName = NameMangler.superDispatchMethod(onType, superMethod.getName()); } else { dispatchName = NameMangler.protectedDispatchMethod(onType, superMethod.getName()); } superMethod = superMethod.resolve(weaver.getWorld()); LazyMethodGen dispatcher = makeDispatcher(gen, dispatchName, superMethod, weaver.getWorld(), isSuper); weaver.addLazyMethodGen(dispatcher); } } } private void signalError(String msgid, BcelClassWeaver weaver, UnresolvedType onType) { IMessage msg = MessageUtil.error(WeaverMessages.format(msgid, onType.getName()), getSourceLocation()); weaver.getWorld().getMessageHandler().handleMessage(msg); } // private void signalWarning(String msgString, BcelClassWeaver weaver) { // IMessage msg = MessageUtil.warn(msgString, getSourceLocation()); // weaver.getWorld().getMessageHandler().handleMessage(msg); // } private void signalError(String msgString, BcelClassWeaver weaver) { IMessage msg = MessageUtil.error(msgString, getSourceLocation()); weaver.getWorld().getMessageHandler().handleMessage(msg); } private boolean mungeNewConstructor(BcelClassWeaver weaver, NewConstructorTypeMunger newConstructorTypeMunger) { final LazyClassGen currentClass = weaver.getLazyClassGen(); final InstructionFactory fact = currentClass.getFactory(); ResolvedMember newConstructorMember = newConstructorTypeMunger.getSyntheticConstructor(); ResolvedType onType = newConstructorMember.getDeclaringType().resolve(weaver.getWorld()); if (onType.isRawType()) { onType = onType.getGenericType(); } if (onType.isAnnotation()) { signalError(WeaverMessages.ITDC_ON_ANNOTATION_NOT_ALLOWED, weaver, onType); return false; } if (onType.isEnum()) { signalError(WeaverMessages.ITDC_ON_ENUM_NOT_ALLOWED, weaver, onType); return false; } if (!onType.equals(currentClass.getType())) { return false; } ResolvedMember explicitConstructor = newConstructorTypeMunger.getExplicitConstructor(); // int declaredParameterCount = // newConstructorTypeMunger.getDeclaredParameterCount(); LazyMethodGen mg = makeMethodGen(currentClass, newConstructorMember); mg.setEffectiveSignature(newConstructorTypeMunger.getSignature(), Shadow.ConstructorExecution, true); // pr98901 // For copying the annotations across, we have to discover the real // member in the aspect // which is holding them. if (weaver.getWorld().isInJava5Mode()) { ResolvedMember interMethodDispatcher = AjcMemberMaker.postIntroducedConstructor(aspectType, onType, newConstructorTypeMunger.getSignature().getParameterTypes()); AnnotationAJ annotationsOnRealMember[] = null; ResolvedMember realMember = getRealMemberForITDFromAspect(aspectType, interMethodDispatcher, true); // 266602 - consider it missing to mean that the corresponding aspect had errors if (realMember == null) { // signalWarning("Unable to apply any annotations attached to " + munger.getSignature(), weaver); // throw new BCException("Couldn't find ITD init member '" + interMethodBody + "' on aspect " + aspectType); } else { annotationsOnRealMember = realMember.getAnnotations(); } if (annotationsOnRealMember != null) { for (int i = 0; i < annotationsOnRealMember.length; i++) { AnnotationAJ annotationX = annotationsOnRealMember[i]; AnnotationGen a = ((BcelAnnotation) annotationX).getBcelAnnotation(); AnnotationGen ag = new AnnotationGen(a, weaver.getLazyClassGen().getConstantPool(), true); mg.addAnnotation(new BcelAnnotation(ag, weaver.getWorld())); } } // the below loop fixes the very special (and very stupid) // case where an aspect declares an annotation // on an ITD it declared on itself. List<DeclareAnnotation> allDecams = weaver.getWorld().getDeclareAnnotationOnMethods(); for (Iterator<DeclareAnnotation> i = allDecams.iterator(); i.hasNext();) { DeclareAnnotation decaMC = i.next(); if (decaMC.matches(explicitConstructor, weaver.getWorld()) && mg.getEnclosingClass().getType() == aspectType) { mg.addAnnotation(decaMC.getAnnotation()); } } } // Might have to remove the default constructor - b275032 // TODO could have tagged the type munger when the fact we needed to do this was detected earlier if (mg.getArgumentTypes().length == 0) { LazyMethodGen toRemove = null; for (LazyMethodGen object : currentClass.getMethodGens()) { if (object.getName().equals("<init>") && object.getArgumentTypes().length == 0) { toRemove = object; } } if (toRemove != null) { currentClass.removeMethodGen(toRemove); } } currentClass.addMethodGen(mg); // weaver.addLazyMethodGen(freshConstructor); InstructionList body = mg.getBody(); // add to body: push arts for call to pre, from actual args starting at // 1 (skipping this), going to // declared argcount + 1 UnresolvedType[] declaredParams = newConstructorTypeMunger.getSignature().getParameterTypes(); Type[] paramTypes = mg.getArgumentTypes(); int frameIndex = 1; for (int i = 0, len = declaredParams.length; i < len; i++) { body.append(InstructionFactory.createLoad(paramTypes[i], frameIndex)); frameIndex += paramTypes[i].getSize(); } // do call to pre Member preMethod = AjcMemberMaker.preIntroducedConstructor(aspectType, onType, declaredParams); body.append(Utility.createInvoke(fact, null, preMethod)); // create a local, and store return pre stuff into it. int arraySlot = mg.allocateLocal(1); body.append(InstructionFactory.createStore(Type.OBJECT, arraySlot)); // put this on the stack body.append(InstructionConstants.ALOAD_0); // unpack pre args onto stack UnresolvedType[] superParamTypes = explicitConstructor.getParameterTypes(); for (int i = 0, len = superParamTypes.length; i < len; i++) { body.append(InstructionFactory.createLoad(Type.OBJECT, arraySlot)); body.append(Utility.createConstant(fact, i)); body.append(InstructionFactory.createArrayLoad(Type.OBJECT)); body.append(Utility.createConversion(fact, Type.OBJECT, BcelWorld.makeBcelType(superParamTypes[i]))); } // call super/this body.append(Utility.createInvoke(fact, null, explicitConstructor)); // put this back on the stack body.append(InstructionConstants.ALOAD_0); // unpack params onto stack Member postMethod = AjcMemberMaker.postIntroducedConstructor(aspectType, onType, declaredParams); UnresolvedType[] postParamTypes = postMethod.getParameterTypes(); for (int i = 1, len = postParamTypes.length; i < len; i++) { body.append(InstructionFactory.createLoad(Type.OBJECT, arraySlot)); body.append(Utility.createConstant(fact, superParamTypes.length + i - 1)); body.append(InstructionFactory.createArrayLoad(Type.OBJECT)); body.append(Utility.createConversion(fact, Type.OBJECT, BcelWorld.makeBcelType(postParamTypes[i]))); } // call post body.append(Utility.createInvoke(fact, null, postMethod)); // don't forget to return!! body.append(InstructionConstants.RETURN); return true; } private static LazyMethodGen makeDispatcher(LazyClassGen onGen, String dispatchName, ResolvedMember superMethod, BcelWorld world, boolean isSuper) { Type[] paramTypes = BcelWorld.makeBcelTypes(superMethod.getParameterTypes()); Type returnType = BcelWorld.makeBcelType(superMethod.getReturnType()); int modifiers = Modifier.PUBLIC; if (onGen.isInterface()) { modifiers |= Modifier.ABSTRACT; } LazyMethodGen mg = new LazyMethodGen(modifiers, returnType, dispatchName, paramTypes, UnresolvedType.getNames(superMethod .getExceptions()), onGen); InstructionList body = mg.getBody(); if (onGen.isInterface()) { return mg; } // assert (!superMethod.isStatic()) InstructionFactory fact = onGen.getFactory(); int pos = 0; body.append(InstructionFactory.createThis()); pos++; for (int i = 0, len = paramTypes.length; i < len; i++) { Type paramType = paramTypes[i]; body.append(InstructionFactory.createLoad(paramType, pos)); pos += paramType.getSize(); } if (isSuper) { body.append(Utility.createSuperInvoke(fact, world, superMethod)); } else { body.append(Utility.createInvoke(fact, world, superMethod)); } body.append(InstructionFactory.createReturn(returnType)); return mg; } private boolean mungeNewField(BcelClassWeaver weaver, NewFieldTypeMunger munger) { /* ResolvedMember initMethod = */munger.getInitMethod(aspectType); LazyClassGen gen = weaver.getLazyClassGen(); ResolvedMember field = munger.getSignature(); ResolvedType onType = weaver.getWorld().resolve(field.getDeclaringType(), munger.getSourceLocation()); if (onType.isRawType()) { onType = onType.getGenericType(); } boolean onInterface = onType.isInterface(); if (onType.isAnnotation()) { signalError(WeaverMessages.ITDF_ON_ANNOTATION_NOT_ALLOWED, weaver, onType); return false; } if (onType.isEnum()) { signalError(WeaverMessages.ITDF_ON_ENUM_NOT_ALLOWED, weaver, onType); return false; } ResolvedMember interMethodBody = munger.getInitMethod(aspectType); AnnotationAJ annotationsOnRealMember[] = null; // pr98901 // For copying the annotations across, we have to discover the real // member in the aspect // which is holding them. if (weaver.getWorld().isInJava5Mode()) { // the below line just gets the method with the same name in // aspectType.getDeclaredMethods(); ResolvedType toLookOn = aspectType; if (aspectType.isRawType()) { toLookOn = aspectType.getGenericType(); } ResolvedMember realMember = getRealMemberForITDFromAspect(toLookOn, interMethodBody, false); if (realMember == null) { // signalWarning("Unable to apply any annotations attached to " + munger.getSignature(), weaver); // throw new BCException("Couldn't find ITD init member '" + interMethodBody + "' on aspect " + aspectType); } else { annotationsOnRealMember = realMember.getAnnotations(); } } if (onType.equals(gen.getType())) { if (onInterface) { ResolvedMember itdfieldGetter = AjcMemberMaker.interFieldInterfaceGetter(field, onType, aspectType); LazyMethodGen mg = makeMethodGen(gen, itdfieldGetter); gen.addMethodGen(mg); LazyMethodGen mg1 = makeMethodGen(gen, AjcMemberMaker.interFieldInterfaceSetter(field, onType, aspectType)); gen.addMethodGen(mg1); } else { weaver.addInitializer(this); ResolvedMember newField = AjcMemberMaker.interFieldClassField(field, aspectType, munger.version == NewFieldTypeMunger.VersionTwo); FieldGen fg = makeFieldGen(gen, newField); if (annotationsOnRealMember != null) { for (int i = 0; i < annotationsOnRealMember.length; i++) { AnnotationAJ annotationX = annotationsOnRealMember[i]; AnnotationGen a = ((BcelAnnotation) annotationX).getBcelAnnotation(); AnnotationGen ag = new AnnotationGen(a, weaver.getLazyClassGen().getConstantPool(), true); fg.addAnnotation(ag); } } if (weaver.getWorld().isInJava5Mode()) { String basicSignature = field.getSignature(); String genericSignature = field.getReturnType().resolve(weaver.getWorld()).getSignatureForAttribute(); // String genericSignature = // ((ResolvedMemberImpl)field).getSignatureForAttribute(); if (!basicSignature.equals(genericSignature)) { // Add a signature attribute to it fg.addAttribute(createSignatureAttribute(gen.getConstantPool(), genericSignature)); } } gen.addField(fg, getSourceLocation()); } return true; } else if (onInterface && gen.getType().isTopmostImplementor(onType)) { // wew know that we can't be static since we don't allow statics on // interfaces if (Modifier.isStatic(field.getModifiers())) { throw new RuntimeException("unimplemented"); } weaver.addInitializer(this); // System.err.println("impl body on " + gen.getType() + " for " + // munger); Type fieldType = BcelWorld.makeBcelType(field.getType()); FieldGen fg = makeFieldGen(gen, AjcMemberMaker.interFieldInterfaceField(field, onType, aspectType)); if (annotationsOnRealMember != null) { for (int i = 0; i < annotationsOnRealMember.length; i++) { AnnotationAJ annotationX = annotationsOnRealMember[i]; AnnotationGen a = ((BcelAnnotation) annotationX).getBcelAnnotation(); AnnotationGen ag = new AnnotationGen(a, weaver.getLazyClassGen().getConstantPool(), true); fg.addAnnotation(ag); } } gen.addField(fg, getSourceLocation()); // this uses a shadow munger to add init method to constructors // weaver.getShadowMungers().add(makeInitCallShadowMunger(initMethod) // ); ResolvedMember itdfieldGetter = AjcMemberMaker.interFieldInterfaceGetter(field, gen.getType()/* onType */, aspectType); LazyMethodGen mg = makeMethodGen(gen, itdfieldGetter); InstructionList il = new InstructionList(); InstructionFactory fact = gen.getFactory(); if (Modifier.isStatic(field.getModifiers())) { il.append(fact.createFieldAccess(gen.getClassName(), fg.getName(), fieldType, Constants.GETSTATIC)); } else { il.append(InstructionConstants.ALOAD_0); il.append(fact.createFieldAccess(gen.getClassName(), fg.getName(), fieldType, Constants.GETFIELD)); } il.append(InstructionFactory.createReturn(fieldType)); mg.getBody().insert(il); gen.addMethodGen(mg); // Check if we need bridge methods for the field getter and setter if (munger.getDeclaredSignature() != null) { // is this munger a // parameterized // form of some // original munger? ResolvedMember toBridgeTo = munger.getDeclaredSignature().parameterizedWith(null, munger.getSignature().getDeclaringType().resolve(getWorld()), false, munger.getTypeVariableAliases()); boolean needsbridging = false; if (!toBridgeTo.getReturnType().getErasureSignature() .equals(munger.getSignature().getReturnType().getErasureSignature())) { needsbridging = true; } if (needsbridging) { ResolvedMember bridgingGetter = AjcMemberMaker.interFieldInterfaceGetter(toBridgeTo, gen.getType(), aspectType); createBridgeMethodForITDF(weaver, gen, itdfieldGetter, bridgingGetter); } } ResolvedMember itdfieldSetter = AjcMemberMaker.interFieldInterfaceSetter(field, gen.getType(), aspectType); LazyMethodGen mg1 = makeMethodGen(gen, itdfieldSetter); InstructionList il1 = new InstructionList(); if (Modifier.isStatic(field.getModifiers())) { il1.append(InstructionFactory.createLoad(fieldType, 0)); il1.append(fact.createFieldAccess(gen.getClassName(), fg.getName(), fieldType, Constants.PUTSTATIC)); } else { il1.append(InstructionConstants.ALOAD_0); il1.append(InstructionFactory.createLoad(fieldType, 1)); il1.append(fact.createFieldAccess(gen.getClassName(), fg.getName(), fieldType, Constants.PUTFIELD)); } il1.append(InstructionFactory.createReturn(Type.VOID)); mg1.getBody().insert(il1); gen.addMethodGen(mg1); if (munger.getDeclaredSignature() != null) { ResolvedMember toBridgeTo = munger.getDeclaredSignature().parameterizedWith(null, munger.getSignature().getDeclaringType().resolve(getWorld()), false, munger.getTypeVariableAliases()); boolean needsbridging = false; if (!toBridgeTo.getReturnType().getErasureSignature() .equals(munger.getSignature().getReturnType().getErasureSignature())) { needsbridging = true; } if (needsbridging) { ResolvedMember bridgingSetter = AjcMemberMaker.interFieldInterfaceSetter(toBridgeTo, gen.getType(), aspectType); createBridgeMethodForITDF(weaver, gen, itdfieldSetter, bridgingSetter); } } return true; } else { return false; } } // FIXME asc combine with other createBridge.. method in this class, avoid // the duplication... private void createBridgeMethodForITDF(BcelClassWeaver weaver, LazyClassGen gen, ResolvedMember itdfieldSetter, ResolvedMember bridgingSetter) { InstructionFactory fact; LazyMethodGen bridgeMethod = makeMethodGen(gen, bridgingSetter); bridgeMethod.setAccessFlags(bridgeMethod.getAccessFlags() | 0x00000040); // BRIDGE = 0x00000040 Type[] paramTypes = BcelWorld.makeBcelTypes(bridgingSetter.getParameterTypes()); Type[] bridgingToParms = BcelWorld.makeBcelTypes(itdfieldSetter.getParameterTypes()); Type returnType = BcelWorld.makeBcelType(bridgingSetter.getReturnType()); InstructionList body = bridgeMethod.getBody(); fact = gen.getFactory(); int pos = 0; if (!Modifier.isStatic(bridgingSetter.getModifiers())) { body.append(InstructionFactory.createThis()); pos++; } for (int i = 0, len = paramTypes.length; i < len; i++) { Type paramType = paramTypes[i]; body.append(InstructionFactory.createLoad(paramType, pos)); if (!bridgingSetter.getParameterTypes()[i].getErasureSignature().equals( itdfieldSetter.getParameterTypes()[i].getErasureSignature())) { body.append(fact.createCast(paramType, bridgingToParms[i])); } pos += paramType.getSize(); } body.append(Utility.createInvoke(fact, weaver.getWorld(), itdfieldSetter)); body.append(InstructionFactory.createReturn(returnType)); gen.addMethodGen(bridgeMethod); } @Override public ConcreteTypeMunger parameterizedFor(ResolvedType target) { return new BcelTypeMunger(munger.parameterizedFor(target), aspectType); } @Override public ConcreteTypeMunger parameterizeWith(Map<String, UnresolvedType> m, World w) { return new BcelTypeMunger(munger.parameterizeWith(m, w), aspectType); } /** * Returns a list of type variable aliases used in this munger. For example, if the ITD is 'int I<A,B>.m(List<A> las,List<B> * lbs) {}' then this returns a list containing the strings "A" and "B". */ public List<String> getTypeVariableAliases() { return munger.getTypeVariableAliases(); } @Override public boolean equals(Object other) { if (!(other instanceof BcelTypeMunger)) { return false; } BcelTypeMunger o = (BcelTypeMunger) other; return ((o.getMunger() == null) ? (getMunger() == null) : o.getMunger().equals(getMunger())) && ((o.getAspectType() == null) ? (getAspectType() == null) : o.getAspectType().equals(getAspectType())); // && (AsmManager.getDefault().getHandleProvider().dependsOnLocation() ? ((o.getSourceLocation() == null) ? // (getSourceLocation() == null) // : o.getSourceLocation().equals(getSourceLocation())) // : true); // pr134471 - remove when handles are improved // to be independent of location } private volatile int hashCode = 0; @Override public int hashCode() { if (hashCode == 0) { int result = 17; result = 37 * result + ((getMunger() == null) ? 0 : getMunger().hashCode()); result = 37 * result + ((getAspectType() == null) ? 0 : getAspectType().hashCode()); hashCode = result; } return hashCode; } }
384,189
Bug 384189 make ajcore file creation optional
Although cores are useful, there may be situations where you are working around whatever they are reporting and are perhaps unable to pick up a later version of AJ that includes the fix. In these situations it might be helpful to make the creation of cores optional, through a sys prop.
resolved fixed
5d0e186
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2012-07-03T20:46:29Z"
"2012-07-03T18:26:40Z"
org.aspectj.matcher/src/org/aspectj/weaver/Dump.java
/* ******************************************************************* * Copyright (c) 2004,2010 Contributors * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Eclipse Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Matthew Webster, IBM * ******************************************************************/ package org.aspectj.weaver; import java.io.File; import java.io.FileOutputStream; import java.io.PrintStream; import java.net.URL; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Iterator; import java.util.List; import java.util.Properties; import org.aspectj.bridge.IMessage; import org.aspectj.bridge.IMessageHolder; import org.aspectj.bridge.Version; import org.aspectj.weaver.tools.Trace; import org.aspectj.weaver.tools.TraceFactory; import org.aspectj.weaver.tools.Traceable; /** * @author Matthew Webster */ public class Dump { public final static String DUMP_CONDITION_PROPERTY = "org.aspectj.weaver.Dump.condition"; public final static String DUMP_DIRECTORY_PROPERTY = "org.aspectj.dump.directory"; /* Format for unique filename based on date & time */ private static final String FILENAME_PREFIX = "ajcore"; // private static final DateFormat dateFormat = new SimpleDateFormat("yyyyMMdd"); // private static final DateFormat timeFormat = new SimpleDateFormat("HHmmss.SSS"); private static final String FILENAME_SUFFIX = "txt"; public static final String UNKNOWN_FILENAME = "Unknown"; public static final String DUMP_EXCLUDED = "Excluded"; public static final String NULL_OR_EMPTY = "Empty"; private static Class<?> exceptionClass; private static IMessage.Kind conditionKind = IMessage.ABORT; private static File directory = new File("."); private String reason; private String fileName; private PrintStream print; private static String[] savedCommandLine; private static List<String> savedFullClasspath; private static IMessageHolder savedMessageHolder; // private static Map<INode, WeakReference<INode>> nodes = Collections // .synchronizedMap(new WeakHashMap<INode, WeakReference<INode>>()); private static String lastDumpFileName = UNKNOWN_FILENAME; private static boolean preserveOnNextReset = false; private static Trace trace = TraceFactory.getTraceFactory().getTrace(Dump.class); /** * for testing only, so that we can verify dump contents after compilation has completely finished */ public static void preserveOnNextReset() { preserveOnNextReset = true; } public static void reset() { if (preserveOnNextReset) { preserveOnNextReset = false; return; } else { // nodes.clear(); savedMessageHolder = null; } } /* * Dump methods */ public static String dump(String reason) { String fileName = UNKNOWN_FILENAME; Dump dump = null; try { dump = new Dump(reason); fileName = dump.getFileName(); dump.dumpDefault(); } finally { if (dump != null) { dump.close(); } } return fileName; } public static String dumpWithException(Throwable th) { return dumpWithException(savedMessageHolder, th); } public static String dumpWithException(IMessageHolder messageHolder, Throwable th) { if (trace.isTraceEnabled()) { trace.enter("dumpWithException", null, new Object[] { messageHolder, th }); } String fileName = UNKNOWN_FILENAME; Dump dump = null; try { dump = new Dump(th.getClass().getName()); fileName = dump.getFileName(); dump.dumpException(messageHolder, th); } finally { if (dump != null) { dump.close(); } } if (trace.isTraceEnabled()) { trace.exit("dumpWithException", fileName); } return fileName; } public static String dumpOnExit() { return dumpOnExit(savedMessageHolder, false); } public static String dumpOnExit(IMessageHolder messageHolder, boolean reset) { if (trace.isTraceEnabled()) { trace.enter("dumpOnExit", null, messageHolder); } String fileName = UNKNOWN_FILENAME; if (!shouldDumpOnExit(messageHolder)) { fileName = DUMP_EXCLUDED; } else { Dump dump = null; try { dump = new Dump(conditionKind.toString()); fileName = dump.getFileName(); dump.dumpDefault(messageHolder); } finally { if (dump != null) { dump.close(); } } } if (reset) { messageHolder.clearMessages(); } if (trace.isTraceEnabled()) { trace.exit("dumpOnExit", fileName); } return fileName; } private static boolean shouldDumpOnExit(IMessageHolder messageHolder) { if (trace.isTraceEnabled()) { trace.enter("shouldDumpOnExit", null, messageHolder); } if (trace.isTraceEnabled()) { trace.event("shouldDumpOnExit", null, conditionKind); } boolean result = (messageHolder == null) || messageHolder.hasAnyMessage(conditionKind, true); if (trace.isTraceEnabled()) { trace.exit("shouldDumpOnExit", result); } return result; } /* * Dump configuration */ public static void setDumpOnException(boolean b) { if (b) { exceptionClass = java.lang.Throwable.class; } else { exceptionClass = null; } } public static boolean setDumpDirectory(String directoryName) { if (trace.isTraceEnabled()) { trace.enter("setDumpDirectory", null, directoryName); } boolean success = false; File newDirectory = new File(directoryName); if (newDirectory.exists()) { directory = newDirectory; success = true; } if (trace.isTraceEnabled()) { trace.exit("setDumpDirectory", success); } return success; } public static boolean getDumpOnException() { return (exceptionClass != null); } public static boolean setDumpOnExit(IMessage.Kind condition) { if (trace.isTraceEnabled()) { trace.event("setDumpOnExit", null, condition); } conditionKind = condition; return true; } public static boolean setDumpOnExit(String condition) { for (IMessage.Kind kind : IMessage.KINDS) { if (kind.toString().equals(condition)) { return setDumpOnExit(kind); } } return false; } public static IMessage.Kind getDumpOnExit() { return conditionKind; } public static String getLastDumpFileName() { return lastDumpFileName; } public static void saveCommandLine(String[] args) { savedCommandLine = new String[args.length]; System.arraycopy(args, 0, savedCommandLine, 0, args.length); } public static void saveFullClasspath(List<String> list) { savedFullClasspath = list; } public static void saveMessageHolder(IMessageHolder holder) { savedMessageHolder = holder; } // public static void registerNode(Class<?> module, INode newNode) { // if (trace.isTraceEnabled()) { // trace.enter("registerNode", null, new Object[] { module, newNode }); // } // // // TODO surely this should preserve the module???? it never has.... // nodes.put(newNode, new WeakReference<INode>(newNode)); // // if (trace.isTraceEnabled()) { // trace.exit("registerNode", nodes.size()); // } // } private Dump(String reason) { if (trace.isTraceEnabled()) { trace.enter("<init>", this, reason); } this.reason = reason; openDump(); dumpAspectJProperties(); dumpDumpConfiguration(); if (trace.isTraceEnabled()) { trace.exit("<init>", this); } } public String getFileName() { return fileName; } private void dumpDefault() { dumpDefault(savedMessageHolder); } private void dumpDefault(IMessageHolder holder) { dumpSytemProperties(); dumpCommandLine(); dumpFullClasspath(); dumpCompilerMessages(holder); // dumpNodes(); } // private void dumpNodes() { // // IVisitor dumpVisitor = new IVisitor() { // // public void visitObject(Object obj) { // println(formatObj(obj)); // } // // public void visitList(List list) { // println(list); // } // }; // // Set<INode> keys = nodes.keySet(); // for (INode dumpNode : keys) { // println("---- " + formatObj(dumpNode) + " ----"); // try { // dumpNode.accept(dumpVisitor); // } catch (Exception ex) { // trace.error(formatObj(dumpNode).toString(), ex); // } // } // } private void dumpException(IMessageHolder messageHolder, Throwable th) { println("---- Exception Information ---"); println(th); dumpDefault(messageHolder); } private void dumpAspectJProperties() { println("---- AspectJ Properties ---"); println("AspectJ Compiler " + Version.text + " built on " + Version.time_text); } private void dumpDumpConfiguration() { println("---- Dump Properties ---"); println("Dump file: " + fileName); println("Dump reason: " + reason); println("Dump on exception: " + (exceptionClass != null)); println("Dump at exit condition: " + conditionKind); } private void dumpFullClasspath() { println("---- Full Classpath ---"); if (savedFullClasspath != null && savedFullClasspath.size() > 0) { for (String fileName : savedFullClasspath) { File file = new File(fileName); println(file); } } else { println(NULL_OR_EMPTY); } } private void dumpSytemProperties() { println("---- System Properties ---"); Properties props = System.getProperties(); println(props); } private void dumpCommandLine() { println("---- Command Line ---"); println(savedCommandLine); } private void dumpCompilerMessages(IMessageHolder messageHolder) { println("---- Compiler Messages ---"); if (messageHolder != null) { for (Iterator<IMessage> i = messageHolder.getUnmodifiableListView().iterator(); i.hasNext();) { IMessage message = i.next(); println(message.toString()); } } else { println(NULL_OR_EMPTY); } } /* * Dump output */ private void openDump() { if (print != null) { return; } Date now = new Date(); fileName = FILENAME_PREFIX + "." + new SimpleDateFormat("yyyyMMdd").format(now) + "." + new SimpleDateFormat("HHmmss.SSS").format(now) + "." + FILENAME_SUFFIX; try { File file = new File(directory, fileName); print = new PrintStream(new FileOutputStream(file), true); trace.info("Dumping to " + file.getAbsolutePath()); } catch (Exception ex) { print = System.err; trace.info("Dumping to stderr"); fileName = UNKNOWN_FILENAME; } lastDumpFileName = fileName; } public void close() { print.close(); } private void println(Object obj) { print.println(obj); } private void println(Object[] array) { if (array == null) { println(NULL_OR_EMPTY); return; } for (int i = 0; i < array.length; i++) { print.println(array[i]); } } private void println(Properties props) { Iterator iter = props.keySet().iterator(); while (iter.hasNext()) { String key = (String) iter.next(); String value = props.getProperty(key); print.println(key + "=" + value); } } private void println(Throwable th) { th.printStackTrace(print); } private void println(File file) { print.print(file.getAbsolutePath()); if (!file.exists()) { println("(missing)"); } else if (file.isDirectory()) { int count = file.listFiles().length; println("(" + count + " entries)"); } else { println("(" + file.length() + " bytes)"); } } @SuppressWarnings("rawtypes") private void println(List list) { if (list == null || list.isEmpty()) { println(NULL_OR_EMPTY); } else { for (Iterator i = list.iterator(); i.hasNext();) { Object o = i.next(); if (o instanceof Exception) { println((Exception) o); } else { println(o.toString()); } } } } private static Object formatObj(Object obj) { /* These classes have a safe implementation of toString() */ if (obj == null || obj instanceof String || obj instanceof Number || obj instanceof Boolean || obj instanceof Exception || obj instanceof Character || obj instanceof Class || obj instanceof File || obj instanceof StringBuffer || obj instanceof URL) { return obj; } else { try { /* Classes can provide an alternative implementation of toString() */ if (obj instanceof Traceable) { Traceable t = (Traceable) obj; return t.toTraceString(); } else { return obj.getClass().getName() + "@" + Integer.toHexString(System.identityHashCode(obj)); } /* Object.hashCode() can be override and may thow an exception */ } catch (Exception ex) { return obj.getClass().getName() + "@FFFFFFFF"; } } } static { String exceptionName = System.getProperty("org.aspectj.weaver.Dump.exception", "true"); if (!exceptionName.equals("false")) { setDumpOnException(true); } String conditionName = System.getProperty(DUMP_CONDITION_PROPERTY); if (conditionName != null) { setDumpOnExit(conditionName); } String directoryName = System.getProperty(DUMP_DIRECTORY_PROPERTY); if (directoryName != null) { setDumpDirectory(directoryName); } } public interface INode { public void accept(IVisitor visior); } public interface IVisitor { public void visitObject(Object s); public void visitList(List list); } }
384,398
Bug 384398 Type Mismatch error when using inner classes contained in generic types within ITDs
Please see attached example project. I get the following (strange) compiler error: Type mismatch: cannot convert from A<T>.InnerA<> to A.InnerA BAspect.aj /AspectJInnerclassInGenericTypeBug/src/de/example line 12
resolved fixed
bf949d3
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2012-07-10T17:18:35Z"
"2012-07-05T17:40:00Z"
org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/compiler/lookup/EclipseFactory.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Eclipse Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * PARC initial implementation * Mik Kersten 2004-07-26 extended to allow overloading of * hierarchy builder * ******************************************************************/ package org.aspectj.ajdt.internal.compiler.lookup; import java.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.ast.AspectDeclaration; import org.aspectj.ajdt.internal.compiler.ast.AstUtil; import org.aspectj.ajdt.internal.core.builder.AjBuildManager; import org.aspectj.bridge.IMessage.Kind; import org.aspectj.bridge.ISourceLocation; import org.aspectj.org.eclipse.jdt.core.Flags; import org.aspectj.org.eclipse.jdt.core.compiler.CharOperation; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.ASTNode; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.EmptyStatement; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.TypeDeclaration; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.Wildcard; import org.aspectj.org.eclipse.jdt.internal.compiler.impl.Constant; import org.aspectj.org.eclipse.jdt.internal.compiler.impl.ReferenceContext; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.ArrayBinding; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.Binding; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.FieldBinding; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.LocalTypeBinding; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.LookupEnvironment; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.MethodBinding; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.ParameterizedTypeBinding; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.ProblemReasons; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.ProblemReferenceBinding; 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.SyntheticFieldBinding; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.TypeBinding; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.TypeVariableBinding; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.WildcardBinding; import org.aspectj.weaver.BCException; import org.aspectj.weaver.BoundedReferenceType; import org.aspectj.weaver.ConcreteTypeMunger; import org.aspectj.weaver.IHasPosition; import org.aspectj.weaver.Member; import org.aspectj.weaver.MemberKind; import org.aspectj.weaver.NameMangler; import org.aspectj.weaver.NewFieldTypeMunger; import org.aspectj.weaver.NewMethodTypeMunger; import org.aspectj.weaver.ReferenceType; import org.aspectj.weaver.ResolvedMember; import org.aspectj.weaver.ResolvedMemberImpl; import org.aspectj.weaver.ResolvedType; import org.aspectj.weaver.ResolvedTypeMunger; import org.aspectj.weaver.Shadow; import org.aspectj.weaver.TypeFactory; import org.aspectj.weaver.TypeVariable; import org.aspectj.weaver.TypeVariableDeclaringElement; import org.aspectj.weaver.TypeVariableReference; import org.aspectj.weaver.UnresolvedType; import org.aspectj.weaver.UnresolvedType.TypeKind; import org.aspectj.weaver.UnresolvedTypeVariableReferenceType; import org.aspectj.weaver.WildcardedUnresolvedType; import org.aspectj.weaver.World; import org.aspectj.weaver.patterns.DeclareAnnotation; import org.aspectj.weaver.patterns.DeclareParents; /** * @author Jim Hugunin */ public class EclipseFactory { public static boolean DEBUG = false; public static int debug_mungerCount = -1; private final AjBuildManager buildManager; private final LookupEnvironment lookupEnvironment; private final boolean xSerializableAspects; private final World world; public PushinCollector pushinCollector; public List<ConcreteTypeMunger> finishedTypeMungers = null; // We can get clashes if we don't treat raw types differently - we end up looking // up a raw and getting the generic type (pr115788) private final Map/* UnresolvedType, TypeBinding */typexToBinding = new HashMap(); private final Map/* UnresolvedType, TypeBinding */rawTypeXToBinding = new HashMap(); // XXX currently unused // private Map/*TypeBinding, ResolvedType*/ bindingToResolvedTypeX = new HashMap(); public static EclipseFactory fromLookupEnvironment(LookupEnvironment env) { AjLookupEnvironment aenv = (AjLookupEnvironment) env; return aenv.factory; } public LookupEnvironment getLookupEnvironment() { return this.lookupEnvironment; } public static EclipseFactory fromScopeLookupEnvironment(Scope scope) { return fromLookupEnvironment(AstUtil.getCompilationUnitScope(scope).environment); } public EclipseFactory(LookupEnvironment lookupEnvironment, AjBuildManager buildManager) { this.lookupEnvironment = lookupEnvironment; this.buildManager = buildManager; this.world = buildManager.getWorld(); this.pushinCollector = PushinCollector.createInstance(this.world); this.xSerializableAspects = buildManager.buildConfig.isXserializableAspects(); } public EclipseFactory(LookupEnvironment lookupEnvironment, World world, boolean xSer) { this.lookupEnvironment = lookupEnvironment; this.world = world; this.xSerializableAspects = xSer; this.pushinCollector = PushinCollector.createInstance(this.world); this.buildManager = null; } public World getWorld() { return world; } public void showMessage(Kind kind, String message, ISourceLocation loc1, ISourceLocation loc2) { getWorld().showMessage(kind, message, loc1, loc2); } public ResolvedType fromEclipse(ReferenceBinding binding) { if (binding == null) { return ResolvedType.MISSING; } // ??? this seems terribly inefficient // System.err.println("resolving: " + binding.getClass() + ", name = " + getName(binding)); ResolvedType ret = getWorld().resolve(fromBinding(binding)); // System.err.println(" got: " + ret); return ret; } public ResolvedType fromTypeBindingToRTX(TypeBinding tb) { if (tb == null) { return ResolvedType.MISSING; } ResolvedType ret = getWorld().resolve(fromBinding(tb)); return ret; } public ResolvedType[] fromEclipse(ReferenceBinding[] bindings) { if (bindings == null) { return ResolvedType.NONE; } int len = bindings.length; ResolvedType[] ret = new ResolvedType[len]; for (int i = 0; i < len; i++) { ret[i] = fromEclipse(bindings[i]); } return ret; } public static String getName(TypeBinding binding) { if (binding instanceof TypeVariableBinding) { // The first bound may be null - so default to object? TypeVariableBinding tvb = (TypeVariableBinding) binding; if (tvb.firstBound != null) { return getName(tvb.firstBound); } else { return getName(tvb.superclass); } } if (binding instanceof ReferenceBinding) { return new String(CharOperation.concatWith(((ReferenceBinding) binding).compoundName, '.')); } String packageName = new String(binding.qualifiedPackageName()); String className = new String(binding.qualifiedSourceName()).replace('.', '$'); if (packageName.length() > 0) { className = packageName + "." + className; } // XXX doesn't handle arrays correctly (or primitives?) return new String(className); } /** * Some generics notes: * * Andy 6-May-05 We were having trouble with parameterized types in a couple of places - due to TypeVariableBindings. When we * see a TypeVariableBinding now we default to either the firstBound if it is specified or java.lang.Object. Not sure when/if * this gets us unstuck? It does mean we forget that it is a type variable when going back the other way from the UnresolvedType * and that would seem a bad thing - but I've yet to see the reason we need to remember the type variable. Adrian 10-July-05 * When we forget it's a type variable we come unstuck when getting the declared members of a parameterized type - since we * don't know it's a type variable we can't replace it with the type parameter. */ // ??? going back and forth between strings and bindings is a waste of cycles public UnresolvedType fromBinding(TypeBinding binding) { if (binding instanceof HelperInterfaceBinding) { return ((HelperInterfaceBinding) binding).getTypeX(); } if (binding == null || binding.qualifiedSourceName() == null) { return ResolvedType.MISSING; } // first piece of generics support! if (binding instanceof TypeVariableBinding) { TypeVariableBinding tb = (TypeVariableBinding) binding; UnresolvedTypeVariableReferenceType utvrt = (UnresolvedTypeVariableReferenceType) fromTypeVariableBinding(tb); return utvrt; } // handle arrays since the component type may need special treatment too... if (binding instanceof ArrayBinding) { ArrayBinding aBinding = (ArrayBinding) binding; UnresolvedType componentType = fromBinding(aBinding.leafComponentType); return UnresolvedType.makeArray(componentType, aBinding.dimensions); } if (binding instanceof WildcardBinding) { WildcardBinding eWB = (WildcardBinding) binding; // Repair the bound // e.g. If the bound for the wildcard is a typevariable, e.g. '? extends E' then // the type variable in the unresolvedtype will be correct only in name. In that // case let's set it correctly based on the one in the eclipse WildcardBinding UnresolvedType theBound = null; if (eWB.bound instanceof TypeVariableBinding) { theBound = fromTypeVariableBinding((TypeVariableBinding) eWB.bound); } else { theBound = fromBinding(eWB.bound); } // if (eWB.boundKind == WildCard.SUPER) { // // } WildcardedUnresolvedType theType = (WildcardedUnresolvedType) TypeFactory.createTypeFromSignature(CharOperation .charToString(eWB.genericTypeSignature())); // if (theType.isGenericWildcard() && theType.isSuper()) theType.setLowerBound(theBound); // if (theType.isGenericWildcard() && theType.isExtends()) theType.setUpperBound(theBound); return theType; } if (binding instanceof ParameterizedTypeBinding) { if (binding instanceof RawTypeBinding) { // special case where no parameters are specified! return UnresolvedType.forRawTypeName(getName(binding)); } ParameterizedTypeBinding ptb = (ParameterizedTypeBinding) binding; UnresolvedType[] arguments = null; if (ptb.arguments != null) { // null can mean this is an inner type of a Parameterized Type with no bounds of its own // (pr100227) arguments = new UnresolvedType[ptb.arguments.length]; for (int i = 0; i < arguments.length; i++) { arguments[i] = fromBinding(ptb.arguments[i]); } } String baseTypeSignature = null; ResolvedType baseType = getWorld().resolve(UnresolvedType.forName(getName(binding)), true); if (!baseType.isMissing()) { // can legitimately be missing if a bound refers to a type we haven't added to the world yet... // pr168044 - sometimes (whilst resolving types) we are working with 'half finished' types and so (for example) the // underlying generic type for a raw type hasnt been set yet // if (!baseType.isGenericType() && arguments!=null) baseType = baseType.getGenericType(); baseTypeSignature = baseType.getErasureSignature(); } else { baseTypeSignature = UnresolvedType.forName(getName(binding)).getSignature(); } // Create an unresolved parameterized type. We can't create a resolved one as the // act of resolution here may cause recursion problems since the parameters may // be type variables that we haven't fixed up yet. if (arguments == null) { arguments = new UnresolvedType[0]; } // StringBuffer parameterizedSig = new StringBuffer(); // parameterizedSig.append(ResolvedType.PARAMETERIZED_TYPE_IDENTIFIER); // // // String parameterizedSig = new // StringBuffer().append(ResolvedType.PARAMETERIZED_TYPE_IDENTIFIER).append(CharOperation // .charToString(binding.genericTypeSignature()).substring(1)).toString(); // return TypeFactory.createUnresolvedParameterizedType(parameterizedSig,baseTypeSignature,arguments); return TypeFactory.createUnresolvedParameterizedType(baseTypeSignature, arguments); } // Convert the source type binding for a generic type into a generic UnresolvedType // notice we can easily determine the type variables from the eclipse object // and we can recover the generic signature from it too - so we pass those // to the forGenericType() method. if (binding.isGenericType() && !binding.isParameterizedType() && !binding.isRawType()) { TypeVariableBinding[] tvbs = binding.typeVariables(); TypeVariable[] tVars = new TypeVariable[tvbs.length]; for (int i = 0; i < tvbs.length; i++) { TypeVariableBinding eclipseV = tvbs[i]; tVars[i] = ((TypeVariableReference) fromTypeVariableBinding(eclipseV)).getTypeVariable(); } // TODO asc generics - temporary guard.... if (!(binding instanceof SourceTypeBinding)) { throw new RuntimeException("Cant get the generic sig for " + binding.debugName()); } return UnresolvedType.forGenericType(getName(binding), tVars, CharOperation.charToString(((SourceTypeBinding) binding).genericSignature())); } // LocalTypeBinding have a name $Local$, we can get the real name by using the signature.... if (binding instanceof LocalTypeBinding) { LocalTypeBinding ltb = (LocalTypeBinding) binding; if (ltb.constantPoolName() != null && ltb.constantPoolName().length > 0) { return UnresolvedType.forSignature(new String(binding.signature())); } else { // we're reporting a problem and don't have a resolved name for an // anonymous local type yet, report the issue on the enclosing type return UnresolvedType.forSignature(new String(ltb.enclosingType.signature())); } } // was: UnresolvedType.forName(getName(binding)); UnresolvedType ut = UnresolvedType.forSignature(new String(binding.signature())); return ut; } /** * Some type variables refer to themselves recursively, this enables us to avoid recursion problems. */ private static Map typeVariableBindingsInProgress = new HashMap(); /** * Convert from the eclipse form of type variable (TypeVariableBinding) to the AspectJ form (TypeVariable). */ private UnresolvedType fromTypeVariableBinding(TypeVariableBinding aTypeVariableBinding) { // first, check for recursive call to this method for the same tvBinding if (typeVariableBindingsInProgress.containsKey(aTypeVariableBinding)) { return (UnresolvedType) typeVariableBindingsInProgress.get(aTypeVariableBinding); } // Check if its a type variable binding that we need to recover to an alias... if (typeVariablesForAliasRecovery != null) { String aliasname = (String) typeVariablesForAliasRecovery.get(aTypeVariableBinding); if (aliasname != null) { UnresolvedTypeVariableReferenceType ret = new UnresolvedTypeVariableReferenceType(); ret.setTypeVariable(new TypeVariable(aliasname)); return ret; } } if (typeVariablesForThisMember.containsKey(new String(aTypeVariableBinding.sourceName))) { return (UnresolvedType) typeVariablesForThisMember.get(new String(aTypeVariableBinding.sourceName)); } // Create the UnresolvedTypeVariableReferenceType for the type variable String name = CharOperation.charToString(aTypeVariableBinding.sourceName()); UnresolvedTypeVariableReferenceType ret = new UnresolvedTypeVariableReferenceType(); typeVariableBindingsInProgress.put(aTypeVariableBinding, ret); TypeVariable tv = new TypeVariable(name); ret.setTypeVariable(tv); // Dont set any bounds here, you'll get in a recursive mess // TODO -- what about lower bounds?? UnresolvedType superclassType = fromBinding(aTypeVariableBinding.superclass()); UnresolvedType[] superinterfaces = null; if (aTypeVariableBinding == null || aTypeVariableBinding.superInterfaces == null) { // sign of another bug that will be reported elsewhere superinterfaces = UnresolvedType.NONE; } else { superinterfaces = new UnresolvedType[aTypeVariableBinding.superInterfaces.length]; for (int i = 0; i < superinterfaces.length; i++) { superinterfaces[i] = fromBinding(aTypeVariableBinding.superInterfaces[i]); } } tv.setSuperclass(superclassType); tv.setAdditionalInterfaceBounds(superinterfaces); tv.setRank(aTypeVariableBinding.rank); if (aTypeVariableBinding.declaringElement instanceof MethodBinding) { tv.setDeclaringElementKind(TypeVariable.METHOD); // tv.setDeclaringElement(fromBinding((MethodBinding)aTypeVariableBinding.declaringElement); } else { tv.setDeclaringElementKind(TypeVariable.TYPE); // // tv.setDeclaringElement(fromBinding(aTypeVariableBinding.declaringElement)); } if (aTypeVariableBinding.declaringElement instanceof MethodBinding) { typeVariablesForThisMember.put(new String(aTypeVariableBinding.sourceName), ret); } typeVariableBindingsInProgress.remove(aTypeVariableBinding); return ret; } public UnresolvedType[] fromBindings(TypeBinding[] bindings) { if (bindings == null) { return UnresolvedType.NONE; } int len = bindings.length; UnresolvedType[] ret = new UnresolvedType[len]; for (int i = 0; i < len; i++) { ret[i] = fromBinding(bindings[i]); } return ret; } public static ASTNode astForLocation(IHasPosition location) { return new EmptyStatement(location.getStart(), location.getEnd()); } public List<DeclareParents> getDeclareParents() { return getWorld().getDeclareParents(); } public List<DeclareAnnotation> getDeclareAnnotationOnTypes() { return getWorld().getDeclareAnnotationOnTypes(); } public List<DeclareAnnotation> getDeclareAnnotationOnFields() { return getWorld().getDeclareAnnotationOnFields(); } public List<DeclareAnnotation> getDeclareAnnotationOnMethods() { return getWorld().getDeclareAnnotationOnMethods(); } public boolean areTypeMungersFinished() { return finishedTypeMungers != null; } public void finishTypeMungers() { // make sure that type mungers are List<ConcreteTypeMunger> ret = new ArrayList<ConcreteTypeMunger>(); List<ConcreteTypeMunger> baseTypeMungers = getWorld().getCrosscuttingMembersSet().getTypeMungers(); // XXX by Andy: why do we mix up the mungers here? it means later we know about two sets // and the late ones are a subset of the complete set? (see pr114436) // XXX by Andy removed this line finally, see pr141956 // baseTypeMungers.addAll(getWorld().getCrosscuttingMembersSet().getLateTypeMungers()); debug_mungerCount = baseTypeMungers.size(); for (ConcreteTypeMunger munger : baseTypeMungers) { EclipseTypeMunger etm = makeEclipseTypeMunger(munger); if (etm != null) { if (munger.getMunger().getKind() == ResolvedTypeMunger.InnerClass) { ret.add(0, etm); } else { ret.add(etm); } } } finishedTypeMungers = ret; } public EclipseTypeMunger makeEclipseTypeMunger(ConcreteTypeMunger concrete) { // System.err.println("make munger: " + concrete); // !!! can't do this if we want incremental to work right // if (concrete instanceof EclipseTypeMunger) return (EclipseTypeMunger)concrete; // System.err.println(" was not eclipse"); if (concrete.getMunger() != null && EclipseTypeMunger.supportsKind(concrete.getMunger().getKind())) { AbstractMethodDeclaration method = null; if (concrete instanceof EclipseTypeMunger) { method = ((EclipseTypeMunger) concrete).getSourceMethod(); } EclipseTypeMunger ret = new EclipseTypeMunger(this, concrete.getMunger(), concrete.getAspectType(), method); if (ret.getSourceLocation() == null) { ret.setSourceLocation(concrete.getSourceLocation()); } return ret; } else { return null; } } public List<ConcreteTypeMunger> getTypeMungers() { // ??? assert finishedTypeMungers != null return finishedTypeMungers; } public ResolvedMemberImpl makeResolvedMember(MethodBinding binding) { return makeResolvedMember(binding, binding.declaringClass); } public ResolvedMemberImpl makeResolvedMember(MethodBinding binding, Shadow.Kind shadowKind) { MemberKind memberKind = binding.isConstructor() ? Member.CONSTRUCTOR : Member.METHOD; if (shadowKind == Shadow.AdviceExecution) { memberKind = Member.ADVICE; } return makeResolvedMember(binding, binding.declaringClass, memberKind); } /** * Conversion from a methodbinding (eclipse) to a resolvedmember (aspectj) is now done in the scope of some type variables. * Before converting the parts of a methodbinding (params, return type) we store the type variables in this structure, then * should any component of the method binding refer to them, we grab them from the map. */ private final Map typeVariablesForThisMember = new HashMap(); /** * This is a map from typevariablebindings (eclipsey things) to the names the user originally specified in their ITD. For * example if the target is 'interface I<N extends Number> {}' and the ITD was 'public void I<X>.m(List<X> lxs) {}' then this * map would contain a pointer from the eclipse type 'N extends Number' to the letter 'X'. */ private Map typeVariablesForAliasRecovery; /** * Construct a resolvedmember from a methodbinding. The supplied map tells us about any typevariablebindings that replaced * typevariables whilst the compiler was resolving types - this only happens if it is a generic itd that shares type variables * with its target type. */ public ResolvedMemberImpl makeResolvedMemberForITD(MethodBinding binding, TypeBinding declaringType, Map /* * TypeVariableBinding > * original alias name */recoveryAliases) { ResolvedMemberImpl result = null; try { typeVariablesForAliasRecovery = recoveryAliases; result = makeResolvedMember(binding, declaringType); } finally { typeVariablesForAliasRecovery = null; } return result; } public ResolvedMemberImpl makeResolvedMember(MethodBinding binding, TypeBinding declaringType) { return makeResolvedMember(binding, declaringType, binding.isConstructor() ? Member.CONSTRUCTOR : Member.METHOD); } public ResolvedMemberImpl makeResolvedMember(MethodBinding binding, TypeBinding declaringType, MemberKind memberKind) { // System.err.println("member for: " + binding + ", " + new String(binding.declaringClass.sourceName)); // Convert the type variables and store them UnresolvedType[] ajTypeRefs = null; typeVariablesForThisMember.clear(); // This is the set of type variables available whilst building the resolved member... if (binding.typeVariables != null) { ajTypeRefs = new UnresolvedType[binding.typeVariables.length]; for (int i = 0; i < binding.typeVariables.length; i++) { ajTypeRefs[i] = fromBinding(binding.typeVariables[i]); typeVariablesForThisMember.put(new String(binding.typeVariables[i].sourceName),/* * new * Integer(binding.typeVariables[ * i].rank), */ajTypeRefs[i]); } } // AMC these next two lines shouldn't be needed once we sort out generic types properly in the world map ResolvedType realDeclaringType = world.resolve(fromBinding(declaringType)); if (realDeclaringType.isRawType()) { realDeclaringType = realDeclaringType.getGenericType(); } ResolvedMemberImpl ret = new EclipseResolvedMember(binding, memberKind, realDeclaringType, binding.modifiers, fromBinding(binding.returnType), new String(binding.selector), fromBindings(binding.parameters), fromBindings(binding.thrownExceptions), this); if (binding.isVarargs()) { ret.setVarargsMethod(); } if (ajTypeRefs != null) { TypeVariable[] tVars = new TypeVariable[ajTypeRefs.length]; for (int i = 0; i < ajTypeRefs.length; i++) { tVars[i] = ((TypeVariableReference) ajTypeRefs[i]).getTypeVariable(); } ret.setTypeVariables(tVars); } typeVariablesForThisMember.clear(); ret.resolve(world); return ret; } public ResolvedMember makeResolvedMember(FieldBinding binding) { return makeResolvedMember(binding, binding.declaringClass); } public ResolvedMember makeResolvedMember(FieldBinding binding, TypeBinding receiverType) { // AMC these next two lines shouldn't be needed once we sort out generic types properly in the world map ResolvedType realDeclaringType = world.resolve(fromBinding(receiverType)); if (realDeclaringType.isRawType()) { realDeclaringType = realDeclaringType.getGenericType(); } ResolvedMemberImpl ret = new EclipseResolvedMember(binding, Member.FIELD, realDeclaringType, binding.modifiers, world.resolve(fromBinding(binding.type)), new String(binding.name), UnresolvedType.NONE); return ret; } public TypeBinding makeTypeBinding(UnresolvedType typeX) { TypeBinding ret = null; // looking up type variables can get us into trouble if (!typeX.isTypeVariableReference() && !isParameterizedWithTypeVariables(typeX)) { if (typeX.isRawType()) { ret = (TypeBinding) rawTypeXToBinding.get(typeX); } else { ret = (TypeBinding) typexToBinding.get(typeX); } } if (ret == null) { ret = makeTypeBinding1(typeX); if (ret != null) {// && !(ret instanceof ProblemReferenceBinding)) { if (!(typeX instanceof BoundedReferenceType) && !(typeX instanceof UnresolvedTypeVariableReferenceType)) { if (typeX.isRawType()) { rawTypeXToBinding.put(typeX, ret); } else { typexToBinding.put(typeX, ret); } } } } return ret; } // return true if this is type variables are in the type arguments private boolean isParameterizedWithTypeVariables(UnresolvedType typeX) { if (!typeX.isParameterizedType()) { return false; } UnresolvedType[] typeArguments = typeX.getTypeParameters(); if (typeArguments != null) { for (int i = 0; i < typeArguments.length; i++) { if (typeArguments[i].isTypeVariableReference()) { return true; } } } return false; } // When converting a parameterized type from our world to the eclipse world, these get set so that // resolution of the type parameters may known in what context it is occurring (pr114744) private ReferenceBinding baseTypeForParameterizedType; private int indexOfTypeParameterBeingConverted; private TypeBinding makeTypeBinding1(UnresolvedType typeX) { if (typeX.isPrimitiveType()) { if (typeX.equals(UnresolvedType.BOOLEAN)) { return TypeBinding.BOOLEAN; } if (typeX.equals(UnresolvedType.BYTE)) { return TypeBinding.BYTE; } if (typeX.equals(UnresolvedType.CHAR)) { return TypeBinding.CHAR; } if (typeX.equals(UnresolvedType.DOUBLE)) { return TypeBinding.DOUBLE; } if (typeX.equals(UnresolvedType.FLOAT)) { return TypeBinding.FLOAT; } if (typeX.equals(UnresolvedType.INT)) { return TypeBinding.INT; } if (typeX.equals(UnresolvedType.LONG)) { return TypeBinding.LONG; } if (typeX.equals(UnresolvedType.SHORT)) { return TypeBinding.SHORT; } if (typeX.equals(UnresolvedType.VOID)) { return TypeBinding.VOID; } throw new RuntimeException("weird primitive type " + typeX); } else if (typeX.isArray()) { int dim = 0; while (typeX.isArray()) { dim++; typeX = typeX.getComponentType(); } return lookupEnvironment.createArrayType(makeTypeBinding(typeX), dim); } else if (typeX.isParameterizedType()) { // Converting back to a binding from a UnresolvedType UnresolvedType[] typeParameters = typeX.getTypeParameters(); ReferenceBinding baseTypeBinding = lookupBinding(typeX.getBaseName()); TypeBinding[] argumentBindings = new TypeBinding[typeParameters.length]; baseTypeForParameterizedType = baseTypeBinding; for (int i = 0; i < argumentBindings.length; i++) { indexOfTypeParameterBeingConverted = i; argumentBindings[i] = makeTypeBinding(typeParameters[i]); } indexOfTypeParameterBeingConverted = 0; baseTypeForParameterizedType = null; ParameterizedTypeBinding ptb = lookupEnvironment.createParameterizedType(baseTypeBinding, argumentBindings, baseTypeBinding.enclosingType()); return ptb; } else if (typeX.isTypeVariableReference()) { // return makeTypeVariableBinding((TypeVariableReference)typeX); return makeTypeVariableBindingFromAJTypeVariable(((TypeVariableReference) typeX).getTypeVariable()); } else if (typeX.isRawType()) { ReferenceBinding baseTypeBinding = lookupBinding(typeX.getBaseName()); RawTypeBinding rtb = lookupEnvironment.createRawType(baseTypeBinding, baseTypeBinding.enclosingType()); return rtb; } else if (typeX.isGenericWildcard()) { if (typeX instanceof WildcardedUnresolvedType) { WildcardedUnresolvedType wut = (WildcardedUnresolvedType) typeX; int boundkind = Wildcard.UNBOUND; TypeBinding bound = null; if (wut.isExtends()) { boundkind = Wildcard.EXTENDS; bound = makeTypeBinding(wut.getUpperBound()); } else if (wut.isSuper()) { boundkind = Wildcard.SUPER; bound = makeTypeBinding(wut.getLowerBound()); } TypeBinding[] otherBounds = null; // TODO 2 ought to support extra bounds for WildcardUnresolvedType // if (wut.getAdditionalBounds()!=null && wut.getAdditionalBounds().length!=0) otherBounds = // makeTypeBindings(wut.getAdditionalBounds()); WildcardBinding wb = lookupEnvironment.createWildcard(baseTypeForParameterizedType, indexOfTypeParameterBeingConverted, bound, otherBounds, boundkind); return wb; } else if (typeX instanceof BoundedReferenceType) { // translate from boundedreferencetype to WildcardBinding BoundedReferenceType brt = (BoundedReferenceType) typeX; // Work out 'kind' for the WildcardBinding int boundkind = Wildcard.UNBOUND; TypeBinding bound = null; if (brt.isExtends()) { boundkind = Wildcard.EXTENDS; bound = makeTypeBinding(brt.getUpperBound()); } else if (brt.isSuper()) { boundkind = Wildcard.SUPER; bound = makeTypeBinding(brt.getLowerBound()); } TypeBinding[] otherBounds = null; if (brt.getAdditionalBounds() != null && brt.getAdditionalBounds().length != 0) { otherBounds = makeTypeBindings(brt.getAdditionalBounds()); } WildcardBinding wb = lookupEnvironment.createWildcard(baseTypeForParameterizedType, indexOfTypeParameterBeingConverted, bound, otherBounds, boundkind); return wb; } else { throw new BCException("This type " + typeX + " (class " + typeX.getClass().getName() + ") should not be claiming to be a wildcard!"); } } else { return lookupBinding(typeX.getName()); } } private ReferenceBinding lookupBinding(String sname) { char[][] name = CharOperation.splitOn('.', sname.toCharArray()); ReferenceBinding rb = lookupEnvironment.getType(name); if (rb == null && !sname.equals(UnresolvedType.MISSING_NAME)) { return new ProblemReferenceBinding(name, null, ProblemReasons.NotFound); } return rb; } public TypeBinding[] makeTypeBindings(UnresolvedType[] types) { int len = types.length; TypeBinding[] ret = new TypeBinding[len]; for (int i = 0; i < len; i++) { ret[i] = makeTypeBinding(types[i]); } return ret; } // just like the code above except it returns an array of ReferenceBindings private ReferenceBinding[] makeReferenceBindings(UnresolvedType[] types) { int len = types.length; ReferenceBinding[] ret = new ReferenceBinding[len]; for (int i = 0; i < len; i++) { ret[i] = (ReferenceBinding) makeTypeBinding(types[i]); } return ret; } // field related public FieldBinding makeFieldBinding(NewFieldTypeMunger nftm) { return internalMakeFieldBinding(nftm.getSignature(), nftm.getTypeVariableAliases()); } /** * Convert a resolvedmember into an eclipse field binding */ public FieldBinding makeFieldBinding(ResolvedMember member, List aliases) { return internalMakeFieldBinding(member, aliases); } /** * Convert a resolvedmember into an eclipse field binding */ public FieldBinding makeFieldBinding(ResolvedMember member) { return internalMakeFieldBinding(member, null); } // OPTIMIZE tidy this up, must be able to optimize for the synthetic case, if we passed in the binding for the declaring type, // that would make things easier /** * Build a new Eclipse SyntheticFieldBinding for an AspectJ ResolvedMember. */ public SyntheticFieldBinding createSyntheticFieldBinding(SourceTypeBinding owningType, ResolvedMember member) { SyntheticFieldBinding sfb = new SyntheticFieldBinding(member.getName().toCharArray(), makeTypeBinding(member.getReturnType()), member.getModifiers() | Flags.AccSynthetic, owningType, Constant.NotAConstant, -1); // index // filled in // later owningType.addSyntheticField(sfb); return sfb; } /** * Take a normal AJ member and convert it into an eclipse fieldBinding. Taking into account any aliases that it may include due * to being a generic itd. Any aliases are put into the typeVariableToBinding map so that they will be substituted as * appropriate in the returned fieldbinding. */ public FieldBinding internalMakeFieldBinding(ResolvedMember member, List aliases) { typeVariableToTypeBinding.clear(); ReferenceBinding declaringType = (ReferenceBinding) makeTypeBinding(member.getDeclaringType()); // If there are aliases, place them in the map if (aliases != null && aliases.size() > 0 && declaringType.typeVariables() != null && declaringType.typeVariables().length != 0) { int i = 0; for (Iterator iter = aliases.iterator(); iter.hasNext();) { String element = (String) iter.next(); typeVariableToTypeBinding.put(element, declaringType.typeVariables()[i++]); } } currentType = declaringType; FieldBinding fb = null; if (member.getName().startsWith(NameMangler.PREFIX)) { fb = new SyntheticFieldBinding(member.getName().toCharArray(), makeTypeBinding(member.getReturnType()), member.getModifiers() | Flags.AccSynthetic, currentType, Constant.NotAConstant, -1); // index filled in later } else { fb = new FieldBinding(member.getName().toCharArray(), makeTypeBinding(member.getReturnType()), member.getModifiers(), currentType, Constant.NotAConstant); } typeVariableToTypeBinding.clear(); currentType = null; if (member.getName().startsWith(NameMangler.PREFIX)) { fb.modifiers |= Flags.AccSynthetic; } return fb; } private ReferenceBinding currentType = null; // method binding related public MethodBinding makeMethodBinding(NewMethodTypeMunger nmtm) { return internalMakeMethodBinding(nmtm.getSignature(), nmtm.getTypeVariableAliases()); } /** * Convert a resolvedmember into an eclipse method binding. */ public MethodBinding makeMethodBinding(ResolvedMember member, List aliases) { return internalMakeMethodBinding(member, aliases); } /** * Creates a method binding for a resolvedmember taking into account type variable aliases - this variant can take an * aliasTargetType and should be used when the alias target type cannot be retrieved from the resolvedmember. */ public MethodBinding makeMethodBinding(ResolvedMember member, List aliases, UnresolvedType aliasTargetType) { return internalMakeMethodBinding(member, aliases, aliasTargetType); } /** * Convert a resolvedmember into an eclipse method binding. */ public MethodBinding makeMethodBinding(ResolvedMember member) { return internalMakeMethodBinding(member, null); // there are no aliases } public MethodBinding internalMakeMethodBinding(ResolvedMember member, List aliases) { return internalMakeMethodBinding(member, aliases, member.getDeclaringType()); } /** * Take a normal AJ member and convert it into an eclipse methodBinding. Taking into account any aliases that it may include due * to being a generic ITD. Any aliases are put into the typeVariableToBinding map so that they will be substituted as * appropriate in the returned methodbinding */ public MethodBinding internalMakeMethodBinding(ResolvedMember member, List aliases, UnresolvedType aliasTargetType) { typeVariableToTypeBinding.clear(); TypeVariableBinding[] tvbs = null; if (member.getTypeVariables() != null) { if (member.getTypeVariables().length == 0) { tvbs = Binding.NO_TYPE_VARIABLES; } else { tvbs = makeTypeVariableBindingsFromAJTypeVariables(member.getTypeVariables()); // QQQ do we need to bother fixing up the declaring element here? } } ReferenceBinding declaringType = (ReferenceBinding) makeTypeBinding(member.getDeclaringType()); // If there are aliases, place them in the map if (aliases != null && aliases.size() != 0 && declaringType.typeVariables() != null && declaringType.typeVariables().length != 0) { int i = 0; ReferenceBinding aliasTarget = (ReferenceBinding) makeTypeBinding(aliasTargetType); if (aliasTarget.isRawType()) { aliasTarget = ((RawTypeBinding) aliasTarget).genericType(); } for (Iterator iter = aliases.iterator(); iter.hasNext();) { String element = (String) iter.next(); typeVariableToTypeBinding.put(element, aliasTarget.typeVariables()[i++]); } } currentType = declaringType; MethodBinding mb = new MethodBinding(member.getModifiers(), member.getName().toCharArray(), makeTypeBinding(member.getReturnType()), makeTypeBindings(member.getParameterTypes()), makeReferenceBindings(member.getExceptions()), declaringType); if (tvbs != null) { mb.typeVariables = tvbs; } typeVariableToTypeBinding.clear(); currentType = null; if (NameMangler.isSyntheticMethod(member.getName(), true)) { mb.modifiers |= Flags.AccSynthetic; } return mb; } /** * Convert a bunch of type variables in one go, from AspectJ form to Eclipse form. */ // private TypeVariableBinding[] makeTypeVariableBindings(UnresolvedType[] typeVariables) { // int len = typeVariables.length; // TypeVariableBinding[] ret = new TypeVariableBinding[len]; // for (int i = 0; i < len; i++) { // ret[i] = makeTypeVariableBinding((TypeVariableReference)typeVariables[i]); // } // return ret; // } private TypeVariableBinding[] makeTypeVariableBindingsFromAJTypeVariables(TypeVariable[] typeVariables) { int len = typeVariables.length; TypeVariableBinding[] ret = new TypeVariableBinding[len]; for (int i = 0; i < len; i++) { ret[i] = makeTypeVariableBindingFromAJTypeVariable(typeVariables[i]); } return ret; } // only accessed through private methods in this class. Ensures all type variables we encounter // map back to the same type binding - this is important later when Eclipse code is processing // a methodbinding trying to come up with possible bindings for the type variables. // key is currently the name of the type variable...is that ok? private final Map typeVariableToTypeBinding = new HashMap(); // /** // * Converts from an TypeVariableReference to a TypeVariableBinding. A TypeVariableReference // * in AspectJ world holds a TypeVariable and it is this type variable that is converted // * to the TypeVariableBinding. // */ // private TypeVariableBinding makeTypeVariableBinding(TypeVariableReference tvReference) { // TypeVariable tv = tvReference.getTypeVariable(); // TypeVariableBinding tvBinding = (TypeVariableBinding)typeVariableToTypeBinding.get(tv.getName()); // if (currentType!=null) { // TypeVariableBinding tvb = currentType.getTypeVariable(tv.getName().toCharArray()); // if (tvb!=null) return tvb; // } // if (tvBinding==null) { // Binding declaringElement = null; // // this will cause an infinite loop or NPE... not required yet luckily. // // if (tVar.getDeclaringElement() instanceof Member) { // // declaringElement = makeMethodBinding((ResolvedMember)tVar.getDeclaringElement()); // // } else { // // declaringElement = makeTypeBinding((UnresolvedType)tVar.getDeclaringElement()); // // } // // tvBinding = new TypeVariableBinding(tv.getName().toCharArray(),null,tv.getRank()); // // typeVariableToTypeBinding.put(tv.getName(),tvBinding); // tvBinding.superclass=(ReferenceBinding)makeTypeBinding(tv.getUpperBound()); // tvBinding.firstBound=makeTypeBinding(tv.getFirstBound()); // if (tv.getAdditionalInterfaceBounds()==null) { // tvBinding.superInterfaces=TypeVariableBinding.NO_SUPERINTERFACES; // } else { // TypeBinding tbs[] = makeTypeBindings(tv.getAdditionalInterfaceBounds()); // ReferenceBinding[] rbs= new ReferenceBinding[tbs.length]; // for (int i = 0; i < tbs.length; i++) { // rbs[i] = (ReferenceBinding)tbs[i]; // } // tvBinding.superInterfaces=rbs; // } // } // return tvBinding; // } private TypeVariableBinding makeTypeVariableBindingFromAJTypeVariable(TypeVariable tv) { TypeVariableBinding tvBinding = (TypeVariableBinding) typeVariableToTypeBinding.get(tv.getName()); if (currentType != null) { TypeVariableBinding tvb = currentType.getTypeVariable(tv.getName().toCharArray()); if (tvb != null) { return tvb; } } if (tvBinding == null) { Binding declaringElement = null; // this will cause an infinite loop or NPE... not required yet luckily. // if (tVar.getDeclaringElement() instanceof Member) { // declaringElement = makeMethodBinding((ResolvedMember)tVar.getDeclaringElement()); // } else { // declaringElement = makeTypeBinding((UnresolvedType)tVar.getDeclaringElement()); // } tvBinding = new TypeVariableBinding(tv.getName().toCharArray(), declaringElement, tv.getRank(),this.lookupEnvironment); typeVariableToTypeBinding.put(tv.getName(), tvBinding); if (tv.getSuperclass() != null && (!tv.getSuperclass().getSignature().equals("Ljava/lang/Object;") || tv.getSuperInterfaces() != null)) { tvBinding.superclass = (ReferenceBinding) makeTypeBinding(tv.getSuperclass()); } tvBinding.firstBound = makeTypeBinding(tv.getFirstBound()); if (tv.getSuperInterfaces() == null) { tvBinding.superInterfaces = TypeVariableBinding.NO_SUPERINTERFACES; } else { TypeBinding tbs[] = makeTypeBindings(tv.getSuperInterfaces()); ReferenceBinding[] rbs = new ReferenceBinding[tbs.length]; for (int i = 0; i < tbs.length; i++) { rbs[i] = (ReferenceBinding) tbs[i]; } tvBinding.superInterfaces = rbs; } } return tvBinding; } public MethodBinding makeMethodBindingForCall(Member member) { return new MethodBinding(member.getModifiers() & ~Modifier.INTERFACE, member.getName().toCharArray(), makeTypeBinding(member.getReturnType()), makeTypeBindings(member.getParameterTypes()), new ReferenceBinding[0], (ReferenceBinding) makeTypeBinding(member.getDeclaringType())); } public void finishedCompilationUnit(CompilationUnitDeclaration unit) { if ((buildManager != null) && buildManager.doGenerateModel()) { AjBuildManager.getAsmHierarchyBuilder().buildStructureForCompilationUnit(unit, buildManager.getStructureModel(), buildManager.buildConfig); } } public void addTypeBinding(TypeBinding binding) { typexToBinding.put(fromBinding(binding), binding); } public void addTypeBindingAndStoreInWorld(TypeBinding binding) { UnresolvedType ut = fromBinding(binding); typexToBinding.put(ut, binding); world.lookupOrCreateName(ut); } public Shadow makeShadow(ASTNode location, ReferenceContext context) { return EclipseShadow.makeShadow(this, location, context); } public Shadow makeShadow(ReferenceContext context) { return EclipseShadow.makeShadow(this, (ASTNode) context, context); } public void addSourceTypeBinding(SourceTypeBinding binding, CompilationUnitDeclaration unit) { TypeDeclaration decl = binding.scope.referenceContext; // Deal with the raw/basic type to give us an entry in the world type map UnresolvedType unresolvedRawType = null; if (binding.isGenericType()) { unresolvedRawType = UnresolvedType.forRawTypeName(getName(binding)); } else if (binding.isLocalType()) { LocalTypeBinding ltb = (LocalTypeBinding) binding; if (ltb.constantPoolName() != null && ltb.constantPoolName().length > 0) { unresolvedRawType = UnresolvedType.forSignature(new String(binding.signature())); } else { unresolvedRawType = UnresolvedType.forName(getName(binding)); } } else { unresolvedRawType = UnresolvedType.forName(getName(binding)); } ReferenceType resolvedRawType = getWorld().lookupOrCreateName(unresolvedRawType); // A type can change from simple > generic > simple across a set of compiles. We need // to ensure the entry in the typemap is promoted and demoted correctly. The call // to setGenericType() below promotes a simple to a raw. This call demotes it back // to simple // pr125405 if (!binding.isRawType() && !binding.isGenericType() && resolvedRawType.getTypekind() == TypeKind.RAW) { resolvedRawType.demoteToSimpleType(); } EclipseSourceType t = new EclipseSourceType(resolvedRawType, this, binding, decl, unit); // For generics, go a bit further - build a typex for the generic type // give it the same delegate and link it to the raw type if (binding.isGenericType()) { UnresolvedType unresolvedGenericType = fromBinding(binding); // fully aware of any generics info ResolvedType resolvedGenericType = world.resolve(unresolvedGenericType, true); ReferenceType complexName = null; if (!resolvedGenericType.isMissing()) { complexName = (ReferenceType) resolvedGenericType; complexName = (ReferenceType) complexName.getGenericType(); if (complexName == null) { complexName = new ReferenceType(unresolvedGenericType, world); } } else { complexName = new ReferenceType(unresolvedGenericType, world); } resolvedRawType.setGenericType(complexName); complexName.setDelegate(t); } resolvedRawType.setDelegate(t); if (decl instanceof AspectDeclaration) { ((AspectDeclaration) decl).typeX = resolvedRawType; ((AspectDeclaration) decl).concreteName = t; } ReferenceBinding[] memberTypes = binding.memberTypes; for (int i = 0, length = memberTypes.length; i < length; i++) { addSourceTypeBinding((SourceTypeBinding) memberTypes[i], unit); } } // XXX this doesn't feel like it belongs here, but it breaks a hard dependency on // exposing AjBuildManager (needed by AspectDeclaration). public boolean isXSerializableAspects() { return xSerializableAspects; } public ResolvedMember fromBinding(MethodBinding binding) { return new ResolvedMemberImpl(Member.METHOD, fromBinding(binding.declaringClass), binding.modifiers, fromBinding(binding.returnType), CharOperation.charToString(binding.selector), fromBindings(binding.parameters)); } public TypeVariableDeclaringElement fromBinding(Binding declaringElement) { if (declaringElement instanceof TypeBinding) { return fromBinding(((TypeBinding) declaringElement)); } else { return fromBinding((MethodBinding) declaringElement); } } public void cleanup() { this.typexToBinding.clear(); this.rawTypeXToBinding.clear(); this.finishedTypeMungers = null; } public void minicleanup() { this.typexToBinding.clear(); this.rawTypeXToBinding.clear(); } public int getItdVersion() { return world.getItdVersion(); } }
384,398
Bug 384398 Type Mismatch error when using inner classes contained in generic types within ITDs
Please see attached example project. I get the following (strange) compiler error: Type mismatch: cannot convert from A<T>.InnerA<> to A.InnerA BAspect.aj /AspectJInnerclassInGenericTypeBug/src/de/example line 12
resolved fixed
bf949d3
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2012-07-10T17:18:35Z"
"2012-07-05T17:40:00Z"
tests/bugs171/pr384398/A.java
384,398
Bug 384398 Type Mismatch error when using inner classes contained in generic types within ITDs
Please see attached example project. I get the following (strange) compiler error: Type mismatch: cannot convert from A<T>.InnerA<> to A.InnerA BAspect.aj /AspectJInnerclassInGenericTypeBug/src/de/example line 12
resolved fixed
bf949d3
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2012-07-10T17:18:35Z"
"2012-07-05T17:40:00Z"
tests/bugs171/pr384398/B.java
384,398
Bug 384398 Type Mismatch error when using inner classes contained in generic types within ITDs
Please see attached example project. I get the following (strange) compiler error: Type mismatch: cannot convert from A<T>.InnerA<> to A.InnerA BAspect.aj /AspectJInnerclassInGenericTypeBug/src/de/example line 12
resolved fixed
bf949d3
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2012-07-10T17:18:35Z"
"2012-07-05T17:40:00Z"
tests/bugs171/pr384398_2/A.java
384,398
Bug 384398 Type Mismatch error when using inner classes contained in generic types within ITDs
Please see attached example project. I get the following (strange) compiler error: Type mismatch: cannot convert from A<T>.InnerA<> to A.InnerA BAspect.aj /AspectJInnerclassInGenericTypeBug/src/de/example line 12
resolved fixed
bf949d3
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2012-07-10T17:18:35Z"
"2012-07-05T17:40:00Z"
tests/bugs171/pr384398_2/B.java
384,398
Bug 384398 Type Mismatch error when using inner classes contained in generic types within ITDs
Please see attached example project. I get the following (strange) compiler error: Type mismatch: cannot convert from A<T>.InnerA<> to A.InnerA BAspect.aj /AspectJInnerclassInGenericTypeBug/src/de/example line 12
resolved fixed
bf949d3
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2012-07-10T17:18:35Z"
"2012-07-05T17:40:00Z"
tests/src/org/aspectj/systemtest/AllTests17.java
/* * Created on 19-01-2005 */ package org.aspectj.systemtest; import junit.framework.Test; import junit.framework.TestSuite; import org.aspectj.systemtest.ajc170.AllTestsAspectJ170; public class AllTests17 { public static Test suite() { TestSuite suite = new TestSuite("AspectJ System Test Suite - JDK 1.7"); // $JUnit-BEGIN$ suite.addTest(AllTestsAspectJ170.suite()); suite.addTest(AllTests16.suite()); suite.addTest(AllTests15.suite()); // $JUnit-END$ return suite; } }
384,398
Bug 384398 Type Mismatch error when using inner classes contained in generic types within ITDs
Please see attached example project. I get the following (strange) compiler error: Type mismatch: cannot convert from A<T>.InnerA<> to A.InnerA BAspect.aj /AspectJInnerclassInGenericTypeBug/src/de/example line 12
resolved fixed
bf949d3
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2012-07-10T17:18:35Z"
"2012-07-05T17:40:00Z"
tests/src/org/aspectj/systemtest/ajc171/Ajc171Tests.java
384,398
Bug 384398 Type Mismatch error when using inner classes contained in generic types within ITDs
Please see attached example project. I get the following (strange) compiler error: Type mismatch: cannot convert from A<T>.InnerA<> to A.InnerA BAspect.aj /AspectJInnerclassInGenericTypeBug/src/de/example line 12
resolved fixed
bf949d3
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2012-07-10T17:18:35Z"
"2012-07-05T17:40:00Z"
tests/src/org/aspectj/systemtest/ajc171/AllTestsAspectJ171.java
386,049
Bug 386049 Error "must implement abstract inter-type declaration" even though build is fine
null
verified fixed
7c6e936
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2012-08-22T19:43:56Z"
"2012-07-26T13:40:00Z"
org.aspectj.matcher/src/org/aspectj/weaver/ResolvedType.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Eclipse Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * PARC initial implementation * Alexandre Vasseur @AspectJ ITDs * ******************************************************************/ package org.aspectj.weaver; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Queue; import java.util.Set; import org.aspectj.bridge.IMessage; import org.aspectj.bridge.ISourceLocation; import org.aspectj.bridge.Message; import org.aspectj.bridge.MessageUtil; import org.aspectj.util.FuzzyBoolean; import org.aspectj.weaver.AjAttribute.WeaverVersionInfo; import org.aspectj.weaver.Iterators.Getter; import org.aspectj.weaver.patterns.Declare; import org.aspectj.weaver.patterns.PerClause; public abstract class ResolvedType extends UnresolvedType implements AnnotatedElement { public static final ResolvedType[] EMPTY_RESOLVED_TYPE_ARRAY = new ResolvedType[0]; public static final String PARAMETERIZED_TYPE_IDENTIFIER = "P"; // Set temporarily during a type pattern match call - this currently used to hold the // annotations that may be attached to a type when it used as a parameter public ResolvedType[] temporaryAnnotationTypes; private ResolvedType[] resolvedTypeParams; private String binaryPath; protected World world; private int bits; private static int AnnotationBitsInitialized = 0x0001; private static int AnnotationMarkedInherited = 0x0002; private static int MungersAnalyzed = 0x0004; private static int HasParentMunger = 0x0008; private static int TypeHierarchyCompleteBit = 0x0010; private static int GroovyObjectInitialized = 0x0020; private static int IsGroovyObject = 0x0040; protected ResolvedType(String signature, World world) { super(signature); this.world = world; } protected ResolvedType(String signature, String signatureErasure, World world) { super(signature, signatureErasure); this.world = world; } public int getSize() { return 1; } /** * Returns an iterator through ResolvedType objects representing all the direct supertypes of this type. That is, through the * superclass, if any, and all declared interfaces. */ public final Iterator<ResolvedType> getDirectSupertypes() { Iterator<ResolvedType> interfacesIterator = Iterators.array(getDeclaredInterfaces()); ResolvedType superclass = getSuperclass(); if (superclass == null) { return interfacesIterator; } else { return Iterators.snoc(interfacesIterator, superclass); } } public abstract ResolvedMember[] getDeclaredFields(); public abstract ResolvedMember[] getDeclaredMethods(); public abstract ResolvedType[] getDeclaredInterfaces(); public abstract ResolvedMember[] getDeclaredPointcuts(); public boolean isCacheable() { return true; } /** * @return the superclass of this type, or null (if this represents a jlObject, primitive, or void) */ public abstract ResolvedType getSuperclass(); public abstract int getModifiers(); // return true if this resolved type couldn't be found (but we know it's name maybe) public boolean isMissing() { return false; } // FIXME asc I wonder if in some circumstances MissingWithKnownSignature // should not be considered // 'really' missing as some code can continue based solely on the signature public static boolean isMissing(UnresolvedType unresolved) { if (unresolved instanceof ResolvedType) { ResolvedType resolved = (ResolvedType) unresolved; return resolved.isMissing(); } else { return (unresolved == MISSING); } } public ResolvedType[] getAnnotationTypes() { return EMPTY_RESOLVED_TYPE_ARRAY; } public AnnotationAJ getAnnotationOfType(UnresolvedType ofType) { return null; } // public final UnresolvedType getSuperclass(World world) { // return getSuperclass(); // } // This set contains pairs of types whose signatures are concatenated // together, this means with a fast lookup we can tell if two types // are equivalent. protected static Set<String> validBoxing = new HashSet<String>(); static { validBoxing.add("Ljava/lang/Byte;B"); validBoxing.add("Ljava/lang/Character;C"); validBoxing.add("Ljava/lang/Double;D"); validBoxing.add("Ljava/lang/Float;F"); validBoxing.add("Ljava/lang/Integer;I"); validBoxing.add("Ljava/lang/Long;J"); validBoxing.add("Ljava/lang/Short;S"); validBoxing.add("Ljava/lang/Boolean;Z"); validBoxing.add("BLjava/lang/Byte;"); validBoxing.add("CLjava/lang/Character;"); validBoxing.add("DLjava/lang/Double;"); validBoxing.add("FLjava/lang/Float;"); validBoxing.add("ILjava/lang/Integer;"); validBoxing.add("JLjava/lang/Long;"); validBoxing.add("SLjava/lang/Short;"); validBoxing.add("ZLjava/lang/Boolean;"); } // utilities public ResolvedType getResolvedComponentType() { return null; } public World getWorld() { return world; } // ---- things from object @Override public boolean equals(Object other) { if (other instanceof ResolvedType) { return this == other; } else { return super.equals(other); } } // ---- difficult things /** * returns an iterator through all of the fields of this type, in order for checking from JVM spec 2ed 5.4.3.2. This means that * the order is * <p/> * <ul> * <li>fields from current class</li> * <li>recur into direct superinterfaces</li> * <li>recur into superclass</li> * </ul> * <p/> * We keep a hashSet of interfaces that we've visited so we don't spiral out into 2^n land. */ public Iterator<ResolvedMember> getFields() { final Iterators.Filter<ResolvedType> dupFilter = Iterators.dupFilter(); Iterators.Getter<ResolvedType, ResolvedType> typeGetter = new Iterators.Getter<ResolvedType, ResolvedType>() { public Iterator<ResolvedType> get(ResolvedType o) { return dupFilter.filter(o.getDirectSupertypes()); } }; return Iterators.mapOver(Iterators.recur(this, typeGetter), FieldGetterInstance); } /** * returns an iterator through all of the methods of this type, in order for checking from JVM spec 2ed 5.4.3.3. This means that * the order is * <p/> * <ul> * <li>methods from current class</li> * <li>recur into superclass, all the way up, not touching interfaces</li> * <li>recur into all superinterfaces, in some unspecified order (but those 'closest' to this type are first)</li> * </ul> * <p/> * * @param wantGenerics is true if the caller would like all generics information, otherwise those methods are collapsed to their * erasure */ public Iterator<ResolvedMember> getMethods(boolean wantGenerics, boolean wantDeclaredParents) { return Iterators.mapOver(getHierarchy(wantGenerics, wantDeclaredParents), MethodGetterInstance); } public Iterator<ResolvedMember> getMethodsIncludingIntertypeDeclarations(boolean wantGenerics, boolean wantDeclaredParents) { return Iterators.mapOver(getHierarchy(wantGenerics, wantDeclaredParents), MethodGetterWithItdsInstance); } /** * An Iterators.Getter that returns an iterator over all methods declared on some resolved type. */ private static class MethodGetter implements Iterators.Getter<ResolvedType, ResolvedMember> { public Iterator<ResolvedMember> get(ResolvedType type) { return Iterators.array(type.getDeclaredMethods()); } } /** * An Iterators.Getter that returns an iterator over all pointcuts declared on some resolved type. */ private static class PointcutGetter implements Iterators.Getter<ResolvedType, ResolvedMember> { public Iterator<ResolvedMember> get(ResolvedType o) { return Iterators.array(o.getDeclaredPointcuts()); } } // OPTIMIZE could cache the result of discovering ITDs // Getter that returns all declared methods for a type through an iterator - including intertype declarations private static class MethodGetterIncludingItds implements Iterators.Getter<ResolvedType, ResolvedMember> { public Iterator<ResolvedMember> get(ResolvedType type) { ResolvedMember[] methods = type.getDeclaredMethods(); if (type.interTypeMungers != null) { int additional = 0; for (ConcreteTypeMunger typeTransformer : type.interTypeMungers) { ResolvedMember rm = typeTransformer.getSignature(); // BUG won't this include fields? When we are looking for methods if (rm != null) { // new parent type munger can have null signature additional++; } } if (additional > 0) { ResolvedMember[] methods2 = new ResolvedMember[methods.length + additional]; System.arraycopy(methods, 0, methods2, 0, methods.length); additional = methods.length; for (ConcreteTypeMunger typeTransformer : type.interTypeMungers) { ResolvedMember rm = typeTransformer.getSignature(); if (rm != null) { // new parent type munger can have null signature methods2[additional++] = typeTransformer.getSignature(); } } methods = methods2; } } return Iterators.array(methods); } } /** * An Iterators.Getter that returns an iterator over all fields declared on some resolved type. */ private static class FieldGetter implements Iterators.Getter<ResolvedType, ResolvedMember> { public Iterator<ResolvedMember> get(ResolvedType type) { return Iterators.array(type.getDeclaredFields()); } } private final static MethodGetter MethodGetterInstance = new MethodGetter(); private final static MethodGetterIncludingItds MethodGetterWithItdsInstance = new MethodGetterIncludingItds(); private final static PointcutGetter PointcutGetterInstance = new PointcutGetter(); private final static FieldGetter FieldGetterInstance = new FieldGetter(); /** * Return an iterator over the types in this types hierarchy - starting with this type first, then all superclasses up to Object * and then all interfaces (starting with those 'nearest' this type). * * @param wantGenerics true if the caller wants full generic information * @param wantDeclaredParents true if the caller even wants those parents introduced via declare parents * @return an iterator over all types in the hierarchy of this type */ public Iterator<ResolvedType> getHierarchy() { return getHierarchy(false, false); } public Iterator<ResolvedType> getHierarchy(final boolean wantGenerics, final boolean wantDeclaredParents) { final Iterators.Getter<ResolvedType, ResolvedType> interfaceGetter = new Iterators.Getter<ResolvedType, ResolvedType>() { List<String> alreadySeen = new ArrayList<String>(); // Strings are signatures (ResolvedType.getSignature()) public Iterator<ResolvedType> get(ResolvedType type) { ResolvedType[] interfaces = type.getDeclaredInterfaces(); // remove interfaces introduced by declare parents // relatively expensive but hopefully uncommon if (!wantDeclaredParents && type.hasNewParentMungers()) { // Throw away interfaces from that array if they were decp'd onto here List<Integer> forRemoval = new ArrayList<Integer>(); for (ConcreteTypeMunger munger : type.interTypeMungers) { if (munger.getMunger() != null) { ResolvedTypeMunger m = munger.getMunger(); if (m.getKind() == ResolvedTypeMunger.Parent) { ResolvedType newType = ((NewParentTypeMunger) m).getNewParent(); if (!wantGenerics && newType.isParameterizedOrGenericType()) { newType = newType.getRawType(); } for (int ii = 0; ii < interfaces.length; ii++) { ResolvedType iface = interfaces[ii]; if (!wantGenerics && iface.isParameterizedOrGenericType()) { iface = iface.getRawType(); } if (newType.getSignature().equals(iface.getSignature())) { // pr171953 forRemoval.add(ii); } } } } } // Found some to remove from those we are going to iterate over if (forRemoval.size() > 0) { ResolvedType[] interfaces2 = new ResolvedType[interfaces.length - forRemoval.size()]; int p = 0; for (int ii = 0; ii < interfaces.length; ii++) { if (!forRemoval.contains(ii)) { interfaces2[p++] = interfaces[ii]; } } interfaces = interfaces2; } } return new Iterators.ResolvedTypeArrayIterator(interfaces, alreadySeen, wantGenerics); } }; // If this type is an interface, there are only interfaces to walk if (this.isInterface()) { return new SuperInterfaceWalker(interfaceGetter, this); } else { SuperInterfaceWalker superInterfaceWalker = new SuperInterfaceWalker(interfaceGetter); Iterator<ResolvedType> superClassesIterator = new SuperClassWalker(this, superInterfaceWalker, wantGenerics); // append() will check if the second iterator is empty before appending - but the types which the superInterfaceWalker // needs to visit are only accumulated whilst the superClassesIterator is in progress return Iterators.append1(superClassesIterator, superInterfaceWalker); } } /** * Return a list of methods, first those declared on this class, then those declared on the superclass (recurse) and then those * declared on the superinterfaces. This is expensive - use the getMethods() method if you can! */ public List<ResolvedMember> getMethodsWithoutIterator(boolean includeITDs, boolean allowMissing, boolean genericsAware) { List<ResolvedMember> methods = new ArrayList<ResolvedMember>(); Set<String> knowninterfaces = new HashSet<String>(); addAndRecurse(knowninterfaces, methods, this, includeITDs, allowMissing, genericsAware); return methods; } /** * Return a list of the types in the hierarchy of this type, starting with this type. The order in the list is the superclasses * followed by the super interfaces. * * @param genericsAware should the list include parameterized/generic types (if not, they will be collapsed to raw)? * @return list of resolvedtypes in this types hierarchy, including this type first */ public List<ResolvedType> getHierarchyWithoutIterator(boolean includeITDs, boolean allowMissing, boolean genericsAware) { List<ResolvedType> types = new ArrayList<ResolvedType>(); Set<String> visited = new HashSet<String>(); recurseHierarchy(visited, types, this, includeITDs, allowMissing, genericsAware); return types; } private void addAndRecurse(Set<String> knowninterfaces, List<ResolvedMember> collector, ResolvedType resolvedType, boolean includeITDs, boolean allowMissing, boolean genericsAware) { // Add the methods declared on this type collector.addAll(Arrays.asList(resolvedType.getDeclaredMethods())); // now add all the inter-typed members too if (includeITDs && resolvedType.interTypeMungers != null) { for (ConcreteTypeMunger typeTransformer : interTypeMungers) { ResolvedMember rm = typeTransformer.getSignature(); if (rm != null) { // new parent type munger can have null signature collector.add(typeTransformer.getSignature()); } } } // BUG? interface type superclass is Object - is that correct? if (!resolvedType.isInterface() && !resolvedType.equals(ResolvedType.OBJECT)) { ResolvedType superType = resolvedType.getSuperclass(); if (superType != null && !superType.isMissing()) { if (!genericsAware && superType.isParameterizedOrGenericType()) { superType = superType.getRawType(); } // Recurse if we are not at the top addAndRecurse(knowninterfaces, collector, superType, includeITDs, allowMissing, genericsAware); } } // Go through the interfaces on the way back down ResolvedType[] interfaces = resolvedType.getDeclaredInterfaces(); for (int i = 0; i < interfaces.length; i++) { ResolvedType iface = interfaces[i]; if (!genericsAware && iface.isParameterizedOrGenericType()) { iface = iface.getRawType(); } // we need to know if it is an interface from Parent kind munger // as those are used for @AJ ITD and we precisely want to skip those boolean shouldSkip = false; for (int j = 0; j < resolvedType.interTypeMungers.size(); j++) { ConcreteTypeMunger munger = resolvedType.interTypeMungers.get(j); if (munger.getMunger() != null && munger.getMunger().getKind() == ResolvedTypeMunger.Parent && ((NewParentTypeMunger) munger.getMunger()).getNewParent().equals(iface) // pr171953 ) { shouldSkip = true; break; } } // Do not do interfaces more than once if (!shouldSkip && !knowninterfaces.contains(iface.getSignature())) { knowninterfaces.add(iface.getSignature()); if (allowMissing && iface.isMissing()) { if (iface instanceof MissingResolvedTypeWithKnownSignature) { ((MissingResolvedTypeWithKnownSignature) iface).raiseWarningOnMissingInterfaceWhilstFindingMethods(); } } else { addAndRecurse(knowninterfaces, collector, iface, includeITDs, allowMissing, genericsAware); } } } } /** * Recurse up a type hierarchy, first the superclasses then the super interfaces. */ private void recurseHierarchy(Set<String> knowninterfaces, List<ResolvedType> collector, ResolvedType resolvedType, boolean includeITDs, boolean allowMissing, boolean genericsAware) { collector.add(resolvedType); if (!resolvedType.isInterface() && !resolvedType.equals(ResolvedType.OBJECT)) { ResolvedType superType = resolvedType.getSuperclass(); if (superType != null && !superType.isMissing()) { if (!genericsAware && (superType.isParameterizedType() || superType.isGenericType())) { superType = superType.getRawType(); } // Recurse if we are not at the top recurseHierarchy(knowninterfaces, collector, superType, includeITDs, allowMissing, genericsAware); } } // Go through the interfaces on the way back down ResolvedType[] interfaces = resolvedType.getDeclaredInterfaces(); for (int i = 0; i < interfaces.length; i++) { ResolvedType iface = interfaces[i]; if (!genericsAware && (iface.isParameterizedType() || iface.isGenericType())) { iface = iface.getRawType(); } // we need to know if it is an interface from Parent kind munger // as those are used for @AJ ITD and we precisely want to skip those boolean shouldSkip = false; for (int j = 0; j < resolvedType.interTypeMungers.size(); j++) { ConcreteTypeMunger munger = resolvedType.interTypeMungers.get(j); if (munger.getMunger() != null && munger.getMunger().getKind() == ResolvedTypeMunger.Parent && ((NewParentTypeMunger) munger.getMunger()).getNewParent().equals(iface) // pr171953 ) { shouldSkip = true; break; } } // Do not do interfaces more than once if (!shouldSkip && !knowninterfaces.contains(iface.getSignature())) { knowninterfaces.add(iface.getSignature()); if (allowMissing && iface.isMissing()) { if (iface instanceof MissingResolvedTypeWithKnownSignature) { ((MissingResolvedTypeWithKnownSignature) iface).raiseWarningOnMissingInterfaceWhilstFindingMethods(); } } else { recurseHierarchy(knowninterfaces, collector, iface, includeITDs, allowMissing, genericsAware); } } } } public ResolvedType[] getResolvedTypeParameters() { if (resolvedTypeParams == null) { resolvedTypeParams = world.resolve(typeParameters); } return resolvedTypeParams; } /** * described in JVM spec 2ed 5.4.3.2 */ public ResolvedMember lookupField(Member field) { Iterator<ResolvedMember> i = getFields(); while (i.hasNext()) { ResolvedMember resolvedMember = i.next(); if (matches(resolvedMember, field)) { return resolvedMember; } if (resolvedMember.hasBackingGenericMember() && field.getName().equals(resolvedMember.getName())) { // might be worth checking the member behind the parameterized member (see pr137496) if (matches(resolvedMember.getBackingGenericMember(), field)) { return resolvedMember; } } } return null; } /** * described in JVM spec 2ed 5.4.3.3. Doesnt check ITDs. * * <p> * Check the current type for the method. If it is not found, check the super class and any super interfaces. Taking care not to * process interfaces multiple times. */ public ResolvedMember lookupMethod(Member m) { List<ResolvedType> typesTolookat = new ArrayList<ResolvedType>(); typesTolookat.add(this); int pos = 0; while (pos < typesTolookat.size()) { ResolvedType type = typesTolookat.get(pos++); if (!type.isMissing()) { ResolvedMember[] methods = type.getDeclaredMethods(); if (methods != null) { for (int i = 0; i < methods.length; i++) { ResolvedMember method = methods[i]; if (matches(method, m)) { return method; } // might be worth checking the method behind the parameterized method (137496) if (method.hasBackingGenericMember() && m.getName().equals(method.getName())) { if (matches(method.getBackingGenericMember(), m)) { return method; } } } } } // Queue the superclass: ResolvedType superclass = type.getSuperclass(); if (superclass != null) { typesTolookat.add(superclass); } // Queue any interfaces not already checked: ResolvedType[] superinterfaces = type.getDeclaredInterfaces(); if (superinterfaces != null) { for (int i = 0; i < superinterfaces.length; i++) { ResolvedType interf = superinterfaces[i]; if (!typesTolookat.contains(interf)) { typesTolookat.add(interf); } } } } return null; } /** * @param member the member to lookup in intertype declarations affecting this type * @return the real signature defined by any matching intertype declaration, otherwise null */ public ResolvedMember lookupMethodInITDs(Member member) { for (ConcreteTypeMunger typeTransformer : interTypeMungers) { if (matches(typeTransformer.getSignature(), member)) { return typeTransformer.getSignature(); } } return null; } /** * return null if not found */ private ResolvedMember lookupMember(Member m, ResolvedMember[] a) { for (int i = 0; i < a.length; i++) { ResolvedMember f = a[i]; if (matches(f, m)) { return f; } } return null; } // Bug (1) Do callers expect ITDs to be involved in the lookup? or do they do their own walk over ITDs? /** * Looks for the first member in the hierarchy matching aMember. This method differs from lookupMember(Member) in that it takes * into account parameters which are type variables - which clearly an unresolved Member cannot do since it does not know * anything about type variables. */ public ResolvedMember lookupResolvedMember(ResolvedMember aMember, boolean allowMissing, boolean eraseGenerics) { Iterator<ResolvedMember> toSearch = null; ResolvedMember found = null; if ((aMember.getKind() == Member.METHOD) || (aMember.getKind() == Member.CONSTRUCTOR)) { // toSearch = getMethodsWithoutIterator(true, allowMissing, !eraseGenerics).iterator(); toSearch = getMethodsIncludingIntertypeDeclarations(!eraseGenerics, true); } else { assert aMember.getKind() == Member.FIELD; toSearch = getFields(); } while (toSearch.hasNext()) { ResolvedMember candidate = toSearch.next(); if (eraseGenerics) { if (candidate.hasBackingGenericMember()) { candidate = candidate.getBackingGenericMember(); } } // OPTIMIZE speed up matches? optimize order of checks if (candidate.matches(aMember, eraseGenerics)) { found = candidate; break; } } return found; } public static boolean matches(Member m1, Member m2) { if (m1 == null) { return m2 == null; } if (m2 == null) { return false; } // Check the names boolean equalNames = m1.getName().equals(m2.getName()); if (!equalNames) { return false; } // Check the signatures boolean equalSignatures = m1.getSignature().equals(m2.getSignature()); if (equalSignatures) { return true; } // If they aren't the same, we need to allow for covariance ... where // one sig might be ()LCar; and // the subsig might be ()LFastCar; - where FastCar is a subclass of Car boolean equalCovariantSignatures = m1.getParameterSignature().equals(m2.getParameterSignature()); if (equalCovariantSignatures) { return true; } return false; } public static boolean conflictingSignature(Member m1, Member m2) { return conflictingSignature(m1,m2,true); } /** * Do the two members conflict? Due to the change in 1.7.1, field itds on interfaces now act like 'default' fields - so types implementing * those fields get the field if they don't have it already, otherwise they keep what they have. The conflict detection below had to be * altered. Previously (<1.7.1) it is not a conflict if the declaring types are different. With v2itds it may still be a conflict if the * declaring types are different. */ public static boolean conflictingSignature(Member m1, Member m2, boolean v2itds) { if (m1 == null || m2 == null) { return false; } if (!m1.getName().equals(m2.getName())) { return false; } if (m1.getKind() != m2.getKind()) { return false; } if (m1.getKind() == Member.FIELD) { if (v2itds) { if (m1.getDeclaringType().equals(m2.getDeclaringType())) { return true; } } else { return m1.getDeclaringType().equals(m2.getDeclaringType()); } } else if (m1.getKind() == Member.POINTCUT) { return true; } UnresolvedType[] p1 = m1.getGenericParameterTypes(); UnresolvedType[] p2 = m2.getGenericParameterTypes(); if (p1 == null) { p1 = m1.getParameterTypes(); } if (p2 == null) { p2 = m2.getParameterTypes(); } int n = p1.length; if (n != p2.length) { return false; } for (int i = 0; i < n; i++) { if (!p1[i].equals(p2[i])) { return false; } } return true; } /** * returns an iterator through all of the pointcuts of this type, in order for checking from JVM spec 2ed 5.4.3.2 (as for * fields). This means that the order is * <p/> * <ul> * <li>pointcuts from current class</li> * <li>recur into direct superinterfaces</li> * <li>recur into superclass</li> * </ul> * <p/> * We keep a hashSet of interfaces that we've visited so we don't spiral out into 2^n land. */ public Iterator<ResolvedMember> getPointcuts() { final Iterators.Filter<ResolvedType> dupFilter = Iterators.dupFilter(); // same order as fields Iterators.Getter<ResolvedType, ResolvedType> typeGetter = new Iterators.Getter<ResolvedType, ResolvedType>() { public Iterator<ResolvedType> get(ResolvedType o) { return dupFilter.filter(o.getDirectSupertypes()); } }; return Iterators.mapOver(Iterators.recur(this, typeGetter), PointcutGetterInstance); } public ResolvedPointcutDefinition findPointcut(String name) { for (Iterator<ResolvedMember> i = getPointcuts(); i.hasNext();) { ResolvedPointcutDefinition f = (ResolvedPointcutDefinition) i.next(); // the ResolvedPointcutDefinition can be null if there are other problems that prevented its resolution if (f != null && name.equals(f.getName())) { return f; } } // pr120521 if (!getOutermostType().equals(this)) { ResolvedType outerType = getOutermostType().resolve(world); ResolvedPointcutDefinition rpd = outerType.findPointcut(name); return rpd; } return null; // should we throw an exception here? } // all about collecting CrosscuttingMembers // ??? collecting data-structure, shouldn't really be a field public CrosscuttingMembers crosscuttingMembers; public CrosscuttingMembers collectCrosscuttingMembers(boolean shouldConcretizeIfNeeded) { crosscuttingMembers = new CrosscuttingMembers(this, shouldConcretizeIfNeeded); if (getPerClause() == null) { return crosscuttingMembers; } crosscuttingMembers.setPerClause(getPerClause()); crosscuttingMembers.addShadowMungers(collectShadowMungers()); // GENERICITDFIX // crosscuttingMembers.addTypeMungers(collectTypeMungers()); crosscuttingMembers.addTypeMungers(getTypeMungers()); // FIXME AV - skip but needed ?? or ?? // crosscuttingMembers.addLateTypeMungers(getLateTypeMungers()); crosscuttingMembers.addDeclares(collectDeclares(!this.doesNotExposeShadowMungers())); crosscuttingMembers.addPrivilegedAccesses(getPrivilegedAccesses()); // System.err.println("collected cc members: " + this + ", " + // collectDeclares()); return crosscuttingMembers; } public final List<Declare> collectDeclares(boolean includeAdviceLike) { if (!this.isAspect()) { return Collections.emptyList(); } List<Declare> ret = new ArrayList<Declare>(); // if (this.isAbstract()) { // for (Iterator i = getDeclares().iterator(); i.hasNext();) { // Declare dec = (Declare) i.next(); // if (!dec.isAdviceLike()) ret.add(dec); // } // // if (!includeAdviceLike) return ret; if (!this.isAbstract()) { // ret.addAll(getDeclares()); final Iterators.Filter<ResolvedType> dupFilter = Iterators.dupFilter(); Iterators.Getter<ResolvedType, ResolvedType> typeGetter = new Iterators.Getter<ResolvedType, ResolvedType>() { public Iterator<ResolvedType> get(ResolvedType o) { return dupFilter.filter((o).getDirectSupertypes()); } }; Iterator<ResolvedType> typeIterator = Iterators.recur(this, typeGetter); while (typeIterator.hasNext()) { ResolvedType ty = typeIterator.next(); // System.out.println("super: " + ty + ", " + ); for (Iterator<Declare> i = ty.getDeclares().iterator(); i.hasNext();) { Declare dec = i.next(); if (dec.isAdviceLike()) { if (includeAdviceLike) { ret.add(dec); } } else { ret.add(dec); } } } } return ret; } private final List<ShadowMunger> collectShadowMungers() { if (!this.isAspect() || this.isAbstract() || this.doesNotExposeShadowMungers()) { return Collections.emptyList(); } List<ShadowMunger> acc = new ArrayList<ShadowMunger>(); final Iterators.Filter<ResolvedType> dupFilter = Iterators.dupFilter(); Iterators.Getter<ResolvedType, ResolvedType> typeGetter = new Iterators.Getter<ResolvedType, ResolvedType>() { public Iterator<ResolvedType> get(ResolvedType o) { return dupFilter.filter((o).getDirectSupertypes()); } }; Iterator<ResolvedType> typeIterator = Iterators.recur(this, typeGetter); while (typeIterator.hasNext()) { ResolvedType ty = typeIterator.next(); acc.addAll(ty.getDeclaredShadowMungers()); } return acc; } public void addParent(ResolvedType newParent) { // Nothing to do for anything except a ReferenceType } protected boolean doesNotExposeShadowMungers() { return false; } public PerClause getPerClause() { return null; } public Collection<Declare> getDeclares() { return Collections.emptyList(); } public Collection<ConcreteTypeMunger> getTypeMungers() { return Collections.emptyList(); } public Collection<ResolvedMember> getPrivilegedAccesses() { return Collections.emptyList(); } // ---- useful things public final boolean isInterface() { return Modifier.isInterface(getModifiers()); } public final boolean isAbstract() { return Modifier.isAbstract(getModifiers()); } public boolean isClass() { return false; } public boolean isAspect() { return false; } public boolean isAnnotationStyleAspect() { return false; } /** * Note: Only overridden by Name subtype. */ public boolean isEnum() { return false; } /** * Note: Only overridden by Name subtype. */ public boolean isAnnotation() { return false; } public boolean isAnonymous() { return false; } public boolean isNested() { return false; } public void addAnnotation(AnnotationAJ annotationX) { throw new RuntimeException("ResolvedType.addAnnotation() should never be called"); } public AnnotationAJ[] getAnnotations() { throw new RuntimeException("ResolvedType.getAnnotations() should never be called"); } /** * Note: Only overridden by ReferenceType subtype */ public boolean canAnnotationTargetType() { return false; } /** * Note: Only overridden by ReferenceType subtype */ public AnnotationTargetKind[] getAnnotationTargetKinds() { return null; } /** * Note: Only overridden by Name subtype. */ public boolean isAnnotationWithRuntimeRetention() { return false; } public boolean isSynthetic() { return signature.indexOf("$ajc") != -1; } public final boolean isFinal() { return Modifier.isFinal(getModifiers()); } protected Map<String, UnresolvedType> getMemberParameterizationMap() { if (!isParameterizedType()) { return Collections.emptyMap(); } TypeVariable[] tvs = getGenericType().getTypeVariables(); Map<String, UnresolvedType> parameterizationMap = new HashMap<String, UnresolvedType>(); for (int i = 0; i < tvs.length; i++) { parameterizationMap.put(tvs[i].getName(), typeParameters[i]); } return parameterizationMap; } public List<ShadowMunger> getDeclaredAdvice() { List<ShadowMunger> l = new ArrayList<ShadowMunger>(); ResolvedMember[] methods = getDeclaredMethods(); if (isParameterizedType()) { methods = getGenericType().getDeclaredMethods(); } Map<String, UnresolvedType> typeVariableMap = getAjMemberParameterizationMap(); for (int i = 0, len = methods.length; i < len; i++) { ShadowMunger munger = methods[i].getAssociatedShadowMunger(); if (munger != null) { if (ajMembersNeedParameterization()) { // munger.setPointcut(munger.getPointcut().parameterizeWith( // typeVariableMap)); munger = munger.parameterizeWith(this, typeVariableMap); if (munger instanceof Advice) { Advice advice = (Advice) munger; // update to use the parameterized signature... UnresolvedType[] ptypes = methods[i].getGenericParameterTypes(); UnresolvedType[] newPTypes = new UnresolvedType[ptypes.length]; for (int j = 0; j < ptypes.length; j++) { if (ptypes[j] instanceof TypeVariableReferenceType) { TypeVariableReferenceType tvrt = (TypeVariableReferenceType) ptypes[j]; if (typeVariableMap.containsKey(tvrt.getTypeVariable().getName())) { newPTypes[j] = typeVariableMap.get(tvrt.getTypeVariable().getName()); } else { newPTypes[j] = ptypes[j]; } } else { newPTypes[j] = ptypes[j]; } } advice.setBindingParameterTypes(newPTypes); } } munger.setDeclaringType(this); l.add(munger); } } return l; } public List<ShadowMunger> getDeclaredShadowMungers() { return getDeclaredAdvice(); } // ---- only for testing! public ResolvedMember[] getDeclaredJavaFields() { return filterInJavaVisible(getDeclaredFields()); } public ResolvedMember[] getDeclaredJavaMethods() { return filterInJavaVisible(getDeclaredMethods()); } private ResolvedMember[] filterInJavaVisible(ResolvedMember[] ms) { List<ResolvedMember> l = new ArrayList<ResolvedMember>(); for (int i = 0, len = ms.length; i < len; i++) { if (!ms[i].isAjSynthetic() && ms[i].getAssociatedShadowMunger() == null) { l.add(ms[i]); } } return l.toArray(new ResolvedMember[l.size()]); } public abstract ISourceContext getSourceContext(); // ---- fields public static final ResolvedType[] NONE = new ResolvedType[0]; public static final ResolvedType[] EMPTY_ARRAY = NONE; public static final Missing MISSING = new Missing(); // ---- types public static ResolvedType makeArray(ResolvedType type, int dim) { if (dim == 0) { return type; } ResolvedType array = new ArrayReferenceType("[" + type.getSignature(), "[" + type.getErasureSignature(), type.getWorld(), type); return makeArray(array, dim - 1); } static class Primitive extends ResolvedType { private final int size; private final int index; Primitive(String signature, int size, int index) { super(signature, null); this.size = size; this.index = index; this.typeKind = TypeKind.PRIMITIVE; } @Override public final int getSize() { return size; } @Override public final int getModifiers() { return Modifier.PUBLIC | Modifier.FINAL; } @Override public final boolean isPrimitiveType() { return true; } public boolean hasAnnotation(UnresolvedType ofType) { return false; } @Override public final boolean isAssignableFrom(ResolvedType other) { if (!other.isPrimitiveType()) { if (!world.isInJava5Mode()) { return false; } return validBoxing.contains(this.getSignature() + other.getSignature()); } return assignTable[((Primitive) other).index][index]; } @Override public final boolean isAssignableFrom(ResolvedType other, boolean allowMissing) { return isAssignableFrom(other); } @Override public final boolean isCoerceableFrom(ResolvedType other) { if (this == other) { return true; } if (!other.isPrimitiveType()) { return false; } if (index > 6 || ((Primitive) other).index > 6) { return false; } return true; } @Override public ResolvedType resolve(World world) { if (this.world != world) { throw new IllegalStateException(); } this.world = world; return super.resolve(world); } @Override public final boolean needsNoConversionFrom(ResolvedType other) { if (!other.isPrimitiveType()) { return false; } return noConvertTable[((Primitive) other).index][index]; } private static final boolean[][] assignTable = {// to: B C D F I J S V Z // from { true, true, true, true, true, true, true, false, false }, // B { false, true, true, true, true, true, false, false, false }, // C { false, false, true, false, false, false, false, false, false }, // D { false, false, true, true, false, false, false, false, false }, // F { false, false, true, true, true, true, false, false, false }, // I { false, false, true, true, false, true, false, false, false }, // J { false, false, true, true, true, true, true, false, false }, // S { false, false, false, false, false, false, false, true, false }, // V { false, false, false, false, false, false, false, false, true }, // Z }; private static final boolean[][] noConvertTable = {// to: B C D F I J S // V Z from { true, true, false, false, true, false, true, false, false }, // B { false, true, false, false, true, false, false, false, false }, // C { false, false, true, false, false, false, false, false, false }, // D { false, false, false, true, false, false, false, false, false }, // F { false, false, false, false, true, false, false, false, false }, // I { false, false, false, false, false, true, false, false, false }, // J { false, false, false, false, true, false, true, false, false }, // S { false, false, false, false, false, false, false, true, false }, // V { false, false, false, false, false, false, false, false, true }, // Z }; // ---- @Override public final ResolvedMember[] getDeclaredFields() { return ResolvedMember.NONE; } @Override public final ResolvedMember[] getDeclaredMethods() { return ResolvedMember.NONE; } @Override public final ResolvedType[] getDeclaredInterfaces() { return ResolvedType.NONE; } @Override public final ResolvedMember[] getDeclaredPointcuts() { return ResolvedMember.NONE; } @Override public final ResolvedType getSuperclass() { return null; } @Override public ISourceContext getSourceContext() { return null; } } static class Missing extends ResolvedType { Missing() { super(MISSING_NAME, null); } // public final String toString() { // return "<missing>"; // } @Override public final String getName() { return MISSING_NAME; } @Override public final boolean isMissing() { return true; } public boolean hasAnnotation(UnresolvedType ofType) { return false; } @Override public final ResolvedMember[] getDeclaredFields() { return ResolvedMember.NONE; } @Override public final ResolvedMember[] getDeclaredMethods() { return ResolvedMember.NONE; } @Override public final ResolvedType[] getDeclaredInterfaces() { return ResolvedType.NONE; } @Override public final ResolvedMember[] getDeclaredPointcuts() { return ResolvedMember.NONE; } @Override public final ResolvedType getSuperclass() { return null; } @Override public final int getModifiers() { return 0; } @Override public final boolean isAssignableFrom(ResolvedType other) { return false; } @Override public final boolean isAssignableFrom(ResolvedType other, boolean allowMissing) { return false; } @Override public final boolean isCoerceableFrom(ResolvedType other) { return false; } @Override public boolean needsNoConversionFrom(ResolvedType other) { return false; } @Override public ISourceContext getSourceContext() { return null; } } /** * Look up a member, takes into account any ITDs on this type. return null if not found */ public ResolvedMember lookupMemberNoSupers(Member member) { ResolvedMember ret = lookupDirectlyDeclaredMemberNoSupers(member); if (ret == null && interTypeMungers != null) { for (ConcreteTypeMunger tm : interTypeMungers) { if (matches(tm.getSignature(), member)) { return tm.getSignature(); } } } return ret; } public ResolvedMember lookupMemberWithSupersAndITDs(Member member) { ResolvedMember ret = lookupMemberNoSupers(member); if (ret != null) { return ret; } ResolvedType supert = getSuperclass(); while (ret == null && supert != null) { ret = supert.lookupMemberNoSupers(member); if (ret == null) { supert = supert.getSuperclass(); } } return ret; } /** * as lookupMemberNoSupers, but does not include ITDs * * @param member * @return */ public ResolvedMember lookupDirectlyDeclaredMemberNoSupers(Member member) { ResolvedMember ret; if (member.getKind() == Member.FIELD) { ret = lookupMember(member, getDeclaredFields()); } else { // assert member.getKind() == Member.METHOD || member.getKind() == // Member.CONSTRUCTOR ret = lookupMember(member, getDeclaredMethods()); } return ret; } /** * This lookup has specialized behaviour - a null result tells the EclipseTypeMunger that it should make a default * implementation of a method on this type. * * @param member * @return */ public ResolvedMember lookupMemberIncludingITDsOnInterfaces(Member member) { return lookupMemberIncludingITDsOnInterfaces(member, this); } private ResolvedMember lookupMemberIncludingITDsOnInterfaces(Member member, ResolvedType onType) { ResolvedMember ret = onType.lookupMemberNoSupers(member); if (ret != null) { return ret; } else { ResolvedType superType = onType.getSuperclass(); if (superType != null) { ret = lookupMemberIncludingITDsOnInterfaces(member, superType); } if (ret == null) { // try interfaces then, but only ITDs now... ResolvedType[] superInterfaces = onType.getDeclaredInterfaces(); for (int i = 0; i < superInterfaces.length; i++) { ret = superInterfaces[i].lookupMethodInITDs(member); if (ret != null) { return ret; } } } } return ret; } protected List<ConcreteTypeMunger> interTypeMungers = new ArrayList<ConcreteTypeMunger>(); public List<ConcreteTypeMunger> getInterTypeMungers() { return interTypeMungers; } public List<ConcreteTypeMunger> getInterTypeParentMungers() { List<ConcreteTypeMunger> l = new ArrayList<ConcreteTypeMunger>(); for (ConcreteTypeMunger element : interTypeMungers) { if (element.getMunger() instanceof NewParentTypeMunger) { l.add(element); } } return l; } /** * ??? This method is O(N*M) where N = number of methods and M is number of inter-type declarations in my super */ public List<ConcreteTypeMunger> getInterTypeMungersIncludingSupers() { ArrayList<ConcreteTypeMunger> ret = new ArrayList<ConcreteTypeMunger>(); collectInterTypeMungers(ret); return ret; } public List<ConcreteTypeMunger> getInterTypeParentMungersIncludingSupers() { ArrayList<ConcreteTypeMunger> ret = new ArrayList<ConcreteTypeMunger>(); collectInterTypeParentMungers(ret); return ret; } private void collectInterTypeParentMungers(List<ConcreteTypeMunger> collector) { for (Iterator<ResolvedType> iter = getDirectSupertypes(); iter.hasNext();) { ResolvedType superType = iter.next(); superType.collectInterTypeParentMungers(collector); } collector.addAll(getInterTypeParentMungers()); } protected void collectInterTypeMungers(List<ConcreteTypeMunger> collector) { for (Iterator<ResolvedType> iter = getDirectSupertypes(); iter.hasNext();) { ResolvedType superType = iter.next(); if (superType == null) { throw new BCException("UnexpectedProblem: a supertype in the hierarchy for " + this.getName() + " is null"); } superType.collectInterTypeMungers(collector); } outer: for (Iterator<ConcreteTypeMunger> iter1 = collector.iterator(); iter1.hasNext();) { ConcreteTypeMunger superMunger = iter1.next(); if (superMunger.getSignature() == null) { continue; } if (!superMunger.getSignature().isAbstract()) { continue; } for (ConcreteTypeMunger myMunger : getInterTypeMungers()) { if (conflictingSignature(myMunger.getSignature(), superMunger.getSignature())) { iter1.remove(); continue outer; } } if (!superMunger.getSignature().isPublic()) { continue; } for (Iterator<ResolvedMember> iter = getMethods(true, true); iter.hasNext();) { ResolvedMember method = iter.next(); if (conflictingSignature(method, superMunger.getSignature())) { iter1.remove(); continue outer; } } } collector.addAll(getInterTypeMungers()); } /** * Check: 1) That we don't have any abstract type mungers unless this type is abstract. 2) That an abstract ITDM on an interface * is declared public. (Compiler limitation) (PR70794) */ public void checkInterTypeMungers() { if (isAbstract()) { return; } boolean itdProblem = false; for (ConcreteTypeMunger munger : getInterTypeMungersIncludingSupers()) { itdProblem = checkAbstractDeclaration(munger) || itdProblem; // Rule 2 } if (itdProblem) { return; // If the rules above are broken, return right now } for (ConcreteTypeMunger munger : getInterTypeMungersIncludingSupers()) { if (munger.getSignature() != null && munger.getSignature().isAbstract()) { // Rule 1 if (munger.getMunger().getKind() == ResolvedTypeMunger.MethodDelegate2) { // ignore for @AJ ITD as munger.getSignature() is the // interface method hence abstract } else { world.getMessageHandler() .handleMessage( new Message("must implement abstract inter-type declaration: " + munger.getSignature(), "", IMessage.ERROR, getSourceLocation(), null, new ISourceLocation[] { getMungerLocation(munger) })); } } } } /** * See PR70794. This method checks that if an abstract inter-type method declaration is made on an interface then it must also * be public. This is a compiler limitation that could be made to work in the future (if someone provides a worthwhile usecase) * * @return indicates if the munger failed the check */ private boolean checkAbstractDeclaration(ConcreteTypeMunger munger) { if (munger.getMunger() != null && (munger.getMunger() instanceof NewMethodTypeMunger)) { ResolvedMember itdMember = munger.getSignature(); ResolvedType onType = itdMember.getDeclaringType().resolve(world); if (onType.isInterface() && itdMember.isAbstract() && !itdMember.isPublic()) { world.getMessageHandler().handleMessage( new Message(WeaverMessages.format(WeaverMessages.ITD_ABSTRACT_MUST_BE_PUBLIC_ON_INTERFACE, munger.getSignature(), onType), "", Message.ERROR, getSourceLocation(), null, new ISourceLocation[] { getMungerLocation(munger) })); return true; } } return false; } /** * Get a source location for the munger. Until intertype mungers remember where they came from, the source location for the * munger itself is null. In these cases use the source location for the aspect containing the ITD. */ private ISourceLocation getMungerLocation(ConcreteTypeMunger munger) { ISourceLocation sloc = munger.getSourceLocation(); if (sloc == null) { sloc = munger.getAspectType().getSourceLocation(); } return sloc; } /** * Returns a ResolvedType object representing the declaring type of this type, or null if this type does not represent a * non-package-level-type. * <p/> * <strong>Warning</strong>: This is guaranteed to work for all member types. For anonymous/local types, the only guarantee is * given in JLS 13.1, where it guarantees that if you call getDeclaringType() repeatedly, you will eventually get the top-level * class, but it does not say anything about classes in between. * * @return the declaring UnresolvedType object, or null. */ public ResolvedType getDeclaringType() { if (isArray()) { return null; } String name = getName(); int lastDollar = name.lastIndexOf('$'); while (lastDollar > 0) { // allow for classes starting '$' (pr120474) ResolvedType ret = world.resolve(UnresolvedType.forName(name.substring(0, lastDollar)), true); if (!ResolvedType.isMissing(ret)) { return ret; } lastDollar = name.lastIndexOf('$', lastDollar - 1); } return null; } public static boolean isVisible(int modifiers, ResolvedType targetType, ResolvedType fromType) { // System.err.println("mod: " + modifiers + ", " + targetType + " and " // + fromType); if (Modifier.isPublic(modifiers)) { return true; } else if (Modifier.isPrivate(modifiers)) { return targetType.getOutermostType().equals(fromType.getOutermostType()); } else if (Modifier.isProtected(modifiers)) { return samePackage(targetType, fromType) || targetType.isAssignableFrom(fromType); } else { // package-visible return samePackage(targetType, fromType); } } private static boolean samePackage(ResolvedType targetType, ResolvedType fromType) { String p1 = targetType.getPackageName(); String p2 = fromType.getPackageName(); if (p1 == null) { return p2 == null; } if (p2 == null) { return false; } return p1.equals(p2); } /** * Checks if the generic type for 'this' and the generic type for 'other' are the same - it can be passed raw or parameterized * versions and will just compare the underlying generic type. */ private boolean genericTypeEquals(ResolvedType other) { ResolvedType rt = other; if (rt.isParameterizedType() || rt.isRawType()) { rt.getGenericType(); } if (((isParameterizedType() || isRawType()) && getGenericType().equals(rt)) || (this.equals(other))) { return true; } return false; } /** * Look up the actual occurence of a particular type in the hierarchy for 'this' type. The input is going to be a generic type, * and the caller wants to know if it was used in its RAW or a PARAMETERIZED form in this hierarchy. * * returns null if it can't be found. */ public ResolvedType discoverActualOccurrenceOfTypeInHierarchy(ResolvedType lookingFor) { if (!lookingFor.isGenericType()) { throw new BCException("assertion failed: method should only be called with generic type, but " + lookingFor + " is " + lookingFor.typeKind); } if (this.equals(ResolvedType.OBJECT)) { return null; } if (genericTypeEquals(lookingFor)) { return this; } ResolvedType superT = getSuperclass(); if (superT.genericTypeEquals(lookingFor)) { return superT; } ResolvedType[] superIs = getDeclaredInterfaces(); for (int i = 0; i < superIs.length; i++) { ResolvedType superI = superIs[i]; if (superI.genericTypeEquals(lookingFor)) { return superI; } ResolvedType checkTheSuperI = superI.discoverActualOccurrenceOfTypeInHierarchy(lookingFor); if (checkTheSuperI != null) { return checkTheSuperI; } } return superT.discoverActualOccurrenceOfTypeInHierarchy(lookingFor); } /** * Called for all type mungers but only does something if they share type variables with a generic type which they target. When * this happens this routine will check for the target type in the target hierarchy and 'bind' any type parameters as * appropriate. For example, for the ITD "List<T> I<T>.x" against a type like this: "class A implements I<String>" this routine * will return a parameterized form of the ITD "List<String> I.x" */ public ConcreteTypeMunger fillInAnyTypeParameters(ConcreteTypeMunger munger) { boolean debug = false; ResolvedMember member = munger.getSignature(); if (munger.isTargetTypeParameterized()) { if (debug) { System.err.println("Processing attempted parameterization of " + munger + " targetting type " + this); } if (debug) { System.err.println(" This type is " + this + " (" + typeKind + ")"); } // need to tailor this munger instance for the particular target... if (debug) { System.err.println(" Signature that needs parameterizing: " + member); } // Retrieve the generic type ResolvedType onTypeResolved = world.resolve(member.getDeclaringType()); ResolvedType onType = onTypeResolved.getGenericType(); if (onType == null) { // The target is not generic getWorld().getMessageHandler().handleMessage( MessageUtil.error("The target type for the intertype declaration is not generic", munger.getSourceLocation())); return munger; } member.resolve(world); // Ensure all parts of the member are resolved if (debug) { System.err.println(" Actual target ontype: " + onType + " (" + onType.typeKind + ")"); } // quickly find the targettype in the type hierarchy for this type // (it will be either RAW or PARAMETERIZED) ResolvedType actualTarget = discoverActualOccurrenceOfTypeInHierarchy(onType); if (actualTarget == null) { throw new BCException("assertion failed: asked " + this + " for occurrence of " + onType + " in its hierarchy??"); } // only bind the tvars if its a parameterized type or the raw type // (in which case they collapse to bounds) - don't do it // for generic types ;) if (!actualTarget.isGenericType()) { if (debug) { System.err.println("Occurrence in " + this + " is actually " + actualTarget + " (" + actualTarget.typeKind + ")"); // parameterize the signature // ResolvedMember newOne = // member.parameterizedWith(actualTarget.getTypeParameters(), // onType,actualTarget.isParameterizedType()); } } // if (!actualTarget.isRawType()) munger = munger.parameterizedFor(actualTarget); if (debug) { System.err.println("New sig: " + munger.getSignature()); } if (debug) { System.err.println("====================================="); } } return munger; } /** * Add an intertype munger to this type. isDuringCompilation tells us if we should be checking for an error scenario where two * ITD fields are trying to use the same name. When this happens during compilation one of them is altered to get mangled name * but when it happens during weaving it is too late and we need to put out an error asking them to recompile. */ public void addInterTypeMunger(ConcreteTypeMunger munger, boolean isDuringCompilation) { ResolvedMember sig = munger.getSignature(); bits = (bits & ~MungersAnalyzed); // clear the bit - as the mungers have changed if (sig == null || munger.getMunger() == null || munger.getMunger().getKind() == ResolvedTypeMunger.PrivilegedAccess) { interTypeMungers.add(munger); return; } // ConcreteTypeMunger originalMunger = munger; // we will use the 'parameterized' ITD for all the comparisons but we // say the original // one passed in actually matched as it will be added to the intertype // member finder // for the target type. It is possible we only want to do this if a // generic type // is discovered and the tvar is collapsed to a bound? munger = fillInAnyTypeParameters(munger); sig = munger.getSignature(); // possibly changed when type parms filled in if (sig.getKind() == Member.METHOD) { // OPTIMIZE can this be sped up? if (clashesWithExistingMember(munger, getMethods(true, false))) { // ITDs checked below return; } if (this.isInterface()) { // OPTIMIZE this set of methods are always the same - must we keep creating them as a list? if (clashesWithExistingMember(munger, Arrays.asList(world.getCoreType(OBJECT).getDeclaredMethods()).iterator())) { return; } } } else if (sig.getKind() == Member.FIELD) { if (clashesWithExistingMember(munger, Arrays.asList(getDeclaredFields()).iterator())) { return; } // Cannot cope with two version '2' style mungers for the same field on the same type // Must error and request the user recompile at least one aspect with the // -Xset:itdStyle=1 option if (!isDuringCompilation) { ResolvedTypeMunger thisRealMunger = munger.getMunger(); if (thisRealMunger instanceof NewFieldTypeMunger) { NewFieldTypeMunger newFieldTypeMunger = (NewFieldTypeMunger) thisRealMunger; if (newFieldTypeMunger.version == NewFieldTypeMunger.VersionTwo) { String thisRealMungerSignatureName = newFieldTypeMunger.getSignature().getName(); for (ConcreteTypeMunger typeMunger : interTypeMungers) { if (typeMunger.getMunger() instanceof NewFieldTypeMunger) { if (typeMunger.getSignature().getKind() == Member.FIELD) { NewFieldTypeMunger existing = (NewFieldTypeMunger) typeMunger.getMunger(); if (existing.getSignature().getName().equals(thisRealMungerSignatureName) && existing.version == NewFieldTypeMunger.VersionTwo // this check ensures no problem for a clash with an ITD on an interface && existing.getSignature().getDeclaringType() .equals(newFieldTypeMunger.getSignature().getDeclaringType())) { // report error on the aspect StringBuffer sb = new StringBuffer(); sb.append("Cannot handle two aspects both attempting to use new style ITDs for the same named field "); sb.append("on the same target type. Please recompile at least one aspect with '-Xset:itdVersion=1'."); sb.append(" Aspects involved: " + munger.getAspectType().getName() + " and " + typeMunger.getAspectType().getName() + "."); sb.append(" Field is named '" + existing.getSignature().getName() + "'"); getWorld().getMessageHandler().handleMessage( new Message(sb.toString(), getSourceLocation(), true)); return; } } } } } } } } else { if (clashesWithExistingMember(munger, Arrays.asList(getDeclaredMethods()).iterator())) { return; } } boolean needsAdding =true; boolean needsToBeAddedEarlier =false; // now compare to existingMungers for (Iterator<ConcreteTypeMunger> i = interTypeMungers.iterator(); i.hasNext();) { ConcreteTypeMunger existingMunger = i.next(); boolean v2itds = munger.getSignature().getKind()== Member.FIELD && (munger.getMunger() instanceof NewFieldTypeMunger) && ((NewFieldTypeMunger)munger.getMunger()).version==NewFieldTypeMunger.VersionTwo; if (conflictingSignature(existingMunger.getSignature(), munger.getSignature(),v2itds)) { // System.err.println("match " + munger + " with " + existingMunger); if (isVisible(munger.getSignature().getModifiers(), munger.getAspectType(), existingMunger.getAspectType())) { // System.err.println(" is visible"); int c = compareMemberPrecedence(sig, existingMunger.getSignature()); if (c == 0) { c = getWorld().compareByPrecedenceAndHierarchy(munger.getAspectType(), existingMunger.getAspectType()); } // System.err.println(" compare: " + c); if (c < 0) { // the existing munger dominates the new munger checkLegalOverride(munger.getSignature(), existingMunger.getSignature(), 0x11, null); needsAdding = false; if (munger.getSignature().getKind()== Member.FIELD && munger.getSignature().getDeclaringType().resolve(world).isInterface() && ((NewFieldTypeMunger)munger.getMunger()).version==NewFieldTypeMunger.VersionTwo) { // still need to add it needsAdding=true; } break; } else if (c > 0) { // the new munger dominates the existing one checkLegalOverride(existingMunger.getSignature(), munger.getSignature(), 0x11, null); // i.remove(); if (existingMunger.getSignature().getKind()==Member.FIELD && existingMunger.getSignature().getDeclaringType().resolve(world).isInterface() && ((NewFieldTypeMunger)existingMunger.getMunger()).version==NewFieldTypeMunger.VersionTwo) { needsToBeAddedEarlier=true; } else { i.remove(); } break; } else { interTypeConflictError(munger, existingMunger); interTypeConflictError(existingMunger, munger); return; } } } } // System.err.println("adding: " + munger + " to " + this); // we are adding the parameterized form of the ITD to the list of // mungers. Within it, the munger knows the original declared // signature for the ITD so it can be retrieved. if (needsAdding) { if (!needsToBeAddedEarlier) { interTypeMungers.add(munger); } else { interTypeMungers.add(0,munger); } } } /** * Compare the type transformer with the existing members. A clash may not be an error (the ITD may be the 'default * implementation') so returning false is not always a sign of an error. * * @return true if there is a clash */ private boolean clashesWithExistingMember(ConcreteTypeMunger typeTransformer, Iterator<ResolvedMember> existingMembers) { ResolvedMember typeTransformerSignature = typeTransformer.getSignature(); // ResolvedType declaringAspectType = munger.getAspectType(); // if (declaringAspectType.isRawType()) declaringAspectType = // declaringAspectType.getGenericType(); // if (declaringAspectType.isGenericType()) { // // ResolvedType genericOnType = // getWorld().resolve(sig.getDeclaringType()).getGenericType(); // ConcreteTypeMunger ctm = // munger.parameterizedFor(discoverActualOccurrenceOfTypeInHierarchy // (genericOnType)); // sig = ctm.getSignature(); // possible sig change when type // } // if (munger.getMunger().hasTypeVariableAliases()) { // ResolvedType genericOnType = // getWorld().resolve(sig.getDeclaringType()).getGenericType(); // ConcreteTypeMunger ctm = // munger.parameterizedFor(discoverActualOccurrenceOfTypeInHierarchy( // genericOnType)); // sig = ctm.getSignature(); // possible sig change when type parameters // filled in // } ResolvedTypeMunger rtm = typeTransformer.getMunger(); boolean v2itds = true; if (rtm instanceof NewFieldTypeMunger && ((NewFieldTypeMunger)rtm).version==NewFieldTypeMunger.VersionOne) { v2itds = false; } while (existingMembers.hasNext()) { ResolvedMember existingMember = existingMembers.next(); // don't worry about clashing with bridge methods if (existingMember.isBridgeMethod()) { continue; } if (conflictingSignature(existingMember, typeTransformerSignature,v2itds)) { // System.err.println("conflict: existingMember=" + // existingMember + " typeMunger=" + munger); // System.err.println(munger.getSourceLocation() + ", " + // munger.getSignature() + ", " + // munger.getSignature().getSourceLocation()); if (isVisible(existingMember.getModifiers(), this, typeTransformer.getAspectType())) { int c = compareMemberPrecedence(typeTransformerSignature, existingMember); // System.err.println(" c: " + c); if (c < 0) { // existingMember dominates munger checkLegalOverride(typeTransformerSignature, existingMember, 0x10, typeTransformer.getAspectType()); return true; } else if (c > 0) { // munger dominates existingMember checkLegalOverride(existingMember, typeTransformerSignature, 0x01, typeTransformer.getAspectType()); // interTypeMungers.add(munger); // ??? might need list of these overridden abstracts continue; } else { // bridge methods can differ solely in return type. // FIXME this whole method seems very hokey - unaware of covariance/varargs/bridging - it // could do with a rewrite ! boolean sameReturnTypes = (existingMember.getReturnType().equals(typeTransformerSignature.getReturnType())); if (sameReturnTypes) { // pr206732 - if the existingMember is due to a // previous application of this same ITD (which can // happen if this is a binary type being brought in // from the aspectpath). The 'better' fix is // to recognize it is from the aspectpath at a // higher level and dont do this, but that is rather // more work. boolean isDuplicateOfPreviousITD = false; ResolvedType declaringRt = existingMember.getDeclaringType().resolve(world); WeaverStateInfo wsi = declaringRt.getWeaverState(); if (wsi != null) { List<ConcreteTypeMunger> mungersAffectingThisType = wsi.getTypeMungers(declaringRt); if (mungersAffectingThisType != null) { for (Iterator<ConcreteTypeMunger> iterator = mungersAffectingThisType.iterator(); iterator .hasNext() && !isDuplicateOfPreviousITD;) { ConcreteTypeMunger ctMunger = iterator.next(); // relatively crude check - is the ITD // for the same as the existingmember // and does it come // from the same aspect if (ctMunger.getSignature().equals(existingMember) && ctMunger.aspectType.equals(typeTransformer.getAspectType())) { isDuplicateOfPreviousITD = true; } } } } if (!isDuplicateOfPreviousITD) { // b275032 - this is OK if it is the default ctor and that default ctor was generated // at compile time, otherwise we cannot overwrite it if (!(typeTransformerSignature.getName().equals("<init>") && existingMember.isDefaultConstructor())) { String aspectName = typeTransformer.getAspectType().getName(); ISourceLocation typeTransformerLocation = typeTransformer.getSourceLocation(); ISourceLocation existingMemberLocation = existingMember.getSourceLocation(); String msg = WeaverMessages.format(WeaverMessages.ITD_MEMBER_CONFLICT, aspectName, existingMember); // this isn't quite right really... as I think the errors should only be recorded against // what is currently being processed or they may get lost or reported twice // report error on the aspect getWorld().getMessageHandler().handleMessage(new Message(msg, typeTransformerLocation, true)); // report error on the affected type, if we can if (existingMemberLocation != null) { getWorld().getMessageHandler() .handleMessage(new Message(msg, existingMemberLocation, true)); } return true; // clash - so ignore this itd } } } } } else if (isDuplicateMemberWithinTargetType(existingMember, this, typeTransformerSignature)) { getWorld().getMessageHandler().handleMessage( MessageUtil.error(WeaverMessages.format(WeaverMessages.ITD_MEMBER_CONFLICT, typeTransformer .getAspectType().getName(), existingMember), typeTransformer.getSourceLocation())); return true; } } } return false; } // we know that the member signature matches, but that the member in the // target type is not visible to the aspect. // this may still be disallowed if it would result in two members within the // same declaring type with the same // signature AND more than one of them is concrete AND they are both visible // within the target type. private boolean isDuplicateMemberWithinTargetType(ResolvedMember existingMember, ResolvedType targetType, ResolvedMember itdMember) { if ((existingMember.isAbstract() || itdMember.isAbstract())) { return false; } UnresolvedType declaringType = existingMember.getDeclaringType(); if (!targetType.equals(declaringType)) { return false; } // now have to test that itdMember is visible from targetType if (Modifier.isPrivate(itdMember.getModifiers())) { return false; } if (itdMember.isPublic()) { return true; } // must be in same package to be visible then... if (!targetType.getPackageName().equals(itdMember.getDeclaringType().getPackageName())) { return false; } // trying to put two members with the same signature into the exact same // type..., and both visible in that type. return true; } /** * @param transformerPosition which parameter is the type transformer (0x10 for first, 0x01 for second, 0x11 for both, 0x00 for * neither) * @param aspectType the declaring type of aspect defining the *first* type transformer * @return true if the override is legal note: calling showMessage with two locations issues TWO messages, not ONE message with * an additional source location. */ public boolean checkLegalOverride(ResolvedMember parent, ResolvedMember child, int transformerPosition, ResolvedType aspectType) { // System.err.println("check: " + child.getDeclaringType() + // " overrides " + parent.getDeclaringType()); if (Modifier.isFinal(parent.getModifiers())) { // If the ITD matching is occurring due to pulling in a BinaryTypeBinding then this check can incorrectly // signal an error because the ITD transformer being examined here will exactly match the member it added // during the first round of compilation. This situation can only occur if the ITD is on an interface whilst // the class is the top most implementor. If the ITD is on the same type that received it during compilation, // this method won't be called as the previous check for precedence level will return 0. if (transformerPosition == 0x10 && aspectType != null) { ResolvedType nonItdDeclaringType = child.getDeclaringType().resolve(world); WeaverStateInfo wsi = nonItdDeclaringType.getWeaverState(); if (wsi != null) { List<ConcreteTypeMunger> transformersOnThisType = wsi.getTypeMungers(nonItdDeclaringType); if (transformersOnThisType != null) { for (ConcreteTypeMunger transformer : transformersOnThisType) { // relatively crude check - is the ITD // for the same as the existingmember // and does it come // from the same aspect if (transformer.aspectType.equals(aspectType)) { if (parent.equalsApartFromDeclaringType(transformer.getSignature())) { return true; } } } } } } world.showMessage(Message.ERROR, WeaverMessages.format(WeaverMessages.CANT_OVERRIDE_FINAL_MEMBER, parent), child.getSourceLocation(), null); return false; } boolean incompatibleReturnTypes = false; // In 1.5 mode, allow for covariance on return type if (world.isInJava5Mode() && parent.getKind() == Member.METHOD) { // Look at the generic types when doing this comparison ResolvedType rtParentReturnType = parent.resolve(world).getGenericReturnType().resolve(world); ResolvedType rtChildReturnType = child.resolve(world).getGenericReturnType().resolve(world); incompatibleReturnTypes = !rtParentReturnType.isAssignableFrom(rtChildReturnType); // For debug, uncomment this bit and we'll repeat the check - stick // a breakpoint on the call // if (incompatibleReturnTypes) { // incompatibleReturnTypes = // !rtParentReturnType.isAssignableFrom(rtChildReturnType); // } } else { incompatibleReturnTypes = !parent.getReturnType().equals(child.getReturnType()); } if (incompatibleReturnTypes) { world.showMessage(IMessage.ERROR, WeaverMessages.format(WeaverMessages.ITD_RETURN_TYPE_MISMATCH, parent, child), child.getSourceLocation(), parent.getSourceLocation()); return false; } if (parent.getKind() == Member.POINTCUT) { UnresolvedType[] pTypes = parent.getParameterTypes(); UnresolvedType[] cTypes = child.getParameterTypes(); if (!Arrays.equals(pTypes, cTypes)) { world.showMessage(IMessage.ERROR, WeaverMessages.format(WeaverMessages.ITD_PARAM_TYPE_MISMATCH, parent, child), child.getSourceLocation(), parent.getSourceLocation()); return false; } } // System.err.println("check: " + child.getModifiers() + // " more visible " + parent.getModifiers()); if (isMoreVisible(parent.getModifiers(), child.getModifiers())) { world.showMessage(IMessage.ERROR, WeaverMessages.format(WeaverMessages.ITD_VISIBILITY_REDUCTION, parent, child), child.getSourceLocation(), parent.getSourceLocation()); return false; } // check declared exceptions ResolvedType[] childExceptions = world.resolve(child.getExceptions()); ResolvedType[] parentExceptions = world.resolve(parent.getExceptions()); ResolvedType runtimeException = world.resolve("java.lang.RuntimeException"); ResolvedType error = world.resolve("java.lang.Error"); outer: for (int i = 0, leni = childExceptions.length; i < leni; i++) { // System.err.println("checking: " + childExceptions[i]); if (runtimeException.isAssignableFrom(childExceptions[i])) { continue; } if (error.isAssignableFrom(childExceptions[i])) { continue; } for (int j = 0, lenj = parentExceptions.length; j < lenj; j++) { if (parentExceptions[j].isAssignableFrom(childExceptions[i])) { continue outer; } } // this message is now better handled my MethodVerifier in JDT core. // world.showMessage(IMessage.ERROR, // WeaverMessages.format(WeaverMessages.ITD_DOESNT_THROW, // childExceptions[i].getName()), // child.getSourceLocation(), null); return false; } boolean parentStatic = Modifier.isStatic(parent.getModifiers()); boolean childStatic = Modifier.isStatic(child.getModifiers()); if (parentStatic && !childStatic) { world.showMessage(IMessage.ERROR, WeaverMessages.format(WeaverMessages.ITD_OVERRIDDEN_STATIC, child, parent), child.getSourceLocation(), null); return false; } else if (childStatic && !parentStatic) { world.showMessage(IMessage.ERROR, WeaverMessages.format(WeaverMessages.ITD_OVERIDDING_STATIC, child, parent), child.getSourceLocation(), null); return false; } return true; } private int compareMemberPrecedence(ResolvedMember m1, ResolvedMember m2) { // if (!m1.getReturnType().equals(m2.getReturnType())) return 0; // need to allow for the special case of 'clone' - which is like // abstract but is // not marked abstract. The code below this next line seems to make // assumptions // about what will have gotten through the compiler based on the normal // java rules. clone goes against these... if (Modifier.isProtected(m2.getModifiers()) && m2.getName().charAt(0) == 'c') { UnresolvedType declaring = m2.getDeclaringType(); if (declaring != null) { if (declaring.getName().equals("java.lang.Object") && m2.getName().equals("clone")) { return +1; } } } if (Modifier.isAbstract(m1.getModifiers())) { return -1; } if (Modifier.isAbstract(m2.getModifiers())) { return +1; } if (m1.getDeclaringType().equals(m2.getDeclaringType())) { return 0; } ResolvedType t1 = m1.getDeclaringType().resolve(world); ResolvedType t2 = m2.getDeclaringType().resolve(world); if (t1.isAssignableFrom(t2)) { return -1; } if (t2.isAssignableFrom(t1)) { return +1; } return 0; } public static boolean isMoreVisible(int m1, int m2) { if (Modifier.isPrivate(m1)) { return false; } if (isPackage(m1)) { return Modifier.isPrivate(m2); } if (Modifier.isProtected(m1)) { return /* private package */(Modifier.isPrivate(m2) || isPackage(m2)); } if (Modifier.isPublic(m1)) { return /* private package protected */!Modifier.isPublic(m2); } throw new RuntimeException("bad modifier: " + m1); } private static boolean isPackage(int i) { return (0 == (i & (Modifier.PUBLIC | Modifier.PRIVATE | Modifier.PROTECTED))); } private void interTypeConflictError(ConcreteTypeMunger m1, ConcreteTypeMunger m2) { // XXX this works only if we ignore separate compilation issues // XXX dual errors possible if (this instanceof BcelObjectType) return; /* * if (m1.getMunger().getKind() == ResolvedTypeMunger.Field && m2.getMunger().getKind() == ResolvedTypeMunger.Field) { // if * *exactly* the same, it's ok return true; } */ // System.err.println("conflict at " + m2.getSourceLocation()); getWorld().showMessage( IMessage.ERROR, WeaverMessages.format(WeaverMessages.ITD_CONFLICT, m1.getAspectType().getName(), m2.getSignature(), m2 .getAspectType().getName()), m2.getSourceLocation(), getSourceLocation()); // return false; } public ResolvedMember lookupSyntheticMember(Member member) { // ??? horribly inefficient // for (Iterator i = // System.err.println("lookup " + member + " in " + interTypeMungers); for (ConcreteTypeMunger m : interTypeMungers) { ResolvedMember ret = m.getMatchingSyntheticMember(member); if (ret != null) { // System.err.println(" found: " + ret); return ret; } } // Handling members for the new array join point if (world.isJoinpointArrayConstructionEnabled() && this.isArray()) { if (member.getKind() == Member.CONSTRUCTOR) { ResolvedMemberImpl ret = new ResolvedMemberImpl(Member.CONSTRUCTOR, this, Modifier.PUBLIC, UnresolvedType.VOID, "<init>", world.resolve(member.getParameterTypes())); // Give the parameters names - they are going to be the dimensions uses to build the array (dim0 > dimN) int count = ret.getParameterTypes().length; String[] paramNames = new String[count]; for (int i = 0; i < count; i++) { paramNames[i] = new StringBuffer("dim").append(i).toString(); } ret.setParameterNames(paramNames); return ret; } } // if (this.getSuperclass() != ResolvedType.OBJECT && // this.getSuperclass() != null) { // return getSuperclass().lookupSyntheticMember(member); // } return null; } static class SuperClassWalker implements Iterator<ResolvedType> { private ResolvedType curr; private SuperInterfaceWalker iwalker; private boolean wantGenerics; public SuperClassWalker(ResolvedType type, SuperInterfaceWalker iwalker, boolean genericsAware) { this.curr = type; this.iwalker = iwalker; this.wantGenerics = genericsAware; } public boolean hasNext() { return curr != null; } public ResolvedType next() { ResolvedType ret = curr; if (!wantGenerics && ret.isParameterizedOrGenericType()) { ret = ret.getRawType(); } iwalker.push(ret); // tell the interface walker about another class whose interfaces need visiting curr = curr.getSuperclass(); return ret; } public void remove() { throw new UnsupportedOperationException(); } } static class SuperInterfaceWalker implements Iterator<ResolvedType> { private Getter<ResolvedType, ResolvedType> ifaceGetter; Iterator<ResolvedType> delegate = null; public Queue<ResolvedType> toPersue = new LinkedList<ResolvedType>(); public Set<ResolvedType> visited = new HashSet<ResolvedType>(); SuperInterfaceWalker(Iterators.Getter<ResolvedType, ResolvedType> ifaceGetter) { this.ifaceGetter = ifaceGetter; } SuperInterfaceWalker(Iterators.Getter<ResolvedType, ResolvedType> ifaceGetter, ResolvedType interfaceType) { this.ifaceGetter = ifaceGetter; this.delegate = Iterators.one(interfaceType); } public boolean hasNext() { if (delegate == null || !delegate.hasNext()) { // either we set it up or we have run out, is there anything else to look at? if (toPersue.isEmpty()) { return false; } do { ResolvedType next = toPersue.remove(); visited.add(next); delegate = ifaceGetter.get(next); // retrieve interfaces from a class or another interface } while (!delegate.hasNext() && !toPersue.isEmpty()); } return delegate.hasNext(); } public void push(ResolvedType ret) { toPersue.add(ret); } public ResolvedType next() { ResolvedType next = delegate.next(); // BUG should check for generics and erase? // if (!visited.contains(next)) { // visited.add(next); if (visited.add(next)) { toPersue.add(next); // pushes on interfaces already visited? } return next; } public void remove() { throw new UnsupportedOperationException(); } } public void clearInterTypeMungers() { if (isRawType()) { ResolvedType genericType = getGenericType(); if (genericType.isRawType()) { // ERROR SITUATION: PR341926 // For some reason the raw type is pointing to another raw form (possibly itself) System.err.println("DebugFor341926: Type " + this.getName() + " has an incorrect generic form"); } else { genericType.clearInterTypeMungers(); } } // interTypeMungers.clear(); // BUG? Why can't this be clear() instead: 293620 c6 interTypeMungers = new ArrayList<ConcreteTypeMunger>(); } public boolean isTopmostImplementor(ResolvedType interfaceType) { boolean b = true; if (isInterface()) { b = false; } else if (!interfaceType.isAssignableFrom(this, true)) { b = false; } else { ResolvedType superclass = this.getSuperclass(); if (superclass.isMissing()) { b = true; // we don't know anything about supertype, and it can't be exposed to weaver } else if (interfaceType.isAssignableFrom(superclass, true)) { // check that I'm truly the topmost implementor b = false; } } // System.out.println("is " + getName() + " topmostimplementor of " + interfaceType + "? " + b); return b; } public ResolvedType getTopmostImplementor(ResolvedType interfaceType) { if (isInterface()) { return null; } if (!interfaceType.isAssignableFrom(this)) { return null; } // Check if my super class is an implementor? ResolvedType higherType = this.getSuperclass().getTopmostImplementor(interfaceType); if (higherType != null) { return higherType; } return this; } public List<ResolvedMember> getExposedPointcuts() { List<ResolvedMember> ret = new ArrayList<ResolvedMember>(); if (getSuperclass() != null) { ret.addAll(getSuperclass().getExposedPointcuts()); } for (ResolvedType type : getDeclaredInterfaces()) { addPointcutsResolvingConflicts(ret, Arrays.asList(type.getDeclaredPointcuts()), false); } addPointcutsResolvingConflicts(ret, Arrays.asList(getDeclaredPointcuts()), true); for (ResolvedMember member : ret) { ResolvedPointcutDefinition inherited = (ResolvedPointcutDefinition) member; if (inherited != null && inherited.isAbstract()) { if (!this.isAbstract()) { getWorld().showMessage(IMessage.ERROR, WeaverMessages.format(WeaverMessages.POINCUT_NOT_CONCRETE, inherited, this.getName()), inherited.getSourceLocation(), this.getSourceLocation()); } } } return ret; } private void addPointcutsResolvingConflicts(List<ResolvedMember> acc, List<ResolvedMember> added, boolean isOverriding) { for (Iterator<ResolvedMember> i = added.iterator(); i.hasNext();) { ResolvedPointcutDefinition toAdd = (ResolvedPointcutDefinition) i.next(); for (Iterator<ResolvedMember> j = acc.iterator(); j.hasNext();) { ResolvedPointcutDefinition existing = (ResolvedPointcutDefinition) j.next(); if (toAdd == null || existing == null || existing == toAdd) { continue; } UnresolvedType pointcutDeclaringTypeUT = existing.getDeclaringType(); if (pointcutDeclaringTypeUT != null) { ResolvedType pointcutDeclaringType = pointcutDeclaringTypeUT.resolve(getWorld()); if (!isVisible(existing.getModifiers(), pointcutDeclaringType, this)) { // if they intended to override it but it is not visible, // give them a nicer message if (existing.isAbstract() && conflictingSignature(existing, toAdd)) { getWorld().showMessage( IMessage.ERROR, WeaverMessages.format(WeaverMessages.POINTCUT_NOT_VISIBLE, existing.getDeclaringType() .getName() + "." + existing.getName() + "()", this.getName()), toAdd.getSourceLocation(), null); j.remove(); } continue; } } if (conflictingSignature(existing, toAdd)) { if (isOverriding) { checkLegalOverride(existing, toAdd, 0x00, null); j.remove(); } else { getWorld().showMessage( IMessage.ERROR, WeaverMessages.format(WeaverMessages.CONFLICTING_INHERITED_POINTCUTS, this.getName() + toAdd.getSignature()), existing.getSourceLocation(), toAdd.getSourceLocation()); j.remove(); } } } acc.add(toAdd); } } public ISourceLocation getSourceLocation() { return null; } public boolean isExposedToWeaver() { return false; } public WeaverStateInfo getWeaverState() { return null; } /** * Overridden by ReferenceType to return a sensible answer for parameterized and raw types. * * @return */ public ReferenceType getGenericType() { // if (!(isParameterizedType() || isRawType())) // throw new BCException("The type " + getBaseName() + " is not parameterized or raw - it has no generic type"); return null; } @Override public ResolvedType getRawType() { return super.getRawType().resolve(world); } public ResolvedType parameterizedWith(UnresolvedType[] typeParameters) { if (!(isGenericType() || isParameterizedType())) { return this; } return TypeFactory.createParameterizedType(this.getGenericType(), typeParameters, getWorld()); } /** * Iff I am a parameterized type, and any of my parameters are type variable references (or nested parameterized types), * return a version with those type parameters replaced in accordance with the passed bindings. */ @Override public UnresolvedType parameterize(Map<String, UnresolvedType> typeBindings) { if (!isParameterizedType()) { // throw new IllegalStateException("Can't parameterize a type that is not a parameterized type"); return this; } boolean workToDo = false; for (int i = 0; i < typeParameters.length; i++) { if (typeParameters[i].isTypeVariableReference() || (typeParameters[i] instanceof BoundedReferenceType) || typeParameters[i].isParameterizedType()) { workToDo = true; } } if (!workToDo) { return this; } else { UnresolvedType[] newTypeParams = new UnresolvedType[typeParameters.length]; for (int i = 0; i < newTypeParams.length; i++) { newTypeParams[i] = typeParameters[i]; if (newTypeParams[i].isTypeVariableReference()) { TypeVariableReferenceType tvrt = (TypeVariableReferenceType) newTypeParams[i]; UnresolvedType binding = typeBindings.get(tvrt.getTypeVariable().getName()); if (binding != null) { newTypeParams[i] = binding; } } else if (newTypeParams[i] instanceof BoundedReferenceType) { BoundedReferenceType brType = (BoundedReferenceType) newTypeParams[i]; newTypeParams[i] = brType.parameterize(typeBindings); // brType.parameterize(typeBindings) } else if (newTypeParams[i].isParameterizedType()) { newTypeParams[i] = newTypeParams[i].parameterize(typeBindings); } } return TypeFactory.createParameterizedType(getGenericType(), newTypeParams, getWorld()); } } // public boolean hasParameterizedSuperType() { // getParameterizedSuperTypes(); // return parameterizedSuperTypes.length > 0; // } // public boolean hasGenericSuperType() { // ResolvedType[] superTypes = getDeclaredInterfaces(); // for (int i = 0; i < superTypes.length; i++) { // if (superTypes[i].isGenericType()) // return true; // } // return false; // } // private ResolvedType[] parameterizedSuperTypes = null; /** * Similar to the above method, but accumulates the super types * * @return */ // public ResolvedType[] getParameterizedSuperTypes() { // if (parameterizedSuperTypes != null) // return parameterizedSuperTypes; // List accumulatedTypes = new ArrayList(); // accumulateParameterizedSuperTypes(this, accumulatedTypes); // ResolvedType[] ret = new ResolvedType[accumulatedTypes.size()]; // parameterizedSuperTypes = (ResolvedType[]) accumulatedTypes.toArray(ret); // return parameterizedSuperTypes; // } // private void accumulateParameterizedSuperTypes(ResolvedType forType, List // parameterizedTypeList) { // if (forType.isParameterizedType()) { // parameterizedTypeList.add(forType); // } // if (forType.getSuperclass() != null) { // accumulateParameterizedSuperTypes(forType.getSuperclass(), // parameterizedTypeList); // } // ResolvedType[] interfaces = forType.getDeclaredInterfaces(); // for (int i = 0; i < interfaces.length; i++) { // accumulateParameterizedSuperTypes(interfaces[i], parameterizedTypeList); // } // } /** * @return true if assignable to java.lang.Exception */ public boolean isException() { return (world.getCoreType(UnresolvedType.JL_EXCEPTION).isAssignableFrom(this)); } /** * @return true if it is an exception and it is a checked one, false otherwise. */ public boolean isCheckedException() { if (!isException()) { return false; } if (world.getCoreType(UnresolvedType.RUNTIME_EXCEPTION).isAssignableFrom(this)) { return false; } return true; } /** * Determines if variables of this type could be assigned values of another with lots of help. java.lang.Object is convertable * from all types. A primitive type is convertable from X iff it's assignable from X. A reference type is convertable from X iff * it's coerceable from X. In other words, X isConvertableFrom Y iff the compiler thinks that _some_ value of Y could be * assignable to a variable of type X without loss of precision. * * @param other the other type * @param world the {@link World} in which the possible assignment should be checked. * @return true iff variables of this type could be assigned values of other with possible conversion */ public final boolean isConvertableFrom(ResolvedType other) { // // version from TypeX // if (this.equals(OBJECT)) return true; // if (this.isPrimitiveType() || other.isPrimitiveType()) return // this.isAssignableFrom(other); // return this.isCoerceableFrom(other); // // version from ResolvedTypeX if (this.equals(OBJECT)) { return true; } if (world.isInJava5Mode()) { if (this.isPrimitiveType() ^ other.isPrimitiveType()) { // If one is // primitive // and the // other // isnt if (validBoxing.contains(this.getSignature() + other.getSignature())) { return true; } } } if (this.isPrimitiveType() || other.isPrimitiveType()) { return this.isAssignableFrom(other); } return this.isCoerceableFrom(other); } /** * Determines if the variables of this type could be assigned values of another type without casting. This still allows for * assignment conversion as per JLS 2ed 5.2. For object types, this means supertypeOrEqual(THIS, OTHER). * * @param other the other type * @param world the {@link World} in which the possible assignment should be checked. * @return true iff variables of this type could be assigned values of other without casting * @throws NullPointerException if other is null */ public abstract boolean isAssignableFrom(ResolvedType other); public abstract boolean isAssignableFrom(ResolvedType other, boolean allowMissing); /** * Determines if values of another type could possibly be cast to this type. The rules followed are from JLS 2ed 5.5, * "Casting Conversion". * <p/> * <p> * This method should be commutative, i.e., for all UnresolvedType a, b and all World w: * <p/> * <blockquote> * * <pre> * a.isCoerceableFrom(b, w) == b.isCoerceableFrom(a, w) * </pre> * * </blockquote> * * @param other the other type * @param world the {@link World} in which the possible coersion should be checked. * @return true iff values of other could possibly be cast to this type. * @throws NullPointerException if other is null. */ public abstract boolean isCoerceableFrom(ResolvedType other); public boolean needsNoConversionFrom(ResolvedType o) { return isAssignableFrom(o); } public String getSignatureForAttribute() { return signature; // Assume if this is being called that it is for a // simple type (eg. void, int, etc) } private FuzzyBoolean parameterizedWithTypeVariable = FuzzyBoolean.MAYBE; /** * return true if the parameterization of this type includes a member type variable. Member type variables occur in generic * methods/ctors. */ public boolean isParameterizedWithTypeVariable() { // MAYBE means we haven't worked it out yet... if (parameterizedWithTypeVariable == FuzzyBoolean.MAYBE) { // if there are no type parameters then we cant be... if (typeParameters == null || typeParameters.length == 0) { parameterizedWithTypeVariable = FuzzyBoolean.NO; return false; } for (int i = 0; i < typeParameters.length; i++) { ResolvedType aType = (ResolvedType) typeParameters[i]; if (aType.isTypeVariableReference() // Changed according to the problems covered in bug 222648 // Don't care what kind of type variable - the fact that there // is one // at all means we can't risk caching it against we get confused // later // by another variation of the parameterization that just // happens to // use the same type variable name // assume the worst - if its definetly not a type declared one, // it could be anything // && ((TypeVariableReference)aType).getTypeVariable(). // getDeclaringElementKind()!=TypeVariable.TYPE ) { parameterizedWithTypeVariable = FuzzyBoolean.YES; return true; } if (aType.isParameterizedType()) { boolean b = aType.isParameterizedWithTypeVariable(); if (b) { parameterizedWithTypeVariable = FuzzyBoolean.YES; return true; } } if (aType.isGenericWildcard()) { BoundedReferenceType boundedRT = (BoundedReferenceType) aType; if (boundedRT.isExtends()) { boolean b = false; UnresolvedType upperBound = boundedRT.getUpperBound(); if (upperBound.isParameterizedType()) { b = ((ResolvedType) upperBound).isParameterizedWithTypeVariable(); } else if (upperBound.isTypeVariableReference() && ((TypeVariableReference) upperBound).getTypeVariable().getDeclaringElementKind() == TypeVariable.METHOD) { b = true; } if (b) { parameterizedWithTypeVariable = FuzzyBoolean.YES; return true; } // FIXME asc need to check additional interface bounds } if (boundedRT.isSuper()) { boolean b = false; UnresolvedType lowerBound = boundedRT.getLowerBound(); if (lowerBound.isParameterizedType()) { b = ((ResolvedType) lowerBound).isParameterizedWithTypeVariable(); } else if (lowerBound.isTypeVariableReference() && ((TypeVariableReference) lowerBound).getTypeVariable().getDeclaringElementKind() == TypeVariable.METHOD) { b = true; } if (b) { parameterizedWithTypeVariable = FuzzyBoolean.YES; return true; } } } } parameterizedWithTypeVariable = FuzzyBoolean.NO; } return parameterizedWithTypeVariable.alwaysTrue(); } protected boolean ajMembersNeedParameterization() { if (isParameterizedType()) { return true; } ResolvedType superclass = getSuperclass(); if (superclass != null && !superclass.isMissing()) { return superclass.ajMembersNeedParameterization(); } return false; } protected Map<String, UnresolvedType> getAjMemberParameterizationMap() { Map<String, UnresolvedType> myMap = getMemberParameterizationMap(); if (myMap.isEmpty()) { // might extend a parameterized aspect that we also need to // consider... if (getSuperclass() != null) { return getSuperclass().getAjMemberParameterizationMap(); } } return myMap; } public void setBinaryPath(String binaryPath) { this.binaryPath = binaryPath; } /** * Returns the path to the jar or class file from which this binary aspect came or null if not a binary aspect */ public String getBinaryPath() { return binaryPath; } /** * Undo any temporary modifications to the type (for example it may be holding annotations temporarily whilst some matching is * occurring - These annotations will be added properly during weaving but sometimes for type completion they need to be held * here for a while). */ public void ensureConsistent() { // Nothing to do for anything except a ReferenceType } /** * For an annotation type, this will return if it is marked with @Inherited */ public boolean isInheritedAnnotation() { ensureAnnotationBitsInitialized(); return (bits & AnnotationMarkedInherited) != 0; } /* * Setup the bitflags if they have not already been done. */ private void ensureAnnotationBitsInitialized() { if ((bits & AnnotationBitsInitialized) == 0) { bits |= AnnotationBitsInitialized; // Is it marked @Inherited? if (hasAnnotation(UnresolvedType.AT_INHERITED)) { bits |= AnnotationMarkedInherited; } } } private boolean hasNewParentMungers() { if ((bits & MungersAnalyzed) == 0) { bits |= MungersAnalyzed; for (ConcreteTypeMunger munger : interTypeMungers) { ResolvedTypeMunger resolvedTypeMunger = munger.getMunger(); if (resolvedTypeMunger != null && resolvedTypeMunger.getKind() == ResolvedTypeMunger.Parent) { bits |= HasParentMunger; } } } return (bits & HasParentMunger) != 0; } public void tagAsTypeHierarchyComplete() { bits |= TypeHierarchyCompleteBit; } public boolean isTypeHierarchyComplete() { return (bits & TypeHierarchyCompleteBit) != 0; } /** * return the weaver version used to build this type - defaults to the most recent version unless discovered otherwise. * * @return the (major) version, {@link WeaverVersionInfo} */ public int getCompilerVersion() { return WeaverVersionInfo.getCurrentWeaverMajorVersion(); } public boolean isPrimitiveArray() { return false; } public boolean isGroovyObject() { if ((bits & GroovyObjectInitialized) == 0) { ResolvedType[] intfaces = getDeclaredInterfaces(); boolean done = false; // TODO do we need to walk more of these? (i.e. the interfaces interfaces and supertypes supertype). Check what groovy // does in the case where a hierarchy is involved and there are types in between GroovyObject/GroovyObjectSupport and // the type if (intfaces != null) { for (ResolvedType intface : intfaces) { if (intface.getName().equals("groovy.lang.GroovyObject")) { bits |= IsGroovyObject; done = true; break; } } } if (!done) { // take a look at the supertype if (getSuperclass().getName().equals("groovy.lang.GroovyObjectSupport")) { bits |= IsGroovyObject; } } bits |= GroovyObjectInitialized; } return (bits & IsGroovyObject) != 0; } }
386,049
Bug 386049 Error "must implement abstract inter-type declaration" even though build is fine
null
verified fixed
7c6e936
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2012-08-22T19:43:56Z"
"2012-07-26T13:40:00Z"
tests/bugs171/pr386049/de/scrum_master/galileo/filter/BasicFilter.java
386,049
Bug 386049 Error "must implement abstract inter-type declaration" even though build is fine
null
verified fixed
7c6e936
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2012-08-22T19:43:56Z"
"2012-07-26T13:40:00Z"
tests/bugs171/pr386049/de/scrum_master/galileo/filter/JsoupFilter.java
386,049
Bug 386049 Error "must implement abstract inter-type declaration" even though build is fine
null
verified fixed
7c6e936
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2012-08-22T19:43:56Z"
"2012-07-26T13:40:00Z"
tests/bugs171/pr387568/Code.java
386,049
Bug 386049 Error "must implement abstract inter-type declaration" even though build is fine
null
verified fixed
7c6e936
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2012-08-22T19:43:56Z"
"2012-07-26T13:40:00Z"
tests/src/org/aspectj/systemtest/ajc171/Ajc171Tests.java
/******************************************************************************* * Copyright (c) 2012 Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Andy Clement - initial API and implementation *******************************************************************************/ package org.aspectj.systemtest.ajc171; import java.io.File; import junit.framework.Test; import org.aspectj.testing.XMLBasedAjcTestCase; /** * @author Andy Clement */ public class Ajc171Tests extends org.aspectj.testing.XMLBasedAjcTestCase { public void testPublicITDFs_pr73507_1() { runTest("public ITDfs - 1"); } public void testPublicITDFs_pr73507_2() { runTest("public ITDfs - 2"); } public void testPublicITDFs_pr73507_3() { runTest("public ITDfs - 3"); } public void testPublicITDFs_pr73507_4() { runTest("public ITDfs - 4"); } public void testPublicITDFs_pr73507_5() { runTest("public ITDfs - 5"); } public void testGenerics_384398() { runTest("generics itds"); } // public void testGenerics_384398_2() { // runTest("generics itds 2"); // } // --- public static Test suite() { return XMLBasedAjcTestCase.loadSuite(Ajc171Tests.class); } @Override protected File getSpecFile() { return new File("../tests/src/org/aspectj/systemtest/ajc171/ajc171.xml"); } }
386,049
Bug 386049 Error "must implement abstract inter-type declaration" even though build is fine
null
verified fixed
7c6e936
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2012-08-22T19:43:56Z"
"2012-07-26T13:40:00Z"
weaver/src/org/aspectj/weaver/bcel/BcelTypeMunger.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Eclipse Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * PARC initial implementation * Alexandre Vasseur @AspectJ ITDs * ******************************************************************/ package org.aspectj.weaver.bcel; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import org.aspectj.apache.bcel.Constants; import org.aspectj.apache.bcel.classfile.ClassFormatException; import org.aspectj.apache.bcel.classfile.ConstantPool; import org.aspectj.apache.bcel.classfile.Signature; import org.aspectj.apache.bcel.classfile.annotation.AnnotationGen; import org.aspectj.apache.bcel.generic.FieldGen; import org.aspectj.apache.bcel.generic.InstructionBranch; import org.aspectj.apache.bcel.generic.InstructionConstants; import org.aspectj.apache.bcel.generic.InstructionFactory; import org.aspectj.apache.bcel.generic.InstructionHandle; import org.aspectj.apache.bcel.generic.InstructionList; import org.aspectj.apache.bcel.generic.InvokeInstruction; import org.aspectj.apache.bcel.generic.Type; import org.aspectj.asm.AsmManager; import org.aspectj.asm.IProgramElement; import org.aspectj.bridge.IMessage; import org.aspectj.bridge.ISourceLocation; import org.aspectj.bridge.Message; import org.aspectj.bridge.MessageUtil; import org.aspectj.bridge.WeaveMessage; import org.aspectj.bridge.context.CompilationAndWeavingContext; import org.aspectj.bridge.context.ContextToken; import org.aspectj.weaver.AjcMemberMaker; import org.aspectj.weaver.AnnotationAJ; import org.aspectj.weaver.AnnotationOnTypeMunger; import org.aspectj.weaver.BCException; import org.aspectj.weaver.ConcreteTypeMunger; import org.aspectj.weaver.Member; import org.aspectj.weaver.MemberUtils; import org.aspectj.weaver.MethodDelegateTypeMunger; import org.aspectj.weaver.NameMangler; import org.aspectj.weaver.NewConstructorTypeMunger; import org.aspectj.weaver.NewFieldTypeMunger; import org.aspectj.weaver.NewMemberClassTypeMunger; import org.aspectj.weaver.NewMethodTypeMunger; import org.aspectj.weaver.NewParentTypeMunger; import org.aspectj.weaver.PerObjectInterfaceTypeMunger; import org.aspectj.weaver.PrivilegedAccessMunger; import org.aspectj.weaver.ResolvedMember; import org.aspectj.weaver.ResolvedMemberImpl; import org.aspectj.weaver.ResolvedType; import org.aspectj.weaver.ResolvedTypeMunger; import org.aspectj.weaver.Shadow; import org.aspectj.weaver.TypeVariableReference; import org.aspectj.weaver.UnresolvedType; import org.aspectj.weaver.WeaverMessages; import org.aspectj.weaver.WeaverStateInfo; import org.aspectj.weaver.World; import org.aspectj.weaver.model.AsmRelationshipProvider; import org.aspectj.weaver.patterns.DeclareAnnotation; import org.aspectj.weaver.patterns.Pointcut; public class BcelTypeMunger extends ConcreteTypeMunger { public BcelTypeMunger(ResolvedTypeMunger munger, ResolvedType aspectType) { super(munger, aspectType); } @Override public String toString() { return "(BcelTypeMunger " + getMunger() + ")"; } @Override public boolean shouldOverwrite() { return false; } public boolean munge(BcelClassWeaver weaver) { ContextToken tok = CompilationAndWeavingContext.enteringPhase(CompilationAndWeavingContext.MUNGING_WITH, this); boolean changed = false; boolean worthReporting = true; if (weaver.getWorld().isOverWeaving()) { WeaverStateInfo typeWeaverState = weaver.getLazyClassGen().getType().getWeaverState(); if (typeWeaverState != null && typeWeaverState.isAspectAlreadyApplied(getAspectType())) { return false; } } if (munger.getKind() == ResolvedTypeMunger.Field) { changed = mungeNewField(weaver, (NewFieldTypeMunger) munger); } else if (munger.getKind() == ResolvedTypeMunger.Method) { changed = mungeNewMethod(weaver, (NewMethodTypeMunger) munger); } else if (munger.getKind() == ResolvedTypeMunger.InnerClass) { changed = mungeNewMemberType(weaver, (NewMemberClassTypeMunger) munger); } else if (munger.getKind() == ResolvedTypeMunger.MethodDelegate2) { changed = mungeMethodDelegate(weaver, (MethodDelegateTypeMunger) munger); } else if (munger.getKind() == ResolvedTypeMunger.FieldHost) { changed = mungeFieldHost(weaver, (MethodDelegateTypeMunger.FieldHostTypeMunger) munger); } else if (munger.getKind() == ResolvedTypeMunger.PerObjectInterface) { changed = mungePerObjectInterface(weaver, (PerObjectInterfaceTypeMunger) munger); worthReporting = false; } else if (munger.getKind() == ResolvedTypeMunger.PerTypeWithinInterface) { // PTWIMPL Transform the target type (add the aspect instance field) changed = mungePerTypeWithinTransformer(weaver); worthReporting = false; } else if (munger.getKind() == ResolvedTypeMunger.PrivilegedAccess) { changed = mungePrivilegedAccess(weaver, (PrivilegedAccessMunger) munger); worthReporting = false; } else if (munger.getKind() == ResolvedTypeMunger.Constructor) { changed = mungeNewConstructor(weaver, (NewConstructorTypeMunger) munger); } else if (munger.getKind() == ResolvedTypeMunger.Parent) { changed = mungeNewParent(weaver, (NewParentTypeMunger) munger); } else if (munger.getKind() == ResolvedTypeMunger.AnnotationOnType) { changed = mungeNewAnnotationOnType(weaver, (AnnotationOnTypeMunger) munger); worthReporting = false; } else { throw new RuntimeException("unimplemented"); } if (changed && munger.changesPublicSignature()) { WeaverStateInfo info = weaver.getLazyClassGen().getOrCreateWeaverStateInfo(weaver.getReweavableMode()); info.addConcreteMunger(this); } if (changed && worthReporting) { ResolvedType declaringAspect = null; AsmManager model = ((BcelWorld) getWorld()).getModelAsAsmManager(); if (model != null) { if (munger instanceof NewParentTypeMunger) { NewParentTypeMunger nptMunger = (NewParentTypeMunger) munger; declaringAspect = nptMunger.getDeclaringType(); if (declaringAspect.isParameterizedOrGenericType()) { declaringAspect = declaringAspect.getRawType(); } ResolvedType thisAspect = getAspectType(); AsmRelationshipProvider.addRelationship(model, weaver.getLazyClassGen().getType(), munger, thisAspect); // Add a relationship on the actual declaring aspect too if (!thisAspect.equals(declaringAspect)) { // Might be the case the declaring aspect is generic and thisAspect is parameterizing it. In that case // record the actual parameterizations ResolvedType target = weaver.getLazyClassGen().getType(); ResolvedType newParent = nptMunger.getNewParent(); IProgramElement thisAspectNode = model.getHierarchy().findElementForType(thisAspect.getPackageName(), thisAspect.getClassName()); Map<String, List<String>> declareParentsMap = thisAspectNode.getDeclareParentsMap(); if (declareParentsMap == null) { declareParentsMap = new HashMap<String, List<String>>(); thisAspectNode.setDeclareParentsMap(declareParentsMap); } String tname = target.getName(); String pname = newParent.getName(); List<String> newparents = declareParentsMap.get(tname); if (newparents == null) { newparents = new ArrayList<String>(); declareParentsMap.put(tname, newparents); } newparents.add(pname); AsmRelationshipProvider.addRelationship(model, weaver.getLazyClassGen().getType(), munger, declaringAspect); } } else { declaringAspect = getAspectType(); AsmRelationshipProvider.addRelationship(model, weaver.getLazyClassGen().getType(), munger, declaringAspect); } } } // TAG: WeavingMessage if (changed && worthReporting && munger != null && !weaver.getWorld().getMessageHandler().isIgnoring(IMessage.WEAVEINFO)) { String tName = weaver.getLazyClassGen().getType().getSourceLocation().getSourceFile().getName(); if (tName.indexOf("no debug info available") != -1) { tName = "no debug info available"; } else { tName = getShortname(weaver.getLazyClassGen().getType().getSourceLocation().getSourceFile().getPath()); } String fName = getShortname(getAspectType().getSourceLocation().getSourceFile().getPath()); if (munger.getKind().equals(ResolvedTypeMunger.Parent)) { // This message could come out of AjLookupEnvironment.addParent // if doing parents munging at compile time only... NewParentTypeMunger parentTM = (NewParentTypeMunger) munger; if (parentTM.isMixin()) { weaver.getWorld() .getMessageHandler() .handleMessage( WeaveMessage.constructWeavingMessage(WeaveMessage.WEAVEMESSAGE_MIXIN, new String[] { parentTM.getNewParent().getName(), fName, weaver.getLazyClassGen().getType().getName(), tName }, weaver.getLazyClassGen().getClassName(), getAspectType().getName())); } else { if (parentTM.getNewParent().isInterface()) { weaver.getWorld() .getMessageHandler() .handleMessage( WeaveMessage.constructWeavingMessage(WeaveMessage.WEAVEMESSAGE_DECLAREPARENTSIMPLEMENTS, new String[] { weaver.getLazyClassGen().getType().getName(), tName, parentTM.getNewParent().getName(), fName }, weaver.getLazyClassGen() .getClassName(), getAspectType().getName())); } else { weaver.getWorld() .getMessageHandler() .handleMessage( WeaveMessage.constructWeavingMessage(WeaveMessage.WEAVEMESSAGE_DECLAREPARENTSEXTENDS, new String[] { weaver.getLazyClassGen().getType().getName(), tName, parentTM.getNewParent().getName(), fName })); // TAG: WeavingMessage DECLARE PARENTS: EXTENDS // reportDeclareParentsMessage(WeaveMessage. // WEAVEMESSAGE_DECLAREPARENTSEXTENDS,sourceType,parent); } } } else if (munger.getKind().equals(ResolvedTypeMunger.FieldHost)) { // hidden } else { ResolvedMember declaredSig = munger.getSignature(); String fromString = fName + ":'" + declaredSig + "'"; // if (declaredSig==null) declaredSig= munger.getSignature(); String kindString = munger.getKind().toString().toLowerCase(); if (kindString.equals("innerclass")) { kindString = "member class"; fromString = fName; } weaver.getWorld() .getMessageHandler() .handleMessage( WeaveMessage.constructWeavingMessage(WeaveMessage.WEAVEMESSAGE_ITD, new String[] { weaver.getLazyClassGen().getType().getName(), tName, kindString, getAspectType().getName(), fromString }, weaver.getLazyClassGen().getClassName(), getAspectType().getName())); } } CompilationAndWeavingContext.leavingPhase(tok); return changed; } private String getShortname(String path) { int takefrom = path.lastIndexOf('/'); if (takefrom == -1) { takefrom = path.lastIndexOf('\\'); } return path.substring(takefrom + 1); } private boolean mungeNewAnnotationOnType(BcelClassWeaver weaver, AnnotationOnTypeMunger munger) { // FIXME asc this has already been done up front, need to do it here too? try { BcelAnnotation anno = (BcelAnnotation) munger.getNewAnnotation(); weaver.getLazyClassGen().addAnnotation(anno.getBcelAnnotation()); } catch (ClassCastException cce) { throw new IllegalStateException("DiagnosticsFor318237: The typemunger "+munger+" contains an annotation of type "+ munger.getNewAnnotation().getClass().getName()+" when it should be a BcelAnnotation",cce); } return true; } /** * For a long time, AspectJ did not allow binary weaving of declare parents. This restriction is now lifted but could do with * more testing! */ private boolean mungeNewParent(BcelClassWeaver weaver, NewParentTypeMunger typeTransformer) { LazyClassGen newParentTarget = weaver.getLazyClassGen(); ResolvedType newParent = typeTransformer.getNewParent(); boolean performChange = true; performChange = enforceDecpRule1_abstractMethodsImplemented(weaver, typeTransformer.getSourceLocation(), newParentTarget, newParent); performChange = enforceDecpRule2_cantExtendFinalClass(weaver, typeTransformer.getSourceLocation(), newParentTarget, newParent) && performChange; List<ResolvedMember> methods = newParent.getMethodsWithoutIterator(false, true, false); for (ResolvedMember method : methods) { if (!method.getName().equals("<init>")) { LazyMethodGen subMethod = findMatchingMethod(newParentTarget, method); // FIXME asc is this safe for all bridge methods? if (subMethod != null && !subMethod.isBridgeMethod()) { if (!(subMethod.isSynthetic() && method.isSynthetic())) { if (!(subMethod.isStatic() && subMethod.getName().startsWith("access$"))) { // ignore generated accessors performChange = enforceDecpRule3_visibilityChanges(weaver, newParent, method, subMethod) && performChange; performChange = enforceDecpRule4_compatibleReturnTypes(weaver, method, subMethod) && performChange; performChange = enforceDecpRule5_cantChangeFromStaticToNonstatic(weaver, typeTransformer.getSourceLocation(), method, subMethod) && performChange; } } } } } if (!performChange) { // A rule was violated and an error message already reported return false; } if (newParent.isClass()) { // Changing the supertype if (!attemptToModifySuperCalls(weaver, newParentTarget, newParent)) { return false; } newParentTarget.setSuperClass(newParent); } else { // Add a new interface newParentTarget.addInterface(newParent, getSourceLocation()); } return true; } /** * Rule 1: For the declare parents to be allowed, the target type must override and implement inherited abstract methods (if the * type is not declared abstract) */ private boolean enforceDecpRule1_abstractMethodsImplemented(BcelClassWeaver weaver, ISourceLocation mungerLoc, LazyClassGen newParentTarget, ResolvedType newParent) { // Ignore abstract classes or interfaces if (newParentTarget.isAbstract() || newParentTarget.isInterface()) { return true; } boolean ruleCheckingSucceeded = true; List<ResolvedMember> newParentMethods = newParent.getMethodsWithoutIterator(false, true, false); for (ResolvedMember newParentMethod : newParentMethods) { String newParentMethodName = newParentMethod.getName(); // Ignore abstract ajc$interField prefixed methods if (newParentMethod.isAbstract() && !newParentMethodName.startsWith("ajc$interField")) { ResolvedMember discoveredImpl = null; List<ResolvedMember> targetMethods = newParentTarget.getType().getMethodsWithoutIterator(false, true, false); for (ResolvedMember targetMethod : targetMethods) { if (!targetMethod.isAbstract() && targetMethod.getName().equals(newParentMethodName)) { String newParentMethodSig = newParentMethod.getParameterSignature(); // ([TT;) String targetMethodSignature = targetMethod.getParameterSignature(); // ([Ljava/lang/Object;) // could be a match if (targetMethodSignature.equals(newParentMethodSig)) { discoveredImpl = targetMethod; } else { // Does the erasure match? In which case a bridge method will be created later to // satisfy the abstract method if (targetMethod.hasBackingGenericMember() && targetMethod.getBackingGenericMember().getParameterSignature().equals(newParentMethodSig)) { discoveredImpl = targetMethod; } else if (newParentMethod.hasBackingGenericMember()) { if (newParentMethod.getBackingGenericMember().getParameterSignature().equals(targetMethodSignature)) { discoveredImpl = targetMethod; } } } if (discoveredImpl != null) { break; } } } if (discoveredImpl == null) { // didnt find a valid implementation, lets check the // ITDs on this type to see if they satisfy it boolean satisfiedByITD = false; for (ConcreteTypeMunger m : newParentTarget.getType().getInterTypeMungersIncludingSupers()) { if (m.getMunger() != null && m.getMunger().getKind() == ResolvedTypeMunger.Method) { ResolvedMember sig = m.getSignature(); if (!Modifier.isAbstract(sig.getModifiers())) { // If the ITD shares a type variable with some target type, we need to tailor it // for that type if (m.isTargetTypeParameterized()) { ResolvedType genericOnType = getWorld().resolve(sig.getDeclaringType()).getGenericType(); m = m.parameterizedFor(newParent.discoverActualOccurrenceOfTypeInHierarchy(genericOnType)); // possible sig change when type parameters filled in sig = m.getSignature(); } if (ResolvedType.matches( AjcMemberMaker.interMethod(sig, m.getAspectType(), sig.getDeclaringType().resolve(weaver.getWorld()).isInterface()), newParentMethod)) { satisfiedByITD = true; } } } else if (m.getMunger() != null && m.getMunger().getKind() == ResolvedTypeMunger.MethodDelegate2) { // AV - that should be enough, no need to check more satisfiedByITD = true; } } if (!satisfiedByITD) { error(weaver, "The type " + newParentTarget.getName() + " must implement the inherited abstract method " + newParentMethod.getDeclaringType() + "." + newParentMethodName + newParentMethod.getParameterSignature(), newParentTarget.getType().getSourceLocation(), new ISourceLocation[] { newParentMethod.getSourceLocation(), mungerLoc }); ruleCheckingSucceeded = false; } } } } return ruleCheckingSucceeded; } /** * Rule 2. Can't extend final types */ private boolean enforceDecpRule2_cantExtendFinalClass(BcelClassWeaver weaver, ISourceLocation transformerLoc, LazyClassGen targetType, ResolvedType newParent) { if (newParent.isFinal()) { error(weaver, "Cannot make type " + targetType.getName() + " extend final class " + newParent.getName(), targetType .getType().getSourceLocation(), new ISourceLocation[] { transformerLoc }); return false; } return true; } /** * Rule 3. Can't narrow visibility of methods when overriding */ private boolean enforceDecpRule3_visibilityChanges(BcelClassWeaver weaver, ResolvedType newParent, ResolvedMember superMethod, LazyMethodGen subMethod) { boolean cont = true; if (Modifier.isPublic(superMethod.getModifiers())) { if (subMethod.isProtected() || subMethod.isDefault() || subMethod.isPrivate()) { weaver.getWorld() .getMessageHandler() .handleMessage( MessageUtil.error("Cannot reduce the visibility of the inherited method '" + superMethod + "' from " + newParent.getName(), superMethod.getSourceLocation())); cont = false; } } else if (Modifier.isProtected(superMethod.getModifiers())) { if (subMethod.isDefault() || subMethod.isPrivate()) { weaver.getWorld() .getMessageHandler() .handleMessage( MessageUtil.error("Cannot reduce the visibility of the inherited method '" + superMethod + "' from " + newParent.getName(), superMethod.getSourceLocation())); cont = false; } } else if (superMethod.isDefault()) { if (subMethod.isPrivate()) { weaver.getWorld() .getMessageHandler() .handleMessage( MessageUtil.error("Cannot reduce the visibility of the inherited method '" + superMethod + "' from " + newParent.getName(), superMethod.getSourceLocation())); cont = false; } } return cont; } /** * Rule 4. Can't have incompatible return types */ private boolean enforceDecpRule4_compatibleReturnTypes(BcelClassWeaver weaver, ResolvedMember superMethod, LazyMethodGen subMethod) { boolean cont = true; String superReturnTypeSig = superMethod.getGenericReturnType().getSignature(); // eg. Pjava/util/Collection<LFoo;> String subReturnTypeSig = subMethod.getGenericReturnTypeSignature(); superReturnTypeSig = superReturnTypeSig.replace('.', '/'); subReturnTypeSig = subReturnTypeSig.replace('.', '/'); if (!superReturnTypeSig.equals(subReturnTypeSig)) { // Check for covariance ResolvedType subType = weaver.getWorld().resolve(subMethod.getReturnType()); ResolvedType superType = weaver.getWorld().resolve(superMethod.getReturnType()); if (!superType.isAssignableFrom(subType)) { weaver.getWorld() .getMessageHandler() .handleMessage( MessageUtil.error("The return type is incompatible with " + superMethod.getDeclaringType() + "." + superMethod.getName() + superMethod.getParameterSignature(), subMethod.getSourceLocation())); // this just might be a better error message... // "The return type '"+subReturnTypeSig+ // "' is incompatible with the overridden method " // +superMethod.getDeclaringType()+"."+ // superMethod.getName()+superMethod.getParameterSignature()+ // " which returns '"+superReturnTypeSig+"'", cont = false; } } return cont; } /** * Rule5. Method overrides can't change the staticality (word?) - you can't override and make an instance method static or * override and make a static method an instance method. */ private boolean enforceDecpRule5_cantChangeFromStaticToNonstatic(BcelClassWeaver weaver, ISourceLocation mungerLoc, ResolvedMember superMethod, LazyMethodGen subMethod) { boolean superMethodStatic = Modifier.isStatic(superMethod.getModifiers()); if (superMethodStatic && !subMethod.isStatic()) { error(weaver, "This instance method " + subMethod.getName() + subMethod.getParameterSignature() + " cannot override the static method from " + superMethod.getDeclaringType().getName(), subMethod.getSourceLocation(), new ISourceLocation[] { mungerLoc }); return false; } else if (!superMethodStatic && subMethod.isStatic()) { error(weaver, "The static method " + subMethod.getName() + subMethod.getParameterSignature() + " cannot hide the instance method from " + superMethod.getDeclaringType().getName(), subMethod.getSourceLocation(), new ISourceLocation[] { mungerLoc }); return false; } return true; } public void error(BcelClassWeaver weaver, String text, ISourceLocation primaryLoc, ISourceLocation[] extraLocs) { IMessage msg = new Message(text, primaryLoc, true, extraLocs); weaver.getWorld().getMessageHandler().handleMessage(msg); } /** * Search the specified type for a particular method - do not use the return value in the comparison as it is not considered for * overriding. */ private LazyMethodGen findMatchingMethod(LazyClassGen type, ResolvedMember searchMethod) { String searchName = searchMethod.getName(); String searchSig = searchMethod.getParameterSignature(); for (LazyMethodGen method : type.getMethodGens()) { if (method.getName().equals(searchName) && method.getParameterSignature().equals(searchSig)) { return method; } } return null; } /** * The main part of implementing declare parents extends. Modify super ctor calls to target the new type. */ public boolean attemptToModifySuperCalls(BcelClassWeaver weaver, LazyClassGen newParentTarget, ResolvedType newParent) { ResolvedType currentParentType = newParentTarget.getSuperClass(); if (currentParentType.getGenericType() != null) { currentParentType = currentParentType.getGenericType(); } String currentParent = currentParentType.getName(); if (newParent.getGenericType() != null) { newParent = newParent.getGenericType(); // target new super calls at } // the generic type if its raw or parameterized List<LazyMethodGen> mgs = newParentTarget.getMethodGens(); // Look for ctors to modify for (LazyMethodGen aMethod : mgs) { if (LazyMethodGen.isConstructor(aMethod)) { InstructionList insList = aMethod.getBody(); InstructionHandle handle = insList.getStart(); while (handle != null) { if (handle.getInstruction().opcode == Constants.INVOKESPECIAL) { ConstantPool cpg = newParentTarget.getConstantPool(); InvokeInstruction invokeSpecial = (InvokeInstruction) handle.getInstruction(); if (invokeSpecial.getClassName(cpg).equals(currentParent) && invokeSpecial.getMethodName(cpg).equals("<init>")) { // System.err.println("Transforming super call '<init>" + invokeSpecial.getSignature(cpg) + "'"); // 1. Check there is a ctor in the new parent with // the same signature ResolvedMember newCtor = getConstructorWithSignature(newParent, invokeSpecial.getSignature(cpg)); if (newCtor == null) { // 2. Check ITDCs to see if the necessary ctor is provided that way boolean satisfiedByITDC = false; for (Iterator<ConcreteTypeMunger> ii = newParentTarget.getType() .getInterTypeMungersIncludingSupers().iterator(); ii.hasNext() && !satisfiedByITDC;) { ConcreteTypeMunger m = ii.next(); if (m.getMunger() instanceof NewConstructorTypeMunger) { if (m.getSignature().getSignature().equals(invokeSpecial.getSignature(cpg))) { satisfiedByITDC = true; } } } if (!satisfiedByITDC) { String csig = createReadableCtorSig(newParent, cpg, invokeSpecial); weaver.getWorld() .getMessageHandler() .handleMessage( MessageUtil.error( "Unable to modify hierarchy for " + newParentTarget.getClassName() + " - the constructor " + csig + " is missing", this.getSourceLocation())); return false; } } int idx = cpg.addMethodref(newParent.getName(), invokeSpecial.getMethodName(cpg), invokeSpecial.getSignature(cpg)); invokeSpecial.setIndex(idx); } } handle = handle.getNext(); } } } return true; } /** * Creates a nice signature for the ctor, something like "(int,Integer,String)" */ private String createReadableCtorSig(ResolvedType newParent, ConstantPool cpg, InvokeInstruction invokeSpecial) { StringBuffer sb = new StringBuffer(); Type[] ctorArgs = invokeSpecial.getArgumentTypes(cpg); sb.append(newParent.getClassName()); sb.append("("); for (int i = 0; i < ctorArgs.length; i++) { String argtype = ctorArgs[i].toString(); if (argtype.lastIndexOf(".") != -1) { sb.append(argtype.substring(argtype.lastIndexOf(".") + 1)); } else { sb.append(argtype); } if (i + 1 < ctorArgs.length) { sb.append(","); } } sb.append(")"); return sb.toString(); } private ResolvedMember getConstructorWithSignature(ResolvedType type, String searchSig) { for (ResolvedMember method : type.getDeclaredJavaMethods()) { if (MemberUtils.isConstructor(method)) { if (method.getSignature().equals(searchSig)) { return method; } } } return null; } private boolean mungePrivilegedAccess(BcelClassWeaver weaver, PrivilegedAccessMunger munger) { LazyClassGen gen = weaver.getLazyClassGen(); ResolvedMember member = munger.getMember(); ResolvedType onType = weaver.getWorld().resolve(member.getDeclaringType(), munger.getSourceLocation()); if (onType.isRawType()) { onType = onType.getGenericType(); } // System.out.println("munging: " + gen + " with " + member); if (onType.equals(gen.getType())) { if (member.getKind() == Member.FIELD) { // System.out.println("matched: " + gen); addFieldGetter(gen, member, AjcMemberMaker.privilegedAccessMethodForFieldGet(aspectType, member, munger.shortSyntax)); addFieldSetter(gen, member, AjcMemberMaker.privilegedAccessMethodForFieldSet(aspectType, member, munger.shortSyntax)); return true; } else if (member.getKind() == Member.METHOD) { addMethodDispatch(gen, member, AjcMemberMaker.privilegedAccessMethodForMethod(aspectType, member)); return true; } else if (member.getKind() == Member.CONSTRUCTOR) { for (Iterator<LazyMethodGen> i = gen.getMethodGens().iterator(); i.hasNext();) { LazyMethodGen m = i.next(); if (m.getMemberView() != null && m.getMemberView().getKind() == Member.CONSTRUCTOR) { // m.getMemberView().equals(member)) { m.forcePublic(); // return true; } } return true; // throw new BCException("no match for " + member + " in " + // gen); } else if (member.getKind() == Member.STATIC_INITIALIZATION) { gen.forcePublic(); return true; } else { throw new RuntimeException("unimplemented"); } } return false; } private void addFieldGetter(LazyClassGen gen, ResolvedMember field, ResolvedMember accessMethod) { LazyMethodGen mg = makeMethodGen(gen, accessMethod); InstructionList il = new InstructionList(); InstructionFactory fact = gen.getFactory(); if (Modifier.isStatic(field.getModifiers())) { il.append(fact.createFieldAccess(gen.getClassName(), field.getName(), BcelWorld.makeBcelType(field.getType()), Constants.GETSTATIC)); } else { il.append(InstructionConstants.ALOAD_0); il.append(fact.createFieldAccess(gen.getClassName(), field.getName(), BcelWorld.makeBcelType(field.getType()), Constants.GETFIELD)); } il.append(InstructionFactory.createReturn(BcelWorld.makeBcelType(field.getType()))); mg.getBody().insert(il); gen.addMethodGen(mg, getSignature().getSourceLocation()); } private void addFieldSetter(LazyClassGen gen, ResolvedMember field, ResolvedMember accessMethod) { LazyMethodGen mg = makeMethodGen(gen, accessMethod); InstructionList il = new InstructionList(); InstructionFactory fact = gen.getFactory(); Type fieldType = BcelWorld.makeBcelType(field.getType()); if (Modifier.isStatic(field.getModifiers())) { il.append(InstructionFactory.createLoad(fieldType, 0)); il.append(fact.createFieldAccess(gen.getClassName(), field.getName(), fieldType, Constants.PUTSTATIC)); } else { il.append(InstructionConstants.ALOAD_0); il.append(InstructionFactory.createLoad(fieldType, 1)); il.append(fact.createFieldAccess(gen.getClassName(), field.getName(), fieldType, Constants.PUTFIELD)); } il.append(InstructionFactory.createReturn(Type.VOID)); mg.getBody().insert(il); gen.addMethodGen(mg, getSignature().getSourceLocation()); } private void addMethodDispatch(LazyClassGen gen, ResolvedMember method, ResolvedMember accessMethod) { LazyMethodGen mg = makeMethodGen(gen, accessMethod); InstructionList il = new InstructionList(); InstructionFactory fact = gen.getFactory(); // Type fieldType = BcelWorld.makeBcelType(field.getType()); Type[] paramTypes = BcelWorld.makeBcelTypes(method.getParameterTypes()); int pos = 0; if (!Modifier.isStatic(method.getModifiers())) { il.append(InstructionConstants.ALOAD_0); pos++; } for (int i = 0, len = paramTypes.length; i < len; i++) { Type paramType = paramTypes[i]; il.append(InstructionFactory.createLoad(paramType, pos)); pos += paramType.getSize(); } il.append(Utility.createInvoke(fact, (BcelWorld) aspectType.getWorld(), method)); il.append(InstructionFactory.createReturn(BcelWorld.makeBcelType(method.getReturnType()))); mg.getBody().insert(il); gen.addMethodGen(mg); } protected LazyMethodGen makeMethodGen(LazyClassGen gen, ResolvedMember member) { try { Type returnType = BcelWorld.makeBcelType(member.getReturnType()); Type[] parameterTypes = BcelWorld.makeBcelTypes(member.getParameterTypes()); LazyMethodGen ret = new LazyMethodGen(member.getModifiers(), returnType, member.getName(), parameterTypes, UnresolvedType.getNames(member .getExceptions()), gen); // 43972 : Static crosscutting makes interfaces unusable for javac // ret.makeSynthetic(); return ret; } catch (ClassFormatException cfe) { throw new RuntimeException("Problem with makeMethodGen for method "+member.getName()+" in type "+gen.getName()+" ret="+member.getReturnType(),cfe); } } protected FieldGen makeFieldGen(LazyClassGen gen, ResolvedMember member) { return new FieldGen(member.getModifiers(), BcelWorld.makeBcelType(member.getReturnType()), member.getName(), gen.getConstantPool()); } private boolean mungePerObjectInterface(BcelClassWeaver weaver, PerObjectInterfaceTypeMunger munger) { // System.err.println("Munging perobject ["+munger+"] onto "+weaver. // getLazyClassGen().getClassName()); LazyClassGen gen = weaver.getLazyClassGen(); if (couldMatch(gen.getBcelObjectType(), munger.getTestPointcut())) { FieldGen fg = makeFieldGen(gen, AjcMemberMaker.perObjectField(gen.getType(), aspectType)); gen.addField(fg, getSourceLocation()); Type fieldType = BcelWorld.makeBcelType(aspectType); LazyMethodGen mg = new LazyMethodGen(Modifier.PUBLIC, fieldType, NameMangler.perObjectInterfaceGet(aspectType), new Type[0], new String[0], gen); InstructionList il = new InstructionList(); InstructionFactory fact = gen.getFactory(); il.append(InstructionConstants.ALOAD_0); il.append(fact.createFieldAccess(gen.getClassName(), fg.getName(), fieldType, Constants.GETFIELD)); il.append(InstructionFactory.createReturn(fieldType)); mg.getBody().insert(il); gen.addMethodGen(mg); LazyMethodGen mg1 = new LazyMethodGen(Modifier.PUBLIC, Type.VOID, NameMangler.perObjectInterfaceSet(aspectType), new Type[] { fieldType, }, new String[0], gen); InstructionList il1 = new InstructionList(); il1.append(InstructionConstants.ALOAD_0); il1.append(InstructionFactory.createLoad(fieldType, 1)); il1.append(fact.createFieldAccess(gen.getClassName(), fg.getName(), fieldType, Constants.PUTFIELD)); il1.append(InstructionFactory.createReturn(Type.VOID)); mg1.getBody().insert(il1); gen.addMethodGen(mg1); gen.addInterface(munger.getInterfaceType().resolve(weaver.getWorld()), getSourceLocation()); return true; } else { return false; } } // PTWIMPL Add field to hold aspect instance and an accessor private boolean mungePerTypeWithinTransformer(BcelClassWeaver weaver) { LazyClassGen gen = weaver.getLazyClassGen(); // if (couldMatch(gen.getBcelObjectType(), munger.getTestPointcut())) { // Add (to the target type) the field that will hold the aspect instance // e.g ajc$com_blah_SecurityAspect$ptwAspectInstance FieldGen fg = makeFieldGen(gen, AjcMemberMaker.perTypeWithinField(gen.getType(), aspectType)); gen.addField(fg, getSourceLocation()); // Add an accessor for this new field, the // ajc$<aspectname>$localAspectOf() method // e.g. // "public com_blah_SecurityAspect ajc$com_blah_SecurityAspect$localAspectOf()" Type fieldType = BcelWorld.makeBcelType(aspectType); LazyMethodGen mg = new LazyMethodGen(Modifier.PUBLIC | Modifier.STATIC, fieldType, NameMangler.perTypeWithinLocalAspectOf(aspectType), new Type[0], new String[0], gen); InstructionList il = new InstructionList(); // PTWIMPL ?? Should check if it is null and throw // NoAspectBoundException InstructionFactory fact = gen.getFactory(); il.append(fact.createFieldAccess(gen.getClassName(), fg.getName(), fieldType, Constants.GETSTATIC)); il.append(InstructionFactory.createReturn(fieldType)); mg.getBody().insert(il); gen.addMethodGen(mg); return true; // } else { // return false; // } } // ??? Why do we have this method? I thought by now we would know if it // matched or not private boolean couldMatch(BcelObjectType bcelObjectType, Pointcut pointcut) { return !bcelObjectType.isInterface(); } private boolean mungeNewMemberType(BcelClassWeaver classWeaver, NewMemberClassTypeMunger munger) { World world = classWeaver.getWorld(); ResolvedType onType = world.resolve(munger.getTargetType()); if (onType.isRawType()) { onType = onType.getGenericType(); } return onType.equals(classWeaver.getLazyClassGen().getType()); } private boolean mungeNewMethod(BcelClassWeaver classWeaver, NewMethodTypeMunger munger) { World world = classWeaver.getWorld(); // Resolving it will sort out the tvars ResolvedMember unMangledInterMethod = munger.getSignature().resolve(world); // do matching on the unMangled one, but actually add them to the mangled method ResolvedMember interMethodBody = munger.getDeclaredInterMethodBody(aspectType, world); ResolvedMember interMethodDispatcher = munger.getDeclaredInterMethodDispatcher(aspectType, world); ResolvedMember memberHoldingAnyAnnotations = interMethodDispatcher; LazyClassGen classGen = classWeaver.getLazyClassGen(); ResolvedType onType = world.resolve(unMangledInterMethod.getDeclaringType(), munger.getSourceLocation()); if (onType.isRawType()) { onType = onType.getGenericType(); } // Simple checks, can't ITD on annotations or enums if (onType.isAnnotation()) { signalError(WeaverMessages.ITDM_ON_ANNOTATION_NOT_ALLOWED, classWeaver, onType); return false; } if (onType.isEnum()) { signalError(WeaverMessages.ITDM_ON_ENUM_NOT_ALLOWED, classWeaver, onType); return false; } boolean mungingInterface = classGen.isInterface(); boolean onInterface = onType.isInterface(); if (onInterface && classGen.getLazyMethodGen(unMangledInterMethod.getName(), unMangledInterMethod.getSignature(), true) != null) { // this is ok, we could be providing the default implementation of a // method // that the target has already declared return false; } // If we are processing the intended ITD target type (might be an interface) if (onType.equals(classGen.getType())) { ResolvedMember mangledInterMethod = AjcMemberMaker.interMethod(unMangledInterMethod, aspectType, onInterface); LazyMethodGen newMethod = makeMethodGen(classGen, mangledInterMethod); if (mungingInterface) { // we want the modifiers of the ITD to be used for all *implementors* of the // interface, but the method itself we add to the interface must be public abstract newMethod.setAccessFlags(Modifier.PUBLIC | Modifier.ABSTRACT); } // pr98901 // For copying the annotations across, we have to discover the real // member in the aspect which is holding them. if (classWeaver.getWorld().isInJava5Mode()) { AnnotationAJ annotationsOnRealMember[] = null; ResolvedType toLookOn = aspectType; if (aspectType.isRawType()) { toLookOn = aspectType.getGenericType(); } ResolvedMember realMember = getRealMemberForITDFromAspect(toLookOn, memberHoldingAnyAnnotations, false); // 266602 - consider it missing to mean that the corresponding aspect had errors if (realMember == null) { // signalWarning("Unable to apply any annotations attached to " + munger.getSignature(), weaver); // throw new BCException("Couldn't find ITD init member '" + interMethodBody + "' on aspect " + aspectType); } else { annotationsOnRealMember = realMember.getAnnotations(); } Set<ResolvedType> addedAnnotations = new HashSet<ResolvedType>(); if (annotationsOnRealMember != null) { for (AnnotationAJ anno : annotationsOnRealMember) { AnnotationGen a = ((BcelAnnotation) anno).getBcelAnnotation(); AnnotationGen ag = new AnnotationGen(a, classGen.getConstantPool(), true); newMethod.addAnnotation(new BcelAnnotation(ag, classWeaver.getWorld())); addedAnnotations.add(anno.getType()); } } if (realMember != null) { copyOverParameterAnnotations(newMethod, realMember); } // the code below was originally added to cope with the case where an aspect declares an annotation on an ITD // declared within itself (an unusual situation). However, it also addresses the case where we may not find the // annotation on the real representation of the ITD. This can happen in a load-time weaving situation where // we couldn't add the annotation in time - and so here we recheck the declare annotations. Not quite ideal but // works. pr288635 List<DeclareAnnotation> allDecams = world.getDeclareAnnotationOnMethods(); for (DeclareAnnotation declareAnnotationMC : allDecams) { if (declareAnnotationMC.matches(unMangledInterMethod, world)) { // && newMethod.getEnclosingClass().getType() == aspectType) { AnnotationAJ annotation = declareAnnotationMC.getAnnotation(); if (!addedAnnotations.contains(annotation.getType())) { newMethod.addAnnotation(annotation); } } } } // If it doesn't target an interface and there is a body (i.e. it // isnt abstract) if (!onInterface && !Modifier.isAbstract(mangledInterMethod.getModifiers())) { InstructionList body = newMethod.getBody(); InstructionFactory fact = classGen.getFactory(); int pos = 0; if (!Modifier.isStatic(unMangledInterMethod.getModifiers())) { body.append(InstructionFactory.createThis()); pos++; } Type[] paramTypes = BcelWorld.makeBcelTypes(mangledInterMethod.getParameterTypes()); for (int i = 0, len = paramTypes.length; i < len; i++) { Type paramType = paramTypes[i]; body.append(InstructionFactory.createLoad(paramType, pos)); pos += paramType.getSize(); } body.append(Utility.createInvoke(fact, classWeaver.getWorld(), interMethodBody)); body.append(InstructionFactory.createReturn(BcelWorld.makeBcelType(mangledInterMethod.getReturnType()))); if (classWeaver.getWorld().isInJava5Mode()) { // Don't need bridge // methods if not in // 1.5 mode. createAnyBridgeMethodsForCovariance(classWeaver, munger, unMangledInterMethod, onType, classGen, paramTypes); } } else { // ??? this is okay // if (!(mg.getBody() == null)) throw new // RuntimeException("bas"); } if (world.isInJava5Mode()) { String basicSignature = mangledInterMethod.getSignature(); String genericSignature = ((ResolvedMemberImpl) mangledInterMethod).getSignatureForAttribute(); if (!basicSignature.equals(genericSignature)) { // Add a signature attribute to it newMethod.addAttribute(createSignatureAttribute(classGen.getConstantPool(), genericSignature)); } } // XXX make sure to check that we set exceptions properly on this // guy. classWeaver.addLazyMethodGen(newMethod); classWeaver.getLazyClassGen().warnOnAddedMethod(newMethod.getMethod(), getSignature().getSourceLocation()); addNeededSuperCallMethods(classWeaver, onType, munger.getSuperMethodsCalled()); return true; } else if (onInterface && !Modifier.isAbstract(unMangledInterMethod.getModifiers())) { // This means the 'gen' should be the top most implementor // - if it is *not* then something went wrong after we worked // out that it was the top most implementor (see pr49657) if (!classGen.getType().isTopmostImplementor(onType)) { ResolvedType rtx = classGen.getType().getTopmostImplementor(onType); if (rtx == null) { // pr302460 // null means there is something wrong with what we are looking at ResolvedType rt = classGen.getType(); if (rt.isInterface()) { ISourceLocation sloc = munger.getSourceLocation(); classWeaver .getWorld() .getMessageHandler() .handleMessage( MessageUtil.error( "ITD target " + rt.getName() + " is an interface but has been incorrectly determined to be the topmost implementor of " + onType.getName() + ". ITD is " + this.getSignature(), sloc)); } if (!onType.isAssignableFrom(rt)) { ISourceLocation sloc = munger.getSourceLocation(); classWeaver .getWorld() .getMessageHandler() .handleMessage( MessageUtil.error( "ITD target " + rt.getName() + " doesn't appear to implement " + onType.getName() + " why did we consider it the top most implementor? ITD is " + this.getSignature(), sloc)); } } else if (!rtx.isExposedToWeaver()) { ISourceLocation sLoc = munger.getSourceLocation(); classWeaver .getWorld() .getMessageHandler() .handleMessage( MessageUtil.error(WeaverMessages.format(WeaverMessages.ITD_NON_EXPOSED_IMPLEMENTOR, rtx, getAspectType().getName()), (sLoc == null ? getAspectType().getSourceLocation() : sLoc))); } else { // XXX what does this state mean? // We have incorrectly identified what is the top most // implementor and its not because // a type wasn't exposed to the weaver } return false; } else { ResolvedMember mangledInterMethod = AjcMemberMaker.interMethod(unMangledInterMethod, aspectType, false); LazyMethodGen mg = makeMethodGen(classGen, mangledInterMethod); // From 98901#29 - need to copy annotations across if (classWeaver.getWorld().isInJava5Mode()) { AnnotationAJ annotationsOnRealMember[] = null; ResolvedType toLookOn = aspectType; if (aspectType.isRawType()) { toLookOn = aspectType.getGenericType(); } ResolvedMember realMember = getRealMemberForITDFromAspect(toLookOn, memberHoldingAnyAnnotations, false); if (realMember == null) { throw new BCException("Couldn't find ITD holder member '" + memberHoldingAnyAnnotations + "' on aspect " + aspectType); } annotationsOnRealMember = realMember.getAnnotations(); if (annotationsOnRealMember != null) { for (AnnotationAJ annotationX : annotationsOnRealMember) { AnnotationGen a = ((BcelAnnotation) annotationX).getBcelAnnotation(); AnnotationGen ag = new AnnotationGen(a, classWeaver.getLazyClassGen().getConstantPool(), true); mg.addAnnotation(new BcelAnnotation(ag, classWeaver.getWorld())); } } copyOverParameterAnnotations(mg, realMember); } if (mungingInterface) { // we want the modifiers of the ITD to be used for all // *implementors* of the // interface, but the method itself we add to the interface // must be public abstract mg.setAccessFlags(Modifier.PUBLIC | Modifier.ABSTRACT); } Type[] paramTypes = BcelWorld.makeBcelTypes(mangledInterMethod.getParameterTypes()); Type returnType = BcelWorld.makeBcelType(mangledInterMethod.getReturnType()); InstructionList body = mg.getBody(); InstructionFactory fact = classGen.getFactory(); int pos = 0; if (!Modifier.isStatic(mangledInterMethod.getModifiers())) { body.append(InstructionFactory.createThis()); pos++; } for (int i = 0, len = paramTypes.length; i < len; i++) { Type paramType = paramTypes[i]; body.append(InstructionFactory.createLoad(paramType, pos)); pos += paramType.getSize(); } body.append(Utility.createInvoke(fact, classWeaver.getWorld(), interMethodBody)); Type t = BcelWorld.makeBcelType(interMethodBody.getReturnType()); if (!t.equals(returnType)) { body.append(fact.createCast(t, returnType)); } body.append(InstructionFactory.createReturn(returnType)); mg.definingType = onType; if (world.isInJava5Mode()) { String basicSignature = mangledInterMethod.getSignature(); String genericSignature = ((ResolvedMemberImpl) mangledInterMethod).getSignatureForAttribute(); if (!basicSignature.equals(genericSignature)) { // Add a signature attribute to it mg.addAttribute(createSignatureAttribute(classGen.getConstantPool(), genericSignature)); } } classWeaver.addOrReplaceLazyMethodGen(mg); addNeededSuperCallMethods(classWeaver, onType, munger.getSuperMethodsCalled()); // Work out if we need a bridge method for the new method added to the topmostimplementor. // Check if the munger being processed is a parameterized form of the original munger createBridgeIfNecessary(classWeaver, munger, unMangledInterMethod, classGen); return true; } } else { return false; } } private void createBridgeIfNecessary(BcelClassWeaver classWeaver, NewMethodTypeMunger munger, ResolvedMember unMangledInterMethod, LazyClassGen classGen) { if (munger.getDeclaredSignature() != null) { boolean needsbridging = false; ResolvedMember mungerSignature = munger.getSignature(); ResolvedMember toBridgeTo = munger.getDeclaredSignature().parameterizedWith(null, mungerSignature.getDeclaringType().resolve(getWorld()), false, munger.getTypeVariableAliases()); if (!toBridgeTo.getReturnType().getErasureSignature().equals(mungerSignature.getReturnType().getErasureSignature())) { needsbridging = true; } UnresolvedType[] originalParams = toBridgeTo.getParameterTypes(); UnresolvedType[] newParams = mungerSignature.getParameterTypes(); for (int ii = 0; ii < originalParams.length; ii++) { if (!originalParams[ii].getErasureSignature().equals(newParams[ii].getErasureSignature())) { needsbridging = true; } } if (needsbridging) { createBridge(classWeaver, unMangledInterMethod, classGen, toBridgeTo); } } } private void copyOverParameterAnnotations(LazyMethodGen receiverMethod, ResolvedMember donorMethod) { AnnotationAJ[][] pAnnos = donorMethod.getParameterAnnotations(); if (pAnnos != null) { int offset = receiverMethod.isStatic() ? 0 : 1; int param = 0; for (int i = offset; i < pAnnos.length; i++) { AnnotationAJ[] annosOnParam = pAnnos[i]; if (annosOnParam != null) { for (AnnotationAJ anno : annosOnParam) { receiverMethod.addParameterAnnotation(param, anno); } } param++; } } } private void createBridge(BcelClassWeaver weaver, ResolvedMember unMangledInterMethod, LazyClassGen classGen, ResolvedMember toBridgeTo) { Type[] paramTypes; Type returnType; InstructionList body; InstructionFactory fact; int pos; ResolvedMember bridgerMethod = AjcMemberMaker.bridgerToInterMethod(unMangledInterMethod, classGen.getType()); ResolvedMember bridgingSetter = AjcMemberMaker.interMethodBridger(toBridgeTo, aspectType, false); // pr250493 LazyMethodGen bridgeMethod = makeMethodGen(classGen, bridgingSetter); paramTypes = BcelWorld.makeBcelTypes(bridgingSetter.getParameterTypes()); Type[] bridgingToParms = BcelWorld.makeBcelTypes(unMangledInterMethod.getParameterTypes()); returnType = BcelWorld.makeBcelType(bridgingSetter.getReturnType()); body = bridgeMethod.getBody(); fact = classGen.getFactory(); pos = 0; if (!Modifier.isStatic(bridgingSetter.getModifiers())) { body.append(InstructionFactory.createThis()); pos++; } for (int i = 0, len = paramTypes.length; i < len; i++) { Type paramType = paramTypes[i]; body.append(InstructionFactory.createLoad(paramType, pos)); if (!bridgingSetter.getParameterTypes()[i].getErasureSignature().equals( unMangledInterMethod.getParameterTypes()[i].getErasureSignature())) { // System.err.println("Putting in cast from "+ // paramType+" to "+bridgingToParms[i]); body.append(fact.createCast(paramType, bridgingToParms[i])); } pos += paramType.getSize(); } body.append(Utility.createInvoke(fact, weaver.getWorld(), bridgerMethod)); body.append(InstructionFactory.createReturn(returnType)); classGen.addMethodGen(bridgeMethod); // mg.definingType = onType; } /** * Helper method to create a signature attribute based on a string signature: e.g. "Ljava/lang/Object;LI<Ljava/lang/Double;>;" */ private Signature createSignatureAttribute(ConstantPool cp, String signature) { int nameIndex = cp.addUtf8("Signature"); int sigIndex = cp.addUtf8(signature); return new Signature(nameIndex, 2, sigIndex, cp); } /** * Create any bridge method required because of covariant returns being used. This method is used in the case where an ITD is * applied to some type and it may be in an override relationship with a method from the supertype - but due to covariance there * is a mismatch in return values. Example of when required: Super defines: Object m(String s) Sub defines: String m(String s) * then we need a bridge method in Sub called 'Object m(String s)' that forwards to 'String m(String s)' */ private void createAnyBridgeMethodsForCovariance(BcelClassWeaver weaver, NewMethodTypeMunger munger, ResolvedMember unMangledInterMethod, ResolvedType onType, LazyClassGen gen, Type[] paramTypes) { // PERFORMANCE BOTTLENECK? Might need investigating, method analysis // between types in a hierarchy just seems expensive... // COVARIANCE BRIDGING // Algorithm: Step1. Check in this type - has someone already created // the bridge method? // Step2. Look above us - do we 'override' a method and yet differ in // return type (i.e. covariance) // Step3. Create a forwarding bridge method // ResolvedType superclass = onType.getSuperclass(); boolean quitRightNow = false; String localMethodName = unMangledInterMethod.getName(); String erasedSig = unMangledInterMethod.getSignatureErased(); // will be something like (LSuperB;)LFoo; String localParameterSig = erasedSig.substring(0,erasedSig.lastIndexOf(')')+1);//unMangledInterMethod.getParameterSignature(); // getParameterSignatureErased() does not include parens, which we do need. String localReturnTypeESig = unMangledInterMethod.getReturnType().getErasureSignature(); // Step1 boolean alreadyDone = false; // Compiler might have done it ResolvedMember[] localMethods = onType.getDeclaredMethods(); for (int i = 0; i < localMethods.length; i++) { ResolvedMember member = localMethods[i]; if (member.getName().equals(localMethodName)) { // Check the params if (member.getParameterSignature().equals(localParameterSig)) { alreadyDone = true; } } } // Step2 if (!alreadyDone) { // Use the iterator form of 'getMethods()' so we do as little work as necessary ResolvedType supertype = onType.getSuperclass(); if (supertype != null) { for (Iterator<ResolvedMember> iter = supertype.getMethods(true, true); iter.hasNext() && !quitRightNow;) { ResolvedMember aMethod = iter.next(); if (aMethod.getName().equals(localMethodName) && aMethod.getParameterSignature().equals(localParameterSig)) { // check the return types, if they are different we need a // bridging method. if (!aMethod.getReturnType().getErasureSignature().equals(localReturnTypeESig) && !Modifier.isPrivate(aMethod.getModifiers())) { // Step3 createBridgeMethod(weaver.getWorld(), munger, unMangledInterMethod, gen, paramTypes, aMethod); quitRightNow = true; } } } } } } /** * Create a bridge method for a particular munger. * * @param world * @param munger * @param unMangledInterMethod the method to bridge 'to' that we have already created in the 'subtype' * @param clazz the class in which to put the bridge method * @param paramTypes Parameter types for the bridge method, passed in as an optimization since the caller is likely to have * already created them. * @param theBridgeMethod */ private void createBridgeMethod(BcelWorld world, NewMethodTypeMunger munger, ResolvedMember unMangledInterMethod, LazyClassGen clazz, Type[] paramTypes, ResolvedMember theBridgeMethod) { InstructionList body; InstructionFactory fact; int pos = 0; // The bridge method in this type will have the same signature as the one in the supertype LazyMethodGen bridgeMethod = makeMethodGen(clazz, theBridgeMethod); bridgeMethod.setAccessFlags(bridgeMethod.getAccessFlags() | 0x00000040 /* BRIDGE = 0x00000040 */); // UnresolvedType[] newParams = munger.getSignature().getParameterTypes(); Type returnType = BcelWorld.makeBcelType(theBridgeMethod.getReturnType()); body = bridgeMethod.getBody(); fact = clazz.getFactory(); if (!Modifier.isStatic(unMangledInterMethod.getModifiers())) { body.append(InstructionFactory.createThis()); pos++; } for (int i = 0, len = paramTypes.length; i < len; i++) { Type paramType = paramTypes[i]; body.append(InstructionFactory.createLoad(paramType, pos)); // if (!bridgingSetter.getParameterTypes()[i].getErasureSignature(). // equals // (unMangledInterMethod.getParameterTypes()[i].getErasureSignature // ())) { // System.err.println("Putting in cast from "+paramType+" to "+ // bridgingToParms[i]); // body.append(fact.createCast(paramType,bridgingToParms[i])); // } pos += paramType.getSize(); } body.append(Utility.createInvoke(fact, world, unMangledInterMethod)); body.append(InstructionFactory.createReturn(returnType)); clazz.addMethodGen(bridgeMethod); } // Unlike toString() on a member, this does not include the declaring type private String stringifyMember(ResolvedMember member) { StringBuffer buf = new StringBuffer(); buf.append(member.getReturnType().getName()); buf.append(' '); buf.append(member.getName()); if (member.getKind() != Member.FIELD) { buf.append("("); UnresolvedType[] params = member.getParameterTypes(); if (params.length != 0) { buf.append(params[0]); for (int i = 1, len = params.length; i < len; i++) { buf.append(", "); buf.append(params[i].getName()); } } buf.append(")"); } return buf.toString(); } private boolean mungeMethodDelegate(BcelClassWeaver weaver, MethodDelegateTypeMunger munger) { World world = weaver.getWorld(); LazyClassGen gen = weaver.getLazyClassGen(); if (gen.getType().isAnnotation() || gen.getType().isEnum()) { // don't signal error as it could be a consequence of a wild type pattern return false; } ResolvedMember introduced = munger.getSignature(); ResolvedType fromType = world.resolve(introduced.getDeclaringType(), munger.getSourceLocation()); if (fromType.isRawType()) { fromType = fromType.getGenericType(); } boolean shouldApply = munger.matches(weaver.getLazyClassGen().getType(), aspectType); if (shouldApply) { Type bcelReturnType = BcelWorld.makeBcelType(introduced.getReturnType()); // If no implementation class was specified, the intention was that // the types matching the pattern // already implemented the interface, let's check that now! if (munger.getImplClassName() == null && !munger.specifiesDelegateFactoryMethod()) { boolean isOK = false; List<LazyMethodGen> existingMethods = gen.getMethodGens(); for (LazyMethodGen m : existingMethods) { if (m.getName().equals(introduced.getName()) && m.getParameterSignature().equals(introduced.getParameterSignature()) && m.getReturnType().equals(bcelReturnType)) { isOK = true; } } if (!isOK) { // the class does not implement this method, they needed to // supply a default impl class IMessage msg = new Message("@DeclareParents: No defaultImpl was specified but the type '" + gen.getName() + "' does not implement the method '" + stringifyMember(introduced) + "' defined on the interface '" + introduced.getDeclaringType() + "'", weaver.getLazyClassGen().getType().getSourceLocation(), true, new ISourceLocation[] { munger.getSourceLocation() }); weaver.getWorld().getMessageHandler().handleMessage(msg); return false; } return true; } LazyMethodGen mg = new LazyMethodGen(introduced.getModifiers() - Modifier.ABSTRACT, bcelReturnType, introduced.getName(), BcelWorld.makeBcelTypes(introduced.getParameterTypes()), BcelWorld.makeBcelTypesAsClassNames(introduced.getExceptions()), gen); // annotation copy from annotation on ITD interface if (weaver.getWorld().isInJava5Mode()) { AnnotationAJ annotationsOnRealMember[] = null; ResolvedType toLookOn = weaver.getWorld().lookupOrCreateName(introduced.getDeclaringType()); if (fromType.isRawType()) { toLookOn = fromType.getGenericType(); } // lookup the method ResolvedMember[] ms = toLookOn.getDeclaredJavaMethods(); for (ResolvedMember m : ms) { if (introduced.getName().equals(m.getName()) && introduced.getSignature().equals(m.getSignature())) { annotationsOnRealMember = m.getAnnotations(); break; } } if (annotationsOnRealMember != null) { for (AnnotationAJ anno : annotationsOnRealMember) { AnnotationGen a = ((BcelAnnotation) anno).getBcelAnnotation(); AnnotationGen ag = new AnnotationGen(a, weaver.getLazyClassGen().getConstantPool(), true); mg.addAnnotation(new BcelAnnotation(ag, weaver.getWorld())); } } } InstructionList body = new InstructionList(); InstructionFactory fact = gen.getFactory(); // getfield body.append(InstructionConstants.ALOAD_0); body.append(Utility.createGet(fact, munger.getDelegate(weaver.getLazyClassGen().getType()))); InstructionBranch ifNonNull = InstructionFactory.createBranchInstruction(Constants.IFNONNULL, null); body.append(ifNonNull); // Create and store a new instance body.append(InstructionConstants.ALOAD_0); // 'this' is where we'll store the field value // TODO for non-static case, call aspectOf() then call the factory method on the retval // TODO decide whether the value can really be cached // locate the aspect and call the static method in it if (munger.specifiesDelegateFactoryMethod()) { ResolvedMember rm = munger.getDelegateFactoryMethod(weaver.getWorld()); // Check the method parameter is compatible with the type of the instance to be passed if (rm.getArity() != 0) { ResolvedType parameterType = rm.getParameterTypes()[0].resolve(weaver.getWorld()); if (!parameterType.isAssignableFrom(weaver.getLazyClassGen().getType())) { signalError("For mixin factory method '" + rm + "': Instance type '" + weaver.getLazyClassGen().getType() + "' is not compatible with factory parameter type '" + parameterType + "'", weaver); return false; } } if (Modifier.isStatic(rm.getModifiers())) { if (rm.getArity() != 0) { body.append(InstructionConstants.ALOAD_0); } body.append(fact.createInvoke(rm.getDeclaringType().getName(), rm.getName(), rm.getSignature(), Constants.INVOKESTATIC)); body.append(Utility.createSet(fact, munger.getDelegate(weaver.getLazyClassGen().getType()))); } else { // Need to call aspectOf() to obtain the aspect instance then call the factory method upon that UnresolvedType theAspect = munger.getAspect(); body.append(fact.createInvoke(theAspect.getName(), "aspectOf", "()" + theAspect.getSignature(), Constants.INVOKESTATIC)); if (rm.getArity() != 0) { body.append(InstructionConstants.ALOAD_0); } body.append(fact.createInvoke(rm.getDeclaringType().getName(), rm.getName(), rm.getSignature(), Constants.INVOKEVIRTUAL)); body.append(Utility.createSet(fact, munger.getDelegate(weaver.getLazyClassGen().getType()))); } } else { body.append(fact.createNew(munger.getImplClassName())); body.append(InstructionConstants.DUP); body.append(fact.createInvoke(munger.getImplClassName(), "<init>", Type.VOID, Type.NO_ARGS, Constants.INVOKESPECIAL)); body.append(Utility.createSet(fact, munger.getDelegate(weaver.getLazyClassGen().getType()))); } // if not null use the instance we've got InstructionHandle ifNonNullElse = body.append(InstructionConstants.ALOAD_0); ifNonNull.setTarget(ifNonNullElse); body.append(Utility.createGet(fact, munger.getDelegate(weaver.getLazyClassGen().getType()))); // args int pos = 0; if (!Modifier.isStatic(introduced.getModifiers())) { // skip 'this' (?? can this really // happen) // body.append(InstructionFactory.createThis()); pos++; } Type[] paramTypes = BcelWorld.makeBcelTypes(introduced.getParameterTypes()); for (int i = 0, len = paramTypes.length; i < len; i++) { Type paramType = paramTypes[i]; body.append(InstructionFactory.createLoad(paramType, pos)); pos += paramType.getSize(); } body.append(Utility.createInvoke(fact, Constants.INVOKEINTERFACE, introduced)); body.append(InstructionFactory.createReturn(bcelReturnType)); mg.getBody().append(body); weaver.addLazyMethodGen(mg); weaver.getLazyClassGen().warnOnAddedMethod(mg.getMethod(), getSignature().getSourceLocation()); return true; } return false; } private boolean mungeFieldHost(BcelClassWeaver weaver, MethodDelegateTypeMunger.FieldHostTypeMunger munger) { LazyClassGen gen = weaver.getLazyClassGen(); if (gen.getType().isAnnotation() || gen.getType().isEnum()) { // don't signal error as it could be a consequence of a wild type // pattern return false; } // boolean shouldApply = munger.matches(weaver.getLazyClassGen().getType(), aspectType); // why // do // this? ResolvedMember host = AjcMemberMaker.itdAtDeclareParentsField(weaver.getLazyClassGen().getType(), munger.getSignature() .getType(), aspectType); FieldGen field = makeFieldGen(weaver.getLazyClassGen(), host); field.setModifiers(field.getModifiers() | BcelField.AccSynthetic); weaver.getLazyClassGen().addField(field, null); return true; } private ResolvedMember getRealMemberForITDFromAspect(ResolvedType aspectType, ResolvedMember lookingFor, boolean isCtorRelated) { World world = aspectType.getWorld(); boolean debug = false; if (debug) { System.err.println("Searching for a member on type: " + aspectType); System.err.println("Member we are looking for: " + lookingFor); } ResolvedMember aspectMethods[] = aspectType.getDeclaredMethods(); UnresolvedType[] lookingForParams = lookingFor.getParameterTypes(); ResolvedMember realMember = null; for (int i = 0; realMember == null && i < aspectMethods.length; i++) { ResolvedMember member = aspectMethods[i]; if (member.getName().equals(lookingFor.getName())) { UnresolvedType[] memberParams = member.getGenericParameterTypes(); if (memberParams.length == lookingForParams.length) { if (debug) { System.err.println("Reviewing potential candidates: " + member); } boolean matchOK = true; // If not related to a ctor ITD then the name is enough to // confirm we have the // right one. If it is ctor related we need to check the // params all match, although // only the erasure. if (isCtorRelated) { for (int j = 0; j < memberParams.length && matchOK; j++) { ResolvedType pMember = memberParams[j].resolve(world); ResolvedType pLookingFor = lookingForParams[j].resolve(world); if (pMember.isTypeVariableReference()) { pMember = ((TypeVariableReference) pMember).getTypeVariable().getFirstBound().resolve(world); } if (pMember.isParameterizedType() || pMember.isGenericType()) { pMember = pMember.getRawType().resolve(aspectType.getWorld()); } if (pLookingFor.isTypeVariableReference()) { pLookingFor = ((TypeVariableReference) pLookingFor).getTypeVariable().getFirstBound() .resolve(world); } if (pLookingFor.isParameterizedType() || pLookingFor.isGenericType()) { pLookingFor = pLookingFor.getRawType().resolve(world); } if (debug) { System.err.println("Comparing parameter " + j + " member=" + pMember + " lookingFor=" + pLookingFor); } if (!pMember.equals(pLookingFor)) { matchOK = false; } } } if (matchOK) { realMember = member; } } } } if (debug && realMember == null) { System.err.println("Didn't find a match"); } return realMember; } private void addNeededSuperCallMethods(BcelClassWeaver weaver, ResolvedType onType, Set<ResolvedMember> neededSuperCalls) { LazyClassGen gen = weaver.getLazyClassGen(); for (Iterator<ResolvedMember> iter = neededSuperCalls.iterator(); iter.hasNext();) { ResolvedMember superMethod = iter.next(); if (weaver.addDispatchTarget(superMethod)) { // System.err.println("super type: " + // superMethod.getDeclaringType() + ", " + gen.getType()); boolean isSuper = !superMethod.getDeclaringType().equals(gen.getType()); String dispatchName; if (isSuper) { dispatchName = NameMangler.superDispatchMethod(onType, superMethod.getName()); } else { dispatchName = NameMangler.protectedDispatchMethod(onType, superMethod.getName()); } superMethod = superMethod.resolve(weaver.getWorld()); LazyMethodGen dispatcher = makeDispatcher(gen, dispatchName, superMethod, weaver.getWorld(), isSuper); weaver.addLazyMethodGen(dispatcher); } } } private void signalError(String msgid, BcelClassWeaver weaver, UnresolvedType onType) { IMessage msg = MessageUtil.error(WeaverMessages.format(msgid, onType.getName()), getSourceLocation()); weaver.getWorld().getMessageHandler().handleMessage(msg); } // private void signalWarning(String msgString, BcelClassWeaver weaver) { // IMessage msg = MessageUtil.warn(msgString, getSourceLocation()); // weaver.getWorld().getMessageHandler().handleMessage(msg); // } private void signalError(String msgString, BcelClassWeaver weaver) { IMessage msg = MessageUtil.error(msgString, getSourceLocation()); weaver.getWorld().getMessageHandler().handleMessage(msg); } private boolean mungeNewConstructor(BcelClassWeaver weaver, NewConstructorTypeMunger newConstructorTypeMunger) { final LazyClassGen currentClass = weaver.getLazyClassGen(); final InstructionFactory fact = currentClass.getFactory(); ResolvedMember newConstructorMember = newConstructorTypeMunger.getSyntheticConstructor(); ResolvedType onType = newConstructorMember.getDeclaringType().resolve(weaver.getWorld()); if (onType.isRawType()) { onType = onType.getGenericType(); } if (onType.isAnnotation()) { signalError(WeaverMessages.ITDC_ON_ANNOTATION_NOT_ALLOWED, weaver, onType); return false; } if (onType.isEnum()) { signalError(WeaverMessages.ITDC_ON_ENUM_NOT_ALLOWED, weaver, onType); return false; } if (!onType.equals(currentClass.getType())) { return false; } ResolvedMember explicitConstructor = newConstructorTypeMunger.getExplicitConstructor(); // int declaredParameterCount = // newConstructorTypeMunger.getDeclaredParameterCount(); LazyMethodGen mg = makeMethodGen(currentClass, newConstructorMember); mg.setEffectiveSignature(newConstructorTypeMunger.getSignature(), Shadow.ConstructorExecution, true); // pr98901 // For copying the annotations across, we have to discover the real // member in the aspect // which is holding them. if (weaver.getWorld().isInJava5Mode()) { ResolvedMember interMethodDispatcher = AjcMemberMaker.postIntroducedConstructor(aspectType, onType, newConstructorTypeMunger.getSignature().getParameterTypes()); AnnotationAJ annotationsOnRealMember[] = null; ResolvedMember realMember = getRealMemberForITDFromAspect(aspectType, interMethodDispatcher, true); // 266602 - consider it missing to mean that the corresponding aspect had errors if (realMember == null) { // signalWarning("Unable to apply any annotations attached to " + munger.getSignature(), weaver); // throw new BCException("Couldn't find ITD init member '" + interMethodBody + "' on aspect " + aspectType); } else { annotationsOnRealMember = realMember.getAnnotations(); } if (annotationsOnRealMember != null) { for (int i = 0; i < annotationsOnRealMember.length; i++) { AnnotationAJ annotationX = annotationsOnRealMember[i]; AnnotationGen a = ((BcelAnnotation) annotationX).getBcelAnnotation(); AnnotationGen ag = new AnnotationGen(a, weaver.getLazyClassGen().getConstantPool(), true); mg.addAnnotation(new BcelAnnotation(ag, weaver.getWorld())); } } // the below loop fixes the very special (and very stupid) // case where an aspect declares an annotation // on an ITD it declared on itself. List<DeclareAnnotation> allDecams = weaver.getWorld().getDeclareAnnotationOnMethods(); for (Iterator<DeclareAnnotation> i = allDecams.iterator(); i.hasNext();) { DeclareAnnotation decaMC = i.next(); if (decaMC.matches(explicitConstructor, weaver.getWorld()) && mg.getEnclosingClass().getType() == aspectType) { mg.addAnnotation(decaMC.getAnnotation()); } } } // Might have to remove the default constructor - b275032 // TODO could have tagged the type munger when the fact we needed to do this was detected earlier if (mg.getArgumentTypes().length == 0) { LazyMethodGen toRemove = null; for (LazyMethodGen object : currentClass.getMethodGens()) { if (object.getName().equals("<init>") && object.getArgumentTypes().length == 0) { toRemove = object; } } if (toRemove != null) { currentClass.removeMethodGen(toRemove); } } currentClass.addMethodGen(mg); // weaver.addLazyMethodGen(freshConstructor); InstructionList body = mg.getBody(); // add to body: push arts for call to pre, from actual args starting at // 1 (skipping this), going to // declared argcount + 1 UnresolvedType[] declaredParams = newConstructorTypeMunger.getSignature().getParameterTypes(); Type[] paramTypes = mg.getArgumentTypes(); int frameIndex = 1; for (int i = 0, len = declaredParams.length; i < len; i++) { body.append(InstructionFactory.createLoad(paramTypes[i], frameIndex)); frameIndex += paramTypes[i].getSize(); } // do call to pre Member preMethod = AjcMemberMaker.preIntroducedConstructor(aspectType, onType, declaredParams); body.append(Utility.createInvoke(fact, null, preMethod)); // create a local, and store return pre stuff into it. int arraySlot = mg.allocateLocal(1); body.append(InstructionFactory.createStore(Type.OBJECT, arraySlot)); // put this on the stack body.append(InstructionConstants.ALOAD_0); // unpack pre args onto stack UnresolvedType[] superParamTypes = explicitConstructor.getParameterTypes(); for (int i = 0, len = superParamTypes.length; i < len; i++) { body.append(InstructionFactory.createLoad(Type.OBJECT, arraySlot)); body.append(Utility.createConstant(fact, i)); body.append(InstructionFactory.createArrayLoad(Type.OBJECT)); body.append(Utility.createConversion(fact, Type.OBJECT, BcelWorld.makeBcelType(superParamTypes[i]))); } // call super/this body.append(Utility.createInvoke(fact, null, explicitConstructor)); // put this back on the stack body.append(InstructionConstants.ALOAD_0); // unpack params onto stack Member postMethod = AjcMemberMaker.postIntroducedConstructor(aspectType, onType, declaredParams); UnresolvedType[] postParamTypes = postMethod.getParameterTypes(); for (int i = 1, len = postParamTypes.length; i < len; i++) { body.append(InstructionFactory.createLoad(Type.OBJECT, arraySlot)); body.append(Utility.createConstant(fact, superParamTypes.length + i - 1)); body.append(InstructionFactory.createArrayLoad(Type.OBJECT)); body.append(Utility.createConversion(fact, Type.OBJECT, BcelWorld.makeBcelType(postParamTypes[i]))); } // call post body.append(Utility.createInvoke(fact, null, postMethod)); // don't forget to return!! body.append(InstructionConstants.RETURN); return true; } private static LazyMethodGen makeDispatcher(LazyClassGen onGen, String dispatchName, ResolvedMember superMethod, BcelWorld world, boolean isSuper) { Type[] paramTypes = BcelWorld.makeBcelTypes(superMethod.getParameterTypes()); Type returnType = BcelWorld.makeBcelType(superMethod.getReturnType()); int modifiers = Modifier.PUBLIC; if (onGen.isInterface()) { modifiers |= Modifier.ABSTRACT; } LazyMethodGen mg = new LazyMethodGen(modifiers, returnType, dispatchName, paramTypes, UnresolvedType.getNames(superMethod .getExceptions()), onGen); InstructionList body = mg.getBody(); if (onGen.isInterface()) { return mg; } // assert (!superMethod.isStatic()) InstructionFactory fact = onGen.getFactory(); int pos = 0; body.append(InstructionFactory.createThis()); pos++; for (int i = 0, len = paramTypes.length; i < len; i++) { Type paramType = paramTypes[i]; body.append(InstructionFactory.createLoad(paramType, pos)); pos += paramType.getSize(); } if (isSuper) { body.append(Utility.createSuperInvoke(fact, world, superMethod)); } else { body.append(Utility.createInvoke(fact, world, superMethod)); } body.append(InstructionFactory.createReturn(returnType)); return mg; } private boolean mungeNewField(BcelClassWeaver weaver, NewFieldTypeMunger munger) { /* ResolvedMember initMethod = */munger.getInitMethod(aspectType); LazyClassGen gen = weaver.getLazyClassGen(); ResolvedMember field = munger.getSignature(); ResolvedType onType = weaver.getWorld().resolve(field.getDeclaringType(), munger.getSourceLocation()); if (onType.isRawType()) { onType = onType.getGenericType(); } boolean onInterface = onType.isInterface(); if (onType.isAnnotation()) { signalError(WeaverMessages.ITDF_ON_ANNOTATION_NOT_ALLOWED, weaver, onType); return false; } if (onType.isEnum()) { signalError(WeaverMessages.ITDF_ON_ENUM_NOT_ALLOWED, weaver, onType); return false; } ResolvedMember interMethodBody = munger.getInitMethod(aspectType); AnnotationAJ annotationsOnRealMember[] = null; // pr98901 // For copying the annotations across, we have to discover the real // member in the aspect // which is holding them. if (weaver.getWorld().isInJava5Mode()) { // the below line just gets the method with the same name in // aspectType.getDeclaredMethods(); ResolvedType toLookOn = aspectType; if (aspectType.isRawType()) { toLookOn = aspectType.getGenericType(); } ResolvedMember realMember = getRealMemberForITDFromAspect(toLookOn, interMethodBody, false); if (realMember == null) { // signalWarning("Unable to apply any annotations attached to " + munger.getSignature(), weaver); // throw new BCException("Couldn't find ITD init member '" + interMethodBody + "' on aspect " + aspectType); } else { annotationsOnRealMember = realMember.getAnnotations(); } } if (onType.equals(gen.getType())) { if (onInterface) { ResolvedMember itdfieldGetter = AjcMemberMaker.interFieldInterfaceGetter(field, onType, aspectType); LazyMethodGen mg = makeMethodGen(gen, itdfieldGetter); gen.addMethodGen(mg); LazyMethodGen mg1 = makeMethodGen(gen, AjcMemberMaker.interFieldInterfaceSetter(field, onType, aspectType)); gen.addMethodGen(mg1); } else { weaver.addInitializer(this); ResolvedMember newField = AjcMemberMaker.interFieldClassField(field, aspectType, munger.version == NewFieldTypeMunger.VersionTwo); FieldGen fg = makeFieldGen(gen, newField); if (annotationsOnRealMember != null) { for (int i = 0; i < annotationsOnRealMember.length; i++) { AnnotationAJ annotationX = annotationsOnRealMember[i]; AnnotationGen a = ((BcelAnnotation) annotationX).getBcelAnnotation(); AnnotationGen ag = new AnnotationGen(a, weaver.getLazyClassGen().getConstantPool(), true); fg.addAnnotation(ag); } } if (weaver.getWorld().isInJava5Mode()) { String basicSignature = field.getSignature(); String genericSignature = field.getReturnType().resolve(weaver.getWorld()).getSignatureForAttribute(); // String genericSignature = // ((ResolvedMemberImpl)field).getSignatureForAttribute(); if (!basicSignature.equals(genericSignature)) { // Add a signature attribute to it fg.addAttribute(createSignatureAttribute(gen.getConstantPool(), genericSignature)); } } gen.addField(fg, getSourceLocation()); } return true; } else if (onInterface && gen.getType().isTopmostImplementor(onType)) { // we know that we can't be static since we don't allow statics on interfaces if (Modifier.isStatic(field.getModifiers())) { throw new RuntimeException("unimplemented"); } boolean alreadyExists = false; // only need to check for version 2 style mungers if (munger.version==NewFieldTypeMunger.VersionTwo) { for (BcelField fieldgen: gen.getFieldGens()) { if (fieldgen.getName().equals(field.getName())) { alreadyExists=true; break; } } } // FieldGen fg = makeFieldGen(gen, AjcMemberMaker.interFieldInterfaceField(field, onType, aspectType)); ResolvedMember newField = AjcMemberMaker.interFieldInterfaceField(field, onType, aspectType, munger.version == NewFieldTypeMunger.VersionTwo); String fieldName = newField.getName(); Type fieldType = BcelWorld.makeBcelType(field.getType()); if (!alreadyExists) { weaver.addInitializer(this); FieldGen fg = makeFieldGen(gen,newField); if (annotationsOnRealMember != null) { for (int i = 0; i < annotationsOnRealMember.length; i++) { AnnotationAJ annotationX = annotationsOnRealMember[i]; AnnotationGen a = ((BcelAnnotation) annotationX).getBcelAnnotation(); AnnotationGen ag = new AnnotationGen(a, weaver.getLazyClassGen().getConstantPool(), true); fg.addAnnotation(ag); } } gen.addField(fg, getSourceLocation()); } // this uses a shadow munger to add init method to constructors // weaver.getShadowMungers().add(makeInitCallShadowMunger(initMethod) // ); ResolvedMember itdfieldGetter = AjcMemberMaker.interFieldInterfaceGetter(field, gen.getType()/* onType */, aspectType); LazyMethodGen mg = makeMethodGen(gen, itdfieldGetter); InstructionList il = new InstructionList(); InstructionFactory fact = gen.getFactory(); if (Modifier.isStatic(field.getModifiers())) { il.append(fact.createFieldAccess(gen.getClassName(), fieldName, fieldType, Constants.GETSTATIC)); } else { il.append(InstructionConstants.ALOAD_0); il.append(fact.createFieldAccess(gen.getClassName(), fieldName, fieldType, Constants.GETFIELD)); } il.append(InstructionFactory.createReturn(fieldType)); mg.getBody().insert(il); gen.addMethodGen(mg); // Check if we need bridge methods for the field getter and setter if (munger.getDeclaredSignature() != null) { // is this munger a // parameterized // form of some // original munger? ResolvedMember toBridgeTo = munger.getDeclaredSignature().parameterizedWith(null, munger.getSignature().getDeclaringType().resolve(getWorld()), false, munger.getTypeVariableAliases()); boolean needsbridging = false; if (!toBridgeTo.getReturnType().getErasureSignature() .equals(munger.getSignature().getReturnType().getErasureSignature())) { needsbridging = true; } if (needsbridging) { ResolvedMember bridgingGetter = AjcMemberMaker.interFieldInterfaceGetter(toBridgeTo, gen.getType(), aspectType); createBridgeMethodForITDF(weaver, gen, itdfieldGetter, bridgingGetter); } } ResolvedMember itdfieldSetter = AjcMemberMaker.interFieldInterfaceSetter(field, gen.getType(), aspectType); LazyMethodGen mg1 = makeMethodGen(gen, itdfieldSetter); InstructionList il1 = new InstructionList(); if (Modifier.isStatic(field.getModifiers())) { il1.append(InstructionFactory.createLoad(fieldType, 0)); il1.append(fact.createFieldAccess(gen.getClassName(), fieldName, fieldType, Constants.PUTSTATIC)); } else { il1.append(InstructionConstants.ALOAD_0); il1.append(InstructionFactory.createLoad(fieldType, 1)); il1.append(fact.createFieldAccess(gen.getClassName(), fieldName, fieldType, Constants.PUTFIELD)); } il1.append(InstructionFactory.createReturn(Type.VOID)); mg1.getBody().insert(il1); gen.addMethodGen(mg1); if (munger.getDeclaredSignature() != null) { ResolvedMember toBridgeTo = munger.getDeclaredSignature().parameterizedWith(null, munger.getSignature().getDeclaringType().resolve(getWorld()), false, munger.getTypeVariableAliases()); boolean needsbridging = false; if (!toBridgeTo.getReturnType().getErasureSignature() .equals(munger.getSignature().getReturnType().getErasureSignature())) { needsbridging = true; } if (needsbridging) { ResolvedMember bridgingSetter = AjcMemberMaker.interFieldInterfaceSetter(toBridgeTo, gen.getType(), aspectType); createBridgeMethodForITDF(weaver, gen, itdfieldSetter, bridgingSetter); } } return true; } else { return false; } } // FIXME asc combine with other createBridge.. method in this class, avoid // the duplication... private void createBridgeMethodForITDF(BcelClassWeaver weaver, LazyClassGen gen, ResolvedMember itdfieldSetter, ResolvedMember bridgingSetter) { InstructionFactory fact; LazyMethodGen bridgeMethod = makeMethodGen(gen, bridgingSetter); bridgeMethod.setAccessFlags(bridgeMethod.getAccessFlags() | 0x00000040); // BRIDGE = 0x00000040 Type[] paramTypes = BcelWorld.makeBcelTypes(bridgingSetter.getParameterTypes()); Type[] bridgingToParms = BcelWorld.makeBcelTypes(itdfieldSetter.getParameterTypes()); Type returnType = BcelWorld.makeBcelType(bridgingSetter.getReturnType()); InstructionList body = bridgeMethod.getBody(); fact = gen.getFactory(); int pos = 0; if (!Modifier.isStatic(bridgingSetter.getModifiers())) { body.append(InstructionFactory.createThis()); pos++; } for (int i = 0, len = paramTypes.length; i < len; i++) { Type paramType = paramTypes[i]; body.append(InstructionFactory.createLoad(paramType, pos)); if (!bridgingSetter.getParameterTypes()[i].getErasureSignature().equals( itdfieldSetter.getParameterTypes()[i].getErasureSignature())) { body.append(fact.createCast(paramType, bridgingToParms[i])); } pos += paramType.getSize(); } body.append(Utility.createInvoke(fact, weaver.getWorld(), itdfieldSetter)); body.append(InstructionFactory.createReturn(returnType)); gen.addMethodGen(bridgeMethod); } @Override public ConcreteTypeMunger parameterizedFor(ResolvedType target) { return new BcelTypeMunger(munger.parameterizedFor(target), aspectType); } @Override public ConcreteTypeMunger parameterizeWith(Map<String, UnresolvedType> m, World w) { return new BcelTypeMunger(munger.parameterizeWith(m, w), aspectType); } /** * Returns a list of type variable aliases used in this munger. For example, if the ITD is 'int I<A,B>.m(List<A> las,List<B> * lbs) {}' then this returns a list containing the strings "A" and "B". */ public List<String> getTypeVariableAliases() { return munger.getTypeVariableAliases(); } @Override public boolean equals(Object other) { if (!(other instanceof BcelTypeMunger)) { return false; } BcelTypeMunger o = (BcelTypeMunger) other; return ((o.getMunger() == null) ? (getMunger() == null) : o.getMunger().equals(getMunger())) && ((o.getAspectType() == null) ? (getAspectType() == null) : o.getAspectType().equals(getAspectType())); // && (AsmManager.getDefault().getHandleProvider().dependsOnLocation() ? ((o.getSourceLocation() == null) ? // (getSourceLocation() == null) // : o.getSourceLocation().equals(getSourceLocation())) // : true); // pr134471 - remove when handles are improved // to be independent of location } private volatile int hashCode = 0; @Override public int hashCode() { if (hashCode == 0) { int result = 17; result = 37 * result + ((getMunger() == null) ? 0 : getMunger().hashCode()); result = 37 * result + ((getAspectType() == null) ? 0 : getAspectType().hashCode()); hashCode = result; } return hashCode; } }
387,718
Bug 387718 RuntimeException when trying to compile broken code
java.lang.RuntimeException at org.aspectj.weaver.NameMangler.makeVisibilityName(NameMangler.java:297) at org.aspectj.weaver.NameMangler.interMethod(NameMangler.java:242) at org.aspectj.weaver.AjcMemberMaker.interMethod(AjcMemberMaker.java:538) at org.aspectj.ajdt.internal.compiler.problem.AjProblemReporter.methodMustOverride(AjProblemReporter.java:385) at org.aspectj.org.eclipse.jdt.internal.compiler.ast.MethodDeclaration.resolveStatements(M ... dJob.java:241) at org.eclipse.core.internal.jobs.Worker.run(Worker.java:54) Compile error: RuntimeException thrown: protected inter-types not allowed
resolved fixed
cbb6f5a
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2012-08-22T20:13:54Z"
"2012-08-21T17:26:40Z"
org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/compiler/problem/AjProblemReporter.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Eclipse Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * PARC initial implementation * ******************************************************************/ package org.aspectj.ajdt.internal.compiler.problem; import java.io.PrintWriter; import java.io.StringWriter; import java.lang.reflect.Modifier; import java.util.Collection; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Set; import org.aspectj.ajdt.internal.compiler.ast.AspectDeclaration; import org.aspectj.ajdt.internal.compiler.ast.DeclareAnnotationDeclaration; import org.aspectj.ajdt.internal.compiler.ast.PointcutDeclaration; import org.aspectj.ajdt.internal.compiler.ast.Proceed; import org.aspectj.ajdt.internal.compiler.lookup.EclipseFactory; import org.aspectj.ajdt.internal.compiler.lookup.InterTypeMethodBinding; import org.aspectj.ajdt.internal.compiler.lookup.PrivilegedFieldBinding; import org.aspectj.bridge.context.CompilationAndWeavingContext; import org.aspectj.org.eclipse.jdt.core.compiler.CharOperation; import org.aspectj.org.eclipse.jdt.core.compiler.IProblem; import org.aspectj.org.eclipse.jdt.internal.compiler.CompilationResult; import org.aspectj.org.eclipse.jdt.internal.compiler.IErrorHandlingPolicy; import org.aspectj.org.eclipse.jdt.internal.compiler.IProblemFactory; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.ASTNode; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.Annotation; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.Argument; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.ExplicitConstructorCall; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.Expression; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.FieldDeclaration; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.LocalDeclaration; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.QualifiedNameReference; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.TypeDeclaration; import org.aspectj.org.eclipse.jdt.internal.compiler.impl.CompilerOptions; import org.aspectj.org.eclipse.jdt.internal.compiler.impl.ReferenceContext; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.ArrayBinding; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.IPrivilegedHandler; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.MethodBinding; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.ParameterizedMethodBinding; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.ReferenceBinding; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.SourceTypeBinding; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.TagBits; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.TypeBinding; import org.aspectj.org.eclipse.jdt.internal.compiler.problem.ProblemReporter; import org.aspectj.org.eclipse.jdt.internal.compiler.problem.ProblemSeverities; import org.aspectj.util.FuzzyBoolean; import org.aspectj.weaver.AjcMemberMaker; import org.aspectj.weaver.ConcreteTypeMunger; 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.DeclareAnnotation; import org.aspectj.weaver.patterns.DeclareParents; import org.aspectj.weaver.patterns.DeclareSoft; import org.aspectj.weaver.patterns.TypePattern; /** * Extends problem reporter to support compiler-side implementation of declare soft. Also overrides error reporting for the need to * implement abstract methods to account for inter-type declarations and pointcut declarations. This second job might be better done * directly in the SourceTypeBinding/ClassScope classes. * * @author Jim Hugunin */ public class AjProblemReporter extends ProblemReporter { private static final boolean DUMP_STACK = false; public EclipseFactory factory; public AjProblemReporter(IErrorHandlingPolicy policy, CompilerOptions options, IProblemFactory problemFactory) { super(policy, options, problemFactory); } public void unhandledException(TypeBinding exceptionType, ASTNode location) { if (!factory.getWorld().getDeclareSoft().isEmpty()) { Shadow callSite = factory.makeShadow(location, referenceContext); Shadow enclosingExec = factory.makeShadow(referenceContext); // PR 72157 - calls to super / this within a constructor are not part of the cons join point. if ((callSite == null) && (enclosingExec.getKind() == Shadow.ConstructorExecution) && (location instanceof ExplicitConstructorCall)) { super.unhandledException(exceptionType, location); return; } // System.err.println("about to show error for unhandled exception: " + new String(exceptionType.sourceName()) + // " at " + location + " in " + referenceContext); for (Iterator i = factory.getWorld().getDeclareSoft().iterator(); i.hasNext();) { DeclareSoft d = (DeclareSoft) i.next(); // We need the exceptionType to match the type in the declare soft statement // This means it must either be the same type or a subtype ResolvedType throwException = factory.fromEclipse((ReferenceBinding) exceptionType); FuzzyBoolean isExceptionTypeOrSubtype = d.getException().matchesInstanceof(throwException); if (!isExceptionTypeOrSubtype.alwaysTrue()) continue; if (callSite != null) { FuzzyBoolean match = d.getPointcut().match(callSite); if (match.alwaysTrue()) { // System.err.println("matched callSite: " + callSite + " with " + d); return; } else if (!match.alwaysFalse()) { // !!! need this check to happen much sooner // throw new RuntimeException("unimplemented, shouldn't have fuzzy match here"); } } if (enclosingExec != null) { FuzzyBoolean match = d.getPointcut().match(enclosingExec); if (match.alwaysTrue()) { // System.err.println("matched enclosingExec: " + enclosingExec + " with " + d); return; } else if (!match.alwaysFalse()) { // !!! need this check to happen much sooner // throw new RuntimeException("unimplemented, shouldn't have fuzzy match here"); } } } } // ??? is this always correct if (location instanceof Proceed) { return; } super.unhandledException(exceptionType, location); } private boolean isPointcutDeclaration(MethodBinding binding) { return CharOperation.prefixEquals(PointcutDeclaration.mangledPrefix, binding.selector); } private boolean isIntertypeDeclaration(MethodBinding binding) { return (binding instanceof InterTypeMethodBinding); } public void abstractMethodCannotBeOverridden(SourceTypeBinding type, MethodBinding concreteMethod) { if (isPointcutDeclaration(concreteMethod)) { return; } super.abstractMethodCannotBeOverridden(type, concreteMethod); } public void inheritedMethodReducesVisibility(SourceTypeBinding type, MethodBinding concreteMethod, MethodBinding[] abstractMethods) { // if we implemented this method by a public inter-type declaration, then there is no error ResolvedType onTypeX = null; // If the type is anonymous, look at its supertype if (!type.isAnonymousType()) { onTypeX = factory.fromEclipse(type); } else { // Hmmm. If the ITD is on an interface that is being 'instantiated' using an anonymous type, // we sort it out elsewhere and don't come into this method - // so we don't have to worry about interfaces, just the superclass. onTypeX = factory.fromEclipse(type.superclass()); // abstractMethod.declaringClass); } for (Iterator i = onTypeX.getInterTypeMungersIncludingSupers().iterator(); i.hasNext();) { ConcreteTypeMunger m = (ConcreteTypeMunger) i.next(); ResolvedMember sig = m.getSignature(); if (!Modifier.isAbstract(sig.getModifiers())) { if (ResolvedType.matches( AjcMemberMaker.interMethod(sig, m.getAspectType(), sig.getDeclaringType().resolve(factory.getWorld()) .isInterface()), factory.makeResolvedMember(concreteMethod))) { return; } } } super.inheritedMethodReducesVisibility(type, concreteMethod, abstractMethods); } // if either of the MethodBinding is an ITD, we have already reported it. public void staticAndInstanceConflict(MethodBinding currentMethod, MethodBinding inheritedMethod) { if (currentMethod instanceof InterTypeMethodBinding) return; if (inheritedMethod instanceof InterTypeMethodBinding) return; super.staticAndInstanceConflict(currentMethod, inheritedMethod); } public void abstractMethodMustBeImplemented(SourceTypeBinding type, MethodBinding abstractMethod) { // if this is a PointcutDeclaration then there is no error if (isPointcutDeclaration(abstractMethod)) return; if (isIntertypeDeclaration(abstractMethod)) return; // when there is a problem with an ITD not being implemented, it will be reported elsewhere if (CharOperation.prefixEquals("ajc$interField".toCharArray(), abstractMethod.selector)) { // ??? think through how this could go wrong return; } // if we implemented this method by an inter-type declaration, then there is no error // ??? be sure this is always right ResolvedType onTypeX = null; // If the type is anonymous, look at its supertype if (!type.isAnonymousType()) { onTypeX = factory.fromEclipse(type); } else { // Hmmm. If the ITD is on an interface that is being 'instantiated' using an anonymous type, // we sort it out elsewhere and don't come into this method - // so we don't have to worry about interfaces, just the superclass. onTypeX = factory.fromEclipse(type.superclass()); // abstractMethod.declaringClass); } if (onTypeX.isRawType()) onTypeX = onTypeX.getGenericType(); List<ConcreteTypeMunger> mungers = onTypeX.getInterTypeMungersIncludingSupers(); for (ConcreteTypeMunger m : mungers) { ResolvedMember sig = m.getSignature(); if (sig != null && !Modifier.isAbstract(sig.getModifiers())) { ResolvedMember abstractMember = factory.makeResolvedMember(abstractMethod); if (abstractMember.getName().startsWith("ajc$interMethodDispatch")) { ResolvedType dType = factory.getWorld().resolve(sig.getDeclaringType(), false); if (ResolvedType.matches(AjcMemberMaker.interMethod(sig, m.getAspectType(), dType.isInterface()), abstractMember)) { return; } } else { // In this case we have something like: // interface I {} // abstract class C implements I { abstract void foo();} // class D extends C {} // ITD: public void I.foo() {...} // The ITD is providing the implementation of foo in the class D but when checking for whether the abstract // method is overridden, we won't be looking at whether the ITD overrides ajc$interMethodDispath$...foo but // whether it overrides the foo method from class C if (ResolvedType.matches(sig, factory.makeResolvedMember(abstractMethod))) return; } } } super.abstractMethodMustBeImplemented(type, abstractMethod); } /* * (non-Javadoc) * * @see * org.aspectj.org.eclipse.jdt.internal.compiler.problem.ProblemReporter#disallowedTargetForAnnotation(org.aspectj.org.eclipse * .jdt.internal.compiler.ast.Annotation) */ public void disallowedTargetForAnnotation(Annotation annotation) { // if the annotation's recipient is an ITD, it might be allowed after all... if (annotation.recipient instanceof MethodBinding) { MethodBinding binding = (MethodBinding) annotation.recipient; String name = new String(binding.selector); if (name.startsWith("ajc$")) { long metaTagBits = annotation.resolvedType.getAnnotationTagBits(); // could be forward reference if (name.indexOf("interField") != -1) { if ((metaTagBits & TagBits.AnnotationForField) != 0) return; } else if (name.indexOf("interConstructor") != -1) { if ((metaTagBits & TagBits.AnnotationForConstructor) != 0) return; } else if (name.indexOf("interMethod") != -1) { if ((metaTagBits & TagBits.AnnotationForMethod) != 0) return; } else if (name.indexOf("declare_" + DeclareAnnotation.AT_TYPE + "_") != -1) { if ((metaTagBits & TagBits.AnnotationForAnnotationType) != 0 || (metaTagBits & TagBits.AnnotationForType) != 0) return; } else if (name.indexOf("declare_" + DeclareAnnotation.AT_FIELD + "_") != -1) { if ((metaTagBits & TagBits.AnnotationForField) != 0) return; } else if (name.indexOf("declare_" + DeclareAnnotation.AT_CONSTRUCTOR + "_") != -1) { if ((metaTagBits & TagBits.AnnotationForConstructor) != 0) return; } else if (name.indexOf("declare_eow") != -1) { if ((metaTagBits & TagBits.AnnotationForField) != 0) return; } } } // not our special case, report the problem... super.disallowedTargetForAnnotation(annotation); } public void overridesPackageDefaultMethod(MethodBinding localMethod, MethodBinding inheritedMethod) { if (new String(localMethod.selector).startsWith("ajc$")) return; super.overridesPackageDefaultMethod(localMethod, inheritedMethod); } public void handle(int problemId, String[] problemArguments, String[] messageArguments, int severity, int problemStartPosition, int problemEndPosition, ReferenceContext referenceContext, CompilationResult unitResult) { if (severity != ProblemSeverities.Ignore && DUMP_STACK) { Thread.dumpStack(); } super.handle(problemId, problemArguments, 0, // no message elaboration messageArguments, severity, problemStartPosition, problemEndPosition, referenceContext, unitResult); } // PR71076 public void javadocMissingParamTag(char[] name, int sourceStart, int sourceEnd, int modifiers) { boolean reportIt = true; String sName = new String(name); if (sName.startsWith("ajc$")) reportIt = false; if (sName.equals("thisJoinPoint")) reportIt = false; if (sName.equals("thisJoinPointStaticPart")) reportIt = false; if (sName.equals("thisEnclosingJoinPointStaticPart")) reportIt = false; if (sName.equals("ajc_aroundClosure")) reportIt = false; if (reportIt) super.javadocMissingParamTag(name, sourceStart, sourceEnd, modifiers); } public void abstractMethodInAbstractClass(SourceTypeBinding type, AbstractMethodDeclaration methodDecl) { String abstractMethodName = new String(methodDecl.selector); if (abstractMethodName.startsWith("ajc$pointcut")) { // This will already have been reported, see: PointcutDeclaration.postParse() return; } String[] arguments = new String[] { new String(type.sourceName()), abstractMethodName }; super.handle(IProblem.AbstractMethodInAbstractClass, arguments, arguments, methodDecl.sourceStart, methodDecl.sourceEnd, this.referenceContext, this.referenceContext == null ? null : this.referenceContext.compilationResult()); } /** * Called when there is an ITD marked @override that doesn't override a supertypes method. The method and the binding are passed * - some information is useful from each. The 'method' knows about source offsets for the message, the 'binding' has the * signature of what the ITD is trying to be in the target class. */ public void itdMethodMustOverride(AbstractMethodDeclaration method, MethodBinding binding) { this.handle(IProblem.MethodMustOverride, new String[] { new String(binding.selector), typesAsString(binding.isVarargs(), binding.parameters, false), new String(binding.declaringClass.readableName()), }, new String[] { new String(binding.selector), typesAsString(binding.isVarargs(), binding.parameters, true), new String(binding.declaringClass.shortReadableName()), }, method.sourceStart, method.sourceEnd, this.referenceContext, this.referenceContext == null ? null : this.referenceContext.compilationResult()); } /** * Overrides the implementation in ProblemReporter and is ITD aware. To report a *real* problem with an ITD marked @override, * the other methodMustOverride() method is used. */ public void methodMustOverride(AbstractMethodDeclaration method, long complianceLevel) { // ignore ajc$ methods if (new String(method.selector).startsWith("ajc$")) return; ResolvedMember possiblyErroneousRm = factory.makeResolvedMember(method.binding); ResolvedType onTypeX = factory.fromEclipse(method.binding.declaringClass); // Can't use 'getInterTypeMungersIncludingSupers()' since that will exclude abstract ITDs // on any super classes - so we have to trawl up ourselves.. I wonder if this problem // affects other code in the problem reporter that looks through ITDs... ResolvedType supertypeToLookAt = onTypeX.getSuperclass(); while (supertypeToLookAt != null) { List itMungers = supertypeToLookAt.getInterTypeMungers(); for (Iterator i = itMungers.iterator(); i.hasNext();) { ConcreteTypeMunger m = (ConcreteTypeMunger) i.next(); ResolvedMember sig = m.getSignature(); if (sig == null) continue; // we aren't interested in other kinds of munger UnresolvedType dType = sig.getDeclaringType(); if (dType == null) continue; ResolvedType resolvedDeclaringType = dType.resolve(factory.getWorld()); ResolvedMember rm = AjcMemberMaker.interMethod(sig, m.getAspectType(), resolvedDeclaringType.isInterface()); if (ResolvedType.matches(rm, possiblyErroneousRm)) { // match, so dont need to report a problem! return; } } supertypeToLookAt = supertypeToLookAt.getSuperclass(); } // report the error... super.methodMustOverride(method,complianceLevel); } private String typesAsString(boolean isVarargs, TypeBinding[] types, boolean makeShort) { StringBuffer buffer = new StringBuffer(10); for (int i = 0, length = types.length; i < length; i++) { if (i != 0) buffer.append(", "); //$NON-NLS-1$ TypeBinding type = types[i]; boolean isVarargType = isVarargs && i == length - 1; if (isVarargType) type = ((ArrayBinding) type).elementsType(); buffer.append(new String(makeShort ? type.shortReadableName() : type.readableName())); if (isVarargType) buffer.append("..."); //$NON-NLS-1$ } return buffer.toString(); } public void visibilityConflict(MethodBinding currentMethod, MethodBinding inheritedMethod) { // Not quite sure if the conditions on this test are right - basically I'm saying // DONT WORRY if its ITDs since the error will be reported another way... if (isIntertypeDeclaration(currentMethod) && isIntertypeDeclaration(inheritedMethod) && Modifier.isPrivate(currentMethod.modifiers) && Modifier.isPrivate(inheritedMethod.modifiers)) { return; } super.visibilityConflict(currentMethod, inheritedMethod); } public void unusedPrivateType(TypeDeclaration typeDecl) { // don't output unused type warnings for aspects! if (typeDecl instanceof AspectDeclaration) return; if (typeDecl.enclosingType != null && (typeDecl.enclosingType instanceof AspectDeclaration)) { AspectDeclaration ad = (AspectDeclaration) typeDecl.enclosingType; if (ad.concreteName != null) { List declares = ad.concreteName.declares; for (Iterator iter = declares.iterator(); iter.hasNext();) { Object dec = iter.next(); if (dec instanceof DeclareParents) { DeclareParents decp = (DeclareParents) dec; TypePattern[] newparents = decp.getParents().getTypePatterns(); for (int i = 0; i < newparents.length; i++) { TypePattern pattern = newparents[i]; UnresolvedType ut = pattern.getExactType(); if (ut == null) continue; if (CharOperation.compareWith(typeDecl.binding.signature(), ut.getSignature().toCharArray()) == 0) return; } } } } } super.unusedPrivateType(typeDecl); } public void abstractMethodInConcreteClass(SourceTypeBinding type) { if (type.scope!=null && type.scope.referenceContext instanceof AspectDeclaration) { // TODO could put out an Aspect specific message here return; } super.abstractMethodInConcreteClass(type); } // Don't warn if there is an ITD method/ctor from a privileged aspect public void unusedPrivateField(FieldDeclaration fieldDecl) { if (fieldDecl!=null && fieldDecl.binding != null && fieldDecl.binding.declaringClass != null) { ReferenceBinding type = fieldDecl.binding.declaringClass; ResolvedType weaverType = null; if (!type.isAnonymousType()) { weaverType = factory.fromEclipse(type); } else { weaverType = factory.fromEclipse(type.superclass()); } Set checked = new HashSet(); for (Iterator i = weaverType.getInterTypeMungersIncludingSupers().iterator(); i.hasNext();) { ConcreteTypeMunger m = (ConcreteTypeMunger) i.next(); ResolvedType theAspect = m.getAspectType(); if (!checked.contains(theAspect)) { TypeBinding tb = factory.makeTypeBinding(m.getAspectType()); // Let's check the privilegedHandler from that aspect if (tb instanceof SourceTypeBinding) { // BinaryTypeBinding is also a SourceTypeBinding ;) IPrivilegedHandler privilegedHandler = ((SourceTypeBinding) tb).privilegedHandler; if (privilegedHandler != null) { if (privilegedHandler.definesPrivilegedAccessToField(fieldDecl.binding)) { return; } } else if (theAspect instanceof ReferenceType) { // ResolvedMember rm = factory.makeResolvedMember(fieldDecl.binding); String fname = new String(fieldDecl.name); Collection/* ResolvedMember */privvies = ((ReferenceType) theAspect).getPrivilegedAccesses(); // On an incremental compile the information is in the bcel delegate if (privvies != null) { for (Iterator iterator = privvies.iterator(); iterator.hasNext();) { ResolvedMember priv = (ResolvedMember) iterator.next(); if (priv.getName().equals(fname)) { return; } } } } } checked.add(theAspect); } } } super.unusedPrivateField(fieldDecl); } public void unusedPrivateMethod(AbstractMethodDeclaration methodDecl) { // don't output unused warnings for pointcuts... if (!(methodDecl instanceof PointcutDeclaration)) super.unusedPrivateMethod(methodDecl); } public void caseExpressionMustBeConstant(Expression expression) { if (expression instanceof QualifiedNameReference) { QualifiedNameReference qnr = (QualifiedNameReference) expression; if (qnr.otherBindings != null && qnr.otherBindings.length > 0 && qnr.otherBindings[0] instanceof PrivilegedFieldBinding) { super.signalError(expression.sourceStart, expression.sourceEnd, "Fields accessible due to an aspect being privileged can not be used in switch statements"); referenceContext.tagAsHavingErrors(); return; } } super.caseExpressionMustBeConstant(expression); } public void unusedArgument(LocalDeclaration localDecl) { // don't warn if this is an aj synthetic arg String argType = new String(localDecl.type.resolvedType.signature()); if (argType.startsWith("Lorg/aspectj/runtime/internal")) return; // If the unused argument is in a pointcut, don't report the problem (for now... pr148219) if (localDecl instanceof Argument) { Argument arg = (Argument) localDecl; if (arg.binding != null && arg.binding.declaringScope != null) { ReferenceContext context = arg.binding.declaringScope.referenceContext(); if (context != null && context instanceof PointcutDeclaration) return; } } if (new String(localDecl.name).startsWith("ajc$")) { // Do not report problems for infrastructure variables beyond the users control - pr195090 return; } super.unusedArgument(localDecl); } /** * A side-effect of the way that we handle itds on default methods on top-most implementors of interfaces is that a class * acquiring a final default ITD will erroneously report that it can't override its own member. This method detects that * situation. */ public void finalMethodCannotBeOverridden(MethodBinding currentMethod, MethodBinding inheritedMethod) { if (currentMethod == inheritedMethod) return; super.finalMethodCannotBeOverridden(currentMethod, inheritedMethod); } /** * The method verifier is a bit 'keen' and doesn't cope well with ITDMs which are of course to be considered a 'default' * implementation if the target type doesn't supply one. This test may not be complete - it is possible that it should read if * *either* is an ITD...but I dont have a testcase that shows that is required. yet. (pr115788) */ public void duplicateInheritedMethods(SourceTypeBinding type, MethodBinding inheritedMethod1, MethodBinding inheritedMethod2) { if (inheritedMethod1 instanceof InterTypeMethodBinding || inheritedMethod2 instanceof InterTypeMethodBinding) return; if ((inheritedMethod1 instanceof ParameterizedMethodBinding) && ((ParameterizedMethodBinding) inheritedMethod1).original() instanceof InterTypeMethodBinding) return; if ((inheritedMethod2 instanceof ParameterizedMethodBinding) && ((ParameterizedMethodBinding) inheritedMethod2).original() instanceof InterTypeMethodBinding) return; super.duplicateInheritedMethods(type, inheritedMethod1, inheritedMethod2); } /** * All problems end up routed through here at some point... */ public IProblem createProblem(char[] fileName, int problemId, String[] problemArguments, String[] messageArguments, int severity, int problemStartPosition, int problemEndPosition, int lineNumber) { IProblem problem = super.createProblem(fileName, problemId, problemArguments, messageArguments, severity, problemStartPosition, problemEndPosition, lineNumber, 0); if (factory.getWorld().isInPinpointMode()) { MessageIssued ex = new MessageIssued(); ex.fillInStackTrace(); StringWriter sw = new StringWriter(); ex.printStackTrace(new PrintWriter(sw)); StringBuffer sb = new StringBuffer(); sb.append(CompilationAndWeavingContext.getCurrentContext()); sb.append(sw.toString()); problem = new PinpointedProblem(problem, sb.toString()); } return problem; } private static class MessageIssued extends RuntimeException { public String getMessage() { return "message issued..."; } } private static class PinpointedProblem implements IProblem { private IProblem delegate; private String message; public PinpointedProblem(IProblem aProblem, String pinpoint) { this.delegate = aProblem; // if this was a problem that came via the weaver, it will already have // pinpoint info, don't do it twice... if (delegate.getMessage().indexOf("message issued...") == -1) { this.message = delegate.getMessage() + "\n" + pinpoint; } else { this.message = delegate.getMessage(); } } public String[] getArguments() { return delegate.getArguments(); } public int getID() { return delegate.getID(); } public String getMessage() { return message; } public char[] getOriginatingFileName() { return delegate.getOriginatingFileName(); } public int getSourceEnd() { return delegate.getSourceEnd(); } public int getSourceLineNumber() { return delegate.getSourceLineNumber(); } public int getSourceStart() { return delegate.getSourceStart(); } public boolean isError() { return delegate.isError(); } public boolean isWarning() { return delegate.isWarning(); } public void setSourceEnd(int sourceEnd) { delegate.setSourceEnd(sourceEnd); } public void setSourceLineNumber(int lineNumber) { delegate.setSourceLineNumber(lineNumber); } public void setSourceStart(int sourceStart) { delegate.setSourceStart(sourceStart); } public void setSeeAlsoProblems(IProblem[] problems) { delegate.setSeeAlsoProblems(problems); } public IProblem[] seeAlso() { return delegate.seeAlso(); } public void setSupplementaryMessageInfo(String msg) { delegate.setSupplementaryMessageInfo(msg); } public String getSupplementaryMessageInfo() { return delegate.getSupplementaryMessageInfo(); } } public void duplicateMethodInType(SourceTypeBinding type, AbstractMethodDeclaration methodDecl, boolean equalParameters, int severity) { if (new String(methodDecl.selector).startsWith("ajc$interMethod")) { // this is an ITD clash and will be reported in another way by AspectJ (173602) return; } super.duplicateMethodInType(type, methodDecl, equalParameters, severity); } // pr246393 - if we are going to complain about privileged, we clearly don't know what is going on, so don't // confuse the user public void parseErrorInsertAfterToken(int start, int end, int currentKind, char[] errorTokenSource, String errorTokenName, String expectedToken) { if (expectedToken.equals("privileged")) { super.parseErrorNoSuggestion(start, end, currentKind, errorTokenSource, errorTokenName); } else { super.parseErrorInsertAfterToken(start, end, currentKind, errorTokenSource, errorTokenName, expectedToken); } } public void missingValueForAnnotationMember(Annotation annotation, char[] memberName) { if (referenceContext instanceof DeclareAnnotationDeclaration) { // If a remover then the values are not necessary if (((DeclareAnnotationDeclaration) referenceContext).isRemover()) { return; } } super.missingValueForAnnotationMember(annotation, memberName); } }
387,444
Bug 387444 Softening exception in try-with-resources
null
resolved fixed
76d695f
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2012-08-23T19:19:58Z"
"2012-08-16T23:33:20Z"
org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/compiler/problem/AjProblemReporter.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Eclipse Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * PARC initial implementation * ******************************************************************/ package org.aspectj.ajdt.internal.compiler.problem; import java.io.PrintWriter; import java.io.StringWriter; import java.lang.reflect.Modifier; import java.util.Collection; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Set; import org.aspectj.ajdt.internal.compiler.ast.AspectDeclaration; import org.aspectj.ajdt.internal.compiler.ast.DeclareAnnotationDeclaration; import org.aspectj.ajdt.internal.compiler.ast.PointcutDeclaration; import org.aspectj.ajdt.internal.compiler.ast.Proceed; import org.aspectj.ajdt.internal.compiler.lookup.EclipseFactory; import org.aspectj.ajdt.internal.compiler.lookup.InterTypeMethodBinding; import org.aspectj.ajdt.internal.compiler.lookup.PrivilegedFieldBinding; import org.aspectj.bridge.context.CompilationAndWeavingContext; import org.aspectj.org.eclipse.jdt.core.compiler.CharOperation; import org.aspectj.org.eclipse.jdt.core.compiler.IProblem; import org.aspectj.org.eclipse.jdt.internal.compiler.CompilationResult; import org.aspectj.org.eclipse.jdt.internal.compiler.IErrorHandlingPolicy; import org.aspectj.org.eclipse.jdt.internal.compiler.IProblemFactory; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.ASTNode; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.Annotation; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.Argument; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.ExplicitConstructorCall; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.Expression; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.FieldDeclaration; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.LocalDeclaration; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.QualifiedNameReference; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.TypeDeclaration; import org.aspectj.org.eclipse.jdt.internal.compiler.impl.CompilerOptions; import org.aspectj.org.eclipse.jdt.internal.compiler.impl.ReferenceContext; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.ArrayBinding; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.IPrivilegedHandler; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.MethodBinding; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.ParameterizedMethodBinding; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.ReferenceBinding; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.SourceTypeBinding; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.TagBits; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.TypeBinding; import org.aspectj.org.eclipse.jdt.internal.compiler.problem.ProblemReporter; import org.aspectj.org.eclipse.jdt.internal.compiler.problem.ProblemSeverities; import org.aspectj.util.FuzzyBoolean; import org.aspectj.weaver.AjcMemberMaker; import org.aspectj.weaver.ConcreteTypeMunger; import org.aspectj.weaver.ReferenceType; import org.aspectj.weaver.ResolvedMember; import org.aspectj.weaver.ResolvedType; import org.aspectj.weaver.ResolvedTypeMunger; import org.aspectj.weaver.Shadow; import org.aspectj.weaver.UnresolvedType; import org.aspectj.weaver.patterns.DeclareAnnotation; import org.aspectj.weaver.patterns.DeclareParents; import org.aspectj.weaver.patterns.DeclareSoft; import org.aspectj.weaver.patterns.TypePattern; /** * Extends problem reporter to support compiler-side implementation of declare soft. Also overrides error reporting for the need to * implement abstract methods to account for inter-type declarations and pointcut declarations. This second job might be better done * directly in the SourceTypeBinding/ClassScope classes. * * @author Jim Hugunin */ public class AjProblemReporter extends ProblemReporter { private static final boolean DUMP_STACK = false; public EclipseFactory factory; public AjProblemReporter(IErrorHandlingPolicy policy, CompilerOptions options, IProblemFactory problemFactory) { super(policy, options, problemFactory); } public void unhandledException(TypeBinding exceptionType, ASTNode location) { if (!factory.getWorld().getDeclareSoft().isEmpty()) { Shadow callSite = factory.makeShadow(location, referenceContext); Shadow enclosingExec = factory.makeShadow(referenceContext); // PR 72157 - calls to super / this within a constructor are not part of the cons join point. if ((callSite == null) && (enclosingExec.getKind() == Shadow.ConstructorExecution) && (location instanceof ExplicitConstructorCall)) { super.unhandledException(exceptionType, location); return; } // System.err.println("about to show error for unhandled exception: " + new String(exceptionType.sourceName()) + // " at " + location + " in " + referenceContext); for (Iterator i = factory.getWorld().getDeclareSoft().iterator(); i.hasNext();) { DeclareSoft d = (DeclareSoft) i.next(); // We need the exceptionType to match the type in the declare soft statement // This means it must either be the same type or a subtype ResolvedType throwException = factory.fromEclipse((ReferenceBinding) exceptionType); FuzzyBoolean isExceptionTypeOrSubtype = d.getException().matchesInstanceof(throwException); if (!isExceptionTypeOrSubtype.alwaysTrue()) continue; if (callSite != null) { FuzzyBoolean match = d.getPointcut().match(callSite); if (match.alwaysTrue()) { // System.err.println("matched callSite: " + callSite + " with " + d); return; } else if (!match.alwaysFalse()) { // !!! need this check to happen much sooner // throw new RuntimeException("unimplemented, shouldn't have fuzzy match here"); } } if (enclosingExec != null) { FuzzyBoolean match = d.getPointcut().match(enclosingExec); if (match.alwaysTrue()) { // System.err.println("matched enclosingExec: " + enclosingExec + " with " + d); return; } else if (!match.alwaysFalse()) { // !!! need this check to happen much sooner // throw new RuntimeException("unimplemented, shouldn't have fuzzy match here"); } } } } // ??? is this always correct if (location instanceof Proceed) { return; } super.unhandledException(exceptionType, location); } private boolean isPointcutDeclaration(MethodBinding binding) { return CharOperation.prefixEquals(PointcutDeclaration.mangledPrefix, binding.selector); } private boolean isIntertypeDeclaration(MethodBinding binding) { return (binding instanceof InterTypeMethodBinding); } public void abstractMethodCannotBeOverridden(SourceTypeBinding type, MethodBinding concreteMethod) { if (isPointcutDeclaration(concreteMethod)) { return; } super.abstractMethodCannotBeOverridden(type, concreteMethod); } public void inheritedMethodReducesVisibility(SourceTypeBinding type, MethodBinding concreteMethod, MethodBinding[] abstractMethods) { // if we implemented this method by a public inter-type declaration, then there is no error ResolvedType onTypeX = null; // If the type is anonymous, look at its supertype if (!type.isAnonymousType()) { onTypeX = factory.fromEclipse(type); } else { // Hmmm. If the ITD is on an interface that is being 'instantiated' using an anonymous type, // we sort it out elsewhere and don't come into this method - // so we don't have to worry about interfaces, just the superclass. onTypeX = factory.fromEclipse(type.superclass()); // abstractMethod.declaringClass); } for (Iterator i = onTypeX.getInterTypeMungersIncludingSupers().iterator(); i.hasNext();) { ConcreteTypeMunger m = (ConcreteTypeMunger) i.next(); ResolvedMember sig = m.getSignature(); if (!Modifier.isAbstract(sig.getModifiers())) { if (ResolvedType.matches( AjcMemberMaker.interMethod(sig, m.getAspectType(), sig.getDeclaringType().resolve(factory.getWorld()) .isInterface()), factory.makeResolvedMember(concreteMethod))) { return; } } } super.inheritedMethodReducesVisibility(type, concreteMethod, abstractMethods); } // if either of the MethodBinding is an ITD, we have already reported it. public void staticAndInstanceConflict(MethodBinding currentMethod, MethodBinding inheritedMethod) { if (currentMethod instanceof InterTypeMethodBinding) return; if (inheritedMethod instanceof InterTypeMethodBinding) return; super.staticAndInstanceConflict(currentMethod, inheritedMethod); } public void abstractMethodMustBeImplemented(SourceTypeBinding type, MethodBinding abstractMethod) { // if this is a PointcutDeclaration then there is no error if (isPointcutDeclaration(abstractMethod)) return; if (isIntertypeDeclaration(abstractMethod)) return; // when there is a problem with an ITD not being implemented, it will be reported elsewhere if (CharOperation.prefixEquals("ajc$interField".toCharArray(), abstractMethod.selector)) { // ??? think through how this could go wrong return; } // if we implemented this method by an inter-type declaration, then there is no error // ??? be sure this is always right ResolvedType onTypeX = null; // If the type is anonymous, look at its supertype if (!type.isAnonymousType()) { onTypeX = factory.fromEclipse(type); } else { // Hmmm. If the ITD is on an interface that is being 'instantiated' using an anonymous type, // we sort it out elsewhere and don't come into this method - // so we don't have to worry about interfaces, just the superclass. onTypeX = factory.fromEclipse(type.superclass()); // abstractMethod.declaringClass); } if (onTypeX.isRawType()) onTypeX = onTypeX.getGenericType(); List<ConcreteTypeMunger> mungers = onTypeX.getInterTypeMungersIncludingSupers(); for (ConcreteTypeMunger m : mungers) { ResolvedMember sig = m.getSignature(); if (sig != null && !Modifier.isAbstract(sig.getModifiers())) { ResolvedMember abstractMember = factory.makeResolvedMember(abstractMethod); if (abstractMember.getName().startsWith("ajc$interMethodDispatch")) { ResolvedType dType = factory.getWorld().resolve(sig.getDeclaringType(), false); if (ResolvedType.matches(AjcMemberMaker.interMethod(sig, m.getAspectType(), dType.isInterface()), abstractMember)) { return; } } else { // In this case we have something like: // interface I {} // abstract class C implements I { abstract void foo();} // class D extends C {} // ITD: public void I.foo() {...} // The ITD is providing the implementation of foo in the class D but when checking for whether the abstract // method is overridden, we won't be looking at whether the ITD overrides ajc$interMethodDispath$...foo but // whether it overrides the foo method from class C if (ResolvedType.matches(sig, factory.makeResolvedMember(abstractMethod))) return; } } } super.abstractMethodMustBeImplemented(type, abstractMethod); } /* * (non-Javadoc) * * @see * org.aspectj.org.eclipse.jdt.internal.compiler.problem.ProblemReporter#disallowedTargetForAnnotation(org.aspectj.org.eclipse * .jdt.internal.compiler.ast.Annotation) */ public void disallowedTargetForAnnotation(Annotation annotation) { // if the annotation's recipient is an ITD, it might be allowed after all... if (annotation.recipient instanceof MethodBinding) { MethodBinding binding = (MethodBinding) annotation.recipient; String name = new String(binding.selector); if (name.startsWith("ajc$")) { long metaTagBits = annotation.resolvedType.getAnnotationTagBits(); // could be forward reference if (name.indexOf("interField") != -1) { if ((metaTagBits & TagBits.AnnotationForField) != 0) return; } else if (name.indexOf("interConstructor") != -1) { if ((metaTagBits & TagBits.AnnotationForConstructor) != 0) return; } else if (name.indexOf("interMethod") != -1) { if ((metaTagBits & TagBits.AnnotationForMethod) != 0) return; } else if (name.indexOf("declare_" + DeclareAnnotation.AT_TYPE + "_") != -1) { if ((metaTagBits & TagBits.AnnotationForAnnotationType) != 0 || (metaTagBits & TagBits.AnnotationForType) != 0) return; } else if (name.indexOf("declare_" + DeclareAnnotation.AT_FIELD + "_") != -1) { if ((metaTagBits & TagBits.AnnotationForField) != 0) return; } else if (name.indexOf("declare_" + DeclareAnnotation.AT_CONSTRUCTOR + "_") != -1) { if ((metaTagBits & TagBits.AnnotationForConstructor) != 0) return; } else if (name.indexOf("declare_eow") != -1) { if ((metaTagBits & TagBits.AnnotationForField) != 0) return; } } } // not our special case, report the problem... super.disallowedTargetForAnnotation(annotation); } public void overridesPackageDefaultMethod(MethodBinding localMethod, MethodBinding inheritedMethod) { if (new String(localMethod.selector).startsWith("ajc$")) return; super.overridesPackageDefaultMethod(localMethod, inheritedMethod); } public void handle(int problemId, String[] problemArguments, String[] messageArguments, int severity, int problemStartPosition, int problemEndPosition, ReferenceContext referenceContext, CompilationResult unitResult) { if (severity != ProblemSeverities.Ignore && DUMP_STACK) { Thread.dumpStack(); } super.handle(problemId, problemArguments, 0, // no message elaboration messageArguments, severity, problemStartPosition, problemEndPosition, referenceContext, unitResult); } // PR71076 public void javadocMissingParamTag(char[] name, int sourceStart, int sourceEnd, int modifiers) { boolean reportIt = true; String sName = new String(name); if (sName.startsWith("ajc$")) reportIt = false; if (sName.equals("thisJoinPoint")) reportIt = false; if (sName.equals("thisJoinPointStaticPart")) reportIt = false; if (sName.equals("thisEnclosingJoinPointStaticPart")) reportIt = false; if (sName.equals("ajc_aroundClosure")) reportIt = false; if (reportIt) super.javadocMissingParamTag(name, sourceStart, sourceEnd, modifiers); } public void abstractMethodInAbstractClass(SourceTypeBinding type, AbstractMethodDeclaration methodDecl) { String abstractMethodName = new String(methodDecl.selector); if (abstractMethodName.startsWith("ajc$pointcut")) { // This will already have been reported, see: PointcutDeclaration.postParse() return; } String[] arguments = new String[] { new String(type.sourceName()), abstractMethodName }; super.handle(IProblem.AbstractMethodInAbstractClass, arguments, arguments, methodDecl.sourceStart, methodDecl.sourceEnd, this.referenceContext, this.referenceContext == null ? null : this.referenceContext.compilationResult()); } /** * Called when there is an ITD marked @override that doesn't override a supertypes method. The method and the binding are passed * - some information is useful from each. The 'method' knows about source offsets for the message, the 'binding' has the * signature of what the ITD is trying to be in the target class. */ public void itdMethodMustOverride(AbstractMethodDeclaration method, MethodBinding binding) { this.handle(IProblem.MethodMustOverride, new String[] { new String(binding.selector), typesAsString(binding.isVarargs(), binding.parameters, false), new String(binding.declaringClass.readableName()), }, new String[] { new String(binding.selector), typesAsString(binding.isVarargs(), binding.parameters, true), new String(binding.declaringClass.shortReadableName()), }, method.sourceStart, method.sourceEnd, this.referenceContext, this.referenceContext == null ? null : this.referenceContext.compilationResult()); } /** * Overrides the implementation in ProblemReporter and is ITD aware. To report a *real* problem with an ITD marked @override, * the other methodMustOverride() method is used. */ public void methodMustOverride(AbstractMethodDeclaration method, long complianceLevel) { // ignore ajc$ methods if (new String(method.selector).startsWith("ajc$")) return; ResolvedMember possiblyErroneousRm = factory.makeResolvedMember(method.binding); ResolvedType onTypeX = factory.fromEclipse(method.binding.declaringClass); // Can't use 'getInterTypeMungersIncludingSupers()' since that will exclude abstract ITDs // on any super classes - so we have to trawl up ourselves.. I wonder if this problem // affects other code in the problem reporter that looks through ITDs... ResolvedType supertypeToLookAt = onTypeX.getSuperclass(); while (supertypeToLookAt != null) { List<ConcreteTypeMunger> itMungers = supertypeToLookAt.getInterTypeMungers(); for (Iterator<ConcreteTypeMunger> i = itMungers.iterator(); i.hasNext();) { ConcreteTypeMunger m = (ConcreteTypeMunger) i.next(); if (m.getMunger()!=null && m.getMunger().getKind()== ResolvedTypeMunger.PrivilegedAccess) { continue; } ResolvedMember sig = m.getSignature(); if (sig == null) continue; // we aren't interested in other kinds of munger UnresolvedType dType = sig.getDeclaringType(); if (dType == null) continue; ResolvedType resolvedDeclaringType = dType.resolve(factory.getWorld()); ResolvedMember rm = AjcMemberMaker.interMethod(sig, m.getAspectType(), resolvedDeclaringType.isInterface()); if (ResolvedType.matches(rm, possiblyErroneousRm)) { // match, so dont need to report a problem! return; } } supertypeToLookAt = supertypeToLookAt.getSuperclass(); } // report the error... super.methodMustOverride(method,complianceLevel); } private String typesAsString(boolean isVarargs, TypeBinding[] types, boolean makeShort) { StringBuffer buffer = new StringBuffer(10); for (int i = 0, length = types.length; i < length; i++) { if (i != 0) buffer.append(", "); //$NON-NLS-1$ TypeBinding type = types[i]; boolean isVarargType = isVarargs && i == length - 1; if (isVarargType) type = ((ArrayBinding) type).elementsType(); buffer.append(new String(makeShort ? type.shortReadableName() : type.readableName())); if (isVarargType) buffer.append("..."); //$NON-NLS-1$ } return buffer.toString(); } public void visibilityConflict(MethodBinding currentMethod, MethodBinding inheritedMethod) { // Not quite sure if the conditions on this test are right - basically I'm saying // DONT WORRY if its ITDs since the error will be reported another way... if (isIntertypeDeclaration(currentMethod) && isIntertypeDeclaration(inheritedMethod) && Modifier.isPrivate(currentMethod.modifiers) && Modifier.isPrivate(inheritedMethod.modifiers)) { return; } super.visibilityConflict(currentMethod, inheritedMethod); } public void unusedPrivateType(TypeDeclaration typeDecl) { // don't output unused type warnings for aspects! if (typeDecl instanceof AspectDeclaration) return; if (typeDecl.enclosingType != null && (typeDecl.enclosingType instanceof AspectDeclaration)) { AspectDeclaration ad = (AspectDeclaration) typeDecl.enclosingType; if (ad.concreteName != null) { List declares = ad.concreteName.declares; for (Iterator iter = declares.iterator(); iter.hasNext();) { Object dec = iter.next(); if (dec instanceof DeclareParents) { DeclareParents decp = (DeclareParents) dec; TypePattern[] newparents = decp.getParents().getTypePatterns(); for (int i = 0; i < newparents.length; i++) { TypePattern pattern = newparents[i]; UnresolvedType ut = pattern.getExactType(); if (ut == null) continue; if (CharOperation.compareWith(typeDecl.binding.signature(), ut.getSignature().toCharArray()) == 0) return; } } } } } super.unusedPrivateType(typeDecl); } public void abstractMethodInConcreteClass(SourceTypeBinding type) { if (type.scope!=null && type.scope.referenceContext instanceof AspectDeclaration) { // TODO could put out an Aspect specific message here return; } super.abstractMethodInConcreteClass(type); } // Don't warn if there is an ITD method/ctor from a privileged aspect public void unusedPrivateField(FieldDeclaration fieldDecl) { if (fieldDecl!=null && fieldDecl.binding != null && fieldDecl.binding.declaringClass != null) { ReferenceBinding type = fieldDecl.binding.declaringClass; ResolvedType weaverType = null; if (!type.isAnonymousType()) { weaverType = factory.fromEclipse(type); } else { weaverType = factory.fromEclipse(type.superclass()); } Set checked = new HashSet(); for (Iterator i = weaverType.getInterTypeMungersIncludingSupers().iterator(); i.hasNext();) { ConcreteTypeMunger m = (ConcreteTypeMunger) i.next(); ResolvedType theAspect = m.getAspectType(); if (!checked.contains(theAspect)) { TypeBinding tb = factory.makeTypeBinding(m.getAspectType()); // Let's check the privilegedHandler from that aspect if (tb instanceof SourceTypeBinding) { // BinaryTypeBinding is also a SourceTypeBinding ;) IPrivilegedHandler privilegedHandler = ((SourceTypeBinding) tb).privilegedHandler; if (privilegedHandler != null) { if (privilegedHandler.definesPrivilegedAccessToField(fieldDecl.binding)) { return; } } else if (theAspect instanceof ReferenceType) { // ResolvedMember rm = factory.makeResolvedMember(fieldDecl.binding); String fname = new String(fieldDecl.name); Collection/* ResolvedMember */privvies = ((ReferenceType) theAspect).getPrivilegedAccesses(); // On an incremental compile the information is in the bcel delegate if (privvies != null) { for (Iterator iterator = privvies.iterator(); iterator.hasNext();) { ResolvedMember priv = (ResolvedMember) iterator.next(); if (priv.getName().equals(fname)) { return; } } } } } checked.add(theAspect); } } } super.unusedPrivateField(fieldDecl); } public void unusedPrivateMethod(AbstractMethodDeclaration methodDecl) { // don't output unused warnings for pointcuts... if (!(methodDecl instanceof PointcutDeclaration)) super.unusedPrivateMethod(methodDecl); } public void caseExpressionMustBeConstant(Expression expression) { if (expression instanceof QualifiedNameReference) { QualifiedNameReference qnr = (QualifiedNameReference) expression; if (qnr.otherBindings != null && qnr.otherBindings.length > 0 && qnr.otherBindings[0] instanceof PrivilegedFieldBinding) { super.signalError(expression.sourceStart, expression.sourceEnd, "Fields accessible due to an aspect being privileged can not be used in switch statements"); referenceContext.tagAsHavingErrors(); return; } } super.caseExpressionMustBeConstant(expression); } public void unusedArgument(LocalDeclaration localDecl) { // don't warn if this is an aj synthetic arg String argType = new String(localDecl.type.resolvedType.signature()); if (argType.startsWith("Lorg/aspectj/runtime/internal")) return; // If the unused argument is in a pointcut, don't report the problem (for now... pr148219) if (localDecl instanceof Argument) { Argument arg = (Argument) localDecl; if (arg.binding != null && arg.binding.declaringScope != null) { ReferenceContext context = arg.binding.declaringScope.referenceContext(); if (context != null && context instanceof PointcutDeclaration) return; } } if (new String(localDecl.name).startsWith("ajc$")) { // Do not report problems for infrastructure variables beyond the users control - pr195090 return; } super.unusedArgument(localDecl); } /** * A side-effect of the way that we handle itds on default methods on top-most implementors of interfaces is that a class * acquiring a final default ITD will erroneously report that it can't override its own member. This method detects that * situation. */ public void finalMethodCannotBeOverridden(MethodBinding currentMethod, MethodBinding inheritedMethod) { if (currentMethod == inheritedMethod) return; super.finalMethodCannotBeOverridden(currentMethod, inheritedMethod); } /** * The method verifier is a bit 'keen' and doesn't cope well with ITDMs which are of course to be considered a 'default' * implementation if the target type doesn't supply one. This test may not be complete - it is possible that it should read if * *either* is an ITD...but I dont have a testcase that shows that is required. yet. (pr115788) */ public void duplicateInheritedMethods(SourceTypeBinding type, MethodBinding inheritedMethod1, MethodBinding inheritedMethod2) { if (inheritedMethod1 instanceof InterTypeMethodBinding || inheritedMethod2 instanceof InterTypeMethodBinding) return; if ((inheritedMethod1 instanceof ParameterizedMethodBinding) && ((ParameterizedMethodBinding) inheritedMethod1).original() instanceof InterTypeMethodBinding) return; if ((inheritedMethod2 instanceof ParameterizedMethodBinding) && ((ParameterizedMethodBinding) inheritedMethod2).original() instanceof InterTypeMethodBinding) return; super.duplicateInheritedMethods(type, inheritedMethod1, inheritedMethod2); } /** * All problems end up routed through here at some point... */ public IProblem createProblem(char[] fileName, int problemId, String[] problemArguments, String[] messageArguments, int severity, int problemStartPosition, int problemEndPosition, int lineNumber) { IProblem problem = super.createProblem(fileName, problemId, problemArguments, messageArguments, severity, problemStartPosition, problemEndPosition, lineNumber, 0); if (factory.getWorld().isInPinpointMode()) { MessageIssued ex = new MessageIssued(); ex.fillInStackTrace(); StringWriter sw = new StringWriter(); ex.printStackTrace(new PrintWriter(sw)); StringBuffer sb = new StringBuffer(); sb.append(CompilationAndWeavingContext.getCurrentContext()); sb.append(sw.toString()); problem = new PinpointedProblem(problem, sb.toString()); } return problem; } private static class MessageIssued extends RuntimeException { public String getMessage() { return "message issued..."; } } private static class PinpointedProblem implements IProblem { private IProblem delegate; private String message; public PinpointedProblem(IProblem aProblem, String pinpoint) { this.delegate = aProblem; // if this was a problem that came via the weaver, it will already have // pinpoint info, don't do it twice... if (delegate.getMessage().indexOf("message issued...") == -1) { this.message = delegate.getMessage() + "\n" + pinpoint; } else { this.message = delegate.getMessage(); } } public String[] getArguments() { return delegate.getArguments(); } public int getID() { return delegate.getID(); } public String getMessage() { return message; } public char[] getOriginatingFileName() { return delegate.getOriginatingFileName(); } public int getSourceEnd() { return delegate.getSourceEnd(); } public int getSourceLineNumber() { return delegate.getSourceLineNumber(); } public int getSourceStart() { return delegate.getSourceStart(); } public boolean isError() { return delegate.isError(); } public boolean isWarning() { return delegate.isWarning(); } public void setSourceEnd(int sourceEnd) { delegate.setSourceEnd(sourceEnd); } public void setSourceLineNumber(int lineNumber) { delegate.setSourceLineNumber(lineNumber); } public void setSourceStart(int sourceStart) { delegate.setSourceStart(sourceStart); } public void setSeeAlsoProblems(IProblem[] problems) { delegate.setSeeAlsoProblems(problems); } public IProblem[] seeAlso() { return delegate.seeAlso(); } public void setSupplementaryMessageInfo(String msg) { delegate.setSupplementaryMessageInfo(msg); } public String getSupplementaryMessageInfo() { return delegate.getSupplementaryMessageInfo(); } } public void duplicateMethodInType(SourceTypeBinding type, AbstractMethodDeclaration methodDecl, boolean equalParameters, int severity) { if (new String(methodDecl.selector).startsWith("ajc$interMethod")) { // this is an ITD clash and will be reported in another way by AspectJ (173602) return; } super.duplicateMethodInType(type, methodDecl, equalParameters, severity); } // pr246393 - if we are going to complain about privileged, we clearly don't know what is going on, so don't // confuse the user public void parseErrorInsertAfterToken(int start, int end, int currentKind, char[] errorTokenSource, String errorTokenName, String expectedToken) { if (expectedToken.equals("privileged")) { super.parseErrorNoSuggestion(start, end, currentKind, errorTokenSource, errorTokenName); } else { super.parseErrorInsertAfterToken(start, end, currentKind, errorTokenSource, errorTokenName, expectedToken); } } public void missingValueForAnnotationMember(Annotation annotation, char[] memberName) { if (referenceContext instanceof DeclareAnnotationDeclaration) { // If a remover then the values are not necessary if (((DeclareAnnotationDeclaration) referenceContext).isRemover()) { return; } } super.missingValueForAnnotationMember(annotation, memberName); } }
387,444
Bug 387444 Softening exception in try-with-resources
null
resolved fixed
76d695f
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2012-08-23T19:19:58Z"
"2012-08-16T23:33:20Z"
tests/bugs171/pr387444/Code.java
387,444
Bug 387444 Softening exception in try-with-resources
null
resolved fixed
76d695f
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2012-08-23T19:19:58Z"
"2012-08-16T23:33:20Z"
tests/bugs171/pr387444/Code2.java
387,444
Bug 387444 Softening exception in try-with-resources
null
resolved fixed
76d695f
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2012-08-23T19:19:58Z"
"2012-08-16T23:33:20Z"
tests/src/org/aspectj/systemtest/ajc171/Ajc171Tests.java
/******************************************************************************* * Copyright (c) 2012 Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Andy Clement - initial API and implementation *******************************************************************************/ package org.aspectj.systemtest.ajc171; import java.io.File; import junit.framework.Test; import org.aspectj.testing.XMLBasedAjcTestCase; /** * @author Andy Clement */ public class Ajc171Tests extends org.aspectj.testing.XMLBasedAjcTestCase { public void testUnresolvableEnum_pr387568() { runTest("unresolvable enum"); } public void testAbstractItds_pr386049() { runTest("itd abstract"); } public void testPublicITDFs_pr73507_1() { runTest("public ITDfs - 1"); } public void testPublicITDFs_pr73507_2() { runTest("public ITDfs - 2"); } public void testPublicITDFs_pr73507_3() { runTest("public ITDfs - 3"); } public void testPublicITDFs_pr73507_4() { runTest("public ITDfs - 4"); } public void testPublicITDFs_pr73507_5() { runTest("public ITDfs - 5"); } public void testGenerics_384398() { runTest("generics itds"); } // public void testGenerics_384398_2() { // runTest("generics itds 2"); // } // --- public static Test suite() { return XMLBasedAjcTestCase.loadSuite(Ajc171Tests.class); } @Override protected File getSpecFile() { return new File("../tests/src/org/aspectj/systemtest/ajc171/ajc171.xml"); } }
387,444
Bug 387444 Softening exception in try-with-resources
null
resolved fixed
76d695f
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2012-08-23T19:19:58Z"
"2012-08-16T23:33:20Z"
tests/src/org/aspectj/systemtest/ajc171/Ajc171Tests_need17jre.java
384,401
Bug 384401 NPE when no pointcut in afterthrowing annotation style advice
From the mailing list: import org.aspectj.lang.JoinPoint; import org.aspectj.lang.annotation.AfterThrowing; import org.aspectj.lang.annotation.Aspect; @Aspect public class X { // @AfterThrowing(pointcut="execution(* *(..))",throwing = "e") @AfterThrowing(throwing = "e") public void bizLoggerWithException(JoinPoint thisJoinPoint,Throwable e) { // .....// do some stuff } } class BizLoggable {}
resolved fixed
55ebaa1
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2012-08-23T20:05:24Z"
"2012-07-05T17:40:00Z"
org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/compiler/ast/ValidateAtAspectJAnnotationsVisitor.java
/* ******************************************************************* * Copyright (c) 2005 IBM Corporation Ltd * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Eclipse Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Adrian Colyer initial implementation * ******************************************************************/ package org.aspectj.ajdt.internal.compiler.ast; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.List; import java.util.Stack; import org.aspectj.ajdt.internal.compiler.lookup.EclipseFactory; import org.aspectj.ajdt.internal.compiler.lookup.EclipseScope; import org.aspectj.ajdt.internal.core.builder.EclipseSourceContext; import org.aspectj.bridge.context.CompilationAndWeavingContext; import org.aspectj.bridge.context.ContextToken; import org.aspectj.org.eclipse.jdt.core.compiler.CharOperation; import org.aspectj.org.eclipse.jdt.internal.compiler.ASTVisitor; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.Annotation; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.Argument; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.FieldDeclaration; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.MemberValuePair; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.MethodDeclaration; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.NameReference; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.NormalAnnotation; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.SingleMemberAnnotation; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.SingleTypeReference; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.StringLiteral; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.TypeDeclaration; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.TypeReference; import org.aspectj.org.eclipse.jdt.internal.compiler.impl.Constant; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.Binding; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.BlockScope; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.ClassScope; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.CompilationUnitScope; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.FieldBinding; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.MethodScope; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.SourceTypeBinding; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.TypeBinding; import org.aspectj.weaver.AdviceKind; import org.aspectj.weaver.AjAttribute; import org.aspectj.weaver.ISourceContext; import org.aspectj.weaver.ResolvedPointcutDefinition; import org.aspectj.weaver.UnresolvedType; import org.aspectj.weaver.patterns.AbstractPatternNodeVisitor; import org.aspectj.weaver.patterns.FormalBinding; import org.aspectj.weaver.patterns.IfPointcut; import org.aspectj.weaver.patterns.ParserException; import org.aspectj.weaver.patterns.PatternParser; import org.aspectj.weaver.patterns.Pointcut; public class ValidateAtAspectJAnnotationsVisitor extends ASTVisitor { private static final char[] beforeAdviceSig = "Lorg/aspectj/lang/annotation/Before;".toCharArray(); private static final char[] afterAdviceSig = "Lorg/aspectj/lang/annotation/After;".toCharArray(); private static final char[] afterReturningAdviceSig = "Lorg/aspectj/lang/annotation/AfterReturning;".toCharArray(); private static final char[] afterThrowingAdviceSig = "Lorg/aspectj/lang/annotation/AfterThrowing;".toCharArray(); private static final char[] aroundAdviceSig = "Lorg/aspectj/lang/annotation/Around;".toCharArray(); private static final char[] pointcutSig = "Lorg/aspectj/lang/annotation/Pointcut;".toCharArray(); private static final char[] aspectSig = "Lorg/aspectj/lang/annotation/Aspect;".toCharArray(); private static final char[] declareParentsSig = "Lorg/aspectj/lang/annotation/DeclareParents;".toCharArray(); private static final char[] adviceNameSig = "Lorg/aspectj/lang/annotation/AdviceName;".toCharArray(); // private static final char[] orgAspectJLangAnnotation = // "org/aspectj/lang/annotation/".toCharArray(); private static final char[] voidType = "void".toCharArray(); private static final char[] booleanType = "boolean".toCharArray(); private static final char[] joinPoint = "Lorg/aspectj/lang/JoinPoint;".toCharArray(); private static final char[] joinPointStaticPart = "Lorg/aspectj/lang/JoinPoint$StaticPart;".toCharArray(); private static final char[] joinPointEnclosingStaticPart = "Lorg/aspectj/lang/JoinPoint$EnclosingStaticPart;".toCharArray(); private static final char[] proceedingJoinPoint = "Lorg/aspectj/lang/ProceedingJoinPoint;".toCharArray(); // private static final char[][] adviceSigs = new char[][] { // beforeAdviceSig, afterAdviceSig, afterReturningAdviceSig, // afterThrowingAdviceSig, aroundAdviceSig }; private final CompilationUnitDeclaration unit; private final Stack typeStack = new Stack(); private AspectJAnnotations ajAnnotations; public ValidateAtAspectJAnnotationsVisitor(CompilationUnitDeclaration unit) { this.unit = unit; } public boolean visit(TypeDeclaration localTypeDeclaration, BlockScope scope) { typeStack.push(localTypeDeclaration); ajAnnotations = new AspectJAnnotations(localTypeDeclaration.annotations); checkTypeDeclaration(localTypeDeclaration); return true; } public void endVisit(TypeDeclaration localTypeDeclaration, BlockScope scope) { typeStack.pop(); } public boolean visit(TypeDeclaration memberTypeDeclaration, ClassScope scope) { typeStack.push(memberTypeDeclaration); ajAnnotations = new AspectJAnnotations(memberTypeDeclaration.annotations); checkTypeDeclaration(memberTypeDeclaration); return true; } public void endVisit(TypeDeclaration memberTypeDeclaration, ClassScope scope) { typeStack.pop(); } public boolean visit(TypeDeclaration typeDeclaration, CompilationUnitScope scope) { typeStack.push(typeDeclaration); ajAnnotations = new AspectJAnnotations(typeDeclaration.annotations); checkTypeDeclaration(typeDeclaration); return true; } public void endVisit(TypeDeclaration typeDeclaration, CompilationUnitScope scope) { typeStack.pop(); } private void checkTypeDeclaration(TypeDeclaration typeDecl) { ContextToken tok = CompilationAndWeavingContext.enteringPhase( CompilationAndWeavingContext.VALIDATING_AT_ASPECTJ_ANNOTATIONS, typeDecl.name); if (!(typeDecl instanceof AspectDeclaration)) { if (ajAnnotations.hasAspectAnnotation) { validateAspectDeclaration(typeDecl); } else { // check that class doesn't extend aspect TypeReference parentRef = typeDecl.superclass; if (parentRef != null) { TypeBinding parentBinding = parentRef.resolvedType; if (parentBinding instanceof SourceTypeBinding) { SourceTypeBinding parentSTB = (SourceTypeBinding) parentBinding; if (parentSTB.scope != null) { TypeDeclaration parentDecl = parentSTB.scope.referenceContext; if (isAspect(parentDecl)) { typeDecl.scope.problemReporter().signalError(typeDecl.sourceStart, typeDecl.sourceEnd, "a class cannot extend an aspect"); } } } } } } else { // check that aspect doesn't have @Aspect annotation, we've already // added on ourselves. if (ajAnnotations.hasMultipleAspectAnnotations) { typeDecl.scope.problemReporter().signalError(typeDecl.sourceStart, typeDecl.sourceEnd, "aspects cannot have @Aspect annotation"); } } CompilationAndWeavingContext.leavingPhase(tok); } public boolean visit(FieldDeclaration fieldDeclaration, MethodScope scope) { ajAnnotations = new AspectJAnnotations(fieldDeclaration.annotations); if (ajAnnotations.hasDeclareParents && !insideAspect()) { scope.problemReporter().signalError(fieldDeclaration.sourceStart, fieldDeclaration.sourceEnd, "DeclareParents can only be used inside an aspect type"); } return true; } public boolean visit(MethodDeclaration methodDeclaration, ClassScope scope) { if (methodDeclaration.hasErrors()) { return false; } ContextToken tok = CompilationAndWeavingContext.enteringPhase( CompilationAndWeavingContext.VALIDATING_AT_ASPECTJ_ANNOTATIONS, methodDeclaration.selector); ajAnnotations = new AspectJAnnotations(methodDeclaration.annotations); if (!methodDeclaration.getClass().equals(AjMethodDeclaration.class)) { // simply test for innapropriate use of annotations on code-style // members if (methodDeclaration instanceof PointcutDeclaration) { if (ajAnnotations.hasMultiplePointcutAnnotations || ajAnnotations.hasAdviceAnnotation || ajAnnotations.hasAspectAnnotation || ajAnnotations.hasAdviceNameAnnotation) { methodDeclaration.scope.problemReporter().signalError(methodDeclaration.sourceStart, methodDeclaration.sourceEnd, "@AspectJ annotations cannot be declared on this aspect member"); } } else if (methodDeclaration instanceof AdviceDeclaration) { if (ajAnnotations.hasMultipleAdviceAnnotations || ajAnnotations.hasAspectAnnotation || ajAnnotations.hasPointcutAnnotation) { methodDeclaration.scope.problemReporter().signalError(methodDeclaration.sourceStart, methodDeclaration.sourceEnd, "Only @AdviceName AspectJ annotation allowed on advice"); } } else { if (ajAnnotations.hasAspectJAnnotations()) { methodDeclaration.scope.problemReporter().signalError(methodDeclaration.sourceStart, methodDeclaration.sourceEnd, "@AspectJ annotations cannot be declared on this aspect member"); } } CompilationAndWeavingContext.leavingPhase(tok); return false; } if (ajAnnotations.hasAdviceAnnotation) { validateAdvice(methodDeclaration); } else if (ajAnnotations.hasPointcutAnnotation) { convertToPointcutDeclaration(methodDeclaration, scope); } CompilationAndWeavingContext.leavingPhase(tok); return false; } // private boolean isAspectJAnnotation(Annotation ann) { // if (ann.resolvedType == null) return false; // char[] sig = ann.resolvedType.signature(); // return CharOperation.contains(orgAspectJLangAnnotation, sig); // } private boolean insideAspect() { if (typeStack.empty()) return false; TypeDeclaration typeDecl = (TypeDeclaration) typeStack.peek(); return isAspect(typeDecl); } private boolean isAspect(TypeDeclaration typeDecl) { if (typeDecl instanceof AspectDeclaration) return true; return new AspectJAnnotations(typeDecl.annotations).hasAspectAnnotation; } /** * aspect must be public nested aspect must be static cannot extend a concrete aspect pointcut in perclause must be good. */ private void validateAspectDeclaration(TypeDeclaration typeDecl) { if (typeStack.size() > 1) { // it's a nested aspect if (!Modifier.isStatic(typeDecl.modifiers)) { typeDecl.scope.problemReporter().signalError(typeDecl.sourceStart, typeDecl.sourceEnd, "inner aspects must be static"); return; } } SourceTypeBinding binding = typeDecl.binding; if (binding != null) { if (binding.isEnum() || binding.isInterface() || binding.isAnnotationType()) { typeDecl.scope.problemReporter().signalError(typeDecl.sourceStart, typeDecl.sourceEnd, "only classes can have an @Aspect annotation"); } } // FIXME AV - do we really want that // if (!Modifier.isPublic(typeDecl.modifiers)) { // typeDecl.scope.problemReporter().signalError(typeDecl.sourceStart, // typeDecl.sourceEnd,"@Aspect class must be public"); // } TypeReference parentRef = typeDecl.superclass; if (parentRef != null) { TypeBinding parentBinding = parentRef.resolvedType; if (parentBinding instanceof SourceTypeBinding) { SourceTypeBinding parentSTB = (SourceTypeBinding) parentBinding; if (parentSTB.scope != null) { // scope is null if its a // binarytypebinding (in AJ // world, thats a subclass of // SourceTypeBinding) TypeDeclaration parentDecl = parentSTB.scope.referenceContext; if (isAspect(parentDecl) && !Modifier.isAbstract(parentDecl.modifiers)) { typeDecl.scope.problemReporter().signalError(typeDecl.sourceStart, typeDecl.sourceEnd, "cannot extend a concrete aspect"); } } } } Annotation aspectAnnotation = ajAnnotations.aspectAnnotation; int[] pcLoc = new int[2]; String perClause = getStringLiteralFor("value", aspectAnnotation, pcLoc); // AspectDeclaration aspectDecl = new // AspectDeclaration(typeDecl.compilationResult); try { if (perClause != null && !perClause.equals("")) { ISourceContext context = new EclipseSourceContext(unit.compilationResult, pcLoc[0]); Pointcut pc = new PatternParser(perClause, context).maybeParsePerClause(); FormalBinding[] bindings = new FormalBinding[0]; if (pc != null) pc.resolve(new EclipseScope(bindings, typeDecl.scope)); } } catch (ParserException pEx) { typeDecl.scope.problemReporter().parseError(pcLoc[0] + pEx.getLocation().getStart(), pcLoc[0] + pEx.getLocation().getEnd(), -1, perClause.toCharArray(), perClause, new String[] { pEx.getMessage() }); } } /** * 1) Advice must be public 2) Advice must have a void return type if not around advice 3) Advice must not have any other @AspectJ * annotations 4) After throwing advice must declare the thrown formal 5) After returning advice must declare the returning * formal 6) Advice must not be static */ private void validateAdvice(MethodDeclaration methodDeclaration) { if (!insideAspect()) { methodDeclaration.scope.problemReporter().signalError(methodDeclaration.sourceStart, methodDeclaration.sourceEnd, "Advice must be declared inside an aspect type"); } if (!Modifier.isPublic(methodDeclaration.modifiers)) { methodDeclaration.scope.problemReporter().signalError(methodDeclaration.sourceStart, methodDeclaration.sourceEnd, "advice must be public"); } if (Modifier.isStatic(methodDeclaration.modifiers)) { methodDeclaration.scope.problemReporter().signalError(methodDeclaration.sourceStart, methodDeclaration.sourceEnd, "advice can not be declared static"); } if (ajAnnotations.hasMultipleAdviceAnnotations) { methodDeclaration.scope.problemReporter().disallowedTargetForAnnotation(ajAnnotations.duplicateAdviceAnnotation); } if (ajAnnotations.hasPointcutAnnotation) { methodDeclaration.scope.problemReporter().disallowedTargetForAnnotation(ajAnnotations.pointcutAnnotation); } if (ajAnnotations.hasAspectAnnotation) { methodDeclaration.scope.problemReporter().disallowedTargetForAnnotation(ajAnnotations.aspectAnnotation); } if (ajAnnotations.hasAdviceNameAnnotation) { methodDeclaration.scope.problemReporter().disallowedTargetForAnnotation(ajAnnotations.adviceNameAnnotation); } if (ajAnnotations.adviceKind != AdviceKind.Around) { ensureVoidReturnType(methodDeclaration); } if (ajAnnotations.adviceKind == AdviceKind.AfterThrowing) { int[] throwingLocation = new int[2]; String thrownFormal = getStringLiteralFor("throwing", ajAnnotations.adviceAnnotation, throwingLocation); if (thrownFormal != null) { // Argument[] arguments = methodDeclaration.arguments; if (!toArgumentNames(methodDeclaration.arguments).contains(thrownFormal)) { methodDeclaration.scope.problemReporter().signalError(methodDeclaration.sourceStart, methodDeclaration.sourceEnd, "throwing formal '" + thrownFormal + "' must be declared as a parameter in the advice signature"); } } } if (ajAnnotations.adviceKind == AdviceKind.AfterReturning) { int[] throwingLocation = new int[2]; String returningFormal = getStringLiteralFor("returning", ajAnnotations.adviceAnnotation, throwingLocation); if (returningFormal != null) { if (!toArgumentNames(methodDeclaration.arguments).contains(returningFormal)) { methodDeclaration.scope.problemReporter().signalError(methodDeclaration.sourceStart, methodDeclaration.sourceEnd, "returning formal '" + returningFormal + "' must be declared as a parameter in the advice signature"); } } } resolveAndSetPointcut(methodDeclaration, ajAnnotations.adviceAnnotation); } /** * Get the argument names as a string list * * @param arguments * @return argument names (possibly empty) */ private List toArgumentNames(Argument[] arguments) { List names = new ArrayList(); if (arguments == null) { return names; } else { for (int i = 0; i < arguments.length; i++) { names.add(new String(arguments[i].name)); } return names; } } private void resolveAndSetPointcut(MethodDeclaration methodDeclaration, Annotation adviceAnn) { int[] pcLocation = new int[2]; String pointcutExpression = getStringLiteralFor("pointcut", adviceAnn, pcLocation); if (pointcutExpression == null) pointcutExpression = getStringLiteralFor("value", adviceAnn, pcLocation); try { // +1 to give first char of pointcut string ISourceContext context = new EclipseSourceContext(unit.compilationResult, pcLocation[0] + 1); PatternParser pp = new PatternParser(pointcutExpression, context); Pointcut pc = pp.parsePointcut(); pp.checkEof(); FormalBinding[] bindings = buildFormalAdviceBindingsFrom(methodDeclaration); pc.resolve(new EclipseScope(bindings, methodDeclaration.scope)); EclipseFactory factory = EclipseFactory.fromScopeLookupEnvironment(methodDeclaration.scope); // now create a ResolvedPointcutDefinition,make an attribute out of // it, and add it to the method UnresolvedType[] paramTypes = new UnresolvedType[bindings.length]; for (int i = 0; i < paramTypes.length; i++) paramTypes[i] = bindings[i].getType(); ResolvedPointcutDefinition resPcutDef = new ResolvedPointcutDefinition(factory.fromBinding(((TypeDeclaration) typeStack .peek()).binding), methodDeclaration.modifiers, "anonymous", paramTypes, pc); AjAttribute attr = new AjAttribute.PointcutDeclarationAttribute(resPcutDef); ((AjMethodDeclaration) methodDeclaration).addAttribute(new EclipseAttributeAdapter(attr)); } catch (ParserException pEx) { methodDeclaration.scope.problemReporter().parseError(pcLocation[0] + pEx.getLocation().getStart(), pcLocation[0] + pEx.getLocation().getEnd(), -1, pointcutExpression.toCharArray(), pointcutExpression, new String[] { pEx.getMessage() }); } } private void ensureVoidReturnType(MethodDeclaration methodDeclaration) { boolean returnsVoid = true; if ((methodDeclaration.returnType instanceof SingleTypeReference)) { SingleTypeReference retType = (SingleTypeReference) methodDeclaration.returnType; if (!CharOperation.equals(voidType, retType.token)) { returnsVoid = false; } } else { returnsVoid = false; } if (!returnsVoid) { methodDeclaration.scope.problemReporter().signalError(methodDeclaration.returnType.sourceStart, methodDeclaration.returnType.sourceEnd, "This advice must return void"); } } private FormalBinding[] buildFormalAdviceBindingsFrom(MethodDeclaration mDecl) { if (mDecl.arguments == null) return new FormalBinding[0]; if (mDecl.binding == null) return new FormalBinding[0]; EclipseFactory factory = EclipseFactory.fromScopeLookupEnvironment(mDecl.scope); String extraArgName = maybeGetExtraArgName(); if (extraArgName == null) extraArgName = ""; FormalBinding[] ret = new FormalBinding[mDecl.arguments.length]; for (int i = 0; i < mDecl.arguments.length; i++) { Argument arg = mDecl.arguments[i]; String name = new String(arg.name); TypeBinding argTypeBinding = mDecl.binding.parameters[i]; UnresolvedType type = factory.fromBinding(argTypeBinding); if (CharOperation.equals(joinPoint, argTypeBinding.signature()) || CharOperation.equals(joinPointStaticPart, argTypeBinding.signature()) || CharOperation.equals(joinPointEnclosingStaticPart, argTypeBinding.signature()) || CharOperation.equals(proceedingJoinPoint, argTypeBinding.signature()) || name.equals(extraArgName)) { ret[i] = new FormalBinding.ImplicitFormalBinding(type, name, i); } else { ret[i] = new FormalBinding(type, name, i, arg.sourceStart, arg.sourceEnd); } } return ret; } private String maybeGetExtraArgName() { String argName = null; if (ajAnnotations.adviceKind == AdviceKind.AfterReturning) { argName = getStringLiteralFor("returning", ajAnnotations.adviceAnnotation, new int[2]); } else if (ajAnnotations.adviceKind == AdviceKind.AfterThrowing) { argName = getStringLiteralFor("throwing", ajAnnotations.adviceAnnotation, new int[2]); } return argName; } private String getStringLiteralFor(String memberName, Annotation inAnnotation, int[] location) { if (inAnnotation instanceof SingleMemberAnnotation && memberName.equals("value")) { SingleMemberAnnotation sma = (SingleMemberAnnotation) inAnnotation; if (sma.memberValue instanceof StringLiteral) { StringLiteral sv = (StringLiteral) sma.memberValue; location[0] = sv.sourceStart; location[1] = sv.sourceEnd; return new String(sv.source()); } else if (sma.memberValue instanceof NameReference && (((NameReference) sma.memberValue).binding instanceof FieldBinding)) { Binding b = ((NameReference) sma.memberValue).binding; Constant c = ((FieldBinding) b).constant; return c.stringValue(); } } if (!(inAnnotation instanceof NormalAnnotation)) return null; NormalAnnotation ann = (NormalAnnotation) inAnnotation; MemberValuePair[] mvps = ann.memberValuePairs; if (mvps == null) return null; for (int i = 0; i < mvps.length; i++) { if (CharOperation.equals(memberName.toCharArray(), mvps[i].name)) { if (mvps[i].value instanceof StringLiteral) { StringLiteral sv = (StringLiteral) mvps[i].value; location[0] = sv.sourceStart; location[1] = sv.sourceEnd; return new String(sv.source()); } } } return null; } private void convertToPointcutDeclaration(MethodDeclaration methodDeclaration, ClassScope scope) { TypeDeclaration typeDecl = (TypeDeclaration) typeStack.peek(); if (typeDecl.binding != null) { if (!typeDecl.binding.isClass()) { methodDeclaration.scope.problemReporter().signalError(methodDeclaration.sourceStart, methodDeclaration.sourceEnd, "pointcuts can only be declared in a class or an aspect"); } } if (methodDeclaration.thrownExceptions != null && methodDeclaration.thrownExceptions.length > 0) { methodDeclaration.scope.problemReporter().signalError(methodDeclaration.sourceStart, methodDeclaration.sourceEnd, "pointcuts cannot throw exceptions!"); } PointcutDeclaration pcDecl = new PointcutDeclaration(unit.compilationResult); copyAllFields(methodDeclaration, pcDecl); if (ajAnnotations.hasAdviceAnnotation) { methodDeclaration.scope.problemReporter().disallowedTargetForAnnotation(ajAnnotations.adviceAnnotation); } if (ajAnnotations.hasAspectAnnotation) { methodDeclaration.scope.problemReporter().disallowedTargetForAnnotation(ajAnnotations.aspectAnnotation); } if (ajAnnotations.hasAdviceNameAnnotation) { methodDeclaration.scope.problemReporter().disallowedTargetForAnnotation(ajAnnotations.adviceNameAnnotation); } boolean noValueSupplied = true; boolean containsIfPcd = false; int[] pcLocation = new int[2]; String pointcutExpression = getStringLiteralFor("value", ajAnnotations.pointcutAnnotation, pcLocation); try { ISourceContext context = new EclipseSourceContext(unit.compilationResult, pcLocation[0]); Pointcut pc = null;// abstract if (pointcutExpression == null || pointcutExpression.length() == 0) { noValueSupplied = true; // matches nothing pointcut } else { noValueSupplied = false; pc = new PatternParser(pointcutExpression, context).parsePointcut(); } pcDecl.pointcutDesignator = (pc == null) ? null : new PointcutDesignator(pc); pcDecl.setGenerateSyntheticPointcutMethod(); TypeDeclaration onType = (TypeDeclaration) typeStack.peek(); pcDecl.postParse(onType); // EclipseFactory factory = // EclipseFactory.fromScopeLookupEnvironment // (methodDeclaration.scope); // int argsLength = methodDeclaration.arguments == null ? 0 : // methodDeclaration.arguments.length; FormalBinding[] bindings = buildFormalAdviceBindingsFrom(methodDeclaration); // FormalBinding[] bindings = new FormalBinding[argsLength]; // for (int i = 0, len = bindings.length; i < len; i++) { // Argument arg = methodDeclaration.arguments[i]; // String name = new String(arg.name); // UnresolvedType type = // factory.fromBinding(methodDeclaration.binding.parameters[i]); // bindings[i] = new FormalBinding(type, name, i, arg.sourceStart, // arg.sourceEnd, "unknown"); // } swap(onType, methodDeclaration, pcDecl); if (pc != null) { // has an expression EclipseScope eScope = new EclipseScope(bindings, methodDeclaration.scope); char[] packageName = null; if (typeDecl.binding != null && typeDecl.binding.getPackage() != null) { packageName = typeDecl.binding.getPackage().readableName(); } eScope.setLimitedImports(packageName); pc.resolve(eScope); HasIfPCDVisitor ifFinder = new HasIfPCDVisitor(); pc.traverse(ifFinder, null); containsIfPcd = ifFinder.containsIfPcd; } } catch (ParserException pEx) { methodDeclaration.scope.problemReporter().parseError(pcLocation[0] + pEx.getLocation().getStart(), pcLocation[0] + pEx.getLocation().getEnd(), -1, pointcutExpression.toCharArray(), pointcutExpression, new String[] { pEx.getMessage() }); } boolean returnsVoid = false; boolean returnsBoolean = false; if ((methodDeclaration.returnType instanceof SingleTypeReference)) { SingleTypeReference retType = (SingleTypeReference) methodDeclaration.returnType; if (CharOperation.equals(voidType, retType.token)) returnsVoid = true; if (CharOperation.equals(booleanType, retType.token)) returnsBoolean = true; } if (!returnsVoid && !containsIfPcd) { methodDeclaration.scope.problemReporter().signalError(methodDeclaration.returnType.sourceStart, methodDeclaration.returnType.sourceEnd, "Methods annotated with @Pointcut must return void unless the pointcut contains an if() expression"); } if (!returnsBoolean && containsIfPcd) { methodDeclaration.scope.problemReporter().signalError(methodDeclaration.returnType.sourceStart, methodDeclaration.returnType.sourceEnd, "Methods annotated with @Pointcut must return boolean when the pointcut contains an if() expression"); } if (methodDeclaration.statements != null && methodDeclaration.statements.length > 0 && !containsIfPcd) { methodDeclaration.scope.problemReporter() .signalError(methodDeclaration.returnType.sourceStart, methodDeclaration.returnType.sourceEnd, "Pointcuts without an if() expression should have an empty method body"); } if (pcDecl.pointcutDesignator == null) { if (Modifier.isAbstract(methodDeclaration.modifiers) || noValueSupplied // this // is // a // matches // nothing // pointcut // those 2 checks makes sense for aop.xml concretization but NOT for // regular abstraction of pointcut // && returnsVoid // && (methodDeclaration.arguments == null || // methodDeclaration.arguments.length == 0)) { ) { // fine } else { methodDeclaration.scope.problemReporter().signalError(methodDeclaration.returnType.sourceStart, methodDeclaration.returnType.sourceEnd, "Method annotated with @Pointcut() for abstract pointcut must be abstract"); } } else if (Modifier.isAbstract(methodDeclaration.modifiers)) { methodDeclaration.scope.problemReporter().signalError(methodDeclaration.returnType.sourceStart, methodDeclaration.returnType.sourceEnd, "Method annotated with non abstract @Pointcut(\"" + pointcutExpression + "\") is abstract"); } } private void copyAllFields(MethodDeclaration from, MethodDeclaration to) { to.annotations = from.annotations; to.arguments = from.arguments; to.binding = from.binding; to.bits = from.bits; to.bodyEnd = from.bodyEnd; to.bodyStart = from.bodyStart; to.declarationSourceEnd = from.declarationSourceEnd; to.declarationSourceStart = from.declarationSourceStart; to.explicitDeclarations = from.explicitDeclarations; to.ignoreFurtherInvestigation = from.ignoreFurtherInvestigation; to.javadoc = from.javadoc; to.modifiers = from.modifiers; to.modifiersSourceStart = from.modifiersSourceStart; to.returnType = from.returnType; to.scope = from.scope; to.selector = from.selector; to.sourceEnd = from.sourceEnd; to.sourceStart = from.sourceStart; to.statements = from.statements; to.thrownExceptions = from.thrownExceptions; to.typeParameters = from.typeParameters; } private void swap(TypeDeclaration inType, MethodDeclaration thisDeclaration, MethodDeclaration forThatDeclaration) { for (int i = 0; i < inType.methods.length; i++) { if (inType.methods[i] == thisDeclaration) { inType.methods[i] = forThatDeclaration; break; } } } private static class AspectJAnnotations { boolean hasAdviceAnnotation = false; boolean hasPointcutAnnotation = false; boolean hasAspectAnnotation = false; boolean hasAdviceNameAnnotation = false; boolean hasDeclareParents = false; boolean hasMultipleAdviceAnnotations = false; boolean hasMultiplePointcutAnnotations = false; boolean hasMultipleAspectAnnotations = false; AdviceKind adviceKind = null; Annotation adviceAnnotation = null; Annotation pointcutAnnotation = null; Annotation aspectAnnotation = null; Annotation adviceNameAnnotation = null; Annotation duplicateAdviceAnnotation = null; Annotation duplicatePointcutAnnotation = null; Annotation duplicateAspectAnnotation = null; public AspectJAnnotations(Annotation[] annotations) { if (annotations == null) return; for (int i = 0; i < annotations.length; i++) { if (annotations[i].resolvedType == null) continue; // user messed up annotation declaration char[] sig = annotations[i].resolvedType.signature(); if (CharOperation.equals(afterAdviceSig, sig)) { adviceKind = AdviceKind.After; addAdviceAnnotation(annotations[i]); } else if (CharOperation.equals(afterReturningAdviceSig, sig)) { adviceKind = AdviceKind.AfterReturning; addAdviceAnnotation(annotations[i]); } else if (CharOperation.equals(afterThrowingAdviceSig, sig)) { adviceKind = AdviceKind.AfterThrowing; addAdviceAnnotation(annotations[i]); } else if (CharOperation.equals(beforeAdviceSig, sig)) { adviceKind = AdviceKind.Before; addAdviceAnnotation(annotations[i]); } else if (CharOperation.equals(aroundAdviceSig, sig)) { adviceKind = AdviceKind.Around; addAdviceAnnotation(annotations[i]); } else if (CharOperation.equals(adviceNameSig, sig)) { hasAdviceNameAnnotation = true; adviceNameAnnotation = annotations[i]; } else if (CharOperation.equals(declareParentsSig, sig)) { hasDeclareParents = true; } else if (CharOperation.equals(aspectSig, sig)) { if (hasAspectAnnotation) { hasMultipleAspectAnnotations = true; duplicateAspectAnnotation = annotations[i]; } else { hasAspectAnnotation = true; aspectAnnotation = annotations[i]; } } else if (CharOperation.equals(pointcutSig, sig)) { if (hasPointcutAnnotation) { hasMultiplePointcutAnnotations = true; duplicatePointcutAnnotation = annotations[i]; } else { hasPointcutAnnotation = true; pointcutAnnotation = annotations[i]; } } } } public boolean hasAspectJAnnotations() { return hasAdviceAnnotation || hasPointcutAnnotation || hasAdviceNameAnnotation || hasAspectAnnotation; } private void addAdviceAnnotation(Annotation annotation) { if (!hasAdviceAnnotation) { hasAdviceAnnotation = true; adviceAnnotation = annotation; } else { hasMultipleAdviceAnnotations = true; duplicateAdviceAnnotation = annotation; } } } private static class HasIfPCDVisitor extends AbstractPatternNodeVisitor { public boolean containsIfPcd = false; public Object visit(IfPointcut node, Object data) { containsIfPcd = true; return data; } } }
384,401
Bug 384401 NPE when no pointcut in afterthrowing annotation style advice
From the mailing list: import org.aspectj.lang.JoinPoint; import org.aspectj.lang.annotation.AfterThrowing; import org.aspectj.lang.annotation.Aspect; @Aspect public class X { // @AfterThrowing(pointcut="execution(* *(..))",throwing = "e") @AfterThrowing(throwing = "e") public void bizLoggerWithException(JoinPoint thisJoinPoint,Throwable e) { // .....// do some stuff } } class BizLoggable {}
resolved fixed
55ebaa1
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2012-08-23T20:05:24Z"
"2012-07-05T17:40:00Z"
tests/bugs171/pr384401/X.java
384,401
Bug 384401 NPE when no pointcut in afterthrowing annotation style advice
From the mailing list: import org.aspectj.lang.JoinPoint; import org.aspectj.lang.annotation.AfterThrowing; import org.aspectj.lang.annotation.Aspect; @Aspect public class X { // @AfterThrowing(pointcut="execution(* *(..))",throwing = "e") @AfterThrowing(throwing = "e") public void bizLoggerWithException(JoinPoint thisJoinPoint,Throwable e) { // .....// do some stuff } } class BizLoggable {}
resolved fixed
55ebaa1
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2012-08-23T20:05:24Z"
"2012-07-05T17:40:00Z"
tests/src/org/aspectj/systemtest/ajc171/Ajc171Tests.java
/******************************************************************************* * Copyright (c) 2012 Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Andy Clement - initial API and implementation *******************************************************************************/ package org.aspectj.systemtest.ajc171; import java.io.File; import junit.framework.Test; import org.aspectj.testing.XMLBasedAjcTestCase; /** * @author Andy Clement */ public class Ajc171Tests extends org.aspectj.testing.XMLBasedAjcTestCase { public void testUnresolvableEnum_pr387568() { runTest("unresolvable enum"); } public void testAbstractItds_pr386049() { runTest("itd abstract"); } public void testPublicITDFs_pr73507_1() { runTest("public ITDfs - 1"); } public void testPublicITDFs_pr73507_2() { runTest("public ITDfs - 2"); } public void testPublicITDFs_pr73507_3() { runTest("public ITDfs - 3"); } public void testPublicITDFs_pr73507_4() { runTest("public ITDfs - 4"); } public void testPublicITDFs_pr73507_5() { runTest("public ITDfs - 5"); } public void testGenerics_384398() { runTest("generics itds"); } // public void testGenerics_384398_2() { // runTest("generics itds 2"); // } // --- public static Test suite() { return XMLBasedAjcTestCase.loadSuite(Ajc171Tests.class); } @Override protected File getSpecFile() { return new File("../tests/src/org/aspectj/systemtest/ajc171/ajc171.xml"); } }
388,971
Bug 388971 Double Synthetic attributes on some around advice members
Some of the support members in aspects were getting Synthetic attributes added twice (once when compiled, once when used as an aspect library). Some JVMs appear to flag this as a verify error. The fix is simply to check before adding to make sure the attribute isn't added twice.
resolved fixed
c2ff74f
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2012-09-06T16:37:31Z"
"2012-09-06T16:46:40Z"
weaver/src/org/aspectj/weaver/bcel/LazyMethodGen.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Eclipse Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * PARC initial implementation * ******************************************************************/ package org.aspectj.weaver.bcel; import java.io.ByteArrayOutputStream; import java.io.PrintStream; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.ListIterator; import java.util.Map; import java.util.Set; import java.util.Stack; import org.aspectj.apache.bcel.Constants; import org.aspectj.apache.bcel.classfile.Attribute; import org.aspectj.apache.bcel.classfile.ConstantPool; import org.aspectj.apache.bcel.classfile.Method; import org.aspectj.apache.bcel.classfile.Synthetic; import org.aspectj.apache.bcel.classfile.annotation.AnnotationGen; import org.aspectj.apache.bcel.generic.BranchHandle; import org.aspectj.apache.bcel.generic.ClassGenException; import org.aspectj.apache.bcel.generic.CodeExceptionGen; import org.aspectj.apache.bcel.generic.Instruction; import org.aspectj.apache.bcel.generic.InstructionBranch; import org.aspectj.apache.bcel.generic.InstructionHandle; import org.aspectj.apache.bcel.generic.InstructionList; import org.aspectj.apache.bcel.generic.InstructionSelect; import org.aspectj.apache.bcel.generic.InstructionTargeter; import org.aspectj.apache.bcel.generic.LineNumberTag; import org.aspectj.apache.bcel.generic.LocalVariableTag; import org.aspectj.apache.bcel.generic.MethodGen; import org.aspectj.apache.bcel.generic.ObjectType; import org.aspectj.apache.bcel.generic.Tag; import org.aspectj.apache.bcel.generic.TargetLostException; import org.aspectj.apache.bcel.generic.Type; import org.aspectj.bridge.IMessage; import org.aspectj.bridge.ISourceLocation; import org.aspectj.weaver.AjAttribute; import org.aspectj.weaver.AjAttribute.WeaverVersionInfo; import org.aspectj.weaver.AnnotationAJ; import org.aspectj.weaver.BCException; import org.aspectj.weaver.ISourceContext; import org.aspectj.weaver.MemberImpl; import org.aspectj.weaver.NameMangler; import org.aspectj.weaver.ResolvedMember; import org.aspectj.weaver.ResolvedType; import org.aspectj.weaver.Shadow; import org.aspectj.weaver.UnresolvedType; import org.aspectj.weaver.WeaverMessages; import org.aspectj.weaver.tools.Traceable; /** * A LazyMethodGen should be treated as a MethodGen. It's our way of abstracting over the low-level Method objects. It converts * through {@link MethodGen} to create and to serialize, but that's it. * * <p> * At any rate, there are two ways to create LazyMethodGens. One is from a method, which does work through MethodGen to do the * correct thing. The other is the creation of a completely empty LazyMethodGen, and it is used when we're constructing code from * scratch. * * <p> * We stay away from targeters for rangey things like Shadows and Exceptions. */ public final class LazyMethodGen implements Traceable { private static final int ACC_SYNTHETIC = 0x1000; private int modifiers; private Type returnType; private final String name; private Type[] argumentTypes; // private final String[] argumentNames; private String[] declaredExceptions; private InstructionList body; private List<Attribute> attributes; private List<AnnotationAJ> newAnnotations; private List<ResolvedType> annotationsForRemoval; private AnnotationAJ[][] newParameterAnnotations; private final LazyClassGen enclosingClass; private BcelMethod memberView; private AjAttribute.EffectiveSignatureAttribute effectiveSignature; int highestLineNumber = 0; boolean wasPackedOptimally = false; private Method savedMethod = null; private static final AnnotationAJ[] NO_ANNOTATIONAJ = new AnnotationAJ[] {}; /* * We use LineNumberTags and not Gens. * * This option specifies whether we let the BCEL classes create LineNumberGens and LocalVariableGens or if we make it create * LineNumberTags and LocalVariableTags. Up until 1.5.1 we always created Gens - then on return from the MethodGen ctor we took * them apart, reprocessed them all and created Tags. (see unpackLocals/unpackLineNumbers). As we have our own copy of Bcel, why * not create the right thing straightaway? So setting this to true will call the MethodGen ctor() in such a way that it creates * Tags - removing the need for unpackLocals/unpackLineNumbers - HOWEVER see the ensureAllLineNumberSetup() method for some * other relevant info. * * Whats the difference between a Tag and a Gen? A Tag is more lightweight, it doesn't know which instructions it targets, it * relies on the instructions targettingit - this reduces the amount of targeter manipulation we have to do. */ /** * This is nonnull if this method is the result of an "inlining". We currently copy methods into other classes for around * advice. We add this field so we can get JSR45 information correct. If/when we do _actual_ inlining, we'll need to subtype * LineNumberTag to have external line numbers. */ String fromFilename = null; private int maxLocals; private boolean canInline = true; private boolean isSynthetic = false; List<BcelShadow> matchedShadows; // Used for interface introduction - this is the type of the interface the method is technically on public ResolvedType definingType = null; public LazyMethodGen(int modifiers, Type returnType, String name, Type[] paramTypes, String[] declaredExceptions, LazyClassGen enclosingClass) { // enclosingClass.getName() + ", " + returnType); this.memberView = null; // should be okay, since constructed ones aren't woven into this.modifiers = modifiers; this.returnType = returnType; this.name = name; this.argumentTypes = paramTypes; // this.argumentNames = Utility.makeArgNames(paramTypes.length); this.declaredExceptions = declaredExceptions; if (!Modifier.isAbstract(modifiers)) { body = new InstructionList(); setMaxLocals(calculateMaxLocals()); } else { body = null; } this.attributes = new ArrayList<Attribute>(); this.enclosingClass = enclosingClass; assertGoodBody(); // @AJ advice are not inlined by default since requires further analysis and weaving ordering control // TODO AV - improve - note: no room for improvement as long as aspects are reweavable // since the inlined version with wrappers and an to be done annotation to keep // inline state will be garbaged due to reweavable impl if (memberView != null && isAdviceMethod()) { if (enclosingClass.getType().isAnnotationStyleAspect()) { // TODO we could check for @Around advice as well this.canInline = false; } } } private int calculateMaxLocals() { int ret = Modifier.isStatic(modifiers) ? 0 : 1; // will there be a 'this'? for (Type type : argumentTypes) { ret += type.getSize(); } return ret; } // build from an existing method, lazy build saves most work for // initialization public LazyMethodGen(Method m, LazyClassGen enclosingClass) { savedMethod = m; this.enclosingClass = enclosingClass; if (!(m.isAbstract() || m.isNative()) && m.getCode() == null) { throw new RuntimeException("bad non-abstract method with no code: " + m + " on " + enclosingClass); } if ((m.isAbstract() || m.isNative()) && m.getCode() != null) { throw new RuntimeException("bad abstract method with code: " + m + " on " + enclosingClass); } this.memberView = new BcelMethod(enclosingClass.getBcelObjectType(), m); this.modifiers = m.getModifiers(); this.name = m.getName(); // @AJ advice are not inlined by default since requires further analysis // and weaving ordering control // TODO AV - improve - note: no room for improvement as long as aspects // are reweavable // since the inlined version with wrappers and an to be done annotation // to keep // inline state will be garbaged due to reweavable impl if (memberView != null && isAdviceMethod()) { if (enclosingClass.getType().isAnnotationStyleAspect()) { // TODO we could check for @Around advice as well this.canInline = false; } } } private boolean isAbstractOrNative(int modifiers) { return Modifier.isAbstract(modifiers) || Modifier.isNative(modifiers); } public LazyMethodGen(BcelMethod m, LazyClassGen enclosingClass) { savedMethod = m.getMethod(); this.enclosingClass = enclosingClass; if (!isAbstractOrNative(m.getModifiers()) && savedMethod.getCode() == null) { throw new RuntimeException("bad non-abstract method with no code: " + m + " on " + enclosingClass); } if (isAbstractOrNative(m.getModifiers()) && savedMethod.getCode() != null) { throw new RuntimeException("bad abstract method with code: " + m + " on " + enclosingClass); } // this.memberView = new BcelMethod(enclosingClass.getBcelObjectType(), // m); this.memberView = m; this.modifiers = savedMethod.getModifiers(); this.name = m.getName(); // @AJ advice are not inlined by default since requires further analysis // and weaving ordering control // TODO AV - improve - note: no room for improvement as long as aspects // are reweavable // since the inlined version with wrappers and an to be done annotation // to keep // inline state will be garbaged due to reweavable impl if (memberView != null && isAdviceMethod()) { if (enclosingClass.getType().isAnnotationStyleAspect()) { // TODO we could check for @Around advice as well this.canInline = false; } } } public boolean hasDeclaredLineNumberInfo() { return (memberView != null && memberView.hasDeclarationLineNumberInfo()); } public int getDeclarationLineNumber() { if (hasDeclaredLineNumberInfo()) { return memberView.getDeclarationLineNumber(); } else { return -1; } } public int getDeclarationOffset() { if (hasDeclaredLineNumberInfo()) { return memberView.getDeclarationOffset(); } else { return 0; } } public void addAnnotation(AnnotationAJ ax) { initialize(); if (memberView == null) { // If member view is null, we manage them in newAnnotations if (newAnnotations == null) { newAnnotations = new ArrayList<AnnotationAJ>(); } newAnnotations.add(ax); } else { memberView.addAnnotation(ax); } } public void removeAnnotation(ResolvedType annotationType) { initialize(); if (memberView == null) { // If member view is null, we manage them in newAnnotations if (annotationsForRemoval == null) { annotationsForRemoval = new ArrayList<ResolvedType>(); } annotationsForRemoval.add(annotationType); } else { memberView.removeAnnotation(annotationType); } } public void addParameterAnnotation(int parameterNumber, AnnotationAJ anno) { initialize(); if (memberView == null) { if (newParameterAnnotations == null) { // time to create it int pcount = getArgumentTypes().length; newParameterAnnotations = new AnnotationAJ[pcount][]; for (int i = 0; i < pcount; i++) { if (i == parameterNumber) { newParameterAnnotations[i] = new AnnotationAJ[1]; newParameterAnnotations[i][0] = anno; } else { newParameterAnnotations[i] = NO_ANNOTATIONAJ; } } } else { AnnotationAJ[] currentAnnoArray = newParameterAnnotations[parameterNumber]; AnnotationAJ[] newAnnoArray = new AnnotationAJ[currentAnnoArray.length + 1]; System.arraycopy(currentAnnoArray, 0, newAnnoArray, 0, currentAnnoArray.length); newAnnoArray[currentAnnoArray.length] = anno; newParameterAnnotations[parameterNumber] = newAnnoArray; } } else { memberView.addParameterAnnotation(parameterNumber, anno); } } public boolean hasAnnotation(UnresolvedType annotationType) { initialize(); if (memberView == null) { if (annotationsForRemoval != null) { for (ResolvedType at : annotationsForRemoval) { if (at.equals(annotationType)) { return false; } } } // Check local annotations first if (newAnnotations != null) { for (AnnotationAJ annotation : newAnnotations) { if (annotation.getTypeSignature().equals(annotationType.getSignature())) { return true; } } } memberView = new BcelMethod(getEnclosingClass().getBcelObjectType(), getMethod()); return memberView.hasAnnotation(annotationType); } return memberView.hasAnnotation(annotationType); } private void initialize() { if (returnType != null) { return; } MethodGen gen = new MethodGen(savedMethod, enclosingClass.getName(), enclosingClass.getConstantPool(), true); this.returnType = gen.getReturnType(); this.argumentTypes = gen.getArgumentTypes(); this.declaredExceptions = gen.getExceptions(); this.attributes = gen.getAttributes(); // this.annotations = gen.getAnnotations(); this.maxLocals = gen.getMaxLocals(); // this.returnType = BcelWorld.makeBcelType(memberView.getReturnType()); // this.argumentTypes = // BcelWorld.makeBcelTypes(memberView.getParameterTypes()); // // this.declaredExceptions = // UnresolvedType.getNames(memberView.getExceptions()); // //gen.getExceptions(); // this.attributes = new Attribute[0]; //gen.getAttributes(); // this.maxLocals = savedMethod.getCode().getMaxLocals(); if (gen.isAbstract() || gen.isNative()) { body = null; } else { // body = new InstructionList(savedMethod.getCode().getCode()); body = gen.getInstructionList(); unpackHandlers(gen); ensureAllLineNumberSetup(); highestLineNumber = gen.getHighestlinenumber(); } assertGoodBody(); } // XXX we're relying on the javac promise I've just made up that we won't // have an early exception // in the list mask a later exception: That is, for two exceptions E and F, // if E preceeds F, then either E \cup F = {}, or E \nonstrictsubset F. So // when we add F, // we add it on the _OUTSIDE_ of any handlers that share starts or ends with // it. // with that in mind, we merrily go adding ranges for exceptions. private void unpackHandlers(MethodGen gen) { CodeExceptionGen[] exns = gen.getExceptionHandlers(); if (exns != null) { int len = exns.length; // if (len > 0) hasExceptionHandlers = true; int priority = len - 1; for (int i = 0; i < len; i++, priority--) { CodeExceptionGen exn = exns[i]; InstructionHandle start = Range.genStart(body, getOutermostExceptionStart(exn.getStartPC())); InstructionHandle end = Range.genEnd(body, getOutermostExceptionEnd(exn.getEndPC())); // this doesn't necessarily handle overlapping correctly!!! ExceptionRange er = new ExceptionRange(body, exn.getCatchType() == null ? null : BcelWorld.fromBcel(exn .getCatchType()), priority); er.associateWithTargets(start, end, exn.getHandlerPC()); exn.setStartPC(null); // also removes from target exn.setEndPC(null); // also removes from target exn.setHandlerPC(null); // also removes from target } gen.removeExceptionHandlers(); } } private InstructionHandle getOutermostExceptionStart(InstructionHandle ih) { while (true) { if (ExceptionRange.isExceptionStart(ih.getPrev())) { ih = ih.getPrev(); } else { return ih; } } } private InstructionHandle getOutermostExceptionEnd(InstructionHandle ih) { while (true) { if (ExceptionRange.isExceptionEnd(ih.getNext())) { ih = ih.getNext(); } else { return ih; } } } /** * On entry to this method we have a method whose instruction stream contains a few instructions that have line numbers assigned * to them (LineNumberTags). The aim is to ensure every instruction has the right line number. This is necessary because some of * them may be extracted out into other methods - and it'd be useful for them to maintain the source line number for debugging. */ public void ensureAllLineNumberSetup() { LineNumberTag lastKnownLineNumberTag = null; boolean skip = false; for (InstructionHandle ih = body.getStart(); ih != null; ih = ih.getNext()) { skip = false; for (InstructionTargeter targeter : ih.getTargeters()) { if (targeter instanceof LineNumberTag) { lastKnownLineNumberTag = (LineNumberTag) targeter; skip = true; } } if (lastKnownLineNumberTag != null && !skip) { ih.addTargeter(lastKnownLineNumberTag); } } } // =============== public int allocateLocal(Type type) { return allocateLocal(type.getSize()); } public int allocateLocal(int slots) { int max = getMaxLocals(); setMaxLocals(max + slots); return max; } public Method getMethod() { if (savedMethod != null) { return savedMethod; // ??? this relies on gentle treatment of // constant pool } try { MethodGen gen = pack(); savedMethod = gen.getMethod(); return savedMethod; } catch (ClassGenException e) { enclosingClass .getBcelObjectType() .getResolvedTypeX() .getWorld() .showMessage( IMessage.ERROR, WeaverMessages.format(WeaverMessages.PROBLEM_GENERATING_METHOD, this.getClassName(), this.getName(), e.getMessage()), this.getMemberView() == null ? null : this.getMemberView().getSourceLocation(), null); // throw e; PR 70201.... let the normal problem reporting // infrastructure deal with this rather than crashing. body = null; MethodGen gen = pack(); return gen.getMethod(); } catch (RuntimeException re) { if (re.getCause() instanceof ClassGenException) { enclosingClass .getBcelObjectType() .getResolvedTypeX() .getWorld() .showMessage( IMessage.ERROR, WeaverMessages.format(WeaverMessages.PROBLEM_GENERATING_METHOD, this.getClassName(), this.getName(), re.getCause().getMessage()), this.getMemberView() == null ? null : this.getMemberView().getSourceLocation(), null); // throw e; PR 70201.... let the normal problem reporting // infrastructure deal with this rather than crashing. body = null; MethodGen gen = pack(); return gen.getMethod(); } throw re; } } public void markAsChanged() { if (wasPackedOptimally) { throw new RuntimeException("Already packed method is being re-modified: " + getClassName() + " " + toShortString()); } initialize(); savedMethod = null; } // ============================= @Override public String toString() { BcelObjectType bot = enclosingClass.getBcelObjectType(); WeaverVersionInfo weaverVersion = (bot == null ? WeaverVersionInfo.CURRENT : bot.getWeaverVersionAttribute()); return toLongString(weaverVersion); } public String toShortString() { String access = org.aspectj.apache.bcel.classfile.Utility.accessToString(getAccessFlags()); StringBuffer buf = new StringBuffer(); if (!access.equals("")) { buf.append(access); buf.append(" "); } buf.append(org.aspectj.apache.bcel.classfile.Utility.signatureToString(getReturnType().getSignature(), true)); buf.append(" "); buf.append(getName()); buf.append("("); { int len = argumentTypes.length; if (len > 0) { buf.append(org.aspectj.apache.bcel.classfile.Utility.signatureToString(argumentTypes[0].getSignature(), true)); for (int i = 1; i < argumentTypes.length; i++) { buf.append(", "); buf.append(org.aspectj.apache.bcel.classfile.Utility.signatureToString(argumentTypes[i].getSignature(), true)); } } } buf.append(")"); { int len = declaredExceptions != null ? declaredExceptions.length : 0; if (len > 0) { buf.append(" throws "); buf.append(declaredExceptions[0]); for (int i = 1; i < declaredExceptions.length; i++) { buf.append(", "); buf.append(declaredExceptions[i]); } } } return buf.toString(); } public String toLongString(WeaverVersionInfo weaverVersion) { ByteArrayOutputStream s = new ByteArrayOutputStream(); print(new PrintStream(s), weaverVersion); return new String(s.toByteArray()); } public void print(WeaverVersionInfo weaverVersion) { print(System.out, weaverVersion); } public void print(PrintStream out, WeaverVersionInfo weaverVersion) { out.print(" " + toShortString()); printAspectAttributes(out, weaverVersion); InstructionList body = getBody(); if (body == null) { out.println(";"); return; } out.println(":"); new BodyPrinter(out).run(); out.println(" end " + toShortString()); } private void printAspectAttributes(PrintStream out, WeaverVersionInfo weaverVersion) { ISourceContext context = null; if (enclosingClass != null && enclosingClass.getType() != null) { context = enclosingClass.getType().getSourceContext(); } List<AjAttribute> as = Utility.readAjAttributes(getClassName(), attributes.toArray(new Attribute[] {}), context, null, weaverVersion, new BcelConstantPoolReader(this.enclosingClass.getConstantPool())); if (!as.isEmpty()) { out.println(" " + as.get(0)); // XXX assuming exactly one // attribute, munger... } } private class BodyPrinter { Map<InstructionHandle, String> labelMap = new HashMap<InstructionHandle, String>(); InstructionList body; PrintStream out; ConstantPool pool; BodyPrinter(PrintStream out) { this.pool = enclosingClass.getConstantPool(); this.body = getBodyForPrint(); this.out = out; } BodyPrinter(PrintStream out, InstructionList il) { this.pool = enclosingClass.getConstantPool(); this.body = il; this.out = out; } void run() { // killNops(); assignLabels(); print(); } // label assignment void assignLabels() { LinkedList<ExceptionRange> exnTable = new LinkedList<ExceptionRange>(); String pendingLabel = null; // boolean hasPendingTargeters = false; int lcounter = 0; for (InstructionHandle ih = body.getStart(); ih != null; ih = ih.getNext()) { Iterator<InstructionTargeter> tIter = ih.getTargeters().iterator(); while (tIter.hasNext()) { InstructionTargeter t = tIter.next();// targeters // [ // i // ] // ; if (t instanceof ExceptionRange) { // assert isRangeHandle(h); ExceptionRange r = (ExceptionRange) t; if (r.getStart() == ih) { insertHandler(r, exnTable); } } else if (t instanceof InstructionBranch) { if (pendingLabel == null) { pendingLabel = "L" + lcounter++; } } else { // assert isRangeHandle(h) } } if (pendingLabel != null) { labelMap.put(ih, pendingLabel); if (!Range.isRangeHandle(ih)) { pendingLabel = null; } } } int ecounter = 0; for (Iterator i = exnTable.iterator(); i.hasNext();) { ExceptionRange er = (ExceptionRange) i.next(); String exceptionLabel = "E" + ecounter++; labelMap.put(Range.getRealStart(er.getHandler()), exceptionLabel); labelMap.put(er.getHandler(), exceptionLabel); } } // printing void print() { int depth = 0; int currLine = -1; bodyPrint: for (InstructionHandle ih = body.getStart(); ih != null; ih = ih.getNext()) { if (Range.isRangeHandle(ih)) { Range r = Range.getRange(ih); // don't print empty ranges, that is, ranges who contain no // actual instructions for (InstructionHandle xx = r.getStart(); Range.isRangeHandle(xx); xx = xx.getNext()) { if (xx == r.getEnd()) { continue bodyPrint; } } // doesn't handle nested: if (r.getStart().getNext() == // r.getEnd()) continue; if (r.getStart() == ih) { printRangeString(r, depth++); } else { if (r.getEnd() != ih) { throw new RuntimeException("bad"); } printRangeString(r, --depth); } } else { printInstruction(ih, depth); int line = getLineNumber(ih, currLine); if (line != currLine) { currLine = line; out.println(" (line " + line + ")"); } else { out.println(); } } } } void printRangeString(Range r, int depth) { printDepth(depth); out.println(getRangeString(r, labelMap)); } String getRangeString(Range r, Map<InstructionHandle, String> labelMap) { if (r instanceof ExceptionRange) { ExceptionRange er = (ExceptionRange) r; return er.toString() + " -> " + labelMap.get(er.getHandler()); // // + " PRI " + er.getPriority(); } else { return r.toString(); } } void printDepth(int depth) { pad(BODY_INDENT); while (depth > 0) { out.print("| "); depth--; } } void printLabel(String s, int depth) { int space = Math.max(CODE_INDENT - depth * 2, 0); if (s == null) { pad(space); } else { space = Math.max(space - (s.length() + 2), 0); pad(space); out.print(s); out.print(": "); } } void printInstruction(InstructionHandle h, int depth) { printDepth(depth); printLabel(labelMap.get(h), depth); Instruction inst = h.getInstruction(); if (inst.isConstantPoolInstruction()) { out.print(Constants.OPCODE_NAMES[inst.opcode].toUpperCase()); out.print(" "); out.print(pool.constantToString(pool.getConstant(inst.getIndex()))); } else if (inst instanceof InstructionSelect) { InstructionSelect sinst = (InstructionSelect) inst; out.println(Constants.OPCODE_NAMES[sinst.opcode].toUpperCase()); int[] matches = sinst.getMatchs(); InstructionHandle[] targets = sinst.getTargets(); InstructionHandle defaultTarget = sinst.getTarget(); for (int i = 0, len = matches.length; i < len; i++) { printDepth(depth); printLabel(null, depth); out.print(" "); out.print(matches[i]); out.print(": \t"); out.println(labelMap.get(targets[i])); } printDepth(depth); printLabel(null, depth); out.print(" "); out.print("default: \t"); out.print(labelMap.get(defaultTarget)); } else if (inst instanceof InstructionBranch) { InstructionBranch brinst = (InstructionBranch) inst; out.print(Constants.OPCODE_NAMES[brinst.getOpcode()].toUpperCase()); out.print(" "); out.print(labelMap.get(brinst.getTarget())); } else if (inst.isLocalVariableInstruction()) { // LocalVariableInstruction lvinst = (LocalVariableInstruction) // inst; out.print(inst.toString(false).toUpperCase()); int index = inst.getIndex(); LocalVariableTag tag = getLocalVariableTag(h, index); if (tag != null) { out.print(" // "); out.print(tag.getType()); out.print(" "); out.print(tag.getName()); } } else { out.print(inst.toString(false).toUpperCase()); } } static final int BODY_INDENT = 4; static final int CODE_INDENT = 16; void pad(int size) { for (int i = 0; i < size; i++) { out.print(" "); } } } static LocalVariableTag getLocalVariableTag(InstructionHandle ih, int index) { for (InstructionTargeter t : ih.getTargeters()) { if (t instanceof LocalVariableTag) { LocalVariableTag lvt = (LocalVariableTag) t; if (lvt.getSlot() == index) { return lvt; } } } return null; } static int getLineNumber(InstructionHandle ih, int prevLine) { for (InstructionTargeter t : ih.getTargeters()) { if (t instanceof LineNumberTag) { return ((LineNumberTag) t).getLineNumber(); } } return prevLine; } public boolean isStatic() { return Modifier.isStatic(getAccessFlags()); } public boolean isAbstract() { return Modifier.isAbstract(getAccessFlags()); } public boolean isBridgeMethod() { return (getAccessFlags() & Constants.ACC_BRIDGE) != 0; } public void addExceptionHandler(InstructionHandle start, InstructionHandle end, InstructionHandle handlerStart, ObjectType catchType, boolean highPriority) { InstructionHandle start1 = Range.genStart(body, start); InstructionHandle end1 = Range.genEnd(body, end); ExceptionRange er = new ExceptionRange(body, (catchType == null ? null : BcelWorld.fromBcel(catchType)), highPriority); er.associateWithTargets(start1, end1, handlerStart); } public int getAccessFlags() { return modifiers; } public int getAccessFlagsWithoutSynchronized() { if (isSynchronized()) { return modifiers - Modifier.SYNCHRONIZED; } return modifiers; } public boolean isSynchronized() { return (modifiers & Modifier.SYNCHRONIZED) != 0; } public void setAccessFlags(int newFlags) { this.modifiers = newFlags; } public Type[] getArgumentTypes() { initialize(); return argumentTypes; } public LazyClassGen getEnclosingClass() { return enclosingClass; } public int getMaxLocals() { return maxLocals; } public String getName() { return name; } public String getGenericReturnTypeSignature() { if (memberView == null) { return getReturnType().getSignature(); } else { return memberView.getGenericReturnType().getSignature(); } } public Type getReturnType() { initialize(); return returnType; } public void setMaxLocals(int maxLocals) { this.maxLocals = maxLocals; } public InstructionList getBody() { markAsChanged(); return body; } public InstructionList getBodyForPrint() { return body; } public boolean hasBody() { if (savedMethod != null) { return savedMethod.getCode() != null; } return body != null; } public List<Attribute> getAttributes() { return attributes; } public String[] getDeclaredExceptions() { return declaredExceptions; } public String getClassName() { return enclosingClass.getName(); } // ---- packing! public MethodGen pack() { forceSyntheticForAjcMagicMembers(); // killNops(); int flags = getAccessFlags(); if (enclosingClass.getWorld().isJoinpointSynchronizationEnabled() && enclosingClass.getWorld().areSynchronizationPointcutsInUse()) { flags = getAccessFlagsWithoutSynchronized(); } MethodGen gen = new MethodGen(flags, getReturnType(), getArgumentTypes(), null, // getArgumentNames(), getName(), getEnclosingClass().getName(), new InstructionList(), getEnclosingClass().getConstantPool()); for (int i = 0, len = declaredExceptions.length; i < len; i++) { gen.addException(declaredExceptions[i]); } for (Attribute attr : attributes) { gen.addAttribute(attr); } if (newAnnotations != null) { for (AnnotationAJ element : newAnnotations) { gen.addAnnotation(new AnnotationGen(((BcelAnnotation) element).getBcelAnnotation(), gen.getConstantPool(), true)); } } if (newParameterAnnotations != null) { for (int i = 0; i < newParameterAnnotations.length; i++) { AnnotationAJ[] annos = newParameterAnnotations[i]; for (int j = 0; j < annos.length; j++) { gen.addParameterAnnotation(i, new AnnotationGen(((BcelAnnotation) annos[j]).getBcelAnnotation(), gen.getConstantPool(), true)); } } } if (memberView != null && memberView.getAnnotations() != null && memberView.getAnnotations().length != 0) { AnnotationAJ[] ans = memberView.getAnnotations(); for (int i = 0, len = ans.length; i < len; i++) { AnnotationGen a = ((BcelAnnotation) ans[i]).getBcelAnnotation(); gen.addAnnotation(new AnnotationGen(a, gen.getConstantPool(), true)); } } if (isSynthetic) { if (enclosingClass.getWorld().isInJava5Mode()) { gen.setModifiers(gen.getModifiers() | ACC_SYNTHETIC); } // belt and braces, do the attribute even on Java 5 in addition to // the modifier flag ConstantPool cpg = gen.getConstantPool(); int index = cpg.addUtf8("Synthetic"); gen.addAttribute(new Synthetic(index, 0, new byte[0], cpg)); } if (hasBody()) { if (this.enclosingClass.getWorld().shouldFastPackMethods()) { if (isAdviceMethod() || getName().equals("<clinit>")) { packBody(gen); } else { optimizedPackBody(gen); } } else { packBody(gen); } gen.setMaxLocals(); gen.setMaxStack(); } else { gen.setInstructionList(null); } return gen; } private void forceSyntheticForAjcMagicMembers() { if (NameMangler.isSyntheticMethod(getName(), inAspect())) { makeSynthetic(); } } private boolean inAspect() { BcelObjectType objectType = enclosingClass.getBcelObjectType(); return (objectType == null ? false : objectType.isAspect()); } public void makeSynthetic() { isSynthetic = true; } private static class LVPosition { InstructionHandle start = null; InstructionHandle end = null; } /** * fill the newly created method gen with our body, inspired by InstructionList.copy() */ public void packBody(MethodGen gen) { InstructionList fresh = gen.getInstructionList(); Map<InstructionHandle, InstructionHandle> map = copyAllInstructionsExceptRangeInstructionsInto(fresh); // at this point, no rangeHandles are in fresh. Let's use that... /* * Update branch targets and insert various attributes. Insert our exceptionHandlers into a sorted list, so they can be * added in order later. */ InstructionHandle oldInstructionHandle = getBody().getStart(); InstructionHandle newInstructionHandle = fresh.getStart(); LinkedList<ExceptionRange> exceptionList = new LinkedList<ExceptionRange>(); Map<LocalVariableTag, LVPosition> localVariables = new HashMap<LocalVariableTag, LVPosition>(); int currLine = -1; int lineNumberOffset = (fromFilename == null) ? 0 : getEnclosingClass().getSourceDebugExtensionOffset(fromFilename); while (oldInstructionHandle != null) { if (map.get(oldInstructionHandle) == null) { // must be a range instruction since they're the only things we // didn't copy across handleRangeInstruction(oldInstructionHandle, exceptionList); // just increment ih. oldInstructionHandle = oldInstructionHandle.getNext(); } else { // assert map.get(ih) == jh Instruction oldInstruction = oldInstructionHandle.getInstruction(); Instruction newInstruction = newInstructionHandle.getInstruction(); if (oldInstruction instanceof InstructionBranch) { handleBranchInstruction(map, oldInstruction, newInstruction); } // now deal with line numbers // and store up info for local variables for (InstructionTargeter targeter : oldInstructionHandle.getTargeters()) { if (targeter instanceof LineNumberTag) { int line = ((LineNumberTag) targeter).getLineNumber(); if (line != currLine) { gen.addLineNumber(newInstructionHandle, line + lineNumberOffset); currLine = line; } } else if (targeter instanceof LocalVariableTag) { LocalVariableTag lvt = (LocalVariableTag) targeter; LVPosition p = localVariables.get(lvt); // If we don't know about it, create a new position and // store // If we do know about it - update its end position if (p == null) { LVPosition newp = new LVPosition(); newp.start = newp.end = newInstructionHandle; localVariables.put(lvt, newp); } else { p.end = newInstructionHandle; } } } // now continue oldInstructionHandle = oldInstructionHandle.getNext(); newInstructionHandle = newInstructionHandle.getNext(); } } addExceptionHandlers(gen, map, exceptionList); if (localVariables.size() == 0) { // Might be a case of 173978 where around advice on an execution join point // has caused everything to be extracted from the method and thus we // are left with no local variables, not even the ones for 'this' and // parameters passed to the method createNewLocalVariables(gen); } else { addLocalVariables(gen, localVariables); } // JAVAC adds line number tables (with just one entry) to generated // accessor methods - this // keeps some tools that rely on finding at least some form of // linenumbertable happy. // Let's check if we have one - if we don't then let's add one. // TODO Could be made conditional on whether line debug info is being // produced if (gen.getLineNumbers().length == 0) { gen.addLineNumber(gen.getInstructionList().getStart(), 1); } } private void createNewLocalVariables(MethodGen gen) { gen.removeLocalVariables(); // ignore <clinit> or <init> for now if (!getName().startsWith("<")) { int slot = 0; InstructionHandle start = gen.getInstructionList().getStart(); InstructionHandle end = gen.getInstructionList().getEnd(); // Add a 'this' if non-static if (!isStatic()) { String cname = this.enclosingClass.getClassName(); if (cname == null) { return; // give up for now } Type enclosingType = BcelWorld.makeBcelType(UnresolvedType.forName(cname)); gen.addLocalVariable("this", enclosingType, slot++, start, end); } // Add entries for the method arguments String[] paramNames = (memberView == null ? null : memberView.getParameterNames()); if (paramNames != null) { for (int i = 0; i < argumentTypes.length; i++) { String pname = paramNames[i]; if (pname == null) { pname = "arg" + i; } gen.addLocalVariable(pname, argumentTypes[i], slot, start, end); slot += argumentTypes[i].getSize(); } } } } /* * Optimized packing that does a 'local packing' of the code rather than building a brand new method and packing into it. Only * usable when the packing is going to be done just once. */ public void optimizedPackBody(MethodGen gen) { InstructionList theBody = getBody(); InstructionHandle iHandle = theBody.getStart(); int currLine = -1; int lineNumberOffset = (fromFilename == null) ? 0 : getEnclosingClass().getSourceDebugExtensionOffset(fromFilename); Map<LocalVariableTag, LVPosition> localVariables = new HashMap<LocalVariableTag, LVPosition>(); LinkedList<ExceptionRange> exceptionList = new LinkedList<ExceptionRange>(); Set<InstructionHandle> forDeletion = new HashSet<InstructionHandle>(); Set<BranchHandle> branchInstructions = new HashSet<BranchHandle>(); // OPTIMIZE sort out in here: getRange()/insertHandler() and type of // exceptionList while (iHandle != null) { Instruction inst = iHandle.getInstruction(); // InstructionHandle nextInst = iHandle.getNext(); // OPTIMIZE remove this instructionhandle as it now points to // nowhere? if (inst == Range.RANGEINSTRUCTION) { Range r = Range.getRange(iHandle); if (r instanceof ExceptionRange) { ExceptionRange er = (ExceptionRange) r; if (er.getStart() == iHandle) { if (!er.isEmpty()) { // order is important, insert handlers in order of start insertHandler(er, exceptionList); } } } forDeletion.add(iHandle); } else { if (inst instanceof InstructionBranch) { branchInstructions.add((BranchHandle) iHandle); } for (InstructionTargeter targeter : iHandle.getTargetersCopy()) { if (targeter instanceof LineNumberTag) { int line = ((LineNumberTag) targeter).getLineNumber(); if (line != currLine) { gen.addLineNumber(iHandle, line + lineNumberOffset); currLine = line; } } else if (targeter instanceof LocalVariableTag) { LocalVariableTag lvt = (LocalVariableTag) targeter; LVPosition p = localVariables.get(lvt); // If we don't know about it, create a new position // and store // If we do know about it - update its end position if (p == null) { LVPosition newp = new LVPosition(); newp.start = newp.end = iHandle; localVariables.put(lvt, newp); } else { p.end = iHandle; } } } } iHandle = iHandle.getNext(); } for (BranchHandle branchHandle : branchInstructions) { handleBranchInstruction(branchHandle, forDeletion); } // now add exception handlers for (ExceptionRange r : exceptionList) { if (r.isEmpty()) { continue; } gen.addExceptionHandler(jumpForward(r.getRealStart(), forDeletion), jumpForward(r.getRealEnd(), forDeletion), jumpForward(r.getHandler(), forDeletion), (r.getCatchType() == null) ? null : (ObjectType) BcelWorld.makeBcelType(r.getCatchType())); } for (InstructionHandle handle : forDeletion) { try { theBody.delete(handle); } catch (TargetLostException e) { e.printStackTrace(); } } gen.setInstructionList(theBody); if (localVariables.size() == 0) { // Might be a case of 173978 where around advice on an execution join point // has caused everything to be extracted from the method and thus we // are left with no local variables, not even the ones for 'this' and // parameters passed to the method createNewLocalVariables(gen); } else { addLocalVariables(gen, localVariables); } // JAVAC adds line number tables (with just one entry) to generated // accessor methods - this // keeps some tools that rely on finding at least some form of // linenumbertable happy. // Let's check if we have one - if we don't then let's add one. // TODO Could be made conditional on whether line debug info is being // produced if (gen.getLineNumbers().length == 0) { gen.addLineNumber(gen.getInstructionList().getStart(), 1); } wasPackedOptimally = true; } private void addLocalVariables(MethodGen gen, Map<LocalVariableTag, LVPosition> localVariables) { // now add local variables gen.removeLocalVariables(); // this next iteration _might_ be overkill, but we had problems with // bcel before with duplicate local variables. Now that we're patching // bcel we should be able to do without it if we're paranoid enough // through the rest of the compiler. InstructionHandle methodStart = gen.getInstructionList().getStart(); InstructionHandle methodEnd = gen.getInstructionList().getEnd(); // Determine how many 'slots' are used by parameters to the method. // Then below we can determine if a local variable is a parameter variable, if it is // we force its range to from the method start (as it may have been shuffled down // due to insertion of advice like cflow entry) int paramSlots = gen.isStatic() ? 0 : 1; Type[] argTypes = gen.getArgumentTypes(); if (argTypes != null) { for (int i = 0; i < argTypes.length; i++) { if (argTypes[i].getSize() == 2) { paramSlots += 2; } else { paramSlots += 1; } } } Map<InstructionHandle, Set<Integer>> duplicatedLocalMap = new HashMap<InstructionHandle, Set<Integer>>(); for (LocalVariableTag tag : localVariables.keySet()) { // have we already added one with the same slot number and start // location? // if so, just continue. LVPosition lvpos = localVariables.get(tag); InstructionHandle start = (tag.getSlot() < paramSlots ? methodStart : lvpos.start); InstructionHandle end = (tag.getSlot() < paramSlots ? methodEnd : lvpos.end); Set<Integer> slots = duplicatedLocalMap.get(start); if (slots == null) { slots = new HashSet<Integer>(); duplicatedLocalMap.put(start, slots); } else if (slots.contains(new Integer(tag.getSlot()))) { // we already have a var starting at this tag with this slot continue; } slots.add(Integer.valueOf(tag.getSlot())); Type t = tag.getRealType(); if (t == null) { t = BcelWorld.makeBcelType(UnresolvedType.forSignature(tag.getType())); } gen.addLocalVariable(tag.getName(), t, tag.getSlot(), start, end); } } private void addExceptionHandlers(MethodGen gen, Map<InstructionHandle, InstructionHandle> map, LinkedList<ExceptionRange> exnList) { // now add exception handlers for (ExceptionRange r : exnList) { if (r.isEmpty()) { continue; } InstructionHandle rMappedStart = remap(r.getRealStart(), map); InstructionHandle rMappedEnd = remap(r.getRealEnd(), map); InstructionHandle rMappedHandler = remap(r.getHandler(), map); gen.addExceptionHandler(rMappedStart, rMappedEnd, rMappedHandler, (r.getCatchType() == null) ? null : (ObjectType) BcelWorld.makeBcelType(r.getCatchType())); } } private void handleBranchInstruction(Map<InstructionHandle, InstructionHandle> map, Instruction oldInstruction, Instruction newInstruction) { InstructionBranch oldBranchInstruction = (InstructionBranch) oldInstruction; InstructionBranch newBranchInstruction = (InstructionBranch) newInstruction; InstructionHandle oldTarget = oldBranchInstruction.getTarget(); // old // target // New target is in hash map newBranchInstruction.setTarget(remap(oldTarget, map)); if (oldBranchInstruction instanceof InstructionSelect) { // Either LOOKUPSWITCH or TABLESWITCH InstructionHandle[] oldTargets = ((InstructionSelect) oldBranchInstruction).getTargets(); InstructionHandle[] newTargets = ((InstructionSelect) newBranchInstruction).getTargets(); for (int k = oldTargets.length - 1; k >= 0; k--) { // Update all targets newTargets[k] = remap(oldTargets[k], map); newTargets[k].addTargeter(newBranchInstruction); } } } private InstructionHandle jumpForward(InstructionHandle t, Set<InstructionHandle> handlesForDeletion) { InstructionHandle target = t; if (handlesForDeletion.contains(target)) { do { target = target.getNext(); } while (handlesForDeletion.contains(target)); } return target; } /** * Process a branch instruction with respect to instructions that are about to be deleted. If the target for the branch is a * candidate for deletion, move it to the next valid instruction after the deleted target. */ private void handleBranchInstruction(BranchHandle branchHandle, Set<InstructionHandle> handlesForDeletion) { InstructionBranch branchInstruction = (InstructionBranch) branchHandle.getInstruction(); InstructionHandle target = branchInstruction.getTarget(); // old target if (handlesForDeletion.contains(target)) { do { target = target.getNext(); } while (handlesForDeletion.contains(target)); branchInstruction.setTarget(target); } if (branchInstruction instanceof InstructionSelect) { // Either LOOKUPSWITCH or TABLESWITCH InstructionSelect iSelect = (InstructionSelect) branchInstruction; InstructionHandle[] targets = iSelect.getTargets(); for (int k = targets.length - 1; k >= 0; k--) { InstructionHandle oneTarget = targets[k]; if (handlesForDeletion.contains(oneTarget)) { do { oneTarget = oneTarget.getNext(); } while (handlesForDeletion.contains(oneTarget)); iSelect.setTarget(k, oneTarget); oneTarget.addTargeter(branchInstruction); } } } } private void handleRangeInstruction(InstructionHandle ih, LinkedList<ExceptionRange> exnList) { // we're a range instruction Range r = Range.getRange(ih); if (r instanceof ExceptionRange) { ExceptionRange er = (ExceptionRange) r; if (er.getStart() == ih) { // System.err.println("er " + er); if (!er.isEmpty()) { // order is important, insert handlers in order of start insertHandler(er, exnList); } } } else { // we must be a shadow range or something equally useless, // so forget about doing anything } } /* * Make copies of all instructions, append them to the new list and associate old instruction references with the new ones, * i.e., a 1:1 mapping. */ private Map<InstructionHandle, InstructionHandle> copyAllInstructionsExceptRangeInstructionsInto(InstructionList intoList) { Map<InstructionHandle, InstructionHandle> map = new HashMap<InstructionHandle, InstructionHandle>(); for (InstructionHandle ih = getBody().getStart(); ih != null; ih = ih.getNext()) { if (Range.isRangeHandle(ih)) { continue; } Instruction inst = ih.getInstruction(); Instruction copy = Utility.copyInstruction(inst); if (copy instanceof InstructionBranch) { map.put(ih, intoList.append((InstructionBranch) copy)); } else { map.put(ih, intoList.append(copy)); } } return map; } /** * This procedure should not currently be used. */ // public void killNops() { // InstructionHandle curr = body.getStart(); // while (true) { // if (curr == null) break; // InstructionHandle next = curr.getNext(); // if (curr.getInstruction() instanceof NOP) { // InstructionTargeter[] targeters = curr.getTargeters(); // if (targeters != null) { // for (int i = 0, len = targeters.length; i < len; i++) { // InstructionTargeter targeter = targeters[i]; // targeter.updateTarget(curr, next); // } // } // try { // body.delete(curr); // } catch (TargetLostException e) { // } // } // curr = next; // } // } // private static InstructionHandle fNext(InstructionHandle ih) { // while (true) { // if (ih.getInstruction()==Range.RANGEINSTRUCTION) ih = ih.getNext(); // else return ih; // } // } private static InstructionHandle remap(InstructionHandle handle, Map<InstructionHandle, InstructionHandle> map) { while (true) { InstructionHandle ret = map.get(handle); if (ret == null) { handle = handle.getNext(); } else { return ret; } } } // Update to all these comments, ASC 11-01-2005 // The right thing to do may be to do more with priorities as // we create new exception handlers, but that is a relatively // complex task. In the meantime, just taking account of the // priority here enables a couple of bugs to be fixed to do // with using return or break in code that contains a finally // block (pr78021,pr79554). // exception ordering. // What we should be doing is dealing with priority inversions way earlier // than we are // and counting on the tree structure. In which case, the below code is in // fact right. // XXX THIS COMMENT BELOW IS CURRENTLY WRONG. // An exception A preceeds an exception B in the exception table iff: // * A and B were in the original method, and A preceeded B in the original // exception table // * If A has a higher priority than B, than it preceeds B. // * If A and B have the same priority, then the one whose START happens // EARLIEST has LEAST priority. // in short, the outermost exception has least priority. // we implement this with a LinkedList. We could possibly implement this // with a java.util.SortedSet, // but I don't trust the only implementation, TreeSet, to do the right // thing. /* private */static void insertHandler(ExceptionRange fresh, LinkedList<ExceptionRange> l) { // Old implementation, simply: l.add(0,fresh); for (ListIterator<ExceptionRange> iter = l.listIterator(); iter.hasNext();) { ExceptionRange r = iter.next(); // int freal = fresh.getRealStart().getPosition(); // int rreal = r.getRealStart().getPosition(); if (fresh.getPriority() >= r.getPriority()) { iter.previous(); iter.add(fresh); return; } } // we have reached the end l.add(fresh); } public boolean isPrivate() { return Modifier.isPrivate(getAccessFlags()); } public boolean isProtected() { return Modifier.isProtected(getAccessFlags()); } public boolean isDefault() { return !(isProtected() || isPrivate() || isPublic()); } public boolean isPublic() { return Modifier.isPublic(getAccessFlags()); } // ---- /** * A good body is a body with the following properties: * * <ul> * <li>For each branch instruction S in body, target T of S is in body. * <li>For each branch instruction S in body, target T of S has S as a targeter. * <li>For each instruction T in body, for each branch instruction S that is a targeter of T, S is in body. * <li>For each non-range-handle instruction T in body, for each instruction S that is a targeter of T, S is either a branch * instruction, an exception range or a tag * <li>For each range-handle instruction T in body, there is exactly one targeter S that is a range. * <li>For each range-handle instruction T in body, the range R targeting T is in body. * <li>For each instruction T in body, for each exception range R targeting T, R is in body. * <li>For each exception range R in body, let T := R.handler. T is in body, and R is one of T's targeters * <li>All ranges are properly nested: For all ranges Q and R, if Q.start preceeds R.start, then R.end preceeds Q.end. * </ul> * * Where the shorthand "R is in body" means "R.start is in body, R.end is in body, and any InstructionHandle stored in a field * of R (such as an exception handle) is in body". */ public void assertGoodBody() { if (true) { return; // only enable for debugging } assertGoodBody(getBody(), toString()); } public static void assertGoodBody(InstructionList il, String from) { if (true) { return; // only to be enabled for debugging } // if (il == null) { // return; // } // Set body = new HashSet(); // Stack<Range> ranges = new Stack<Range>(); // for (InstructionHandle ih = il.getStart(); ih != null; ih = ih.getNext()) { // body.add(ih); // if (ih.getInstruction() instanceof InstructionBranch) { // body.add(ih.getInstruction()); // } // } // // for (InstructionHandle ih = il.getStart(); ih != null; ih = ih.getNext()) { // assertGoodHandle(ih, body, ranges, from); // Iterator<InstructionTargeter> tIter = ih.getTargeters().iterator(); // while (tIter.hasNext()) { // assertGoodTargeter(tIter.next(), ih, body, from); // } // } } // private static void assertGoodHandle(InstructionHandle ih, Set body, Stack<Range> ranges, String from) { // Instruction inst = ih.getInstruction(); // if ((inst instanceof InstructionBranch) ^ (ih instanceof BranchHandle)) { // throw new BCException("bad instruction/handle pair in " + from); // } // if (Range.isRangeHandle(ih)) { // assertGoodRangeHandle(ih, body, ranges, from); // } else if (inst instanceof InstructionBranch) { // assertGoodBranchInstruction((BranchHandle) ih, (InstructionBranch) inst, body, ranges, from); // } // } // private static void assertGoodBranchInstruction(BranchHandle ih, InstructionBranch inst, Set body, Stack<Range> ranges, // String from) { // if (ih.getTarget() != inst.getTarget()) { // throw new BCException("bad branch instruction/handle pair in " + from); // } // InstructionHandle target = ih.getTarget(); // assertInBody(target, body, from); // assertTargetedBy(target, inst, from); // if (inst instanceof InstructionSelect) { // InstructionSelect sel = (InstructionSelect) inst; // InstructionHandle[] itargets = sel.getTargets(); // for (int k = itargets.length - 1; k >= 0; k--) { // assertInBody(itargets[k], body, from); // assertTargetedBy(itargets[k], inst, from); // } // } // } /** ih is an InstructionHandle or a BranchInstruction */ // private static void assertInBody(Object ih, Set body, String from) { // if (!body.contains(ih)) { // throw new BCException("thing not in body in " + from); // } // } // private static void assertGoodRangeHandle(InstructionHandle ih, Set body, Stack ranges, String from) { // Range r = getRangeAndAssertExactlyOne(ih, from); // assertGoodRange(r, body, from); // if (r.getStart() == ih) { // ranges.push(r); // } else if (r.getEnd() == ih) { // if (ranges.peek() != r) { // throw new BCException("bad range inclusion in " + from); // } // ranges.pop(); // } // } // private static void assertGoodRange(Range r, Set body, String from) { // assertInBody(r.getStart(), body, from); // assertRangeHandle(r.getStart(), from); // assertTargetedBy(r.getStart(), r, from); // // assertInBody(r.getEnd(), body, from); // assertRangeHandle(r.getEnd(), from); // assertTargetedBy(r.getEnd(), r, from); // // if (r instanceof ExceptionRange) { // ExceptionRange er = (ExceptionRange) r; // assertInBody(er.getHandler(), body, from); // assertTargetedBy(er.getHandler(), r, from); // } // } // private static void assertRangeHandle(InstructionHandle ih, String from) { // if (!Range.isRangeHandle(ih)) { // throw new BCException("bad range handle " + ih + " in " + from); // } // } private static void assertTargetedBy(InstructionHandle target, InstructionTargeter targeter, String from) { Iterator tIter = target.getTargeters().iterator(); while (tIter.hasNext()) { if (((InstructionTargeter) tIter.next()) == targeter) { return; } } throw new RuntimeException("bad targeting relationship in " + from); } private static void assertTargets(InstructionTargeter targeter, InstructionHandle target, String from) { if (targeter instanceof Range) { Range r = (Range) targeter; if (r.getStart() == target || r.getEnd() == target) { return; } if (r instanceof ExceptionRange) { if (((ExceptionRange) r).getHandler() == target) { return; } } } else if (targeter instanceof InstructionBranch) { InstructionBranch bi = (InstructionBranch) targeter; if (bi.getTarget() == target) { return; } if (targeter instanceof InstructionSelect) { InstructionSelect sel = (InstructionSelect) targeter; InstructionHandle[] itargets = sel.getTargets(); for (int k = itargets.length - 1; k >= 0; k--) { if (itargets[k] == target) { return; } } } } else if (targeter instanceof Tag) { return; } throw new BCException(targeter + " doesn't target " + target + " in " + from); } private static Range getRangeAndAssertExactlyOne(InstructionHandle ih, String from) { Range ret = null; Iterator<InstructionTargeter> tIter = ih.getTargeters().iterator(); if (!tIter.hasNext()) { throw new BCException("range handle with no range in " + from); } while (tIter.hasNext()) { InstructionTargeter ts = tIter.next(); if (ts instanceof Range) { if (ret != null) { throw new BCException("range handle with multiple ranges in " + from); } ret = (Range) ts; } } if (ret == null) { throw new BCException("range handle with no range in " + from); } return ret; } // private static void assertGoodTargeter(InstructionTargeter t, InstructionHandle ih, Set body, String from) { // assertTargets(t, ih, from); // if (t instanceof Range) { // assertGoodRange((Range) t, body, from); // } else if (t instanceof InstructionBranch) { // assertInBody(t, body, from); // } // } // ---- boolean isAdviceMethod() { if (memberView == null) { return false; } return memberView.getAssociatedShadowMunger() != null; } boolean isAjSynthetic() { if (memberView == null) { return true; } return memberView.isAjSynthetic(); } boolean isSynthetic() { if (memberView == null) { return false; } return memberView.isSynthetic(); } public ISourceLocation getSourceLocation() { if (memberView != null) { return memberView.getSourceLocation(); } return null; } public AjAttribute.EffectiveSignatureAttribute getEffectiveSignature() { // if (memberView == null) return null; if (effectiveSignature != null) { return effectiveSignature; } return memberView.getEffectiveSignature(); } public void setEffectiveSignature(ResolvedMember member, Shadow.Kind kind, boolean shouldWeave) { this.effectiveSignature = new AjAttribute.EffectiveSignatureAttribute(member, kind, shouldWeave); } public String getSignature() { if (memberView != null) { return memberView.getSignature(); } return MemberImpl.typesToSignature(BcelWorld.fromBcel(getReturnType()), BcelWorld.fromBcel(getArgumentTypes()), false); } public String getParameterSignature() { if (memberView != null) { return memberView.getParameterSignature(); } return MemberImpl.typesToSignature(BcelWorld.fromBcel(getArgumentTypes())); } public BcelMethod getMemberView() { return memberView; } public void forcePublic() { markAsChanged(); modifiers = Utility.makePublic(modifiers); } public boolean getCanInline() { return canInline; } public void setCanInline(boolean canInline) { this.canInline = canInline; } public void addAttribute(Attribute attribute) { attributes.add(attribute); } public String toTraceString() { return toShortString(); } public ConstantPool getConstantPool() { return enclosingClass.getConstantPool(); } public static boolean isConstructor(LazyMethodGen aMethod) { return aMethod.getName().equals("<init>"); } }
389,750
Bug 389750 Inconsistent classfile encountered: The undefined type parameter xxx is referenced from within yyy
With the declare parents pattern below, I'm getting this **runtime** error (compiler completes ok): Inconsistent classfile encountered: The undefined type parameter ID is referenced from within PersistableAspect If I remove the generics part of the interface declaration, the error goes away. Here's the pattern: interface: ========== package example.trait; // imports... public interface Persistable<ID extends Serializable> { Object getOid(); ID getId(); String getIdString(); long getVersion(); } annotation: =========== package example.anno; // imports... @Target(TYPE) @Retention(RUNTIME) @Trait public @interface Persistable { String in() default "MONGO"; StoreType inAsEnum() default StoreType.MONGO; String id() default "STRING"; IdType idAsEnum() default IdType.STRING; } aspect: ======= package example.aspect; // imports... public privileged aspect PersistableAspect { public interface I<ID extends Serializable> extends example.trait.Persistable<ID> { } public interface L extends I<Long> { } public interface S extends I<String> { } declare parents : (@Persistable(id="LONG") *) implements L; declare parents : (@Persistable(id="STRING") *) implements S; // remaining code is ITDs introducing vars & methods... }
resolved fixed
b9c7a19
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2012-09-19T17:19:17Z"
"2012-09-17T19:26:40Z"
org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/compiler/ast/AstUtil.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Eclipse Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * PARC initial implementation * ******************************************************************/ package org.aspectj.ajdt.internal.compiler.ast; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.List; import org.aspectj.org.eclipse.jdt.core.compiler.CharOperation; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.ASTNode; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.Argument; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.Expression; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.MessageSend; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.MethodDeclaration; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.NameReference; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.QualifiedNameReference; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.QualifiedTypeReference; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.ReturnStatement; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.SingleNameReference; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.Statement; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.TypeDeclaration; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.TypeReference; import org.aspectj.org.eclipse.jdt.internal.compiler.classfmt.ClassFileConstants; import org.aspectj.org.eclipse.jdt.internal.compiler.codegen.CodeStream; import org.aspectj.org.eclipse.jdt.internal.compiler.impl.Constant; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.Binding; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.CompilationUnitScope; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.LocalVariableBinding; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.MethodBinding; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.ReferenceBinding; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.Scope; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.SourceTypeBinding; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.TypeBinding; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.TypeIds; import org.aspectj.weaver.AjAttribute; import org.aspectj.weaver.patterns.WildTypePattern; public class AstUtil { private AstUtil() { } public static void addMethodBinding(SourceTypeBinding sourceType, MethodBinding method) { int len = sourceType.methods.length; MethodBinding[] temp = new MethodBinding[len + 1]; System.arraycopy(sourceType.methods, 0, temp, 0, len); temp[len] = method; sourceType.methods = temp; } public static void addMethodDeclaration(TypeDeclaration typeDec, AbstractMethodDeclaration dec) { AbstractMethodDeclaration[] methods = typeDec.methods; int len = methods.length; AbstractMethodDeclaration[] newMethods = new AbstractMethodDeclaration[len + 1]; System.arraycopy(methods, 0, newMethods, 0, len); newMethods[len] = dec; typeDec.methods = newMethods; } public static Argument makeFinalArgument(char[] name, TypeBinding typeBinding) { long pos = 0; // XXX encode start and end location LocalVariableBinding binding = new LocalVariableBinding(name, typeBinding, Modifier.FINAL, true); Argument ret = new Argument(name, pos, makeTypeReference(typeBinding), Modifier.FINAL); ret.binding = binding; return ret; } public static TypeReference makeTypeReference(TypeBinding binding) { // ??? does this work for primitives QualifiedTypeReference ref = new QualifiedTypeReference(new char[][] { binding.sourceName() }, new long[] { 0 }); // ??? ref.resolvedType = binding; ref.constant = Constant.NotAConstant; return ref; } public static NameReference makeNameReference(TypeBinding binding) { char[][] name = new char[][] { binding.sourceName() }; long[] dummyPositions = new long[name.length]; QualifiedNameReference ref = new QualifiedNameReference(name, dummyPositions, 0, 0); ref.binding = binding; ref.constant = Constant.NotAConstant; return ref; } public static ReturnStatement makeReturnStatement(Expression expr) { return new ReturnStatement(expr, 0, 0); } public static MethodDeclaration makeMethodDeclaration(MethodBinding binding) { MethodDeclaration ret = new MethodDeclaration(null); ret.binding = binding; int nargs = binding.parameters.length; ret.arguments = new Argument[nargs]; for (int i = 0; i < nargs; i++) { ret.arguments[i] = makeFinalArgument(("arg" + i).toCharArray(), binding.parameters[i]); } return ret; } public static void setStatements(MethodDeclaration ret, List statements) { ret.statements = (Statement[]) statements.toArray(new Statement[statements.size()]); } public static SingleNameReference makeLocalVariableReference(LocalVariableBinding binding) { SingleNameReference ret = new SingleNameReference(binding.name, 0); ret.binding = binding; // ret.codegenBinding = binding; ret.constant = Constant.NotAConstant; ret.bits &= ~ASTNode.RestrictiveFlagMASK; // clear bits ret.bits |= Binding.VARIABLE; return ret; } public static SingleNameReference makeResolvedLocalVariableReference(LocalVariableBinding binding) { SingleNameReference ret = new SingleNameReference(binding.name, 0); ret.binding = binding; // ret.codegenBinding = binding; ret.constant = Constant.NotAConstant; ret.bits &= ~ASTNode.RestrictiveFlagMASK; // clear bits ret.bits |= Binding.LOCAL; return ret; } public static int makePublic(int modifiers) { return makePackageVisible(modifiers) | ClassFileConstants.AccPublic; } public static int makePackageVisible(int modifiers) { modifiers &= ~(ClassFileConstants.AccPublic | ClassFileConstants.AccPrivate | ClassFileConstants.AccProtected); return modifiers; } public static CompilationUnitScope getCompilationUnitScope(Scope scope) { if (scope instanceof CompilationUnitScope) { return (CompilationUnitScope) scope; } return getCompilationUnitScope(scope.parent); } public static void generateParameterLoads(TypeBinding[] parameters, CodeStream codeStream) { int paramIndex = 0; int varIndex = 0; while (paramIndex < parameters.length) { TypeBinding param = parameters[paramIndex++]; codeStream.load(param, varIndex); varIndex += slotsNeeded(param); } } public static void generateParameterLoads(TypeBinding[] parameters, CodeStream codeStream, int offset) { int paramIndex = 0; int varIndex = offset; while (paramIndex < parameters.length) { TypeBinding param = parameters[paramIndex++]; codeStream.load(param, varIndex); varIndex += slotsNeeded(param); } } public static void generateReturn(TypeBinding returnType, CodeStream codeStream) { if (returnType.id == TypeIds.T_void) { codeStream.return_(); } else if (returnType.isBaseType()) { switch (returnType.id) { case TypeIds.T_boolean: case TypeIds.T_int: case TypeIds.T_byte: case TypeIds.T_short: case TypeIds.T_char: codeStream.ireturn(); break; case TypeIds.T_float: codeStream.freturn(); break; case TypeIds.T_long: codeStream.lreturn(); break; case TypeIds.T_double: codeStream.dreturn(); break; default: throw new RuntimeException("huh"); } } else { codeStream.areturn(); } } // XXX this could be inconsistent for wierd case, i.e. a class named "java_lang_String" public static char[] makeMangledName(ReferenceBinding type) { return CharOperation.concatWith(type.compoundName, '_'); } public static final char[] PREFIX = "ajc".toCharArray(); // XXX not efficient public static char[] makeAjcMangledName(char[] kind, ReferenceBinding type, char[] name) { return CharOperation.concat(CharOperation.concat(PREFIX, new char[] { '$' }, kind), '$', makeMangledName(type), '$', name); } public static char[] makeAjcMangledName(char[] kind, char[] p, char[] name) { return CharOperation.concat(CharOperation.concat(PREFIX, new char[] { '$' }, kind), '$', p, '$', name); } public static List getAjSyntheticAttribute() { ArrayList ret = new ArrayList(1); ret.add(new EclipseAttributeAdapter(new AjAttribute.AjSynthetic())); return ret; } public static long makeLongPos(int start, int end) { return (long) end | ((long) start << 32); } public static char[][] getCompoundName(String string) { return WildTypePattern.splitNames(string, true); } public static TypeBinding[] insert(TypeBinding first, TypeBinding[] rest) { if (rest == null) { return new TypeBinding[] { first }; } int len = rest.length; TypeBinding[] ret = new TypeBinding[len + 1]; ret[0] = first; System.arraycopy(rest, 0, ret, 1, len); return ret; } public static Argument[] insert(Argument first, Argument[] rest) { if (rest == null) { return new Argument[] { first }; } int len = rest.length; Argument[] ret = new Argument[len + 1]; ret[0] = first; System.arraycopy(rest, 0, ret, 1, len); return ret; } public static Expression[] insert(Expression first, Expression[] rest) { if (rest == null) { return new Expression[] { first }; } int len = rest.length; Expression[] ret = new Expression[len + 1]; ret[0] = first; System.arraycopy(rest, 0, ret, 1, len); return ret; } public static Argument[] copyArguments(Argument[] inArgs) { // Lets do a proper copy if (inArgs == null) return new Argument[] {}; Argument[] outArgs = new Argument[inArgs.length]; for (int i = 0; i < inArgs.length; i++) { Argument argument = inArgs[i]; outArgs[i] = new Argument(argument.name, 0, argument.type, argument.modifiers); } return outArgs; // if (inArgs == null) return new Argument[] {}; // int len = inArgs.length; // Argument[] outArgs = new Argument[len]; // //??? we're not sure whether or not copying these is okay // System.arraycopy(inArgs, 0, outArgs, 0, len); // return outArgs; } public static Statement[] remove(int i, Statement[] statements) { int len = statements.length; Statement[] ret = new Statement[len - 1]; System.arraycopy(statements, 0, ret, 0, i); System.arraycopy(statements, i + 1, ret, i, len - i - 1); return ret; } public static int slotsNeeded(TypeBinding type) { if (type == TypeBinding.DOUBLE || type == TypeBinding.LONG) return 2; else return 1; } public static void replaceMethodBinding(MessageSend send, MethodBinding newBinding) { send.binding =/* send.codegenBinding =*/ newBinding; send.setActualReceiverType(newBinding.declaringClass); } }
389,750
Bug 389750 Inconsistent classfile encountered: The undefined type parameter xxx is referenced from within yyy
With the declare parents pattern below, I'm getting this **runtime** error (compiler completes ok): Inconsistent classfile encountered: The undefined type parameter ID is referenced from within PersistableAspect If I remove the generics part of the interface declaration, the error goes away. Here's the pattern: interface: ========== package example.trait; // imports... public interface Persistable<ID extends Serializable> { Object getOid(); ID getId(); String getIdString(); long getVersion(); } annotation: =========== package example.anno; // imports... @Target(TYPE) @Retention(RUNTIME) @Trait public @interface Persistable { String in() default "MONGO"; StoreType inAsEnum() default StoreType.MONGO; String id() default "STRING"; IdType idAsEnum() default IdType.STRING; } aspect: ======= package example.aspect; // imports... public privileged aspect PersistableAspect { public interface I<ID extends Serializable> extends example.trait.Persistable<ID> { } public interface L extends I<Long> { } public interface S extends I<String> { } declare parents : (@Persistable(id="LONG") *) implements L; declare parents : (@Persistable(id="STRING") *) implements S; // remaining code is ITDs introducing vars & methods... }
resolved fixed
b9c7a19
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2012-09-19T17:19:17Z"
"2012-09-17T19:26:40Z"
org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/compiler/ast/InterTypeMethodDeclaration.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Eclipse Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * PARC initial implementation * ******************************************************************/ package org.aspectj.ajdt.internal.compiler.ast; import java.lang.reflect.Modifier; import org.aspectj.ajdt.internal.compiler.lookup.EclipseFactory; import org.aspectj.ajdt.internal.compiler.lookup.EclipseTypeMunger; import org.aspectj.ajdt.internal.compiler.problem.AjProblemReporter; 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.Argument; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.LocalDeclaration; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.TypeReference; import org.aspectj.org.eclipse.jdt.internal.compiler.classfmt.ClassFileConstants; import org.aspectj.org.eclipse.jdt.internal.compiler.codegen.CodeStream; import org.aspectj.org.eclipse.jdt.internal.compiler.codegen.Opcodes; import org.aspectj.org.eclipse.jdt.internal.compiler.flow.FlowInfo; import org.aspectj.org.eclipse.jdt.internal.compiler.flow.InitializationFlowContext; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.ClassScope; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.ExtraCompilerModifiers; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.LocalVariableBinding; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.MethodBinding; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.ReferenceBinding; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.SourceTypeBinding; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.TagBits; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.TypeBinding; import org.aspectj.org.eclipse.jdt.internal.compiler.parser.Parser; import org.aspectj.org.eclipse.jdt.internal.compiler.problem.AbortCompilationUnit; import org.aspectj.weaver.AjAttribute; import org.aspectj.weaver.AjcMemberMaker; import org.aspectj.weaver.Constants; import org.aspectj.weaver.NameMangler; 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.UnresolvedType; /** * An inter-type method declaration. * * @author Jim Hugunin */ public class InterTypeMethodDeclaration extends InterTypeDeclaration { public InterTypeMethodDeclaration(CompilationResult result, TypeReference onType) { super(result, onType); } public void parseStatements(Parser parser, CompilationUnitDeclaration unit) { if (ignoreFurtherInvestigation) return; if (!Modifier.isAbstract(declaredModifiers)) { parser.parse(this, unit); } } protected char[] getPrefix() { return (NameMangler.ITD_PREFIX + "interMethod$").toCharArray(); } public boolean isFinal() { return (declaredModifiers & ClassFileConstants.AccFinal) != 0; } public void analyseCode(ClassScope currentScope, InitializationFlowContext flowContext, FlowInfo flowInfo) { if (Modifier.isAbstract(declaredModifiers)) return; super.analyseCode(currentScope, flowContext, flowInfo); } public void resolve(ClassScope upperScope) { if (munger == null) ignoreFurtherInvestigation = true; if (binding == null) ignoreFurtherInvestigation = true; if (ignoreFurtherInvestigation) return; if (!Modifier.isStatic(declaredModifiers)) { this.arguments = AstUtil.insert(AstUtil.makeFinalArgument("ajc$this_".toCharArray(), onTypeBinding), this.arguments); binding.parameters = AstUtil.insert(onTypeBinding, binding.parameters); } super.resolve(upperScope); } public void resolveStatements() { checkAndSetModifiersForMethod(); if ((modifiers & ExtraCompilerModifiers.AccSemicolonBody) != 0) { if ((declaredModifiers & ClassFileConstants.AccAbstract) == 0) scope.problemReporter().methodNeedBody(this); } else { // the method HAS a body --> abstract native modifiers are forbiden if (((declaredModifiers & ClassFileConstants.AccAbstract) != 0)) scope.problemReporter().methodNeedingNoBody(this); } // XXX AMC we need to do this, but I'm not 100% comfortable as I don't // know why the return type is wrong in this case. Also, we don't seem to need // to do it for args... if (munger.getSignature().getReturnType().isRawType()) { if (!binding.returnType.isRawType()) { EclipseFactory world = EclipseFactory.fromScopeLookupEnvironment(scope); binding.returnType = world.makeTypeBinding(munger.getSignature().getReturnType()); } } // check @Override annotation - based on MethodDeclaration.resolveStatements() @Override processing checkOverride: { if (this.binding == null) break checkOverride; if (this.scope.compilerOptions().sourceLevel < ClassFileConstants.JDK1_5) break checkOverride; boolean hasOverrideAnnotation = (this.binding.tagBits & TagBits.AnnotationOverride) != 0; // Need to verify if (hasOverrideAnnotation) { // Work out the real method binding that we can use for comparison EclipseFactory world = EclipseFactory.fromScopeLookupEnvironment(scope); MethodBinding realthing = world.makeMethodBinding(munger.getSignature(), munger.getTypeVariableAliases()); boolean reportError = true; // Go up the hierarchy, looking for something we override ReferenceBinding supertype = onTypeBinding.superclass(); while (supertype != null && reportError) { MethodBinding[] possibles = supertype.getMethods(declaredSelector); for (int i = 0; i < possibles.length; i++) { MethodBinding mb = possibles[i]; boolean couldBeMatch = true; if (mb.parameters.length != realthing.parameters.length) couldBeMatch = false; else { for (int j = 0; j < mb.parameters.length && couldBeMatch; j++) { if (!mb.parameters[j].equals(realthing.parameters[j])) couldBeMatch = false; } } // return types compatible? (allow for covariance) if (couldBeMatch && !returnType.resolvedType.isCompatibleWith(mb.returnType)) couldBeMatch = false; if (couldBeMatch) reportError = false; } supertype = supertype.superclass(); // superclass of object is null } // If we couldn't find something we override, report the error if (reportError) ((AjProblemReporter) this.scope.problemReporter()).itdMethodMustOverride(this, realthing); } } if (!Modifier.isAbstract(declaredModifiers)) super.resolveStatements(); if (Modifier.isStatic(declaredModifiers)) { // Check the target for ITD is not an interface if (onTypeBinding.isInterface()) { scope.problemReporter().signalError(sourceStart, sourceEnd, "methods in interfaces cannot be declared static"); } } } public EclipseTypeMunger build(ClassScope classScope) { EclipseFactory factory = EclipseFactory.fromScopeLookupEnvironment(classScope); resolveOnType(classScope); if (ignoreFurtherInvestigation) return null; binding = classScope.referenceContext.binding.resolveTypesFor(binding); if (binding == null) { // if binding is null, we failed to find a type used in the method params, this error // has already been reported. this.ignoreFurtherInvestigation = true; // return null; throw new AbortCompilationUnit(compilationResult, null); } if (isTargetAnnotation(classScope, "method")) return null; // Error message output in isTargetAnnotation if (isTargetEnum(classScope, "method")) return null; // Error message output in isTargetEnum if (interTypeScope == null) return null; // We encountered a problem building the scope, don't continue - error already reported // This signature represents what we want consumers of the targetted type to 'see' // must use the factory method to build it since there may be typevariables from the binding // referred to in the parameters/returntype ResolvedMemberImpl sig = factory.makeResolvedMemberForITD(binding, onTypeBinding, interTypeScope.getRecoveryAliases()); sig.resetName(new String(declaredSelector)); int resetModifiers = declaredModifiers; if (binding.isVarargs()) resetModifiers = resetModifiers | Constants.ACC_VARARGS; sig.resetModifiers(resetModifiers); NewMethodTypeMunger myMunger = new NewMethodTypeMunger(sig, null, typeVariableAliases); setMunger(myMunger); ResolvedType aspectType = factory.fromEclipse(classScope.referenceContext.binding); ResolvedMember me = myMunger.getInterMethodBody(aspectType); this.selector = binding.selector = me.getName().toCharArray(); return new EclipseTypeMunger(factory, myMunger, aspectType, this); } private AjAttribute makeAttribute() { return new AjAttribute.TypeMunger(munger); } public void generateCode(ClassScope classScope, ClassFile classFile) { if (ignoreFurtherInvestigation) { // System.err.println("no code for " + this); return; } classFile.extraAttributes.add(new EclipseAttributeAdapter(makeAttribute())); if (!Modifier.isAbstract(declaredModifiers)) { super.generateCode(classScope, classFile); // this makes the interMethodBody } // annotations on the ITD declaration get put on this method generateDispatchMethod(classScope, classFile); } public void generateDispatchMethod(ClassScope classScope, ClassFile classFile) { EclipseFactory world = EclipseFactory.fromScopeLookupEnvironment(classScope); UnresolvedType aspectType = world.fromBinding(classScope.referenceContext.binding); ResolvedMember signature = munger.getSignature(); ResolvedMember dispatchMember = AjcMemberMaker.interMethodDispatcher(signature, aspectType); MethodBinding dispatchBinding = world.makeMethodBinding(dispatchMember, munger.getTypeVariableAliases(), munger .getSignature().getDeclaringType()); MethodBinding introducedMethod = world.makeMethodBinding(AjcMemberMaker.interMethod(signature, aspectType, onTypeBinding .isInterface()), munger.getTypeVariableAliases()); classFile.generateMethodInfoHeader(dispatchBinding); int methodAttributeOffset = classFile.contentsOffset; // Watch out! We are passing in 'binding' here (instead of dispatchBinding) so that // the dispatch binding attributes will include the annotations from the 'binding'. // There is a chance that something else on the binding (e.g. throws clause) might // damage the attributes generated for the dispatch binding. int attributeNumber = classFile.generateMethodInfoAttributes(binding, makeEffectiveSignatureAttribute(signature, Shadow.MethodCall, false)); int codeAttributeOffset = classFile.contentsOffset; classFile.generateCodeAttributeHeader(); CodeStream codeStream = classFile.codeStream; codeStream.reset(this, classFile); codeStream.initializeMaxLocals(dispatchBinding); Argument[] itdArgs = this.arguments; if (itdArgs != null) { for (int a = 0; a < itdArgs.length; a++) { LocalVariableBinding lvb = itdArgs[a].binding; LocalVariableBinding lvbCopy = new LocalVariableBinding(lvb.name, lvb.type, lvb.modifiers, true); // e37: have to create a declaration so that the check in ClassFile (line 2538) won't skip it lvbCopy.declaration = new LocalDeclaration(itdArgs[a].name,0,0); codeStream.record(lvbCopy); lvbCopy.recordInitializationStartPC(0); lvbCopy.resolvedPosition = lvb.resolvedPosition; } } MethodBinding methodBinding = introducedMethod; TypeBinding[] parameters = methodBinding.parameters; int length = parameters.length; int resolvedPosition; if (methodBinding.isStatic()) resolvedPosition = 0; else { codeStream.aload_0(); resolvedPosition = 1; } for (int i = 0; i < length; i++) { codeStream.load(parameters[i], resolvedPosition); if ((parameters[i] == TypeBinding.DOUBLE) || (parameters[i] == TypeBinding.LONG)) resolvedPosition += 2; else resolvedPosition++; } // TypeBinding type; if (methodBinding.isStatic()) codeStream.invoke(Opcodes.OPC_invokestatic,methodBinding,null); else { if (methodBinding.declaringClass.isInterface()) { codeStream.invoke(Opcodes.OPC_invokeinterface, methodBinding, null); } else { codeStream.invoke(Opcodes.OPC_invokevirtual, methodBinding, null); } } AstUtil.generateReturn(dispatchBinding.returnType, codeStream); // tag the local variables as used throughout the method if (itdArgs != null && codeStream.locals != null) { for (int a = 0; a < itdArgs.length; a++) { if (codeStream.locals[a] != null) { codeStream.locals[a].recordInitializationEndPC(codeStream.position); } } } classFile.completeCodeAttribute(codeAttributeOffset); attributeNumber++; classFile.completeMethodInfo(binding,methodAttributeOffset, attributeNumber); } protected Shadow.Kind getShadowKindForBody() { return Shadow.MethodExecution; } // XXX this code is copied from MethodScope, with a few adjustments for ITDs... private void checkAndSetModifiersForMethod() { // for reported problems, we want the user to see the declared selector char[] realSelector = this.selector; this.selector = declaredSelector; final ReferenceBinding declaringClass = this.binding.declaringClass; if ((declaredModifiers & ExtraCompilerModifiers.AccAlternateModifierProblem) != 0) scope.problemReporter().duplicateModifierForMethod(onTypeBinding, this); // after this point, tests on the 16 bits reserved. int realModifiers = declaredModifiers & ExtraCompilerModifiers.AccJustFlag; // check for abnormal modifiers int unexpectedModifiers = ~(ClassFileConstants.AccPublic | ClassFileConstants.AccPrivate | ClassFileConstants.AccProtected | ClassFileConstants.AccAbstract | ClassFileConstants.AccStatic | ClassFileConstants.AccFinal | ClassFileConstants.AccSynchronized | ClassFileConstants.AccNative | ClassFileConstants.AccStrictfp); if ((realModifiers & unexpectedModifiers) != 0) { scope.problemReporter().illegalModifierForMethod(this); declaredModifiers &= ~ExtraCompilerModifiers.AccJustFlag | ~unexpectedModifiers; } // check for incompatible modifiers in the visibility bits, isolate the visibility bits int accessorBits = realModifiers & (ClassFileConstants.AccPublic | ClassFileConstants.AccProtected | ClassFileConstants.AccPrivate); if ((accessorBits & (accessorBits - 1)) != 0) { scope.problemReporter().illegalVisibilityModifierCombinationForMethod(onTypeBinding, this); // need to keep the less restrictive so disable Protected/Private as necessary if ((accessorBits & ClassFileConstants.AccPublic) != 0) { if ((accessorBits & ClassFileConstants.AccProtected) != 0) declaredModifiers &= ~ClassFileConstants.AccProtected; if ((accessorBits & ClassFileConstants.AccPrivate) != 0) declaredModifiers &= ~ClassFileConstants.AccPrivate; } else if ((accessorBits & ClassFileConstants.AccProtected) != 0 && (accessorBits & ClassFileConstants.AccPrivate) != 0) { declaredModifiers &= ~ClassFileConstants.AccPrivate; } } // check for modifiers incompatible with abstract modifier if ((declaredModifiers & ClassFileConstants.AccAbstract) != 0) { int incompatibleWithAbstract = ClassFileConstants.AccStatic | ClassFileConstants.AccFinal | ClassFileConstants.AccSynchronized | ClassFileConstants.AccNative | ClassFileConstants.AccStrictfp; if ((declaredModifiers & incompatibleWithAbstract) != 0) scope.problemReporter().illegalAbstractModifierCombinationForMethod(onTypeBinding, this); if (!onTypeBinding.isAbstract()) scope.problemReporter().abstractMethodInAbstractClass((SourceTypeBinding) onTypeBinding, this); } /* * DISABLED for backward compatibility with javac (if enabled should also mark private methods as final) // methods from a * final class are final : 8.4.3.3 if (methodBinding.declaringClass.isFinal()) modifiers |= AccFinal; */ // native methods cannot also be tagged as strictfp if ((declaredModifiers & ClassFileConstants.AccNative) != 0 && (declaredModifiers & ClassFileConstants.AccStrictfp) != 0) scope.problemReporter().nativeMethodsCannotBeStrictfp(onTypeBinding, this); // static members are only authorized in a static member or top level type if (((realModifiers & ClassFileConstants.AccStatic) != 0) && declaringClass.isNestedType() && !declaringClass.isStatic()) scope.problemReporter().unexpectedStaticModifierForMethod(onTypeBinding, this); // restore the true selector now that any problems have been reported this.selector = realSelector; } }
389,750
Bug 389750 Inconsistent classfile encountered: The undefined type parameter xxx is referenced from within yyy
With the declare parents pattern below, I'm getting this **runtime** error (compiler completes ok): Inconsistent classfile encountered: The undefined type parameter ID is referenced from within PersistableAspect If I remove the generics part of the interface declaration, the error goes away. Here's the pattern: interface: ========== package example.trait; // imports... public interface Persistable<ID extends Serializable> { Object getOid(); ID getId(); String getIdString(); long getVersion(); } annotation: =========== package example.anno; // imports... @Target(TYPE) @Retention(RUNTIME) @Trait public @interface Persistable { String in() default "MONGO"; StoreType inAsEnum() default StoreType.MONGO; String id() default "STRING"; IdType idAsEnum() default IdType.STRING; } aspect: ======= package example.aspect; // imports... public privileged aspect PersistableAspect { public interface I<ID extends Serializable> extends example.trait.Persistable<ID> { } public interface L extends I<Long> { } public interface S extends I<String> { } declare parents : (@Persistable(id="LONG") *) implements L; declare parents : (@Persistable(id="STRING") *) implements S; // remaining code is ITDs introducing vars & methods... }
resolved fixed
b9c7a19
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2012-09-19T17:19:17Z"
"2012-09-17T19:26:40Z"
tests/bugs172/pr389750/Clazz.java
389,750
Bug 389750 Inconsistent classfile encountered: The undefined type parameter xxx is referenced from within yyy
With the declare parents pattern below, I'm getting this **runtime** error (compiler completes ok): Inconsistent classfile encountered: The undefined type parameter ID is referenced from within PersistableAspect If I remove the generics part of the interface declaration, the error goes away. Here's the pattern: interface: ========== package example.trait; // imports... public interface Persistable<ID extends Serializable> { Object getOid(); ID getId(); String getIdString(); long getVersion(); } annotation: =========== package example.anno; // imports... @Target(TYPE) @Retention(RUNTIME) @Trait public @interface Persistable { String in() default "MONGO"; StoreType inAsEnum() default StoreType.MONGO; String id() default "STRING"; IdType idAsEnum() default IdType.STRING; } aspect: ======= package example.aspect; // imports... public privileged aspect PersistableAspect { public interface I<ID extends Serializable> extends example.trait.Persistable<ID> { } public interface L extends I<Long> { } public interface S extends I<String> { } declare parents : (@Persistable(id="LONG") *) implements L; declare parents : (@Persistable(id="STRING") *) implements S; // remaining code is ITDs introducing vars & methods... }
resolved fixed
b9c7a19
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2012-09-19T17:19:17Z"
"2012-09-17T19:26:40Z"
tests/bugs172/pr389750/Clazz2.java
389,750
Bug 389750 Inconsistent classfile encountered: The undefined type parameter xxx is referenced from within yyy
With the declare parents pattern below, I'm getting this **runtime** error (compiler completes ok): Inconsistent classfile encountered: The undefined type parameter ID is referenced from within PersistableAspect If I remove the generics part of the interface declaration, the error goes away. Here's the pattern: interface: ========== package example.trait; // imports... public interface Persistable<ID extends Serializable> { Object getOid(); ID getId(); String getIdString(); long getVersion(); } annotation: =========== package example.anno; // imports... @Target(TYPE) @Retention(RUNTIME) @Trait public @interface Persistable { String in() default "MONGO"; StoreType inAsEnum() default StoreType.MONGO; String id() default "STRING"; IdType idAsEnum() default IdType.STRING; } aspect: ======= package example.aspect; // imports... public privileged aspect PersistableAspect { public interface I<ID extends Serializable> extends example.trait.Persistable<ID> { } public interface L extends I<Long> { } public interface S extends I<String> { } declare parents : (@Persistable(id="LONG") *) implements L; declare parents : (@Persistable(id="STRING") *) implements S; // remaining code is ITDs introducing vars & methods... }
resolved fixed
b9c7a19
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2012-09-19T17:19:17Z"
"2012-09-17T19:26:40Z"
tests/bugs172/pr389750/Clazz3.java
389,750
Bug 389750 Inconsistent classfile encountered: The undefined type parameter xxx is referenced from within yyy
With the declare parents pattern below, I'm getting this **runtime** error (compiler completes ok): Inconsistent classfile encountered: The undefined type parameter ID is referenced from within PersistableAspect If I remove the generics part of the interface declaration, the error goes away. Here's the pattern: interface: ========== package example.trait; // imports... public interface Persistable<ID extends Serializable> { Object getOid(); ID getId(); String getIdString(); long getVersion(); } annotation: =========== package example.anno; // imports... @Target(TYPE) @Retention(RUNTIME) @Trait public @interface Persistable { String in() default "MONGO"; StoreType inAsEnum() default StoreType.MONGO; String id() default "STRING"; IdType idAsEnum() default IdType.STRING; } aspect: ======= package example.aspect; // imports... public privileged aspect PersistableAspect { public interface I<ID extends Serializable> extends example.trait.Persistable<ID> { } public interface L extends I<Long> { } public interface S extends I<String> { } declare parents : (@Persistable(id="LONG") *) implements L; declare parents : (@Persistable(id="STRING") *) implements S; // remaining code is ITDs introducing vars & methods... }
resolved fixed
b9c7a19
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2012-09-19T17:19:17Z"
"2012-09-17T19:26:40Z"
tests/bugs172/pr389750/Clazz4.java
389,750
Bug 389750 Inconsistent classfile encountered: The undefined type parameter xxx is referenced from within yyy
With the declare parents pattern below, I'm getting this **runtime** error (compiler completes ok): Inconsistent classfile encountered: The undefined type parameter ID is referenced from within PersistableAspect If I remove the generics part of the interface declaration, the error goes away. Here's the pattern: interface: ========== package example.trait; // imports... public interface Persistable<ID extends Serializable> { Object getOid(); ID getId(); String getIdString(); long getVersion(); } annotation: =========== package example.anno; // imports... @Target(TYPE) @Retention(RUNTIME) @Trait public @interface Persistable { String in() default "MONGO"; StoreType inAsEnum() default StoreType.MONGO; String id() default "STRING"; IdType idAsEnum() default IdType.STRING; } aspect: ======= package example.aspect; // imports... public privileged aspect PersistableAspect { public interface I<ID extends Serializable> extends example.trait.Persistable<ID> { } public interface L extends I<Long> { } public interface S extends I<String> { } declare parents : (@Persistable(id="LONG") *) implements L; declare parents : (@Persistable(id="STRING") *) implements S; // remaining code is ITDs introducing vars & methods... }
resolved fixed
b9c7a19
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2012-09-19T17:19:17Z"
"2012-09-17T19:26:40Z"
tests/src/org/aspectj/systemtest/AllTests17.java
/* * Created on 19-01-2005 */ package org.aspectj.systemtest; import junit.framework.Test; import junit.framework.TestSuite; import org.aspectj.systemtest.ajc170.AllTestsAspectJ170; import org.aspectj.systemtest.ajc171.AllTestsAspectJ171; public class AllTests17 { public static Test suite() { TestSuite suite = new TestSuite("AspectJ System Test Suite - 1.7"); // $JUnit-BEGIN$ suite.addTest(AllTestsAspectJ171.suite()); suite.addTest(AllTestsAspectJ170.suite()); suite.addTest(AllTests16.suite()); suite.addTest(AllTests15.suite()); // $JUnit-END$ return suite; } }
389,750
Bug 389750 Inconsistent classfile encountered: The undefined type parameter xxx is referenced from within yyy
With the declare parents pattern below, I'm getting this **runtime** error (compiler completes ok): Inconsistent classfile encountered: The undefined type parameter ID is referenced from within PersistableAspect If I remove the generics part of the interface declaration, the error goes away. Here's the pattern: interface: ========== package example.trait; // imports... public interface Persistable<ID extends Serializable> { Object getOid(); ID getId(); String getIdString(); long getVersion(); } annotation: =========== package example.anno; // imports... @Target(TYPE) @Retention(RUNTIME) @Trait public @interface Persistable { String in() default "MONGO"; StoreType inAsEnum() default StoreType.MONGO; String id() default "STRING"; IdType idAsEnum() default IdType.STRING; } aspect: ======= package example.aspect; // imports... public privileged aspect PersistableAspect { public interface I<ID extends Serializable> extends example.trait.Persistable<ID> { } public interface L extends I<Long> { } public interface S extends I<String> { } declare parents : (@Persistable(id="LONG") *) implements L; declare parents : (@Persistable(id="STRING") *) implements S; // remaining code is ITDs introducing vars & methods... }
resolved fixed
b9c7a19
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2012-09-19T17:19:17Z"
"2012-09-17T19:26:40Z"
tests/src/org/aspectj/systemtest/ajc172/Ajc172Tests.java
389,750
Bug 389750 Inconsistent classfile encountered: The undefined type parameter xxx is referenced from within yyy
With the declare parents pattern below, I'm getting this **runtime** error (compiler completes ok): Inconsistent classfile encountered: The undefined type parameter ID is referenced from within PersistableAspect If I remove the generics part of the interface declaration, the error goes away. Here's the pattern: interface: ========== package example.trait; // imports... public interface Persistable<ID extends Serializable> { Object getOid(); ID getId(); String getIdString(); long getVersion(); } annotation: =========== package example.anno; // imports... @Target(TYPE) @Retention(RUNTIME) @Trait public @interface Persistable { String in() default "MONGO"; StoreType inAsEnum() default StoreType.MONGO; String id() default "STRING"; IdType idAsEnum() default IdType.STRING; } aspect: ======= package example.aspect; // imports... public privileged aspect PersistableAspect { public interface I<ID extends Serializable> extends example.trait.Persistable<ID> { } public interface L extends I<Long> { } public interface S extends I<String> { } declare parents : (@Persistable(id="LONG") *) implements L; declare parents : (@Persistable(id="STRING") *) implements S; // remaining code is ITDs introducing vars & methods... }
resolved fixed
b9c7a19
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2012-09-19T17:19:17Z"
"2012-09-17T19:26:40Z"
tests/src/org/aspectj/systemtest/ajc172/AllTestsAspectJ172.java
389,752
Bug 389752 declare parents & @type not matching on annotation properties of enum types
NOTE: real project private git repo demonstrating bug has been shared with Andy Clement privately. I'm reporting bug as Andy requested with as much info as I feel I can. I have a case where 'declare parents' and 'declare @type' instructions are not being applied because their type patterns, which use annotations whose properties are of enumerated types, are not matching. Below find the relevant artifacts and their shapes. The lines in the aspect PersistableJpaAspect that are not matching as they should are the 'declare parents' and 'declare @type'. If I change the annotation properties to be of type String and change the type patterns to use string literals (see "matches" comments in annotation: StoreType.JPA => "JPA" and IdType.LONG => "LONG"), the matching works properly. enums: ====== public enum StoreType { MONGO, JDO, JPA; } ===== public enum IdType { LONG, STRING; } annotation: =========== public @interface Persistable { StoreType in() default StoreType.MONGO; // doesn't match // matches: String in() default "MONGO"; IdType id() default IdType.STRING; // doesn't match // matches: String id() default "STRING"; } aspect: ======= public abstract privileged aspect PersistableAspect { public interface I extends ....trait.interfaces.persistence.Persistable { long version(); void version(long version); } public interface L extends I { Long idLong(); void idLong(Long id); } public interface S extends I { String idString(); void idString(String id); } declare @type : I+ : @Configurable; // ... } ===== public privileged aspect PersistableJpaAspect extends PersistableAspect { public interface JL extends L { } public interface JS extends S { } declare parents : (@Persistable(id = IdType.LONG, in = StoreType.JPA) *) implements JL; declare parents : (@Persistable(id = IdType.STRING, in = StoreType.JPA) *) implements JS; declare @type : @Persistable(in="JPA") JL+ : @Entity; declare @type : @Persistable(in="JPA") JS+ : @Entity; // ... }
resolved fixed
0d69bd3
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2012-09-19T23:35:53Z"
"2012-09-17T19:26:40Z"
org.aspectj.matcher/src/org/aspectj/weaver/EnumAnnotationValue.java
/* ******************************************************************* * Copyright (c) 2006 Contributors * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Eclipse Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Andy Clement IBM initial implementation * ******************************************************************/ package org.aspectj.weaver; public class EnumAnnotationValue extends AnnotationValue { private String typeSignature; private String value; public EnumAnnotationValue(String typeSignature, String value) { super(AnnotationValue.ENUM_CONSTANT); this.typeSignature = typeSignature; this.value = value; } public String getType() { return typeSignature; } public String stringify() { return value; } public String toString() { return "E(" + typeSignature + " " + value + ")"; } }
389,752
Bug 389752 declare parents & @type not matching on annotation properties of enum types
NOTE: real project private git repo demonstrating bug has been shared with Andy Clement privately. I'm reporting bug as Andy requested with as much info as I feel I can. I have a case where 'declare parents' and 'declare @type' instructions are not being applied because their type patterns, which use annotations whose properties are of enumerated types, are not matching. Below find the relevant artifacts and their shapes. The lines in the aspect PersistableJpaAspect that are not matching as they should are the 'declare parents' and 'declare @type'. If I change the annotation properties to be of type String and change the type patterns to use string literals (see "matches" comments in annotation: StoreType.JPA => "JPA" and IdType.LONG => "LONG"), the matching works properly. enums: ====== public enum StoreType { MONGO, JDO, JPA; } ===== public enum IdType { LONG, STRING; } annotation: =========== public @interface Persistable { StoreType in() default StoreType.MONGO; // doesn't match // matches: String in() default "MONGO"; IdType id() default IdType.STRING; // doesn't match // matches: String id() default "STRING"; } aspect: ======= public abstract privileged aspect PersistableAspect { public interface I extends ....trait.interfaces.persistence.Persistable { long version(); void version(long version); } public interface L extends I { Long idLong(); void idLong(Long id); } public interface S extends I { String idString(); void idString(String id); } declare @type : I+ : @Configurable; // ... } ===== public privileged aspect PersistableJpaAspect extends PersistableAspect { public interface JL extends L { } public interface JS extends S { } declare parents : (@Persistable(id = IdType.LONG, in = StoreType.JPA) *) implements JL; declare parents : (@Persistable(id = IdType.STRING, in = StoreType.JPA) *) implements JS; declare @type : @Persistable(in="JPA") JL+ : @Entity; declare @type : @Persistable(in="JPA") JS+ : @Entity; // ... }
resolved fixed
0d69bd3
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2012-09-19T23:35:53Z"
"2012-09-17T19:26:40Z"
org.aspectj.matcher/src/org/aspectj/weaver/StandardAnnotation.java
/* ******************************************************************* * Copyright (c) 2008 Contributors * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Eclipse Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/epl-v10.html * * ******************************************************************/ package org.aspectj.weaver; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Set; /** * This type represents the weavers abstraction of an annotation - it is not tied to any underlying BCI toolkit. The weaver actualy * handles these through AnnotationX wrapper objects - until we start transforming the BCEL annotations into this form (expensive) * or offer a clever visitor mechanism over the BCEL annotation stuff that builds these annotation types directly. * * @author AndyClement */ public class StandardAnnotation extends AbstractAnnotationAJ { private final boolean isRuntimeVisible; private List<AnnotationNameValuePair> nvPairs = null; public StandardAnnotation(ResolvedType type, boolean isRuntimeVisible) { super(type); this.isRuntimeVisible = isRuntimeVisible; } /** * {@inheritDoc} */ public boolean isRuntimeVisible() { return isRuntimeVisible; } /** * {@inheritDoc} */ public String stringify() { StringBuffer sb = new StringBuffer(); sb.append("@").append(type.getClassName()); if (hasNameValuePairs()) { sb.append("("); for (AnnotationNameValuePair nvPair : nvPairs) { sb.append(nvPair.stringify()); } sb.append(")"); } return sb.toString(); } public String toString() { StringBuffer sb = new StringBuffer(); sb.append("Anno[" + getTypeSignature() + " " + (isRuntimeVisible ? "rVis" : "rInvis")); if (nvPairs != null) { sb.append(" "); for (Iterator<AnnotationNameValuePair> iter = nvPairs.iterator(); iter.hasNext();) { AnnotationNameValuePair element = iter.next(); sb.append(element.toString()); if (iter.hasNext()) { sb.append(","); } } } sb.append("]"); return sb.toString(); } /** * {@inheritDoc} */ public boolean hasNamedValue(String n) { if (nvPairs == null) { return false; } for (int i = 0; i < nvPairs.size(); i++) { AnnotationNameValuePair pair = nvPairs.get(i); if (pair.getName().equals(n)) { return true; } } return false; } /** * {@inheritDoc} */ public boolean hasNameValuePair(String n, String v) { if (nvPairs == null) { return false; } for (int i = 0; i < nvPairs.size(); i++) { AnnotationNameValuePair pair = nvPairs.get(i); if (pair.getName().equals(n)) { if (pair.getValue().stringify().equals(v)) { return true; } } } return false; } /** * {@inheritDoc} */ public Set<String> getTargets() { if (!type.equals(UnresolvedType.AT_TARGET)) { return Collections.emptySet(); } AnnotationNameValuePair nvp = nvPairs.get(0); ArrayAnnotationValue aav = (ArrayAnnotationValue) nvp.getValue(); AnnotationValue[] avs = aav.getValues(); Set<String> targets = new HashSet<String>(); for (int i = 0; i < avs.length; i++) { AnnotationValue value = avs[i]; targets.add(value.stringify()); } return targets; } public List<AnnotationNameValuePair> getNameValuePairs() { return nvPairs; } public boolean hasNameValuePairs() { return nvPairs != null && nvPairs.size() != 0; } public void addNameValuePair(AnnotationNameValuePair pair) { if (nvPairs == null) { nvPairs = new ArrayList<AnnotationNameValuePair>(); } nvPairs.add(pair); } /** * {@inheritDoc} */ public String getStringFormOfValue(String name) { if (hasNameValuePairs()) { for (AnnotationNameValuePair nvPair : nvPairs) { if (nvPair.getName().equals(name)) { return nvPair.getValue().stringify(); } } } return null; } }
389,752
Bug 389752 declare parents & @type not matching on annotation properties of enum types
NOTE: real project private git repo demonstrating bug has been shared with Andy Clement privately. I'm reporting bug as Andy requested with as much info as I feel I can. I have a case where 'declare parents' and 'declare @type' instructions are not being applied because their type patterns, which use annotations whose properties are of enumerated types, are not matching. Below find the relevant artifacts and their shapes. The lines in the aspect PersistableJpaAspect that are not matching as they should are the 'declare parents' and 'declare @type'. If I change the annotation properties to be of type String and change the type patterns to use string literals (see "matches" comments in annotation: StoreType.JPA => "JPA" and IdType.LONG => "LONG"), the matching works properly. enums: ====== public enum StoreType { MONGO, JDO, JPA; } ===== public enum IdType { LONG, STRING; } annotation: =========== public @interface Persistable { StoreType in() default StoreType.MONGO; // doesn't match // matches: String in() default "MONGO"; IdType id() default IdType.STRING; // doesn't match // matches: String id() default "STRING"; } aspect: ======= public abstract privileged aspect PersistableAspect { public interface I extends ....trait.interfaces.persistence.Persistable { long version(); void version(long version); } public interface L extends I { Long idLong(); void idLong(Long id); } public interface S extends I { String idString(); void idString(String id); } declare @type : I+ : @Configurable; // ... } ===== public privileged aspect PersistableJpaAspect extends PersistableAspect { public interface JL extends L { } public interface JS extends S { } declare parents : (@Persistable(id = IdType.LONG, in = StoreType.JPA) *) implements JL; declare parents : (@Persistable(id = IdType.STRING, in = StoreType.JPA) *) implements JS; declare @type : @Persistable(in="JPA") JL+ : @Entity; declare @type : @Persistable(in="JPA") JS+ : @Entity; // ... }
resolved fixed
0d69bd3
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2012-09-19T23:35:53Z"
"2012-09-17T19:26:40Z"
org.aspectj.matcher/src/org/aspectj/weaver/patterns/WildAnnotationTypePattern.java
/* ******************************************************************* * Copyright (c) 2004 IBM Corporation. * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Eclipse Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/epl-v10.html * * ******************************************************************/ package org.aspectj.weaver.patterns; import java.io.IOException; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Set; import org.aspectj.bridge.IMessage; import org.aspectj.bridge.MessageUtil; import org.aspectj.util.FuzzyBoolean; import org.aspectj.weaver.AjAttribute.WeaverVersionInfo; import org.aspectj.weaver.AnnotatedElement; import org.aspectj.weaver.BCException; import org.aspectj.weaver.CompressingDataOutputStream; import org.aspectj.weaver.ISourceContext; import org.aspectj.weaver.ResolvedMember; import org.aspectj.weaver.ResolvedType; import org.aspectj.weaver.UnresolvedType; import org.aspectj.weaver.VersionedDataInputStream; import org.aspectj.weaver.WeaverMessages; import org.aspectj.weaver.World; /** * @author colyer * @author Andy Clement */ public class WildAnnotationTypePattern extends AnnotationTypePattern { private TypePattern typePattern; private boolean resolved = false; Map<String, String> annotationValues; public WildAnnotationTypePattern(TypePattern typePattern) { super(); this.typePattern = typePattern; this.setLocation(typePattern.getSourceContext(), typePattern.start, typePattern.end); } public WildAnnotationTypePattern(TypePattern typePattern, Map<String, String> annotationValues) { super(); this.typePattern = typePattern; this.annotationValues = annotationValues; // PVAL make the location be from start of type pattern to end of values this.setLocation(typePattern.getSourceContext(), typePattern.start, typePattern.end); } public TypePattern getTypePattern() { return typePattern; } /* * (non-Javadoc) * * @see org.aspectj.weaver.patterns.AnnotationTypePattern#matches(org.aspectj.weaver.AnnotatedElement) */ @Override public FuzzyBoolean matches(AnnotatedElement annotated) { return matches(annotated, null); } /** * Resolve any annotation values specified, checking they are all well formed (valid names, valid values) * * @param annotationType the annotation type for which the values have been specified * @param scope the scope within which to resolve type references (eg. Color.GREEN) */ protected void resolveAnnotationValues(ResolvedType annotationType, IScope scope) { if (annotationValues == null) { return; } // Check any values specified are OK: // - the value names are for valid annotation fields // - the specified values are of the correct type // - for enums, check the specified values can be resolved in the specified scope Set<String> keys = annotationValues.keySet(); ResolvedMember[] ms = annotationType.getDeclaredMethods(); for (Iterator<String> kIter = keys.iterator(); kIter.hasNext();) { String k = kIter.next(); String key = k; // a trailing ! indicates the the user expressed key!=value rather than key=value as a match constraint if (k.endsWith("!")) { key = key.substring(0, k.length() - 1); } String v = annotationValues.get(k); boolean validKey = false; for (int i = 0; i < ms.length; i++) { ResolvedMember resolvedMember = ms[i]; if (resolvedMember.getName().equals(key) && resolvedMember.isAbstract()) { validKey = true; ResolvedType t = resolvedMember.getReturnType().resolve(scope.getWorld()); if (t.isEnum()) { // value must be an enum reference X.Y int pos = v.lastIndexOf("."); if (pos == -1) { IMessage m = MessageUtil.error( WeaverMessages.format(WeaverMessages.INVALID_ANNOTATION_VALUE, v, "enum"), getSourceLocation()); scope.getWorld().getMessageHandler().handleMessage(m); } else { String typename = v.substring(0, pos); ResolvedType rt = scope.lookupType(typename, this).resolve(scope.getWorld()); v = rt.getSignature() + v.substring(pos + 1); // from 'Color.RED' to 'Lp/Color;RED' annotationValues.put(k, v); } } else if (t.isPrimitiveType()) { if (t.getSignature() == "I") { try { int value = Integer.parseInt(v); annotationValues.put(k, Integer.toString(value)); } catch (NumberFormatException nfe) { IMessage m = MessageUtil.error( WeaverMessages.format(WeaverMessages.INVALID_ANNOTATION_VALUE, v, "int"), getSourceLocation()); scope.getWorld().getMessageHandler().handleMessage(m); } } else if (t.getSignature() == "F") { try { float value = Float.parseFloat(v); annotationValues.put(k, Float.toString(value)); } catch (NumberFormatException nfe) { IMessage m = MessageUtil.error( WeaverMessages.format(WeaverMessages.INVALID_ANNOTATION_VALUE, v, "float"), getSourceLocation()); scope.getWorld().getMessageHandler().handleMessage(m); } } else if (t.getSignature() == "Z") { if (v.equalsIgnoreCase("true") || v.equalsIgnoreCase("false")) { // is it ok ! } else { IMessage m = MessageUtil.error( WeaverMessages.format(WeaverMessages.INVALID_ANNOTATION_VALUE, v, "boolean"), getSourceLocation()); scope.getWorld().getMessageHandler().handleMessage(m); } } else if (t.getSignature() == "S") { try { short value = Short.parseShort(v); annotationValues.put(k, Short.toString(value)); } catch (NumberFormatException nfe) { IMessage m = MessageUtil.error( WeaverMessages.format(WeaverMessages.INVALID_ANNOTATION_VALUE, v, "short"), getSourceLocation()); scope.getWorld().getMessageHandler().handleMessage(m); } } else if (t.getSignature() == "J") { try { long value = Long.parseLong(v); annotationValues.put(k, Long.toString(value)); } catch (NumberFormatException nfe) { IMessage m = MessageUtil.error( WeaverMessages.format(WeaverMessages.INVALID_ANNOTATION_VALUE, v, "long"), getSourceLocation()); scope.getWorld().getMessageHandler().handleMessage(m); } } else if (t.getSignature() == "D") { try { double value = Double.parseDouble(v); annotationValues.put(k, Double.toString(value)); } catch (NumberFormatException nfe) { IMessage m = MessageUtil.error( WeaverMessages.format(WeaverMessages.INVALID_ANNOTATION_VALUE, v, "double"), getSourceLocation()); scope.getWorld().getMessageHandler().handleMessage(m); } } else if (t.getSignature() == "B") { try { byte value = Byte.parseByte(v); annotationValues.put(k, Byte.toString(value)); } catch (NumberFormatException nfe) { IMessage m = MessageUtil.error( WeaverMessages.format(WeaverMessages.INVALID_ANNOTATION_VALUE, v, "byte"), getSourceLocation()); scope.getWorld().getMessageHandler().handleMessage(m); } } else if (t.getSignature() == "C") { if (v.length() != 3) { // '?' IMessage m = MessageUtil.error( WeaverMessages.format(WeaverMessages.INVALID_ANNOTATION_VALUE, v, "char"), getSourceLocation()); scope.getWorld().getMessageHandler().handleMessage(m); } else { annotationValues.put(k, v.substring(1, 2)); } } else { throw new RuntimeException("Not implemented for " + t); } } else if (t.equals(ResolvedType.JL_STRING)) { // nothing to do, it will be OK } else if (t.equals(ResolvedType.JL_CLASS)) { String typename = v.substring(0, v.lastIndexOf('.')); // strip off '.class' ResolvedType rt = scope.lookupType(typename, this).resolve(scope.getWorld()); if (rt.isMissing()) { IMessage m = MessageUtil.error("Unable to resolve type '" + v + "' specified for value '" + k + "'", getSourceLocation()); scope.getWorld().getMessageHandler().handleMessage(m); } annotationValues.put(k, rt.getSignature()); } else { if (t.isAnnotation()) { if (v.indexOf("(") != -1) { throw new RuntimeException( "Compiler limitation: annotation values can only currently be marker annotations (no values): " + v); } String typename = v.substring(1); ResolvedType rt = scope.lookupType(typename, this).resolve(scope.getWorld()); if (rt.isMissing()) { IMessage m = MessageUtil.error( "Unable to resolve type '" + v + "' specified for value '" + k + "'", getSourceLocation()); scope.getWorld().getMessageHandler().handleMessage(m); } annotationValues.put(k, rt.getSignature()); } else { throw new RuntimeException("Compiler limitation: annotation value support not implemented for type " + t); } } } } if (!validKey) { IMessage m = MessageUtil.error(WeaverMessages.format(WeaverMessages.UNKNOWN_ANNOTATION_VALUE, annotationType, k), getSourceLocation()); scope.getWorld().getMessageHandler().handleMessage(m); } else { break; } } } @Override public FuzzyBoolean matches(AnnotatedElement annotated, ResolvedType[] parameterAnnotations) { if (!resolved) { throw new IllegalStateException("Can't match on an unresolved annotation type pattern"); } if (annotationValues != null && !typePattern.hasFailedResolution()) { // PVAL improve this restriction, would allow '*(value=Color.RED)' throw new IllegalStateException("Cannot use annotationvalues with a wild annotation pattern"); } if (isForParameterAnnotationMatch()) { if (parameterAnnotations != null && parameterAnnotations.length != 0) { for (int i = 0; i < parameterAnnotations.length; i++) { if (typePattern.matches(parameterAnnotations[i], TypePattern.STATIC).alwaysTrue()) { return FuzzyBoolean.YES; } } } } else { // matches if the type of any of the annotations on the AnnotatedElement is // matched by the typePattern. ResolvedType[] annTypes = annotated.getAnnotationTypes(); if (annTypes != null && annTypes.length != 0) { for (int i = 0; i < annTypes.length; i++) { if (typePattern.matches(annTypes[i], TypePattern.STATIC).alwaysTrue()) { return FuzzyBoolean.YES; } } } } return FuzzyBoolean.NO; } /* * (non-Javadoc) * * @see org.aspectj.weaver.patterns.AnnotationTypePattern#resolve(org.aspectj.weaver.World) */ @Override public void resolve(World world) { if (!resolved) { // attempt resolution - this helps with the Spring bug where they resolve() the pointcut in no scope (SPR-5307) if (typePattern instanceof WildTypePattern && (annotationValues == null || annotationValues.isEmpty())) { WildTypePattern wildTypePattern = (WildTypePattern) typePattern; String fullyQualifiedName = wildTypePattern.maybeGetCleanName(); if (fullyQualifiedName != null && fullyQualifiedName.indexOf(".") != -1) { ResolvedType resolvedType = world.resolve(UnresolvedType.forName(fullyQualifiedName)); if (resolvedType != null && !resolvedType.isMissing()) { typePattern = new ExactTypePattern(resolvedType, false, false); } } } resolved = true; } } /** * This can modify in place, or return a new TypePattern if the type changes. */ @Override public AnnotationTypePattern resolveBindings(IScope scope, Bindings bindings, boolean allowBinding) { if (!scope.getWorld().isInJava5Mode()) { scope.message(MessageUtil.error(WeaverMessages.format(WeaverMessages.ANNOTATIONS_NEED_JAVA5), getSourceLocation())); return this; } if (resolved) { return this; } this.typePattern = typePattern.resolveBindings(scope, bindings, false, false); resolved = true; if (typePattern instanceof ExactTypePattern) { ExactTypePattern et = (ExactTypePattern) typePattern; if (!et.getExactType().resolve(scope.getWorld()).isAnnotation()) { IMessage m = MessageUtil.error( WeaverMessages.format(WeaverMessages.REFERENCE_TO_NON_ANNOTATION_TYPE, et.getExactType().getName()), getSourceLocation()); scope.getWorld().getMessageHandler().handleMessage(m); resolved = false; } ResolvedType annotationType = et.getExactType().resolve(scope.getWorld()); resolveAnnotationValues(annotationType, scope); ExactAnnotationTypePattern eatp = new ExactAnnotationTypePattern(annotationType, annotationValues); eatp.copyLocationFrom(this); if (isForParameterAnnotationMatch()) { eatp.setForParameterAnnotationMatch(); } return eatp; } else { return this; } } @Override public AnnotationTypePattern parameterizeWith(Map typeVariableMap, World w) { WildAnnotationTypePattern ret = new WildAnnotationTypePattern(typePattern.parameterizeWith(typeVariableMap, w)); ret.copyLocationFrom(this); ret.resolved = resolved; return ret; } private static final byte VERSION = 1; // rev if ser. form changes @Override public void write(CompressingDataOutputStream s) throws IOException { s.writeByte(AnnotationTypePattern.WILD); s.writeByte(VERSION); typePattern.write(s); writeLocation(s); s.writeBoolean(isForParameterAnnotationMatch()); // PVAL if (annotationValues == null) { s.writeInt(0); } else { s.writeInt(annotationValues.size()); Set<String> key = annotationValues.keySet(); for (Iterator<String> keys = key.iterator(); keys.hasNext();) { String k = keys.next(); s.writeUTF(k); s.writeUTF(annotationValues.get(k)); } } } public static AnnotationTypePattern read(VersionedDataInputStream s, ISourceContext context) throws IOException { WildAnnotationTypePattern ret; byte version = s.readByte(); if (version > VERSION) { throw new BCException("ExactAnnotationTypePattern was written by a newer version of AspectJ"); } TypePattern t = TypePattern.read(s, context); ret = new WildAnnotationTypePattern(t); ret.readLocation(context, s); if (s.getMajorVersion() >= WeaverVersionInfo.WEAVER_VERSION_MAJOR_AJ160) { if (s.readBoolean()) { ret.setForParameterAnnotationMatch(); } } if (s.getMajorVersion() >= WeaverVersionInfo.WEAVER_VERSION_MAJOR_AJ160M2) { int annotationValueCount = s.readInt(); if (annotationValueCount > 0) { Map<String, String> aValues = new HashMap<String, String>(); for (int i = 0; i < annotationValueCount; i++) { String key = s.readUTF(); String val = s.readUTF(); aValues.put(key, val); } ret.annotationValues = aValues; } } return ret; } @Override public boolean equals(Object obj) { if (!(obj instanceof WildAnnotationTypePattern)) { return false; } WildAnnotationTypePattern other = (WildAnnotationTypePattern) obj; return other.typePattern.equals(typePattern) && this.isForParameterAnnotationMatch() == other.isForParameterAnnotationMatch() && (annotationValues == null ? other.annotationValues == null : annotationValues.equals(other.annotationValues)); } @Override public int hashCode() { return (((17 + 37 * typePattern.hashCode()) * 37 + (isForParameterAnnotationMatch() ? 0 : 1)) * 37) + (annotationValues == null ? 0 : annotationValues.hashCode()); } @Override public String toString() { return "@(" + typePattern.toString() + ")"; } @Override public Object accept(PatternNodeVisitor visitor, Object data) { return visitor.visit(this, data); } }
389,752
Bug 389752 declare parents & @type not matching on annotation properties of enum types
NOTE: real project private git repo demonstrating bug has been shared with Andy Clement privately. I'm reporting bug as Andy requested with as much info as I feel I can. I have a case where 'declare parents' and 'declare @type' instructions are not being applied because their type patterns, which use annotations whose properties are of enumerated types, are not matching. Below find the relevant artifacts and their shapes. The lines in the aspect PersistableJpaAspect that are not matching as they should are the 'declare parents' and 'declare @type'. If I change the annotation properties to be of type String and change the type patterns to use string literals (see "matches" comments in annotation: StoreType.JPA => "JPA" and IdType.LONG => "LONG"), the matching works properly. enums: ====== public enum StoreType { MONGO, JDO, JPA; } ===== public enum IdType { LONG, STRING; } annotation: =========== public @interface Persistable { StoreType in() default StoreType.MONGO; // doesn't match // matches: String in() default "MONGO"; IdType id() default IdType.STRING; // doesn't match // matches: String id() default "STRING"; } aspect: ======= public abstract privileged aspect PersistableAspect { public interface I extends ....trait.interfaces.persistence.Persistable { long version(); void version(long version); } public interface L extends I { Long idLong(); void idLong(Long id); } public interface S extends I { String idString(); void idString(String id); } declare @type : I+ : @Configurable; // ... } ===== public privileged aspect PersistableJpaAspect extends PersistableAspect { public interface JL extends L { } public interface JS extends S { } declare parents : (@Persistable(id = IdType.LONG, in = StoreType.JPA) *) implements JL; declare parents : (@Persistable(id = IdType.STRING, in = StoreType.JPA) *) implements JS; declare @type : @Persistable(in="JPA") JL+ : @Entity; declare @type : @Persistable(in="JPA") JS+ : @Entity; // ... }
resolved fixed
0d69bd3
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2012-09-19T23:35:53Z"
"2012-09-17T19:26:40Z"
tests/bugs172/pr389752/Code.java
389,752
Bug 389752 declare parents & @type not matching on annotation properties of enum types
NOTE: real project private git repo demonstrating bug has been shared with Andy Clement privately. I'm reporting bug as Andy requested with as much info as I feel I can. I have a case where 'declare parents' and 'declare @type' instructions are not being applied because their type patterns, which use annotations whose properties are of enumerated types, are not matching. Below find the relevant artifacts and their shapes. The lines in the aspect PersistableJpaAspect that are not matching as they should are the 'declare parents' and 'declare @type'. If I change the annotation properties to be of type String and change the type patterns to use string literals (see "matches" comments in annotation: StoreType.JPA => "JPA" and IdType.LONG => "LONG"), the matching works properly. enums: ====== public enum StoreType { MONGO, JDO, JPA; } ===== public enum IdType { LONG, STRING; } annotation: =========== public @interface Persistable { StoreType in() default StoreType.MONGO; // doesn't match // matches: String in() default "MONGO"; IdType id() default IdType.STRING; // doesn't match // matches: String id() default "STRING"; } aspect: ======= public abstract privileged aspect PersistableAspect { public interface I extends ....trait.interfaces.persistence.Persistable { long version(); void version(long version); } public interface L extends I { Long idLong(); void idLong(Long id); } public interface S extends I { String idString(); void idString(String id); } declare @type : I+ : @Configurable; // ... } ===== public privileged aspect PersistableJpaAspect extends PersistableAspect { public interface JL extends L { } public interface JS extends S { } declare parents : (@Persistable(id = IdType.LONG, in = StoreType.JPA) *) implements JL; declare parents : (@Persistable(id = IdType.STRING, in = StoreType.JPA) *) implements JS; declare @type : @Persistable(in="JPA") JL+ : @Entity; declare @type : @Persistable(in="JPA") JS+ : @Entity; // ... }
resolved fixed
0d69bd3
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2012-09-19T23:35:53Z"
"2012-09-17T19:26:40Z"
tests/bugs172/pr389752/Code2.java
389,752
Bug 389752 declare parents & @type not matching on annotation properties of enum types
NOTE: real project private git repo demonstrating bug has been shared with Andy Clement privately. I'm reporting bug as Andy requested with as much info as I feel I can. I have a case where 'declare parents' and 'declare @type' instructions are not being applied because their type patterns, which use annotations whose properties are of enumerated types, are not matching. Below find the relevant artifacts and their shapes. The lines in the aspect PersistableJpaAspect that are not matching as they should are the 'declare parents' and 'declare @type'. If I change the annotation properties to be of type String and change the type patterns to use string literals (see "matches" comments in annotation: StoreType.JPA => "JPA" and IdType.LONG => "LONG"), the matching works properly. enums: ====== public enum StoreType { MONGO, JDO, JPA; } ===== public enum IdType { LONG, STRING; } annotation: =========== public @interface Persistable { StoreType in() default StoreType.MONGO; // doesn't match // matches: String in() default "MONGO"; IdType id() default IdType.STRING; // doesn't match // matches: String id() default "STRING"; } aspect: ======= public abstract privileged aspect PersistableAspect { public interface I extends ....trait.interfaces.persistence.Persistable { long version(); void version(long version); } public interface L extends I { Long idLong(); void idLong(Long id); } public interface S extends I { String idString(); void idString(String id); } declare @type : I+ : @Configurable; // ... } ===== public privileged aspect PersistableJpaAspect extends PersistableAspect { public interface JL extends L { } public interface JS extends S { } declare parents : (@Persistable(id = IdType.LONG, in = StoreType.JPA) *) implements JL; declare parents : (@Persistable(id = IdType.STRING, in = StoreType.JPA) *) implements JS; declare @type : @Persistable(in="JPA") JL+ : @Entity; declare @type : @Persistable(in="JPA") JS+ : @Entity; // ... }
resolved fixed
0d69bd3
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2012-09-19T23:35:53Z"
"2012-09-17T19:26:40Z"
tests/bugs172/pr389752/Code3.java
389,752
Bug 389752 declare parents & @type not matching on annotation properties of enum types
NOTE: real project private git repo demonstrating bug has been shared with Andy Clement privately. I'm reporting bug as Andy requested with as much info as I feel I can. I have a case where 'declare parents' and 'declare @type' instructions are not being applied because their type patterns, which use annotations whose properties are of enumerated types, are not matching. Below find the relevant artifacts and their shapes. The lines in the aspect PersistableJpaAspect that are not matching as they should are the 'declare parents' and 'declare @type'. If I change the annotation properties to be of type String and change the type patterns to use string literals (see "matches" comments in annotation: StoreType.JPA => "JPA" and IdType.LONG => "LONG"), the matching works properly. enums: ====== public enum StoreType { MONGO, JDO, JPA; } ===== public enum IdType { LONG, STRING; } annotation: =========== public @interface Persistable { StoreType in() default StoreType.MONGO; // doesn't match // matches: String in() default "MONGO"; IdType id() default IdType.STRING; // doesn't match // matches: String id() default "STRING"; } aspect: ======= public abstract privileged aspect PersistableAspect { public interface I extends ....trait.interfaces.persistence.Persistable { long version(); void version(long version); } public interface L extends I { Long idLong(); void idLong(Long id); } public interface S extends I { String idString(); void idString(String id); } declare @type : I+ : @Configurable; // ... } ===== public privileged aspect PersistableJpaAspect extends PersistableAspect { public interface JL extends L { } public interface JS extends S { } declare parents : (@Persistable(id = IdType.LONG, in = StoreType.JPA) *) implements JL; declare parents : (@Persistable(id = IdType.STRING, in = StoreType.JPA) *) implements JS; declare @type : @Persistable(in="JPA") JL+ : @Entity; declare @type : @Persistable(in="JPA") JS+ : @Entity; // ... }
resolved fixed
0d69bd3
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2012-09-19T23:35:53Z"
"2012-09-17T19:26:40Z"
tests/src/org/aspectj/systemtest/ajc172/Ajc172Tests.java
/******************************************************************************* * Copyright (c) 2012 Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Andy Clement - initial API and implementation *******************************************************************************/ package org.aspectj.systemtest.ajc172; import java.io.File; import junit.framework.Test; import org.aspectj.testing.XMLBasedAjcTestCase; /** * @author Andy Clement */ public class Ajc172Tests extends org.aspectj.testing.XMLBasedAjcTestCase { public void testInconsistentClassFile_pr389750() { runTest("inconsistent class file"); } public void testInconsistentClassFile_pr389750_2() { runTest("inconsistent class file 2"); } public void testInconsistentClassFile_pr389750_3() { runTest("inconsistent class file 3"); } public void testInconsistentClassFile_pr389750_4() { runTest("inconsistent class file 4"); } // --- public static Test suite() { return XMLBasedAjcTestCase.loadSuite(Ajc172Tests.class); } @Override protected File getSpecFile() { return new File("../tests/src/org/aspectj/systemtest/ajc172/ajc172.xml"); } }
389,456
Bug 389456 NPE in EclipseTypeMunger.mungeNewMethod()
null
resolved fixed
b8ebdc3
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2012-09-20T20:38:35Z"
"2012-09-12T22:46:40Z"
org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/compiler/lookup/EclipseTypeMunger.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Eclipse Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * PARC initial implementation * ******************************************************************/ package org.aspectj.ajdt.internal.compiler.lookup; import java.lang.reflect.Modifier; import java.util.Map; import org.aspectj.bridge.ISourceLocation; import org.aspectj.org.eclipse.jdt.core.compiler.CharOperation; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration; import org.aspectj.org.eclipse.jdt.internal.compiler.classfmt.ClassFileConstants; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.BinaryTypeBinding; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.FieldBinding; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.MethodBinding; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.ReferenceBinding; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.SourceTypeBinding; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.TagBits; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.TypeVariableBinding; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.UnresolvedReferenceBinding; import org.aspectj.weaver.ConcreteTypeMunger; import org.aspectj.weaver.NewConstructorTypeMunger; import org.aspectj.weaver.NewFieldTypeMunger; import org.aspectj.weaver.NewMemberClassTypeMunger; import org.aspectj.weaver.NewMethodTypeMunger; import org.aspectj.weaver.ResolvedMember; import org.aspectj.weaver.ResolvedType; import org.aspectj.weaver.ResolvedTypeMunger; import org.aspectj.weaver.World; public class EclipseTypeMunger extends ConcreteTypeMunger { private ResolvedType targetTypeX; // protected ReferenceBinding targetBinding = null; public AbstractMethodDeclaration sourceMethod; private EclipseFactory world; private ISourceLocation sourceLocation; public EclipseTypeMunger(EclipseFactory world, ResolvedTypeMunger munger, ResolvedType aspectType, AbstractMethodDeclaration sourceMethod) { super(munger, aspectType); this.world = world; this.sourceMethod = sourceMethod; // A null sourceMethod can be because of binary weaving if (sourceMethod != null) { this.sourceLocation = new EclipseSourceLocation(sourceMethod.compilationResult, sourceMethod.sourceStart, sourceMethod.sourceEnd); // Piece of magic that tells type mungers where they came from. // Won't be persisted unless ResolvedTypeMunger.persistSourceLocation is true. munger.setSourceLocation(sourceLocation); // use a different ctor for type level inter type decls I think // } else { // this.sourceLocation = aspectType.getSourceLocation(); // munger.setSourceLocation(sourceLocation); } // was targetTypeX = munger.getDeclaringType().resolve(world.getWorld()); // targetTypeX = munger.getSignature().getDeclaringType().resolve(world.getWorld()); // AMC, needed until generic and raw have distinct sigs... if (targetTypeX.isParameterizedType() || targetTypeX.isRawType()) { targetTypeX = targetTypeX.getGenericType(); // targetBinding = (ReferenceBinding)world.makeTypeBinding(targetTypeX); } } public static boolean supportsKind(ResolvedTypeMunger.Kind kind) { return kind == ResolvedTypeMunger.Field || kind == ResolvedTypeMunger.Method || kind == ResolvedTypeMunger.Constructor || kind == ResolvedTypeMunger.InnerClass; } public String toString() { return "(EclipseTypeMunger " + getMunger() + ")"; } /** * Modifies signatures of a TypeBinding through its ClassScope, i.e. adds Method|FieldBindings, plays with inheritance, ... */ public boolean munge(SourceTypeBinding sourceType, ResolvedType onType) { ResolvedType rt = onType; if (rt.isRawType() || rt.isParameterizedType()) { rt = rt.getGenericType(); } boolean isExactTargetType = rt.equals(targetTypeX); if (!isExactTargetType) { // might be the topmost implementor of an interface we care about if (munger.getKind() != ResolvedTypeMunger.Method) { return false; } if (onType.isInterface()) { return false; } if (!munger.needsAccessToTopmostImplementor()) { return false; } // so we do need access, and this type could be it... if (!onType.isTopmostImplementor(targetTypeX)) { return false; } // we are the topmost implementor of an interface type that needs munging // but we only care about public methods here (we only do this at all to // drive the JDT MethodVerifier correctly) if (!Modifier.isPublic(munger.getSignature().getModifiers())) { return false; } } // System.out.println("munging: " + sourceType); // System.out.println("match: " + world.fromEclipse(sourceType) + // " with " + targetTypeX); if (munger.getKind() == ResolvedTypeMunger.Field) { mungeNewField(sourceType, (NewFieldTypeMunger) munger); } else if (munger.getKind() == ResolvedTypeMunger.Method) { return mungeNewMethod(sourceType, onType, (NewMethodTypeMunger) munger, isExactTargetType); } else if (munger.getKind() == ResolvedTypeMunger.Constructor) { mungeNewConstructor(sourceType, (NewConstructorTypeMunger) munger); } else if (munger.getKind() == ResolvedTypeMunger.InnerClass) { mungeNewInnerClass(sourceType, onType, (NewMemberClassTypeMunger) munger, isExactTargetType); } else { throw new RuntimeException("unimplemented: " + munger.getKind()); } return true; } private boolean mungeNewMethod(SourceTypeBinding sourceType, ResolvedType onType, NewMethodTypeMunger munger, boolean isExactTargetType) { InterTypeMethodBinding binding = new InterTypeMethodBinding(world, munger, aspectType, sourceMethod); if (!isExactTargetType) { // we're munging an interface ITD onto a topmost implementor ResolvedMember existingMember = onType.lookupMemberIncludingITDsOnInterfaces(getSignature()); if (existingMember != null) { // already have an implementation, so don't do anything if (onType == existingMember.getDeclaringType() && Modifier.isFinal(munger.getSignature().getModifiers())) { // final modifier on default implementation is taken to mean that // no-one else can provide an implementation MethodBinding offendingBinding = sourceType.getExactMethod(binding.selector, binding.parameters, sourceType.scope.compilationUnitScope()); sourceType.scope.problemReporter().finalMethodCannotBeOverridden(offendingBinding, binding); } // so that we find methods from our superinterfaces later on... findOrCreateInterTypeMemberFinder(sourceType); return false; } } // retain *only* the visibility modifiers and abstract when putting methods on an interface... if (sourceType.isInterface()) { boolean isAbstract = (binding.modifiers & ClassFileConstants.AccAbstract) != 0; binding.modifiers = (binding.modifiers & (ClassFileConstants.AccPublic | ClassFileConstants.AccProtected | ClassFileConstants.AccPrivate)); if (isAbstract) { binding.modifiers |= ClassFileConstants.AccAbstract; } } if (munger.getSignature().isVarargsMethod()) { binding.modifiers |= ClassFileConstants.AccVarargs; } findOrCreateInterTypeMemberFinder(sourceType).addInterTypeMethod(binding); return true; } // very similar to code in AspectDeclaration private boolean mungeNewInnerClass(SourceTypeBinding sourceType, ResolvedType onType, NewMemberClassTypeMunger munger, boolean isExactTargetType) { SourceTypeBinding aspectTypeBinding = (SourceTypeBinding) world.makeTypeBinding(aspectType); char[] mungerMemberTypeName = ("$" + munger.getMemberTypeName()).toCharArray(); ReferenceBinding innerTypeBinding = null; for (ReferenceBinding innerType : aspectTypeBinding.memberTypes) { char[] compounded = CharOperation.concatWith(innerType.compoundName, '.'); if (org.aspectj.org.eclipse.jdt.core.compiler.CharOperation.endsWith(compounded, mungerMemberTypeName)) { innerTypeBinding = innerType; break; } } // may be unresolved if the aspect type binding was a BinaryTypeBinding if (innerTypeBinding instanceof UnresolvedReferenceBinding) { innerTypeBinding = (ReferenceBinding)BinaryTypeBinding.resolveType(innerTypeBinding, world.getLookupEnvironment(), true); } // rb = new InterTypeMemberClassBinding(world, munger, aspectType, aspectTypeBinding, onType, munger.getMemberTypeName(), // sourceType); // TODO adjust modifier? // TODO deal with itd of it onto an interface findOrCreateInterTypeMemberClassFinder(sourceType).addInterTypeMemberType(innerTypeBinding); return true; } private void mungeNewConstructor(SourceTypeBinding sourceType, NewConstructorTypeMunger munger) { if (shouldTreatAsPublic()) { MethodBinding binding = world.makeMethodBinding(munger.getSignature(), munger.getTypeVariableAliases()); findOrCreateInterTypeMemberFinder(sourceType).addInterTypeMethod(binding); TypeVariableBinding[] typeVariables = binding.typeVariables; for (int i = 0; i < typeVariables.length; i++) { TypeVariableBinding tv = typeVariables[i]; String name = new String(tv.sourceName); TypeVariableBinding[] tv2 = sourceMethod.binding.typeVariables; for (int j = 0; j < tv2.length; j++) { if (new String(tv2[j].sourceName).equals(name)) { typeVariables[i].declaringElement = binding; } } } for (int i = 0; i < typeVariables.length; i++) { if (typeVariables[i].declaringElement == null) { throw new RuntimeException("Declaring element not set"); } } // classScope.referenceContext.binding.addMethod(binding); } else { InterTypeMethodBinding binding = new InterTypeMethodBinding(world, munger, aspectType, sourceMethod); findOrCreateInterTypeMemberFinder(sourceType).addInterTypeMethod(binding); } } private void mungeNewField(SourceTypeBinding sourceType, NewFieldTypeMunger munger) { if (shouldTreatAsPublic() && !targetTypeX.isInterface()) { FieldBinding binding = world.makeFieldBinding(munger); findOrCreateInterTypeMemberFinder(sourceType).addInterTypeField(binding); // classScope.referenceContext.binding.addField(binding); } else { InterTypeFieldBinding binding = new InterTypeFieldBinding(world, munger, aspectType, sourceMethod); InterTypeMemberFinder finder = findOrCreateInterTypeMemberFinder(sourceType); // Downgrade this field munger if name is already 'claimed' if (finder.definesField(munger.getSignature().getName())) { munger.version = NewFieldTypeMunger.VersionOne; } finder.addInterTypeField(binding); } } private boolean shouldTreatAsPublic() { // ??? this is where we could fairly easily choose to treat package-protected // ??? introductions like public ones when the target type and the aspect // ??? are in the same package return Modifier.isPublic(munger.getSignature().getModifiers()); } private InterTypeMemberFinder findOrCreateInterTypeMemberFinder(SourceTypeBinding sourceType) { InterTypeMemberFinder finder = (InterTypeMemberFinder) sourceType.memberFinder; if (finder == null) { finder = new InterTypeMemberFinder(); sourceType.memberFinder = finder; finder.sourceTypeBinding = sourceType; } return finder; } private IntertypeMemberTypeFinder findOrCreateInterTypeMemberClassFinder(SourceTypeBinding sourceType) { IntertypeMemberTypeFinder finder = (IntertypeMemberTypeFinder) sourceType.typeFinder; if (finder == null) { finder = new IntertypeMemberTypeFinder(); sourceType.typeFinder = finder; finder.targetTypeBinding = sourceType; sourceType.tagBits &= ~TagBits.HasNoMemberTypes; // ensure it thinks it has one } return finder; } public ISourceLocation getSourceLocation() { return sourceLocation; } public void setSourceLocation(ISourceLocation sourceLocation) { this.sourceLocation = sourceLocation; } /** * @return AbstractMethodDeclaration */ public AbstractMethodDeclaration getSourceMethod() { return sourceMethod; } public ConcreteTypeMunger parameterizedFor(ResolvedType target) { return new EclipseTypeMunger(world, munger.parameterizedFor(target), aspectType, sourceMethod); } public ConcreteTypeMunger parameterizeWith(Map m, World w) { return new EclipseTypeMunger(world, munger.parameterizeWith(m, w), aspectType, sourceMethod); } }
389,967
Bug 389967 Weaved aspects mechanism does not take into account modified classes
The current caching mechanism assumes that if the same class is encountered then its cached weaved version can be used. However, the mechanism uses only the (fully qualified) class name to identify the class and does not take into account the fact that the class bytes may have changed (e.g., the user re-compiled and re-deployed some changes to the same class).
resolved fixed
9a3cc2b
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2012-10-01T20:22:37Z"
"2012-09-20T05:46: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 * John Kew (vmware) caching hook *******************************************************************************/ package org.aspectj.weaver.loadtime; import java.io.*; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.net.MalformedURLException; import java.net.URL; import java.security.ProtectionDomain; import java.util.*; import org.aspectj.bridge.AbortException; import org.aspectj.bridge.Constants; import org.aspectj.util.LangUtil; import org.aspectj.weaver.Lint; import org.aspectj.weaver.Lint.Kind; import org.aspectj.weaver.ResolvedType; import org.aspectj.weaver.UnresolvedType; import org.aspectj.weaver.World; import org.aspectj.weaver.bcel.BcelWeakClassLoaderReference; import org.aspectj.weaver.bcel.BcelWeaver; import org.aspectj.weaver.bcel.BcelWorld; import org.aspectj.weaver.bcel.Utility; import org.aspectj.weaver.loadtime.definition.Definition; import org.aspectj.weaver.loadtime.definition.DocumentParser; import org.aspectj.weaver.ltw.LTWWorld; import org.aspectj.weaver.patterns.PatternParser; import org.aspectj.weaver.patterns.TypePattern; import org.aspectj.weaver.tools.*; import org.aspectj.weaver.tools.cache.WeavedClassCache; /** * @author Alexandre Vasseur * @author Andy Clement * @author Abraham Nevado */ public class ClassLoaderWeavingAdaptor extends WeavingAdaptor { private final static String AOP_XML = Constants.AOP_USER_XML + ";" + Constants.AOP_AJC_XML + ";" + Constants.AOP_OSGI_XML; private boolean initialized; private List m_dumpTypePattern = new ArrayList(); private boolean m_dumpBefore = false; private boolean dumpDirPerClassloader = false; private boolean hasExcludes = false; private List<TypePattern> excludeTypePattern = new ArrayList<TypePattern>(); // anything private List<String> excludeStartsWith = new ArrayList<String>(); // com.foo..* private List<String> excludeStarDotDotStar = new ArrayList<String>(); // *..*CGLIB* private List<String> excludeExactName = new ArrayList<String>(); // com.foo.Bar private List<String> excludeEndsWith = new ArrayList<String>(); // com.foo.Bar private List<String[]> excludeSpecial = new ArrayList<String[]>(); private boolean hasIncludes = false; private List<TypePattern> includeTypePattern = new ArrayList<TypePattern>(); private List<String> m_includeStartsWith = new ArrayList<String>(); private List<String> includeExactName = new ArrayList<String>(); private boolean includeStar = false; private List<TypePattern> m_aspectExcludeTypePattern = new ArrayList<TypePattern>(); private List<String> m_aspectExcludeStartsWith = new ArrayList<String>(); private List<TypePattern> m_aspectIncludeTypePattern = new ArrayList<TypePattern>(); private List<String> m_aspectIncludeStartsWith = new ArrayList<String>(); private StringBuffer namespace; private IWeavingContext weavingContext; private List<ConcreteAspectCodeGen> concreteAspects = new ArrayList<ConcreteAspectCodeGen>(); private static Trace trace = TraceFactory.getTraceFactory().getTrace(ClassLoaderWeavingAdaptor.class); public ClassLoaderWeavingAdaptor() { super(); if (trace.isTraceEnabled()) { trace.enter("<init>", this); } if (trace.isTraceEnabled()) { trace.exit("<init>"); } } /** * We don't need a reference to the class loader and using it during construction can cause problems with recursion. It also * makes sense to supply the weaving context during initialization to. * * @deprecated */ public ClassLoaderWeavingAdaptor(final ClassLoader deprecatedLoader, final IWeavingContext deprecatedContext) { super(); if (trace.isTraceEnabled()) { trace.enter("<init>", this, new Object[] { deprecatedLoader, deprecatedContext }); } if (trace.isTraceEnabled()) { trace.exit("<init>"); } } class SimpleGeneratedClassHandler implements GeneratedClassHandler { private BcelWeakClassLoaderReference loaderRef; SimpleGeneratedClassHandler(ClassLoader loader) { loaderRef = new BcelWeakClassLoaderReference(loader); } /** * Callback when we need to define a Closure in the JVM * */ public void acceptClass(String name, byte[] bytes) { try { if (shouldDump(name.replace('/', '.'), false)) { dump(name, bytes, false); } } catch (Throwable throwable) { throwable.printStackTrace(); } if (activeProtectionDomain != null) { defineClass(loaderRef.getClassLoader(), name, bytes, activeProtectionDomain); } else { defineClass(loaderRef.getClassLoader(), name, bytes); // could be done lazily using the hook } } } public void initialize(final ClassLoader classLoader, IWeavingContext context) { if (initialized) { return; } boolean success = true; this.weavingContext = context; if (weavingContext == null) { weavingContext = new DefaultWeavingContext(classLoader); } createMessageHandler(); this.generatedClassHandler = new SimpleGeneratedClassHandler(classLoader); List definitions = weavingContext.getDefinitions(classLoader, this); if (definitions.isEmpty()) { disable(); // TODO maw Needed to ensure messages are flushed if (trace.isTraceEnabled()) { trace.exit("initialize", definitions); } return; } // TODO when the world works in terms of the context, we can remove the loader bcelWorld = new LTWWorld(classLoader, weavingContext, getMessageHandler(), null); weaver = new BcelWeaver(bcelWorld); // register the definitions success = registerDefinitions(weaver, classLoader, definitions); if (success) { // after adding aspects weaver.prepareForWeave(); enable(); // TODO maw Needed to ensure messages are flushed success = weaveAndDefineConceteAspects(); } if (success) { enable(); } else { disable(); bcelWorld = null; weaver = null; } if (WeavedClassCache.isEnabled()) { initializeCache(classLoader, getAspectClassNames(definitions), generatedClassHandler, getMessageHandler()); } initialized = true; if (trace.isTraceEnabled()) { trace.exit("initialize", isEnabled()); } } /** * Get the list of all aspects from the defintion list * @param definitions * @return */ List<String> getAspectClassNames(List<Definition> definitions) { List<String> aspects = new LinkedList<String>(); for (Iterator<Definition> it = definitions.iterator(); it.hasNext(); ) { Definition def = it.next(); List<String> defAspects = def.getAspectClassNames(); if (defAspects != null) { aspects.addAll(defAspects); } } return aspects; } /** * Load and cache the aop.xml/properties according to the classloader visibility rules * * @param loader */ List<Definition> parseDefinitions(final ClassLoader loader) { if (trace.isTraceEnabled()) { trace.enter("parseDefinitions", this); } List<Definition> definitions = new ArrayList<Definition>(); try { info("register classloader " + getClassLoaderName(loader)); // TODO av underoptimized: we will parse each XML once per CL that see it // TODO av dev mode needed ? TBD -Daj5.def=... if (loader.equals(ClassLoader.getSystemClassLoader())) { String file = System.getProperty("aj5.def", null); if (file != null) { info("using (-Daj5.def) " + file); definitions.add(DocumentParser.parse((new File(file)).toURL())); } } String resourcePath = System.getProperty("org.aspectj.weaver.loadtime.configuration", AOP_XML); if (trace.isTraceEnabled()) { trace.event("parseDefinitions", this, resourcePath); } StringTokenizer st = new StringTokenizer(resourcePath, ";"); while (st.hasMoreTokens()) { String nextDefinition = st.nextToken(); if (nextDefinition.startsWith("file:")) { try { String fpath = new URL(nextDefinition).getFile(); File configFile = new File(fpath); if (!configFile.exists()) { warn("configuration does not exist: " + nextDefinition); } else { definitions.add(DocumentParser.parse(configFile.toURL())); } } catch (MalformedURLException mue) { error("malformed definition url: " + nextDefinition); } } else { Enumeration<URL> xmls = weavingContext.getResources(nextDefinition); // System.out.println("? registerDefinitions: found-aop.xml=" + xmls.hasMoreElements() + ", loader=" + loader); Set<URL> seenBefore = new HashSet<URL>(); while (xmls.hasMoreElements()) { URL xml = xmls.nextElement(); if (trace.isTraceEnabled()) { trace.event("parseDefinitions", this, xml); } if (!seenBefore.contains(xml)) { info("using configuration " + weavingContext.getFile(xml)); definitions.add(DocumentParser.parse(xml)); seenBefore.add(xml); } else { debug("ignoring duplicate definition: " + xml); } } } } if (definitions.isEmpty()) { info("no configuration found. Disabling weaver for class loader " + getClassLoaderName(loader)); } } catch (Exception e) { definitions.clear(); warn("parse definitions failed", e); } if (trace.isTraceEnabled()) { trace.exit("parseDefinitions", definitions); } return definitions; } private boolean registerDefinitions(final BcelWeaver weaver, final ClassLoader loader, List<Definition> definitions) { if (trace.isTraceEnabled()) { trace.enter("registerDefinitions", this, definitions); } boolean success = true; try { registerOptions(weaver, loader, definitions); registerAspectExclude(weaver, loader, definitions); registerAspectInclude(weaver, loader, definitions); success = registerAspects(weaver, loader, definitions); registerIncludeExclude(weaver, loader, definitions); registerDump(weaver, loader, definitions); } catch (Exception ex) { trace.error("register definition failed", ex); success = false; warn("register definition failed", (ex instanceof AbortException) ? null : ex); } if (trace.isTraceEnabled()) { trace.exit("registerDefinitions", success); } return success; } private String getClassLoaderName(ClassLoader loader) { return weavingContext.getClassLoaderName(); } /** * Configure the weaver according to the option directives TODO av - don't know if it is that good to reuse, since we only allow * a small subset of options in LTW * * @param weaver * @param loader * @param definitions */ private void registerOptions(final BcelWeaver weaver, final ClassLoader loader, final List<Definition> definitions) { StringBuffer allOptions = new StringBuffer(); for (Definition definition : definitions) { allOptions.append(definition.getWeaverOptions()).append(' '); } Options.WeaverOption weaverOption = Options.parse(allOptions.toString(), loader, getMessageHandler()); // configure the weaver and world // AV - code duplicates AspectJBuilder.initWorldAndWeaver() World world = weaver.getWorld(); setMessageHandler(weaverOption.messageHandler); world.setXlazyTjp(weaverOption.lazyTjp); world.setXHasMemberSupportEnabled(weaverOption.hasMember); world.setTiming(weaverOption.timers, true); world.setOptionalJoinpoints(weaverOption.optionalJoinpoints); world.setPinpointMode(weaverOption.pinpoint); weaver.setReweavableMode(weaverOption.notReWeavable); world.performExtraConfiguration(weaverOption.xSet); world.setXnoInline(weaverOption.noInline); // AMC - autodetect as per line below, needed for AtAjLTWTests.testLTWUnweavable world.setBehaveInJava5Way(LangUtil.is15VMOrGreater()); world.setAddSerialVerUID(weaverOption.addSerialVersionUID); /* First load defaults */ bcelWorld.getLint().loadDefaultProperties(); /* Second overlay LTW defaults */ bcelWorld.getLint().adviceDidNotMatch.setKind(null); /* Third load user file using -Xlintfile so that -Xlint wins */ if (weaverOption.lintFile != null) { InputStream resource = null; try { resource = loader.getResourceAsStream(weaverOption.lintFile); Exception failure = null; if (resource != null) { try { Properties properties = new Properties(); properties.load(resource); world.getLint().setFromProperties(properties); } catch (IOException e) { failure = e; } } if (failure != null || resource == null) { warn("Cannot access resource for -Xlintfile:" + weaverOption.lintFile, failure); // world.getMessageHandler().handleMessage(new Message( // "Cannot access resource for -Xlintfile:"+weaverOption.lintFile, // IMessage.WARNING, // failure, // null)); } } finally { try { resource.close(); } catch (Throwable t) { } } } /* Fourth override with -Xlint */ if (weaverOption.lint != null) { if (weaverOption.lint.equals("default")) {// FIXME should be AjBuildConfig.AJLINT_DEFAULT but yetanother deps.. bcelWorld.getLint().loadDefaultProperties(); } else { bcelWorld.getLint().setAll(weaverOption.lint); if (weaverOption.lint.equals("ignore")) { bcelWorld.setAllLintIgnored(); } } } // TODO proceedOnError option } private void registerAspectExclude(final BcelWeaver weaver, final ClassLoader loader, final List<Definition> definitions) { String fastMatchInfo = null; for (Definition definition : definitions) { for (String exclude : definition.getAspectExcludePatterns()) { TypePattern excludePattern = new PatternParser(exclude).parseTypePattern(); m_aspectExcludeTypePattern.add(excludePattern); fastMatchInfo = looksLikeStartsWith(exclude); if (fastMatchInfo != null) { m_aspectExcludeStartsWith.add(fastMatchInfo); } } } } private void registerAspectInclude(final BcelWeaver weaver, final ClassLoader loader, final List<Definition> definitions) { String fastMatchInfo = null; for (Definition definition : definitions) { for (String include : definition.getAspectIncludePatterns()) { TypePattern includePattern = new PatternParser(include).parseTypePattern(); m_aspectIncludeTypePattern.add(includePattern); fastMatchInfo = looksLikeStartsWith(include); if (fastMatchInfo != null) { m_aspectIncludeStartsWith.add(fastMatchInfo); } } } } protected void lint(String name, String[] infos) { Lint lint = bcelWorld.getLint(); Kind kind = lint.getLintKind(name); kind.signal(infos, null, null); } @Override public String getContextId() { return weavingContext.getId(); } /** * Register the aspect, following include / exclude rules * * @param weaver * @param loader * @param definitions */ private boolean registerAspects(final BcelWeaver weaver, final ClassLoader loader, final List<Definition> definitions) { if (trace.isTraceEnabled()) { trace.enter("registerAspects", this, new Object[] { weaver, loader, definitions }); } boolean success = true; // TODO: the exclude aspect allow to exclude aspect defined upper in the CL hierarchy - is it what we want ?? // if not, review the getResource so that we track which resource is defined by which CL // iterate aspectClassNames // exclude if in any of the exclude list for (Definition definition : definitions) { for (String aspectClassName : definition.getAspectClassNames()) { if (acceptAspect(aspectClassName)) { info("register aspect " + aspectClassName); // System.err.println("? ClassLoaderWeavingAdaptor.registerAspects() aspectName=" + aspectClassName + // ", loader=" + loader + ", bundle=" + weavingContext.getClassLoaderName()); String requiredType = definition.getAspectRequires(aspectClassName); if (requiredType != null) { // This aspect expresses that it requires a type to be around, otherwise it should 'switch off' ((BcelWorld) weaver.getWorld()).addAspectRequires(aspectClassName, requiredType); } String definedScope = definition.getScopeForAspect(aspectClassName); if (definedScope != null) { ((BcelWorld) weaver.getWorld()).addScopedAspect(aspectClassName, definedScope); } // ResolvedType aspect = weaver.addLibraryAspect(aspectClassName); // generate key for SC if (namespace == null) { namespace = new StringBuffer(aspectClassName); } else { namespace = namespace.append(";").append(aspectClassName); } } else { // warn("aspect excluded: " + aspectClassName); lint("aspectExcludedByConfiguration", new String[] { aspectClassName, getClassLoaderName(loader) }); } } } // iterate concreteAspects // exclude if in any of the exclude list - note that the user defined name matters for that to happen for (Definition definition : definitions) { for (Definition.ConcreteAspect concreteAspect : definition.getConcreteAspects()) { if (acceptAspect(concreteAspect.name)) { info("define aspect " + concreteAspect.name); ConcreteAspectCodeGen gen = new ConcreteAspectCodeGen(concreteAspect, weaver.getWorld()); if (!gen.validate()) { error("Concrete-aspect '" + concreteAspect.name + "' could not be registered"); success = false; break; } ((BcelWorld) weaver.getWorld()).addSourceObjectType(Utility.makeJavaClass(concreteAspect.name, gen.getBytes()), true); concreteAspects.add(gen); weaver.addLibraryAspect(concreteAspect.name); // generate key for SC if (namespace == null) { namespace = new StringBuffer(concreteAspect.name); } else { namespace = namespace.append(";" + concreteAspect.name); } } } } /* We couldn't register one or more aspects so disable the adaptor */ if (!success) { warn("failure(s) registering aspects. Disabling weaver for class loader " + getClassLoaderName(loader)); } /* We didn't register any aspects so disable the adaptor */ else if (namespace == null) { success = false; info("no aspects registered. Disabling weaver for class loader " + getClassLoaderName(loader)); } if (trace.isTraceEnabled()) { trace.exit("registerAspects", success); } return success; } private boolean weaveAndDefineConceteAspects() { if (trace.isTraceEnabled()) { trace.enter("weaveAndDefineConceteAspects", this, concreteAspects); } boolean success = true; for (ConcreteAspectCodeGen gen : concreteAspects) { String name = gen.getClassName(); byte[] bytes = gen.getBytes(); try { byte[] newBytes = weaveClass(name, bytes, true); this.generatedClassHandler.acceptClass(name, newBytes); } catch (IOException ex) { trace.error("weaveAndDefineConceteAspects", ex); error("exception weaving aspect '" + name + "'", ex); } } if (trace.isTraceEnabled()) { trace.exit("weaveAndDefineConceteAspects", success); } return success; } /** * Register the include / exclude filters. We duplicate simple patterns in startWith filters that will allow faster matching * without ResolvedType * * @param weaver * @param loader * @param definitions */ private void registerIncludeExclude(final BcelWeaver weaver, final ClassLoader loader, final List<Definition> definitions) { String fastMatchInfo = null; for (Definition definition : definitions) { for (Iterator<String> iterator1 = definition.getIncludePatterns().iterator(); iterator1.hasNext();) { hasIncludes = true; String include = iterator1.next(); fastMatchInfo = looksLikeStartsWith(include); if (fastMatchInfo != null) { m_includeStartsWith.add(fastMatchInfo); } else if (include.equals("*")) { includeStar = true; } else if ((fastMatchInfo = looksLikeExactName(include)) != null) { includeExactName.add(fastMatchInfo); } else { TypePattern includePattern = new PatternParser(include).parseTypePattern(); includeTypePattern.add(includePattern); } } for (Iterator<String> iterator1 = definition.getExcludePatterns().iterator(); iterator1.hasNext();) { hasExcludes = true; String exclude = iterator1.next(); fastMatchInfo = looksLikeStartsWith(exclude); if (fastMatchInfo != null) { excludeStartsWith.add(fastMatchInfo); } else if ((fastMatchInfo = looksLikeStarDotDotStarExclude(exclude)) != null) { excludeStarDotDotStar.add(fastMatchInfo); } else if ((fastMatchInfo = looksLikeExactName(exclude)) != null) { excludeExactName.add(exclude); } else if ((fastMatchInfo = looksLikeEndsWith(exclude)) != null) { excludeEndsWith.add(fastMatchInfo); } else if (exclude .equals("org.codehaus.groovy..* && !org.codehaus.groovy.grails.web.servlet.mvc.SimpleGrailsController*")) { // TODO need a more sophisticated analysis here, to allow for similar situations excludeSpecial.add(new String[] { "org.codehaus.groovy.", "org.codehaus.groovy.grails.web.servlet.mvc.SimpleGrailsController" }); // for the related test: // } else if (exclude.equals("testdata..* && !testdata.sub.Oran*")) { // excludeSpecial.add(new String[] { "testdata.", "testdata.sub.Oran" }); } else { TypePattern excludePattern = new PatternParser(exclude).parseTypePattern(); excludeTypePattern.add(excludePattern); } } } } /** * Checks if the pattern looks like "*..*XXXX*" and if so returns XXXX. This will enable fast name matching of CGLIB exclusion * */ private String looksLikeStarDotDotStarExclude(String typePattern) { if (!typePattern.startsWith("*..*")) { return null; } if (!typePattern.endsWith("*")) { return null; } String subPattern = typePattern.substring(4, typePattern.length() - 1); if (hasStarDot(subPattern, 0)) { return null; } return subPattern.replace('$', '.'); } /** * Checks if the pattern looks like "com.foo.Bar" - an exact name */ private String looksLikeExactName(String typePattern) { if (hasSpaceAnnotationPlus(typePattern, 0) || typePattern.indexOf("*") != -1) { return null; } return typePattern.replace('$', '.'); } /** * Checks if the pattern looks like "*Exception" */ private String looksLikeEndsWith(String typePattern) { if (typePattern.charAt(0) != '*') { return null; } if (hasSpaceAnnotationPlus(typePattern, 1) || hasStarDot(typePattern, 1)) { return null; } return typePattern.substring(1).replace('$', '.'); } /** * Determine if something in the string is going to affect our ability to optimize. Checks for: ' ' '@' '+' */ private boolean hasSpaceAnnotationPlus(String string, int pos) { for (int i = pos, max = string.length(); i < max; i++) { char ch = string.charAt(i); if (ch == ' ' || ch == '@' || ch == '+') { return true; } } return false; } /** * Determine if something in the string is going to affect our ability to optimize. Checks for: '*' '.' */ private boolean hasStarDot(String string, int pos) { for (int i = pos, max = string.length(); i < max; i++) { char ch = string.charAt(i); if (ch == '*' || ch == '.') { return true; } } return false; } /** * Checks if the type pattern looks like "com.foo..*" */ private String looksLikeStartsWith(String typePattern) { if (hasSpaceAnnotationPlus(typePattern, 0) || typePattern.charAt(typePattern.length() - 1) != '*') { return null; } // now must looks like with "charsss..*" or "cha.rss..*" etc // note that "*" and "*..*" won't be fast matched // and that "charsss.*" will not neither int length = typePattern.length(); if (typePattern.endsWith("..*") && length > 3) { if (typePattern.indexOf("..") == length - 3 // no ".." before last sequence && typePattern.indexOf('*') == length - 1) { // no earlier '*' return typePattern.substring(0, length - 2).replace('$', '.'); // "charsss." or "char.rss." etc } } return null; } /** * Register the dump filter * * @param weaver * @param loader * @param definitions */ private void registerDump(final BcelWeaver weaver, final ClassLoader loader, final List<Definition> definitions) { for (Definition definition : definitions) { for (Iterator<String> iterator1 = definition.getDumpPatterns().iterator(); iterator1.hasNext();) { String dump = iterator1.next(); TypePattern pattern = new PatternParser(dump).parseTypePattern(); m_dumpTypePattern.add(pattern); } if (definition.shouldDumpBefore()) { m_dumpBefore = true; } if (definition.createDumpDirPerClassloader()) { dumpDirPerClassloader = true; } } } /** * Determine whether a type should be accepted for weaving, by checking it against any includes/excludes. * * @param className the name of the type to possibly accept * @param bytes the bytecode for the type (in case we need to look inside, eg. annotations) * @return true if it should be accepted for weaving */ @Override protected boolean accept(String className, byte[] bytes) { if (!hasExcludes && !hasIncludes) { return true; } // still try to avoid ResolvedType if we have simple patterns String fastClassName = className.replace('/', '.'); for (String excludeStartsWithString : excludeStartsWith) { if (fastClassName.startsWith(excludeStartsWithString)) { return false; } } // Fast exclusion of patterns like: "*..*CGLIB*" if (!excludeStarDotDotStar.isEmpty()) { for (String namePiece : excludeStarDotDotStar) { int index = fastClassName.lastIndexOf('.'); if (fastClassName.indexOf(namePiece, index + 1) != -1) { return false; } } } fastClassName = fastClassName.replace('$', '.'); if (!excludeEndsWith.isEmpty()) { for (String lastPiece : excludeEndsWith) { if (fastClassName.endsWith(lastPiece)) { return false; } } } // Fast exclusion of exact names if (!excludeExactName.isEmpty()) { for (String name : excludeExactName) { if (fastClassName.equals(name)) { return false; } } } if (!excludeSpecial.isEmpty()) { for (String[] entry : excludeSpecial) { String excludeThese = entry[0]; String exceptThese = entry[1]; if (fastClassName.startsWith(excludeThese) && !fastClassName.startsWith(exceptThese)) { return false; } } } /* * Bug 120363 If we have an exclude pattern that cannot be matched using "starts with" then we cannot fast accept */ boolean didSomeIncludeMatching = false; if (excludeTypePattern.isEmpty()) { if (includeStar) { return true; } if (!includeExactName.isEmpty()) { didSomeIncludeMatching = true; for (String exactname : includeExactName) { if (fastClassName.equals(exactname)) { return true; } } } boolean fastAccept = false;// defaults to false if no fast include for (int i = 0; i < m_includeStartsWith.size(); i++) { didSomeIncludeMatching = true; fastAccept = fastClassName.startsWith(m_includeStartsWith.get(i)); if (fastAccept) { return true; } } // We may have processed all patterns now... check that and return if (includeTypePattern.isEmpty()) { return !didSomeIncludeMatching; } } boolean accept; try { ensureDelegateInitialized(className, bytes); ResolvedType classInfo = delegateForCurrentClass.getResolvedTypeX(); // exclude are "AND"ed for (TypePattern typePattern : excludeTypePattern) { if (typePattern.matchesStatically(classInfo)) { // exclude match - skip return false; } } // include are "OR"ed if (includeStar) { return true; } if (!includeExactName.isEmpty()) { didSomeIncludeMatching = true; for (String exactname : includeExactName) { if (fastClassName.equals(exactname)) { return true; } } } for (int i = 0; i < m_includeStartsWith.size(); i++) { didSomeIncludeMatching = true; boolean fastaccept = fastClassName.startsWith(m_includeStartsWith.get(i)); if (fastaccept) { return true; } } accept = !didSomeIncludeMatching; // only true if no includes at all for (TypePattern typePattern : includeTypePattern) { accept = typePattern.matchesStatically(classInfo); if (accept) { break; } // goes on if this include did not match ("OR"ed) } } finally { this.bcelWorld.demote(); } return accept; } // FIXME we don't use include/exclude of others aop.xml // this can be nice but very dangerous as well to change that private boolean acceptAspect(String aspectClassName) { // avoid ResolvedType if not needed if (m_aspectExcludeTypePattern.isEmpty() && m_aspectIncludeTypePattern.isEmpty()) { return true; } // still try to avoid ResolvedType if we have simple patterns // EXCLUDE: if one match then reject String fastClassName = aspectClassName.replace('/', '.').replace('.', '$'); for (int i = 0; i < m_aspectExcludeStartsWith.size(); i++) { if (fastClassName.startsWith(m_aspectExcludeStartsWith.get(i))) { return false; } } // INCLUDE: if one match then accept for (int i = 0; i < m_aspectIncludeStartsWith.size(); i++) { if (fastClassName.startsWith(m_aspectIncludeStartsWith.get(i))) { return true; } } // needs further analysis ResolvedType classInfo = weaver.getWorld().resolve(UnresolvedType.forName(aspectClassName), true); // exclude are "AND"ed for (Iterator iterator = m_aspectExcludeTypePattern.iterator(); iterator.hasNext();) { TypePattern typePattern = (TypePattern) iterator.next(); if (typePattern.matchesStatically(classInfo)) { // exclude match - skip return false; } } // include are "OR"ed boolean accept = true;// defaults to true if no include for (Iterator iterator = m_aspectIncludeTypePattern.iterator(); iterator.hasNext();) { TypePattern typePattern = (TypePattern) iterator.next(); accept = typePattern.matchesStatically(classInfo); if (accept) { break; } // goes on if this include did not match ("OR"ed) } return accept; } @Override protected boolean shouldDump(String className, boolean before) { // Don't dump before weaving unless asked to if (before && !m_dumpBefore) { return false; } // avoid ResolvedType if not needed if (m_dumpTypePattern.isEmpty()) { return false; } // TODO AV - optimize for className.startWith only ResolvedType classInfo = weaver.getWorld().resolve(UnresolvedType.forName(className), true); // dump for (Iterator iterator = m_dumpTypePattern.iterator(); iterator.hasNext();) { TypePattern typePattern = (TypePattern) iterator.next(); if (typePattern.matchesStatically(classInfo)) { // dump match return true; } } return false; } @Override protected String getDumpDir() { if (dumpDirPerClassloader) { StringBuffer dir = new StringBuffer(); dir.append("_ajdump").append(File.separator).append(weavingContext.getId()); return dir.toString(); } else { return super.getDumpDir(); } } /* * shared classes methods */ /** * @return Returns the key. */ public String getNamespace() { // System.out.println("ClassLoaderWeavingAdaptor.getNamespace() classloader=" + weavingContext.getClassLoaderName() + // ", namespace=" + namespace); if (namespace == null) { return ""; } else { return new String(namespace); } } /** * Check to see if any classes are stored in the generated classes cache. Then flush the cache if it is not empty * * @param className TODO * @return true if a class has been generated and is stored in the cache */ public boolean generatedClassesExistFor(String className) { // System.err.println("? ClassLoaderWeavingAdaptor.generatedClassesExist() classname=" + className + ", size=" + // generatedClasses); if (className == null) { return !generatedClasses.isEmpty(); } else { return generatedClasses.containsKey(className); } } /** * Flush the generated classes cache */ public void flushGeneratedClasses() { // System.err.println("? ClassLoaderWeavingAdaptor.flushGeneratedClasses() generatedClasses=" + generatedClasses); generatedClasses = new HashMap(); } private Method defineClassMethod; private Method defineClassWithProtectionDomainMethod; private void defineClass(ClassLoader loader, String name, byte[] bytes) { if (trace.isTraceEnabled()) { trace.enter("defineClass", this, new Object[] { loader, name, bytes }); } Object clazz = null; debug("generating class '" + name + "'"); try { if (defineClassMethod == null) { defineClassMethod = ClassLoader.class.getDeclaredMethod("defineClass", new Class[] { String.class, bytes.getClass(), int.class, int.class }); } defineClassMethod.setAccessible(true); clazz = defineClassMethod.invoke(loader, new Object[] { name, bytes, new Integer(0), new Integer(bytes.length) }); } catch (InvocationTargetException e) { if (e.getTargetException() instanceof LinkageError) { warn("define generated class failed", e.getTargetException()); // is already defined (happens for X$ajcMightHaveAspect interfaces since aspects are reweaved) // TODO maw I don't think this is OK and } else { warn("define generated class failed", e.getTargetException()); } } catch (Exception e) { warn("define generated class failed", e); } if (trace.isTraceEnabled()) { trace.exit("defineClass", clazz); } } private void defineClass(ClassLoader loader, String name, byte[] bytes, ProtectionDomain protectionDomain) { if (trace.isTraceEnabled()) { trace.enter("defineClass", this, new Object[] { loader, name, bytes, protectionDomain }); } Object clazz = null; debug("generating class '" + name + "'"); try { // System.out.println(">> Defining with protection domain " + name + " pd=" + protectionDomain); if (defineClassWithProtectionDomainMethod == null) { defineClassWithProtectionDomainMethod = ClassLoader.class.getDeclaredMethod("defineClass", new Class[] { String.class, bytes.getClass(), int.class, int.class, ProtectionDomain.class }); } defineClassWithProtectionDomainMethod.setAccessible(true); clazz = defineClassWithProtectionDomainMethod.invoke(loader, new Object[] { name, bytes, Integer.valueOf(0), new Integer(bytes.length), protectionDomain }); } catch (InvocationTargetException e) { if (e.getTargetException() instanceof LinkageError) { warn("define generated class failed", e.getTargetException()); // is already defined (happens for X$ajcMightHaveAspect interfaces since aspects are reweaved) // TODO maw I don't think this is OK and } else { warn("define generated class failed", e.getTargetException()); } } catch (Exception e) { warn("define generated class failed", e); } if (trace.isTraceEnabled()) { trace.exit("defineClass", clazz); } } }
389,967
Bug 389967 Weaved aspects mechanism does not take into account modified classes
The current caching mechanism assumes that if the same class is encountered then its cached weaved version can be used. However, the mechanism uses only the (fully qualified) class name to identify the class and does not take into account the fact that the class bytes may have changed (e.g., the user re-compiled and re-deployed some changes to the same class).
resolved fixed
9a3cc2b
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2012-10-01T20:22:37Z"
"2012-09-20T05:46:40Z"
loadtime/src/org/aspectj/weaver/loadtime/WeavingURLClassLoader.java
/* ******************************************************************* * Copyright (c) 2004 IBM Corporation * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Eclipse Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Matthew Webster, Adrian Colyer, * Martin Lippert initial implementation * Andy Clement * Abraham Nevado * ******************************************************************/ package org.aspectj.weaver.loadtime; import java.io.File; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import java.security.CodeSource; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.StringTokenizer; import org.aspectj.bridge.AbortException; import org.aspectj.weaver.bcel.ExtensibleURLClassLoader; import org.aspectj.weaver.tools.Trace; import org.aspectj.weaver.tools.TraceFactory; import org.aspectj.weaver.tools.WeavingAdaptor; import org.aspectj.weaver.tools.WeavingClassLoader; public class WeavingURLClassLoader extends ExtensibleURLClassLoader implements WeavingClassLoader { public static final String WEAVING_CLASS_PATH = "aj.class.path"; public static final String WEAVING_ASPECT_PATH = "aj.aspect.path"; private URL[] aspectURLs; private WeavingAdaptor adaptor; private boolean initializingAdaptor; private Map generatedClasses = new HashMap(); /* String -> byte[] */ private static Trace trace = TraceFactory.getTraceFactory().getTrace(WeavingURLClassLoader.class); /* * This constructor is needed when using "-Djava.system.class.loader". */ public WeavingURLClassLoader(ClassLoader parent) { this(getURLs(getClassPath()), getURLs(getAspectPath()), parent); // System.out.println("? WeavingURLClassLoader.WeavingURLClassLoader()"); } public WeavingURLClassLoader(URL[] urls, ClassLoader parent) { super(urls, parent); if (trace.isTraceEnabled()) trace.enter("<init>", this, new Object[] { urls, parent }); // System.out.println("WeavingURLClassLoader.WeavingURLClassLoader()"); if (trace.isTraceEnabled()) trace.exit("<init>"); } public WeavingURLClassLoader(URL[] classURLs, URL[] aspectURLs, ClassLoader parent) { super(classURLs, parent); // System.out.println("> WeavingURLClassLoader.WeavingURLClassLoader() classURLs=" + Arrays.asList(classURLs)); this.aspectURLs = aspectURLs; /* * If either we nor our parent is using an ASPECT_PATH use a new-style adaptor */ if (this.aspectURLs.length > 0 || getParent() instanceof WeavingClassLoader) { try { adaptor = new WeavingAdaptor(this); } catch (ExceptionInInitializerError ex) { ex.printStackTrace(System.out); throw ex; } } // System.out.println("< WeavingURLClassLoader.WeavingURLClassLoader() adaptor=" + adaptor); } private static String getAspectPath() { return System.getProperty(WEAVING_ASPECT_PATH, ""); } private static String getClassPath() { return System.getProperty(WEAVING_CLASS_PATH, ""); } private static URL[] getURLs(String path) { List urlList = new ArrayList(); for (StringTokenizer t = new StringTokenizer(path, File.pathSeparator); t.hasMoreTokens();) { File f = new File(t.nextToken().trim()); try { if (f.exists()) { URL url = f.toURL(); if (url != null) urlList.add(url); } } catch (MalformedURLException e) { } } URL[] urls = new URL[urlList.size()]; urlList.toArray(urls); return urls; } protected void addURL(URL url) { if (adaptor == null) { createAdaptor(); } adaptor.addURL(url); super.addURL(url); } /** * Override to weave class using WeavingAdaptor */ protected Class defineClass(String name, byte[] b, CodeSource cs) throws IOException { if (trace.isTraceEnabled()) trace.enter("defineClass", this, new Object[] { name, b, cs }); // System.err.println("? WeavingURLClassLoader.defineClass(" + name + ", [" + b.length + "])"); byte orig[] = b; /* Avoid recursion during adaptor initialization */ if (!initializingAdaptor) { /* Need to defer creation because of possible recursion during constructor execution */ if (adaptor == null && !initializingAdaptor) { createAdaptor(); } try { b = adaptor.weaveClass(name, b, false); } catch (AbortException ex) { trace.error("defineClass", ex); throw ex; } catch (Throwable th) { trace.error("defineClass", th); } } Class clazz; // On error, define the original form of the class and log the issue try { clazz= super.defineClass(name, b, cs); } catch (Throwable th) { trace.error("Weaving class problem. Original class has been returned. The error was caused because of: " + th, th); clazz= super.defineClass(name, orig, cs); } if (trace.isTraceEnabled()) trace.exit("defineClass", clazz); return clazz; } private void createAdaptor() { DefaultWeavingContext weavingContext = new DefaultWeavingContext(this) { /* Ensures consistent LTW messages for testing */ public String getClassLoaderName() { ClassLoader loader = getClassLoader(); return loader.getClass().getName(); } }; ClassLoaderWeavingAdaptor clwAdaptor = new ClassLoaderWeavingAdaptor(); initializingAdaptor = true; clwAdaptor.initialize(this, weavingContext); initializingAdaptor = false; adaptor = clwAdaptor; } /** * Override to find classes generated by WeavingAdaptor */ protected byte[] getBytes(String name) throws IOException { byte[] bytes = super.getBytes(name); if (bytes == null) { // return adaptor.findClass(name); return (byte[]) generatedClasses.remove(name); } return bytes; } /** * Implement method from WeavingClassLoader */ public URL[] getAspectURLs() { return aspectURLs; } public void acceptClass(String name, byte[] bytes) { generatedClasses.put(name, bytes); } // protected synchronized Class loadClass(String name, boolean resolve) throws ClassNotFoundException { // System.err.println("> WeavingURLClassLoader.loadClass() name=" + name); // Class clazz= super.loadClass(name, resolve); // System.err.println("< WeavingURLClassLoader.loadClass() clazz=" + clazz + ", loader=" + clazz.getClassLoader()); // return clazz; // } // private interface ClassPreProcessorAdaptor extends ClassPreProcessor { // public void addURL(URL url); // } // // private class WeavingAdaptorPreProcessor implements ClassPreProcessorAdaptor { // // private WeavingAdaptor adaptor; // // public WeavingAdaptorPreProcessor (WeavingClassLoader wcl) { // adaptor = new WeavingAdaptor(wcl); // } // // public void initialize() { // } // // public byte[] preProcess(String className, byte[] bytes, ClassLoader classLoader) { // return adaptor.weaveClass(className,bytes); // } // // public void addURL(URL url) { // // } // } }
389,967
Bug 389967 Weaved aspects mechanism does not take into account modified classes
The current caching mechanism assumes that if the same class is encountered then its cached weaved version can be used. However, the mechanism uses only the (fully qualified) class name to identify the class and does not take into account the fact that the class bytes may have changed (e.g., the user re-compiled and re-deployed some changes to the same class).
resolved fixed
9a3cc2b
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2012-10-01T20:22:37Z"
"2012-09-20T05:46:40Z"
org.aspectj.matcher/src/org/aspectj/weaver/tools/GeneratedClassHandler.java
/* ******************************************************************* * Copyright (c) 2004 IBM Corporation * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Eclipse Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Matthew Webster, Adrian Colyer, * Martin Lippert initial implementation * ******************************************************************/ package org.aspectj.weaver.tools; /** * Interface implemented by weaving class loaders to allow classes generated by * the weaving process to be defined. */ public interface GeneratedClassHandler { /** * Accept class generated by WeavingAdaptor. The class loader should store * the class definition in its local cache until called upon to load it. * @param name class name * @param bytes class definition */ public void acceptClass (String name, byte[] bytes); }
389,967
Bug 389967 Weaved aspects mechanism does not take into account modified classes
The current caching mechanism assumes that if the same class is encountered then its cached weaved version can be used. However, the mechanism uses only the (fully qualified) class name to identify the class and does not take into account the fact that the class bytes may have changed (e.g., the user re-compiled and re-deployed some changes to the same class).
resolved fixed
9a3cc2b
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2012-10-01T20:22:37Z"
"2012-09-20T05:46:40Z"
util/src/org/aspectj/util/LangUtil.java
/* ******************************************************************* * Copyright (c) 1999-2001 Xerox Corporation, * 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Eclipse Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Xerox/PARC initial implementation * ******************************************************************/ package org.aspectj.util; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.io.PrintWriter; import java.io.StringWriter; import java.lang.reflect.Array; import java.lang.reflect.InvocationTargetException; import java.security.PrivilegedActionException; import java.sql.SQLException; import java.util.ArrayList; import java.util.Arrays; import java.util.BitSet; import java.util.Collection; import java.util.Collections; import java.util.LinkedList; import java.util.List; import java.util.StringTokenizer; /** * */ public class LangUtil { public static final String EOL; private static double vmVersion; static { StringWriter buf = new StringWriter(); PrintWriter writer = new PrintWriter(buf); writer.println(""); String eol = "\n"; try { buf.close(); StringBuffer sb = buf.getBuffer(); if (sb != null) { eol = buf.toString(); } } catch (Throwable t) { } EOL = eol; } static { try { String vm = System.getProperty("java.version"); // JLS 20.18.7 if (vm == null) { vm = System.getProperty("java.runtime.version"); } if (vm == null) { vm = System.getProperty("java.vm.version"); } if (vm == null) { new RuntimeException( "System properties appear damaged, cannot find: java.version/java.runtime.version/java.vm.version") .printStackTrace(System.err); vmVersion = 1.5; } else { try { String versionString = vm.substring(0, 3); Double temp = new Double(Double.parseDouble(versionString)); vmVersion = temp.floatValue(); } catch (Exception e) { vmVersion = 1.4; } } } catch (Throwable t) { new RuntimeException( "System properties appear damaged, cannot find: java.version/java.runtime.version/java.vm.version", t) .printStackTrace(System.err); vmVersion = 1.5; } } public static boolean is13VMOrGreater() { return 1.3 <= vmVersion; } public static boolean is14VMOrGreater() { return 1.4 <= vmVersion; } public static boolean is15VMOrGreater() { return 1.5 <= vmVersion; } public static boolean is16VMOrGreater() { return 1.6 <= vmVersion; } public static boolean is17VMOrGreater() { return 1.7 <= vmVersion; } /** * Shorthand for "if null, throw IllegalArgumentException" * * @throws IllegalArgumentException "null {name}" if o is null */ public static final void throwIaxIfNull(final Object o, final String name) { if (null == o) { String message = "null " + (null == name ? "input" : name); throw new IllegalArgumentException(message); } } /** * Shorthand for "if not null or not assignable, throw IllegalArgumentException" * * @param c the Class to check - use null to ignore type check * @throws IllegalArgumentException "null {name}" if o is null */ public static final void throwIaxIfNotAssignable(final Object ra[], final Class<?> c, final String name) { throwIaxIfNull(ra, name); String label = (null == name ? "input" : name); for (int i = 0; i < ra.length; i++) { if (null == ra[i]) { String m = " null " + label + "[" + i + "]"; throw new IllegalArgumentException(m); } else if (null != c) { Class<?> actualClass = ra[i].getClass(); if (!c.isAssignableFrom(actualClass)) { String message = label + " not assignable to " + c.getName(); throw new IllegalArgumentException(message); } } } } /** * Shorthand for "if not null or not assignable, throw IllegalArgumentException" * * @throws IllegalArgumentException "null {name}" if o is null */ public static final void throwIaxIfNotAssignable(final Object o, final Class<?> c, final String name) { throwIaxIfNull(o, name); if (null != c) { Class<?> actualClass = o.getClass(); if (!c.isAssignableFrom(actualClass)) { String message = name + " not assignable to " + c.getName(); throw new IllegalArgumentException(message); } } } // /** // * Shorthand for // "if any not null or not assignable, throw IllegalArgumentException" // * @throws IllegalArgumentException "{name} is not assignable to {c}" // */ // public static final void throwIaxIfNotAllAssignable(final Collection // collection, // final Class c, final String name) { // throwIaxIfNull(collection, name); // if (null != c) { // for (Iterator iter = collection.iterator(); iter.hasNext();) { // throwIaxIfNotAssignable(iter.next(), c, name); // // } // } // } /** * Shorthand for "if false, throw IllegalArgumentException" * * @throws IllegalArgumentException "{message}" if test is false */ public static final void throwIaxIfFalse(final boolean test, final String message) { if (!test) { throw new IllegalArgumentException(message); } } // /** @return ((null == s) || (0 == s.trim().length())); */ // public static boolean isEmptyTrimmed(String s) { // return ((null == s) || (0 == s.length()) // || (0 == s.trim().length())); // } /** @return ((null == s) || (0 == s.length())); */ public static boolean isEmpty(String s) { return ((null == s) || (0 == s.length())); } /** @return ((null == ra) || (0 == ra.length)) */ public static boolean isEmpty(Object[] ra) { return ((null == ra) || (0 == ra.length)); } /** @return ((null == collection) || (0 == collection.size())) */ public static boolean isEmpty(Collection<?> collection) { return ((null == collection) || (0 == collection.size())); } /** * Splits <code>text</code> at whitespace. * * @param text <code>String</code> to split. */ public static String[] split(String text) { return (String[]) strings(text).toArray(new String[0]); } /** * Splits <code>input</code> at commas, trimming any white space. * * @param input <code>String</code> to split. * @return List of String of elements. */ public static List<String> commaSplit(String input) { return anySplit(input, ","); } /** * Split string as classpath, delimited at File.pathSeparator. Entries are not trimmed, but empty entries are ignored. * * @param classpath the String to split - may be null or empty * @return String[] of classpath entries */ public static String[] splitClasspath(String classpath) { if (LangUtil.isEmpty(classpath)) { return new String[0]; } StringTokenizer st = new StringTokenizer(classpath, File.pathSeparator); ArrayList<String> result = new ArrayList<String>(st.countTokens()); while (st.hasMoreTokens()) { String entry = st.nextToken(); if (!LangUtil.isEmpty(entry)) { result.add(entry); } } return (String[]) result.toArray(new String[0]); } /** * Get System property as boolean, but use default value where the system property is not set. * * @return true if value is set to true, false otherwise */ public static boolean getBoolean(String propertyName, boolean defaultValue) { if (null != propertyName) { try { String value = System.getProperty(propertyName); if (null != value) { return Boolean.valueOf(value).booleanValue(); } } catch (Throwable t) { // default below } } return defaultValue; } /** * Splits <code>input</code>, removing delimiter and trimming any white space. Returns an empty collection if the input is null. * If delimiter is null or empty or if the input contains no delimiters, the input itself is returned after trimming white * space. * * @param input <code>String</code> to split. * @param delim <code>String</code> separators for input. * @return List of String of elements. */ public static List<String> anySplit(String input, String delim) { if (null == input) { return Collections.emptyList(); } ArrayList<String> result = new ArrayList<String>(); if (LangUtil.isEmpty(delim) || (-1 == input.indexOf(delim))) { result.add(input.trim()); } else { StringTokenizer st = new StringTokenizer(input, delim); while (st.hasMoreTokens()) { result.add(st.nextToken().trim()); } } return result; } /** * Splits strings into a <code>List</code> using a <code>StringTokenizer</code>. * * @param text <code>String</code> to split. */ public static List<String> strings(String text) { if (LangUtil.isEmpty(text)) { return Collections.emptyList(); } List<String> strings = new ArrayList<String>(); StringTokenizer tok = new StringTokenizer(text); while (tok.hasMoreTokens()) { strings.add(tok.nextToken()); } return strings; } /** @return a non-null unmodifiable List */ public static <T> List<T> safeList(List<T> list) { return (null == list ? Collections.<T>emptyList() : Collections.unmodifiableList(list)); } // /** // * Select from input String[] based on suffix-matching // * @param inputs String[] of input - null ignored // * @param suffixes String[] of suffix selectors - null ignored // * @param ignoreCase if true, ignore case // * @return String[] of input that end with any input // */ // public static String[] endsWith(String[] inputs, String[] suffixes, // boolean ignoreCase) { // if (LangUtil.isEmpty(inputs) || LangUtil.isEmpty(suffixes)) { // return new String[0]; // } // if (ignoreCase) { // String[] temp = new String[suffixes.length]; // for (int i = 0; i < temp.length; i++) { // String suff = suffixes[i]; // temp[i] = (null == suff ? null : suff.toLowerCase()); // } // suffixes = temp; // } // ArrayList result = new ArrayList(); // for (int i = 0; i < inputs.length; i++) { // String input = inputs[i]; // if (null == input) { // continue; // } // if (!ignoreCase) { // input = input.toLowerCase(); // } // for (int j = 0; j < suffixes.length; j++) { // String suffix = suffixes[j]; // if (null == suffix) { // continue; // } // if (input.endsWith(suffix)) { // result.add(input); // break; // } // } // } // return (String[]) result.toArray(new String[0]); // } // // /** // * Select from input String[] if readable directories // * @param inputs String[] of input - null ignored // * @param baseDir the base directory of the input // * @return String[] of input that end with any input // */ // public static String[] selectDirectories(String[] inputs, File baseDir) { // if (LangUtil.isEmpty(inputs)) { // return new String[0]; // } // ArrayList result = new ArrayList(); // for (int i = 0; i < inputs.length; i++) { // String input = inputs[i]; // if (null == input) { // continue; // } // File inputFile = new File(baseDir, input); // if (inputFile.canRead() && inputFile.isDirectory()) { // result.add(input); // } // } // return (String[]) result.toArray(new String[0]); // } /** * copy non-null two-dimensional String[][] * * @see extractOptions(String[], String[][]) */ public static String[][] copyStrings(String[][] in) { String[][] out = new String[in.length][]; for (int i = 0; i < out.length; i++) { out[i] = new String[in[i].length]; System.arraycopy(in[i], 0, out[i], 0, out[i].length); } return out; } /** * Extract options and arguments to input option list, returning remainder. The input options will be nullified if not found. * e.g., * * <pre> * String[] options = new String[][] { new String[] { &quot;-verbose&quot; }, new String[] { &quot;-classpath&quot;, null } }; * String[] args = extractOptions(args, options); * boolean verbose = null != options[0][0]; * boolean classpath = options[1][1]; * </pre> * * @param args the String[] input options * @param options the String[][]options to find in the input args - not null for each String[] component the first subcomponent * is the option itself, and there is one String subcomponent for each additional argument. * @return String[] of args remaining after extracting options to extracted */ public static String[] extractOptions(String[] args, String[][] options) { if (LangUtil.isEmpty(args) || LangUtil.isEmpty(options)) { return args; } BitSet foundSet = new BitSet(); String[] result = new String[args.length]; int resultIndex = 0; for (int j = 0; j < args.length; j++) { boolean found = false; for (int i = 0; !found && (i < options.length); i++) { String[] option = options[i]; LangUtil.throwIaxIfFalse(!LangUtil.isEmpty(option), "options"); String sought = option[0]; found = sought.equals(args[j]); if (found) { foundSet.set(i); int doMore = option.length - 1; if (0 < doMore) { final int MAX = j + doMore; if (MAX >= args.length) { String s = "expecting " + doMore + " args after "; throw new IllegalArgumentException(s + args[j]); } for (int k = 1; k < option.length; k++) { option[k] = args[++j]; } } } } if (!found) { result[resultIndex++] = args[j]; } } // unset any not found for (int i = 0; i < options.length; i++) { if (!foundSet.get(i)) { options[i][0] = null; } } // fixup remainder if (resultIndex < args.length) { String[] temp = new String[resultIndex]; System.arraycopy(result, 0, temp, 0, resultIndex); args = temp; } return args; } // // /** // * Extract options and arguments to input parameter list, returning // remainder. // * @param args the String[] input options // * @param validOptions the String[] options to find in the input args - // not null // * @param optionArgs the int[] number of arguments for each option in // validOptions // * (if null, then no arguments for any option) // * @param extracted the List for the matched options // * @return String[] of args remaining after extracting options to // extracted // */ // public static String[] extractOptions(String[] args, String[] // validOptions, // int[] optionArgs, List extracted) { // if (LangUtil.isEmpty(args) // || LangUtil.isEmpty(validOptions) ) { // return args; // } // if (null != optionArgs) { // if (optionArgs.length != validOptions.length) { // throw new IllegalArgumentException("args must match options"); // } // } // String[] result = new String[args.length]; // int resultIndex = 0; // for (int j = 0; j < args.length; j++) { // boolean found = false; // for (int i = 0; !found && (i < validOptions.length); i++) { // String sought = validOptions[i]; // int doMore = (null == optionArgs ? 0 : optionArgs[i]); // if (LangUtil.isEmpty(sought)) { // continue; // } // found = sought.equals(args[j]); // if (found) { // if (null != extracted) { // extracted.add(sought); // } // if (0 < doMore) { // final int MAX = j + doMore; // if (MAX >= args.length) { // String s = "expecting " + doMore + " args after "; // throw new IllegalArgumentException(s + args[j]); // } // if (null != extracted) { // while (j < MAX) { // extracted.add(args[++j]); // } // } else { // j = MAX; // } // } // break; // } // } // if (!found) { // result[resultIndex++] = args[j]; // } // } // if (resultIndex < args.length) { // String[] temp = new String[resultIndex]; // System.arraycopy(result, 0, temp, 0, resultIndex); // args = temp; // } // return args; // } // /** @return String[] of entries in validOptions found in args */ // public static String[] selectOptions(String[] args, String[] // validOptions) { // if (LangUtil.isEmpty(args) || LangUtil.isEmpty(validOptions)) { // return new String[0]; // } // ArrayList result = new ArrayList(); // for (int i = 0; i < validOptions.length; i++) { // String sought = validOptions[i]; // if (LangUtil.isEmpty(sought)) { // continue; // } // for (int j = 0; j < args.length; j++) { // if (sought.equals(args[j])) { // result.add(sought); // break; // } // } // } // return (String[]) result.toArray(new String[0]); // } // /** @return String[] of entries in validOptions found in args */ // public static String[] selectOptions(List args, String[] validOptions) { // if (LangUtil.isEmpty(args) || LangUtil.isEmpty(validOptions)) { // return new String[0]; // } // ArrayList result = new ArrayList(); // for (int i = 0; i < validOptions.length; i++) { // String sought = validOptions[i]; // if (LangUtil.isEmpty(sought)) { // continue; // } // for (Iterator iter = args.iterator(); iter.hasNext();) { // String arg = (String) iter.next(); // if (sought.equals(arg)) { // result.add(sought); // break; // } // } // } // return (String[]) result.toArray(new String[0]); // } // /** // * Generate variants of String[] options by creating an extra set for // * each option that ends with "-". If none end with "-", then an // * array equal to <code>new String[][] { options }</code> is returned; // * if one ends with "-", then two sets are returned, // * three causes eight sets, etc. // * @return String[][] with each option set. // * @throws IllegalArgumentException if any option is null or empty. // */ // public static String[][] optionVariants(String[] options) { // if ((null == options) || (0 == options.length)) { // return new String[][] { new String[0]}; // } // // be nice, don't stomp input // String[] temp = new String[options.length]; // System.arraycopy(options, 0, temp, 0, temp.length); // options = temp; // boolean[] dup = new boolean[options.length]; // int numDups = 0; // // for (int i = 0; i < options.length; i++) { // String option = options[i]; // if (LangUtil.isEmpty(option)) { // throw new IllegalArgumentException("empty option at " + i); // } // if (option.endsWith("-")) { // options[i] = option.substring(0, option.length()-1); // dup[i] = true; // numDups++; // } // } // final String[] NONE = new String[0]; // final int variants = exp(2, numDups); // final String[][] result = new String[variants][]; // // variant is a bitmap wrt doing extra value when dup[k]=true // for (int variant = 0; variant < variants; variant++) { // ArrayList next = new ArrayList(); // int nextOption = 0; // for (int k = 0; k < options.length; k++) { // if (!dup[k] || (0 != (variant & (1 << (nextOption++))))) { // next.add(options[k]); // } // } // result[variant] = (String[]) next.toArray(NONE); // } // return result; // } // // private static int exp(int base, int power) { // not in Math? // if (0 > power) { // throw new IllegalArgumentException("negative power: " + power); // } // int result = 1; // while (0 < power--) { // result *= base; // } // return result; // } // /** // * Make a copy of the array. // * @return an array with the same component type as source // * containing same elements, even if null. // * @throws IllegalArgumentException if source is null // */ // public static final Object[] copy(Object[] source) { // LangUtil.throwIaxIfNull(source, "source"); // final Class c = source.getClass().getComponentType(); // Object[] result = (Object[]) Array.newInstance(c, source.length); // System.arraycopy(source, 0, result, 0, result.length); // return result; // } /** * Convert arrays safely. The number of elements in the result will be 1 smaller for each element that is null or not * assignable. This will use sink if it has exactly the right size. The result will always have the same component type as sink. * * @return an array with the same component type as sink containing any assignable elements in source (in the same order). * @throws IllegalArgumentException if either is null */ public static Object[] safeCopy(Object[] source, Object[] sink) { final Class<?> sinkType = (null == sink ? Object.class : sink.getClass().getComponentType()); final int sourceLength = (null == source ? 0 : source.length); final int sinkLength = (null == sink ? 0 : sink.length); final int resultSize; ArrayList<Object> result = null; if (0 == sourceLength) { resultSize = 0; } else { result = new ArrayList<Object>(sourceLength); for (int i = 0; i < sourceLength; i++) { if ((null != source[i]) && (sinkType.isAssignableFrom(source[i].getClass()))) { result.add(source[i]); } } resultSize = result.size(); } if (resultSize != sinkLength) { sink = (Object[]) Array.newInstance(sinkType, result.size()); } if (0 < resultSize) { sink = result.toArray(sink); } return sink; } /** * @return a String with the unqualified class name of the class (or "null") */ public static String unqualifiedClassName(Class<?> c) { if (null == c) { return "null"; } String name = c.getName(); int loc = name.lastIndexOf("."); if (-1 != loc) { name = name.substring(1 + loc); } return name; } /** * @return a String with the unqualified class name of the object (or "null") */ public static String unqualifiedClassName(Object o) { return LangUtil.unqualifiedClassName(null == o ? null : o.getClass()); } /** inefficient way to replace all instances of sought with replace */ public static String replace(String in, String sought, String replace) { if (LangUtil.isEmpty(in) || LangUtil.isEmpty(sought)) { return in; } StringBuffer result = new StringBuffer(); final int len = sought.length(); int start = 0; int loc; while (-1 != (loc = in.indexOf(sought, start))) { result.append(in.substring(start, loc)); if (!LangUtil.isEmpty(replace)) { result.append(replace); } start = loc + len; } result.append(in.substring(start)); return result.toString(); } /** render i right-justified with a given width less than about 40 */ public static String toSizedString(long i, int width) { String result = "" + i; int size = result.length(); if (width > size) { final String pad = " "; final int padLength = pad.length(); if (width > padLength) { width = padLength; } int topad = width - size; result = pad.substring(0, topad) + result; } return result; } // /** clip StringBuffer to maximum number of lines */ // static String clipBuffer(StringBuffer buffer, int maxLines) { // if ((null == buffer) || (1 > buffer.length())) return ""; // StringBuffer result = new StringBuffer(); // int j = 0; // final int MAX = maxLines; // final int N = buffer.length(); // for (int i = 0, srcBegin = 0; i < MAX; srcBegin += j) { // // todo: replace with String variant if/since getting char? // char[] chars = new char[128]; // int srcEnd = srcBegin+chars.length; // if (srcEnd >= N) { // srcEnd = N-1; // } // if (srcBegin == srcEnd) break; // //log("srcBegin:" + srcBegin + ":srcEnd:" + srcEnd); // buffer.getChars(srcBegin, srcEnd, chars, 0); // for (j = 0; j < srcEnd-srcBegin/*chars.length*/; j++) { // char c = chars[j]; // if (c == '\n') { // i++; // j++; // break; // } // } // try { result.append(chars, 0, j); } // catch (Throwable t) { } // } // return result.toString(); // } /** * @return "({UnqualifiedExceptionClass}) {message}" */ public static String renderExceptionShort(Throwable e) { if (null == e) { return "(Throwable) null"; } return "(" + LangUtil.unqualifiedClassName(e) + ") " + e.getMessage(); } /** * Renders exception <code>t</code> after unwrapping and eliding any test packages. * * @param t <code>Throwable</code> to print. * @see #maxStackTrace */ public static String renderException(Throwable t) { return renderException(t, true); } /** * Renders exception <code>t</code>, unwrapping, optionally eliding and limiting total number of lines. * * @param t <code>Throwable</code> to print. * @param elide true to limit to 100 lines and elide test packages * @see StringChecker#TEST_PACKAGES */ public static String renderException(Throwable t, boolean elide) { if (null == t) { return "null throwable"; } t = unwrapException(t); StringBuffer stack = stackToString(t, false); if (elide) { elideEndingLines(StringChecker.TEST_PACKAGES, stack, 100); } return stack.toString(); } /** * Trim ending lines from a StringBuffer, clipping to maxLines and further removing any number of trailing lines accepted by * checker. * * @param checker returns true if trailing line should be elided. * @param stack StringBuffer with lines to elide * @param maxLines int for maximum number of resulting lines */ static void elideEndingLines(StringChecker checker, StringBuffer stack, int maxLines) { if (null == checker || (null == stack) || (0 == stack.length())) { return; } final LinkedList<String> lines = new LinkedList<String>(); StringTokenizer st = new StringTokenizer(stack.toString(), "\n\r"); while (st.hasMoreTokens() && (0 < --maxLines)) { lines.add(st.nextToken()); } st = null; String line; int elided = 0; while (!lines.isEmpty()) { line = (String) lines.getLast(); if (!checker.acceptString(line)) { break; } else { elided++; lines.removeLast(); } } if ((elided > 0) || (maxLines < 1)) { final int EOL_LEN = EOL.length(); int totalLength = 0; while (!lines.isEmpty()) { totalLength += EOL_LEN + ((String) lines.getFirst()).length(); lines.removeFirst(); } if (stack.length() > totalLength) { stack.setLength(totalLength); if (elided > 0) { stack.append(" (... " + elided + " lines...)"); } } } } /** Dump message and stack to StringBuffer. */ public static StringBuffer stackToString(Throwable throwable, boolean skipMessage) { if (null == throwable) { return new StringBuffer(); } StringWriter buf = new StringWriter(); PrintWriter writer = new PrintWriter(buf); if (!skipMessage) { writer.println(throwable.getMessage()); } throwable.printStackTrace(writer); try { buf.close(); } catch (IOException ioe) { } // ignored return buf.getBuffer(); } /** @return Throwable input or tail of any wrapped exception chain */ public static Throwable unwrapException(Throwable t) { Throwable current = t; Throwable next = null; while (current != null) { // Java 1.2 exceptions that carry exceptions if (current instanceof InvocationTargetException) { next = ((InvocationTargetException) current).getTargetException(); } else if (current instanceof ClassNotFoundException) { next = ((ClassNotFoundException) current).getException(); } else if (current instanceof ExceptionInInitializerError) { next = ((ExceptionInInitializerError) current).getException(); } else if (current instanceof PrivilegedActionException) { next = ((PrivilegedActionException) current).getException(); } else if (current instanceof SQLException) { next = ((SQLException) current).getNextException(); } // ...getException(): // javax.naming.event.NamingExceptionEvent // javax.naming.ldap.UnsolicitedNotification // javax.xml.parsers.FactoryConfigurationError // javax.xml.transform.TransformerFactoryConfigurationError // javax.xml.transform.TransformerException // org.xml.sax.SAXException // 1.4: Throwable.getCause // java.util.logging.LogRecord.getThrown() if (null == next) { break; } else { current = next; next = null; } } return current; } /** * Replacement for Arrays.asList(..) which gacks on null and returns a List in which remove is an unsupported operation. * * @param array the Object[] to convert (may be null) * @return the List corresponding to array (never null) */ public static List<Object> arrayAsList(Object[] array) { if ((null == array) || (1 > array.length)) { return Collections.emptyList(); } ArrayList<Object> list = new ArrayList<Object>(); list.addAll(Arrays.asList(array)); return list; } /** check if input contains any packages to elide. */ public static class StringChecker { static StringChecker TEST_PACKAGES = new StringChecker(new String[] { "org.aspectj.testing", "org.eclipse.jdt.internal.junit", "junit.framework.", "org.apache.tools.ant.taskdefs.optional.junit.JUnitTestRunner" }); String[] infixes; /** @param infixes adopted */ StringChecker(String[] infixes) { this.infixes = infixes; } /** @return true if input contains infixes */ public boolean acceptString(String input) { boolean result = false; if (!LangUtil.isEmpty(input)) { for (int i = 0; !result && (i < infixes.length); i++) { result = (-1 != input.indexOf(infixes[i])); } } return result; } } /** * Gen classpath. * * @param bootclasspath * @param classpath * @param classesDir * @param outputJar * @return String combining classpath elements */ public static String makeClasspath( // XXX dumb implementation String bootclasspath, String classpath, String classesDir, String outputJar) { StringBuffer sb = new StringBuffer(); addIfNotEmpty(bootclasspath, sb, File.pathSeparator); addIfNotEmpty(classpath, sb, File.pathSeparator); if (!addIfNotEmpty(classesDir, sb, File.pathSeparator)) { addIfNotEmpty(outputJar, sb, File.pathSeparator); } return sb.toString(); } /** * @param input ignored if null * @param sink the StringBuffer to add input to - return false if null * @param delimiter the String to append to input when added - ignored if empty * @return true if input + delimiter added to sink */ private static boolean addIfNotEmpty(String input, StringBuffer sink, String delimiter) { if (LangUtil.isEmpty(input) || (null == sink)) { return false; } sink.append(input); if (!LangUtil.isEmpty(delimiter)) { sink.append(delimiter); } return true; } /** * Create or initialize a process controller to run a process in another VM asynchronously. * * @param controller the ProcessController to initialize, if not null * @param classpath * @param mainClass * @param args * @return initialized ProcessController */ public static ProcessController makeProcess(ProcessController controller, String classpath, String mainClass, String[] args) { File java = LangUtil.getJavaExecutable(); ArrayList<String> cmd = new ArrayList<String>(); cmd.add(java.getAbsolutePath()); cmd.add("-classpath"); cmd.add(classpath); cmd.add(mainClass); if (!LangUtil.isEmpty(args)) { cmd.addAll(Arrays.asList(args)); } String[] command = (String[]) cmd.toArray(new String[0]); if (null == controller) { controller = new ProcessController(); } controller.init(command, mainClass); return controller; } // /** // * Create a process to run asynchronously. // * @param controller if not null, initialize this one // * @param command the String[] command to run // * @param controller the ProcessControl for streams and results // */ // public static ProcessController makeProcess( // not needed? // ProcessController controller, // String[] command, // String label) { // if (null == controller) { // controller = new ProcessController(); // } // controller.init(command, label); // return controller; // } /** * Find java executable File path from java.home system property. * * @return File associated with the java command, or null if not found. */ public static File getJavaExecutable() { String javaHome = null; File result = null; // java.home // java.class.path // java.ext.dirs try { javaHome = System.getProperty("java.home"); } catch (Throwable t) { // ignore } if (null != javaHome) { File binDir = new File(javaHome, "bin"); if (binDir.isDirectory() && binDir.canRead()) { String[] execs = new String[] { "java", "java.exe" }; for (int i = 0; i < execs.length; i++) { result = new File(binDir, execs[i]); if (result.canRead()) { break; } } } } return result; } // /** // * Sleep for a particular period (in milliseconds). // * // * @param time the long time in milliseconds to sleep // * @return true if delay succeeded, false if interrupted 100 times // */ // public static boolean sleep(long milliseconds) { // if (milliseconds == 0) { // return true; // } else if (milliseconds < 0) { // throw new IllegalArgumentException("negative: " + milliseconds); // } // return sleepUntil(milliseconds + System.currentTimeMillis()); // } /** * Sleep until a particular time. * * @param time the long time in milliseconds to sleep until * @return true if delay succeeded, false if interrupted 100 times */ public static boolean sleepUntil(long time) { if (time == 0) { return true; } else if (time < 0) { throw new IllegalArgumentException("negative: " + time); } // final Thread thread = Thread.currentThread(); long curTime = System.currentTimeMillis(); for (int i = 0; (i < 100) && (curTime < time); i++) { try { Thread.sleep(time - curTime); } catch (InterruptedException e) { // ignore } curTime = System.currentTimeMillis(); } return (curTime >= time); } /** * Handle an external process asynchrously. <code>start()</code> launches a main thread to wait for the process and pipes * streams (in child threads) through to the corresponding streams (e.g., the process System.err to this System.err). This can * complete normally, by exception, or on demand by a client. Clients can implement <code>doCompleting(..)</code> to get notice * when the process completes. * <p> * The following sample code creates a process with a completion callback starts it, and some time later retries the process. * * <pre> * LangUtil.ProcessController controller = new LangUtil.ProcessController() { * protected void doCompleting(LangUtil.ProcessController.Thrown thrown, int result) { * // signal result * } * }; * controller.init(new String[] { &quot;java&quot;, &quot;-version&quot; }, &quot;java version&quot;); * controller.start(); * // some time later... * // retry... * if (!controller.completed()) { * controller.stop(); * controller.reinit(); * controller.start(); * } * </pre> * * <u>warning</u>: Currently this does not close the input or output streams, since doing so prevents their use later. */ public static class ProcessController { /* * XXX not verified thread-safe, but should be. Known problems: - user stops (completed = true) then exception thrown from * destroying process (stop() expects !completed) ... */ private String[] command; private String[] envp; private String label; private boolean init; private boolean started; private boolean completed; /** if true, stopped by user when not completed */ private boolean userStopped; private Process process; private FileUtil.Pipe errStream; private FileUtil.Pipe outStream; private FileUtil.Pipe inStream; private ByteArrayOutputStream errSnoop; private ByteArrayOutputStream outSnoop; private int result; private Thrown thrown; public ProcessController() { } /** * Permit re-running using the same command if this is not started or if completed. Can also call this when done with * results to release references associated with results (e.g., stack traces). */ public final void reinit() { if (!init) { throw new IllegalStateException("must init(..) before reinit()"); } if (started && !completed) { throw new IllegalStateException("not completed - do stop()"); } // init everything but command and label started = false; completed = false; result = Integer.MIN_VALUE; thrown = null; process = null; errStream = null; outStream = null; inStream = null; } public final void init(String classpath, String mainClass, String[] args) { init(LangUtil.getJavaExecutable(), classpath, mainClass, args); } public final void init(File java, String classpath, String mainClass, String[] args) { LangUtil.throwIaxIfNull(java, "java"); LangUtil.throwIaxIfNull(mainClass, "mainClass"); LangUtil.throwIaxIfNull(args, "args"); ArrayList<String> cmd = new ArrayList<String>(); cmd.add(java.getAbsolutePath()); cmd.add("-classpath"); cmd.add(classpath); cmd.add(mainClass); if (!LangUtil.isEmpty(args)) { cmd.addAll(Arrays.asList(args)); } init((String[]) cmd.toArray(new String[0]), mainClass); } public final void init(String[] command, String label) { this.command = (String[]) LangUtil.safeCopy(command, new String[0]); if (1 > this.command.length) { throw new IllegalArgumentException("empty command"); } this.label = LangUtil.isEmpty(label) ? command[0] : label; init = true; reinit(); } public final void setEnvp(String[] envp) { this.envp = (String[]) LangUtil.safeCopy(envp, new String[0]); if (1 > this.envp.length) { throw new IllegalArgumentException("empty envp"); } } public final void setErrSnoop(ByteArrayOutputStream snoop) { errSnoop = snoop; if (null != errStream) { errStream.setSnoop(errSnoop); } } public final void setOutSnoop(ByteArrayOutputStream snoop) { outSnoop = snoop; if (null != outStream) { outStream.setSnoop(outSnoop); } } /** * Start running the process and pipes asynchronously. * * @return Thread started or null if unable to start thread (results available via <code>getThrown()</code>, etc.) */ public final Thread start() { if (!init) { throw new IllegalStateException("not initialized"); } synchronized (this) { if (started) { throw new IllegalStateException("already started"); } started = true; } try { process = Runtime.getRuntime().exec(command); } catch (IOException e) { stop(e, Integer.MIN_VALUE); return null; } errStream = new FileUtil.Pipe(process.getErrorStream(), System.err); if (null != errSnoop) { errStream.setSnoop(errSnoop); } outStream = new FileUtil.Pipe(process.getInputStream(), System.out); if (null != outSnoop) { outStream.setSnoop(outSnoop); } inStream = new FileUtil.Pipe(System.in, process.getOutputStream()); // start 4 threads, process & pipes for in, err, out Runnable processRunner = new Runnable() { public void run() { Throwable thrown = null; int result = Integer.MIN_VALUE; try { // pipe threads are children new Thread(errStream).start(); new Thread(outStream).start(); new Thread(inStream).start(); process.waitFor(); result = process.exitValue(); } catch (Throwable e) { thrown = e; } finally { stop(thrown, result); } } }; Thread result = new Thread(processRunner, label); result.start(); return result; } /** * Destroy any process, stop any pipes. This waits for the pipes to clear (reading until no more input is available), but * does not wait for the input stream for the pipe to close (i.e., not waiting for end-of-file on input stream). */ public final synchronized void stop() { if (completed) { return; } userStopped = true; stop(null, Integer.MIN_VALUE); } public final String[] getCommand() { String[] toCopy = command; if (LangUtil.isEmpty(toCopy)) { return new String[0]; } String[] result = new String[toCopy.length]; System.arraycopy(toCopy, 0, result, 0, result.length); return result; } public final boolean completed() { return completed; } public final boolean started() { return started; } public final boolean userStopped() { return userStopped; } /** * Get any Throwable thrown. Note that the process can complete normally (with a valid return value), at the same time the * pipes throw exceptions, and that this may return some exceptions even if the process is not complete. * * @return null if not complete or Thrown containing exceptions thrown by the process and streams. */ public final Thrown getThrown() { // cache this return makeThrown(null); } public final int getResult() { return result; } /** * Subclasses implement this to get synchronous notice of completion. All pipes and processes should be complete at this * time. To get the exceptions thrown for the pipes, use <code>getThrown()</code>. If there is an exception, the process * completed abruptly (including side-effects of the user halting the process). If <code>userStopped()</code> is true, then * some client asked that the process be destroyed using <code>stop()</code>. Otherwise, the result code should be the * result value returned by the process. * * @param thrown same as <code>getThrown().fromProcess</code>. * @param result same as <code>getResult()</code> * @see getThrown() * @see getResult() * @see stop() */ protected void doCompleting(Thrown thrown, int result) { } /** * Handle termination (on-demand, abrupt, or normal) by destroying and/or halting process and pipes. * * @param thrown ignored if null * @param result ignored if Integer.MIN_VALUE */ private final synchronized void stop(Throwable thrown, int result) { if (completed) { throw new IllegalStateException("already completed"); } else if (null != this.thrown) { throw new IllegalStateException("already set thrown: " + thrown); } // assert null == this.thrown this.thrown = makeThrown(thrown); if (null != process) { process.destroy(); } if (null != inStream) { inStream.halt(false, true); // this will block if waiting inStream = null; } if (null != outStream) { outStream.halt(true, true); outStream = null; } if (null != errStream) { errStream.halt(true, true); errStream = null; } if (Integer.MIN_VALUE != result) { this.result = result; } completed = true; doCompleting(this.thrown, result); } /** * Create snapshot of Throwable's thrown. * * @param thrown ignored if null or if this.thrown is not null */ private final synchronized Thrown makeThrown(Throwable processThrown) { if (null != thrown) { return thrown; } return new Thrown(processThrown, (null == outStream ? null : outStream.getThrown()), (null == errStream ? null : errStream.getThrown()), (null == inStream ? null : inStream.getThrown())); } public static class Thrown { public final Throwable fromProcess; public final Throwable fromErrPipe; public final Throwable fromOutPipe; public final Throwable fromInPipe; /** true only if some Throwable is not null */ public final boolean thrown; private Thrown(Throwable fromProcess, Throwable fromOutPipe, Throwable fromErrPipe, Throwable fromInPipe) { this.fromProcess = fromProcess; this.fromErrPipe = fromErrPipe; this.fromOutPipe = fromOutPipe; this.fromInPipe = fromInPipe; thrown = ((null != fromProcess) || (null != fromInPipe) || (null != fromOutPipe) || (null != fromErrPipe)); } public String toString() { StringBuffer sb = new StringBuffer(); append(sb, fromProcess, "process"); append(sb, fromOutPipe, " stdout"); append(sb, fromErrPipe, " stderr"); append(sb, fromInPipe, " stdin"); if (0 == sb.length()) { return "Thrown (none)"; } else { return sb.toString(); } } private void append(StringBuffer sb, Throwable thrown, String label) { if (null != thrown) { sb.append("from " + label + ": "); sb.append(LangUtil.renderExceptionShort(thrown)); sb.append(LangUtil.EOL); } } } // class Thrown } }
389,967
Bug 389967 Weaved aspects mechanism does not take into account modified classes
The current caching mechanism assumes that if the same class is encountered then its cached weaved version can be used. However, the mechanism uses only the (fully qualified) class name to identify the class and does not take into account the fact that the class bytes may have changed (e.g., the user re-compiled and re-deployed some changes to the same class).
resolved fixed
9a3cc2b
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2012-10-01T20:22:37Z"
"2012-09-20T05:46:40Z"
weaver/src/org/aspectj/weaver/tools/WeavingAdaptor.java
/* ******************************************************************* * Copyright (c) 2004 IBM Corporation * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Eclipse Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Matthew Webster, Adrian Colyer, John Kew (caching) * 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.security.ProtectionDomain; import java.util.*; import org.aspectj.bridge.AbortException; import org.aspectj.bridge.IMessage; import org.aspectj.bridge.IMessage.Kind; import org.aspectj.bridge.IMessageContext; import org.aspectj.bridge.IMessageHandler; import org.aspectj.bridge.IMessageHolder; import org.aspectj.bridge.Message; import org.aspectj.bridge.MessageHandler; import org.aspectj.bridge.MessageUtil; import org.aspectj.bridge.MessageWriter; import org.aspectj.bridge.Version; import org.aspectj.bridge.WeaveMessage; import org.aspectj.util.FileUtil; import org.aspectj.util.LangUtil; import org.aspectj.weaver.IClassFileProvider; import org.aspectj.weaver.IUnwovenClassFile; import org.aspectj.weaver.IWeaveRequestor; import org.aspectj.weaver.World; import org.aspectj.weaver.bcel.BcelObjectType; import org.aspectj.weaver.bcel.BcelWeaver; import org.aspectj.weaver.bcel.BcelWorld; import org.aspectj.weaver.bcel.UnwovenClassFile; import org.aspectj.weaver.tools.cache.CachedClassEntry; import org.aspectj.weaver.tools.cache.CachedClassReference; import org.aspectj.weaver.tools.cache.WeavedClassCache; // OPTIMIZE add guards for all the debug/info/etc /** * 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 implements IMessageContext { /** * 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"; public static final String TRACE_MESSAGES_PROPERTY = "org.aspectj.tracing.messages"; private boolean enabled = false; protected boolean verbose = getVerbose(); protected BcelWorld bcelWorld; protected BcelWeaver weaver; private IMessageHandler messageHandler; private WeavingAdaptorMessageHolder messageHolder; private boolean abortOnError = false; protected GeneratedClassHandler generatedClassHandler; protected Map<String, IUnwovenClassFile> generatedClasses = new HashMap<String, IUnwovenClassFile>(); public BcelObjectType delegateForCurrentClass; // lazily initialized, should be used to prevent parsing bytecode multiple // times protected ProtectionDomain activeProtectionDomain; private boolean haveWarnedOnJavax = false; protected WeavedClassCache cache; private int weavingSpecialTypes = 0; private static final int INITIALIZED = 0x1; private static final int WEAVE_JAVA_PACKAGE = 0x2; private static final int WEAVE_JAVAX_PACKAGE = 0x4; private static Trace trace = TraceFactory.getTraceFactory().getTrace(WeavingAdaptor.class); protected WeavingAdaptor() { } /** * 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 for weaving. * * @param loader instance of <code>ClassLoader</code> */ public WeavingAdaptor(WeavingClassLoader loader) { // System.err.println("? WeavingAdaptor.<init>(" + loader +"," + aspectURLs.length + ")"); generatedClassHandler = loader; init((ClassLoader)loader, getFullClassPath((ClassLoader) loader), getFullAspectPath((ClassLoader) loader/* ,aspectURLs */)); } /** * Construct a WeavingAdaptor 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(null, FileUtil.makeClasspath(classURLs), FileUtil.makeClasspath(aspectURLs)); } protected List<String> getFullClassPath(ClassLoader loader) { List<String> list = new LinkedList<String>(); 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<String> getFullAspectPath(ClassLoader loader) { List<String> list = new LinkedList<String>(); 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() { try { return Boolean.getBoolean(WEAVING_ADAPTOR_VERBOSE); } catch (Throwable t) { // security exception return false; } } /** * Initialize the WeavingAdapter * @param loader ClassLoader used by this adapter; which can be null * @param classPath classpath of this adapter * @param aspectPath list of aspect paths */ private void init(ClassLoader loader, List<String> classPath, List<String> aspectPath) { abortOnError = true; 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); initializeCache(loader, aspectPath, null, getMessageHandler()); enabled = true; } /** * If the cache is enabled, initialize it and swap out the existing classhandler * for the caching one - * * @param loader classloader for this adapter, may be null * @param aspects List of strings representing aspects managed by the adapter; these could be urls or classnames * @param existingClassHandler current class handler * @param myMessageHandler current message handler */ protected void initializeCache(ClassLoader loader, List<String> aspects, GeneratedClassHandler existingClassHandler, IMessageHandler myMessageHandler) { if (WeavedClassCache.isEnabled()) { cache = WeavedClassCache.createCache(loader, aspects, existingClassHandler, myMessageHandler); // Wrap the existing class handler so that any generated classes are also cached if (cache != null) { this.generatedClassHandler = cache.getCachingClassHandler(); } } } protected void createMessageHandler() { messageHolder = new WeavingAdaptorMessageHolder(new PrintWriter(System.err)); messageHandler = messageHolder; if (verbose) { messageHandler.dontIgnore(IMessage.INFO); } if (Boolean.getBoolean(SHOW_WEAVE_INFO_PROPERTY)) { messageHandler.dontIgnore(IMessage.WEAVEINFO); } info("AspectJ Weaver Version " + Version.text + " built on " + Version.time_text); //$NON-NLS-1$ } protected IMessageHandler getMessageHandler() { return messageHandler; } public IMessageHolder getMessageHolder() { return messageHolder; } protected void setMessageHandler(IMessageHandler mh) { if (mh instanceof ISupportsMessageContext) { ISupportsMessageContext smc = (ISupportsMessageContext) mh; smc.setMessageContext(this); } if (mh != messageHolder) { messageHolder.setDelegate(mh); } messageHolder.flushMessages(); } protected void disable() { if (trace.isTraceEnabled()) { trace.enter("disable", this); } enabled = false; messageHolder.flushMessages(); if (trace.isTraceEnabled()) { trace.exit("disable"); } } protected void enable() { enabled = true; messageHolder.flushMessages(); } protected boolean isEnabled() { return enabled; } /** * 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 { return weaveClass(name, bytes, false); } // Track if the weaver is already running on this thread - don't allow re-entrant calls private ThreadLocal<Boolean> weaverRunning = new ThreadLocal<Boolean>() { @Override protected Boolean initialValue() { return Boolean.FALSE; } }; /** * Weave a class using aspects previously supplied to the adaptor. * * @param name the name of the class * @param bytes the class bytes * @param mustWeave if true then this class *must* get woven (used for concrete aspects generated from XML) * @return the woven bytes * @exception IOException weave failed */ public byte[] weaveClass(String name, byte[] bytes, boolean mustWeave) throws IOException { if (trace == null) { // Pr231945: we are likely to be under tomcat and ENABLE_CLEAR_REFERENCES hasn't been set System.err .println("AspectJ Weaver cannot continue to weave, static state has been cleared. Are you under Tomcat? In order to weave '" + name + "' during shutdown, 'org.apache.catalina.loader.WebappClassLoader.ENABLE_CLEAR_REFERENCES=false' must be set (see https://bugs.eclipse.org/bugs/show_bug.cgi?id=231945)."); return bytes; } if (weaverRunning.get()) { // System.out.println("AJC: avoiding re-entrant call to transform " + name); return bytes; } try { weaverRunning.set(true); if (trace.isTraceEnabled()) { trace.enter("weaveClass", this, new Object[] { name, bytes }); } if (!enabled) { if (trace.isTraceEnabled()) { trace.exit("weaveClass", false); } return bytes; } boolean debugOn = !messageHandler.isIgnoring(Message.DEBUG); try { delegateForCurrentClass = null; name = name.replace('/', '.'); if (couldWeave(name, bytes)) { if (accept(name, bytes)) { // Determine if we have the weaved class cached CachedClassReference cacheKey = null; byte[] original_bytes = bytes; if (cache != null && !mustWeave) { cacheKey = cache.createCacheKey(name, bytes); CachedClassEntry entry = cache.get(cacheKey); if (entry != null) { // If the entry has been explicitly ignored // return the original bytes if (entry.isIgnored()) { return bytes; } return entry.getBytes(); } } // TODO @AspectJ problem // Annotation style aspects need to be included regardless in order to get // a valid aspectOf()/hasAspect() generated in them. However - if they are excluded // (via include/exclude in aop.xml) they really should only get aspectOf()/hasAspect() // and not be included in the full set of aspects being applied by 'this' weaver if (debugOn) { debug("weaving '" + name + "'"); } bytes = getWovenBytes(name, bytes); // temporarily out - searching for @Aspect annotated types is a slow thing to do - we should // expect the user to name them if they want them woven - just like code style // } else if (shouldWeaveAnnotationStyleAspect(name, bytes)) { // if (mustWeave) { // if (bcelWorld.getLint().mustWeaveXmlDefinedAspects.isEnabled()) { // bcelWorld.getLint().mustWeaveXmlDefinedAspects.signal(name, null); // } // } // // an @AspectJ aspect needs to be at least munged by the aspectOf munger // if (debugOn) { // debug("weaving '" + name + "'"); // } // bytes = getAtAspectJAspectBytes(name, bytes); // Add the weaved class to the cache only if there // has been an actual change // JVK: Is there a better way to check if the class has // been transformed without carrying up some value // from the depths? if (cacheKey != null) { // If no transform has been applied, mark the class // as ignored. if (Arrays.equals(original_bytes, bytes)) { cache.ignore(cacheKey); } else { cache.put(cacheKey, bytes); } } } else if (debugOn) { debug("not weaving '" + name + "'"); } } else if (debugOn) { debug("cannot weave '" + name + "'"); } } finally { delegateForCurrentClass = null; } if (trace.isTraceEnabled()) { trace.exit("weaveClass", bytes); } return bytes; } finally { weaverRunning.set(false); } } /** * @param name * @return true if even valid to weave: either with an accept check or to munge it for @AspectJ aspectof support */ private boolean couldWeave(String name, byte[] bytes) { return !generatedClasses.containsKey(name) && shouldWeaveName(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) { if ("osj".indexOf(name.charAt(0)) != -1) { if ((weavingSpecialTypes & INITIALIZED) == 0) { weavingSpecialTypes |= INITIALIZED; // initialize it Properties p = weaver.getWorld().getExtraConfiguration(); if (p != null) { boolean b = p.getProperty(World.xsetWEAVE_JAVA_PACKAGES, "false").equalsIgnoreCase("true"); if (b) { weavingSpecialTypes |= WEAVE_JAVA_PACKAGE; } b = p.getProperty(World.xsetWEAVE_JAVAX_PACKAGES, "false").equalsIgnoreCase("true"); if (b) { weavingSpecialTypes |= WEAVE_JAVAX_PACKAGE; } } } if (name.startsWith("org.aspectj.")) { return false; } if (name.startsWith("sun.reflect.")) {// JDK reflect return false; } if (name.startsWith("javax.")) { if ((weavingSpecialTypes & WEAVE_JAVAX_PACKAGE) != 0) { return true; } else { if (!haveWarnedOnJavax) { haveWarnedOnJavax = true; warn("javax.* types are not being woven because the weaver option '-Xset:weaveJavaxPackages=true' has not been specified"); } return false; } } if (name.startsWith("java.")) { if ((weavingSpecialTypes & WEAVE_JAVA_PACKAGE) != 0) { return true; } else { return false; } } } // boolean should = !(name.startsWith("org.aspectj.") // || (name.startsWith("java.") && (weavingSpecialTypes & WEAVE_JAVA_PACKAGE) == 0) // || (name.startsWith("javax.") && (weavingSpecialTypes & WEAVE_JAVAX_PACKAGE) == 0) // // || name.startsWith("$Proxy")//JDK proxies//FIXME AV is that 1.3 proxy ? fe. ataspect.$Proxy0 is a java5 proxy... // || name.startsWith("sun.reflect.")); return true; } /** * 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) { if (delegateForCurrentClass == null) { // if (weaver.getWorld().isASMAround()) return asmCheckAnnotationStyleAspect(bytes); // else ensureDelegateInitialized(name, bytes); } return (delegateForCurrentClass.isAnnotationStyleAspect()); } // private boolean asmCheckAnnotationStyleAspect(byte[] bytes) { // IsAtAspectAnnotationVisitor detector = new IsAtAspectAnnotationVisitor(); // // ClassReader cr = new ClassReader(bytes); // try { // cr.accept(detector, true);//, ClassReader.SKIP_DEBUG | ClassReader.SKIP_CODE | ClassReader.SKIP_FRAMES); // } catch (Exception spe) { // // if anything goes wrong, e.g., an NPE, then assume it's NOT an @AspectJ aspect... // System.err.println("Unexpected problem parsing bytes to discover @Aspect annotation"); // spe.printStackTrace(); // return false; // } // // return detector.isAspect(); // } protected void ensureDelegateInitialized(String name, byte[] bytes) { if (delegateForCurrentClass == null) { BcelWorld world = (BcelWorld) weaver.getWorld(); delegateForCurrentClass = world.addSourceObjectType(name, bytes, false); } } /** * Weave a set of bytes defining a class. * * @param name the name of the class being woven * @param bytes the bytes that define the class * @return byte[] the woven bytes for the class * @throws IOException */ private byte[] getWovenBytes(String name, byte[] bytes) throws IOException { WeavingClassFileProvider wcp = new WeavingClassFileProvider(name, bytes); weaver.weave(wcp); return wcp.getBytes(); } /** * Weave a set of bytes defining a class for only what is needed to turn @AspectJ aspect in a usefull form ie with aspectOf * method - see #113587 * * @param name the name of the class being woven * @param bytes the bytes that define the class * @return byte[] the woven bytes for the class * @throws IOException */ private byte[] getAtAspectJAspectBytes(String name, byte[] bytes) throws IOException { WeavingClassFileProvider wcp = new WeavingClassFileProvider(name, bytes); wcp.setApplyAtAspectJMungersOnly(); weaver.weave(wcp); return wcp.getBytes(); } private void registerAspectLibraries(List aspectPath) { // System.err.println("? WeavingAdaptor.registerAspectLibraries(" + aspectPath + ")"); for (Iterator i = aspectPath.iterator(); i.hasNext();) { String libName = (String) i.next(); addAspectLibrary(libName); } weaver.prepareForWeave(); } /* * Register an aspect library with this classloader for use during weaving. This class loader will also return (unmodified) any * of the classes in the library in response to a <code>findClass()</code> request. The library is not required to be on the * weavingClasspath given when this classloader was constructed. * * @param aspectLibraryJarFile a jar file representing an aspect library * * @throws IOException */ private void addAspectLibrary(String aspectLibraryName) { File aspectLibrary = new File(aspectLibraryName); if (aspectLibrary.isDirectory() || (FileUtil.isZipFile(aspectLibrary))) { try { info("adding aspect library: '" + aspectLibrary + "'"); weaver.addLibraryJarFile(aspectLibrary); } catch (IOException ex) { error("exception adding aspect library: '" + ex + "'"); } } else { error("bad aspect library: '" + aspectLibrary + "'"); } } private static List<String> makeClasspath(String cp) { List<String> ret = new ArrayList<String>(); if (cp != null) { StringTokenizer tok = new StringTokenizer(cp, File.pathSeparator); while (tok.hasMoreTokens()) { ret.add(tok.nextToken()); } } return ret; } protected boolean debug(String message) { return MessageUtil.debug(messageHandler, message); } 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); } protected boolean error(String message, Throwable th) { return messageHandler.handleMessage(new Message(message, IMessage.ERROR, th, null)); } public String getContextId() { return "WeavingAdaptor"; } /** * 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 = getDumpDir(); 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); } } /** * @return the directory in which to dump - default is _ajdump but it */ protected String getDumpDir() { return "_ajdump"; } /** * Processes messages arising from weaver operations. Tell weaver to abort on any message more severe than warning. */ protected class WeavingAdaptorMessageHolder extends MessageHandler { private IMessageHandler delegate; private List<IMessage> savedMessages; protected boolean traceMessages = Boolean.getBoolean(TRACE_MESSAGES_PROPERTY); public WeavingAdaptorMessageHolder(PrintWriter writer) { this.delegate = new WeavingAdaptorMessageWriter(writer); super.dontIgnore(IMessage.WEAVEINFO); } private void traceMessage(IMessage message) { if (message instanceof WeaveMessage) { trace.debug(render(message)); } else if (message.isDebug()) { trace.debug(render(message)); } else if (message.isInfo()) { trace.info(render(message)); } else if (message.isWarning()) { trace.warn(render(message), message.getThrown()); } else if (message.isError()) { trace.error(render(message), message.getThrown()); } else if (message.isFailed()) { trace.fatal(render(message), message.getThrown()); } else if (message.isAbort()) { trace.fatal(render(message), message.getThrown()); } else { trace.error(render(message), message.getThrown()); } } protected String render(IMessage message) { return "[" + getContextId() + "] " + message.toString(); } public void flushMessages() { if (savedMessages == null) { savedMessages = new ArrayList<IMessage>(); savedMessages.addAll(super.getUnmodifiableListView()); clearMessages(); for (IMessage message : savedMessages) { delegate.handleMessage(message); } } // accumulating = false; // messages.clear(); } public void setDelegate(IMessageHandler messageHandler) { delegate = messageHandler; } /* * IMessageHandler */ @Override public boolean handleMessage(IMessage message) throws AbortException { if (traceMessages) { traceMessage(message); } super.handleMessage(message); if (abortOnError && 0 <= message.getKind().compareTo(IMessage.ERROR)) { throw new AbortException(message); } // if (accumulating) { // boolean result = addMessage(message); // if (abortOnError && 0 <= message.getKind().compareTo(IMessage.ERROR)) { // throw new AbortException(message); // } // return result; // } // else return delegate.handleMessage(message); if (savedMessages != null) { delegate.handleMessage(message); } return true; } @Override public boolean isIgnoring(Kind kind) { return delegate.isIgnoring(kind); } @Override public void dontIgnore(IMessage.Kind kind) { if (null != kind && delegate != null) { delegate.dontIgnore(kind); } } @Override public void ignore(Kind kind) { if (null != kind && delegate != null) { delegate.ignore(kind); } } /* * IMessageHolder */ @Override public List<IMessage> getUnmodifiableListView() { // System.err.println("? WeavingAdaptorMessageHolder.getUnmodifiableListView() savedMessages=" + savedMessages); List<IMessage> allMessages = new ArrayList<IMessage>(); allMessages.addAll(savedMessages); allMessages.addAll(super.getUnmodifiableListView()); return allMessages; } } protected class WeavingAdaptorMessageWriter extends MessageWriter { private final Set<IMessage.Kind> ignoring = new HashSet<IMessage.Kind>(); private final IMessage.Kind failKind; public WeavingAdaptorMessageWriter(PrintWriter writer) { super(writer, true); ignore(IMessage.WEAVEINFO); ignore(IMessage.DEBUG); ignore(IMessage.INFO); this.failKind = IMessage.ERROR; } @Override public boolean handleMessage(IMessage message) throws AbortException { // boolean result = super.handleMessage(message); if (abortOnError && 0 <= message.getKind().compareTo(failKind)) { throw new AbortException(message); } return true; } @Override public boolean isIgnoring(Kind kind) { return ((null != kind) && (ignoring.contains(kind))); } /** * Set a message kind to be ignored from now on */ @Override 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. */ @Override public void dontIgnore(IMessage.Kind kind) { if (null != kind) { ignoring.remove(kind); } } @Override protected String render(IMessage message) { return "[" + getContextId() + "] " + super.render(message); } } private class WeavingClassFileProvider implements IClassFileProvider { private final UnwovenClassFile unwovenClass; private final List<UnwovenClassFile> unwovenClasses = new ArrayList<UnwovenClassFile>(); private IUnwovenClassFile wovenClass; private boolean isApplyAtAspectJMungersOnly = false; public WeavingClassFileProvider(String name, byte[] bytes) { ensureDelegateInitialized(name, bytes); this.unwovenClass = new UnwovenClassFile(name, delegateForCurrentClass.getResolvedTypeX().getName(), bytes); this.unwovenClasses.add(unwovenClass); if (shouldDump(name.replace('/', '.'), true)) { dump(name, bytes, true); } } 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<UnwovenClassFile> getClassFileIterator() { return unwovenClasses.iterator(); } public IWeaveRequestor getRequestor() { return new IWeaveRequestor() { public void acceptResult(IUnwovenClassFile result) { if (wovenClass == null) { wovenClass = result; String name = result.getClassName(); if (shouldDump(name.replace('/', '.'), false)) { dump(name, result.getBytes(), false); } } else { // Classes generated by weaver e.g. around closure advice String className = result.getClassName(); generatedClasses.put(className, result); generatedClasses.put(wovenClass.getClassName(), result); generatedClassHandler.acceptClass(className, result.getBytes()); } } public void processingReweavableState() { } public void addingTypeMungers() { } public void weavingAspects() { } public void weavingClasses() { } public void weaveCompleted() { // ResolvedType.resetPrimitives(); if (delegateForCurrentClass != null) { delegateForCurrentClass.weavingCompleted(); } // ResolvedType.resetPrimitives(); // bcelWorld.discardType(typeBeingProcessed.getResolvedTypeX()); // work in progress } }; } } public void setActiveProtectionDomain(ProtectionDomain protectionDomain) { activeProtectionDomain = protectionDomain; } }
389,967
Bug 389967 Weaved aspects mechanism does not take into account modified classes
The current caching mechanism assumes that if the same class is encountered then its cached weaved version can be used. However, the mechanism uses only the (fully qualified) class name to identify the class and does not take into account the fact that the class bytes may have changed (e.g., the user re-compiled and re-deployed some changes to the same class).
resolved fixed
9a3cc2b
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2012-10-01T20:22:37Z"
"2012-09-20T05:46:40Z"
weaver/src/org/aspectj/weaver/tools/cache/CacheBacking.java
/******************************************************************************* * Copyright (c) 2012 Contributors. * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Eclipse Public License v1.0 * which accompanies this distribution and is available at * http://eclipse.org/legal/epl-v10.html * * Contributors: * John Kew (vmware) initial implementation *******************************************************************************/ package org.aspectj.weaver.tools.cache; /** * Interface for the backing to the cache; usually a file, * but could be an in-memory backing for testing. * <p/> * aspectj and jvmti provide no suitable guarantees * on locking for class redefinitions, so every implementation * must have a some locking mechanism to prevent invalid reads. */ public interface CacheBacking { /** * Return a list of keys which match the given * regex. * * @param regex * @return */ public String[] getKeys(String regex); /** * Remove an entry from the cache * * @param ref */ public void remove(CachedClassReference ref); /** * Clear the entire cache */ public void clear(); /** * Get a cache entry * * @param ref entry to retrieve * @return the cached bytes or null, if the entry does not exist */ public CachedClassEntry get(CachedClassReference ref); /** * Put an entry in the cache * * @param entry key of the entry */ public void put(CachedClassEntry entry); }
389,967
Bug 389967 Weaved aspects mechanism does not take into account modified classes
The current caching mechanism assumes that if the same class is encountered then its cached weaved version can be used. However, the mechanism uses only the (fully qualified) class name to identify the class and does not take into account the fact that the class bytes may have changed (e.g., the user re-compiled and re-deployed some changes to the same class).
resolved fixed
9a3cc2b
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2012-10-01T20:22:37Z"
"2012-09-20T05:46:40Z"
weaver/src/org/aspectj/weaver/tools/cache/CacheStatistics.java
/******************************************************************************* * Copyright (c) 2012 Contributors. * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Eclipse Public License v1.0 * which accompanies this distribution and is available at * http://eclipse.org/legal/epl-v10.html * * Contributors: * John Kew (vmware) initial implementation *******************************************************************************/ package org.aspectj.weaver.tools.cache; /** * Maintains some basic statistics on the class cache. */ public class CacheStatistics { private volatile int hits; private volatile int misses; private volatile int weaved; private volatile int generated; private volatile int ignored; private volatile int puts; private volatile int puts_ignored; public void hit() { hits++; } public void miss() { misses++; } public void weaved() { weaved++; } public void generated() { generated++; } public void ignored() { ignored++; } public void put() { puts++; } public void putIgnored() { puts_ignored++; } public int getHits() { return hits; } public int getMisses() { return misses; } public int getWeaved() { return weaved; } public int getGenerated() { return generated; } public int getIgnored() { return ignored; } public int getPuts() { return puts; } public int getPutsIgnored() { return puts_ignored; } public void reset() { hits = 0; misses = 0; weaved = 0; generated = 0; ignored = 0; puts = 0; puts_ignored = 0; } public String toString() { return "CacheStatistics{" + "hits=" + hits + ", misses=" + misses + ", weaved=" + weaved + ", generated=" + generated + ", ignored=" + ignored + ", puts=" + puts + ", puts_ignored=" + puts_ignored + '}'; } }
389,967
Bug 389967 Weaved aspects mechanism does not take into account modified classes
The current caching mechanism assumes that if the same class is encountered then its cached weaved version can be used. However, the mechanism uses only the (fully qualified) class name to identify the class and does not take into account the fact that the class bytes may have changed (e.g., the user re-compiled and re-deployed some changes to the same class).
resolved fixed
9a3cc2b
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2012-10-01T20:22:37Z"
"2012-09-20T05:46:40Z"
weaver/src/org/aspectj/weaver/tools/cache/CachedClassEntry.java
/******************************************************************************* * Copyright (c) 2012 Contributors. * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Eclipse Public License v1.0 * which accompanies this distribution and is available at * http://eclipse.org/legal/epl-v10.html * * Contributors: * John Kew (vmware) initial implementation *******************************************************************************/ package org.aspectj.weaver.tools.cache; /** * Represents a class which has been cached */ public class CachedClassEntry { enum EntryType { GENERATED, WEAVED, IGNORED, } private final CachedClassReference ref; private final byte[] bytes; private final EntryType type; public CachedClassEntry(CachedClassReference ref, byte[] bytes, EntryType type) { this.bytes = bytes; this.ref = ref; this.type = type; } public String getClassName() { return ref.getClassName(); } public byte[] getBytes() { return bytes; } public String getKey() { return ref.getKey(); } public boolean isGenerated() { return type == EntryType.GENERATED; } public boolean isWeaved() { return type == EntryType.WEAVED; } public boolean isIgnored() { return type == EntryType.IGNORED; } }
389,967
Bug 389967 Weaved aspects mechanism does not take into account modified classes
The current caching mechanism assumes that if the same class is encountered then its cached weaved version can be used. However, the mechanism uses only the (fully qualified) class name to identify the class and does not take into account the fact that the class bytes may have changed (e.g., the user re-compiled and re-deployed some changes to the same class).
resolved fixed
9a3cc2b
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2012-10-01T20:22:37Z"
"2012-09-20T05:46:40Z"
weaver/src/org/aspectj/weaver/tools/cache/CachedClassReference.java
/******************************************************************************* * Copyright (c) 2012 Contributors. * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Eclipse Public License v1.0 * which accompanies this distribution and is available at * http://eclipse.org/legal/epl-v10.html * * Contributors: * John Kew (vmware) initial implementation *******************************************************************************/ package org.aspectj.weaver.tools.cache; /** * A typed reference to a cached class entry. The key to any * cache entry is a simple string, but that string may contain * some specialized encoding. This class handles all of that * encoding. * <p/> * External users of the cache should not be able to create these * objects manually. */ public class CachedClassReference { enum EntryType { GENERATED, WEAVED, IGNORED, } private final String key; private final String className; protected CachedClassReference(String key, CacheKeyResolver resolver) { this.key = key; this.className = resolver.keyToClass(key); } /** * Protected to allow only the WeavedClassCache initialization rights * * @param key encoded key of the class * @param className the classname */ protected CachedClassReference(String key, String className) { this.key = key; this.className = className; } public String getKey() { return key; } public String getClassName() { return className; } }
389,967
Bug 389967 Weaved aspects mechanism does not take into account modified classes
The current caching mechanism assumes that if the same class is encountered then its cached weaved version can be used. However, the mechanism uses only the (fully qualified) class name to identify the class and does not take into account the fact that the class bytes may have changed (e.g., the user re-compiled and re-deployed some changes to the same class).
resolved fixed
9a3cc2b
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2012-10-01T20:22:37Z"
"2012-09-20T05:46:40Z"
weaver/src/org/aspectj/weaver/tools/cache/DefaultCacheFactory.java
/******************************************************************************* * Copyright (c) 2012 Contributors. * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Eclipse Public License v1.0 * which accompanies this distribution and is available at * http://eclipse.org/legal/epl-v10.html * * Contributors: * John Kew (vmware) initial implementation *******************************************************************************/ package org.aspectj.weaver.tools.cache; /** * Default factory for creating the backing and resolving classes. */ public class DefaultCacheFactory implements CacheFactory { public CacheKeyResolver createResolver() { return new DefaultCacheKeyResolver(); } public CacheBacking createBacking(String scope) { return DefaultFileCacheBacking.createBacking(scope, createResolver()); } }
389,967
Bug 389967 Weaved aspects mechanism does not take into account modified classes
The current caching mechanism assumes that if the same class is encountered then its cached weaved version can be used. However, the mechanism uses only the (fully qualified) class name to identify the class and does not take into account the fact that the class bytes may have changed (e.g., the user re-compiled and re-deployed some changes to the same class).
resolved fixed
9a3cc2b
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2012-10-01T20:22:37Z"
"2012-09-20T05:46:40Z"
weaver/src/org/aspectj/weaver/tools/cache/DefaultCacheKeyResolver.java
/******************************************************************************* * Copyright (c) 2012 Contributors. * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Eclipse Public License v1.0 * which accompanies this distribution and is available at * http://eclipse.org/legal/epl-v10.html * * Contributors: * John Kew (vmware) initial implementation *******************************************************************************/ package org.aspectj.weaver.tools.cache; import java.math.BigInteger; import java.net.URL; import java.net.URLClassLoader; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.Collections; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.zip.CRC32; /** * Naive default class and classloader hashing implementation useful * for some multi-classloader environments. * <p/> * This implementation creates classloader scopes of the form:<br/> * "ExampleClassLoaderName.[crc hash]" * <p/> * And weaved class keys of the form:<br/> * "com.foo.BarClassName.[bytes len][crc].weaved" * <p/> * And generated class keys of the form:<br/> * "com.foo.BarClassName$AjClosure.generated */ public class DefaultCacheKeyResolver implements CacheKeyResolver { public static final String GENERATED_SUFFIX = ".generated"; public static final String WEAVED_SUFFIX = ".weaved"; /** * Create a scope from a set of urls and aspect urls. Creates scope * of the form "ExampleClassLoaderName.[md5sum]" or * "ExampleClassLoaderName.[crc]" * * @param cl the classloader which uses the cache, can be null * @param aspects the aspects * @return a unique string for URLClassloaders, otherwise a non-unique classname */ public String createClassLoaderScope(ClassLoader cl, List<String> aspects) { String name = cl != null ? cl.getClass().getSimpleName() : "unknown"; List<String> hashableStrings = new LinkedList<String>(); StringBuilder hashable = new StringBuilder(256); // Add the list of loader urls to the hash list if (cl != null && cl instanceof URLClassLoader) { URL[] urls = ((URLClassLoader) cl).getURLs(); for (int i = 0; i < urls.length; i++) { hashableStrings.add(urls[i].toString()); } } hashableStrings.addAll(aspects); Collections.sort(hashableStrings); for (Iterator<String> it = hashableStrings.iterator(); it.hasNext(); ) { String url = it.next(); hashable.append(url); } String hash = null; byte[] bytes = hashable.toString().getBytes(); hash = crc(bytes); return name + '.' + hash; } private String crc(byte[] input) { CRC32 crc32 = new CRC32(); crc32.update(input); return String.valueOf(crc32.getValue()); } public String getGeneratedRegex() { return ".*" + GENERATED_SUFFIX; } public String getWeavedRegex() { return ".*" + WEAVED_SUFFIX; } /** * Converts a cache key back to a className * * @param key to convert * @return className, e.g. "com.foo.Bar" */ public String keyToClass(String key) { if (key.endsWith(GENERATED_SUFFIX)) { return key.replaceAll(GENERATED_SUFFIX + "$", ""); } if (key.endsWith(WEAVED_SUFFIX)) { return key.replaceAll("\\.[^.]+" + WEAVED_SUFFIX, ""); } return key; } public CachedClassReference weavedKey(String className, byte[] original_bytes) { String hash = crc(original_bytes); return new CachedClassReference(className + "." + hash + WEAVED_SUFFIX, className); } public CachedClassReference generatedKey(String className) { return new CachedClassReference(className + GENERATED_SUFFIX, className); } }
389,967
Bug 389967 Weaved aspects mechanism does not take into account modified classes
The current caching mechanism assumes that if the same class is encountered then its cached weaved version can be used. However, the mechanism uses only the (fully qualified) class name to identify the class and does not take into account the fact that the class bytes may have changed (e.g., the user re-compiled and re-deployed some changes to the same class).
resolved fixed
9a3cc2b
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2012-10-01T20:22:37Z"
"2012-09-20T05:46:40Z"
weaver/src/org/aspectj/weaver/tools/cache/DefaultFileCacheBacking.java
/******************************************************************************* * Copyright (c) 2012 Contributors. * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Eclipse Public License v1.0 * which accompanies this distribution and is available at * http://eclipse.org/legal/epl-v10.html * * Contributors: * John Kew (vmware) initial implementation *******************************************************************************/ package org.aspectj.weaver.tools.cache; import org.aspectj.bridge.MessageUtil; import org.aspectj.util.FileUtil; import java.io.*; import java.util.HashMap; import java.util.zip.CRC32; /** * Naive File-Backed Class Cache with no expiry or application * centric invalidation. * <p/> * Enabled with the system property, "aj.weaving.cache.dir" * If this system property is not set, no caching will be * performed. * <p/> * A CRC checksum is stored alongside the class file to verify * the bytes on read. If for some reason there is an error * reading either the class or crc file, or if the crc does not * match the class data the cache entry is deleted. * <p/> * An alternate implementation of this could store the class file * as a jar/zip directly, which would have the required crc; as * a first pass however it is somewhat useful to view these files * in expanded form for debugging. */ public class DefaultFileCacheBacking implements CacheBacking { public static final String WEAVED_CLASS_CACHE_DIR = "aj.weaving.cache.dir"; public static final String INDEX_FILE = "cache.idx"; public static class IndexEntry implements Serializable { public String key; public boolean generated; public boolean ignored; public long crc; } private final File cacheDirectory; private final CacheKeyResolver resolver; private final HashMap<String, IndexEntry> index = new HashMap<String, IndexEntry>(); private static final Object LOCK = new Object(); protected DefaultFileCacheBacking(File cacheDirectory, CacheKeyResolver resolver) { this.cacheDirectory = cacheDirectory; this.resolver = resolver; readIndex(); } public static CacheBacking createBacking(File cacheDir, CacheKeyResolver resolver) { if (!cacheDir.exists()) { if (!cacheDir.mkdirs()) { MessageUtil.error("Unable to create cache directory at " + cacheDir.getName()); return null; } } if (!cacheDir.canWrite()) { MessageUtil.error("Cache directory is not writable at " + cacheDir.getName()); return null; } return new DefaultFileCacheBacking(cacheDir, resolver); } public static IndexEntry[] readIndex(File indexFile) { IndexEntry[] iea = new IndexEntry[0]; FileInputStream fis = null; ObjectInputStream ois = null; try { if (!indexFile.canRead()) { return iea; } fis = new FileInputStream(indexFile); ois = new ObjectInputStream(fis); iea = (IndexEntry[]) ois.readObject(); } catch (Exception e) { delete(indexFile); } finally { close(fis, indexFile); close(ois, indexFile); } return iea; } private void readIndex() { synchronized (LOCK) { IndexEntry[] idx = readIndex(new File(cacheDirectory, INDEX_FILE)); for (IndexEntry ie : idx) { File cacheFile = new File(cacheDirectory, ie.key); if (cacheFile.canRead() || ie.ignored) { index.put(ie.key, ie); } } } } private void writeIndex() { synchronized (LOCK) { if (!cacheDirectory.exists()) cacheDirectory.mkdirs(); File indexFile = new File(cacheDirectory, INDEX_FILE); FileOutputStream fos = null; ObjectOutputStream oos = null; try { delete(indexFile); fos = new FileOutputStream(indexFile); oos = new ObjectOutputStream(fos); oos.writeObject(index.values().toArray(new IndexEntry[0])); } catch (Exception e) { throw new RuntimeException(e); } finally { close(fos, indexFile); close(oos, indexFile); } } } private void removeIndexEntry(String key) { synchronized (LOCK) { index.remove(key); writeIndex(); } } private void addIndexEntry(IndexEntry ie) { synchronized (LOCK) { index.put(ie.key, ie); writeIndex(); } } public void clear() { synchronized (LOCK) { FileUtil.deleteContents(cacheDirectory); } } public static CacheBacking createBacking(String scope, CacheKeyResolver resolver) { String cache = System.getProperty(WEAVED_CLASS_CACHE_DIR); if (cache == null) { return null; } File cacheDir = new File(cache, scope); return createBacking(cacheDir, resolver); } public String[] getKeys(final String regex) { File[] files = cacheDirectory.listFiles(new FilenameFilter() { public boolean accept(File file, String s) { if (s.matches(regex)) { return true; } return false; } }); if (files == null) { return new String[0]; } String[] keys = new String[files.length]; for (int i = 0; i < files.length; i++) { keys[i] = files[i].getName(); } return keys; } public CachedClassEntry get(CachedClassReference ref) { IndexEntry ie = index.get(ref.getKey()); if (ie != null && ie.ignored) { return new CachedClassEntry(ref, WeavedClassCache.ZERO_BYTES, CachedClassEntry.EntryType.IGNORED); } File cacheFile = new File(cacheDirectory, ref.getKey()); if (cacheFile.canRead()) { if (ie == null) { // no index, delete delete(cacheFile); return null; } byte[] bytes = read(cacheFile, ie.crc); if (bytes != null) { if (!ie.generated) { return new CachedClassEntry(ref, bytes, CachedClassEntry.EntryType.WEAVED); } else { return new CachedClassEntry(ref, bytes, CachedClassEntry.EntryType.GENERATED); } } } return null; } public void put(CachedClassEntry entry) { File cacheFile = new File(cacheDirectory, entry.getKey()); if (!cacheFile.exists()) { IndexEntry ie = new IndexEntry(); ie.key = entry.getKey(); ie.generated = entry.isGenerated(); ie.ignored = entry.isIgnored(); if (!entry.isIgnored()) { ie.crc = write(cacheFile, entry.getBytes()); } addIndexEntry(ie); } } public void remove(CachedClassReference ref) { synchronized (LOCK) { File cacheFile = new File(cacheDirectory, ref.getKey()); removeIndexEntry(ref.getKey()); delete(cacheFile); } } protected byte[] read(File file, long expectedCRC) { CRC32 checksum = new CRC32(); synchronized (LOCK) { FileInputStream fis = null; try { fis = new FileInputStream(file); byte[] bytes = FileUtil.readAsByteArray(fis); checksum.update(bytes); if (checksum.getValue() == expectedCRC) { return bytes; } } catch (FileNotFoundException e) { // file disappeared MessageUtil.error("File not found " + file.getName()); } catch (IOException e) { MessageUtil.error("Error reading cached class " + e.getLocalizedMessage()); } finally { close(fis, file); } // delete the file if there was an exception reading it // or the expected checksum does not match delete(file); } return null; } protected long write(File file, byte[] bytes) { if (file.exists()) { return -1; } synchronized (LOCK) { if (file.exists()) { return -1; } OutputStream out = null; ObjectOutputStream crcOut = null; CRC32 checksum = new CRC32(); try { out = new FileOutputStream(file); out.write(bytes); checksum.update(bytes); return checksum.getValue(); } catch (FileNotFoundException e) { MessageUtil.error("Error writing (File Not Found) " + file.getName() + ": " + e.getLocalizedMessage()); } catch (IOException e) { MessageUtil.error("Error writing " + file.getName()); } finally { close(out, file); } // delete the file if there was an exception writing it delete(file); } return -1; } protected static void delete(File file) { if (file.exists()) { file.delete(); } } protected static void close(OutputStream out, File file) { if (out != null) { try { out.close(); } catch (IOException e) { // error MessageUtil.error("Error closing write file " + file.getName()); } } } protected static void close(InputStream in, File file) { if (in != null) { try { in.close(); } catch (IOException e) { // error MessageUtil.error("Error closing read file " + file.getName()); } } } }
389,967
Bug 389967 Weaved aspects mechanism does not take into account modified classes
The current caching mechanism assumes that if the same class is encountered then its cached weaved version can be used. However, the mechanism uses only the (fully qualified) class name to identify the class and does not take into account the fact that the class bytes may have changed (e.g., the user re-compiled and re-deployed some changes to the same class).
resolved fixed
9a3cc2b
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2012-10-01T20:22:37Z"
"2012-09-20T05:46:40Z"
weaver/src/org/aspectj/weaver/tools/cache/GeneratedCachedClassHandler.java
/******************************************************************************* * Copyright (c) 2012 Contributors. * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Eclipse Public License v1.0 * which accompanies this distribution and is available at * http://eclipse.org/legal/epl-v10.html * * Contributors: * John Kew (vmware) initial implementation *******************************************************************************/ package org.aspectj.weaver.tools.cache; import org.aspectj.weaver.tools.GeneratedClassHandler; /** * Handler for generated classes; such as Shadowed closures, etc. This wraps the normal * generated class handler with caching */ public class GeneratedCachedClassHandler implements GeneratedClassHandler { private final WeavedClassCache cache; private final GeneratedClassHandler nextGeneratedClassHandler; public GeneratedCachedClassHandler(WeavedClassCache cache, GeneratedClassHandler nextHandler) { this.cache = cache; this.nextGeneratedClassHandler = nextHandler; } public void acceptClass(String name, byte[] bytes) { // The cache expects classNames in dot form CachedClassReference ref = cache.createGeneratedCacheKey(name.replace('/', '.')); cache.put(ref, bytes); if (nextGeneratedClassHandler != null) { nextGeneratedClassHandler.acceptClass(name, bytes); } } }
389,967
Bug 389967 Weaved aspects mechanism does not take into account modified classes
The current caching mechanism assumes that if the same class is encountered then its cached weaved version can be used. However, the mechanism uses only the (fully qualified) class name to identify the class and does not take into account the fact that the class bytes may have changed (e.g., the user re-compiled and re-deployed some changes to the same class).
resolved fixed
9a3cc2b
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2012-10-01T20:22:37Z"
"2012-09-20T05:46:40Z"
weaver/src/org/aspectj/weaver/tools/cache/WeavedClassCache.java
/******************************************************************************* * Copyright (c) 2012 Contributors. * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Eclipse Public License v1.0 * which accompanies this distribution and is available at * http://eclipse.org/legal/epl-v10.html * * Contributors: * John Kew (vmware) initial implementation *******************************************************************************/ package org.aspectj.weaver.tools.cache; import org.aspectj.bridge.IMessage; import org.aspectj.bridge.IMessageHandler; import org.aspectj.bridge.Message; import org.aspectj.bridge.MessageUtil; import org.aspectj.weaver.tools.GeneratedClassHandler; import java.util.LinkedList; import java.util.List; /** * Manages a cache of weaved and generated classes similar to Eclipse Equinox, * except designed to operate across multiple restarts of the JVM and with one * cache per classloader; allowing URLClassLoaders with the same set of URI * paths to share the same cache (with the default configuration). * <p/> * To enable the default configuration two system properties must be set: * <pre> * "-Daj.weaving.cache.enabled=true" * "-Daj.weaving.cache.dir=/some/directory" * </pre> * <p/> * The class cache is often something that application developers or * containers would like to manage, so there are a few interfaces for overriding the * default behavior and performing other management functions. * <p/> * {@link CacheBacking} <br/> * Provides an interface for implementing a custom backing store * for the cache; The default implementation in {@link DefaultFileCacheBacking} * provides a naive file-backed cache. An alternate implementation may ignore * caching until signaled explicitly by the application, or only cache files * for a specific duration. This class delegates the locking and synchronization * requirements to the CacheBacking implementation. * <p/> * {@link CacheKeyResolver} <br/> * Provides methods for creating keys from classes to be cached and for * creating the "scope" of the cache itself for a given classloader and aspect * list. The default implementation is provided by {@link DefaultCacheKeyResolver} * but an alternate implementation may want to associate a cache with a particular * application running underneath a container. * <p/> * This naive cache does not normally invalidate *any* classes; the interfaces above * must be used to implement more intelligent behavior. Cache invalidation * problems may occur in at least three scenarios: * <pre> * 1. New aspects are added dynamically somewhere in the classloader hierarchy; affecting * other classes elsewhere. * 2. Use of declare parent in aspects to change the type hierarchy; if the cache * has not invalidated the right classes in the type hierarchy aspectj may not * be reconstruct the class incorrectly. * 3. Similarly to (2), the addition of fields or methods on classes which have * already been weaved and cached could have inter-type conflicts. * </pre> */ public class WeavedClassCache { public static final String WEAVED_CLASS_CACHE_ENABLED = "aj.weaving.cache.enabled"; private static CacheFactory DEFAULT_FACTORY = new DefaultCacheFactory(); public static final byte[] ZERO_BYTES = new byte[0]; private final IMessageHandler messageHandler; private final GeneratedCachedClassHandler cachingClassHandler; private final CacheBacking backing; private final CacheStatistics stats; private final CacheKeyResolver resolver; private final String name; private static final List<WeavedClassCache> cacheRegistry = new LinkedList<WeavedClassCache>(); protected WeavedClassCache(GeneratedClassHandler existingClassHandler, IMessageHandler messageHandler, String name, CacheBacking backing, CacheKeyResolver resolver) { this.resolver = resolver; this.name = name; this.backing = backing; this.messageHandler = messageHandler; initializeGenerated(existingClassHandler); // wrap the existing class handler with a caching version cachingClassHandler = new GeneratedCachedClassHandler(this, existingClassHandler); this.stats = new CacheStatistics(); synchronized (cacheRegistry) { cacheRegistry.add(this); } } /** * Creates a new cache using the resolver and backing returned by the DefaultCacheFactory. * * @param loader classloader for this cache * @param aspects list of aspects used by the WeavingAdapter * @param existingClassHandler the existing GeneratedClassHandler used by the weaver * @param messageHandler the existing messageHandler used by the weaver * @return */ public static WeavedClassCache createCache(ClassLoader loader, List<String> aspects, GeneratedClassHandler existingClassHandler, IMessageHandler messageHandler) { CacheKeyResolver resolver = DEFAULT_FACTORY.createResolver(); String name = resolver.createClassLoaderScope(loader, aspects); if (name == null) { return null; } CacheBacking backing = DEFAULT_FACTORY.createBacking(name); if (backing != null) { return new WeavedClassCache(existingClassHandler, messageHandler, name, backing, resolver); } return null; } public String getName() { return name; } /** * The Cache and be extended in two ways, through a specialized CacheKeyResolver and * a specialized CacheBacking. The default factory used to create these classes can * be set with this method. Since each weaver will create a cache, this method must be * called before the weaver is first initialized. * * @param factory */ public static void setDefaultCacheFactory(CacheFactory factory) { DEFAULT_FACTORY = factory; } /** * Created a key for a generated class * * @param className ClassName, e.g. "com.foo.Bar" * @return the cache key, or null if no caching should be performed */ public CachedClassReference createGeneratedCacheKey(String className) { return resolver.generatedKey(className); } /** * Create a key for a normal weaved class * * @param className ClassName, e.g. "com.foo.Bar" * @param originalBytes Original byte array of the class * @return a cache key, or null if no caching should be performed */ public CachedClassReference createCacheKey(String className, byte[] originalBytes) { return resolver.weavedKey(className, originalBytes); } /** * Returns a generated class handler which wraps the handler this cache was initialized * with; this handler should be used to make sure that generated classes are added * to the cache */ public GeneratedClassHandler getCachingClassHandler() { return cachingClassHandler; } /** * Has caching been enabled through the System property, * WEAVED_CLASS_CACHE_ENABLED * * @return true if caching is enabled */ public static boolean isEnabled() { return System.getProperty(WEAVED_CLASS_CACHE_ENABLED) != null; } /** * Put a class in the cache * * @param ref reference to the entry, as created through createCacheKey * @param weavedBytes bytes to cache */ public void put(CachedClassReference ref, byte[] weavedBytes) { CachedClassEntry.EntryType type = CachedClassEntry.EntryType.WEAVED; if (ref.getKey().matches(resolver.getGeneratedRegex())) { type = CachedClassEntry.EntryType.GENERATED; } backing.put(new CachedClassEntry(ref, weavedBytes, type)); stats.put(); } /** * Get a cache value * * @param ref reference to the cache entry, created through createCacheKey * @return the CacheEntry, or null if no entry exists in the cache */ public CachedClassEntry get(CachedClassReference ref) { CachedClassEntry entry = backing.get(ref); if (entry == null) { stats.miss(); } else { stats.hit(); if (entry.isGenerated()) stats.generated(); if (entry.isWeaved()) stats.weaved(); if (entry.isIgnored()) stats.ignored(); } return entry; } /** * Put a cache entry to indicate that the class should not be * weaved; the original bytes of the class should be used. * * @param ref */ public void ignore(CachedClassReference ref) { stats.putIgnored(); backing.put(new CachedClassEntry(ref, ZERO_BYTES, CachedClassEntry.EntryType.IGNORED)); } /** * Invalidate a cache entry * * @param ref */ public void remove(CachedClassReference ref) { backing.remove(ref); } /** * Clear the entire cache */ public void clear() { backing.clear(); } /** * Get the statistics associated with this cache, or * null if statistics have not been enabled. * * @return */ public CacheStatistics getStats() { return stats; } /** * Return a list of all WeavedClassCaches which have been initialized * * @return */ public static List<WeavedClassCache> getCaches() { synchronized (cacheRegistry) { return new LinkedList<WeavedClassCache>(cacheRegistry); } } /** * Get all generated classes which have been cached * * @return */ protected CachedClassEntry[] getGeneratedClasses() { return getEntries(resolver.getGeneratedRegex()); } /** * Get all weaved classes which have been cached * * @return */ protected CachedClassEntry[] getWeavedClasses() { return getEntries(resolver.getWeavedRegex()); } /** * For each cached, generated class, pass that class through the given * GeneratedClassHandler, typically which defines that handler within the * current ClassLoader. * * @param handler class handler */ private void initializeGenerated(GeneratedClassHandler handler) { if (handler == null) return; CachedClassEntry[] classes = getGeneratedClasses(); for (CachedClassEntry entry : classes) { handler.acceptClass(entry.getClassName(), entry.getBytes()); } } /** * Gets an array of CacheClassEntries with the given regex * * @param regex filter * @return array of entries */ protected CachedClassEntry[] getEntries(String regex) { String[] keys = backing.getKeys(regex); List<CachedClassEntry> entries = new LinkedList<CachedClassEntry>(); for (int i = 0; i < keys.length; i++) { String key = keys[i]; CachedClassReference ref = new CachedClassReference(key, resolver); CachedClassEntry entry = backing.get(ref); if (entry != null) { entries.add(entry); } } return entries.toArray(new CachedClassEntry[entries.size()]); } protected void error(String message, Throwable th) { messageHandler.handleMessage(new Message(message, IMessage.ERROR, th, null)); } protected void error(String message) { MessageUtil.error(messageHandler, message); } protected void info(String message) { MessageUtil.info(message); } }
389,967
Bug 389967 Weaved aspects mechanism does not take into account modified classes
The current caching mechanism assumes that if the same class is encountered then its cached weaved version can be used. However, the mechanism uses only the (fully qualified) class name to identify the class and does not take into account the fact that the class bytes may have changed (e.g., the user re-compiled and re-deployed some changes to the same class).
resolved fixed
9a3cc2b
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2012-10-01T20:22:37Z"
"2012-09-20T05:46:40Z"
weaver/testsrc/org/aspectj/weaver/tools/cache/DefaultFileCacheBackingTest.java
/******************************************************************************* * Copyright (c) 2012 Contributors. * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Eclipse Public License v1.0 * which accompanies this distribution and is available at * http://eclipse.org/legal/epl-v10.html * * Contributors: * John Kew (vmware) initial implementation *******************************************************************************/ package org.aspectj.weaver.tools.cache; import junit.framework.TestCase; import org.aspectj.util.FileUtil; import java.io.File; import java.util.zip.CRC32; /** */ public class DefaultFileCacheBackingTest extends TestCase { File root = null; byte[] FAKE_BYTES = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; String FAKE_CLASS = "com.example.foo.Bar"; CacheKeyResolver resolver = new DefaultCacheKeyResolver(); CachedClassReference fakeRef = resolver.weavedKey(FAKE_CLASS, FAKE_BYTES); public void setUp() throws Exception { if (root == null) { File tempFile = File.createTempFile("aspectj", "test"); File tempDir = tempFile.getParentFile(); root = new File(tempDir, "aspectj-test-cache"); } } public void tearDown() throws Exception { FileUtil.deleteContents(root); root = null; } public void testCreateBacking() throws Exception { CacheBacking backing = DefaultFileCacheBacking.createBacking(root, resolver); assertNotNull(backing); assertTrue(root.exists()); assertTrue(root.isDirectory()); } public void testClear() { CacheBacking backing = DefaultFileCacheBacking.createBacking(root, resolver); backing.put(new CachedClassEntry(fakeRef, FAKE_BYTES, CachedClassEntry.EntryType.WEAVED)); assertNotNull(backing.get(fakeRef)); backing.clear(); assertNull(backing.get(fakeRef)); } private CachedClassEntry createTestEntry(String key) { return new CachedClassEntry(new CachedClassReference(key, key), FAKE_BYTES, CachedClassEntry.EntryType.WEAVED); } public void testGetKeys() throws Exception { CacheBacking backing = DefaultFileCacheBacking.createBacking(root, resolver); backing.put(createTestEntry("apple")); backing.put(createTestEntry("apply")); backing.put(createTestEntry("orange")); String[] matches = backing.getKeys("app.*"); assertEquals(2, matches.length); matches = backing.getKeys("orange"); assertEquals(1, matches.length); assertEquals("orange", matches[0]); } public void testPut() throws Exception { CacheBacking backing = DefaultFileCacheBacking.createBacking(root, resolver); backing.put(new CachedClassEntry(fakeRef, FAKE_BYTES, CachedClassEntry.EntryType.WEAVED)); File cachedFile = new File(root, fakeRef.getKey()); assertTrue(cachedFile.exists()); assertTrue(cachedFile.isFile()); assertEquals(FAKE_BYTES.length, cachedFile.length()); } private boolean indexEntryExists(String key, long expectedCRC) throws Exception { long storedCRC = 0; DefaultFileCacheBacking.IndexEntry[] index = DefaultFileCacheBacking.readIndex(new File(root, DefaultFileCacheBacking.INDEX_FILE)); if (index == null) { throw new NullPointerException("No index at " + root.getAbsolutePath()); } for (DefaultFileCacheBacking.IndexEntry ie : index) { if (ie.key.equals(key)) { storedCRC = ie.crc; if (!ie.ignored) { assertEquals(expectedCRC, storedCRC); } return true; } } return false; } public void testGet() throws Exception { CacheBacking backing = DefaultFileCacheBacking.createBacking(root, resolver); assertNull(backing.get(fakeRef)); backing.put(new CachedClassEntry(fakeRef, FAKE_BYTES, CachedClassEntry.EntryType.WEAVED)); File cachedFile = new File(root, fakeRef.getKey()); assertTrue(cachedFile.isFile()); assertEquals(FAKE_BYTES.length, cachedFile.length()); CRC32 expectedCRC = new CRC32(); expectedCRC.update(FAKE_BYTES); assertTrue(indexEntryExists(fakeRef.getKey(), expectedCRC.getValue())); CachedClassEntry entry = backing.get(fakeRef); assertEquals(FAKE_BYTES.length, entry.getBytes().length); } public void testRemove() throws Exception { CacheBacking backing = DefaultFileCacheBacking.createBacking(root, resolver); backing.put(new CachedClassEntry(fakeRef, FAKE_BYTES, CachedClassEntry.EntryType.WEAVED)); File cachedFile = new File(root, fakeRef.getKey()); assertTrue(cachedFile.exists()); assertTrue(cachedFile.isFile()); CRC32 expectedCRC = new CRC32(); expectedCRC.update(FAKE_BYTES); assertTrue(indexEntryExists(fakeRef.getKey(), expectedCRC.getValue())); backing.remove(fakeRef); cachedFile = new File(root, fakeRef.getKey()); assertFalse("CacheFile Still exists!" + cachedFile.getAbsolutePath(), cachedFile.exists()); assertFalse(cachedFile.isFile()); assertFalse(indexEntryExists(fakeRef.getKey(), expectedCRC.getValue())); } public void testMultiFile() throws Exception { CachedClassEntry entry; File cachedFile; CRC32 expectedCRC = new CRC32(); expectedCRC.update(FAKE_BYTES); CacheBacking backing = DefaultFileCacheBacking.createBacking(root, resolver); // add weaved CachedClassReference wref = resolver.weavedKey(FAKE_CLASS + "WEAVED", FAKE_BYTES); entry = new CachedClassEntry(wref, FAKE_BYTES, CachedClassEntry.EntryType.WEAVED); backing.put(entry); cachedFile = new File(root, wref.getKey()); assertTrue(cachedFile.exists()); assertTrue(cachedFile.isFile()); assertTrue(indexEntryExists(wref.getKey(), expectedCRC.getValue())); // add generated CachedClassReference gref = resolver.generatedKey(FAKE_CLASS + "GENERATED"); entry = new CachedClassEntry(gref, FAKE_BYTES, CachedClassEntry.EntryType.GENERATED); backing.put(entry); cachedFile = new File(root, gref.getKey()); assertTrue(cachedFile.exists()); assertTrue(cachedFile.isFile()); assertTrue(indexEntryExists(gref.getKey(), expectedCRC.getValue())); // add ignored CachedClassReference iref = resolver.generatedKey(FAKE_CLASS + "IGNORED"); entry = new CachedClassEntry(iref, FAKE_BYTES, CachedClassEntry.EntryType.IGNORED); backing.put(entry); cachedFile = new File(root, iref.getKey()); assertFalse(cachedFile.exists()); assertTrue(indexEntryExists(iref.getKey(), expectedCRC.getValue())); backing.remove(wref); backing.remove(gref); backing.remove(iref); } }
389,967
Bug 389967 Weaved aspects mechanism does not take into account modified classes
The current caching mechanism assumes that if the same class is encountered then its cached weaved version can be used. However, the mechanism uses only the (fully qualified) class name to identify the class and does not take into account the fact that the class bytes may have changed (e.g., the user re-compiled and re-deployed some changes to the same class).
resolved fixed
9a3cc2b
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2012-10-01T20:22:37Z"
"2012-09-20T05:46:40Z"
weaver/testsrc/org/aspectj/weaver/tools/cache/WeavedClassCacheTest.java
/******************************************************************************* * Copyright (c) 2012 Contributors. * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Eclipse Public License v1.0 * which accompanies this distribution and is available at * http://eclipse.org/legal/epl-v10.html * * Contributors: * John Kew (vmware) initial implementation *******************************************************************************/ package org.aspectj.weaver.tools.cache; import junit.framework.TestCase; import org.aspectj.bridge.AbortException; import org.aspectj.bridge.IMessage; import org.aspectj.bridge.IMessageHandler; import org.aspectj.weaver.tools.GeneratedClassHandler; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Set; /** */ public class WeavedClassCacheTest extends TestCase { String FAKE_CLASS = "com.example.foo.Bar"; byte[] FAKE_BYTES = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; public class MemoryCacheBacking implements CacheBacking { HashMap<String, CachedClassEntry> cache = new HashMap<String, CachedClassEntry>(); public String[] getKeys(String regex) { Set<String> keys = cache.keySet(); List<String> matches = new LinkedList<String>(); for (String key : keys) { if (key.matches(regex)) { matches.add(key); } } return matches.toArray(new String[0]); } public void remove(CachedClassReference ref) { cache.remove(ref.getKey()); } public void clear() { cache.clear(); } public CachedClassEntry get(CachedClassReference ref) { return cache.get(ref.getKey()); } public void put(CachedClassEntry entry) { cache.put(entry.getKey(), entry); } } MemoryCacheBacking memoryBacking = new MemoryCacheBacking(); IMessageHandler messageHandler = new IMessageHandler() { public boolean handleMessage(IMessage message) throws AbortException { return true; } public boolean isIgnoring(IMessage.Kind kind) { return true; } public void dontIgnore(IMessage.Kind kind) { } public void ignore(IMessage.Kind kind) { } }; public class TestGeneratedClassHandler implements GeneratedClassHandler { public int accepts = 0; public List<String> classesISaw = new LinkedList<String>(); public void acceptClass(String name, byte[] bytes) { accepts++; classesISaw.add(name); } } TestGeneratedClassHandler generatedClassHandler = new TestGeneratedClassHandler(); CacheKeyResolver resolver = new DefaultCacheKeyResolver(); private WeavedClassCache createCache() throws Exception { return new WeavedClassCache(generatedClassHandler, messageHandler, "test", memoryBacking, resolver); } private void reset() throws Exception { memoryBacking.cache.clear(); generatedClassHandler.accepts = 0; generatedClassHandler.classesISaw.clear(); } public void testGetCachingClassHandler() throws Exception { WeavedClassCache cache = createCache(); GeneratedClassHandler newHandle = cache.getCachingClassHandler(); assertTrue(generatedClassHandler != newHandle); assertTrue(newHandle instanceof GeneratedCachedClassHandler); } public void testExistingGeneratedClassesPassedThroughHandler() throws Exception { String classA = "com.generated.A"; String classB = "com.generated.B"; reset(); memoryBacking.put(new CachedClassEntry(resolver.generatedKey(classA), FAKE_BYTES, CachedClassEntry.EntryType.GENERATED)); memoryBacking.put(new CachedClassEntry(resolver.generatedKey(classB), FAKE_BYTES, CachedClassEntry.EntryType.GENERATED)); createCache(); assertEquals(2, generatedClassHandler.accepts); for (String cName : generatedClassHandler.classesISaw) { assertTrue("Got: " + cName, cName.equals(classA) || cName.equals(classB)); } } public void testCache() throws Exception { reset(); WeavedClassCache cache = createCache(); CacheStatistics stats = cache.getStats(); CachedClassReference ref = cache.createCacheKey(FAKE_CLASS, FAKE_BYTES); assertNull(cache.get(ref)); cache.put(ref, FAKE_BYTES); assertNotNull(cache.get(ref)); assertEquals(new String(FAKE_BYTES), new String(cache.get(ref).getBytes())); assertEquals(1, cache.getWeavedClasses().length); assertEquals(ref.getKey(), cache.getWeavedClasses()[0].getKey()); ref = cache.createGeneratedCacheKey(FAKE_CLASS); assertNull(cache.get(ref)); cache.put(ref, FAKE_BYTES); assertNotNull(cache.get(ref)); assertEquals(new String(FAKE_BYTES), new String(cache.get(ref).getBytes())); assertEquals(1, cache.getGeneratedClasses().length); assertEquals(ref.getKey(), cache.getGeneratedClasses()[0].getKey()); assertEquals(4, stats.getHits()); assertEquals(2, stats.getMisses()); } public void testRemove() throws Exception { reset(); WeavedClassCache cache = createCache(); CachedClassReference ref = cache.createCacheKey(FAKE_CLASS, FAKE_BYTES); assertNull(cache.get(ref)); cache.put(ref, FAKE_BYTES); assertNotNull(cache.get(ref)); cache.remove(ref); assertNull(cache.get(ref)); } }
391,123
Bug 391123 Added support for more cache backing(s)
null
closed fixed
df1823b
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2012-10-29T19:46:03Z"
"2012-10-04T14:13:20Z"
build/src/org/aspectj/internal/tools/ant/taskdefs/Checklics.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Eclipse Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Xerox/PARC initial implementation * ******************************************************************/ package org.aspectj.internal.tools.ant.taskdefs; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.PrintStream; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Collections; import java.util.Hashtable; import java.util.Iterator; import java.util.List; import java.util.Map; import org.apache.tools.ant.BuildException; import org.apache.tools.ant.Project; import org.apache.tools.ant.taskdefs.MatchingTask; import org.apache.tools.ant.types.Path; import org.apache.tools.ant.types.Reference; /** * Check that included .java files contain license and copyright strings for MPL 1.0 (default), Apache, or CPL. Use list="true" to * get a list of known license variants {license}-{copyrightHolder} todo reimplement with regexp and jdiff FileLine utilities */ public class Checklics extends MatchingTask { /* * This does not enforce that copyrights are correct/current, only that they exist. E.g., the default behavior requires MPL but * permits either Xerox or PARC copyright holders and any valid year. */ public static final String MPL_TAG = "mpl"; public static final String APACHE_TAG = "apache"; public static final String CPL_IBM_PARC_TAG = "cpl-ibm|parc"; public static final String CPL_IBM_TAG = "cpl-ibm"; public static final String MPL_XEROX_PARC_TAG = "mpl-parc|xerox"; public static final String MPL_ONLY_TAG = "mpl-only"; public static final String MPL_PARC_TAG = "mpl-parc"; public static final String PARC_COPYRIGHT_TAG = "parc-copy"; public static final String CPL_IBM_PARC_XEROX_TAG = "cpl-ibm|parc|xerox"; public static final String CPL_IBM_PARC_XEROX_OTHERS_TAG = "cpl-ibm|parc|xerox|others"; public static final String EPL_CPL_IBM_PARC_XEROX_OTHERS_TAG = "epl-cpl-ibm|parc|xerox|others"; public static final String DEFAULT = EPL_CPL_IBM_PARC_XEROX_OTHERS_TAG; static final Map LICENSES; // unmodifiable Map static { final String CONTRIBUTORS = "Contributors"; final String XEROX = "Xerox"; final String PARC = "Palo Alto Research Center"; final String APACHE = "The Apache Software Foundation"; final String IBM = "IBM"; final String IBM_LONG = "International Business Machines"; final String LIC_APL = "Apache Software Foundation (http://www.apache.org/)"; final String LIC_MPL = "http://aspectj.org/MPL/"; final String LIC_CPL = "Eclipse Public License"; final String LIC_ECPL = " Public License"; License APL = new License(APACHE_TAG, LIC_APL, APACHE); License MPL = new License(MPL_TAG, LIC_MPL, XEROX); License MPL_XEROX_PARC = new License(DEFAULT, LIC_MPL, XEROX, PARC); License CPL_IBM_PARC = new License(CPL_IBM_PARC_TAG, LIC_CPL, new String[] { IBM_LONG, IBM, PARC }); License CPL_IBM_PARC_XEROX = new License(CPL_IBM_PARC_XEROX_TAG, LIC_CPL, new String[] { IBM_LONG, IBM, PARC, XEROX }); License CPL_IBM_PARC_XEROX_OTHERS = new License(CPL_IBM_PARC_XEROX_OTHERS_TAG, LIC_CPL, new String[] { IBM_LONG, IBM, PARC, XEROX, CONTRIBUTORS }); License EPL_CPL_IBM_PARC_XEROX_OTHERS = new License(EPL_CPL_IBM_PARC_XEROX_OTHERS_TAG, LIC_ECPL, new String[] { IBM_LONG, IBM, PARC, XEROX, CONTRIBUTORS }); License CPL_IBM = new License(CPL_IBM_TAG, LIC_CPL, IBM, IBM_LONG); License MPL_ONLY = new License(MPL_ONLY_TAG, LIC_MPL); License MPL_PARC = new License(MPL_PARC_TAG, LIC_MPL, PARC); License PARC_COPYRIGHT = new License(PARC_COPYRIGHT_TAG, null, PARC); LICENSES = new Hashtable(); LICENSES.put(APL.tag, APL); LICENSES.put(MPL.tag, MPL); LICENSES.put(MPL_PARC.tag, MPL_PARC); LICENSES.put(MPL_XEROX_PARC.tag, MPL_XEROX_PARC); LICENSES.put(CPL_IBM_PARC.tag, CPL_IBM_PARC); LICENSES.put(MPL_ONLY.tag, MPL_ONLY); LICENSES.put(CPL_IBM.tag, CPL_IBM); LICENSES.put(PARC_COPYRIGHT.tag, PARC_COPYRIGHT); LICENSES.put(CPL_IBM_PARC_XEROX.tag, CPL_IBM_PARC_XEROX); LICENSES.put(CPL_IBM_PARC_XEROX_OTHERS.tag, CPL_IBM_PARC_XEROX_OTHERS); LICENSES.put(EPL_CPL_IBM_PARC_XEROX_OTHERS.tag, EPL_CPL_IBM_PARC_XEROX_OTHERS); } /** @param args String[] { &lt; sourcepath &gt; {, &lt; licenseTag &gt; } } */ public static void main(String[] args) { switch (args.length) { case 1: runDirect(args[0], null, false); break; case 2: runDirect(args[0], args[1], false); break; default: String options = "{replace-headers|get-years|list|{licenseTag}}"; System.err.println("java {me} sourcepath " + options); break; } } /** * Run the license check directly * * @param sourcepaths String[] of paths to source directories * @param license the String tag for the license, if any * @param failonerror boolean flag to pass to Checklics * @throws IllegalArgumentException if sourcepaths is empty * @return total number of failed licenses */ public static int runDirect(String sourcepath, String license, boolean failonerror) { if ((null == sourcepath) || (1 > sourcepath.length())) { throw new IllegalArgumentException("bad sourcepath: " + sourcepath); } Checklics me = new Checklics(); Project p = new Project(); p.setName("direct interface to Checklics"); p.setBasedir("."); me.setProject(p); me.setFailOnError(failonerror); me.setSourcepath(new Path(p, sourcepath)); if (null != license) { if ("replace-headers".equals(license)) { me.setReplaceheaders(true); } else if ("get-years".equals(license)) { me.setGetYears(true); } else if ("list".equals(license)) { me.setList(true); } else { me.setLicense(license); } } me.execute(); return me.failed; } private Path sourcepath; private License license; private boolean list; private String streamTag; private boolean failOnError; private boolean getYears; private boolean replaceHeaders; private int failed; private int passed; private boolean printDirectories; /** @param list if true, don't run but list known license tags */ public void setList(boolean list) { this.list = list; } public void setPrintDirectories(boolean print) { printDirectories = print; } /** * When failOnError is true, if any file failed, throw BuildException listing number of files that file failed to pass license * check * * @param fail if true, report errors by throwing BuildException */ public void setFailOnError(boolean fail) { this.failOnError = fail; } /** @param tl mpl | apache | cpl */ public void setLicense(String tl) { License input = (License) LICENSES.get(tl); if (null == input) { throw new BuildException("no license known for " + tl); } license = input; } public void setSourcepath(Path path) { if (sourcepath == null) { sourcepath = path; } else { sourcepath.append(path); } } public Path createSourcepath() { return sourcepath == null ? (sourcepath = new Path(project)) : sourcepath.createPath(); } public void setSourcepathRef(Reference id) { createSourcepath().setRefid(id); } /** @param out "out" or "err" */ public void setOutputStream(String out) { this.streamTag = out; } public void setReplaceheaders(boolean replaceHeaders) { this.replaceHeaders = replaceHeaders; } public void setGetYears(boolean getYears) { this.getYears = getYears; } /** list known licenses or check source tree */ public void execute() throws BuildException { if (list) { list(); } else if (replaceHeaders) { replaceHeaders(); } else if (getYears) { getYears(); } else { checkLicenses(); } } private PrintStream getOut() { return ("err".equals(streamTag) ? System.err : System.out); } interface FileVisitor { void visit(File file); } /** visit all .java files in all directories... */ private void visitAll(FileVisitor visitor) { // List filelist = new ArrayList(); String[] dirs = sourcepath.list(); for (int i = 0; i < dirs.length; i++) { File dir = project.resolveFile(dirs[i]); String[] files = getDirectoryScanner(dir).getIncludedFiles(); for (int j = 0; j < files.length; j++) { File file = new File(dir, files[j]); String path = file.getPath(); if (path.endsWith(".java")) { visitor.visit(file); } } } } private void replaceHeaders() { class YearVisitor implements FileVisitor { public void visit(File file) { HeaderInfo info = Header.checkFile(file); if (!Header.replaceHeader(file, info)) { throw new BuildException("failed to replace header for " + file + " using " + info); } } } visitAll(new YearVisitor()); } private void getYears() { final PrintStream out = getOut(); class YearVisitor implements FileVisitor { public void visit(File file) { HeaderInfo info = Header.checkFile(file); out.println(info.toString()); } } visitAll(new YearVisitor()); } private void checkLicenses() throws BuildException { if (null == license) { setLicense(DEFAULT); } final License license = this.license; // being paranoid... if (null == license) { throw new BuildException("no license"); } final PrintStream out = getOut(); class Visitor implements FileVisitor { int failed = 0; int passed = 0; public void visit(File file) { if (license.checkFile(file)) { passed++; } else { failed++; String path = file.getPath(); if (!license.foundLicense()) { out.println(license.tag + " LICENSE FAIL: " + path); } if (!license.foundCopyright()) { out.println(license.tag + " COPYRIGHT FAIL: " + path); } } } } Visitor visitor = new Visitor(); visitAll(visitor); this.failed = visitor.failed; this.passed = visitor.passed; if (0 < visitor.failed) { getOut().println("Total passed: " + visitor.passed + (visitor.failed == 0 ? "" : " failed: " + visitor.failed)); if (failOnError) { throw new BuildException(failed + " files failed license check"); } } } private void list() { Iterator enu = LICENSES.keySet().iterator(); StringBuffer sb = new StringBuffer(); sb.append("known license keys:"); boolean first = true; while (enu.hasNext()) { sb.append((first ? " " : ", ") + enu.next()); if (first) { first = false; } } getOut().println(sb.toString()); } /** * Encapsulate license and copyright specifications to check files use hokey string matching. */ public static class License { /** acceptable years for copyright prefix to company - append " " */ static final String[] YEARS = // remove older after license xfer? new String[] { "2002 ", "2003 ", "2004 ", "2005", "2006", "2007", "2008", "2009", "2010", "2011", "2012", "2001 ", "2000 ", "1999 " }; public final String tag; public final String license; private final String[] copyright; private boolean gotLicense; private boolean gotCopyright; License(String tag, String license) { this(tag, license, (String[]) null); } License(String tag, String license, String copyright) { this(tag, license, new String[] { copyright }); } License(String tag, String license, String copyright, String altCopyright) { this(tag, license, new String[] { copyright, altCopyright }); } License(String tag, String license, String[] copyright) { this.tag = tag; if ((null == tag) || (0 == tag.length())) { throw new IllegalArgumentException("null tag"); } this.license = license; this.copyright = copyright; } public final boolean gotValidFile() { return foundLicense() && foundCopyright(); } /** @return true if no license sought or if some license found */ public final boolean foundLicense() { return ((null == license) || gotLicense); } /** @return true if no copyright sought or if some copyright found */ public final boolean foundCopyright() { return ((null == copyright) || gotCopyright); } public boolean checkFile(final File file) { clear(); // boolean result = false; BufferedReader input = null; int lineNum = 0; try { input = new BufferedReader(new FileReader(file)); String line; while (!gotValidFile() && (line = input.readLine()) != null) { lineNum++; checkLine(line); } } catch (IOException e) { System.err.println("reading line " + lineNum + " of " + file); e.printStackTrace(System.err); } finally { if (null != input) { try { input.close(); } catch (IOException e) { } // ignore } } return gotValidFile(); } public String toString() { return tag; } private void checkLine(String line) { if ((null == line) || (0 == line.length())) { return; } if (!gotLicense && (null != license) && (-1 != line.indexOf(license))) { gotLicense = true; } if (!gotCopyright && (null != copyright)) { int loc; for (int j = 0; !gotCopyright && (j < YEARS.length); j++) { if (-1 != (loc = line.indexOf(YEARS[j]))) { loc += YEARS[j].length(); String afterLoc = line.substring(loc).trim(); for (int i = 0; !gotCopyright && (i < copyright.length); i++) { if (0 == afterLoc.indexOf(copyright[i])) { gotCopyright = true; } } } } } } private void clear() { if (gotLicense) { gotLicense = false; } if (gotCopyright) { gotCopyright = false; } } } // class License } class HeaderInfo { /** File for which this is the info */ public final File file; /** unmodifiable List of String years */ public final List years; /** last line of license */ public final int lastLine; /** last line of license */ public final boolean hasLicense; public HeaderInfo(File file, int lastLine, List years, boolean hasLicense) { this.lastLine = lastLine; this.file = file; this.hasLicense = hasLicense; List newYears = new ArrayList(); newYears.addAll(years); Collections.sort(newYears); this.years = Collections.unmodifiableList(newYears); if ((null == file) || !file.canWrite()) { throw new IllegalArgumentException("bad file: " + this); } if (!hasLicense) { if ((0 > lastLine) || (65 < lastLine)) { throw new IllegalArgumentException("bad last line: " + this); } } else { if ((null == years) || (1 > years.size())) { throw new IllegalArgumentException("no years: " + this); } if ((20 > lastLine) || (65 < lastLine)) { throw new IllegalArgumentException("bad last line: " + this); } } } public String toString() { return file.getPath() + ":" + lastLine + " " + years; } public void writeHeader(PrintWriter writer) { if (!hasLicense) { writer.println(TOP); writer.println(PARC_ONLY); writeRest(writer); } else { final int size = years.size(); if (1 > size) { throw new Error("no years found in " + toString()); } String first = (String) years.get(0); String last = (String) years.get(size - 1); boolean lastIs2002 = "2002".equals(last); String xlast = last; if (lastIs2002) { // 2002 was PARC xlast = (String) (size > 1 ? years.get(size - 2) : null); // 1999-2002 Xerox implies 1999-2001 Xerox if (first.equals(xlast) && !"2001".equals(xlast)) { xlast = "2001"; } } String xyears = first + "-" + xlast; if (first.equals(last)) { xyears = first; } writer.println(TOP); if (!lastIs2002) { // Xerox only writer.println(XEROX_PREFIX + xyears + XEROX_SUFFIX + ". "); } else if (size == 1) { // PARC only writer.println(PARC_ONLY); } else { // XEROX plus PARC writer.println(XEROX_PREFIX + xyears + XEROX_SUFFIX + ", "); writer.println(PARC); } writeRest(writer); } } void writeRest(PrintWriter writer) { writer.println(" * All rights reserved. "); writer.println(" * This program and the accompanying materials are made available "); writer.println(" * under the terms of the Eclipse Public License v1.0 "); writer.println(" * which accompanies this distribution and is available at "); writer.println(" * http://www.eclipse.org/legal/epl-v10.html "); writer.println(" * "); writer.println(" * Contributors: "); writer.println(" * Xerox/PARC initial implementation "); writer.println(" * ******************************************************************/"); writer.println(""); } public static final String TOP = "/* *******************************************************************"; public static final String PARC = " * 2002 Palo Alto Research Center, Incorporated (PARC)."; public static final String PARC_ONLY = " * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC)."; public static final String XEROX_PREFIX = " * Copyright (c) "; public static final String XEROX_SUFFIX = " Xerox Corporation"; /* * /* ******************************************************************* Copyright (c) 1998-2001 Xerox Corporation, 2002 Palo * Alto Research Center, Incorporated (PARC). All rights reserved. This program and the accompanying materials are made * available under the terms of the Eclipse Public License v1.0 which accompanies this distribution and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: Xerox/PARC initial implementation ****************************************************************** */ } /** * header search/replace using hokey string matching */ class Header { /** replace the header in file */ public static boolean replaceHeader(File file, HeaderInfo info) { // ArrayList years = new ArrayList(); // int endLine = 0; BufferedReader input = null; PrintWriter output = null; FileWriter outWriter = null; int lineNum = 0; boolean result = false; final File inFile = new File(file.getPath() + ".tmp"); try { File outFile = new File(file.getPath()); if (!file.renameTo(inFile) || !inFile.canRead()) { throw new Error("unable to rename " + file + " to " + inFile); } outWriter = new FileWriter(outFile); input = new BufferedReader(new FileReader(inFile)); output = new PrintWriter(outWriter, true); info.writeHeader(output); String line; while (null != (line = input.readLine())) { lineNum++; if (lineNum > info.lastLine) { output.println(line); } } } catch (IOException e) { System.err.println("writing line " + lineNum + " of " + file); e.printStackTrace(System.err); result = false; } finally { if (null != input) { try { input.close(); } catch (IOException e) { result = false; } } if (null != outWriter) { try { outWriter.close(); } catch (IOException e) { result = false; } } result = inFile.delete(); } return result; } public static HeaderInfo checkFile(final File file) { ArrayList years = new ArrayList(); int endLine = 0; BufferedReader input = null; int lineNum = 0; try { input = new BufferedReader(new FileReader(file)); String line; while (null != (line = input.readLine())) { lineNum++; String ll = line.trim(); if (ll.startsWith("package ") || ll.startsWith("import ")) { break; // ignore default package w/o imports } if (checkLine(line, years)) { endLine = lineNum; break; } } } catch (IOException e) { System.err.println("reading line " + lineNum + " of " + file); e.printStackTrace(System.err); } finally { if (null != input) { try { input.close(); } catch (IOException e) { } // ignore } } return new HeaderInfo(file, endLine, years, endLine > 0); } /** * Add any years found (as String) to years, and return true at the first end-of-comment * * @return true if this line has end-of-comment */ private static boolean checkLine(String line, ArrayList years) { if ((null == line) || (0 == line.length())) { return false; } int loc; int start = 0; while ((-1 != (loc = line.indexOf("199", start)) || (-1 != (loc = line.indexOf("200", start))))) { char c = line.charAt(loc + 3); if ((c <= '9') && (c >= '0')) { years.add(line.substring(loc, loc + 4)); } start = loc + 4; } return (-1 != line.indexOf("*/")); } } // class Header
391,123
Bug 391123 Added support for more cache backing(s)
null
closed fixed
df1823b
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2012-10-29T19:46:03Z"
"2012-10-04T14:13:20Z"
util/src/org/aspectj/util/LangUtil.java
/* ******************************************************************* * Copyright (c) 1999-2001 Xerox Corporation, * 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Eclipse Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Xerox/PARC initial implementation * ******************************************************************/ package org.aspectj.util; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.io.PrintWriter; import java.io.StringWriter; import java.lang.reflect.Array; import java.lang.reflect.InvocationTargetException; import java.security.PrivilegedActionException; import java.sql.SQLException; import java.util.ArrayList; import java.util.Arrays; import java.util.BitSet; import java.util.Collection; import java.util.Collections; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.StringTokenizer; /** * */ public class LangUtil { public static final String EOL; private static double vmVersion; static { StringWriter buf = new StringWriter(); PrintWriter writer = new PrintWriter(buf); writer.println(""); String eol = "\n"; try { buf.close(); StringBuffer sb = buf.getBuffer(); if (sb != null) { eol = buf.toString(); } } catch (Throwable t) { } EOL = eol; } static { try { String vm = System.getProperty("java.version"); // JLS 20.18.7 if (vm == null) { vm = System.getProperty("java.runtime.version"); } if (vm == null) { vm = System.getProperty("java.vm.version"); } if (vm == null) { new RuntimeException( "System properties appear damaged, cannot find: java.version/java.runtime.version/java.vm.version") .printStackTrace(System.err); vmVersion = 1.5; } else { try { String versionString = vm.substring(0, 3); Double temp = new Double(Double.parseDouble(versionString)); vmVersion = temp.floatValue(); } catch (Exception e) { vmVersion = 1.4; } } } catch (Throwable t) { new RuntimeException( "System properties appear damaged, cannot find: java.version/java.runtime.version/java.vm.version", t) .printStackTrace(System.err); vmVersion = 1.5; } } public static boolean is13VMOrGreater() { return 1.3 <= vmVersion; } public static boolean is14VMOrGreater() { return 1.4 <= vmVersion; } public static boolean is15VMOrGreater() { return 1.5 <= vmVersion; } public static boolean is16VMOrGreater() { return 1.6 <= vmVersion; } public static boolean is17VMOrGreater() { return 1.7 <= vmVersion; } /** * Shorthand for "if null, throw IllegalArgumentException" * * @throws IllegalArgumentException "null {name}" if o is null */ public static final void throwIaxIfNull(final Object o, final String name) { if (null == o) { String message = "null " + (null == name ? "input" : name); throw new IllegalArgumentException(message); } } /** * Shorthand for "if not null or not assignable, throw IllegalArgumentException" * * @param c the Class to check - use null to ignore type check * @throws IllegalArgumentException "null {name}" if o is null */ public static final void throwIaxIfNotAssignable(final Object ra[], final Class<?> c, final String name) { throwIaxIfNull(ra, name); String label = (null == name ? "input" : name); for (int i = 0; i < ra.length; i++) { if (null == ra[i]) { String m = " null " + label + "[" + i + "]"; throw new IllegalArgumentException(m); } else if (null != c) { Class<?> actualClass = ra[i].getClass(); if (!c.isAssignableFrom(actualClass)) { String message = label + " not assignable to " + c.getName(); throw new IllegalArgumentException(message); } } } } /** * Shorthand for "if not null or not assignable, throw IllegalArgumentException" * * @throws IllegalArgumentException "null {name}" if o is null */ public static final void throwIaxIfNotAssignable(final Object o, final Class<?> c, final String name) { throwIaxIfNull(o, name); if (null != c) { Class<?> actualClass = o.getClass(); if (!c.isAssignableFrom(actualClass)) { String message = name + " not assignable to " + c.getName(); throw new IllegalArgumentException(message); } } } // /** // * Shorthand for // "if any not null or not assignable, throw IllegalArgumentException" // * @throws IllegalArgumentException "{name} is not assignable to {c}" // */ // public static final void throwIaxIfNotAllAssignable(final Collection // collection, // final Class c, final String name) { // throwIaxIfNull(collection, name); // if (null != c) { // for (Iterator iter = collection.iterator(); iter.hasNext();) { // throwIaxIfNotAssignable(iter.next(), c, name); // // } // } // } /** * Shorthand for "if false, throw IllegalArgumentException" * * @throws IllegalArgumentException "{message}" if test is false */ public static final void throwIaxIfFalse(final boolean test, final String message) { if (!test) { throw new IllegalArgumentException(message); } } // /** @return ((null == s) || (0 == s.trim().length())); */ // public static boolean isEmptyTrimmed(String s) { // return ((null == s) || (0 == s.length()) // || (0 == s.trim().length())); // } /** @return ((null == s) || (0 == s.length())); */ public static boolean isEmpty(String s) { return ((null == s) || (0 == s.length())); } /** @return ((null == ra) || (0 == ra.length)) */ public static boolean isEmpty(Object[] ra) { return ((null == ra) || (0 == ra.length)); } /** @return ((null == collection) || (0 == collection.size())) */ public static boolean isEmpty(Collection<?> collection) { return ((null == collection) || (0 == collection.size())); } /** @return ((null == map) || (0 == map.size())) */ public static boolean isEmpty(Map<?,?> map) { return ((null == map) || (0 == map.size())); } /** * Splits <code>text</code> at whitespace. * * @param text <code>String</code> to split. */ public static String[] split(String text) { return (String[]) strings(text).toArray(new String[0]); } /** * Splits <code>input</code> at commas, trimming any white space. * * @param input <code>String</code> to split. * @return List of String of elements. */ public static List<String> commaSplit(String input) { return anySplit(input, ","); } /** * Split string as classpath, delimited at File.pathSeparator. Entries are not trimmed, but empty entries are ignored. * * @param classpath the String to split - may be null or empty * @return String[] of classpath entries */ public static String[] splitClasspath(String classpath) { if (LangUtil.isEmpty(classpath)) { return new String[0]; } StringTokenizer st = new StringTokenizer(classpath, File.pathSeparator); ArrayList<String> result = new ArrayList<String>(st.countTokens()); while (st.hasMoreTokens()) { String entry = st.nextToken(); if (!LangUtil.isEmpty(entry)) { result.add(entry); } } return (String[]) result.toArray(new String[0]); } /** * Get System property as boolean, but use default value where the system property is not set. * * @return true if value is set to true, false otherwise */ public static boolean getBoolean(String propertyName, boolean defaultValue) { if (null != propertyName) { try { String value = System.getProperty(propertyName); if (null != value) { return Boolean.valueOf(value).booleanValue(); } } catch (Throwable t) { // default below } } return defaultValue; } /** * Splits <code>input</code>, removing delimiter and trimming any white space. Returns an empty collection if the input is null. * If delimiter is null or empty or if the input contains no delimiters, the input itself is returned after trimming white * space. * * @param input <code>String</code> to split. * @param delim <code>String</code> separators for input. * @return List of String of elements. */ public static List<String> anySplit(String input, String delim) { if (null == input) { return Collections.emptyList(); } ArrayList<String> result = new ArrayList<String>(); if (LangUtil.isEmpty(delim) || (-1 == input.indexOf(delim))) { result.add(input.trim()); } else { StringTokenizer st = new StringTokenizer(input, delim); while (st.hasMoreTokens()) { result.add(st.nextToken().trim()); } } return result; } /** * Splits strings into a <code>List</code> using a <code>StringTokenizer</code>. * * @param text <code>String</code> to split. */ public static List<String> strings(String text) { if (LangUtil.isEmpty(text)) { return Collections.emptyList(); } List<String> strings = new ArrayList<String>(); StringTokenizer tok = new StringTokenizer(text); while (tok.hasMoreTokens()) { strings.add(tok.nextToken()); } return strings; } /** @return a non-null unmodifiable List */ public static <T> List<T> safeList(List<T> list) { return (null == list ? Collections.<T>emptyList() : Collections.unmodifiableList(list)); } // /** // * Select from input String[] based on suffix-matching // * @param inputs String[] of input - null ignored // * @param suffixes String[] of suffix selectors - null ignored // * @param ignoreCase if true, ignore case // * @return String[] of input that end with any input // */ // public static String[] endsWith(String[] inputs, String[] suffixes, // boolean ignoreCase) { // if (LangUtil.isEmpty(inputs) || LangUtil.isEmpty(suffixes)) { // return new String[0]; // } // if (ignoreCase) { // String[] temp = new String[suffixes.length]; // for (int i = 0; i < temp.length; i++) { // String suff = suffixes[i]; // temp[i] = (null == suff ? null : suff.toLowerCase()); // } // suffixes = temp; // } // ArrayList result = new ArrayList(); // for (int i = 0; i < inputs.length; i++) { // String input = inputs[i]; // if (null == input) { // continue; // } // if (!ignoreCase) { // input = input.toLowerCase(); // } // for (int j = 0; j < suffixes.length; j++) { // String suffix = suffixes[j]; // if (null == suffix) { // continue; // } // if (input.endsWith(suffix)) { // result.add(input); // break; // } // } // } // return (String[]) result.toArray(new String[0]); // } // // /** // * Select from input String[] if readable directories // * @param inputs String[] of input - null ignored // * @param baseDir the base directory of the input // * @return String[] of input that end with any input // */ // public static String[] selectDirectories(String[] inputs, File baseDir) { // if (LangUtil.isEmpty(inputs)) { // return new String[0]; // } // ArrayList result = new ArrayList(); // for (int i = 0; i < inputs.length; i++) { // String input = inputs[i]; // if (null == input) { // continue; // } // File inputFile = new File(baseDir, input); // if (inputFile.canRead() && inputFile.isDirectory()) { // result.add(input); // } // } // return (String[]) result.toArray(new String[0]); // } /** * copy non-null two-dimensional String[][] * * @see extractOptions(String[], String[][]) */ public static String[][] copyStrings(String[][] in) { String[][] out = new String[in.length][]; for (int i = 0; i < out.length; i++) { out[i] = new String[in[i].length]; System.arraycopy(in[i], 0, out[i], 0, out[i].length); } return out; } /** * Extract options and arguments to input option list, returning remainder. The input options will be nullified if not found. * e.g., * * <pre> * String[] options = new String[][] { new String[] { &quot;-verbose&quot; }, new String[] { &quot;-classpath&quot;, null } }; * String[] args = extractOptions(args, options); * boolean verbose = null != options[0][0]; * boolean classpath = options[1][1]; * </pre> * * @param args the String[] input options * @param options the String[][]options to find in the input args - not null for each String[] component the first subcomponent * is the option itself, and there is one String subcomponent for each additional argument. * @return String[] of args remaining after extracting options to extracted */ public static String[] extractOptions(String[] args, String[][] options) { if (LangUtil.isEmpty(args) || LangUtil.isEmpty(options)) { return args; } BitSet foundSet = new BitSet(); String[] result = new String[args.length]; int resultIndex = 0; for (int j = 0; j < args.length; j++) { boolean found = false; for (int i = 0; !found && (i < options.length); i++) { String[] option = options[i]; LangUtil.throwIaxIfFalse(!LangUtil.isEmpty(option), "options"); String sought = option[0]; found = sought.equals(args[j]); if (found) { foundSet.set(i); int doMore = option.length - 1; if (0 < doMore) { final int MAX = j + doMore; if (MAX >= args.length) { String s = "expecting " + doMore + " args after "; throw new IllegalArgumentException(s + args[j]); } for (int k = 1; k < option.length; k++) { option[k] = args[++j]; } } } } if (!found) { result[resultIndex++] = args[j]; } } // unset any not found for (int i = 0; i < options.length; i++) { if (!foundSet.get(i)) { options[i][0] = null; } } // fixup remainder if (resultIndex < args.length) { String[] temp = new String[resultIndex]; System.arraycopy(result, 0, temp, 0, resultIndex); args = temp; } return args; } // // /** // * Extract options and arguments to input parameter list, returning // remainder. // * @param args the String[] input options // * @param validOptions the String[] options to find in the input args - // not null // * @param optionArgs the int[] number of arguments for each option in // validOptions // * (if null, then no arguments for any option) // * @param extracted the List for the matched options // * @return String[] of args remaining after extracting options to // extracted // */ // public static String[] extractOptions(String[] args, String[] // validOptions, // int[] optionArgs, List extracted) { // if (LangUtil.isEmpty(args) // || LangUtil.isEmpty(validOptions) ) { // return args; // } // if (null != optionArgs) { // if (optionArgs.length != validOptions.length) { // throw new IllegalArgumentException("args must match options"); // } // } // String[] result = new String[args.length]; // int resultIndex = 0; // for (int j = 0; j < args.length; j++) { // boolean found = false; // for (int i = 0; !found && (i < validOptions.length); i++) { // String sought = validOptions[i]; // int doMore = (null == optionArgs ? 0 : optionArgs[i]); // if (LangUtil.isEmpty(sought)) { // continue; // } // found = sought.equals(args[j]); // if (found) { // if (null != extracted) { // extracted.add(sought); // } // if (0 < doMore) { // final int MAX = j + doMore; // if (MAX >= args.length) { // String s = "expecting " + doMore + " args after "; // throw new IllegalArgumentException(s + args[j]); // } // if (null != extracted) { // while (j < MAX) { // extracted.add(args[++j]); // } // } else { // j = MAX; // } // } // break; // } // } // if (!found) { // result[resultIndex++] = args[j]; // } // } // if (resultIndex < args.length) { // String[] temp = new String[resultIndex]; // System.arraycopy(result, 0, temp, 0, resultIndex); // args = temp; // } // return args; // } // /** @return String[] of entries in validOptions found in args */ // public static String[] selectOptions(String[] args, String[] // validOptions) { // if (LangUtil.isEmpty(args) || LangUtil.isEmpty(validOptions)) { // return new String[0]; // } // ArrayList result = new ArrayList(); // for (int i = 0; i < validOptions.length; i++) { // String sought = validOptions[i]; // if (LangUtil.isEmpty(sought)) { // continue; // } // for (int j = 0; j < args.length; j++) { // if (sought.equals(args[j])) { // result.add(sought); // break; // } // } // } // return (String[]) result.toArray(new String[0]); // } // /** @return String[] of entries in validOptions found in args */ // public static String[] selectOptions(List args, String[] validOptions) { // if (LangUtil.isEmpty(args) || LangUtil.isEmpty(validOptions)) { // return new String[0]; // } // ArrayList result = new ArrayList(); // for (int i = 0; i < validOptions.length; i++) { // String sought = validOptions[i]; // if (LangUtil.isEmpty(sought)) { // continue; // } // for (Iterator iter = args.iterator(); iter.hasNext();) { // String arg = (String) iter.next(); // if (sought.equals(arg)) { // result.add(sought); // break; // } // } // } // return (String[]) result.toArray(new String[0]); // } // /** // * Generate variants of String[] options by creating an extra set for // * each option that ends with "-". If none end with "-", then an // * array equal to <code>new String[][] { options }</code> is returned; // * if one ends with "-", then two sets are returned, // * three causes eight sets, etc. // * @return String[][] with each option set. // * @throws IllegalArgumentException if any option is null or empty. // */ // public static String[][] optionVariants(String[] options) { // if ((null == options) || (0 == options.length)) { // return new String[][] { new String[0]}; // } // // be nice, don't stomp input // String[] temp = new String[options.length]; // System.arraycopy(options, 0, temp, 0, temp.length); // options = temp; // boolean[] dup = new boolean[options.length]; // int numDups = 0; // // for (int i = 0; i < options.length; i++) { // String option = options[i]; // if (LangUtil.isEmpty(option)) { // throw new IllegalArgumentException("empty option at " + i); // } // if (option.endsWith("-")) { // options[i] = option.substring(0, option.length()-1); // dup[i] = true; // numDups++; // } // } // final String[] NONE = new String[0]; // final int variants = exp(2, numDups); // final String[][] result = new String[variants][]; // // variant is a bitmap wrt doing extra value when dup[k]=true // for (int variant = 0; variant < variants; variant++) { // ArrayList next = new ArrayList(); // int nextOption = 0; // for (int k = 0; k < options.length; k++) { // if (!dup[k] || (0 != (variant & (1 << (nextOption++))))) { // next.add(options[k]); // } // } // result[variant] = (String[]) next.toArray(NONE); // } // return result; // } // // private static int exp(int base, int power) { // not in Math? // if (0 > power) { // throw new IllegalArgumentException("negative power: " + power); // } // int result = 1; // while (0 < power--) { // result *= base; // } // return result; // } // /** // * Make a copy of the array. // * @return an array with the same component type as source // * containing same elements, even if null. // * @throws IllegalArgumentException if source is null // */ // public static final Object[] copy(Object[] source) { // LangUtil.throwIaxIfNull(source, "source"); // final Class c = source.getClass().getComponentType(); // Object[] result = (Object[]) Array.newInstance(c, source.length); // System.arraycopy(source, 0, result, 0, result.length); // return result; // } /** * Convert arrays safely. The number of elements in the result will be 1 smaller for each element that is null or not * assignable. This will use sink if it has exactly the right size. The result will always have the same component type as sink. * * @return an array with the same component type as sink containing any assignable elements in source (in the same order). * @throws IllegalArgumentException if either is null */ public static Object[] safeCopy(Object[] source, Object[] sink) { final Class<?> sinkType = (null == sink ? Object.class : sink.getClass().getComponentType()); final int sourceLength = (null == source ? 0 : source.length); final int sinkLength = (null == sink ? 0 : sink.length); final int resultSize; ArrayList<Object> result = null; if (0 == sourceLength) { resultSize = 0; } else { result = new ArrayList<Object>(sourceLength); for (int i = 0; i < sourceLength; i++) { if ((null != source[i]) && (sinkType.isAssignableFrom(source[i].getClass()))) { result.add(source[i]); } } resultSize = result.size(); } if (resultSize != sinkLength) { sink = (Object[]) Array.newInstance(sinkType, result.size()); } if (0 < resultSize) { sink = result.toArray(sink); } return sink; } /** * @return a String with the unqualified class name of the class (or "null") */ public static String unqualifiedClassName(Class<?> c) { if (null == c) { return "null"; } String name = c.getName(); int loc = name.lastIndexOf("."); if (-1 != loc) { name = name.substring(1 + loc); } return name; } /** * @return a String with the unqualified class name of the object (or "null") */ public static String unqualifiedClassName(Object o) { return LangUtil.unqualifiedClassName(null == o ? null : o.getClass()); } /** inefficient way to replace all instances of sought with replace */ public static String replace(String in, String sought, String replace) { if (LangUtil.isEmpty(in) || LangUtil.isEmpty(sought)) { return in; } StringBuffer result = new StringBuffer(); final int len = sought.length(); int start = 0; int loc; while (-1 != (loc = in.indexOf(sought, start))) { result.append(in.substring(start, loc)); if (!LangUtil.isEmpty(replace)) { result.append(replace); } start = loc + len; } result.append(in.substring(start)); return result.toString(); } /** render i right-justified with a given width less than about 40 */ public static String toSizedString(long i, int width) { String result = "" + i; int size = result.length(); if (width > size) { final String pad = " "; final int padLength = pad.length(); if (width > padLength) { width = padLength; } int topad = width - size; result = pad.substring(0, topad) + result; } return result; } // /** clip StringBuffer to maximum number of lines */ // static String clipBuffer(StringBuffer buffer, int maxLines) { // if ((null == buffer) || (1 > buffer.length())) return ""; // StringBuffer result = new StringBuffer(); // int j = 0; // final int MAX = maxLines; // final int N = buffer.length(); // for (int i = 0, srcBegin = 0; i < MAX; srcBegin += j) { // // todo: replace with String variant if/since getting char? // char[] chars = new char[128]; // int srcEnd = srcBegin+chars.length; // if (srcEnd >= N) { // srcEnd = N-1; // } // if (srcBegin == srcEnd) break; // //log("srcBegin:" + srcBegin + ":srcEnd:" + srcEnd); // buffer.getChars(srcBegin, srcEnd, chars, 0); // for (j = 0; j < srcEnd-srcBegin/*chars.length*/; j++) { // char c = chars[j]; // if (c == '\n') { // i++; // j++; // break; // } // } // try { result.append(chars, 0, j); } // catch (Throwable t) { } // } // return result.toString(); // } /** * @return "({UnqualifiedExceptionClass}) {message}" */ public static String renderExceptionShort(Throwable e) { if (null == e) { return "(Throwable) null"; } return "(" + LangUtil.unqualifiedClassName(e) + ") " + e.getMessage(); } /** * Renders exception <code>t</code> after unwrapping and eliding any test packages. * * @param t <code>Throwable</code> to print. * @see #maxStackTrace */ public static String renderException(Throwable t) { return renderException(t, true); } /** * Renders exception <code>t</code>, unwrapping, optionally eliding and limiting total number of lines. * * @param t <code>Throwable</code> to print. * @param elide true to limit to 100 lines and elide test packages * @see StringChecker#TEST_PACKAGES */ public static String renderException(Throwable t, boolean elide) { if (null == t) { return "null throwable"; } t = unwrapException(t); StringBuffer stack = stackToString(t, false); if (elide) { elideEndingLines(StringChecker.TEST_PACKAGES, stack, 100); } return stack.toString(); } /** * Trim ending lines from a StringBuffer, clipping to maxLines and further removing any number of trailing lines accepted by * checker. * * @param checker returns true if trailing line should be elided. * @param stack StringBuffer with lines to elide * @param maxLines int for maximum number of resulting lines */ static void elideEndingLines(StringChecker checker, StringBuffer stack, int maxLines) { if (null == checker || (null == stack) || (0 == stack.length())) { return; } final LinkedList<String> lines = new LinkedList<String>(); StringTokenizer st = new StringTokenizer(stack.toString(), "\n\r"); while (st.hasMoreTokens() && (0 < --maxLines)) { lines.add(st.nextToken()); } st = null; String line; int elided = 0; while (!lines.isEmpty()) { line = (String) lines.getLast(); if (!checker.acceptString(line)) { break; } else { elided++; lines.removeLast(); } } if ((elided > 0) || (maxLines < 1)) { final int EOL_LEN = EOL.length(); int totalLength = 0; while (!lines.isEmpty()) { totalLength += EOL_LEN + ((String) lines.getFirst()).length(); lines.removeFirst(); } if (stack.length() > totalLength) { stack.setLength(totalLength); if (elided > 0) { stack.append(" (... " + elided + " lines...)"); } } } } /** Dump message and stack to StringBuffer. */ public static StringBuffer stackToString(Throwable throwable, boolean skipMessage) { if (null == throwable) { return new StringBuffer(); } StringWriter buf = new StringWriter(); PrintWriter writer = new PrintWriter(buf); if (!skipMessage) { writer.println(throwable.getMessage()); } throwable.printStackTrace(writer); try { buf.close(); } catch (IOException ioe) { } // ignored return buf.getBuffer(); } /** @return Throwable input or tail of any wrapped exception chain */ public static Throwable unwrapException(Throwable t) { Throwable current = t; Throwable next = null; while (current != null) { // Java 1.2 exceptions that carry exceptions if (current instanceof InvocationTargetException) { next = ((InvocationTargetException) current).getTargetException(); } else if (current instanceof ClassNotFoundException) { next = ((ClassNotFoundException) current).getException(); } else if (current instanceof ExceptionInInitializerError) { next = ((ExceptionInInitializerError) current).getException(); } else if (current instanceof PrivilegedActionException) { next = ((PrivilegedActionException) current).getException(); } else if (current instanceof SQLException) { next = ((SQLException) current).getNextException(); } // ...getException(): // javax.naming.event.NamingExceptionEvent // javax.naming.ldap.UnsolicitedNotification // javax.xml.parsers.FactoryConfigurationError // javax.xml.transform.TransformerFactoryConfigurationError // javax.xml.transform.TransformerException // org.xml.sax.SAXException // 1.4: Throwable.getCause // java.util.logging.LogRecord.getThrown() if (null == next) { break; } else { current = next; next = null; } } return current; } /** * Replacement for Arrays.asList(..) which gacks on null and returns a List in which remove is an unsupported operation. * * @param array the Object[] to convert (may be null) * @return the List corresponding to array (never null) */ public static List<Object> arrayAsList(Object[] array) { if ((null == array) || (1 > array.length)) { return Collections.emptyList(); } ArrayList<Object> list = new ArrayList<Object>(); list.addAll(Arrays.asList(array)); return list; } /** check if input contains any packages to elide. */ public static class StringChecker { static StringChecker TEST_PACKAGES = new StringChecker(new String[] { "org.aspectj.testing", "org.eclipse.jdt.internal.junit", "junit.framework.", "org.apache.tools.ant.taskdefs.optional.junit.JUnitTestRunner" }); String[] infixes; /** @param infixes adopted */ StringChecker(String[] infixes) { this.infixes = infixes; } /** @return true if input contains infixes */ public boolean acceptString(String input) { boolean result = false; if (!LangUtil.isEmpty(input)) { for (int i = 0; !result && (i < infixes.length); i++) { result = (-1 != input.indexOf(infixes[i])); } } return result; } } /** * Gen classpath. * * @param bootclasspath * @param classpath * @param classesDir * @param outputJar * @return String combining classpath elements */ public static String makeClasspath( // XXX dumb implementation String bootclasspath, String classpath, String classesDir, String outputJar) { StringBuffer sb = new StringBuffer(); addIfNotEmpty(bootclasspath, sb, File.pathSeparator); addIfNotEmpty(classpath, sb, File.pathSeparator); if (!addIfNotEmpty(classesDir, sb, File.pathSeparator)) { addIfNotEmpty(outputJar, sb, File.pathSeparator); } return sb.toString(); } /** * @param input ignored if null * @param sink the StringBuffer to add input to - return false if null * @param delimiter the String to append to input when added - ignored if empty * @return true if input + delimiter added to sink */ private static boolean addIfNotEmpty(String input, StringBuffer sink, String delimiter) { if (LangUtil.isEmpty(input) || (null == sink)) { return false; } sink.append(input); if (!LangUtil.isEmpty(delimiter)) { sink.append(delimiter); } return true; } /** * Create or initialize a process controller to run a process in another VM asynchronously. * * @param controller the ProcessController to initialize, if not null * @param classpath * @param mainClass * @param args * @return initialized ProcessController */ public static ProcessController makeProcess(ProcessController controller, String classpath, String mainClass, String[] args) { File java = LangUtil.getJavaExecutable(); ArrayList<String> cmd = new ArrayList<String>(); cmd.add(java.getAbsolutePath()); cmd.add("-classpath"); cmd.add(classpath); cmd.add(mainClass); if (!LangUtil.isEmpty(args)) { cmd.addAll(Arrays.asList(args)); } String[] command = (String[]) cmd.toArray(new String[0]); if (null == controller) { controller = new ProcessController(); } controller.init(command, mainClass); return controller; } // /** // * Create a process to run asynchronously. // * @param controller if not null, initialize this one // * @param command the String[] command to run // * @param controller the ProcessControl for streams and results // */ // public static ProcessController makeProcess( // not needed? // ProcessController controller, // String[] command, // String label) { // if (null == controller) { // controller = new ProcessController(); // } // controller.init(command, label); // return controller; // } /** * Find java executable File path from java.home system property. * * @return File associated with the java command, or null if not found. */ public static File getJavaExecutable() { String javaHome = null; File result = null; // java.home // java.class.path // java.ext.dirs try { javaHome = System.getProperty("java.home"); } catch (Throwable t) { // ignore } if (null != javaHome) { File binDir = new File(javaHome, "bin"); if (binDir.isDirectory() && binDir.canRead()) { String[] execs = new String[] { "java", "java.exe" }; for (int i = 0; i < execs.length; i++) { result = new File(binDir, execs[i]); if (result.canRead()) { break; } } } } return result; } // /** // * Sleep for a particular period (in milliseconds). // * // * @param time the long time in milliseconds to sleep // * @return true if delay succeeded, false if interrupted 100 times // */ // public static boolean sleep(long milliseconds) { // if (milliseconds == 0) { // return true; // } else if (milliseconds < 0) { // throw new IllegalArgumentException("negative: " + milliseconds); // } // return sleepUntil(milliseconds + System.currentTimeMillis()); // } /** * Sleep until a particular time. * * @param time the long time in milliseconds to sleep until * @return true if delay succeeded, false if interrupted 100 times */ public static boolean sleepUntil(long time) { if (time == 0) { return true; } else if (time < 0) { throw new IllegalArgumentException("negative: " + time); } // final Thread thread = Thread.currentThread(); long curTime = System.currentTimeMillis(); for (int i = 0; (i < 100) && (curTime < time); i++) { try { Thread.sleep(time - curTime); } catch (InterruptedException e) { // ignore } curTime = System.currentTimeMillis(); } return (curTime >= time); } /** * Handle an external process asynchrously. <code>start()</code> launches a main thread to wait for the process and pipes * streams (in child threads) through to the corresponding streams (e.g., the process System.err to this System.err). This can * complete normally, by exception, or on demand by a client. Clients can implement <code>doCompleting(..)</code> to get notice * when the process completes. * <p> * The following sample code creates a process with a completion callback starts it, and some time later retries the process. * * <pre> * LangUtil.ProcessController controller = new LangUtil.ProcessController() { * protected void doCompleting(LangUtil.ProcessController.Thrown thrown, int result) { * // signal result * } * }; * controller.init(new String[] { &quot;java&quot;, &quot;-version&quot; }, &quot;java version&quot;); * controller.start(); * // some time later... * // retry... * if (!controller.completed()) { * controller.stop(); * controller.reinit(); * controller.start(); * } * </pre> * * <u>warning</u>: Currently this does not close the input or output streams, since doing so prevents their use later. */ public static class ProcessController { /* * XXX not verified thread-safe, but should be. Known problems: - user stops (completed = true) then exception thrown from * destroying process (stop() expects !completed) ... */ private String[] command; private String[] envp; private String label; private boolean init; private boolean started; private boolean completed; /** if true, stopped by user when not completed */ private boolean userStopped; private Process process; private FileUtil.Pipe errStream; private FileUtil.Pipe outStream; private FileUtil.Pipe inStream; private ByteArrayOutputStream errSnoop; private ByteArrayOutputStream outSnoop; private int result; private Thrown thrown; public ProcessController() { } /** * Permit re-running using the same command if this is not started or if completed. Can also call this when done with * results to release references associated with results (e.g., stack traces). */ public final void reinit() { if (!init) { throw new IllegalStateException("must init(..) before reinit()"); } if (started && !completed) { throw new IllegalStateException("not completed - do stop()"); } // init everything but command and label started = false; completed = false; result = Integer.MIN_VALUE; thrown = null; process = null; errStream = null; outStream = null; inStream = null; } public final void init(String classpath, String mainClass, String[] args) { init(LangUtil.getJavaExecutable(), classpath, mainClass, args); } public final void init(File java, String classpath, String mainClass, String[] args) { LangUtil.throwIaxIfNull(java, "java"); LangUtil.throwIaxIfNull(mainClass, "mainClass"); LangUtil.throwIaxIfNull(args, "args"); ArrayList<String> cmd = new ArrayList<String>(); cmd.add(java.getAbsolutePath()); cmd.add("-classpath"); cmd.add(classpath); cmd.add(mainClass); if (!LangUtil.isEmpty(args)) { cmd.addAll(Arrays.asList(args)); } init((String[]) cmd.toArray(new String[0]), mainClass); } public final void init(String[] command, String label) { this.command = (String[]) LangUtil.safeCopy(command, new String[0]); if (1 > this.command.length) { throw new IllegalArgumentException("empty command"); } this.label = LangUtil.isEmpty(label) ? command[0] : label; init = true; reinit(); } public final void setEnvp(String[] envp) { this.envp = (String[]) LangUtil.safeCopy(envp, new String[0]); if (1 > this.envp.length) { throw new IllegalArgumentException("empty envp"); } } public final void setErrSnoop(ByteArrayOutputStream snoop) { errSnoop = snoop; if (null != errStream) { errStream.setSnoop(errSnoop); } } public final void setOutSnoop(ByteArrayOutputStream snoop) { outSnoop = snoop; if (null != outStream) { outStream.setSnoop(outSnoop); } } /** * Start running the process and pipes asynchronously. * * @return Thread started or null if unable to start thread (results available via <code>getThrown()</code>, etc.) */ public final Thread start() { if (!init) { throw new IllegalStateException("not initialized"); } synchronized (this) { if (started) { throw new IllegalStateException("already started"); } started = true; } try { process = Runtime.getRuntime().exec(command); } catch (IOException e) { stop(e, Integer.MIN_VALUE); return null; } errStream = new FileUtil.Pipe(process.getErrorStream(), System.err); if (null != errSnoop) { errStream.setSnoop(errSnoop); } outStream = new FileUtil.Pipe(process.getInputStream(), System.out); if (null != outSnoop) { outStream.setSnoop(outSnoop); } inStream = new FileUtil.Pipe(System.in, process.getOutputStream()); // start 4 threads, process & pipes for in, err, out Runnable processRunner = new Runnable() { public void run() { Throwable thrown = null; int result = Integer.MIN_VALUE; try { // pipe threads are children new Thread(errStream).start(); new Thread(outStream).start(); new Thread(inStream).start(); process.waitFor(); result = process.exitValue(); } catch (Throwable e) { thrown = e; } finally { stop(thrown, result); } } }; Thread result = new Thread(processRunner, label); result.start(); return result; } /** * Destroy any process, stop any pipes. This waits for the pipes to clear (reading until no more input is available), but * does not wait for the input stream for the pipe to close (i.e., not waiting for end-of-file on input stream). */ public final synchronized void stop() { if (completed) { return; } userStopped = true; stop(null, Integer.MIN_VALUE); } public final String[] getCommand() { String[] toCopy = command; if (LangUtil.isEmpty(toCopy)) { return new String[0]; } String[] result = new String[toCopy.length]; System.arraycopy(toCopy, 0, result, 0, result.length); return result; } public final boolean completed() { return completed; } public final boolean started() { return started; } public final boolean userStopped() { return userStopped; } /** * Get any Throwable thrown. Note that the process can complete normally (with a valid return value), at the same time the * pipes throw exceptions, and that this may return some exceptions even if the process is not complete. * * @return null if not complete or Thrown containing exceptions thrown by the process and streams. */ public final Thrown getThrown() { // cache this return makeThrown(null); } public final int getResult() { return result; } /** * Subclasses implement this to get synchronous notice of completion. All pipes and processes should be complete at this * time. To get the exceptions thrown for the pipes, use <code>getThrown()</code>. If there is an exception, the process * completed abruptly (including side-effects of the user halting the process). If <code>userStopped()</code> is true, then * some client asked that the process be destroyed using <code>stop()</code>. Otherwise, the result code should be the * result value returned by the process. * * @param thrown same as <code>getThrown().fromProcess</code>. * @param result same as <code>getResult()</code> * @see getThrown() * @see getResult() * @see stop() */ protected void doCompleting(Thrown thrown, int result) { } /** * Handle termination (on-demand, abrupt, or normal) by destroying and/or halting process and pipes. * * @param thrown ignored if null * @param result ignored if Integer.MIN_VALUE */ private final synchronized void stop(Throwable thrown, int result) { if (completed) { throw new IllegalStateException("already completed"); } else if (null != this.thrown) { throw new IllegalStateException("already set thrown: " + thrown); } // assert null == this.thrown this.thrown = makeThrown(thrown); if (null != process) { process.destroy(); } if (null != inStream) { inStream.halt(false, true); // this will block if waiting inStream = null; } if (null != outStream) { outStream.halt(true, true); outStream = null; } if (null != errStream) { errStream.halt(true, true); errStream = null; } if (Integer.MIN_VALUE != result) { this.result = result; } completed = true; doCompleting(this.thrown, result); } /** * Create snapshot of Throwable's thrown. * * @param thrown ignored if null or if this.thrown is not null */ private final synchronized Thrown makeThrown(Throwable processThrown) { if (null != thrown) { return thrown; } return new Thrown(processThrown, (null == outStream ? null : outStream.getThrown()), (null == errStream ? null : errStream.getThrown()), (null == inStream ? null : inStream.getThrown())); } public static class Thrown { public final Throwable fromProcess; public final Throwable fromErrPipe; public final Throwable fromOutPipe; public final Throwable fromInPipe; /** true only if some Throwable is not null */ public final boolean thrown; private Thrown(Throwable fromProcess, Throwable fromOutPipe, Throwable fromErrPipe, Throwable fromInPipe) { this.fromProcess = fromProcess; this.fromErrPipe = fromErrPipe; this.fromOutPipe = fromOutPipe; this.fromInPipe = fromInPipe; thrown = ((null != fromProcess) || (null != fromInPipe) || (null != fromOutPipe) || (null != fromErrPipe)); } public String toString() { StringBuffer sb = new StringBuffer(); append(sb, fromProcess, "process"); append(sb, fromOutPipe, " stdout"); append(sb, fromErrPipe, " stderr"); append(sb, fromInPipe, " stdin"); if (0 == sb.length()) { return "Thrown (none)"; } else { return sb.toString(); } } private void append(StringBuffer sb, Throwable thrown, String label) { if (null != thrown) { sb.append("from " + label + ": "); sb.append(LangUtil.renderExceptionShort(thrown)); sb.append(LangUtil.EOL); } } } // class Thrown } }
391,123
Bug 391123 Added support for more cache backing(s)
null
closed fixed
df1823b
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2012-10-29T19:46:03Z"
"2012-10-04T14:13:20Z"
weaver/src/org/aspectj/weaver/tools/cache/AbstractIndexedFileCacheBacking.java
/******************************************************************************* * Copyright (c) 2012 Contributors. * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Eclipse Public License v1.0 * which accompanies this distribution and is available at * http://eclipse.org/legal/epl-v10.html * * Contributors: * John Kew (vmware) initial implementation * Lyor Goldstein (vmware) add support for weaved class being re-defined *******************************************************************************/ package org.aspectj.weaver.tools.cache; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.io.StreamCorruptedException; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.LinkedList; import java.util.Map; import java.util.TreeMap; import org.aspectj.util.LangUtil; /** * Uses an <code>index</code> file to keep track of the cached entries */ public abstract class AbstractIndexedFileCacheBacking extends AbstractFileCacheBacking { /** * Default name of cache index file - assumed to contain {@link IndexEntry}-s */ public static final String INDEX_FILE = "cache.idx"; protected static final IndexEntry[] EMPTY_INDEX=new IndexEntry[0]; protected static final String[] EMPTY_KEYS=new String[0]; private final File indexFile; protected AbstractIndexedFileCacheBacking(File cacheDir) { super(cacheDir); indexFile = new File(cacheDir, INDEX_FILE); } public File getIndexFile () { return indexFile; } public String[] getKeys(String regex) { Map<String, IndexEntry> index=getIndex(); if ((index == null) || index.isEmpty()) { return EMPTY_KEYS; } Collection<String> matches=new LinkedList<String>(); synchronized(index) { for (String key : index.keySet()) { if (key.matches(regex)) { matches.add(key); } } } if (matches.isEmpty()) { return EMPTY_KEYS; } else { return matches.toArray(new String[matches.size()]); } } protected Map<String, IndexEntry> readIndex () { return readIndex(getCacheDirectory(), getIndexFile()); } protected void writeIndex () { writeIndex(getIndexFile()); } protected void writeIndex (File file) { try { writeIndex(file, getIndex()); } catch(Exception e) { if ((logger != null) && logger.isTraceEnabled()) { logger.warn("writeIndex(" + file + ") " + e.getClass().getSimpleName() + ": " + e.getMessage(), e); } } } protected abstract Map<String, IndexEntry> getIndex (); protected Map<String, IndexEntry> readIndex (File cacheDir, File cacheFile) { Map<String, IndexEntry> indexMap=new TreeMap<String, IndexEntry>(); IndexEntry[] idxValues=readIndex(cacheFile); if (LangUtil.isEmpty(idxValues)) { if ((logger != null) && logger.isTraceEnabled()) { logger.debug("readIndex(" + cacheFile + ") no index entries"); } return indexMap; } for (IndexEntry ie : idxValues) { IndexEntry resEntry=resolveIndexMapEntry(cacheDir, ie); if (resEntry != null) { indexMap.put(resEntry.key, resEntry); } else if ((logger != null) && logger.isTraceEnabled()) { logger.debug("readIndex(" + cacheFile + ") skip " + ie.key); } } return indexMap; } protected IndexEntry resolveIndexMapEntry (File cacheDir, IndexEntry ie) { return ie; } public IndexEntry[] readIndex(File indexFile) { if (!indexFile.canRead()) { return EMPTY_INDEX; } ObjectInputStream ois = null; try { ois = new ObjectInputStream(new FileInputStream(indexFile)); return (IndexEntry[]) ois.readObject(); } catch (Exception e) { if ((logger != null) && logger.isTraceEnabled()) { logger.error("Failed (" + e.getClass().getSimpleName() + ")" + " to read index from " + indexFile.getAbsolutePath() + " : " + e.getMessage(), e); } delete(indexFile); } finally { close(ois, indexFile); } return EMPTY_INDEX; } protected void writeIndex (File indexFile, Map<String,? extends IndexEntry> index) throws IOException { writeIndex(indexFile, LangUtil.isEmpty(index) ? Collections.<IndexEntry>emptyList() : index.values()); } protected void writeIndex (File indexFile, IndexEntry ... entries) throws IOException { writeIndex(indexFile, LangUtil.isEmpty(entries) ? Collections.<IndexEntry>emptyList() : Arrays.asList(entries)); } protected void writeIndex (File indexFile, Collection<? extends IndexEntry> entries) throws IOException { File indexDir=indexFile.getParentFile(); if ((!indexDir.exists()) && (!indexDir.mkdirs())) { throw new IOException("Failed to create path to " + indexFile.getAbsolutePath()); } int numEntries=LangUtil.isEmpty(entries) ? 0 : entries.size(); IndexEntry[] entryValues=(numEntries <= 0) ? null : entries.toArray(new IndexEntry[numEntries]); // if no entries, simply delete the index file if (LangUtil.isEmpty(entryValues)) { if (indexFile.exists() && (!indexFile.delete())) { throw new StreamCorruptedException("Failed to clean up index file at " + indexFile.getAbsolutePath()); } return; } ObjectOutputStream oos=new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream(indexFile), 4096)); try { oos.writeObject(entryValues); } finally { close(oos, indexFile); } } /** * The default index entry in the index file */ public static class IndexEntry implements Serializable, Cloneable { private static final long serialVersionUID = 756391290557029363L; public String key; public boolean generated; public boolean ignored; public long crcClass; public long crcWeaved; public IndexEntry () { super(); } @Override public IndexEntry clone () { try { return getClass().cast(super.clone()); } catch(CloneNotSupportedException e) { throw new RuntimeException("Failed to clone: " + toString() + ": " + e.getMessage(), e); } } @Override public int hashCode() { return (int) (key.hashCode() + (generated ? 1 : 0) + (ignored ? 1 : 0) + crcClass + crcWeaved); } @Override public boolean equals(Object obj) { if (obj == null) return false; if (this == obj) return true; if (getClass() != obj.getClass()) return false; IndexEntry other=(IndexEntry) obj; if (this.key.equals(other.key) && (this.ignored == other.ignored) && (this.generated == other.generated) && (this.crcClass == other.crcClass) && (this.crcWeaved == other.crcWeaved)) { return true; } else { return false; } } @Override public String toString() { return key + "[" + (generated ? "generated" : "ignored") + "]" + ";crcClass=0x" + Long.toHexString(crcClass) + ";crcWeaved=0x" + Long.toHexString(crcWeaved) ; } } }
391,123
Bug 391123 Added support for more cache backing(s)
null
closed fixed
df1823b
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2012-10-29T19:46:03Z"
"2012-10-04T14:13:20Z"
weaver/src/org/aspectj/weaver/tools/cache/AsynchronousFileCacheBacking.java
391,123
Bug 391123 Added support for more cache backing(s)
null
closed fixed
df1823b
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2012-10-29T19:46:03Z"
"2012-10-04T14:13:20Z"
weaver/src/org/aspectj/weaver/tools/cache/DefaultFileCacheBacking.java
/******************************************************************************* * Copyright (c) 2012 Contributors. * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Eclipse Public License v1.0 * which accompanies this distribution and is available at * http://eclipse.org/legal/epl-v10.html * * Contributors: * John Kew (vmware) initial implementation * Lyor Goldstein (vmware) add support for weaved class being re-defined *******************************************************************************/ package org.aspectj.weaver.tools.cache; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.FilenameFilter; import java.io.OutputStream; import java.util.Map; import org.aspectj.bridge.MessageUtil; import org.aspectj.util.FileUtil; import org.aspectj.util.LangUtil; /** * Naive File-Backed Class Cache with no expiry or application * centric invalidation. * <p/> * Enabled with the system property, "aj.weaving.cache.dir" * If this system property is not set, no caching will be * performed. * <p/> * A CRC checksum is stored alongside the class file to verify * the bytes on read. If for some reason there is an error * reading either the class or crc file, or if the crc does not * match the class data the cache entry is deleted. * <p/> * An alternate implementation of this could store the class file * as a jar/zip directly, which would have the required crc; as * a first pass however it is somewhat useful to view these files * in expanded form for debugging. */ public class DefaultFileCacheBacking extends AbstractIndexedFileCacheBacking { private final Map<String, IndexEntry> index; private static final Object LOCK = new Object(); protected DefaultFileCacheBacking(File cacheDir) { super(cacheDir); index = readIndex(); } public static final DefaultFileCacheBacking createBacking(File cacheDir) { if (!cacheDir.exists()) { if (!cacheDir.mkdirs()) { MessageUtil.error("Unable to create cache directory at " + cacheDir.getName()); return null; } } else if (!cacheDir.isDirectory()) { MessageUtil.error("Not a cache directory at " + cacheDir.getName()); return null; } if (!cacheDir.canWrite()) { MessageUtil.error("Cache directory is not writable at " + cacheDir.getName()); return null; } return new DefaultFileCacheBacking(cacheDir); } @Override protected Map<String, IndexEntry> getIndex() { return index; } @Override protected IndexEntry resolveIndexMapEntry (File cacheDir, IndexEntry ie) { File cacheEntry = new File(cacheDir, ie.key); if (ie.ignored || cacheEntry.canRead()) { return ie; } else { return null; } } private void removeIndexEntry(String key) { synchronized (LOCK) { index.remove(key); writeIndex(); } } private void addIndexEntry(IndexEntry ie) { synchronized (LOCK) { index.put(ie.key, ie); writeIndex(); } } @Override protected Map<String, IndexEntry> readIndex() { synchronized (LOCK) { return super.readIndex(); } } @Override protected void writeIndex() { synchronized (LOCK) { super.writeIndex(); } } public void clear() { File cacheDir=getCacheDirectory(); int numDeleted=0; synchronized (LOCK) { numDeleted = FileUtil.deleteContents(cacheDir); } if ((numDeleted > 0) && (logger != null) && logger.isTraceEnabled()) { logger.info("clear(" + cacheDir + ") deleted"); } } public static CacheBacking createBacking(String scope) { String cache = System.getProperty(WEAVED_CLASS_CACHE_DIR); if (cache == null) { return null; } File cacheDir = new File(cache, scope); return createBacking(cacheDir); } @Override public String[] getKeys(final String regex) { File cacheDirectory = getCacheDirectory(); File[] files = cacheDirectory.listFiles(new FilenameFilter() { public boolean accept(File file, String s) { if (s.matches(regex)) { return true; } return false; } }); if (LangUtil.isEmpty(files)) { return EMPTY_KEYS; } String[] keys = new String[files.length]; for (int i = 0; i < files.length; i++) { keys[i] = files[i].getName(); } return keys; } public CachedClassEntry get(CachedClassReference ref, byte[] originalBytes) { File cacheDirectory = getCacheDirectory(); String refKey=ref.getKey(); File cacheFile = new File(cacheDirectory, refKey); IndexEntry ie = index.get(refKey); if (ie == null) { // no index, delete delete(cacheFile); return null; } // check if original file changed if (crc(originalBytes) != ie.crcClass) { delete(cacheFile); return null; } if (ie.ignored) { return new CachedClassEntry(ref, WeavedClassCache.ZERO_BYTES, CachedClassEntry.EntryType.IGNORED); } if (cacheFile.canRead()) { byte[] bytes = read(cacheFile, ie.crcWeaved); if (bytes != null) { if (!ie.generated) { return new CachedClassEntry(ref, bytes, CachedClassEntry.EntryType.WEAVED); } else { return new CachedClassEntry(ref, bytes, CachedClassEntry.EntryType.GENERATED); } } } return null; } public void put(CachedClassEntry entry, byte[] originalBytes) { File cacheDirectory = getCacheDirectory(); String refKey = entry.getKey(); IndexEntry ie = index.get(refKey); File cacheFile = new File(cacheDirectory, refKey); final boolean writeEntryBytes; // check if original bytes changed or the ignored/generated flags if ((ie != null) && ((ie.ignored != entry.isIgnored()) || (ie.generated != entry.isGenerated()) || (crc(originalBytes) != ie.crcClass))) { delete(cacheFile); writeEntryBytes = true; } else { writeEntryBytes = !cacheFile.exists(); } if (writeEntryBytes) { ie = new IndexEntry(); ie.key = entry.getKey(); ie.generated = entry.isGenerated(); ie.ignored = entry.isIgnored(); if (!entry.isIgnored()) { ie.crcClass = crc(originalBytes); ie.crcWeaved = write(cacheFile, entry.getBytes()); } addIndexEntry(ie); } } public void remove(CachedClassReference ref) { File cacheDirectory = getCacheDirectory(); String refKey = ref.getKey(); File cacheFile = new File(cacheDirectory, refKey); synchronized (LOCK) { removeIndexEntry(refKey); delete(cacheFile); } } @Override protected void delete(File file) { synchronized (LOCK) { super.delete(file); } } protected byte[] read(File file, long expectedCRC) { byte[] bytes=null; synchronized (LOCK) { FileInputStream fis = null; try { fis = new FileInputStream(file); bytes = FileUtil.readAsByteArray(fis); } catch (Exception e) { if ((logger != null) && logger.isTraceEnabled()) { logger.warn("read(" + file.getAbsolutePath() + ")" + " failed (" + e.getClass().getSimpleName() + ")" + " to read contents: " + e.getMessage(), e); } } finally { close(fis, file); } // delete the file if there was an exception reading it or mismatched crc if ((bytes == null) || (crc(bytes) != expectedCRC)) { delete(file); return null; } } return bytes; } protected long write(File file, byte[] bytes) { synchronized (LOCK) { if (file.exists()) { return -1L; } OutputStream out = null; try { out = new FileOutputStream(file); out.write(bytes); } catch (Exception e) { if ((logger != null) && logger.isTraceEnabled()) { logger.warn("write(" + file.getAbsolutePath() + ")" + " failed (" + e.getClass().getSimpleName() + ")" + " to write contents: " + e.getMessage(), e); } // delete the file if there was an exception writing it delete(file); return -1L; } finally { close(out, file); } return crc(bytes); } } }
391,123
Bug 391123 Added support for more cache backing(s)
null
closed fixed
df1823b
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2012-10-29T19:46:03Z"
"2012-10-04T14:13:20Z"
weaver/src/org/aspectj/weaver/tools/cache/FlatFileCacheBacking.java
391,123
Bug 391123 Added support for more cache backing(s)
null
closed fixed
df1823b
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2012-10-29T19:46:03Z"
"2012-10-04T14:13:20Z"
weaver/src/org/aspectj/weaver/tools/cache/ZippedFileCacheBacking.java
391,123
Bug 391123 Added support for more cache backing(s)
null
closed fixed
df1823b
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2012-10-29T19:46:03Z"
"2012-10-04T14:13:20Z"
weaver/testsrc/org/aspectj/weaver/tools/cache/AbstractCacheBackingTestSupport.java
391,123
Bug 391123 Added support for more cache backing(s)
null
closed fixed
df1823b
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2012-10-29T19:46:03Z"
"2012-10-04T14:13:20Z"
weaver/testsrc/org/aspectj/weaver/tools/cache/AsynchronousFileCacheBackingTestSupport.java
391,123
Bug 391123 Added support for more cache backing(s)
null
closed fixed
df1823b
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2012-10-29T19:46:03Z"
"2012-10-04T14:13:20Z"
weaver/testsrc/org/aspectj/weaver/tools/cache/CacheTests.java
/******************************************************************************* * Copyright (c) 2012 Contributors. * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Eclipse Public License v1.0 * which accompanies this distribution and is available at * http://eclipse.org/legal/epl-v10.html * * Contributors: * John Kew (vmware) initial implementation *******************************************************************************/ package org.aspectj.weaver.tools.cache; import junit.framework.Test; import junit.framework.TestSuite; /** */ public class CacheTests { public static Test suite() { TestSuite suite = new TestSuite(CacheTests.class.getName()); suite.addTestSuite(SimpleClassCacheTest.class); suite.addTestSuite(WeavedClassCacheTest.class); suite.addTestSuite(DefaultCacheKeyResolverTest.class); suite.addTestSuite(DefaultFileCacheBackingTest.class); return suite; } }
391,123
Bug 391123 Added support for more cache backing(s)
null
closed fixed
df1823b
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2012-10-29T19:46:03Z"
"2012-10-04T14:13:20Z"
weaver/testsrc/org/aspectj/weaver/tools/cache/DefaultCacheKeyResolverTest.java
/******************************************************************************* * Copyright (c) 2012 Contributors. * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Eclipse Public License v1.0 * which accompanies this distribution and is available at * http://eclipse.org/legal/epl-v10.html * * Contributors: * John Kew (vmware) initial implementation *******************************************************************************/ package org.aspectj.weaver.tools.cache; import junit.framework.TestCase; import java.net.URL; import java.net.URLClassLoader; import java.util.Arrays; import java.util.Collections; /** */ public class DefaultCacheKeyResolverTest extends TestCase { byte[] FAKE_BYTES = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; String FAKE_CLASS = "com.example.foo.Bar"; DefaultCacheKeyResolver resolver = new DefaultCacheKeyResolver(); class BasicTestCL extends ClassLoader { } class URLTestCL extends URLClassLoader { public URLTestCL(URL... urls) { super(urls); } } public void testNonURLClassLoaderScope() throws Exception { String scope = resolver.createClassLoaderScope(new BasicTestCL(), Collections.<String>emptyList()); assertTrue(scope.startsWith(BasicTestCL.class.getSimpleName())); } public void testCreateURLClassLoaderScope() throws Exception { URL testURLA = new URL("http://example.com"); URL testURLB = new URL("file:///tmp"); URL testURLC = new URL("ftp://ftp.example.com"); URLTestCL A = new URLTestCL(testURLA); URLTestCL AB = new URLTestCL(testURLA, testURLB); URLTestCL BC = new URLTestCL(testURLB, testURLC); URLTestCL BC2 = new URLTestCL(testURLC, testURLB); String[] a = {"one", "two", "three", "four"}; String[] a2 = {"one", "two", "three"}; String scopeAa = resolver.createClassLoaderScope(A, Arrays.asList(a)); String scopeABa = resolver.createClassLoaderScope(AB, Arrays.asList(a)); String scopeBCa = resolver.createClassLoaderScope(BC, Arrays.asList(a)); String scopeBC2a = resolver.createClassLoaderScope(BC2, Arrays.asList(a)); String scopeAa2 = resolver.createClassLoaderScope(A, Arrays.asList(a2)); String scopeABa2 = resolver.createClassLoaderScope(AB, Arrays.asList(a2)); String scopeBCa2 = resolver.createClassLoaderScope(BC, Arrays.asList(a2)); String scopeBC2a2 = resolver.createClassLoaderScope(BC2, Arrays.asList(a2)); assertFalse(scopeAa.equals(scopeABa)); assertFalse(scopeAa.equals(scopeBCa)); assertFalse(scopeABa.equals(scopeBCa)); assertTrue(scopeBC2a.equals(scopeBCa)); assertFalse(scopeAa.equals(scopeAa2)); assertFalse(scopeABa.equals(scopeABa2)); assertFalse(scopeBCa.equals(scopeBCa2)); assertFalse(scopeBC2a.equals(scopeBC2a2)); } public void testCreateGeneratedCacheKey() throws Exception { CachedClassReference ref = resolver.generatedKey(FAKE_CLASS); assertTrue(ref.getKey().startsWith(FAKE_CLASS)); assertTrue(ref.getKey().matches(resolver.getGeneratedRegex())); assertEquals(FAKE_CLASS, resolver.keyToClass(ref.getKey())); } public void testCreateCacheKey() throws Exception { // crc hashing CachedClassReference ref = resolver.weavedKey(FAKE_CLASS, FAKE_BYTES); assertTrue("key " + ref.getKey() + " does not match " + resolver.getWeavedRegex(), ref.getKey().matches(resolver.getWeavedRegex())); String className = resolver.keyToClass(ref.getKey()); assertEquals("class " + FAKE_CLASS + " != " + className, FAKE_CLASS, className); } }
391,123
Bug 391123 Added support for more cache backing(s)
null
closed fixed
df1823b
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2012-10-29T19:46:03Z"
"2012-10-04T14:13:20Z"
weaver/testsrc/org/aspectj/weaver/tools/cache/DefaultFileCacheBackingTest.java
/******************************************************************************* * Copyright (c) 2012 Contributors. * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Eclipse Public License v1.0 * which accompanies this distribution and is available at * http://eclipse.org/legal/epl-v10.html * * Contributors: * John Kew (vmware) initial implementation * Lyor Goldstein (vmware) add support for weaved class being re-defined *******************************************************************************/ package org.aspectj.weaver.tools.cache; import java.io.File; import java.util.zip.CRC32; import junit.framework.TestCase; import org.aspectj.util.FileUtil; import org.aspectj.util.LangUtil; import org.aspectj.weaver.tools.cache.AbstractIndexedFileCacheBacking.IndexEntry; /** */ public class DefaultFileCacheBackingTest extends TestCase { private final byte[] FAKE_BYTES = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; private final String FAKE_CLASS = "com.example.foo.Bar"; private final CacheKeyResolver resolver = new DefaultCacheKeyResolver(); private final CachedClassReference fakeRef = resolver.weavedKey(FAKE_CLASS, FAKE_BYTES); private final String fakeKey=fakeRef.getKey(); private File root; public DefaultFileCacheBackingTest () { super(); } @Override public void setUp() throws Exception { if (root == null) { File tempFile = File.createTempFile("aspectj", "test"); File tempDir = tempFile.getParentFile(); root = new File(tempDir, "aspectj-test-cache"); } } @Override public void tearDown() throws Exception { FileUtil.deleteContents(root); root = null; } public void testCreateBacking() throws Exception { CacheBacking backing = DefaultFileCacheBacking.createBacking(root); assertNotNull(backing); assertTrue("Root folder not created: " + root, root.exists()); assertTrue("Root folder not a directory: " + root, root.isDirectory()); } public void testClear() { CacheBacking backing = DefaultFileCacheBacking.createBacking(root); backing.put(new CachedClassEntry(fakeRef, FAKE_BYTES, CachedClassEntry.EntryType.WEAVED), FAKE_BYTES); assertNotNull(backing.get(fakeRef, FAKE_BYTES)); backing.clear(); assertNull(backing.get(fakeRef, FAKE_BYTES)); } private CachedClassEntry createTestEntry(String key) { return new CachedClassEntry(new CachedClassReference(key, key), FAKE_BYTES, CachedClassEntry.EntryType.WEAVED); } public void testGetKeys() throws Exception { CacheBacking backing = DefaultFileCacheBacking.createBacking(root); backing.put(createTestEntry("apple"), FAKE_BYTES); backing.put(createTestEntry("apply"), FAKE_BYTES); backing.put(createTestEntry("orange"), FAKE_BYTES); String[] matches = backing.getKeys("app.*"); assertEquals(2, matches.length); matches = backing.getKeys("orange"); assertEquals(1, matches.length); assertEquals("orange", matches[0]); } public void testPut() throws Exception { CacheBacking backing = DefaultFileCacheBacking.createBacking(root); backing.put(new CachedClassEntry(fakeRef, FAKE_BYTES, CachedClassEntry.EntryType.WEAVED), FAKE_BYTES); File cachedFile = new File(root, fakeKey); assertTrue(cachedFile.exists()); assertTrue(cachedFile.isFile()); assertEquals(FAKE_BYTES.length, cachedFile.length()); } public void testGet() throws Exception { DefaultFileCacheBacking backing = DefaultFileCacheBacking.createBacking(root); assertNull(backing.get(fakeRef, FAKE_BYTES)); backing.put(new CachedClassEntry(fakeRef, FAKE_BYTES, CachedClassEntry.EntryType.WEAVED), FAKE_BYTES); File cachedFile = new File(root, fakeKey); assertTrue(cachedFile.isFile()); assertEquals(FAKE_BYTES.length, cachedFile.length()); CRC32 expectedCRC = new CRC32(); expectedCRC.update(FAKE_BYTES); assertTrue(indexEntryExists(backing, fakeKey, expectedCRC.getValue())); CachedClassEntry entry = backing.get(fakeRef, FAKE_BYTES); assertEquals(FAKE_BYTES.length, entry.getBytes().length); } public void testRemove() throws Exception { DefaultFileCacheBacking backing = DefaultFileCacheBacking.createBacking(root); backing.put(new CachedClassEntry(fakeRef, FAKE_BYTES, CachedClassEntry.EntryType.WEAVED), FAKE_BYTES); File cachedFile = new File(root, fakeKey); assertTrue("Cached file not found: " + cachedFile, cachedFile.exists()); assertTrue("Cached file not a file: " + cachedFile, cachedFile.isFile()); CRC32 expectedCRC = new CRC32(); expectedCRC.update(FAKE_BYTES); assertTrue("Cached entry index not found", indexEntryExists(backing, fakeKey, expectedCRC.getValue())); backing.remove(fakeRef); assertFalse("CacheFile Still exists: " + cachedFile, cachedFile.exists()); assertFalse("Cached file is a file: " + cachedFile, cachedFile.isFile()); assertFalse("Cached entry index not removed", indexEntryExists(backing, fakeKey, expectedCRC.getValue())); } public void testMultiFile() throws Exception { CachedClassEntry entry; File cachedFile; CRC32 expectedCRC = new CRC32(); expectedCRC.update(FAKE_BYTES); DefaultFileCacheBacking backing = DefaultFileCacheBacking.createBacking(root); // add weaved CachedClassReference wref = resolver.weavedKey(FAKE_CLASS + "WEAVED", FAKE_BYTES); entry = new CachedClassEntry(wref, FAKE_BYTES, CachedClassEntry.EntryType.WEAVED); backing.put(entry, FAKE_BYTES); cachedFile = new File(root, wref.getKey()); assertTrue(cachedFile.exists()); assertTrue(cachedFile.isFile()); assertTrue(indexEntryExists(backing, wref.getKey(), expectedCRC.getValue())); // add generated CachedClassReference gref = resolver.generatedKey(FAKE_CLASS + "GENERATED"); entry = new CachedClassEntry(gref, FAKE_BYTES, CachedClassEntry.EntryType.GENERATED); backing.put(entry, FAKE_BYTES); cachedFile = new File(root, gref.getKey()); assertTrue(cachedFile.exists()); assertTrue(cachedFile.isFile()); assertTrue(indexEntryExists(backing, gref.getKey(), expectedCRC.getValue())); // add ignored CachedClassReference iref = resolver.generatedKey(FAKE_CLASS + "IGNORED"); entry = new CachedClassEntry(iref, FAKE_BYTES, CachedClassEntry.EntryType.IGNORED); backing.put(entry, FAKE_BYTES); cachedFile = new File(root, iref.getKey()); assertFalse(cachedFile.exists()); assertTrue(indexEntryExists(backing, iref.getKey(), expectedCRC.getValue())); backing.remove(wref); backing.remove(gref); backing.remove(iref); } public void testOriginalClassBytesChanged () { DefaultFileCacheBacking backing = DefaultFileCacheBacking.createBacking(root); backing.put(new CachedClassEntry(fakeRef, FAKE_BYTES, CachedClassEntry.EntryType.WEAVED), FAKE_BYTES); CachedClassEntry entry = backing.get(fakeRef, FAKE_BYTES); assertNotNull("No initial entry", entry); byte[] newBytes=new byte[FAKE_BYTES.length]; for (int index=0; index < FAKE_BYTES.length; index++) { newBytes[index] = (byte) (0 - FAKE_BYTES[index]); } entry = backing.get(fakeRef, newBytes); assertNull("Unexpected modified bytes entry: " + entry, entry); File cachedFile = new File(root, fakeKey); assertFalse("Cache file not removed", cachedFile.exists()); } private boolean indexEntryExists(AbstractIndexedFileCacheBacking cache, String key, long expectedCRC) throws Exception { long storedCRC = 0L; IndexEntry[] index = cache.readIndex(new File(root, AbstractIndexedFileCacheBacking.INDEX_FILE)); if (LangUtil.isEmpty(index)) { return false; } for (IndexEntry ie : index) { if (ie.key.equals(key)) { storedCRC = ie.crcWeaved; if (!ie.ignored) { assertEquals(expectedCRC, storedCRC); } return true; } } return false; } }
391,123
Bug 391123 Added support for more cache backing(s)
null
closed fixed
df1823b
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2012-10-29T19:46:03Z"
"2012-10-04T14:13:20Z"
weaver/testsrc/org/aspectj/weaver/tools/cache/FlatFileCacheBackingTest.java
391,123
Bug 391123 Added support for more cache backing(s)
null
closed fixed
df1823b
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2012-10-29T19:46:03Z"
"2012-10-04T14:13:20Z"
weaver/testsrc/org/aspectj/weaver/tools/cache/SimpleClassCacheTest.java
/******************************************************************************* * Copyright (c) 2012 Contributors. * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Eclipse Public License v1.0 * which accompanies this distribution and is available at * http://eclipse.org/legal/epl-v10.html * * Contributors: * Abraham Nevado (lucierna) initial implementation ********************************************************************************/ package org.aspectj.weaver.tools.cache; import junit.framework.TestCase; import org.aspectj.bridge.AbortException; import org.aspectj.bridge.IMessage; import org.aspectj.bridge.IMessageHandler; import org.aspectj.weaver.tools.GeneratedClassHandler; import java.io.File; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Set; /** */ public class SimpleClassCacheTest extends TestCase { byte[] FAKE_BYTES_V1 = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; byte[] FAKE_BYTES_V2 = {1, 1, 2, 3, 4, 5, 6, 7, 8, 9}; byte[] FAKE_WOVEN_BYTES_V1 = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9,10}; byte[] FAKE_WOVEN_BYTES_V2 = {1, 1, 2, 3, 4, 5, 6, 7, 8, 9,10}; private SimpleCache createCache() throws Exception { return new SimpleCache(System.getProperty("java.io.tmpdir"),true); } public void testCache() throws Exception { String classA = "com.generated.A"; SimpleCache cache = createCache(); cache.put(classA, FAKE_BYTES_V1, FAKE_WOVEN_BYTES_V1); // Test the returned woven bytes are the original one byte result[] = cache.getAndInitialize(classA, FAKE_BYTES_V1, null, null); for(int i = 0; i < result.length; i ++){ assertEquals("Cached version byte[" +i+"] should be equal to the original woven classe",result[i],FAKE_WOVEN_BYTES_V1[i]); } // Assure the class is properly backed up in the backing folder File f = new File (System.getProperty("java.io.tmpdir") + File.separator + "com.generated.A-1164760902"); assertTrue("Class should be backed up to backing folder, with te CRC:1164760902 ",f.exists()); } public void testDifferentVersionCache() throws Exception { String classA = "com.generated.A"; SimpleCache cache = createCache(); cache.put(classA, FAKE_BYTES_V1, FAKE_WOVEN_BYTES_V1); cache.put(classA, FAKE_BYTES_V2, FAKE_WOVEN_BYTES_V2); // Test the returned woven bytes are the original one for v1 byte result[] = cache.getAndInitialize(classA, FAKE_BYTES_V1, null, null); for(int i = 0; i < result.length; i ++){ assertEquals("Cached version v1 byte[" +i+"] should be equal to the original woven classe",result[i],FAKE_WOVEN_BYTES_V1[i]); } // Test the returned woven bytes are the original one for v2 result = cache.getAndInitialize(classA, FAKE_BYTES_V2, null, null); for(int i = 0; i < result.length; i ++){ assertEquals("Cached version v2 byte[" +i+"] should be equal to the original woven classe",result[i],FAKE_WOVEN_BYTES_V2[i]); } } }
391,123
Bug 391123 Added support for more cache backing(s)
null
closed fixed
df1823b
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2012-10-29T19:46:03Z"
"2012-10-04T14:13:20Z"
weaver/testsrc/org/aspectj/weaver/tools/cache/WeavedClassCacheTest.java
/******************************************************************************* * Copyright (c) 2012 Contributors. * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Eclipse Public License v1.0 * which accompanies this distribution and is available at * http://eclipse.org/legal/epl-v10.html * * Contributors: * John Kew (vmware) initial implementation *******************************************************************************/ package org.aspectj.weaver.tools.cache; import junit.framework.TestCase; import org.aspectj.bridge.AbortException; import org.aspectj.bridge.IMessage; import org.aspectj.bridge.IMessageHandler; import org.aspectj.weaver.tools.GeneratedClassHandler; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Set; /** */ public class WeavedClassCacheTest extends TestCase { String FAKE_CLASS = "com.example.foo.Bar"; byte[] FAKE_BYTES = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; public class MemoryCacheBacking implements CacheBacking { HashMap<String, CachedClassEntry> cache = new HashMap<String, CachedClassEntry>(); public String[] getKeys(String regex) { Set<String> keys = cache.keySet(); List<String> matches = new LinkedList<String>(); for (String key : keys) { if (key.matches(regex)) { matches.add(key); } } return matches.toArray(new String[0]); } public void remove(CachedClassReference ref) { cache.remove(ref.getKey()); } public void clear() { cache.clear(); } public CachedClassEntry get(CachedClassReference ref, byte[] originalBytes) { return cache.get(ref.getKey()); } public void put(CachedClassEntry entry, byte[] originalBytes) { assertNotNull("put(" + entry + ") no original bytes", originalBytes); cache.put(entry.getKey(), entry); } } MemoryCacheBacking memoryBacking = new MemoryCacheBacking(); IMessageHandler messageHandler = new IMessageHandler() { public boolean handleMessage(IMessage message) throws AbortException { return true; } public boolean isIgnoring(IMessage.Kind kind) { return true; } public void dontIgnore(IMessage.Kind kind) { } public void ignore(IMessage.Kind kind) { } }; public class TestGeneratedClassHandler implements GeneratedClassHandler { public int accepts = 0; public List<String> classesISaw = new LinkedList<String>(); @Override public void acceptClass (String name, byte[] originalBytes, byte[] wovenBytes) { accepts++; classesISaw.add(name); } } TestGeneratedClassHandler generatedClassHandler = new TestGeneratedClassHandler(); CacheKeyResolver resolver = new DefaultCacheKeyResolver(); private WeavedClassCache createCache() throws Exception { return new WeavedClassCache(generatedClassHandler, messageHandler, "test", memoryBacking, resolver); } private void reset() throws Exception { memoryBacking.cache.clear(); generatedClassHandler.accepts = 0; generatedClassHandler.classesISaw.clear(); } public void testGetCachingClassHandler() throws Exception { WeavedClassCache cache = createCache(); GeneratedClassHandler newHandle = cache.getCachingClassHandler(); assertTrue(generatedClassHandler != newHandle); assertTrue(newHandle instanceof GeneratedCachedClassHandler); } // public void testExistingGeneratedClassesPassedThroughHandler() throws Exception { // String classA = "com.generated.A"; // String classB = "com.generated.B"; // reset(); // memoryBacking.put(new CachedClassEntry(resolver.generatedKey(classA), FAKE_BYTES, CachedClassEntry.EntryType.GENERATED), FAKE_BYTES); // memoryBacking.put(new CachedClassEntry(resolver.generatedKey(classB), FAKE_BYTES, CachedClassEntry.EntryType.GENERATED), FAKE_BYTES); // createCache(); // assertEquals(2, generatedClassHandler.accepts); // for (String cName : generatedClassHandler.classesISaw) { // assertTrue("Got: " + cName, cName.equals(classA) || cName.equals(classB)); // } // } public void testCache() throws Exception { reset(); WeavedClassCache cache = createCache(); CacheStatistics stats = cache.getStats(); CachedClassReference ref = cache.createCacheKey(FAKE_CLASS, FAKE_BYTES); assertNull(cache.get(ref, FAKE_BYTES)); cache.put(ref, FAKE_BYTES, FAKE_BYTES); assertNotNull(cache.get(ref, FAKE_BYTES)); assertEquals(new String(FAKE_BYTES), new String(cache.get(ref, FAKE_BYTES).getBytes())); ref = cache.createGeneratedCacheKey(FAKE_CLASS); assertNull(cache.get(ref, FAKE_BYTES)); cache.put(ref, FAKE_BYTES, FAKE_BYTES); assertNotNull(cache.get(ref, FAKE_BYTES)); assertEquals(new String(FAKE_BYTES), new String(cache.get(ref, FAKE_BYTES).getBytes())); assertEquals(4, stats.getHits()); assertEquals(2, stats.getMisses()); } public void testRemove() throws Exception { reset(); WeavedClassCache cache = createCache(); CachedClassReference ref = cache.createCacheKey(FAKE_CLASS, FAKE_BYTES); assertNull(cache.get(ref, FAKE_BYTES)); cache.put(ref, FAKE_BYTES, FAKE_BYTES); assertNotNull(cache.get(ref, FAKE_BYTES)); cache.remove(ref); assertNull(cache.get(ref, FAKE_BYTES)); } }
391,123
Bug 391123 Added support for more cache backing(s)
null
closed fixed
df1823b
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2012-10-29T19:46:03Z"
"2012-10-04T14:13:20Z"
weaver/testsrc/org/aspectj/weaver/tools/cache/ZippedFileCacheBackingTest.java
394,234
Bug 394234 Invalid StackMapTable generated in Java 7
When compiling for Java 7, AspectJ can compute an invalid StackMapTable. The verifier will throw a ClassNotFoundException when the generated class is loaded. Example: class Parent<T> {} class ChildA<T> extends Parent<T> {} class ChildB<T> extends Parent<T> {} public Object methodWithBadStackMapTable(boolean value) { return value ? new ChildA<String>() : new ChildB<String>(); } javap shows the computed StackMapTable to be: StackMapTable: number_of_entries = 2 frame_type = 15 /* same */ frame_type = 71 /* same_locals_1_stack_item */ stack = [ class "Parent<T>" ] when it should be: StackMapTable: number_of_entries = 2 frame_type = 15 /* same */ frame_type = 71 /* same_locals_1_stack_item */ stack = [ class Parent ]
resolved fixed
fc55431
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2012-11-14T23:41:57Z"
"2012-11-13T23:40:00Z"
weaver/src/org/aspectj/weaver/bcel/asm/StackMapAdder.java
/* ******************************************************************* * Copyright (c) 2008 Contributors * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Eclipse Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Andy Clement * ******************************************************************/ package org.aspectj.weaver.bcel.asm; import org.aspectj.weaver.ResolvedType; import org.aspectj.weaver.UnresolvedType; import org.aspectj.weaver.World; import aj.org.objectweb.asm.*; /** * Uses asm to add the stack map attribute to methods in a class. The class is passed in as pure byte data and then a reader/writer * process it. The writer is wired into the world so that types can be resolved and getCommonSuperClass() can be implemented without * class loading using the context class loader. * * It is important that the constant pool is preserved here and asm does not try to remove unused entries. That is because some * entries are refered to from classfile attributes. Asm cannot see into these attributes so does not realise the constant pool * entries are in use. In order to ensure the copying of cp occurs, we use the variant super constructor call in AspectJConnectClassWriter * that passes in the classreader. However, ordinarily that change causes a further optimization: that if a classreader sees * a methodvisitor that has been created by a ClassWriter then it just copies the data across without changing it (and so it * fails to attach the stackmapattribute). In order to avoid this further optimization we use our own minimal MethodVisitor. * * @author Andy Clement */ public class StackMapAdder { public static byte[] addStackMaps(World world, byte[] data) { try { ClassReader cr = new ClassReader(data); ClassWriter cw = new AspectJConnectClassWriter(cr, world); ClassVisitor cv = new AspectJClassVisitor(cw); cr.accept(cv, 0); return cw.toByteArray(); } catch (Throwable t) { System.err.println("AspectJ Internal Error: unable to add stackmap attributes. " + t.getMessage()); AsmDetector.isAsmAround = false; return data; } } private static class AspectJClassVisitor extends ClassVisitor { public AspectJClassVisitor(ClassVisitor classwriter) { super(Opcodes.ASM4, classwriter); } @Override public MethodVisitor visitMethod(int access, String name, String desc, String signature, String[] exceptions) { MethodVisitor mv = super.visitMethod(access, name, desc, signature, exceptions); return new AJMethodVisitor(mv); } // Minimal pass through MethodVisitor just so that the ClassReader doesn't see one that has been directly // created by a ClassWriter (see top level class comment) static class AJMethodVisitor extends MethodVisitor { public AJMethodVisitor(MethodVisitor mv) { super(Opcodes.ASM4,mv); } } } private static class AspectJConnectClassWriter extends ClassWriter { private final World world; public AspectJConnectClassWriter(ClassReader cr, World w) { super(cr, ClassWriter.COMPUTE_FRAMES); // passing in cr is necessary so cpool isnt modified (see 2.2.4 of asm doc) this.world = w; } // Implementation of getCommonSuperClass() that avoids Class.forName() protected String getCommonSuperClass(final String type1, final String type2) { ResolvedType resolvedType1 = world.resolve(UnresolvedType.forName(type1.replace('/', '.'))); ResolvedType resolvedType2 = world.resolve(UnresolvedType.forName(type2.replace('/', '.'))); if (resolvedType1.isAssignableFrom(resolvedType2)) { return type1; } if (resolvedType2.isAssignableFrom(resolvedType1)) { return type2; } if (resolvedType1.isInterface() || resolvedType2.isInterface()) { return "java/lang/Object"; } else { do { resolvedType1 = resolvedType1.getSuperclass(); } while (!resolvedType1.isAssignableFrom(resolvedType2)); return resolvedType1.getName().replace('.', '/'); } } } }
395,221
Bug 395221 weird error about unbound formals when mixing generics with annotation style
From the mailing list: I have following problem with following Aspect: @Aspect public class CounterAspect extends AbstractMoskitoAspect { @Around(value = "execution(* *(..)) && (@annotation(method))") public Object countMethod(ProceedingJoinPoint pjp, Count method) throws Throwable { return count(pjp, method.producerId(), method.subsystem(), method.category()); } @Around(value = "execution(* *(..)) && (@annotation(method))") public Object countByParameter(ProceedingJoinPoint pjp, CountByParameter method) throws Throwable { return countByParameter(pjp, method.producerId(), method.subsystem(), method.category()); } @Around(value = "execution(* *.*(..)) && (@within(clazz))") public Object countClass(ProceedingJoinPoint pjp, Count clazz) throws Throwable { return count(pjp, clazz.producerId(), clazz.subsystem(), clazz.category()); } private Object countByParameter(ProceedingJoinPoint pjp, String aProducerId, String aSubsystem, String aCategory) throws Throwable { .... It works. However, since I have two similar aspects that differ only in using some internal classes, I made my super class using generics: public class AbstractMoskitoAspect<S extends IStats> { @Aspect public class CounterAspect extends AbstractMoskitoAspect<CounterStats> { this breaks the build instantly with the very unhelpful error message: [ERROR] Failed to execute goal org.codehaus.mojo:aspectj-maven-plugin:1.4:compile (default) on project moskito-aop: Compiler errors: [ERROR] error at @Around(value = "execution(* *(..)) && (@annotation(method))") [ERROR] ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ [ERROR] /Users/another/projects/moskito/moskito-aop/java/net/anotheria/moskito/aop/aspect/CounterAspect.java:24:0::0 the parameter pjp is not bound in [all branches of] pointcut [ERROR] error at @Around(value = "execution(* *(..)) && (@annotation(method))") [ERROR] ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ [ERROR] /Users/another/projects/moskito/moskito-aop/java/net/anotheria/moskito/aop/aspect/CounterAspect.java:29:0::0 the parameter pjp is not bound in [all branches of] pointcut [ERROR] error at @Around(value = "execution(* *.*(..)) && (@within(clazz))") [ERROR] ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ [ERROR] /Users/another/projects/moskito/moskito-aop/java/net/anotheria/moskito/aop/aspect/CounterAspect.java:34:0::0 the parameter pjp is not bound in [all branches of] pointcut what am i doing wrong here?
resolved fixed
3e5af0f
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2012-11-27T22:52:33Z"
"2012-11-27T23:46:40Z"
org.aspectj.matcher/src/org/aspectj/weaver/patterns/AndPointcut.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Eclipse Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * PARC initial implementation * ******************************************************************/ package org.aspectj.weaver.patterns; import java.io.IOException; import java.util.Map; import org.aspectj.util.FuzzyBoolean; import org.aspectj.weaver.CompressingDataOutputStream; 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.World; import org.aspectj.weaver.ast.Test; public class AndPointcut extends Pointcut { Pointcut left, right; // exposed for testing private int couldMatchKinds; public AndPointcut(Pointcut left, Pointcut right) { super(); this.left = left; this.right = right; this.pointcutKind = AND; setLocation(left.getSourceContext(), left.getStart(), right.getEnd()); couldMatchKinds = left.couldMatchKinds() & right.couldMatchKinds(); } public int couldMatchKinds() { return couldMatchKinds; } public FuzzyBoolean fastMatch(FastMatchInfo type) { return left.fastMatch(type).and(right.fastMatch(type)); } protected FuzzyBoolean matchInternal(Shadow shadow) { FuzzyBoolean leftMatch = left.match(shadow); if (leftMatch.alwaysFalse()) { return leftMatch; } return leftMatch.and(right.match(shadow)); } public String toString() { return "(" + left.toString() + " && " + right.toString() + ")"; } public boolean equals(Object other) { if (!(other instanceof AndPointcut)) { return false; } AndPointcut o = (AndPointcut) other; return o.left.equals(left) && o.right.equals(right); } public int hashCode() { int result = 19; result = 37 * result + left.hashCode(); result = 37 * result + right.hashCode(); return result; } public void resolveBindings(IScope scope, Bindings bindings) { left.resolveBindings(scope, bindings); right.resolveBindings(scope, bindings); } public void write(CompressingDataOutputStream s) throws IOException { s.writeByte(Pointcut.AND); left.write(s); right.write(s); writeLocation(s); } public static Pointcut read(VersionedDataInputStream s, ISourceContext context) throws IOException { AndPointcut ret = new AndPointcut(Pointcut.read(s, context), Pointcut.read(s, context)); ret.readLocation(context, s); return ret; } protected Test findResidueInternal(Shadow shadow, ExposedState state) { return Test.makeAnd(left.findResidue(shadow, state), right.findResidue(shadow, state)); } public Pointcut concretize1(ResolvedType inAspect, ResolvedType declaringType, IntMap bindings) { AndPointcut ret = new AndPointcut(left.concretize(inAspect, declaringType, bindings), right.concretize(inAspect, declaringType, bindings)); ret.copyLocationFrom(this); return ret; } public Pointcut parameterizeWith(Map typeVariableMap, World w) { AndPointcut ret = new AndPointcut(left.parameterizeWith(typeVariableMap, w), right.parameterizeWith(typeVariableMap, w)); ret.copyLocationFrom(this); return ret; } public Pointcut getLeft() { return left; } public Pointcut getRight() { return right; } public Object accept(PatternNodeVisitor visitor, Object data) { return visitor.visit(this, data); } public Object traverse(PatternNodeVisitor visitor, Object data) { Object ret = accept(visitor, data); left.traverse(visitor, ret); right.traverse(visitor, ret); return ret; } }
398,588
Bug 398588 Using aspect 'requires' clause causes all aspects with 'requires' clauses not be loaded regardless
The usage of the 'requires' clause causes all aspects that have have 'requires' clauses not to be loaded regardless of whether the specified required class exists or not. Here is the scenario and why it happens: Let's assume we have a bunch of aspects (A1, A2, A3, etc.) - all with 'requires' clauses and all referencing classes that can be satisfied. ClassLoaderWeavingAdaptor#registerAspects goes over the aspects in a Definition one by one. It reaches aspect A1 and detects that it has a 'requires' clause, and so it invokes BcelWorld#addAspectRequires. This causes the aspect A1 and its required class to be registered in an internal 'aspectRequiredTypes' map. Then the code calls BcelWeaver#addLibraryAspect with A1 as the argument, which in turn calls addOrReplaceAspect which invokes 'hasUnsatisfiedDependency'. The 'hasUnsatisfiedDependency' has been written to run only ONCE - i.e., it checks if it has already run, and if so then it does nothing. Otherwise, it removes from the 'aspectRequiredTypes' map all the types that can be resolved, thus leaving only those that cannot be resolved. In other words, it assumes that after having run (once !!!) any remaining type must be unsatified. Thus, when it is invoked with A1, being the 1st time, it resolves the required type by A1 and leaves the 'aspectRequiredTypes' map empty - but also marks that no further running is required. When the ClassLoaderWeavingAdaptor#registerAspects loop reaches A2, it call BcelWorld#addAspectRequires since A2 also declares a 'requires' clause. This causes A2 and its referenced class to be mapped in the 'aspectRequiredTypes' map. However, when BcelWeaver#addLibraryAspect is called with A2 and the code reaches 'hasUnsatisfiedDependency' - the code assumes that it has already run (which it has - with A1), so it does not check if indeed A2's referenced class can be satisfied (which we assume it can). In other words, all subsequent aspects (A2, A3, etc.) are declared as having unsatisified dependencies - which they don't. The (quick) bugfix seems rather simple: every time BcelWorld#addAspectRequires method is called, it should mark 'aspectRequiredTypesProcessed' as FALSE, in order to force a re-evaluation in case 'hasUnsatisfiedDependency' is called.
resolved fixed
96ebaae
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2013-01-21T18:46:15Z"
"2013-01-20T05:33:20Z"
tests/bugs172/pr398588/Anno.java
398,588
Bug 398588 Using aspect 'requires' clause causes all aspects with 'requires' clauses not be loaded regardless
The usage of the 'requires' clause causes all aspects that have have 'requires' clauses not to be loaded regardless of whether the specified required class exists or not. Here is the scenario and why it happens: Let's assume we have a bunch of aspects (A1, A2, A3, etc.) - all with 'requires' clauses and all referencing classes that can be satisfied. ClassLoaderWeavingAdaptor#registerAspects goes over the aspects in a Definition one by one. It reaches aspect A1 and detects that it has a 'requires' clause, and so it invokes BcelWorld#addAspectRequires. This causes the aspect A1 and its required class to be registered in an internal 'aspectRequiredTypes' map. Then the code calls BcelWeaver#addLibraryAspect with A1 as the argument, which in turn calls addOrReplaceAspect which invokes 'hasUnsatisfiedDependency'. The 'hasUnsatisfiedDependency' has been written to run only ONCE - i.e., it checks if it has already run, and if so then it does nothing. Otherwise, it removes from the 'aspectRequiredTypes' map all the types that can be resolved, thus leaving only those that cannot be resolved. In other words, it assumes that after having run (once !!!) any remaining type must be unsatified. Thus, when it is invoked with A1, being the 1st time, it resolves the required type by A1 and leaves the 'aspectRequiredTypes' map empty - but also marks that no further running is required. When the ClassLoaderWeavingAdaptor#registerAspects loop reaches A2, it call BcelWorld#addAspectRequires since A2 also declares a 'requires' clause. This causes A2 and its referenced class to be mapped in the 'aspectRequiredTypes' map. However, when BcelWeaver#addLibraryAspect is called with A2 and the code reaches 'hasUnsatisfiedDependency' - the code assumes that it has already run (which it has - with A1), so it does not check if indeed A2's referenced class can be satisfied (which we assume it can). In other words, all subsequent aspects (A2, A3, etc.) are declared as having unsatisified dependencies - which they don't. The (quick) bugfix seems rather simple: every time BcelWorld#addAspectRequires method is called, it should mark 'aspectRequiredTypesProcessed' as FALSE, in order to force a re-evaluation in case 'hasUnsatisfiedDependency' is called.
resolved fixed
96ebaae
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2013-01-21T18:46:15Z"
"2013-01-20T05:33:20Z"
tests/bugs172/pr398588/Anno2.java
398,588
Bug 398588 Using aspect 'requires' clause causes all aspects with 'requires' clauses not be loaded regardless
The usage of the 'requires' clause causes all aspects that have have 'requires' clauses not to be loaded regardless of whether the specified required class exists or not. Here is the scenario and why it happens: Let's assume we have a bunch of aspects (A1, A2, A3, etc.) - all with 'requires' clauses and all referencing classes that can be satisfied. ClassLoaderWeavingAdaptor#registerAspects goes over the aspects in a Definition one by one. It reaches aspect A1 and detects that it has a 'requires' clause, and so it invokes BcelWorld#addAspectRequires. This causes the aspect A1 and its required class to be registered in an internal 'aspectRequiredTypes' map. Then the code calls BcelWeaver#addLibraryAspect with A1 as the argument, which in turn calls addOrReplaceAspect which invokes 'hasUnsatisfiedDependency'. The 'hasUnsatisfiedDependency' has been written to run only ONCE - i.e., it checks if it has already run, and if so then it does nothing. Otherwise, it removes from the 'aspectRequiredTypes' map all the types that can be resolved, thus leaving only those that cannot be resolved. In other words, it assumes that after having run (once !!!) any remaining type must be unsatified. Thus, when it is invoked with A1, being the 1st time, it resolves the required type by A1 and leaves the 'aspectRequiredTypes' map empty - but also marks that no further running is required. When the ClassLoaderWeavingAdaptor#registerAspects loop reaches A2, it call BcelWorld#addAspectRequires since A2 also declares a 'requires' clause. This causes A2 and its referenced class to be mapped in the 'aspectRequiredTypes' map. However, when BcelWeaver#addLibraryAspect is called with A2 and the code reaches 'hasUnsatisfiedDependency' - the code assumes that it has already run (which it has - with A1), so it does not check if indeed A2's referenced class can be satisfied (which we assume it can). In other words, all subsequent aspects (A2, A3, etc.) are declared as having unsatisified dependencies - which they don't. The (quick) bugfix seems rather simple: every time BcelWorld#addAspectRequires method is called, it should mark 'aspectRequiredTypesProcessed' as FALSE, in order to force a re-evaluation in case 'hasUnsatisfiedDependency' is called.
resolved fixed
96ebaae
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2013-01-21T18:46:15Z"
"2013-01-20T05:33:20Z"
tests/bugs172/pr398588/AspectA.java
398,588
Bug 398588 Using aspect 'requires' clause causes all aspects with 'requires' clauses not be loaded regardless
The usage of the 'requires' clause causes all aspects that have have 'requires' clauses not to be loaded regardless of whether the specified required class exists or not. Here is the scenario and why it happens: Let's assume we have a bunch of aspects (A1, A2, A3, etc.) - all with 'requires' clauses and all referencing classes that can be satisfied. ClassLoaderWeavingAdaptor#registerAspects goes over the aspects in a Definition one by one. It reaches aspect A1 and detects that it has a 'requires' clause, and so it invokes BcelWorld#addAspectRequires. This causes the aspect A1 and its required class to be registered in an internal 'aspectRequiredTypes' map. Then the code calls BcelWeaver#addLibraryAspect with A1 as the argument, which in turn calls addOrReplaceAspect which invokes 'hasUnsatisfiedDependency'. The 'hasUnsatisfiedDependency' has been written to run only ONCE - i.e., it checks if it has already run, and if so then it does nothing. Otherwise, it removes from the 'aspectRequiredTypes' map all the types that can be resolved, thus leaving only those that cannot be resolved. In other words, it assumes that after having run (once !!!) any remaining type must be unsatified. Thus, when it is invoked with A1, being the 1st time, it resolves the required type by A1 and leaves the 'aspectRequiredTypes' map empty - but also marks that no further running is required. When the ClassLoaderWeavingAdaptor#registerAspects loop reaches A2, it call BcelWorld#addAspectRequires since A2 also declares a 'requires' clause. This causes A2 and its referenced class to be mapped in the 'aspectRequiredTypes' map. However, when BcelWeaver#addLibraryAspect is called with A2 and the code reaches 'hasUnsatisfiedDependency' - the code assumes that it has already run (which it has - with A1), so it does not check if indeed A2's referenced class can be satisfied (which we assume it can). In other words, all subsequent aspects (A2, A3, etc.) are declared as having unsatisified dependencies - which they don't. The (quick) bugfix seems rather simple: every time BcelWorld#addAspectRequires method is called, it should mark 'aspectRequiredTypesProcessed' as FALSE, in order to force a re-evaluation in case 'hasUnsatisfiedDependency' is called.
resolved fixed
96ebaae
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2013-01-21T18:46:15Z"
"2013-01-20T05:33:20Z"
tests/bugs172/pr398588/AspectB.java
398,588
Bug 398588 Using aspect 'requires' clause causes all aspects with 'requires' clauses not be loaded regardless
The usage of the 'requires' clause causes all aspects that have have 'requires' clauses not to be loaded regardless of whether the specified required class exists or not. Here is the scenario and why it happens: Let's assume we have a bunch of aspects (A1, A2, A3, etc.) - all with 'requires' clauses and all referencing classes that can be satisfied. ClassLoaderWeavingAdaptor#registerAspects goes over the aspects in a Definition one by one. It reaches aspect A1 and detects that it has a 'requires' clause, and so it invokes BcelWorld#addAspectRequires. This causes the aspect A1 and its required class to be registered in an internal 'aspectRequiredTypes' map. Then the code calls BcelWeaver#addLibraryAspect with A1 as the argument, which in turn calls addOrReplaceAspect which invokes 'hasUnsatisfiedDependency'. The 'hasUnsatisfiedDependency' has been written to run only ONCE - i.e., it checks if it has already run, and if so then it does nothing. Otherwise, it removes from the 'aspectRequiredTypes' map all the types that can be resolved, thus leaving only those that cannot be resolved. In other words, it assumes that after having run (once !!!) any remaining type must be unsatified. Thus, when it is invoked with A1, being the 1st time, it resolves the required type by A1 and leaves the 'aspectRequiredTypes' map empty - but also marks that no further running is required. When the ClassLoaderWeavingAdaptor#registerAspects loop reaches A2, it call BcelWorld#addAspectRequires since A2 also declares a 'requires' clause. This causes A2 and its referenced class to be mapped in the 'aspectRequiredTypes' map. However, when BcelWeaver#addLibraryAspect is called with A2 and the code reaches 'hasUnsatisfiedDependency' - the code assumes that it has already run (which it has - with A1), so it does not check if indeed A2's referenced class can be satisfied (which we assume it can). In other words, all subsequent aspects (A2, A3, etc.) are declared as having unsatisified dependencies - which they don't. The (quick) bugfix seems rather simple: every time BcelWorld#addAspectRequires method is called, it should mark 'aspectRequiredTypesProcessed' as FALSE, in order to force a re-evaluation in case 'hasUnsatisfiedDependency' is called.
resolved fixed
96ebaae
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2013-01-21T18:46:15Z"
"2013-01-20T05:33:20Z"
tests/bugs172/pr398588/AspectC.java
398,588
Bug 398588 Using aspect 'requires' clause causes all aspects with 'requires' clauses not be loaded regardless
The usage of the 'requires' clause causes all aspects that have have 'requires' clauses not to be loaded regardless of whether the specified required class exists or not. Here is the scenario and why it happens: Let's assume we have a bunch of aspects (A1, A2, A3, etc.) - all with 'requires' clauses and all referencing classes that can be satisfied. ClassLoaderWeavingAdaptor#registerAspects goes over the aspects in a Definition one by one. It reaches aspect A1 and detects that it has a 'requires' clause, and so it invokes BcelWorld#addAspectRequires. This causes the aspect A1 and its required class to be registered in an internal 'aspectRequiredTypes' map. Then the code calls BcelWeaver#addLibraryAspect with A1 as the argument, which in turn calls addOrReplaceAspect which invokes 'hasUnsatisfiedDependency'. The 'hasUnsatisfiedDependency' has been written to run only ONCE - i.e., it checks if it has already run, and if so then it does nothing. Otherwise, it removes from the 'aspectRequiredTypes' map all the types that can be resolved, thus leaving only those that cannot be resolved. In other words, it assumes that after having run (once !!!) any remaining type must be unsatified. Thus, when it is invoked with A1, being the 1st time, it resolves the required type by A1 and leaves the 'aspectRequiredTypes' map empty - but also marks that no further running is required. When the ClassLoaderWeavingAdaptor#registerAspects loop reaches A2, it call BcelWorld#addAspectRequires since A2 also declares a 'requires' clause. This causes A2 and its referenced class to be mapped in the 'aspectRequiredTypes' map. However, when BcelWeaver#addLibraryAspect is called with A2 and the code reaches 'hasUnsatisfiedDependency' - the code assumes that it has already run (which it has - with A1), so it does not check if indeed A2's referenced class can be satisfied (which we assume it can). In other words, all subsequent aspects (A2, A3, etc.) are declared as having unsatisified dependencies - which they don't. The (quick) bugfix seems rather simple: every time BcelWorld#addAspectRequires method is called, it should mark 'aspectRequiredTypesProcessed' as FALSE, in order to force a re-evaluation in case 'hasUnsatisfiedDependency' is called.
resolved fixed
96ebaae
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2013-01-21T18:46:15Z"
"2013-01-20T05:33:20Z"
tests/bugs172/pr398588/AspectD.java
398,588
Bug 398588 Using aspect 'requires' clause causes all aspects with 'requires' clauses not be loaded regardless
The usage of the 'requires' clause causes all aspects that have have 'requires' clauses not to be loaded regardless of whether the specified required class exists or not. Here is the scenario and why it happens: Let's assume we have a bunch of aspects (A1, A2, A3, etc.) - all with 'requires' clauses and all referencing classes that can be satisfied. ClassLoaderWeavingAdaptor#registerAspects goes over the aspects in a Definition one by one. It reaches aspect A1 and detects that it has a 'requires' clause, and so it invokes BcelWorld#addAspectRequires. This causes the aspect A1 and its required class to be registered in an internal 'aspectRequiredTypes' map. Then the code calls BcelWeaver#addLibraryAspect with A1 as the argument, which in turn calls addOrReplaceAspect which invokes 'hasUnsatisfiedDependency'. The 'hasUnsatisfiedDependency' has been written to run only ONCE - i.e., it checks if it has already run, and if so then it does nothing. Otherwise, it removes from the 'aspectRequiredTypes' map all the types that can be resolved, thus leaving only those that cannot be resolved. In other words, it assumes that after having run (once !!!) any remaining type must be unsatified. Thus, when it is invoked with A1, being the 1st time, it resolves the required type by A1 and leaves the 'aspectRequiredTypes' map empty - but also marks that no further running is required. When the ClassLoaderWeavingAdaptor#registerAspects loop reaches A2, it call BcelWorld#addAspectRequires since A2 also declares a 'requires' clause. This causes A2 and its referenced class to be mapped in the 'aspectRequiredTypes' map. However, when BcelWeaver#addLibraryAspect is called with A2 and the code reaches 'hasUnsatisfiedDependency' - the code assumes that it has already run (which it has - with A1), so it does not check if indeed A2's referenced class can be satisfied (which we assume it can). In other words, all subsequent aspects (A2, A3, etc.) are declared as having unsatisified dependencies - which they don't. The (quick) bugfix seems rather simple: every time BcelWorld#addAspectRequires method is called, it should mark 'aspectRequiredTypesProcessed' as FALSE, in order to force a re-evaluation in case 'hasUnsatisfiedDependency' is called.
resolved fixed
96ebaae
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2013-01-21T18:46:15Z"
"2013-01-20T05:33:20Z"
tests/bugs172/pr398588/Blah.java
398,588
Bug 398588 Using aspect 'requires' clause causes all aspects with 'requires' clauses not be loaded regardless
The usage of the 'requires' clause causes all aspects that have have 'requires' clauses not to be loaded regardless of whether the specified required class exists or not. Here is the scenario and why it happens: Let's assume we have a bunch of aspects (A1, A2, A3, etc.) - all with 'requires' clauses and all referencing classes that can be satisfied. ClassLoaderWeavingAdaptor#registerAspects goes over the aspects in a Definition one by one. It reaches aspect A1 and detects that it has a 'requires' clause, and so it invokes BcelWorld#addAspectRequires. This causes the aspect A1 and its required class to be registered in an internal 'aspectRequiredTypes' map. Then the code calls BcelWeaver#addLibraryAspect with A1 as the argument, which in turn calls addOrReplaceAspect which invokes 'hasUnsatisfiedDependency'. The 'hasUnsatisfiedDependency' has been written to run only ONCE - i.e., it checks if it has already run, and if so then it does nothing. Otherwise, it removes from the 'aspectRequiredTypes' map all the types that can be resolved, thus leaving only those that cannot be resolved. In other words, it assumes that after having run (once !!!) any remaining type must be unsatified. Thus, when it is invoked with A1, being the 1st time, it resolves the required type by A1 and leaves the 'aspectRequiredTypes' map empty - but also marks that no further running is required. When the ClassLoaderWeavingAdaptor#registerAspects loop reaches A2, it call BcelWorld#addAspectRequires since A2 also declares a 'requires' clause. This causes A2 and its referenced class to be mapped in the 'aspectRequiredTypes' map. However, when BcelWeaver#addLibraryAspect is called with A2 and the code reaches 'hasUnsatisfiedDependency' - the code assumes that it has already run (which it has - with A1), so it does not check if indeed A2's referenced class can be satisfied (which we assume it can). In other words, all subsequent aspects (A2, A3, etc.) are declared as having unsatisified dependencies - which they don't. The (quick) bugfix seems rather simple: every time BcelWorld#addAspectRequires method is called, it should mark 'aspectRequiredTypesProcessed' as FALSE, in order to force a re-evaluation in case 'hasUnsatisfiedDependency' is called.
resolved fixed
96ebaae
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2013-01-21T18:46:15Z"
"2013-01-20T05:33:20Z"
tests/bugs172/pr398588/Code.java
398,588
Bug 398588 Using aspect 'requires' clause causes all aspects with 'requires' clauses not be loaded regardless
The usage of the 'requires' clause causes all aspects that have have 'requires' clauses not to be loaded regardless of whether the specified required class exists or not. Here is the scenario and why it happens: Let's assume we have a bunch of aspects (A1, A2, A3, etc.) - all with 'requires' clauses and all referencing classes that can be satisfied. ClassLoaderWeavingAdaptor#registerAspects goes over the aspects in a Definition one by one. It reaches aspect A1 and detects that it has a 'requires' clause, and so it invokes BcelWorld#addAspectRequires. This causes the aspect A1 and its required class to be registered in an internal 'aspectRequiredTypes' map. Then the code calls BcelWeaver#addLibraryAspect with A1 as the argument, which in turn calls addOrReplaceAspect which invokes 'hasUnsatisfiedDependency'. The 'hasUnsatisfiedDependency' has been written to run only ONCE - i.e., it checks if it has already run, and if so then it does nothing. Otherwise, it removes from the 'aspectRequiredTypes' map all the types that can be resolved, thus leaving only those that cannot be resolved. In other words, it assumes that after having run (once !!!) any remaining type must be unsatified. Thus, when it is invoked with A1, being the 1st time, it resolves the required type by A1 and leaves the 'aspectRequiredTypes' map empty - but also marks that no further running is required. When the ClassLoaderWeavingAdaptor#registerAspects loop reaches A2, it call BcelWorld#addAspectRequires since A2 also declares a 'requires' clause. This causes A2 and its referenced class to be mapped in the 'aspectRequiredTypes' map. However, when BcelWeaver#addLibraryAspect is called with A2 and the code reaches 'hasUnsatisfiedDependency' - the code assumes that it has already run (which it has - with A1), so it does not check if indeed A2's referenced class can be satisfied (which we assume it can). In other words, all subsequent aspects (A2, A3, etc.) are declared as having unsatisified dependencies - which they don't. The (quick) bugfix seems rather simple: every time BcelWorld#addAspectRequires method is called, it should mark 'aspectRequiredTypesProcessed' as FALSE, in order to force a re-evaluation in case 'hasUnsatisfiedDependency' is called.
resolved fixed
96ebaae
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2013-01-21T18:46:15Z"
"2013-01-20T05:33:20Z"
tests/bugs172/pr398588/Code2.java
398,588
Bug 398588 Using aspect 'requires' clause causes all aspects with 'requires' clauses not be loaded regardless
The usage of the 'requires' clause causes all aspects that have have 'requires' clauses not to be loaded regardless of whether the specified required class exists or not. Here is the scenario and why it happens: Let's assume we have a bunch of aspects (A1, A2, A3, etc.) - all with 'requires' clauses and all referencing classes that can be satisfied. ClassLoaderWeavingAdaptor#registerAspects goes over the aspects in a Definition one by one. It reaches aspect A1 and detects that it has a 'requires' clause, and so it invokes BcelWorld#addAspectRequires. This causes the aspect A1 and its required class to be registered in an internal 'aspectRequiredTypes' map. Then the code calls BcelWeaver#addLibraryAspect with A1 as the argument, which in turn calls addOrReplaceAspect which invokes 'hasUnsatisfiedDependency'. The 'hasUnsatisfiedDependency' has been written to run only ONCE - i.e., it checks if it has already run, and if so then it does nothing. Otherwise, it removes from the 'aspectRequiredTypes' map all the types that can be resolved, thus leaving only those that cannot be resolved. In other words, it assumes that after having run (once !!!) any remaining type must be unsatified. Thus, when it is invoked with A1, being the 1st time, it resolves the required type by A1 and leaves the 'aspectRequiredTypes' map empty - but also marks that no further running is required. When the ClassLoaderWeavingAdaptor#registerAspects loop reaches A2, it call BcelWorld#addAspectRequires since A2 also declares a 'requires' clause. This causes A2 and its referenced class to be mapped in the 'aspectRequiredTypes' map. However, when BcelWeaver#addLibraryAspect is called with A2 and the code reaches 'hasUnsatisfiedDependency' - the code assumes that it has already run (which it has - with A1), so it does not check if indeed A2's referenced class can be satisfied (which we assume it can). In other words, all subsequent aspects (A2, A3, etc.) are declared as having unsatisified dependencies - which they don't. The (quick) bugfix seems rather simple: every time BcelWorld#addAspectRequires method is called, it should mark 'aspectRequiredTypesProcessed' as FALSE, in order to force a re-evaluation in case 'hasUnsatisfiedDependency' is called.
resolved fixed
96ebaae
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2013-01-21T18:46:15Z"
"2013-01-20T05:33:20Z"
tests/src/org/aspectj/systemtest/ajc172/Ajc172Tests.java
/******************************************************************************* * Copyright (c) 2012 Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Andy Clement - initial API and implementation *******************************************************************************/ package org.aspectj.systemtest.ajc172; import java.io.File; import junit.framework.Test; import org.aspectj.testing.XMLBasedAjcTestCase; /** * @author Andy Clement */ public class Ajc172Tests extends org.aspectj.testing.XMLBasedAjcTestCase { public void testInconsistentClassFile_pr389750() { runTest("inconsistent class file"); } public void testInconsistentClassFile_pr389750_2() { runTest("inconsistent class file 2"); } public void testInconsistentClassFile_pr389750_3() { runTest("inconsistent class file 3"); } public void testInconsistentClassFile_pr389750_4() { runTest("inconsistent class file 4"); } public void testAnnotationValueError_pr389752_1() { runTest("annotation value error 1"); } public void testAnnotationValueError_pr389752_2() { runTest("annotation value error 2"); } // this needs some cleverness to fix... the annotation value is parsed as a string and then not checked // to see if the user is accidentally supplying, for example, an enum value. Due to the use of strings, it // is hard to check. The verification code might go here: WildAnnotationTypePattern, line 205 (the string case) // public void testAnnotationValueError_pr389752_3() { // runTest("annotation value error 3"); // } // --- public static Test suite() { return XMLBasedAjcTestCase.loadSuite(Ajc172Tests.class); } @Override protected File getSpecFile() { return new File("../tests/src/org/aspectj/systemtest/ajc172/ajc172.xml"); } }
398,588
Bug 398588 Using aspect 'requires' clause causes all aspects with 'requires' clauses not be loaded regardless
The usage of the 'requires' clause causes all aspects that have have 'requires' clauses not to be loaded regardless of whether the specified required class exists or not. Here is the scenario and why it happens: Let's assume we have a bunch of aspects (A1, A2, A3, etc.) - all with 'requires' clauses and all referencing classes that can be satisfied. ClassLoaderWeavingAdaptor#registerAspects goes over the aspects in a Definition one by one. It reaches aspect A1 and detects that it has a 'requires' clause, and so it invokes BcelWorld#addAspectRequires. This causes the aspect A1 and its required class to be registered in an internal 'aspectRequiredTypes' map. Then the code calls BcelWeaver#addLibraryAspect with A1 as the argument, which in turn calls addOrReplaceAspect which invokes 'hasUnsatisfiedDependency'. The 'hasUnsatisfiedDependency' has been written to run only ONCE - i.e., it checks if it has already run, and if so then it does nothing. Otherwise, it removes from the 'aspectRequiredTypes' map all the types that can be resolved, thus leaving only those that cannot be resolved. In other words, it assumes that after having run (once !!!) any remaining type must be unsatified. Thus, when it is invoked with A1, being the 1st time, it resolves the required type by A1 and leaves the 'aspectRequiredTypes' map empty - but also marks that no further running is required. When the ClassLoaderWeavingAdaptor#registerAspects loop reaches A2, it call BcelWorld#addAspectRequires since A2 also declares a 'requires' clause. This causes A2 and its referenced class to be mapped in the 'aspectRequiredTypes' map. However, when BcelWeaver#addLibraryAspect is called with A2 and the code reaches 'hasUnsatisfiedDependency' - the code assumes that it has already run (which it has - with A1), so it does not check if indeed A2's referenced class can be satisfied (which we assume it can). In other words, all subsequent aspects (A2, A3, etc.) are declared as having unsatisified dependencies - which they don't. The (quick) bugfix seems rather simple: every time BcelWorld#addAspectRequires method is called, it should mark 'aspectRequiredTypesProcessed' as FALSE, in order to force a re-evaluation in case 'hasUnsatisfiedDependency' is called.
resolved fixed
96ebaae
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2013-01-21T18:46:15Z"
"2013-01-20T05:33:20Z"
weaver/src/org/aspectj/weaver/bcel/BcelWorld.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Eclipse Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * PARC initial implementation * Alexandre Vasseur perClause support for @AJ aspects * ******************************************************************/ package org.aspectj.weaver.bcel; import java.io.File; import java.io.IOException; import java.lang.reflect.Modifier; import java.net.MalformedURLException; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.StringTokenizer; import org.aspectj.apache.bcel.Constants; import org.aspectj.apache.bcel.classfile.ClassParser; import org.aspectj.apache.bcel.classfile.ConstantPool; import org.aspectj.apache.bcel.classfile.JavaClass; import org.aspectj.apache.bcel.generic.FieldInstruction; import org.aspectj.apache.bcel.generic.INVOKEINTERFACE; import org.aspectj.apache.bcel.generic.Instruction; import org.aspectj.apache.bcel.generic.InstructionHandle; import org.aspectj.apache.bcel.generic.InvokeInstruction; import org.aspectj.apache.bcel.generic.MULTIANEWARRAY; import org.aspectj.apache.bcel.generic.ObjectType; import org.aspectj.apache.bcel.generic.Type; import org.aspectj.apache.bcel.util.ClassLoaderReference; import org.aspectj.apache.bcel.util.ClassLoaderRepository; import org.aspectj.apache.bcel.util.ClassPath; import org.aspectj.apache.bcel.util.NonCachingClassLoaderRepository; import org.aspectj.apache.bcel.util.Repository; import org.aspectj.asm.AsmManager; import org.aspectj.asm.IRelationship; import org.aspectj.asm.internal.CharOperation; import org.aspectj.bridge.IMessage; import org.aspectj.bridge.IMessageHandler; import org.aspectj.bridge.ISourceLocation; import org.aspectj.bridge.Message; import org.aspectj.bridge.MessageUtil; import org.aspectj.bridge.WeaveMessage; import org.aspectj.weaver.Advice; import org.aspectj.weaver.AdviceKind; import org.aspectj.weaver.AnnotationAJ; import org.aspectj.weaver.AnnotationOnTypeMunger; import org.aspectj.weaver.BCException; import org.aspectj.weaver.Checker; import org.aspectj.weaver.ICrossReferenceHandler; import org.aspectj.weaver.IWeavingSupport; import org.aspectj.weaver.Member; import org.aspectj.weaver.MemberImpl; import org.aspectj.weaver.MemberKind; import org.aspectj.weaver.NewParentTypeMunger; import org.aspectj.weaver.ReferenceType; import org.aspectj.weaver.ReferenceTypeDelegate; import org.aspectj.weaver.ResolvedMember; import org.aspectj.weaver.ResolvedMemberImpl; import org.aspectj.weaver.ResolvedType; import org.aspectj.weaver.ResolvedTypeMunger; import org.aspectj.weaver.Shadow; import org.aspectj.weaver.ShadowMunger; import org.aspectj.weaver.UnresolvedType; import org.aspectj.weaver.World; import org.aspectj.weaver.loadtime.definition.Definition; import org.aspectj.weaver.loadtime.definition.DocumentParser; import org.aspectj.weaver.model.AsmRelationshipProvider; import org.aspectj.weaver.patterns.DeclareAnnotation; import org.aspectj.weaver.patterns.DeclareParents; import org.aspectj.weaver.patterns.ParserException; import org.aspectj.weaver.patterns.PatternParser; import org.aspectj.weaver.patterns.TypePattern; import org.aspectj.weaver.tools.Trace; import org.aspectj.weaver.tools.TraceFactory; public class BcelWorld extends World implements Repository { private final ClassPathManager classPath; protected Repository delegate; private BcelWeakClassLoaderReference loaderRef; private final BcelWeavingSupport bcelWeavingSupport = new BcelWeavingSupport(); private boolean isXmlConfiguredWorld = false; private WeavingXmlConfig xmlConfiguration; private List<TypeDelegateResolver> typeDelegateResolvers; private static Trace trace = TraceFactory.getTraceFactory().getTrace(BcelWorld.class); public BcelWorld() { this(""); } public BcelWorld(String cp) { this(makeDefaultClasspath(cp), IMessageHandler.THROW, null); } public IRelationship.Kind determineRelKind(ShadowMunger munger) { AdviceKind ak = ((Advice) munger).getKind(); if (ak.getKey() == AdviceKind.Before.getKey()) { return IRelationship.Kind.ADVICE_BEFORE; } else if (ak.getKey() == AdviceKind.After.getKey()) { return IRelationship.Kind.ADVICE_AFTER; } else if (ak.getKey() == AdviceKind.AfterThrowing.getKey()) { return IRelationship.Kind.ADVICE_AFTERTHROWING; } else if (ak.getKey() == AdviceKind.AfterReturning.getKey()) { return IRelationship.Kind.ADVICE_AFTERRETURNING; } else if (ak.getKey() == AdviceKind.Around.getKey()) { return IRelationship.Kind.ADVICE_AROUND; } else if (ak.getKey() == AdviceKind.CflowEntry.getKey() || ak.getKey() == AdviceKind.CflowBelowEntry.getKey() || ak.getKey() == AdviceKind.InterInitializer.getKey() || ak.getKey() == AdviceKind.PerCflowEntry.getKey() || ak.getKey() == AdviceKind.PerCflowBelowEntry.getKey() || ak.getKey() == AdviceKind.PerThisEntry.getKey() || ak.getKey() == AdviceKind.PerTargetEntry.getKey() || ak.getKey() == AdviceKind.Softener.getKey() || ak.getKey() == AdviceKind.PerTypeWithinEntry.getKey()) { // System.err.println("Dont want a message about this: "+ak); return null; } throw new RuntimeException("Shadow.determineRelKind: What the hell is it? " + ak); } @Override public void reportMatch(ShadowMunger munger, Shadow shadow) { if (getCrossReferenceHandler() != null) { getCrossReferenceHandler().addCrossReference(munger.getSourceLocation(), // What is being applied shadow.getSourceLocation(), // Where is it being applied determineRelKind(munger).getName(), // What kind of advice? ((Advice) munger).hasDynamicTests() // Is a runtime test being stuffed in the code? ); } if (!getMessageHandler().isIgnoring(IMessage.WEAVEINFO)) { reportWeavingMessage(munger, shadow); } if (getModel() != null) { AsmRelationshipProvider.addAdvisedRelationship(getModelAsAsmManager(), shadow, munger); } } /* * Report a message about the advice weave that has occurred. Some messing about to make it pretty ! This code is just asking * for an NPE to occur ... */ private void reportWeavingMessage(ShadowMunger munger, Shadow shadow) { Advice advice = (Advice) munger; AdviceKind aKind = advice.getKind(); // Only report on interesting advice kinds ... if (aKind == null || advice.getConcreteAspect() == null) { // We suspect someone is programmatically driving the weaver // (e.g. IdWeaveTestCase in the weaver testcases) return; } if (!(aKind.equals(AdviceKind.Before) || aKind.equals(AdviceKind.After) || aKind.equals(AdviceKind.AfterReturning) || aKind.equals(AdviceKind.AfterThrowing) || aKind.equals(AdviceKind.Around) || aKind.equals(AdviceKind.Softener))) { return; } // synchronized blocks are implemented with multiple monitor_exit instructions in the bytecode // (one for normal exit from the method, one for abnormal exit), we only want to tell the user // once we have advised the end of the sync block, even though under the covers we will have // woven both exit points if (shadow.getKind() == Shadow.SynchronizationUnlock) { if (advice.lastReportedMonitorExitJoinpointLocation == null) { // this is the first time through, let's continue... advice.lastReportedMonitorExitJoinpointLocation = shadow.getSourceLocation(); } else { if (areTheSame(shadow.getSourceLocation(), advice.lastReportedMonitorExitJoinpointLocation)) { // Don't report it again! advice.lastReportedMonitorExitJoinpointLocation = null; return; } // hmmm, this means some kind of nesting is going on, urgh advice.lastReportedMonitorExitJoinpointLocation = shadow.getSourceLocation(); } } String description = advice.getKind().toString(); String advisedType = shadow.getEnclosingType().getName(); String advisingType = advice.getConcreteAspect().getName(); Message msg = null; if (advice.getKind().equals(AdviceKind.Softener)) { msg = WeaveMessage.constructWeavingMessage(WeaveMessage.WEAVEMESSAGE_SOFTENS, new String[] { advisedType, beautifyLocation(shadow.getSourceLocation()), advisingType, beautifyLocation(munger.getSourceLocation()) }, advisedType, advisingType); } else { boolean runtimeTest = advice.hasDynamicTests(); String joinPointDescription = shadow.toString(); msg = WeaveMessage .constructWeavingMessage(WeaveMessage.WEAVEMESSAGE_ADVISES, new String[] { joinPointDescription, advisedType, beautifyLocation(shadow.getSourceLocation()), description, advisingType, beautifyLocation(munger.getSourceLocation()), (runtimeTest ? " [with runtime test]" : "") }, advisedType, advisingType); // Boolean.toString(runtimeTest)}); } getMessageHandler().handleMessage(msg); } private boolean areTheSame(ISourceLocation locA, ISourceLocation locB) { if (locA == null) { return locB == null; } if (locB == null) { return false; } if (locA.getLine() != locB.getLine()) { return false; } File fA = locA.getSourceFile(); File fB = locA.getSourceFile(); if (fA == null) { return fB == null; } if (fB == null) { return false; } return fA.getName().equals(fB.getName()); } /* * Ensure we report a nice source location - particular in the case where the source info is missing (binary weave). */ private String beautifyLocation(ISourceLocation isl) { StringBuffer nice = new StringBuffer(); if (isl == null || isl.getSourceFile() == null || isl.getSourceFile().getName().indexOf("no debug info available") != -1) { nice.append("no debug info available"); } else { // can't use File.getName() as this fails when a Linux box encounters a path created on Windows and vice-versa int takeFrom = isl.getSourceFile().getPath().lastIndexOf('/'); if (takeFrom == -1) { takeFrom = isl.getSourceFile().getPath().lastIndexOf('\\'); } int binary = isl.getSourceFile().getPath().lastIndexOf('!'); if (binary != -1 && binary < takeFrom) { // we have been woven by a binary aspect String pathToBinaryLoc = isl.getSourceFile().getPath().substring(0, binary + 1); if (pathToBinaryLoc.indexOf(".jar") != -1) { // only want to add the extra info if we're from a jar file int lastSlash = pathToBinaryLoc.lastIndexOf('/'); if (lastSlash == -1) { lastSlash = pathToBinaryLoc.lastIndexOf('\\'); } nice.append(pathToBinaryLoc.substring(lastSlash + 1)); } } nice.append(isl.getSourceFile().getPath().substring(takeFrom + 1)); if (isl.getLine() != 0) { nice.append(":").append(isl.getLine()); } // if it's a binary file then also want to give the file name if (isl.getSourceFileName() != null) { nice.append("(from " + isl.getSourceFileName() + ")"); } } return nice.toString(); } private static List<String> makeDefaultClasspath(String cp) { List<String> classPath = new ArrayList<String>(); classPath.addAll(getPathEntries(cp)); classPath.addAll(getPathEntries(ClassPath.getClassPath())); return classPath; } private static List<String> getPathEntries(String s) { List<String> ret = new ArrayList<String>(); StringTokenizer tok = new StringTokenizer(s, File.pathSeparator); while (tok.hasMoreTokens()) { ret.add(tok.nextToken()); } return ret; } public BcelWorld(List classPath, IMessageHandler handler, ICrossReferenceHandler xrefHandler) { // this.aspectPath = new ClassPathManager(aspectPath, handler); this.classPath = new ClassPathManager(classPath, handler); setMessageHandler(handler); setCrossReferenceHandler(xrefHandler); // Tell BCEL to use us for resolving any classes delegate = this; } public BcelWorld(ClassPathManager cpm, IMessageHandler handler, ICrossReferenceHandler xrefHandler) { classPath = cpm; setMessageHandler(handler); setCrossReferenceHandler(xrefHandler); // Tell BCEL to use us for resolving any classes delegate = this; } /** * Build a World from a ClassLoader, for LTW support * * @param loader * @param handler * @param xrefHandler */ public BcelWorld(ClassLoader loader, IMessageHandler handler, ICrossReferenceHandler xrefHandler) { classPath = null; loaderRef = new BcelWeakClassLoaderReference(loader); setMessageHandler(handler); setCrossReferenceHandler(xrefHandler); // Tell BCEL to use us for resolving any classes // delegate = getClassLoaderRepositoryFor(loader); } public void ensureRepositorySetup() { if (delegate == null) { delegate = getClassLoaderRepositoryFor(loaderRef); } } public Repository getClassLoaderRepositoryFor(ClassLoaderReference loader) { if (bcelRepositoryCaching) { return new ClassLoaderRepository(loader); } else { return new NonCachingClassLoaderRepository(loader); } } public void addPath(String name) { classPath.addPath(name, this.getMessageHandler()); } // ---- various interactions with bcel public static Type makeBcelType(UnresolvedType type) { return Type.getType(type.getErasureSignature()); } static Type[] makeBcelTypes(UnresolvedType[] types) { Type[] ret = new Type[types.length]; for (int i = 0, len = types.length; i < len; i++) { ret[i] = makeBcelType(types[i]); } return ret; } static String[] makeBcelTypesAsClassNames(UnresolvedType[] types) { String[] ret = new String[types.length]; for (int i = 0, len = types.length; i < len; i++) { ret[i] = types[i].getName(); } return ret; } public static UnresolvedType fromBcel(Type t) { return UnresolvedType.forSignature(t.getSignature()); } static UnresolvedType[] fromBcel(Type[] ts) { UnresolvedType[] ret = new UnresolvedType[ts.length]; for (int i = 0, len = ts.length; i < len; i++) { ret[i] = fromBcel(ts[i]); } return ret; } public ResolvedType resolve(Type t) { return resolve(fromBcel(t)); } @Override protected ReferenceTypeDelegate resolveDelegate(ReferenceType ty) { String name = ty.getName(); ensureAdvancedConfigurationProcessed(); JavaClass jc = lookupJavaClass(classPath, name); if (jc == null) { // Anyone else to ask? if (typeDelegateResolvers != null) { for (TypeDelegateResolver tdr : typeDelegateResolvers) { ReferenceTypeDelegate delegate = tdr.getDelegate(ty); if (delegate != null) { return delegate; } } } return null; } else { return buildBcelDelegate(ty, jc, false, false); } } public BcelObjectType buildBcelDelegate(ReferenceType type, JavaClass jc, boolean artificial, boolean exposedToWeaver) { BcelObjectType ret = new BcelObjectType(type, jc, artificial, exposedToWeaver); return ret; } private JavaClass lookupJavaClass(ClassPathManager classPath, String name) { if (classPath == null) { try { ensureRepositorySetup(); JavaClass jc = delegate.loadClass(name); if (trace.isTraceEnabled()) { trace.event("lookupJavaClass", this, new Object[] { name, jc }); } return jc; } catch (ClassNotFoundException e) { if (trace.isTraceEnabled()) { trace.error("Unable to find class '" + name + "' in repository", e); } return null; } } ClassPathManager.ClassFile file = null; try { file = classPath.find(UnresolvedType.forName(name)); if (file == null) { return null; } ClassParser parser = new ClassParser(file.getInputStream(), file.getPath()); JavaClass jc = parser.parse(); return jc; } catch (IOException ioe) { return null; } finally { if (file != null) { file.close(); } } } // public BcelObjectType addSourceObjectType(JavaClass jc) { // return addSourceObjectType(jc.getClassName(), jc, -1); // } public BcelObjectType addSourceObjectType(JavaClass jc, boolean artificial) { return addSourceObjectType(jc.getClassName(), jc, artificial); } public BcelObjectType addSourceObjectType(String classname, JavaClass jc, boolean artificial) { BcelObjectType ret = null; if (!jc.getClassName().equals(classname)) { throw new RuntimeException(jc.getClassName() + "!=" + classname); } String signature = UnresolvedType.forName(jc.getClassName()).getSignature(); ResolvedType fromTheMap = typeMap.get(signature); if (fromTheMap != null && !(fromTheMap instanceof ReferenceType)) { // what on earth is it then? See pr 112243 StringBuffer exceptionText = new StringBuffer(); exceptionText.append("Found invalid (not a ReferenceType) entry in the type map. "); exceptionText.append("Signature=[" + signature + "] Found=[" + fromTheMap + "] Class=[" + fromTheMap.getClass() + "]"); throw new BCException(exceptionText.toString()); } ReferenceType nameTypeX = (ReferenceType) fromTheMap; if (nameTypeX == null) { if (jc.isGeneric() && isInJava5Mode()) { nameTypeX = ReferenceType.fromTypeX(UnresolvedType.forRawTypeName(jc.getClassName()), this); ret = buildBcelDelegate(nameTypeX, jc, artificial, true); ReferenceType genericRefType = new ReferenceType(UnresolvedType.forGenericTypeSignature(signature, ret.getDeclaredGenericSignature()), this); nameTypeX.setDelegate(ret); genericRefType.setDelegate(ret); nameTypeX.setGenericType(genericRefType); typeMap.put(signature, nameTypeX); } else { nameTypeX = new ReferenceType(signature, this); ret = buildBcelDelegate(nameTypeX, jc, artificial, true); typeMap.put(signature, nameTypeX); } } else { ret = buildBcelDelegate(nameTypeX, jc, artificial, true); } return ret; } public BcelObjectType addSourceObjectType(String classname, byte[] bytes, boolean artificial) { BcelObjectType ret = null; String signature = UnresolvedType.forName(classname).getSignature(); ResolvedType fromTheMap = typeMap.get(signature); if (fromTheMap != null && !(fromTheMap instanceof ReferenceType)) { // what on earth is it then? See pr 112243 StringBuffer exceptionText = new StringBuffer(); exceptionText.append("Found invalid (not a ReferenceType) entry in the type map. "); exceptionText.append("Signature=[" + signature + "] Found=[" + fromTheMap + "] Class=[" + fromTheMap.getClass() + "]"); throw new BCException(exceptionText.toString()); } ReferenceType nameTypeX = (ReferenceType) fromTheMap; if (nameTypeX == null) { JavaClass jc = Utility.makeJavaClass(classname, bytes); if (jc.isGeneric() && isInJava5Mode()) { nameTypeX = ReferenceType.fromTypeX(UnresolvedType.forRawTypeName(jc.getClassName()), this); ret = buildBcelDelegate(nameTypeX, jc, artificial, true); ReferenceType genericRefType = new ReferenceType(UnresolvedType.forGenericTypeSignature(signature, ret.getDeclaredGenericSignature()), this); nameTypeX.setDelegate(ret); genericRefType.setDelegate(ret); nameTypeX.setGenericType(genericRefType); typeMap.put(signature, nameTypeX); } else { nameTypeX = new ReferenceType(signature, this); ret = buildBcelDelegate(nameTypeX, jc, artificial, true); typeMap.put(signature, nameTypeX); } } else { Object o = nameTypeX.getDelegate(); if (!(o instanceof BcelObjectType)) { throw new IllegalStateException("For " + classname + " should be BcelObjectType, but is " + o.getClass()); } ret = (BcelObjectType) o; // byte[] bs = ret.javaClass.getBytes(); // if (bs.length != bytes.length) { // throw new RuntimeException(""); // } // If the type is already exposed to the weaver (ret.isExposedToWeaver()) then this is likely // to be a hotswap reweave so build a new delegate, dont accidentally use the old data if (ret.isArtificial() || ret.isExposedToWeaver()) { // System.out.println("Rebuilding " + nameTypeX.getName()); ret = buildBcelDelegate(nameTypeX, Utility.makeJavaClass(classname, bytes), artificial, true); } else { ret.setExposedToWeaver(true); } } return ret; } void deleteSourceObjectType(UnresolvedType ty) { typeMap.remove(ty.getSignature()); } public static Member makeFieldJoinPointSignature(LazyClassGen cg, FieldInstruction fi) { ConstantPool cpg = cg.getConstantPool(); return MemberImpl.field(fi.getClassName(cpg), (fi.opcode == Constants.GETSTATIC || fi.opcode == Constants.PUTSTATIC) ? Modifier.STATIC : 0, fi.getName(cpg), fi.getSignature(cpg)); } public Member makeJoinPointSignatureFromMethod(LazyMethodGen mg, MemberKind kind) { Member ret = mg.getMemberView(); if (ret == null) { int mods = mg.getAccessFlags(); if (mg.getEnclosingClass().isInterface()) { mods |= Modifier.INTERFACE; } return new ResolvedMemberImpl(kind, UnresolvedType.forName(mg.getClassName()), mods, fromBcel(mg.getReturnType()), mg.getName(), fromBcel(mg.getArgumentTypes())); } else { return ret; } } public Member makeJoinPointSignatureForMonitorEnter(LazyClassGen cg, InstructionHandle h) { return MemberImpl.monitorEnter(); } public Member makeJoinPointSignatureForMonitorExit(LazyClassGen cg, InstructionHandle h) { return MemberImpl.monitorExit(); } public Member makeJoinPointSignatureForArrayConstruction(LazyClassGen cg, InstructionHandle handle) { Instruction i = handle.getInstruction(); ConstantPool cpg = cg.getConstantPool(); Member retval = null; if (i.opcode == Constants.ANEWARRAY) { // ANEWARRAY arrayInstruction = (ANEWARRAY)i; Type ot = i.getType(cpg); UnresolvedType ut = fromBcel(ot); ut = UnresolvedType.makeArray(ut, 1); retval = MemberImpl.method(ut, Modifier.PUBLIC, UnresolvedType.VOID, "<init>", new ResolvedType[] { INT }); } else if (i instanceof MULTIANEWARRAY) { MULTIANEWARRAY arrayInstruction = (MULTIANEWARRAY) i; UnresolvedType ut = null; short dimensions = arrayInstruction.getDimensions(); ObjectType ot = arrayInstruction.getLoadClassType(cpg); if (ot != null) { ut = fromBcel(ot); ut = UnresolvedType.makeArray(ut, dimensions); } else { Type t = arrayInstruction.getType(cpg); ut = fromBcel(t); } ResolvedType[] parms = new ResolvedType[dimensions]; for (int ii = 0; ii < dimensions; ii++) { parms[ii] = INT; } retval = MemberImpl.method(ut, Modifier.PUBLIC, UnresolvedType.VOID, "<init>", parms); } else if (i.opcode == Constants.NEWARRAY) { // NEWARRAY arrayInstruction = (NEWARRAY)i; Type ot = i.getType(); UnresolvedType ut = fromBcel(ot); retval = MemberImpl.method(ut, Modifier.PUBLIC, UnresolvedType.VOID, "<init>", new ResolvedType[] { INT }); } else { throw new BCException("Cannot create array construction signature for this non-array instruction:" + i); } return retval; } public Member makeJoinPointSignatureForMethodInvocation(LazyClassGen cg, InvokeInstruction ii) { ConstantPool cpg = cg.getConstantPool(); String name = ii.getName(cpg); String declaring = ii.getClassName(cpg); UnresolvedType declaringType = null; String signature = ii.getSignature(cpg); int modifier = (ii instanceof INVOKEINTERFACE) ? Modifier.INTERFACE : (ii.opcode == Constants.INVOKESTATIC) ? Modifier.STATIC : (ii.opcode == Constants.INVOKESPECIAL && !name .equals("<init>")) ? Modifier.PRIVATE : 0; // in Java 1.4 and after, static method call of super class within // subclass method appears // as declared by the subclass in the bytecode - but they are not // see #104212 if (ii.opcode == Constants.INVOKESTATIC) { ResolvedType appearsDeclaredBy = resolve(declaring); // look for the method there for (Iterator<ResolvedMember> iterator = appearsDeclaredBy.getMethods(true, true); iterator.hasNext();) { ResolvedMember method = iterator.next(); if (Modifier.isStatic(method.getModifiers())) { if (name.equals(method.getName()) && signature.equals(method.getSignature())) { // we found it declaringType = method.getDeclaringType(); break; } } } } if (declaringType == null) { if (declaring.charAt(0) == '[') { declaringType = UnresolvedType.forSignature(declaring); } else { declaringType = UnresolvedType.forName(declaring); } } return MemberImpl.method(declaringType, modifier, name, signature); } @Override public String toString() { StringBuffer buf = new StringBuffer(); buf.append("BcelWorld("); // buf.append(shadowMungerMap); buf.append(")"); return buf.toString(); } /** * Retrieve a bcel delegate for an aspect - this will return NULL if the delegate is an EclipseSourceType and not a * BcelObjectType - this happens quite often when incrementally compiling. */ public static BcelObjectType getBcelObjectType(ResolvedType concreteAspect) { if (concreteAspect == null) { return null; } if (!(concreteAspect instanceof ReferenceType)) { // Might be Missing return null; } ReferenceTypeDelegate rtDelegate = ((ReferenceType) concreteAspect).getDelegate(); if (rtDelegate instanceof BcelObjectType) { return (BcelObjectType) rtDelegate; } else { return null; } } public void tidyUp() { // At end of compile, close any open files so deletion of those archives // is possible classPath.closeArchives(); typeMap.report(); typeMap.demote(true); // ResolvedType.resetPrimitives(); } // / The repository interface methods public JavaClass findClass(String className) { return lookupJavaClass(classPath, className); } public JavaClass loadClass(String className) throws ClassNotFoundException { return lookupJavaClass(classPath, className); } public void storeClass(JavaClass clazz) { // doesn't need to do anything } public void removeClass(JavaClass clazz) { throw new RuntimeException("Not implemented"); } public JavaClass loadClass(Class clazz) throws ClassNotFoundException { throw new RuntimeException("Not implemented"); } public void clear() { delegate.clear(); // throw new RuntimeException("Not implemented"); } /** * The aim of this method is to make sure a particular type is 'ok'. Some operations on the delegate for a type modify it and * this method is intended to undo that... see pr85132 */ @Override public void validateType(UnresolvedType type) { ResolvedType result = typeMap.get(type.getSignature()); if (result == null) { return; // We haven't heard of it yet } if (!result.isExposedToWeaver()) { return; // cant need resetting } result.ensureConsistent(); // If we want to rebuild it 'from scratch' then: // ClassParser cp = new ClassParser(new // ByteArrayInputStream(newbytes),new String(cs)); // try { // rt.setDelegate(makeBcelObjectType(rt,cp.parse(),true)); // } catch (ClassFormatException e) { // e.printStackTrace(); // } catch (IOException e) { // e.printStackTrace(); // } } /** * Apply a single declare parents - return true if we change the type */ private boolean applyDeclareParents(DeclareParents p, ResolvedType onType) { boolean didSomething = false; List<ResolvedType> newParents = p.findMatchingNewParents(onType, true); if (!newParents.isEmpty()) { didSomething = true; BcelObjectType classType = BcelWorld.getBcelObjectType(onType); // System.err.println("need to do declare parents for: " + onType); for (ResolvedType newParent : newParents) { // We set it here so that the imminent matching for ITDs can // succeed - we still haven't done the necessary changes to the class file // itself (like transform super calls) - that is done in // BcelTypeMunger.mungeNewParent() // classType.addParent(newParent); onType.addParent(newParent); ResolvedTypeMunger newParentMunger = new NewParentTypeMunger(newParent, p.getDeclaringType()); newParentMunger.setSourceLocation(p.getSourceLocation()); onType.addInterTypeMunger(new BcelTypeMunger(newParentMunger, getCrosscuttingMembersSet() .findAspectDeclaringParents(p)), false); } } return didSomething; } /** * Apply a declare @type - return true if we change the type */ private boolean applyDeclareAtType(DeclareAnnotation decA, ResolvedType onType, boolean reportProblems) { boolean didSomething = false; if (decA.matches(onType)) { if (onType.hasAnnotation(decA.getAnnotation().getType())) { // already has it return false; } AnnotationAJ annoX = decA.getAnnotation(); // check the annotation is suitable for the target boolean isOK = checkTargetOK(decA, onType, annoX); if (isOK) { didSomething = true; ResolvedTypeMunger newAnnotationTM = new AnnotationOnTypeMunger(annoX); newAnnotationTM.setSourceLocation(decA.getSourceLocation()); onType.addInterTypeMunger(new BcelTypeMunger(newAnnotationTM, decA.getAspect().resolve(this)), false); decA.copyAnnotationTo(onType); } } return didSomething; } /** * Apply the specified declare @field construct to any matching fields in the specified type. * @param deca the declare annotation targeting fields * @param type the type to check for members matching the declare annotation * @return true if something matched and the type was modified */ private boolean applyDeclareAtField(DeclareAnnotation deca, ResolvedType type) { boolean changedType = false; ResolvedMember[] fields = type.getDeclaredFields(); for (ResolvedMember field: fields) { if (deca.matches(field, this)) { AnnotationAJ anno = deca.getAnnotation(); if (!field.hasAnnotation(anno.getType())) { field.addAnnotation(anno); changedType=true; } } } return changedType; } /** * Checks for an @target() on the annotation and if found ensures it allows the annotation to be attached to the target type * that matched. */ private boolean checkTargetOK(DeclareAnnotation decA, ResolvedType onType, AnnotationAJ annoX) { if (annoX.specifiesTarget()) { if ((onType.isAnnotation() && !annoX.allowedOnAnnotationType()) || (!annoX.allowedOnRegularType())) { return false; } } return true; } // Hmmm - very similar to the code in BcelWeaver.weaveParentTypeMungers - // this code // doesn't need to produce errors/warnings though as it won't really be // weaving. protected void weaveInterTypeDeclarations(ResolvedType onType) { List<DeclareParents> declareParentsList = getCrosscuttingMembersSet().getDeclareParents(); if (onType.isRawType()) { onType = onType.getGenericType(); } onType.clearInterTypeMungers(); List<DeclareParents> decpToRepeat = new ArrayList<DeclareParents>(); boolean aParentChangeOccurred = false; boolean anAnnotationChangeOccurred = false; // First pass - apply all decp mungers for (Iterator<DeclareParents> i = declareParentsList.iterator(); i.hasNext();) { DeclareParents decp = i.next(); boolean typeChanged = applyDeclareParents(decp, onType); if (typeChanged) { aParentChangeOccurred = true; } else { // Perhaps it would have matched if a 'dec @type' had // modified the type if (!decp.getChild().isStarAnnotation()) { decpToRepeat.add(decp); } } } // Still first pass - apply all dec @type mungers for (DeclareAnnotation decA : getCrosscuttingMembersSet().getDeclareAnnotationOnTypes()) { boolean typeChanged = applyDeclareAtType(decA, onType, true); if (typeChanged) { anAnnotationChangeOccurred = true; } } // apply declare @field for (DeclareAnnotation deca: getCrosscuttingMembersSet().getDeclareAnnotationOnFields()) { if (applyDeclareAtField(deca,onType)) { anAnnotationChangeOccurred = true; } } while ((aParentChangeOccurred || anAnnotationChangeOccurred) && !decpToRepeat.isEmpty()) { anAnnotationChangeOccurred = aParentChangeOccurred = false; List<DeclareParents> decpToRepeatNextTime = new ArrayList<DeclareParents>(); for (DeclareParents decp: decpToRepeat) { if (applyDeclareParents(decp, onType)) { aParentChangeOccurred = true; } else { decpToRepeatNextTime.add(decp); } } for (DeclareAnnotation deca: getCrosscuttingMembersSet().getDeclareAnnotationOnTypes()) { if (applyDeclareAtType(deca, onType, false)) { anAnnotationChangeOccurred = true; } } for (DeclareAnnotation deca: getCrosscuttingMembersSet().getDeclareAnnotationOnFields()) { if (applyDeclareAtField(deca, onType)) { anAnnotationChangeOccurred = true; } } decpToRepeat = decpToRepeatNextTime; } } @Override public IWeavingSupport getWeavingSupport() { return bcelWeavingSupport; } @Override public void reportCheckerMatch(Checker checker, Shadow shadow) { IMessage iMessage = new Message(checker.getMessage(shadow), shadow.toString(), checker.isError() ? IMessage.ERROR : IMessage.WARNING, shadow.getSourceLocation(), null, new ISourceLocation[] { checker.getSourceLocation() }, true, 0, -1, -1); getMessageHandler().handleMessage(iMessage); if (getCrossReferenceHandler() != null) { getCrossReferenceHandler() .addCrossReference( checker.getSourceLocation(), shadow.getSourceLocation(), (checker.isError() ? IRelationship.Kind.DECLARE_ERROR.getName() : IRelationship.Kind.DECLARE_WARNING .getName()), false); } if (getModel() != null) { AsmRelationshipProvider.addDeclareErrorOrWarningRelationship(getModelAsAsmManager(), shadow, checker); } } public AsmManager getModelAsAsmManager() { return (AsmManager) getModel(); // For now... always an AsmManager in a bcel environment } void raiseError(String message) { getMessageHandler().handleMessage(MessageUtil.error(message)); } /** * These are aop.xml files that can be used to alter the aspects that actually apply from those passed in - and also their scope * of application to other files in the system. * * @param xmlFiles list of File objects representing any aop.xml files passed in to configure the build process */ public void setXmlFiles(List<File> xmlFiles) { if (!isXmlConfiguredWorld && !xmlFiles.isEmpty()) { raiseError("xml configuration files only supported by the compiler when -xmlConfigured option specified"); return; } if (!xmlFiles.isEmpty()) { xmlConfiguration = new WeavingXmlConfig(this, WeavingXmlConfig.MODE_COMPILE); } for (File xmlfile : xmlFiles) { try { Definition d = DocumentParser.parse(xmlfile.toURI().toURL()); xmlConfiguration.add(d); } catch (MalformedURLException e) { raiseError("Unexpected problem processing XML config file '" + xmlfile.getName() + "' :" + e.getMessage()); } catch (Exception e) { raiseError("Unexpected problem processing XML config file '" + xmlfile.getName() + "' :" + e.getMessage()); } } } /** * Add a scoped aspects where the scoping was defined in an aop.xml file and this world is being used in a LTW configuration */ public void addScopedAspect(String name, String scope) { this.isXmlConfiguredWorld = true; if (xmlConfiguration == null) { xmlConfiguration = new WeavingXmlConfig(this, WeavingXmlConfig.MODE_LTW); } xmlConfiguration.addScopedAspect(name, scope); } public void setXmlConfigured(boolean b) { this.isXmlConfiguredWorld = b; } @Override public boolean isXmlConfigured() { return isXmlConfiguredWorld && xmlConfiguration != null; } public WeavingXmlConfig getXmlConfiguration() { return xmlConfiguration; } @Override public boolean isAspectIncluded(ResolvedType aspectType) { if (!isXmlConfigured()) { return true; } return xmlConfiguration.specifiesInclusionOfAspect(aspectType.getName()); } @Override public TypePattern getAspectScope(ResolvedType declaringType) { return xmlConfiguration.getScopeFor(declaringType.getName()); } @Override public boolean hasUnsatisfiedDependency(ResolvedType aspectType) { if (!aspectRequiredTypesProcessed) { if (aspectRequiredTypes != null) { List<String> forRemoval = new ArrayList<String>(); for (Map.Entry<String, String> entry : aspectRequiredTypes.entrySet()) { ResolvedType rt = this.resolve(UnresolvedType.forName(entry.getValue())); if (!rt.isMissing()) { forRemoval.add(entry.getKey()); } else { if (!getMessageHandler().isIgnoring(IMessage.INFO)) { getMessageHandler().handleMessage( MessageUtil.info("deactivating aspect '" + aspectType.getName() + "' as it requires type '" + rt.getName() + "' which cannot be found on the classpath")); } } } for (String key : forRemoval) { aspectRequiredTypes.remove(key); } } aspectRequiredTypesProcessed = true; } if (aspectRequiredTypes == null) { return false; } return aspectRequiredTypes.containsKey(aspectType.getName()); } private boolean aspectRequiredTypesProcessed = false; private Map<String, String> aspectRequiredTypes = null; public void addAspectRequires(String name, String requiredType) { if (aspectRequiredTypes == null) { aspectRequiredTypes = new HashMap<String, String>(); } aspectRequiredTypes.put(name, requiredType); } /** * A WeavingXmlConfig is initially a collection of definitions from XML files - once the world is ready and weaving is running * it will initialize and transform those definitions into an optimized set of values (eg. resolve type patterns and string * names to real entities). It can then answer questions quickly: (1) is this aspect included in the weaving? (2) Is there a * scope specified for this aspect and does it include type X? * */ static class WeavingXmlConfig { final static int MODE_COMPILE = 1; final static int MODE_LTW = 2; private int mode; private boolean initialized = false; // Lazily done private List<Definition> definitions = new ArrayList<Definition>(); private List<String> resolvedIncludedAspects = new ArrayList<String>(); private Map<String, TypePattern> scopes = new HashMap<String, TypePattern>(); // these are not set for LTW mode (exclusion of these fast match patterns is handled before the weaver/world are used) private List<String> includedFastMatchPatterns = Collections.emptyList(); private List<TypePattern> includedPatterns = Collections.emptyList(); private List<String> excludedFastMatchPatterns = Collections.emptyList(); private List<TypePattern> excludedPatterns = Collections.emptyList(); private BcelWorld world; public WeavingXmlConfig(BcelWorld bcelWorld, int mode) { this.world = bcelWorld; this.mode = mode; } public void add(Definition d) { definitions.add(d); } public void addScopedAspect(String aspectName, String scope) { ensureInitialized(); resolvedIncludedAspects.add(aspectName); try { TypePattern scopePattern = new PatternParser(scope).parseTypePattern(); scopePattern.resolve(world); scopes.put(aspectName, scopePattern); if (!world.getMessageHandler().isIgnoring(IMessage.INFO)) { world.getMessageHandler().handleMessage( MessageUtil.info("Aspect '" + aspectName + "' is scoped to apply against types matching pattern '" + scopePattern.toString() + "'")); } } catch (Exception e) { world.getMessageHandler().handleMessage( MessageUtil.error("Unable to parse scope as type pattern. Scope was '" + scope + "': " + e.getMessage())); } } public void ensureInitialized() { if (!initialized) { try { resolvedIncludedAspects = new ArrayList<String>(); // Process the definitions into something more optimal for (Definition definition : definitions) { List<String> aspectNames = definition.getAspectClassNames(); for (String name : aspectNames) { resolvedIncludedAspects.add(name); // TODO check for existence? // ResolvedType resolvedAspect = resolve(UnresolvedType.forName(name)); // if (resolvedAspect.isMissing()) { // // ERROR // } else { // resolvedIncludedAspects.add(resolvedAspect); // } String scope = definition.getScopeForAspect(name); if (scope != null) { // Resolve the type pattern try { TypePattern scopePattern = new PatternParser(scope).parseTypePattern(); scopePattern.resolve(world); scopes.put(name, scopePattern); if (!world.getMessageHandler().isIgnoring(IMessage.INFO)) { world.getMessageHandler().handleMessage( MessageUtil.info("Aspect '" + name + "' is scoped to apply against types matching pattern '" + scopePattern.toString() + "'")); } } catch (Exception e) { // TODO definitions should remember which file they came from, for inclusion in this message world.getMessageHandler().handleMessage( MessageUtil.error("Unable to parse scope as type pattern. Scope was '" + scope + "': " + e.getMessage())); } } } try { List<String> includePatterns = definition.getIncludePatterns(); if (includePatterns.size() > 0) { includedPatterns = new ArrayList<TypePattern>(); includedFastMatchPatterns = new ArrayList<String>(); } for (String includePattern : includePatterns) { if (includePattern.endsWith("..*")) { // from 'blah.blah.blah..*' leave the 'blah.blah.blah.' includedFastMatchPatterns.add(includePattern.substring(0, includePattern.length() - 2)); } else { TypePattern includedPattern = new PatternParser(includePattern).parseTypePattern(); includedPatterns.add(includedPattern); } } List<String> excludePatterns = definition.getExcludePatterns(); if (excludePatterns.size() > 0) { excludedPatterns = new ArrayList<TypePattern>(); excludedFastMatchPatterns = new ArrayList<String>(); } for (String excludePattern : excludePatterns) { if (excludePattern.endsWith("..*")) { // from 'blah.blah.blah..*' leave the 'blah.blah.blah.' excludedFastMatchPatterns.add(excludePattern.substring(0, excludePattern.length() - 2)); } else { TypePattern excludedPattern = new PatternParser(excludePattern).parseTypePattern(); excludedPatterns.add(excludedPattern); } } } catch (ParserException pe) { // TODO definitions should remember which file they came from, for inclusion in this message world.getMessageHandler().handleMessage( MessageUtil.error("Unable to parse type pattern: " + pe.getMessage())); } } } finally { initialized = true; } } } public boolean specifiesInclusionOfAspect(String name) { ensureInitialized(); return resolvedIncludedAspects.contains(name); } public TypePattern getScopeFor(String name) { return scopes.get(name); } // Can't quite follow the same rules for exclusion as used for loadtime weaving: // "The set of types to be woven are those types matched by at least one weaver include element and not matched by any // weaver // exclude element. If there are no weaver include statements then all non-excluded types are included." // Since if the weaver is seeing it during this kind of build, the type is implicitly included. So all we should check // for is exclusion public boolean excludesType(ResolvedType type) { if (mode == MODE_LTW) { return false; } String typename = type.getName(); boolean excluded = false; for (String excludedPattern : excludedFastMatchPatterns) { if (typename.startsWith(excludedPattern)) { excluded = true; break; } } if (!excluded) { for (TypePattern excludedPattern : excludedPatterns) { if (excludedPattern.matchesStatically(type)) { excluded = true; break; } } } return excluded; } } public TypeMap getTypeMap() { return typeMap; } public boolean isLoadtimeWeaving() { return false; } public void addTypeDelegateResolver(TypeDelegateResolver typeDelegateResolver) { if (typeDelegateResolvers == null) { typeDelegateResolvers = new ArrayList<TypeDelegateResolver>(); } typeDelegateResolvers.add(typeDelegateResolver); } public void classWriteEvent(char[][] compoundName) { typeMap.classWriteEvent(new String(CharOperation.concatWith(compoundName, '.'))); } /** * Force demote a type. */ public void demote(ResolvedType type) { typeMap.demote(type); } }
399,408
Bug 399408 NPE in ExactAnnotationTypePattern.matches
[ERROR] java.lang.NullPointerException [ERROR] at org.aspectj.weaver.patterns.ExactAnnotationTypePattern.matches(ExactAnnotationTypePattern.java:137) [ERROR] at org.aspectj.weaver.patterns.ExactAnnotationTypePattern.matches(ExactAnnotationTypePattern.java:96) [ERROR] at org.aspectj.weaver.patterns.AnyWithAnnotationTypePattern.matchesExactly(AnyWithAnnotationTypePattern.java:55) [ERROR] at org.aspectj.weaver.patterns.TypePattern.matchesStatically(TypePattern.java:132) [ERROR] at org.aspectj.weaver.patterns.DeclareParents.match(DeclareParents.java:63) [ERROR] at org.aspectj.weaver.patterns.DeclareParents.findMatchingNewParents(DeclareParents.java:358) [ERROR] at org.aspectj.ajdt.internal.compiler.lookup.AjLookupEnvironment.doDeclareParents(AjLookupEnvironment.java:885) [ERROR] at org.aspectj.ajdt.internal.compiler.lookup.AjLookupEnvironment.weaveInterTypeDeclarations(AjLookupEnvironment.java:766) [ERROR] at org.aspectj.ajdt.internal.compiler.lookup.AjLookupEnvironment.weaveIntertypes(AjLookupEnvironment.java:424) [ERROR] at org.aspectj.ajdt.internal.compiler.lookup.AjLookupEnvironment.weaveIntertypes(AjLookupEnvironment.java:410) [ERROR] at org.aspectj.ajdt.internal.compiler.lookup.AjLookupEnvironment.completeTypeBindings(AjLookupEnvironment.java:261)
resolved fixed
d524403
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2013-01-29T17:20:10Z"
"2013-01-29T17:20:00Z"
org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/compiler/lookup/EclipseSourceType.java
/* ******************************************************************* * Copyright (c) 2002,2010 Contributors * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Eclipse Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * PARC initial implementation * Alexandre Vasseur support for @AJ perClause * ******************************************************************/ package org.aspectj.ajdt.internal.compiler.lookup; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; import org.aspectj.ajdt.internal.compiler.ast.AdviceDeclaration; import org.aspectj.ajdt.internal.compiler.ast.AspectDeclaration; import org.aspectj.ajdt.internal.compiler.ast.DeclareAnnotationDeclaration; import org.aspectj.ajdt.internal.compiler.ast.DeclareDeclaration; import org.aspectj.ajdt.internal.compiler.ast.InterTypeDeclaration; import org.aspectj.ajdt.internal.compiler.ast.PointcutDeclaration; import org.aspectj.ajdt.internal.core.builder.EclipseSourceContext; import org.aspectj.bridge.IMessage; import org.aspectj.org.eclipse.jdt.core.compiler.CharOperation; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.ASTNode; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.Annotation; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.Argument; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.ArrayInitializer; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.Expression; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.Literal; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.MarkerAnnotation; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.MemberValuePair; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.NameReference; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.NormalAnnotation; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.QualifiedNameReference; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.SingleMemberAnnotation; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.SingleNameReference; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.StringLiteral; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.TypeDeclaration; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.TypeParameter; import org.aspectj.org.eclipse.jdt.internal.compiler.impl.Constant; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.AnnotationBinding; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.ArrayBinding; 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.ExtraCompilerModifiers; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.FieldBinding; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.MethodBinding; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.ReferenceBinding; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.SourceTypeBinding; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.SyntheticMethodBinding; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.TagBits; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.TypeBinding; import org.aspectj.weaver.AbstractReferenceTypeDelegate; import org.aspectj.weaver.AnnotationAJ; import org.aspectj.weaver.AnnotationAnnotationValue; import org.aspectj.weaver.AnnotationNameValuePair; import org.aspectj.weaver.AnnotationTargetKind; import org.aspectj.weaver.AnnotationValue; import org.aspectj.weaver.ArrayAnnotationValue; import org.aspectj.weaver.BCException; import org.aspectj.weaver.EnumAnnotationValue; import org.aspectj.weaver.ReferenceType; import org.aspectj.weaver.ResolvedMember; import org.aspectj.weaver.ResolvedMemberImpl; import org.aspectj.weaver.ResolvedPointcutDefinition; import org.aspectj.weaver.ResolvedType; import org.aspectj.weaver.StandardAnnotation; import org.aspectj.weaver.TypeVariable; import org.aspectj.weaver.UnresolvedType; import org.aspectj.weaver.WeaverStateInfo; import org.aspectj.weaver.World; import org.aspectj.weaver.bcel.AtAjAttributes.LazyResolvedPointcutDefinition; import org.aspectj.weaver.patterns.Declare; import org.aspectj.weaver.patterns.FormalBinding; import org.aspectj.weaver.patterns.ParserException; import org.aspectj.weaver.patterns.PatternParser; import org.aspectj.weaver.patterns.PerClause; import org.aspectj.weaver.patterns.PerFromSuper; import org.aspectj.weaver.patterns.PerSingleton; import org.aspectj.weaver.patterns.Pointcut; /** * Supports viewing eclipse TypeDeclarations/SourceTypeBindings as a ResolvedType * * @author Jim Hugunin * @author Andy Clement */ public class EclipseSourceType extends AbstractReferenceTypeDelegate { private static final char[] pointcutSig = "Lorg/aspectj/lang/annotation/Pointcut;".toCharArray(); private static final char[] aspectSig = "Lorg/aspectj/lang/annotation/Aspect;".toCharArray(); protected ResolvedPointcutDefinition[] declaredPointcuts = null; protected ResolvedMember[] declaredMethods = null; protected ResolvedMember[] declaredFields = null; public List<Declare> declares = new ArrayList<Declare>(); public List<EclipseTypeMunger> typeMungers = new ArrayList<EclipseTypeMunger>(); private final EclipseFactory factory; private final SourceTypeBinding binding; private final TypeDeclaration declaration; private final CompilationUnitDeclaration unit; private boolean annotationsFullyResolved = false; private boolean annotationTypesAreResolved = false; private ResolvedType[] annotationTypes = null; private boolean discoveredAnnotationTargetKinds = false; private AnnotationTargetKind[] annotationTargetKinds; private AnnotationAJ[] annotations = null; protected EclipseFactory eclipseWorld() { return factory; } public EclipseSourceType(ReferenceType resolvedTypeX, EclipseFactory factory, SourceTypeBinding binding, TypeDeclaration declaration, CompilationUnitDeclaration unit) { super(resolvedTypeX, true); this.factory = factory; this.binding = binding; this.declaration = declaration; this.unit = unit; setSourceContext(new EclipseSourceContext(declaration.compilationResult)); resolvedTypeX.setStartPos(declaration.sourceStart); resolvedTypeX.setEndPos(declaration.sourceEnd); } public boolean isAspect() { final boolean isCodeStyle = declaration instanceof AspectDeclaration; return isCodeStyle ? isCodeStyle : isAnnotationStyleAspect(); } public boolean isAnonymous() { if (declaration.binding != null) { return declaration.binding.isAnonymousType(); } return ((declaration.modifiers & (ASTNode.IsAnonymousType | ASTNode.IsLocalType)) != 0); } public boolean isNested() { if (declaration.binding != null) { return (declaration.binding.isMemberType()); } return ((declaration.modifiers & ASTNode.IsMemberType) != 0); } public ResolvedType getOuterClass() { if (declaration.enclosingType == null) { return null; } return eclipseWorld().fromEclipse(declaration.enclosingType.binding); } public boolean isAnnotationStyleAspect() { if (declaration.annotations == null) { return false; } ResolvedType[] annotations = getAnnotationTypes(); for (int i = 0; i < annotations.length; i++) { if ("org.aspectj.lang.annotation.Aspect".equals(annotations[i].getName())) { return true; } } return false; } /** Returns "" if there is a problem */ private String getPointcutStringFromAnnotationStylePointcut(AbstractMethodDeclaration amd) { Annotation[] ans = amd.annotations; if (ans == null) { return ""; } for (int i = 0; i < ans.length; i++) { if (ans[i].resolvedType == null) { continue; // XXX happens if we do this very early from } // buildInterTypeandPerClause // may prevent us from resolving references made in @Pointcuts to // an @Pointcut in a code-style aspect char[] sig = ans[i].resolvedType.signature(); if (CharOperation.equals(pointcutSig, sig)) { if (ans[i].memberValuePairs().length == 0) { return ""; // empty pointcut expression } Expression expr = ans[i].memberValuePairs()[0].value; if (expr instanceof StringLiteral) { StringLiteral sLit = ((StringLiteral) expr); return new String(sLit.source()); } else if (expr instanceof NameReference && (((NameReference) expr).binding instanceof FieldBinding)) { Binding b = ((NameReference) expr).binding; Constant c = ((FieldBinding) b).constant; return c.stringValue(); } else { throw new BCException("Do not know how to recover pointcut definition from " + expr + " (type " + expr.getClass().getName() + ")"); } } } return ""; } private boolean isAnnotationStylePointcut(Annotation[] annotations) { if (annotations == null) { return false; } for (int i = 0; i < annotations.length; i++) { if (annotations[i].resolvedType == null) { continue; // XXX happens if we do this very early from } // buildInterTypeandPerClause // may prevent us from resolving references made in @Pointcuts to // an @Pointcut in a code-style aspect char[] sig = annotations[i].resolvedType.signature(); if (CharOperation.equals(pointcutSig, sig)) { return true; } } return false; } public WeaverStateInfo getWeaverState() { return null; } public ResolvedType getSuperclass() { if (binding.isInterface()) { return getResolvedTypeX().getWorld().getCoreType(UnresolvedType.OBJECT); } // XXX what about java.lang.Object return eclipseWorld().fromEclipse(binding.superclass()); } public ResolvedType[] getDeclaredInterfaces() { return eclipseWorld().fromEclipse(binding.superInterfaces()); } protected void fillDeclaredMembers() { List<ResolvedMember> declaredPointcuts = new ArrayList<ResolvedMember>(); List<ResolvedMember> declaredMethods = new ArrayList<ResolvedMember>(); List<ResolvedMember> declaredFields = new ArrayList<ResolvedMember>(); MethodBinding[] ms = binding.methods(); // the important side-effect of this call is to make // sure bindings are completed AbstractMethodDeclaration[] methods = declaration.methods; if (methods != null) { for (int i = 0, len = methods.length; i < len; i++) { AbstractMethodDeclaration amd = methods[i]; if (amd == null || amd.ignoreFurtherInvestigation) { continue; } if (amd instanceof PointcutDeclaration) { PointcutDeclaration d = (PointcutDeclaration) amd; ResolvedPointcutDefinition df = d.makeResolvedPointcutDefinition(factory); if (df != null) { declaredPointcuts.add(df); } } else if (amd instanceof InterTypeDeclaration) { // these are handled in a separate pass continue; } else if (amd instanceof DeclareDeclaration && !(amd instanceof DeclareAnnotationDeclaration)) { // surfaces // the // annotated // ajc$ method // these are handled in a separate pass continue; } else if (amd instanceof AdviceDeclaration) { // these are ignored during compilation and only used during // weaving continue; } else if ((amd.annotations != null) && isAnnotationStylePointcut(amd.annotations)) { // consider pointcuts defined via annotations ResolvedPointcutDefinition df = makeResolvedPointcutDefinition(amd); if (df != null) { declaredPointcuts.add(df); } } else { if (amd.binding == null || !amd.binding.isValidBinding()) { continue; } ResolvedMember member = factory.makeResolvedMember(amd.binding); if (unit != null) { boolean positionKnown = true; if (amd.binding.sourceMethod() == null) { if (amd.binding.declaringClass instanceof SourceTypeBinding) { SourceTypeBinding stb = ((SourceTypeBinding) amd.binding.declaringClass); if (stb.scope == null || stb.scope.referenceContext == null) { positionKnown = false; } } } if (positionKnown) { // pr229829 member.setSourceContext(new EclipseSourceContext(unit.compilationResult, amd.binding.sourceStart())); member.setPosition(amd.binding.sourceStart(), amd.binding.sourceEnd()); } else { member.setSourceContext(new EclipseSourceContext(unit.compilationResult, 0)); member.setPosition(0, 0); } } declaredMethods.add(member); } } } if (isEnum()) { // The bindings for the eclipse binding will include values/valueof for (int m=0,len=ms.length;m<len;m++) { MethodBinding mb = ms[m]; if ((mb instanceof SyntheticMethodBinding) && mb.isStatic()) { // cannot use .isSynthetic() because it isn't truly synthetic if (CharOperation.equals(mb.selector,valuesCharArray) && mb.parameters.length==0 && mb.returnType.isArrayType() && ((ArrayBinding)mb.returnType).leafComponentType()==binding) { // static <EnumType>[] values() ResolvedMember valuesMember = factory.makeResolvedMember(mb); valuesMember.setSourceContext(new EclipseSourceContext(unit.compilationResult, 0)); valuesMember.setPosition(0, 0); declaredMethods.add(valuesMember); } else if (CharOperation.equals(mb.selector,valueOfCharArray) && mb.parameters.length==1 && CharOperation.equals(mb.parameters[0].signature(),jlString) && mb.returnType==binding) { // static <EnumType> valueOf(String) ResolvedMember valueOfMember = factory.makeResolvedMember(mb); valueOfMember.setSourceContext(new EclipseSourceContext(unit.compilationResult, 0)); valueOfMember.setPosition(0, 0); declaredMethods.add(valueOfMember); } } } } FieldBinding[] fields = binding.fields(); for (int i = 0, len = fields.length; i < len; i++) { FieldBinding f = fields[i]; declaredFields.add(factory.makeResolvedMember(f)); } this.declaredPointcuts = declaredPointcuts.toArray(new ResolvedPointcutDefinition[declaredPointcuts.size()]); this.declaredMethods = declaredMethods.toArray(new ResolvedMember[declaredMethods.size()]); this.declaredFields = declaredFields.toArray(new ResolvedMember[declaredFields.size()]); } private final static char[] valuesCharArray = "values".toCharArray(); private final static char[] valueOfCharArray = "valueOf".toCharArray(); private final static char[] jlString = "Ljava/lang/String;".toCharArray(); private ResolvedPointcutDefinition makeResolvedPointcutDefinition(AbstractMethodDeclaration md) { if (md.binding == null) { return null; // there is another error that has caused this... // pr138143 } EclipseSourceContext eSourceContext = new EclipseSourceContext(md.compilationResult); Pointcut pc = null; if (!md.isAbstract()) { String expression = getPointcutStringFromAnnotationStylePointcut(md); try { pc = new PatternParser(expression, eSourceContext).parsePointcut(); } catch (ParserException pe) { // error will be reported by other // means... pc = Pointcut.makeMatchesNothing(Pointcut.SYMBOLIC); } } FormalBinding[] bindings = buildFormalAdviceBindingsFrom(md); ResolvedPointcutDefinition rpd = new LazyResolvedPointcutDefinition(factory.fromBinding(md.binding.declaringClass), md.modifiers, new String(md.selector), factory.fromBindings(md.binding.parameters), factory.fromBinding(md.binding.returnType), pc, new EclipseScope(bindings, md.scope)); rpd.setPosition(md.sourceStart, md.sourceEnd); rpd.setSourceContext(eSourceContext); return rpd; } private static final char[] joinPoint = "Lorg/aspectj/lang/JoinPoint;".toCharArray(); private static final char[] joinPointStaticPart = "Lorg/aspectj/lang/JoinPoint$StaticPart;".toCharArray(); private static final char[] joinPointEnclosingStaticPart = "Lorg/aspectj/lang/JoinPoint$EnclosingStaticPart;".toCharArray(); private static final char[] proceedingJoinPoint = "Lorg/aspectj/lang/ProceedingJoinPoint;".toCharArray(); private FormalBinding[] buildFormalAdviceBindingsFrom(AbstractMethodDeclaration mDecl) { if (mDecl.arguments == null) { return new FormalBinding[0]; } if (mDecl.binding == null) { return new FormalBinding[0]; } EclipseFactory factory = EclipseFactory.fromScopeLookupEnvironment(mDecl.scope); String extraArgName = "";// maybeGetExtraArgName(); FormalBinding[] ret = new FormalBinding[mDecl.arguments.length]; for (int i = 0; i < mDecl.arguments.length; i++) { Argument arg = mDecl.arguments[i]; String name = new String(arg.name); TypeBinding argTypeBinding = mDecl.binding.parameters[i]; UnresolvedType type = factory.fromBinding(argTypeBinding); if (CharOperation.equals(joinPoint, argTypeBinding.signature()) || CharOperation.equals(joinPointStaticPart, argTypeBinding.signature()) || CharOperation.equals(joinPointEnclosingStaticPart, argTypeBinding.signature()) || CharOperation.equals(proceedingJoinPoint, argTypeBinding.signature()) || name.equals(extraArgName)) { ret[i] = new FormalBinding.ImplicitFormalBinding(type, name, i); } else { ret[i] = new FormalBinding(type, name, i, arg.sourceStart, arg.sourceEnd); } } return ret; } /** * This method may not return all fields, for example it may not include the ajc$initFailureCause or ajc$perSingletonInstance * fields - see bug 129613 */ public ResolvedMember[] getDeclaredFields() { if (declaredFields == null) { fillDeclaredMembers(); } return declaredFields; } /** * This method may not return all methods, for example it may not include clinit, aspectOf, hasAspect or ajc$postClinit methods * - see bug 129613 */ public ResolvedMember[] getDeclaredMethods() { if (declaredMethods == null) { fillDeclaredMembers(); } return declaredMethods; } public ResolvedMember[] getDeclaredPointcuts() { if (declaredPointcuts == null) { fillDeclaredMembers(); } return declaredPointcuts; } public int getModifiers() { // only return the real Java modifiers, not the extra eclipse ones return binding.modifiers & ExtraCompilerModifiers.AccJustFlag; } public String toString() { return "EclipseSourceType(" + new String(binding.sourceName()) + ")"; } // XXX make sure this is applied to classes and interfaces public void checkPointcutDeclarations() { ResolvedMember[] pointcuts = getDeclaredPointcuts(); boolean sawError = false; for (int i = 0, len = pointcuts.length; i < len; i++) { if (pointcuts[i] == null) { // Something else is broken in this file and will be reported separately continue; } if (pointcuts[i].isAbstract()) { if (!this.isAspect()) { eclipseWorld().showMessage(IMessage.ERROR, "abstract pointcut only allowed in aspect" + pointcuts[i].getName(), pointcuts[i].getSourceLocation(), null); sawError = true; } else if (!binding.isAbstract()) { eclipseWorld().showMessage(IMessage.ERROR, "abstract pointcut in concrete aspect" + pointcuts[i], pointcuts[i].getSourceLocation(), null); sawError = true; } } for (int j = i + 1; j < len; j++) { if (pointcuts[j] == null) { // Something else is broken in this file and will be reported separately continue; } if (pointcuts[i].getName().equals(pointcuts[j].getName())) { eclipseWorld().showMessage(IMessage.ERROR, "duplicate pointcut name: " + pointcuts[j].getName(), pointcuts[i].getSourceLocation(), pointcuts[j].getSourceLocation()); sawError = true; } } } // now check all inherited pointcuts to be sure that they're handled // reasonably if (sawError || !isAspect()) { return; } // find all pointcuts that override ones from super and check override // is legal // i.e. same signatures and greater or equal visibility // find all inherited abstract pointcuts and make sure they're // concretized if I'm concrete // find all inherited pointcuts and make sure they don't conflict getResolvedTypeX().getExposedPointcuts(); // ??? this is an odd // construction } // ??? // public CrosscuttingMembers collectCrosscuttingMembers() { // return crosscuttingMembers; // } // public ISourceLocation getSourceLocation() { // TypeDeclaration dec = binding.scope.referenceContext; // return new EclipseSourceLocation(dec.compilationResult, dec.sourceStart, // dec.sourceEnd); // } public boolean isInterface() { return binding.isInterface(); } // XXXAJ5: Should be constants in the eclipse compiler somewhere, once it // supports 1.5 public final static short ACC_ANNOTATION = 0x2000; public final static short ACC_ENUM = 0x4000; public boolean isEnum() { return (binding.getAccessFlags() & ACC_ENUM) != 0; } public boolean isAnnotation() { return (binding.getAccessFlags() & ACC_ANNOTATION) != 0; } public boolean isAnnotationWithRuntimeRetention() { if (!isAnnotation()) { return false; } else { return (binding.getAnnotationTagBits() & TagBits.AnnotationRetentionMASK) == TagBits.AnnotationRuntimeRetention; } } public String getRetentionPolicy() { if (isAnnotation()) { if ((binding.getAnnotationTagBits() & TagBits.AnnotationRetentionMASK) == TagBits.AnnotationRuntimeRetention) { return "RUNTIME"; } if ((binding.getAnnotationTagBits() & TagBits.AnnotationRetentionMASK) == TagBits.AnnotationSourceRetention) { return "SOURCE"; } if ((binding.getAnnotationTagBits() & TagBits.AnnotationRetentionMASK) == TagBits.AnnotationClassRetention) { return "CLASS"; } } return null; } public boolean canAnnotationTargetType() { if (isAnnotation()) { return ((binding.getAnnotationTagBits() & TagBits.AnnotationForType) != 0); } 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 // if (isAnnotation()) { // Annotation[] annotationsOnThisType = declaration.annotations; // if (annotationsOnThisType != null) { // for (int i = 0; i < annotationsOnThisType.length; i++) { // Annotation a = annotationsOnThisType[i]; // if (a.resolvedType != null) { // String packageName = new // String(a.resolvedType.qualifiedPackageName()).concat("."); // String sourceName = new String(a.resolvedType.qualifiedSourceName()); // if ((packageName + // sourceName).equals(UnresolvedType.AT_TARGET.getName())) { // MemberValuePair[] pairs = a.memberValuePairs(); // for (int j = 0; j < pairs.length; j++) { // MemberValuePair pair = pairs[j]; // targetKind = pair.value.toString(); // return targetKind; // } // } // } // } // } // } // return targetKind; if (isAnnotation()) { List<AnnotationTargetKind> targetKinds = new ArrayList<AnnotationTargetKind>(); if ((binding.getAnnotationTagBits() & TagBits.AnnotationForAnnotationType) != 0) { targetKinds.add(AnnotationTargetKind.ANNOTATION_TYPE); } if ((binding.getAnnotationTagBits() & TagBits.AnnotationForConstructor) != 0) { targetKinds.add(AnnotationTargetKind.CONSTRUCTOR); } if ((binding.getAnnotationTagBits() & TagBits.AnnotationForField) != 0) { targetKinds.add(AnnotationTargetKind.FIELD); } if ((binding.getAnnotationTagBits() & TagBits.AnnotationForLocalVariable) != 0) { targetKinds.add(AnnotationTargetKind.LOCAL_VARIABLE); } if ((binding.getAnnotationTagBits() & TagBits.AnnotationForMethod) != 0) { targetKinds.add(AnnotationTargetKind.METHOD); } if ((binding.getAnnotationTagBits() & TagBits.AnnotationForPackage) != 0) { targetKinds.add(AnnotationTargetKind.PACKAGE); } if ((binding.getAnnotationTagBits() & TagBits.AnnotationForParameter) != 0) { targetKinds.add(AnnotationTargetKind.PARAMETER); } if ((binding.getAnnotationTagBits() & TagBits.AnnotationForType) != 0) { targetKinds.add(AnnotationTargetKind.TYPE); } if (!targetKinds.isEmpty()) { annotationTargetKinds = new AnnotationTargetKind[targetKinds.size()]; return targetKinds.toArray(annotationTargetKinds); } } return annotationTargetKinds; } /** * Ensure the annotation types have been resolved, where resolved means the eclipse type bindings have been converted to their * ResolvedType representations. This does not deeply resolve the annotations, it only does the type names. */ private void ensureAnnotationTypesResolved() { // may need to re-resolve if new annotations have been added int declarationAnnoCount = (declaration.annotations == null ? 0 : declaration.annotations.length); if (!annotationTypesAreResolved || declarationAnnoCount != annotationTypes.length) { Annotation[] as = declaration.annotations; if (as == null) { annotationTypes = ResolvedType.NONE; } else { annotationTypes = new ResolvedType[as.length]; for (int a = 0; a < as.length; a++) { TypeBinding tb = as[a].type.resolveType(declaration.staticInitializerScope); if (tb == null) { annotationTypes[a] = ResolvedType.MISSING; } else { annotationTypes[a] = factory.fromTypeBindingToRTX(tb); } } } annotationTypesAreResolved = true; } } public boolean hasAnnotation(UnresolvedType ofType) { ensureAnnotationTypesResolved(); for (int a = 0, max = annotationTypes.length; a < max; a++) { if (ofType.equals(annotationTypes[a])) { return true; } } return false; } /** * WARNING: This method does not have a complete implementation. * * The aim is that it converts Eclipse annotation objects to the AspectJ form of annotations (the type AnnotationAJ). The * AnnotationX objects returned are wrappers over either a Bcel annotation type or the AspectJ AnnotationAJ type. The minimal * implementation provided here is for processing the RetentionPolicy and Target annotation types - these are the only ones * which the weaver will attempt to process from an EclipseSourceType. * * More notes: The pipeline has required us to implement this. With the pipeline we can be weaving a type and asking questions * of annotations before they have been turned into Bcel objects - ie. when they are still in EclipseSourceType form. Without * the pipeline we would have converted everything to Bcel objects before proceeding with weaving. Because the pipeline won't * start weaving until all aspects have been compiled and the fact that no AspectJ constructs match on the values within * annotations, this code only needs to deal with converting system annotations that the weaver needs to process * (RetentionPolicy, Target). */ public AnnotationAJ[] getAnnotations() { if (annotations != null) { return annotations; // only do this once } if (!annotationsFullyResolved) { TypeDeclaration.resolveAnnotations(declaration.staticInitializerScope, declaration.annotations, binding); annotationsFullyResolved = true; } Annotation[] as = declaration.annotations; if (as == null || as.length == 0) { annotations = AnnotationAJ.EMPTY_ARRAY; } else { annotations = new AnnotationAJ[as.length]; for (int i = 0; i < as.length; i++) { annotations[i] = convertEclipseAnnotation(as[i], factory.getWorld()); } } return annotations; } /** * Convert one eclipse annotation into an AnnotationX object containing an AnnotationAJ object. * * This code and the helper methods used by it will go *BANG* if they encounter anything not currently supported - this is safer * than limping along with a malformed annotation. When the *BANG* is encountered the bug reporter should indicate the kind of * annotation they were working with and this code can be enhanced to support it. */ public AnnotationAJ convertEclipseAnnotation(Annotation eclipseAnnotation, World w) { // TODO if it is sourcevisible, we shouldn't let it through!!!!!!!!! // testcase! ResolvedType annotationType = factory.fromTypeBindingToRTX(eclipseAnnotation.type.resolvedType); // long bs = (eclipseAnnotation.bits & TagBits.AnnotationRetentionMASK); boolean isRuntimeVisible = (eclipseAnnotation.bits & TagBits.AnnotationRetentionMASK) == TagBits.AnnotationRuntimeRetention; StandardAnnotation annotationAJ = new StandardAnnotation(annotationType, isRuntimeVisible); generateAnnotation(eclipseAnnotation, annotationAJ, w); return annotationAJ; } static class MissingImplementationException extends RuntimeException { MissingImplementationException(String reason) { super(reason); } } /** * Use the information in the supplied eclipse based annotation to fill in the standard annotation. * * @param annotation eclipse based annotation representation * @param annotationAJ AspectJ based annotation representation */ private void generateAnnotation(Annotation annotation, StandardAnnotation annotationAJ, World w) { if (annotation instanceof NormalAnnotation) { NormalAnnotation normalAnnotation = (NormalAnnotation) annotation; MemberValuePair[] memberValuePairs = normalAnnotation.memberValuePairs; if (memberValuePairs != null) { int memberValuePairsLength = memberValuePairs.length; for (int i = 0; i < memberValuePairsLength; i++) { MemberValuePair memberValuePair = memberValuePairs[i]; MethodBinding methodBinding = memberValuePair.binding; if (methodBinding == null) { // is this just a marker annotation? if (memberValuePair.value instanceof MarkerAnnotation) { MarkerAnnotation eMarkerAnnotation = (MarkerAnnotation) memberValuePair.value; AnnotationBinding eMarkerAnnotationBinding = eMarkerAnnotation.getCompilerAnnotation(); ReferenceBinding eAnnotationType = eMarkerAnnotationBinding.getAnnotationType(); ResolvedType ajAnnotationType = factory.fromTypeBindingToRTX(eAnnotationType); boolean isRuntimeVisible = (eMarkerAnnotation.bits & TagBits.AnnotationRetentionMASK) == TagBits.AnnotationRuntimeRetention; StandardAnnotation ajAnnotation = new StandardAnnotation(ajAnnotationType, isRuntimeVisible); AnnotationValue av = new AnnotationAnnotationValue(ajAnnotation); AnnotationNameValuePair anvp = new AnnotationNameValuePair(new String(memberValuePair.name), av); annotationAJ.addNameValuePair(anvp); // } else if (memberValuePair.value instanceof NormalAnnotation) { // NormalAnnotation eNormalAnnotation = (NormalAnnotation) memberValuePair.value; // AnnotationBinding eMarkerAnnotationBinding = eNormalAnnotation.getCompilerAnnotation(); // ReferenceBinding eAnnotationType = eMarkerAnnotationBinding.getAnnotationType(); // ResolvedType ajAnnotationType = factory.fromTypeBindingToRTX(eAnnotationType); // boolean isRuntimeVisible = (eNormalAnnotation.bits & TagBits.AnnotationRetentionMASK) == // TagBits.AnnotationRuntimeRetention; // StandardAnnotation ajAnnotation = new StandardAnnotation(ajAnnotationType, isRuntimeVisible); // MemberValuePair[] pairs = eNormalAnnotation.memberValuePairs; // if (pairs != null) { // for (int p = 0; p < pairs.length; p++) { // MemberValuePair pair = pairs[p]; // throw new IllegalStateException("nyi"); // // } // } // AnnotationValue av = new AnnotationAnnotationValue(ajAnnotation); // AnnotationNameValuePair anvp = new AnnotationNameValuePair(new String(memberValuePair.name), av); // annotationAJ.addNameValuePair(anvp); } else if (memberValuePair.value instanceof Literal) { AnnotationValue av = generateElementValue(memberValuePair.value, ((Literal) memberValuePair.value).resolvedType); AnnotationNameValuePair anvp = new AnnotationNameValuePair(new String(memberValuePair.name), av); annotationAJ.addNameValuePair(anvp); } else if (memberValuePair.value instanceof ArrayInitializer) { ArrayInitializer arrayInitializer = (ArrayInitializer) memberValuePair.value; Expression[] expressions = arrayInitializer.expressions; AnnotationValue[] arrayValues = new AnnotationValue[expressions.length]; for (int e = 0; e < expressions.length; e++) { arrayValues[e] = generateElementValue(expressions[e], ((ArrayBinding) arrayInitializer.resolvedType).leafComponentType); } AnnotationValue array = new ArrayAnnotationValue(arrayValues); AnnotationNameValuePair anvp = new AnnotationNameValuePair(new String(memberValuePair.name), array); annotationAJ.addNameValuePair(anvp); } else { throw new MissingImplementationException( "Please raise an AspectJ bug. AspectJ does not know how to convert this annotation [" + annotation + "]"); } } else { AnnotationValue av = generateElementValue(memberValuePair.value, methodBinding.returnType); AnnotationNameValuePair anvp = new AnnotationNameValuePair(new String(memberValuePair.name), av); annotationAJ.addNameValuePair(anvp); } } } } else if (annotation instanceof SingleMemberAnnotation) { // this is a single member annotation (one member value) SingleMemberAnnotation singleMemberAnnotation = (SingleMemberAnnotation) annotation; MethodBinding methodBinding = singleMemberAnnotation.memberValuePairs()[0].binding; if (methodBinding == null) { throw new MissingImplementationException( "Please raise an AspectJ bug. AspectJ does not know how to convert this annotation [" + annotation + "]"); } else { AnnotationValue av = generateElementValue(singleMemberAnnotation.memberValue, methodBinding.returnType); annotationAJ.addNameValuePair(new AnnotationNameValuePair(new String( singleMemberAnnotation.memberValuePairs()[0].name), av)); } } else if (annotation instanceof MarkerAnnotation) { return; } else { // this is something else... throw new MissingImplementationException( "Please raise an AspectJ bug. AspectJ does not know how to convert this annotation [" + annotation + "]"); } } private AnnotationValue generateElementValue(Expression defaultValue, TypeBinding memberValuePairReturnType) { Constant constant = defaultValue.constant; TypeBinding defaultValueBinding = defaultValue.resolvedType; if (defaultValueBinding == null) { throw new MissingImplementationException( "Please raise an AspectJ bug. AspectJ does not know how to convert this annotation value [" + defaultValue + "]"); } else { if (memberValuePairReturnType.isArrayType() && !defaultValueBinding.isArrayType()) { if (constant != null && constant != Constant.NotAConstant) { // Testcase for this clause is MultiProjectIncrementalTests.testAnnotations_pr262154() AnnotationValue av = EclipseAnnotationConvertor.generateElementValueForConstantExpression(defaultValue, defaultValueBinding); return new ArrayAnnotationValue(new AnnotationValue[] { av }); } else { AnnotationValue av = generateElementValueForNonConstantExpression(defaultValue, defaultValueBinding); return new ArrayAnnotationValue(new AnnotationValue[] { av }); } } else { if (constant != null && constant != Constant.NotAConstant) { AnnotationValue av = EclipseAnnotationConvertor.generateElementValueForConstantExpression(defaultValue, defaultValueBinding); if (av == null) { throw new MissingImplementationException( "Please raise an AspectJ bug. AspectJ does not know how to convert this annotation value [" + defaultValue + "]"); } return av; // generateElementValue(attributeOffset, defaultValue, // constant, memberValuePairReturnType.leafComponentType()); } else { AnnotationValue av = generateElementValueForNonConstantExpression(defaultValue, defaultValueBinding); return av; } } } } private AnnotationValue generateElementValueForNonConstantExpression(Expression defaultValue, TypeBinding defaultValueBinding) { if (defaultValueBinding != null) { if (defaultValueBinding.isEnum()) { FieldBinding fieldBinding = null; if (defaultValue instanceof QualifiedNameReference) { QualifiedNameReference nameReference = (QualifiedNameReference) defaultValue; fieldBinding = (FieldBinding) nameReference.binding; } else if (defaultValue instanceof SingleNameReference) { SingleNameReference nameReference = (SingleNameReference) defaultValue; fieldBinding = (FieldBinding) nameReference.binding; } else { throw new MissingImplementationException( "Please raise an AspectJ bug. AspectJ does not know how to convert this annotation value [" + defaultValue + "]"); } if (fieldBinding != null) { String sig = new String(fieldBinding.type.signature()); AnnotationValue enumValue = new EnumAnnotationValue(sig, new String(fieldBinding.name)); return enumValue; } throw new MissingImplementationException( "Please raise an AspectJ bug. AspectJ does not know how to convert this annotation value [" + defaultValue + "]"); } else if (defaultValueBinding.isAnnotationType()) { if (defaultValue instanceof MarkerAnnotation) { ResolvedType ajAnnotationType = factory.fromTypeBindingToRTX(defaultValueBinding); StandardAnnotation ajAnnotation = new StandardAnnotation(ajAnnotationType, ajAnnotationType.isAnnotationWithRuntimeRetention()); AnnotationValue av = new AnnotationAnnotationValue(ajAnnotation); return av; } else if (defaultValue instanceof NormalAnnotation) { NormalAnnotation normalAnnotation = (NormalAnnotation) defaultValue; ResolvedType ajAnnotationType = factory.fromTypeBindingToRTX(defaultValueBinding); StandardAnnotation ajAnnotation = new StandardAnnotation(ajAnnotationType, ajAnnotationType.isAnnotationWithRuntimeRetention()); MemberValuePair[] pairs = normalAnnotation.memberValuePairs; if (pairs != null) { for (int p = 0; p < pairs.length; p++) { MemberValuePair pair = pairs[p]; Expression valueEx = pair.value; AnnotationValue pairValue = null; if (valueEx instanceof Literal) { pairValue = generateElementValue(valueEx, ((Literal) valueEx).resolvedType); } else { pairValue = generateElementValue(pair.value, pair.binding.returnType); } ajAnnotation.addNameValuePair(new AnnotationNameValuePair(new String(pair.name), pairValue)); } } AnnotationValue av = new AnnotationAnnotationValue(ajAnnotation); return av; } else { throw new MissingImplementationException( "Please raise an AspectJ bug. AspectJ does not know how to convert this annotation value [" + defaultValue + "]"); } } else if (defaultValueBinding.isArrayType()) { // array type if (defaultValue instanceof ArrayInitializer) { ArrayInitializer arrayInitializer = (ArrayInitializer) defaultValue; int arrayLength = arrayInitializer.expressions != null ? arrayInitializer.expressions.length : 0; AnnotationValue[] values = new AnnotationValue[arrayLength]; for (int i = 0; i < arrayLength; i++) { values[i] = generateElementValue(arrayInitializer.expressions[i], defaultValueBinding.leafComponentType());// , // attributeOffset // ) // ; } ArrayAnnotationValue aav = new ArrayAnnotationValue(values); return aav; } else { throw new MissingImplementationException( "Please raise an AspectJ bug. AspectJ does not know how to convert this annotation value [" + defaultValue + "]"); } // } else if (defaultValue instanceof MagicLiteral) { // if (defaultValue instanceof FalseLiteral) { // new AnnotationValue // } else if (defaultValue instanceof TrueLiteral) { // // } else { // throw new MissingImplementationException( // "Please raise an AspectJ bug. AspectJ does not know how to convert this annotation value [" // +defaultValue+"]"); // } } else { // class type throw new MissingImplementationException( "Please raise an AspectJ bug. AspectJ does not know how to convert this annotation value [" + defaultValue + "]"); // if (contentsOffset + 3 >= this.contents.length) { // resizeContents(3); // } // contents[contentsOffset++] = (byte) 'c'; // if (defaultValue instanceof ClassLiteralAccess) { // ClassLiteralAccess classLiteralAccess = (ClassLiteralAccess) // defaultValue; // final int classInfoIndex = // constantPool.literalIndex(classLiteralAccess // .targetType.signature()); // contents[contentsOffset++] = (byte) (classInfoIndex >> 8); // contents[contentsOffset++] = (byte) classInfoIndex; // } else { // contentsOffset = attributeOffset; // } } } else { throw new MissingImplementationException( "Please raise an AspectJ bug. AspectJ does not know how to convert this annotation value [" + defaultValue + "]"); // contentsOffset = attributeOffset; } } public ResolvedType[] getAnnotationTypes() { ensureAnnotationTypesResolved(); return annotationTypes; } public PerClause getPerClause() { // should probably be: ((AspectDeclaration)declaration).perClause; // but we don't need this level of detail, and working with real per // clauses // at this stage of compilation is not worth the trouble if (!isAnnotationStyleAspect()) { if (declaration instanceof AspectDeclaration) { PerClause pc = ((AspectDeclaration) declaration).perClause; if (pc != null) { return pc; } } return new PerSingleton(); } else { // for @Aspect, we do need the real kind though we don't need the // real perClause // at least try to get the right perclause PerClause pc = null; if (declaration instanceof AspectDeclaration) { pc = ((AspectDeclaration) declaration).perClause; } if (pc == null) { PerClause.Kind kind = getPerClauseForTypeDeclaration(declaration); // returning a perFromSuper is enough to get the correct kind.. // (that's really a hack - AV) return new PerFromSuper(kind); } return pc; } } PerClause.Kind getPerClauseForTypeDeclaration(TypeDeclaration typeDeclaration) { Annotation[] annotations = typeDeclaration.annotations; for (int i = 0; i < annotations.length; i++) { Annotation annotation = annotations[i]; if (annotation != null && annotation.resolvedType != null && CharOperation.equals(aspectSig, annotation.resolvedType.signature())) { // found @Aspect(...) if (annotation.memberValuePairs() == null || annotation.memberValuePairs().length == 0) { // it is an @Aspect or @Aspect() // needs to use PerFromSuper if declaration extends a super // aspect PerClause.Kind kind = lookupPerClauseKind(typeDeclaration.binding.superclass); // if no super aspect, we have a @Aspect() means singleton if (kind == null) { return PerClause.SINGLETON; } else { return kind; } } else if (annotation instanceof SingleMemberAnnotation) { // it is an @Aspect(...something...) SingleMemberAnnotation theAnnotation = (SingleMemberAnnotation) annotation; String clause = new String(((StringLiteral) theAnnotation.memberValue).source());// TODO // cast // safe // ? return determinePerClause(typeDeclaration, clause); } else if (annotation instanceof NormalAnnotation) { // this // kind // if it // was // added // by // the // visitor // ! // it is an @Aspect(...something...) NormalAnnotation theAnnotation = (NormalAnnotation) annotation; if (theAnnotation.memberValuePairs == null || theAnnotation.memberValuePairs.length < 1) { return PerClause.SINGLETON; } String clause = new String(((StringLiteral) theAnnotation.memberValuePairs[0].value).source());// TODO // cast // safe // ? return determinePerClause(typeDeclaration, clause); } else { eclipseWorld().showMessage( IMessage.ABORT, "@Aspect annotation is expected to be SingleMemberAnnotation with 'String value()' as unique element", new EclipseSourceLocation(typeDeclaration.compilationResult, typeDeclaration.sourceStart, typeDeclaration.sourceEnd), null); return PerClause.SINGLETON;// fallback strategy just to // avoid NPE } } } return null;// no @Aspect annotation at all (not as aspect) } private PerClause.Kind determinePerClause(TypeDeclaration typeDeclaration, String clause) { if (clause.startsWith("perthis(")) { return PerClause.PEROBJECT; } else if (clause.startsWith("pertarget(")) { return PerClause.PEROBJECT; } else if (clause.startsWith("percflow(")) { return PerClause.PERCFLOW; } else if (clause.startsWith("percflowbelow(")) { return PerClause.PERCFLOW; } else if (clause.startsWith("pertypewithin(")) { return PerClause.PERTYPEWITHIN; } else if (clause.startsWith("issingleton(")) { return PerClause.SINGLETON; } else { eclipseWorld().showMessage( IMessage.ABORT, "cannot determine perClause '" + clause + "'", new EclipseSourceLocation(typeDeclaration.compilationResult, typeDeclaration.sourceStart, typeDeclaration.sourceEnd), null); return PerClause.SINGLETON;// fallback strategy just to avoid NPE } } // adapted from AspectDeclaration private PerClause.Kind lookupPerClauseKind(ReferenceBinding binding) { final PerClause.Kind kind; if (binding instanceof BinaryTypeBinding) { ResolvedType superTypeX = factory.fromEclipse(binding); PerClause perClause = superTypeX.getPerClause(); // clause is null for non aspect classes since coming from BCEL // attributes if (perClause != null) { kind = superTypeX.getPerClause().getKind(); } else { kind = null; } } else if (binding instanceof SourceTypeBinding) { SourceTypeBinding sourceSc = (SourceTypeBinding) binding; if (sourceSc.scope.referenceContext instanceof AspectDeclaration) { // code style kind = ((AspectDeclaration) sourceSc.scope.referenceContext).perClause.getKind(); } else { // if (sourceSc.scope.referenceContext instanceof // TypeDeclaration) { // if @Aspect: perFromSuper, else if @Aspect(..) get from anno // value, else null kind = getPerClauseForTypeDeclaration((sourceSc.scope.referenceContext)); } } else { // XXX need to handle this too kind = null; } return kind; } public Collection getDeclares() { return declares; } public Collection getPrivilegedAccesses() { return Collections.EMPTY_LIST; } public Collection getTypeMungers() { return typeMungers; } public boolean doesNotExposeShadowMungers() { return true; } public String getDeclaredGenericSignature() { return CharOperation.charToString(binding.genericSignature()); } public boolean isGeneric() { return binding.isGenericType(); } public TypeVariable[] getTypeVariables() { if (declaration.typeParameters == null) { return new TypeVariable[0]; } TypeVariable[] typeVariables = new TypeVariable[declaration.typeParameters.length]; for (int i = 0; i < typeVariables.length; i++) { typeVariables[i] = typeParameter2TypeVariable(declaration.typeParameters[i]); } return typeVariables; } private TypeVariable typeParameter2TypeVariable(TypeParameter typeParameter) { String name = new String(typeParameter.name); ReferenceBinding superclassBinding = typeParameter.binding.superclass; UnresolvedType superclass = UnresolvedType.forSignature(new String(superclassBinding.signature())); UnresolvedType[] superinterfaces = null; ReferenceBinding[] superInterfaceBindings = typeParameter.binding.superInterfaces; if (superInterfaceBindings != null) { superinterfaces = new UnresolvedType[superInterfaceBindings.length]; for (int i = 0; i < superInterfaceBindings.length; i++) { superinterfaces[i] = UnresolvedType.forSignature(new String(superInterfaceBindings[i].signature())); } } // XXX what about lower binding? TypeVariable tv = new TypeVariable(name, superclass, superinterfaces); tv.setDeclaringElement(factory.fromBinding(typeParameter.binding.declaringElement)); tv.setRank(typeParameter.binding.rank); return tv; } }
399,590
Bug 399590 Bad generics signature generated
null
resolved fixed
4af4b1e
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2013-02-04T21:33:26Z"
"2013-01-31T08:13:20Z"
org.aspectj.matcher/src/org/aspectj/weaver/BoundedReferenceType.java
/* ******************************************************************* * Copyright (c) 2010 Contributors. * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Eclipse Public License v1.0 * which accompanies this distribution and is available at * http://eclipse.org/legal/epl-v10.html * ******************************************************************/ package org.aspectj.weaver; import java.util.Map; /** * A BoundedReferenceType is the result of a generics wildcard expression ? extends String, ? super Foo etc.. * * The "signature" for a bounded reference type follows the generic signature specification in section 4.4 of JVM spec: *,+,- plus * signature strings. * * The bound may be a type variable (e.g. ? super T) * * @author Adrian Colyer * @author Andy Clement */ public class BoundedReferenceType extends ReferenceType { // possible kinds of BoundedReferenceType public static final int UNBOUND = 0; public static final int EXTENDS = 1; public static final int SUPER = 2; public int kind; private ResolvedType lowerBound; private ResolvedType upperBound; protected ReferenceType[] additionalInterfaceBounds = ReferenceType.EMPTY_ARRAY; public BoundedReferenceType(ReferenceType aBound, boolean isExtends, World world) { super((isExtends ? "+" : "-") + aBound.signature, aBound.signatureErasure, world); if (isExtends) { this.kind = EXTENDS; } else { this.kind = SUPER; } if (isExtends) { upperBound = aBound; } else { lowerBound = aBound; upperBound = world.resolve(UnresolvedType.OBJECT); } setDelegate(new BoundedReferenceTypeDelegate((ReferenceType) getUpperBound())); } public BoundedReferenceType(ReferenceType aBound, boolean isExtends, World world, ReferenceType[] additionalInterfaces) { this(aBound, isExtends, world); this.additionalInterfaceBounds = additionalInterfaces; } /** * only for use when resolving GenericsWildcardTypeX or a TypeVariableReferenceType */ protected BoundedReferenceType(String signature, String erasedSignature, World world) { super(signature, erasedSignature, world); if (signature.equals("*")) { // pure wildcard this.kind = UNBOUND; upperBound = world.resolve(UnresolvedType.OBJECT); } else { upperBound = world.resolve(forSignature(erasedSignature)); } setDelegate(new BoundedReferenceTypeDelegate((ReferenceType) upperBound)); } /** * Constructs the BoundedReferenceType representing an unbounded wildcard '?'. In this situation the signature is '*' and the * erased signature is Ljava/lang/Object; */ public BoundedReferenceType(World world) { super("*", "Ljava/lang/Object;", world); this.kind = UNBOUND; upperBound = world.resolve(UnresolvedType.OBJECT); setDelegate(new BoundedReferenceTypeDelegate((ReferenceType) upperBound)); } public UnresolvedType getUpperBound() { return upperBound; } public UnresolvedType getLowerBound() { return lowerBound; } public ReferenceType[] getAdditionalBounds() { return additionalInterfaceBounds; } @Override public UnresolvedType parameterize(Map<String, UnresolvedType> typeBindings) { if (this.kind == UNBOUND) { return this; } ReferenceType[] parameterizedAdditionalInterfaces = new ReferenceType[additionalInterfaceBounds == null ? 0 : additionalInterfaceBounds.length]; for (int i = 0; i < parameterizedAdditionalInterfaces.length; i++) { parameterizedAdditionalInterfaces[i] = (ReferenceType) additionalInterfaceBounds[i].parameterize(typeBindings); } if (this.kind == EXTENDS) { return new BoundedReferenceType((ReferenceType) getUpperBound().parameterize(typeBindings), true, world, parameterizedAdditionalInterfaces); } else { // (this.kind == SUPER) return new BoundedReferenceType((ReferenceType) getLowerBound().parameterize(typeBindings), false, world, parameterizedAdditionalInterfaces); } } public boolean hasLowerBound() { return lowerBound != null; } public boolean isExtends() { return this.kind == EXTENDS; } public boolean isSuper() { return this.kind == SUPER; } public boolean isUnbound() { return this.kind == UNBOUND; } public boolean alwaysMatches(ResolvedType aCandidateType) { if (isExtends()) { // aCandidateType must be a subtype of upperBound return ((ReferenceType) getUpperBound()).isAssignableFrom(aCandidateType); } else if (isSuper()) { // aCandidateType must be a supertype of lowerBound return aCandidateType.isAssignableFrom((ReferenceType) getLowerBound()); } else { return true; // straight '?' } } // this "maybe matches" that public boolean canBeCoercedTo(ResolvedType aCandidateType) { if (alwaysMatches(aCandidateType)) { return true; } if (aCandidateType.isGenericWildcard()) { BoundedReferenceType boundedRT = (BoundedReferenceType) aCandidateType; ResolvedType myUpperBound = (ResolvedType) getUpperBound(); ResolvedType myLowerBound = (ResolvedType) getLowerBound(); if (isExtends()) { if (boundedRT.isExtends()) { return myUpperBound.isAssignableFrom((ResolvedType) boundedRT.getUpperBound()); } else if (boundedRT.isSuper()) { return myUpperBound == boundedRT.getLowerBound(); } else { return true; // it's '?' } } else if (isSuper()) { if (boundedRT.isSuper()) { return ((ResolvedType) boundedRT.getLowerBound()).isAssignableFrom(myLowerBound); } else if (boundedRT.isExtends()) { return myLowerBound == boundedRT.getUpperBound(); } else { return true; } } else { return true; } } else { return false; } } @Override public String getSimpleName() { if (!isExtends() && !isSuper()) { return "?"; } if (isExtends()) { return ("? extends " + getUpperBound().getSimpleName()); } else { return ("? super " + getLowerBound().getSimpleName()); } } // override to include additional interface bounds... @Override public ResolvedType[] getDeclaredInterfaces() { ResolvedType[] interfaces = super.getDeclaredInterfaces(); if (additionalInterfaceBounds.length > 0) { ResolvedType[] allInterfaces = new ResolvedType[interfaces.length + additionalInterfaceBounds.length]; System.arraycopy(interfaces, 0, allInterfaces, 0, interfaces.length); System.arraycopy(additionalInterfaceBounds, 0, allInterfaces, interfaces.length, additionalInterfaceBounds.length); return allInterfaces; } else { return interfaces; } } @Override public boolean isGenericWildcard() { return true; } }
399,590
Bug 399590 Bad generics signature generated
null
resolved fixed
4af4b1e
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2013-02-04T21:33:26Z"
"2013-01-31T08:13:20Z"
tests/bugs172/pr399590/Cage.java