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
149,293
Bug 149293 declare annotation problem: AIOOBE at ProblemReporter.java:2992
This has been happening a lot, but I'm having trouble figuring out why it's happening. It's always "5". It happens both in Eclipse and from the command line. java.lang.ArrayIndexOutOfBoundsException at org.aspectj.org.eclipse.jdt.internal.compiler.problem.ProblemReporter.invalidType(ProblemReporter.java:2992) at org.aspectj.org.eclipse.jdt.internal.compiler.ast.TypeReference.reportInvalidType(TypeReference.java:170) at org.aspectj.org.eclipse.jdt.internal.compiler.ast.TypeReference.resolveType(TypeReference.java:136) at org.aspectj.org.eclipse.jdt.internal.compiler.ast.TypeReference.resolveType(TypeReference.java:123) at org.aspectj.org.eclipse.jdt.internal.compiler.ast.Annotation.resolveType(Annotation.java:214) at org.aspectj.org.eclipse.jdt.internal.compiler.ast.ASTNode.resolveAnnotations(ASTNode.java:436) at org.aspectj.ajdt.internal.compiler.lookup.EclipseSourceType.getAnnotationTypes(EclipseSourceType.java:443) at org.aspectj.ajdt.internal.compiler.lookup.EclipseSourceType.isAnnotationStyleAspect(EclipseSourceType.java:123) at org.aspectj.ajdt.internal.compiler.lookup.EclipseSourceType.isAspect(EclipseSourceType.java:108) at org.aspectj.weaver.ReferenceType.isAspect(ReferenceType.java:159) at org.aspectj.ajdt.internal.compiler.lookup.AjLookupEnvironment.verifyAnyTypeParametersMeetBounds(AjLookupEnvironment.java:269) at org.aspectj.ajdt.internal.compiler.lookup.AjLookupEnvironment.completeTypeBindings(AjLookupEnvironment.java:228) at org.aspectj.org.eclipse.jdt.internal.compiler.Compiler.beginToCompile(Compiler.java:301) at org.aspectj.org.eclipse.jdt.internal.compiler.Compiler.compile(Compiler.java:315) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.performCompilation(AjBuildManager.java:887) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.doBuild(AjBuildManager.java:244) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.batchBuild(AjBuildManager.java:163) at org.aspectj.ajde.internal.CompilerAdapter.compile(CompilerAdapter.java:122) at org.aspectj.ajde.internal.AspectJBuildManager$CompilerThread.run(AspectJBuildManager.java:191) ArrayIndexOutOfBoundsException thrown: 5
resolved fixed
bc2f36f
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2006-10-17T08:08:12Z"
"2006-06-30T12:20:00Z"
tests/src/org/aspectj/systemtest/incremental/tools/MultiProjectIncrementalTests.java
/* ******************************************************************* * Copyright (c) 2005 Contributors. * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Eclipse Public License v1.0 * which accompanies this distribution and is available at * http://eclipse.org/legal/epl-v10.html * * Contributors: * Andy Clement initial implementation * ******************************************************************/ package org.aspectj.systemtest.incremental.tools; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Set; import org.aspectj.ajdt.internal.compiler.lookup.EclipseFactory; import org.aspectj.ajdt.internal.core.builder.AjState; import org.aspectj.ajdt.internal.core.builder.IncrementalStateManager; import org.aspectj.asm.AsmManager; import org.aspectj.asm.IElementHandleProvider; import org.aspectj.asm.IHierarchy; import org.aspectj.asm.IProgramElement; import org.aspectj.asm.IRelationship; import org.aspectj.asm.IRelationshipMap; import org.aspectj.asm.internal.JDTLikeHandleProvider; import org.aspectj.asm.internal.Relationship; import org.aspectj.bridge.IMessage; import org.aspectj.bridge.IMessageHandler; import org.aspectj.bridge.IMessageHolder; import org.aspectj.tools.ajc.Ajc; import org.aspectj.weaver.LintMessage; /** * The superclass knows all about talking through Ajde to the compiler. * The superclass isn't in charge of knowing how to simulate overlays * for incremental builds, that is in here. As is the ability to * generate valid build configs based on a directory structure. To * support this we just need access to a sandbox directory - this * sandbox is managed by the superclass (it only assumes all builds occur * in <sandboxDir>/<projectName>/ ) * * The idea is you can initialize multiple projects in the sandbox and * they can all be built independently, hopefully exploiting * incremental compilation. Between builds you can alter the contents * of a project using the alter() method that overlays some set of * new files onto the current set (adding new files/changing existing * ones) - you can then drive a new build and check it behaves as * expected. */ public class MultiProjectIncrementalTests extends AbstractMultiProjectIncrementalAjdeInteractionTestbed { /* A.aj package pack; public aspect A { pointcut p() : call(* C.method before() : p() { // line 7 } } C.java package pack; public class C { public void method1() { method2(); // line 6 } public void method2() { } public void method3() { method2(); // line 13 } }*/ public void testDontLoseAdviceMarkers_pr134471() { try { // see pr148027 AsmHierarchyBuilder.shouldAddUsesPointcut=false; configureBuildStructureModel(true); initialiseProject("P4"); build("P4"); Ajc.dumpAJDEStructureModel("after full build where advice is applying"); // should be 4 relationship entries // In inc1 the first advised line is 'commented out' alter("P4","inc1"); build("P4"); checkWasntFullBuild(); Ajc.dumpAJDEStructureModel("after inc build where first advised line is gone"); // should now be 2 relationship entries // This will be the line 6 entry in C.java IProgramElement codeElement = findCode(checkForNode("pack","C",true)); // This will be the line 7 entry in A.java IProgramElement advice = findAdvice(checkForNode("pack","A",true)); IRelationshipMap asmRelMap = AsmManager.getDefault().getRelationshipMap(); assertEquals("There should be two relationships in the relationship map", 2,asmRelMap.getEntries().size()); for (Iterator iter = asmRelMap.getEntries().iterator(); iter.hasNext();) { String sourceOfRelationship = (String) iter.next(); IProgramElement ipe = AsmManager.getDefault().getHierarchy() .findElementForHandle(sourceOfRelationship); assertNotNull("expected to find IProgramElement with handle " + sourceOfRelationship + " but didn't",ipe); if (ipe.getKind().equals(IProgramElement.Kind.ADVICE)) { assertEquals("expected source of relationship to be " + advice.toString() + " but found " + ipe.toString(),advice,ipe); } else if (ipe.getKind().equals(IProgramElement.Kind.CODE)) { assertEquals("expected source of relationship to be " + codeElement.toString() + " but found " + ipe.toString(),codeElement,ipe); } else { fail("found unexpected relationship source " + ipe + " with kind " + ipe.getKind()+" when looking up handle: "+sourceOfRelationship); } List relationships = asmRelMap.get(ipe); assertNotNull("expected " + ipe.getName() +" to have some " + "relationships",relationships); for (Iterator iterator = relationships.iterator(); iterator.hasNext();) { Relationship rel = (Relationship) iterator.next(); List targets = rel.getTargets(); for (Iterator iterator2 = targets.iterator(); iterator2.hasNext();) { String t = (String) iterator2.next(); IProgramElement link = AsmManager.getDefault().getHierarchy().findElementForHandle(t); if (ipe.getKind().equals(IProgramElement.Kind.ADVICE)) { assertEquals("expected target of relationship to be " + codeElement.toString() + " but found " + link.toString(),codeElement,link); } else if (ipe.getKind().equals(IProgramElement.Kind.CODE)) { assertEquals("expected target of relationship to be " + advice.toString() + " but found " + link.toString(),advice,link); } else { fail("found unexpected relationship source " + ipe.getName() + " with kind " + ipe.getKind()); } } } } } finally { // see pr148027 AsmHierarchyBuilder.shouldAddUsesPointcut=true; configureBuildStructureModel(false); } } // Compile a single simple project public void testTheBasics() { initialiseProject("P1"); build("P1"); // This first build will be batch build("P1"); checkWasntFullBuild(); checkCompileWeaveCount(0,0); } // source code doesnt matter, we are checking invalid path handling public void testInvalidAspectpath_pr121395() { initialiseProject("P1"); File f = new File("foo.jar"); Set s = new HashSet(); s.add(f); configureAspectPath(s); build("P1"); // This first build will be batch checkForError("invalid aspectpath entry"); } /** * Build a project containing a resource - then mark the resource readOnly(), then * do an inc-compile, it will report an error about write access to the resource * in the output folder being denied */ /*public void testProblemCopyingResources_pr138171() { initialiseProject("PR138171"); File f=getProjectRelativePath("PR138171","res.txt"); Map m = new HashMap(); m.put("res.txt",f); AjdeInteractionTestbed.MyProjectPropertiesAdapter.getInstance().setSourcePathResources(m); build("PR138171"); File f2 = getProjectOutputRelativePath("PR138171","res.txt"); boolean successful = f2.setReadOnly(); alter("PR138171","inc1"); AjdeInteractionTestbed.MyProjectPropertiesAdapter.getInstance().setSourcePathResources(m); build("PR138171"); List msgs = MyTaskListManager.getErrorMessages(); assertTrue("there should be one message but there are "+(msgs==null?0:msgs.size())+":\n"+msgs,msgs!=null && msgs.size()==1); IMessage msg = (IMessage)msgs.get(0); String exp = "unable to copy resource to output folder: 'res.txt'"; assertTrue("Expected message to include this text ["+exp+"] but it does not: "+msg,msg.toString().indexOf(exp)!=-1); }*/ // Make simple changes to a project, adding a class public void testSimpleChanges() { initialiseProject("P1"); build("P1"); // This first build will be batch alter("P1","inc1"); // adds a single class build("P1"); checkCompileWeaveCount(1,-1); build("P1"); checkCompileWeaveCount(0,-1); } // Make simple changes to a project, adding a class and an aspect public void testAddingAnAspect() { initialiseProject("P1"); build("P1"); // build 1, weave 1 alter("P1","inc1"); // adds a class alter("P1","inc2"); // adds an aspect build("P1"); // build 1, long timeTakenForFullBuildAndWeave = getTimeTakenForBuild(); checkWasFullBuild(); // it *will* be a full build under the new // "back-to-the-source strategy checkCompileWeaveCount(5,3); // we compile X and A (the delta) find out that // an aspect has changed, go back to the source // and compile X,A,C, then weave them all. build("P1"); long timeTakenForSimpleIncBuild = getTimeTakenForBuild(); // I don't think this test will have timing issues as the times should be *RADICALLY* different // On my config, first build time is 2093ms and the second is 30ms assertTrue("Should not take longer for the trivial incremental build! first="+timeTakenForFullBuildAndWeave+ "ms second="+timeTakenForSimpleIncBuild+"ms", timeTakenForSimpleIncBuild<timeTakenForFullBuildAndWeave); } public void testBuildingTwoProjectsInTurns() { configureBuildStructureModel(true); initialiseProject("P1"); initialiseProject("P2"); build("P1"); build("P2"); build("P1"); checkWasntFullBuild(); build("P2"); checkWasntFullBuild(); } /* public void testRefactoring_pr148285() { configureBuildStructureModel(true); initialiseProject("PR148285"); build("PR148285"); System.err.println("xxx"); alter("PR148285","inc1"); build("PR148285"); } */ /** * In order for this next test to run, I had to move the weaver/world pair we keep in the * AjBuildManager instance down into the state object - this makes perfect sense - otherwise * when reusing the state for another project we'd not be switching to the right weaver/world * for that project. */ public void testBuildingTwoProjectsMakingSmallChanges() { configureBuildStructureModel(true); initialiseProject("P1"); initialiseProject("P2"); build("P1"); build("P2"); build("P1"); checkWasntFullBuild(); build("P2"); checkWasntFullBuild(); alter("P1","inc1"); // adds a class alter("P1","inc2"); // adds an aspect build("P1"); checkWasFullBuild(); // adding an aspect makes us go back to the source } public void testPr134371() { initialiseProject("PR134371"); build("PR134371"); alter("PR134371","inc1"); build("PR134371"); assertTrue("There should be no exceptions handled:\n"+MyErrorHandler.getErrorMessages(), MyErrorHandler.getErrorMessages().isEmpty()); } /** * Setup up two simple projects and build them in turn - check the * structure model is right after each build */ public void testBuildingTwoProjectsAndVerifyingModel() { configureBuildStructureModel(true); initialiseProject("P1"); initialiseProject("P2"); build("P1"); checkForNode("pkg","C",true); build("P2"); checkForNode("pkg","C",false); build("P1"); checkForNode("pkg","C",true); build("P2"); checkForNode("pkg","C",false); } // Setup up two simple projects and build them in turn - check the // structure model is right after each build public void testBuildingTwoProjectsAndVerifyingStuff() { configureBuildStructureModel(true); initialiseProject("P1"); initialiseProject("P2"); build("P1"); checkForNode("pkg","C",true); build("P2"); checkForNode("pkg","C",false); build("P1"); checkForNode("pkg","C",true); build("P2"); checkForNode("pkg","C",false); } /** * Complex. Here we are testing that a state object records structural changes since * the last full build correctly. We build a simple project from scratch - this will * be a full build and so the structural changes since last build count should be 0. * We then alter a class, adding a new method and check structural changes is 1. */ public void testStateManagement1() { File binDirectoryForP1 = new File(getFile("P1","bin")); initialiseProject("P1"); build("P1"); // full build AjState ajs = IncrementalStateManager.findStateManagingOutputLocation(binDirectoryForP1); assertTrue("There should be a state object for project P1",ajs!=null); assertTrue("Should be no structural changes as it was a full build but found: "+ ajs.getNumberOfStructuralChangesSinceLastFullBuild(), ajs.getNumberOfStructuralChangesSinceLastFullBuild()==0); alter("P1","inc3"); // adds a method to the class C.java build("P1"); checkWasntFullBuild(); ajs = IncrementalStateManager.findStateManagingOutputLocation(new File(getFile("P1","bin"))); assertTrue("There should be state for project P1",ajs!=null); checkWasntFullBuild(); assertTrue("Should be one structural changes as it was a full build but found: "+ ajs.getNumberOfStructuralChangesSinceLastFullBuild(), ajs.getNumberOfStructuralChangesSinceLastFullBuild()==1); } /** * Complex. Here we are testing that a state object records structural changes since * the last full build correctly. We build a simple project from scratch - this will * be a full build and so the structural changes since last build count should be 0. * We then alter a class, changing body of a method, not the structure and * check struc changes is still 0. */ public void testStateManagement2() { File binDirectoryForP1 = new File(getFile("P1","bin")); initialiseProject("P1"); alter("P1","inc3"); // need this change in here so 'inc4' can be applied without making // it a structural change build("P1"); // full build AjState ajs = IncrementalStateManager.findStateManagingOutputLocation(binDirectoryForP1); assertTrue("There should be state for project P1",ajs!=null); assertTrue("Should be no struc changes as its a full build: "+ ajs.getNumberOfStructuralChangesSinceLastFullBuild(), ajs.getNumberOfStructuralChangesSinceLastFullBuild()==0); alter("P1","inc4"); // changes body of main() method but does *not* change the structure of C.java build("P1"); checkWasntFullBuild(); ajs = IncrementalStateManager.findStateManagingOutputLocation(new File(getFile("P1","bin"))); assertTrue("There should be state for project P1",ajs!=null); checkWasntFullBuild(); assertTrue("Shouldn't be any structural changes but there were "+ ajs.getNumberOfStructuralChangesSinceLastFullBuild(), ajs.getNumberOfStructuralChangesSinceLastFullBuild()==0); } /** * The C.java file modified in this test has an inner class - this means the inner class * has a this$0 field and <init>(C) ctor to watch out for when checking for structural changes * */ public void testStateManagement3() { File binDirForInterproject1 = new File(getFile("interprojectdeps1","bin")); initialiseProject("interprojectdeps1"); build("interprojectdeps1"); // full build AjState ajs = IncrementalStateManager.findStateManagingOutputLocation(binDirForInterproject1); assertTrue("There should be state for project P1",ajs!=null); assertTrue("Should be no struc changes as its a full build: "+ ajs.getNumberOfStructuralChangesSinceLastFullBuild(), ajs.getNumberOfStructuralChangesSinceLastFullBuild()==0); alter("interprojectdeps1","inc1"); // adds a space to C.java build("interprojectdeps1"); checkWasntFullBuild(); ajs = IncrementalStateManager.findStateManagingOutputLocation(new File(getFile("interprojectdeps1","bin"))); assertTrue("There should be state for project interprojectdeps1",ajs!=null); checkWasntFullBuild(); assertTrue("Shouldn't be any structural changes but there were "+ ajs.getNumberOfStructuralChangesSinceLastFullBuild(), ajs.getNumberOfStructuralChangesSinceLastFullBuild()==0); } /** * The C.java file modified in this test has an inner class - which has two ctors - this checks * how they are mangled with an instance of C. * */ public void testStateManagement4() { File binDirForInterproject2 = new File(getFile("interprojectdeps2","bin")); initialiseProject("interprojectdeps2"); build("interprojectdeps2"); // full build AjState ajs = IncrementalStateManager.findStateManagingOutputLocation(binDirForInterproject2); assertTrue("There should be state for project interprojectdeps2",ajs!=null); assertTrue("Should be no struc changes as its a full build: "+ ajs.getNumberOfStructuralChangesSinceLastFullBuild(), ajs.getNumberOfStructuralChangesSinceLastFullBuild()==0); alter("interprojectdeps2","inc1"); // minor change to C.java build("interprojectdeps2"); checkWasntFullBuild(); ajs = IncrementalStateManager.findStateManagingOutputLocation(new File(getFile("interprojectdeps2","bin"))); assertTrue("There should be state for project interprojectdeps1",ajs!=null); checkWasntFullBuild(); assertTrue("Shouldn't be any structural changes but there were "+ ajs.getNumberOfStructuralChangesSinceLastFullBuild(), ajs.getNumberOfStructuralChangesSinceLastFullBuild()==0); } /** * The C.java file modified in this test has an inner class - it has two ctors but * also a reference to C.this in it - which will give rise to an accessor being * created in C * */ public void testStateManagement5() { File binDirForInterproject3 = new File(getFile("interprojectdeps3","bin")); initialiseProject("interprojectdeps3"); build("interprojectdeps3"); // full build AjState ajs = IncrementalStateManager.findStateManagingOutputLocation(binDirForInterproject3); assertTrue("There should be state for project interprojectdeps3",ajs!=null); assertTrue("Should be no struc changes as its a full build: "+ ajs.getNumberOfStructuralChangesSinceLastFullBuild(), ajs.getNumberOfStructuralChangesSinceLastFullBuild()==0); alter("interprojectdeps3","inc1"); // minor change to C.java build("interprojectdeps3"); checkWasntFullBuild(); ajs = IncrementalStateManager.findStateManagingOutputLocation(new File(getFile("interprojectdeps3","bin"))); assertTrue("There should be state for project interprojectdeps1",ajs!=null); checkWasntFullBuild(); assertTrue("Shouldn't be any structural changes but there were "+ ajs.getNumberOfStructuralChangesSinceLastFullBuild(), ajs.getNumberOfStructuralChangesSinceLastFullBuild()==0); } /** * Now the most complex test. Create a dependancy between two projects. Building * one may affect whether the other does an incremental or full build. The * structural information recorded in the state object should be getting used * to control whether a full build is necessary... */ public void testBuildingDependantProjects() { initialiseProject("P1"); initialiseProject("P2"); configureNewProjectDependency("P2","P1"); build("P1"); build("P2"); // now everything is consistent and compiled alter("P1","inc1"); // adds a second class build("P1"); build("P2"); // although a second class was added - P2 can't be using it, so we don't full build here :) checkWasntFullBuild(); alter("P1","inc3"); // structurally changes one of the classes build("P1"); build("P2"); // build notices the structural change checkWasFullBuild(); alter("P1","inc4"); build("P1"); build("P2"); // build sees a change but works out its not structural checkWasntFullBuild(); } public void testPr85132() { initialiseProject("PR85132"); build("PR85132"); alter("PR85132","inc1"); build("PR85132"); } // parameterization of generic aspects public void testPr125405() { initialiseProject("PR125405"); build("PR125405"); checkCompileWeaveCount(1,1); alter("PR125405","inc1"); build("PR125405"); // "only abstract aspects can have type parameters" checkForError("only abstract aspects can have type parameters"); alter("PR125405","inc2"); build("PR125405"); checkCompileWeaveCount(1,1); assertTrue("Should be no errors, but got "+MyTaskListManager.getErrorMessages(),MyTaskListManager.getErrorMessages().size()==0); } public void testPr128618() { initialiseProject("PR128618_1"); initialiseProject("PR128618_2"); configureNewProjectDependency("PR128618_2","PR128618_1"); assertTrue("there should be no warning messages before we start", MyTaskListManager.getWarningMessages().isEmpty()); build("PR128618_1"); build("PR128618_2"); List warnings = MyTaskListManager.getWarningMessages(); assertTrue("Should be one warning, but there are #"+warnings.size(),warnings.size()==1); IMessage msg = (IMessage)(MyTaskListManager.getWarningMessages().get(0)); assertEquals("warning should be against the FFDC.aj resource","FFDC.aj",msg.getSourceLocation().getSourceFile().getName()); alter("PR128618_2","inc1"); build("PR128618_2"); checkWasntFullBuild(); IMessage msg2 = (IMessage)(MyTaskListManager.getWarningMessages().get(0)); assertEquals("warning should be against the FFDC.aj resource","FFDC.aj",msg2.getSourceLocation().getSourceFile().getName()); assertFalse("a new warning message should have been generated", msg.equals(msg2)); } public void testPr92837() { initialiseProject("PR92837"); build("PR92837"); alter("PR92837","inc1"); build("PR92837"); } public void testPr119570() { initialiseProject("PR119570"); build("PR119570"); assertTrue("Should be no errors, but got "+MyTaskListManager.getErrorMessages(),MyTaskListManager.getErrorMessages().size()==0); } public void testPr119570_2() { initialiseProject("PR119570_2"); build("PR119570_2"); List l = MyTaskListManager.getWarningMessages(); assertTrue("Should be no warnings, but got "+l,l.size()==0); } // If you fiddle with the compiler options - you must manually reset the options at the end of the test public void testPr117209() { try { initialiseProject("pr117209"); configureNonStandardCompileOptions("-proceedOnError"); build("pr117209"); checkCompileWeaveCount(6,6); } finally { MyBuildOptionsAdapter.reset(); } } public void testPr114875() { initialiseProject("pr114875"); build("pr114875"); alter("pr114875","inc1"); build("pr114875"); checkWasFullBuild(); alter("pr114875","inc2"); build("pr114875"); checkWasFullBuild(); // back to the source for an aspect change } public void testPr117882() { // AjdeInteractionTestbed.VERBOSE=true; // AjdeInteractionTestbed.configureBuildStructureModel(true); initialiseProject("PR117882"); build("PR117882"); checkWasFullBuild(); alter("PR117882","inc1"); build("PR117882"); checkWasFullBuild(); // back to the source for an aspect // AjdeInteractionTestbed.VERBOSE=false; // AjdeInteractionTestbed.configureBuildStructureModel(false); } public void testPr117882_2() { // AjdeInteractionTestbed.VERBOSE=true; // AjdeInteractionTestbed.configureBuildStructureModel(true); initialiseProject("PR117882_2"); build("PR117882_2"); checkWasFullBuild(); alter("PR117882_2","inc1"); build("PR117882_2"); checkWasFullBuild(); // back to the source... //checkCompileWeaveCount(1,4); //fullBuild("PR117882_2"); //checkWasFullBuild(); // AjdeInteractionTestbed.VERBOSE=false; // AjdeInteractionTestbed.configureBuildStructureModel(false); } public void testPr115251() { //AjdeInteractionTestbed.VERBOSE=true; initialiseProject("PR115251"); build("PR115251"); checkWasFullBuild(); alter("PR115251","inc1"); build("PR115251"); checkWasFullBuild(); // back to the source } public void testPr157054() { configureBuildStructureModel(true); MyBuildOptionsAdapter.setNonStandardOptions("-showWeaveInfo"); initialiseProject("PR157054"); build("PR157054"); checkWasFullBuild(); List weaveMessages = MyTaskListManager.getWeavingMessages(); assertTrue("Should be two weaving messages but there are "+weaveMessages.size(),weaveMessages.size()==2); alter("PR157054","inc1"); build("PR157054"); weaveMessages = MyTaskListManager.getWeavingMessages(); assertTrue("Should be three weaving messages but there are "+weaveMessages.size(),weaveMessages.size()==3); checkWasntFullBuild(); fullBuild("PR157054"); weaveMessages = MyTaskListManager.getWeavingMessages(); assertTrue("Should be three weaving messages but there are "+weaveMessages.size(),weaveMessages.size()==3); } /** * Checks we aren't leaking mungers across compiles (accumulating multiple instances of the same one that * all do the same thing). On the first compile the munger is added late on - so at the time we set * the count it is still zero. On the subsequent compiles we know about this extra one. */ public void testPr141956_IncrementallyCompilingAtAj() { initialiseProject("PR141956"); build("PR141956"); assertTrue("Should be zero but reports "+EclipseFactory.debug_mungerCount,EclipseFactory.debug_mungerCount==0); alter("PR141956","inc1"); build("PR141956"); assertTrue("Should be two but reports "+EclipseFactory.debug_mungerCount,EclipseFactory.debug_mungerCount==2); alter("PR141956","inc1"); build("PR141956"); assertTrue("Should be two but reports "+EclipseFactory.debug_mungerCount,EclipseFactory.debug_mungerCount==2); alter("PR141956","inc1"); build("PR141956"); assertTrue("Should be two but reports "+EclipseFactory.debug_mungerCount,EclipseFactory.debug_mungerCount==2); alter("PR141956","inc1"); build("PR141956"); assertTrue("Should be two but reports "+EclipseFactory.debug_mungerCount,EclipseFactory.debug_mungerCount==2); } // public void testPr124399() { // AjdeInteractionTestbed.VERBOSE=true; // configureBuildStructureModel(true); // initialiseProject("PR124399"); // build("PR124399"); // checkWasFullBuild(); // alter("PR124399","inc1"); // build("PR124399"); // checkWasntFullBuild(); // } public void testPr121384() { // AjdeInteractionTestbed.VERBOSE=true; // AsmManager.setReporting("c:/foo.txt",true,true,true,false); MyBuildOptionsAdapter.setNonStandardOptions("-showWeaveInfo"); configureBuildStructureModel(true); initialiseProject("pr121384"); build("pr121384"); checkWasFullBuild(); alter("pr121384","inc1"); build("pr121384"); checkWasntFullBuild(); } /* public void testPr111779() { super.VERBOSE=true; initialiseProject("PR111779"); build("PR111779"); alter("PR111779","inc1"); build("PR111779"); } */ public void testPr93310_1() { initialiseProject("PR93310_1"); build("PR93310_1"); checkWasFullBuild(); String fileC2 = getWorkingDir().getAbsolutePath() + File.separatorChar + "PR93310_1" + File.separatorChar + "src" + File.separatorChar + "pack" + File.separatorChar + "C2.java"; (new File(fileC2)).delete(); alter("PR93310_1","inc1"); build("PR93310_1"); checkWasFullBuild(); int l = AjdeInteractionTestbed.MyStateListener.detectedDeletions.size(); assertTrue("Expected one deleted file to be noticed, but detected: "+l,l==1); String name = (String)AjdeInteractionTestbed.MyStateListener.detectedDeletions.get(0); assertTrue("Should end with C2.java but is "+name,name.endsWith("C2.java")); } public void testPr93310_2() { initialiseProject("PR93310_2"); build("PR93310_2"); checkWasFullBuild(); String fileC2 = getWorkingDir().getAbsolutePath() + File.separatorChar + "PR93310_2" + File.separatorChar + "src" + File.separatorChar + "pack" + File.separatorChar + "C2.java"; (new File(fileC2)).delete(); alter("PR93310_2","inc1"); build("PR93310_2"); checkWasFullBuild(); int l = AjdeInteractionTestbed.MyStateListener.detectedDeletions.size(); assertTrue("Expected one deleted file to be noticed, but detected: "+l,l==1); String name = (String)AjdeInteractionTestbed.MyStateListener.detectedDeletions.get(0); assertTrue("Should end with C2.java but is "+name,name.endsWith("C2.java")); } // Stage1: Compile two files, pack.A and pack.A1 - A1 sets a protected field in A. // Stage2: make the field private in class A > gives compile error // Stage3: Add a new aspect whilst there is a compile error ! public void testPr113531() { initialiseProject("PR113531"); build("PR113531"); assertFalse("build should have compiled ok", MyTaskListManager.hasErrorMessages()); alter("PR113531","inc1"); build("PR113531"); assertEquals("error message should be 'foo cannot be resolved' ", "foo cannot be resolved", ((IMessage)MyTaskListManager.getErrorMessages().get(0)) .getMessage()); alter("PR113531","inc2"); build("PR113531"); assertTrue("There should be no exceptions handled:\n"+MyErrorHandler.getErrorMessages(), MyErrorHandler.getErrorMessages().isEmpty()); assertEquals("error message should be 'foo cannot be resolved' ", "foo cannot be resolved", ((IMessage)MyTaskListManager.getErrorMessages().get(0)) .getMessage()); } // Stage 1: Compile the 4 files, pack.A2 extends pack.A1 (aspects) where // A2 uses a protected field in A1 and pack.C2 extends pack.C1 (classes) // where C2 uses a protected field in C1 // Stage 2: make the field private in class C1 ==> compile errors in C2 // Stage 3: make the field private in aspect A1 whilst there's the compile // error. // There shouldn't be a BCExcpetion saying can't find delegate for pack.C2 public void testPr119882() { initialiseProject("PR119882"); build("PR119882"); assertFalse("build should have compiled ok",MyTaskListManager.hasErrorMessages()); alter("PR119882","inc1"); build("PR119882"); //fullBuild("PR119882"); List errors = MyTaskListManager.getErrorMessages(); assertTrue("Should be at least one error, but got none",errors.size()==1); assertEquals("error message should be 'i cannot be resolved' ", "i cannot be resolved", ((IMessage)errors.get(0)) .getMessage()); alter("PR119882","inc2"); build("PR119882"); assertTrue("There should be no exceptions handled:\n"+MyErrorHandler.getErrorMessages(), MyErrorHandler.getErrorMessages().isEmpty()); assertEquals("error message should be 'i cannot be resolved' ", "i cannot be resolved", ((IMessage)errors.get(0)) .getMessage()); } public void testPr112736() { initialiseProject("PR112736"); build("PR112736"); checkWasFullBuild(); String fileC2 = getWorkingDir().getAbsolutePath() + File.separatorChar + "PR112736" + File.separatorChar + "src" + File.separatorChar + "pack" + File.separatorChar + "A.java"; (new File(fileC2)).delete(); alter("PR112736","inc1"); build("PR112736"); checkWasFullBuild(); } /** * We have problems with multiple rewrites of a pointcut across incremental builds. */ public void testPr113257() { initialiseProject("PR113257"); build("PR113257"); alter("PR113257","inc1"); build("PR113257"); checkWasFullBuild(); // back to the source alter("PR113257","inc1"); build("PR113257"); } public void testPr123612() { initialiseProject("PR123612"); build("PR123612"); alter("PR123612","inc1"); build("PR123612"); checkWasFullBuild(); // back to the source } //Bugzilla Bug 152257 - Incremental compiler doesn't handle exception declaration correctly public void testPr152257() { configureNonStandardCompileOptions("-XnoInline"); initialiseProject("PR152257"); build("PR152257"); List errors = MyTaskListManager.getErrorMessages(); assertTrue("Should be no warnings, but there are #"+errors.size(),errors.size()==0); checkWasFullBuild(); alter("PR152257","inc1"); build("PR152257"); errors = MyTaskListManager.getErrorMessages(); assertTrue("Should be no warnings, but there are #"+errors.size(),errors.size()==0); checkWasntFullBuild(); } public void testPr128655() { configureNonStandardCompileOptions("-showWeaveInfo"); initialiseProject("pr128655"); build("pr128655"); List firstBuildMessages = MyTaskListManager.getWeavingMessages(); assertTrue("Should be at least one message about the dec @type, but there were none",firstBuildMessages.size()>0); alter("pr128655","inc1"); build("pr128655"); checkWasntFullBuild(); // back to the source List secondBuildMessages = MyTaskListManager.getWeavingMessages(); // check they are the same for (int i = 0; i < firstBuildMessages.size(); i++) { IMessage m1 = (IMessage)firstBuildMessages.get(i); IMessage m2 = (IMessage)secondBuildMessages.get(i); if (!m1.toString().equals(m2.toString())) { System.err.println("Message during first build was: "+m1); System.err.println("Message during second build was: "+m1); fail("The two messages should be the same, but are not: \n"+m1+"!="+m2); } } } // Similar to above, but now the annotation is in the default package public void testPr128655_2() { configureNonStandardCompileOptions("-showWeaveInfo"); initialiseProject("pr128655_2"); build("pr128655_2"); List firstBuildMessages = MyTaskListManager.getWeavingMessages(); assertTrue("Should be at least one message about the dec @type, but there were none",firstBuildMessages.size()>0); alter("pr128655_2","inc1"); build("pr128655_2"); checkWasntFullBuild(); // back to the source List secondBuildMessages = MyTaskListManager.getWeavingMessages(); // check they are the same for (int i = 0; i < firstBuildMessages.size(); i++) { IMessage m1 = (IMessage)firstBuildMessages.get(i); IMessage m2 = (IMessage)secondBuildMessages.get(i); if (!m1.toString().equals(m2.toString())) { System.err.println("Message during first build was: "+m1); System.err.println("Message during second build was: "+m1); fail("The two messages should be the same, but are not: \n"+m1+"!="+m2); } } } // test for comment #31 - NPE public void testPr129163() { configureBuildStructureModel(true); initialiseProject("PR129613"); build("PR129613"); alter("PR129613","inc1"); build("PR129613"); assertTrue("There should be no exceptions handled:\n"+MyErrorHandler.getErrorMessages(), MyErrorHandler.getErrorMessages().isEmpty()); assertEquals("warning message should be 'no match for this type name: File [Xlint:invalidAbsoluteTypeName]' ", "no match for this type name: File [Xlint:invalidAbsoluteTypeName]", ((IMessage)MyTaskListManager.getWarningMessages().get(0)) .getMessage()); configureBuildStructureModel(false); } // test for comment #0 - adding a comment to a class file shouldn't // cause us to go back to source and recompile everything. To force this // to behave like AJDT we need to include the aspect in 'inc1' so that // when AjState looks at its timestamp it thinks the aspect has been modified. // The logic within CrosscuttingMembers should then work out correctly // that there haven't really been any changes within the aspect and so // we shouldn't go back to source. public void testPr129163_2() { // want to behave like AJDT configureBuildStructureModel(true); initialiseProject("pr129163_2"); build("pr129163_2"); checkWasFullBuild(); alter("pr129163_2","inc1"); build("pr129163_2"); checkWasntFullBuild(); // shouldn't be a full build because the // aspect hasn't changed configureBuildStructureModel(false); } // test for comment #6 - simulates AJDT core builder test testBug99133a - // changing the contents of a method within a class shouldn't force a // full build of a dependant project. To force this to behave like AJDT // 'inc1' of the dependant project should just be a copy of 'base' so that // AjState thinks somethings changed within the dependant project and // we do a build. Similarly, 'inc1' of the project depended on should // include the aspect even though nothing's changed within it. This causes // AjState to think that the aspect has changed. Together its then up to // logic within CrosscuttingMembers and various equals methods to decide // correctly that we don't have to go back to source. public void testPr129163_3() { configureBuildStructureModel(true); initialiseProject("PR129163_4"); build("PR129163_4"); checkWasFullBuild(); // should be a full build because initializing project initialiseProject("PR129163_3"); configureNewProjectDependency("PR129163_3","PR129163_4"); build("PR129163_3"); checkWasFullBuild(); // should be a full build because initializing project alter("PR129163_4","inc1"); build("PR129163_4"); checkWasntFullBuild(); // should be an incremental build because although // "inc1" includes the aspect A1.aj, it actually hasn't // changed so we shouldn't go back to source alter("PR129163_3","inc1"); build("PR129163_3"); checkWasntFullBuild(); // should be an incremental build because nothing has // changed within the class and no aspects have changed // within the running of the test configureBuildStructureModel(false); } public void testPr133117() { // System.gc(); // System.exit(); configureNonStandardCompileOptions("-Xlint:warning"); initialiseProject("PR133117"); build("PR133117"); assertTrue("There should only be one xlint warning message reported:\n" +MyTaskListManager.getWarningMessages(), MyTaskListManager.getWarningMessages().size()==1); alter("PR133117","inc1"); build("PR133117"); List warnings = MyTaskListManager.getWarningMessages(); List noGuardWarnings = new ArrayList(); for (Iterator iter = warnings.iterator(); iter.hasNext();) { IMessage element = (IMessage) iter.next(); if (element.getMessage().indexOf("Xlint:noGuardForLazyTjp") != -1) { noGuardWarnings.add(element); } } assertTrue("There should only be two Xlint:noGuardForLazyTjp warning message reported:\n" +noGuardWarnings,noGuardWarnings.size() == 2); } public void testPr131505() { configureNonStandardCompileOptions("-outxml"); initialiseProject("PR131505"); build("PR131505"); checkWasFullBuild(); // aop.xml file shouldn't contain any aspects checkXMLAspectCount("PR131505","",0); // add a new aspect A which should be included in the aop.xml file alter("PR131505","inc1"); build("PR131505"); checkWasFullBuild(); checkXMLAspectCount("PR131505","",1); checkXMLAspectCount("PR131505","A",1); // make changes to the class file which shouldn't affect the contents // of the aop.xml file alter("PR131505","inc2"); build("PR131505"); checkWasntFullBuild(); checkXMLAspectCount("PR131505","",1); checkXMLAspectCount("PR131505","A",1); // add another new aspect A1 which should also be included in the aop.xml file // ...there should be no duplicate entries in the file alter("PR131505","inc3"); build("PR131505"); checkWasFullBuild(); checkXMLAspectCount("PR131505","",2); checkXMLAspectCount("PR131505","A1",1); checkXMLAspectCount("PR131505","A",1); // delete aspect A1 which meanss that aop.xml file should only contain A File a1 = new File(getWorkingDir().getAbsolutePath() + File.separatorChar + "PR131505" + File.separatorChar + "A1.aj"); a1.delete(); build("PR131505"); checkWasFullBuild(); checkXMLAspectCount("PR131505","",1); checkXMLAspectCount("PR131505","A1",0); checkXMLAspectCount("PR131505","A",1); // add another aspect called A which is in a different package, both A // and pkg.A should be included in the aop.xml file alter("PR131505","inc4"); build("PR131505"); checkWasFullBuild(); checkXMLAspectCount("PR131505","",2); checkXMLAspectCount("PR131505","A",1); checkXMLAspectCount("PR131505","pkg.A",1); } public void testPr136585() { initialiseProject("PR136585"); build("PR136585"); alter("PR136585","inc1"); build("PR136585"); assertTrue("There should be no errors reported:\n"+MyTaskListManager.getErrorMessages(), MyTaskListManager.getErrorMessages().isEmpty()); } public void testPr133532() { initialiseProject("PR133532"); build("PR133532"); alter("PR133532","inc1"); build("PR133532"); alter("PR133532","inc2"); build("PR133532"); assertTrue("There should be no errors reported:\n"+MyTaskListManager.getErrorMessages(), MyTaskListManager.getErrorMessages().isEmpty()); } public void testPr133532_2() { initialiseProject("pr133532_2"); build("pr133532_2"); alter("pr133532_2","inc2"); build("pr133532_2"); assertTrue("There should be no errors reported:\n"+MyTaskListManager.getErrorMessages(), MyTaskListManager.getErrorMessages().isEmpty()); String decisions = AjdeInteractionTestbed.MyStateListener.getDecisions(); String expect="Need to recompile 'A.aj'"; assertTrue("Couldn't find build decision: '"+expect+"' in the list of decisions made:\n"+decisions, decisions.indexOf(expect)!=-1); } public void testPr133532_3() { initialiseProject("PR133532_3"); build("PR133532_3"); alter("PR133532_3","inc1"); build("PR133532_3"); assertTrue("There should be no errors reported:\n"+MyTaskListManager.getErrorMessages(), MyTaskListManager.getErrorMessages().isEmpty()); } public void testPr134541() { initialiseProject("PR134541"); build("PR134541"); assertEquals("[Xlint:adviceDidNotMatch] should be associated with line 5",5, ((IMessage)MyTaskListManager.getWarningMessages().get(0)).getSourceLocation().getLine()); alter("PR134541","inc1"); build("PR134541"); if (AsmManager.getDefault().getHandleProvider().dependsOnLocation()) checkWasFullBuild(); // the line number has changed... but nothing structural about the code else checkWasntFullBuild(); // the line number has changed... but nothing structural about the code assertEquals("[Xlint:adviceDidNotMatch] should now be associated with line 7",7, ((IMessage)MyTaskListManager.getWarningMessages().get(0)).getSourceLocation().getLine()); } public void testJDTLikeHandleProviderWithLstFile_pr141730() { IElementHandleProvider handleProvider = AsmManager.getDefault().getHandleProvider(); AsmManager.getDefault().setHandleProvider(new JDTLikeHandleProvider()); configureBuildStructureModel(true); try { // The JDTLike-handles should start with the name // of the buildconfig file initialiseProject("JDTLikeHandleProvider"); build("JDTLikeHandleProvider"); IHierarchy top = AsmManager.getDefault().getHierarchy(); IProgramElement pe = top.findElementForType("pkg","A"); String expectedHandle = "build<pkg*A.aj}A"; assertEquals("expected handle to be " + expectedHandle + ", but found " + pe.getHandleIdentifier(),expectedHandle,pe.getHandleIdentifier()); } finally { AsmManager.getDefault().setHandleProvider(handleProvider); configureBuildStructureModel(false); } } public void testMovingAdviceDoesntChangeHandles_pr141730() { IElementHandleProvider handleProvider = AsmManager.getDefault().getHandleProvider(); AsmManager.getDefault().setHandleProvider(new JDTLikeHandleProvider()); configureBuildStructureModel(true); try { initialiseProject("JDTLikeHandleProvider"); build("JDTLikeHandleProvider"); checkWasFullBuild(); IHierarchy top = AsmManager.getDefault().getHierarchy(); IProgramElement pe = top.findElementForLabel(top.getRoot(), IProgramElement.Kind.ADVICE,"before(): <anonymous pointcut>"); // add a line which shouldn't change the handle alter("JDTLikeHandleProvider","inc1"); build("JDTLikeHandleProvider"); checkWasntFullBuild(); IHierarchy top2 = AsmManager.getDefault().getHierarchy(); IProgramElement pe2 = top.findElementForLabel(top2.getRoot(), IProgramElement.Kind.ADVICE,"before(): <anonymous pointcut>"); assertEquals("expected advice to be on line " + pe.getSourceLocation().getLine() + 1 + " but was on " + pe2.getSourceLocation().getLine(), pe.getSourceLocation().getLine()+1,pe2.getSourceLocation().getLine()); assertEquals("expected advice to have handle " + pe.getHandleIdentifier() + " but found handle " + pe2.getHandleIdentifier(), pe.getHandleIdentifier(),pe2.getHandleIdentifier()); } finally { AsmManager.getDefault().setHandleProvider(handleProvider); configureBuildStructureModel(false); } } public void testSwappingAdviceAndHandles_pr141730() { IElementHandleProvider handleProvider = AsmManager.getDefault().getHandleProvider(); AsmManager.getDefault().setHandleProvider(new JDTLikeHandleProvider()); configureBuildStructureModel(true); try { initialiseProject("JDTLikeHandleProvider"); build("JDTLikeHandleProvider"); IHierarchy top = AsmManager.getDefault().getHierarchy(); IProgramElement call = top.findElementForLabel(top.getRoot(), IProgramElement.Kind.ADVICE, "after(): callPCD.."); IProgramElement exec = top.findElementForLabel(top.getRoot(), IProgramElement.Kind.ADVICE, "after(): execPCD.."); // swap the two after advice statements over. This forces // a full build which means 'after(): callPCD..' will now // be the second after advice in the file and have the same // handle as 'after(): execPCD..' originally did. alter("JDTLikeHandleProvider","inc2"); build("JDTLikeHandleProvider"); checkWasFullBuild(); IHierarchy top2 = AsmManager.getDefault().getHierarchy(); IProgramElement newCall = top2.findElementForLabel(top2.getRoot(), IProgramElement.Kind.ADVICE, "after(): callPCD.."); IProgramElement newExec = top2.findElementForLabel(top2.getRoot(), IProgramElement.Kind.ADVICE, "after(): execPCD.."); assertEquals("after swapping places, expected 'after(): callPCD..' " + "to be on line " + newExec.getSourceLocation().getLine() + " but was on line " + call.getSourceLocation().getLine(), newExec.getSourceLocation().getLine(), call.getSourceLocation().getLine()); assertEquals("after swapping places, expected 'after(): callPCD..' " + "to have handle " + exec.getHandleIdentifier() + " (because was full build) but had " + newCall.getHandleIdentifier(), exec.getHandleIdentifier(), newCall.getHandleIdentifier()); } finally { AsmManager.getDefault().setHandleProvider(handleProvider); configureBuildStructureModel(false); } } public void testInitializerCountForJDTLikeHandleProvider_pr141730() { IElementHandleProvider handleProvider = AsmManager.getDefault().getHandleProvider(); AsmManager.getDefault().setHandleProvider(new JDTLikeHandleProvider()); configureBuildStructureModel(true); try { initialiseProject("JDTLikeHandleProvider"); build("JDTLikeHandleProvider"); String expected = "build<pkg*A.aj[C|1"; IHierarchy top = AsmManager.getDefault().getHierarchy(); IProgramElement init = top.findElementForLabel(top.getRoot(), IProgramElement.Kind.INITIALIZER, "..."); assertEquals("expected initializers handle to be " + expected + "," + " but found " + init.getHandleIdentifier(true), expected,init.getHandleIdentifier(true)); alter("JDTLikeHandleProvider","inc2"); build("JDTLikeHandleProvider"); checkWasFullBuild(); IHierarchy top2 = AsmManager.getDefault().getHierarchy(); IProgramElement init2 = top2.findElementForLabel(top2.getRoot(), IProgramElement.Kind.INITIALIZER, "..."); assertEquals("expected initializers handle to still be " + expected + "," + " but found " + init2.getHandleIdentifier(true), expected,init2.getHandleIdentifier(true)); } finally { AsmManager.getDefault().setHandleProvider(handleProvider); configureBuildStructureModel(false); } } // 134471 related tests perform incremental compilation and verify features of the structure model post compile public void testPr134471_IncrementalCompilationAndModelUpdates() { try { // see pr148027 AsmHierarchyBuilder.shouldAddUsesPointcut=false; configureBuildStructureModel(true); configureNonStandardCompileOptions("-showWeaveInfo -emacssym"); // Step1. Build the code, simple advice from aspect A onto class C initialiseProject("PR134471"); build("PR134471"); // Step2. Quick check that the advice points to something... IProgramElement nodeForTypeA = checkForNode("pkg","A",true); IProgramElement nodeForAdvice = findAdvice(nodeForTypeA); List relatedElements = getRelatedElements(nodeForAdvice,1); // Step3. Check the advice applying at the first 'code' join point in pkg.C is from aspect pkg.A, line 7 IProgramElement programElement = getFirstRelatedElement(findCode(checkForNode("pkg","C",true))); int line = programElement.getSourceLocation().getLine(); assertTrue("advice should be at line 7 - but is at line "+line,line==7); // Step4. Simulate the aspect being saved but with no change at all in it alter("PR134471","inc1"); build("PR134471"); // Step5. Quick check that the advice points to something... nodeForTypeA = checkForNode("pkg","A",true); nodeForAdvice = findAdvice(nodeForTypeA); relatedElements = getRelatedElements(nodeForAdvice,1); // Step6. Check the advice applying at the first 'code' join point in pkg.C is from aspect pkg.A, line 7 programElement = getFirstRelatedElement(findCode(checkForNode("pkg","C",true))); line = programElement.getSourceLocation().getLine(); assertTrue("advice should be at line 7 - but is at line "+line,line==7); } finally { // see pr148027 AsmHierarchyBuilder.shouldAddUsesPointcut=true; } } // now the advice moves down a few lines - hopefully the model will notice... see discussion in 134471 public void testPr134471_MovingAdvice() { configureBuildStructureModel(true); configureNonStandardCompileOptions("-showWeaveInfo -emacssym"); // Step1. build the project initialiseProject("PR134471_2"); build("PR134471_2"); // Step2. confirm advice is from correct location IProgramElement programElement = getFirstRelatedElement(findCode(checkForNode("pkg","C",true))); int line = programElement.getSourceLocation().getLine(); assertTrue("advice should be at line 7 - but is at line "+line,line==7); // Step3. No structural change to the aspect but the advice has moved down a few lines... (change in source location) alter("PR134471_2","inc1"); build("PR134471_2"); if (AsmManager.getDefault().getHandleProvider().dependsOnLocation()) checkWasFullBuild(); // the line number has changed... but nothing structural about the code else checkWasntFullBuild(); // the line number has changed... but nothing structural about the code //checkWasFullBuild(); // this is true whilst we consider sourcelocation in the type/shadow munger equals() method - have to until the handles are independent of location // Step4. Check we have correctly realised the advice moved to line 11 programElement = getFirstRelatedElement(findCode(checkForNode("pkg","C",true))); line = programElement.getSourceLocation().getLine(); assertTrue("advice should be at line 11 - but is at line "+line,line==11); } public void testAddingAndRemovingDecwWithStructureModel() { configureBuildStructureModel(true); initialiseProject("P3"); build("P3"); alter("P3","inc1"); build("P3"); assertTrue("There should be no exceptions handled:\n"+MyErrorHandler.getErrorMessages(), MyErrorHandler.getErrorMessages().isEmpty()); alter("P3","inc2"); build("P3"); assertTrue("There should be no exceptions handled:\n"+MyErrorHandler.getErrorMessages(), MyErrorHandler.getErrorMessages().isEmpty()); configureBuildStructureModel(false); } // same as first test with an extra stage that asks for C to be recompiled, it should still be advised... public void testPr134471_IncrementallyRecompilingTheAffectedClass() { try { // see pr148027 AsmHierarchyBuilder.shouldAddUsesPointcut=false; configureBuildStructureModel(true); configureNonStandardCompileOptions("-showWeaveInfo -emacssym"); // Step1. build the project initialiseProject("PR134471"); build("PR134471"); // Step2. confirm advice is from correct location IProgramElement programElement = getFirstRelatedElement(findCode(checkForNode("pkg","C",true))); int line = programElement.getSourceLocation().getLine(); assertTrue("advice should be at line 7 - but is at line "+line,line==7); // Step3. No change to the aspect at all alter("PR134471","inc1"); build("PR134471"); // Step4. Quick check that the advice points to something... IProgramElement nodeForTypeA = checkForNode("pkg","A",true); IProgramElement nodeForAdvice = findAdvice(nodeForTypeA); List relatedElements = getRelatedElements(nodeForAdvice,1); // Step5. No change to the file C but it should still be advised afterwards alter("PR134471","inc2"); build("PR134471"); checkWasntFullBuild(); // Step6. confirm advice is from correct location programElement = getFirstRelatedElement(findCode(checkForNode("pkg","C",true))); line = programElement.getSourceLocation().getLine(); assertTrue("advice should be at line 7 - but is at line "+line,line==7); } finally { // see pr148027 AsmHierarchyBuilder.shouldAddUsesPointcut=true; } } // similar to previous test but with 'declare warning' as well as advice public void testPr134471_IncrementallyRecompilingAspectContainingDeclare() { configureBuildStructureModel(true); configureNonStandardCompileOptions("-showWeaveInfo -emacssym"); // Step1. build the project initialiseProject("PR134471_3"); build("PR134471_3"); checkWasFullBuild(); // Step2. confirm declare warning is from correct location, decw matches line 7 in pkg.C IProgramElement programElement = getFirstRelatedElement(findCode(checkForNode("pkg","C",true),7)); int line = programElement.getSourceLocation().getLine(); assertTrue("declare warning should be at line 10 - but is at line "+line,line==10); // Step3. confirm advice is from correct location, advice matches line 6 in pkg.C programElement = getFirstRelatedElement(findCode(checkForNode("pkg","C",true),6)); line = programElement.getSourceLocation().getLine(); assertTrue("advice should be at line 7 - but is at line "+line,line==7); // Step4. Move declare warning in the aspect alter("PR134471_3","inc1"); build("PR134471_3"); if (AsmManager.getDefault().getHandleProvider().dependsOnLocation()) checkWasFullBuild(); // the line number has changed... but nothing structural about the code else checkWasntFullBuild(); // the line number has changed... but nothing structural about the code //checkWasFullBuild(); // Step5. confirm declare warning is from correct location, decw (now at line 12) in pkg.A matches line 7 in pkg.C programElement = getFirstRelatedElement(findCode(checkForNode("pkg","C",true),7)); line = programElement.getSourceLocation().getLine(); assertTrue("declare warning should be at line 12 - but is at line "+line,line==12); // Step6. Now just simulate 'resave' of the aspect, nothing has changed alter("PR134471_3","inc2"); build("PR134471_3"); checkWasntFullBuild(); // Step7. confirm declare warning is from correct location, decw (now at line 12) in pkg.A matches line 7 in pkg.C programElement = getFirstRelatedElement(findCode(checkForNode("pkg","C",true),7)); line = programElement.getSourceLocation().getLine(); assertTrue("declare warning should be at line 12 - but is at line "+line,line==12); configureBuildStructureModel(false); } // similar to previous test but with 'declare warning' as well as advice public void testPr134471_IncrementallyRecompilingTheClassAffectedByDeclare() { configureBuildStructureModel(true); configureNonStandardCompileOptions("-showWeaveInfo -emacssym"); // Step1. build the project initialiseProject("PR134471_3"); build("PR134471_3"); checkWasFullBuild(); // Step2. confirm declare warning is from correct location, decw matches line 7 in pkg.C IProgramElement programElement = getFirstRelatedElement(findCode(checkForNode("pkg","C",true),7)); int line = programElement.getSourceLocation().getLine(); assertTrue("declare warning should be at line 10 - but is at line "+line,line==10); // Step3. confirm advice is from correct location, advice matches line 6 in pkg.C programElement = getFirstRelatedElement(findCode(checkForNode("pkg","C",true),6)); line = programElement.getSourceLocation().getLine(); assertTrue("advice should be at line 7 - but is at line "+line,line==7); // Step4. Move declare warning in the aspect alter("PR134471_3","inc1"); build("PR134471_3"); if (AsmManager.getDefault().getHandleProvider().dependsOnLocation()) checkWasFullBuild(); // the line number has changed... but nothing structural about the code else checkWasntFullBuild(); // the line number has changed... but nothing structural about the code //checkWasFullBuild(); // Step5. confirm declare warning is from correct location, decw (now at line 12) in pkg.A matches line 7 in pkg.C programElement = getFirstRelatedElement(findCode(checkForNode("pkg","C",true),7)); line = programElement.getSourceLocation().getLine(); assertTrue("declare warning should be at line 12 - but is at line "+line,line==12); // Step6. Now just simulate 'resave' of the aspect, nothing has changed alter("PR134471_3","inc2"); build("PR134471_3"); checkWasntFullBuild(); // Step7. confirm declare warning is from correct location, decw (now at line 12) in pkg.A matches line 7 in pkg.C programElement = getFirstRelatedElement(findCode(checkForNode("pkg","C",true),7)); line = programElement.getSourceLocation().getLine(); assertTrue("declare warning should be at line 12 - but is at line "+line,line==12); // Step8. Now just simulate resave of the pkg.C type - no change at all... are relationships gonna be repaired OK? alter("PR134471_3","inc3"); build("PR134471_3"); checkWasntFullBuild(); // Step9. confirm declare warning is from correct location, decw (now at line 12) in pkg.A matches line 7 in pkg.C programElement = getFirstRelatedElement(findCode(checkForNode("pkg","C",true),7)); line = programElement.getSourceLocation().getLine(); assertTrue("declare warning should be at line 12 - but is at line "+line,line==12); configureBuildStructureModel(false); } public void testDontLoseXlintWarnings_pr141556() { configureNonStandardCompileOptions("-Xlint:warning"); initialiseProject("PR141556"); build("PR141556"); checkWasFullBuild(); String warningMessage = "can not build thisJoinPoint " + "lazily for this advice since it has no suitable guard " + "[Xlint:noGuardForLazyTjp]"; assertEquals("warning message should be '" + warningMessage + "'", warningMessage, ((IMessage)MyTaskListManager.getWarningMessages().get(0)) .getMessage()); // add a space to the Aspect but dont do a build alter("PR141556","inc1"); // remove the space so that the Aspect is exactly as it was alter("PR141556","inc2"); // build the project and we should not have lost the xlint warning build("PR141556"); checkWasntFullBuild(); assertTrue("there should still be a warning message ", !MyTaskListManager.getWarningMessages().isEmpty()); assertEquals("warning message should be '" + warningMessage + "'", warningMessage, ((IMessage)MyTaskListManager.getWarningMessages().get(0)) .getMessage()); } public void testLintMessage_pr141564() { configureNonStandardCompileOptions("-Xlint:warning"); initialiseProject("PR141556"); build("PR141556"); IMessageHandler handler = AjdeManager.getMessageHandler(); // the handler used to be an IMessageHolder (extended MessageHandler) // which stored the messages, consequently we checked that none // were being stored. Since we no longer stored any messages (fix // for bug 141564) it was unnecessary to be an IMessageHolder as all the // IMessageHolder methods in MessageHander used the list of stored // messages. Therefore, rather than checking that the list of messages // is empty we can check that we're an IMessageHandler but not an // IMessageHolder. assertFalse("expected the handler not to be an IMessageHolder but was ", handler instanceof IMessageHolder); List tasklistMessages = MyTaskListManager.getWarningMessages(); assertTrue("Should be one message but found "+tasklistMessages.size(),tasklistMessages.size()==1); IMessage msg = (IMessage)tasklistMessages.get(0); assertTrue("expected message to be a LintMessage but wasn't", msg instanceof LintMessage); assertTrue("expected message to be noGuardForLazyTjp xlint message but" + " instead was " + ((LintMessage)msg).getKind().toString(), ((LintMessage)msg).getLintKind().equals("noGuardForLazyTjp")); assertTrue("expected message to be against file in project 'PR141556' but wasn't", msg.getSourceLocation().getSourceFile().getAbsolutePath().indexOf("PR141556") != -1); } public void testAdviceDidNotMatch_pr152589() { initialiseProject("PR152589"); build("PR152589"); List warnings = MyTaskListManager.getWarningMessages(); assertTrue("There should be no warnings:\n"+warnings, warnings.isEmpty()); alter("PR152589","inc1"); build("PR152589"); if (AsmManager.getDefault().getHandleProvider().dependsOnLocation()) checkWasFullBuild(); // the line number has changed... but nothing structural about the code else checkWasntFullBuild(); // the line number has changed... but nothing structural about the code // checkWasFullBuild(); warnings = MyTaskListManager.getWarningMessages(); assertTrue("There should be no warnings after adding a whitespace:\n" +warnings,warnings.isEmpty()); } // see comment #11 of bug 154054 public void testNoFullBuildOnChangeInSysOutInAdviceBody_pr154054() { initialiseProject("PR154054"); build("PR154054"); alter("PR154054","inc1"); build("PR154054"); checkWasntFullBuild(); } // change exception type in around advice, does it notice? public void testShouldFullBuildOnExceptionChange_pr154054() { initialiseProject("PR154054_2"); build("PR154054_2"); alter("PR154054_2","inc1"); build("PR154054_2"); checkWasFullBuild(); } public void testPR158573() { IElementHandleProvider handleProvider = AsmManager.getDefault().getHandleProvider(); AsmManager.getDefault().setHandleProvider(new JDTLikeHandleProvider()); initialiseProject("PR158573"); build("PR158573"); List warnings = MyTaskListManager.getWarningMessages(); assertTrue("There should be no warnings:\n"+warnings,warnings.isEmpty()); alter("PR158573","inc1"); build("PR158573"); checkWasntFullBuild(); warnings = MyTaskListManager.getWarningMessages(); assertTrue("There should be no warnings after changing the value of a " + "variable:\n"+warnings,warnings.isEmpty()); AsmManager.getDefault().setHandleProvider(handleProvider); } // --- helper code --- /** * Retrieve program elements related to this one regardless of the relationship. A JUnit assertion is * made that the number that the 'expected' number are found. * * @param programElement Program element whose related elements are to be found * @param expected the number of expected related elements */ private List/*IProgramElement*/ getRelatedElements(IProgramElement programElement,int expected) { List relatedElements = getRelatedElements(programElement); StringBuffer debugString = new StringBuffer(); if (relatedElements!=null) { for (Iterator iter = relatedElements.iterator(); iter.hasNext();) { String element = (String) iter.next(); debugString.append(AsmManager.getDefault().getHierarchy().findElementForHandle(element).toLabelString()).append("\n"); } } assertTrue("Should be "+expected+" element"+(expected>1?"s":"")+" related to this one '"+programElement+ "' but found :\n "+debugString,relatedElements!=null && relatedElements.size()==1); return relatedElements; } private IProgramElement getFirstRelatedElement(IProgramElement programElement) { List rels = getRelatedElements(programElement,1); return AsmManager.getDefault().getHierarchy().findElementForHandle((String)rels.get(0)); } private List/*IProgramElement*/ getRelatedElements(IProgramElement advice) { List output = null; IRelationshipMap map = AsmManager.getDefault().getRelationshipMap(); List/*IRelationship*/ rels = (List)map.get(advice); if (rels==null) fail("Did not find any related elements!"); for (Iterator iter = rels.iterator(); iter.hasNext();) { IRelationship element = (IRelationship) iter.next(); List/*String*/ targets = element.getTargets(); if (output==null) output = new ArrayList(); output.addAll(targets); } return output; } private IProgramElement findAdvice(IProgramElement ipe) { return findAdvice(ipe,1); } private IProgramElement findAdvice(IProgramElement ipe,int whichOne) { if (ipe.getKind()==IProgramElement.Kind.ADVICE) { whichOne=whichOne-1; if (whichOne==0) return ipe; } List kids = ipe.getChildren(); for (Iterator iter = kids.iterator(); iter.hasNext();) { IProgramElement kid = (IProgramElement) iter.next(); IProgramElement found = findAdvice(kid,whichOne); if (found!=null) return found; } return null; } /** * Finds the first 'code' program element below the element supplied - will return null if there aren't any */ private IProgramElement findCode(IProgramElement ipe) { return findCode(ipe,-1); } /** * Searches a hierarchy of program elements for a 'code' element at the specified line number, a line number * of -1 means just return the first one you find */ private IProgramElement findCode(IProgramElement ipe,int linenumber) { if (ipe.getKind()==IProgramElement.Kind.CODE) { if (linenumber==-1 || ipe.getSourceLocation().getLine()==linenumber) return ipe; } List kids = ipe.getChildren(); for (Iterator iter = kids.iterator(); iter.hasNext();) { IProgramElement kid = (IProgramElement) iter.next(); IProgramElement found = findCode(kid,linenumber); if (found!=null) return found; } return null; } // other possible tests: // - memory usage (freemem calls?) // - relationship map // --------------------------------------------------------------------------------------------------- /** * Check we compiled/wove the right number of files, passing '-1' indicates you don't care about * that number. */ private void checkCompileWeaveCount(int expCompile,int expWoven) { if (expCompile!=-1 && getCompiledFiles().size()!=expCompile) fail("Expected compilation of "+expCompile+" files but compiled "+getCompiledFiles().size()+ "\n"+printCompiledAndWovenFiles()); if (expWoven!=-1 && getWovenClasses().size()!=expWoven) fail("Expected weaving of "+expWoven+" files but wove "+getWovenClasses().size()+ "\n"+printCompiledAndWovenFiles()); } private void checkWasntFullBuild() { assertTrue("Shouldn't have been a full (batch) build",!wasFullBuild()); } private void checkWasFullBuild() { assertTrue("Should have been a full (batch) build",wasFullBuild()); } private IProgramElement checkForNode(String packageName,String typeName,boolean shouldBeFound) { IProgramElement ipe = AsmManager.getDefault().getHierarchy().findElementForType(packageName,typeName); if (shouldBeFound) { if (ipe==null) printModel(); assertTrue("Should have been able to find '"+packageName+"."+typeName+"' in the asm",ipe!=null); } else { if (ipe!=null) printModel(); assertTrue("Should have NOT been able to find '"+packageName+"."+typeName+"' in the asm",ipe==null); } return ipe; } private void printModel() { try { AsmManager.dumptree(AsmManager.getDefault().getHierarchy().getRoot(),0); } catch (IOException e) { e.printStackTrace(); } } /* * Applies an overlay onto the project being tested - copying * the contents of the specified overlay directory. */ private void alter(String projectName,String overlayDirectory) { File projectSrc =new File(testdataSrcDir+File.separatorChar+projectName+ File.separatorChar+overlayDirectory); File destination=new File(getWorkingDir(),projectName); copy(projectSrc,destination); } private static void log(String msg) { if (VERBOSE) System.out.println(msg); } /** * Count the number of times a specified aspectName appears in the default * aop.xml file and compare with the expected number of occurrences. If just * want to count the number of aspects mentioned within the file then * pass "" for the aspectName, otherwise, specify the name of the * aspect interested in. */ private void checkXMLAspectCount(String projectName, String aspectName, int expectedOccurrences) { int aspectCount = 0; File aopXML = new File(getWorkingDir().getAbsolutePath() + File.separatorChar + projectName + File.separatorChar + "bin" + File.separatorChar + "META-INF" + File.separatorChar + "aop-ajc.xml"); if (!aopXML.exists()) { fail("Expected file " + aopXML.getAbsolutePath() + " to exist but it doesn't"); } try { BufferedReader reader = new BufferedReader(new FileReader(aopXML)); String line = reader.readLine(); while (line != null) { if (aspectName.equals("") && line.indexOf("aspect name=\"") != -1) { aspectCount++; } else if (line.indexOf("aspect name=\""+aspectName+"\"") != -1) { aspectCount++; } line = reader.readLine(); } reader.close(); } catch (IOException ie) { ie.printStackTrace(); } if (aspectCount != expectedOccurrences) { fail("Expected aspect " + aspectName + " to appear " + expectedOccurrences + " times" + " in the aop.xml file but found " + aspectCount + " occurrences"); } } private File getProjectRelativePath(String p,String filename) { File projDir = new File(getWorkingDir(),p); return new File(projDir,filename); } private File getProjectOutputRelativePath(String p,String filename) { File projDir = new File(getWorkingDir(),p); return new File(projDir,"bin"+File.separator+filename); } }
161,217
Bug 161217 NPE in BcelAdvice
I've been playing with some aspect deployment models and got into this error during project rebuild from AJDT: java.lang.NullPointerException at org.aspectj.weaver.bcel.BcelAdvice.implementOn(BcelAdvice.java:199) at org.aspectj.weaver.Shadow.implementMungers(Shadow.java:699) at org.aspectj.weaver.Shadow.implement(Shadow.java:471) at org.aspectj.weaver.bcel.BcelClassWeaver.implement(BcelClassWeaver.java:2832) at org.aspectj.weaver.bcel.BcelClassWeaver.weave(BcelClassWeaver.java:506) at org.aspectj.weaver.bcel.BcelClassWeaver.weave(BcelClassWeave ... lasses when weaving when batch building BuildConfig[...] #Files=6 Here is the aspect and classes it is applied to: ----- @Aspect("percflow(execution(* InstrumentedBean.getProperty2()))") public class GetFieldAtAspect { @Around("execution(* ConfigurableBean.getProperty2())") public Object onGet(ProceedingJoinPoint jp) throws Throwable { return jp.proceed(); } } ------ import org.springframework.beans.factory.InitializingBean; public class InstrumentedBean implements InitializingBean, IInstrumentedBean { private ConfigurableBean configurableBean; private String value; private transient String transientValue = "aaa"; public void afterPropertiesSet() throws Exception { this.configurableBean = new ConfigurableBean(); } public String getProperty1() { synchronized(this) { return this.configurableBean.getProperty1(); } } public String getProperty2() { synchronized(this) { return this.configurableBean.getProperty2(); } } public void setValue(String value) { synchronized(this) { this.value = value; } } public Object getValue() { synchronized(this) { return value; } } public Object getTransientValue() { return transientValue; } public void setTransientValue(String transientValue) { this.transientValue = transientValue; } } ------ import java.io.Serializable; import org.springframework.beans.factory.annotation.Configurable; @Configurable public class ConfigurableBean implements Serializable { private static final long serialVersionUID = 1L; private String property1; private String property2; public ConfigurableBean() { } public String getProperty1() { return this.property1; } public String getProperty2() { return this.property2; } public void setProperty1(String property1) { this.property1 = property1; } public void setProperty2(String property2) { this.property2 = property2; } }
resolved fixed
044542c
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2006-10-19T14:05:02Z"
"2006-10-17T13:00:00Z"
tests/bugs153/pr161217/AtAspectJAspect.java
161,217
Bug 161217 NPE in BcelAdvice
I've been playing with some aspect deployment models and got into this error during project rebuild from AJDT: java.lang.NullPointerException at org.aspectj.weaver.bcel.BcelAdvice.implementOn(BcelAdvice.java:199) at org.aspectj.weaver.Shadow.implementMungers(Shadow.java:699) at org.aspectj.weaver.Shadow.implement(Shadow.java:471) at org.aspectj.weaver.bcel.BcelClassWeaver.implement(BcelClassWeaver.java:2832) at org.aspectj.weaver.bcel.BcelClassWeaver.weave(BcelClassWeaver.java:506) at org.aspectj.weaver.bcel.BcelClassWeaver.weave(BcelClassWeave ... lasses when weaving when batch building BuildConfig[...] #Files=6 Here is the aspect and classes it is applied to: ----- @Aspect("percflow(execution(* InstrumentedBean.getProperty2()))") public class GetFieldAtAspect { @Around("execution(* ConfigurableBean.getProperty2())") public Object onGet(ProceedingJoinPoint jp) throws Throwable { return jp.proceed(); } } ------ import org.springframework.beans.factory.InitializingBean; public class InstrumentedBean implements InitializingBean, IInstrumentedBean { private ConfigurableBean configurableBean; private String value; private transient String transientValue = "aaa"; public void afterPropertiesSet() throws Exception { this.configurableBean = new ConfigurableBean(); } public String getProperty1() { synchronized(this) { return this.configurableBean.getProperty1(); } } public String getProperty2() { synchronized(this) { return this.configurableBean.getProperty2(); } } public void setValue(String value) { synchronized(this) { this.value = value; } } public Object getValue() { synchronized(this) { return value; } } public Object getTransientValue() { return transientValue; } public void setTransientValue(String transientValue) { this.transientValue = transientValue; } } ------ import java.io.Serializable; import org.springframework.beans.factory.annotation.Configurable; @Configurable public class ConfigurableBean implements Serializable { private static final long serialVersionUID = 1L; private String property1; private String property2; public ConfigurableBean() { } public String getProperty1() { return this.property1; } public String getProperty2() { return this.property2; } public void setProperty1(String property1) { this.property1 = property1; } public void setProperty2(String property2) { this.property2 = property2; } }
resolved fixed
044542c
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2006-10-19T14:05:02Z"
"2006-10-17T13:00:00Z"
tests/bugs153/pr161217/C.java
161,217
Bug 161217 NPE in BcelAdvice
I've been playing with some aspect deployment models and got into this error during project rebuild from AJDT: java.lang.NullPointerException at org.aspectj.weaver.bcel.BcelAdvice.implementOn(BcelAdvice.java:199) at org.aspectj.weaver.Shadow.implementMungers(Shadow.java:699) at org.aspectj.weaver.Shadow.implement(Shadow.java:471) at org.aspectj.weaver.bcel.BcelClassWeaver.implement(BcelClassWeaver.java:2832) at org.aspectj.weaver.bcel.BcelClassWeaver.weave(BcelClassWeaver.java:506) at org.aspectj.weaver.bcel.BcelClassWeaver.weave(BcelClassWeave ... lasses when weaving when batch building BuildConfig[...] #Files=6 Here is the aspect and classes it is applied to: ----- @Aspect("percflow(execution(* InstrumentedBean.getProperty2()))") public class GetFieldAtAspect { @Around("execution(* ConfigurableBean.getProperty2())") public Object onGet(ProceedingJoinPoint jp) throws Throwable { return jp.proceed(); } } ------ import org.springframework.beans.factory.InitializingBean; public class InstrumentedBean implements InitializingBean, IInstrumentedBean { private ConfigurableBean configurableBean; private String value; private transient String transientValue = "aaa"; public void afterPropertiesSet() throws Exception { this.configurableBean = new ConfigurableBean(); } public String getProperty1() { synchronized(this) { return this.configurableBean.getProperty1(); } } public String getProperty2() { synchronized(this) { return this.configurableBean.getProperty2(); } } public void setValue(String value) { synchronized(this) { this.value = value; } } public Object getValue() { synchronized(this) { return value; } } public Object getTransientValue() { return transientValue; } public void setTransientValue(String transientValue) { this.transientValue = transientValue; } } ------ import java.io.Serializable; import org.springframework.beans.factory.annotation.Configurable; @Configurable public class ConfigurableBean implements Serializable { private static final long serialVersionUID = 1L; private String property1; private String property2; public ConfigurableBean() { } public String getProperty1() { return this.property1; } public String getProperty2() { return this.property2; } public void setProperty1(String property1) { this.property1 = property1; } public void setProperty2(String property2) { this.property2 = property2; } }
resolved fixed
044542c
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2006-10-19T14:05:02Z"
"2006-10-17T13:00:00Z"
tests/src/org/aspectj/systemtest/ajc153/Ajc153Tests.java
/******************************************************************************* * Copyright (c) 2006 IBM * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Andy Clement - initial API and implementation *******************************************************************************/ package org.aspectj.systemtest.ajc153; import java.io.File; import junit.framework.Test; import org.aspectj.asm.AsmManager; import org.aspectj.asm.IHierarchy; import org.aspectj.asm.IProgramElement; import org.aspectj.testing.Utils; import org.aspectj.testing.XMLBasedAjcTestCase; import org.aspectj.weaver.bcel.Utility; public class Ajc153Tests extends org.aspectj.testing.XMLBasedAjcTestCase { //public void testGenericsProblem_pr151978() { runTest("generics problem");} // public void testArgnamesAndJavac_pr148381() { runTest("argNames and javac");} // public void testCFlowXMLAspectLTW_pr149096() { runTest("cflow xml concrete aspect"); } // public void testAmbiguousBinding_pr121805() { runTest("ambiguous binding");} // public void testNegatedAnnotationMatchingProblem_pr153464() { runTest("negated annotation matching problem");} public void testPTWgetWithinTypeName_pr123423_1() { runTest("basic usage of getWithinTypeName");} public void testPTWgetWithinTypeName_pr123423_2() { runTest("basic usage of getWithinTypeName - multiple types");} public void testPTWgetWithinTypeName_pr123423_3() { runTest("basic usage of getWithinTypeName - non matching types");} public void testPTWgetWithinTypeName_pr123423_4() { runTest("basic usage of getWithinTypeName - types in packages");} public void testPTWgetWithinTypeName_pr123423_5() { runTest("basic usage of getWithinTypeName - annotation style");} public void testTurningOffBcelCaching_pr160674() { runTest("turning off bcel caching");} public void testNoIllegalStateExceptionWithGenericInnerAspect_pr156058() { runTest("no IllegalStateException with generic inner aspect"); } public void testNoIllegalStateExceptionWithGenericInnerAspect_pr156058_2() { runTest("no IllegalStateException with generic inner aspect - 2"); } public void testDeclareMethodAnnotations_pr159143() { runTest("declare method annotations");} public void testVisibilityProblem_pr149071() { runTest("visibility problem");} public void testMissingLineNumbersInStacktraceAfter_pr145442() { runTest("missing line numbers in stacktrace after");} public void testMissingLineNumbersInStacktraceAround_pr145442() { runTest("missing line numbers in stacktrace around");} public void testGenericArrays_pr158624() { runTest("generics and arrays"); } public void testMissingLineNumbersInStacktraceBefore_pr145442() { runTest("missing line numbers in stacktrace before");} public void testMissingLineNumbersInStacktraceBefore_pr145442_Binary() { runTest("missing line numbers in stacktrace before - binary");} public void testAnnotationStylePointcutNPE_pr158412() { runTest("annotation style pointcut npe"); } public void testAnnotationStylePointcutNPE_pr158412_2() { runTest("annotation style pointcut npe - 2"); } public void testAnnotationsCallConstructors_pr158126() { runTest("annotations, call and constructors problem");} public void testIllegalStateExceptionGenerics_pr153845() { runTest("IllegalStateException at GenericSignatureParser.java"); } public void testNoIllegalStateExceptionFromAsmDelegate_pr153490_1() { runTest("no illegal state exception from AsmDelegate - 1");} public void testNoIllegalStateExceptionFromAsmDelegate_pr153490_2() { runTest("no illegal state exception from AsmDelegate - 2");} public void testNoIllegalStateExceptionFromAsmDelegate_pr153490_3() { runTest("no illegal state exception from AsmDelegate - 3");} public void testAnnotMethod_pr156962() { runTest("Test Annot Method");} public void testAnnotMethodHasMember_pr156962() { runTest("Test Annot Method Has Member"); } public void testMixingGenerics_pr152848() { runTest("mixing generics"); } public void testIncorrectStaticinitializationWeaving_pr149560_1() { runTest("incorrect staticinitialization weaving - codestyle");} public void testIncorrectStaticinitializationWeaving_pr149560_2() { runTest("incorrect staticinitialization weaving - annstyle");} public void testIncorrectDeprecatedAnnotationProcessing_pr154332() { runTest("incorrect deprecated annotation processing");} public void testPipeliningProblemWithAnnotationsDecp_pr153380_1() { runTest("pipelining decps");} public void testUnwantedPointcutWarning_pr148219() { runTest("unwanted warning for pointcut");} public void testDecpAndCflowadderMungerClash_pr152631() { runTest("decp and cflowadder munger clash");} public void testGenericInheritanceDecp_pr150095() { runTest("generics, inheritance and decp");} public void testIllegalStateException_pr148737() { runTest("illegalstateexception for non generic type");} public void testAtajInheritance_pr149305_1() { runTest("ataj inheritance - 1");} public void testAtajInheritance_pr149305_2() { runTest("ataj inheritance - 2");} public void testAtajInheritance_pr149305_3() { runTest("ataj inheritance - 3");} public void testVerificationFailureForAspectOf_pr148693() { runTest("verification problem"); // build the code Utils.verifyClass(ajc,"mypackage.MyAspect"); // verify it <<< BRAND NEW VERIFY UTILITY FOR EVERYONE TO TRY ;) } public void testIncorrectAnnotationValue_pr148537() { runTest("incorrect annotation value");} public void testVerifyErrNoTypeCflowField_pr145693_1() { runTest("verifyErrNoTypeCflowField"); } public void testVerifyErrInpathNoTypeCflowField_pr145693_2() { runTest("verifyErrInpathNoTypeCflowField"); } public void testCpathNoTypeCflowField_pr145693_3() { runTest("cpathNoTypeCflowField"); } // public void testAdviceNotWovenAspectPath_pr147841() { runTest("advice not woven on aspectpath");} public void testGenericSignatures_pr148409() { runTest("generic signature problem"); } // public void testBrokenIfArgsCflowAtAj_pr145018() { runTest("ataj crashing with cflow, if and args");} public void testCantFindType_pr149322_01() {runTest("can't find type on interface call 1");} public void testCantFindType_pr149322_02() {runTest("can't find type on interface call 2");} public void testCantFindType_pr149322_03() {runTest("can't find type on interface call 3");} public void testParsingBytecodeLess_pr152871() { Utility.testingParseCounter=0; runTest("parsing bytecode less"); assertTrue("Should have called parse 5 times, not "+Utility.testingParseCounter+" times",Utility.testingParseCounter==5); // 5 means: // (1)=registerAspect // (2,3)=checkingIfShouldWeave,AcceptingResult for class // (4,5)=checkingIfShouldWeave,AcceptingResult for aspect } public void testMatchVolatileField_pr150671() {runTest("match volatile field");}; public void testDuplicateJVMTIAgents_pr151938() {runTest("Duplicate JVMTI agents");}; public void testLTWWorldWithAnnotationMatching_pr153572() { runTest("LTWWorld with annotation matching");} public void testReweavableAspectNotRegistered_pr129525 () { runTest("reweavableAspectNotRegistered error"); } public void testNPEinConstructorSignatureImpl_pr155972 () { runTest("NPE in ConstructorSignatureImpl"); } public void testNPEinFieldSignatureImpl_pr155972 () { runTest("NPE in FieldSignatureImpl"); } public void testNPEinInitializerSignatureImpl_pr155972 () { runTest("NPE in InitializerSignatureImpl"); } public void testLineNumberTableCorrectWithGenericsForEachAndContinue_pr155763() { runTest("ensure LineNumberTable correct with generics, for each and continue"); } public void testDeclareSoftDoesntAllowUndeclaredExInAnonInnerClass_pr151772() { runTest("ensure declare soft doesn't allow undeclared exception in anonymous inner class"); } public void testDeclareSoftDoesntAllowUndeclaredExInAnonInnerClass_pr151772_2() { runTest("ensure declare soft doesn't allow undeclared exception in anonymous inner class - 2"); } public void testDeclareSoftAndInnerClasses_pr125981() { runTest("declare soft and inner classes"); } public void testGetSourceSignature_pr148908() { runTest("ensure getSourceSignature correct with static field"); IHierarchy top = AsmManager.getDefault().getHierarchy(); IProgramElement ipe = top.findElementForLabel(top.getRoot(), IProgramElement.Kind.FIELD,"MY_COMPARATOR"); String expected = "static final Comparator MY_COMPARATOR = new Comparator() {\n" + " public int compare(Object o1, Object o2) {\n" + " return 0;\n" + " }\n" + "};"; assertEquals("expected source signature to be " + expected + " but found " + ipe.getSourceSignature(), expected, ipe.getSourceSignature()); } public void testNPEWithCustomAgent_pr158005() { runTest("NPE with custom agent"); } public void testWeaveConcreteSubaspectWithAdvice_pr132080() { runTest("Weave concrete sub-aspect with advice"); } public void testWeaveConcreteSubaspectWithITD_pr132080() { runTest("Weave concrete sub-aspect with ITD"); } public void testWeaveConcreteSubaspectWithAroundClosure_pr132080() { runTest("Weave concrete sub-aspect with around closure"); } public void testWeaveConcreteSubaspectWithCflow_pr132080() { runTest("Weave concrete sub-aspect with cflow"); } public void testNPEWithLTWPointcutLibraryAndMissingAspectDependency_pr158957 () { runTest("NPE with LTW, pointcut library and missing aspect dependency"); } public void testNoInvalidAbsoluteTypeNameWarning_pr156904_1() {runTest("ensure no invalidAbsoluteTypeName when do match - 1");} public void testNoInvalidAbsoluteTypeNameWarning_pr156904_2() {runTest("ensure no invalidAbsoluteTypeName when do match - 2");} public void testNoInvalidAbsoluteTypeNameWarning_pr156904_3() {runTest("ensure no invalidAbsoluteTypeName when do match - 3");} public void testNoInvalidAbsoluteTypeNameWarning_pr156904_4() {runTest("ensure no invalidAbsoluteTypeName when do match - 4");} ///////////////////////////////////////// public static Test suite() { return XMLBasedAjcTestCase.loadSuite(Ajc153Tests.class); } protected File getSpecFile() { return new File("../tests/src/org/aspectj/systemtest/ajc153/ajc153.xml"); } }
161,217
Bug 161217 NPE in BcelAdvice
I've been playing with some aspect deployment models and got into this error during project rebuild from AJDT: java.lang.NullPointerException at org.aspectj.weaver.bcel.BcelAdvice.implementOn(BcelAdvice.java:199) at org.aspectj.weaver.Shadow.implementMungers(Shadow.java:699) at org.aspectj.weaver.Shadow.implement(Shadow.java:471) at org.aspectj.weaver.bcel.BcelClassWeaver.implement(BcelClassWeaver.java:2832) at org.aspectj.weaver.bcel.BcelClassWeaver.weave(BcelClassWeaver.java:506) at org.aspectj.weaver.bcel.BcelClassWeaver.weave(BcelClassWeave ... lasses when weaving when batch building BuildConfig[...] #Files=6 Here is the aspect and classes it is applied to: ----- @Aspect("percflow(execution(* InstrumentedBean.getProperty2()))") public class GetFieldAtAspect { @Around("execution(* ConfigurableBean.getProperty2())") public Object onGet(ProceedingJoinPoint jp) throws Throwable { return jp.proceed(); } } ------ import org.springframework.beans.factory.InitializingBean; public class InstrumentedBean implements InitializingBean, IInstrumentedBean { private ConfigurableBean configurableBean; private String value; private transient String transientValue = "aaa"; public void afterPropertiesSet() throws Exception { this.configurableBean = new ConfigurableBean(); } public String getProperty1() { synchronized(this) { return this.configurableBean.getProperty1(); } } public String getProperty2() { synchronized(this) { return this.configurableBean.getProperty2(); } } public void setValue(String value) { synchronized(this) { this.value = value; } } public Object getValue() { synchronized(this) { return value; } } public Object getTransientValue() { return transientValue; } public void setTransientValue(String transientValue) { this.transientValue = transientValue; } } ------ import java.io.Serializable; import org.springframework.beans.factory.annotation.Configurable; @Configurable public class ConfigurableBean implements Serializable { private static final long serialVersionUID = 1L; private String property1; private String property2; public ConfigurableBean() { } public String getProperty1() { return this.property1; } public String getProperty2() { return this.property2; } public void setProperty1(String property1) { this.property1 = property1; } public void setProperty2(String property2) { this.property2 = property2; } }
resolved fixed
044542c
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2006-10-19T14:05:02Z"
"2006-10-17T13:00:00Z"
weaver/src/org/aspectj/weaver/bcel/BcelAdvice.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Eclipse Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * PARC initial implementation * Alexandre Vasseur support for @AJ aspects * ******************************************************************/ package org.aspectj.weaver.bcel; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Map; import org.aspectj.apache.bcel.generic.InstructionConstants; import org.aspectj.apache.bcel.generic.InstructionFactory; import org.aspectj.apache.bcel.generic.InstructionHandle; import org.aspectj.apache.bcel.generic.InstructionList; import org.aspectj.apache.bcel.generic.LineNumberTag; import org.aspectj.bridge.ISourceLocation; import org.aspectj.bridge.Message; import org.aspectj.weaver.Advice; import org.aspectj.weaver.AdviceKind; import org.aspectj.weaver.AjAttribute; import org.aspectj.weaver.BCException; import org.aspectj.weaver.IEclipseSourceContext; import org.aspectj.weaver.ISourceContext; import org.aspectj.weaver.Member; import org.aspectj.weaver.ResolvedMember; import org.aspectj.weaver.ResolvedType; import org.aspectj.weaver.Shadow; import org.aspectj.weaver.ShadowMunger; import org.aspectj.weaver.UnresolvedType; import org.aspectj.weaver.WeaverMessages; import org.aspectj.weaver.World; import org.aspectj.weaver.ast.Literal; import org.aspectj.weaver.ast.Test; import org.aspectj.weaver.patterns.ExactTypePattern; import org.aspectj.weaver.patterns.ExposedState; import org.aspectj.weaver.patterns.PerClause; import org.aspectj.weaver.patterns.Pointcut; /** * Advice implemented for bcel. * * @author Erik Hilsdale * @author Jim Hugunin */ public class BcelAdvice extends Advice { private Test pointcutTest; private ExposedState exposedState; private boolean hasMatchedAtLeastOnce = false; public BcelAdvice( AjAttribute.AdviceAttribute attribute, Pointcut pointcut, Member signature, ResolvedType concreteAspect) { super(attribute, pointcut, signature); this.concreteAspect = concreteAspect; } // !!! must only be used for testing public BcelAdvice(AdviceKind kind, Pointcut pointcut, Member signature, int extraArgumentFlags, int start, int end, ISourceContext sourceContext, ResolvedType concreteAspect) { this(new AjAttribute.AdviceAttribute(kind, pointcut, extraArgumentFlags, start, end, sourceContext), pointcut, signature, concreteAspect); thrownExceptions = Collections.EMPTY_LIST; //!!! interaction with unit tests } // ---- implementations of ShadowMunger's methods public ShadowMunger concretize(ResolvedType fromType, World world, PerClause clause) { suppressLintWarnings(world); ShadowMunger ret = super.concretize(fromType, world, clause); clearLintSuppressions(world,this.suppressedLintKinds); IfFinder ifinder = new IfFinder(); ret.getPointcut().accept(ifinder,null); boolean hasGuardTest = ifinder.hasIf && getKind() != AdviceKind.Around; boolean isAround = getKind() == AdviceKind.Around; if ((getExtraParameterFlags() & ThisJoinPoint) != 0) { if (!isAround && !hasGuardTest && world.getLint().noGuardForLazyTjp.isEnabled()) { // can't build tjp lazily, no suitable test... // ... only want to record it once against the advice(bug 133117) world.getLint().noGuardForLazyTjp.signal("",getSourceLocation()); } } return ret; } public ShadowMunger parameterizeWith(ResolvedType declaringType,Map typeVariableMap) { Pointcut pc = getPointcut().parameterizeWith(typeVariableMap); BcelAdvice ret = null; Member adviceSignature = signature; // allows for around advice where the return value is a type variable (see pr115250) if (signature instanceof ResolvedMember && signature.getDeclaringType().isGenericType()) { adviceSignature = ((ResolvedMember)signature).parameterizedWith(declaringType.getTypeParameters(),declaringType,declaringType.isParameterizedType()); } ret = new BcelAdvice(this.attribute,pc,adviceSignature,this.concreteAspect); return ret; } public boolean match(Shadow shadow, World world) { suppressLintWarnings(world); boolean ret = super.match(shadow, world); clearLintSuppressions(world,this.suppressedLintKinds); return ret; } public void specializeOn(Shadow shadow) { if (getKind() == AdviceKind.Around) { ((BcelShadow)shadow).initializeForAroundClosure(); } //XXX this case is just here for supporting lazy test code if (getKind() == null) { exposedState = new ExposedState(0); return; } if (getKind().isPerEntry()) { exposedState = new ExposedState(0); } else if (getKind().isCflow()) { exposedState = new ExposedState(nFreeVars); } else if (getSignature() != null) { exposedState = new ExposedState(getSignature()); } else { exposedState = new ExposedState(0); return; //XXX this case is just here for supporting lazy test code } World world = shadow.getIWorld(); suppressLintWarnings(world); pointcutTest = getPointcut().findResidue(shadow, exposedState); clearLintSuppressions(world,this.suppressedLintKinds); // these initializations won't be performed by findResidue, but need to be // so that the joinpoint is primed for weaving if (getKind() == AdviceKind.PerThisEntry) { shadow.getThisVar(); } else if (getKind() == AdviceKind.PerTargetEntry) { shadow.getTargetVar(); } // make sure thisJoinPoint parameters are initialized if ((getExtraParameterFlags() & ThisJoinPointStaticPart) != 0) { ((BcelShadow)shadow).getThisJoinPointStaticPartVar(); ((BcelShadow)shadow).getEnclosingClass().warnOnAddedStaticInitializer(shadow,getSourceLocation()); } if ((getExtraParameterFlags() & ThisJoinPoint) != 0) { boolean hasGuardTest = pointcutTest != Literal.TRUE && getKind() != AdviceKind.Around; boolean isAround = getKind() == AdviceKind.Around; ((BcelShadow)shadow).requireThisJoinPoint(hasGuardTest,isAround); ((BcelShadow)shadow).getEnclosingClass().warnOnAddedStaticInitializer(shadow,getSourceLocation()); if (!hasGuardTest && world.getLint().multipleAdviceStoppingLazyTjp.isEnabled()) { // collect up the problematic advice ((BcelShadow)shadow).addAdvicePreventingLazyTjp(this); } } if ((getExtraParameterFlags() & ThisEnclosingJoinPointStaticPart) != 0) { ((BcelShadow)shadow).getThisEnclosingJoinPointStaticPartVar(); ((BcelShadow)shadow).getEnclosingClass().warnOnAddedStaticInitializer(shadow,getSourceLocation()); } } private boolean canInline(Shadow s) { if (attribute.isProceedInInners()) return false; //XXX this guard seems to only be needed for bad test cases if (concreteAspect == null || concreteAspect.isMissing()) return false; if (concreteAspect.getWorld().isXnoInline()) return false; //System.err.println("isWoven? " + ((BcelObjectType)concreteAspect).getLazyClassGen().getWeaverState()); return BcelWorld.getBcelObjectType(concreteAspect).getLazyClassGen().isWoven(); } public void implementOn(Shadow s) { hasMatchedAtLeastOnce=true; BcelShadow shadow = (BcelShadow) s; // remove any unnecessary exceptions if the compiler option is set to // error or warning and if this piece of advice throws exceptions // (bug 129282). This may be expanded to include other compiler warnings // at the moment it only deals with 'declared exception is not thrown' if (!shadow.getWorld().isIgnoringUnusedDeclaredThrownException() && !thrownExceptions.isEmpty()) { Member member = shadow.getSignature(); if (member instanceof BcelMethod) { removeUnnecessaryProblems((BcelMethod)member, ((BcelMethod)member).getDeclarationLineNumber()); } else { // we're in a call shadow therefore need the line number of the // declared method (which may be in a different type). However, // we want to remove the problems from the CompilationResult // held within the current type's EclipseSourceContext so need // the enclosing shadow too ResolvedMember resolvedMember = shadow.getSignature().resolve(shadow.getWorld()); if (resolvedMember instanceof BcelMethod && shadow.getEnclosingShadow() instanceof BcelShadow) { Member enclosingMember = shadow.getEnclosingShadow().getSignature(); if (enclosingMember instanceof BcelMethod) { removeUnnecessaryProblems((BcelMethod)enclosingMember, ((BcelMethod)resolvedMember).getDeclarationLineNumber()); } } } } if (shadow.getIWorld().isJoinpointSynchronizationEnabled() && shadow.getKind()==Shadow.MethodExecution && (s.getSignature().getModifiers() & Modifier.SYNCHRONIZED)!=0) { Message m = new Message("advice matching the synchronized method shadow '"+shadow.toString()+ "' will be executed outside the lock rather than inside (compiler limitation)",shadow.getSourceLocation(),false,new ISourceLocation[]{getSourceLocation()}); shadow.getIWorld().getMessageHandler().handleMessage(m); } //FIXME AV - see #75442, this logic is not enough so for now comment it out until we fix the bug // // callback for perObject AJC MightHaveAspect postMunge (#75442) // if (getConcreteAspect() != null // && getConcreteAspect().getPerClause() != null // && PerClause.PEROBJECT.equals(getConcreteAspect().getPerClause().getKind())) { // final PerObject clause; // if (getConcreteAspect().getPerClause() instanceof PerFromSuper) { // clause = (PerObject)((PerFromSuper) getConcreteAspect().getPerClause()).lookupConcretePerClause(getConcreteAspect()); // } else { // clause = (PerObject) getConcreteAspect().getPerClause(); // } // if (clause.isThis()) { // PerObjectInterfaceTypeMunger.registerAsAdvisedBy(s.getThisVar().getType(), getConcreteAspect()); // } else { // PerObjectInterfaceTypeMunger.registerAsAdvisedBy(s.getTargetVar().getType(), getConcreteAspect()); // } // } if (getKind() == AdviceKind.Before) { shadow.weaveBefore(this); } else if (getKind() == AdviceKind.AfterReturning) { shadow.weaveAfterReturning(this); } else if (getKind() == AdviceKind.AfterThrowing) { UnresolvedType catchType = hasExtraParameter() ? getExtraParameterType() : UnresolvedType.THROWABLE; shadow.weaveAfterThrowing(this, catchType); } else if (getKind() == AdviceKind.After) { shadow.weaveAfter(this); } else if (getKind() == AdviceKind.Around) { // Note: under regular LTW the aspect is usually loaded after the first use of any class affecteted by it // This means that as long as the aspect has not been thru the LTW, it's woven state is unknown // and thus canInline(s) will return false. // To force inlining (test), ones can do Class aspect = FQNAspect.class in the clinit of the target class // FIXME AV : for AJC compiled @AJ aspect (or any code style aspect), the woven state can never be known // if the aspect belongs to a parent classloader. In that case the aspect will never be inlined. // It might be dangerous to change that especially for @AJ aspect non compiled with AJC since if those // are not weaved (f.e. use of some limiteed LTW etc) then they cannot be prepared for inlining. // One solution would be to flag @AJ aspect with an annotation as "prepared" and query that one. if (!canInline(s)) { shadow.weaveAroundClosure(this, hasDynamicTests()); } else { shadow.weaveAroundInline(this, hasDynamicTests()); } } else if (getKind() == AdviceKind.InterInitializer) { shadow.weaveAfterReturning(this); } else if (getKind().isCflow()) { shadow.weaveCflowEntry(this, getSignature()); } else if (getKind() == AdviceKind.PerThisEntry) { shadow.weavePerObjectEntry(this, (BcelVar)shadow.getThisVar()); } else if (getKind() == AdviceKind.PerTargetEntry) { shadow.weavePerObjectEntry(this, (BcelVar)shadow.getTargetVar()); } else if (getKind() == AdviceKind.Softener) { shadow.weaveSoftener(this, ((ExactTypePattern)exceptionType).getType()); } else if (getKind() == AdviceKind.PerTypeWithinEntry) { // PTWIMPL Entry to ptw is the static initialization of a type that matched the ptw type pattern shadow.weavePerTypeWithinAspectInitialization(this,shadow.getEnclosingType()); } else { throw new BCException("unimplemented kind: " + getKind()); } } private void removeUnnecessaryProblems(BcelMethod method, int problemLineNumber) { ISourceContext sourceContext = method.getSourceContext(); if (sourceContext instanceof IEclipseSourceContext) { if (sourceContext != null && sourceContext instanceof IEclipseSourceContext) { ((IEclipseSourceContext)sourceContext).removeUnnecessaryProblems(method, problemLineNumber); } } } // ---- implementations private Collection collectCheckedExceptions(UnresolvedType[] excs) { if (excs == null || excs.length == 0) return Collections.EMPTY_LIST; Collection ret = new ArrayList(); World world = concreteAspect.getWorld(); ResolvedType runtimeException = world.getCoreType(UnresolvedType.RUNTIME_EXCEPTION); ResolvedType error = world.getCoreType(UnresolvedType.ERROR); for (int i=0, len=excs.length; i < len; i++) { ResolvedType t = world.resolve(excs[i],true); if (t.isMissing()) { world.getLint().cantFindType.signal( WeaverMessages.format(WeaverMessages.CANT_FIND_TYPE_EXCEPTION_TYPE,excs[i].getName()), getSourceLocation() ); // IMessage msg = new Message( // WeaverMessages.format(WeaverMessages.CANT_FIND_TYPE_EXCEPTION_TYPE,excs[i].getName()), // "",IMessage.ERROR,getSourceLocation(),null,null); // world.getMessageHandler().handleMessage(msg); } if (!(runtimeException.isAssignableFrom(t) || error.isAssignableFrom(t))) { ret.add(t); } } return ret; } private Collection thrownExceptions = null; public Collection getThrownExceptions() { if (thrownExceptions == null) { //??? can we really lump in Around here, how does this interact with Throwable if (concreteAspect != null && concreteAspect.getWorld() != null && // null tests for test harness (getKind().isAfter() || getKind() == AdviceKind.Before || getKind() == AdviceKind.Around)) { World world = concreteAspect.getWorld(); ResolvedMember m = world.resolve(signature); if (m == null) { thrownExceptions = Collections.EMPTY_LIST; } else { thrownExceptions = collectCheckedExceptions(m.getExceptions()); } } else { thrownExceptions = Collections.EMPTY_LIST; } } return thrownExceptions; } /** * The munger must not check for the advice exceptions to be declared by the shadow in the case * of @AJ aspects so that around can throws Throwable * * @return */ public boolean mustCheckExceptions() { if (getConcreteAspect() == null) { return true; } return !getConcreteAspect().isAnnotationStyleAspect(); } // only call me after prepare has been called public boolean hasDynamicTests() { // if (hasExtraParameter() && getKind() == AdviceKind.AfterReturning) { // UnresolvedType extraParameterType = getExtraParameterType(); // if (! extraParameterType.equals(UnresolvedType.OBJECT) // && ! extraParameterType.isPrimitive()) // return true; // } return pointcutTest != null && !(pointcutTest == Literal.TRUE);// || pointcutTest == Literal.NO_TEST); } /** * get the instruction list for the really simple version of this advice. * Is broken apart * for other advice, but if you want it in one block, this is the method to call. * * @param s The shadow around which these instructions will eventually live. * @param extraArgVar The var that will hold the return value or thrown exception * for afterX advice * @param ifNoAdvice The instructionHandle to jump to if the dynamic * tests for this munger fails. */ InstructionList getAdviceInstructions( BcelShadow s, BcelVar extraArgVar, InstructionHandle ifNoAdvice) { BcelShadow shadow = (BcelShadow) s; InstructionFactory fact = shadow.getFactory(); BcelWorld world = shadow.getWorld(); InstructionList il = new InstructionList(); // we test to see if we have the right kind of thing... // after throwing does this just by the exception mechanism. if (hasExtraParameter() && getKind() == AdviceKind.AfterReturning) { UnresolvedType extraParameterType = getExtraParameterType(); if (! extraParameterType.equals(UnresolvedType.OBJECT) && ! extraParameterType.isPrimitiveType()) { il.append( BcelRenderer.renderTest( fact, world, Test.makeInstanceof( extraArgVar, getExtraParameterType().resolve(world)), null, ifNoAdvice, null)); } } il.append(getAdviceArgSetup(shadow, extraArgVar, null)); il.append(getNonTestAdviceInstructions(shadow)); InstructionHandle ifYesAdvice = il.getStart(); il.insert(getTestInstructions(shadow, ifYesAdvice, ifNoAdvice, ifYesAdvice)); // If inserting instructions at the start of a method, we need a nice line number for this entry // in the stack trace if (shadow.getKind()==Shadow.MethodExecution && getKind()==AdviceKind.Before) { int lineNumber=0; // Uncomment this code if you think we should use the method decl line number when it exists... // // If the advised join point is in a class built by AspectJ, we can use the declaration line number // boolean b = shadow.getEnclosingMethod().getMemberView().hasDeclarationLineNumberInfo(); // if (b) { // lineNumber = shadow.getEnclosingMethod().getMemberView().getDeclarationLineNumber(); // } else { // If it wasn't, the best we can do is the line number of the first instruction in the method lineNumber = shadow.getEnclosingMethod().getMemberView().getLineNumberOfFirstInstruction(); // } if (lineNumber>0) il.getStart().addTargeter(new LineNumberTag(lineNumber)); } return il; } public InstructionList getAdviceArgSetup( BcelShadow shadow, BcelVar extraVar, InstructionList closureInstantiation) { InstructionFactory fact = shadow.getFactory(); BcelWorld world = shadow.getWorld(); InstructionList il = new InstructionList(); // if (targetAspectField != null) { // il.append(fact.createFieldAccess( // targetAspectField.getDeclaringType().getName(), // targetAspectField.getName(), // BcelWorld.makeBcelType(targetAspectField.getType()), // Constants.GETSTATIC)); // } // //System.err.println("BcelAdvice: " + exposedState); if (exposedState.getAspectInstance() != null) { il.append(BcelRenderer.renderExpr(fact, world, exposedState.getAspectInstance())); } // pr121385 boolean x = this.getDeclaringAspect().resolve(world).isAnnotationStyleAspect(); final boolean isAnnotationStyleAspect = getConcreteAspect()!=null && getConcreteAspect().isAnnotationStyleAspect() && x; boolean previousIsClosure = false; for (int i = 0, len = exposedState.size(); i < len; i++) { if (exposedState.isErroneousVar(i)) continue; // Erroneous vars have already had error msgs reported! BcelVar v = (BcelVar) exposedState.get(i); if (v == null) { // if not @AJ aspect, go on with the regular binding handling if (!isAnnotationStyleAspect) { ; } else { // ATAJ: for @AJ aspects, handle implicit binding of xxJoinPoint //if (getKind() == AdviceKind.Around) { // previousIsClosure = true; // il.append(closureInstantiation); if ("Lorg/aspectj/lang/ProceedingJoinPoint;".equals(getSignature().getParameterTypes()[i].getSignature())) { //make sure we are in an around, since we deal with the closure, not the arg here if (getKind() != AdviceKind.Around) { previousIsClosure = false; getConcreteAspect().getWorld().getMessageHandler().handleMessage( new Message( "use of ProceedingJoinPoint is allowed only on around advice (" + "arg " + i + " in " + toString() + ")", this.getSourceLocation(), true ) ); // try to avoid verify error and pass in null il.append(InstructionConstants.ACONST_NULL); } else { if (previousIsClosure) { il.append(InstructionConstants.DUP); } else { previousIsClosure = true; il.append(closureInstantiation.copy()); } } } else if ("Lorg/aspectj/lang/JoinPoint$StaticPart;".equals(getSignature().getParameterTypes()[i].getSignature())) { previousIsClosure = false; if ((getExtraParameterFlags() & ThisJoinPointStaticPart) != 0) { shadow.getThisJoinPointStaticPartBcelVar().appendLoad(il, fact); } } else if ("Lorg/aspectj/lang/JoinPoint;".equals(getSignature().getParameterTypes()[i].getSignature())) { previousIsClosure = false; if ((getExtraParameterFlags() & ThisJoinPoint) != 0) { il.append(shadow.loadThisJoinPoint()); } } else if ("Lorg/aspectj/lang/JoinPoint$EnclosingStaticPart;".equals(getSignature().getParameterTypes()[i].getSignature())) { previousIsClosure = false; if ((getExtraParameterFlags() & ThisEnclosingJoinPointStaticPart) != 0) { shadow.getThisEnclosingJoinPointStaticPartBcelVar().appendLoad(il, fact); } } else if (hasExtraParameter()) { previousIsClosure = false; extraVar.appendLoadAndConvert( il, fact, getExtraParameterType().resolve(world)); } else { previousIsClosure = false; getConcreteAspect().getWorld().getMessageHandler().handleMessage( new Message( "use of ProceedingJoinPoint is allowed only on around advice (" + "arg " + i + " in " + toString() + ")", this.getSourceLocation(), true ) ); // try to avoid verify error and pass in null il.append(InstructionConstants.ACONST_NULL); } } } else { UnresolvedType desiredTy = getBindingParameterTypes()[i]; v.appendLoadAndConvert(il, fact, desiredTy.resolve(world)); } } // ATAJ: for code style aspect, handles the extraFlag as usual ie not // in the middle of the formal bindings but at the end, in a rock solid ordering if (!isAnnotationStyleAspect) { if (getKind() == AdviceKind.Around) { il.append(closureInstantiation); } else if (hasExtraParameter()) { extraVar.appendLoadAndConvert( il, fact, getExtraParameterType().resolve(world)); } // handle thisJoinPoint parameters // these need to be in that same order as parameters in // org.aspectj.ajdt.internal.compiler.ast.AdviceDeclaration if ((getExtraParameterFlags() & ThisJoinPointStaticPart) != 0) { shadow.getThisJoinPointStaticPartBcelVar().appendLoad(il, fact); } if ((getExtraParameterFlags() & ThisJoinPoint) != 0) { il.append(shadow.loadThisJoinPoint()); } if ((getExtraParameterFlags() & ThisEnclosingJoinPointStaticPart) != 0) { shadow.getThisEnclosingJoinPointStaticPartBcelVar().appendLoad(il, fact); } } return il; } public InstructionList getNonTestAdviceInstructions(BcelShadow shadow) { return new InstructionList( Utility.createInvoke(shadow.getFactory(), shadow.getWorld(), getOriginalSignature())); } public Member getOriginalSignature() { Member sig = getSignature(); if (sig instanceof ResolvedMember) { ResolvedMember rsig = (ResolvedMember)sig; if (rsig.hasBackingGenericMember()) return rsig.getBackingGenericMember(); } return sig; } public InstructionList getTestInstructions( BcelShadow shadow, InstructionHandle sk, InstructionHandle fk, InstructionHandle next) { //System.err.println("test: " + pointcutTest); return BcelRenderer.renderTest( shadow.getFactory(), shadow.getWorld(), pointcutTest, sk, fk, next); } public int compareTo(Object other) { if (!(other instanceof BcelAdvice)) return 0; BcelAdvice o = (BcelAdvice)other; //System.err.println("compareTo: " + this + ", " + o); if (kind.getPrecedence() != o.kind.getPrecedence()) { if (kind.getPrecedence() > o.kind.getPrecedence()) return +1; else return -1; } if (kind.isCflow()) { // System.err.println("sort: " + this + " innerCflowEntries " + innerCflowEntries); // System.err.println(" " + o + " innerCflowEntries " + o.innerCflowEntries); boolean isBelow = (kind == AdviceKind.CflowBelowEntry); if (this.innerCflowEntries.contains(o)) return isBelow ? +1 : -1; else if (o.innerCflowEntries.contains(this)) return isBelow ? -1 : +1; else return 0; } if (kind.isPerEntry() || kind == AdviceKind.Softener) { return 0; } //System.out.println("compare: " + this + " with " + other); World world = concreteAspect.getWorld(); int ret = concreteAspect.getWorld().compareByPrecedence( concreteAspect, o.concreteAspect); if (ret != 0) return ret; ResolvedType declaringAspect = getDeclaringAspect().resolve(world); ResolvedType o_declaringAspect = o.getDeclaringAspect().resolve(world); if (declaringAspect == o_declaringAspect) { if (kind.isAfter() || o.kind.isAfter()) { return this.getStart() < o.getStart() ? -1: +1; } else { return this.getStart()< o.getStart() ? +1: -1; } } else if (declaringAspect.isAssignableFrom(o_declaringAspect)) { return -1; } else if (o_declaringAspect.isAssignableFrom(declaringAspect)) { return +1; } else { return 0; } } public BcelVar[] getExposedStateAsBcelVars(boolean isAround) { // ATAJ aspect if (isAround) { // the closure instantiation has the same mapping as the extracted method from wich it is called if (getConcreteAspect()!= null && getConcreteAspect().isAnnotationStyleAspect()) { return BcelVar.NONE; } } //System.out.println("vars: " + Arrays.asList(exposedState.vars)); if (exposedState == null) return BcelVar.NONE; int len = exposedState.vars.length; BcelVar[] ret = new BcelVar[len]; for (int i=0; i < len; i++) { ret[i] = (BcelVar)exposedState.vars[i]; } return ret; //(BcelVar[]) exposedState.vars; } public boolean hasMatchedSomething() { return hasMatchedAtLeastOnce; } public void setHasMatchedSomething(boolean hasMatchedSomething) { hasMatchedAtLeastOnce = hasMatchedSomething; } protected void suppressLintWarnings(World inWorld) { if (suppressedLintKinds == null) { if (signature instanceof BcelMethod) { this.suppressedLintKinds = Utility.getSuppressedWarnings(signature.getAnnotations(), inWorld.getLint()); } else { this.suppressedLintKinds = Collections.EMPTY_LIST; } } inWorld.getLint().suppressKinds(suppressedLintKinds); } protected void clearLintSuppressions(World inWorld,Collection toClear) { inWorld.getLint().clearSuppressions(toClear); } }
160,496
Bug 160496 ajdoc Main class needs refactoring for ease of use
Whilst looking at other ajdoc bugs it was slightly confusing to read the main ajdoc method. I didn't want to include the refactoring of this within patches for the other bugs as this is mearly for ease of use. Therefore, raising this enhancement to cover it.
resolved fixed
efe6cc7
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2006-10-23T10:39:38Z"
"2006-10-11T15:20:00Z"
ajdoc/src/org/aspectj/tools/ajdoc/Main.java
/* ******************************************************************* * Copyright (c) 1999-2001 Xerox Corporation, * 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the 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 * Mik Kersten port to AspectJ 1.1+ code base * ******************************************************************/ package org.aspectj.tools.ajdoc; import java.io.*; import java.util.*; import java.io.FileFilter; import org.aspectj.bridge.Version; import org.aspectj.util.FileUtil; /** * This is an old implementation of ajdoc that does not use an OO style. However, it * does the job, and should serve to evolve a lightweight ajdoc implementation until * we can make a properly extended javadoc implementation. * * @author Mik Kersten */ public class Main implements Config { private static final String FAIL_MESSAGE = "> compile failed, exiting ajdoc"; /** Command line options. */ static Vector options; /** Options to pass to ajc. */ static Vector ajcOptions; /** All of the files to be processed by ajdoc. */ static Vector filenames; /** List of files to pass to javadoc. */ static Vector fileList; /** List of packages to pass to javadoc. */ static Vector packageList; /** Default to package visiblity. */ static String docModifier = "package"; static Vector sourcepath; static boolean verboseMode = false; static boolean packageMode = false; static boolean authorStandardDocletSwitch = false; static boolean versionStandardDocletSwitch = false; static File rootDir = null; static Hashtable declIDTable = new Hashtable(); static String docDir = "."; private static boolean deleteTempFilesOnExit = true; private static boolean aborted = false; // creating a local variable to enable us to create the ajdocworkingdir // in a local sandbox during testing private static String outputWorkingDir = Config.WORKING_DIR; public static void clearState() { options = new Vector(); ajcOptions = new Vector(); filenames = new Vector(); fileList= new Vector(); packageList = new Vector(); docModifier = "package"; sourcepath = new Vector(); verboseMode = false; packageMode = false; rootDir = null; declIDTable = new Hashtable(); docDir = "."; aborted = false; deleteTempFilesOnExit = true; } public static void main(String[] args) { clearState(); if (!JavadocRunner.has14ToolsAvailable()) { System.err.println("ajdoc requires a JDK 1.4 or later tools jar - exiting"); aborted = true; return; } // STEP 1: parse the command line and do other global setup sourcepath.addElement("."); // add the current directory to the classapth parseCommandLine(args); rootDir = getRootDir(); File[] inputFiles = new File[filenames.size()]; File[] signatureFiles = new File[filenames.size()]; try { // create the workingdir if it doesn't exist if ( !(new File( outputWorkingDir ).isDirectory()) ) { File dir = new File( outputWorkingDir ); dir.mkdir(); if (deleteTempFilesOnExit) dir.deleteOnExit(); } for (int i = 0; i < filenames.size(); i++) { inputFiles[i] = new File((String)filenames.elementAt(i)); //signatureFiles[i] = createSignatureFile(inputFiles[i]); } // PHASE 0: call ajc ajcOptions.addElement("-noExit"); ajcOptions.addElement("-XjavadocsInModel"); // TODO: wrong option to force model gen ajcOptions.addElement("-d"); ajcOptions.addElement(rootDir.getAbsolutePath()); String[] argsToCompiler = new String[ajcOptions.size() + inputFiles.length]; int i = 0; for ( ; i < ajcOptions.size(); i++ ) { argsToCompiler[i] = (String)ajcOptions.elementAt(i); } for ( int j = 0; j < inputFiles.length; j++) { argsToCompiler[i] = inputFiles[j].getAbsolutePath(); //System.out.println(">> file to ajc: " + inputFiles[j].getAbsolutePath()); i++; } // System.out.println(Arrays.asList(argsToCompiler)); System.out.println( "> Calling ajc..." ); CompilerWrapper.main(argsToCompiler); if (CompilerWrapper.hasErrors()) { System.out.println(FAIL_MESSAGE); aborted = true; return; } /* for (int ii = 0; ii < inputFiles.length; ii++) { String tempFP = inputFiles[ii].getAbsolutePath(); tempFP = tempFP.substring(0, tempFP.length()-4); tempFP += "ajsym"; System.out.println( ">> checking: " + tempFP); File tempF = new File(tempFP); if ( !tempF.exists() ) System.out.println( ">>> doesn't exist!" ); } */ for (int ii = 0; ii < filenames.size(); ii++) { signatureFiles[ii] = createSignatureFile(inputFiles[ii]); } // PHASE 1: generate Signature files (Java with DeclIDs and no bodies). System.out.println( "> Building signature files..." ); try{ StubFileGenerator.doFiles(declIDTable, inputFiles, signatureFiles); } catch (DocException d){ System.err.println(d.getMessage()); // d.printStackTrace(); return; } // PHASE 2: let Javadoc generate HTML (with DeclIDs) System.out.println( "> Calling javadoc..." ); String[] javadocargs = null; if ( packageMode ) { int numExtraArgs = 2; if (authorStandardDocletSwitch) numExtraArgs++; if (versionStandardDocletSwitch) numExtraArgs++; javadocargs = new String[numExtraArgs + options.size() + packageList.size() + fileList.size() ]; javadocargs[0] = "-sourcepath"; javadocargs[1] = outputWorkingDir; int argIndex = 2; if (authorStandardDocletSwitch) { javadocargs[argIndex] = "-author"; argIndex++; } if (versionStandardDocletSwitch) { javadocargs[argIndex] = "-version"; } //javadocargs[1] = getSourcepathAsString(); for (int k = 0; k < options.size(); k++) { javadocargs[numExtraArgs+k] = (String)options.elementAt(k); } for (int k = 0; k < packageList.size(); k++) { javadocargs[numExtraArgs+options.size() + k] = (String)packageList.elementAt(k); } for (int k = 0; k < fileList.size(); k++) { javadocargs[numExtraArgs+options.size() + packageList.size() + k] = (String)fileList.elementAt(k); } } else { javadocargs = new String[options.size() + signatureFiles.length]; for (int k = 0; k < options.size(); k++) { javadocargs[k] = (String)options.elementAt(k); } for (int k = 0; k < signatureFiles.length; k++) { javadocargs[options.size() + k] = StructureUtil.translateAjPathName(signatureFiles[k].getCanonicalPath()); } } JavadocRunner.callJavadoc(javadocargs); //for ( int o = 0; o < inputFiles.length; o++ ) { // System.out.println( "file: " + inputFiles[o] ); //} // PHASE 3: add AspectDoc specific stuff to the HTML (and remove the DeclIDS). /** We start with the known HTML files (the ones that correspond directly to the * input files.) As we go along, we may learn that Javadoc split one .java file * into multiple .html files to handle inner classes or local classes. The html * file decorator picks that up. */ System.out.println( "> Decorating html files..." ); HtmlDecorator.decorateHTMLFromInputFiles(declIDTable, rootDir, inputFiles, docModifier); System.out.println( "> Removing generated tags (this may take a while)..." ); removeDeclIDsFromFile("index-all.html", true); removeDeclIDsFromFile("serialized-form.html", true); if (packageList.size() > 0) { for (int p = 0; p < packageList.size(); p++) { removeDeclIDsFromFile(((String)packageList.elementAt(p)).replace('.','/') + Config.DIR_SEP_CHAR + "package-summary.html", true); } } else { File[] files = rootDir.listFiles(); if (files == null){ System.err.println("Destination directory is not a directory: " + rootDir.toString()); return; } files = FileUtil.listFiles(rootDir, new FileFilter() { public boolean accept(File f) { return f.getName().equals("package-summary.html"); } }); for (int j = 0; j < files.length; j++) { removeDeclIDsFromFile(files[j].getAbsolutePath(), false); } } System.out.println( "> Finished." ); } catch (Throwable e) { handleInternalError(e); exit(-2); } } private static void removeDeclIDsFromFile(String filename, boolean relativePath) { // Remove the decl ids from "index-all.html" File indexFile; if (relativePath) { indexFile = new File(docDir + Config.DIR_SEP_CHAR + filename); } else { indexFile = new File(filename); } try { if ( indexFile.exists() ) { BufferedReader indexFileReader = new BufferedReader( new FileReader( indexFile ) ); String indexFileBuffer = ""; String line = indexFileReader.readLine(); while ( line != null ) { int indexStart = line.indexOf( Config.DECL_ID_STRING ); int indexEnd = line.indexOf( Config.DECL_ID_TERMINATOR ); if ( indexStart != -1 && indexEnd != -1 ) { line = line.substring( 0, indexStart ) + line.substring( indexEnd+Config.DECL_ID_TERMINATOR.length() ); } indexFileBuffer += line; line = indexFileReader.readLine(); } FileOutputStream fos = new FileOutputStream( indexFile ); fos.write( indexFileBuffer.getBytes() ); indexFileReader.close(); fos.close(); } } catch (IOException ioe) { // be siltent } } static Vector getSourcePath() { Vector sourcePath = new Vector(); boolean found = false; for ( int i = 0; i < options.size(); i++ ) { String currOption = (String)options.elementAt(i); if (found && !currOption.startsWith("-")) { sourcePath.add(currOption); } if (currOption.equals("-sourcepath")) { found = true; } } return sourcePath; } static File getRootDir() { File rootDir = new File( "." ); for ( int i = 0; i < options.size(); i++ ) { if ( ((String)options.elementAt(i)).equals( "-d" ) ) { rootDir = new File((String)options.elementAt(i+1)); if ( !rootDir.exists() ) { rootDir.mkdir(); // System.out.println( "Destination directory not found: " + // (String)options.elementAt(i+1) ); // System.exit( -1 ); } } } return rootDir; } static File createSignatureFile(File inputFile) throws IOException { String packageName = StructureUtil.getPackageDeclarationFromFile(inputFile); String filename = ""; if ( packageName != null ) { String pathName = outputWorkingDir + '/' + packageName.replace('.', '/'); File packageDir = new File(pathName); if ( !packageDir.exists() ) { packageDir.mkdirs(); if (deleteTempFilesOnExit) packageDir.deleteOnExit(); } //verifyPackageDirExists(packageName, null); packageName = packageName.replace( '.','/' ); // !!! filename = outputWorkingDir + Config.DIR_SEP_CHAR + packageName + Config.DIR_SEP_CHAR + inputFile.getName(); } else { filename = outputWorkingDir + Config.DIR_SEP_CHAR + inputFile.getName(); } File signatureFile = new File( filename ); if (deleteTempFilesOnExit) signatureFile.deleteOnExit(); return signatureFile; } // static void verifyPackageDirExists( String packageName, String offset ) { // System.err.println(">>> name: " + packageName + ", offset: " + offset); // if ( packageName.indexOf( "." ) != -1 ) { // File tempFile = new File("c:/aspectj-test/d1/d2/d3"); // tempFile.mkdirs(); // String currPkgDir = packageName.substring( 0, packageName.indexOf( "." ) ); // String remainingPkg = packageName.substring( packageName.indexOf( "." )+1 ); // String filePath = null; // if ( offset != null ) { // filePath = Config.WORKING_DIR + Config.DIR_SEP_CHAR + // offset + Config.DIR_SEP_CHAR + currPkgDir ; // } // else { // filePath = Config.WORKING_DIR + Config.DIR_SEP_CHAR + currPkgDir; // } // File packageDir = new File( filePath ); // if ( !packageDir.exists() ) { // packageDir.mkdir(); // if (deleteTempFilesOnExit) packageDir.deleteOnExit(); // } // if ( remainingPkg != "" ) { // verifyPackageDirExists( remainingPkg, currPkgDir ); // } // } // else { // String filePath = null; // if ( offset != null ) { // filePath = Config.WORKING_DIR + Config.DIR_SEP_CHAR + offset + Config.DIR_SEP_CHAR + packageName; // } // else { // filePath = Config.WORKING_DIR + Config.DIR_SEP_CHAR + packageName; // } // File packageDir = new File( filePath ); // if ( !packageDir.exists() ) { // packageDir.mkdir(); // if (deleteTempFilesOnExit) packageDir.deleteOnExit(); // } // } // } /** * Can read Eclipse-generated single-line arg */ static void parseCommandLine(String[] args) { if (args.length == 0) { displayHelpAndExit( null ); } else if (args.length == 1 && args[0].startsWith("@")) { String argFile = args[0].substring(1); System.out.println("> Using arg file: " + argFile); BufferedReader br; try { br = new BufferedReader(new FileReader(argFile)); String line = ""; line = br.readLine(); StringTokenizer st = new StringTokenizer(line, " "); List argList = new ArrayList(); while(st.hasMoreElements()) { argList.add((String)st.nextElement()); } //System.err.println(argList); args = new String[argList.size()]; int counter = 0; for (Iterator it = argList.iterator(); it.hasNext(); ) { args[counter] = (String)it.next(); counter++; } } catch (FileNotFoundException e) { System.err.println("> could not read arg file: " + argFile); e.printStackTrace(); } catch (IOException ioe) { System.err.println("> could not read arg file: " + argFile); ioe.printStackTrace(); } } List vargs = new LinkedList(Arrays.asList(args)); parseArgs(vargs, new File( "." )); // !!! if (filenames.size() == 0) { displayHelpAndExit( "ajdoc: No packages or classes specified" ); } } static void setSourcepath(String arg) { sourcepath.clear(); arg = arg + File.pathSeparator; // makes things easier for ourselves StringTokenizer tokenizer = new StringTokenizer(arg, File.pathSeparator); while (tokenizer.hasMoreElements()) { sourcepath.addElement(tokenizer.nextElement()); } } static String getSourcepathAsString() { String cPath = ""; for (int i = 0; i < sourcepath.size(); i++) { cPath += (String)sourcepath.elementAt(i) + Config.DIR_SEP_CHAR + outputWorkingDir; if (i != sourcepath.size()-1) { cPath += File.pathSeparator; } } return cPath; } static void parseArgs(List vargs, File currentWorkingDir) { boolean addNextAsOption = false; boolean addNextAsArgFile = false; boolean addNextToAJCOptions = false; boolean addNextAsDocDir = false; boolean addNextAsClasspath = false; boolean ignoreArg = false; // used for discrepancy betwen class/sourcepath in ajc/javadoc boolean addNextAsSourcePath = false; if ( vargs.size() == 0 ) { displayHelpAndExit( null ); } for (int i = 0; i < vargs.size() ; i++) { String arg = (String)vargs.get(i); ignoreArg = false; if ( addNextToAJCOptions ) { ajcOptions.addElement( arg ); addNextToAJCOptions = false; } if ( addNextAsDocDir ) { docDir = arg; addNextAsDocDir = false; } if ( addNextAsClasspath ) { addNextAsClasspath = false; } if ( addNextAsSourcePath ) { setSourcepath( arg ); addNextAsSourcePath = false; ignoreArg = true; } if ( arg.startsWith("@") ) { expandAtSignFile(arg.substring(1), currentWorkingDir); } else if ( arg.equals( "-argfile" ) ) { addNextAsArgFile = true; } else if ( addNextAsArgFile ) { expandAtSignFile(arg, currentWorkingDir); addNextAsArgFile = false; } else if (arg.equals("-d") ) { addNextAsOption = true; options.addElement(arg); addNextAsDocDir = true; } else if ( arg.equals( "-bootclasspath" ) ) { addNextAsOption = true; addNextToAJCOptions = true; options.addElement( arg ); ajcOptions.addElement( arg ); } else if ( arg.equals( "-source" ) ) { addNextAsOption = true; addNextToAJCOptions = true; addNextAsClasspath = true; options.addElement(arg); ajcOptions.addElement(arg); } else if ( arg.equals( "-classpath" ) ) { addNextAsOption = true; addNextToAJCOptions = true; addNextAsClasspath = true; options.addElement( arg ); ajcOptions.addElement( arg ); } else if ( arg.equals( "-encoding" ) ) { addNextAsOption = true; addNextToAJCOptions = false; options.addElement( arg ); } else if ( arg.equals( "-docencoding" ) ) { addNextAsOption = true; addNextToAJCOptions = false; options.addElement( arg ); } else if ( arg.equals( "-charset" ) ) { addNextAsOption = true; addNextToAJCOptions = false; options.addElement( arg ); } else if ( arg.equals( "-sourcepath" ) ) { addNextAsSourcePath = true; //options.addElement( arg ); //ajcOptions.addElement( arg ); } else if (arg.equals("-XajdocDebug")) { deleteTempFilesOnExit = false; } else if (arg.equals("-use")) { System.out.println("> Ignoring unsupported option: -use"); } else if (arg.equals("-splitindex")) { // passed to javadoc } else if (arg.startsWith("-") || addNextAsOption) { if ( arg.equals( "-private" ) ) { docModifier = "private"; }else if ( arg.equals( "-package" ) ) { docModifier = "package"; } else if ( arg.equals( "-protected" ) ) { docModifier = "protected"; } else if ( arg.equals( "-public" ) ) { docModifier = "public"; } else if ( arg.equals( "-verbose" ) ) { verboseMode = true; } else if ( arg.equals( "-author" ) ) { authorStandardDocletSwitch = true; } else if ( arg.equals( "-version" ) ) { versionStandardDocletSwitch = true; } else if ( arg.equals( "-v" ) ) { System.out.println(getVersion()); exit(0); } else if ( arg.equals( "-help" ) ) { displayHelpAndExit( null ); } else if ( arg.equals( "-doclet" ) || arg.equals( "-docletpath" ) ) { System.out.println( "The doclet and docletpath options are not currently supported \n" + "since ajdoc makes assumptions about the behavior of the standard \n" + "doclet. If you would find this option useful please email us at: \n" + " \n" + " aspectj-dev@eclipse.org \n" + " \n" ); exit(0); } else if (arg.equals("-nonavbar") || arg.equals("-noindex")) { // pass through //System.err.println("> ignoring unsupported option: " + arg); } else if ( addNextAsOption ) { // pass through } else { System.err.println("> unrecognized argument: " + arg); displayHelpAndExit( null ); } options.addElement(arg); addNextAsOption = false; } else { // check if this is a file or a package // System.err.println(">>>>>>>> " + ); // String entryName = arg.substring(arg.lastIndexOf(File.separator)+1); if (FileUtil.hasSourceSuffix(arg) || arg.endsWith(".lst") && arg != null ) { File f = new File(arg); if (f.isAbsolute()) { filenames.addElement(arg); } else { filenames.addElement( currentWorkingDir + Config.DIR_SEP_CHAR + arg ); } fileList.addElement( arg ); } // PACKAGE MODE STUFF else if (!ignoreArg) { packageMode = true; packageList.addElement( arg ); arg = arg.replace( '.', '/' ); // !!! // do this for every item in the classpath for ( int c = 0; c < sourcepath.size(); c++ ) { String path = (String)sourcepath.elementAt(c) + Config.DIR_SEP_CHAR + arg; File pkg = new File(path); if ( pkg.isDirectory() ) { String[] files = pkg.list( new FilenameFilter() { public boolean accept( File dir, String name ) { int index1 = name.lastIndexOf( "." ); int index2 = name.length(); if ( (index1 >= 0 && index2 >= 0 ) && (name.substring(index1, index2).equals( ".java" ) || name.substring(index1, index2).equals( ".aj" ))) { return true; } else { return false; } } } ); for ( int j = 0; j < files.length; j++ ) { filenames.addElement( (String)sourcepath.elementAt(c) + Config.DIR_SEP_CHAR + arg + Config.DIR_SEP_CHAR + files[j] ); } } else if (c == sourcepath.size() ) { // last element on classpath System.out.println( "ajdoc: No package, class, or source file " + "found named " + arg + "." ); } else { // didn't find it on that element of the classpath but that's ok } } } } } // set the default visibility as an option to javadoc option if ( !options.contains( "-private" ) && !options.contains( "-package" ) && !options.contains( "-protected" ) && !options.contains( "-public" ) ) { options.addElement( "-package" ); } } static void expandAtSignFile(String filename, File currentWorkingDir) { List result = new LinkedList(); File atFile = qualifiedFile(filename, currentWorkingDir); String atFileParent = atFile.getParent(); File myWorkingDir = null; if (atFileParent != null) myWorkingDir = new File(atFileParent); try { BufferedReader stream = new BufferedReader(new FileReader(atFile)); String line = null; while ( (line = stream.readLine()) != null) { // strip out any comments of the form # to end of line int commentStart = line.indexOf("//"); if (commentStart != -1) { line = line.substring(0, commentStart); } // remove extra whitespace that might have crept in line = line.trim(); // ignore blank lines if (line.length() == 0) continue; result.add(line); } } catch (IOException e) { System.err.println("Error while reading the @ file " + atFile.getPath() + ".\n" + e); System.exit( -1 ); } parseArgs(result, myWorkingDir); } static File qualifiedFile(String name, File currentWorkingDir) { name = name.replace('/', File.separatorChar); File file = new File(name); if (!file.isAbsolute() && currentWorkingDir != null) { file = new File(currentWorkingDir, name); } return file; } static void displayHelpAndExit(String message) { if (message != null) { System.err.println(message); System.err.println(); System.err.println(Config.USAGE); } else { System.out.println(Config.USAGE); exit(0); } } static protected void exit(int value) { System.out.flush(); System.err.flush(); System.exit(value); } /* This section of code handles errors that occur during compilation */ static final String internalErrorMessage = " \n"+ "If this has not already been logged as a bug raised please raise \n"+ "a new AspectJ bug at https://bugs.eclipse.org/bugs including the \n"+ "text below. To make the bug a priority, please also include a test\n"+ "program that can reproduce this problem.\n "; static public void handleInternalError(Throwable uncaughtThrowable) { System.err.println("An internal error occured in ajdoc"); System.err.println(internalErrorMessage); System.err.println(uncaughtThrowable.toString()); uncaughtThrowable.printStackTrace(); System.err.println(); } static String getVersion() { return "ajdoc version " + Version.text; } public static boolean hasAborted() { return aborted; } /** * Sets the output working dir to be <fullyQualifiedOutputDir>\ajdocworkingdir * Useful in testing to redirect the ajdocworkingdir to the sandbox */ public static void setOutputWorkingDir(String fullyQulifiedOutputDir) { if (fullyQulifiedOutputDir == null) { resetOutputWorkingDir(); } else { outputWorkingDir = fullyQulifiedOutputDir + File.separatorChar + Config.WORKING_DIR; } } /** * Resets the output working dir to be the default which is * <the current directory>\ajdocworkingdir */ public static void resetOutputWorkingDir() { outputWorkingDir = Config.WORKING_DIR; } }
149,908
Bug 149908 NPE in org.aspectj.weaver.MemberImpl.getModifiers(MemberImpl.java:526)
java.lang.NullPointerException at org.aspectj.weaver.MemberImpl.getModifiers(MemberImpl.java:526) at org.aspectj.weaver.MemberImpl.getMethodSignatureString(MemberImpl.java:824) at org.aspectj.weaver.MemberImpl.getSignatureString(MemberImpl.java:753) at org.aspectj.weaver.bcel.LazyClassGen.initializeTjp(LazyClassGen.java:1039) at org.aspectj.weaver.bcel.LazyClassGen.initializeAllTjps(LazyClassGen.java:1016) at org.aspectj.weaver.bcel.LazyClassGen.addAjcInitializers(LazyClassGen.java:964) at org.aspectj.weaver.bcel.LazyClassGen.writeBack(LazyClassGen.java:502) at org.aspectj.weaver.bcel.LazyClassGen.getJavaClassBytesIncludingReweavable(LazyClassGen.java:652) at org.aspectj.weaver.bcel.BcelWeaver.getClassFilesFor(BcelWeaver.java:1337) at org.aspectj.weaver.bcel.BcelWeaver.weaveAndNotify(BcelWeaver.java:1309) at org.aspectj.weaver.bcel.BcelWeaver.weave(BcelWeaver.java:1127) at org.aspectj.weaver.tools.WeavingAdaptor.getWovenBytes(WeavingAdaptor.java:284) at org.aspectj.weaver.tools.WeavingAdaptor.weaveClass(WeavingAdaptor.java:212) at org.aspectj.weaver.loadtime.WeavingURLClassLoader.defineClass(WeavingURLClassLoader.java:125) at org.aspectj.weaver.ExtensibleURLClassLoader.defineClass(ExtensibleURLClassLoader.java:80) at org.aspectj.weaver.ExtensibleURLClassLoader.findClass(ExtensibleURLClassLoader.java:46) at java.lang.ClassLoader.loadClass(ClassLoader.java:306) at java.lang.ClassLoader.loadClass(ClassLoader.java:251) at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:319) Exception in thread "main" public aspect JoinPointTraceAspect { private int _callDepth = -1; pointcut tracePoints() : !within(JoinPointTraceAspect); before() : tracePoints() { _callDepth++; print("Before", thisJoinPoint); } after() : tracePoints() { print("After", thisJoinPoint); _callDepth--; } private void print(String prefix, Object message) { for(int i = 0, spaces = _callDepth * 2; i < spaces; i++) { System.out.print(" "); } System.out.println(prefix + ": " + message); } } aspect EdtRuleChecker { private boolean isStressChecking = true; public pointcut anySwingMethods(JComponent c): target(c) && call(* *(..)); public pointcut threadSafeMethods(): call(* repaint(..)) || call(* revalidate()) || call(* invalidate()) || call(* getListeners(..)) || call(* add*Listener(..)) || call(* remove*Listener(..)); //calls of any JComponent method, including subclasses before(JComponent c): anySwingMethods(c) && !threadSafeMethods() && !within(EdtRuleChecker) { if(!SwingUtilities.isEventDispatchThread() && (isStressChecking || c.isShowing())) { System.err.println(thisJoinPoint.getSourceLocation()); System.err.println(thisJoinPoint.getSignature()); System.err.println(); } } //calls of any JComponent constructor, including subclasses before(): call(JComponent+.new(..)) { if (isStressChecking && !SwingUtilities.isEventDispatchThread()) { System.err.println(thisJoinPoint.getSourceLocation()); System.err.println(thisJoinPoint.getSignature() + " *constructor*"); System.err.println(); } } } Running with SwingSet2.
resolved fixed
757004c
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2006-10-23T11:55:54Z"
"2006-07-06T21:06:40Z"
tests/bugs153/pr149908/C.java
149,908
Bug 149908 NPE in org.aspectj.weaver.MemberImpl.getModifiers(MemberImpl.java:526)
java.lang.NullPointerException at org.aspectj.weaver.MemberImpl.getModifiers(MemberImpl.java:526) at org.aspectj.weaver.MemberImpl.getMethodSignatureString(MemberImpl.java:824) at org.aspectj.weaver.MemberImpl.getSignatureString(MemberImpl.java:753) at org.aspectj.weaver.bcel.LazyClassGen.initializeTjp(LazyClassGen.java:1039) at org.aspectj.weaver.bcel.LazyClassGen.initializeAllTjps(LazyClassGen.java:1016) at org.aspectj.weaver.bcel.LazyClassGen.addAjcInitializers(LazyClassGen.java:964) at org.aspectj.weaver.bcel.LazyClassGen.writeBack(LazyClassGen.java:502) at org.aspectj.weaver.bcel.LazyClassGen.getJavaClassBytesIncludingReweavable(LazyClassGen.java:652) at org.aspectj.weaver.bcel.BcelWeaver.getClassFilesFor(BcelWeaver.java:1337) at org.aspectj.weaver.bcel.BcelWeaver.weaveAndNotify(BcelWeaver.java:1309) at org.aspectj.weaver.bcel.BcelWeaver.weave(BcelWeaver.java:1127) at org.aspectj.weaver.tools.WeavingAdaptor.getWovenBytes(WeavingAdaptor.java:284) at org.aspectj.weaver.tools.WeavingAdaptor.weaveClass(WeavingAdaptor.java:212) at org.aspectj.weaver.loadtime.WeavingURLClassLoader.defineClass(WeavingURLClassLoader.java:125) at org.aspectj.weaver.ExtensibleURLClassLoader.defineClass(ExtensibleURLClassLoader.java:80) at org.aspectj.weaver.ExtensibleURLClassLoader.findClass(ExtensibleURLClassLoader.java:46) at java.lang.ClassLoader.loadClass(ClassLoader.java:306) at java.lang.ClassLoader.loadClass(ClassLoader.java:251) at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:319) Exception in thread "main" public aspect JoinPointTraceAspect { private int _callDepth = -1; pointcut tracePoints() : !within(JoinPointTraceAspect); before() : tracePoints() { _callDepth++; print("Before", thisJoinPoint); } after() : tracePoints() { print("After", thisJoinPoint); _callDepth--; } private void print(String prefix, Object message) { for(int i = 0, spaces = _callDepth * 2; i < spaces; i++) { System.out.print(" "); } System.out.println(prefix + ": " + message); } } aspect EdtRuleChecker { private boolean isStressChecking = true; public pointcut anySwingMethods(JComponent c): target(c) && call(* *(..)); public pointcut threadSafeMethods(): call(* repaint(..)) || call(* revalidate()) || call(* invalidate()) || call(* getListeners(..)) || call(* add*Listener(..)) || call(* remove*Listener(..)); //calls of any JComponent method, including subclasses before(JComponent c): anySwingMethods(c) && !threadSafeMethods() && !within(EdtRuleChecker) { if(!SwingUtilities.isEventDispatchThread() && (isStressChecking || c.isShowing())) { System.err.println(thisJoinPoint.getSourceLocation()); System.err.println(thisJoinPoint.getSignature()); System.err.println(); } } //calls of any JComponent constructor, including subclasses before(): call(JComponent+.new(..)) { if (isStressChecking && !SwingUtilities.isEventDispatchThread()) { System.err.println(thisJoinPoint.getSourceLocation()); System.err.println(thisJoinPoint.getSignature() + " *constructor*"); System.err.println(); } } } Running with SwingSet2.
resolved fixed
757004c
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2006-10-23T11:55:54Z"
"2006-07-06T21:06:40Z"
tests/bugs153/pr149908/C1.java
149,908
Bug 149908 NPE in org.aspectj.weaver.MemberImpl.getModifiers(MemberImpl.java:526)
java.lang.NullPointerException at org.aspectj.weaver.MemberImpl.getModifiers(MemberImpl.java:526) at org.aspectj.weaver.MemberImpl.getMethodSignatureString(MemberImpl.java:824) at org.aspectj.weaver.MemberImpl.getSignatureString(MemberImpl.java:753) at org.aspectj.weaver.bcel.LazyClassGen.initializeTjp(LazyClassGen.java:1039) at org.aspectj.weaver.bcel.LazyClassGen.initializeAllTjps(LazyClassGen.java:1016) at org.aspectj.weaver.bcel.LazyClassGen.addAjcInitializers(LazyClassGen.java:964) at org.aspectj.weaver.bcel.LazyClassGen.writeBack(LazyClassGen.java:502) at org.aspectj.weaver.bcel.LazyClassGen.getJavaClassBytesIncludingReweavable(LazyClassGen.java:652) at org.aspectj.weaver.bcel.BcelWeaver.getClassFilesFor(BcelWeaver.java:1337) at org.aspectj.weaver.bcel.BcelWeaver.weaveAndNotify(BcelWeaver.java:1309) at org.aspectj.weaver.bcel.BcelWeaver.weave(BcelWeaver.java:1127) at org.aspectj.weaver.tools.WeavingAdaptor.getWovenBytes(WeavingAdaptor.java:284) at org.aspectj.weaver.tools.WeavingAdaptor.weaveClass(WeavingAdaptor.java:212) at org.aspectj.weaver.loadtime.WeavingURLClassLoader.defineClass(WeavingURLClassLoader.java:125) at org.aspectj.weaver.ExtensibleURLClassLoader.defineClass(ExtensibleURLClassLoader.java:80) at org.aspectj.weaver.ExtensibleURLClassLoader.findClass(ExtensibleURLClassLoader.java:46) at java.lang.ClassLoader.loadClass(ClassLoader.java:306) at java.lang.ClassLoader.loadClass(ClassLoader.java:251) at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:319) Exception in thread "main" public aspect JoinPointTraceAspect { private int _callDepth = -1; pointcut tracePoints() : !within(JoinPointTraceAspect); before() : tracePoints() { _callDepth++; print("Before", thisJoinPoint); } after() : tracePoints() { print("After", thisJoinPoint); _callDepth--; } private void print(String prefix, Object message) { for(int i = 0, spaces = _callDepth * 2; i < spaces; i++) { System.out.print(" "); } System.out.println(prefix + ": " + message); } } aspect EdtRuleChecker { private boolean isStressChecking = true; public pointcut anySwingMethods(JComponent c): target(c) && call(* *(..)); public pointcut threadSafeMethods(): call(* repaint(..)) || call(* revalidate()) || call(* invalidate()) || call(* getListeners(..)) || call(* add*Listener(..)) || call(* remove*Listener(..)); //calls of any JComponent method, including subclasses before(JComponent c): anySwingMethods(c) && !threadSafeMethods() && !within(EdtRuleChecker) { if(!SwingUtilities.isEventDispatchThread() && (isStressChecking || c.isShowing())) { System.err.println(thisJoinPoint.getSourceLocation()); System.err.println(thisJoinPoint.getSignature()); System.err.println(); } } //calls of any JComponent constructor, including subclasses before(): call(JComponent+.new(..)) { if (isStressChecking && !SwingUtilities.isEventDispatchThread()) { System.err.println(thisJoinPoint.getSourceLocation()); System.err.println(thisJoinPoint.getSignature() + " *constructor*"); System.err.println(); } } } Running with SwingSet2.
resolved fixed
757004c
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2006-10-23T11:55:54Z"
"2006-07-06T21:06:40Z"
tests/bugs153/pr149908/MyStringBuilder.java
149,908
Bug 149908 NPE in org.aspectj.weaver.MemberImpl.getModifiers(MemberImpl.java:526)
java.lang.NullPointerException at org.aspectj.weaver.MemberImpl.getModifiers(MemberImpl.java:526) at org.aspectj.weaver.MemberImpl.getMethodSignatureString(MemberImpl.java:824) at org.aspectj.weaver.MemberImpl.getSignatureString(MemberImpl.java:753) at org.aspectj.weaver.bcel.LazyClassGen.initializeTjp(LazyClassGen.java:1039) at org.aspectj.weaver.bcel.LazyClassGen.initializeAllTjps(LazyClassGen.java:1016) at org.aspectj.weaver.bcel.LazyClassGen.addAjcInitializers(LazyClassGen.java:964) at org.aspectj.weaver.bcel.LazyClassGen.writeBack(LazyClassGen.java:502) at org.aspectj.weaver.bcel.LazyClassGen.getJavaClassBytesIncludingReweavable(LazyClassGen.java:652) at org.aspectj.weaver.bcel.BcelWeaver.getClassFilesFor(BcelWeaver.java:1337) at org.aspectj.weaver.bcel.BcelWeaver.weaveAndNotify(BcelWeaver.java:1309) at org.aspectj.weaver.bcel.BcelWeaver.weave(BcelWeaver.java:1127) at org.aspectj.weaver.tools.WeavingAdaptor.getWovenBytes(WeavingAdaptor.java:284) at org.aspectj.weaver.tools.WeavingAdaptor.weaveClass(WeavingAdaptor.java:212) at org.aspectj.weaver.loadtime.WeavingURLClassLoader.defineClass(WeavingURLClassLoader.java:125) at org.aspectj.weaver.ExtensibleURLClassLoader.defineClass(ExtensibleURLClassLoader.java:80) at org.aspectj.weaver.ExtensibleURLClassLoader.findClass(ExtensibleURLClassLoader.java:46) at java.lang.ClassLoader.loadClass(ClassLoader.java:306) at java.lang.ClassLoader.loadClass(ClassLoader.java:251) at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:319) Exception in thread "main" public aspect JoinPointTraceAspect { private int _callDepth = -1; pointcut tracePoints() : !within(JoinPointTraceAspect); before() : tracePoints() { _callDepth++; print("Before", thisJoinPoint); } after() : tracePoints() { print("After", thisJoinPoint); _callDepth--; } private void print(String prefix, Object message) { for(int i = 0, spaces = _callDepth * 2; i < spaces; i++) { System.out.print(" "); } System.out.println(prefix + ": " + message); } } aspect EdtRuleChecker { private boolean isStressChecking = true; public pointcut anySwingMethods(JComponent c): target(c) && call(* *(..)); public pointcut threadSafeMethods(): call(* repaint(..)) || call(* revalidate()) || call(* invalidate()) || call(* getListeners(..)) || call(* add*Listener(..)) || call(* remove*Listener(..)); //calls of any JComponent method, including subclasses before(JComponent c): anySwingMethods(c) && !threadSafeMethods() && !within(EdtRuleChecker) { if(!SwingUtilities.isEventDispatchThread() && (isStressChecking || c.isShowing())) { System.err.println(thisJoinPoint.getSourceLocation()); System.err.println(thisJoinPoint.getSignature()); System.err.println(); } } //calls of any JComponent constructor, including subclasses before(): call(JComponent+.new(..)) { if (isStressChecking && !SwingUtilities.isEventDispatchThread()) { System.err.println(thisJoinPoint.getSourceLocation()); System.err.println(thisJoinPoint.getSignature() + " *constructor*"); System.err.println(); } } } Running with SwingSet2.
resolved fixed
757004c
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2006-10-23T11:55:54Z"
"2006-07-06T21:06:40Z"
tests/bugs153/pr149908/withoutMethod/MyStringBuilder.java
149,908
Bug 149908 NPE in org.aspectj.weaver.MemberImpl.getModifiers(MemberImpl.java:526)
java.lang.NullPointerException at org.aspectj.weaver.MemberImpl.getModifiers(MemberImpl.java:526) at org.aspectj.weaver.MemberImpl.getMethodSignatureString(MemberImpl.java:824) at org.aspectj.weaver.MemberImpl.getSignatureString(MemberImpl.java:753) at org.aspectj.weaver.bcel.LazyClassGen.initializeTjp(LazyClassGen.java:1039) at org.aspectj.weaver.bcel.LazyClassGen.initializeAllTjps(LazyClassGen.java:1016) at org.aspectj.weaver.bcel.LazyClassGen.addAjcInitializers(LazyClassGen.java:964) at org.aspectj.weaver.bcel.LazyClassGen.writeBack(LazyClassGen.java:502) at org.aspectj.weaver.bcel.LazyClassGen.getJavaClassBytesIncludingReweavable(LazyClassGen.java:652) at org.aspectj.weaver.bcel.BcelWeaver.getClassFilesFor(BcelWeaver.java:1337) at org.aspectj.weaver.bcel.BcelWeaver.weaveAndNotify(BcelWeaver.java:1309) at org.aspectj.weaver.bcel.BcelWeaver.weave(BcelWeaver.java:1127) at org.aspectj.weaver.tools.WeavingAdaptor.getWovenBytes(WeavingAdaptor.java:284) at org.aspectj.weaver.tools.WeavingAdaptor.weaveClass(WeavingAdaptor.java:212) at org.aspectj.weaver.loadtime.WeavingURLClassLoader.defineClass(WeavingURLClassLoader.java:125) at org.aspectj.weaver.ExtensibleURLClassLoader.defineClass(ExtensibleURLClassLoader.java:80) at org.aspectj.weaver.ExtensibleURLClassLoader.findClass(ExtensibleURLClassLoader.java:46) at java.lang.ClassLoader.loadClass(ClassLoader.java:306) at java.lang.ClassLoader.loadClass(ClassLoader.java:251) at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:319) Exception in thread "main" public aspect JoinPointTraceAspect { private int _callDepth = -1; pointcut tracePoints() : !within(JoinPointTraceAspect); before() : tracePoints() { _callDepth++; print("Before", thisJoinPoint); } after() : tracePoints() { print("After", thisJoinPoint); _callDepth--; } private void print(String prefix, Object message) { for(int i = 0, spaces = _callDepth * 2; i < spaces; i++) { System.out.print(" "); } System.out.println(prefix + ": " + message); } } aspect EdtRuleChecker { private boolean isStressChecking = true; public pointcut anySwingMethods(JComponent c): target(c) && call(* *(..)); public pointcut threadSafeMethods(): call(* repaint(..)) || call(* revalidate()) || call(* invalidate()) || call(* getListeners(..)) || call(* add*Listener(..)) || call(* remove*Listener(..)); //calls of any JComponent method, including subclasses before(JComponent c): anySwingMethods(c) && !threadSafeMethods() && !within(EdtRuleChecker) { if(!SwingUtilities.isEventDispatchThread() && (isStressChecking || c.isShowing())) { System.err.println(thisJoinPoint.getSourceLocation()); System.err.println(thisJoinPoint.getSignature()); System.err.println(); } } //calls of any JComponent constructor, including subclasses before(): call(JComponent+.new(..)) { if (isStressChecking && !SwingUtilities.isEventDispatchThread()) { System.err.println(thisJoinPoint.getSourceLocation()); System.err.println(thisJoinPoint.getSignature() + " *constructor*"); System.err.println(); } } } Running with SwingSet2.
resolved fixed
757004c
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2006-10-23T11:55:54Z"
"2006-07-06T21:06:40Z"
tests/src/org/aspectj/systemtest/ajc153/Ajc153Tests.java
/******************************************************************************* * Copyright (c) 2006 IBM * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Andy Clement - initial API and implementation *******************************************************************************/ package org.aspectj.systemtest.ajc153; import java.io.File; import junit.framework.Test; import org.aspectj.asm.AsmManager; import org.aspectj.asm.IHierarchy; import org.aspectj.asm.IProgramElement; import org.aspectj.testing.Utils; import org.aspectj.testing.XMLBasedAjcTestCase; import org.aspectj.weaver.bcel.Utility; public class Ajc153Tests extends org.aspectj.testing.XMLBasedAjcTestCase { //public void testGenericsProblem_pr151978() { runTest("generics problem");} // public void testArgnamesAndJavac_pr148381() { runTest("argNames and javac");} // public void testCFlowXMLAspectLTW_pr149096() { runTest("cflow xml concrete aspect"); } // public void testAmbiguousBinding_pr121805() { runTest("ambiguous binding");} // public void testNegatedAnnotationMatchingProblem_pr153464() { runTest("negated annotation matching problem");} public void testPTWgetWithinTypeName_pr123423_1() { runTest("basic usage of getWithinTypeName");} public void testPTWgetWithinTypeName_pr123423_2() { runTest("basic usage of getWithinTypeName - multiple types");} public void testPTWgetWithinTypeName_pr123423_3() { runTest("basic usage of getWithinTypeName - non matching types");} public void testPTWgetWithinTypeName_pr123423_4() { runTest("basic usage of getWithinTypeName - types in packages");} public void testPTWgetWithinTypeName_pr123423_5() { runTest("basic usage of getWithinTypeName - annotation style");} public void testTurningOffBcelCaching_pr160674() { runTest("turning off bcel caching");} public void testNoIllegalStateExceptionWithGenericInnerAspect_pr156058() { runTest("no IllegalStateException with generic inner aspect"); } public void testNoIllegalStateExceptionWithGenericInnerAspect_pr156058_2() { runTest("no IllegalStateException with generic inner aspect - 2"); } public void testDeclareMethodAnnotations_pr159143() { runTest("declare method annotations");} public void testVisibilityProblem_pr149071() { runTest("visibility problem");} public void testMissingLineNumbersInStacktraceAfter_pr145442() { runTest("missing line numbers in stacktrace after");} public void testMissingLineNumbersInStacktraceAround_pr145442() { runTest("missing line numbers in stacktrace around");} public void testGenericArrays_pr158624() { runTest("generics and arrays"); } public void testMissingLineNumbersInStacktraceBefore_pr145442() { runTest("missing line numbers in stacktrace before");} public void testMissingLineNumbersInStacktraceBefore_pr145442_Binary() { runTest("missing line numbers in stacktrace before - binary");} public void testAnnotationStylePointcutNPE_pr158412() { runTest("annotation style pointcut npe"); } public void testAnnotationStylePointcutNPE_pr158412_2() { runTest("annotation style pointcut npe - 2"); } public void testAnnotationsCallConstructors_pr158126() { runTest("annotations, call and constructors problem");} public void testIllegalStateExceptionGenerics_pr153845() { runTest("IllegalStateException at GenericSignatureParser.java"); } public void testNoIllegalStateExceptionFromAsmDelegate_pr153490_1() { runTest("no illegal state exception from AsmDelegate - 1");} public void testNoIllegalStateExceptionFromAsmDelegate_pr153490_2() { runTest("no illegal state exception from AsmDelegate - 2");} public void testNoIllegalStateExceptionFromAsmDelegate_pr153490_3() { runTest("no illegal state exception from AsmDelegate - 3");} public void testAnnotMethod_pr156962() { runTest("Test Annot Method");} public void testAnnotMethodHasMember_pr156962() { runTest("Test Annot Method Has Member"); } public void testMixingGenerics_pr152848() { runTest("mixing generics"); } public void testIncorrectStaticinitializationWeaving_pr149560_1() { runTest("incorrect staticinitialization weaving - codestyle");} public void testIncorrectStaticinitializationWeaving_pr149560_2() { runTest("incorrect staticinitialization weaving - annstyle");} public void testIncorrectDeprecatedAnnotationProcessing_pr154332() { runTest("incorrect deprecated annotation processing");} public void testPipeliningProblemWithAnnotationsDecp_pr153380_1() { runTest("pipelining decps");} public void testUnwantedPointcutWarning_pr148219() { runTest("unwanted warning for pointcut");} public void testDecpAndCflowadderMungerClash_pr152631() { runTest("decp and cflowadder munger clash");} public void testGenericInheritanceDecp_pr150095() { runTest("generics, inheritance and decp");} public void testIllegalStateException_pr148737() { runTest("illegalstateexception for non generic type");} public void testAtajInheritance_pr149305_1() { runTest("ataj inheritance - 1");} public void testAtajInheritance_pr149305_2() { runTest("ataj inheritance - 2");} public void testAtajInheritance_pr149305_3() { runTest("ataj inheritance - 3");} public void testVerificationFailureForAspectOf_pr148693() { runTest("verification problem"); // build the code Utils.verifyClass(ajc,"mypackage.MyAspect"); // verify it <<< BRAND NEW VERIFY UTILITY FOR EVERYONE TO TRY ;) } public void testIncorrectAnnotationValue_pr148537() { runTest("incorrect annotation value");} public void testVerifyErrNoTypeCflowField_pr145693_1() { runTest("verifyErrNoTypeCflowField"); } public void testVerifyErrInpathNoTypeCflowField_pr145693_2() { runTest("verifyErrInpathNoTypeCflowField"); } public void testCpathNoTypeCflowField_pr145693_3() { runTest("cpathNoTypeCflowField"); } // public void testAdviceNotWovenAspectPath_pr147841() { runTest("advice not woven on aspectpath");} public void testGenericSignatures_pr148409() { runTest("generic signature problem"); } // public void testBrokenIfArgsCflowAtAj_pr145018() { runTest("ataj crashing with cflow, if and args");} public void testCantFindType_pr149322_01() {runTest("can't find type on interface call 1");} public void testCantFindType_pr149322_02() {runTest("can't find type on interface call 2");} public void testCantFindType_pr149322_03() {runTest("can't find type on interface call 3");} public void testParsingBytecodeLess_pr152871() { Utility.testingParseCounter=0; runTest("parsing bytecode less"); assertTrue("Should have called parse 5 times, not "+Utility.testingParseCounter+" times",Utility.testingParseCounter==5); // 5 means: // (1)=registerAspect // (2,3)=checkingIfShouldWeave,AcceptingResult for class // (4,5)=checkingIfShouldWeave,AcceptingResult for aspect } public void testMatchVolatileField_pr150671() {runTest("match volatile field");}; public void testDuplicateJVMTIAgents_pr151938() {runTest("Duplicate JVMTI agents");}; public void testLTWWorldWithAnnotationMatching_pr153572() { runTest("LTWWorld with annotation matching");} public void testReweavableAspectNotRegistered_pr129525 () { runTest("reweavableAspectNotRegistered error"); } public void testNPEinConstructorSignatureImpl_pr155972 () { runTest("NPE in ConstructorSignatureImpl"); } public void testNPEinFieldSignatureImpl_pr155972 () { runTest("NPE in FieldSignatureImpl"); } public void testNPEinInitializerSignatureImpl_pr155972 () { runTest("NPE in InitializerSignatureImpl"); } public void testLineNumberTableCorrectWithGenericsForEachAndContinue_pr155763() { runTest("ensure LineNumberTable correct with generics, for each and continue"); } public void testDeclareSoftDoesntAllowUndeclaredExInAnonInnerClass_pr151772() { runTest("ensure declare soft doesn't allow undeclared exception in anonymous inner class"); } public void testDeclareSoftDoesntAllowUndeclaredExInAnonInnerClass_pr151772_2() { runTest("ensure declare soft doesn't allow undeclared exception in anonymous inner class - 2"); } public void testDeclareSoftAndInnerClasses_pr125981() { runTest("declare soft and inner classes"); } public void testGetSourceSignature_pr148908() { runTest("ensure getSourceSignature correct with static field"); IHierarchy top = AsmManager.getDefault().getHierarchy(); IProgramElement ipe = top.findElementForLabel(top.getRoot(), IProgramElement.Kind.FIELD,"MY_COMPARATOR"); String expected = "static final Comparator MY_COMPARATOR = new Comparator() {\n" + " public int compare(Object o1, Object o2) {\n" + " return 0;\n" + " }\n" + "};"; assertEquals("expected source signature to be " + expected + " but found " + ipe.getSourceSignature(), expected, ipe.getSourceSignature()); } public void testNPEWithCustomAgent_pr158005() { runTest("NPE with custom agent"); } public void testWeaveConcreteSubaspectWithAdvice_pr132080() { runTest("Weave concrete sub-aspect with advice"); } public void testWeaveConcreteSubaspectWithITD_pr132080() { runTest("Weave concrete sub-aspect with ITD"); } public void testWeaveConcreteSubaspectWithAroundClosure_pr132080() { runTest("Weave concrete sub-aspect with around closure"); } public void testWeaveConcreteSubaspectWithCflow_pr132080() { runTest("Weave concrete sub-aspect with cflow"); } public void testNPEWithLTWPointcutLibraryAndMissingAspectDependency_pr158957 () { runTest("NPE with LTW, pointcut library and missing aspect dependency"); } public void testNoInvalidAbsoluteTypeNameWarning_pr156904_1() {runTest("ensure no invalidAbsoluteTypeName when do match - 1");} public void testNoInvalidAbsoluteTypeNameWarning_pr156904_2() {runTest("ensure no invalidAbsoluteTypeName when do match - 2");} public void testNoInvalidAbsoluteTypeNameWarning_pr156904_3() {runTest("ensure no invalidAbsoluteTypeName when do match - 3");} public void testNoInvalidAbsoluteTypeNameWarning_pr156904_4() {runTest("ensure no invalidAbsoluteTypeName when do match - 4");} public void testNoNPEWithThrownExceptionWarningAndAtAspectj_pr161217() {runTest("NPE with thrown exception warning and at aspectj");} ///////////////////////////////////////// public static Test suite() { return XMLBasedAjcTestCase.loadSuite(Ajc153Tests.class); } protected File getSpecFile() { return new File("../tests/src/org/aspectj/systemtest/ajc153/ajc153.xml"); } }
149,908
Bug 149908 NPE in org.aspectj.weaver.MemberImpl.getModifiers(MemberImpl.java:526)
java.lang.NullPointerException at org.aspectj.weaver.MemberImpl.getModifiers(MemberImpl.java:526) at org.aspectj.weaver.MemberImpl.getMethodSignatureString(MemberImpl.java:824) at org.aspectj.weaver.MemberImpl.getSignatureString(MemberImpl.java:753) at org.aspectj.weaver.bcel.LazyClassGen.initializeTjp(LazyClassGen.java:1039) at org.aspectj.weaver.bcel.LazyClassGen.initializeAllTjps(LazyClassGen.java:1016) at org.aspectj.weaver.bcel.LazyClassGen.addAjcInitializers(LazyClassGen.java:964) at org.aspectj.weaver.bcel.LazyClassGen.writeBack(LazyClassGen.java:502) at org.aspectj.weaver.bcel.LazyClassGen.getJavaClassBytesIncludingReweavable(LazyClassGen.java:652) at org.aspectj.weaver.bcel.BcelWeaver.getClassFilesFor(BcelWeaver.java:1337) at org.aspectj.weaver.bcel.BcelWeaver.weaveAndNotify(BcelWeaver.java:1309) at org.aspectj.weaver.bcel.BcelWeaver.weave(BcelWeaver.java:1127) at org.aspectj.weaver.tools.WeavingAdaptor.getWovenBytes(WeavingAdaptor.java:284) at org.aspectj.weaver.tools.WeavingAdaptor.weaveClass(WeavingAdaptor.java:212) at org.aspectj.weaver.loadtime.WeavingURLClassLoader.defineClass(WeavingURLClassLoader.java:125) at org.aspectj.weaver.ExtensibleURLClassLoader.defineClass(ExtensibleURLClassLoader.java:80) at org.aspectj.weaver.ExtensibleURLClassLoader.findClass(ExtensibleURLClassLoader.java:46) at java.lang.ClassLoader.loadClass(ClassLoader.java:306) at java.lang.ClassLoader.loadClass(ClassLoader.java:251) at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:319) Exception in thread "main" public aspect JoinPointTraceAspect { private int _callDepth = -1; pointcut tracePoints() : !within(JoinPointTraceAspect); before() : tracePoints() { _callDepth++; print("Before", thisJoinPoint); } after() : tracePoints() { print("After", thisJoinPoint); _callDepth--; } private void print(String prefix, Object message) { for(int i = 0, spaces = _callDepth * 2; i < spaces; i++) { System.out.print(" "); } System.out.println(prefix + ": " + message); } } aspect EdtRuleChecker { private boolean isStressChecking = true; public pointcut anySwingMethods(JComponent c): target(c) && call(* *(..)); public pointcut threadSafeMethods(): call(* repaint(..)) || call(* revalidate()) || call(* invalidate()) || call(* getListeners(..)) || call(* add*Listener(..)) || call(* remove*Listener(..)); //calls of any JComponent method, including subclasses before(JComponent c): anySwingMethods(c) && !threadSafeMethods() && !within(EdtRuleChecker) { if(!SwingUtilities.isEventDispatchThread() && (isStressChecking || c.isShowing())) { System.err.println(thisJoinPoint.getSourceLocation()); System.err.println(thisJoinPoint.getSignature()); System.err.println(); } } //calls of any JComponent constructor, including subclasses before(): call(JComponent+.new(..)) { if (isStressChecking && !SwingUtilities.isEventDispatchThread()) { System.err.println(thisJoinPoint.getSourceLocation()); System.err.println(thisJoinPoint.getSignature() + " *constructor*"); System.err.println(); } } } Running with SwingSet2.
resolved fixed
757004c
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2006-10-23T11:55:54Z"
"2006-07-06T21:06:40Z"
weaver/src/org/aspectj/weaver/MemberImpl.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Eclipse Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * PARC initial implementation * ******************************************************************/ package org.aspectj.weaver; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.Collection; import java.util.HashSet; import java.util.Iterator; import java.util.List; public class MemberImpl implements Comparable, AnnotatedElement,Member { protected Kind kind; protected UnresolvedType declaringType; protected int modifiers; protected UnresolvedType returnType; protected String name; protected UnresolvedType[] parameterTypes; private final String signature; private String paramSignature; /** * All the signatures that a join point with this member as its signature has. * The fact that this has to go on MemberImpl and not ResolvedMemberImpl says a lot about * how broken the Member/ResolvedMember distinction currently is. */ private JoinPointSignatureIterator joinPointSignatures = null; public MemberImpl( Kind kind, UnresolvedType declaringType, int modifiers, String name, String signature) { this.kind = kind; this.declaringType = declaringType; this.modifiers = modifiers; this.name = name; this.signature = signature; if (kind == FIELD) { this.returnType = UnresolvedType.forSignature(signature); this.parameterTypes = UnresolvedType.NONE; } else { Object[] returnAndParams = signatureToTypes(signature,false); this.returnType = (UnresolvedType) returnAndParams[0]; this.parameterTypes = (UnresolvedType[]) returnAndParams[1]; // always safe not to do this ?!? // String oldsig=new String(signature); // signature = typesToSignature(returnType,parameterTypes,true); } } public MemberImpl( Kind kind, UnresolvedType declaringType, int modifiers, UnresolvedType returnType, String name, UnresolvedType[] parameterTypes) { super(); this.kind = kind; this.declaringType = declaringType; this.modifiers = modifiers; this.returnType = returnType; this.name = name; this.parameterTypes = parameterTypes; if (kind == FIELD) { this.signature = returnType.getErasureSignature(); } else { this.signature = typesToSignature(returnType, parameterTypes,true); } } /* (non-Javadoc) * @see org.aspectj.weaver.Member#resolve(org.aspectj.weaver.World) */ public ResolvedMember resolve(World world) { return world.resolve(this); } // ---- utility methods /** returns an Object[] pair of UnresolvedType, UnresolvedType[] representing return type, * argument types parsed from the JVM bytecode signature of a method. Yes, * this should actually return a nice statically-typed pair object, but we * don't have one of those. * * <blockquote><pre> * UnresolvedType.signatureToTypes("()[Z")[0].equals(Type.forSignature("[Z")) * UnresolvedType.signatureToTypes("(JJ)I")[1] * .equals(UnresolvedType.forSignatures(new String[] {"J", "J"})) * </pre></blockquote> * * @param signature the JVM bytecode method signature string we want to break apart * @return a pair of UnresolvedType, UnresolvedType[] representing the return types and parameter types. */ public static String typesToSignature(UnresolvedType returnType, UnresolvedType[] paramTypes, boolean useRawTypes) { StringBuffer buf = new StringBuffer(); buf.append("("); for (int i = 0, len = paramTypes.length; i < len; i++) { if (paramTypes[i].isParameterizedType() && useRawTypes) buf.append(paramTypes[i].getErasureSignature()); else if (paramTypes[i].isTypeVariableReference() && useRawTypes) buf.append(paramTypes[i].getErasureSignature()); else buf.append(paramTypes[i].getSignature()); } buf.append(")"); if (returnType.isParameterizedType() && useRawTypes) buf.append(returnType.getErasureSignature()); else if (returnType.isTypeVariableReference() && useRawTypes) buf.append(returnType.getErasureSignature()); else buf.append(returnType.getSignature()); return buf.toString(); } /** * Returns "(<signaturesOfParamTypes>,...)" - unlike the other typesToSignature * that also includes the return type, this one just deals with the parameter types. */ public static String typesToSignature(UnresolvedType[] paramTypes) { StringBuffer buf = new StringBuffer(); buf.append("("); for(int i=0;i<paramTypes.length;i++) { buf.append(paramTypes[i].getSignature()); } buf.append(")"); return buf.toString(); } /** * returns an Object[] pair of UnresolvedType, UnresolvedType[] representing return type, * argument types parsed from the JVM bytecode signature of a method. Yes, * this should actually return a nice statically-typed pair object, but we * don't have one of those. * * <blockquote><pre> * UnresolvedType.signatureToTypes("()[Z")[0].equals(Type.forSignature("[Z")) * UnresolvedType.signatureToTypes("(JJ)I")[1] * .equals(UnresolvedType.forSignatures(new String[] {"J", "J"})) * </pre></blockquote> * * @param signature the JVM bytecode method signature string we want to break apart * @return a pair of UnresolvedType, UnresolvedType[] representing the return types and parameter types. */ private static Object[] signatureToTypes(String sig,boolean keepParameterizationInfo) { List l = new ArrayList(); int i = 1; boolean hasAnyAnglies = sig.indexOf('<')!=-1; while (true) { char c = sig.charAt(i); if (c == ')') break; // break out when the hit the ')' int start = i; while (c == '[') c = sig.charAt(++i); if (c == 'L' || c == 'P') { int nextSemicolon = sig.indexOf(';',start); int firstAngly = (hasAnyAnglies?sig.indexOf('<',start):-1); if (!hasAnyAnglies || firstAngly == -1 || firstAngly>nextSemicolon) { i = nextSemicolon + 1; l.add(UnresolvedType.forSignature(sig.substring(start, i))); } else { // generics generics generics // Have to skip to the *correct* ';' boolean endOfSigReached = false; int posn = firstAngly; int genericDepth=0; while (!endOfSigReached) { switch (sig.charAt(posn)) { case '<': genericDepth++;break; case '>': genericDepth--;break; case ';': if (genericDepth==0) endOfSigReached=true;break; default: } posn++; } // posn now points to the correct nextSemicolon :) i=posn; l.add(UnresolvedType.forSignature(sig.substring(start,i))); } } else if (c=='T') { // assumed 'reference' to a type variable, so just "Tname;" int nextSemicolon = sig.indexOf(';',start); String nextbit = sig.substring(start,nextSemicolon); l.add(UnresolvedType.forSignature(nextbit)); i=nextSemicolon+1; } else { i++; l.add(UnresolvedType.forSignature(sig.substring(start, i))); } } UnresolvedType[] paramTypes = (UnresolvedType[]) l.toArray(new UnresolvedType[l.size()]); UnresolvedType returnType = UnresolvedType.forSignature(sig.substring(i+1, sig.length())); return new Object[] { returnType, paramTypes }; } // ---- factory methods public static MemberImpl field(String declaring, int mods, String name, String signature) { return field(declaring, mods, UnresolvedType.forSignature(signature), name); } public static Member field(UnresolvedType declaring, int mods, String name, UnresolvedType type) { return new MemberImpl(FIELD, declaring, mods, type, name, UnresolvedType.NONE); } public static MemberImpl method(UnresolvedType declaring, int mods, String name, String signature) { Object[] pair = signatureToTypes(signature,false); return method(declaring, mods, (UnresolvedType) pair[0], name, (UnresolvedType[]) pair[1]); } public static MemberImpl monitorEnter() { return new MemberImpl(MONITORENTER,UnresolvedType.OBJECT,Modifier.STATIC,ResolvedType.VOID,"<lock>",UnresolvedType.ARRAY_WITH_JUST_OBJECT); } public static MemberImpl monitorExit() { return new MemberImpl(MONITOREXIT,UnresolvedType.OBJECT,Modifier.STATIC,ResolvedType.VOID,"<unlock>",UnresolvedType.ARRAY_WITH_JUST_OBJECT); } public static Member pointcut(UnresolvedType declaring, String name, String signature) { Object[] pair = signatureToTypes(signature,false); return pointcut(declaring, 0, (UnresolvedType) pair[0], name, (UnresolvedType[]) pair[1]); } private static MemberImpl field(String declaring, int mods, UnresolvedType ty, String name) { return new MemberImpl( FIELD, UnresolvedType.forName(declaring), mods, ty, name, UnresolvedType.NONE); } public static MemberImpl method(UnresolvedType declTy, int mods, UnresolvedType rTy, String name, UnresolvedType[] paramTys) { return new MemberImpl( //??? this calls <clinit> a method name.equals("<init>") ? CONSTRUCTOR : METHOD, declTy, mods, rTy, name, paramTys); } private static Member pointcut(UnresolvedType declTy, int mods, UnresolvedType rTy, String name, UnresolvedType[] paramTys) { return new MemberImpl( POINTCUT, declTy, mods, rTy, name, paramTys); } public static ResolvedMemberImpl makeExceptionHandlerSignature(UnresolvedType inType, UnresolvedType catchType) { return new ResolvedMemberImpl( HANDLER, inType, Modifier.STATIC, "<catch>", "(" + catchType.getSignature() + ")V"); } // ---- parsing methods /** Takes a string in this form: * * <blockquote><pre> * static? TypeName TypeName.Id * </pre></blockquote> * Pretty much just for testing, and as such should perhaps be moved. */ public static MemberImpl fieldFromString(String str) { str = str.trim(); final int len = str.length(); int i = 0; int mods = 0; if (str.startsWith("static", i)) { mods = Modifier.STATIC; i += 6; while (Character.isWhitespace(str.charAt(i))) i++; } int start = i; while (! Character.isWhitespace(str.charAt(i))) i++; UnresolvedType retTy = UnresolvedType.forName(str.substring(start, i)); start = i; i = str.lastIndexOf('.'); UnresolvedType declaringTy = UnresolvedType.forName(str.substring(start, i).trim()); start = ++i; String name = str.substring(start, len).trim(); return new MemberImpl( FIELD, declaringTy, mods, retTy, name, UnresolvedType.NONE); } /** Takes a string in this form: * * <blockquote><pre> * (static|interface|private)? TypeName TypeName . Id ( TypeName , ...) * </pre></blockquote> * Pretty much just for testing, and as such should perhaps be moved. */ public static Member methodFromString(String str) { str = str.trim(); // final int len = str.length(); int i = 0; int mods = 0; if (str.startsWith("static", i)) { mods = Modifier.STATIC; i += 6; } else if (str.startsWith("interface", i)) { mods = Modifier.INTERFACE; i += 9; } else if (str.startsWith("private", i)) { mods = Modifier.PRIVATE; i += 7; } while (Character.isWhitespace(str.charAt(i))) i++; int start = i; while (! Character.isWhitespace(str.charAt(i))) i++; UnresolvedType returnTy = UnresolvedType.forName(str.substring(start, i)); start = i; i = str.indexOf('(', i); i = str.lastIndexOf('.', i); UnresolvedType declaringTy = UnresolvedType.forName(str.substring(start, i).trim()); start = ++i; i = str.indexOf('(', i); String name = str.substring(start, i).trim(); start = ++i; i = str.indexOf(')', i); String[] paramTypeNames = parseIds(str.substring(start, i).trim()); return method(declaringTy, mods, returnTy, name, UnresolvedType.forNames(paramTypeNames)); } private static String[] parseIds(String str) { if (str.length() == 0) return ZERO_STRINGS; List l = new ArrayList(); int start = 0; while (true) { int i = str.indexOf(',', start); if (i == -1) { l.add(str.substring(start).trim()); break; } l.add(str.substring(start, i).trim()); start = i+1; } return (String[]) l.toArray(new String[l.size()]); } private static final String[] ZERO_STRINGS = new String[0]; // ---- things we know without resolution public boolean equals(Object other) { if (! (other instanceof Member)) return false; Member o = (Member) other; return (getKind() == o.getKind() && getName().equals(o.getName()) && getSignature().equals(o.getSignature()) && getDeclaringType().equals(o.getDeclaringType())); } /** * Equality is checked based on the underlying signature, so the hash code * of a member is based on its kind, name, signature, and declaring type. The * algorithm for this was taken from page 38 of effective java. */ private volatile int hashCode = 0; public int hashCode() { if (hashCode == 0) { int result = 17; result = 37*result + getKind().hashCode(); result = 37*result + getName().hashCode(); result = 37*result + getSignature().hashCode(); result = 37*result + getDeclaringType().hashCode(); hashCode = result; } return hashCode; } /* (non-Javadoc) * @see org.aspectj.weaver.Member#compareTo(java.lang.Object) */ public int compareTo(Object other) { Member o = (Member) other; int i = getName().compareTo(o.getName()); if (i != 0) return i; return getSignature().compareTo(o.getSignature()); } public String toString() { StringBuffer buf = new StringBuffer(); buf.append(returnType.getName()); buf.append(' '); buf.append(declaringType.getName()); buf.append('.'); buf.append(name); if (kind != FIELD) { buf.append("("); if (parameterTypes.length != 0) { buf.append(parameterTypes[0]); for (int i=1, len = parameterTypes.length; i < len; i++) { buf.append(", "); buf.append(parameterTypes[i].getName()); } } buf.append(")"); } return buf.toString(); } /* (non-Javadoc) * @see org.aspectj.weaver.Member#toLongString() */ public String toLongString() { StringBuffer buf = new StringBuffer(); buf.append(kind); buf.append(' '); if (modifiers != 0) { buf.append(Modifier.toString(modifiers)); buf.append(' '); } buf.append(toString()); buf.append(" <"); buf.append(signature); buf.append(" >"); return buf.toString(); } /* (non-Javadoc) * @see org.aspectj.weaver.Member#getKind() */ public Kind getKind() { return kind; } /* (non-Javadoc) * @see org.aspectj.weaver.Member#getDeclaringType() */ public UnresolvedType getDeclaringType() { return declaringType; } /* (non-Javadoc) * @see org.aspectj.weaver.Member#getReturnType() */ public UnresolvedType getReturnType() { return returnType; } public UnresolvedType getGenericReturnType() { return getReturnType(); } /* (non-Javadoc) * @see org.aspectj.weaver.Member#getType() */ public UnresolvedType getType() { return returnType; } /* (non-Javadoc) * @see org.aspectj.weaver.Member#getName() */ public String getName() { return name; } /* (non-Javadoc) * @see org.aspectj.weaver.Member#getParameterTypes() */ public UnresolvedType[] getParameterTypes() { return parameterTypes; } /* (non-Javadoc) * @see org.aspectj.weaver.Member#getSignature() */ public String getSignature() { return signature; } public int getArity() { return parameterTypes.length; } /* (non-Javadoc) * @see org.aspectj.weaver.Member#getParameterSignature() */ public String getParameterSignature() { if (paramSignature != null) return paramSignature; StringBuffer sb = new StringBuffer(); sb.append("("); for (int i = 0; i < parameterTypes.length; i++) { UnresolvedType tx = parameterTypes[i]; sb.append(tx.getSignature()); } sb.append(")"); paramSignature = sb.toString(); return paramSignature; } /* (non-Javadoc) * @see org.aspectj.weaver.Member#isCompatibleWith(org.aspectj.weaver.Member) */ public boolean isCompatibleWith(Member am) { if (kind != METHOD || am.getKind() != METHOD) return true; if (! name.equals(am.getName())) return true; if (! equalTypes(getParameterTypes(), am.getParameterTypes())) return true; return getReturnType().equals(am.getReturnType()); } private static boolean equalTypes(UnresolvedType[] a, UnresolvedType[] b) { int len = a.length; if (len != b.length) return false; for (int i = 0; i < len; i++) { if (!a[i].equals(b[i])) return false; } return true; } // ---- things we know only with resolution /* (non-Javadoc) * @see org.aspectj.weaver.Member#getModifiers(org.aspectj.weaver.World) */ public int getModifiers(World world) { return resolve(world).getModifiers(); } /* (non-Javadoc) * @see org.aspectj.weaver.Member#getExceptions(org.aspectj.weaver.World) */ public UnresolvedType[] getExceptions(World world) { return resolve(world).getExceptions(); } /* (non-Javadoc) * @see org.aspectj.weaver.Member#isProtected(org.aspectj.weaver.World) */ public final boolean isProtected(World world) { return Modifier.isProtected(resolve(world).getModifiers()); } /* (non-Javadoc) * @see org.aspectj.weaver.Member#isStatic(org.aspectj.weaver.World) */ public final boolean isStatic(World world) { return Modifier.isStatic(resolve(world).getModifiers()); } /* (non-Javadoc) * @see org.aspectj.weaver.Member#isStrict(org.aspectj.weaver.World) */ public final boolean isStrict(World world) { return Modifier.isStrict(resolve(world).getModifiers()); } /* (non-Javadoc) * @see org.aspectj.weaver.Member#isStatic() */ public final boolean isStatic() { return Modifier.isStatic(modifiers); } /* (non-Javadoc) * @see org.aspectj.weaver.Member#isInterface() */ public final boolean isInterface() { return Modifier.isInterface(modifiers); // this is kinda weird } /* (non-Javadoc) * @see org.aspectj.weaver.Member#isPrivate() */ public final boolean isPrivate() { return Modifier.isPrivate(modifiers); } /* (non-Javadoc) * @see org.aspectj.weaver.Member#canBeParameterized() */ public boolean canBeParameterized() { return false; } /* (non-Javadoc) * @see org.aspectj.weaver.Member#getCallsiteModifiers() */ public final int getCallsiteModifiers() { return modifiers & ~ Modifier.INTERFACE; } public int getModifiers() { return modifiers; } /* (non-Javadoc) * @see org.aspectj.weaver.Member#getExtractableName() */ public final String getExtractableName() { if (name.equals("<init>")) return "init$"; else if (name.equals("<clinit>")) return "clinit$"; else return name; } /* (non-Javadoc) * @see org.aspectj.weaver.Member#hasAnnotation(org.aspectj.weaver.UnresolvedType) */ public boolean hasAnnotation(UnresolvedType ofType) { throw new UnsupportedOperationException("You should resolve this member and call hasAnnotation() on the result..."); } /* (non-Javadoc) * @see org.aspectj.weaver.AnnotatedElement#getAnnotationTypes() */ /* (non-Javadoc) * @see org.aspectj.weaver.Member#getAnnotationTypes() */ public ResolvedType[] getAnnotationTypes() { throw new UnsupportedOperationException("You should resolve this member and call hasAnnotation() on the result..."); } /* (non-Javadoc) * @see org.aspectj.weaver.Member#getAnnotations() */ public AnnotationX[] getAnnotations() { throw new UnsupportedOperationException("You should resolve this member '"+this+"' and call getAnnotations() on the result..."); } // ---- fields 'n' stuff /* (non-Javadoc) * @see org.aspectj.weaver.Member#getDeclaringTypes(org.aspectj.weaver.World) */ public Collection/*ResolvedType*/ getDeclaringTypes(World world) { ResolvedType myType = getDeclaringType().resolve(world); Collection ret = new HashSet(); if (kind == CONSTRUCTOR) { // this is wrong if the member doesn't exist, but that doesn't matter ret.add(myType); } else if (isStatic() || kind == FIELD) { walkUpStatic(ret, myType); } else { walkUp(ret, myType); } return ret; } private boolean walkUp(Collection acc, ResolvedType curr) { if (acc.contains(curr)) return true; boolean b = false; for (Iterator i = curr.getDirectSupertypes(); i.hasNext(); ) { b |= walkUp(acc, (ResolvedType)i.next()); } if (!b && curr.isParameterizedType()) { b = walkUp(acc,curr.getGenericType()); } if (!b) { b = curr.lookupMemberNoSupers(this) != null; } if (b) acc.add(curr); return b; } private boolean walkUpStatic(Collection acc, ResolvedType curr) { if (curr.lookupMemberNoSupers(this) != null) { acc.add(curr); return true; } else { boolean b = false; for (Iterator i = curr.getDirectSupertypes(); i.hasNext(); ) { b |= walkUpStatic(acc, (ResolvedType)i.next()); } if (!b && curr.isParameterizedType()) { b = walkUpStatic(acc,curr.getGenericType()); } if (b) acc.add(curr); return b; } } // ---- reflective thisJoinPoint stuff /* (non-Javadoc) * @see org.aspectj.weaver.Member#getSignatureMakerName() */ public String getSignatureMakerName() { if (getName().equals("<clinit>")) return "makeInitializerSig"; Kind kind = getKind(); if (kind == METHOD) { return "makeMethodSig"; } else if (kind == CONSTRUCTOR) { return "makeConstructorSig"; } else if (kind == FIELD) { return "makeFieldSig"; } else if (kind == HANDLER) { return "makeCatchClauseSig"; } else if (kind == STATIC_INITIALIZATION) { return "makeInitializerSig"; } else if (kind == ADVICE) { return "makeAdviceSig"; } else if (kind == MONITORENTER) { return "makeLockSig"; } else if (kind == MONITOREXIT) { return "makeUnlockSig"; } else { throw new RuntimeException("unimplemented"); } } /* (non-Javadoc) * @see org.aspectj.weaver.Member#getSignatureType() */ public String getSignatureType() { Kind kind = getKind(); if (getName().equals("<clinit>")) return "org.aspectj.lang.reflect.InitializerSignature"; if (kind == METHOD) { return "org.aspectj.lang.reflect.MethodSignature"; } else if (kind == CONSTRUCTOR) { return "org.aspectj.lang.reflect.ConstructorSignature"; } else if (kind == FIELD) { return "org.aspectj.lang.reflect.FieldSignature"; } else if (kind == HANDLER) { return "org.aspectj.lang.reflect.CatchClauseSignature"; } else if (kind == STATIC_INITIALIZATION) { return "org.aspectj.lang.reflect.InitializerSignature"; } else if (kind == ADVICE) { return "org.aspectj.lang.reflect.AdviceSignature"; } else if (kind == MONITORENTER) { return "org.aspectj.lang.reflect.LockSignature"; } else if (kind == MONITOREXIT) { return "org.aspectj.lang.reflect.UnlockSignature"; } else { throw new RuntimeException("unimplemented"); } } /* (non-Javadoc) * @see org.aspectj.weaver.Member#getSignatureString(org.aspectj.weaver.World) */ public String getSignatureString(World world) { if (getName().equals("<clinit>")) return getStaticInitializationSignatureString(world); Kind kind = getKind(); if (kind == METHOD) { return getMethodSignatureString(world); } else if (kind == CONSTRUCTOR) { return getConstructorSignatureString(world); } else if (kind == FIELD) { return getFieldSignatureString(world); } else if (kind == HANDLER) { return getHandlerSignatureString(world); } else if (kind == STATIC_INITIALIZATION) { return getStaticInitializationSignatureString(world); } else if (kind == ADVICE) { return getAdviceSignatureString(world); } else if (kind == MONITORENTER || kind == MONITOREXIT) { return getMonitorSignatureString(world); } else { throw new RuntimeException("unimplemented"); } } private String getHandlerSignatureString(World world) { StringBuffer buf = new StringBuffer(); buf.append(makeString(0)); buf.append('-'); //buf.append(getName()); buf.append('-'); buf.append(makeString(getDeclaringType())); buf.append('-'); buf.append(makeString(getParameterTypes()[0])); buf.append('-'); String pName = "<missing>"; String[] names = getParameterNames(world); if (names != null) pName = names[0]; buf.append(pName); buf.append('-'); return buf.toString(); } private String getStaticInitializationSignatureString(World world) { StringBuffer buf = new StringBuffer(); buf.append(makeString(getModifiers(world))); buf.append('-'); //buf.append(getName()); buf.append('-'); buf.append(makeString(getDeclaringType())); buf.append('-'); return buf.toString(); } protected String getAdviceSignatureString(World world) { StringBuffer buf = new StringBuffer(); buf.append(makeString(getModifiers(world))); buf.append('-'); buf.append(getName()); buf.append('-'); buf.append(makeString(getDeclaringType())); buf.append('-'); buf.append(makeString(getParameterTypes())); buf.append('-'); buf.append(makeString(getParameterNames(world))); buf.append('-'); buf.append(makeString(getExceptions(world))); buf.append('-'); buf.append(makeString(getReturnType())); buf.append('-'); return buf.toString(); } protected String getMethodSignatureString(World world) { StringBuffer buf = new StringBuffer(); buf.append(makeString(getModifiers(world))); buf.append('-'); buf.append(getName()); buf.append('-'); buf.append(makeString(getDeclaringType())); buf.append('-'); buf.append(makeString(getParameterTypes())); buf.append('-'); buf.append(makeString(getParameterNames(world))); buf.append('-'); buf.append(makeString(getExceptions(world))); buf.append('-'); buf.append(makeString(getReturnType())); buf.append('-'); return buf.toString(); } protected String getMonitorSignatureString(World world) { StringBuffer buf = new StringBuffer(); buf.append(makeString(Modifier.STATIC)); // modifiers buf.append('-'); buf.append(getName()); // name buf.append('-'); buf.append(makeString(getDeclaringType())); // Declaring Type buf.append('-'); buf.append(makeString(getParameterTypes()[0])); // Parameter Types buf.append('-'); buf.append(""); // Parameter names buf.append('-'); return buf.toString(); } protected String getConstructorSignatureString(World world) { StringBuffer buf = new StringBuffer(); buf.append(makeString(getModifiers(world))); buf.append('-'); buf.append('-'); buf.append(makeString(getDeclaringType())); buf.append('-'); buf.append(makeString(getParameterTypes())); buf.append('-'); buf.append(makeString(getParameterNames(world))); buf.append('-'); buf.append(makeString(getExceptions(world))); buf.append('-'); return buf.toString(); } protected String getFieldSignatureString(World world) { StringBuffer buf = new StringBuffer(); buf.append(makeString(getModifiers(world))); buf.append('-'); buf.append(getName()); buf.append('-'); buf.append(makeString(getDeclaringType())); buf.append('-'); buf.append(makeString(getReturnType())); buf.append('-'); return buf.toString(); } protected String makeString(int i) { return Integer.toString(i, 16); //??? expensive } protected String makeString(UnresolvedType t) { // this is the inverse of the odd behavior for Class.forName w/ arrays if (t.isArray()) { // this behavior matches the string used by the eclipse compiler for Foo.class literals return t.getSignature().replace('/', '.'); } else { return t.getName(); } } protected String makeString(UnresolvedType[] types) { if (types == null) return ""; StringBuffer buf = new StringBuffer(); for (int i = 0, len=types.length; i < len; i++) { buf.append(makeString(types[i])); buf.append(':'); } return buf.toString(); } protected String makeString(String[] names) { if (names == null) return ""; StringBuffer buf = new StringBuffer(); for (int i = 0, len=names.length; i < len; i++) { buf.append(names[i]); buf.append(':'); } return buf.toString(); } /* (non-Javadoc) * @see org.aspectj.weaver.Member#getParameterNames(org.aspectj.weaver.World) */ public String[] getParameterNames(World world) { return resolve(world).getParameterNames(); } /** * All the signatures that a join point with this member as its signature has. */ public Iterator getJoinPointSignatures(World inAWorld) { if (joinPointSignatures == null) { joinPointSignatures = new JoinPointSignatureIterator(this,inAWorld); } joinPointSignatures.reset(); return joinPointSignatures; } }
161,502
Bug 161502 UnsupportedOperationException thrown: unable to parameterize unresolved type: Pjava/util/List<+Ljava/lang/Object; >;
Generic parameters (like List<? extends T>) in pointcuts throw UnsupportedOperationException. java.lang.UnsupportedOperationException at org.aspectj.weaver.UnresolvedType.parameterize(UnresolvedType.java: 220) at org.aspectj.weaver.patterns.ExactTypePattern.parameterizeWith (ExactTypePattern.java:244) at org.aspectj.weaver.patterns.SignaturePattern.parameterizeWith (SignaturePattern.java:265) at org.aspectj.weaver.patterns.KindedPointcut.parameterizeWith (KindedPointcut.java:381) at org.aspectj.weaver.bcel.BcelAdvice.parameterizeWith (BcelAdvice.java:93) at org.aspectj.weaver.ResolvedType.getDeclaredAdvice (ResolvedType.java:710) at org.aspectj.weaver.ResolvedType.getDeclaredShadowMungers (ResolvedType.java:739) at org.aspectj.weaver.ResolvedType.collectShadowMungers (ResolvedType.java:575) at org.aspectj.weaver.ResolvedType.collectCrosscuttingMembers (ResolvedType.java:504) at org.aspectj.weaver.CrosscuttingMembersSet.addOrReplaceAspect (CrosscuttingMembersSet.java:68) at org.aspectj.weaver.CrosscuttingMembersSet.addOrReplaceAspect (CrosscuttingMembersSet.java:57) at org.aspectj.weaver.bcel.BcelWeaver.prepareForWeave(BcelWeaver.java: 450) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.weave (AjCompilerAdapter.java:299) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.afterCompiling (AjCompilerAdapter.java:192) at org.aspectj.ajdt.internal.compiler.CompilerAdapter.ajc $afterReturning$org_aspectj_ajdt_internal_compiler_CompilerAdapter$2 $f9cc9ca0(CompilerAdapter.aj:70) at org.aspectj.org.eclipse.jdt.internal.compiler.Compiler.compile (Compiler.java:367) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.performCompilation (AjBuildManager.java:887) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.doBuild (AjBuildManager.java:244) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.batchBuild (AjBuildManager.java:163) at org.aspectj.ajde.internal.CompilerAdapter.compile (CompilerAdapter.java:122) at org.aspectj.ajde.internal.AspectJBuildManager$CompilerThread.run (AspectJBuildManager.java:191) UnsupportedOperationException thrown: unable to parameterize unresolved type: Pjava/util/List<+Ljava/lang/Object;>; To reproduce this exception compile the following code snippet. import java.util.ArrayList; import java.util.List; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; public class Main { public List<? extends Element> getElements() { return new ArrayList<Element>(); } class Element {}; @Aspect static abstract class Base<T> { @Around("call(List<? extends T> *.*(..))") public List<? extends T> elementList(ProceedingJoinPoint thisJoinPoint) { try { return (List<? extends T>)thisJoinPoint.proceed(); } catch (Throwable e) { throw new RuntimeException(e); } } } @Aspect static class Concrete extends Base<Element> {} public static void main(String[] args) { new Main().getElements(); } }
resolved fixed
7b40e7e
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2006-10-24T12:42:57Z"
"2006-10-19T01:06:40Z"
tests/bugs153/pr161502/Main.java
161,502
Bug 161502 UnsupportedOperationException thrown: unable to parameterize unresolved type: Pjava/util/List<+Ljava/lang/Object; >;
Generic parameters (like List<? extends T>) in pointcuts throw UnsupportedOperationException. java.lang.UnsupportedOperationException at org.aspectj.weaver.UnresolvedType.parameterize(UnresolvedType.java: 220) at org.aspectj.weaver.patterns.ExactTypePattern.parameterizeWith (ExactTypePattern.java:244) at org.aspectj.weaver.patterns.SignaturePattern.parameterizeWith (SignaturePattern.java:265) at org.aspectj.weaver.patterns.KindedPointcut.parameterizeWith (KindedPointcut.java:381) at org.aspectj.weaver.bcel.BcelAdvice.parameterizeWith (BcelAdvice.java:93) at org.aspectj.weaver.ResolvedType.getDeclaredAdvice (ResolvedType.java:710) at org.aspectj.weaver.ResolvedType.getDeclaredShadowMungers (ResolvedType.java:739) at org.aspectj.weaver.ResolvedType.collectShadowMungers (ResolvedType.java:575) at org.aspectj.weaver.ResolvedType.collectCrosscuttingMembers (ResolvedType.java:504) at org.aspectj.weaver.CrosscuttingMembersSet.addOrReplaceAspect (CrosscuttingMembersSet.java:68) at org.aspectj.weaver.CrosscuttingMembersSet.addOrReplaceAspect (CrosscuttingMembersSet.java:57) at org.aspectj.weaver.bcel.BcelWeaver.prepareForWeave(BcelWeaver.java: 450) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.weave (AjCompilerAdapter.java:299) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.afterCompiling (AjCompilerAdapter.java:192) at org.aspectj.ajdt.internal.compiler.CompilerAdapter.ajc $afterReturning$org_aspectj_ajdt_internal_compiler_CompilerAdapter$2 $f9cc9ca0(CompilerAdapter.aj:70) at org.aspectj.org.eclipse.jdt.internal.compiler.Compiler.compile (Compiler.java:367) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.performCompilation (AjBuildManager.java:887) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.doBuild (AjBuildManager.java:244) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.batchBuild (AjBuildManager.java:163) at org.aspectj.ajde.internal.CompilerAdapter.compile (CompilerAdapter.java:122) at org.aspectj.ajde.internal.AspectJBuildManager$CompilerThread.run (AspectJBuildManager.java:191) UnsupportedOperationException thrown: unable to parameterize unresolved type: Pjava/util/List<+Ljava/lang/Object;>; To reproduce this exception compile the following code snippet. import java.util.ArrayList; import java.util.List; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; public class Main { public List<? extends Element> getElements() { return new ArrayList<Element>(); } class Element {}; @Aspect static abstract class Base<T> { @Around("call(List<? extends T> *.*(..))") public List<? extends T> elementList(ProceedingJoinPoint thisJoinPoint) { try { return (List<? extends T>)thisJoinPoint.proceed(); } catch (Throwable e) { throw new RuntimeException(e); } } } @Aspect static class Concrete extends Base<Element> {} public static void main(String[] args) { new Main().getElements(); } }
resolved fixed
7b40e7e
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2006-10-24T12:42:57Z"
"2006-10-19T01:06:40Z"
tests/bugs153/pr161502/Main2.java
161,502
Bug 161502 UnsupportedOperationException thrown: unable to parameterize unresolved type: Pjava/util/List<+Ljava/lang/Object; >;
Generic parameters (like List<? extends T>) in pointcuts throw UnsupportedOperationException. java.lang.UnsupportedOperationException at org.aspectj.weaver.UnresolvedType.parameterize(UnresolvedType.java: 220) at org.aspectj.weaver.patterns.ExactTypePattern.parameterizeWith (ExactTypePattern.java:244) at org.aspectj.weaver.patterns.SignaturePattern.parameterizeWith (SignaturePattern.java:265) at org.aspectj.weaver.patterns.KindedPointcut.parameterizeWith (KindedPointcut.java:381) at org.aspectj.weaver.bcel.BcelAdvice.parameterizeWith (BcelAdvice.java:93) at org.aspectj.weaver.ResolvedType.getDeclaredAdvice (ResolvedType.java:710) at org.aspectj.weaver.ResolvedType.getDeclaredShadowMungers (ResolvedType.java:739) at org.aspectj.weaver.ResolvedType.collectShadowMungers (ResolvedType.java:575) at org.aspectj.weaver.ResolvedType.collectCrosscuttingMembers (ResolvedType.java:504) at org.aspectj.weaver.CrosscuttingMembersSet.addOrReplaceAspect (CrosscuttingMembersSet.java:68) at org.aspectj.weaver.CrosscuttingMembersSet.addOrReplaceAspect (CrosscuttingMembersSet.java:57) at org.aspectj.weaver.bcel.BcelWeaver.prepareForWeave(BcelWeaver.java: 450) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.weave (AjCompilerAdapter.java:299) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.afterCompiling (AjCompilerAdapter.java:192) at org.aspectj.ajdt.internal.compiler.CompilerAdapter.ajc $afterReturning$org_aspectj_ajdt_internal_compiler_CompilerAdapter$2 $f9cc9ca0(CompilerAdapter.aj:70) at org.aspectj.org.eclipse.jdt.internal.compiler.Compiler.compile (Compiler.java:367) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.performCompilation (AjBuildManager.java:887) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.doBuild (AjBuildManager.java:244) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.batchBuild (AjBuildManager.java:163) at org.aspectj.ajde.internal.CompilerAdapter.compile (CompilerAdapter.java:122) at org.aspectj.ajde.internal.AspectJBuildManager$CompilerThread.run (AspectJBuildManager.java:191) UnsupportedOperationException thrown: unable to parameterize unresolved type: Pjava/util/List<+Ljava/lang/Object;>; To reproduce this exception compile the following code snippet. import java.util.ArrayList; import java.util.List; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; public class Main { public List<? extends Element> getElements() { return new ArrayList<Element>(); } class Element {}; @Aspect static abstract class Base<T> { @Around("call(List<? extends T> *.*(..))") public List<? extends T> elementList(ProceedingJoinPoint thisJoinPoint) { try { return (List<? extends T>)thisJoinPoint.proceed(); } catch (Throwable e) { throw new RuntimeException(e); } } } @Aspect static class Concrete extends Base<Element> {} public static void main(String[] args) { new Main().getElements(); } }
resolved fixed
7b40e7e
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2006-10-24T12:42:57Z"
"2006-10-19T01:06:40Z"
tests/src/org/aspectj/systemtest/ajc153/Ajc153Tests.java
/******************************************************************************* * Copyright (c) 2006 IBM * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Andy Clement - initial API and implementation *******************************************************************************/ package org.aspectj.systemtest.ajc153; import java.io.File; import junit.framework.Test; import org.aspectj.asm.AsmManager; import org.aspectj.asm.IHierarchy; import org.aspectj.asm.IProgramElement; import org.aspectj.testing.Utils; import org.aspectj.testing.XMLBasedAjcTestCase; import org.aspectj.weaver.bcel.Utility; public class Ajc153Tests extends org.aspectj.testing.XMLBasedAjcTestCase { //public void testGenericsProblem_pr151978() { runTest("generics problem");} // public void testArgnamesAndJavac_pr148381() { runTest("argNames and javac");} // public void testCFlowXMLAspectLTW_pr149096() { runTest("cflow xml concrete aspect"); } // public void testAmbiguousBinding_pr121805() { runTest("ambiguous binding");} // public void testNegatedAnnotationMatchingProblem_pr153464() { runTest("negated annotation matching problem");} public void testNoNPEDueToMissingType_pr149908() { runTest("ensure no npe due to missing type");} public void testNoNPEDueToMember_pr149908() { runTest("ensure no npe due to missing member");} public void testPTWgetWithinTypeName_pr123423_1() { runTest("basic usage of getWithinTypeName");} public void testPTWgetWithinTypeName_pr123423_2() { runTest("basic usage of getWithinTypeName - multiple types");} public void testPTWgetWithinTypeName_pr123423_3() { runTest("basic usage of getWithinTypeName - non matching types");} public void testPTWgetWithinTypeName_pr123423_4() { runTest("basic usage of getWithinTypeName - types in packages");} public void testPTWgetWithinTypeName_pr123423_5() { runTest("basic usage of getWithinTypeName - annotation style");} public void testTurningOffBcelCaching_pr160674() { runTest("turning off bcel caching");} public void testNoIllegalStateExceptionWithGenericInnerAspect_pr156058() { runTest("no IllegalStateException with generic inner aspect"); } public void testNoIllegalStateExceptionWithGenericInnerAspect_pr156058_2() { runTest("no IllegalStateException with generic inner aspect - 2"); } public void testDeclareMethodAnnotations_pr159143() { runTest("declare method annotations");} public void testVisibilityProblem_pr149071() { runTest("visibility problem");} public void testMissingLineNumbersInStacktraceAfter_pr145442() { runTest("missing line numbers in stacktrace after");} public void testMissingLineNumbersInStacktraceAround_pr145442() { runTest("missing line numbers in stacktrace around");} public void testGenericArrays_pr158624() { runTest("generics and arrays"); } public void testMissingLineNumbersInStacktraceBefore_pr145442() { runTest("missing line numbers in stacktrace before");} public void testMissingLineNumbersInStacktraceBefore_pr145442_Binary() { runTest("missing line numbers in stacktrace before - binary");} public void testAnnotationStylePointcutNPE_pr158412() { runTest("annotation style pointcut npe"); } public void testAnnotationStylePointcutNPE_pr158412_2() { runTest("annotation style pointcut npe - 2"); } public void testAnnotationsCallConstructors_pr158126() { runTest("annotations, call and constructors problem");} public void testIllegalStateExceptionGenerics_pr153845() { runTest("IllegalStateException at GenericSignatureParser.java"); } public void testNoIllegalStateExceptionFromAsmDelegate_pr153490_1() { runTest("no illegal state exception from AsmDelegate - 1");} public void testNoIllegalStateExceptionFromAsmDelegate_pr153490_2() { runTest("no illegal state exception from AsmDelegate - 2");} public void testNoIllegalStateExceptionFromAsmDelegate_pr153490_3() { runTest("no illegal state exception from AsmDelegate - 3");} public void testAnnotMethod_pr156962() { runTest("Test Annot Method");} public void testAnnotMethodHasMember_pr156962() { runTest("Test Annot Method Has Member"); } public void testMixingGenerics_pr152848() { runTest("mixing generics"); } public void testIncorrectStaticinitializationWeaving_pr149560_1() { runTest("incorrect staticinitialization weaving - codestyle");} public void testIncorrectStaticinitializationWeaving_pr149560_2() { runTest("incorrect staticinitialization weaving - annstyle");} public void testIncorrectDeprecatedAnnotationProcessing_pr154332() { runTest("incorrect deprecated annotation processing");} public void testPipeliningProblemWithAnnotationsDecp_pr153380_1() { runTest("pipelining decps");} public void testUnwantedPointcutWarning_pr148219() { runTest("unwanted warning for pointcut");} public void testDecpAndCflowadderMungerClash_pr152631() { runTest("decp and cflowadder munger clash");} public void testGenericInheritanceDecp_pr150095() { runTest("generics, inheritance and decp");} public void testIllegalStateException_pr148737() { runTest("illegalstateexception for non generic type");} public void testAtajInheritance_pr149305_1() { runTest("ataj inheritance - 1");} public void testAtajInheritance_pr149305_2() { runTest("ataj inheritance - 2");} public void testAtajInheritance_pr149305_3() { runTest("ataj inheritance - 3");} public void testVerificationFailureForAspectOf_pr148693() { runTest("verification problem"); // build the code Utils.verifyClass(ajc,"mypackage.MyAspect"); // verify it <<< BRAND NEW VERIFY UTILITY FOR EVERYONE TO TRY ;) } public void testIncorrectAnnotationValue_pr148537() { runTest("incorrect annotation value");} public void testVerifyErrNoTypeCflowField_pr145693_1() { runTest("verifyErrNoTypeCflowField"); } public void testVerifyErrInpathNoTypeCflowField_pr145693_2() { runTest("verifyErrInpathNoTypeCflowField"); } public void testCpathNoTypeCflowField_pr145693_3() { runTest("cpathNoTypeCflowField"); } // public void testAdviceNotWovenAspectPath_pr147841() { runTest("advice not woven on aspectpath");} public void testGenericSignatures_pr148409() { runTest("generic signature problem"); } // public void testBrokenIfArgsCflowAtAj_pr145018() { runTest("ataj crashing with cflow, if and args");} public void testCantFindType_pr149322_01() {runTest("can't find type on interface call 1");} public void testCantFindType_pr149322_02() {runTest("can't find type on interface call 2");} public void testCantFindType_pr149322_03() {runTest("can't find type on interface call 3");} public void testParsingBytecodeLess_pr152871() { Utility.testingParseCounter=0; runTest("parsing bytecode less"); assertTrue("Should have called parse 5 times, not "+Utility.testingParseCounter+" times",Utility.testingParseCounter==5); // 5 means: // (1)=registerAspect // (2,3)=checkingIfShouldWeave,AcceptingResult for class // (4,5)=checkingIfShouldWeave,AcceptingResult for aspect } public void testMatchVolatileField_pr150671() {runTest("match volatile field");}; public void testDuplicateJVMTIAgents_pr151938() {runTest("Duplicate JVMTI agents");}; public void testLTWWorldWithAnnotationMatching_pr153572() { runTest("LTWWorld with annotation matching");} public void testReweavableAspectNotRegistered_pr129525 () { runTest("reweavableAspectNotRegistered error"); } public void testNPEinConstructorSignatureImpl_pr155972 () { runTest("NPE in ConstructorSignatureImpl"); } public void testNPEinFieldSignatureImpl_pr155972 () { runTest("NPE in FieldSignatureImpl"); } public void testNPEinInitializerSignatureImpl_pr155972 () { runTest("NPE in InitializerSignatureImpl"); } public void testLineNumberTableCorrectWithGenericsForEachAndContinue_pr155763() { runTest("ensure LineNumberTable correct with generics, for each and continue"); } public void testDeclareSoftDoesntAllowUndeclaredExInAnonInnerClass_pr151772() { runTest("ensure declare soft doesn't allow undeclared exception in anonymous inner class"); } public void testDeclareSoftDoesntAllowUndeclaredExInAnonInnerClass_pr151772_2() { runTest("ensure declare soft doesn't allow undeclared exception in anonymous inner class - 2"); } public void testDeclareSoftAndInnerClasses_pr125981() { runTest("declare soft and inner classes"); } public void testGetSourceSignature_pr148908() { runTest("ensure getSourceSignature correct with static field"); IHierarchy top = AsmManager.getDefault().getHierarchy(); IProgramElement ipe = top.findElementForLabel(top.getRoot(), IProgramElement.Kind.FIELD,"MY_COMPARATOR"); String expected = "static final Comparator MY_COMPARATOR = new Comparator() {\n" + " public int compare(Object o1, Object o2) {\n" + " return 0;\n" + " }\n" + "};"; assertEquals("expected source signature to be " + expected + " but found " + ipe.getSourceSignature(), expected, ipe.getSourceSignature()); } public void testNPEWithCustomAgent_pr158005() { runTest("NPE with custom agent"); } public void testWeaveConcreteSubaspectWithAdvice_pr132080() { runTest("Weave concrete sub-aspect with advice"); } public void testWeaveConcreteSubaspectWithITD_pr132080() { runTest("Weave concrete sub-aspect with ITD"); } public void testWeaveConcreteSubaspectWithAroundClosure_pr132080() { runTest("Weave concrete sub-aspect with around closure"); } public void testWeaveConcreteSubaspectWithCflow_pr132080() { runTest("Weave concrete sub-aspect with cflow"); } public void testNPEWithLTWPointcutLibraryAndMissingAspectDependency_pr158957 () { runTest("NPE with LTW, pointcut library and missing aspect dependency"); } public void testNoInvalidAbsoluteTypeNameWarning_pr156904_1() {runTest("ensure no invalidAbsoluteTypeName when do match - 1");} public void testNoInvalidAbsoluteTypeNameWarning_pr156904_2() {runTest("ensure no invalidAbsoluteTypeName when do match - 2");} public void testNoInvalidAbsoluteTypeNameWarning_pr156904_3() {runTest("ensure no invalidAbsoluteTypeName when do match - 3");} public void testNoInvalidAbsoluteTypeNameWarning_pr156904_4() {runTest("ensure no invalidAbsoluteTypeName when do match - 4");} public void testNoNPEWithThrownExceptionWarningAndAtAspectj_pr161217() {runTest("NPE with thrown exception warning and at aspectj");} ///////////////////////////////////////// public static Test suite() { return XMLBasedAjcTestCase.loadSuite(Ajc153Tests.class); } protected File getSpecFile() { return new File("../tests/src/org/aspectj/systemtest/ajc153/ajc153.xml"); } }
161,502
Bug 161502 UnsupportedOperationException thrown: unable to parameterize unresolved type: Pjava/util/List<+Ljava/lang/Object; >;
Generic parameters (like List<? extends T>) in pointcuts throw UnsupportedOperationException. java.lang.UnsupportedOperationException at org.aspectj.weaver.UnresolvedType.parameterize(UnresolvedType.java: 220) at org.aspectj.weaver.patterns.ExactTypePattern.parameterizeWith (ExactTypePattern.java:244) at org.aspectj.weaver.patterns.SignaturePattern.parameterizeWith (SignaturePattern.java:265) at org.aspectj.weaver.patterns.KindedPointcut.parameterizeWith (KindedPointcut.java:381) at org.aspectj.weaver.bcel.BcelAdvice.parameterizeWith (BcelAdvice.java:93) at org.aspectj.weaver.ResolvedType.getDeclaredAdvice (ResolvedType.java:710) at org.aspectj.weaver.ResolvedType.getDeclaredShadowMungers (ResolvedType.java:739) at org.aspectj.weaver.ResolvedType.collectShadowMungers (ResolvedType.java:575) at org.aspectj.weaver.ResolvedType.collectCrosscuttingMembers (ResolvedType.java:504) at org.aspectj.weaver.CrosscuttingMembersSet.addOrReplaceAspect (CrosscuttingMembersSet.java:68) at org.aspectj.weaver.CrosscuttingMembersSet.addOrReplaceAspect (CrosscuttingMembersSet.java:57) at org.aspectj.weaver.bcel.BcelWeaver.prepareForWeave(BcelWeaver.java: 450) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.weave (AjCompilerAdapter.java:299) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.afterCompiling (AjCompilerAdapter.java:192) at org.aspectj.ajdt.internal.compiler.CompilerAdapter.ajc $afterReturning$org_aspectj_ajdt_internal_compiler_CompilerAdapter$2 $f9cc9ca0(CompilerAdapter.aj:70) at org.aspectj.org.eclipse.jdt.internal.compiler.Compiler.compile (Compiler.java:367) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.performCompilation (AjBuildManager.java:887) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.doBuild (AjBuildManager.java:244) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.batchBuild (AjBuildManager.java:163) at org.aspectj.ajde.internal.CompilerAdapter.compile (CompilerAdapter.java:122) at org.aspectj.ajde.internal.AspectJBuildManager$CompilerThread.run (AspectJBuildManager.java:191) UnsupportedOperationException thrown: unable to parameterize unresolved type: Pjava/util/List<+Ljava/lang/Object;>; To reproduce this exception compile the following code snippet. import java.util.ArrayList; import java.util.List; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; public class Main { public List<? extends Element> getElements() { return new ArrayList<Element>(); } class Element {}; @Aspect static abstract class Base<T> { @Around("call(List<? extends T> *.*(..))") public List<? extends T> elementList(ProceedingJoinPoint thisJoinPoint) { try { return (List<? extends T>)thisJoinPoint.proceed(); } catch (Throwable e) { throw new RuntimeException(e); } } } @Aspect static class Concrete extends Base<Element> {} public static void main(String[] args) { new Main().getElements(); } }
resolved fixed
7b40e7e
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2006-10-24T12:42:57Z"
"2006-10-19T01:06:40Z"
weaver/src/org/aspectj/weaver/BoundedReferenceType.java
/* ******************************************************************* * Copyright (c) 2005 Contributors. * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Eclipse Public License v1.0 * which accompanies this distribution and is available at * http://eclipse.org/legal/epl-v10.html * * Contributors: * Adrian Colyer Initial implementation * ******************************************************************/ package org.aspectj.weaver; import java.util.Collection; import java.util.Collections; import org.aspectj.weaver.patterns.PerClause; /** * 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) */ public class BoundedReferenceType extends ReferenceType { protected ReferenceType[] additionalInterfaceBounds = new ReferenceType[0]; protected boolean isExtends = true; protected boolean isSuper = false; public BoundedReferenceType(ReferenceType aBound, boolean isExtends, World world) { super((isExtends ? "+" : "-") + aBound.signature,world); this.isExtends = isExtends; this.isSuper = !isExtends; if (isExtends) { setUpperBound(aBound); } else { setLowerBound(aBound); setUpperBound(world.resolve(UnresolvedType.OBJECT)); } setDelegate(new ReferenceTypeReferenceTypeDelegate((ReferenceType)getUpperBound())); } public BoundedReferenceType(ReferenceType aBound, boolean isExtends, World world, ReferenceType[] additionalInterfaces) { this(aBound,isExtends,world); this.additionalInterfaceBounds = additionalInterfaces; } public ReferenceType[] getAdditionalBounds() { return additionalInterfaceBounds; } /** * only for use when resolving GenericsWildcardTypeX or a TypeVariableReferenceType */ protected BoundedReferenceType(String sig, String sigErasure, World world) { super(sig, sigErasure, world); setUpperBound(world.resolve(UnresolvedType.OBJECT)); setDelegate(new ReferenceTypeReferenceTypeDelegate((ReferenceType)getUpperBound())); } public ReferenceType[] getInterfaceBounds() { return additionalInterfaceBounds; } public boolean hasLowerBound() { return getLowerBound() != null; } public boolean isExtends() { return (isExtends && !getUpperBound().getSignature().equals("Ljava/lang/Object;")); } public boolean isSuper() { return isSuper; } 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()) { ResolvedType myUpperBound = (ResolvedType) getUpperBound(); ResolvedType myLowerBound = (ResolvedType) getLowerBound(); if (isExtends()) { if (aCandidateType.isExtends()) { return myUpperBound.isAssignableFrom((ResolvedType)aCandidateType.getUpperBound()); } else if (aCandidateType.isSuper()) { return myUpperBound == aCandidateType.getLowerBound(); } else { return true; // it's '?' } } else if (isSuper()) { if (aCandidateType.isSuper()) { return ((ResolvedType)aCandidateType.getLowerBound()).isAssignableFrom(myLowerBound); } else if (aCandidateType.isExtends()) { return myLowerBound == aCandidateType.getUpperBound(); } else { return true; } } else { return true; } } else { return false; } } public String getSimpleName() { if (!isExtends() && !isSuper()) return "?"; if (isExtends()) { return ("? extends " + getUpperBound().getSimpleName()); } else { return ("? super " + getLowerBound().getSimpleName()); } } // override to include additional interface bounds... 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; } } public boolean isGenericWildcard() { return true; } protected static class ReferenceTypeReferenceTypeDelegate extends AbstractReferenceTypeDelegate { public ReferenceTypeReferenceTypeDelegate(ReferenceType backing) { super(backing,false); } public void addAnnotation(AnnotationX annotationX) { throw new UnsupportedOperationException("What on earth do you think you are doing???"); } public boolean isAspect() { return resolvedTypeX.isAspect(); } public boolean isAnnotationStyleAspect() { return resolvedTypeX.isAnnotationStyleAspect(); } public boolean isInterface() { return resolvedTypeX.isInterface(); } public boolean isEnum() { return resolvedTypeX.isEnum(); } public boolean isAnnotation() { return resolvedTypeX.isAnnotation(); } public boolean isAnnotationWithRuntimeRetention() { return resolvedTypeX.isAnnotationWithRuntimeRetention(); } public boolean isAnonymous() { return resolvedTypeX.isAnonymous(); } public boolean isNested() { return resolvedTypeX.isNested(); } public ResolvedType getOuterClass() { return resolvedTypeX.getOuterClass(); } public String getRetentionPolicy() { return resolvedTypeX.getRetentionPolicy(); } public boolean canAnnotationTargetType() { return resolvedTypeX.canAnnotationTargetType(); } public AnnotationTargetKind[] getAnnotationTargetKinds() { return resolvedTypeX.getAnnotationTargetKinds(); } public boolean isGeneric() { return resolvedTypeX.isGenericType(); } public String getDeclaredGenericSignature() { return resolvedTypeX.getDeclaredGenericSignature(); } public boolean hasAnnotation(UnresolvedType ofType) { return resolvedTypeX.hasAnnotation(ofType); } public AnnotationX[] getAnnotations() { return resolvedTypeX.getAnnotations(); } public ResolvedType[] getAnnotationTypes() { return resolvedTypeX.getAnnotationTypes(); } public ResolvedMember[] getDeclaredFields() { return resolvedTypeX.getDeclaredFields(); } public ResolvedType[] getDeclaredInterfaces() { return resolvedTypeX.getDeclaredInterfaces(); } public ResolvedMember[] getDeclaredMethods() { return resolvedTypeX.getDeclaredMethods(); } public ResolvedMember[] getDeclaredPointcuts() { return resolvedTypeX.getDeclaredPointcuts(); } public PerClause getPerClause() { return resolvedTypeX.getPerClause(); } public Collection getDeclares() { return resolvedTypeX.getDeclares(); } public Collection getTypeMungers() { return resolvedTypeX.getTypeMungers(); } public Collection getPrivilegedAccesses() { return Collections.EMPTY_LIST; } public int getModifiers() { return resolvedTypeX.getModifiers(); } public ResolvedType getSuperclass() { return resolvedTypeX.getSuperclass(); } public WeaverStateInfo getWeaverState() { return null; } public TypeVariable[] getTypeVariables() { return resolvedTypeX.getTypeVariables(); } public void ensureDelegateConsistent() { resolvedTypeX.getDelegate().ensureDelegateConsistent(); } } }
161,502
Bug 161502 UnsupportedOperationException thrown: unable to parameterize unresolved type: Pjava/util/List<+Ljava/lang/Object; >;
Generic parameters (like List<? extends T>) in pointcuts throw UnsupportedOperationException. java.lang.UnsupportedOperationException at org.aspectj.weaver.UnresolvedType.parameterize(UnresolvedType.java: 220) at org.aspectj.weaver.patterns.ExactTypePattern.parameterizeWith (ExactTypePattern.java:244) at org.aspectj.weaver.patterns.SignaturePattern.parameterizeWith (SignaturePattern.java:265) at org.aspectj.weaver.patterns.KindedPointcut.parameterizeWith (KindedPointcut.java:381) at org.aspectj.weaver.bcel.BcelAdvice.parameterizeWith (BcelAdvice.java:93) at org.aspectj.weaver.ResolvedType.getDeclaredAdvice (ResolvedType.java:710) at org.aspectj.weaver.ResolvedType.getDeclaredShadowMungers (ResolvedType.java:739) at org.aspectj.weaver.ResolvedType.collectShadowMungers (ResolvedType.java:575) at org.aspectj.weaver.ResolvedType.collectCrosscuttingMembers (ResolvedType.java:504) at org.aspectj.weaver.CrosscuttingMembersSet.addOrReplaceAspect (CrosscuttingMembersSet.java:68) at org.aspectj.weaver.CrosscuttingMembersSet.addOrReplaceAspect (CrosscuttingMembersSet.java:57) at org.aspectj.weaver.bcel.BcelWeaver.prepareForWeave(BcelWeaver.java: 450) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.weave (AjCompilerAdapter.java:299) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.afterCompiling (AjCompilerAdapter.java:192) at org.aspectj.ajdt.internal.compiler.CompilerAdapter.ajc $afterReturning$org_aspectj_ajdt_internal_compiler_CompilerAdapter$2 $f9cc9ca0(CompilerAdapter.aj:70) at org.aspectj.org.eclipse.jdt.internal.compiler.Compiler.compile (Compiler.java:367) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.performCompilation (AjBuildManager.java:887) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.doBuild (AjBuildManager.java:244) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.batchBuild (AjBuildManager.java:163) at org.aspectj.ajde.internal.CompilerAdapter.compile (CompilerAdapter.java:122) at org.aspectj.ajde.internal.AspectJBuildManager$CompilerThread.run (AspectJBuildManager.java:191) UnsupportedOperationException thrown: unable to parameterize unresolved type: Pjava/util/List<+Ljava/lang/Object;>; To reproduce this exception compile the following code snippet. import java.util.ArrayList; import java.util.List; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; public class Main { public List<? extends Element> getElements() { return new ArrayList<Element>(); } class Element {}; @Aspect static abstract class Base<T> { @Around("call(List<? extends T> *.*(..))") public List<? extends T> elementList(ProceedingJoinPoint thisJoinPoint) { try { return (List<? extends T>)thisJoinPoint.proceed(); } catch (Throwable e) { throw new RuntimeException(e); } } } @Aspect static class Concrete extends Base<Element> {} public static void main(String[] args) { new Main().getElements(); } }
resolved fixed
7b40e7e
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2006-10-24T12:42:57Z"
"2006-10-19T01:06:40Z"
weaver/src/org/aspectj/weaver/Checker.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Eclipse Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * PARC initial implementation * ******************************************************************/ package org.aspectj.weaver; import java.util.Collection; import java.util.Collections; import java.util.Map; import org.aspectj.asm.AsmManager; import org.aspectj.asm.IRelationship; import org.aspectj.bridge.IMessage; import org.aspectj.bridge.ISourceLocation; import org.aspectj.bridge.Message; import org.aspectj.weaver.patterns.DeclareErrorOrWarning; import org.aspectj.weaver.patterns.PerClause; import org.aspectj.weaver.patterns.Pointcut; public class Checker extends ShadowMunger { private String msg; private boolean isError; public Checker(DeclareErrorOrWarning deow) { super(deow.getPointcut(), deow.getStart(), deow.getEnd(), deow.getSourceContext()); this.msg = deow.getMessage(); this.isError = deow.isError(); } private Checker(Pointcut pc, int start, int end, ISourceContext context) { super(pc,start,end,context); } public ShadowMunger concretize(ResolvedType fromType, World world, PerClause clause) { pointcut = pointcut.concretize(fromType, getDeclaringType(), 0, this); return this; } public void specializeOn(Shadow shadow) { throw new RuntimeException("illegal state"); } public void implementOn(Shadow shadow) { throw new RuntimeException("illegal state"); } public ShadowMunger parameterizeWith(ResolvedType declaringType,Map typeVariableMap) { Checker ret = new Checker( getPointcut().parameterizeWith(typeVariableMap), getStart(), getEnd(), this.sourceContext); ret.msg = this.msg; ret.isError = this.isError; return ret; } public boolean match(Shadow shadow, World world) { if (super.match(shadow, world)) { IMessage message = new Message( msg, shadow.toString(), isError ? IMessage.ERROR : IMessage.WARNING, shadow.getSourceLocation(), null, new ISourceLocation[]{this.getSourceLocation()},true, 0, // id -1,-1); // source start/end world.getMessageHandler().handleMessage(message); if (world.getCrossReferenceHandler() != null) { world.getCrossReferenceHandler().addCrossReference(this.getSourceLocation(), shadow.getSourceLocation(), (this.isError?IRelationship.Kind.DECLARE_ERROR:IRelationship.Kind.DECLARE_WARNING),false); } if (world.getModel() != null) { AsmRelationshipProvider.getDefault().checkerMunger(world.getModel(), shadow, this); } } return false; } public int compareTo(Object other) { return 0; } public Collection getThrownExceptions() { return Collections.EMPTY_LIST; } /** * Default to true * FIXME Alex: ATAJ is that ok in all cases ? * @return */ public boolean mustCheckExceptions() { return true; } // XXX this perhaps ought to take account of the other fields in advice ... public boolean equals(Object other) { if (! (other instanceof Checker)) return false; Checker o = (Checker) other; return o.isError == isError && ((o.pointcut == null) ? (pointcut == null) : o.pointcut.equals(pointcut)) && (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 = -1; public int hashCode() { if (hashCode == -1) { int result = 17; result = 37*result + (isError?1:0); result = 37*result + ((pointcut == null) ? 0 : pointcut.hashCode()); hashCode = result; } return hashCode; } public boolean isError() { return isError; } }
161,502
Bug 161502 UnsupportedOperationException thrown: unable to parameterize unresolved type: Pjava/util/List<+Ljava/lang/Object; >;
Generic parameters (like List<? extends T>) in pointcuts throw UnsupportedOperationException. java.lang.UnsupportedOperationException at org.aspectj.weaver.UnresolvedType.parameterize(UnresolvedType.java: 220) at org.aspectj.weaver.patterns.ExactTypePattern.parameterizeWith (ExactTypePattern.java:244) at org.aspectj.weaver.patterns.SignaturePattern.parameterizeWith (SignaturePattern.java:265) at org.aspectj.weaver.patterns.KindedPointcut.parameterizeWith (KindedPointcut.java:381) at org.aspectj.weaver.bcel.BcelAdvice.parameterizeWith (BcelAdvice.java:93) at org.aspectj.weaver.ResolvedType.getDeclaredAdvice (ResolvedType.java:710) at org.aspectj.weaver.ResolvedType.getDeclaredShadowMungers (ResolvedType.java:739) at org.aspectj.weaver.ResolvedType.collectShadowMungers (ResolvedType.java:575) at org.aspectj.weaver.ResolvedType.collectCrosscuttingMembers (ResolvedType.java:504) at org.aspectj.weaver.CrosscuttingMembersSet.addOrReplaceAspect (CrosscuttingMembersSet.java:68) at org.aspectj.weaver.CrosscuttingMembersSet.addOrReplaceAspect (CrosscuttingMembersSet.java:57) at org.aspectj.weaver.bcel.BcelWeaver.prepareForWeave(BcelWeaver.java: 450) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.weave (AjCompilerAdapter.java:299) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.afterCompiling (AjCompilerAdapter.java:192) at org.aspectj.ajdt.internal.compiler.CompilerAdapter.ajc $afterReturning$org_aspectj_ajdt_internal_compiler_CompilerAdapter$2 $f9cc9ca0(CompilerAdapter.aj:70) at org.aspectj.org.eclipse.jdt.internal.compiler.Compiler.compile (Compiler.java:367) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.performCompilation (AjBuildManager.java:887) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.doBuild (AjBuildManager.java:244) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.batchBuild (AjBuildManager.java:163) at org.aspectj.ajde.internal.CompilerAdapter.compile (CompilerAdapter.java:122) at org.aspectj.ajde.internal.AspectJBuildManager$CompilerThread.run (AspectJBuildManager.java:191) UnsupportedOperationException thrown: unable to parameterize unresolved type: Pjava/util/List<+Ljava/lang/Object;>; To reproduce this exception compile the following code snippet. import java.util.ArrayList; import java.util.List; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; public class Main { public List<? extends Element> getElements() { return new ArrayList<Element>(); } class Element {}; @Aspect static abstract class Base<T> { @Around("call(List<? extends T> *.*(..))") public List<? extends T> elementList(ProceedingJoinPoint thisJoinPoint) { try { return (List<? extends T>)thisJoinPoint.proceed(); } catch (Throwable e) { throw new RuntimeException(e); } } } @Aspect static class Concrete extends Base<Element> {} public static void main(String[] args) { new Main().getElements(); } }
resolved fixed
7b40e7e
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2006-10-24T12:42:57Z"
"2006-10-19T01:06:40Z"
weaver/src/org/aspectj/weaver/ReferenceType.java
/* ******************************************************************* * Copyright (c) 2002 Contributors * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Eclipse Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * PARC initial implementation * Andy Clement - June 2005 - separated out from ResolvedType * ******************************************************************/ package org.aspectj.weaver; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.Map; import org.aspectj.bridge.ISourceLocation; import org.aspectj.weaver.bcel.BcelObjectType; import org.aspectj.weaver.patterns.Declare; import org.aspectj.weaver.patterns.PerClause; /** * A reference type represents some 'real' type, not a primitive, not an array - but * a real type, for example java.util.List. Each ReferenceType has a delegate * that is the underlying artifact - either an eclipse artifact or a * bcel artifact. If the type represents a raw type (i.e. there is * a generic form) then the genericType field is set to point to the * generic type. If it is for a parameterized type then the generic type * is also set to point to the generic form. */ public class ReferenceType extends ResolvedType { /** * For generic types, this list holds references to all the derived raw * and parameterized versions. We need this so that if the generic delegate * is swapped during incremental compilation, the delegate of the derivatives * is swapped also. */ private List/*ReferenceType*/ derivativeTypes = new ArrayList(); /** * For parameterized types (or the raw type) - this field points to the actual * reference type from which they are derived. */ ReferenceType genericType = null; ReferenceTypeDelegate delegate = null; int startPos = 0; int endPos = 0; public static ReferenceType fromTypeX(UnresolvedType tx, World world) { ReferenceType rt = new ReferenceType(tx.getErasureSignature(),world); rt.typeKind = tx.typeKind; return rt; } // cached values for members ResolvedMember[] parameterizedMethods = null; ResolvedMember[] parameterizedFields = null; ResolvedMember[] parameterizedPointcuts = null; ResolvedType[] parameterizedInterfaces = null; Collection parameterizedDeclares = null; //??? should set delegate before any use public ReferenceType(String signature, World world) { super(signature, world); } public ReferenceType(String signature, String signatureErasure, World world) { super(signature,signatureErasure, world); } /** * Constructor used when creating a parameterized type. */ public ReferenceType( ResolvedType theGenericType, ResolvedType[] theParameters, World aWorld) { super(makeParameterizedSignature(theGenericType,theParameters), theGenericType.signatureErasure, aWorld); ReferenceType genericReferenceType = (ReferenceType) theGenericType; this.typeParameters = theParameters; this.genericType = genericReferenceType; this.typeKind = TypeKind.PARAMETERIZED; this.delegate = genericReferenceType.getDelegate(); genericReferenceType.addDependentType(this); } /** * Constructor used when creating a raw type. */ public ReferenceType( ResolvedType theGenericType, World aWorld) { super(theGenericType.getErasureSignature(), theGenericType.getErasureSignature(), aWorld); ReferenceType genericReferenceType = (ReferenceType) theGenericType; this.typeParameters = null; this.genericType = genericReferenceType; this.typeKind = TypeKind.RAW; this.delegate = genericReferenceType.getDelegate(); genericReferenceType.addDependentType(this); } private void addDependentType(ReferenceType dependent) { this.derivativeTypes.add(dependent); } public String getSignatureForAttribute() { if (genericType == null || typeParameters == null) return getSignature(); return makeDeclaredSignature(genericType,typeParameters); } /** * Create a reference type for a generic type */ public ReferenceType(UnresolvedType genericType, World world) { super(genericType.getSignature(),world); typeKind=TypeKind.GENERIC; } public final boolean isClass() { return delegate.isClass(); } public final boolean isGenericType() { return !isParameterizedType() && !isRawType() && delegate.isGeneric(); } public String getGenericSignature() { String sig = delegate.getDeclaredGenericSignature(); return (sig == null) ? "" : sig; } public AnnotationX[] getAnnotations() { return delegate.getAnnotations(); } public void addAnnotation(AnnotationX annotationX) { delegate.addAnnotation(annotationX); } public boolean hasAnnotation(UnresolvedType ofType) { return delegate.hasAnnotation(ofType); } public ResolvedType[] getAnnotationTypes() { return delegate.getAnnotationTypes(); } public boolean isAspect() { return delegate.isAspect(); } public boolean isAnnotationStyleAspect() { return delegate.isAnnotationStyleAspect(); } public boolean isEnum() { return delegate.isEnum(); } public boolean isAnnotation() { return delegate.isAnnotation(); } public boolean isAnonymous() { return delegate.isAnonymous(); } public boolean isNested() { return delegate.isNested(); } public ResolvedType getOuterClass() { return delegate.getOuterClass(); } public String getRetentionPolicy() { return delegate.getRetentionPolicy(); } public boolean isAnnotationWithRuntimeRetention() { return delegate.isAnnotationWithRuntimeRetention(); } public boolean canAnnotationTargetType() { return delegate.canAnnotationTargetType(); } public AnnotationTargetKind[] getAnnotationTargetKinds() { return delegate.getAnnotationTargetKinds(); } // true iff the statement "this = (ThisType) other" would compile public final boolean isCoerceableFrom(ResolvedType o) { ResolvedType other = o.resolve(world); if (this.isAssignableFrom(other) || other.isAssignableFrom(this)) { return true; } if (this.isParameterizedType() && other.isParameterizedType()) { return isCoerceableFromParameterizedType(other); } if (!this.isInterface() && !other.isInterface()) { return false; } if (this.isFinal() || other.isFinal()) { return false; } // ??? needs to be Methods, not just declared methods? JLS 5.5 unclear ResolvedMember[] a = getDeclaredMethods(); ResolvedMember[] b = other.getDeclaredMethods(); //??? is this cast always safe for (int ai = 0, alen = a.length; ai < alen; ai++) { for (int bi = 0, blen = b.length; bi < blen; bi++) { if (! b[bi].isCompatibleWith(a[ai])) return false; } } return true; } private final boolean isCoerceableFromParameterizedType(ResolvedType other) { if (!other.isParameterizedType()) return false; ResolvedType myRawType = (ResolvedType) getRawType(); ResolvedType theirRawType = (ResolvedType) other.getRawType(); if (myRawType == theirRawType) { if (getTypeParameters().length == other.getTypeParameters().length) { // there's a chance it can be done ResolvedType[] myTypeParameters = getResolvedTypeParameters(); ResolvedType[] theirTypeParameters = other.getResolvedTypeParameters(); for (int i = 0; i < myTypeParameters.length; i++) { if (myTypeParameters[i] != theirTypeParameters[i]) { // thin ice now... but List<String> may still be coerceable from e.g. List<T> if (myTypeParameters[i].isGenericWildcard()) { BoundedReferenceType wildcard = (BoundedReferenceType) myTypeParameters[i]; if (!wildcard.canBeCoercedTo(theirTypeParameters[i])) return false; } else if (myTypeParameters[i].isTypeVariableReference()) { TypeVariableReferenceType tvrt = (TypeVariableReferenceType) myTypeParameters[i]; TypeVariable tv = tvrt.getTypeVariable(); tv.resolve(world); if (!tv.canBeBoundTo(theirTypeParameters[i])) return false; } else if (theirTypeParameters[i].isTypeVariableReference()) { TypeVariableReferenceType tvrt = (TypeVariableReferenceType) theirTypeParameters[i]; TypeVariable tv = tvrt.getTypeVariable(); tv.resolve(world); if (!tv.canBeBoundTo(myTypeParameters[i])) return false; } else { return false; } } } return true; } } else { // we do this walk for situations like the following: // Base<T>, Sub<S,T> extends Base<S> // is Sub<Y,Z> coerceable from Base<X> ??? for(Iterator i = getDirectSupertypes(); i.hasNext(); ) { ReferenceType parent = (ReferenceType) i.next(); if (parent.isCoerceableFromParameterizedType(other)) return true; } } return false; } public final boolean isAssignableFrom(ResolvedType other) { return isAssignableFrom(other,false); } // true iff the statement "this = other" would compile. public final boolean isAssignableFrom(ResolvedType other,boolean allowMissing) { if (other.isPrimitiveType()) { if (!world.isInJava5Mode()) return false; if (ResolvedType.validBoxing.contains(this.getSignature()+other.getSignature())) return true; } if (this == other) return true; if (this.getSignature().equals(ResolvedType.OBJECT.getSignature())) return true; if ((this.isRawType() || this.isGenericType()) && other.isParameterizedType()) { if (isAssignableFrom((ResolvedType)other.getRawType())) return true; } if (this.isRawType() && other.isGenericType()) { if (isAssignableFrom((ResolvedType)other.getRawType())) return true; } if (this.isGenericType() && other.isRawType()) { if (isAssignableFrom((ResolvedType)other.getGenericType())) return true; } if (this.isParameterizedType()) { // look at wildcards... if (((ReferenceType)this.getRawType()).isAssignableFrom(other)) { boolean wildcardsAllTheWay = true; ResolvedType[] myParameters = this.getResolvedTypeParameters(); for (int i = 0; i < myParameters.length; i++) { if (!myParameters[i].isGenericWildcard()) { wildcardsAllTheWay = false; } else if (myParameters[i].isExtends() || myParameters[i].isSuper()) { wildcardsAllTheWay = false; } } if (wildcardsAllTheWay && !other.isParameterizedType()) return true; // we have to match by parameters one at a time ResolvedType[] theirParameters = other.getResolvedTypeParameters(); boolean parametersAssignable = true; if (myParameters.length == theirParameters.length) { for (int i = 0; i < myParameters.length; i++) { if (myParameters[i] == theirParameters[i]) continue; if (!myParameters[i].isGenericWildcard()) { parametersAssignable = false; break; } else { BoundedReferenceType wildcardType = (BoundedReferenceType) myParameters[i]; if (!wildcardType.alwaysMatches(theirParameters[i])) { parametersAssignable = false; break; } } } } else { parametersAssignable = false; } if (parametersAssignable) return true; } } if (isTypeVariableReference() && !other.isTypeVariableReference()) { // eg. this=T other=Ljava/lang/Object; TypeVariable aVar = ((TypeVariableReference)this).getTypeVariable(); return aVar.resolve(world).canBeBoundTo(other); } if (other.isTypeVariableReference()) { TypeVariableReferenceType otherType = (TypeVariableReferenceType) other; if (this instanceof TypeVariableReference) { return ((TypeVariableReference)this).getTypeVariable()==otherType.getTypeVariable(); } else { // FIXME asc should this say canBeBoundTo?? return this.isAssignableFrom(otherType.getTypeVariable().getFirstBound().resolve(world)); } } if (allowMissing && other.isMissing()) return false; for(Iterator i = other.getDirectSupertypes(); i.hasNext(); ) { if (this.isAssignableFrom((ResolvedType) i.next(),allowMissing)) return true; } return false; } public ISourceContext getSourceContext() { return delegate.getSourceContext(); } public ISourceLocation getSourceLocation() { ISourceContext isc = delegate.getSourceContext(); return isc.makeSourceLocation(new Position(startPos, endPos)); } public boolean isExposedToWeaver() { return (delegate == null) || delegate.isExposedToWeaver(); //??? where does this belong } public WeaverStateInfo getWeaverState() { return delegate.getWeaverState(); } public ResolvedMember[] getDeclaredFields() { if (parameterizedFields != null) return parameterizedFields; if (isParameterizedType() || isRawType()) { ResolvedMember[] delegateFields = delegate.getDeclaredFields(); parameterizedFields = new ResolvedMember[delegateFields.length]; for (int i = 0; i < delegateFields.length; i++) { parameterizedFields[i] = delegateFields[i].parameterizedWith(getTypesForMemberParameterization(),this, isParameterizedType()); } return parameterizedFields; } else { return delegate.getDeclaredFields(); } } /** * Find out from the generic signature the true signature of any interfaces * I implement. If I am parameterized, these may then need to be parameterized * before returning. */ public ResolvedType[] getDeclaredInterfaces() { if (parameterizedInterfaces != null) return parameterizedInterfaces; if (isParameterizedType()) { ResolvedType[] delegateInterfaces = delegate.getDeclaredInterfaces(); UnresolvedType[] paramTypes = getTypesForMemberParameterization(); parameterizedInterfaces = new ResolvedType[delegateInterfaces.length]; for (int i = 0; i < delegateInterfaces.length; i++) { // We may have to sub/super set the set of parametertypes if the implemented interface // needs more or less than this type does. (pr124803/pr125080) if (delegateInterfaces[i].isParameterizedType()) { parameterizedInterfaces[i] = delegateInterfaces[i].parameterize(getMemberParameterizationMap()).resolve(world); } else { parameterizedInterfaces[i] = delegateInterfaces[i]; } } return parameterizedInterfaces; } else if (isRawType()){ ResolvedType[] delegateInterfaces = delegate.getDeclaredInterfaces(); UnresolvedType[] paramTypes = getTypesForMemberParameterization(); parameterizedInterfaces = new ResolvedType[delegateInterfaces.length]; for (int i = 0; i < parameterizedInterfaces.length; i++) { parameterizedInterfaces[i] = delegateInterfaces[i]; if (parameterizedInterfaces[i].isGenericType()) { // a generic supertype of a raw type is replaced by its raw equivalent parameterizedInterfaces[i] = parameterizedInterfaces[i].getRawType().resolve(getWorld()); } else if (parameterizedInterfaces[i].isParameterizedType()) { // a parameterized supertype collapses any type vars to their upper bounds UnresolvedType[] toUseForParameterization = determineThoseTypesToUse(parameterizedInterfaces[i],paramTypes); parameterizedInterfaces[i] = parameterizedInterfaces[i].parameterizedWith(toUseForParameterization); } } return parameterizedInterfaces; } return delegate.getDeclaredInterfaces(); } /** * Locates the named type variable in the list of those on this generic type and returns * the type parameter from the second list supplied. Returns null if it can't be found */ private UnresolvedType findTypeParameterInList(String name, TypeVariable[] tvarsOnThisGenericType, UnresolvedType[] paramTypes) { int position = -1; for (int i = 0; i < tvarsOnThisGenericType.length; i++) { TypeVariable tv = tvarsOnThisGenericType[i]; if (tv.getName().equals(name)) position = i; } if (position == -1 ) return null; return paramTypes[position]; } /** * It is possible this type has multiple type variables but the interface we are about to parameterize * only uses a subset - this method determines the subset to use by looking at the type variable names * used. For example: * <code> * class Foo<T extends String,E extends Number> implements SuperInterface<T> {} * </code> * where * <code> * interface SuperInterface<Z> {} * </code> * In that example, a use of the 'Foo' raw type should know that it implements * the SuperInterface<String>. */ private UnresolvedType[] determineThoseTypesToUse(ResolvedType parameterizedInterface,UnresolvedType[] paramTypes) { // What are the type parameters for the supertype? UnresolvedType[] tParms = parameterizedInterface.getTypeParameters(); UnresolvedType[] retVal = new UnresolvedType[tParms.length]; // Go through the supertypes type parameters, if any of them is a type variable, use the // real type variable on the declaring type. // it is possibly overkill to look up the type variable - ideally the entry in the type parameter list for the // interface should be the a ref to the type variable in the current type ... but I'm not 100% confident right now. for (int i = 0; i < tParms.length; i++) { UnresolvedType tParm = tParms[i]; if (tParm.isTypeVariableReference()) { TypeVariableReference tvrt = (TypeVariableReference)tParm; TypeVariable tv = tvrt.getTypeVariable(); int rank = getRank(tv.getName()); // -1 probably means it is a reference to a type variable on the outer generic type (see pr129566) if (rank!=-1) { retVal[i] = paramTypes[rank]; } else { retVal[i] = tParms[i]; } } else { retVal[i] = tParms[i]; } } return retVal; } /** * Returns the position within the set of type variables for this type for the specified type variable name. * Returns -1 if there is no type variable with the specified name. */ private int getRank(String tvname) { TypeVariable[] thisTypesTVars = getGenericType().getTypeVariables(); for (int i = 0; i < thisTypesTVars.length; i++) { TypeVariable tv = thisTypesTVars[i]; if (tv.getName().equals(tvname)) return i; } return -1; } public ResolvedMember[] getDeclaredMethods() { if (parameterizedMethods != null) return parameterizedMethods; if (isParameterizedType() || isRawType()) { ResolvedMember[] delegateMethods = delegate.getDeclaredMethods(); UnresolvedType[] parameters = getTypesForMemberParameterization(); parameterizedMethods = new ResolvedMember[delegateMethods.length]; for (int i = 0; i < delegateMethods.length; i++) { parameterizedMethods[i] = delegateMethods[i].parameterizedWith(parameters,this,isParameterizedType()); } return parameterizedMethods; } else { return delegate.getDeclaredMethods(); } } public ResolvedMember[] getDeclaredPointcuts() { if (parameterizedPointcuts != null) return parameterizedPointcuts; if (isParameterizedType()) { ResolvedMember[] delegatePointcuts = delegate.getDeclaredPointcuts(); parameterizedPointcuts = new ResolvedMember[delegatePointcuts.length]; for (int i = 0; i < delegatePointcuts.length; i++) { parameterizedPointcuts[i] = delegatePointcuts[i].parameterizedWith(getTypesForMemberParameterization(),this,isParameterizedType()); } return parameterizedPointcuts; } else { return delegate.getDeclaredPointcuts(); } } private UnresolvedType[] getTypesForMemberParameterization() { UnresolvedType[] parameters = null; if (isParameterizedType()) { parameters = getTypeParameters(); } else if (isRawType()){ // raw type, use upper bounds of type variables on generic type TypeVariable[] tvs = getGenericType().getTypeVariables(); parameters = new UnresolvedType[tvs.length]; for (int i = 0; i < tvs.length; i++) { parameters[i] = tvs[i].getFirstBound(); } } return parameters; } public UnresolvedType getRawType() { return super.getRawType().resolve(getWorld()); } public TypeVariable[] getTypeVariables() { if (this.typeVariables == null) { this.typeVariables = delegate.getTypeVariables(); for (int i = 0; i < this.typeVariables.length; i++) { this.typeVariables[i].resolve(world); } } return this.typeVariables; } public PerClause getPerClause() { PerClause pclause = delegate.getPerClause(); if (isParameterizedType()) { // could cache the result here... Map parameterizationMap = getAjMemberParameterizationMap(); pclause = (PerClause)pclause.parameterizeWith(parameterizationMap); } return pclause; } protected Collection getDeclares() { if (parameterizedDeclares != null) return parameterizedDeclares; Collection declares = null; if (ajMembersNeedParameterization()) { Collection genericDeclares = delegate.getDeclares(); parameterizedDeclares = new ArrayList(); Map parameterizationMap = getAjMemberParameterizationMap(); for (Iterator iter = genericDeclares.iterator(); iter.hasNext();) { Declare declareStatement = (Declare) iter.next(); parameterizedDeclares.add(declareStatement.parameterizeWith(parameterizationMap)); } declares = parameterizedDeclares; } else { declares = delegate.getDeclares(); } for (Iterator iter = declares.iterator(); iter.hasNext();) { Declare d = (Declare) iter.next(); d.setDeclaringType(this); } return declares; } protected Collection getTypeMungers() { return delegate.getTypeMungers(); } protected Collection getPrivilegedAccesses() { return delegate.getPrivilegedAccesses(); } public int getModifiers() { return delegate.getModifiers(); } public ResolvedType getSuperclass() { ResolvedType ret = delegate.getSuperclass(); if (this.isParameterizedType() && ret.isParameterizedType()) { ret = ret.parameterize(getMemberParameterizationMap()).resolve(getWorld()); } return ret; } public ReferenceTypeDelegate getDelegate() { return delegate; } public void setDelegate(ReferenceTypeDelegate delegate) { // Don't copy from BcelObjectType to EclipseSourceType - the context may be tidied (result null'd) after previous weaving if (this.delegate!=null && !(this.delegate instanceof BcelObjectType) && this.delegate.getSourceContext()!=SourceContextImpl.UNKNOWN_SOURCE_CONTEXT) ((AbstractReferenceTypeDelegate)delegate).setSourceContext(this.delegate.getSourceContext()); this.delegate = delegate; for(Iterator it = this.derivativeTypes.iterator(); it.hasNext(); ) { ReferenceType dependent = (ReferenceType) it.next(); dependent.setDelegate(delegate); } // If we are raw, we have a generic type - we should ensure it uses the // same delegate if (isRawType() && getGenericType()!=null ) { ReferenceType genType = (ReferenceType) getGenericType(); if (genType.getDelegate() != delegate) { // avoids circular updates genType.setDelegate(delegate); } } clearParameterizationCaches(); } private void clearParameterizationCaches() { parameterizedFields = null; parameterizedInterfaces = null; parameterizedMethods = null; parameterizedPointcuts = null; } public int getEndPos() { return endPos; } public int getStartPos() { return startPos; } public void setEndPos(int endPos) { this.endPos = endPos; } public void setStartPos(int startPos) { this.startPos = startPos; } public boolean doesNotExposeShadowMungers() { return delegate.doesNotExposeShadowMungers(); } public String getDeclaredGenericSignature() { return delegate.getDeclaredGenericSignature(); } public void setGenericType(ReferenceType rt) { genericType = rt; // Should we 'promote' this reference type from simple to raw? // makes sense if someone is specifying that it has a generic form if ( typeKind == TypeKind.SIMPLE ) { typeKind = TypeKind.RAW; signatureErasure = signature; } } public void demoteToSimpleType() { genericType = null; typeKind = TypeKind.SIMPLE; signatureErasure = null; } public ResolvedType getGenericType() { if (isGenericType()) return this; return genericType; } /** * a parameterized signature starts with a "P" in place of the "L", * see the comment on signatures in UnresolvedType. * @param aGenericType * @param someParameters * @return */ private static String makeParameterizedSignature(ResolvedType aGenericType, ResolvedType[] someParameters) { String rawSignature = aGenericType.getErasureSignature(); String prefix = PARAMETERIZED_TYPE_IDENTIFIER + rawSignature.substring(1,rawSignature.length()-1); StringBuffer ret = new StringBuffer(); ret.append(prefix); ret.append("<"); for (int i = 0; i < someParameters.length; i++) { ret.append(someParameters[i].getSignature()); } ret.append(">;"); return ret.toString(); } private static String makeDeclaredSignature(ResolvedType aGenericType, UnresolvedType[] someParameters) { StringBuffer ret = new StringBuffer(); String rawSig = aGenericType.getErasureSignature(); ret.append(rawSig.substring(0,rawSig.length()-1)); ret.append("<"); for (int i = 0; i < someParameters.length; i++) { ret.append(((ReferenceType)someParameters[i]).getSignatureForAttribute()); } ret.append(">;"); return ret.toString(); } }
161,502
Bug 161502 UnsupportedOperationException thrown: unable to parameterize unresolved type: Pjava/util/List<+Ljava/lang/Object; >;
Generic parameters (like List<? extends T>) in pointcuts throw UnsupportedOperationException. java.lang.UnsupportedOperationException at org.aspectj.weaver.UnresolvedType.parameterize(UnresolvedType.java: 220) at org.aspectj.weaver.patterns.ExactTypePattern.parameterizeWith (ExactTypePattern.java:244) at org.aspectj.weaver.patterns.SignaturePattern.parameterizeWith (SignaturePattern.java:265) at org.aspectj.weaver.patterns.KindedPointcut.parameterizeWith (KindedPointcut.java:381) at org.aspectj.weaver.bcel.BcelAdvice.parameterizeWith (BcelAdvice.java:93) at org.aspectj.weaver.ResolvedType.getDeclaredAdvice (ResolvedType.java:710) at org.aspectj.weaver.ResolvedType.getDeclaredShadowMungers (ResolvedType.java:739) at org.aspectj.weaver.ResolvedType.collectShadowMungers (ResolvedType.java:575) at org.aspectj.weaver.ResolvedType.collectCrosscuttingMembers (ResolvedType.java:504) at org.aspectj.weaver.CrosscuttingMembersSet.addOrReplaceAspect (CrosscuttingMembersSet.java:68) at org.aspectj.weaver.CrosscuttingMembersSet.addOrReplaceAspect (CrosscuttingMembersSet.java:57) at org.aspectj.weaver.bcel.BcelWeaver.prepareForWeave(BcelWeaver.java: 450) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.weave (AjCompilerAdapter.java:299) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.afterCompiling (AjCompilerAdapter.java:192) at org.aspectj.ajdt.internal.compiler.CompilerAdapter.ajc $afterReturning$org_aspectj_ajdt_internal_compiler_CompilerAdapter$2 $f9cc9ca0(CompilerAdapter.aj:70) at org.aspectj.org.eclipse.jdt.internal.compiler.Compiler.compile (Compiler.java:367) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.performCompilation (AjBuildManager.java:887) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.doBuild (AjBuildManager.java:244) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.batchBuild (AjBuildManager.java:163) at org.aspectj.ajde.internal.CompilerAdapter.compile (CompilerAdapter.java:122) at org.aspectj.ajde.internal.AspectJBuildManager$CompilerThread.run (AspectJBuildManager.java:191) UnsupportedOperationException thrown: unable to parameterize unresolved type: Pjava/util/List<+Ljava/lang/Object;>; To reproduce this exception compile the following code snippet. import java.util.ArrayList; import java.util.List; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; public class Main { public List<? extends Element> getElements() { return new ArrayList<Element>(); } class Element {}; @Aspect static abstract class Base<T> { @Around("call(List<? extends T> *.*(..))") public List<? extends T> elementList(ProceedingJoinPoint thisJoinPoint) { try { return (List<? extends T>)thisJoinPoint.proceed(); } catch (Throwable e) { throw new RuntimeException(e); } } } @Aspect static class Concrete extends Base<Element> {} public static void main(String[] args) { new Main().getElements(); } }
resolved fixed
7b40e7e
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2006-10-24T12:42:57Z"
"2006-10-19T01:06:40Z"
weaver/src/org/aspectj/weaver/ResolvedPointcutDefinition.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Eclipse Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * PARC initial implementation * ******************************************************************/ package org.aspectj.weaver; import java.io.DataOutputStream; import java.io.IOException; import java.util.HashMap; import java.util.Map; import org.aspectj.weaver.patterns.Pointcut; public class ResolvedPointcutDefinition extends ResolvedMemberImpl { private Pointcut pointcut; public ResolvedPointcutDefinition( UnresolvedType declaringType, int modifiers, String name, UnresolvedType[] parameterTypes, Pointcut pointcut) { this(declaringType, modifiers, name, parameterTypes, ResolvedType.VOID, pointcut); } /** * An instance which can be given a specific returnType, used f.e. in if() pointcut for @AJ * * @param declaringType * @param modifiers * @param name * @param parameterTypes * @param returnType * @param pointcut */ public ResolvedPointcutDefinition( UnresolvedType declaringType, int modifiers, String name, UnresolvedType[] parameterTypes, UnresolvedType returnType, Pointcut pointcut) { super( POINTCUT, declaringType, modifiers, returnType, name, parameterTypes); this.pointcut = pointcut; //XXXpointcut.assertState(Pointcut.RESOLVED); checkedExceptions = UnresolvedType.NONE; } // ---- public void write(DataOutputStream s) throws IOException { getDeclaringType().write(s); s.writeInt(getModifiers()); s.writeUTF(getName()); UnresolvedType.writeArray(getParameterTypes(), s); pointcut.write(s); } public static ResolvedPointcutDefinition read(VersionedDataInputStream s, ISourceContext context) throws IOException { ResolvedPointcutDefinition rpd = new ResolvedPointcutDefinition( UnresolvedType.read(s), s.readInt(), s.readUTF(), UnresolvedType.readArray(s), Pointcut.read(s, context)); rpd.setSourceContext(context); // whilst we have a source context, let's remember it return rpd; } public String toString() { StringBuffer buf = new StringBuffer(); buf.append("pointcut "); buf.append((getDeclaringType()==null?"<nullDeclaringType>":getDeclaringType().getName())); buf.append("."); buf.append(getName()); buf.append("("); for (int i=0; i < getParameterTypes().length; i++) { if (i > 0) buf.append(", "); buf.append(getParameterTypes()[i].toString()); } buf.append(")"); //buf.append(pointcut); return buf.toString(); } public Pointcut getPointcut() { return pointcut; } public boolean isAjSynthetic() { return true; } /** * Called when asking a parameterized super-aspect for its pointcuts. */ public ResolvedMemberImpl parameterizedWith(UnresolvedType[] typeParameters, ResolvedType newDeclaringType, boolean isParameterized) { TypeVariable[] typeVariables = getDeclaringType().resolve(newDeclaringType.getWorld()).getTypeVariables(); if (isParameterized && (typeVariables.length != typeParameters.length)) { throw new IllegalStateException("Wrong number of type parameters supplied"); } Map typeMap = new HashMap(); boolean typeParametersSupplied = typeParameters!=null && typeParameters.length>0; if (typeVariables!=null) { // If no 'replacements' were supplied in the typeParameters array then collapse // type variables to their first bound. for (int i = 0; i < typeVariables.length; i++) { UnresolvedType ut = (!typeParametersSupplied?typeVariables[i].getFirstBound():typeParameters[i]); typeMap.put(typeVariables[i].getName(),ut); } } UnresolvedType parameterizedReturnType = parameterize(getGenericReturnType(),typeMap,isParameterized); UnresolvedType[] parameterizedParameterTypes = new UnresolvedType[getGenericParameterTypes().length]; for (int i = 0; i < parameterizedParameterTypes.length; i++) { parameterizedParameterTypes[i] = parameterize(getGenericParameterTypes()[i], typeMap,isParameterized); } ResolvedPointcutDefinition ret = new ResolvedPointcutDefinition( newDeclaringType, getModifiers(), getName(), parameterizedParameterTypes, parameterizedReturnType, pointcut.parameterizeWith(typeMap) ); ret.setTypeVariables(getTypeVariables()); ret.setSourceContext(getSourceContext()); ret.setPosition(getStart(),getEnd()); ret.setParameterNames(getParameterNames()); return ret; //return this; } // for testing public static final ResolvedPointcutDefinition DUMMY = new ResolvedPointcutDefinition(UnresolvedType.OBJECT, 0, "missing", UnresolvedType.NONE, Pointcut.makeMatchesNothing(Pointcut.RESOLVED)); public void setPointcut(Pointcut pointcut) { this.pointcut = pointcut; } }
161,502
Bug 161502 UnsupportedOperationException thrown: unable to parameterize unresolved type: Pjava/util/List<+Ljava/lang/Object; >;
Generic parameters (like List<? extends T>) in pointcuts throw UnsupportedOperationException. java.lang.UnsupportedOperationException at org.aspectj.weaver.UnresolvedType.parameterize(UnresolvedType.java: 220) at org.aspectj.weaver.patterns.ExactTypePattern.parameterizeWith (ExactTypePattern.java:244) at org.aspectj.weaver.patterns.SignaturePattern.parameterizeWith (SignaturePattern.java:265) at org.aspectj.weaver.patterns.KindedPointcut.parameterizeWith (KindedPointcut.java:381) at org.aspectj.weaver.bcel.BcelAdvice.parameterizeWith (BcelAdvice.java:93) at org.aspectj.weaver.ResolvedType.getDeclaredAdvice (ResolvedType.java:710) at org.aspectj.weaver.ResolvedType.getDeclaredShadowMungers (ResolvedType.java:739) at org.aspectj.weaver.ResolvedType.collectShadowMungers (ResolvedType.java:575) at org.aspectj.weaver.ResolvedType.collectCrosscuttingMembers (ResolvedType.java:504) at org.aspectj.weaver.CrosscuttingMembersSet.addOrReplaceAspect (CrosscuttingMembersSet.java:68) at org.aspectj.weaver.CrosscuttingMembersSet.addOrReplaceAspect (CrosscuttingMembersSet.java:57) at org.aspectj.weaver.bcel.BcelWeaver.prepareForWeave(BcelWeaver.java: 450) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.weave (AjCompilerAdapter.java:299) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.afterCompiling (AjCompilerAdapter.java:192) at org.aspectj.ajdt.internal.compiler.CompilerAdapter.ajc $afterReturning$org_aspectj_ajdt_internal_compiler_CompilerAdapter$2 $f9cc9ca0(CompilerAdapter.aj:70) at org.aspectj.org.eclipse.jdt.internal.compiler.Compiler.compile (Compiler.java:367) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.performCompilation (AjBuildManager.java:887) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.doBuild (AjBuildManager.java:244) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.batchBuild (AjBuildManager.java:163) at org.aspectj.ajde.internal.CompilerAdapter.compile (CompilerAdapter.java:122) at org.aspectj.ajde.internal.AspectJBuildManager$CompilerThread.run (AspectJBuildManager.java:191) UnsupportedOperationException thrown: unable to parameterize unresolved type: Pjava/util/List<+Ljava/lang/Object;>; To reproduce this exception compile the following code snippet. import java.util.ArrayList; import java.util.List; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; public class Main { public List<? extends Element> getElements() { return new ArrayList<Element>(); } class Element {}; @Aspect static abstract class Base<T> { @Around("call(List<? extends T> *.*(..))") public List<? extends T> elementList(ProceedingJoinPoint thisJoinPoint) { try { return (List<? extends T>)thisJoinPoint.proceed(); } catch (Throwable e) { throw new RuntimeException(e); } } } @Aspect static class Concrete extends Base<Element> {} public static void main(String[] args) { new Main().getElements(); } }
resolved fixed
7b40e7e
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2006-10-24T12:42:57Z"
"2006-10-19T01:06:40Z"
weaver/src/org/aspectj/weaver/ResolvedType.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the 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.List; import java.util.Map; import java.util.Set; import org.aspectj.bridge.IMessage; import org.aspectj.bridge.ISourceLocation; import org.aspectj.bridge.Message; import org.aspectj.bridge.MessageUtil; import org.aspectj.util.FuzzyBoolean; import org.aspectj.weaver.patterns.Declare; import org.aspectj.weaver.patterns.PerClause; public abstract class ResolvedType extends UnresolvedType implements AnnotatedElement { public static final ResolvedType[] EMPTY_RESOLVED_TYPE_ARRAY = new ResolvedType[0]; public static final String PARAMETERIZED_TYPE_IDENTIFIER = "P"; private ResolvedType[] resolvedTypeParams; private String binaryPath; protected World world; protected ResolvedType(String signature, World world) { super(signature); this.world = world; } protected ResolvedType(String signature, String signatureErasure, World world) { super(signature,signatureErasure); this.world = world; } // ---- things that don't require a world /** * Returns an iterator through ResolvedType objects representing all the direct * supertypes of this type. That is, through the superclass, if any, and * all declared interfaces. */ public final Iterator getDirectSupertypes() { Iterator ifacesIterator = Iterators.array(getDeclaredInterfaces()); ResolvedType superclass = getSuperclass(); if (superclass == null) { return ifacesIterator; } else { return Iterators.snoc(ifacesIterator, superclass); } } public abstract ResolvedMember[] getDeclaredFields(); public abstract ResolvedMember[] getDeclaredMethods(); public abstract ResolvedType[] getDeclaredInterfaces(); public abstract ResolvedMember[] getDeclaredPointcuts(); /** * Returns a ResolvedType object representing the superclass of this type, or null. * If this represents a java.lang.Object, a primitive type, or void, this * method returns null. */ public abstract ResolvedType getSuperclass(); /** * Returns the modifiers for this type. * <p/> * See {@link Class#getModifiers()} for a description * of the weirdness of this methods on primitives and arrays. * * @param world the {@link World} in which the lookup is made. * @return an int representing the modifiers for this type * @see java.lang.reflect.Modifier */ public abstract int getModifiers(); // return true if this resolved type couldn't be found (but we know it's name maybe) public boolean isMissing() { return false; } // FIXME asc I wonder if in some circumstances MissingWithKnownSignature should not be considered // 'really' missing as some code can continue based solely on the signature public static boolean isMissing (UnresolvedType unresolved) { if (unresolved instanceof ResolvedType) { ResolvedType resolved = (ResolvedType)unresolved; return resolved.isMissing(); } else return (unresolved == MISSING); } public ResolvedType[] getAnnotationTypes() { return EMPTY_RESOLVED_TYPE_ARRAY; } public final UnresolvedType getSuperclass(World world) { return getSuperclass(); } // This set contains pairs of types whose signatures are concatenated // together, this means with a fast lookup we can tell if two types // are equivalent. static Set validBoxing = new HashSet(); static { validBoxing.add("Ljava/lang/Byte;B"); validBoxing.add("Ljava/lang/Character;C"); validBoxing.add("Ljava/lang/Double;D"); validBoxing.add("Ljava/lang/Float;F"); validBoxing.add("Ljava/lang/Integer;I"); validBoxing.add("Ljava/lang/Long;J"); validBoxing.add("Ljava/lang/Short;S"); validBoxing.add("Ljava/lang/Boolean;Z"); validBoxing.add("BLjava/lang/Byte;"); validBoxing.add("CLjava/lang/Character;"); validBoxing.add("DLjava/lang/Double;"); validBoxing.add("FLjava/lang/Float;"); validBoxing.add("ILjava/lang/Integer;"); validBoxing.add("JLjava/lang/Long;"); validBoxing.add("SLjava/lang/Short;"); validBoxing.add("ZLjava/lang/Boolean;"); } // utilities public ResolvedType getResolvedComponentType() { return null; } public World getWorld() { return world; } // ---- things from object public final boolean equals(Object other) { if (other instanceof ResolvedType) { return this == other; } else { return super.equals(other); } } // ---- difficult things /** * returns an iterator through all of the fields of this type, in order * for checking from JVM spec 2ed 5.4.3.2. This means that the order is * <p/> * <ul><li> fields from current class </li> * <li> recur into direct superinterfaces </li> * <li> recur into superclass </li> * </ul> * <p/> * We keep a hashSet of interfaces that we've visited so we don't spiral * out into 2^n land. */ public Iterator getFields() { final Iterators.Filter dupFilter = Iterators.dupFilter(); Iterators.Getter typeGetter = new Iterators.Getter() { public Iterator get(Object o) { return dupFilter.filter( ((ResolvedType)o).getDirectSupertypes()); } }; Iterators.Getter fieldGetter = new Iterators.Getter() { public Iterator get(Object o) { return Iterators.array(((ResolvedType)o).getDeclaredFields()); } }; return Iterators.mapOver( Iterators.recur(this, typeGetter), fieldGetter); } /** * returns an iterator through all of the methods of this type, in order * for checking from JVM spec 2ed 5.4.3.3. This means that the order is * <p/> * <ul><li> methods from current class </li> * <li> recur into superclass, all the way up, not touching interfaces </li> * <li> recur into all superinterfaces, in some unspecified order </li> * </ul> * <p/> * We keep a hashSet of interfaces that we've visited so we don't spiral * out into 2^n land. * NOTE: Take a look at the javadoc on getMethodsWithoutIterator() to see if * you are sensitive to a quirk in getMethods() */ public Iterator getMethods() { final Iterators.Filter dupFilter = Iterators.dupFilter(); Iterators.Getter ifaceGetter = new Iterators.Getter() { public Iterator get(Object o) { return dupFilter.filter( Iterators.array(((ResolvedType)o).getDeclaredInterfaces()) ); } }; Iterators.Getter methodGetter = new Iterators.Getter() { public Iterator get(Object o) { return Iterators.array(((ResolvedType)o).getDeclaredMethods()); } }; return Iterators.mapOver( Iterators.append( new Iterator() { ResolvedType curr = ResolvedType.this; public boolean hasNext() { return curr != null; } public Object next() { ResolvedType ret = curr; curr = curr.getSuperclass(); return ret; } public void remove() { throw new UnsupportedOperationException(); } }, Iterators.recur(this, ifaceGetter)), methodGetter); } /** * Return a list of methods, first those declared on this class, then those declared on the superclass (recurse) and then those declared * on the superinterfaces. The getMethods() call above doesn't quite work the same as it will (through the iterator) return methods * declared on *this* class twice, once at the start and once at the end - I couldn't debug that problem, so created this alternative. */ public List getMethodsWithoutIterator(boolean includeITDs, boolean allowMissing) { List methods = new ArrayList(); Set knowninterfaces = new HashSet(); addAndRecurse(knowninterfaces,methods,this,includeITDs,allowMissing); return methods; } private void addAndRecurse(Set knowninterfaces,List collector, ResolvedType rtx, boolean includeITDs, boolean allowMissing) { collector.addAll(Arrays.asList(rtx.getDeclaredMethods())); // Add the methods declared on this type // now add all the inter-typed members too if (includeITDs && rtx.interTypeMungers != null) { for (Iterator i = interTypeMungers.iterator(); i.hasNext();) { ConcreteTypeMunger tm = (ConcreteTypeMunger) i.next(); ResolvedMember rm = tm.getSignature(); if (rm != null) { // new parent type munger can have null signature... collector.add(tm.getSignature()); } } } if (!rtx.equals(ResolvedType.OBJECT)) { ResolvedType superType = rtx.getSuperclass(); if (superType != null && !superType.isMissing()) { addAndRecurse(knowninterfaces,collector,superType,includeITDs,allowMissing); // Recurse if we aren't at the top } } ResolvedType[] interfaces = rtx.getDeclaredInterfaces(); // Go through the interfaces on the way back down for (int i = 0; i < interfaces.length; i++) { ResolvedType iface = interfaces[i]; // we need to know if it is an interface from Parent kind munger // as those are used for @AJ ITD and we precisely want to skip those boolean shouldSkip = false; for (int j = 0; j < rtx.interTypeMungers.size(); j++) { ConcreteTypeMunger munger = (ConcreteTypeMunger) rtx.interTypeMungers.get(j); if (munger.getMunger()!=null && munger.getMunger().getKind() == ResolvedTypeMunger.Parent) { shouldSkip = true; break; } } if (!shouldSkip && !knowninterfaces.contains(iface)) { // Dont do interfaces more than once knowninterfaces.add(iface); if (allowMissing && iface.isMissing()) { if (iface instanceof MissingResolvedTypeWithKnownSignature) { ((MissingResolvedTypeWithKnownSignature)iface).raiseWarningOnMissingInterfaceWhilstFindingMethods(); } } else { addAndRecurse(knowninterfaces,collector,iface,includeITDs,allowMissing); } } } } public ResolvedType[] getResolvedTypeParameters() { if (resolvedTypeParams == null) { resolvedTypeParams = world.resolve(typeParameters); } return resolvedTypeParams; } /** * described in JVM spec 2ed 5.4.3.2 */ public ResolvedMember lookupField(Member m) { return lookupMember(m, getFields()); } /** * described in JVM spec 2ed 5.4.3.3. * Doesnt check ITDs. */ public ResolvedMember lookupMethod(Member m) { return lookupMember(m, getMethods()); } public ResolvedMember lookupMethodInITDs(Member m) { if (interTypeMungers != null) { for (Iterator i = interTypeMungers.iterator(); i.hasNext();) { ConcreteTypeMunger tm = (ConcreteTypeMunger) i.next(); if (matches(tm.getSignature(), m)) { return tm.getSignature(); } } } return null; } /** * return null if not found */ private ResolvedMember lookupMember(Member m, Iterator i) { while (i.hasNext()) { ResolvedMember f = (ResolvedMember) i.next(); if (matches(f, m)) return f; if (f.hasBackingGenericMember() && m.getName().equals(f.getName())) { // might be worth checking the method behind the parameterized method (see pr137496) if (matches(f.getBackingGenericMember(),m)) return f; } } return null; //ResolvedMember.Missing; //throw new BCException("can't find " + m); } /** * return null if not found */ private ResolvedMember lookupMember(Member m, ResolvedMember[] a) { for (int i = 0; i < a.length; i++) { ResolvedMember f = a[i]; if (matches(f, m)) return f; } return null; } /** * Looks for the first member in the hierarchy matching aMember. This method * differs from lookupMember(Member) in that it takes into account parameters * which are type variables - which clearly an unresolved Member cannot do since * it does not know anything about type variables. */ public ResolvedMember lookupResolvedMember(ResolvedMember aMember,boolean allowMissing) { Iterator toSearch = null; ResolvedMember found = null; if ((aMember.getKind() == Member.METHOD) || (aMember.getKind() == Member.CONSTRUCTOR)) { toSearch = getMethodsWithoutIterator(true,allowMissing).iterator(); } else { if (aMember.getKind() != Member.FIELD) throw new IllegalStateException("I didn't know you would look for members of kind " + aMember.getKind()); toSearch = getFields(); } while(toSearch.hasNext()) { ResolvedMemberImpl candidate = (ResolvedMemberImpl) toSearch.next(); if (candidate.matches(aMember)) { found = candidate; break; } } return found; } public static boolean matches(Member m1, Member m2) { if (m1 == null) return m2 == null; if (m2 == null) return false; // Check the names boolean equalNames = m1.getName().equals(m2.getName()); if (!equalNames) return false; // Check the signatures boolean equalSignatures = m1.getSignature().equals(m2.getSignature()); if (equalSignatures) return true; // If they aren't the same, we need to allow for covariance ... where one sig might be ()LCar; and // the subsig might be ()LFastCar; - where FastCar is a subclass of Car boolean equalCovariantSignatures = m1.getParameterSignature().equals(m2.getParameterSignature()); if (equalCovariantSignatures) return true; return false; } public static boolean conflictingSignature(Member m1, Member m2) { if (m1 == null || m2 == null) return false; if (!m1.getName().equals(m2.getName())) { return false; } if (m1.getKind() != m2.getKind()) { return false; } if (m1.getKind() == Member.FIELD) { return m1.getDeclaringType().equals(m2.getDeclaringType()); } else if (m1.getKind() == Member.POINTCUT) { return true; } UnresolvedType[] p1 = m1.getParameterTypes(); UnresolvedType[] p2 = m2.getParameterTypes(); int n = p1.length; if (n != p2.length) return false; for (int i=0; i < n; i++) { if (!p1[i].equals(p2[i])) return false; } return true; } /** * returns an iterator through all of the pointcuts of this type, in order * for checking from JVM spec 2ed 5.4.3.2 (as for fields). This means that the order is * <p/> * <ul><li> pointcuts from current class </li> * <li> recur into direct superinterfaces </li> * <li> recur into superclass </li> * </ul> * <p/> * We keep a hashSet of interfaces that we've visited so we don't spiral * out into 2^n land. */ public Iterator getPointcuts() { final Iterators.Filter dupFilter = Iterators.dupFilter(); // same order as fields Iterators.Getter typeGetter = new Iterators.Getter() { public Iterator get(Object o) { return dupFilter.filter( ((ResolvedType)o).getDirectSupertypes()); } }; Iterators.Getter pointcutGetter = new Iterators.Getter() { public Iterator get(Object o) { //System.err.println("getting for " + o); return Iterators.array(((ResolvedType)o).getDeclaredPointcuts()); } }; return Iterators.mapOver( Iterators.recur(this, typeGetter), pointcutGetter); } public ResolvedPointcutDefinition findPointcut(String name) { //System.err.println("looking for pointcuts " + this); for (Iterator i = getPointcuts(); i.hasNext(); ) { ResolvedPointcutDefinition f = (ResolvedPointcutDefinition) i.next(); //System.err.println(f); if (name.equals(f.getName())) { return f; } } // pr120521 if (!getOutermostType().equals(this)) { ResolvedType outerType = getOutermostType().resolve(world); ResolvedPointcutDefinition rpd = outerType.findPointcut(name); return rpd; } return null; // should we throw an exception here? } // all about collecting CrosscuttingMembers //??? collecting data-structure, shouldn't really be a field public CrosscuttingMembers crosscuttingMembers; public CrosscuttingMembers collectCrosscuttingMembers(boolean shouldConcretizeIfNeeded) { crosscuttingMembers = new CrosscuttingMembers(this,shouldConcretizeIfNeeded); crosscuttingMembers.setPerClause(getPerClause()); crosscuttingMembers.addShadowMungers(collectShadowMungers()); crosscuttingMembers.addTypeMungers(getTypeMungers()); //FIXME AV - skip but needed ?? or ?? crosscuttingMembers.addLateTypeMungers(getLateTypeMungers()); crosscuttingMembers.addDeclares(collectDeclares(!this.doesNotExposeShadowMungers())); crosscuttingMembers.addPrivilegedAccesses(getPrivilegedAccesses()); //System.err.println("collected cc members: " + this + ", " + collectDeclares()); return crosscuttingMembers; } public final Collection collectDeclares(boolean includeAdviceLike) { if (! this.isAspect() ) return Collections.EMPTY_LIST; ArrayList ret = new ArrayList(); //if (this.isAbstract()) { // for (Iterator i = getDeclares().iterator(); i.hasNext();) { // Declare dec = (Declare) i.next(); // if (!dec.isAdviceLike()) ret.add(dec); // } // // if (!includeAdviceLike) return ret; if (!this.isAbstract()) { //ret.addAll(getDeclares()); final Iterators.Filter dupFilter = Iterators.dupFilter(); Iterators.Getter typeGetter = new Iterators.Getter() { public Iterator get(Object o) { return dupFilter.filter( ((ResolvedType)o).getDirectSupertypes()); } }; Iterator typeIterator = Iterators.recur(this, typeGetter); while (typeIterator.hasNext()) { ResolvedType ty = (ResolvedType) typeIterator.next(); //System.out.println("super: " + ty + ", " + ); for (Iterator i = ty.getDeclares().iterator(); i.hasNext();) { Declare dec = (Declare) i.next(); if (dec.isAdviceLike()) { if (includeAdviceLike) ret.add(dec); } else { ret.add(dec); } } } } return ret; } private final Collection collectShadowMungers() { if (! this.isAspect() || this.isAbstract() || this.doesNotExposeShadowMungers()) return Collections.EMPTY_LIST; ArrayList acc = new ArrayList(); final Iterators.Filter dupFilter = Iterators.dupFilter(); Iterators.Getter typeGetter = new Iterators.Getter() { public Iterator get(Object o) { return dupFilter.filter( ((ResolvedType)o).getDirectSupertypes()); } }; Iterator typeIterator = Iterators.recur(this, typeGetter); while (typeIterator.hasNext()) { ResolvedType ty = (ResolvedType) typeIterator.next(); acc.addAll(ty.getDeclaredShadowMungers()); } return acc; } protected boolean doesNotExposeShadowMungers() { return false; } public PerClause getPerClause() { return null; } protected Collection getDeclares() { return Collections.EMPTY_LIST; } protected Collection getTypeMungers() { return Collections.EMPTY_LIST; } protected Collection getPrivilegedAccesses() { return Collections.EMPTY_LIST; } // ---- useful things public final boolean isInterface() { return Modifier.isInterface(getModifiers()); } public final boolean isAbstract() { return Modifier.isAbstract(getModifiers()); } public boolean isClass() { return false; } public boolean isAspect() { return false; } public boolean isAnnotationStyleAspect() { return false; } /** * Note: Only overridden by Name subtype. */ public boolean isEnum() { return false; } /** * Note: Only overridden by Name subtype. */ public boolean isAnnotation() { return false; } public boolean isAnonymous() { return false; } public boolean isNested() { return false; } /** * Note: Only overridden by Name subtype */ public void addAnnotation(AnnotationX annotationX) { throw new RuntimeException("ResolvedType.addAnnotation() should never be called"); } /** * Note: Only overridden by Name subtype */ public AnnotationX[] getAnnotations() { throw new RuntimeException("ResolvedType.getAnnotations() should never be called"); } /** * Note: Only overridden by ReferenceType subtype */ public boolean canAnnotationTargetType() { return false; } /** * Note: Only overridden by ReferenceType subtype */ public AnnotationTargetKind[] getAnnotationTargetKinds() { return null; } /** * Note: Only overridden by Name subtype. */ public boolean isAnnotationWithRuntimeRetention() { return false; } public boolean isSynthetic() { return signature.indexOf("$ajc") != -1; } public final boolean isFinal() { return Modifier.isFinal(getModifiers()); } protected Map /*Type variable name -> UnresolvedType*/ getMemberParameterizationMap() { if (!isParameterizedType()) return Collections.EMPTY_MAP; TypeVariable[] tvs = getGenericType().getTypeVariables(); Map parameterizationMap = new HashMap(); for (int i = 0; i < tvs.length; i++) { parameterizationMap.put(tvs[i].getName(), typeParameters[i]); } return parameterizationMap; } public Collection getDeclaredAdvice() { List l = new ArrayList(); ResolvedMember[] methods = getDeclaredMethods(); if (isParameterizedType()) methods = getGenericType().getDeclaredMethods(); Map typeVariableMap = getAjMemberParameterizationMap(); for (int i=0, len = methods.length; i < len; i++) { ShadowMunger munger = methods[i].getAssociatedShadowMunger(); if (munger != null) { if (ajMembersNeedParameterization()) { //munger.setPointcut(munger.getPointcut().parameterizeWith(typeVariableMap)); munger = munger.parameterizeWith(this,typeVariableMap); if (munger instanceof Advice) { Advice advice = (Advice) munger; // update to use the parameterized signature... UnresolvedType[] ptypes = methods[i].getGenericParameterTypes() ; UnresolvedType[] newPTypes = new UnresolvedType[ptypes.length]; for (int j = 0; j < ptypes.length; j++) { if (ptypes[j] instanceof TypeVariableReferenceType) { TypeVariableReferenceType tvrt = (TypeVariableReferenceType) ptypes[j]; if (typeVariableMap.containsKey(tvrt.getTypeVariable().getName())) { newPTypes[j] = (UnresolvedType) typeVariableMap.get(tvrt.getTypeVariable().getName()); } else { newPTypes[j] = ptypes[j]; } } else { newPTypes[j] = ptypes[j]; } } advice.setBindingParameterTypes(newPTypes); } } munger.setDeclaringType(this); l.add(munger); } } return l; } public Collection getDeclaredShadowMungers() { Collection c = getDeclaredAdvice(); return c; } // ---- only for testing! public ResolvedMember[] getDeclaredJavaFields() { return filterInJavaVisible(getDeclaredFields()); } public ResolvedMember[] getDeclaredJavaMethods() { return filterInJavaVisible(getDeclaredMethods()); } public ShadowMunger[] getDeclaredShadowMungersArray() { List l = (List) getDeclaredShadowMungers(); return (ShadowMunger[]) l.toArray(new ShadowMunger[l.size()]); } private ResolvedMember[] filterInJavaVisible(ResolvedMember[] ms) { List l = new ArrayList(); for (int i=0, len = ms.length; i < len; i++) { if (! ms[i].isAjSynthetic() && ms[i].getAssociatedShadowMunger() == null) { l.add(ms[i]); } } return (ResolvedMember[]) l.toArray(new ResolvedMember[l.size()]); } public abstract ISourceContext getSourceContext(); // ---- fields public static final ResolvedType[] NONE = new ResolvedType[0]; public static final Primitive BYTE = new Primitive("B", 1, 0); public static final Primitive CHAR = new Primitive("C", 1, 1); public static final Primitive DOUBLE = new Primitive("D", 2, 2); public static final Primitive FLOAT = new Primitive("F", 1, 3); public static final Primitive INT = new Primitive("I", 1, 4); public static final Primitive LONG = new Primitive("J", 2, 5); public static final Primitive SHORT = new Primitive("S", 1, 6); public static final Primitive VOID = new Primitive("V", 0, 8); public static final Primitive BOOLEAN = new Primitive("Z", 1, 7); public static final Missing MISSING = new Missing(); /** Reset the static state in the primitive types */ public static void resetPrimitives() { BYTE.world=null; CHAR.world=null; DOUBLE.world=null; FLOAT.world=null; INT.world=null; LONG.world=null; SHORT.world=null; VOID.world=null; BOOLEAN.world=null; } // ---- types public static ResolvedType makeArray(ResolvedType type, int dim) { if (dim == 0) return type; ResolvedType array = new Array("[" + type.getSignature(),"["+type.getErasureSignature(),type.getWorld(),type); return makeArray(array,dim-1); } static class Array extends ResolvedType { ResolvedType componentType; // Sometimes the erasure is different, eg. [TT; and [Ljava/lang/Object; Array(String sig, String erasureSig,World world, ResolvedType componentType) { super(sig,erasureSig, world); this.componentType = componentType; } public final ResolvedMember[] getDeclaredFields() { return ResolvedMember.NONE; } public final ResolvedMember[] getDeclaredMethods() { // ??? should this return clone? Probably not... // If it ever does, here is the code: // ResolvedMember cloneMethod = // new ResolvedMember(Member.METHOD,this,Modifier.PUBLIC,UnresolvedType.OBJECT,"clone",new UnresolvedType[]{}); // return new ResolvedMember[]{cloneMethod}; return ResolvedMember.NONE; } public final ResolvedType[] getDeclaredInterfaces() { return new ResolvedType[] { world.getCoreType(CLONEABLE), world.getCoreType(SERIALIZABLE) }; } public final ResolvedMember[] getDeclaredPointcuts() { return ResolvedMember.NONE; } public boolean hasAnnotation(UnresolvedType ofType) { return false; } public final ResolvedType getSuperclass() { return world.getCoreType(OBJECT); } public final boolean isAssignableFrom(ResolvedType o) { if (! o.isArray()) return false; if (o.getComponentType().isPrimitiveType()) { return o.equals(this); } else { return getComponentType().resolve(world).isAssignableFrom(o.getComponentType().resolve(world)); } } public boolean isAssignableFrom(ResolvedType o, boolean allowMissing) { return isAssignableFrom(o); } public final boolean isCoerceableFrom(ResolvedType o) { if (o.equals(UnresolvedType.OBJECT) || o.equals(UnresolvedType.SERIALIZABLE) || o.equals(UnresolvedType.CLONEABLE)) { return true; } if (! o.isArray()) return false; if (o.getComponentType().isPrimitiveType()) { return o.equals(this); } else { return getComponentType().resolve(world).isCoerceableFrom(o.getComponentType().resolve(world)); } } public final int getModifiers() { int mask = Modifier.PUBLIC | Modifier.PRIVATE | Modifier.PROTECTED; return (componentType.getModifiers() & mask) | Modifier.FINAL; } public UnresolvedType getComponentType() { return componentType; } public ResolvedType getResolvedComponentType() { return componentType; } public ISourceContext getSourceContext() { return getResolvedComponentType().getSourceContext(); } } static class Primitive extends ResolvedType { private int size; private int index; Primitive(String signature, int size, int index) { super(signature, null); this.size = size; this.index = index; this.typeKind=TypeKind.PRIMITIVE; } public final int getSize() { return size; } public final int getModifiers() { return Modifier.PUBLIC | Modifier.FINAL; } public final boolean isPrimitiveType() { return true; } public boolean hasAnnotation(UnresolvedType ofType) { return false; } public final boolean isAssignableFrom(ResolvedType other) { if (!other.isPrimitiveType()) { if (!world.isInJava5Mode()) return false; return validBoxing.contains(this.getSignature()+other.getSignature()); } return assignTable[((Primitive)other).index][index]; } public final boolean isAssignableFrom(ResolvedType other, boolean allowMissing) { return isAssignableFrom(other); } public final boolean isCoerceableFrom(ResolvedType other) { if (this == other) return true; if (! other.isPrimitiveType()) return false; if (index > 6 || ((Primitive)other).index > 6) return false; return true; } public ResolvedType resolve(World world) { this.world = world; return super.resolve(world); } public final boolean needsNoConversionFrom(ResolvedType other) { if (! other.isPrimitiveType()) return false; return noConvertTable[((Primitive)other).index][index]; } private static final boolean[][] assignTable = {// to: B C D F I J S V Z from { true , true , true , true , true , true , true , false, false }, // B { false, true , true , true , true , true , false, false, false }, // C { false, false, true , false, false, false, false, false, false }, // D { false, false, true , true , false, false, false, false, false }, // F { false, false, true , true , true , true , false, false, false }, // I { false, false, true , true , false, true , false, false, false }, // J { false, false, true , true , true , true , true , false, false }, // S { false, false, false, false, false, false, false, true , false }, // V { false, false, false, false, false, false, false, false, true }, // Z }; private static final boolean[][] noConvertTable = {// to: B C D F I J S V Z from { true , true , false, false, true , false, true , false, false }, // B { false, true , false, false, true , false, false, false, false }, // C { false, false, true , false, false, false, false, false, false }, // D { false, false, false, true , false, false, false, false, false }, // F { false, false, false, false, true , false, false, false, false }, // I { false, false, false, false, false, true , false, false, false }, // J { false, false, false, false, true , false, true , false, false }, // S { false, false, false, false, false, false, false, true , false }, // V { false, false, false, false, false, false, false, false, true }, // Z }; // ---- public final ResolvedMember[] getDeclaredFields() { return ResolvedMember.NONE; } public final ResolvedMember[] getDeclaredMethods() { return ResolvedMember.NONE; } public final ResolvedType[] getDeclaredInterfaces() { return ResolvedType.NONE; } public final ResolvedMember[] getDeclaredPointcuts() { return ResolvedMember.NONE; } public final ResolvedType getSuperclass() { return null; } public ISourceContext getSourceContext() { return null; } } static class Missing extends ResolvedType { Missing() { super(MISSING_NAME, null); } // public final String toString() { // return "<missing>"; // } public final String getName() { return MISSING_NAME; } public final boolean isMissing() { return true; } public boolean hasAnnotation(UnresolvedType ofType) { return false; } public final ResolvedMember[] getDeclaredFields() { return ResolvedMember.NONE; } public final ResolvedMember[] getDeclaredMethods() { return ResolvedMember.NONE; } public final ResolvedType[] getDeclaredInterfaces() { return ResolvedType.NONE; } public final ResolvedMember[] getDeclaredPointcuts() { return ResolvedMember.NONE; } public final ResolvedType getSuperclass() { return null; } public final int getModifiers() { return 0; } public final boolean isAssignableFrom(ResolvedType other) { return false; } public final boolean isAssignableFrom(ResolvedType other, boolean allowMissing) { return false; } public final boolean isCoerceableFrom(ResolvedType other) { return false; } public boolean needsNoConversionFrom(ResolvedType other) { return false; } public ISourceContext getSourceContext() { return null; } } /** * Look up a member, takes into account any ITDs on this type. * return null if not found */ public ResolvedMember lookupMemberNoSupers(Member member) { ResolvedMember ret = lookupDirectlyDeclaredMemberNoSupers(member); if (ret == null && interTypeMungers != null) { for (Iterator i = interTypeMungers.iterator(); i.hasNext();) { ConcreteTypeMunger tm = (ConcreteTypeMunger) i.next(); if (matches(tm.getSignature(), member)) { return tm.getSignature(); } } } return ret; } public ResolvedMember lookupMemberWithSupersAndITDs(Member member) { ResolvedMember ret = lookupMemberNoSupers(member); if (ret != null) return ret; ResolvedType supert = getSuperclass(); if (supert != null) { ret = supert.lookupMemberNoSupers(member); } return ret; } /** * as lookupMemberNoSupers, but does not include ITDs * * @param member * @return */ public ResolvedMember lookupDirectlyDeclaredMemberNoSupers(Member member) { ResolvedMember ret; if (member.getKind() == Member.FIELD) { ret = lookupMember(member, getDeclaredFields()); } else { // assert member.getKind() == Member.METHOD || member.getKind() == Member.CONSTRUCTOR ret = lookupMember(member, getDeclaredMethods()); } return ret; } /** * This lookup has specialized behaviour - a null result tells the * EclipseTypeMunger that it should make a default implementation of a * method on this type. * * @param member * @return */ public ResolvedMember lookupMemberIncludingITDsOnInterfaces(Member member) { return lookupMemberIncludingITDsOnInterfaces(member, this); } private ResolvedMember lookupMemberIncludingITDsOnInterfaces(Member member, ResolvedType onType) { ResolvedMember ret = onType.lookupMemberNoSupers(member); if (ret != null) { return ret; } else { ResolvedType superType = onType.getSuperclass(); if (superType != null) { ret = lookupMemberIncludingITDsOnInterfaces(member,superType); } if (ret == null) { // try interfaces then, but only ITDs now... ResolvedType[] superInterfaces = onType.getDeclaredInterfaces(); for (int i = 0; i < superInterfaces.length; i++) { ret = superInterfaces[i].lookupMethodInITDs(member); if (ret != null) return ret; } } } return ret; } protected List interTypeMungers = new ArrayList(0); public List getInterTypeMungers() { return interTypeMungers; } public List getInterTypeParentMungers() { List l = new ArrayList(); for (Iterator iter = interTypeMungers.iterator(); iter.hasNext();) { ConcreteTypeMunger element = (ConcreteTypeMunger) iter.next(); if (element.getMunger() instanceof NewParentTypeMunger) l.add(element); } return l; } /** * ??? This method is O(N*M) where N = number of methods and M is number of * inter-type declarations in my super */ public List getInterTypeMungersIncludingSupers() { ArrayList ret = new ArrayList(); collectInterTypeMungers(ret); return ret; } public List getInterTypeParentMungersIncludingSupers() { ArrayList ret = new ArrayList(); collectInterTypeParentMungers(ret); return ret; } private void collectInterTypeParentMungers(List collector) { for (Iterator iter = getDirectSupertypes(); iter.hasNext();) { ResolvedType superType = (ResolvedType) iter.next(); superType.collectInterTypeParentMungers(collector); } collector.addAll(getInterTypeParentMungers()); } protected void collectInterTypeMungers(List collector) { for (Iterator iter = getDirectSupertypes(); iter.hasNext();) { ResolvedType superType = (ResolvedType) iter.next(); superType.collectInterTypeMungers(collector); } outer: for (Iterator iter1 = collector.iterator(); iter1.hasNext();) { ConcreteTypeMunger superMunger = (ConcreteTypeMunger) iter1.next(); if ( superMunger.getSignature() == null) continue; if ( !superMunger.getSignature().isAbstract()) continue; for (Iterator iter = getInterTypeMungers().iterator(); iter.hasNext();) { ConcreteTypeMunger myMunger = (ConcreteTypeMunger) iter.next(); if (conflictingSignature(myMunger.getSignature(), superMunger.getSignature())) { iter1.remove(); continue outer; } } if (!superMunger.getSignature().isPublic()) continue; for (Iterator iter = getMethods(); iter.hasNext(); ) { ResolvedMember method = (ResolvedMember)iter.next(); if (conflictingSignature(method, superMunger.getSignature())) { iter1.remove(); continue outer; } } } collector.addAll(getInterTypeMungers()); } /** * Check: * 1) That we don't have any abstract type mungers unless this type is abstract. * 2) That an abstract ITDM on an interface is declared public. (Compiler limitation) (PR70794) */ public void checkInterTypeMungers() { if (isAbstract()) return; boolean itdProblem = false; for (Iterator iter = getInterTypeMungersIncludingSupers().iterator(); iter.hasNext();) { ConcreteTypeMunger munger = (ConcreteTypeMunger) iter.next(); itdProblem = checkAbstractDeclaration(munger) || itdProblem; // Rule 2 } if (itdProblem) return; // If the rules above are broken, return right now for (Iterator iter = getInterTypeMungersIncludingSupers().iterator(); iter.hasNext();) { ConcreteTypeMunger munger = (ConcreteTypeMunger) iter.next(); if (munger.getSignature() != null && munger.getSignature().isAbstract()) { // Rule 1 if (munger.getMunger().getKind() == ResolvedTypeMunger.MethodDelegate) { ;//ignore for @AJ ITD as munger.getSignature() is the interface method hence abstract } else { world.getMessageHandler().handleMessage( new Message("must implement abstract inter-type declaration: " + munger.getSignature(), "", IMessage.ERROR, getSourceLocation(), null, new ISourceLocation[] { getMungerLocation(munger) })); } } } } /** * See PR70794. This method checks that if an abstract inter-type method declaration is made on * an interface then it must also be public. * This is a compiler limitation that could be made to work in the future (if someone * provides a worthwhile usecase) * * @return indicates if the munger failed the check */ private boolean checkAbstractDeclaration(ConcreteTypeMunger munger) { if (munger.getMunger()!=null && (munger.getMunger() instanceof NewMethodTypeMunger)) { ResolvedMember itdMember = munger.getSignature(); ResolvedType onType = itdMember.getDeclaringType().resolve(world); if (onType.isInterface() && itdMember.isAbstract() && !itdMember.isPublic()) { world.getMessageHandler().handleMessage( new Message(WeaverMessages.format(WeaverMessages.ITD_ABSTRACT_MUST_BE_PUBLIC_ON_INTERFACE,munger.getSignature(),onType),"", Message.ERROR,getSourceLocation(),null, new ISourceLocation[]{getMungerLocation(munger)}) ); return true; } } return false; } /** * Get a source location for the munger. * Until intertype mungers remember where they came from, the source location * for the munger itself is null. In these cases use the * source location for the aspect containing the ITD. */ private ISourceLocation getMungerLocation(ConcreteTypeMunger munger) { ISourceLocation sloc = munger.getSourceLocation(); if (sloc == null) { sloc = munger.getAspectType().getSourceLocation(); } return sloc; } /** * Returns a ResolvedType object representing the declaring type of this type, or * null if this type does not represent a non-package-level-type. * <p/> * <strong>Warning</strong>: This is guaranteed to work for all member types. * For anonymous/local types, the only guarantee is given in JLS 13.1, where * it guarantees that if you call getDeclaringType() repeatedly, you will eventually * get the top-level class, but it does not say anything about classes in between. * * @return the declaring UnresolvedType object, or null. */ public ResolvedType getDeclaringType() { if (isArray()) return null; String name = getName(); int lastDollar = name.lastIndexOf('$'); while (lastDollar >0) { // allow for classes starting '$' (pr120474) ResolvedType ret = world.resolve(UnresolvedType.forName(name.substring(0, lastDollar)), true); if (!ResolvedType.isMissing(ret)) return ret; lastDollar = name.lastIndexOf('$', lastDollar-1); } return null; } public static boolean isVisible(int modifiers, ResolvedType targetType, ResolvedType fromType) { //System.err.println("mod: " + modifiers + ", " + targetType + " and " + fromType); if (Modifier.isPublic(modifiers)) { return true; } else if (Modifier.isPrivate(modifiers)) { return targetType.getOutermostType().equals(fromType.getOutermostType()); } else if (Modifier.isProtected(modifiers)) { return samePackage(targetType, fromType) || targetType.isAssignableFrom(fromType); } else { // package-visible return samePackage(targetType, fromType); } } public static boolean hasBridgeModifier(int modifiers) { return (modifiers & Constants.ACC_BRIDGE)!=0; } private static boolean samePackage( ResolvedType targetType, ResolvedType fromType) { String p1 = targetType.getPackageName(); String p2 = fromType.getPackageName(); if (p1 == null) return p2 == null; if (p2 == null) return false; return p1.equals(p2); } /** * Checks if the generic type for 'this' and the generic type for 'other' are the same - * it can be passed raw or parameterized versions and will just compare the underlying * generic type. */ private boolean genericTypeEquals(ResolvedType other) { ResolvedType rt = other; if (rt.isParameterizedType() || rt.isRawType()) rt.getGenericType(); if (( (isParameterizedType() || isRawType()) && getGenericType().equals(rt)) || (this.equals(other))) return true; return false; } /** * Look up the actual occurence of a particular type in the hierarchy for * 'this' type. The input is going to be a generic type, and the caller * wants to know if it was used in its RAW or a PARAMETERIZED form in this * hierarchy. * * returns null if it can't be found. */ public ResolvedType discoverActualOccurrenceOfTypeInHierarchy(ResolvedType lookingFor) { if (!lookingFor.isGenericType()) throw new BCException("assertion failed: method should only be called with generic type, but "+lookingFor+" is "+lookingFor.typeKind); if (this.equals(ResolvedType.OBJECT)) return null; if (genericTypeEquals(lookingFor)) return this; ResolvedType superT = getSuperclass(); if (superT.genericTypeEquals(lookingFor)) return superT; ResolvedType[] superIs = getDeclaredInterfaces(); for (int i = 0; i < superIs.length; i++) { ResolvedType superI = superIs[i]; if (superI.genericTypeEquals(lookingFor)) return superI; ResolvedType checkTheSuperI = superI.discoverActualOccurrenceOfTypeInHierarchy(lookingFor); if (checkTheSuperI!=null) return checkTheSuperI; } return superT.discoverActualOccurrenceOfTypeInHierarchy(lookingFor); } /** * Called for all type mungers but only does something if they share type variables * with a generic type which they target. When this happens this routine will check * for the target type in the target hierarchy and 'bind' any type parameters as * appropriate. For example, for the ITD "List<T> I<T>.x" against a type like this: * "class A implements I<String>" this routine will return a parameterized form of * the ITD "List<String> I.x" */ public ConcreteTypeMunger fillInAnyTypeParameters(ConcreteTypeMunger munger) { boolean debug = false; ResolvedMember member = munger.getSignature(); if (munger.isTargetTypeParameterized()) { if (debug) System.err.println("Processing attempted parameterization of "+munger+" targetting type "+this); if (debug) System.err.println(" This type is "+this+" ("+typeKind+")"); // need to tailor this munger instance for the particular target... if (debug) System.err.println(" Signature that needs parameterizing: "+member); // Retrieve the generic type ResolvedType onType = world.resolve(member.getDeclaringType()).getGenericType(); member.resolve(world); // Ensure all parts of the member are resolved if (debug) System.err.println(" Actual target ontype: "+onType+" ("+onType.typeKind+")"); // quickly find the targettype in the type hierarchy for this type (it will be either RAW or PARAMETERIZED) ResolvedType actualTarget = discoverActualOccurrenceOfTypeInHierarchy(onType); if (actualTarget==null) throw new BCException("assertion failed: asked "+this+" for occurrence of "+onType+" in its hierarchy??"); // only bind the tvars if its a parameterized type or the raw type (in which case they collapse to bounds) - don't do it for generic types ;) if (!actualTarget.isGenericType()) { if (debug) System.err.println("Occurrence in "+this+" is actually "+actualTarget+" ("+actualTarget.typeKind+")"); // parameterize the signature // ResolvedMember newOne = member.parameterizedWith(actualTarget.getTypeParameters(),onType,actualTarget.isParameterizedType()); } //if (!actualTarget.isRawType()) munger = munger.parameterizedFor(actualTarget); if (debug) System.err.println("New sig: "+munger.getSignature()); if (debug) System.err.println("====================================="); } return munger; } public void addInterTypeMunger(ConcreteTypeMunger munger) { ResolvedMember sig = munger.getSignature(); if (sig == null || munger.getMunger() == null || munger.getMunger().getKind() == ResolvedTypeMunger.PrivilegedAccess) { interTypeMungers.add(munger); return; } ConcreteTypeMunger originalMunger = munger; // we will use the 'parameterized' ITD for all the comparisons but we say the original // one passed in actually matched as it will be added to the intertype member finder // for the target type. It is possible we only want to do this if a generic type // is discovered and the tvar is collapsed to a bound? munger = fillInAnyTypeParameters(munger); sig = munger.getSignature(); // possibly changed when type parms filled in //System.err.println("add: " + munger + " to " + this.getClassName() + " with " + interTypeMungers); if (sig.getKind() == Member.METHOD) { if (!compareToExistingMembers(munger, getMethodsWithoutIterator(false,true) /*getMethods()*/)) return; if (this.isInterface()) { if (!compareToExistingMembers(munger, Arrays.asList(world.getCoreType(OBJECT).getDeclaredMethods()).iterator())) return; } } else if (sig.getKind() == Member.FIELD) { if (!compareToExistingMembers(munger, Arrays.asList(getDeclaredFields()).iterator())) return; } else { if (!compareToExistingMembers(munger, Arrays.asList(getDeclaredMethods()).iterator())) return; } // now compare to existingMungers for (Iterator i = interTypeMungers.iterator(); i.hasNext(); ) { ConcreteTypeMunger existingMunger = (ConcreteTypeMunger)i.next(); if (conflictingSignature(existingMunger.getSignature(), munger.getSignature())) { //System.err.println("match " + munger + " with " + existingMunger); if (isVisible(munger.getSignature().getModifiers(), munger.getAspectType(), existingMunger.getAspectType())) { //System.err.println(" is visible"); int c = compareMemberPrecedence(sig, existingMunger.getSignature()); if (c == 0) { c = getWorld().compareByPrecedenceAndHierarchy(munger.getAspectType(), existingMunger.getAspectType()); } //System.err.println(" compare: " + c); if (c < 0) { // the existing munger dominates the new munger checkLegalOverride(munger.getSignature(), existingMunger.getSignature()); return; } else if (c > 0) { // the new munger dominates the existing one checkLegalOverride(existingMunger.getSignature(), munger.getSignature()); i.remove(); break; } else { interTypeConflictError(munger, existingMunger); interTypeConflictError(existingMunger, munger); return; } } } } //System.err.println("adding: " + munger + " to " + this); // we are adding the parameterized form of the ITD to the list of // mungers. Within it, the munger knows the original declared // signature for the ITD so it can be retrieved. interTypeMungers.add(munger); } private boolean compareToExistingMembers(ConcreteTypeMunger munger, List existingMembersList) { return compareToExistingMembers(munger,existingMembersList.iterator()); } //??? returning too soon private boolean compareToExistingMembers(ConcreteTypeMunger munger, Iterator existingMembers) { ResolvedMember sig = munger.getSignature(); while (existingMembers.hasNext()) { ResolvedMember existingMember = (ResolvedMember)existingMembers.next(); // don't worry about clashing with bridge methods if (existingMember.isBridgeMethod()) continue; //System.err.println("Comparing munger: "+sig+" with member "+existingMember); if (conflictingSignature(existingMember, munger.getSignature())) { //System.err.println("conflict: existingMember=" + existingMember + " typeMunger=" + munger); //System.err.println(munger.getSourceLocation() + ", " + munger.getSignature() + ", " + munger.getSignature().getSourceLocation()); if (isVisible(existingMember.getModifiers(), this, munger.getAspectType())) { int c = compareMemberPrecedence(sig, existingMember); //System.err.println(" c: " + c); if (c < 0) { // existingMember dominates munger checkLegalOverride(munger.getSignature(), existingMember); return false; } else if (c > 0) { // munger dominates existingMember checkLegalOverride(existingMember, munger.getSignature()); //interTypeMungers.add(munger); //??? might need list of these overridden abstracts continue; } else { // bridge methods can differ solely in return type. // FIXME this whole method seems very hokey - unaware of covariance/varargs/bridging - it // could do with a rewrite ! boolean sameReturnTypes = (existingMember.getReturnType().equals(sig.getReturnType())); if (sameReturnTypes) getWorld().getMessageHandler().handleMessage( MessageUtil.error(WeaverMessages.format(WeaverMessages.ITD_MEMBER_CONFLICT,munger.getAspectType().getName(), existingMember), munger.getSourceLocation()) ); } } else if (isDuplicateMemberWithinTargetType(existingMember,this,sig)) { getWorld().getMessageHandler().handleMessage( MessageUtil.error(WeaverMessages.format(WeaverMessages.ITD_MEMBER_CONFLICT,munger.getAspectType().getName(), existingMember), munger.getSourceLocation()) ); ; } //return; } } return true; } // we know that the member signature matches, but that the member in the target type is not visible to the aspect. // this may still be disallowed if it would result in two members within the same declaring type with the same // signature AND more than one of them is concrete AND they are both visible within the target type. private boolean isDuplicateMemberWithinTargetType(ResolvedMember existingMember, ResolvedType targetType,ResolvedMember itdMember) { if ( (existingMember.isAbstract() || itdMember.isAbstract())) return false; UnresolvedType declaringType = existingMember.getDeclaringType(); if (!targetType.equals(declaringType)) return false; // now have to test that itdMember is visible from targetType if (itdMember.isPrivate()) return false; if (itdMember.isPublic()) return true; // must be in same package to be visible then... if (!targetType.getPackageName().equals(itdMember.getDeclaringType().getPackageName())) return false; // trying to put two members with the same signature into the exact same type..., and both visible in that type. return true; } /** * @return true if the override is legal * note: calling showMessage with two locations issues TWO messages, not ONE message * with an additional source location. */ public boolean checkLegalOverride(ResolvedMember parent, ResolvedMember child) { //System.err.println("check: " + child.getDeclaringType() + " overrides " + parent.getDeclaringType()); if (Modifier.isFinal(parent.getModifiers())) { world.showMessage(Message.ERROR, WeaverMessages.format(WeaverMessages.CANT_OVERRIDE_FINAL_MEMBER,parent), child.getSourceLocation(),null); return false; } boolean incompatibleReturnTypes = false; // In 1.5 mode, allow for covariance on return type if (world.isInJava5Mode() && parent.getKind()==Member.METHOD) { // Look at the generic types when doing this comparison ResolvedType rtParentReturnType = parent.getGenericReturnType().resolve(world); ResolvedType rtChildReturnType = child.getGenericReturnType().resolve(world); incompatibleReturnTypes = !rtParentReturnType.isAssignableFrom(rtChildReturnType); if (incompatibleReturnTypes) { incompatibleReturnTypes = !rtParentReturnType.isAssignableFrom(rtChildReturnType); } } else { incompatibleReturnTypes =!parent.getReturnType().equals(child.getReturnType()); } if (incompatibleReturnTypes) { world.showMessage(IMessage.ERROR, WeaverMessages.format(WeaverMessages.ITD_RETURN_TYPE_MISMATCH,parent,child), child.getSourceLocation(), parent.getSourceLocation()); return false; } if (parent.getKind() == Member.POINTCUT) { UnresolvedType[] pTypes = parent.getParameterTypes(); UnresolvedType[] cTypes = child.getParameterTypes(); if (!Arrays.equals(pTypes, cTypes)) { world.showMessage(IMessage.ERROR, WeaverMessages.format(WeaverMessages.ITD_PARAM_TYPE_MISMATCH,parent,child), child.getSourceLocation(), parent.getSourceLocation()); return false; } } //System.err.println("check: " + child.getModifiers() + " more visible " + parent.getModifiers()); if (isMoreVisible(parent.getModifiers(), child.getModifiers())) { world.showMessage(IMessage.ERROR, WeaverMessages.format(WeaverMessages.ITD_VISIBILITY_REDUCTION,parent,child), child.getSourceLocation(), parent.getSourceLocation()); return false; } // check declared exceptions ResolvedType[] childExceptions = world.resolve(child.getExceptions()); ResolvedType[] parentExceptions = world.resolve(parent.getExceptions()); ResolvedType runtimeException = world.resolve("java.lang.RuntimeException"); ResolvedType error = world.resolve("java.lang.Error"); outer: for (int i = 0, leni = childExceptions.length; i < leni; i++) { //System.err.println("checking: " + childExceptions[i]); if (runtimeException.isAssignableFrom(childExceptions[i])) continue; if (error.isAssignableFrom(childExceptions[i])) continue; for (int j = 0, lenj = parentExceptions.length; j < lenj; j++) { if (parentExceptions[j].isAssignableFrom(childExceptions[i])) continue outer; } // this message is now better handled my MethodVerifier in JDT core. // world.showMessage(IMessage.ERROR, // WeaverMessages.format(WeaverMessages.ITD_DOESNT_THROW,childExceptions[i].getName()), // child.getSourceLocation(), null); return false; } if (parent.isStatic() && !child.isStatic()) { world.showMessage(IMessage.ERROR, WeaverMessages.format(WeaverMessages.ITD_OVERRIDDEN_STATIC,child,parent), child.getSourceLocation(),null); return false; } else if (child.isStatic() && !parent.isStatic()) { world.showMessage(IMessage.ERROR, WeaverMessages.format(WeaverMessages.ITD_OVERIDDING_STATIC,child,parent), child.getSourceLocation(),null); return false; } return true; } private int compareMemberPrecedence(ResolvedMember m1, ResolvedMember m2) { //if (!m1.getReturnType().equals(m2.getReturnType())) return 0; // need to allow for the special case of 'clone' - which is like abstract but is // not marked abstract. The code below this next line seems to make assumptions // about what will have gotten through the compiler based on the normal // java rules. clone goes against these... if (m2.isProtected() && m2.getName().charAt(0)=='c') { UnresolvedType declaring = m2.getDeclaringType(); if (declaring!=null) { if (declaring.getName().equals("java.lang.Object") && m2.getName().equals("clone")) return +1; } } if (Modifier.isAbstract(m1.getModifiers())) return -1; if (Modifier.isAbstract(m2.getModifiers())) return +1; if (m1.getDeclaringType().equals(m2.getDeclaringType())) return 0; ResolvedType t1 = m1.getDeclaringType().resolve(world); ResolvedType t2 = m2.getDeclaringType().resolve(world); if (t1.isAssignableFrom(t2)) { return -1; } if (t2.isAssignableFrom(t1)) { return +1; } return 0; } public static boolean isMoreVisible(int m1, int m2) { if (Modifier.isPrivate(m1)) return false; if (isPackage(m1)) return Modifier.isPrivate(m2); if (Modifier.isProtected(m1)) return /* private package */ (Modifier.isPrivate(m2) || isPackage(m2)); if (Modifier.isPublic(m1)) return /* private package protected */ ! Modifier.isPublic(m2); throw new RuntimeException("bad modifier: " + m1); } private static boolean isPackage(int i) { return (0 == (i & (Modifier.PUBLIC | Modifier.PRIVATE | Modifier.PROTECTED))); } private void interTypeConflictError( ConcreteTypeMunger m1, ConcreteTypeMunger m2) { //XXX this works only if we ignore separate compilation issues //XXX dual errors possible if (this instanceof BcelObjectType) return; //System.err.println("conflict at " + m2.getSourceLocation()); getWorld().showMessage(IMessage.ERROR, WeaverMessages.format(WeaverMessages.ITD_CONFLICT,m1.getAspectType().getName(), m2.getSignature(),m2.getAspectType().getName()), m2.getSourceLocation(), getSourceLocation()); } public ResolvedMember lookupSyntheticMember(Member member) { //??? horribly inefficient //for (Iterator i = //System.err.println("lookup " + member + " in " + interTypeMungers); for (Iterator i = interTypeMungers.iterator(); i.hasNext(); ) { ConcreteTypeMunger m = (ConcreteTypeMunger)i.next(); ResolvedMember ret = m.getMatchingSyntheticMember(member); if (ret != null) { //System.err.println(" found: " + ret); return ret; } } // Handling members for the new array join point if (world.isJoinpointArrayConstructionEnabled() && this.isArray()) { if (member.getKind()==Member.CONSTRUCTOR) { ResolvedMemberImpl ret = new ResolvedMemberImpl(Member.CONSTRUCTOR,this,Modifier.PUBLIC, ResolvedType.VOID,"<init>",world.resolve(member.getParameterTypes())); return ret; } } // if (this.getSuperclass() != ResolvedType.OBJECT && this.getSuperclass() != null) { // return getSuperclass().lookupSyntheticMember(member); // } return null; } public void clearInterTypeMungers() { if (isRawType()) getGenericType().clearInterTypeMungers(); interTypeMungers = new ArrayList(); } public boolean isTopmostImplementor(ResolvedType interfaceType) { if (isInterface()) return false; if (!interfaceType.isAssignableFrom(this,true)) return false; // check that I'm truly the topmost implementor if (this.getSuperclass().isMissing()) return true; // we don't know anything about supertype, and it can't be exposed to weaver if (interfaceType.isAssignableFrom(this.getSuperclass(),true)) { return false; } return true; } public ResolvedType getTopmostImplementor(ResolvedType interfaceType) { if (isInterface()) return null; if (!interfaceType.isAssignableFrom(this)) return null; // Check if my super class is an implementor? ResolvedType higherType = this.getSuperclass().getTopmostImplementor(interfaceType); if (higherType!=null) return higherType; return this; } private ResolvedType findHigher(ResolvedType other) { if (this == other) return this; for(Iterator i = other.getDirectSupertypes(); i.hasNext(); ) { ResolvedType rtx = (ResolvedType)i.next(); boolean b = this.isAssignableFrom(rtx); if (b) return rtx; } return null; } public List getExposedPointcuts() { List ret = new ArrayList(); if (getSuperclass() != null) ret.addAll(getSuperclass().getExposedPointcuts()); for (Iterator i = Arrays.asList(getDeclaredInterfaces()).iterator(); i.hasNext(); ) { ResolvedType t = (ResolvedType)i.next(); addPointcutsResolvingConflicts(ret, Arrays.asList(t.getDeclaredPointcuts()), false); } addPointcutsResolvingConflicts(ret, Arrays.asList(getDeclaredPointcuts()), true); for (Iterator i = ret.iterator(); i.hasNext(); ) { ResolvedPointcutDefinition inherited = (ResolvedPointcutDefinition)i.next(); // System.err.println("looking at: " + inherited + " in " + this); // System.err.println(" " + inherited.isAbstract() + " in " + this.isAbstract()); if (inherited.isAbstract()) { if (!this.isAbstract()) { getWorld().showMessage(IMessage.ERROR, WeaverMessages.format(WeaverMessages.POINCUT_NOT_CONCRETE,inherited,this.getName()), inherited.getSourceLocation(), this.getSourceLocation()); } } } return ret; } private void addPointcutsResolvingConflicts(List acc, List added, boolean isOverriding) { for (Iterator i = added.iterator(); i.hasNext();) { ResolvedPointcutDefinition toAdd = (ResolvedPointcutDefinition) i.next(); //System.err.println("adding: " + toAdd); for (Iterator j = acc.iterator(); j.hasNext();) { ResolvedPointcutDefinition existing = (ResolvedPointcutDefinition) j.next(); if (existing == toAdd) continue; if (!isVisible(existing.getModifiers(), existing.getDeclaringType().resolve(getWorld()), this)) { continue; } if (conflictingSignature(existing, toAdd)) { if (isOverriding) { checkLegalOverride(existing, toAdd); j.remove(); } else { getWorld().showMessage( IMessage.ERROR, WeaverMessages.format(WeaverMessages.CONFLICTING_INHERITED_POINTCUTS,this.getName() + toAdd.getSignature()), existing.getSourceLocation(), toAdd.getSourceLocation()); j.remove(); } } } acc.add(toAdd); } } public ISourceLocation getSourceLocation() { return null; } public boolean isExposedToWeaver() { return false; } public WeaverStateInfo getWeaverState() { return null; } /** * Overridden by ReferenceType to return a sensible answer for parameterized and raw types. * * @return */ public ResolvedType getGenericType() { if (!(isParameterizedType() || isRawType())) throw new BCException("The type "+getBaseName()+" is not parameterized or raw - it has no generic type"); return null; } /** * overriden by ReferenceType to return the gsig for a generic type * @return */ public String getGenericSignature() { return ""; } public ResolvedType parameterizedWith(UnresolvedType[] typeParameters) { if (!(isGenericType() || isParameterizedType())) return this; return TypeFactory.createParameterizedType(this.getGenericType(), typeParameters, getWorld()); } /** * Iff I am a parameterized type, and any of my parameters are type variable * references, return a version with those type parameters replaced in accordance * with the passed bindings. */ public UnresolvedType parameterize(Map typeBindings) { if (!isParameterizedType()) throw new IllegalStateException("Can't parameterize a type that is not a parameterized type"); boolean workToDo = false; for (int i = 0; i < typeParameters.length; i++) { if (typeParameters[i].isTypeVariableReference()) { workToDo = true; } } if (!workToDo) { return this; } else { UnresolvedType[] newTypeParams = new UnresolvedType[typeParameters.length]; for (int i = 0; i < newTypeParams.length; i++) { newTypeParams[i] = typeParameters[i]; if (newTypeParams[i].isTypeVariableReference()) { TypeVariableReferenceType tvrt = (TypeVariableReferenceType) newTypeParams[i]; UnresolvedType binding = (UnresolvedType) typeBindings.get(tvrt.getTypeVariable().getName()); if (binding != null) newTypeParams[i] = binding; } } return TypeFactory.createParameterizedType(getGenericType(), newTypeParams, getWorld()); } } public boolean hasParameterizedSuperType() { getParameterizedSuperTypes(); return parameterizedSuperTypes.length > 0; } public boolean hasGenericSuperType() { ResolvedType[] superTypes = getDeclaredInterfaces(); for (int i = 0; i < superTypes.length; i++) { if (superTypes[i].isGenericType()) return true; } return false; } private ResolvedType[] parameterizedSuperTypes = null; /** * Similar to the above method, but accumulates the super types * * @return */ public ResolvedType[] getParameterizedSuperTypes() { if (parameterizedSuperTypes != null) return parameterizedSuperTypes; List accumulatedTypes = new ArrayList(); accumulateParameterizedSuperTypes(this,accumulatedTypes); ResolvedType[] ret = new ResolvedType[accumulatedTypes.size()]; parameterizedSuperTypes = (ResolvedType[]) accumulatedTypes.toArray(ret); return parameterizedSuperTypes; } private void accumulateParameterizedSuperTypes(ResolvedType forType, List parameterizedTypeList) { if (forType.isParameterizedType()) { parameterizedTypeList.add(forType); } if (forType.getSuperclass() != null) { accumulateParameterizedSuperTypes(forType.getSuperclass(), parameterizedTypeList); } ResolvedType[] interfaces = forType.getDeclaredInterfaces(); for (int i = 0; i < interfaces.length; i++) { accumulateParameterizedSuperTypes(interfaces[i], parameterizedTypeList); } } /** * Types may have pointcuts just as they have methods and fields. */ public ResolvedPointcutDefinition findPointcut(String name, World world) { throw new UnsupportedOperationException("Not yet implemenented"); } /** * @return true if assignable to java.lang.Exception */ public boolean isException() { return (world.getCoreType(UnresolvedType.JAVA_LANG_EXCEPTION).isAssignableFrom(this)); } /** * @return true if it is an exception and it is a checked one, false otherwise. */ public boolean isCheckedException() { if (!isException()) return false; if (world.getCoreType(UnresolvedType.RUNTIME_EXCEPTION).isAssignableFrom(this)) return false; return true; } /** * Determines if variables of this type could be assigned values of another * with lots of help. * java.lang.Object is convertable from all types. * A primitive type is convertable from X iff it's assignable from X. * A reference type is convertable from X iff it's coerceable from X. * In other words, X isConvertableFrom Y iff the compiler thinks that _some_ value of Y * could be assignable to a variable of type X without loss of precision. * * @param other the other type * @param world the {@link World} in which the possible assignment should be checked. * @return true iff variables of this type could be assigned values of other with possible conversion */ public final boolean isConvertableFrom(ResolvedType other) { // // version from TypeX // if (this.equals(OBJECT)) return true; // if (this.isPrimitiveType() || other.isPrimitiveType()) return this.isAssignableFrom(other); // return this.isCoerceableFrom(other); // // version from ResolvedTypeX if (this.equals(OBJECT)) return true; if (world.isInJava5Mode()) { if (this.isPrimitiveType()^other.isPrimitiveType()) { // If one is primitive and the other isnt if (validBoxing.contains(this.getSignature()+other.getSignature())) return true; } } if (this.isPrimitiveType() || other.isPrimitiveType()) return this.isAssignableFrom(other); return this.isCoerceableFrom(other); } /** * Determines if the variables of this type could be assigned values * of another type without casting. This still allows for assignment conversion * as per JLS 2ed 5.2. For object types, this means supertypeOrEqual(THIS, OTHER). * * @param other the other type * @param world the {@link World} in which the possible assignment should be checked. * @return true iff variables of this type could be assigned values of other without casting * @throws NullPointerException if other is null */ public abstract boolean isAssignableFrom(ResolvedType other); public abstract boolean isAssignableFrom(ResolvedType other, boolean allowMissing); /** * Determines if values of another type could possibly be cast to * this type. The rules followed are from JLS 2ed 5.5, "Casting Conversion". * <p/> * <p> This method should be commutative, i.e., for all UnresolvedType a, b and all World w: * <p/> * <blockquote><pre> * a.isCoerceableFrom(b, w) == b.isCoerceableFrom(a, w) * </pre></blockquote> * * @param other the other type * @param world the {@link World} in which the possible coersion should be checked. * @return true iff values of other could possibly be cast to this type. * @throws NullPointerException if other is null. */ public abstract boolean isCoerceableFrom(ResolvedType other); public boolean needsNoConversionFrom(ResolvedType o) { return isAssignableFrom(o); } /** * Implemented by ReferenceTypes */ public String getSignatureForAttribute() { throw new RuntimeException("Cannot ask this type "+this+" for a generic sig attribute"); } private FuzzyBoolean parameterizedWithAMemberTypeVariable = FuzzyBoolean.MAYBE; /** * return true if the parameterization of this type includes a member type variable. Member * type variables occur in generic methods/ctors. */ public boolean isParameterizedWithAMemberTypeVariable() { // MAYBE means we haven't worked it out yet... if (parameterizedWithAMemberTypeVariable==FuzzyBoolean.MAYBE) { // if there are no type parameters then we cant be... if (typeParameters==null || typeParameters.length==0) { parameterizedWithAMemberTypeVariable = FuzzyBoolean.NO; return false; } for (int i = 0; i < typeParameters.length; i++) { UnresolvedType aType = (ResolvedType)typeParameters[i]; if (aType.isTypeVariableReference() && // assume the worst - if its definetly not a type declared one, it could be anything ((TypeVariableReference)aType).getTypeVariable().getDeclaringElementKind()!=TypeVariable.TYPE) { parameterizedWithAMemberTypeVariable = FuzzyBoolean.YES; return true; } if (aType.isParameterizedType()) { boolean b = aType.isParameterizedWithAMemberTypeVariable(); if (b) { parameterizedWithAMemberTypeVariable = FuzzyBoolean.YES; return true; } } if (aType.isGenericWildcard()) { if (aType.isExtends()) { boolean b = false; UnresolvedType upperBound = aType.getUpperBound(); if (upperBound.isParameterizedType()) { b = upperBound.isParameterizedWithAMemberTypeVariable(); } else if (upperBound.isTypeVariableReference() && ((TypeVariableReference)upperBound).getTypeVariable().getDeclaringElementKind()==TypeVariable.METHOD) { b = true; } if (b) { parameterizedWithAMemberTypeVariable = FuzzyBoolean.YES; return true; } // FIXME asc need to check additional interface bounds } if (aType.isSuper()) { boolean b = false; UnresolvedType lowerBound = aType.getLowerBound(); if (lowerBound.isParameterizedType()) { b = lowerBound.isParameterizedWithAMemberTypeVariable(); } else if (lowerBound.isTypeVariableReference() && ((TypeVariableReference)lowerBound).getTypeVariable().getDeclaringElementKind()==TypeVariable.METHOD) { b = true; } if (b) { parameterizedWithAMemberTypeVariable = FuzzyBoolean.YES; return true; } } } } parameterizedWithAMemberTypeVariable=FuzzyBoolean.NO; } return parameterizedWithAMemberTypeVariable.alwaysTrue(); } protected boolean ajMembersNeedParameterization() { if (isParameterizedType()) return true; if (getSuperclass() != null) return getSuperclass().ajMembersNeedParameterization(); return false; } protected Map getAjMemberParameterizationMap() { Map myMap = getMemberParameterizationMap(); if (myMap.size() == 0) { // might extend a parameterized aspect that we also need to consider... if (getSuperclass() != null) return getSuperclass().getAjMemberParameterizationMap(); } return myMap; } 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; } }
161,502
Bug 161502 UnsupportedOperationException thrown: unable to parameterize unresolved type: Pjava/util/List<+Ljava/lang/Object; >;
Generic parameters (like List<? extends T>) in pointcuts throw UnsupportedOperationException. java.lang.UnsupportedOperationException at org.aspectj.weaver.UnresolvedType.parameterize(UnresolvedType.java: 220) at org.aspectj.weaver.patterns.ExactTypePattern.parameterizeWith (ExactTypePattern.java:244) at org.aspectj.weaver.patterns.SignaturePattern.parameterizeWith (SignaturePattern.java:265) at org.aspectj.weaver.patterns.KindedPointcut.parameterizeWith (KindedPointcut.java:381) at org.aspectj.weaver.bcel.BcelAdvice.parameterizeWith (BcelAdvice.java:93) at org.aspectj.weaver.ResolvedType.getDeclaredAdvice (ResolvedType.java:710) at org.aspectj.weaver.ResolvedType.getDeclaredShadowMungers (ResolvedType.java:739) at org.aspectj.weaver.ResolvedType.collectShadowMungers (ResolvedType.java:575) at org.aspectj.weaver.ResolvedType.collectCrosscuttingMembers (ResolvedType.java:504) at org.aspectj.weaver.CrosscuttingMembersSet.addOrReplaceAspect (CrosscuttingMembersSet.java:68) at org.aspectj.weaver.CrosscuttingMembersSet.addOrReplaceAspect (CrosscuttingMembersSet.java:57) at org.aspectj.weaver.bcel.BcelWeaver.prepareForWeave(BcelWeaver.java: 450) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.weave (AjCompilerAdapter.java:299) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.afterCompiling (AjCompilerAdapter.java:192) at org.aspectj.ajdt.internal.compiler.CompilerAdapter.ajc $afterReturning$org_aspectj_ajdt_internal_compiler_CompilerAdapter$2 $f9cc9ca0(CompilerAdapter.aj:70) at org.aspectj.org.eclipse.jdt.internal.compiler.Compiler.compile (Compiler.java:367) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.performCompilation (AjBuildManager.java:887) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.doBuild (AjBuildManager.java:244) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.batchBuild (AjBuildManager.java:163) at org.aspectj.ajde.internal.CompilerAdapter.compile (CompilerAdapter.java:122) at org.aspectj.ajde.internal.AspectJBuildManager$CompilerThread.run (AspectJBuildManager.java:191) UnsupportedOperationException thrown: unable to parameterize unresolved type: Pjava/util/List<+Ljava/lang/Object;>; To reproduce this exception compile the following code snippet. import java.util.ArrayList; import java.util.List; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; public class Main { public List<? extends Element> getElements() { return new ArrayList<Element>(); } class Element {}; @Aspect static abstract class Base<T> { @Around("call(List<? extends T> *.*(..))") public List<? extends T> elementList(ProceedingJoinPoint thisJoinPoint) { try { return (List<? extends T>)thisJoinPoint.proceed(); } catch (Throwable e) { throw new RuntimeException(e); } } } @Aspect static class Concrete extends Base<Element> {} public static void main(String[] args) { new Main().getElements(); } }
resolved fixed
7b40e7e
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2006-10-24T12:42:57Z"
"2006-10-19T01:06:40Z"
weaver/src/org/aspectj/weaver/TypeVariable.java
/* ******************************************************************* * Copyright (c) 2005 Contributors. * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Eclipse Public License v1.0 * which accompanies this distribution and is available at * http://eclipse.org/legal/epl-v10.html * * Contributors: * Adrian Colyer Initial implementation * ******************************************************************/ package org.aspectj.weaver; import java.io.DataOutputStream; import java.io.IOException; import java.util.HashSet; import java.util.Set; /** * Represents a type variable with bounds */ public class TypeVariable { public static final TypeVariable[] NONE = new TypeVariable[0]; /** * whether or not the bounds of this type variable have been * resolved */ private boolean isResolved = false; private boolean beingResolved = false; /** * the name of the type variable as recorded in the generic signature */ private String name; private int rank; // It would be nice to push this field onto the TypeVariableDeclaringElement // interface (a getKind()) but at the moment we don't always guarantee // to set the declaring element (eclipse seems to utilise the knowledge of // what declared the type variable, but we dont yet...) /** * What kind of element declared this type variable? */ private int declaringElementKind = UNKNOWN; public static final int UNKNOWN = -1; public static final int METHOD = 1; public static final int TYPE = 2; private TypeVariableDeclaringElement declaringElement; /** * the upper bound of the type variable (default to Object). * From the extends clause, eg. T extends Number. */ private UnresolvedType upperBound = UnresolvedType.OBJECT; /** * any additional upper (interface) bounds. * from the extends clause, e.g. T extends Number & Comparable */ private UnresolvedType[] additionalInterfaceBounds = new UnresolvedType[0]; /** * any lower bound. * from the super clause, eg T super Foo */ private UnresolvedType lowerBound = null; public TypeVariable(String aName) { this.name = aName; } public TypeVariable(String aName, UnresolvedType anUpperBound) { this(aName); this.upperBound = anUpperBound; } public TypeVariable(String aName, UnresolvedType anUpperBound, UnresolvedType[] someAdditionalInterfaceBounds) { this(aName,anUpperBound); this.additionalInterfaceBounds = someAdditionalInterfaceBounds; } public TypeVariable(String aName, UnresolvedType anUpperBound, UnresolvedType[] someAdditionalInterfaceBounds, UnresolvedType aLowerBound) { this(aName,anUpperBound,someAdditionalInterfaceBounds); this.lowerBound = aLowerBound; } // First bound is the first 'real' bound, this can be an interface if // no class bound was specified (it will default to object) public UnresolvedType getFirstBound() { if (upperBound.equals(UnresolvedType.OBJECT) && additionalInterfaceBounds!=null && additionalInterfaceBounds.length!=0) { return additionalInterfaceBounds[0]; } return upperBound; } public UnresolvedType getUpperBound() { return upperBound; } public UnresolvedType[] getAdditionalInterfaceBounds() { return additionalInterfaceBounds; } public UnresolvedType getLowerBound() { return lowerBound; } public String getName() { return name; } /** * resolve all the bounds of this type variable */ public TypeVariable resolve(World inSomeWorld) { if (beingResolved) { return this; } // avoid spiral of death beingResolved = true; if (isResolved) return this; TypeVariable resolvedTVar = null; if (declaringElement != null) { // resolve by finding the real type var that we refer to... if (declaringElementKind == TYPE) { UnresolvedType declaring = (UnresolvedType) declaringElement; ReferenceType rd = (ReferenceType) declaring.resolve(inSomeWorld); TypeVariable[] tVars = rd.getTypeVariables(); for (int i = 0; i < tVars.length; i++) { if (tVars[i].getName().equals(getName())) { resolvedTVar = tVars[i]; break; } } } else { // look for type variable on method... ResolvedMember declaring = (ResolvedMember) declaringElement; TypeVariable[] tvrts = declaring.getTypeVariables(); for (int i = 0; i < tvrts.length; i++) { if (tvrts[i].getName().equals(getName())) resolvedTVar = tvrts[i]; // if (tvrts[i].isTypeVariableReference()) { // TypeVariableReferenceType tvrt = (TypeVariableReferenceType) tvrts[i].resolve(inSomeWorld); // TypeVariable tv = tvrt.getTypeVariable(); // if (tv.getName().equals(getName())) resolvedTVar = tv; // } } } if (resolvedTVar == null) { // well, this is bad... we didn't find the type variable on the member // could be a separate compilation issue... // should issue message, this is a workaround to get us going... resolvedTVar = this; } } else { resolvedTVar = this; } upperBound = resolvedTVar.upperBound; lowerBound = resolvedTVar.lowerBound; additionalInterfaceBounds = resolvedTVar.additionalInterfaceBounds; upperBound = upperBound.resolve(inSomeWorld); if (lowerBound != null) lowerBound = lowerBound.resolve(inSomeWorld); if (additionalInterfaceBounds!=null) { for (int i = 0; i < additionalInterfaceBounds.length; i++) { additionalInterfaceBounds[i] = additionalInterfaceBounds[i].resolve(inSomeWorld); } } isResolved = true; beingResolved = false; return this; } /** * answer true if the given type satisfies all of the bound constraints of this * type variable. * If type variable has not been resolved then throws IllegalStateException */ public boolean canBeBoundTo(ResolvedType aCandidateType) { if (!isResolved) throw new IllegalStateException("Can't answer binding questions prior to resolving"); if (aCandidateType.isTypeVariableReference()) { return matchingBounds((TypeVariableReferenceType)aCandidateType); } // wildcard can accept any binding if (aCandidateType.isGenericWildcard()) { // AMC - need a more robust test! return true; } // otherwise can be bound iff... // aCandidateType is a subtype of upperBound if (!isASubtypeOf(upperBound,aCandidateType)) { return false; } // aCandidateType is a subtype of all additionalInterfaceBounds for (int i = 0; i < additionalInterfaceBounds.length; i++) { if (!isASubtypeOf(additionalInterfaceBounds[i], aCandidateType)) { return false; } } // lowerBound is a subtype of aCandidateType if ((lowerBound != null) && (!isASubtypeOf(aCandidateType,lowerBound))) { return false; } return true; } // can match any type in the range of the type variable... // XXX what about interfaces? private boolean matchingBounds(TypeVariableReferenceType tvrt) { if (tvrt.getUpperBound() != getUpperBound()) return false; if (tvrt.hasLowerBound() != (getLowerBound() != null)) return false; if (tvrt.hasLowerBound() && tvrt.getLowerBound() != getLowerBound()) return false; // either we both have bounds, or neither of us have bounds ReferenceType[] tvrtBounds = tvrt.getAdditionalBounds(); if ((tvrtBounds != null) != (additionalInterfaceBounds != null)) return false; if (additionalInterfaceBounds != null) { // we both have bounds, compare if (tvrtBounds.length != additionalInterfaceBounds.length) return false; Set aAndNotB = new HashSet(); Set bAndNotA = new HashSet(); for (int i = 0; i < additionalInterfaceBounds.length; i++) { aAndNotB.add(additionalInterfaceBounds[i]); } for (int i = 0; i < tvrtBounds.length; i++) { bAndNotA.add(tvrtBounds[i]); } for (int i = 0; i < additionalInterfaceBounds.length; i++) { bAndNotA.remove(additionalInterfaceBounds[i]); } for (int i = 0; i < tvrtBounds.length; i++) { aAndNotB.remove(tvrtBounds[i]); } if (! (aAndNotB.isEmpty() && bAndNotA.isEmpty()) ) return false; } return true; } private boolean isASubtypeOf(UnresolvedType candidateSuperType, UnresolvedType candidateSubType) { ResolvedType superType = (ResolvedType) candidateSuperType; ResolvedType subType = (ResolvedType) candidateSubType; return superType.isAssignableFrom(subType); } // only used when resolving public void setUpperBound(UnresolvedType aTypeX) { this.upperBound = aTypeX; } // only used when resolving public void setLowerBound(UnresolvedType aTypeX) { this.lowerBound = aTypeX; } // only used when resolving public void setAdditionalInterfaceBounds(UnresolvedType[] someTypeXs) { this.additionalInterfaceBounds = someTypeXs; } public String toDebugString() { return getDisplayName(); } public String getDisplayName() { StringBuffer ret = new StringBuffer(); ret.append(name); if (!getFirstBound().getName().equals("java.lang.Object")) { ret.append(" extends "); ret.append(getFirstBound().getName()); if (additionalInterfaceBounds != null) { for (int i = 0; i < additionalInterfaceBounds.length; i++) { if (!getFirstBound().equals(additionalInterfaceBounds[i])) { ret.append(" & "); ret.append(additionalInterfaceBounds[i].getName()); } } } } if (lowerBound != null) { ret.append(" super "); ret.append(lowerBound.getName()); } return ret.toString(); } // good enough approximation public String toString() { return "TypeVar " + getDisplayName(); } /** * Return *full* signature for insertion in signature attribute, e.g. "T extends Number" would return "T:Ljava/lang/Number;" */ public String getSignature() { StringBuffer sb = new StringBuffer(); sb.append(name); sb.append(":"); sb.append(upperBound.getSignature()); if (additionalInterfaceBounds!=null && additionalInterfaceBounds.length!=0) { sb.append(":"); for (int i = 0; i < additionalInterfaceBounds.length; i++) { UnresolvedType iBound = additionalInterfaceBounds[i]; sb.append(iBound.getSignature()); } } return sb.toString(); } public void setRank(int rank) { this.rank=rank; } public int getRank() { return rank; } public void setDeclaringElement(TypeVariableDeclaringElement element) { this.declaringElement = element; if (element instanceof UnresolvedType) { this.declaringElementKind = TYPE; } else { this.declaringElementKind = METHOD; } } public TypeVariableDeclaringElement getDeclaringElement() { return declaringElement; } public void setDeclaringElementKind(int kind) { this.declaringElementKind = kind; } public int getDeclaringElementKind() { // if (declaringElementKind==UNKNOWN) throw new RuntimeException("Dont know declarer of this tvar : "+this); return declaringElementKind; } public void write(DataOutputStream s) throws IOException { // name, upperbound, additionalInterfaceBounds, lowerbound s.writeUTF(name); upperBound.write(s); if (additionalInterfaceBounds==null || additionalInterfaceBounds.length==0) { s.writeInt(0); } else { s.writeInt(additionalInterfaceBounds.length); for (int i = 0; i < additionalInterfaceBounds.length; i++) { UnresolvedType ibound = additionalInterfaceBounds[i]; ibound.write(s); } } } public static TypeVariable read(VersionedDataInputStream s) throws IOException { //if (s.getMajorVersion()>=AjAttribute.WeaverVersionInfo.WEAVER_VERSION_MAJOR_AJ150) { String name = s.readUTF(); UnresolvedType ubound = UnresolvedType.read(s); int iboundcount = s.readInt(); UnresolvedType[] ibounds = null; if (iboundcount>0) { ibounds = new UnresolvedType[iboundcount]; for (int i=0; i<iboundcount; i++) { ibounds[i] = UnresolvedType.read(s); } } TypeVariable newVariable = new TypeVariable(name,ubound,ibounds); return newVariable; } }
161,502
Bug 161502 UnsupportedOperationException thrown: unable to parameterize unresolved type: Pjava/util/List<+Ljava/lang/Object; >;
Generic parameters (like List<? extends T>) in pointcuts throw UnsupportedOperationException. java.lang.UnsupportedOperationException at org.aspectj.weaver.UnresolvedType.parameterize(UnresolvedType.java: 220) at org.aspectj.weaver.patterns.ExactTypePattern.parameterizeWith (ExactTypePattern.java:244) at org.aspectj.weaver.patterns.SignaturePattern.parameterizeWith (SignaturePattern.java:265) at org.aspectj.weaver.patterns.KindedPointcut.parameterizeWith (KindedPointcut.java:381) at org.aspectj.weaver.bcel.BcelAdvice.parameterizeWith (BcelAdvice.java:93) at org.aspectj.weaver.ResolvedType.getDeclaredAdvice (ResolvedType.java:710) at org.aspectj.weaver.ResolvedType.getDeclaredShadowMungers (ResolvedType.java:739) at org.aspectj.weaver.ResolvedType.collectShadowMungers (ResolvedType.java:575) at org.aspectj.weaver.ResolvedType.collectCrosscuttingMembers (ResolvedType.java:504) at org.aspectj.weaver.CrosscuttingMembersSet.addOrReplaceAspect (CrosscuttingMembersSet.java:68) at org.aspectj.weaver.CrosscuttingMembersSet.addOrReplaceAspect (CrosscuttingMembersSet.java:57) at org.aspectj.weaver.bcel.BcelWeaver.prepareForWeave(BcelWeaver.java: 450) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.weave (AjCompilerAdapter.java:299) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.afterCompiling (AjCompilerAdapter.java:192) at org.aspectj.ajdt.internal.compiler.CompilerAdapter.ajc $afterReturning$org_aspectj_ajdt_internal_compiler_CompilerAdapter$2 $f9cc9ca0(CompilerAdapter.aj:70) at org.aspectj.org.eclipse.jdt.internal.compiler.Compiler.compile (Compiler.java:367) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.performCompilation (AjBuildManager.java:887) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.doBuild (AjBuildManager.java:244) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.batchBuild (AjBuildManager.java:163) at org.aspectj.ajde.internal.CompilerAdapter.compile (CompilerAdapter.java:122) at org.aspectj.ajde.internal.AspectJBuildManager$CompilerThread.run (AspectJBuildManager.java:191) UnsupportedOperationException thrown: unable to parameterize unresolved type: Pjava/util/List<+Ljava/lang/Object;>; To reproduce this exception compile the following code snippet. import java.util.ArrayList; import java.util.List; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; public class Main { public List<? extends Element> getElements() { return new ArrayList<Element>(); } class Element {}; @Aspect static abstract class Base<T> { @Around("call(List<? extends T> *.*(..))") public List<? extends T> elementList(ProceedingJoinPoint thisJoinPoint) { try { return (List<? extends T>)thisJoinPoint.proceed(); } catch (Throwable e) { throw new RuntimeException(e); } } } @Aspect static class Concrete extends Base<Element> {} public static void main(String[] args) { new Main().getElements(); } }
resolved fixed
7b40e7e
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2006-10-24T12:42:57Z"
"2006-10-19T01:06:40Z"
weaver/src/org/aspectj/weaver/TypeVariableReferenceType.java
/* ******************************************************************* * Copyright (c) 2005 Contributors. * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Eclipse Public License v1.0 * which accompanies this distribution and is available at * http://eclipse.org/legal/epl-v10.html * * Contributors: * Adrian Colyer Initial implementation * ******************************************************************/ package org.aspectj.weaver; import java.io.DataOutputStream; import java.io.IOException; /** * Represents a type variable in a type or generic method declaration */ public class TypeVariableReferenceType extends BoundedReferenceType implements TypeVariableReference { private TypeVariable typeVariable; private boolean resolvedIfBounds = false; // If 'fixedUp' then the type variable in here is a reference to the real one that may // exist either on a member or a type. Not fixedUp means that we unpacked a generic // signature and weren't able to fix it up during resolution (didn't quite know enough // at the right time). Wonder if we can fix it up late? boolean fixedUp = false; public TypeVariableReferenceType( TypeVariable aTypeVariable, World aWorld) { super(aTypeVariable.getFirstBound().getSignature(), aTypeVariable.getFirstBound().getErasureSignature(), aWorld); this.typeVariable = aTypeVariable; this.isExtends = false; this.isSuper = false; } public ReferenceTypeDelegate getDelegate() { if (delegate==null) setDelegate(new ReferenceTypeReferenceTypeDelegate((ReferenceType)typeVariable.getFirstBound())); return delegate; } public UnresolvedType getUpperBound() { if (typeVariable==null) return super.getUpperBound(); return typeVariable.getUpperBound(); } public UnresolvedType getLowerBound() { return typeVariable.getLowerBound(); } private void setAdditionalInterfaceBoundsFromTypeVar() { if (typeVariable.getAdditionalInterfaceBounds() == null) { return; } else { UnresolvedType [] ifBounds = typeVariable.getAdditionalInterfaceBounds(); additionalInterfaceBounds = new ReferenceType[ifBounds.length]; for (int i = 0; i < ifBounds.length; i++) { additionalInterfaceBounds[i] = (ReferenceType) ifBounds[i].resolve(getWorld()); } } } public ReferenceType[] getAdditionalBounds() { if (!resolvedIfBounds) { setAdditionalInterfaceBoundsFromTypeVar(); resolvedIfBounds = true; } return super.getAdditionalBounds(); } public TypeVariable getTypeVariable() { // if (!fixedUp) throw new BCException("ARGH"); // SAUSAGES - fix it up now? return typeVariable; } public boolean isTypeVariableReference() { return true; } public String toString() { return typeVariable.getName(); } public boolean isGenericWildcard() { return false; } //public ResolvedType resolve(World world) { // return super.resolve(world); //} public boolean isAnnotation() { World world = ((ReferenceType)getUpperBound()).getWorld(); ResolvedType annotationType = ResolvedType.ANNOTATION.resolve(world); if (getUpperBound() != null && ((ReferenceType)getUpperBound()).isAnnotation()) return true; ReferenceType[] ifBounds = getAdditionalBounds(); for (int i = 0; i < ifBounds.length; i++) { if (ifBounds[i].isAnnotation()) return true; if (ifBounds[i] == annotationType) return true; // annotation itself does not have the annotation flag set in Java! } return false; } /** * return the signature for a *REFERENCE* to a type variable, which is simply: * Tname; * there is no bounds info included, that is in the signature of the type variable itself */ public String getSignature() { StringBuffer sb = new StringBuffer(); sb.append("T"); sb.append(typeVariable.getName()); sb.append(";"); return sb.toString(); } public void write(DataOutputStream s) throws IOException { super.write(s); // TypeVariableDeclaringElement tvde = typeVariable.getDeclaringElement(); // if (tvde == null) { // s.writeInt(TypeVariable.UNKNOWN); // } else { // s.writeInt(typeVariable.getDeclaringElementKind()); // if (typeVariable.getDeclaringElementKind() == TypeVariable.TYPE) { // ((UnresolvedType)tvde).write(s); // } else if (typeVariable.getDeclaringElementKind() == TypeVariable.METHOD){ // // it's a method // ((ResolvedMember)tvde).write(s); // } // } } }
161,502
Bug 161502 UnsupportedOperationException thrown: unable to parameterize unresolved type: Pjava/util/List<+Ljava/lang/Object; >;
Generic parameters (like List<? extends T>) in pointcuts throw UnsupportedOperationException. java.lang.UnsupportedOperationException at org.aspectj.weaver.UnresolvedType.parameterize(UnresolvedType.java: 220) at org.aspectj.weaver.patterns.ExactTypePattern.parameterizeWith (ExactTypePattern.java:244) at org.aspectj.weaver.patterns.SignaturePattern.parameterizeWith (SignaturePattern.java:265) at org.aspectj.weaver.patterns.KindedPointcut.parameterizeWith (KindedPointcut.java:381) at org.aspectj.weaver.bcel.BcelAdvice.parameterizeWith (BcelAdvice.java:93) at org.aspectj.weaver.ResolvedType.getDeclaredAdvice (ResolvedType.java:710) at org.aspectj.weaver.ResolvedType.getDeclaredShadowMungers (ResolvedType.java:739) at org.aspectj.weaver.ResolvedType.collectShadowMungers (ResolvedType.java:575) at org.aspectj.weaver.ResolvedType.collectCrosscuttingMembers (ResolvedType.java:504) at org.aspectj.weaver.CrosscuttingMembersSet.addOrReplaceAspect (CrosscuttingMembersSet.java:68) at org.aspectj.weaver.CrosscuttingMembersSet.addOrReplaceAspect (CrosscuttingMembersSet.java:57) at org.aspectj.weaver.bcel.BcelWeaver.prepareForWeave(BcelWeaver.java: 450) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.weave (AjCompilerAdapter.java:299) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.afterCompiling (AjCompilerAdapter.java:192) at org.aspectj.ajdt.internal.compiler.CompilerAdapter.ajc $afterReturning$org_aspectj_ajdt_internal_compiler_CompilerAdapter$2 $f9cc9ca0(CompilerAdapter.aj:70) at org.aspectj.org.eclipse.jdt.internal.compiler.Compiler.compile (Compiler.java:367) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.performCompilation (AjBuildManager.java:887) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.doBuild (AjBuildManager.java:244) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.batchBuild (AjBuildManager.java:163) at org.aspectj.ajde.internal.CompilerAdapter.compile (CompilerAdapter.java:122) at org.aspectj.ajde.internal.AspectJBuildManager$CompilerThread.run (AspectJBuildManager.java:191) UnsupportedOperationException thrown: unable to parameterize unresolved type: Pjava/util/List<+Ljava/lang/Object;>; To reproduce this exception compile the following code snippet. import java.util.ArrayList; import java.util.List; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; public class Main { public List<? extends Element> getElements() { return new ArrayList<Element>(); } class Element {}; @Aspect static abstract class Base<T> { @Around("call(List<? extends T> *.*(..))") public List<? extends T> elementList(ProceedingJoinPoint thisJoinPoint) { try { return (List<? extends T>)thisJoinPoint.proceed(); } catch (Throwable e) { throw new RuntimeException(e); } } } @Aspect static class Concrete extends Base<Element> {} public static void main(String[] args) { new Main().getElements(); } }
resolved fixed
7b40e7e
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2006-10-24T12:42:57Z"
"2006-10-19T01:06:40Z"
weaver/src/org/aspectj/weaver/bcel/BcelAdvice.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Eclipse Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * PARC initial implementation * Alexandre Vasseur support for @AJ aspects * ******************************************************************/ package org.aspectj.weaver.bcel; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Map; import org.aspectj.apache.bcel.generic.InstructionConstants; import org.aspectj.apache.bcel.generic.InstructionFactory; import org.aspectj.apache.bcel.generic.InstructionHandle; import org.aspectj.apache.bcel.generic.InstructionList; import org.aspectj.apache.bcel.generic.LineNumberTag; import org.aspectj.bridge.ISourceLocation; import org.aspectj.bridge.Message; import org.aspectj.weaver.Advice; import org.aspectj.weaver.AdviceKind; import org.aspectj.weaver.AjAttribute; import org.aspectj.weaver.BCException; import org.aspectj.weaver.IEclipseSourceContext; import org.aspectj.weaver.ISourceContext; import org.aspectj.weaver.Member; import org.aspectj.weaver.ResolvedMember; import org.aspectj.weaver.ResolvedType; import org.aspectj.weaver.Shadow; import org.aspectj.weaver.ShadowMunger; import org.aspectj.weaver.UnresolvedType; import org.aspectj.weaver.WeaverMessages; import org.aspectj.weaver.World; import org.aspectj.weaver.ast.Literal; import org.aspectj.weaver.ast.Test; import org.aspectj.weaver.patterns.ExactTypePattern; import org.aspectj.weaver.patterns.ExposedState; import org.aspectj.weaver.patterns.PerClause; import org.aspectj.weaver.patterns.Pointcut; /** * Advice implemented for bcel. * * @author Erik Hilsdale * @author Jim Hugunin */ public class BcelAdvice extends Advice { private Test pointcutTest; private ExposedState exposedState; private boolean hasMatchedAtLeastOnce = false; public BcelAdvice( AjAttribute.AdviceAttribute attribute, Pointcut pointcut, Member signature, ResolvedType concreteAspect) { super(attribute, pointcut, signature); this.concreteAspect = concreteAspect; } // !!! must only be used for testing public BcelAdvice(AdviceKind kind, Pointcut pointcut, Member signature, int extraArgumentFlags, int start, int end, ISourceContext sourceContext, ResolvedType concreteAspect) { this(new AjAttribute.AdviceAttribute(kind, pointcut, extraArgumentFlags, start, end, sourceContext), pointcut, signature, concreteAspect); thrownExceptions = Collections.EMPTY_LIST; //!!! interaction with unit tests } // ---- implementations of ShadowMunger's methods public ShadowMunger concretize(ResolvedType fromType, World world, PerClause clause) { suppressLintWarnings(world); ShadowMunger ret = super.concretize(fromType, world, clause); clearLintSuppressions(world,this.suppressedLintKinds); IfFinder ifinder = new IfFinder(); ret.getPointcut().accept(ifinder,null); boolean hasGuardTest = ifinder.hasIf && getKind() != AdviceKind.Around; boolean isAround = getKind() == AdviceKind.Around; if ((getExtraParameterFlags() & ThisJoinPoint) != 0) { if (!isAround && !hasGuardTest && world.getLint().noGuardForLazyTjp.isEnabled()) { // can't build tjp lazily, no suitable test... // ... only want to record it once against the advice(bug 133117) world.getLint().noGuardForLazyTjp.signal("",getSourceLocation()); } } return ret; } public ShadowMunger parameterizeWith(ResolvedType declaringType,Map typeVariableMap) { Pointcut pc = getPointcut().parameterizeWith(typeVariableMap); BcelAdvice ret = null; Member adviceSignature = signature; // allows for around advice where the return value is a type variable (see pr115250) if (signature instanceof ResolvedMember && signature.getDeclaringType().isGenericType()) { adviceSignature = ((ResolvedMember)signature).parameterizedWith(declaringType.getTypeParameters(),declaringType,declaringType.isParameterizedType()); } ret = new BcelAdvice(this.attribute,pc,adviceSignature,this.concreteAspect); return ret; } public boolean match(Shadow shadow, World world) { suppressLintWarnings(world); boolean ret = super.match(shadow, world); clearLintSuppressions(world,this.suppressedLintKinds); return ret; } public void specializeOn(Shadow shadow) { if (getKind() == AdviceKind.Around) { ((BcelShadow)shadow).initializeForAroundClosure(); } //XXX this case is just here for supporting lazy test code if (getKind() == null) { exposedState = new ExposedState(0); return; } if (getKind().isPerEntry()) { exposedState = new ExposedState(0); } else if (getKind().isCflow()) { exposedState = new ExposedState(nFreeVars); } else if (getSignature() != null) { exposedState = new ExposedState(getSignature()); } else { exposedState = new ExposedState(0); return; //XXX this case is just here for supporting lazy test code } World world = shadow.getIWorld(); suppressLintWarnings(world); pointcutTest = getPointcut().findResidue(shadow, exposedState); clearLintSuppressions(world,this.suppressedLintKinds); // these initializations won't be performed by findResidue, but need to be // so that the joinpoint is primed for weaving if (getKind() == AdviceKind.PerThisEntry) { shadow.getThisVar(); } else if (getKind() == AdviceKind.PerTargetEntry) { shadow.getTargetVar(); } // make sure thisJoinPoint parameters are initialized if ((getExtraParameterFlags() & ThisJoinPointStaticPart) != 0) { ((BcelShadow)shadow).getThisJoinPointStaticPartVar(); ((BcelShadow)shadow).getEnclosingClass().warnOnAddedStaticInitializer(shadow,getSourceLocation()); } if ((getExtraParameterFlags() & ThisJoinPoint) != 0) { boolean hasGuardTest = pointcutTest != Literal.TRUE && getKind() != AdviceKind.Around; boolean isAround = getKind() == AdviceKind.Around; ((BcelShadow)shadow).requireThisJoinPoint(hasGuardTest,isAround); ((BcelShadow)shadow).getEnclosingClass().warnOnAddedStaticInitializer(shadow,getSourceLocation()); if (!hasGuardTest && world.getLint().multipleAdviceStoppingLazyTjp.isEnabled()) { // collect up the problematic advice ((BcelShadow)shadow).addAdvicePreventingLazyTjp(this); } } if ((getExtraParameterFlags() & ThisEnclosingJoinPointStaticPart) != 0) { ((BcelShadow)shadow).getThisEnclosingJoinPointStaticPartVar(); ((BcelShadow)shadow).getEnclosingClass().warnOnAddedStaticInitializer(shadow,getSourceLocation()); } } private boolean canInline(Shadow s) { if (attribute.isProceedInInners()) return false; //XXX this guard seems to only be needed for bad test cases if (concreteAspect == null || concreteAspect.isMissing()) return false; if (concreteAspect.getWorld().isXnoInline()) return false; //System.err.println("isWoven? " + ((BcelObjectType)concreteAspect).getLazyClassGen().getWeaverState()); return BcelWorld.getBcelObjectType(concreteAspect).getLazyClassGen().isWoven(); } public void implementOn(Shadow s) { hasMatchedAtLeastOnce=true; BcelShadow shadow = (BcelShadow) s; // remove any unnecessary exceptions if the compiler option is set to // error or warning and if this piece of advice throws exceptions // (bug 129282). This may be expanded to include other compiler warnings // at the moment it only deals with 'declared exception is not thrown' if (!shadow.getWorld().isIgnoringUnusedDeclaredThrownException() && !getThrownExceptions().isEmpty()) { Member member = shadow.getSignature(); if (member instanceof BcelMethod) { removeUnnecessaryProblems((BcelMethod)member, ((BcelMethod)member).getDeclarationLineNumber()); } else { // we're in a call shadow therefore need the line number of the // declared method (which may be in a different type). However, // we want to remove the problems from the CompilationResult // held within the current type's EclipseSourceContext so need // the enclosing shadow too ResolvedMember resolvedMember = shadow.getSignature().resolve(shadow.getWorld()); if (resolvedMember instanceof BcelMethod && shadow.getEnclosingShadow() instanceof BcelShadow) { Member enclosingMember = shadow.getEnclosingShadow().getSignature(); if (enclosingMember instanceof BcelMethod) { removeUnnecessaryProblems((BcelMethod)enclosingMember, ((BcelMethod)resolvedMember).getDeclarationLineNumber()); } } } } if (shadow.getIWorld().isJoinpointSynchronizationEnabled() && shadow.getKind()==Shadow.MethodExecution && (s.getSignature().getModifiers() & Modifier.SYNCHRONIZED)!=0) { Message m = new Message("advice matching the synchronized method shadow '"+shadow.toString()+ "' will be executed outside the lock rather than inside (compiler limitation)",shadow.getSourceLocation(),false,new ISourceLocation[]{getSourceLocation()}); shadow.getIWorld().getMessageHandler().handleMessage(m); } //FIXME AV - see #75442, this logic is not enough so for now comment it out until we fix the bug // // callback for perObject AJC MightHaveAspect postMunge (#75442) // if (getConcreteAspect() != null // && getConcreteAspect().getPerClause() != null // && PerClause.PEROBJECT.equals(getConcreteAspect().getPerClause().getKind())) { // final PerObject clause; // if (getConcreteAspect().getPerClause() instanceof PerFromSuper) { // clause = (PerObject)((PerFromSuper) getConcreteAspect().getPerClause()).lookupConcretePerClause(getConcreteAspect()); // } else { // clause = (PerObject) getConcreteAspect().getPerClause(); // } // if (clause.isThis()) { // PerObjectInterfaceTypeMunger.registerAsAdvisedBy(s.getThisVar().getType(), getConcreteAspect()); // } else { // PerObjectInterfaceTypeMunger.registerAsAdvisedBy(s.getTargetVar().getType(), getConcreteAspect()); // } // } if (getKind() == AdviceKind.Before) { shadow.weaveBefore(this); } else if (getKind() == AdviceKind.AfterReturning) { shadow.weaveAfterReturning(this); } else if (getKind() == AdviceKind.AfterThrowing) { UnresolvedType catchType = hasExtraParameter() ? getExtraParameterType() : UnresolvedType.THROWABLE; shadow.weaveAfterThrowing(this, catchType); } else if (getKind() == AdviceKind.After) { shadow.weaveAfter(this); } else if (getKind() == AdviceKind.Around) { // Note: under regular LTW the aspect is usually loaded after the first use of any class affecteted by it // This means that as long as the aspect has not been thru the LTW, it's woven state is unknown // and thus canInline(s) will return false. // To force inlining (test), ones can do Class aspect = FQNAspect.class in the clinit of the target class // FIXME AV : for AJC compiled @AJ aspect (or any code style aspect), the woven state can never be known // if the aspect belongs to a parent classloader. In that case the aspect will never be inlined. // It might be dangerous to change that especially for @AJ aspect non compiled with AJC since if those // are not weaved (f.e. use of some limiteed LTW etc) then they cannot be prepared for inlining. // One solution would be to flag @AJ aspect with an annotation as "prepared" and query that one. if (!canInline(s)) { shadow.weaveAroundClosure(this, hasDynamicTests()); } else { shadow.weaveAroundInline(this, hasDynamicTests()); } } else if (getKind() == AdviceKind.InterInitializer) { shadow.weaveAfterReturning(this); } else if (getKind().isCflow()) { shadow.weaveCflowEntry(this, getSignature()); } else if (getKind() == AdviceKind.PerThisEntry) { shadow.weavePerObjectEntry(this, (BcelVar)shadow.getThisVar()); } else if (getKind() == AdviceKind.PerTargetEntry) { shadow.weavePerObjectEntry(this, (BcelVar)shadow.getTargetVar()); } else if (getKind() == AdviceKind.Softener) { shadow.weaveSoftener(this, ((ExactTypePattern)exceptionType).getType()); } else if (getKind() == AdviceKind.PerTypeWithinEntry) { // PTWIMPL Entry to ptw is the static initialization of a type that matched the ptw type pattern shadow.weavePerTypeWithinAspectInitialization(this,shadow.getEnclosingType()); } else { throw new BCException("unimplemented kind: " + getKind()); } } private void removeUnnecessaryProblems(BcelMethod method, int problemLineNumber) { ISourceContext sourceContext = method.getSourceContext(); if (sourceContext instanceof IEclipseSourceContext) { if (sourceContext != null && sourceContext instanceof IEclipseSourceContext) { ((IEclipseSourceContext)sourceContext).removeUnnecessaryProblems(method, problemLineNumber); } } } // ---- implementations private Collection collectCheckedExceptions(UnresolvedType[] excs) { if (excs == null || excs.length == 0) return Collections.EMPTY_LIST; Collection ret = new ArrayList(); World world = concreteAspect.getWorld(); ResolvedType runtimeException = world.getCoreType(UnresolvedType.RUNTIME_EXCEPTION); ResolvedType error = world.getCoreType(UnresolvedType.ERROR); for (int i=0, len=excs.length; i < len; i++) { ResolvedType t = world.resolve(excs[i],true); if (t.isMissing()) { world.getLint().cantFindType.signal( WeaverMessages.format(WeaverMessages.CANT_FIND_TYPE_EXCEPTION_TYPE,excs[i].getName()), getSourceLocation() ); // IMessage msg = new Message( // WeaverMessages.format(WeaverMessages.CANT_FIND_TYPE_EXCEPTION_TYPE,excs[i].getName()), // "",IMessage.ERROR,getSourceLocation(),null,null); // world.getMessageHandler().handleMessage(msg); } if (!(runtimeException.isAssignableFrom(t) || error.isAssignableFrom(t))) { ret.add(t); } } return ret; } private Collection thrownExceptions = null; public Collection getThrownExceptions() { if (thrownExceptions == null) { //??? can we really lump in Around here, how does this interact with Throwable if (concreteAspect != null && concreteAspect.getWorld() != null && // null tests for test harness (getKind().isAfter() || getKind() == AdviceKind.Before || getKind() == AdviceKind.Around)) { World world = concreteAspect.getWorld(); ResolvedMember m = world.resolve(signature); if (m == null) { thrownExceptions = Collections.EMPTY_LIST; } else { thrownExceptions = collectCheckedExceptions(m.getExceptions()); } } else { thrownExceptions = Collections.EMPTY_LIST; } } return thrownExceptions; } /** * The munger must not check for the advice exceptions to be declared by the shadow in the case * of @AJ aspects so that around can throws Throwable * * @return */ public boolean mustCheckExceptions() { if (getConcreteAspect() == null) { return true; } return !getConcreteAspect().isAnnotationStyleAspect(); } // only call me after prepare has been called public boolean hasDynamicTests() { // if (hasExtraParameter() && getKind() == AdviceKind.AfterReturning) { // UnresolvedType extraParameterType = getExtraParameterType(); // if (! extraParameterType.equals(UnresolvedType.OBJECT) // && ! extraParameterType.isPrimitive()) // return true; // } return pointcutTest != null && !(pointcutTest == Literal.TRUE);// || pointcutTest == Literal.NO_TEST); } /** * get the instruction list for the really simple version of this advice. * Is broken apart * for other advice, but if you want it in one block, this is the method to call. * * @param s The shadow around which these instructions will eventually live. * @param extraArgVar The var that will hold the return value or thrown exception * for afterX advice * @param ifNoAdvice The instructionHandle to jump to if the dynamic * tests for this munger fails. */ InstructionList getAdviceInstructions( BcelShadow s, BcelVar extraArgVar, InstructionHandle ifNoAdvice) { BcelShadow shadow = (BcelShadow) s; InstructionFactory fact = shadow.getFactory(); BcelWorld world = shadow.getWorld(); InstructionList il = new InstructionList(); // we test to see if we have the right kind of thing... // after throwing does this just by the exception mechanism. if (hasExtraParameter() && getKind() == AdviceKind.AfterReturning) { UnresolvedType extraParameterType = getExtraParameterType(); if (! extraParameterType.equals(UnresolvedType.OBJECT) && ! extraParameterType.isPrimitiveType()) { il.append( BcelRenderer.renderTest( fact, world, Test.makeInstanceof( extraArgVar, getExtraParameterType().resolve(world)), null, ifNoAdvice, null)); } } il.append(getAdviceArgSetup(shadow, extraArgVar, null)); il.append(getNonTestAdviceInstructions(shadow)); InstructionHandle ifYesAdvice = il.getStart(); il.insert(getTestInstructions(shadow, ifYesAdvice, ifNoAdvice, ifYesAdvice)); // If inserting instructions at the start of a method, we need a nice line number for this entry // in the stack trace if (shadow.getKind()==Shadow.MethodExecution && getKind()==AdviceKind.Before) { int lineNumber=0; // Uncomment this code if you think we should use the method decl line number when it exists... // // If the advised join point is in a class built by AspectJ, we can use the declaration line number // boolean b = shadow.getEnclosingMethod().getMemberView().hasDeclarationLineNumberInfo(); // if (b) { // lineNumber = shadow.getEnclosingMethod().getMemberView().getDeclarationLineNumber(); // } else { // If it wasn't, the best we can do is the line number of the first instruction in the method lineNumber = shadow.getEnclosingMethod().getMemberView().getLineNumberOfFirstInstruction(); // } if (lineNumber>0) il.getStart().addTargeter(new LineNumberTag(lineNumber)); } return il; } public InstructionList getAdviceArgSetup( BcelShadow shadow, BcelVar extraVar, InstructionList closureInstantiation) { InstructionFactory fact = shadow.getFactory(); BcelWorld world = shadow.getWorld(); InstructionList il = new InstructionList(); // if (targetAspectField != null) { // il.append(fact.createFieldAccess( // targetAspectField.getDeclaringType().getName(), // targetAspectField.getName(), // BcelWorld.makeBcelType(targetAspectField.getType()), // Constants.GETSTATIC)); // } // //System.err.println("BcelAdvice: " + exposedState); if (exposedState.getAspectInstance() != null) { il.append(BcelRenderer.renderExpr(fact, world, exposedState.getAspectInstance())); } // pr121385 boolean x = this.getDeclaringAspect().resolve(world).isAnnotationStyleAspect(); final boolean isAnnotationStyleAspect = getConcreteAspect()!=null && getConcreteAspect().isAnnotationStyleAspect() && x; boolean previousIsClosure = false; for (int i = 0, len = exposedState.size(); i < len; i++) { if (exposedState.isErroneousVar(i)) continue; // Erroneous vars have already had error msgs reported! BcelVar v = (BcelVar) exposedState.get(i); if (v == null) { // if not @AJ aspect, go on with the regular binding handling if (!isAnnotationStyleAspect) { ; } else { // ATAJ: for @AJ aspects, handle implicit binding of xxJoinPoint //if (getKind() == AdviceKind.Around) { // previousIsClosure = true; // il.append(closureInstantiation); if ("Lorg/aspectj/lang/ProceedingJoinPoint;".equals(getSignature().getParameterTypes()[i].getSignature())) { //make sure we are in an around, since we deal with the closure, not the arg here if (getKind() != AdviceKind.Around) { previousIsClosure = false; getConcreteAspect().getWorld().getMessageHandler().handleMessage( new Message( "use of ProceedingJoinPoint is allowed only on around advice (" + "arg " + i + " in " + toString() + ")", this.getSourceLocation(), true ) ); // try to avoid verify error and pass in null il.append(InstructionConstants.ACONST_NULL); } else { if (previousIsClosure) { il.append(InstructionConstants.DUP); } else { previousIsClosure = true; il.append(closureInstantiation.copy()); } } } else if ("Lorg/aspectj/lang/JoinPoint$StaticPart;".equals(getSignature().getParameterTypes()[i].getSignature())) { previousIsClosure = false; if ((getExtraParameterFlags() & ThisJoinPointStaticPart) != 0) { shadow.getThisJoinPointStaticPartBcelVar().appendLoad(il, fact); } } else if ("Lorg/aspectj/lang/JoinPoint;".equals(getSignature().getParameterTypes()[i].getSignature())) { previousIsClosure = false; if ((getExtraParameterFlags() & ThisJoinPoint) != 0) { il.append(shadow.loadThisJoinPoint()); } } else if ("Lorg/aspectj/lang/JoinPoint$EnclosingStaticPart;".equals(getSignature().getParameterTypes()[i].getSignature())) { previousIsClosure = false; if ((getExtraParameterFlags() & ThisEnclosingJoinPointStaticPart) != 0) { shadow.getThisEnclosingJoinPointStaticPartBcelVar().appendLoad(il, fact); } } else if (hasExtraParameter()) { previousIsClosure = false; extraVar.appendLoadAndConvert( il, fact, getExtraParameterType().resolve(world)); } else { previousIsClosure = false; getConcreteAspect().getWorld().getMessageHandler().handleMessage( new Message( "use of ProceedingJoinPoint is allowed only on around advice (" + "arg " + i + " in " + toString() + ")", this.getSourceLocation(), true ) ); // try to avoid verify error and pass in null il.append(InstructionConstants.ACONST_NULL); } } } else { UnresolvedType desiredTy = getBindingParameterTypes()[i]; v.appendLoadAndConvert(il, fact, desiredTy.resolve(world)); } } // ATAJ: for code style aspect, handles the extraFlag as usual ie not // in the middle of the formal bindings but at the end, in a rock solid ordering if (!isAnnotationStyleAspect) { if (getKind() == AdviceKind.Around) { il.append(closureInstantiation); } else if (hasExtraParameter()) { extraVar.appendLoadAndConvert( il, fact, getExtraParameterType().resolve(world)); } // handle thisJoinPoint parameters // these need to be in that same order as parameters in // org.aspectj.ajdt.internal.compiler.ast.AdviceDeclaration if ((getExtraParameterFlags() & ThisJoinPointStaticPart) != 0) { shadow.getThisJoinPointStaticPartBcelVar().appendLoad(il, fact); } if ((getExtraParameterFlags() & ThisJoinPoint) != 0) { il.append(shadow.loadThisJoinPoint()); } if ((getExtraParameterFlags() & ThisEnclosingJoinPointStaticPart) != 0) { shadow.getThisEnclosingJoinPointStaticPartBcelVar().appendLoad(il, fact); } } return il; } public InstructionList getNonTestAdviceInstructions(BcelShadow shadow) { return new InstructionList( Utility.createInvoke(shadow.getFactory(), shadow.getWorld(), getOriginalSignature())); } public Member getOriginalSignature() { Member sig = getSignature(); if (sig instanceof ResolvedMember) { ResolvedMember rsig = (ResolvedMember)sig; if (rsig.hasBackingGenericMember()) return rsig.getBackingGenericMember(); } return sig; } public InstructionList getTestInstructions( BcelShadow shadow, InstructionHandle sk, InstructionHandle fk, InstructionHandle next) { //System.err.println("test: " + pointcutTest); return BcelRenderer.renderTest( shadow.getFactory(), shadow.getWorld(), pointcutTest, sk, fk, next); } public int compareTo(Object other) { if (!(other instanceof BcelAdvice)) return 0; BcelAdvice o = (BcelAdvice)other; //System.err.println("compareTo: " + this + ", " + o); if (kind.getPrecedence() != o.kind.getPrecedence()) { if (kind.getPrecedence() > o.kind.getPrecedence()) return +1; else return -1; } if (kind.isCflow()) { // System.err.println("sort: " + this + " innerCflowEntries " + innerCflowEntries); // System.err.println(" " + o + " innerCflowEntries " + o.innerCflowEntries); boolean isBelow = (kind == AdviceKind.CflowBelowEntry); if (this.innerCflowEntries.contains(o)) return isBelow ? +1 : -1; else if (o.innerCflowEntries.contains(this)) return isBelow ? -1 : +1; else return 0; } if (kind.isPerEntry() || kind == AdviceKind.Softener) { return 0; } //System.out.println("compare: " + this + " with " + other); World world = concreteAspect.getWorld(); int ret = concreteAspect.getWorld().compareByPrecedence( concreteAspect, o.concreteAspect); if (ret != 0) return ret; ResolvedType declaringAspect = getDeclaringAspect().resolve(world); ResolvedType o_declaringAspect = o.getDeclaringAspect().resolve(world); if (declaringAspect == o_declaringAspect) { if (kind.isAfter() || o.kind.isAfter()) { return this.getStart() < o.getStart() ? -1: +1; } else { return this.getStart()< o.getStart() ? +1: -1; } } else if (declaringAspect.isAssignableFrom(o_declaringAspect)) { return -1; } else if (o_declaringAspect.isAssignableFrom(declaringAspect)) { return +1; } else { return 0; } } public BcelVar[] getExposedStateAsBcelVars(boolean isAround) { // ATAJ aspect if (isAround) { // the closure instantiation has the same mapping as the extracted method from wich it is called if (getConcreteAspect()!= null && getConcreteAspect().isAnnotationStyleAspect()) { return BcelVar.NONE; } } //System.out.println("vars: " + Arrays.asList(exposedState.vars)); if (exposedState == null) return BcelVar.NONE; int len = exposedState.vars.length; BcelVar[] ret = new BcelVar[len]; for (int i=0; i < len; i++) { ret[i] = (BcelVar)exposedState.vars[i]; } return ret; //(BcelVar[]) exposedState.vars; } public boolean hasMatchedSomething() { return hasMatchedAtLeastOnce; } public void setHasMatchedSomething(boolean hasMatchedSomething) { hasMatchedAtLeastOnce = hasMatchedSomething; } protected void suppressLintWarnings(World inWorld) { if (suppressedLintKinds == null) { if (signature instanceof BcelMethod) { this.suppressedLintKinds = Utility.getSuppressedWarnings(signature.getAnnotations(), inWorld.getLint()); } else { this.suppressedLintKinds = Collections.EMPTY_LIST; } } inWorld.getLint().suppressKinds(suppressedLintKinds); } protected void clearLintSuppressions(World inWorld,Collection toClear) { inWorld.getLint().clearSuppressions(toClear); } }
161,502
Bug 161502 UnsupportedOperationException thrown: unable to parameterize unresolved type: Pjava/util/List<+Ljava/lang/Object; >;
Generic parameters (like List<? extends T>) in pointcuts throw UnsupportedOperationException. java.lang.UnsupportedOperationException at org.aspectj.weaver.UnresolvedType.parameterize(UnresolvedType.java: 220) at org.aspectj.weaver.patterns.ExactTypePattern.parameterizeWith (ExactTypePattern.java:244) at org.aspectj.weaver.patterns.SignaturePattern.parameterizeWith (SignaturePattern.java:265) at org.aspectj.weaver.patterns.KindedPointcut.parameterizeWith (KindedPointcut.java:381) at org.aspectj.weaver.bcel.BcelAdvice.parameterizeWith (BcelAdvice.java:93) at org.aspectj.weaver.ResolvedType.getDeclaredAdvice (ResolvedType.java:710) at org.aspectj.weaver.ResolvedType.getDeclaredShadowMungers (ResolvedType.java:739) at org.aspectj.weaver.ResolvedType.collectShadowMungers (ResolvedType.java:575) at org.aspectj.weaver.ResolvedType.collectCrosscuttingMembers (ResolvedType.java:504) at org.aspectj.weaver.CrosscuttingMembersSet.addOrReplaceAspect (CrosscuttingMembersSet.java:68) at org.aspectj.weaver.CrosscuttingMembersSet.addOrReplaceAspect (CrosscuttingMembersSet.java:57) at org.aspectj.weaver.bcel.BcelWeaver.prepareForWeave(BcelWeaver.java: 450) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.weave (AjCompilerAdapter.java:299) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.afterCompiling (AjCompilerAdapter.java:192) at org.aspectj.ajdt.internal.compiler.CompilerAdapter.ajc $afterReturning$org_aspectj_ajdt_internal_compiler_CompilerAdapter$2 $f9cc9ca0(CompilerAdapter.aj:70) at org.aspectj.org.eclipse.jdt.internal.compiler.Compiler.compile (Compiler.java:367) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.performCompilation (AjBuildManager.java:887) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.doBuild (AjBuildManager.java:244) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.batchBuild (AjBuildManager.java:163) at org.aspectj.ajde.internal.CompilerAdapter.compile (CompilerAdapter.java:122) at org.aspectj.ajde.internal.AspectJBuildManager$CompilerThread.run (AspectJBuildManager.java:191) UnsupportedOperationException thrown: unable to parameterize unresolved type: Pjava/util/List<+Ljava/lang/Object;>; To reproduce this exception compile the following code snippet. import java.util.ArrayList; import java.util.List; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; public class Main { public List<? extends Element> getElements() { return new ArrayList<Element>(); } class Element {}; @Aspect static abstract class Base<T> { @Around("call(List<? extends T> *.*(..))") public List<? extends T> elementList(ProceedingJoinPoint thisJoinPoint) { try { return (List<? extends T>)thisJoinPoint.proceed(); } catch (Throwable e) { throw new RuntimeException(e); } } } @Aspect static class Concrete extends Base<Element> {} public static void main(String[] args) { new Main().getElements(); } }
resolved fixed
7b40e7e
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2006-10-24T12:42:57Z"
"2006-10-19T01:06:40Z"
weaver/src/org/aspectj/weaver/bcel/BcelTypeMunger.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Eclipse Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * PARC initial implementation * Alexandre Vasseur @AspectJ ITDs * ******************************************************************/ package org.aspectj.weaver.bcel; import java.lang.reflect.Modifier; import java.util.Iterator; import java.util.List; import java.util.Set; import org.aspectj.apache.bcel.Constants; import org.aspectj.apache.bcel.classfile.annotation.Annotation; import org.aspectj.apache.bcel.generic.BranchInstruction; import org.aspectj.apache.bcel.generic.ConstantPoolGen; import org.aspectj.apache.bcel.generic.FieldGen; import org.aspectj.apache.bcel.generic.INVOKESPECIAL; import org.aspectj.apache.bcel.generic.InstructionConstants; import org.aspectj.apache.bcel.generic.InstructionFactory; import org.aspectj.apache.bcel.generic.InstructionHandle; import org.aspectj.apache.bcel.generic.InstructionList; import org.aspectj.apache.bcel.generic.Type; import org.aspectj.apache.bcel.generic.annotation.AnnotationGen; import org.aspectj.asm.AsmManager; import org.aspectj.bridge.IMessage; import org.aspectj.bridge.ISourceLocation; import org.aspectj.bridge.Message; import org.aspectj.bridge.MessageUtil; import org.aspectj.bridge.WeaveMessage; import org.aspectj.bridge.context.CompilationAndWeavingContext; import org.aspectj.bridge.context.ContextToken; import org.aspectj.weaver.AjcMemberMaker; import org.aspectj.weaver.AnnotationOnTypeMunger; import org.aspectj.weaver.AnnotationX; import org.aspectj.weaver.AsmRelationshipProvider; import org.aspectj.weaver.BCException; import org.aspectj.weaver.ConcreteTypeMunger; import org.aspectj.weaver.Member; import org.aspectj.weaver.MethodDelegateTypeMunger; import org.aspectj.weaver.NameMangler; import org.aspectj.weaver.NewConstructorTypeMunger; import org.aspectj.weaver.NewFieldTypeMunger; import org.aspectj.weaver.NewMethodTypeMunger; import org.aspectj.weaver.NewParentTypeMunger; import org.aspectj.weaver.PerObjectInterfaceTypeMunger; import org.aspectj.weaver.PrivilegedAccessMunger; import org.aspectj.weaver.ResolvedMember; import org.aspectj.weaver.ResolvedType; import org.aspectj.weaver.ResolvedTypeMunger; import org.aspectj.weaver.Shadow; import org.aspectj.weaver.TypeVariableReference; import org.aspectj.weaver.UnresolvedType; import org.aspectj.weaver.WeaverMessages; import org.aspectj.weaver.WeaverStateInfo; import org.aspectj.weaver.World; import org.aspectj.weaver.patterns.DeclareAnnotation; import org.aspectj.weaver.patterns.Pointcut; //XXX addLazyMethodGen is probably bad everywhere public class BcelTypeMunger extends ConcreteTypeMunger { public BcelTypeMunger(ResolvedTypeMunger munger, ResolvedType aspectType) { super(munger, aspectType); } public String toString() { return "(BcelTypeMunger " + getMunger() + ")"; } public boolean munge(BcelClassWeaver weaver) { ContextToken tok = CompilationAndWeavingContext.enteringPhase(CompilationAndWeavingContext.MUNGING_WITH, this); boolean changed = false; boolean worthReporting = true; if (munger.getKind() == ResolvedTypeMunger.Field) { changed = mungeNewField(weaver, (NewFieldTypeMunger)munger); } else if (munger.getKind() == ResolvedTypeMunger.Method) { changed = mungeNewMethod(weaver, (NewMethodTypeMunger)munger); } else if (munger.getKind() == ResolvedTypeMunger.MethodDelegate) { changed = mungeMethodDelegate(weaver, (MethodDelegateTypeMunger)munger); } else if (munger.getKind() == ResolvedTypeMunger.FieldHost) { changed = mungeFieldHost(weaver, (MethodDelegateTypeMunger.FieldHostTypeMunger)munger); } else if (munger.getKind() == ResolvedTypeMunger.PerObjectInterface) { changed = mungePerObjectInterface(weaver, (PerObjectInterfaceTypeMunger)munger); worthReporting = false; } else if (munger.getKind() == ResolvedTypeMunger.PerTypeWithinInterface) { // PTWIMPL Transform the target type (add the aspect instance field) changed = mungePerTypeWithinTransformer(weaver); worthReporting = false; } else if (munger.getKind() == ResolvedTypeMunger.PrivilegedAccess) { changed = mungePrivilegedAccess(weaver, (PrivilegedAccessMunger)munger); worthReporting = false; } else if (munger.getKind() == ResolvedTypeMunger.Constructor) { changed = mungeNewConstructor(weaver, (NewConstructorTypeMunger)munger); } else if (munger.getKind() == ResolvedTypeMunger.Parent) { changed = mungeNewParent(weaver, (NewParentTypeMunger)munger); } else if (munger.getKind() == ResolvedTypeMunger.AnnotationOnType) { changed = mungeNewAnnotationOnType(weaver,(AnnotationOnTypeMunger)munger); worthReporting=false; } else { throw new RuntimeException("unimplemented"); } if (changed && munger.changesPublicSignature()) { WeaverStateInfo info = weaver.getLazyClassGen().getOrCreateWeaverStateInfo(BcelClassWeaver.getReweavableMode()); info.addConcreteMunger(this); } if (changed && worthReporting) { if (munger.getKind().equals(ResolvedTypeMunger.Parent)) { AsmRelationshipProvider.getDefault().addRelationship(weaver.getLazyClassGen().getType(), munger,getAspectType()); } else { AsmRelationshipProvider.getDefault().addRelationship(weaver.getLazyClassGen().getType(), munger,getAspectType()); } } // TAG: WeavingMessage if (changed && worthReporting && munger!=null && !weaver.getWorld().getMessageHandler().isIgnoring(IMessage.WEAVEINFO)) { String tName = weaver.getLazyClassGen().getType().getSourceLocation().getSourceFile().getName(); if (tName.indexOf("no debug info available")!=-1) tName = "no debug info available"; else tName = getShortname(weaver.getLazyClassGen().getType().getSourceLocation().getSourceFile().getPath()); String fName = getShortname(getAspectType().getSourceLocation().getSourceFile().getPath()); if (munger.getKind().equals(ResolvedTypeMunger.Parent)) { // This message could come out of AjLookupEnvironment.addParent if doing parents // munging at compile time only... NewParentTypeMunger parentTM = (NewParentTypeMunger)munger; if (parentTM.getNewParent().isInterface()) { weaver.getWorld().getMessageHandler().handleMessage(WeaveMessage.constructWeavingMessage(WeaveMessage.WEAVEMESSAGE_DECLAREPARENTSIMPLEMENTS, new String[]{weaver.getLazyClassGen().getType().getName(), tName,parentTM.getNewParent().getName(),fName}, weaver.getLazyClassGen().getClassName(), getAspectType().getName())); } else { weaver.getWorld().getMessageHandler().handleMessage( WeaveMessage.constructWeavingMessage(WeaveMessage.WEAVEMESSAGE_DECLAREPARENTSEXTENDS, new String[]{weaver.getLazyClassGen().getType().getName(), tName,parentTM.getNewParent().getName(),fName })); // TAG: WeavingMessage DECLARE PARENTS: EXTENDS // reportDeclareParentsMessage(WeaveMessage.WEAVEMESSAGE_DECLAREPARENTSEXTENDS,sourceType,parent); } } else if (munger.getKind().equals(ResolvedTypeMunger.FieldHost)) { ;//hidden } else { ResolvedMember declaredSig = munger.getDeclaredSignature(); if (declaredSig==null) declaredSig= munger.getSignature(); weaver.getWorld().getMessageHandler().handleMessage(WeaveMessage.constructWeavingMessage(WeaveMessage.WEAVEMESSAGE_ITD, new String[]{weaver.getLazyClassGen().getType().getName(), tName,munger.getKind().toString().toLowerCase(), getAspectType().getName(), fName+":'"+declaredSig+"'"}, weaver.getLazyClassGen().getClassName(), getAspectType().getName())); } } CompilationAndWeavingContext.leavingPhase(tok); return changed; } private String getShortname(String path) { int takefrom = path.lastIndexOf('/'); if (takefrom == -1) { takefrom = path.lastIndexOf('\\'); } return path.substring(takefrom+1); } private boolean mungeNewAnnotationOnType(BcelClassWeaver weaver,AnnotationOnTypeMunger munger) { // FIXME asc this has already been done up front, need to do it here too? weaver.getLazyClassGen().addAnnotation(munger.getNewAnnotation().getBcelAnnotation()); return true; } /** * For a long time, AspectJ did not allow binary weaving of declare parents. This restriction is now lifted * but could do with more testing! */ private boolean mungeNewParent(BcelClassWeaver weaver, NewParentTypeMunger munger) { LazyClassGen newParentTarget = weaver.getLazyClassGen(); ResolvedType newParent = munger.getNewParent(); boolean cont = true; // Set to false when we error, so we don't actually *do* the munge cont = enforceDecpRule1_abstractMethodsImplemented(weaver, munger.getSourceLocation(),newParentTarget, newParent); cont = enforceDecpRule2_cantExtendFinalClass(weaver,munger.getSourceLocation(),newParentTarget,newParent) && cont; List methods = newParent.getMethodsWithoutIterator(false,true); for (Iterator iter = methods.iterator(); iter.hasNext();) { ResolvedMember superMethod = (ResolvedMember) iter.next(); if (!superMethod.getName().equals("<init>")) { LazyMethodGen subMethod = findMatchingMethod(newParentTarget, superMethod); if (subMethod!=null && !subMethod.isBridgeMethod()) { // FIXME asc is this safe for all bridge methods? if (!(subMethod.isSynthetic() && superMethod.isSynthetic())) { if (!(subMethod.isStatic() && subMethod.getName().startsWith("access$"))) { // ignore generated accessors cont = enforceDecpRule3_visibilityChanges(weaver, newParent, superMethod, subMethod) && cont; cont = enforceDecpRule4_compatibleReturnTypes(weaver, superMethod, subMethod) && cont; cont = enforceDecpRule5_cantChangeFromStaticToNonstatic(weaver,munger.getSourceLocation(),superMethod,subMethod) && cont; } } } } } if (!cont) return false; // A rule was violated and an error message already reported if (newParent.isClass()) { // Changing the supertype if (!attemptToModifySuperCalls(weaver,newParentTarget,newParent)) return false; newParentTarget.setSuperClass(newParent); } else { // Adding a new interface newParentTarget.addInterface(newParent,getSourceLocation()); } return true; } /** * Rule 1: For the declare parents to be allowed, the target type must override and implement * inherited abstract methods (if the type is not declared abstract) */ private boolean enforceDecpRule1_abstractMethodsImplemented(BcelClassWeaver weaver, ISourceLocation mungerLoc,LazyClassGen newParentTarget, ResolvedType newParent) { boolean ruleCheckingSucceeded = true; if (!(newParentTarget.isAbstract() || newParentTarget.isInterface())) { // Ignore abstract classes or interfaces List methods = newParent.getMethodsWithoutIterator(false,true); for (Iterator i = methods.iterator(); i.hasNext();) { ResolvedMember o = (ResolvedMember)i.next(); if (o.isAbstract() && !o.getName().startsWith("ajc$interField")) { // Ignore abstract methods of ajc$interField prefixed methods ResolvedMember discoveredImpl = null; List newParentTargetMethods = newParentTarget.getType().getMethodsWithoutIterator(false,true); for (Iterator ii = newParentTargetMethods.iterator(); ii.hasNext() && discoveredImpl==null;) { ResolvedMember gen2 = (ResolvedMember) ii.next(); if (gen2.getName().equals(o.getName()) && gen2.getParameterSignature().equals(o.getParameterSignature()) && !gen2.isAbstract()) { discoveredImpl = gen2; // Found a valid implementation ! } } if (discoveredImpl == null) { // didnt find a valid implementation, lets check the ITDs on this type to see if they satisfy it boolean satisfiedByITD = false; for (Iterator ii = newParentTarget.getType().getInterTypeMungersIncludingSupers().iterator(); ii.hasNext(); ) { ConcreteTypeMunger m = (ConcreteTypeMunger)ii.next(); if (m.getMunger()!=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)); sig = m.getSignature(); // possible sig change when type parameters filled in } if (ResolvedType .matches( AjcMemberMaker.interMethod( sig,m.getAspectType(),sig.getDeclaringType().resolve(weaver.getWorld()).isInterface()),o)) { satisfiedByITD = true; } } } else if (m.getMunger()!=null && m.getMunger().getKind() == ResolvedTypeMunger.MethodDelegate) { satisfiedByITD = true;//AV - that should be enough, no need to check more } } if (!satisfiedByITD) { error(weaver, "The type " + newParentTarget.getName() + " must implement the inherited abstract method "+o.getDeclaringType()+"."+o.getName()+o.getParameterSignature(), newParentTarget.getType().getSourceLocation(),new ISourceLocation[]{o.getSourceLocation(),mungerLoc}); ruleCheckingSucceeded=false; } } } } } return ruleCheckingSucceeded; } /** * Rule 2. Can't extend final types */ private boolean enforceDecpRule2_cantExtendFinalClass(BcelClassWeaver weaver, ISourceLocation mungerLoc, LazyClassGen newParentTarget, ResolvedType newParent) { if (newParent.isFinal()) { error(weaver,"Cannot make type "+newParentTarget.getName()+" extend final class "+newParent.getName(), newParentTarget.getType().getSourceLocation(), new ISourceLocation[]{mungerLoc}); return false; } return true; } /** * Rule 3. Can't narrow visibility of methods when overriding */ private boolean enforceDecpRule3_visibilityChanges(BcelClassWeaver weaver, ResolvedType newParent, ResolvedMember superMethod, LazyMethodGen subMethod) { boolean cont = true; if (superMethod.isPublic()) { if (subMethod.isProtected() || subMethod.isDefault() || subMethod.isPrivate()) { weaver.getWorld().getMessageHandler().handleMessage(MessageUtil.error( "Cannot reduce the visibility of the inherited method '"+superMethod+"' from "+newParent.getName(), superMethod.getSourceLocation())); cont=false; } } else if (superMethod.isProtected()) { if (subMethod.isDefault() || subMethod.isPrivate()) { weaver.getWorld().getMessageHandler().handleMessage(MessageUtil.error( "Cannot reduce the visibility of the inherited method '"+superMethod+"' from "+newParent.getName(), superMethod.getSourceLocation())); cont=false; } } else if (superMethod.isDefault()) { if (subMethod.isPrivate()) { weaver.getWorld().getMessageHandler().handleMessage(MessageUtil.error( "Cannot reduce the visibility of the inherited method '"+superMethod+"' from "+newParent.getName(), superMethod.getSourceLocation())); cont=false; } } return cont; } /** * Rule 4. Can't have incompatible return types */ private boolean enforceDecpRule4_compatibleReturnTypes(BcelClassWeaver weaver, ResolvedMember superMethod, LazyMethodGen subMethod) { boolean cont = true; String superReturnTypeSig = superMethod.getReturnType().getSignature(); String subReturnTypeSig = subMethod.getReturnType().getSignature(); superReturnTypeSig = superReturnTypeSig.replace('.','/'); subReturnTypeSig = subReturnTypeSig.replace('.','/'); if (!superReturnTypeSig.equals(subReturnTypeSig)) { // Allow for covariance - wish I could test this (need Java5...) ResolvedType subType = weaver.getWorld().resolve(subMethod.getReturnType()); ResolvedType superType = weaver.getWorld().resolve(superMethod.getReturnType()); if (!superType.isAssignableFrom(subType)) { ISourceLocation sloc = subMethod.getSourceLocation(); weaver.getWorld().getMessageHandler().handleMessage(MessageUtil.error( "The return type is incompatible with "+superMethod.getDeclaringType()+"."+superMethod.getName()+superMethod.getParameterSignature(), subMethod.getSourceLocation())); // 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 ) { if (superMethod.isStatic() && !subMethod.isStatic()) { error(weaver,"This instance method "+subMethod.getName()+subMethod.getParameterSignature()+ " cannot override the static method from "+superMethod.getDeclaringType().getName(), subMethod.getSourceLocation(),new ISourceLocation[]{mungerLoc}); return false; } else if (!superMethod.isStatic() && subMethod.isStatic()) { error(weaver,"The static method "+subMethod.getName()+subMethod.getParameterSignature()+ " cannot hide the instance method from "+superMethod.getDeclaringType().getName(), subMethod.getSourceLocation(),new ISourceLocation[]{mungerLoc}); return false; } return true; } public void error(BcelClassWeaver weaver,String text,ISourceLocation primaryLoc,ISourceLocation[] extraLocs) { IMessage msg = new Message(text, primaryLoc, true, extraLocs); weaver.getWorld().getMessageHandler().handleMessage(msg); } private LazyMethodGen findMatchingMethod(LazyClassGen newParentTarget, ResolvedMember m) { LazyMethodGen found = null; // Search the type for methods overriding super methods (methods that come from the new parent) // Don't use the return value in the comparison as overriding doesnt for (Iterator i = newParentTarget.getMethodGens().iterator(); i.hasNext() && found==null;) { LazyMethodGen gen = (LazyMethodGen) i.next(); if (gen.getName().equals(m.getName()) && gen.getParameterSignature().equals(m.getParameterSignature())) { found = gen; } } return found; } /** * The main part of implementing declare parents extends. Modify super ctor calls to target the new type. */ public boolean attemptToModifySuperCalls(BcelClassWeaver weaver,LazyClassGen newParentTarget, ResolvedType newParent) { String currentParent = newParentTarget.getSuperClassname(); if (newParent.getGenericType()!=null) newParent = newParent.getGenericType(); // target new super calls at the generic type if its raw or parameterized List mgs = newParentTarget.getMethodGens(); // Look for ctors to modify for (Iterator iter = mgs.iterator(); iter.hasNext();) { LazyMethodGen aMethod = (LazyMethodGen) iter.next(); if (aMethod.getName().equals("<init>")) { InstructionList insList = aMethod.getBody(); InstructionHandle handle = insList.getStart(); while (handle!= null) { if (handle.getInstruction() instanceof INVOKESPECIAL) { ConstantPoolGen cpg = newParentTarget.getConstantPoolGen(); INVOKESPECIAL invokeSpecial = (INVOKESPECIAL)handle.getInstruction(); if (invokeSpecial.getClassName(cpg).equals(currentParent) && invokeSpecial.getMethodName(cpg).equals("<init>")) { // System.err.println("Transforming super call '<init>"+sp.getSignature(cpg)+"'"); // 1. Check there is a ctor in the new parent with the same signature ResolvedMember newCtor = getConstructorWithSignature(newParent,invokeSpecial.getSignature(cpg)); if (newCtor == null) { // 2. Check ITDCs to see if the necessary ctor is provided that way boolean satisfiedByITDC = false; for (Iterator ii = newParentTarget.getType().getInterTypeMungersIncludingSupers().iterator(); ii.hasNext() && !satisfiedByITDC; ) { ConcreteTypeMunger m = (ConcreteTypeMunger)ii.next(); if (m.getMunger() instanceof NewConstructorTypeMunger) { if (m.getSignature().getSignature().equals(invokeSpecial.getSignature(cpg))) { satisfiedByITDC = true; } } } if (!satisfiedByITDC) { String csig = createReadableCtorSig(newParent, cpg, invokeSpecial); weaver.getWorld().getMessageHandler().handleMessage(MessageUtil.error( "Unable to modify hierarchy for "+newParentTarget.getClassName()+" - the constructor "+ csig+" is missing",this.getSourceLocation())); return false; } } int idx = cpg.addMethodref(newParent.getName(), invokeSpecial.getMethodName(cpg), invokeSpecial.getSignature(cpg)); invokeSpecial.setIndex(idx); } } handle = handle.getNext(); } } } return true; } /** * Creates a nice signature for the ctor, something like "(int,Integer,String)" */ private String createReadableCtorSig(ResolvedType newParent, ConstantPoolGen cpg, INVOKESPECIAL invokeSpecial) { StringBuffer sb = new StringBuffer(); Type[] ctorArgs = invokeSpecial.getArgumentTypes(cpg); sb.append(newParent.getClassName()); sb.append("("); for (int i = 0; i < ctorArgs.length; i++) { String argtype = ctorArgs[i].toString(); if (argtype.lastIndexOf(".")!=-1) sb.append(argtype.substring(argtype.lastIndexOf(".")+1)); else sb.append(argtype); if (i+1<ctorArgs.length) sb.append(","); } sb.append(")"); return sb.toString(); } private ResolvedMember getConstructorWithSignature(ResolvedType tx,String signature) { ResolvedMember[] mems = tx.getDeclaredJavaMethods(); for (int i = 0; i < mems.length; i++) { ResolvedMember rm = mems[i]; if (rm.getName().equals("<init>")) { if (rm.getSignature().equals(signature)) return rm; } } return null; } private boolean mungePrivilegedAccess( BcelClassWeaver weaver, PrivilegedAccessMunger munger) { LazyClassGen gen = weaver.getLazyClassGen(); ResolvedMember member = munger.getMember(); ResolvedType onType = weaver.getWorld().resolve(member.getDeclaringType(),munger.getSourceLocation()); if (onType.isRawType()) onType = onType.getGenericType(); //System.out.println("munging: " + gen + " with " + member); if (onType.equals(gen.getType())) { if (member.getKind() == Member.FIELD) { //System.out.println("matched: " + gen); addFieldGetter(gen, member, AjcMemberMaker.privilegedAccessMethodForFieldGet(aspectType, member)); addFieldSetter(gen, member, AjcMemberMaker.privilegedAccessMethodForFieldSet(aspectType, member)); return true; } else if (member.getKind() == Member.METHOD) { addMethodDispatch(gen, member, AjcMemberMaker.privilegedAccessMethodForMethod(aspectType, member)); return true; } else if (member.getKind() == Member.CONSTRUCTOR) { for (Iterator i = gen.getMethodGens().iterator(); i.hasNext(); ) { LazyMethodGen m = (LazyMethodGen)i.next(); if (m.getMemberView() != null && m.getMemberView().getKind() == Member.CONSTRUCTOR) { // m.getMemberView().equals(member)) { m.forcePublic(); //return true; } } return true; //throw new BCException("no match for " + member + " in " + gen); } else if (member.getKind() == Member.STATIC_INITIALIZATION) { gen.forcePublic(); return true; } else { throw new RuntimeException("unimplemented"); } } return false; } private void addFieldGetter( LazyClassGen gen, ResolvedMember field, ResolvedMember accessMethod) { LazyMethodGen mg = makeMethodGen(gen, accessMethod); InstructionList il = new InstructionList(); InstructionFactory fact = gen.getFactory(); if (field.isStatic()) { il.append(fact.createFieldAccess( gen.getClassName(), field.getName(), BcelWorld.makeBcelType(field.getType()), Constants.GETSTATIC)); } else { il.append(InstructionConstants.ALOAD_0); il.append(fact.createFieldAccess( gen.getClassName(), field.getName(), BcelWorld.makeBcelType(field.getType()), Constants.GETFIELD)); } il.append(InstructionFactory.createReturn(BcelWorld.makeBcelType(field.getType()))); mg.getBody().insert(il); gen.addMethodGen(mg,getSignature().getSourceLocation()); } private void addFieldSetter( LazyClassGen gen, ResolvedMember field, ResolvedMember accessMethod) { LazyMethodGen mg = makeMethodGen(gen, accessMethod); InstructionList il = new InstructionList(); InstructionFactory fact = gen.getFactory(); Type fieldType = BcelWorld.makeBcelType(field.getType()); if (field.isStatic()) { il.append(InstructionFactory.createLoad(fieldType, 0)); il.append(fact.createFieldAccess( gen.getClassName(), field.getName(), fieldType, Constants.PUTSTATIC)); } else { il.append(InstructionConstants.ALOAD_0); il.append(InstructionFactory.createLoad(fieldType, 1)); il.append(fact.createFieldAccess( gen.getClassName(), field.getName(), fieldType, Constants.PUTFIELD)); } il.append(InstructionFactory.createReturn(Type.VOID)); mg.getBody().insert(il); gen.addMethodGen(mg,getSignature().getSourceLocation()); } private void addMethodDispatch( LazyClassGen gen, ResolvedMember method, ResolvedMember accessMethod) { LazyMethodGen mg = makeMethodGen(gen, accessMethod); InstructionList il = new InstructionList(); InstructionFactory fact = gen.getFactory(); //Type fieldType = BcelWorld.makeBcelType(field.getType()); Type[] paramTypes = BcelWorld.makeBcelTypes(method.getParameterTypes()); int pos = 0; if (!method.isStatic()) { il.append(InstructionConstants.ALOAD_0); pos++; } for (int i = 0, len = paramTypes.length; i < len; i++) { Type paramType = paramTypes[i]; il.append(InstructionFactory.createLoad(paramType, pos)); pos+=paramType.getSize(); } il.append(Utility.createInvoke(fact, (BcelWorld)aspectType.getWorld(), method)); il.append(InstructionFactory.createReturn(BcelWorld.makeBcelType(method.getReturnType()))); mg.getBody().insert(il); gen.addMethodGen(mg); } protected LazyMethodGen makeMethodGen(LazyClassGen gen, ResolvedMember member) { LazyMethodGen ret = new LazyMethodGen( member.getModifiers(), BcelWorld.makeBcelType(member.getReturnType()), member.getName(), BcelWorld.makeBcelTypes(member.getParameterTypes()), UnresolvedType.getNames(member.getExceptions()), gen); // 43972 : Static crosscutting makes interfaces unusable for javac // ret.makeSynthetic(); return ret; } protected FieldGen makeFieldGen(LazyClassGen gen, ResolvedMember member) { return new FieldGen( member.getModifiers(), BcelWorld.makeBcelType(member.getReturnType()), member.getName(), gen.getConstantPoolGen()); } private boolean mungePerObjectInterface( BcelClassWeaver weaver, PerObjectInterfaceTypeMunger munger) { //System.err.println("Munging perobject ["+munger+"] onto "+weaver.getLazyClassGen().getClassName()); LazyClassGen gen = weaver.getLazyClassGen(); if (couldMatch(gen.getBcelObjectType(), munger.getTestPointcut())) { FieldGen fg = makeFieldGen(gen, AjcMemberMaker.perObjectField(gen.getType(), aspectType)); gen.addField(fg.getField(),getSourceLocation()); Type fieldType = BcelWorld.makeBcelType(aspectType); LazyMethodGen mg = new LazyMethodGen( Modifier.PUBLIC, fieldType, NameMangler.perObjectInterfaceGet(aspectType), new Type[0], new String[0], gen); InstructionList il = new InstructionList(); InstructionFactory fact = gen.getFactory(); il.append(InstructionConstants.ALOAD_0); il.append(fact.createFieldAccess( gen.getClassName(), fg.getName(), fieldType, Constants.GETFIELD)); il.append(InstructionFactory.createReturn(fieldType)); mg.getBody().insert(il); gen.addMethodGen(mg); LazyMethodGen mg1 = new LazyMethodGen( Modifier.PUBLIC, Type.VOID, NameMangler.perObjectInterfaceSet(aspectType), new Type[]{fieldType,}, new String[0], gen); InstructionList il1 = new InstructionList(); il1.append(InstructionConstants.ALOAD_0); il1.append(InstructionFactory.createLoad(fieldType, 1)); il1.append(fact.createFieldAccess( gen.getClassName(), fg.getName(), fieldType, Constants.PUTFIELD)); il1.append(InstructionFactory.createReturn(Type.VOID)); mg1.getBody().insert(il1); gen.addMethodGen(mg1); gen.addInterface(munger.getInterfaceType(),getSourceLocation()); return true; } else { return false; } } // PTWIMPL Add field to hold aspect instance and an accessor private boolean mungePerTypeWithinTransformer(BcelClassWeaver weaver) { LazyClassGen gen = weaver.getLazyClassGen(); // if (couldMatch(gen.getBcelObjectType(), munger.getTestPointcut())) { // Add (to the target type) the field that will hold the aspect instance // e.g ajc$com_blah_SecurityAspect$ptwAspectInstance FieldGen fg = makeFieldGen(gen, AjcMemberMaker.perTypeWithinField(gen.getType(), aspectType)); gen.addField(fg.getField(),getSourceLocation()); // Add an accessor for this new field, the ajc$<aspectname>$localAspectOf() method // e.g. "public com_blah_SecurityAspect ajc$com_blah_SecurityAspect$localAspectOf()" Type fieldType = BcelWorld.makeBcelType(aspectType); LazyMethodGen mg = new LazyMethodGen( Modifier.PUBLIC | Modifier.STATIC,fieldType, NameMangler.perTypeWithinLocalAspectOf(aspectType), new Type[0], new String[0],gen); InstructionList il = new InstructionList(); //PTWIMPL ?? Should check if it is null and throw NoAspectBoundException InstructionFactory fact = gen.getFactory(); il.append(fact.createFieldAccess( gen.getClassName(), fg.getName(), fieldType, Constants.GETSTATIC)); il.append(InstructionFactory.createReturn(fieldType)); mg.getBody().insert(il); gen.addMethodGen(mg); return true; // } else { // return false; // } } // ??? Why do we have this method? I thought by now we would know if it matched or not private boolean couldMatch( BcelObjectType bcelObjectType, Pointcut pointcut) { return !bcelObjectType.isInterface(); } private boolean mungeNewMethod(BcelClassWeaver weaver, NewMethodTypeMunger munger) { World w = weaver.getWorld(); // Resolving it will sort out the tvars ResolvedMember unMangledInterMethod = munger.getSignature().resolve(w); // do matching on the unMangled one, but actually add them to the mangled method ResolvedMember interMethodBody = munger.getDeclaredInterMethodBody(aspectType,w); ResolvedMember interMethodDispatcher = munger.getDeclaredInterMethodDispatcher(aspectType,w); ResolvedMember memberHoldingAnyAnnotations = interMethodDispatcher; ResolvedType onType = weaver.getWorld().resolve(unMangledInterMethod.getDeclaringType(),munger.getSourceLocation()); LazyClassGen gen = weaver.getLazyClassGen(); boolean mungingInterface = gen.isInterface(); if (onType.isRawType()) onType = onType.getGenericType(); boolean onInterface = onType.isInterface(); // Simple checks, can't ITD on annotations or enums if (onType.isAnnotation()) { signalError(WeaverMessages.ITDM_ON_ANNOTATION_NOT_ALLOWED,weaver,onType); return false; } if (onType.isEnum()) { signalError(WeaverMessages.ITDM_ON_ENUM_NOT_ALLOWED,weaver,onType); return false; } if (onInterface && gen.getLazyMethodGen(unMangledInterMethod.getName(), unMangledInterMethod.getSignature(),true) != null) { // this is ok, we could be providing the default implementation of a method // that the target has already declared return false; } // If we are processing the intended ITD target type (might be an interface) if (onType.equals(gen.getType())) { ResolvedMember mangledInterMethod = AjcMemberMaker.interMethod(unMangledInterMethod, aspectType, onInterface); LazyMethodGen newMethod = makeMethodGen(gen, mangledInterMethod); if (mungingInterface) { // we want the modifiers of the ITD to be used for all *implementors* of the // interface, but the method itself we add to the interface must be public abstract newMethod.setAccessFlags(Modifier.PUBLIC | Modifier.ABSTRACT); } // pr98901 // For copying the annotations across, we have to discover the real member in the aspect // which is holding them. if (weaver.getWorld().isInJava5Mode()){ AnnotationX annotationsOnRealMember[] = null; ResolvedType toLookOn = aspectType; if (aspectType.isRawType()) toLookOn = aspectType.getGenericType(); ResolvedMember realMember = getRealMemberForITDFromAspect(toLookOn,memberHoldingAnyAnnotations,false); if (realMember==null) throw new BCException("Couldn't find ITD holder member '"+ memberHoldingAnyAnnotations+"' on aspect "+aspectType); annotationsOnRealMember = realMember.getAnnotations(); if (annotationsOnRealMember!=null) { for (int i = 0; i < annotationsOnRealMember.length; i++) { AnnotationX annotationX = annotationsOnRealMember[i]; Annotation a = annotationX.getBcelAnnotation(); AnnotationGen ag = new AnnotationGen(a,weaver.getLazyClassGen().getConstantPoolGen(),true); newMethod.addAnnotation(new AnnotationX(ag.getAnnotation(),weaver.getWorld())); } } // the below loop fixes the very special (and very stupid) // case where an aspect declares an annotation // on an ITD it declared on itself. List allDecams = weaver.getWorld().getDeclareAnnotationOnMethods(); for (Iterator i = allDecams.iterator(); i.hasNext();){ DeclareAnnotation decaMC = (DeclareAnnotation) i.next(); if (decaMC.matches(unMangledInterMethod,weaver.getWorld()) && newMethod.getEnclosingClass().getType() == aspectType) { newMethod.addAnnotation(decaMC.getAnnotationX()); } } } // If it doesn't target an interface and there is a body (i.e. it isnt abstract) if (!onInterface && !Modifier.isAbstract(mangledInterMethod.getModifiers())) { InstructionList body = newMethod.getBody(); InstructionFactory fact = gen.getFactory(); int pos = 0; if (!unMangledInterMethod.isStatic()) { body.append(InstructionFactory.createThis()); pos++; } Type[] paramTypes = BcelWorld.makeBcelTypes(mangledInterMethod.getParameterTypes()); for (int i = 0, len = paramTypes.length; i < len; i++) { Type paramType = paramTypes[i]; body.append(InstructionFactory.createLoad(paramType, pos)); pos+=paramType.getSize(); } body.append(Utility.createInvoke(fact, weaver.getWorld(), interMethodBody)); body.append( InstructionFactory.createReturn( BcelWorld.makeBcelType(mangledInterMethod.getReturnType()))); if (weaver.getWorld().isInJava5Mode()) { // Don't need bridge methods if not in 1.5 mode. createAnyBridgeMethodsForCovariance(weaver, munger, unMangledInterMethod, onType, gen, paramTypes); } } else { //??? this is okay //if (!(mg.getBody() == null)) throw new RuntimeException("bas"); } // XXX make sure to check that we set exceptions properly on this guy. weaver.addLazyMethodGen(newMethod); weaver.getLazyClassGen().warnOnAddedMethod(newMethod.getMethod(),getSignature().getSourceLocation()); addNeededSuperCallMethods(weaver, onType, munger.getSuperMethodsCalled()); return true; } else if (onInterface && !Modifier.isAbstract(unMangledInterMethod.getModifiers())) { // This means the 'gen' should be the top most implementor // - if it is *not* then something went wrong after we worked // out that it was the top most implementor (see pr49657) if (!gen.getType().isTopmostImplementor(onType)) { ResolvedType rtx = gen.getType().getTopmostImplementor(onType); if (!rtx.isExposedToWeaver()) { ISourceLocation sLoc = munger.getSourceLocation(); weaver.getWorld().getMessageHandler().handleMessage(MessageUtil.error( WeaverMessages.format(WeaverMessages.ITD_NON_EXPOSED_IMPLEMENTOR,rtx,getAspectType().getName()), (sLoc==null?getAspectType().getSourceLocation():sLoc))); } else { // XXX what does this state mean? // We have incorrectly identified what is the top most implementor and its not because // a type wasn't exposed to the weaver } return false; } else { ResolvedMember mangledInterMethod = AjcMemberMaker.interMethod(unMangledInterMethod, aspectType, false); LazyMethodGen mg = makeMethodGen(gen, mangledInterMethod); // From 98901#29 - need to copy annotations across if (weaver.getWorld().isInJava5Mode()){ AnnotationX annotationsOnRealMember[] = null; ResolvedType toLookOn = aspectType; if (aspectType.isRawType()) toLookOn = aspectType.getGenericType(); ResolvedMember realMember = getRealMemberForITDFromAspect(toLookOn,memberHoldingAnyAnnotations,false); if (realMember==null) throw new BCException("Couldn't find ITD holder member '"+ memberHoldingAnyAnnotations+"' on aspect "+aspectType); annotationsOnRealMember = realMember.getAnnotations(); if (annotationsOnRealMember!=null) { for (int i = 0; i < annotationsOnRealMember.length; i++) { AnnotationX annotationX = annotationsOnRealMember[i]; Annotation a = annotationX.getBcelAnnotation(); AnnotationGen ag = new AnnotationGen(a,weaver.getLazyClassGen().getConstantPoolGen(),true); mg.addAnnotation(new AnnotationX(ag.getAnnotation(),weaver.getWorld())); } } } if (mungingInterface) { // we want the modifiers of the ITD to be used for all *implementors* of the // interface, but the method itself we add to the interface must be public abstract mg.setAccessFlags(Modifier.PUBLIC | Modifier.ABSTRACT); } Type[] paramTypes = BcelWorld.makeBcelTypes(mangledInterMethod.getParameterTypes()); Type returnType = BcelWorld.makeBcelType(mangledInterMethod.getReturnType()); InstructionList body = mg.getBody(); InstructionFactory fact = gen.getFactory(); int pos = 0; if (!mangledInterMethod.isStatic()) { body.append(InstructionFactory.createThis()); pos++; } for (int i = 0, len = paramTypes.length; i < len; i++) { Type paramType = paramTypes[i]; body.append(InstructionFactory.createLoad(paramType, pos)); pos+=paramType.getSize(); } body.append(Utility.createInvoke(fact, weaver.getWorld(), interMethodBody)); Type t= BcelWorld.makeBcelType(interMethodBody.getReturnType()); if (!t.equals(returnType)) { body.append(fact.createCast(t,returnType)); } body.append(InstructionFactory.createReturn(returnType)); mg.definingType = onType; weaver.addOrReplaceLazyMethodGen(mg); addNeededSuperCallMethods(weaver, onType, munger.getSuperMethodsCalled()); // Work out if we need a bridge method for the new method added to the topmostimplementor. if (munger.getDeclaredSignature()!=null) { // Check if the munger being processed is a parameterized form of some original munger. boolean needsbridging = false; ResolvedMember toBridgeTo = munger.getDeclaredSignature().parameterizedWith(null,munger.getSignature().getDeclaringType().resolve(getWorld()),false,munger.getTypeVariableAliases()); if (!toBridgeTo.getReturnType().getErasureSignature().equals(munger.getSignature().getReturnType().getErasureSignature())) needsbridging = true; UnresolvedType[] originalParams = toBridgeTo.getParameterTypes(); UnresolvedType[] newParams = munger.getSignature().getParameterTypes(); for (int ii = 0;ii<originalParams.length;ii++) { if (!originalParams[ii].getErasureSignature().equals(newParams[ii].getErasureSignature())) needsbridging=true; } if (toBridgeTo!=null && needsbridging) { ResolvedMember bridgerMethod = AjcMemberMaker.bridgerToInterMethod(unMangledInterMethod,gen.getType()); ResolvedMember bridgingSetter = AjcMemberMaker.interMethod(toBridgeTo, aspectType, false); // FIXME asc ----------------8<---------------- extract method LazyMethodGen bridgeMethod = makeMethodGen(gen,bridgingSetter); paramTypes = BcelWorld.makeBcelTypes(bridgingSetter.getParameterTypes()); Type[] bridgingToParms = BcelWorld.makeBcelTypes(unMangledInterMethod.getParameterTypes()); returnType = BcelWorld.makeBcelType(bridgingSetter.getReturnType()); body = bridgeMethod.getBody(); fact = gen.getFactory(); pos = 0; if (!bridgingSetter.isStatic()) { body.append(InstructionFactory.createThis()); pos++; } for (int i = 0, len = paramTypes.length; i < len; i++) { Type paramType = paramTypes[i]; body.append(InstructionFactory.createLoad(paramType, pos)); if (!bridgingSetter.getParameterTypes()[i].getErasureSignature().equals(unMangledInterMethod.getParameterTypes()[i].getErasureSignature()) ) { // System.err.println("Putting in cast from "+paramType+" to "+bridgingToParms[i]); body.append(fact.createCast(paramType,bridgingToParms[i])); } pos+=paramType.getSize(); } body.append(Utility.createInvoke(fact, weaver.getWorld(), bridgerMethod)); body.append(InstructionFactory.createReturn(returnType)); gen.addMethodGen(bridgeMethod); // mg.definingType = onType; // FIXME asc (see above) ---------------------8<--------------- extract method } } return true; } } else { return false; } } /** * Create any bridge method required because of covariant returns being used. This method is used in the case * where an ITD is applied to some type and it may be in an override relationship with a method from the supertype - but * due to covariance there is a mismatch in return values. * Example of when required: Super defines: Object m(String s) Sub defines: String m(String s) then we need a bridge method in Sub called 'Object m(String s)' that forwards to 'String m(String s)' */ private void createAnyBridgeMethodsForCovariance(BcelClassWeaver weaver, NewMethodTypeMunger munger, ResolvedMember unMangledInterMethod, ResolvedType onType, LazyClassGen gen, Type[] paramTypes) { // PERFORMANCE BOTTLENECK? Might need investigating, method analysis between types in a hierarchy just seems expensive... // COVARIANCE BRIDGING // Algorithm: Step1. Check in this type - has someone already created the bridge method? // Step2. Look above us - do we 'override' a method and yet differ in return type (i.e. covariance) // Step3. Create a forwarding bridge method ResolvedType superclass = onType.getSuperclass(); boolean quitRightNow = false; String localMethodName = unMangledInterMethod.getName(); String localParameterSig = unMangledInterMethod.getParameterSignature(); String localReturnTypeESig = unMangledInterMethod.getReturnType().getErasureSignature(); // Step1 boolean alreadyDone = false; // Compiler might have done it ResolvedMember[] localMethods = onType.getDeclaredMethods(); for (int i = 0; i < localMethods.length; i++) { ResolvedMember member = localMethods[i]; if (member.getName().equals(localMethodName)) { // Check the params if (member.getParameterSignature().equals(localParameterSig)) alreadyDone = true; } } // Step2 if (!alreadyDone) { // Use the iterator form of 'getMethods()' so we do as little work as necessary for (Iterator iter = onType.getSuperclass().getMethods();iter.hasNext() && !quitRightNow;) { ResolvedMember aMethod = (ResolvedMember) iter.next(); if (aMethod.getName().equals(localMethodName) && aMethod.getParameterSignature().equals(localParameterSig)) { // check the return types, if they are different we need a bridging method. if (!aMethod.getReturnType().getErasureSignature().equals(localReturnTypeESig) && !Modifier.isPrivate(aMethod.getModifiers())) { // Step3 createBridgeMethod(weaver.getWorld(), munger, unMangledInterMethod, gen, paramTypes, aMethod); quitRightNow = true; } } } } } /** * Create a bridge method for a particular munger. * @param world * @param munger * @param unMangledInterMethod the method to bridge 'to' that we have already created in the 'subtype' * @param clazz the class in which to put the bridge method * @param paramTypes Parameter types for the bridge method, passed in as an optimization since the caller is likely to have already created them. * @param theBridgeMethod */ private void createBridgeMethod(BcelWorld world, NewMethodTypeMunger munger, ResolvedMember unMangledInterMethod, LazyClassGen clazz, Type[] paramTypes, ResolvedMember theBridgeMethod) { InstructionList body; InstructionFactory fact; int pos = 0; LazyMethodGen bridgeMethod = makeMethodGen(clazz,theBridgeMethod); // The bridge method in this type will have the same signature as the one in the supertype bridgeMethod.setAccessFlags(bridgeMethod.getAccessFlags() | 0x00000040 /*BRIDGE = 0x00000040*/ ); UnresolvedType[] newParams = munger.getSignature().getParameterTypes(); Type returnType = BcelWorld.makeBcelType(theBridgeMethod.getReturnType()); body = bridgeMethod.getBody(); fact = clazz.getFactory(); if (!unMangledInterMethod.isStatic()) { body.append(InstructionFactory.createThis()); pos++; } for (int i = 0, len = paramTypes.length; i < len; i++) { Type paramType = paramTypes[i]; body.append(InstructionFactory.createLoad(paramType, pos)); // if (!bridgingSetter.getParameterTypes()[i].getErasureSignature().equals(unMangledInterMethod.getParameterTypes()[i].getErasureSignature())) { // System.err.println("Putting in cast from "+paramType+" to "+bridgingToParms[i]); // body.append(fact.createCast(paramType,bridgingToParms[i])); // } pos+=paramType.getSize(); } body.append(Utility.createInvoke(fact, world,unMangledInterMethod)); body.append(InstructionFactory.createReturn(returnType)); clazz.addMethodGen(bridgeMethod); } private boolean mungeMethodDelegate(BcelClassWeaver weaver, MethodDelegateTypeMunger munger) { ResolvedMember introduced = munger.getSignature(); LazyClassGen gen = weaver.getLazyClassGen(); ResolvedType fromType = weaver.getWorld().resolve(introduced.getDeclaringType(),munger.getSourceLocation()); if (fromType.isRawType()) fromType = fromType.getGenericType(); if (gen.getType().isAnnotation() || gen.getType().isEnum()) { // don't signal error as it could be a consequence of a wild type pattern return false; } boolean shouldApply = munger.matches(weaver.getLazyClassGen().getType(), aspectType); if (shouldApply) { LazyMethodGen mg = new LazyMethodGen( introduced.getModifiers() - Modifier.ABSTRACT, BcelWorld.makeBcelType(introduced.getReturnType()), introduced.getName(), BcelWorld.makeBcelTypes(introduced.getParameterTypes()), BcelWorld.makeBcelTypesAsClassNames(introduced.getExceptions()), gen ); //annotation copy from annotation on ITD interface if (weaver.getWorld().isInJava5Mode()){ AnnotationX annotationsOnRealMember[] = null; ResolvedType toLookOn = weaver.getWorld().lookupOrCreateName(introduced.getDeclaringType()); if (fromType.isRawType()) toLookOn = fromType.getGenericType(); // lookup the method ResolvedMember[] ms = toLookOn.getDeclaredJavaMethods(); for (int i = 0; i < ms.length; i++) { ResolvedMember m = ms[i]; if (introduced.getName().equals(m.getName()) && introduced.getSignature().equals(m.getSignature())) { annotationsOnRealMember = m.getAnnotations(); } } if (annotationsOnRealMember!=null) { for (int i = 0; i < annotationsOnRealMember.length; i++) { AnnotationX annotationX = annotationsOnRealMember[i]; Annotation a = annotationX.getBcelAnnotation(); AnnotationGen ag = new AnnotationGen(a,weaver.getLazyClassGen().getConstantPoolGen(),true); mg.addAnnotation(new AnnotationX(ag.getAnnotation(),weaver.getWorld())); } } } InstructionList body = new InstructionList(); InstructionFactory fact = gen.getFactory(); // getfield body.append(InstructionConstants.ALOAD_0); body.append(Utility.createGet(fact, munger.getDelegate(weaver.getLazyClassGen().getType()))); BranchInstruction ifNonNull = InstructionFactory.createBranchInstruction(Constants.IFNONNULL, null); body.append(ifNonNull); // Create and store a new instance body.append(InstructionConstants.ALOAD_0); body.append(fact.createNew(munger.getImplClassName())); body.append(InstructionConstants.DUP); body.append(fact.createInvoke(munger.getImplClassName(), "<init>", Type.VOID, Type.NO_ARGS, Constants.INVOKESPECIAL)); body.append(Utility.createSet(fact, munger.getDelegate(weaver.getLazyClassGen().getType()))); // if not null use the instance we've got InstructionHandle ifNonNullElse = body.append(InstructionConstants.ALOAD_0); ifNonNull.setTarget(ifNonNullElse); body.append(Utility.createGet(fact, munger.getDelegate(weaver.getLazyClassGen().getType()))); //args int pos = 0; if (!introduced.isStatic()) { // skip 'this' (?? can this really happen) //body.append(InstructionFactory.createThis()); pos++; } Type[] paramTypes = BcelWorld.makeBcelTypes(introduced.getParameterTypes()); for (int i = 0, len = paramTypes.length; i < len; i++) { Type paramType = paramTypes[i]; body.append(InstructionFactory.createLoad(paramType, pos)); pos+=paramType.getSize(); } body.append(Utility.createInvoke(fact, Constants.INVOKEINTERFACE, introduced)); body.append( InstructionFactory.createReturn( BcelWorld.makeBcelType(introduced.getReturnType()) ) ); mg.getBody().append(body); weaver.addLazyMethodGen(mg); weaver.getLazyClassGen().warnOnAddedMethod(mg.getMethod(),getSignature().getSourceLocation()); return true; } return false; } private boolean mungeFieldHost(BcelClassWeaver weaver, MethodDelegateTypeMunger.FieldHostTypeMunger munger) { LazyClassGen gen = weaver.getLazyClassGen(); if (gen.getType().isAnnotation() || gen.getType().isEnum()) { // don't signal error as it could be a consequence of a wild type pattern return false; } boolean shouldApply = munger.matches(weaver.getLazyClassGen().getType(), aspectType); ResolvedMember host = AjcMemberMaker.itdAtDeclareParentsField( weaver.getLazyClassGen().getType(), munger.getSignature().getType(), aspectType); weaver.getLazyClassGen().addField(makeFieldGen( weaver.getLazyClassGen(), host).getField(), null); return true; } private ResolvedMember getRealMemberForITDFromAspect(ResolvedType aspectType,ResolvedMember lookingFor,boolean isCtorRelated) { World world = aspectType.getWorld(); boolean debug = false; if (debug) { System.err.println("Searching for a member on type: "+aspectType); System.err.println("Member we are looking for: "+lookingFor); } ResolvedMember aspectMethods[] = aspectType.getDeclaredMethods(); UnresolvedType [] lookingForParams = lookingFor.getParameterTypes(); ResolvedMember realMember = null; for (int i = 0; realMember==null && i < aspectMethods.length; i++) { ResolvedMember member = aspectMethods[i]; if (member.getName().equals(lookingFor.getName())){ UnresolvedType [] memberParams = member.getGenericParameterTypes(); if (memberParams.length == lookingForParams.length){ if (debug) System.err.println("Reviewing potential candidates: "+member); boolean matchOK = true; // If not related to a ctor ITD then the name is enough to confirm we have the // right one. If it is ctor related we need to check the params all match, although // only the erasure. if (isCtorRelated) { for (int j = 0; j < memberParams.length && matchOK; j++){ ResolvedType pMember = memberParams[j].resolve(world); ResolvedType pLookingFor = lookingForParams[j].resolve(world); if (pMember.isTypeVariableReference()) pMember = ((TypeVariableReference)pMember).getTypeVariable().getFirstBound().resolve(world); if (pMember.isParameterizedType() || pMember.isGenericType()) pMember = pMember.getRawType().resolve(aspectType.getWorld()); if (pLookingFor.isTypeVariableReference()) pLookingFor = ((TypeVariableReference)pLookingFor).getTypeVariable().getFirstBound().resolve(world); if (pLookingFor.isParameterizedType() || pLookingFor.isGenericType()) pLookingFor = pLookingFor.getRawType().resolve(world); if (debug) System.err.println("Comparing parameter "+j+" member="+pMember+" lookingFor="+pLookingFor); if (!pMember.equals(pLookingFor)){ matchOK=false; } } } if (matchOK) realMember = member; } } } if (debug && realMember==null) System.err.println("Didn't find a match"); return realMember; } private void addNeededSuperCallMethods( BcelClassWeaver weaver, ResolvedType onType, Set neededSuperCalls) { LazyClassGen gen = weaver.getLazyClassGen(); for (Iterator iter = neededSuperCalls.iterator(); iter.hasNext();) { ResolvedMember superMethod = (ResolvedMember) iter.next(); if (weaver.addDispatchTarget(superMethod)) { //System.err.println("super type: " + superMethod.getDeclaringType() + ", " + gen.getType()); boolean isSuper = !superMethod.getDeclaringType().equals(gen.getType()); String dispatchName; if (isSuper) dispatchName = NameMangler.superDispatchMethod(onType, superMethod.getName()); else dispatchName = NameMangler.protectedDispatchMethod( onType, superMethod.getName()); LazyMethodGen dispatcher = makeDispatcher( gen, dispatchName, superMethod, weaver.getWorld(), isSuper); weaver.addLazyMethodGen(dispatcher); } } } private void signalError(String msgid,BcelClassWeaver weaver,UnresolvedType onType) { IMessage msg = MessageUtil.error( WeaverMessages.format(msgid,onType.getName()),getSourceLocation()); weaver.getWorld().getMessageHandler().handleMessage(msg); } private boolean mungeNewConstructor( BcelClassWeaver weaver, NewConstructorTypeMunger newConstructorTypeMunger) { final LazyClassGen currentClass = weaver.getLazyClassGen(); final InstructionFactory fact = currentClass.getFactory(); ResolvedMember newConstructorMember = newConstructorTypeMunger.getSyntheticConstructor(); ResolvedType onType = newConstructorMember.getDeclaringType().resolve(weaver.getWorld()); if (onType.isRawType()) onType = onType.getGenericType(); if (onType.isAnnotation()) { signalError(WeaverMessages.ITDC_ON_ANNOTATION_NOT_ALLOWED,weaver,onType); return false; } if (onType.isEnum()) { signalError(WeaverMessages.ITDC_ON_ENUM_NOT_ALLOWED,weaver,onType); return false; } if (! onType.equals(currentClass.getType())) return false; ResolvedMember explicitConstructor = newConstructorTypeMunger.getExplicitConstructor(); //int declaredParameterCount = newConstructorTypeMunger.getDeclaredParameterCount(); LazyMethodGen mg = makeMethodGen(currentClass, newConstructorMember); mg.setEffectiveSignature(newConstructorTypeMunger.getSignature(),Shadow.ConstructorExecution,true); // pr98901 // For copying the annotations across, we have to discover the real member in the aspect // which is holding them. if (weaver.getWorld().isInJava5Mode()){ ResolvedMember interMethodDispatcher =AjcMemberMaker.postIntroducedConstructor(aspectType,onType,newConstructorTypeMunger.getSignature().getParameterTypes()); AnnotationX annotationsOnRealMember[] = null; ResolvedMember realMember = getRealMemberForITDFromAspect(aspectType,interMethodDispatcher,true); if (realMember==null) throw new BCException("Couldn't find ITD holder member '"+ interMethodDispatcher+"' on aspect "+aspectType); annotationsOnRealMember = realMember.getAnnotations(); if (annotationsOnRealMember!=null) { for (int i = 0; i < annotationsOnRealMember.length; i++) { AnnotationX annotationX = annotationsOnRealMember[i]; Annotation a = annotationX.getBcelAnnotation(); AnnotationGen ag = new AnnotationGen(a,weaver.getLazyClassGen().getConstantPoolGen(),true); mg.addAnnotation(new AnnotationX(ag.getAnnotation(),weaver.getWorld())); } } // the below loop fixes the very special (and very stupid) // case where an aspect declares an annotation // on an ITD it declared on itself. List allDecams = weaver.getWorld().getDeclareAnnotationOnMethods(); for (Iterator i = allDecams.iterator(); i.hasNext();){ DeclareAnnotation decaMC = (DeclareAnnotation) i.next(); if (decaMC.matches(explicitConstructor,weaver.getWorld()) && mg.getEnclosingClass().getType() == aspectType) { mg.addAnnotation(decaMC.getAnnotationX()); } } } currentClass.addMethodGen(mg); //weaver.addLazyMethodGen(freshConstructor); InstructionList body = mg.getBody(); // add to body: push arts for call to pre, from actual args starting at 1 (skipping this), going to // declared argcount + 1 UnresolvedType[] declaredParams = newConstructorTypeMunger.getSignature().getParameterTypes(); Type[] paramTypes = mg.getArgumentTypes(); int frameIndex = 1; for (int i = 0, len = declaredParams.length; i < len; i++) { body.append(InstructionFactory.createLoad(paramTypes[i], frameIndex)); frameIndex += paramTypes[i].getSize(); } // do call to pre Member preMethod = AjcMemberMaker.preIntroducedConstructor(aspectType, onType, declaredParams); body.append(Utility.createInvoke(fact, null, preMethod)); // create a local, and store return pre stuff into it. int arraySlot = mg.allocateLocal(1); body.append(InstructionFactory.createStore(Type.OBJECT, arraySlot)); // put this on the stack body.append(InstructionConstants.ALOAD_0); // unpack pre args onto stack UnresolvedType[] superParamTypes = explicitConstructor.getParameterTypes(); for (int i = 0, len = superParamTypes.length; i < len; i++) { body.append(InstructionFactory.createLoad(Type.OBJECT, arraySlot)); body.append(Utility.createConstant(fact, i)); body.append(InstructionFactory.createArrayLoad(Type.OBJECT)); body.append( Utility.createConversion( fact, Type.OBJECT, BcelWorld.makeBcelType(superParamTypes[i]))); } // call super/this body.append(Utility.createInvoke(fact, null, explicitConstructor)); // put this back on the stack body.append(InstructionConstants.ALOAD_0); // unpack params onto stack Member postMethod = AjcMemberMaker.postIntroducedConstructor(aspectType, onType, declaredParams); UnresolvedType[] postParamTypes = postMethod.getParameterTypes(); for (int i = 1, len = postParamTypes.length; i < len; i++) { body.append(InstructionFactory.createLoad(Type.OBJECT, arraySlot)); body.append(Utility.createConstant(fact, superParamTypes.length + i-1)); body.append(InstructionFactory.createArrayLoad(Type.OBJECT)); body.append( Utility.createConversion( fact, Type.OBJECT, BcelWorld.makeBcelType(postParamTypes[i]))); } // call post body.append(Utility.createInvoke(fact, null, postMethod)); // don't forget to return!! body.append(InstructionConstants.RETURN); return true; } private static LazyMethodGen makeDispatcher( LazyClassGen onGen, String dispatchName, ResolvedMember superMethod, BcelWorld world, boolean isSuper) { Type[] paramTypes = BcelWorld.makeBcelTypes(superMethod.getParameterTypes()); Type returnType = BcelWorld.makeBcelType(superMethod.getReturnType()); int modifiers = Modifier.PUBLIC; if (onGen.isInterface()) modifiers |= Modifier.ABSTRACT; LazyMethodGen mg = new LazyMethodGen( modifiers, returnType, dispatchName, paramTypes, UnresolvedType.getNames(superMethod.getExceptions()), onGen); InstructionList body = mg.getBody(); if (onGen.isInterface()) return mg; // assert (!superMethod.isStatic()) InstructionFactory fact = onGen.getFactory(); int pos = 0; body.append(InstructionFactory.createThis()); pos++; for (int i = 0, len = paramTypes.length; i < len; i++) { Type paramType = paramTypes[i]; body.append(InstructionFactory.createLoad(paramType, pos)); pos+=paramType.getSize(); } if (isSuper) { body.append(Utility.createSuperInvoke(fact, world, superMethod)); } else { body.append(Utility.createInvoke(fact, world, superMethod)); } body.append(InstructionFactory.createReturn(returnType)); return mg; } private boolean mungeNewField(BcelClassWeaver weaver, NewFieldTypeMunger munger) { /*ResolvedMember initMethod = */munger.getInitMethod(aspectType); LazyClassGen gen = weaver.getLazyClassGen(); ResolvedMember field = munger.getSignature(); ResolvedType onType = weaver.getWorld().resolve(field.getDeclaringType(),munger.getSourceLocation()); if (onType.isRawType()) onType = onType.getGenericType(); boolean onInterface = onType.isInterface(); if (onType.isAnnotation()) { signalError(WeaverMessages.ITDF_ON_ANNOTATION_NOT_ALLOWED,weaver,onType); return false; } if (onType.isEnum()) { signalError(WeaverMessages.ITDF_ON_ENUM_NOT_ALLOWED,weaver,onType); return false; } ResolvedMember interMethodBody = munger.getInitMethod(aspectType); AnnotationX annotationsOnRealMember[] = null; // pr98901 // For copying the annotations across, we have to discover the real member in the aspect // which is holding them. if (weaver.getWorld().isInJava5Mode()){ // the below line just gets the method with the same name in aspectType.getDeclaredMethods(); ResolvedType toLookOn = aspectType; if (aspectType.isRawType()) toLookOn = aspectType.getGenericType(); ResolvedMember realMember = getRealMemberForITDFromAspect(toLookOn,interMethodBody,false); if (realMember==null) throw new BCException("Couldn't find ITD init member '"+ interMethodBody+"' on aspect "+aspectType); annotationsOnRealMember = realMember.getAnnotations(); } if (onType.equals(gen.getType())) { if (onInterface) { ResolvedMember itdfieldGetter = AjcMemberMaker.interFieldInterfaceGetter(field, onType, aspectType); LazyMethodGen mg = makeMethodGen(gen, itdfieldGetter); gen.addMethodGen(mg); LazyMethodGen mg1 = makeMethodGen(gen, AjcMemberMaker.interFieldInterfaceSetter(field, onType, aspectType)); gen.addMethodGen(mg1); } else { weaver.addInitializer(this); FieldGen fg = makeFieldGen(gen, AjcMemberMaker.interFieldClassField(field, aspectType)); if (annotationsOnRealMember!=null) { for (int i = 0; i < annotationsOnRealMember.length; i++) { AnnotationX annotationX = annotationsOnRealMember[i]; Annotation a = annotationX.getBcelAnnotation(); AnnotationGen ag = new AnnotationGen(a,weaver.getLazyClassGen().getConstantPoolGen(),true); fg.addAnnotation(ag); } } gen.addField(fg.getField(),getSourceLocation()); } return true; } else if (onInterface && gen.getType().isTopmostImplementor(onType)) { // wew know that we can't be static since we don't allow statics on interfaces if (field.isStatic()) throw new RuntimeException("unimplemented"); weaver.addInitializer(this); //System.err.println("impl body on " + gen.getType() + " for " + munger); Type fieldType = BcelWorld.makeBcelType(field.getType()); FieldGen fg = makeFieldGen(gen,AjcMemberMaker.interFieldInterfaceField(field, onType, aspectType)); if (annotationsOnRealMember!=null) { for (int i = 0; i < annotationsOnRealMember.length; i++) { AnnotationX annotationX = annotationsOnRealMember[i]; Annotation a = annotationX.getBcelAnnotation(); AnnotationGen ag = new AnnotationGen(a,weaver.getLazyClassGen().getConstantPoolGen(),true); fg.addAnnotation(ag); } } gen.addField(fg.getField(),getSourceLocation()); //this uses a shadow munger to add init method to constructors //weaver.getShadowMungers().add(makeInitCallShadowMunger(initMethod)); ResolvedMember itdfieldGetter = AjcMemberMaker.interFieldInterfaceGetter(field, gen.getType()/*onType*/, aspectType); LazyMethodGen mg = makeMethodGen(gen, itdfieldGetter); InstructionList il = new InstructionList(); InstructionFactory fact = gen.getFactory(); if (field.isStatic()) { il.append(fact.createFieldAccess( gen.getClassName(), fg.getName(), fieldType, Constants.GETSTATIC)); } else { il.append(InstructionConstants.ALOAD_0); il.append(fact.createFieldAccess( gen.getClassName(), fg.getName(), fieldType, Constants.GETFIELD)); } il.append(InstructionFactory.createReturn(fieldType)); mg.getBody().insert(il); gen.addMethodGen(mg); // Check if we need bridge methods for the field getter and setter if (munger.getDeclaredSignature()!=null) { // is this munger a parameterized form of some original munger? ResolvedMember toBridgeTo = munger.getDeclaredSignature().parameterizedWith(null,munger.getSignature().getDeclaringType().resolve(getWorld()),false,munger.getTypeVariableAliases()); boolean needsbridging = false; if (!toBridgeTo.getReturnType().getErasureSignature().equals(munger.getSignature().getReturnType().getErasureSignature())) needsbridging = true; if (toBridgeTo!=null && needsbridging) { ResolvedMember bridgingGetter = AjcMemberMaker.interFieldInterfaceGetter(toBridgeTo, gen.getType(), aspectType); createBridgeMethodForITDF(weaver,gen,itdfieldGetter,bridgingGetter); } } ResolvedMember itdfieldSetter = AjcMemberMaker.interFieldInterfaceSetter(field, gen.getType(), aspectType); LazyMethodGen mg1 = makeMethodGen(gen, itdfieldSetter); InstructionList il1 = new InstructionList(); if (field.isStatic()) { il1.append(InstructionFactory.createLoad(fieldType, 0)); il1.append(fact.createFieldAccess( gen.getClassName(), fg.getName(), fieldType, Constants.PUTSTATIC)); } else { il1.append(InstructionConstants.ALOAD_0); il1.append(InstructionFactory.createLoad(fieldType, 1)); il1.append(fact.createFieldAccess( gen.getClassName(), fg.getName(), fieldType, Constants.PUTFIELD)); } il1.append(InstructionFactory.createReturn(Type.VOID)); mg1.getBody().insert(il1); gen.addMethodGen(mg1); if (munger.getDeclaredSignature()!=null) { ResolvedMember toBridgeTo = munger.getDeclaredSignature().parameterizedWith(null,munger.getSignature().getDeclaringType().resolve(getWorld()),false,munger.getTypeVariableAliases()); boolean needsbridging = false; if (!toBridgeTo.getReturnType().getErasureSignature().equals(munger.getSignature().getReturnType().getErasureSignature())) needsbridging = true; if (toBridgeTo!=null && needsbridging) { ResolvedMember bridgingSetter = AjcMemberMaker.interFieldInterfaceSetter(toBridgeTo, gen.getType(), aspectType); createBridgeMethodForITDF(weaver, gen, itdfieldSetter, bridgingSetter); } } return true; } else { return false; } } // FIXME asc combine with other createBridge.. method in this class, avoid the duplication... private void createBridgeMethodForITDF(BcelClassWeaver weaver, LazyClassGen gen, ResolvedMember itdfieldSetter, ResolvedMember bridgingSetter) { InstructionFactory fact; LazyMethodGen bridgeMethod = makeMethodGen(gen,bridgingSetter); Type[] paramTypes = BcelWorld.makeBcelTypes(bridgingSetter.getParameterTypes()); Type[] bridgingToParms = BcelWorld.makeBcelTypes(itdfieldSetter.getParameterTypes()); Type returnType = BcelWorld.makeBcelType(bridgingSetter.getReturnType()); InstructionList body = bridgeMethod.getBody(); fact = gen.getFactory(); int pos = 0; if (!bridgingSetter.isStatic()) { body.append(InstructionFactory.createThis()); pos++; } for (int i = 0, len = paramTypes.length; i < len; i++) { Type paramType = paramTypes[i]; body.append(InstructionFactory.createLoad(paramType, pos)); if (!bridgingSetter.getParameterTypes()[i].getErasureSignature().equals(itdfieldSetter.getParameterTypes()[i].getErasureSignature()) ) { // une cast est required System.err.println("Putting in cast from "+paramType+" to "+bridgingToParms[i]); body.append(fact.createCast(paramType,bridgingToParms[i])); } pos+=paramType.getSize(); } body.append(Utility.createInvoke(fact, weaver.getWorld(), itdfieldSetter)); body.append(InstructionFactory.createReturn(returnType)); gen.addMethodGen(bridgeMethod); } public ConcreteTypeMunger parameterizedFor(ResolvedType target) { return new BcelTypeMunger(munger.parameterizedFor(target),aspectType); } /** * Returns a list of type variable aliases used in this munger. For example, if the * ITD is 'int I<A,B>.m(List<A> las,List<B> lbs) {}' then this returns a list containing * the strings "A" and "B". */ public List /*String*/ getTypeVariableAliases() { return munger.getTypeVariableAliases(); } public boolean equals(Object other) { if (! (other instanceof BcelTypeMunger)) return false; BcelTypeMunger o = (BcelTypeMunger) other; return ((o.getMunger() == null) ? (getMunger() == null) : o.getMunger().equals(getMunger())) && ((o.getAspectType() == null) ? (getAspectType() == null) : o.getAspectType().equals(getAspectType())) && (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; public int hashCode() { if (hashCode == 0) { int result = 17; result = 37*result + ((getMunger() == null) ? 0 : getMunger().hashCode()); result = 37*result + ((getAspectType() == null) ? 0 : getAspectType().hashCode()); hashCode = result; } return hashCode; } /** * Some type mungers are created purely to help with the implementation of shadow mungers. * For example to support the cflow() pointcut we create a new cflow field in the aspect, and * that is added via a BcelCflowCounterFieldAdder. * * During compilation we need to compare sets of type mungers, and if some only come into * existence after the 'shadowy' type things have been processed, we need to ignore * them during the comparison. * * Returning true from this method indicates the type munger exists to support 'shadowy' stuff - * and so can be ignored in some comparison. */ public boolean existsToSupportShadowMunging() { if (munger != null) { return munger.existsToSupportShadowMunging(); } return false; } }
161,502
Bug 161502 UnsupportedOperationException thrown: unable to parameterize unresolved type: Pjava/util/List<+Ljava/lang/Object; >;
Generic parameters (like List<? extends T>) in pointcuts throw UnsupportedOperationException. java.lang.UnsupportedOperationException at org.aspectj.weaver.UnresolvedType.parameterize(UnresolvedType.java: 220) at org.aspectj.weaver.patterns.ExactTypePattern.parameterizeWith (ExactTypePattern.java:244) at org.aspectj.weaver.patterns.SignaturePattern.parameterizeWith (SignaturePattern.java:265) at org.aspectj.weaver.patterns.KindedPointcut.parameterizeWith (KindedPointcut.java:381) at org.aspectj.weaver.bcel.BcelAdvice.parameterizeWith (BcelAdvice.java:93) at org.aspectj.weaver.ResolvedType.getDeclaredAdvice (ResolvedType.java:710) at org.aspectj.weaver.ResolvedType.getDeclaredShadowMungers (ResolvedType.java:739) at org.aspectj.weaver.ResolvedType.collectShadowMungers (ResolvedType.java:575) at org.aspectj.weaver.ResolvedType.collectCrosscuttingMembers (ResolvedType.java:504) at org.aspectj.weaver.CrosscuttingMembersSet.addOrReplaceAspect (CrosscuttingMembersSet.java:68) at org.aspectj.weaver.CrosscuttingMembersSet.addOrReplaceAspect (CrosscuttingMembersSet.java:57) at org.aspectj.weaver.bcel.BcelWeaver.prepareForWeave(BcelWeaver.java: 450) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.weave (AjCompilerAdapter.java:299) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.afterCompiling (AjCompilerAdapter.java:192) at org.aspectj.ajdt.internal.compiler.CompilerAdapter.ajc $afterReturning$org_aspectj_ajdt_internal_compiler_CompilerAdapter$2 $f9cc9ca0(CompilerAdapter.aj:70) at org.aspectj.org.eclipse.jdt.internal.compiler.Compiler.compile (Compiler.java:367) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.performCompilation (AjBuildManager.java:887) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.doBuild (AjBuildManager.java:244) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.batchBuild (AjBuildManager.java:163) at org.aspectj.ajde.internal.CompilerAdapter.compile (CompilerAdapter.java:122) at org.aspectj.ajde.internal.AspectJBuildManager$CompilerThread.run (AspectJBuildManager.java:191) UnsupportedOperationException thrown: unable to parameterize unresolved type: Pjava/util/List<+Ljava/lang/Object;>; To reproduce this exception compile the following code snippet. import java.util.ArrayList; import java.util.List; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; public class Main { public List<? extends Element> getElements() { return new ArrayList<Element>(); } class Element {}; @Aspect static abstract class Base<T> { @Around("call(List<? extends T> *.*(..))") public List<? extends T> elementList(ProceedingJoinPoint thisJoinPoint) { try { return (List<? extends T>)thisJoinPoint.proceed(); } catch (Throwable e) { throw new RuntimeException(e); } } } @Aspect static class Concrete extends Base<Element> {} public static void main(String[] args) { new Main().getElements(); } }
resolved fixed
7b40e7e
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2006-10-24T12:42:57Z"
"2006-10-19T01:06:40Z"
weaver/src/org/aspectj/weaver/internal/tools/PointcutDesignatorHandlerBasedPointcut.java
/* ******************************************************************* * Copyright (c) 2005 Contributors. * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Eclipse Public License v1.0 * which accompanies this distribution and is available at * http://eclipse.org/legal/epl-v10.html * * Contributors: * Adrian Colyer Initial implementation * ******************************************************************/ package org.aspectj.weaver.internal.tools; import java.io.DataOutputStream; import java.io.IOException; import java.util.Map; import org.aspectj.util.FuzzyBoolean; import org.aspectj.weaver.IntMap; import org.aspectj.weaver.ResolvedType; import org.aspectj.weaver.Shadow; import org.aspectj.weaver.ast.Literal; import org.aspectj.weaver.ast.Test; import org.aspectj.weaver.patterns.Bindings; import org.aspectj.weaver.patterns.ExposedState; import org.aspectj.weaver.patterns.FastMatchInfo; import org.aspectj.weaver.patterns.IScope; import org.aspectj.weaver.patterns.PatternNodeVisitor; import org.aspectj.weaver.patterns.Pointcut; import org.aspectj.weaver.reflect.ReflectionFastMatchInfo; import org.aspectj.weaver.reflect.ReflectionShadow; import org.aspectj.weaver.reflect.ReflectionWorld; import org.aspectj.weaver.tools.ContextBasedMatcher; import org.aspectj.weaver.tools.MatchingContext; /** * Implementation of Pointcut that is backed by a user-extension * pointcut designator handler. * */ public class PointcutDesignatorHandlerBasedPointcut extends Pointcut{ private final ContextBasedMatcher matcher; private final ReflectionWorld world; public PointcutDesignatorHandlerBasedPointcut( ContextBasedMatcher expr, ReflectionWorld world) { this.matcher = expr; this.world = world; } /* (non-Javadoc) * @see org.aspectj.weaver.patterns.Pointcut#getPointcutKind() */ public byte getPointcutKind() { return Pointcut.USER_EXTENSION; } /* (non-Javadoc) * @see org.aspectj.weaver.patterns.Pointcut#fastMatch(org.aspectj.weaver.patterns.FastMatchInfo) */ public FuzzyBoolean fastMatch(FastMatchInfo info) { if (info instanceof ReflectionFastMatchInfo) { try { return FuzzyBoolean.fromBoolean( this.matcher.couldMatchJoinPointsInType( Class.forName(info.getType().getName(),false,world.getClassLoader()), ((ReflectionFastMatchInfo)info).getMatchingContext()) ); } catch (ClassNotFoundException cnfEx) { return FuzzyBoolean.MAYBE; } } throw new IllegalStateException("Can only match user-extension pcds against Reflection FastMatchInfo objects"); } /* (non-Javadoc) * @see org.aspectj.weaver.patterns.Pointcut#couldMatchKinds() */ public int couldMatchKinds() { return Shadow.ALL_SHADOW_KINDS_BITS; } /* (non-Javadoc) * @see org.aspectj.weaver.patterns.Pointcut#matchInternal(org.aspectj.weaver.Shadow) */ protected FuzzyBoolean matchInternal(Shadow shadow) { if (shadow instanceof ReflectionShadow) { MatchingContext context = ((ReflectionShadow)shadow).getMatchingContext(); org.aspectj.weaver.tools.FuzzyBoolean match = this.matcher.matchesStatically(context); if (match == org.aspectj.weaver.tools.FuzzyBoolean.MAYBE) { return FuzzyBoolean.MAYBE; } else if (match == org.aspectj.weaver.tools.FuzzyBoolean.YES) { return FuzzyBoolean.YES; } else if (match == org.aspectj.weaver.tools.FuzzyBoolean.NO) { return FuzzyBoolean.NO; } } throw new IllegalStateException("Can only match user-extension pcds against Reflection shadows (not BCEL)"); } /* (non-Javadoc) * @see org.aspectj.weaver.patterns.Pointcut#resolveBindings(org.aspectj.weaver.patterns.IScope, org.aspectj.weaver.patterns.Bindings) */ protected void resolveBindings(IScope scope, Bindings bindings) { // no-op } /* (non-Javadoc) * @see org.aspectj.weaver.patterns.Pointcut#concretize1(org.aspectj.weaver.ResolvedType, org.aspectj.weaver.ResolvedType, org.aspectj.weaver.IntMap) */ protected Pointcut concretize1(ResolvedType inAspect, ResolvedType declaringType, IntMap bindings) { return this; } /* (non-Javadoc) * @see org.aspectj.weaver.patterns.Pointcut#findResidueInternal(org.aspectj.weaver.Shadow, org.aspectj.weaver.patterns.ExposedState) */ protected Test findResidueInternal(Shadow shadow, ExposedState state) { if (!this.matcher.mayNeedDynamicTest()) { return Literal.TRUE; } else { // could be more efficient here! matchInternal(shadow); return new MatchingContextBasedTest(this.matcher); } } /* (non-Javadoc) * @see org.aspectj.weaver.patterns.Pointcut#parameterizeWith(java.util.Map) */ public Pointcut parameterizeWith(Map typeVariableMap) { return this; } /* (non-Javadoc) * @see org.aspectj.weaver.patterns.PatternNode#write(java.io.DataOutputStream) */ public void write(DataOutputStream s) throws IOException { throw new UnsupportedOperationException("can't write custom pointcut designator expressions to stream"); } /* (non-Javadoc) * @see org.aspectj.weaver.patterns.PatternNode#accept(org.aspectj.weaver.patterns.PatternNodeVisitor, java.lang.Object) */ public Object accept(PatternNodeVisitor visitor, Object data) { //visitor.visit(this); // no-op? return data; } }
161,502
Bug 161502 UnsupportedOperationException thrown: unable to parameterize unresolved type: Pjava/util/List<+Ljava/lang/Object; >;
Generic parameters (like List<? extends T>) in pointcuts throw UnsupportedOperationException. java.lang.UnsupportedOperationException at org.aspectj.weaver.UnresolvedType.parameterize(UnresolvedType.java: 220) at org.aspectj.weaver.patterns.ExactTypePattern.parameterizeWith (ExactTypePattern.java:244) at org.aspectj.weaver.patterns.SignaturePattern.parameterizeWith (SignaturePattern.java:265) at org.aspectj.weaver.patterns.KindedPointcut.parameterizeWith (KindedPointcut.java:381) at org.aspectj.weaver.bcel.BcelAdvice.parameterizeWith (BcelAdvice.java:93) at org.aspectj.weaver.ResolvedType.getDeclaredAdvice (ResolvedType.java:710) at org.aspectj.weaver.ResolvedType.getDeclaredShadowMungers (ResolvedType.java:739) at org.aspectj.weaver.ResolvedType.collectShadowMungers (ResolvedType.java:575) at org.aspectj.weaver.ResolvedType.collectCrosscuttingMembers (ResolvedType.java:504) at org.aspectj.weaver.CrosscuttingMembersSet.addOrReplaceAspect (CrosscuttingMembersSet.java:68) at org.aspectj.weaver.CrosscuttingMembersSet.addOrReplaceAspect (CrosscuttingMembersSet.java:57) at org.aspectj.weaver.bcel.BcelWeaver.prepareForWeave(BcelWeaver.java: 450) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.weave (AjCompilerAdapter.java:299) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.afterCompiling (AjCompilerAdapter.java:192) at org.aspectj.ajdt.internal.compiler.CompilerAdapter.ajc $afterReturning$org_aspectj_ajdt_internal_compiler_CompilerAdapter$2 $f9cc9ca0(CompilerAdapter.aj:70) at org.aspectj.org.eclipse.jdt.internal.compiler.Compiler.compile (Compiler.java:367) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.performCompilation (AjBuildManager.java:887) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.doBuild (AjBuildManager.java:244) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.batchBuild (AjBuildManager.java:163) at org.aspectj.ajde.internal.CompilerAdapter.compile (CompilerAdapter.java:122) at org.aspectj.ajde.internal.AspectJBuildManager$CompilerThread.run (AspectJBuildManager.java:191) UnsupportedOperationException thrown: unable to parameterize unresolved type: Pjava/util/List<+Ljava/lang/Object;>; To reproduce this exception compile the following code snippet. import java.util.ArrayList; import java.util.List; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; public class Main { public List<? extends Element> getElements() { return new ArrayList<Element>(); } class Element {}; @Aspect static abstract class Base<T> { @Around("call(List<? extends T> *.*(..))") public List<? extends T> elementList(ProceedingJoinPoint thisJoinPoint) { try { return (List<? extends T>)thisJoinPoint.proceed(); } catch (Throwable e) { throw new RuntimeException(e); } } } @Aspect static class Concrete extends Base<Element> {} public static void main(String[] args) { new Main().getElements(); } }
resolved fixed
7b40e7e
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2006-10-24T12:42:57Z"
"2006-10-19T01:06:40Z"
weaver/src/org/aspectj/weaver/patterns/AndAnnotationTypePattern.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.DataOutputStream; import java.io.IOException; import java.util.Map; import org.aspectj.util.FuzzyBoolean; import org.aspectj.weaver.AnnotatedElement; import org.aspectj.weaver.ISourceContext; import org.aspectj.weaver.VersionedDataInputStream; import org.aspectj.weaver.World; /** * @author colyer * * TODO To change the template for this generated type comment go to * Window - Preferences - Java - Code Style - Code Templates */ public class AndAnnotationTypePattern extends AnnotationTypePattern { private AnnotationTypePattern left; private AnnotationTypePattern right; public AndAnnotationTypePattern(AnnotationTypePattern left, AnnotationTypePattern right) { this.left = left; this.right = right; setLocation(left.getSourceContext(), left.getStart(), right.getEnd()); } public FuzzyBoolean matches(AnnotatedElement annotated) { return left.matches(annotated).and(right.matches(annotated)); } public void resolve(World world) { left.resolve(world); right.resolve(world); } /* (non-Javadoc) * @see org.aspectj.weaver.patterns.AnnotationTypePattern#resolveBindings(org.aspectj.weaver.patterns.IScope, org.aspectj.weaver.patterns.Bindings, boolean) */ public AnnotationTypePattern resolveBindings(IScope scope, Bindings bindings, boolean allowBinding) { left = left.resolveBindings(scope,bindings,allowBinding); right =right.resolveBindings(scope,bindings,allowBinding); return this; } public AnnotationTypePattern parameterizeWith(Map typeVariableMap) { AnnotationTypePattern newLeft = left.parameterizeWith(typeVariableMap); AnnotationTypePattern newRight = right.parameterizeWith(typeVariableMap); AndAnnotationTypePattern ret = new AndAnnotationTypePattern(newLeft,newRight); ret.copyLocationFrom(this); return ret; } public static AnnotationTypePattern read(VersionedDataInputStream s, ISourceContext context) throws IOException { AnnotationTypePattern p = new AndAnnotationTypePattern( AnnotationTypePattern.read(s,context), AnnotationTypePattern.read(s,context)); p.readLocation(context,s); return p; } public void write(DataOutputStream s) throws IOException { s.writeByte(AnnotationTypePattern.AND); left.write(s); right.write(s); writeLocation(s); } public boolean equals(Object obj) { if (!(obj instanceof AndAnnotationTypePattern)) return false; AndAnnotationTypePattern other = (AndAnnotationTypePattern) obj; return (left.equals(other.left) && right.equals(other.right)); } public int hashCode() { int result = 17; result = result*37 + left.hashCode(); result = result*37 + right.hashCode(); return result; } public String toString() { return left.toString() + " " + right.toString(); } public AnnotationTypePattern getLeft() { return left; } public AnnotationTypePattern 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; } }
161,502
Bug 161502 UnsupportedOperationException thrown: unable to parameterize unresolved type: Pjava/util/List<+Ljava/lang/Object; >;
Generic parameters (like List<? extends T>) in pointcuts throw UnsupportedOperationException. java.lang.UnsupportedOperationException at org.aspectj.weaver.UnresolvedType.parameterize(UnresolvedType.java: 220) at org.aspectj.weaver.patterns.ExactTypePattern.parameterizeWith (ExactTypePattern.java:244) at org.aspectj.weaver.patterns.SignaturePattern.parameterizeWith (SignaturePattern.java:265) at org.aspectj.weaver.patterns.KindedPointcut.parameterizeWith (KindedPointcut.java:381) at org.aspectj.weaver.bcel.BcelAdvice.parameterizeWith (BcelAdvice.java:93) at org.aspectj.weaver.ResolvedType.getDeclaredAdvice (ResolvedType.java:710) at org.aspectj.weaver.ResolvedType.getDeclaredShadowMungers (ResolvedType.java:739) at org.aspectj.weaver.ResolvedType.collectShadowMungers (ResolvedType.java:575) at org.aspectj.weaver.ResolvedType.collectCrosscuttingMembers (ResolvedType.java:504) at org.aspectj.weaver.CrosscuttingMembersSet.addOrReplaceAspect (CrosscuttingMembersSet.java:68) at org.aspectj.weaver.CrosscuttingMembersSet.addOrReplaceAspect (CrosscuttingMembersSet.java:57) at org.aspectj.weaver.bcel.BcelWeaver.prepareForWeave(BcelWeaver.java: 450) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.weave (AjCompilerAdapter.java:299) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.afterCompiling (AjCompilerAdapter.java:192) at org.aspectj.ajdt.internal.compiler.CompilerAdapter.ajc $afterReturning$org_aspectj_ajdt_internal_compiler_CompilerAdapter$2 $f9cc9ca0(CompilerAdapter.aj:70) at org.aspectj.org.eclipse.jdt.internal.compiler.Compiler.compile (Compiler.java:367) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.performCompilation (AjBuildManager.java:887) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.doBuild (AjBuildManager.java:244) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.batchBuild (AjBuildManager.java:163) at org.aspectj.ajde.internal.CompilerAdapter.compile (CompilerAdapter.java:122) at org.aspectj.ajde.internal.AspectJBuildManager$CompilerThread.run (AspectJBuildManager.java:191) UnsupportedOperationException thrown: unable to parameterize unresolved type: Pjava/util/List<+Ljava/lang/Object;>; To reproduce this exception compile the following code snippet. import java.util.ArrayList; import java.util.List; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; public class Main { public List<? extends Element> getElements() { return new ArrayList<Element>(); } class Element {}; @Aspect static abstract class Base<T> { @Around("call(List<? extends T> *.*(..))") public List<? extends T> elementList(ProceedingJoinPoint thisJoinPoint) { try { return (List<? extends T>)thisJoinPoint.proceed(); } catch (Throwable e) { throw new RuntimeException(e); } } } @Aspect static class Concrete extends Base<Element> {} public static void main(String[] args) { new Main().getElements(); } }
resolved fixed
7b40e7e
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2006-10-24T12:42:57Z"
"2006-10-19T01:06:40Z"
weaver/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.DataOutputStream; import java.io.IOException; import java.util.Map; import org.aspectj.util.FuzzyBoolean; import org.aspectj.weaver.ISourceContext; import org.aspectj.weaver.IntMap; import org.aspectj.weaver.ResolvedType; import org.aspectj.weaver.Shadow; import org.aspectj.weaver.VersionedDataInputStream; import org.aspectj.weaver.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(DataOutputStream 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) { AndPointcut ret = new AndPointcut(left.parameterizeWith(typeVariableMap), right.parameterizeWith(typeVariableMap)); 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; } }
161,502
Bug 161502 UnsupportedOperationException thrown: unable to parameterize unresolved type: Pjava/util/List<+Ljava/lang/Object; >;
Generic parameters (like List<? extends T>) in pointcuts throw UnsupportedOperationException. java.lang.UnsupportedOperationException at org.aspectj.weaver.UnresolvedType.parameterize(UnresolvedType.java: 220) at org.aspectj.weaver.patterns.ExactTypePattern.parameterizeWith (ExactTypePattern.java:244) at org.aspectj.weaver.patterns.SignaturePattern.parameterizeWith (SignaturePattern.java:265) at org.aspectj.weaver.patterns.KindedPointcut.parameterizeWith (KindedPointcut.java:381) at org.aspectj.weaver.bcel.BcelAdvice.parameterizeWith (BcelAdvice.java:93) at org.aspectj.weaver.ResolvedType.getDeclaredAdvice (ResolvedType.java:710) at org.aspectj.weaver.ResolvedType.getDeclaredShadowMungers (ResolvedType.java:739) at org.aspectj.weaver.ResolvedType.collectShadowMungers (ResolvedType.java:575) at org.aspectj.weaver.ResolvedType.collectCrosscuttingMembers (ResolvedType.java:504) at org.aspectj.weaver.CrosscuttingMembersSet.addOrReplaceAspect (CrosscuttingMembersSet.java:68) at org.aspectj.weaver.CrosscuttingMembersSet.addOrReplaceAspect (CrosscuttingMembersSet.java:57) at org.aspectj.weaver.bcel.BcelWeaver.prepareForWeave(BcelWeaver.java: 450) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.weave (AjCompilerAdapter.java:299) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.afterCompiling (AjCompilerAdapter.java:192) at org.aspectj.ajdt.internal.compiler.CompilerAdapter.ajc $afterReturning$org_aspectj_ajdt_internal_compiler_CompilerAdapter$2 $f9cc9ca0(CompilerAdapter.aj:70) at org.aspectj.org.eclipse.jdt.internal.compiler.Compiler.compile (Compiler.java:367) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.performCompilation (AjBuildManager.java:887) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.doBuild (AjBuildManager.java:244) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.batchBuild (AjBuildManager.java:163) at org.aspectj.ajde.internal.CompilerAdapter.compile (CompilerAdapter.java:122) at org.aspectj.ajde.internal.AspectJBuildManager$CompilerThread.run (AspectJBuildManager.java:191) UnsupportedOperationException thrown: unable to parameterize unresolved type: Pjava/util/List<+Ljava/lang/Object;>; To reproduce this exception compile the following code snippet. import java.util.ArrayList; import java.util.List; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; public class Main { public List<? extends Element> getElements() { return new ArrayList<Element>(); } class Element {}; @Aspect static abstract class Base<T> { @Around("call(List<? extends T> *.*(..))") public List<? extends T> elementList(ProceedingJoinPoint thisJoinPoint) { try { return (List<? extends T>)thisJoinPoint.proceed(); } catch (Throwable e) { throw new RuntimeException(e); } } } @Aspect static class Concrete extends Base<Element> {} public static void main(String[] args) { new Main().getElements(); } }
resolved fixed
7b40e7e
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2006-10-24T12:42:57Z"
"2006-10-19T01:06:40Z"
weaver/src/org/aspectj/weaver/patterns/AndTypePattern.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.DataOutputStream; import java.io.IOException; import java.util.Map; import org.aspectj.util.FuzzyBoolean; import org.aspectj.weaver.ISourceContext; import org.aspectj.weaver.ResolvedType; import org.aspectj.weaver.VersionedDataInputStream; /** * left && right * * <p>any binding to formals is explicitly forbidden for any composite by the language * * @author Erik Hilsdale * @author Jim Hugunin */ public class AndTypePattern extends TypePattern { private TypePattern left, right; public AndTypePattern(TypePattern left, TypePattern right) { super(false,false); //?? we override all methods that care about includeSubtypes this.left = left; this.right = right; setLocation(left.getSourceContext(), left.getStart(), right.getEnd()); } protected boolean couldEverMatchSameTypesAs(TypePattern other) { return true; // don't dive into ands yet.... } public FuzzyBoolean matchesInstanceof(ResolvedType type) { return left.matchesInstanceof(type).and(right.matchesInstanceof(type)); } protected boolean matchesExactly(ResolvedType type) { //??? if these had side-effects, this sort-circuit could be a mistake return left.matchesExactly(type) && right.matchesExactly(type); } protected boolean matchesExactly(ResolvedType type, ResolvedType annotatedType) { return left.matchesExactly(type,annotatedType) && right.matchesExactly(type,annotatedType); } public boolean matchesStatically(ResolvedType type) { return left.matchesStatically(type) && right.matchesStatically(type); } public void setIsVarArgs(boolean isVarArgs) { this.isVarArgs = isVarArgs; left.setIsVarArgs(isVarArgs); right.setIsVarArgs(isVarArgs); } public void setAnnotationTypePattern(AnnotationTypePattern annPatt) { if (annPatt == AnnotationTypePattern.ANY) return; if (left.annotationPattern == AnnotationTypePattern.ANY) { left.setAnnotationTypePattern(annPatt); } else { left.setAnnotationTypePattern( new AndAnnotationTypePattern(left.annotationPattern,annPatt)); } if (right.annotationPattern == AnnotationTypePattern.ANY) { right.setAnnotationTypePattern(annPatt); } else { right.setAnnotationTypePattern( new AndAnnotationTypePattern(right.annotationPattern,annPatt)); } } public void write(DataOutputStream s) throws IOException { s.writeByte(TypePattern.AND); left.write(s); right.write(s); writeLocation(s); } public static TypePattern read(VersionedDataInputStream s, ISourceContext context) throws IOException { AndTypePattern ret = new AndTypePattern(TypePattern.read(s, context), TypePattern.read(s, context)); ret.readLocation(context, s); if (ret.left.isVarArgs && ret.right.isVarArgs) ret.isVarArgs = true; return ret; } public TypePattern resolveBindings( IScope scope, Bindings bindings, boolean allowBinding, boolean requireExactType) { if (requireExactType) return notExactType(scope); left = left.resolveBindings(scope, bindings, false, false); right = right.resolveBindings(scope, bindings, false, false); return this; } public TypePattern parameterizeWith(Map typeVariableMap) { TypePattern newLeft = left.parameterizeWith(typeVariableMap); TypePattern newRight = right.parameterizeWith(typeVariableMap); AndTypePattern ret = new AndTypePattern(newLeft,newRight); ret.copyLocationFrom(this); return ret; } public String toString() { StringBuffer buff = new StringBuffer(); if (annotationPattern != AnnotationTypePattern.ANY) { buff.append('('); buff.append(annotationPattern.toString()); buff.append(' '); } buff.append('('); buff.append(left.toString()); buff.append(" && "); buff.append(right.toString()); buff.append(')'); if (annotationPattern != AnnotationTypePattern.ANY) { buff.append(')'); } return buff.toString(); } public TypePattern getLeft() { return left; } public TypePattern getRight() { return right; } public boolean equals(Object obj) { if (! (obj instanceof AndTypePattern)) return false; AndTypePattern atp = (AndTypePattern) obj; return left.equals(atp.left) && right.equals(atp.right); } /* (non-Javadoc) * @see java.lang.Object#hashCode() */ public int hashCode() { int ret = 17; ret = ret + 37 * left.hashCode(); ret = ret + 37 * right.hashCode(); return ret; } 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; } }
161,502
Bug 161502 UnsupportedOperationException thrown: unable to parameterize unresolved type: Pjava/util/List<+Ljava/lang/Object; >;
Generic parameters (like List<? extends T>) in pointcuts throw UnsupportedOperationException. java.lang.UnsupportedOperationException at org.aspectj.weaver.UnresolvedType.parameterize(UnresolvedType.java: 220) at org.aspectj.weaver.patterns.ExactTypePattern.parameterizeWith (ExactTypePattern.java:244) at org.aspectj.weaver.patterns.SignaturePattern.parameterizeWith (SignaturePattern.java:265) at org.aspectj.weaver.patterns.KindedPointcut.parameterizeWith (KindedPointcut.java:381) at org.aspectj.weaver.bcel.BcelAdvice.parameterizeWith (BcelAdvice.java:93) at org.aspectj.weaver.ResolvedType.getDeclaredAdvice (ResolvedType.java:710) at org.aspectj.weaver.ResolvedType.getDeclaredShadowMungers (ResolvedType.java:739) at org.aspectj.weaver.ResolvedType.collectShadowMungers (ResolvedType.java:575) at org.aspectj.weaver.ResolvedType.collectCrosscuttingMembers (ResolvedType.java:504) at org.aspectj.weaver.CrosscuttingMembersSet.addOrReplaceAspect (CrosscuttingMembersSet.java:68) at org.aspectj.weaver.CrosscuttingMembersSet.addOrReplaceAspect (CrosscuttingMembersSet.java:57) at org.aspectj.weaver.bcel.BcelWeaver.prepareForWeave(BcelWeaver.java: 450) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.weave (AjCompilerAdapter.java:299) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.afterCompiling (AjCompilerAdapter.java:192) at org.aspectj.ajdt.internal.compiler.CompilerAdapter.ajc $afterReturning$org_aspectj_ajdt_internal_compiler_CompilerAdapter$2 $f9cc9ca0(CompilerAdapter.aj:70) at org.aspectj.org.eclipse.jdt.internal.compiler.Compiler.compile (Compiler.java:367) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.performCompilation (AjBuildManager.java:887) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.doBuild (AjBuildManager.java:244) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.batchBuild (AjBuildManager.java:163) at org.aspectj.ajde.internal.CompilerAdapter.compile (CompilerAdapter.java:122) at org.aspectj.ajde.internal.AspectJBuildManager$CompilerThread.run (AspectJBuildManager.java:191) UnsupportedOperationException thrown: unable to parameterize unresolved type: Pjava/util/List<+Ljava/lang/Object;>; To reproduce this exception compile the following code snippet. import java.util.ArrayList; import java.util.List; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; public class Main { public List<? extends Element> getElements() { return new ArrayList<Element>(); } class Element {}; @Aspect static abstract class Base<T> { @Around("call(List<? extends T> *.*(..))") public List<? extends T> elementList(ProceedingJoinPoint thisJoinPoint) { try { return (List<? extends T>)thisJoinPoint.proceed(); } catch (Throwable e) { throw new RuntimeException(e); } } } @Aspect static class Concrete extends Base<Element> {} public static void main(String[] args) { new Main().getElements(); } }
resolved fixed
7b40e7e
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2006-10-24T12:42:57Z"
"2006-10-19T01:06:40Z"
weaver/src/org/aspectj/weaver/patterns/AnnotationPatternList.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.DataOutputStream; import java.io.IOException; import java.util.List; import java.util.Map; import org.aspectj.util.FuzzyBoolean; import org.aspectj.weaver.ISourceContext; import org.aspectj.weaver.IntMap; import org.aspectj.weaver.ResolvedType; import org.aspectj.weaver.VersionedDataInputStream; import org.aspectj.weaver.World; /** * @author colyer * * TODO To change the template for this generated type comment go to * Window - Preferences - Java - Code Style - Code Templates */ public class AnnotationPatternList extends PatternNode { private AnnotationTypePattern[] typePatterns; int ellipsisCount = 0; public static final AnnotationPatternList EMPTY = new AnnotationPatternList(new AnnotationTypePattern[] {}); public static final AnnotationPatternList ANY = new AnnotationPatternList(new AnnotationTypePattern[] {AnnotationTypePattern.ELLIPSIS}); public AnnotationPatternList() { typePatterns = new AnnotationTypePattern[0]; ellipsisCount = 0; } public AnnotationPatternList(AnnotationTypePattern[] arguments) { this.typePatterns = arguments; for (int i=0; i<arguments.length; i++) { if (arguments[i] == AnnotationTypePattern.ELLIPSIS) ellipsisCount++; } } public AnnotationPatternList(List l) { this((AnnotationTypePattern[]) l.toArray(new AnnotationTypePattern[l.size()])); } protected AnnotationTypePattern[] getAnnotationPatterns() { return typePatterns; } public AnnotationPatternList parameterizeWith(Map typeVariableMap) { AnnotationTypePattern[] parameterizedPatterns = new AnnotationTypePattern[this.typePatterns.length]; for (int i = 0; i < parameterizedPatterns.length; i++) { parameterizedPatterns[i] = this.typePatterns[i].parameterizeWith(typeVariableMap); } AnnotationPatternList ret = new AnnotationPatternList(parameterizedPatterns); ret.copyLocationFrom(this); return ret; } public void resolve(World inWorld) { for (int i = 0; i < typePatterns.length; i++) { typePatterns[i].resolve(inWorld); } } public FuzzyBoolean matches(ResolvedType[] someArgs) { // do some quick length tests first int numArgsMatchedByEllipsis = (someArgs.length + ellipsisCount) - typePatterns.length; if (numArgsMatchedByEllipsis < 0) return FuzzyBoolean.NO; if ((numArgsMatchedByEllipsis > 0) && (ellipsisCount == 0)) { return FuzzyBoolean.NO; } // now work through the args and the patterns, skipping at ellipsis FuzzyBoolean ret = FuzzyBoolean.YES; int argsIndex = 0; for (int i = 0; i < typePatterns.length; i++) { if (typePatterns[i] == AnnotationTypePattern.ELLIPSIS) { // match ellipsisMatchCount args argsIndex += numArgsMatchedByEllipsis; } else if (typePatterns[i] == AnnotationTypePattern.ANY) { argsIndex++; } else { // match the argument type at argsIndex with the ExactAnnotationTypePattern // we know it is exact because nothing else is allowed in args if (someArgs[argsIndex].isPrimitiveType()) return FuzzyBoolean.NO; // can never match ExactAnnotationTypePattern ap = (ExactAnnotationTypePattern)typePatterns[i]; FuzzyBoolean matches = ap.matchesRuntimeType(someArgs[argsIndex]); if (matches == FuzzyBoolean.NO) { return FuzzyBoolean.MAYBE; // could still match at runtime } else { argsIndex++; ret = ret.and(matches); } } } return ret; } public int size() { return typePatterns.length; } public AnnotationTypePattern get(int index) { return typePatterns[index]; } public AnnotationPatternList resolveBindings(IScope scope, Bindings bindings, boolean allowBinding) { for (int i=0; i<typePatterns.length; i++) { AnnotationTypePattern p = typePatterns[i]; if (p != null) { typePatterns[i] = typePatterns[i].resolveBindings(scope, bindings, allowBinding); } } return this; } public AnnotationPatternList resolveReferences(IntMap bindings) { int len = typePatterns.length; AnnotationTypePattern[] ret = new AnnotationTypePattern[len]; for (int i=0; i < len; i++) { ret[i] = typePatterns[i].remapAdviceFormals(bindings); } return new AnnotationPatternList(ret); } public String toString() { StringBuffer buf = new StringBuffer(); buf.append("("); for (int i=0, len=typePatterns.length; i < len; i++) { AnnotationTypePattern type = typePatterns[i]; if (i > 0) buf.append(", "); if (type == AnnotationTypePattern.ELLIPSIS) { buf.append(".."); } else { String annPatt = type.toString(); buf.append(annPatt.startsWith("@") ? annPatt.substring(1) : annPatt); } } buf.append(")"); return buf.toString(); } public boolean equals(Object other) { if (!(other instanceof AnnotationPatternList)) return false; AnnotationPatternList o = (AnnotationPatternList)other; int len = o.typePatterns.length; if (len != this.typePatterns.length) return false; for (int i=0; i<len; i++) { if (!this.typePatterns[i].equals(o.typePatterns[i])) return false; } return true; } public int hashCode() { int result = 41; for (int i = 0, len = typePatterns.length; i < len; i++) { result = 37*result + typePatterns[i].hashCode(); } return result; } public static AnnotationPatternList read(VersionedDataInputStream s, ISourceContext context) throws IOException { short len = s.readShort(); AnnotationTypePattern[] arguments = new AnnotationTypePattern[len]; for (int i=0; i<len; i++) { arguments[i] = AnnotationTypePattern.read(s, context); } AnnotationPatternList ret = new AnnotationPatternList(arguments); ret.readLocation(context, s); return ret; } public void write(DataOutputStream s) throws IOException { s.writeShort(typePatterns.length); for (int i=0; i<typePatterns.length; i++) { typePatterns[i].write(s); } writeLocation(s); } public Object accept(PatternNodeVisitor visitor, Object data) { return visitor.visit(this, data); } public Object traverse(PatternNodeVisitor visitor, Object data) { Object ret = accept(visitor, data); for (int i = 0; i < typePatterns.length; i++) { typePatterns[i].traverse(visitor,ret); } return ret; } }
161,502
Bug 161502 UnsupportedOperationException thrown: unable to parameterize unresolved type: Pjava/util/List<+Ljava/lang/Object; >;
Generic parameters (like List<? extends T>) in pointcuts throw UnsupportedOperationException. java.lang.UnsupportedOperationException at org.aspectj.weaver.UnresolvedType.parameterize(UnresolvedType.java: 220) at org.aspectj.weaver.patterns.ExactTypePattern.parameterizeWith (ExactTypePattern.java:244) at org.aspectj.weaver.patterns.SignaturePattern.parameterizeWith (SignaturePattern.java:265) at org.aspectj.weaver.patterns.KindedPointcut.parameterizeWith (KindedPointcut.java:381) at org.aspectj.weaver.bcel.BcelAdvice.parameterizeWith (BcelAdvice.java:93) at org.aspectj.weaver.ResolvedType.getDeclaredAdvice (ResolvedType.java:710) at org.aspectj.weaver.ResolvedType.getDeclaredShadowMungers (ResolvedType.java:739) at org.aspectj.weaver.ResolvedType.collectShadowMungers (ResolvedType.java:575) at org.aspectj.weaver.ResolvedType.collectCrosscuttingMembers (ResolvedType.java:504) at org.aspectj.weaver.CrosscuttingMembersSet.addOrReplaceAspect (CrosscuttingMembersSet.java:68) at org.aspectj.weaver.CrosscuttingMembersSet.addOrReplaceAspect (CrosscuttingMembersSet.java:57) at org.aspectj.weaver.bcel.BcelWeaver.prepareForWeave(BcelWeaver.java: 450) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.weave (AjCompilerAdapter.java:299) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.afterCompiling (AjCompilerAdapter.java:192) at org.aspectj.ajdt.internal.compiler.CompilerAdapter.ajc $afterReturning$org_aspectj_ajdt_internal_compiler_CompilerAdapter$2 $f9cc9ca0(CompilerAdapter.aj:70) at org.aspectj.org.eclipse.jdt.internal.compiler.Compiler.compile (Compiler.java:367) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.performCompilation (AjBuildManager.java:887) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.doBuild (AjBuildManager.java:244) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.batchBuild (AjBuildManager.java:163) at org.aspectj.ajde.internal.CompilerAdapter.compile (CompilerAdapter.java:122) at org.aspectj.ajde.internal.AspectJBuildManager$CompilerThread.run (AspectJBuildManager.java:191) UnsupportedOperationException thrown: unable to parameterize unresolved type: Pjava/util/List<+Ljava/lang/Object;>; To reproduce this exception compile the following code snippet. import java.util.ArrayList; import java.util.List; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; public class Main { public List<? extends Element> getElements() { return new ArrayList<Element>(); } class Element {}; @Aspect static abstract class Base<T> { @Around("call(List<? extends T> *.*(..))") public List<? extends T> elementList(ProceedingJoinPoint thisJoinPoint) { try { return (List<? extends T>)thisJoinPoint.proceed(); } catch (Throwable e) { throw new RuntimeException(e); } } } @Aspect static class Concrete extends Base<Element> {} public static void main(String[] args) { new Main().getElements(); } }
resolved fixed
7b40e7e
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2006-10-24T12:42:57Z"
"2006-10-19T01:06:40Z"
weaver/src/org/aspectj/weaver/patterns/AnnotationPointcut.java
/* ******************************************************************* * Copyright (c) 2004 IBM Corporation. * All rights reserved. * This program and the accompanying materials are made available * under the terms of the 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.DataOutputStream; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.Map; import org.aspectj.bridge.MessageUtil; import org.aspectj.util.FuzzyBoolean; import org.aspectj.weaver.AjcMemberMaker; import org.aspectj.weaver.AnnotatedElement; import org.aspectj.weaver.ISourceContext; import org.aspectj.weaver.IntMap; import org.aspectj.weaver.Member; import org.aspectj.weaver.NameMangler; import org.aspectj.weaver.NewFieldTypeMunger; import org.aspectj.weaver.ResolvedMember; import org.aspectj.weaver.ResolvedType; import org.aspectj.weaver.Shadow; import org.aspectj.weaver.ShadowMunger; import org.aspectj.weaver.UnresolvedType; import org.aspectj.weaver.VersionedDataInputStream; import org.aspectj.weaver.WeaverMessages; import org.aspectj.weaver.ast.Literal; import org.aspectj.weaver.ast.Test; import org.aspectj.weaver.ast.Var; import org.aspectj.weaver.bcel.BcelTypeMunger; /** * @annotation(@Foo) or @annotation(foo) * * Matches any join point where the subject of the join point has an * annotation matching the annotationTypePattern: * * Join Point Kind Subject * ================================ * method call the target method * method execution the method * constructor call the constructor * constructor execution the constructor * get the target field * set the target field * adviceexecution the advice * initialization the constructor * preinitialization the constructor * staticinitialization the type being initialized * handler the declared type of the handled exception */ public class AnnotationPointcut extends NameBindingPointcut { private ExactAnnotationTypePattern annotationTypePattern; private ShadowMunger munger = null; // only set after concretization private String declarationText; public AnnotationPointcut(ExactAnnotationTypePattern type) { super(); this.annotationTypePattern = type; this.pointcutKind = Pointcut.ANNOTATION; buildDeclarationText(); } public AnnotationPointcut(ExactAnnotationTypePattern type, ShadowMunger munger) { this(type); this.munger = munger; buildDeclarationText(); } public ExactAnnotationTypePattern getAnnotationTypePattern() { return annotationTypePattern; } public int couldMatchKinds() { return Shadow.ALL_SHADOW_KINDS_BITS; } public Pointcut parameterizeWith(Map typeVariableMap) { AnnotationPointcut ret = new AnnotationPointcut((ExactAnnotationTypePattern)annotationTypePattern.parameterizeWith(typeVariableMap)); ret.copyLocationFrom(this); return ret; } /* (non-Javadoc) * @see org.aspectj.weaver.patterns.Pointcut#fastMatch(org.aspectj.weaver.patterns.FastMatchInfo) */ public FuzzyBoolean fastMatch(FastMatchInfo info) { if (info.getKind() == Shadow.StaticInitialization) { return annotationTypePattern.fastMatches(info.getType()); } else { return FuzzyBoolean.MAYBE; } } /* (non-Javadoc) * @see org.aspectj.weaver.patterns.Pointcut#match(org.aspectj.weaver.Shadow) */ protected FuzzyBoolean matchInternal(Shadow shadow) { AnnotatedElement toMatchAgainst = null; Member member = shadow.getSignature(); ResolvedMember rMember = member.resolve(shadow.getIWorld()); if (rMember == null) { if (member.getName().startsWith(NameMangler.PREFIX)) { return FuzzyBoolean.NO; } shadow.getIWorld().getLint().unresolvableMember.signal(member.toString(), getSourceLocation()); return FuzzyBoolean.NO; } Shadow.Kind kind = shadow.getKind(); if (kind == Shadow.StaticInitialization) { toMatchAgainst = rMember.getDeclaringType().resolve(shadow.getIWorld()); } else if ( (kind == Shadow.ExceptionHandler)) { toMatchAgainst = rMember.getParameterTypes()[0].resolve(shadow.getIWorld()); } else { toMatchAgainst = rMember; // FIXME asc I'd like to get rid of this bit of logic altogether, shame ITD fields don't have an effective sig attribute // FIXME asc perf cache the result of discovering the member that contains the real annotations if (rMember.isAnnotatedElsewhere()) { if (kind==Shadow.FieldGet || kind==Shadow.FieldSet) { List mungers = rMember.getDeclaringType().resolve(shadow.getIWorld()).getInterTypeMungers(); // FIXME asc should include supers with getInterTypeMungersIncludingSupers? for (Iterator iter = mungers.iterator(); iter.hasNext();) { BcelTypeMunger typeMunger = (BcelTypeMunger) iter.next(); if (typeMunger.getMunger() instanceof NewFieldTypeMunger) { ResolvedMember fakerm = typeMunger.getSignature(); if (fakerm.equals(member)) { ResolvedMember ajcMethod = AjcMemberMaker.interFieldInitializer(fakerm,typeMunger.getAspectType()); ResolvedMember rmm = findMethod(typeMunger.getAspectType(),ajcMethod); toMatchAgainst = rmm; } } } } } } annotationTypePattern.resolve(shadow.getIWorld()); return annotationTypePattern.matches(toMatchAgainst); } private ResolvedMember findMethod(ResolvedType aspectType, ResolvedMember ajcMethod) { ResolvedMember decMethods[] = aspectType.getDeclaredMethods(); for (int i = 0; i < decMethods.length; i++) { ResolvedMember member = decMethods[i]; if (member.equals(ajcMethod)) return member; } return null; } /* (non-Javadoc) * @see org.aspectj.weaver.patterns.Pointcut#resolveBindings(org.aspectj.weaver.patterns.IScope, org.aspectj.weaver.patterns.Bindings) */ protected void resolveBindings(IScope scope, Bindings bindings) { if (!scope.getWorld().isInJava5Mode()) { scope.message(MessageUtil.error(WeaverMessages.format(WeaverMessages.ATANNOTATION_ONLY_SUPPORTED_AT_JAVA5_LEVEL), getSourceLocation())); return; } annotationTypePattern = (ExactAnnotationTypePattern) annotationTypePattern.resolveBindings(scope,bindings,true); // must be either a Var, or an annotation type pattern } /* (non-Javadoc) * @see org.aspectj.weaver.patterns.Pointcut#concretize1(org.aspectj.weaver.ResolvedType, org.aspectj.weaver.IntMap) */ protected Pointcut concretize1(ResolvedType inAspect, ResolvedType declaringType, IntMap bindings) { ExactAnnotationTypePattern newType = (ExactAnnotationTypePattern) annotationTypePattern.remapAdviceFormals(bindings); Pointcut ret = new AnnotationPointcut(newType, bindings.getEnclosingAdvice()); ret.copyLocationFrom(this); return ret; } /* (non-Javadoc) * @see org.aspectj.weaver.patterns.Pointcut#findResidue(org.aspectj.weaver.Shadow, org.aspectj.weaver.patterns.ExposedState) */ protected Test findResidueInternal(Shadow shadow, ExposedState state) { if (annotationTypePattern instanceof BindingAnnotationTypePattern) { BindingAnnotationTypePattern btp = (BindingAnnotationTypePattern)annotationTypePattern; UnresolvedType annotationType = btp.getAnnotationType(); Var var = shadow.getKindedAnnotationVar(annotationType); // At this point, var *could* be null. The only reason this could happen (if we aren't failing...) // is if another binding annotation designator elsewhere in the pointcut is going to expose the annotation // eg. (execution(* a*(..)) && @annotation(foo)) || (execution(* b*(..)) && @this(foo)) // where sometimes @annotation will be providing the value, and sometimes // @this will be providing the value (see pr138223) // If we are here for other indecipherable reasons (it's not the case above...) then // you might want to uncomment this next bit of code to collect the diagnostics // if (var == null) throw new BCException("Impossible! annotation=["+annotationType+ // "] shadow=["+shadow+" at "+shadow.getSourceLocation()+ // "] pointcut is at ["+getSourceLocation()+"]"); if (var==null) { if (matchInternal(shadow).alwaysTrue()) return Literal.TRUE; else return Literal.FALSE; } state.set(btp.getFormalIndex(),var); } if (matchInternal(shadow).alwaysTrue()) return Literal.TRUE; else return Literal.FALSE; } /* (non-Javadoc) * @see org.aspectj.weaver.patterns.NameBindingPointcut#getBindingAnnotationTypePatterns() */ public List getBindingAnnotationTypePatterns() { if (annotationTypePattern instanceof BindingAnnotationTypePattern) { List l = new ArrayList(); l.add(annotationTypePattern); return l; } else return Collections.EMPTY_LIST; } /* (non-Javadoc) * @see org.aspectj.weaver.patterns.NameBindingPointcut#getBindingTypePatterns() */ public List getBindingTypePatterns() { return Collections.EMPTY_LIST; } /* (non-Javadoc) * @see org.aspectj.weaver.patterns.PatternNode#write(java.io.DataOutputStream) */ public void write(DataOutputStream s) throws IOException { s.writeByte(Pointcut.ANNOTATION); annotationTypePattern.write(s); writeLocation(s); } public static Pointcut read(VersionedDataInputStream s, ISourceContext context) throws IOException { AnnotationTypePattern type = AnnotationTypePattern.read(s, context); AnnotationPointcut ret = new AnnotationPointcut((ExactAnnotationTypePattern)type); ret.readLocation(context, s); return ret; } public boolean equals(Object other) { if (!(other instanceof AnnotationPointcut)) return false; AnnotationPointcut o = (AnnotationPointcut)other; return o.annotationTypePattern.equals(this.annotationTypePattern); } public int hashCode() { int result = 17; result = 37*result + annotationTypePattern.hashCode(); return result; } public void buildDeclarationText() { StringBuffer buf = new StringBuffer(); buf.append("@annotation("); String annPatt = annotationTypePattern.toString(); buf.append(annPatt.startsWith("@") ? annPatt.substring(1) : annPatt); buf.append(")"); this.declarationText = buf.toString(); } public String toString() { return this.declarationText; } public Object accept(PatternNodeVisitor visitor, Object data) { return visitor.visit(this, data); } }
161,502
Bug 161502 UnsupportedOperationException thrown: unable to parameterize unresolved type: Pjava/util/List<+Ljava/lang/Object; >;
Generic parameters (like List<? extends T>) in pointcuts throw UnsupportedOperationException. java.lang.UnsupportedOperationException at org.aspectj.weaver.UnresolvedType.parameterize(UnresolvedType.java: 220) at org.aspectj.weaver.patterns.ExactTypePattern.parameterizeWith (ExactTypePattern.java:244) at org.aspectj.weaver.patterns.SignaturePattern.parameterizeWith (SignaturePattern.java:265) at org.aspectj.weaver.patterns.KindedPointcut.parameterizeWith (KindedPointcut.java:381) at org.aspectj.weaver.bcel.BcelAdvice.parameterizeWith (BcelAdvice.java:93) at org.aspectj.weaver.ResolvedType.getDeclaredAdvice (ResolvedType.java:710) at org.aspectj.weaver.ResolvedType.getDeclaredShadowMungers (ResolvedType.java:739) at org.aspectj.weaver.ResolvedType.collectShadowMungers (ResolvedType.java:575) at org.aspectj.weaver.ResolvedType.collectCrosscuttingMembers (ResolvedType.java:504) at org.aspectj.weaver.CrosscuttingMembersSet.addOrReplaceAspect (CrosscuttingMembersSet.java:68) at org.aspectj.weaver.CrosscuttingMembersSet.addOrReplaceAspect (CrosscuttingMembersSet.java:57) at org.aspectj.weaver.bcel.BcelWeaver.prepareForWeave(BcelWeaver.java: 450) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.weave (AjCompilerAdapter.java:299) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.afterCompiling (AjCompilerAdapter.java:192) at org.aspectj.ajdt.internal.compiler.CompilerAdapter.ajc $afterReturning$org_aspectj_ajdt_internal_compiler_CompilerAdapter$2 $f9cc9ca0(CompilerAdapter.aj:70) at org.aspectj.org.eclipse.jdt.internal.compiler.Compiler.compile (Compiler.java:367) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.performCompilation (AjBuildManager.java:887) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.doBuild (AjBuildManager.java:244) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.batchBuild (AjBuildManager.java:163) at org.aspectj.ajde.internal.CompilerAdapter.compile (CompilerAdapter.java:122) at org.aspectj.ajde.internal.AspectJBuildManager$CompilerThread.run (AspectJBuildManager.java:191) UnsupportedOperationException thrown: unable to parameterize unresolved type: Pjava/util/List<+Ljava/lang/Object;>; To reproduce this exception compile the following code snippet. import java.util.ArrayList; import java.util.List; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; public class Main { public List<? extends Element> getElements() { return new ArrayList<Element>(); } class Element {}; @Aspect static abstract class Base<T> { @Around("call(List<? extends T> *.*(..))") public List<? extends T> elementList(ProceedingJoinPoint thisJoinPoint) { try { return (List<? extends T>)thisJoinPoint.proceed(); } catch (Throwable e) { throw new RuntimeException(e); } } } @Aspect static class Concrete extends Base<Element> {} public static void main(String[] args) { new Main().getElements(); } }
resolved fixed
7b40e7e
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2006-10-24T12:42:57Z"
"2006-10-19T01:06:40Z"
weaver/src/org/aspectj/weaver/patterns/AnnotationTypePattern.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.DataOutputStream; import java.io.IOException; import java.util.Map; import org.aspectj.util.FuzzyBoolean; import org.aspectj.weaver.AnnotatedElement; import org.aspectj.weaver.BCException; import org.aspectj.weaver.ISourceContext; import org.aspectj.weaver.IntMap; import org.aspectj.weaver.VersionedDataInputStream; import org.aspectj.weaver.World; public abstract class AnnotationTypePattern extends PatternNode { public static final AnnotationTypePattern ANY = new AnyAnnotationTypePattern(); public static final AnnotationTypePattern ELLIPSIS = new EllipsisAnnotationTypePattern(); /** * TODO: write, read, equals & hashcode both in annotation hierarachy and * in altered TypePattern hierarchy */ protected AnnotationTypePattern() { super(); } public abstract FuzzyBoolean matches(AnnotatedElement annotated); public FuzzyBoolean fastMatches(AnnotatedElement annotated) { return FuzzyBoolean.MAYBE; } public AnnotationTypePattern remapAdviceFormals(IntMap bindings) { return this; } public abstract void resolve(World world); public abstract AnnotationTypePattern parameterizeWith(Map/*name -> ResolvedType*/ typeVariableMap); public boolean isAny() { return false; } /** * This can modify in place, or return a new TypePattern if the type changes. */ public AnnotationTypePattern resolveBindings(IScope scope, Bindings bindings, boolean allowBinding) { return this; } public static final byte EXACT = 1; public static final byte BINDING = 2; public static final byte NOT = 3; public static final byte OR = 4; public static final byte AND = 5; public static final byte ELLIPSIS_KEY = 6; public static final byte ANY_KEY = 7; public static final byte WILD = 8; public static AnnotationTypePattern read(VersionedDataInputStream s, ISourceContext context) throws IOException { byte key = s.readByte(); switch(key) { case EXACT: return ExactAnnotationTypePattern.read(s, context); case BINDING: return BindingAnnotationTypePattern.read(s, context); case NOT: return NotAnnotationTypePattern.read(s, context); case OR: return OrAnnotationTypePattern.read(s, context); case AND: return AndAnnotationTypePattern.read(s, context); case WILD: return WildAnnotationTypePattern.read(s,context); case ELLIPSIS_KEY: return ELLIPSIS; case ANY_KEY: return ANY; } throw new BCException("unknown TypePattern kind: " + key); } } class AnyAnnotationTypePattern extends AnnotationTypePattern { public FuzzyBoolean fastMatches(AnnotatedElement annotated) { return FuzzyBoolean.YES; } public FuzzyBoolean matches(AnnotatedElement annotated) { return FuzzyBoolean.YES; } public void write(DataOutputStream s) throws IOException { s.writeByte(AnnotationTypePattern.ANY_KEY); } public void resolve(World world) { } public String toString() { return "@ANY"; } public Object accept(PatternNodeVisitor visitor, Object data) { return visitor.visit(this, data); } public boolean isAny() { return true; } public AnnotationTypePattern parameterizeWith(Map arg0) { return this; } } class EllipsisAnnotationTypePattern extends AnnotationTypePattern { public FuzzyBoolean matches(AnnotatedElement annotated) { return FuzzyBoolean.NO; } public void write(DataOutputStream s) throws IOException { s.writeByte(AnnotationTypePattern.ELLIPSIS_KEY); } public void resolve(World world) { } public String toString() { return ".."; } public Object accept(PatternNodeVisitor visitor, Object data) { return visitor.visit(this, data); } public AnnotationTypePattern parameterizeWith(Map arg0) { return this; } }
161,502
Bug 161502 UnsupportedOperationException thrown: unable to parameterize unresolved type: Pjava/util/List<+Ljava/lang/Object; >;
Generic parameters (like List<? extends T>) in pointcuts throw UnsupportedOperationException. java.lang.UnsupportedOperationException at org.aspectj.weaver.UnresolvedType.parameterize(UnresolvedType.java: 220) at org.aspectj.weaver.patterns.ExactTypePattern.parameterizeWith (ExactTypePattern.java:244) at org.aspectj.weaver.patterns.SignaturePattern.parameterizeWith (SignaturePattern.java:265) at org.aspectj.weaver.patterns.KindedPointcut.parameterizeWith (KindedPointcut.java:381) at org.aspectj.weaver.bcel.BcelAdvice.parameterizeWith (BcelAdvice.java:93) at org.aspectj.weaver.ResolvedType.getDeclaredAdvice (ResolvedType.java:710) at org.aspectj.weaver.ResolvedType.getDeclaredShadowMungers (ResolvedType.java:739) at org.aspectj.weaver.ResolvedType.collectShadowMungers (ResolvedType.java:575) at org.aspectj.weaver.ResolvedType.collectCrosscuttingMembers (ResolvedType.java:504) at org.aspectj.weaver.CrosscuttingMembersSet.addOrReplaceAspect (CrosscuttingMembersSet.java:68) at org.aspectj.weaver.CrosscuttingMembersSet.addOrReplaceAspect (CrosscuttingMembersSet.java:57) at org.aspectj.weaver.bcel.BcelWeaver.prepareForWeave(BcelWeaver.java: 450) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.weave (AjCompilerAdapter.java:299) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.afterCompiling (AjCompilerAdapter.java:192) at org.aspectj.ajdt.internal.compiler.CompilerAdapter.ajc $afterReturning$org_aspectj_ajdt_internal_compiler_CompilerAdapter$2 $f9cc9ca0(CompilerAdapter.aj:70) at org.aspectj.org.eclipse.jdt.internal.compiler.Compiler.compile (Compiler.java:367) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.performCompilation (AjBuildManager.java:887) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.doBuild (AjBuildManager.java:244) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.batchBuild (AjBuildManager.java:163) at org.aspectj.ajde.internal.CompilerAdapter.compile (CompilerAdapter.java:122) at org.aspectj.ajde.internal.AspectJBuildManager$CompilerThread.run (AspectJBuildManager.java:191) UnsupportedOperationException thrown: unable to parameterize unresolved type: Pjava/util/List<+Ljava/lang/Object;>; To reproduce this exception compile the following code snippet. import java.util.ArrayList; import java.util.List; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; public class Main { public List<? extends Element> getElements() { return new ArrayList<Element>(); } class Element {}; @Aspect static abstract class Base<T> { @Around("call(List<? extends T> *.*(..))") public List<? extends T> elementList(ProceedingJoinPoint thisJoinPoint) { try { return (List<? extends T>)thisJoinPoint.proceed(); } catch (Throwable e) { throw new RuntimeException(e); } } } @Aspect static class Concrete extends Base<Element> {} public static void main(String[] args) { new Main().getElements(); } }
resolved fixed
7b40e7e
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2006-10-24T12:42:57Z"
"2006-10-19T01:06:40Z"
weaver/src/org/aspectj/weaver/patterns/ArgsAnnotationPointcut.java
/* ******************************************************************* * Copyright (c) 2004 IBM Corporation. * All rights reserved. * This program and the accompanying materials are made available * under the terms of the 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.DataOutputStream; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map; import org.aspectj.bridge.IMessage; import org.aspectj.bridge.ISourceLocation; import org.aspectj.bridge.MessageUtil; import org.aspectj.util.FuzzyBoolean; import org.aspectj.weaver.ISourceContext; import org.aspectj.weaver.IntMap; import org.aspectj.weaver.ResolvedType; import org.aspectj.weaver.Shadow; import org.aspectj.weaver.UnresolvedType; import org.aspectj.weaver.VersionedDataInputStream; import org.aspectj.weaver.WeaverMessages; import org.aspectj.weaver.ast.Literal; import org.aspectj.weaver.ast.Test; import org.aspectj.weaver.ast.Var; /** * @author colyer * * TODO To change the template for this generated type comment go to * Window - Preferences - Java - Code Style - Code Templates */ public class ArgsAnnotationPointcut extends NameBindingPointcut { private AnnotationPatternList arguments; private String declarationText; /** * */ public ArgsAnnotationPointcut(AnnotationPatternList arguments) { super(); this.arguments = arguments; this.pointcutKind = ATARGS; buildDeclarationText(); } public AnnotationPatternList getArguments() { return arguments; } public int couldMatchKinds() { return Shadow.ALL_SHADOW_KINDS_BITS; // empty args() matches jps with no args } public Pointcut parameterizeWith(Map typeVariableMap) { ArgsAnnotationPointcut ret = new ArgsAnnotationPointcut(arguments.parameterizeWith(typeVariableMap)); ret.copyLocationFrom(this); return ret; } /* (non-Javadoc) * @see org.aspectj.weaver.patterns.Pointcut#fastMatch(org.aspectj.weaver.patterns.FastMatchInfo) */ public FuzzyBoolean fastMatch(FastMatchInfo info) { return FuzzyBoolean.MAYBE; } /* (non-Javadoc) * @see org.aspectj.weaver.patterns.Pointcut#match(org.aspectj.weaver.Shadow) */ protected FuzzyBoolean matchInternal(Shadow shadow) { arguments.resolve(shadow.getIWorld()); FuzzyBoolean ret = arguments.matches(shadow.getIWorld().resolve(shadow.getArgTypes())); return ret; } /* (non-Javadoc) * @see org.aspectj.weaver.patterns.Pointcut#resolveBindings(org.aspectj.weaver.patterns.IScope, org.aspectj.weaver.patterns.Bindings) */ protected void resolveBindings(IScope scope, Bindings bindings) { if (!scope.getWorld().isInJava5Mode()) { scope.message(MessageUtil.error(WeaverMessages.format(WeaverMessages.ATARGS_ONLY_SUPPORTED_AT_JAVA5_LEVEL), getSourceLocation())); return; } arguments.resolveBindings(scope, bindings, true); if (arguments.ellipsisCount > 1) { scope.message(IMessage.ERROR, this, "uses more than one .. in args (compiler limitation)"); } } /* (non-Javadoc) * @see org.aspectj.weaver.patterns.Pointcut#concretize1(org.aspectj.weaver.ResolvedType, org.aspectj.weaver.IntMap) */ protected Pointcut concretize1(ResolvedType inAspect, ResolvedType declaringType, IntMap bindings) { if (isDeclare(bindings.getEnclosingAdvice())) { // Enforce rule about which designators are supported in declare inAspect.getWorld().showMessage(IMessage.ERROR, WeaverMessages.format(WeaverMessages.ARGS_IN_DECLARE), bindings.getEnclosingAdvice().getSourceLocation(), null); return Pointcut.makeMatchesNothing(Pointcut.CONCRETE); } AnnotationPatternList list = arguments.resolveReferences(bindings); Pointcut ret = new ArgsAnnotationPointcut(list); ret.copyLocationFrom(this); return ret; } /* (non-Javadoc) * @see org.aspectj.weaver.patterns.Pointcut#findResidue(org.aspectj.weaver.Shadow, org.aspectj.weaver.patterns.ExposedState) */ protected Test findResidueInternal(Shadow shadow, ExposedState state) { int len = shadow.getArgCount(); // do some quick length tests first int numArgsMatchedByEllipsis = (len + arguments.ellipsisCount) - arguments.size(); if (numArgsMatchedByEllipsis < 0) return Literal.FALSE; // should never happen if ((numArgsMatchedByEllipsis > 0) && (arguments.ellipsisCount == 0)) { return Literal.FALSE; // should never happen } // now work through the args and the patterns, skipping at ellipsis Test ret = Literal.TRUE; int argsIndex = 0; for (int i = 0; i < arguments.size(); i++) { if (arguments.get(i) == AnnotationTypePattern.ELLIPSIS) { // match ellipsisMatchCount args argsIndex += numArgsMatchedByEllipsis; } else if (arguments.get(i) == AnnotationTypePattern.ANY) { argsIndex++; } else { // match the argument type at argsIndex with the ExactAnnotationTypePattern // we know it is exact because nothing else is allowed in args ExactAnnotationTypePattern ap = (ExactAnnotationTypePattern)arguments.get(i); UnresolvedType argType = shadow.getArgType(argsIndex); ResolvedType rArgType = argType.resolve(shadow.getIWorld()); if (rArgType.isMissing()) { shadow.getIWorld().getLint().cantFindType.signal( new String[] {WeaverMessages.format(WeaverMessages.CANT_FIND_TYPE_ARG_TYPE,argType.getName())}, shadow.getSourceLocation(), new ISourceLocation[]{getSourceLocation()} ); // IMessage msg = new Message( // WeaverMessages.format(WeaverMessages.CANT_FIND_TYPE_ARG_TYPE,argType.getName()), // "",IMessage.ERROR,shadow.getSourceLocation(),null,new ISourceLocation[]{getSourceLocation()}); } ResolvedType rAnnType = ap.getAnnotationType().resolve(shadow.getIWorld()); if (ap instanceof BindingAnnotationTypePattern) { BindingAnnotationTypePattern btp = (BindingAnnotationTypePattern)ap; Var annvar = shadow.getArgAnnotationVar(argsIndex,rAnnType); state.set(btp.getFormalIndex(),annvar); } if (!ap.matches(rArgType).alwaysTrue()) { // we need a test... ret = Test.makeAnd(ret, Test.makeHasAnnotation( shadow.getArgVar(argsIndex), rAnnType)); } argsIndex++; } } return ret; } /* (non-Javadoc) * @see org.aspectj.weaver.patterns.NameBindingPointcut#getBindingAnnotationTypePatterns() */ public List getBindingAnnotationTypePatterns() { List l = new ArrayList(); AnnotationTypePattern[] pats = arguments.getAnnotationPatterns(); for (int i = 0; i < pats.length; i++) { if (pats[i] instanceof BindingAnnotationTypePattern) { l.add(pats[i]); } } return l; } /* (non-Javadoc) * @see org.aspectj.weaver.patterns.NameBindingPointcut#getBindingTypePatterns() */ public List getBindingTypePatterns() { return Collections.EMPTY_LIST; } /* (non-Javadoc) * @see org.aspectj.weaver.patterns.PatternNode#write(java.io.DataOutputStream) */ public void write(DataOutputStream s) throws IOException { s.writeByte(Pointcut.ATARGS); arguments.write(s); writeLocation(s); } public static Pointcut read(VersionedDataInputStream s, ISourceContext context) throws IOException { AnnotationPatternList annotationPatternList = AnnotationPatternList.read(s,context); ArgsAnnotationPointcut ret = new ArgsAnnotationPointcut(annotationPatternList); ret.readLocation(context, s); return ret; } /* (non-Javadoc) * @see java.lang.Object#equals(java.lang.Object) */ public boolean equals(Object obj) { if (!(obj instanceof ArgsAnnotationPointcut)) return false; ArgsAnnotationPointcut other = (ArgsAnnotationPointcut) obj; return other.arguments.equals(arguments); } /* (non-Javadoc) * @see java.lang.Object#hashCode() */ public int hashCode() { return 17 + 37*arguments.hashCode(); } /* (non-Javadoc) * @see java.lang.Object#toString() */ private void buildDeclarationText() { StringBuffer buf = new StringBuffer("@args"); buf.append(arguments.toString()); this.declarationText = buf.toString(); } public String toString() { return this.declarationText; } public Object accept(PatternNodeVisitor visitor, Object data) { return visitor.visit(this, data); } }
161,502
Bug 161502 UnsupportedOperationException thrown: unable to parameterize unresolved type: Pjava/util/List<+Ljava/lang/Object; >;
Generic parameters (like List<? extends T>) in pointcuts throw UnsupportedOperationException. java.lang.UnsupportedOperationException at org.aspectj.weaver.UnresolvedType.parameterize(UnresolvedType.java: 220) at org.aspectj.weaver.patterns.ExactTypePattern.parameterizeWith (ExactTypePattern.java:244) at org.aspectj.weaver.patterns.SignaturePattern.parameterizeWith (SignaturePattern.java:265) at org.aspectj.weaver.patterns.KindedPointcut.parameterizeWith (KindedPointcut.java:381) at org.aspectj.weaver.bcel.BcelAdvice.parameterizeWith (BcelAdvice.java:93) at org.aspectj.weaver.ResolvedType.getDeclaredAdvice (ResolvedType.java:710) at org.aspectj.weaver.ResolvedType.getDeclaredShadowMungers (ResolvedType.java:739) at org.aspectj.weaver.ResolvedType.collectShadowMungers (ResolvedType.java:575) at org.aspectj.weaver.ResolvedType.collectCrosscuttingMembers (ResolvedType.java:504) at org.aspectj.weaver.CrosscuttingMembersSet.addOrReplaceAspect (CrosscuttingMembersSet.java:68) at org.aspectj.weaver.CrosscuttingMembersSet.addOrReplaceAspect (CrosscuttingMembersSet.java:57) at org.aspectj.weaver.bcel.BcelWeaver.prepareForWeave(BcelWeaver.java: 450) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.weave (AjCompilerAdapter.java:299) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.afterCompiling (AjCompilerAdapter.java:192) at org.aspectj.ajdt.internal.compiler.CompilerAdapter.ajc $afterReturning$org_aspectj_ajdt_internal_compiler_CompilerAdapter$2 $f9cc9ca0(CompilerAdapter.aj:70) at org.aspectj.org.eclipse.jdt.internal.compiler.Compiler.compile (Compiler.java:367) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.performCompilation (AjBuildManager.java:887) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.doBuild (AjBuildManager.java:244) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.batchBuild (AjBuildManager.java:163) at org.aspectj.ajde.internal.CompilerAdapter.compile (CompilerAdapter.java:122) at org.aspectj.ajde.internal.AspectJBuildManager$CompilerThread.run (AspectJBuildManager.java:191) UnsupportedOperationException thrown: unable to parameterize unresolved type: Pjava/util/List<+Ljava/lang/Object;>; To reproduce this exception compile the following code snippet. import java.util.ArrayList; import java.util.List; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; public class Main { public List<? extends Element> getElements() { return new ArrayList<Element>(); } class Element {}; @Aspect static abstract class Base<T> { @Around("call(List<? extends T> *.*(..))") public List<? extends T> elementList(ProceedingJoinPoint thisJoinPoint) { try { return (List<? extends T>)thisJoinPoint.proceed(); } catch (Throwable e) { throw new RuntimeException(e); } } } @Aspect static class Concrete extends Base<Element> {} public static void main(String[] args) { new Main().getElements(); } }
resolved fixed
7b40e7e
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2006-10-24T12:42:57Z"
"2006-10-19T01:06:40Z"
weaver/src/org/aspectj/weaver/patterns/ArgsPointcut.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.DataOutputStream; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map; import org.aspectj.bridge.IMessage; import org.aspectj.bridge.ISourceLocation; import org.aspectj.util.FuzzyBoolean; import org.aspectj.weaver.BetaException; import org.aspectj.weaver.ISourceContext; import org.aspectj.weaver.IntMap; import org.aspectj.weaver.ResolvedType; import org.aspectj.weaver.Shadow; import org.aspectj.weaver.UnresolvedType; import org.aspectj.weaver.VersionedDataInputStream; import org.aspectj.weaver.WeaverMessages; import org.aspectj.weaver.World; import org.aspectj.weaver.ast.Literal; import org.aspectj.weaver.ast.Test; /** * args(arguments) * * @author Erik Hilsdale * @author Jim Hugunin */ public class ArgsPointcut extends NameBindingPointcut { private static final String ASPECTJ_JP_SIGNATURE_PREFIX = "Lorg/aspectj/lang/JoinPoint"; private static final String ASPECTJ_SYNTHETIC_SIGNATURE_PREFIX = "Lorg/aspectj/runtime/internal/"; private TypePatternList arguments; private String stringRepresentation; public ArgsPointcut(TypePatternList arguments) { this.arguments = arguments; this.pointcutKind = ARGS; this.stringRepresentation = "args" + arguments.toString() + ""; } public TypePatternList getArguments() { return arguments; } public Pointcut parameterizeWith(Map typeVariableMap) { ArgsPointcut ret = new ArgsPointcut(this.arguments.parameterizeWith(typeVariableMap)); ret.copyLocationFrom(this); return ret; } public int couldMatchKinds() { return Shadow.ALL_SHADOW_KINDS_BITS; // empty args() matches jps with no args } public FuzzyBoolean fastMatch(FastMatchInfo type) { return FuzzyBoolean.MAYBE; } protected FuzzyBoolean matchInternal(Shadow shadow) { ResolvedType[] argumentsToMatchAgainst = getArgumentsToMatchAgainst(shadow); FuzzyBoolean ret = arguments.matches(argumentsToMatchAgainst, TypePattern.DYNAMIC); return ret; } private ResolvedType[] getArgumentsToMatchAgainst(Shadow shadow) { if (shadow.isShadowForArrayConstructionJoinpoint()) { return shadow.getArgumentTypesForArrayConstructionShadow(); } ResolvedType[] argumentsToMatchAgainst = shadow.getIWorld().resolve(shadow.getGenericArgTypes()); // special treatment for adviceexecution which may have synthetic arguments we // want to ignore. if (shadow.getKind() == Shadow.AdviceExecution) { int numExtraArgs = 0; for (int i = 0; i < argumentsToMatchAgainst.length; i++) { String argumentSignature = argumentsToMatchAgainst[i].getSignature(); if (argumentSignature.startsWith(ASPECTJ_JP_SIGNATURE_PREFIX) || argumentSignature.startsWith(ASPECTJ_SYNTHETIC_SIGNATURE_PREFIX)) { numExtraArgs++; } else { // normal arg after AJ type means earlier arg was NOT synthetic numExtraArgs = 0; } } if (numExtraArgs > 0) { int newArgLength = argumentsToMatchAgainst.length - numExtraArgs; ResolvedType[] argsSubset = new ResolvedType[newArgLength]; System.arraycopy(argumentsToMatchAgainst, 0, argsSubset, 0, newArgLength); argumentsToMatchAgainst = argsSubset; } } else if (shadow.getKind() == Shadow.ConstructorExecution) { if (shadow.getMatchingSignature().getParameterTypes().length < argumentsToMatchAgainst.length) { // there are one or more synthetic args on the end, caused by non-public itd constructor int newArgLength = shadow.getMatchingSignature().getParameterTypes().length; ResolvedType[] argsSubset = new ResolvedType[newArgLength]; System.arraycopy(argumentsToMatchAgainst, 0, argsSubset, 0, newArgLength); argumentsToMatchAgainst = argsSubset; } } return argumentsToMatchAgainst; } /* (non-Javadoc) * @see org.aspectj.weaver.patterns.NameBindingPointcut#getBindingAnnotationTypePatterns() */ public List getBindingAnnotationTypePatterns() { return Collections.EMPTY_LIST; } /* (non-Javadoc) * @see org.aspectj.weaver.patterns.NameBindingPointcut#getBindingTypePatterns() */ public List getBindingTypePatterns() { List l = new ArrayList(); TypePattern[] pats = arguments.getTypePatterns(); for (int i = 0; i < pats.length; i++) { if (pats[i] instanceof BindingTypePattern) { l.add(pats[i]); } } return l; } public void write(DataOutputStream s) throws IOException { s.writeByte(Pointcut.ARGS); arguments.write(s); writeLocation(s); } public static Pointcut read(VersionedDataInputStream s, ISourceContext context) throws IOException { ArgsPointcut ret = new ArgsPointcut(TypePatternList.read(s, context)); ret.readLocation(context, s); return ret; } public boolean equals(Object other) { if (!(other instanceof ArgsPointcut)) return false; ArgsPointcut o = (ArgsPointcut)other; return o.arguments.equals(this.arguments); } public int hashCode() { return arguments.hashCode(); } public void resolveBindings(IScope scope, Bindings bindings) { arguments.resolveBindings(scope, bindings, true, true); if (arguments.ellipsisCount > 1) { scope.message(IMessage.ERROR, this, "uses more than one .. in args (compiler limitation)"); } } public void postRead(ResolvedType enclosingType) { arguments.postRead(enclosingType); } public Pointcut concretize1(ResolvedType inAspect, ResolvedType declaringType, IntMap bindings) { if (isDeclare(bindings.getEnclosingAdvice())) { // Enforce rule about which designators are supported in declare inAspect.getWorld().showMessage(IMessage.ERROR, WeaverMessages.format(WeaverMessages.ARGS_IN_DECLARE), bindings.getEnclosingAdvice().getSourceLocation(), null); return Pointcut.makeMatchesNothing(Pointcut.CONCRETE); } TypePatternList args = arguments.resolveReferences(bindings); if (inAspect.crosscuttingMembers != null) { inAspect.crosscuttingMembers.exposeTypes(args.getExactTypes()); } Pointcut ret = new ArgsPointcut(args); ret.copyLocationFrom(this); return ret; } private Test findResidueNoEllipsis(Shadow shadow, ExposedState state, TypePattern[] patterns) { ResolvedType[] argumentsToMatchAgainst = getArgumentsToMatchAgainst(shadow); int len = argumentsToMatchAgainst.length; //System.err.println("boudn to : " + len + ", " + patterns.length); if (patterns.length != len) { return Literal.FALSE; } Test ret = Literal.TRUE; for (int i=0; i < len; i++) { UnresolvedType argType = shadow.getGenericArgTypes()[i]; TypePattern type = patterns[i]; ResolvedType argRTX = shadow.getIWorld().resolve(argType,true); if (!(type instanceof BindingTypePattern)) { if (argRTX.isMissing()) { shadow.getIWorld().getLint().cantFindType.signal( new String[] {WeaverMessages.format(WeaverMessages.CANT_FIND_TYPE_ARG_TYPE,argType.getName())}, shadow.getSourceLocation(), new ISourceLocation[]{getSourceLocation()} ); // IMessage msg = new Message( // WeaverMessages.format(WeaverMessages.CANT_FIND_TYPE_ARG_TYPE,argType.getName()), // "",IMessage.ERROR,shadow.getSourceLocation(),null,new ISourceLocation[]{getSourceLocation()}); // shadow.getIWorld().getMessageHandler().handleMessage(msg); } if (type.matchesInstanceof(argRTX).alwaysTrue()) { continue; } } World world = shadow.getIWorld(); ResolvedType typeToExpose = type.getExactType().resolve(world); if (typeToExpose.isParameterizedType()) { boolean inDoubt = (type.matchesInstanceof(argRTX) == FuzzyBoolean.MAYBE); if (inDoubt && world.getLint().uncheckedArgument.isEnabled()) { String uncheckedMatchWith = typeToExpose.getSimpleBaseName(); if (argRTX.isParameterizedType() && (argRTX.getRawType() == typeToExpose.getRawType())) { uncheckedMatchWith = argRTX.getSimpleName(); } if (!isUncheckedArgumentWarningSuppressed()) { world.getLint().uncheckedArgument.signal( new String[] { typeToExpose.getSimpleName(), uncheckedMatchWith, typeToExpose.getSimpleBaseName(), shadow.toResolvedString(world)}, getSourceLocation(), new ISourceLocation[] {shadow.getSourceLocation()}); } } } ret = Test.makeAnd(ret, exposeStateForVar(shadow.getArgVar(i), type, state,shadow.getIWorld())); } return ret; } /** * We need to find out if someone has put the @SuppressAjWarnings{"uncheckedArgument"} * annotation somewhere. That somewhere is going to be an a piece of advice that uses this * pointcut. But how do we find it??? * @return */ private boolean isUncheckedArgumentWarningSuppressed() { return false; } protected Test findResidueInternal(Shadow shadow, ExposedState state) { ResolvedType[] argsToMatch = getArgumentsToMatchAgainst(shadow); if (arguments.matches(argsToMatch, TypePattern.DYNAMIC).alwaysFalse()) { return Literal.FALSE; } int ellipsisCount = arguments.ellipsisCount; if (ellipsisCount == 0) { return findResidueNoEllipsis(shadow, state, arguments.getTypePatterns()); } else if (ellipsisCount == 1) { TypePattern[] patternsWithEllipsis = arguments.getTypePatterns(); TypePattern[] patternsWithoutEllipsis = new TypePattern[argsToMatch.length]; int lenWithEllipsis = patternsWithEllipsis.length; int lenWithoutEllipsis = patternsWithoutEllipsis.length; // l1+1 >= l0 int indexWithEllipsis = 0; int indexWithoutEllipsis = 0; while (indexWithoutEllipsis < lenWithoutEllipsis) { TypePattern p = patternsWithEllipsis[indexWithEllipsis++]; if (p == TypePattern.ELLIPSIS) { int newLenWithoutEllipsis = lenWithoutEllipsis - (lenWithEllipsis-indexWithEllipsis); while (indexWithoutEllipsis < newLenWithoutEllipsis) { patternsWithoutEllipsis[indexWithoutEllipsis++] = TypePattern.ANY; } } else { patternsWithoutEllipsis[indexWithoutEllipsis++] = p; } } return findResidueNoEllipsis(shadow, state, patternsWithoutEllipsis); } else { throw new BetaException("unimplemented"); } } public String toString() { return this.stringRepresentation; } public Object accept(PatternNodeVisitor visitor, Object data) { return visitor.visit(this, data); } }
161,502
Bug 161502 UnsupportedOperationException thrown: unable to parameterize unresolved type: Pjava/util/List<+Ljava/lang/Object; >;
Generic parameters (like List<? extends T>) in pointcuts throw UnsupportedOperationException. java.lang.UnsupportedOperationException at org.aspectj.weaver.UnresolvedType.parameterize(UnresolvedType.java: 220) at org.aspectj.weaver.patterns.ExactTypePattern.parameterizeWith (ExactTypePattern.java:244) at org.aspectj.weaver.patterns.SignaturePattern.parameterizeWith (SignaturePattern.java:265) at org.aspectj.weaver.patterns.KindedPointcut.parameterizeWith (KindedPointcut.java:381) at org.aspectj.weaver.bcel.BcelAdvice.parameterizeWith (BcelAdvice.java:93) at org.aspectj.weaver.ResolvedType.getDeclaredAdvice (ResolvedType.java:710) at org.aspectj.weaver.ResolvedType.getDeclaredShadowMungers (ResolvedType.java:739) at org.aspectj.weaver.ResolvedType.collectShadowMungers (ResolvedType.java:575) at org.aspectj.weaver.ResolvedType.collectCrosscuttingMembers (ResolvedType.java:504) at org.aspectj.weaver.CrosscuttingMembersSet.addOrReplaceAspect (CrosscuttingMembersSet.java:68) at org.aspectj.weaver.CrosscuttingMembersSet.addOrReplaceAspect (CrosscuttingMembersSet.java:57) at org.aspectj.weaver.bcel.BcelWeaver.prepareForWeave(BcelWeaver.java: 450) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.weave (AjCompilerAdapter.java:299) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.afterCompiling (AjCompilerAdapter.java:192) at org.aspectj.ajdt.internal.compiler.CompilerAdapter.ajc $afterReturning$org_aspectj_ajdt_internal_compiler_CompilerAdapter$2 $f9cc9ca0(CompilerAdapter.aj:70) at org.aspectj.org.eclipse.jdt.internal.compiler.Compiler.compile (Compiler.java:367) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.performCompilation (AjBuildManager.java:887) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.doBuild (AjBuildManager.java:244) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.batchBuild (AjBuildManager.java:163) at org.aspectj.ajde.internal.CompilerAdapter.compile (CompilerAdapter.java:122) at org.aspectj.ajde.internal.AspectJBuildManager$CompilerThread.run (AspectJBuildManager.java:191) UnsupportedOperationException thrown: unable to parameterize unresolved type: Pjava/util/List<+Ljava/lang/Object;>; To reproduce this exception compile the following code snippet. import java.util.ArrayList; import java.util.List; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; public class Main { public List<? extends Element> getElements() { return new ArrayList<Element>(); } class Element {}; @Aspect static abstract class Base<T> { @Around("call(List<? extends T> *.*(..))") public List<? extends T> elementList(ProceedingJoinPoint thisJoinPoint) { try { return (List<? extends T>)thisJoinPoint.proceed(); } catch (Throwable e) { throw new RuntimeException(e); } } } @Aspect static class Concrete extends Base<Element> {} public static void main(String[] args) { new Main().getElements(); } }
resolved fixed
7b40e7e
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2006-10-24T12:42:57Z"
"2006-10-19T01:06:40Z"
weaver/src/org/aspectj/weaver/patterns/BindingAnnotationTypePattern.java
/* ******************************************************************* * Copyright (c) 2004 IBM Corporation. * All rights reserved. * This program and the accompanying materials are made available * under the terms of the 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.DataOutputStream; import java.io.IOException; import java.util.Map; import org.aspectj.bridge.IMessage; import org.aspectj.bridge.MessageUtil; import org.aspectj.weaver.BCException; import org.aspectj.weaver.ISourceContext; import org.aspectj.weaver.IntMap; import org.aspectj.weaver.ResolvedType; import org.aspectj.weaver.TypeVariableReference; import org.aspectj.weaver.UnresolvedType; import org.aspectj.weaver.VersionedDataInputStream; import org.aspectj.weaver.WeaverMessages; import org.aspectj.weaver.World; public class BindingAnnotationTypePattern extends ExactAnnotationTypePattern implements BindingPattern { private int formalIndex; /** * @param annotationType */ public BindingAnnotationTypePattern(UnresolvedType annotationType, int index) { super(annotationType); this.formalIndex = index; } public BindingAnnotationTypePattern(FormalBinding binding) { this(binding.getType(),binding.getIndex()); } public void resolveBinding(World world) { if (resolved) return; resolved = true; annotationType = annotationType.resolve(world); ResolvedType resolvedAnnotationType = (ResolvedType) annotationType; if (!resolvedAnnotationType.isAnnotation()) { IMessage m = MessageUtil.error( WeaverMessages.format(WeaverMessages.REFERENCE_TO_NON_ANNOTATION_TYPE,annotationType.getName()), getSourceLocation()); world.getMessageHandler().handleMessage(m); resolved = false; } if (annotationType.isTypeVariableReference()) return; // we'll deal with this next check when the type var is actually bound... verifyRuntimeRetention(world, resolvedAnnotationType); } private void verifyRuntimeRetention(World world, ResolvedType resolvedAnnotationType) { if (!resolvedAnnotationType.isAnnotationWithRuntimeRetention()) { // default is class visibility // default is class visibility IMessage m = MessageUtil.error( WeaverMessages.format(WeaverMessages.BINDING_NON_RUNTIME_RETENTION_ANNOTATION,annotationType.getName()), getSourceLocation()); world.getMessageHandler().handleMessage(m); resolved = false; } } public AnnotationTypePattern parameterizeWith(Map typeVariableMap) { UnresolvedType newAnnotationType = annotationType; if (annotationType.isTypeVariableReference()) { TypeVariableReference t = (TypeVariableReference) annotationType; String key = t.getTypeVariable().getName(); if (typeVariableMap.containsKey(key)) { newAnnotationType = (UnresolvedType) typeVariableMap.get(key); } } else if (annotationType.isParameterizedType()) { newAnnotationType = annotationType.parameterize(typeVariableMap); } BindingAnnotationTypePattern ret = new BindingAnnotationTypePattern(newAnnotationType,this.formalIndex); if (newAnnotationType instanceof ResolvedType) { ResolvedType rat = (ResolvedType) newAnnotationType; verifyRuntimeRetention(rat.getWorld(),rat); } ret.copyLocationFrom(this); return ret; } public int getFormalIndex() { return formalIndex; } public boolean equals(Object obj) { if (!(obj instanceof BindingAnnotationTypePattern)) return false; BindingAnnotationTypePattern btp = (BindingAnnotationTypePattern) obj; return (super.equals(btp) && (btp.formalIndex == formalIndex)); } public int hashCode() { return super.hashCode()*37 + formalIndex; } public AnnotationTypePattern remapAdviceFormals(IntMap bindings) { if (!bindings.hasKey(formalIndex)) { return new ExactAnnotationTypePattern(annotationType); } else { int newFormalIndex = bindings.get(formalIndex); return new BindingAnnotationTypePattern(annotationType, newFormalIndex); } } private static final byte VERSION = 1; // rev if serialised form changed /* (non-Javadoc) * @see org.aspectj.weaver.patterns.ExactAnnotationTypePattern#write(java.io.DataOutputStream) */ public void write(DataOutputStream s) throws IOException { s.writeByte(AnnotationTypePattern.BINDING); s.writeByte(VERSION); annotationType.write(s); s.writeShort((short)formalIndex); writeLocation(s); } public static AnnotationTypePattern read(VersionedDataInputStream s, ISourceContext context) throws IOException { byte version = s.readByte(); if (version > VERSION) { throw new BCException("BindingAnnotationTypePattern was written by a more recent version of AspectJ"); } AnnotationTypePattern ret = new BindingAnnotationTypePattern(UnresolvedType.read(s),s.readShort()); ret.readLocation(context,s); return ret; } }
161,502
Bug 161502 UnsupportedOperationException thrown: unable to parameterize unresolved type: Pjava/util/List<+Ljava/lang/Object; >;
Generic parameters (like List<? extends T>) in pointcuts throw UnsupportedOperationException. java.lang.UnsupportedOperationException at org.aspectj.weaver.UnresolvedType.parameterize(UnresolvedType.java: 220) at org.aspectj.weaver.patterns.ExactTypePattern.parameterizeWith (ExactTypePattern.java:244) at org.aspectj.weaver.patterns.SignaturePattern.parameterizeWith (SignaturePattern.java:265) at org.aspectj.weaver.patterns.KindedPointcut.parameterizeWith (KindedPointcut.java:381) at org.aspectj.weaver.bcel.BcelAdvice.parameterizeWith (BcelAdvice.java:93) at org.aspectj.weaver.ResolvedType.getDeclaredAdvice (ResolvedType.java:710) at org.aspectj.weaver.ResolvedType.getDeclaredShadowMungers (ResolvedType.java:739) at org.aspectj.weaver.ResolvedType.collectShadowMungers (ResolvedType.java:575) at org.aspectj.weaver.ResolvedType.collectCrosscuttingMembers (ResolvedType.java:504) at org.aspectj.weaver.CrosscuttingMembersSet.addOrReplaceAspect (CrosscuttingMembersSet.java:68) at org.aspectj.weaver.CrosscuttingMembersSet.addOrReplaceAspect (CrosscuttingMembersSet.java:57) at org.aspectj.weaver.bcel.BcelWeaver.prepareForWeave(BcelWeaver.java: 450) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.weave (AjCompilerAdapter.java:299) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.afterCompiling (AjCompilerAdapter.java:192) at org.aspectj.ajdt.internal.compiler.CompilerAdapter.ajc $afterReturning$org_aspectj_ajdt_internal_compiler_CompilerAdapter$2 $f9cc9ca0(CompilerAdapter.aj:70) at org.aspectj.org.eclipse.jdt.internal.compiler.Compiler.compile (Compiler.java:367) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.performCompilation (AjBuildManager.java:887) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.doBuild (AjBuildManager.java:244) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.batchBuild (AjBuildManager.java:163) at org.aspectj.ajde.internal.CompilerAdapter.compile (CompilerAdapter.java:122) at org.aspectj.ajde.internal.AspectJBuildManager$CompilerThread.run (AspectJBuildManager.java:191) UnsupportedOperationException thrown: unable to parameterize unresolved type: Pjava/util/List<+Ljava/lang/Object;>; To reproduce this exception compile the following code snippet. import java.util.ArrayList; import java.util.List; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; public class Main { public List<? extends Element> getElements() { return new ArrayList<Element>(); } class Element {}; @Aspect static abstract class Base<T> { @Around("call(List<? extends T> *.*(..))") public List<? extends T> elementList(ProceedingJoinPoint thisJoinPoint) { try { return (List<? extends T>)thisJoinPoint.proceed(); } catch (Throwable e) { throw new RuntimeException(e); } } } @Aspect static class Concrete extends Base<Element> {} public static void main(String[] args) { new Main().getElements(); } }
resolved fixed
7b40e7e
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2006-10-24T12:42:57Z"
"2006-10-19T01:06:40Z"
weaver/src/org/aspectj/weaver/patterns/BindingTypePattern.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.DataOutputStream; import java.io.IOException; import java.util.Map; import org.aspectj.weaver.AjAttribute; import org.aspectj.weaver.ISourceContext; import org.aspectj.weaver.IntMap; import org.aspectj.weaver.UnresolvedType; import org.aspectj.weaver.VersionedDataInputStream; public class BindingTypePattern extends ExactTypePattern implements BindingPattern { private int formalIndex; public BindingTypePattern(UnresolvedType type, int index,boolean isVarArgs) { super(type, false,isVarArgs); this.formalIndex = index; } public BindingTypePattern(FormalBinding binding, boolean isVarArgs) { this(binding.getType(), binding.getIndex(),isVarArgs); } public int getFormalIndex() { return formalIndex; } public boolean equals(Object other) { if (!(other instanceof BindingTypePattern)) return false; BindingTypePattern o = (BindingTypePattern)other; if (includeSubtypes != o.includeSubtypes) return false; if (isVarArgs != o.isVarArgs) return false; return o.type.equals(this.type) && o.formalIndex == this.formalIndex; } public int hashCode() { int result = 17; result = 37*result + super.hashCode(); result = 37*result + formalIndex; return result; } public void write(DataOutputStream out) throws IOException { out.writeByte(TypePattern.BINDING); type.write(out); out.writeShort((short)formalIndex); out.writeBoolean(isVarArgs); writeLocation(out); } public static TypePattern read(VersionedDataInputStream s, ISourceContext context) throws IOException { UnresolvedType type = UnresolvedType.read(s); int index = s.readShort(); boolean isVarargs = false; if (s.getMajorVersion()>=AjAttribute.WeaverVersionInfo.WEAVER_VERSION_MAJOR_AJ150) { isVarargs = s.readBoolean(); } TypePattern ret = new BindingTypePattern(type,index,isVarargs); ret.readLocation(context, s); return ret; } public TypePattern remapAdviceFormals(IntMap bindings) { if (!bindings.hasKey(formalIndex)) { return new ExactTypePattern(type, false, isVarArgs); } else { int newFormalIndex = bindings.get(formalIndex); return new BindingTypePattern(type, newFormalIndex, isVarArgs); } } public TypePattern parameterizeWith(Map typeVariableMap) { ExactTypePattern superParameterized = (ExactTypePattern) super.parameterizeWith(typeVariableMap); BindingTypePattern ret = new BindingTypePattern(superParameterized.getExactType(),this.formalIndex,this.isVarArgs); ret.copyLocationFrom(this); return ret; } public String toString() { //Thread.currentThread().dumpStack(); return "BindingTypePattern(" + super.toString() + ", " + formalIndex + ")"; } }
161,502
Bug 161502 UnsupportedOperationException thrown: unable to parameterize unresolved type: Pjava/util/List<+Ljava/lang/Object; >;
Generic parameters (like List<? extends T>) in pointcuts throw UnsupportedOperationException. java.lang.UnsupportedOperationException at org.aspectj.weaver.UnresolvedType.parameterize(UnresolvedType.java: 220) at org.aspectj.weaver.patterns.ExactTypePattern.parameterizeWith (ExactTypePattern.java:244) at org.aspectj.weaver.patterns.SignaturePattern.parameterizeWith (SignaturePattern.java:265) at org.aspectj.weaver.patterns.KindedPointcut.parameterizeWith (KindedPointcut.java:381) at org.aspectj.weaver.bcel.BcelAdvice.parameterizeWith (BcelAdvice.java:93) at org.aspectj.weaver.ResolvedType.getDeclaredAdvice (ResolvedType.java:710) at org.aspectj.weaver.ResolvedType.getDeclaredShadowMungers (ResolvedType.java:739) at org.aspectj.weaver.ResolvedType.collectShadowMungers (ResolvedType.java:575) at org.aspectj.weaver.ResolvedType.collectCrosscuttingMembers (ResolvedType.java:504) at org.aspectj.weaver.CrosscuttingMembersSet.addOrReplaceAspect (CrosscuttingMembersSet.java:68) at org.aspectj.weaver.CrosscuttingMembersSet.addOrReplaceAspect (CrosscuttingMembersSet.java:57) at org.aspectj.weaver.bcel.BcelWeaver.prepareForWeave(BcelWeaver.java: 450) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.weave (AjCompilerAdapter.java:299) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.afterCompiling (AjCompilerAdapter.java:192) at org.aspectj.ajdt.internal.compiler.CompilerAdapter.ajc $afterReturning$org_aspectj_ajdt_internal_compiler_CompilerAdapter$2 $f9cc9ca0(CompilerAdapter.aj:70) at org.aspectj.org.eclipse.jdt.internal.compiler.Compiler.compile (Compiler.java:367) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.performCompilation (AjBuildManager.java:887) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.doBuild (AjBuildManager.java:244) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.batchBuild (AjBuildManager.java:163) at org.aspectj.ajde.internal.CompilerAdapter.compile (CompilerAdapter.java:122) at org.aspectj.ajde.internal.AspectJBuildManager$CompilerThread.run (AspectJBuildManager.java:191) UnsupportedOperationException thrown: unable to parameterize unresolved type: Pjava/util/List<+Ljava/lang/Object;>; To reproduce this exception compile the following code snippet. import java.util.ArrayList; import java.util.List; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; public class Main { public List<? extends Element> getElements() { return new ArrayList<Element>(); } class Element {}; @Aspect static abstract class Base<T> { @Around("call(List<? extends T> *.*(..))") public List<? extends T> elementList(ProceedingJoinPoint thisJoinPoint) { try { return (List<? extends T>)thisJoinPoint.proceed(); } catch (Throwable e) { throw new RuntimeException(e); } } } @Aspect static class Concrete extends Base<Element> {} public static void main(String[] args) { new Main().getElements(); } }
resolved fixed
7b40e7e
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2006-10-24T12:42:57Z"
"2006-10-19T01:06:40Z"
weaver/src/org/aspectj/weaver/patterns/CflowPointcut.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.DataOutputStream; import java.io.IOException; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.Collection; import java.util.Enumeration; import java.util.Hashtable; import java.util.Iterator; import java.util.List; import java.util.Map; import org.aspectj.bridge.IMessage; import org.aspectj.util.FileUtil; import org.aspectj.util.FuzzyBoolean; import org.aspectj.weaver.Advice; import org.aspectj.weaver.CrosscuttingMembers; import org.aspectj.weaver.ISourceContext; import org.aspectj.weaver.IntMap; import org.aspectj.weaver.Member; import org.aspectj.weaver.NameMangler; import org.aspectj.weaver.ResolvedMember; import org.aspectj.weaver.ResolvedMemberImpl; import org.aspectj.weaver.ResolvedPointcutDefinition; import org.aspectj.weaver.ResolvedType; import org.aspectj.weaver.Shadow; import org.aspectj.weaver.UnresolvedType; import org.aspectj.weaver.VersionedDataInputStream; import org.aspectj.weaver.WeaverMessages; import org.aspectj.weaver.World; import org.aspectj.weaver.ast.Test; public class CflowPointcut extends Pointcut { private Pointcut entry; // The pointcut inside the cflow() that represents the 'entry' point boolean isBelow;// Is this cflowbelow? private int[] freeVars; private static Hashtable cflowFields = new Hashtable(); private static Hashtable cflowBelowFields = new Hashtable(); /** * Used to indicate that we're in the context of a cflow when concretizing if's * * Will be removed or replaced with something better when we handle this * as a non-error */ public static final ResolvedPointcutDefinition CFLOW_MARKER = new ResolvedPointcutDefinition(null, 0, null, UnresolvedType.NONE, Pointcut.makeMatchesNothing(Pointcut.RESOLVED)); public CflowPointcut(Pointcut entry, boolean isBelow, int[] freeVars) { // System.err.println("Building cflow pointcut "+entry.toString()); this.entry = entry; this.isBelow = isBelow; this.freeVars = freeVars; this.pointcutKind = CFLOW; } /** * @return Returns true is this is a cflowbelow pointcut */ public boolean isCflowBelow() { return isBelow; } public int couldMatchKinds() { return Shadow.ALL_SHADOW_KINDS_BITS; } // enh 76055 public Pointcut getEntry() { return entry; } public FuzzyBoolean fastMatch(FastMatchInfo type) { return FuzzyBoolean.MAYBE; } protected FuzzyBoolean matchInternal(Shadow shadow) { //??? this is not maximally efficient return FuzzyBoolean.MAYBE; } public void write(DataOutputStream s) throws IOException { s.writeByte(Pointcut.CFLOW); entry.write(s); s.writeBoolean(isBelow); FileUtil.writeIntArray(freeVars, s); writeLocation(s); } public static Pointcut read(VersionedDataInputStream s, ISourceContext context) throws IOException { CflowPointcut ret = new CflowPointcut(Pointcut.read(s, context), s.readBoolean(), FileUtil.readIntArray(s)); ret.readLocation(context, s); return ret; } public Pointcut parameterizeWith(Map typeVariableMap) { CflowPointcut ret = new CflowPointcut(entry.parameterizeWith(typeVariableMap),isBelow,freeVars); ret.copyLocationFrom(this); return ret; } public void resolveBindings(IScope scope, Bindings bindings) { if (bindings == null) { entry.resolveBindings(scope, null); entry.state = RESOLVED; freeVars = new int[0]; } else { //??? for if's sake we might need to be more careful here Bindings entryBindings = new Bindings(bindings.size()); entry.resolveBindings(scope, entryBindings); entry.state = RESOLVED; freeVars = entryBindings.getUsedFormals(); bindings.mergeIn(entryBindings, scope); } } public boolean equals(Object other) { if (!(other instanceof CflowPointcut)) return false; CflowPointcut o = (CflowPointcut)other; return o.entry.equals(this.entry) && o.isBelow == this.isBelow; } public int hashCode() { int result = 17; result = 37*result + entry.hashCode(); result = 37*result + (isBelow ? 0 : 1); return result; } public String toString() { return "cflow" + (isBelow ? "below" : "") + "(" + entry + ")"; } protected Test findResidueInternal(Shadow shadow, ExposedState state) { throw new RuntimeException("unimplemented - did concretization fail?"); } public Pointcut concretize1(ResolvedType inAspect, ResolvedType declaringType, IntMap bindings) { // the pointcut is marked as CONCRETE after returning from this // call - so we can't skip concretization // if (this.entry.state == Pointcut.SYMBOLIC) { // // too early to concretize, return unchanged // return this; // } // Enforce rule about which designators are supported in declare if (isDeclare(bindings.getEnclosingAdvice())) { inAspect.getWorld().showMessage(IMessage.ERROR, WeaverMessages.format(WeaverMessages.CFLOW_IN_DECLARE,isBelow?"below":""), bindings.getEnclosingAdvice().getSourceLocation(), null); return Pointcut.makeMatchesNothing(Pointcut.CONCRETE); } //make this remap from formal positions to arrayIndices IntMap entryBindings = new IntMap(); if (freeVars!=null) { for (int i=0, len=freeVars.length; i < len; i++) { int freeVar = freeVars[i]; //int formalIndex = bindings.get(freeVar); entryBindings.put(freeVar, i); } } entryBindings.copyContext(bindings); //System.out.println(this + " bindings: " + entryBindings); World world = inAspect.getWorld(); Pointcut concreteEntry; ResolvedType concreteAspect = bindings.getConcreteAspect(); CrosscuttingMembers xcut = concreteAspect.crosscuttingMembers; Collection previousCflowEntries = xcut.getCflowEntries(); entryBindings.pushEnclosingDefinition(CFLOW_MARKER); // This block concretizes the pointcut within the cflow pointcut try { concreteEntry = entry.concretize(inAspect, declaringType, entryBindings); } finally { entryBindings.popEnclosingDefinitition(); } List innerCflowEntries = new ArrayList(xcut.getCflowEntries()); innerCflowEntries.removeAll(previousCflowEntries); // Four routes of interest through this code (did I hear someone say refactor??) // 1) no state in the cflow - we can use a counter *and* we have seen this pointcut // before - so use the same counter as before. // 2) no state in the cflow - we can use a counter, but this is the first time // we have seen this pointcut, so build the infrastructure. // 3) state in the cflow - we need to use a stack *and* we have seen this pointcut // before - so share the stack. // 4) state in the cflow - we need to use a stack, but this is the first time // we have seen this pointcut, so build the infrastructure. if (freeVars==null || freeVars.length == 0) { // No state, so don't use a stack, use a counter. ResolvedMember localCflowField = null; Object field = getCflowfield(concreteEntry,concreteAspect,"counter"); // Check if we have already got a counter for this cflow pointcut if (field != null) { localCflowField = (ResolvedMember)field; // Use the one we already have } else { // Create a counter field in the aspect localCflowField = new ResolvedMemberImpl(Member.FIELD,concreteAspect,Modifier.STATIC | Modifier.PUBLIC | Modifier.FINAL, NameMangler.cflowCounter(xcut),UnresolvedType.forName(NameMangler.CFLOW_COUNTER_TYPE).getSignature()); // Create type munger to add field to the aspect concreteAspect.crosscuttingMembers.addTypeMunger(world.makeCflowCounterFieldAdder(localCflowField)); // Create shadow munger to push stuff onto the stack concreteAspect.crosscuttingMembers.addConcreteShadowMunger( Advice.makeCflowEntry(world,concreteEntry,isBelow,localCflowField,freeVars==null?0:freeVars.length,innerCflowEntries,inAspect)); putCflowfield(concreteEntry,concreteAspect,localCflowField,"counter"); // Remember it } Pointcut ret = new ConcreteCflowPointcut(localCflowField, null,true); ret.copyLocationFrom(this); return ret; } else { List slots = new ArrayList(); for (int i=0, len=freeVars.length; i < len; i++) { int freeVar = freeVars[i]; // we don't need to keep state that isn't actually exposed to advice //??? this means that we will store some state that we won't actually use, optimize this later if (!bindings.hasKey(freeVar)) continue; int formalIndex = bindings.get(freeVar); // We need to look in the right place for the type of the formal. Suppose the advice looks like this: // before(String s): somePointcut(*,s) // where the first argument in somePointcut is of type Number // for free variable 0 we want to ask the pointcut for the type of its first argument, if we only // ask the advice for the type of its first argument then we'll get the wrong type (pr86903) ResolvedPointcutDefinition enclosingDef = bindings.peekEnclosingDefinition(); ResolvedType formalType = null; // Is there a useful enclosing pointcut? if (enclosingDef!=null && enclosingDef.getParameterTypes().length>0) { formalType = enclosingDef.getParameterTypes()[freeVar].resolve(world); } else { formalType = bindings.getAdviceSignature().getParameterTypes()[formalIndex].resolve(world); } ConcreteCflowPointcut.Slot slot = new ConcreteCflowPointcut.Slot(formalIndex, formalType, i); slots.add(slot); } ResolvedMember localCflowField = null; Object field = getCflowfield(concreteEntry,concreteAspect,"stack"); if (field != null) { localCflowField = (ResolvedMember)field; } else { localCflowField = new ResolvedMemberImpl( Member.FIELD, concreteAspect, Modifier.STATIC | Modifier.PUBLIC | Modifier.FINAL, NameMangler.cflowStack(xcut), UnresolvedType.forName(NameMangler.CFLOW_STACK_TYPE).getSignature()); //System.out.println("adding field to: " + inAspect + " field " + cflowField); // add field and initializer to inAspect //XXX and then that info above needs to be mapped down here to help with //XXX getting the exposed state right concreteAspect.crosscuttingMembers.addConcreteShadowMunger( Advice.makeCflowEntry(world, concreteEntry, isBelow, localCflowField, freeVars.length, innerCflowEntries,inAspect)); concreteAspect.crosscuttingMembers.addTypeMunger( world.makeCflowStackFieldAdder(localCflowField)); putCflowfield(concreteEntry,concreteAspect,localCflowField,"stack"); } Pointcut ret = new ConcreteCflowPointcut(localCflowField, slots,false); ret.copyLocationFrom(this); return ret; } } public static void clearCaches() { cflowFields.clear(); cflowBelowFields.clear(); } private String getKey(Pointcut p,ResolvedType a,String stackOrCounter) { StringBuffer sb = new StringBuffer(); sb.append(a.getName()); sb.append("::"); sb.append(p.toString()); sb.append("::"); sb.append(stackOrCounter); return sb.toString(); } private Object getCflowfield(Pointcut pcutkey, ResolvedType concreteAspect,String stackOrCounter) { String key = getKey(pcutkey,concreteAspect,stackOrCounter); Object o =null; if (isBelow) o = cflowBelowFields.get(key); else o = cflowFields.get(key); //System.err.println("Retrieving for key "+key+" returning "+o); return o; } private void putCflowfield(Pointcut pcutkey,ResolvedType concreteAspect,Object o,String stackOrCounter) { String key = getKey(pcutkey,concreteAspect,stackOrCounter); //System.err.println("Storing cflow field for key"+key); if (isBelow) { cflowBelowFields.put(key,o); } else { cflowFields.put(key,o); } } public Object accept(PatternNodeVisitor visitor, Object data) { return visitor.visit(this, data); } public static void clearCaches(ResolvedType aspectType) { //System.err.println("Wiping entries starting "+aspectType.getName()); String key = aspectType.getName()+"::"; wipeKeys(key,cflowFields); wipeKeys(key,cflowBelowFields); } private static void wipeKeys(String keyPrefix,Hashtable ht) { Enumeration keys = ht.keys(); List forRemoval = new ArrayList(); while (keys.hasMoreElements()) { String s = (String)keys.nextElement(); if (s.startsWith(keyPrefix)) forRemoval.add(s); } for (Iterator iter = forRemoval.iterator(); iter.hasNext();) { String element = (String) iter.next(); ht.remove(element); } } }
161,502
Bug 161502 UnsupportedOperationException thrown: unable to parameterize unresolved type: Pjava/util/List<+Ljava/lang/Object; >;
Generic parameters (like List<? extends T>) in pointcuts throw UnsupportedOperationException. java.lang.UnsupportedOperationException at org.aspectj.weaver.UnresolvedType.parameterize(UnresolvedType.java: 220) at org.aspectj.weaver.patterns.ExactTypePattern.parameterizeWith (ExactTypePattern.java:244) at org.aspectj.weaver.patterns.SignaturePattern.parameterizeWith (SignaturePattern.java:265) at org.aspectj.weaver.patterns.KindedPointcut.parameterizeWith (KindedPointcut.java:381) at org.aspectj.weaver.bcel.BcelAdvice.parameterizeWith (BcelAdvice.java:93) at org.aspectj.weaver.ResolvedType.getDeclaredAdvice (ResolvedType.java:710) at org.aspectj.weaver.ResolvedType.getDeclaredShadowMungers (ResolvedType.java:739) at org.aspectj.weaver.ResolvedType.collectShadowMungers (ResolvedType.java:575) at org.aspectj.weaver.ResolvedType.collectCrosscuttingMembers (ResolvedType.java:504) at org.aspectj.weaver.CrosscuttingMembersSet.addOrReplaceAspect (CrosscuttingMembersSet.java:68) at org.aspectj.weaver.CrosscuttingMembersSet.addOrReplaceAspect (CrosscuttingMembersSet.java:57) at org.aspectj.weaver.bcel.BcelWeaver.prepareForWeave(BcelWeaver.java: 450) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.weave (AjCompilerAdapter.java:299) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.afterCompiling (AjCompilerAdapter.java:192) at org.aspectj.ajdt.internal.compiler.CompilerAdapter.ajc $afterReturning$org_aspectj_ajdt_internal_compiler_CompilerAdapter$2 $f9cc9ca0(CompilerAdapter.aj:70) at org.aspectj.org.eclipse.jdt.internal.compiler.Compiler.compile (Compiler.java:367) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.performCompilation (AjBuildManager.java:887) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.doBuild (AjBuildManager.java:244) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.batchBuild (AjBuildManager.java:163) at org.aspectj.ajde.internal.CompilerAdapter.compile (CompilerAdapter.java:122) at org.aspectj.ajde.internal.AspectJBuildManager$CompilerThread.run (AspectJBuildManager.java:191) UnsupportedOperationException thrown: unable to parameterize unresolved type: Pjava/util/List<+Ljava/lang/Object;>; To reproduce this exception compile the following code snippet. import java.util.ArrayList; import java.util.List; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; public class Main { public List<? extends Element> getElements() { return new ArrayList<Element>(); } class Element {}; @Aspect static abstract class Base<T> { @Around("call(List<? extends T> *.*(..))") public List<? extends T> elementList(ProceedingJoinPoint thisJoinPoint) { try { return (List<? extends T>)thisJoinPoint.proceed(); } catch (Throwable e) { throw new RuntimeException(e); } } } @Aspect static class Concrete extends Base<Element> {} public static void main(String[] args) { new Main().getElements(); } }
resolved fixed
7b40e7e
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2006-10-24T12:42:57Z"
"2006-10-19T01:06:40Z"
weaver/src/org/aspectj/weaver/patterns/ConcreteCflowPointcut.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.DataOutputStream; import java.io.IOException; import java.util.Iterator; import java.util.List; import java.util.Map; import org.aspectj.bridge.ISourceLocation; import org.aspectj.bridge.Message; import org.aspectj.util.FuzzyBoolean; import org.aspectj.weaver.IntMap; import org.aspectj.weaver.Member; import org.aspectj.weaver.MemberImpl; import org.aspectj.weaver.NameMangler; import org.aspectj.weaver.ResolvedType; import org.aspectj.weaver.Shadow; import org.aspectj.weaver.UnresolvedType; import org.aspectj.weaver.WeaverMessages; import org.aspectj.weaver.ast.Expr; import org.aspectj.weaver.ast.Test; import org.aspectj.weaver.bcel.BcelCflowAccessVar; public class ConcreteCflowPointcut extends Pointcut { private Member cflowField; List/*Slot*/ slots; // exposed for testing boolean usesCounter; // Can either use a counter or a stack to implement cflow. public ConcreteCflowPointcut(Member cflowField, List slots,boolean usesCounter) { this.cflowField = cflowField; this.slots = slots; this.usesCounter = usesCounter; this.pointcutKind = CFLOW; } public int couldMatchKinds() { return Shadow.ALL_SHADOW_KINDS_BITS; } public FuzzyBoolean fastMatch(FastMatchInfo type) { return FuzzyBoolean.MAYBE; } protected FuzzyBoolean matchInternal(Shadow shadow) { //??? this is not maximally efficient // Check we'll be able to do the residue! // this bit is for pr145693 - we cannot match at all if one of the types is missing, we will be unable // to create the residue if (slots != null) { for (Iterator i = slots.iterator(); i.hasNext();) { Slot slot = (Slot) i.next(); ResolvedType rt = slot.formalType; if (rt.isMissing()) { ISourceLocation[] locs = new ISourceLocation[]{getSourceLocation()}; Message m = new Message( WeaverMessages.format(WeaverMessages.MISSING_TYPE_PREVENTS_MATCH,rt.getName()), "",Message.WARNING,shadow.getSourceLocation(),null,locs); rt.getWorld().getMessageHandler().handleMessage(m); return FuzzyBoolean.NO; } } } return FuzzyBoolean.MAYBE; } // used by weaver when validating bindings public int[] getUsedFormalSlots() { if (slots == null) return new int[0]; int[] indices = new int[slots.size()]; for (int i = 0; i < indices.length; i++) { indices[i] = ((Slot)slots.get(i)).formalIndex; } return indices; } public void write(DataOutputStream s) throws IOException { throw new RuntimeException("unimplemented"); } public void resolveBindings(IScope scope, Bindings bindings) { throw new RuntimeException("unimplemented"); } public Pointcut parameterizeWith(Map typeVariableMap) { throw new RuntimeException("unimplemented"); } public boolean equals(Object other) { if (!(other instanceof ConcreteCflowPointcut)) return false; ConcreteCflowPointcut o = (ConcreteCflowPointcut)other; return o.cflowField.equals(this.cflowField); } public int hashCode() { int result = 17; result = 37*result + cflowField.hashCode(); return result; } public String toString() { return "concretecflow(" + cflowField + ")"; } protected Test findResidueInternal(Shadow shadow, ExposedState state) { //System.out.println("find residue: " + this); if (usesCounter) { return Test.makeFieldGetCall(cflowField, cflowCounterIsValidMethod, Expr.NONE); } else { if (slots != null) { // null for cflows managed by counters for (Iterator i = slots.iterator(); i.hasNext();) { Slot slot = (Slot) i.next(); //System.out.println("slot: " + slot.formalIndex); state.set(slot.formalIndex, new BcelCflowAccessVar(slot.formalType, cflowField, slot.arrayIndex)); } } return Test.makeFieldGetCall(cflowField, cflowStackIsValidMethod, Expr.NONE); } } private static final Member cflowStackIsValidMethod = MemberImpl.method(UnresolvedType.forName(NameMangler.CFLOW_STACK_TYPE), 0, "isValid", "()Z"); private static final Member cflowCounterIsValidMethod = MemberImpl.method(UnresolvedType.forName(NameMangler.CFLOW_COUNTER_TYPE), 0, "isValid", "()Z"); public Pointcut concretize1(ResolvedType inAspect, ResolvedType declaringType, IntMap bindings) { throw new RuntimeException("unimplemented"); } public Object accept(PatternNodeVisitor visitor, Object data) { return visitor.visit(this, data); } public static class Slot { int formalIndex; ResolvedType formalType; int arrayIndex; public Slot( int formalIndex, ResolvedType formalType, int arrayIndex) { this.formalIndex = formalIndex; this.formalType = formalType; this.arrayIndex = arrayIndex; } public boolean equals(Object other) { if (!(other instanceof Slot)) return false; Slot o = (Slot)other; return o.formalIndex == this.formalIndex && o.arrayIndex == this.arrayIndex && o.formalType.equals(this.formalType); } public String toString() { return "Slot(" + formalIndex + ", " + formalType + ", " + arrayIndex + ")"; } } }
161,502
Bug 161502 UnsupportedOperationException thrown: unable to parameterize unresolved type: Pjava/util/List<+Ljava/lang/Object; >;
Generic parameters (like List<? extends T>) in pointcuts throw UnsupportedOperationException. java.lang.UnsupportedOperationException at org.aspectj.weaver.UnresolvedType.parameterize(UnresolvedType.java: 220) at org.aspectj.weaver.patterns.ExactTypePattern.parameterizeWith (ExactTypePattern.java:244) at org.aspectj.weaver.patterns.SignaturePattern.parameterizeWith (SignaturePattern.java:265) at org.aspectj.weaver.patterns.KindedPointcut.parameterizeWith (KindedPointcut.java:381) at org.aspectj.weaver.bcel.BcelAdvice.parameterizeWith (BcelAdvice.java:93) at org.aspectj.weaver.ResolvedType.getDeclaredAdvice (ResolvedType.java:710) at org.aspectj.weaver.ResolvedType.getDeclaredShadowMungers (ResolvedType.java:739) at org.aspectj.weaver.ResolvedType.collectShadowMungers (ResolvedType.java:575) at org.aspectj.weaver.ResolvedType.collectCrosscuttingMembers (ResolvedType.java:504) at org.aspectj.weaver.CrosscuttingMembersSet.addOrReplaceAspect (CrosscuttingMembersSet.java:68) at org.aspectj.weaver.CrosscuttingMembersSet.addOrReplaceAspect (CrosscuttingMembersSet.java:57) at org.aspectj.weaver.bcel.BcelWeaver.prepareForWeave(BcelWeaver.java: 450) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.weave (AjCompilerAdapter.java:299) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.afterCompiling (AjCompilerAdapter.java:192) at org.aspectj.ajdt.internal.compiler.CompilerAdapter.ajc $afterReturning$org_aspectj_ajdt_internal_compiler_CompilerAdapter$2 $f9cc9ca0(CompilerAdapter.aj:70) at org.aspectj.org.eclipse.jdt.internal.compiler.Compiler.compile (Compiler.java:367) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.performCompilation (AjBuildManager.java:887) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.doBuild (AjBuildManager.java:244) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.batchBuild (AjBuildManager.java:163) at org.aspectj.ajde.internal.CompilerAdapter.compile (CompilerAdapter.java:122) at org.aspectj.ajde.internal.AspectJBuildManager$CompilerThread.run (AspectJBuildManager.java:191) UnsupportedOperationException thrown: unable to parameterize unresolved type: Pjava/util/List<+Ljava/lang/Object;>; To reproduce this exception compile the following code snippet. import java.util.ArrayList; import java.util.List; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; public class Main { public List<? extends Element> getElements() { return new ArrayList<Element>(); } class Element {}; @Aspect static abstract class Base<T> { @Around("call(List<? extends T> *.*(..))") public List<? extends T> elementList(ProceedingJoinPoint thisJoinPoint) { try { return (List<? extends T>)thisJoinPoint.proceed(); } catch (Throwable e) { throw new RuntimeException(e); } } } @Aspect static class Concrete extends Base<Element> {} public static void main(String[] args) { new Main().getElements(); } }
resolved fixed
7b40e7e
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2006-10-24T12:42:57Z"
"2006-10-19T01:06:40Z"
weaver/src/org/aspectj/weaver/patterns/Declare.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.weaver.ISourceContext; import org.aspectj.weaver.ResolvedType; import org.aspectj.weaver.VersionedDataInputStream; public abstract class Declare extends PatternNode { public static final byte ERROR_OR_WARNING = 1; public static final byte PARENTS = 2; public static final byte SOFT = 3; public static final byte DOMINATES = 4; public static final byte ANNOTATION = 5; // set when reading declare from aspect private ResolvedType declaringType; public static Declare read(VersionedDataInputStream s, ISourceContext context) throws IOException { byte kind = s.readByte(); switch (kind) { case ERROR_OR_WARNING: return DeclareErrorOrWarning.read(s, context); case DOMINATES: return DeclarePrecedence.read(s, context); case PARENTS: return DeclareParents.read(s, context); case SOFT: return DeclareSoft.read(s, context); case ANNOTATION: return DeclareAnnotation.read(s,context); default: throw new RuntimeException("unimplemented"); } } /** * Returns this declare mutated */ public abstract void resolve(IScope scope); /** * Returns a version of this declare element in which all references to type variables * are replaced with their bindings given in the map. */ public abstract Declare parameterizeWith(Map typeVariableBindingMap); /** * Indicates if this declare should be treated like advice. If true, the * declare will have no effect in an abstract aspect. It will be inherited by * any concrete aspects and will have an effect for each concrete aspect it * is ultimately inherited by. */ public abstract boolean isAdviceLike(); /** * Declares have methods in the .class file against which info can be stored * (for example, the annotation in the case of declare annotation). The * name is of the form ajc$declare_XXX_NNN where XXX can optionally be set in * this 'getNameSuffix()' method - depending on whether, at weave time, we * want to easily differentiate between the declare methods. */ public abstract String getNameSuffix(); public void setDeclaringType(ResolvedType aType) { this.declaringType = aType; } public ResolvedType getDeclaringType() { return declaringType; } }
161,502
Bug 161502 UnsupportedOperationException thrown: unable to parameterize unresolved type: Pjava/util/List<+Ljava/lang/Object; >;
Generic parameters (like List<? extends T>) in pointcuts throw UnsupportedOperationException. java.lang.UnsupportedOperationException at org.aspectj.weaver.UnresolvedType.parameterize(UnresolvedType.java: 220) at org.aspectj.weaver.patterns.ExactTypePattern.parameterizeWith (ExactTypePattern.java:244) at org.aspectj.weaver.patterns.SignaturePattern.parameterizeWith (SignaturePattern.java:265) at org.aspectj.weaver.patterns.KindedPointcut.parameterizeWith (KindedPointcut.java:381) at org.aspectj.weaver.bcel.BcelAdvice.parameterizeWith (BcelAdvice.java:93) at org.aspectj.weaver.ResolvedType.getDeclaredAdvice (ResolvedType.java:710) at org.aspectj.weaver.ResolvedType.getDeclaredShadowMungers (ResolvedType.java:739) at org.aspectj.weaver.ResolvedType.collectShadowMungers (ResolvedType.java:575) at org.aspectj.weaver.ResolvedType.collectCrosscuttingMembers (ResolvedType.java:504) at org.aspectj.weaver.CrosscuttingMembersSet.addOrReplaceAspect (CrosscuttingMembersSet.java:68) at org.aspectj.weaver.CrosscuttingMembersSet.addOrReplaceAspect (CrosscuttingMembersSet.java:57) at org.aspectj.weaver.bcel.BcelWeaver.prepareForWeave(BcelWeaver.java: 450) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.weave (AjCompilerAdapter.java:299) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.afterCompiling (AjCompilerAdapter.java:192) at org.aspectj.ajdt.internal.compiler.CompilerAdapter.ajc $afterReturning$org_aspectj_ajdt_internal_compiler_CompilerAdapter$2 $f9cc9ca0(CompilerAdapter.aj:70) at org.aspectj.org.eclipse.jdt.internal.compiler.Compiler.compile (Compiler.java:367) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.performCompilation (AjBuildManager.java:887) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.doBuild (AjBuildManager.java:244) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.batchBuild (AjBuildManager.java:163) at org.aspectj.ajde.internal.CompilerAdapter.compile (CompilerAdapter.java:122) at org.aspectj.ajde.internal.AspectJBuildManager$CompilerThread.run (AspectJBuildManager.java:191) UnsupportedOperationException thrown: unable to parameterize unresolved type: Pjava/util/List<+Ljava/lang/Object;>; To reproduce this exception compile the following code snippet. import java.util.ArrayList; import java.util.List; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; public class Main { public List<? extends Element> getElements() { return new ArrayList<Element>(); } class Element {}; @Aspect static abstract class Base<T> { @Around("call(List<? extends T> *.*(..))") public List<? extends T> elementList(ProceedingJoinPoint thisJoinPoint) { try { return (List<? extends T>)thisJoinPoint.proceed(); } catch (Throwable e) { throw new RuntimeException(e); } } } @Aspect static class Concrete extends Base<Element> {} public static void main(String[] args) { new Main().getElements(); } }
resolved fixed
7b40e7e
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2006-10-24T12:42:57Z"
"2006-10-19T01:06:40Z"
weaver/src/org/aspectj/weaver/patterns/DeclareAnnotation.java
/* ******************************************************************* * Copyright (c) 2005 IBM Corporation * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Eclipse Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Adrian Colyer initial implementation * Andy Clement got it working * ******************************************************************/ package org.aspectj.weaver.patterns; import java.io.DataOutputStream; import java.io.IOException; import java.util.Iterator; import java.util.Map; import org.aspectj.bridge.MessageUtil; import org.aspectj.weaver.AnnotationX; 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; public class DeclareAnnotation extends Declare { public static final Kind AT_TYPE = new Kind(1,"type"); public static final Kind AT_FIELD = new Kind(2,"field"); public static final Kind AT_METHOD = new Kind(3,"method"); public static final Kind AT_CONSTRUCTOR = new Kind(4,"constructor"); private Kind kind; private TypePattern typePattern; // for declare @type private SignaturePattern sigPattern; // for declare @field,@method,@constructor private String annotationMethod = "unknown"; private String annotationString = "@<annotation>"; private ResolvedType containingAspect; private AnnotationX annotation; /** * Captures type of declare annotation (method/type/field/constructor) */ public static class Kind { private final int id; private String s; private Kind(int n,String name) { id = n; s = name; } public int hashCode() { return (19 + 37*id); } public boolean equals(Object obj) { if (!(obj instanceof Kind)) return false; Kind other = (Kind) obj; return other.id == id; } public String toString() { return "at_"+s; } } public DeclareAnnotation(Kind kind, TypePattern typePattern) { this.typePattern = typePattern; this.kind = kind; } /** * Returns the string, useful before the real annotation has been resolved */ public String getAnnotationString() { return annotationString;} public DeclareAnnotation(Kind kind, SignaturePattern sigPattern) { this.sigPattern = sigPattern; this.kind = kind; } public boolean isExactPattern() { return typePattern instanceof ExactTypePattern; } public String getAnnotationMethod() { return annotationMethod;} public String toString() { StringBuffer ret = new StringBuffer(); ret.append("declare @"); ret.append(kind); ret.append(" : "); ret.append(typePattern != null ? typePattern.toString() : sigPattern.toString()); ret.append(" : "); ret.append(annotationString); return ret.toString(); } public Object accept(PatternNodeVisitor visitor, Object data) { return visitor.visit(this,data); } public void resolve(IScope scope) { if (!scope.getWorld().isInJava5Mode()) { String msg = null; if (kind == AT_TYPE) { msg = WeaverMessages.DECLARE_ATTYPE_ONLY_SUPPORTED_AT_JAVA5_LEVEL; } else if (kind == AT_METHOD) { msg = WeaverMessages.DECLARE_ATMETHOD_ONLY_SUPPORTED_AT_JAVA5_LEVEL;} else if (kind == AT_FIELD) { msg = WeaverMessages.DECLARE_ATFIELD_ONLY_SUPPORTED_AT_JAVA5_LEVEL;} else if (kind == AT_CONSTRUCTOR) { msg = WeaverMessages.DECLARE_ATCONS_ONLY_SUPPORTED_AT_JAVA5_LEVEL;} scope.message(MessageUtil.error(WeaverMessages.format(msg), getSourceLocation())); return; } if (typePattern != null) { typePattern = typePattern.resolveBindings(scope,Bindings.NONE,false,false); } if (sigPattern != null) { sigPattern = sigPattern.resolveBindings(scope,Bindings.NONE); } this.containingAspect = scope.getEnclosingType(); } public Declare parameterizeWith(Map typeVariableBindingMap) { DeclareAnnotation ret; if (this.kind == AT_TYPE) { ret = new DeclareAnnotation(kind,this.typePattern.parameterizeWith(typeVariableBindingMap)); } else { ret = new DeclareAnnotation(kind, this.sigPattern.parameterizeWith(typeVariableBindingMap)); } ret.annotationMethod = this.annotationMethod; ret.annotationString = this.annotationString; ret.containingAspect = this.containingAspect; ret.annotation = this.annotation; ret.copyLocationFrom(this); return ret; } public boolean isAdviceLike() { return false; } public void setAnnotationString(String as) { this.annotationString = as; } public void setAnnotationMethod(String methName){ this.annotationMethod = methName; } public boolean equals(Object obj) { if (!(obj instanceof DeclareAnnotation)) return false; DeclareAnnotation other = (DeclareAnnotation) obj; if (!this.kind.equals(other.kind)) return false; if (!this.annotationString.equals(other.annotationString)) return false; if (!this.annotationMethod.equals(other.annotationMethod)) return false; if (this.typePattern != null) { if (!typePattern.equals(other.typePattern)) return false; } if (this.sigPattern != null) { if (!sigPattern.equals(other.sigPattern)) return false; } return true; } public int hashCode() { int result = 19; result = 37*result + kind.hashCode(); result = 37*result + annotationString.hashCode(); result = 37*result + annotationMethod.hashCode(); if (typePattern != null) result = 37*result + typePattern.hashCode(); if (sigPattern != null) result = 37*result + sigPattern.hashCode(); return result; } /* (non-Javadoc) * @see org.aspectj.weaver.patterns.PatternNode#write(java.io.DataOutputStream) */ public void write(DataOutputStream s) throws IOException { s.writeByte(Declare.ANNOTATION); s.writeInt(kind.id); s.writeUTF(annotationString); s.writeUTF(annotationMethod); if (typePattern != null) typePattern.write(s); if (sigPattern != null) sigPattern.write(s); writeLocation(s); } public static Declare read(VersionedDataInputStream s, ISourceContext context) throws IOException { DeclareAnnotation ret = null; int kind = s.readInt(); String annotationString = s.readUTF(); String annotationMethod = s.readUTF(); TypePattern tp = null; SignaturePattern sp = null; switch (kind) { case 1: tp = TypePattern.read(s,context); ret = new DeclareAnnotation(AT_TYPE,tp); break; case 2: sp = SignaturePattern.read(s,context); ret = new DeclareAnnotation(AT_FIELD,sp); break; case 3: sp = SignaturePattern.read(s,context); ret = new DeclareAnnotation(AT_METHOD,sp); break; case 4: sp = SignaturePattern.read(s,context); ret = new DeclareAnnotation(AT_CONSTRUCTOR,sp); break; } // if (kind==AT_TYPE.id) { // tp = TypePattern.read(s,context); // ret = new DeclareAnnotation(AT_TYPE,tp); // } else { // sp = SignaturePattern.read(s,context); // ret = new DeclareAnnotation(kind,sp); // } ret.setAnnotationString(annotationString); ret.setAnnotationMethod(annotationMethod); ret.readLocation(context,s); return ret; } // public boolean getAnnotationIfMatches(ResolvedType onType) { // return (match(onType)); // } /** * For @constructor, @method, @field */ public boolean matches(ResolvedMember rm,World world) { return sigPattern.matches(rm,world,false); } /** * For @type */ public boolean matches(ResolvedType typeX) { if (!typePattern.matchesStatically(typeX)) return false; if (typeX.getWorld().getLint().typeNotExposedToWeaver.isEnabled() && !typeX.isExposedToWeaver()) { typeX.getWorld().getLint().typeNotExposedToWeaver.signal(typeX.getName(), getSourceLocation()); } return true; } public void setAspect(ResolvedType typeX) { containingAspect = typeX; } public UnresolvedType getAspect() { return containingAspect; } public void copyAnnotationTo(ResolvedType onType) { ensureAnnotationDiscovered(); if (!onType.hasAnnotation(annotation.getSignature())) { onType.addAnnotation(annotation); } } public AnnotationX getAnnotationX() { ensureAnnotationDiscovered(); return annotation; } /** * The annotation specified in the declare @type is stored against * a simple method of the form "ajc$declare_<NN>", this method * finds that method and retrieves the annotation */ private void ensureAnnotationDiscovered() { if (annotation!=null) return; for (Iterator iter = containingAspect.getMethods(); iter.hasNext();) { ResolvedMember member = (ResolvedMember) iter.next(); if (member.getName().equals(annotationMethod)) { annotation = member.getAnnotations()[0]; } } } public TypePattern getTypePattern() { return typePattern; } public SignaturePattern getSignaturePattern() { return sigPattern; } public boolean isStarredAnnotationPattern() { if (typePattern!=null) return typePattern.isStarAnnotation(); if (sigPattern!=null) return sigPattern.isStarAnnotation(); throw new RuntimeException("Impossible! what kind of deca is this: "+this); } public Kind getKind() { return kind; } public boolean isDeclareAtConstuctor() { return kind.equals(AT_CONSTRUCTOR); } public boolean isDeclareAtMethod() { return kind.equals(AT_METHOD); } public boolean isDeclareAtType() { return kind.equals(AT_TYPE); } public boolean isDeclareAtField() { return kind.equals(AT_FIELD); } /** * @return UnresolvedType for the annotation */ public UnresolvedType getAnnotationTypeX() { ensureAnnotationDiscovered(); return this.annotation.getSignature(); } /** * @return true if the annotation specified is allowed on a field */ public boolean isAnnotationAllowedOnField() { ensureAnnotationDiscovered(); return annotation.allowedOnField(); } public String getPatternAsString() { if (sigPattern!=null) return sigPattern.toString(); if (typePattern!=null) return typePattern.toString(); return "DONT KNOW"; } /** * Return true if this declare annotation could ever match something * in the specified type - only really able to make intelligent * decision if a type was specified in the sig/type pattern * signature. */ public boolean couldEverMatch(ResolvedType type) { // Haven't implemented variant for typePattern (doesn't seem worth it!) // BUGWARNING This test might not be sufficient for funny cases relating // to interfaces and the use of '+' - but it seems really important to // do something here so we don't iterate over all fields and all methods // in all types exposed to the weaver! So look out for bugs here and // we can update the test as appropriate. if (sigPattern!=null) return sigPattern.getDeclaringType().matches(type,TypePattern.STATIC).maybeTrue(); return true; } /** * Provide a name suffix so that we can tell the different declare annotations * forms apart in the AjProblemReporter */ public String getNameSuffix() { return getKind().toString(); } }
161,502
Bug 161502 UnsupportedOperationException thrown: unable to parameterize unresolved type: Pjava/util/List<+Ljava/lang/Object; >;
Generic parameters (like List<? extends T>) in pointcuts throw UnsupportedOperationException. java.lang.UnsupportedOperationException at org.aspectj.weaver.UnresolvedType.parameterize(UnresolvedType.java: 220) at org.aspectj.weaver.patterns.ExactTypePattern.parameterizeWith (ExactTypePattern.java:244) at org.aspectj.weaver.patterns.SignaturePattern.parameterizeWith (SignaturePattern.java:265) at org.aspectj.weaver.patterns.KindedPointcut.parameterizeWith (KindedPointcut.java:381) at org.aspectj.weaver.bcel.BcelAdvice.parameterizeWith (BcelAdvice.java:93) at org.aspectj.weaver.ResolvedType.getDeclaredAdvice (ResolvedType.java:710) at org.aspectj.weaver.ResolvedType.getDeclaredShadowMungers (ResolvedType.java:739) at org.aspectj.weaver.ResolvedType.collectShadowMungers (ResolvedType.java:575) at org.aspectj.weaver.ResolvedType.collectCrosscuttingMembers (ResolvedType.java:504) at org.aspectj.weaver.CrosscuttingMembersSet.addOrReplaceAspect (CrosscuttingMembersSet.java:68) at org.aspectj.weaver.CrosscuttingMembersSet.addOrReplaceAspect (CrosscuttingMembersSet.java:57) at org.aspectj.weaver.bcel.BcelWeaver.prepareForWeave(BcelWeaver.java: 450) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.weave (AjCompilerAdapter.java:299) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.afterCompiling (AjCompilerAdapter.java:192) at org.aspectj.ajdt.internal.compiler.CompilerAdapter.ajc $afterReturning$org_aspectj_ajdt_internal_compiler_CompilerAdapter$2 $f9cc9ca0(CompilerAdapter.aj:70) at org.aspectj.org.eclipse.jdt.internal.compiler.Compiler.compile (Compiler.java:367) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.performCompilation (AjBuildManager.java:887) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.doBuild (AjBuildManager.java:244) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.batchBuild (AjBuildManager.java:163) at org.aspectj.ajde.internal.CompilerAdapter.compile (CompilerAdapter.java:122) at org.aspectj.ajde.internal.AspectJBuildManager$CompilerThread.run (AspectJBuildManager.java:191) UnsupportedOperationException thrown: unable to parameterize unresolved type: Pjava/util/List<+Ljava/lang/Object;>; To reproduce this exception compile the following code snippet. import java.util.ArrayList; import java.util.List; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; public class Main { public List<? extends Element> getElements() { return new ArrayList<Element>(); } class Element {}; @Aspect static abstract class Base<T> { @Around("call(List<? extends T> *.*(..))") public List<? extends T> elementList(ProceedingJoinPoint thisJoinPoint) { try { return (List<? extends T>)thisJoinPoint.proceed(); } catch (Throwable e) { throw new RuntimeException(e); } } } @Aspect static class Concrete extends Base<Element> {} public static void main(String[] args) { new Main().getElements(); } }
resolved fixed
7b40e7e
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2006-10-24T12:42:57Z"
"2006-10-19T01:06:40Z"
weaver/src/org/aspectj/weaver/patterns/DeclareErrorOrWarning.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.DataOutputStream; import java.io.IOException; import java.util.Map; import org.aspectj.weaver.ISourceContext; import org.aspectj.weaver.VersionedDataInputStream; public class DeclareErrorOrWarning extends Declare { private boolean isError; private Pointcut pointcut; private String message; public DeclareErrorOrWarning(boolean isError, Pointcut pointcut, String message) { this.isError = isError; this.pointcut = pointcut; this.message = message; } /** * returns "declare warning: <message>" or "declare error: <message>" */ public String toString() { StringBuffer buf = new StringBuffer(); buf.append("declare "); if (isError) buf.append("error: "); else buf.append("warning: "); buf.append(pointcut); buf.append(": "); buf.append("\""); buf.append(message); buf.append("\";"); return buf.toString(); } public boolean equals(Object other) { if (!(other instanceof DeclareErrorOrWarning)) return false; DeclareErrorOrWarning o = (DeclareErrorOrWarning)other; return (o.isError == isError) && o.pointcut.equals(pointcut) && o.message.equals(message); } public int hashCode() { int result = isError ? 19 : 23; result = 37*result + pointcut.hashCode(); result = 37*result + message.hashCode(); return result; } public Object accept(PatternNodeVisitor visitor, Object data) { return visitor.visit(this,data); } public void write(DataOutputStream s) throws IOException { s.writeByte(Declare.ERROR_OR_WARNING); s.writeBoolean(isError); pointcut.write(s); s.writeUTF(message); writeLocation(s); } public static Declare read(VersionedDataInputStream s, ISourceContext context) throws IOException { Declare ret = new DeclareErrorOrWarning( s.readBoolean(), Pointcut.read(s, context), s.readUTF() ); ret.readLocation(context, s); return ret; } public boolean isError() { return isError; } public String getMessage() { return message; } public Pointcut getPointcut() { return pointcut; } public void resolve(IScope scope) { pointcut = pointcut.resolve(scope); } public Declare parameterizeWith(Map typeVariableBindingMap) { Declare ret = new DeclareErrorOrWarning(isError,pointcut.parameterizeWith(typeVariableBindingMap),message); ret.copyLocationFrom(this); return ret; } public boolean isAdviceLike() { return true; } public String getNameSuffix() { return "eow"; } /** * returns "declare warning" or "declare error" */ public String getName() { StringBuffer buf = new StringBuffer(); buf.append("declare "); if (isError) buf.append("error"); else buf.append("warning"); return buf.toString(); } }
161,502
Bug 161502 UnsupportedOperationException thrown: unable to parameterize unresolved type: Pjava/util/List<+Ljava/lang/Object; >;
Generic parameters (like List<? extends T>) in pointcuts throw UnsupportedOperationException. java.lang.UnsupportedOperationException at org.aspectj.weaver.UnresolvedType.parameterize(UnresolvedType.java: 220) at org.aspectj.weaver.patterns.ExactTypePattern.parameterizeWith (ExactTypePattern.java:244) at org.aspectj.weaver.patterns.SignaturePattern.parameterizeWith (SignaturePattern.java:265) at org.aspectj.weaver.patterns.KindedPointcut.parameterizeWith (KindedPointcut.java:381) at org.aspectj.weaver.bcel.BcelAdvice.parameterizeWith (BcelAdvice.java:93) at org.aspectj.weaver.ResolvedType.getDeclaredAdvice (ResolvedType.java:710) at org.aspectj.weaver.ResolvedType.getDeclaredShadowMungers (ResolvedType.java:739) at org.aspectj.weaver.ResolvedType.collectShadowMungers (ResolvedType.java:575) at org.aspectj.weaver.ResolvedType.collectCrosscuttingMembers (ResolvedType.java:504) at org.aspectj.weaver.CrosscuttingMembersSet.addOrReplaceAspect (CrosscuttingMembersSet.java:68) at org.aspectj.weaver.CrosscuttingMembersSet.addOrReplaceAspect (CrosscuttingMembersSet.java:57) at org.aspectj.weaver.bcel.BcelWeaver.prepareForWeave(BcelWeaver.java: 450) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.weave (AjCompilerAdapter.java:299) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.afterCompiling (AjCompilerAdapter.java:192) at org.aspectj.ajdt.internal.compiler.CompilerAdapter.ajc $afterReturning$org_aspectj_ajdt_internal_compiler_CompilerAdapter$2 $f9cc9ca0(CompilerAdapter.aj:70) at org.aspectj.org.eclipse.jdt.internal.compiler.Compiler.compile (Compiler.java:367) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.performCompilation (AjBuildManager.java:887) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.doBuild (AjBuildManager.java:244) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.batchBuild (AjBuildManager.java:163) at org.aspectj.ajde.internal.CompilerAdapter.compile (CompilerAdapter.java:122) at org.aspectj.ajde.internal.AspectJBuildManager$CompilerThread.run (AspectJBuildManager.java:191) UnsupportedOperationException thrown: unable to parameterize unresolved type: Pjava/util/List<+Ljava/lang/Object;>; To reproduce this exception compile the following code snippet. import java.util.ArrayList; import java.util.List; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; public class Main { public List<? extends Element> getElements() { return new ArrayList<Element>(); } class Element {}; @Aspect static abstract class Base<T> { @Around("call(List<? extends T> *.*(..))") public List<? extends T> elementList(ProceedingJoinPoint thisJoinPoint) { try { return (List<? extends T>)thisJoinPoint.proceed(); } catch (Throwable e) { throw new RuntimeException(e); } } } @Aspect static class Concrete extends Base<Element> {} public static void main(String[] args) { new Main().getElements(); } }
resolved fixed
7b40e7e
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2006-10-24T12:42:57Z"
"2006-10-19T01:06:40Z"
weaver/src/org/aspectj/weaver/patterns/DeclareParents.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.DataOutputStream; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.Map; import org.aspectj.bridge.IMessage; import org.aspectj.bridge.ISourceLocation; import org.aspectj.bridge.Message; import org.aspectj.weaver.ISourceContext; 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; public class DeclareParents extends Declare { private TypePattern child; private TypePatternList parents; private boolean isWildChild = false; private boolean isExtends = true; // private String[] typeVariablesInScope = new String[0]; // AspectJ 5 extension for generic types public DeclareParents(TypePattern child, List parents, boolean isExtends) { this(child, new TypePatternList(parents),isExtends); } private DeclareParents(TypePattern child, TypePatternList parents, boolean isExtends) { this.child = child; this.parents = parents; this.isExtends = isExtends; if (child instanceof WildTypePattern) isWildChild = true; } // public String[] getTypeParameterNames() { // return this.typeVariablesInScope; // } // // public void setTypeParametersInScope(String[] typeParameters) { // this.typeVariablesInScope = typeParameters; // } public boolean match(ResolvedType typeX) { if (!child.matchesStatically(typeX)) return false; if (typeX.getWorld().getLint().typeNotExposedToWeaver.isEnabled() && !typeX.isExposedToWeaver()) { typeX.getWorld().getLint().typeNotExposedToWeaver.signal(typeX.getName(), getSourceLocation()); } return true; } public Object accept(PatternNodeVisitor visitor, Object data) { return visitor.visit(this,data); } public Declare parameterizeWith(Map typeVariableBindingMap) { DeclareParents ret = new DeclareParents( child.parameterizeWith(typeVariableBindingMap), parents.parameterizeWith(typeVariableBindingMap), isExtends); ret.copyLocationFrom(this); return ret; } public String toString() { StringBuffer buf = new StringBuffer(); buf.append("declare parents: "); buf.append(child); buf.append(isExtends ? " extends " : " implements "); //extends and implements are treated equivalently buf.append(parents); buf.append(";"); return buf.toString(); } public boolean equals(Object other) { if (!(other instanceof DeclareParents)) return false; DeclareParents o = (DeclareParents)other; return o.child.equals(child) && o.parents.equals(parents); } //??? cache this public int hashCode() { int result = 23; result = 37*result + child.hashCode(); result = 37*result + parents.hashCode(); return result; } public void write(DataOutputStream s) throws IOException { s.writeByte(Declare.PARENTS); child.write(s); parents.write(s); // s.writeInt(typeVariablesInScope.length); // for (int i = 0; i < typeVariablesInScope.length; i++) { // s.writeUTF(typeVariablesInScope[i]); // } writeLocation(s); } public static Declare read(VersionedDataInputStream s, ISourceContext context) throws IOException { DeclareParents ret = new DeclareParents(TypePattern.read(s, context), TypePatternList.read(s, context),true); // if (s.getMajorVersion()>=AjAttribute.WeaverVersionInfo.WEAVER_VERSION_MAJOR_AJ150) { // int numTypeVariablesInScope = s.readInt(); // ret.typeVariablesInScope = new String[numTypeVariablesInScope]; // for (int i = 0; i < numTypeVariablesInScope; i++) { // ret.typeVariablesInScope[i] = s.readUTF(); // } // } ret.readLocation(context, s); return ret; } public boolean parentsIncludeInterface(World w) { for (int i = 0; i < parents.size(); i++) { if (parents.get(i).getExactType().resolve(w).isInterface()) return true; } return false; } public boolean parentsIncludeClass(World w) { for (int i = 0; i < parents.size(); i++) { if (parents.get(i).getExactType().resolve(w).isClass()) return true; } return false; } public void resolve(IScope scope) { // ScopeWithTypeVariables resolutionScope = new ScopeWithTypeVariables(typeVariablesInScope,scope); child = child.resolveBindings(scope, Bindings.NONE, false, false); parents = parents.resolveBindings(scope, Bindings.NONE, false, true); // Could assert this ... // for (int i=0; i < parents.size(); i++) { // parents.get(i).assertExactType(scope.getMessageHandler()); // } } public TypePatternList getParents() { return parents; } public TypePattern getChild() { return child; } // note - will always return true after deserialization, this doesn't affect weaver public boolean isExtends() { return this.isExtends; } public boolean isAdviceLike() { return false; } private ResolvedType maybeGetNewParent(ResolvedType targetType, TypePattern typePattern, World world,boolean reportErrors) { if (typePattern == TypePattern.NO) return null; // already had an error here UnresolvedType iType = typePattern.getExactType(); ResolvedType parentType = iType.resolve(world); if (targetType.equals(world.getCoreType(UnresolvedType.OBJECT))) { world.showMessage(IMessage.ERROR, WeaverMessages.format(WeaverMessages.DECP_OBJECT), this.getSourceLocation(), null); return null; } // Ensure the target doesn't already have an // alternate parameterization of the generic type on it if (parentType.isParameterizedType() || parentType.isRawType()) { // Let's take a look at the parents we already have boolean isOK = verifyNoInheritedAlternateParameterization(targetType,parentType,world); if (!isOK) return null; } if (parentType.isAssignableFrom(targetType)) return null; // already a parent // Enum types that are targetted for decp through a wild type pattern get linted if (reportErrors && isWildChild && targetType.isEnum()) { world.getLint().enumAsTargetForDecpIgnored.signal(targetType.toString(),getSourceLocation()); } // Annotation types that are targetted for decp through a wild type pattern get linted if (reportErrors && isWildChild && targetType.isAnnotation()) { world.getLint().annotationAsTargetForDecpIgnored.signal(targetType.toString(),getSourceLocation()); } // 1. Can't use decp to make an enum/annotation type implement an interface if (targetType.isEnum() && parentType.isInterface()) { if (reportErrors && !isWildChild) { world.showMessage(IMessage.ERROR, WeaverMessages.format(WeaverMessages.CANT_DECP_ON_ENUM_TO_IMPL_INTERFACE,targetType),getSourceLocation(),null); } return null; } if (targetType.isAnnotation() && parentType.isInterface()) { if (reportErrors && !isWildChild) { world.showMessage(IMessage.ERROR,WeaverMessages.format(WeaverMessages.CANT_DECP_ON_ANNOTATION_TO_IMPL_INTERFACE,targetType),getSourceLocation(),null); } return null; } // 2. Can't use decp to change supertype of an enum/annotation if (targetType.isEnum() && parentType.isClass()) { if (reportErrors && !isWildChild) { world.showMessage(IMessage.ERROR,WeaverMessages.format(WeaverMessages.CANT_DECP_ON_ENUM_TO_EXTEND_CLASS,targetType),getSourceLocation(),null); } return null; } if (targetType.isAnnotation() && parentType.isClass()) { if (reportErrors && !isWildChild) { world.showMessage(IMessage.ERROR,WeaverMessages.format(WeaverMessages.CANT_DECP_ON_ANNOTATION_TO_EXTEND_CLASS,targetType),getSourceLocation(),null); } return null; } // 3. Can't use decp to declare java.lang.Enum/java.lang.annotation.Annotation as the parent of a type if (parentType.getSignature().equals(UnresolvedType.ENUM.getSignature())) { if (reportErrors && !isWildChild) { world.showMessage(IMessage.ERROR, WeaverMessages.format(WeaverMessages.CANT_DECP_TO_MAKE_ENUM_SUPERTYPE,targetType),getSourceLocation(),null); } return null; } if (parentType.getSignature().equals(UnresolvedType.ANNOTATION.getSignature())) { if (reportErrors && !isWildChild) { world.showMessage(IMessage.ERROR, WeaverMessages.format(WeaverMessages.CANT_DECP_TO_MAKE_ANNOTATION_SUPERTYPE,targetType),getSourceLocation(),null); } return null; } if (parentType.isAssignableFrom(targetType)) return null; // already a parent if (targetType.isAssignableFrom(parentType)) { world.showMessage(IMessage.ERROR, WeaverMessages.format(WeaverMessages.CANT_EXTEND_SELF,targetType.getName()), this.getSourceLocation(), null ); return null; } if (parentType.isClass()) { if (targetType.isInterface()) { world.showMessage(IMessage.ERROR, WeaverMessages.format(WeaverMessages.INTERFACE_CANT_EXTEND_CLASS), this.getSourceLocation(), null ); return null; // how to handle xcutting errors??? } if (!targetType.getSuperclass().isAssignableFrom(parentType)) { world.showMessage(IMessage.ERROR, WeaverMessages.format(WeaverMessages.DECP_HIERARCHY_ERROR, iType.getName(), targetType.getSuperclass().getName()), this.getSourceLocation(), null ); return null; } else { return parentType; } } else { return parentType; } } /** * This method looks through the type hierarchy for some target type - it is attempting to * find an existing parameterization that clashes with the new parent that the user * wants to apply to the type. If it finds an existing parameterization that matches the * new one, it silently completes, if it finds one that clashes (e.g. a type already has * A<String> when the user wants to add A<Number>) then it will produce an error. * * It uses recursion and exits recursion on hitting 'jlObject' * * Related bugzilla entries: pr110788 */ private boolean verifyNoInheritedAlternateParameterization(ResolvedType typeToVerify,ResolvedType newParent,World world) { if (typeToVerify.equals(ResolvedType.OBJECT)) return true; ResolvedType newParentGenericType = newParent.getGenericType(); Iterator iter = typeToVerify.getDirectSupertypes(); while (iter.hasNext()) { ResolvedType supertype = (ResolvedType)iter.next(); if ( ((supertype.isRawType() && newParent.isParameterizedType()) || (supertype.isParameterizedType() && newParent.isRawType())) && newParentGenericType.equals(supertype.getGenericType())) { // new parent is a parameterized type, but this is a raw type world.getMessageHandler().handleMessage(new Message( WeaverMessages.format(WeaverMessages.CANT_DECP_MULTIPLE_PARAMETERIZATIONS,newParent.getName(),typeToVerify.getName(),supertype.getName()), getSourceLocation(), true, new ISourceLocation[]{typeToVerify.getSourceLocation()})); return false; } if (supertype.isParameterizedType()) { ResolvedType generictype = supertype.getGenericType(); // If the generic types are compatible but the parameterizations aren't then we have a problem if (generictype.isAssignableFrom(newParentGenericType) && !supertype.isAssignableFrom(newParent)) { world.getMessageHandler().handleMessage(new Message( WeaverMessages.format(WeaverMessages.CANT_DECP_MULTIPLE_PARAMETERIZATIONS,newParent.getName(),typeToVerify.getName(),supertype.getName()), getSourceLocation(), true, new ISourceLocation[]{typeToVerify.getSourceLocation()})); return false; } } return verifyNoInheritedAlternateParameterization(supertype,newParent,world); } return true; } public List/*<ResolvedType>*/ findMatchingNewParents(ResolvedType onType,boolean reportErrors) { if (onType.isRawType()) onType = onType.getGenericType(); if (!match(onType)) return Collections.EMPTY_LIST; List ret = new ArrayList(); for (int i=0; i < parents.size(); i++) { ResolvedType t = maybeGetNewParent(onType, parents.get(i), onType.getWorld(),reportErrors); if (t != null) ret.add(t); } return ret; } public String getNameSuffix() { return "parents"; } }
161,502
Bug 161502 UnsupportedOperationException thrown: unable to parameterize unresolved type: Pjava/util/List<+Ljava/lang/Object; >;
Generic parameters (like List<? extends T>) in pointcuts throw UnsupportedOperationException. java.lang.UnsupportedOperationException at org.aspectj.weaver.UnresolvedType.parameterize(UnresolvedType.java: 220) at org.aspectj.weaver.patterns.ExactTypePattern.parameterizeWith (ExactTypePattern.java:244) at org.aspectj.weaver.patterns.SignaturePattern.parameterizeWith (SignaturePattern.java:265) at org.aspectj.weaver.patterns.KindedPointcut.parameterizeWith (KindedPointcut.java:381) at org.aspectj.weaver.bcel.BcelAdvice.parameterizeWith (BcelAdvice.java:93) at org.aspectj.weaver.ResolvedType.getDeclaredAdvice (ResolvedType.java:710) at org.aspectj.weaver.ResolvedType.getDeclaredShadowMungers (ResolvedType.java:739) at org.aspectj.weaver.ResolvedType.collectShadowMungers (ResolvedType.java:575) at org.aspectj.weaver.ResolvedType.collectCrosscuttingMembers (ResolvedType.java:504) at org.aspectj.weaver.CrosscuttingMembersSet.addOrReplaceAspect (CrosscuttingMembersSet.java:68) at org.aspectj.weaver.CrosscuttingMembersSet.addOrReplaceAspect (CrosscuttingMembersSet.java:57) at org.aspectj.weaver.bcel.BcelWeaver.prepareForWeave(BcelWeaver.java: 450) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.weave (AjCompilerAdapter.java:299) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.afterCompiling (AjCompilerAdapter.java:192) at org.aspectj.ajdt.internal.compiler.CompilerAdapter.ajc $afterReturning$org_aspectj_ajdt_internal_compiler_CompilerAdapter$2 $f9cc9ca0(CompilerAdapter.aj:70) at org.aspectj.org.eclipse.jdt.internal.compiler.Compiler.compile (Compiler.java:367) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.performCompilation (AjBuildManager.java:887) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.doBuild (AjBuildManager.java:244) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.batchBuild (AjBuildManager.java:163) at org.aspectj.ajde.internal.CompilerAdapter.compile (CompilerAdapter.java:122) at org.aspectj.ajde.internal.AspectJBuildManager$CompilerThread.run (AspectJBuildManager.java:191) UnsupportedOperationException thrown: unable to parameterize unresolved type: Pjava/util/List<+Ljava/lang/Object;>; To reproduce this exception compile the following code snippet. import java.util.ArrayList; import java.util.List; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; public class Main { public List<? extends Element> getElements() { return new ArrayList<Element>(); } class Element {}; @Aspect static abstract class Base<T> { @Around("call(List<? extends T> *.*(..))") public List<? extends T> elementList(ProceedingJoinPoint thisJoinPoint) { try { return (List<? extends T>)thisJoinPoint.proceed(); } catch (Throwable e) { throw new RuntimeException(e); } } } @Aspect static class Concrete extends Base<Element> {} public static void main(String[] args) { new Main().getElements(); } }
resolved fixed
7b40e7e
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2006-10-24T12:42:57Z"
"2006-10-19T01:06:40Z"
weaver/src/org/aspectj/weaver/patterns/DeclarePrecedence.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.DataOutputStream; import java.io.IOException; import java.util.List; import java.util.Map; import org.aspectj.bridge.IMessage; import org.aspectj.weaver.ISourceContext; import org.aspectj.weaver.ResolvedType; import org.aspectj.weaver.VersionedDataInputStream; import org.aspectj.weaver.WeaverMessages; public class DeclarePrecedence extends Declare { private TypePatternList patterns; public DeclarePrecedence(List patterns) { this(new TypePatternList(patterns)); } private DeclarePrecedence(TypePatternList patterns) { this.patterns = patterns; } public Object accept(PatternNodeVisitor visitor, Object data) { return visitor.visit(this,data); } public Declare parameterizeWith(Map typeVariableBindingMap) { DeclarePrecedence ret = new DeclarePrecedence(this.patterns.parameterizeWith(typeVariableBindingMap)); ret.copyLocationFrom(this); return ret; } public String toString() { StringBuffer buf = new StringBuffer(); buf.append("declare precedence: "); buf.append(patterns); buf.append(";"); return buf.toString(); } public boolean equals(Object other) { if (!(other instanceof DeclarePrecedence)) return false; DeclarePrecedence o = (DeclarePrecedence)other; return o.patterns.equals(patterns); } public int hashCode() { return patterns.hashCode(); } public void write(DataOutputStream s) throws IOException { s.writeByte(Declare.DOMINATES); patterns.write(s); writeLocation(s); } public static Declare read(VersionedDataInputStream s, ISourceContext context) throws IOException { Declare ret = new DeclarePrecedence(TypePatternList.read(s, context)); ret.readLocation(context, s); return ret; } public void resolve(IScope scope) { patterns = patterns.resolveBindings(scope, Bindings.NONE, false, false); boolean seenStar = false; for (int i=0; i < patterns.size(); i++) { TypePattern pi = patterns.get(i); if (pi.isStar()) { if (seenStar) { scope.getWorld().showMessage(IMessage.ERROR, WeaverMessages.format(WeaverMessages.TWO_STARS_IN_PRECEDENCE), pi.getSourceLocation(), null); } seenStar = true; continue; } ResolvedType exactType = pi.getExactType().resolve(scope.getWorld()); if (exactType.isMissing()) continue; // Cannot do a dec prec specifying a non-aspect types unless suffixed with a '+' if (!exactType.isAspect() && !pi.isIncludeSubtypes() && !exactType.isTypeVariableReference()) { scope.getWorld().showMessage(IMessage.ERROR, WeaverMessages.format(WeaverMessages.CLASSES_IN_PRECEDENCE,exactType.getName()), pi.getSourceLocation(),null); } for (int j=0; j < patterns.size(); j++) { if (j == i) continue; TypePattern pj = patterns.get(j); if (pj.isStar()) continue; if (pj.matchesStatically(exactType)) { scope.getWorld().showMessage(IMessage.ERROR, WeaverMessages.format(WeaverMessages.TWO_PATTERN_MATCHES_IN_PRECEDENCE,exactType.getName()), pi.getSourceLocation(), pj.getSourceLocation()); } } } } public TypePatternList getPatterns() { return patterns; } private int matchingIndex(ResolvedType a) { int knownMatch = -1; int starMatch = -1; for (int i=0, len=patterns.size(); i < len; i++) { TypePattern p = patterns.get(i); if (p.isStar()) { starMatch = i; } else if (p.matchesStatically(a)) { if (knownMatch != -1) { a.getWorld().showMessage(IMessage.ERROR, WeaverMessages.format(WeaverMessages.MULTIPLE_MATCHES_IN_PRECEDENCE,a,patterns.get(knownMatch),p), patterns.get(knownMatch).getSourceLocation(), p.getSourceLocation()); return -1; } else { knownMatch = i; } } } if (knownMatch == -1) return starMatch; else return knownMatch; } public int compare(ResolvedType aspect1, ResolvedType aspect2) { int index1 = matchingIndex(aspect1); int index2 = matchingIndex(aspect2); //System.out.println("a1: " + aspect1 + ", " + aspect2 + " = " + index1 + ", " + index2); if (index1 == -1 || index2 == -1) return 0; if (index1 == index2) return 0; else if (index1 > index2) return -1; else return +1; } public boolean isAdviceLike() { return false; } public String getNameSuffix() { return "precedence"; } }
161,502
Bug 161502 UnsupportedOperationException thrown: unable to parameterize unresolved type: Pjava/util/List<+Ljava/lang/Object; >;
Generic parameters (like List<? extends T>) in pointcuts throw UnsupportedOperationException. java.lang.UnsupportedOperationException at org.aspectj.weaver.UnresolvedType.parameterize(UnresolvedType.java: 220) at org.aspectj.weaver.patterns.ExactTypePattern.parameterizeWith (ExactTypePattern.java:244) at org.aspectj.weaver.patterns.SignaturePattern.parameterizeWith (SignaturePattern.java:265) at org.aspectj.weaver.patterns.KindedPointcut.parameterizeWith (KindedPointcut.java:381) at org.aspectj.weaver.bcel.BcelAdvice.parameterizeWith (BcelAdvice.java:93) at org.aspectj.weaver.ResolvedType.getDeclaredAdvice (ResolvedType.java:710) at org.aspectj.weaver.ResolvedType.getDeclaredShadowMungers (ResolvedType.java:739) at org.aspectj.weaver.ResolvedType.collectShadowMungers (ResolvedType.java:575) at org.aspectj.weaver.ResolvedType.collectCrosscuttingMembers (ResolvedType.java:504) at org.aspectj.weaver.CrosscuttingMembersSet.addOrReplaceAspect (CrosscuttingMembersSet.java:68) at org.aspectj.weaver.CrosscuttingMembersSet.addOrReplaceAspect (CrosscuttingMembersSet.java:57) at org.aspectj.weaver.bcel.BcelWeaver.prepareForWeave(BcelWeaver.java: 450) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.weave (AjCompilerAdapter.java:299) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.afterCompiling (AjCompilerAdapter.java:192) at org.aspectj.ajdt.internal.compiler.CompilerAdapter.ajc $afterReturning$org_aspectj_ajdt_internal_compiler_CompilerAdapter$2 $f9cc9ca0(CompilerAdapter.aj:70) at org.aspectj.org.eclipse.jdt.internal.compiler.Compiler.compile (Compiler.java:367) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.performCompilation (AjBuildManager.java:887) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.doBuild (AjBuildManager.java:244) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.batchBuild (AjBuildManager.java:163) at org.aspectj.ajde.internal.CompilerAdapter.compile (CompilerAdapter.java:122) at org.aspectj.ajde.internal.AspectJBuildManager$CompilerThread.run (AspectJBuildManager.java:191) UnsupportedOperationException thrown: unable to parameterize unresolved type: Pjava/util/List<+Ljava/lang/Object;>; To reproduce this exception compile the following code snippet. import java.util.ArrayList; import java.util.List; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; public class Main { public List<? extends Element> getElements() { return new ArrayList<Element>(); } class Element {}; @Aspect static abstract class Base<T> { @Around("call(List<? extends T> *.*(..))") public List<? extends T> elementList(ProceedingJoinPoint thisJoinPoint) { try { return (List<? extends T>)thisJoinPoint.proceed(); } catch (Throwable e) { throw new RuntimeException(e); } } } @Aspect static class Concrete extends Base<Element> {} public static void main(String[] args) { new Main().getElements(); } }
resolved fixed
7b40e7e
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2006-10-24T12:42:57Z"
"2006-10-19T01:06:40Z"
weaver/src/org/aspectj/weaver/patterns/DeclareSoft.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.DataOutputStream; import java.io.IOException; import java.util.Map; import org.aspectj.bridge.IMessage; import org.aspectj.weaver.ISourceContext; import org.aspectj.weaver.ResolvedType; import org.aspectj.weaver.UnresolvedType; import org.aspectj.weaver.VersionedDataInputStream; import org.aspectj.weaver.WeaverMessages; public class DeclareSoft extends Declare { private TypePattern exception; private Pointcut pointcut; public DeclareSoft(TypePattern exception, Pointcut pointcut) { this.exception = exception; this.pointcut = pointcut; } public Object accept(PatternNodeVisitor visitor, Object data) { return visitor.visit(this,data); } public Declare parameterizeWith(Map typeVariableBindingMap) { DeclareSoft ret = new DeclareSoft( exception.parameterizeWith(typeVariableBindingMap), pointcut.parameterizeWith(typeVariableBindingMap)); ret.copyLocationFrom(this); return ret; } public String toString() { StringBuffer buf = new StringBuffer(); buf.append("declare soft: "); buf.append(exception); buf.append(": "); buf.append(pointcut); buf.append(";"); return buf.toString(); } public boolean equals(Object other) { if (!(other instanceof DeclareSoft)) return false; DeclareSoft o = (DeclareSoft)other; return o.pointcut.equals(pointcut) && o.exception.equals(exception); } public int hashCode() { int result = 19; result = 37*result + pointcut.hashCode(); result = 37*result + exception.hashCode(); return result; } public void write(DataOutputStream s) throws IOException { s.writeByte(Declare.SOFT); exception.write(s); pointcut.write(s); writeLocation(s); } public static Declare read(VersionedDataInputStream s, ISourceContext context) throws IOException { Declare ret = new DeclareSoft( TypePattern.read(s, context), Pointcut.read(s, context) ); ret.readLocation(context, s); return ret; } public Pointcut getPointcut() { return pointcut; } public TypePattern getException() { return exception; } public void resolve(IScope scope) { exception = exception.resolveBindings(scope, null, false, true); ResolvedType excType = exception.getExactType().resolve(scope.getWorld()); if (!excType.isMissing()) { if (excType.isTypeVariableReference()) { // a declare soft in a generic abstract aspect, we need to check the upper bound excType = excType.getUpperBound().resolve(scope.getWorld()); } if (!scope.getWorld().getCoreType(UnresolvedType.THROWABLE).isAssignableFrom(excType)) { scope.getWorld().showMessage(IMessage.ERROR, WeaverMessages.format(WeaverMessages.NOT_THROWABLE,excType.getName()), exception.getSourceLocation(), null); pointcut = Pointcut.makeMatchesNothing(Pointcut.RESOLVED); return; } // ENH 42743 suggests that we don't soften runtime exceptions. if (scope.getWorld().getCoreType(UnresolvedType.RUNTIME_EXCEPTION).isAssignableFrom(excType)) { scope.getWorld().getLint().runtimeExceptionNotSoftened.signal( new String[]{excType.getName()}, exception.getSourceLocation(),null); pointcut = Pointcut.makeMatchesNothing(Pointcut.RESOLVED); return; } } pointcut = pointcut.resolve(scope); } public boolean isAdviceLike() { return true; } public String getNameSuffix() { return "soft"; } }
161,502
Bug 161502 UnsupportedOperationException thrown: unable to parameterize unresolved type: Pjava/util/List<+Ljava/lang/Object; >;
Generic parameters (like List<? extends T>) in pointcuts throw UnsupportedOperationException. java.lang.UnsupportedOperationException at org.aspectj.weaver.UnresolvedType.parameterize(UnresolvedType.java: 220) at org.aspectj.weaver.patterns.ExactTypePattern.parameterizeWith (ExactTypePattern.java:244) at org.aspectj.weaver.patterns.SignaturePattern.parameterizeWith (SignaturePattern.java:265) at org.aspectj.weaver.patterns.KindedPointcut.parameterizeWith (KindedPointcut.java:381) at org.aspectj.weaver.bcel.BcelAdvice.parameterizeWith (BcelAdvice.java:93) at org.aspectj.weaver.ResolvedType.getDeclaredAdvice (ResolvedType.java:710) at org.aspectj.weaver.ResolvedType.getDeclaredShadowMungers (ResolvedType.java:739) at org.aspectj.weaver.ResolvedType.collectShadowMungers (ResolvedType.java:575) at org.aspectj.weaver.ResolvedType.collectCrosscuttingMembers (ResolvedType.java:504) at org.aspectj.weaver.CrosscuttingMembersSet.addOrReplaceAspect (CrosscuttingMembersSet.java:68) at org.aspectj.weaver.CrosscuttingMembersSet.addOrReplaceAspect (CrosscuttingMembersSet.java:57) at org.aspectj.weaver.bcel.BcelWeaver.prepareForWeave(BcelWeaver.java: 450) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.weave (AjCompilerAdapter.java:299) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.afterCompiling (AjCompilerAdapter.java:192) at org.aspectj.ajdt.internal.compiler.CompilerAdapter.ajc $afterReturning$org_aspectj_ajdt_internal_compiler_CompilerAdapter$2 $f9cc9ca0(CompilerAdapter.aj:70) at org.aspectj.org.eclipse.jdt.internal.compiler.Compiler.compile (Compiler.java:367) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.performCompilation (AjBuildManager.java:887) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.doBuild (AjBuildManager.java:244) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.batchBuild (AjBuildManager.java:163) at org.aspectj.ajde.internal.CompilerAdapter.compile (CompilerAdapter.java:122) at org.aspectj.ajde.internal.AspectJBuildManager$CompilerThread.run (AspectJBuildManager.java:191) UnsupportedOperationException thrown: unable to parameterize unresolved type: Pjava/util/List<+Ljava/lang/Object;>; To reproduce this exception compile the following code snippet. import java.util.ArrayList; import java.util.List; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; public class Main { public List<? extends Element> getElements() { return new ArrayList<Element>(); } class Element {}; @Aspect static abstract class Base<T> { @Around("call(List<? extends T> *.*(..))") public List<? extends T> elementList(ProceedingJoinPoint thisJoinPoint) { try { return (List<? extends T>)thisJoinPoint.proceed(); } catch (Throwable e) { throw new RuntimeException(e); } } } @Aspect static class Concrete extends Base<Element> {} public static void main(String[] args) { new Main().getElements(); } }
resolved fixed
7b40e7e
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2006-10-24T12:42:57Z"
"2006-10-19T01:06:40Z"
weaver/src/org/aspectj/weaver/patterns/ExactAnnotationTypePattern.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.DataOutputStream; import java.io.IOException; import java.util.Map; import org.aspectj.bridge.IMessage; import org.aspectj.bridge.MessageUtil; import org.aspectj.util.FuzzyBoolean; import org.aspectj.weaver.AnnotatedElement; import org.aspectj.weaver.BCException; import org.aspectj.weaver.ISourceContext; import org.aspectj.weaver.ReferenceType; import org.aspectj.weaver.ResolvedType; import org.aspectj.weaver.TypeVariableReference; import org.aspectj.weaver.UnresolvedType; import org.aspectj.weaver.VersionedDataInputStream; import org.aspectj.weaver.WeaverMessages; import org.aspectj.weaver.World; /** * Matches an annotation of a given type */ public class ExactAnnotationTypePattern extends AnnotationTypePattern { protected UnresolvedType annotationType; protected String formalName; protected boolean resolved = false; private boolean bindingPattern = false; /** * */ public ExactAnnotationTypePattern(UnresolvedType annotationType) { this.annotationType = annotationType; this.resolved = (annotationType instanceof ResolvedType); } protected ExactAnnotationTypePattern(String formalName) { this.formalName = formalName; this.resolved = false; this.bindingPattern = true; // will be turned into BindingAnnotationTypePattern during resolution } public ResolvedType getResolvedAnnotationType() { if (!resolved) throw new IllegalStateException("I need to be resolved first!"); return (ResolvedType) annotationType; } public UnresolvedType getAnnotationType() { return annotationType; } public FuzzyBoolean fastMatches(AnnotatedElement annotated) { if (annotated.hasAnnotation(annotationType)) { return FuzzyBoolean.YES; } else { // could be inherited, but we don't know that until we are // resolved, and we're not yet... return FuzzyBoolean.MAYBE; } } public FuzzyBoolean matches(AnnotatedElement annotated) { boolean checkSupers = false; if (getResolvedAnnotationType().hasAnnotation(UnresolvedType.AT_INHERITED)) { if (annotated instanceof ResolvedType) { checkSupers = true; } } if (annotated.hasAnnotation(annotationType)) { if (annotationType instanceof ReferenceType) { ReferenceType rt = (ReferenceType)annotationType; if (rt.getRetentionPolicy()!=null && rt.getRetentionPolicy().equals("SOURCE")) { rt.getWorld().getMessageHandler().handleMessage( MessageUtil.warn(WeaverMessages.format(WeaverMessages.NO_MATCH_BECAUSE_SOURCE_RETENTION,annotationType,annotated),getSourceLocation())); return FuzzyBoolean.NO; } } return FuzzyBoolean.YES; } else if (checkSupers) { ResolvedType toMatchAgainst = ((ResolvedType) annotated).getSuperclass(); while (toMatchAgainst != null) { if (toMatchAgainst.hasAnnotation(annotationType)) return FuzzyBoolean.YES; toMatchAgainst = toMatchAgainst.getSuperclass(); } } return FuzzyBoolean.NO; } // this version should be called for @this, @target, @args public FuzzyBoolean matchesRuntimeType(AnnotatedElement annotated) { if (getResolvedAnnotationType().hasAnnotation(UnresolvedType.AT_INHERITED)) { // a static match is good enough if (matches(annotated).alwaysTrue()) { return FuzzyBoolean.YES; } } // a subtype could match at runtime return FuzzyBoolean.MAYBE; } public void resolve(World world) { if (!resolved) annotationType = annotationType.resolve(world); resolved = true; } /* (non-Javadoc) * @see org.aspectj.weaver.patterns.AnnotationTypePattern#resolveBindings(org.aspectj.weaver.patterns.IScope, org.aspectj.weaver.patterns.Bindings, boolean) */ public AnnotationTypePattern resolveBindings(IScope scope, Bindings bindings, boolean allowBinding) { if (resolved) return this; resolved = true; String simpleName = maybeGetSimpleName(); if (simpleName != null) { FormalBinding formalBinding = scope.lookupFormal(simpleName); if (formalBinding != null) { if (bindings == null) { scope.message(IMessage.ERROR, this, "negation doesn't allow binding"); return this; } if (!allowBinding) { scope.message(IMessage.ERROR, this, "name binding only allowed in @pcds, args, this, and target"); return this; } formalName = simpleName; bindingPattern = true; verifyIsAnnotationType(formalBinding.getType().resolve(scope.getWorld()),scope); BindingAnnotationTypePattern binding = new BindingAnnotationTypePattern(formalBinding); binding.copyLocationFrom(this); bindings.register(binding, scope); binding.resolveBinding(scope.getWorld()); return binding; } } // Non binding case String cleanname = annotationType.getName(); annotationType = scope.getWorld().resolve(annotationType,true); // We may not have found it if it is in a package, lets look it up... if (ResolvedType.isMissing(annotationType)) { UnresolvedType type = null; while (ResolvedType.isMissing(type = scope.lookupType(cleanname,this))) { int lastDot = cleanname.lastIndexOf('.'); if (lastDot == -1) break; cleanname = cleanname.substring(0,lastDot)+"$"+cleanname.substring(lastDot+1); } annotationType = scope.getWorld().resolve(type,true); } verifyIsAnnotationType((ResolvedType)annotationType,scope); return this; } public AnnotationTypePattern parameterizeWith(Map typeVariableMap) { UnresolvedType newAnnotationType = annotationType; if (annotationType.isTypeVariableReference()) { TypeVariableReference t = (TypeVariableReference) annotationType; String key = t.getTypeVariable().getName(); if (typeVariableMap.containsKey(key)) { newAnnotationType = (UnresolvedType) typeVariableMap.get(key); } } else if (annotationType.isParameterizedType()) { newAnnotationType = annotationType.parameterize(typeVariableMap); } ExactAnnotationTypePattern ret = new ExactAnnotationTypePattern(newAnnotationType); ret.formalName = formalName; ret.bindingPattern = bindingPattern; ret.copyLocationFrom(this); return ret; } private String maybeGetSimpleName() { if (formalName != null) return formalName; String ret = annotationType.getName(); return (ret.indexOf('.') == -1) ? ret : null; } /** * @param scope */ private void verifyIsAnnotationType(ResolvedType type,IScope scope) { if (!type.isAnnotation()) { IMessage m = MessageUtil.error( WeaverMessages.format(WeaverMessages.REFERENCE_TO_NON_ANNOTATION_TYPE,type.getName()), getSourceLocation()); scope.getWorld().getMessageHandler().handleMessage(m); resolved = false; } } private static byte VERSION = 1; // rev if serialisation form changes /* (non-Javadoc) * @see org.aspectj.weaver.patterns.PatternNode#write(java.io.DataOutputStream) */ public void write(DataOutputStream s) throws IOException { s.writeByte(AnnotationTypePattern.EXACT); s.writeByte(VERSION); s.writeBoolean(bindingPattern); if (bindingPattern) { s.writeUTF(formalName); } else { annotationType.write(s); } writeLocation(s); } public static AnnotationTypePattern read(VersionedDataInputStream s,ISourceContext context) throws IOException { AnnotationTypePattern ret; byte version = s.readByte(); if (version > VERSION) { throw new BCException("ExactAnnotationTypePattern was written by a newer version of AspectJ"); } boolean isBindingPattern = s.readBoolean(); if (isBindingPattern) { ret = new ExactAnnotationTypePattern(s.readUTF()); } else { ret = new ExactAnnotationTypePattern(UnresolvedType.read(s)); } ret.readLocation(context,s); return ret; } /* (non-Javadoc) * @see java.lang.Object#equals(java.lang.Object) */ public boolean equals(Object obj) { if (!(obj instanceof ExactAnnotationTypePattern)) return false; ExactAnnotationTypePattern other = (ExactAnnotationTypePattern) obj; return (other.annotationType.equals(annotationType)); } /* (non-Javadoc) * @see java.lang.Object#hashCode() */ public int hashCode() { return annotationType.hashCode(); } public String toString() { if (!resolved && formalName != null) return formalName; String ret = "@" + annotationType.toString(); if (formalName != null) ret = ret + " " + formalName; return ret; } public Object accept(PatternNodeVisitor visitor, Object data) { return visitor.visit(this, data); } }
161,502
Bug 161502 UnsupportedOperationException thrown: unable to parameterize unresolved type: Pjava/util/List<+Ljava/lang/Object; >;
Generic parameters (like List<? extends T>) in pointcuts throw UnsupportedOperationException. java.lang.UnsupportedOperationException at org.aspectj.weaver.UnresolvedType.parameterize(UnresolvedType.java: 220) at org.aspectj.weaver.patterns.ExactTypePattern.parameterizeWith (ExactTypePattern.java:244) at org.aspectj.weaver.patterns.SignaturePattern.parameterizeWith (SignaturePattern.java:265) at org.aspectj.weaver.patterns.KindedPointcut.parameterizeWith (KindedPointcut.java:381) at org.aspectj.weaver.bcel.BcelAdvice.parameterizeWith (BcelAdvice.java:93) at org.aspectj.weaver.ResolvedType.getDeclaredAdvice (ResolvedType.java:710) at org.aspectj.weaver.ResolvedType.getDeclaredShadowMungers (ResolvedType.java:739) at org.aspectj.weaver.ResolvedType.collectShadowMungers (ResolvedType.java:575) at org.aspectj.weaver.ResolvedType.collectCrosscuttingMembers (ResolvedType.java:504) at org.aspectj.weaver.CrosscuttingMembersSet.addOrReplaceAspect (CrosscuttingMembersSet.java:68) at org.aspectj.weaver.CrosscuttingMembersSet.addOrReplaceAspect (CrosscuttingMembersSet.java:57) at org.aspectj.weaver.bcel.BcelWeaver.prepareForWeave(BcelWeaver.java: 450) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.weave (AjCompilerAdapter.java:299) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.afterCompiling (AjCompilerAdapter.java:192) at org.aspectj.ajdt.internal.compiler.CompilerAdapter.ajc $afterReturning$org_aspectj_ajdt_internal_compiler_CompilerAdapter$2 $f9cc9ca0(CompilerAdapter.aj:70) at org.aspectj.org.eclipse.jdt.internal.compiler.Compiler.compile (Compiler.java:367) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.performCompilation (AjBuildManager.java:887) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.doBuild (AjBuildManager.java:244) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.batchBuild (AjBuildManager.java:163) at org.aspectj.ajde.internal.CompilerAdapter.compile (CompilerAdapter.java:122) at org.aspectj.ajde.internal.AspectJBuildManager$CompilerThread.run (AspectJBuildManager.java:191) UnsupportedOperationException thrown: unable to parameterize unresolved type: Pjava/util/List<+Ljava/lang/Object;>; To reproduce this exception compile the following code snippet. import java.util.ArrayList; import java.util.List; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; public class Main { public List<? extends Element> getElements() { return new ArrayList<Element>(); } class Element {}; @Aspect static abstract class Base<T> { @Around("call(List<? extends T> *.*(..))") public List<? extends T> elementList(ProceedingJoinPoint thisJoinPoint) { try { return (List<? extends T>)thisJoinPoint.proceed(); } catch (Throwable e) { throw new RuntimeException(e); } } } @Aspect static class Concrete extends Base<Element> {} public static void main(String[] args) { new Main().getElements(); } }
resolved fixed
7b40e7e
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2006-10-24T12:42:57Z"
"2006-10-19T01:06:40Z"
weaver/src/org/aspectj/weaver/patterns/ExactTypePattern.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.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.util.HashMap; import java.util.Map; import org.aspectj.util.FuzzyBoolean; import org.aspectj.weaver.AjAttribute; import org.aspectj.weaver.BCException; import org.aspectj.weaver.ISourceContext; import org.aspectj.weaver.ResolvedType; import org.aspectj.weaver.TypeVariableReference; import org.aspectj.weaver.TypeVariableReferenceType; import org.aspectj.weaver.UnresolvedType; import org.aspectj.weaver.VersionedDataInputStream; public class ExactTypePattern extends TypePattern { protected UnresolvedType type; public static final Map primitiveTypesMap; public static final Map boxedPrimitivesMap; private static final Map boxedTypesMap; static { primitiveTypesMap = new HashMap(); primitiveTypesMap.put("int",int.class); primitiveTypesMap.put("short",short.class); primitiveTypesMap.put("long",long.class); primitiveTypesMap.put("byte",byte.class); primitiveTypesMap.put("char",char.class); primitiveTypesMap.put("float",float.class); primitiveTypesMap.put("double",double.class); boxedPrimitivesMap = new HashMap(); boxedPrimitivesMap.put("java.lang.Integer",Integer.class); boxedPrimitivesMap.put("java.lang.Short",Short.class); boxedPrimitivesMap.put("java.lang.Long",Long.class); boxedPrimitivesMap.put("java.lang.Byte",Byte.class); boxedPrimitivesMap.put("java.lang.Character",Character.class); boxedPrimitivesMap.put("java.lang.Float",Float.class); boxedPrimitivesMap.put("java.lang.Double",Double.class); boxedTypesMap = new HashMap(); boxedTypesMap.put("int",Integer.class); boxedTypesMap.put("short",Short.class); boxedTypesMap.put("long",Long.class); boxedTypesMap.put("byte",Byte.class); boxedTypesMap.put("char",Character.class); boxedTypesMap.put("float",Float.class); boxedTypesMap.put("double",Double.class); } public ExactTypePattern(UnresolvedType type, boolean includeSubtypes,boolean isVarArgs) { super(includeSubtypes,isVarArgs); this.type = type; } public boolean isArray() { return type.isArray(); } /* (non-Javadoc) * @see org.aspectj.weaver.patterns.TypePattern#couldEverMatchSameTypesAs(org.aspectj.weaver.patterns.TypePattern) */ protected boolean couldEverMatchSameTypesAs(TypePattern other) { if (super.couldEverMatchSameTypesAs(other)) return true; // false is necessary but not sufficient UnresolvedType otherType = other.getExactType(); if (!ResolvedType.isMissing(otherType)) { return type.equals(otherType); } if (other instanceof WildTypePattern) { WildTypePattern owtp = (WildTypePattern) other; String yourSimpleNamePrefix = owtp.getNamePatterns()[0].maybeGetSimpleName(); if (yourSimpleNamePrefix != null) { return (type.getName().startsWith(yourSimpleNamePrefix)); } } return true; } protected boolean matchesExactly(ResolvedType matchType) { boolean typeMatch = this.type.equals(matchType); if (!typeMatch && (matchType.isParameterizedType() || matchType.isGenericType())) { typeMatch = this.type.equals(matchType.getRawType()); } if (!typeMatch && matchType.isTypeVariableReference()) { typeMatch = matchesTypeVariable((TypeVariableReferenceType)matchType); } annotationPattern.resolve(matchType.getWorld()); boolean annMatch = this.annotationPattern.matches(matchType).alwaysTrue(); return (typeMatch && annMatch); } private boolean matchesTypeVariable(TypeVariableReferenceType matchType) { // was this method previously coded to return false *on purpose* ?? pr124808 return this.type.equals(((TypeVariableReference)matchType).getTypeVariable().getFirstBound()); //return false; } protected boolean matchesExactly(ResolvedType matchType, ResolvedType annotatedType) { boolean typeMatch = this.type.equals(matchType); if (!typeMatch && (matchType.isParameterizedType() || matchType.isGenericType())) { typeMatch = this.type.equals(matchType.getRawType()); } if (!typeMatch && matchType.isTypeVariableReference()) { typeMatch = matchesTypeVariable((TypeVariableReferenceType)matchType); } annotationPattern.resolve(matchType.getWorld()); boolean annMatch = this.annotationPattern.matches(annotatedType).alwaysTrue(); return (typeMatch && annMatch); } public UnresolvedType getType() { return type; } // true if (matchType instanceof this.type) public FuzzyBoolean matchesInstanceof(ResolvedType matchType) { // in our world, Object is assignable from anything if (type.equals(ResolvedType.OBJECT)) return FuzzyBoolean.YES.and(annotationPattern.matches(matchType)); if (type.resolve(matchType.getWorld()).isAssignableFrom(matchType)) { return FuzzyBoolean.YES.and(annotationPattern.matches(matchType)); } // fix for PR 64262 - shouldn't try to coerce primitives if (type.isPrimitiveType()) { return FuzzyBoolean.NO; } else { return matchType.isCoerceableFrom(type.resolve(matchType.getWorld())) ? FuzzyBoolean.MAYBE : FuzzyBoolean.NO; } } public boolean equals(Object other) { if (!(other instanceof ExactTypePattern)) return false; if (other instanceof BindingTypePattern) return false; ExactTypePattern o = (ExactTypePattern)other; if (includeSubtypes != o.includeSubtypes) return false; if (isVarArgs != o.isVarArgs) return false; if (!typeParameters.equals(o.typeParameters)) return false; return (o.type.equals(this.type) && o.annotationPattern.equals(this.annotationPattern)); } public int hashCode() { int result = 17; result = 37*result + type.hashCode(); result = 37*result + new Boolean(includeSubtypes).hashCode(); result = 37*result + new Boolean(isVarArgs).hashCode(); result = 37*result + typeParameters.hashCode(); result = 37*result + annotationPattern.hashCode(); return result; } private static final byte EXACT_VERSION = 1; // rev if changed public void write(DataOutputStream out) throws IOException { out.writeByte(TypePattern.EXACT); out.writeByte(EXACT_VERSION); type.write(out); out.writeBoolean(includeSubtypes); out.writeBoolean(isVarArgs); annotationPattern.write(out); typeParameters.write(out); writeLocation(out); } public static TypePattern read(VersionedDataInputStream s, ISourceContext context) throws IOException { if (s.getMajorVersion()>=AjAttribute.WeaverVersionInfo.WEAVER_VERSION_MAJOR_AJ150) { return readTypePattern150(s,context); } else { return readTypePatternOldStyle(s,context); } } public static TypePattern readTypePattern150(VersionedDataInputStream s, ISourceContext context) throws IOException { byte version = s.readByte(); if (version > EXACT_VERSION) throw new BCException("ExactTypePattern was written by a more recent version of AspectJ"); TypePattern ret = new ExactTypePattern(UnresolvedType.read(s), s.readBoolean(), s.readBoolean()); ret.setAnnotationTypePattern(AnnotationTypePattern.read(s,context)); ret.setTypeParameters(TypePatternList.read(s,context)); ret.readLocation(context, s); return ret; } public static TypePattern readTypePatternOldStyle(DataInputStream s, ISourceContext context) throws IOException { TypePattern ret = new ExactTypePattern(UnresolvedType.read(s), s.readBoolean(),false); ret.readLocation(context, s); return ret; } public String toString() { StringBuffer buff = new StringBuffer(); if (annotationPattern != AnnotationTypePattern.ANY) { buff.append('('); buff.append(annotationPattern.toString()); buff.append(' '); } String typeString = type.toString(); if (isVarArgs) typeString = typeString.substring(0,typeString.lastIndexOf('[')); buff.append(typeString); if (includeSubtypes) buff.append('+'); if (isVarArgs) buff.append("..."); if (annotationPattern != AnnotationTypePattern.ANY) { buff.append(')'); } return buff.toString(); } public TypePattern resolveBindings(IScope scope, Bindings bindings, boolean allowBinding, boolean requireExactType) { throw new BCException("trying to re-resolve"); } /** * return a version of this type pattern with all type variables references replaced * by the corresponding entry in the map. */ public TypePattern parameterizeWith(Map typeVariableMap) { UnresolvedType newType = type; if (type.isTypeVariableReference()) { TypeVariableReference t = (TypeVariableReference) type; String key = t.getTypeVariable().getName(); if (typeVariableMap.containsKey(key)) { newType = (UnresolvedType) typeVariableMap.get(key); } } else if (type.isParameterizedType()) { newType = type.parameterize(typeVariableMap); } ExactTypePattern ret = new ExactTypePattern(newType,includeSubtypes,isVarArgs); ret.annotationPattern = annotationPattern.parameterizeWith(typeVariableMap); ret.copyLocationFrom(this); return ret; } public Object accept(PatternNodeVisitor visitor, Object data) { return visitor.visit(this, data); } }
161,502
Bug 161502 UnsupportedOperationException thrown: unable to parameterize unresolved type: Pjava/util/List<+Ljava/lang/Object; >;
Generic parameters (like List<? extends T>) in pointcuts throw UnsupportedOperationException. java.lang.UnsupportedOperationException at org.aspectj.weaver.UnresolvedType.parameterize(UnresolvedType.java: 220) at org.aspectj.weaver.patterns.ExactTypePattern.parameterizeWith (ExactTypePattern.java:244) at org.aspectj.weaver.patterns.SignaturePattern.parameterizeWith (SignaturePattern.java:265) at org.aspectj.weaver.patterns.KindedPointcut.parameterizeWith (KindedPointcut.java:381) at org.aspectj.weaver.bcel.BcelAdvice.parameterizeWith (BcelAdvice.java:93) at org.aspectj.weaver.ResolvedType.getDeclaredAdvice (ResolvedType.java:710) at org.aspectj.weaver.ResolvedType.getDeclaredShadowMungers (ResolvedType.java:739) at org.aspectj.weaver.ResolvedType.collectShadowMungers (ResolvedType.java:575) at org.aspectj.weaver.ResolvedType.collectCrosscuttingMembers (ResolvedType.java:504) at org.aspectj.weaver.CrosscuttingMembersSet.addOrReplaceAspect (CrosscuttingMembersSet.java:68) at org.aspectj.weaver.CrosscuttingMembersSet.addOrReplaceAspect (CrosscuttingMembersSet.java:57) at org.aspectj.weaver.bcel.BcelWeaver.prepareForWeave(BcelWeaver.java: 450) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.weave (AjCompilerAdapter.java:299) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.afterCompiling (AjCompilerAdapter.java:192) at org.aspectj.ajdt.internal.compiler.CompilerAdapter.ajc $afterReturning$org_aspectj_ajdt_internal_compiler_CompilerAdapter$2 $f9cc9ca0(CompilerAdapter.aj:70) at org.aspectj.org.eclipse.jdt.internal.compiler.Compiler.compile (Compiler.java:367) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.performCompilation (AjBuildManager.java:887) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.doBuild (AjBuildManager.java:244) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.batchBuild (AjBuildManager.java:163) at org.aspectj.ajde.internal.CompilerAdapter.compile (CompilerAdapter.java:122) at org.aspectj.ajde.internal.AspectJBuildManager$CompilerThread.run (AspectJBuildManager.java:191) UnsupportedOperationException thrown: unable to parameterize unresolved type: Pjava/util/List<+Ljava/lang/Object;>; To reproduce this exception compile the following code snippet. import java.util.ArrayList; import java.util.List; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; public class Main { public List<? extends Element> getElements() { return new ArrayList<Element>(); } class Element {}; @Aspect static abstract class Base<T> { @Around("call(List<? extends T> *.*(..))") public List<? extends T> elementList(ProceedingJoinPoint thisJoinPoint) { try { return (List<? extends T>)thisJoinPoint.proceed(); } catch (Throwable e) { throw new RuntimeException(e); } } } @Aspect static class Concrete extends Base<Element> {} public static void main(String[] args) { new Main().getElements(); } }
resolved fixed
7b40e7e
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2006-10-24T12:42:57Z"
"2006-10-19T01:06:40Z"
weaver/src/org/aspectj/weaver/patterns/HandlerPointcut.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.DataOutputStream; import java.io.IOException; import java.util.Map; import org.aspectj.bridge.MessageUtil; import org.aspectj.util.FuzzyBoolean; import org.aspectj.weaver.ISourceContext; import org.aspectj.weaver.IntMap; import org.aspectj.weaver.ResolvedType; import org.aspectj.weaver.Shadow; import org.aspectj.weaver.UnresolvedType; import org.aspectj.weaver.VersionedDataInputStream; import org.aspectj.weaver.WeaverMessages; import org.aspectj.weaver.ast.Literal; import org.aspectj.weaver.ast.Test; /** * This is a kind of KindedPointcut. This belongs either in * a hierarchy with it or in a new place to share code * with other potential future statement-level pointcuts like * synchronized and throws */ public class HandlerPointcut extends Pointcut { TypePattern exceptionType; private static final int MATCH_KINDS = Shadow.ExceptionHandler.bit; public HandlerPointcut(TypePattern exceptionType) { this.exceptionType = exceptionType; this.pointcutKind = HANDLER; } public int couldMatchKinds() { return MATCH_KINDS; } public FuzzyBoolean fastMatch(FastMatchInfo type) { //??? should be able to do better by finding all referenced types in type return FuzzyBoolean.MAYBE; } protected FuzzyBoolean matchInternal(Shadow shadow) { if (shadow.getKind() != Shadow.ExceptionHandler) return FuzzyBoolean.NO; exceptionType.resolve(shadow.getIWorld()); // we know we have exactly one parameter since we're checking an exception handler return exceptionType.matches( shadow.getSignature().getParameterTypes()[0].resolve(shadow.getIWorld()), TypePattern.STATIC); } public Pointcut parameterizeWith(Map typeVariableMap) { HandlerPointcut ret = new HandlerPointcut(exceptionType.parameterizeWith(typeVariableMap)); ret.copyLocationFrom(this); return ret; } public boolean equals(Object other) { if (!(other instanceof HandlerPointcut)) return false; HandlerPointcut o = (HandlerPointcut)other; return o.exceptionType.equals(this.exceptionType); } public int hashCode() { int result = 17; result = 37*result + exceptionType.hashCode(); return result; } public String toString() { StringBuffer buf = new StringBuffer(); buf.append("handler("); buf.append(exceptionType.toString()); buf.append(")"); return buf.toString(); } public void write(DataOutputStream s) throws IOException { s.writeByte(Pointcut.HANDLER); exceptionType.write(s); writeLocation(s); } public static Pointcut read(VersionedDataInputStream s, ISourceContext context) throws IOException { HandlerPointcut ret = new HandlerPointcut(TypePattern.read(s, context)); ret.readLocation(context, s); return ret; } // XXX note: there is no namebinding in any kinded pointcut. // still might want to do something for better error messages // We want to do something here to make sure we don't sidestep the parameter // list in capturing type identifiers. public void resolveBindings(IScope scope, Bindings bindings) { exceptionType = exceptionType.resolveBindings(scope, bindings, false, false); boolean invalidParameterization = false; if (exceptionType.getTypeParameters().size() > 0) invalidParameterization = true ; UnresolvedType exactType = exceptionType.getExactType(); if (exactType != null && exactType.isParameterizedType()) invalidParameterization = true; if (invalidParameterization) { // no parameterized or generic types for handler scope.message( MessageUtil.error(WeaverMessages.format(WeaverMessages.HANDLER_PCD_DOESNT_SUPPORT_PARAMETERS), getSourceLocation())); } //XXX add error if exact binding and not an exception } protected Test findResidueInternal(Shadow shadow, ExposedState state) { return match(shadow).alwaysTrue() ? Literal.TRUE : Literal.FALSE; } public Pointcut concretize1(ResolvedType inAspect, ResolvedType declaringType, IntMap bindings) { Pointcut ret = new HandlerPointcut(exceptionType); ret.copyLocationFrom(this); return ret; } public Object accept(PatternNodeVisitor visitor, Object data) { return visitor.visit(this, data); } }
161,502
Bug 161502 UnsupportedOperationException thrown: unable to parameterize unresolved type: Pjava/util/List<+Ljava/lang/Object; >;
Generic parameters (like List<? extends T>) in pointcuts throw UnsupportedOperationException. java.lang.UnsupportedOperationException at org.aspectj.weaver.UnresolvedType.parameterize(UnresolvedType.java: 220) at org.aspectj.weaver.patterns.ExactTypePattern.parameterizeWith (ExactTypePattern.java:244) at org.aspectj.weaver.patterns.SignaturePattern.parameterizeWith (SignaturePattern.java:265) at org.aspectj.weaver.patterns.KindedPointcut.parameterizeWith (KindedPointcut.java:381) at org.aspectj.weaver.bcel.BcelAdvice.parameterizeWith (BcelAdvice.java:93) at org.aspectj.weaver.ResolvedType.getDeclaredAdvice (ResolvedType.java:710) at org.aspectj.weaver.ResolvedType.getDeclaredShadowMungers (ResolvedType.java:739) at org.aspectj.weaver.ResolvedType.collectShadowMungers (ResolvedType.java:575) at org.aspectj.weaver.ResolvedType.collectCrosscuttingMembers (ResolvedType.java:504) at org.aspectj.weaver.CrosscuttingMembersSet.addOrReplaceAspect (CrosscuttingMembersSet.java:68) at org.aspectj.weaver.CrosscuttingMembersSet.addOrReplaceAspect (CrosscuttingMembersSet.java:57) at org.aspectj.weaver.bcel.BcelWeaver.prepareForWeave(BcelWeaver.java: 450) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.weave (AjCompilerAdapter.java:299) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.afterCompiling (AjCompilerAdapter.java:192) at org.aspectj.ajdt.internal.compiler.CompilerAdapter.ajc $afterReturning$org_aspectj_ajdt_internal_compiler_CompilerAdapter$2 $f9cc9ca0(CompilerAdapter.aj:70) at org.aspectj.org.eclipse.jdt.internal.compiler.Compiler.compile (Compiler.java:367) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.performCompilation (AjBuildManager.java:887) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.doBuild (AjBuildManager.java:244) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.batchBuild (AjBuildManager.java:163) at org.aspectj.ajde.internal.CompilerAdapter.compile (CompilerAdapter.java:122) at org.aspectj.ajde.internal.AspectJBuildManager$CompilerThread.run (AspectJBuildManager.java:191) UnsupportedOperationException thrown: unable to parameterize unresolved type: Pjava/util/List<+Ljava/lang/Object;>; To reproduce this exception compile the following code snippet. import java.util.ArrayList; import java.util.List; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; public class Main { public List<? extends Element> getElements() { return new ArrayList<Element>(); } class Element {}; @Aspect static abstract class Base<T> { @Around("call(List<? extends T> *.*(..))") public List<? extends T> elementList(ProceedingJoinPoint thisJoinPoint) { try { return (List<? extends T>)thisJoinPoint.proceed(); } catch (Throwable e) { throw new RuntimeException(e); } } } @Aspect static class Concrete extends Base<Element> {} public static void main(String[] args) { new Main().getElements(); } }
resolved fixed
7b40e7e
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2006-10-24T12:42:57Z"
"2006-10-19T01:06:40Z"
weaver/src/org/aspectj/weaver/patterns/HasMemberTypePattern.java
/* ******************************************************************* * Copyright (c) 2005 Contributors. * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Eclipse Public License v1.0 * which accompanies this distribution and is available at * http://eclipse.org/legal/epl-v10.html * * Contributors: * Adrian Colyer Initial implementation * ******************************************************************/ package org.aspectj.weaver.patterns; import java.io.DataOutputStream; import java.io.IOException; import java.lang.reflect.Modifier; import java.util.Iterator; import java.util.List; import java.util.Map; import org.aspectj.bridge.IMessage; import org.aspectj.util.FuzzyBoolean; import org.aspectj.weaver.ConcreteTypeMunger; import org.aspectj.weaver.ISourceContext; import org.aspectj.weaver.Member; import org.aspectj.weaver.ResolvedType; import org.aspectj.weaver.VersionedDataInputStream; import org.aspectj.weaver.WeaverMessages; import org.aspectj.weaver.World; /** * @author colyer * Matches types that have a certain method / constructor / field * Currently only allowed within declare parents and declare @type */ public class HasMemberTypePattern extends TypePattern { private SignaturePattern signaturePattern; public HasMemberTypePattern(SignaturePattern aSignaturePattern) { super(false,false); this.signaturePattern = aSignaturePattern; } protected boolean matchesExactly(ResolvedType type) { if (signaturePattern.getKind() == Member.FIELD) { return hasField(type); } else { return hasMethod(type); } } private final static String declareAtPrefix = "ajc$declare_at"; private boolean hasField(ResolvedType type) { // TODO what about ITDs World world = type.getWorld(); for (Iterator iter = type.getFields(); iter.hasNext();) { Member field = (Member) iter.next(); if (field.getName().startsWith(declareAtPrefix)) continue; if (signaturePattern.matches(field, type.getWorld(), false)) { if (field.getDeclaringType().resolve(world) != type) { if (Modifier.isPrivate(field.getModifiers())) continue; } return true; } } return false; } private boolean hasMethod(ResolvedType type) { // TODO what about ITDs World world = type.getWorld(); for (Iterator iter = type.getMethods(); iter.hasNext();) { Member method = (Member) iter.next(); if (method.getName().startsWith(declareAtPrefix)) continue; if (signaturePattern.matches(method, type.getWorld(), false)) { if (method.getDeclaringType().resolve(world) != type) { if (Modifier.isPrivate(method.getModifiers())) continue; } return true; } } // try itds before we give up List mungers = type.getInterTypeMungersIncludingSupers(); for (Iterator iter = mungers.iterator(); iter.hasNext();) { ConcreteTypeMunger munger = (ConcreteTypeMunger) iter.next(); Member member = munger.getSignature(); if (signaturePattern.matches(member, type.getWorld(), false)) { if (!Modifier.isPublic(member.getModifiers())) continue; return true; } } return false; } protected boolean matchesExactly(ResolvedType type, ResolvedType annotatedType) { return matchesExactly(type); } public FuzzyBoolean matchesInstanceof(ResolvedType type) { throw new UnsupportedOperationException("hasmethod/field do not support instanceof matching"); } public TypePattern parameterizeWith(Map typeVariableMap) { HasMemberTypePattern ret = new HasMemberTypePattern(signaturePattern.parameterizeWith(typeVariableMap)); ret.copyLocationFrom(this); return ret; } public TypePattern resolveBindings(IScope scope, Bindings bindings, boolean allowBinding, boolean requireExactType) { // check that hasmember type patterns are allowed! if (!scope.getWorld().isHasMemberSupportEnabled()) { String msg = WeaverMessages.format(WeaverMessages.HAS_MEMBER_NOT_ENABLED,this.toString()); scope.message(IMessage.ERROR, this, msg); } signaturePattern.resolveBindings(scope,bindings); return this; } public boolean equals(Object obj) { if (!(obj instanceof HasMemberTypePattern)) return false; if (this == obj) return true; return signaturePattern.equals(((HasMemberTypePattern)obj).signaturePattern); } public int hashCode() { return signaturePattern.hashCode(); } public String toString() { StringBuffer buff = new StringBuffer(); if (signaturePattern.getKind() == Member.FIELD) { buff.append("hasfield("); } else { buff.append("hasmethod("); } buff.append(signaturePattern.toString()); buff.append(")"); return buff.toString(); } public void write(DataOutputStream s) throws IOException { s.writeByte(TypePattern.HAS_MEMBER); signaturePattern.write(s); writeLocation(s); } public static TypePattern read(VersionedDataInputStream s, ISourceContext context) throws IOException { SignaturePattern sp = SignaturePattern.read(s, context); HasMemberTypePattern ret = new HasMemberTypePattern(sp); ret.readLocation(context,s); return ret; } public Object accept(PatternNodeVisitor visitor, Object data) { return visitor.visit(this, data); } }
161,502
Bug 161502 UnsupportedOperationException thrown: unable to parameterize unresolved type: Pjava/util/List<+Ljava/lang/Object; >;
Generic parameters (like List<? extends T>) in pointcuts throw UnsupportedOperationException. java.lang.UnsupportedOperationException at org.aspectj.weaver.UnresolvedType.parameterize(UnresolvedType.java: 220) at org.aspectj.weaver.patterns.ExactTypePattern.parameterizeWith (ExactTypePattern.java:244) at org.aspectj.weaver.patterns.SignaturePattern.parameterizeWith (SignaturePattern.java:265) at org.aspectj.weaver.patterns.KindedPointcut.parameterizeWith (KindedPointcut.java:381) at org.aspectj.weaver.bcel.BcelAdvice.parameterizeWith (BcelAdvice.java:93) at org.aspectj.weaver.ResolvedType.getDeclaredAdvice (ResolvedType.java:710) at org.aspectj.weaver.ResolvedType.getDeclaredShadowMungers (ResolvedType.java:739) at org.aspectj.weaver.ResolvedType.collectShadowMungers (ResolvedType.java:575) at org.aspectj.weaver.ResolvedType.collectCrosscuttingMembers (ResolvedType.java:504) at org.aspectj.weaver.CrosscuttingMembersSet.addOrReplaceAspect (CrosscuttingMembersSet.java:68) at org.aspectj.weaver.CrosscuttingMembersSet.addOrReplaceAspect (CrosscuttingMembersSet.java:57) at org.aspectj.weaver.bcel.BcelWeaver.prepareForWeave(BcelWeaver.java: 450) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.weave (AjCompilerAdapter.java:299) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.afterCompiling (AjCompilerAdapter.java:192) at org.aspectj.ajdt.internal.compiler.CompilerAdapter.ajc $afterReturning$org_aspectj_ajdt_internal_compiler_CompilerAdapter$2 $f9cc9ca0(CompilerAdapter.aj:70) at org.aspectj.org.eclipse.jdt.internal.compiler.Compiler.compile (Compiler.java:367) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.performCompilation (AjBuildManager.java:887) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.doBuild (AjBuildManager.java:244) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.batchBuild (AjBuildManager.java:163) at org.aspectj.ajde.internal.CompilerAdapter.compile (CompilerAdapter.java:122) at org.aspectj.ajde.internal.AspectJBuildManager$CompilerThread.run (AspectJBuildManager.java:191) UnsupportedOperationException thrown: unable to parameterize unresolved type: Pjava/util/List<+Ljava/lang/Object;>; To reproduce this exception compile the following code snippet. import java.util.ArrayList; import java.util.List; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; public class Main { public List<? extends Element> getElements() { return new ArrayList<Element>(); } class Element {}; @Aspect static abstract class Base<T> { @Around("call(List<? extends T> *.*(..))") public List<? extends T> elementList(ProceedingJoinPoint thisJoinPoint) { try { return (List<? extends T>)thisJoinPoint.proceed(); } catch (Throwable e) { throw new RuntimeException(e); } } } @Aspect static class Concrete extends Base<Element> {} public static void main(String[] args) { new Main().getElements(); } }
resolved fixed
7b40e7e
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2006-10-24T12:42:57Z"
"2006-10-19T01:06:40Z"
weaver/src/org/aspectj/weaver/patterns/IfPointcut.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the 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 if() implementation for @AJ style * ******************************************************************/ package org.aspectj.weaver.patterns; import java.io.DataOutputStream; import java.io.IOException; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Map; import org.aspectj.bridge.IMessage; import org.aspectj.lang.JoinPoint; import org.aspectj.util.FuzzyBoolean; import org.aspectj.weaver.Advice; import org.aspectj.weaver.AjcMemberMaker; import org.aspectj.weaver.ISourceContext; import org.aspectj.weaver.IntMap; import org.aspectj.weaver.ResolvedMember; import org.aspectj.weaver.ResolvedMemberImpl; import org.aspectj.weaver.ResolvedPointcutDefinition; import org.aspectj.weaver.ResolvedType; import org.aspectj.weaver.Shadow; import org.aspectj.weaver.ShadowMunger; import org.aspectj.weaver.UnresolvedType; import org.aspectj.weaver.VersionedDataInputStream; import org.aspectj.weaver.WeaverMessages; import org.aspectj.weaver.ast.Expr; import org.aspectj.weaver.ast.Literal; import org.aspectj.weaver.ast.Test; import org.aspectj.weaver.ast.Var; public class IfPointcut extends Pointcut { public ResolvedMember testMethod; public int extraParameterFlags; /** * A token source dump that looks like a pointcut (but is NOT parseable at all - just here to help debugging etc) */ private String enclosingPointcutHint; public Pointcut residueSource; int baseArgsCount; //XXX some way to compute args public IfPointcut(ResolvedMember testMethod, int extraParameterFlags) { this.testMethod = testMethod; this.extraParameterFlags = extraParameterFlags; this.pointcutKind = IF; this.enclosingPointcutHint = null; } /** * No-arg constructor for @AJ style, where the if() body is actually the @Pointcut annotated method */ public IfPointcut(String enclosingPointcutHint) { this.pointcutKind = IF; this.enclosingPointcutHint = enclosingPointcutHint; this.testMethod = null;// resolved during concretize this.extraParameterFlags = -1;//allows to keep track of the @Aj style } public int couldMatchKinds() { return Shadow.ALL_SHADOW_KINDS_BITS; } public FuzzyBoolean fastMatch(FastMatchInfo type) { return FuzzyBoolean.MAYBE; } protected FuzzyBoolean matchInternal(Shadow shadow) { //??? this is not maximally efficient return FuzzyBoolean.MAYBE; } public boolean alwaysFalse() { return false; } public boolean alwaysTrue() { return false; } // enh 76055 public Pointcut getResidueSource() { return residueSource; } public void write(DataOutputStream s) throws IOException { s.writeByte(Pointcut.IF); s.writeBoolean(testMethod != null); // do we have a test method? if (testMethod != null) testMethod.write(s); s.writeByte(extraParameterFlags); writeLocation(s); } public static Pointcut read(VersionedDataInputStream s, ISourceContext context) throws IOException { boolean hasTestMethod = s.readBoolean(); ResolvedMember resolvedTestMethod = null; if (hasTestMethod) { // should always have a test method unless @AJ style resolvedTestMethod = ResolvedMemberImpl.readResolvedMember(s, context); } IfPointcut ret = new IfPointcut(resolvedTestMethod, s.readByte()); ret.readLocation(context, s); return ret; } public void resolveBindings(IScope scope, Bindings bindings) { //??? all we need is good error messages in here in cflow contexts } public boolean equals(Object other) { if (!(other instanceof IfPointcut)) return false; IfPointcut o = (IfPointcut)other; if (o.testMethod==null) return (this.testMethod==null); return o.testMethod.equals(this.testMethod); } public int hashCode() { int result = 17; result = 37*result + testMethod.hashCode(); return result; } public String toString() { if (extraParameterFlags < 0) { //@AJ style return "if()"; } else { return "if(" + testMethod + ")";//FIXME AV - bad, this makes it unparsable. Perhaps we can use if() for code style behind the scene! } } //??? The implementation of name binding and type checking in if PCDs is very convoluted // There has to be a better way... private boolean findingResidue = false; // Similar to lastMatchedShadowId - but only for if PCDs. private int ifLastMatchedShadowId; private Test ifLastMatchedShadowResidue; /** * At each shadow that matched, the residue can be different. */ protected Test findResidueInternal(Shadow shadow, ExposedState state) { if (findingResidue) return Literal.TRUE; findingResidue = true; try { // Have we already been asked this question? if (shadow.shadowId == ifLastMatchedShadowId) return ifLastMatchedShadowResidue; Test ret = Literal.TRUE; List args = new ArrayList(); // code style if (extraParameterFlags >= 0) { // If there are no args to sort out, don't bother with the recursive call if (baseArgsCount > 0) { ExposedState myState = new ExposedState(baseArgsCount); //??? we throw out the test that comes from this walk. All we want here // is bindings for the arguments residueSource.findResidue(shadow, myState); // pr118149 // It is possible for vars in myState (which would normally be set // in the call to residueSource.findResidue) to not be set (be null) // in an Or pointcut with if expressions in both branches, and where // one branch is known statically to not match. In this situation we // simply return Test. for (int i=0; i < baseArgsCount; i++) { Var v = myState.get(i); if (v == null) continue; // pr118149 args.add(v); ret = Test.makeAnd(ret, Test.makeInstanceof(v, testMethod.getParameterTypes()[i].resolve(shadow.getIWorld()))); } } // handle thisJoinPoint parameters if ((extraParameterFlags & Advice.ThisJoinPoint) != 0) { args.add(shadow.getThisJoinPointVar()); } if ((extraParameterFlags & Advice.ThisJoinPointStaticPart) != 0) { args.add(shadow.getThisJoinPointStaticPartVar()); } if ((extraParameterFlags & Advice.ThisEnclosingJoinPointStaticPart) != 0) { args.add(shadow.getThisEnclosingJoinPointStaticPartVar()); } } else { // @style is slightly different int currentStateIndex = 0; //FIXME AV - "args(jp)" test(jp, thejp) will fail here for (int i = 0; i < testMethod.getParameterTypes().length; i++) { String argSignature = testMethod.getParameterTypes()[i].getSignature(); if (AjcMemberMaker.TYPEX_JOINPOINT.getSignature().equals(argSignature)) { args.add(shadow.getThisJoinPointVar()); } else if (AjcMemberMaker.TYPEX_PROCEEDINGJOINPOINT.getSignature().equals(argSignature)) { args.add(shadow.getThisJoinPointVar()); } else if (AjcMemberMaker.TYPEX_STATICJOINPOINT.getSignature().equals(argSignature)) { args.add(shadow.getThisJoinPointStaticPartVar()); } else if (AjcMemberMaker.TYPEX_ENCLOSINGSTATICJOINPOINT.getSignature().equals(argSignature)) { args.add(shadow.getThisEnclosingJoinPointStaticPartVar()); } else { // we don't use i as JoinPoint.* can be anywhere in the signature in @style Var v = state.get(currentStateIndex++); args.add(v); ret = Test.makeAnd(ret, Test.makeInstanceof(v, testMethod.getParameterTypes()[i].resolve(shadow.getIWorld()))); } } } ret = Test.makeAnd(ret, Test.makeCall(testMethod, (Expr[])args.toArray(new Expr[args.size()]))); // Remember... ifLastMatchedShadowId = shadow.shadowId; ifLastMatchedShadowResidue = ret; return ret; } finally { findingResidue = false; } } // amc - the only reason this override seems to be here is to stop the copy, but // that can be prevented by overriding shouldCopyLocationForConcretization, // allowing me to make the method final in Pointcut. // public Pointcut concretize(ResolvedType inAspect, IntMap bindings) { // return this.concretize1(inAspect, bindings); // } protected boolean shouldCopyLocationForConcretize() { return false; } private IfPointcut partiallyConcretized = null; public Pointcut concretize1(ResolvedType inAspect, ResolvedType declaringType, IntMap bindings) { //System.err.println("concretize: " + this + " already: " + partiallyConcretized); if (isDeclare(bindings.getEnclosingAdvice())) { // Enforce rule about which designators are supported in declare inAspect.getWorld().showMessage(IMessage.ERROR, WeaverMessages.format(WeaverMessages.IF_IN_DECLARE), bindings.getEnclosingAdvice().getSourceLocation(), null); return Pointcut.makeMatchesNothing(Pointcut.CONCRETE); } if (partiallyConcretized != null) { return partiallyConcretized; } final IfPointcut ret; if (extraParameterFlags < 0 && testMethod == null) { // @AJ style, we need to find the testMethod in the aspect defining the "if()" enclosing pointcut ResolvedPointcutDefinition def = bindings.peekEnclosingDefinition(); if (def != null) { ResolvedType aspect = inAspect.getWorld().resolve(def.getDeclaringType()); for (Iterator memberIter = aspect.getMethods(); memberIter.hasNext();) { ResolvedMember method = (ResolvedMember) memberIter.next(); if (def.getName().equals(method.getName()) && def.getParameterTypes().length == method.getParameterTypes().length) { boolean sameSig = true; for (int j = 0; j < method.getParameterTypes().length; j++) { UnresolvedType argJ = method.getParameterTypes()[j]; if (!argJ.equals(def.getParameterTypes()[j])) { sameSig = false; break; } } if (sameSig) { testMethod = method; break; } } } if (testMethod == null) { inAspect.getWorld().showMessage( IMessage.ERROR, "Cannot find if() body from '" + def.toString() + "' for '" + enclosingPointcutHint + "'", this.getSourceLocation(), null ); return Pointcut.makeMatchesNothing(Pointcut.CONCRETE); } } else { testMethod = inAspect.getWorld().resolve(bindings.getAdviceSignature()); } ret = new IfPointcut(enclosingPointcutHint); ret.testMethod = testMethod; } else { ret = new IfPointcut(testMethod, extraParameterFlags); } ret.copyLocationFrom(this); partiallyConcretized = ret; // It is possible to directly code your pointcut expression in a per clause // rather than defining a pointcut declaration and referencing it in your // per clause. If you do this, we have problems (bug #62458). For now, // let's police that you are trying to code a pointcut in a per clause and // put out a compiler error. if (bindings.directlyInAdvice() && bindings.getEnclosingAdvice()==null) { // Assumption: if() is in a per clause if we say we are directly in advice // but we have no enclosing advice. inAspect.getWorld().showMessage(IMessage.ERROR, WeaverMessages.format(WeaverMessages.IF_IN_PERCLAUSE), this.getSourceLocation(),null); return Pointcut.makeMatchesNothing(Pointcut.CONCRETE); } if (bindings.directlyInAdvice()) { ShadowMunger advice = bindings.getEnclosingAdvice(); if (advice instanceof Advice) { ret.baseArgsCount = ((Advice)advice).getBaseParameterCount(); } else { ret.baseArgsCount = 0; } ret.residueSource = advice.getPointcut().concretize(inAspect, inAspect, ret.baseArgsCount, advice); } else { ResolvedPointcutDefinition def = bindings.peekEnclosingDefinition(); if (def == CflowPointcut.CFLOW_MARKER) { inAspect.getWorld().showMessage(IMessage.ERROR, WeaverMessages.format(WeaverMessages.IF_LEXICALLY_IN_CFLOW), getSourceLocation(), null); return Pointcut.makeMatchesNothing(Pointcut.CONCRETE); } ret.baseArgsCount = def.getParameterTypes().length; // for @style, we have implicit binding for JoinPoint.* things //FIXME AV - will lead to failure for "args(jp)" test(jp, thejp) / see args() implementation if (ret.extraParameterFlags < 0) { ret.baseArgsCount = 0; for (int i = 0; i < testMethod.getParameterTypes().length; i++) { String argSignature = testMethod.getParameterTypes()[i].getSignature(); if (AjcMemberMaker.TYPEX_JOINPOINT.getSignature().equals(argSignature) || AjcMemberMaker.TYPEX_PROCEEDINGJOINPOINT.getSignature().equals(argSignature) || AjcMemberMaker.TYPEX_STATICJOINPOINT.getSignature().equals(argSignature) || AjcMemberMaker.TYPEX_ENCLOSINGSTATICJOINPOINT.getSignature().equals(argSignature)) { ; } else { ret.baseArgsCount++; } } } IntMap newBindings = IntMap.idMap(ret.baseArgsCount); newBindings.copyContext(bindings); ret.residueSource = def.getPointcut().concretize(inAspect, declaringType, newBindings); } return ret; } // we can't touch "if" methods public Pointcut parameterizeWith(Map typeVariableMap) { return this; } // public static Pointcut MatchesNothing = new MatchesNothingPointcut(); // ??? there could possibly be some good optimizations to be done at this point public static IfPointcut makeIfFalsePointcut(State state) { IfPointcut ret = new IfFalsePointcut(); ret.state = state; return ret; } public Object accept(PatternNodeVisitor visitor, Object data) { return visitor.visit(this, data); } public static class IfFalsePointcut extends IfPointcut { public IfFalsePointcut() { super(null,0); this.pointcutKind = Pointcut.IF_FALSE; } public int couldMatchKinds() { return Shadow.NO_SHADOW_KINDS_BITS; } public boolean alwaysFalse() { return true; } protected Test findResidueInternal(Shadow shadow, ExposedState state) { return Literal.FALSE; // can only get here if an earlier error occurred } public FuzzyBoolean fastMatch(FastMatchInfo type) { return FuzzyBoolean.NO; } protected FuzzyBoolean matchInternal(Shadow shadow) { return FuzzyBoolean.NO; } public FuzzyBoolean match(JoinPoint.StaticPart jpsp) { return FuzzyBoolean.NO; } public void resolveBindings(IScope scope, Bindings bindings) { } public void postRead(ResolvedType enclosingType) { } public Pointcut concretize1( ResolvedType inAspect, ResolvedType declaringType, IntMap bindings) { if (isDeclare(bindings.getEnclosingAdvice())) { // Enforce rule about which designators are supported in declare inAspect.getWorld().showMessage(IMessage.ERROR, WeaverMessages.format(WeaverMessages.IF_IN_DECLARE), bindings.getEnclosingAdvice().getSourceLocation(), null); return Pointcut.makeMatchesNothing(Pointcut.CONCRETE); } return makeIfFalsePointcut(state); } public void write(DataOutputStream s) throws IOException { s.writeByte(Pointcut.IF_FALSE); } public int hashCode() { int result = 17; return result; } public String toString() { return "if(false)"; } } public static IfPointcut makeIfTruePointcut(State state) { IfPointcut ret = new IfTruePointcut(); ret.state = state; return ret; } public static class IfTruePointcut extends IfPointcut { public IfTruePointcut() { super(null,0); this.pointcutKind = Pointcut.IF_TRUE; } public boolean alwaysTrue() { return true; } protected Test findResidueInternal(Shadow shadow, ExposedState state) { return Literal.TRUE; // can only get here if an earlier error occurred } public FuzzyBoolean fastMatch(FastMatchInfo type) { return FuzzyBoolean.YES; } protected FuzzyBoolean matchInternal(Shadow shadow) { return FuzzyBoolean.YES; } public FuzzyBoolean match(JoinPoint.StaticPart jpsp) { return FuzzyBoolean.YES; } public void resolveBindings(IScope scope, Bindings bindings) { } public void postRead(ResolvedType enclosingType) { } public Pointcut concretize1( ResolvedType inAspect, ResolvedType declaringType, IntMap bindings) { if (isDeclare(bindings.getEnclosingAdvice())) { // Enforce rule about which designators are supported in declare inAspect.getWorld().showMessage(IMessage.ERROR, WeaverMessages.format(WeaverMessages.IF_IN_DECLARE), bindings.getEnclosingAdvice().getSourceLocation(), null); return Pointcut.makeMatchesNothing(Pointcut.CONCRETE); } return makeIfTruePointcut(state); } public void write(DataOutputStream s) throws IOException { s.writeByte(IF_TRUE); } public int hashCode() { int result = 37; return result; } public String toString() { return "if(true)"; } } }
161,502
Bug 161502 UnsupportedOperationException thrown: unable to parameterize unresolved type: Pjava/util/List<+Ljava/lang/Object; >;
Generic parameters (like List<? extends T>) in pointcuts throw UnsupportedOperationException. java.lang.UnsupportedOperationException at org.aspectj.weaver.UnresolvedType.parameterize(UnresolvedType.java: 220) at org.aspectj.weaver.patterns.ExactTypePattern.parameterizeWith (ExactTypePattern.java:244) at org.aspectj.weaver.patterns.SignaturePattern.parameterizeWith (SignaturePattern.java:265) at org.aspectj.weaver.patterns.KindedPointcut.parameterizeWith (KindedPointcut.java:381) at org.aspectj.weaver.bcel.BcelAdvice.parameterizeWith (BcelAdvice.java:93) at org.aspectj.weaver.ResolvedType.getDeclaredAdvice (ResolvedType.java:710) at org.aspectj.weaver.ResolvedType.getDeclaredShadowMungers (ResolvedType.java:739) at org.aspectj.weaver.ResolvedType.collectShadowMungers (ResolvedType.java:575) at org.aspectj.weaver.ResolvedType.collectCrosscuttingMembers (ResolvedType.java:504) at org.aspectj.weaver.CrosscuttingMembersSet.addOrReplaceAspect (CrosscuttingMembersSet.java:68) at org.aspectj.weaver.CrosscuttingMembersSet.addOrReplaceAspect (CrosscuttingMembersSet.java:57) at org.aspectj.weaver.bcel.BcelWeaver.prepareForWeave(BcelWeaver.java: 450) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.weave (AjCompilerAdapter.java:299) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.afterCompiling (AjCompilerAdapter.java:192) at org.aspectj.ajdt.internal.compiler.CompilerAdapter.ajc $afterReturning$org_aspectj_ajdt_internal_compiler_CompilerAdapter$2 $f9cc9ca0(CompilerAdapter.aj:70) at org.aspectj.org.eclipse.jdt.internal.compiler.Compiler.compile (Compiler.java:367) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.performCompilation (AjBuildManager.java:887) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.doBuild (AjBuildManager.java:244) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.batchBuild (AjBuildManager.java:163) at org.aspectj.ajde.internal.CompilerAdapter.compile (CompilerAdapter.java:122) at org.aspectj.ajde.internal.AspectJBuildManager$CompilerThread.run (AspectJBuildManager.java:191) UnsupportedOperationException thrown: unable to parameterize unresolved type: Pjava/util/List<+Ljava/lang/Object;>; To reproduce this exception compile the following code snippet. import java.util.ArrayList; import java.util.List; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; public class Main { public List<? extends Element> getElements() { return new ArrayList<Element>(); } class Element {}; @Aspect static abstract class Base<T> { @Around("call(List<? extends T> *.*(..))") public List<? extends T> elementList(ProceedingJoinPoint thisJoinPoint) { try { return (List<? extends T>)thisJoinPoint.proceed(); } catch (Throwable e) { throw new RuntimeException(e); } } } @Aspect static class Concrete extends Base<Element> {} public static void main(String[] args) { new Main().getElements(); } }
resolved fixed
7b40e7e
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2006-10-24T12:42:57Z"
"2006-10-19T01:06:40Z"
weaver/src/org/aspectj/weaver/patterns/KindedPointcut.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.DataOutputStream; import java.io.IOException; import java.util.Map; import org.aspectj.bridge.ISourceLocation; import org.aspectj.bridge.MessageUtil; import org.aspectj.util.FuzzyBoolean; import org.aspectj.weaver.Checker; import org.aspectj.weaver.ISourceContext; import org.aspectj.weaver.IntMap; import org.aspectj.weaver.Member; import org.aspectj.weaver.ResolvedMember; import org.aspectj.weaver.ResolvedType; import org.aspectj.weaver.Shadow; import org.aspectj.weaver.ShadowMunger; import org.aspectj.weaver.UnresolvedType; import org.aspectj.weaver.VersionedDataInputStream; import org.aspectj.weaver.WeaverMessages; import org.aspectj.weaver.World; import org.aspectj.weaver.ast.Literal; import org.aspectj.weaver.ast.Test; public class KindedPointcut extends Pointcut { Shadow.Kind kind; private SignaturePattern signature; private int matchKinds; private ShadowMunger munger = null; // only set after concretization public KindedPointcut( Shadow.Kind kind, SignaturePattern signature) { this.kind = kind; this.signature = signature; this.pointcutKind = KINDED; this.matchKinds = kind.bit; } public KindedPointcut( Shadow.Kind kind, SignaturePattern signature, ShadowMunger munger) { this(kind, signature); this.munger = munger; } public SignaturePattern getSignature() { return signature; } /* (non-Javadoc) * @see org.aspectj.weaver.patterns.Pointcut#couldMatchKinds() */ public int couldMatchKinds() { return matchKinds; } public boolean couldEverMatchSameJoinPointsAs(KindedPointcut other) { if (this.kind != other.kind) return false; String myName = signature.getName().maybeGetSimpleName(); String yourName = other.signature.getName().maybeGetSimpleName(); if (myName != null && yourName != null) { if ( !myName.equals(yourName)) { return false; } } if (signature.getParameterTypes().ellipsisCount == 0) { if (other.signature.getParameterTypes().ellipsisCount == 0) { if (signature.getParameterTypes().getTypePatterns().length != other.signature.getParameterTypes().getTypePatterns().length) { return false; } } } return true; } public FuzzyBoolean fastMatch(FastMatchInfo info) { if (info.getKind() != null) { if (info.getKind() != kind) return FuzzyBoolean.NO; } return FuzzyBoolean.MAYBE; } protected FuzzyBoolean matchInternal(Shadow shadow) { if (shadow.getKind() != kind) return FuzzyBoolean.NO; if (shadow.getKind() == Shadow.SynchronizationLock && kind == Shadow.SynchronizationLock) return FuzzyBoolean.YES; if (shadow.getKind() == Shadow.SynchronizationUnlock && kind == Shadow.SynchronizationUnlock) return FuzzyBoolean.YES; if (!signature.matches(shadow.getMatchingSignature(), shadow.getIWorld(),this.kind == Shadow.MethodCall)){ if(kind == Shadow.MethodCall) { warnOnConfusingSig(shadow); //warnOnBridgeMethod(shadow); } return FuzzyBoolean.NO; } return FuzzyBoolean.YES; } // private void warnOnBridgeMethod(Shadow shadow) { // if (shadow.getIWorld().getLint().noJoinpointsForBridgeMethods.isEnabled()) { // ResolvedMember rm = shadow.getSignature().resolve(shadow.getIWorld()); // if (rm!=null) { // int shadowModifiers = rm.getModifiers(); //shadow.getSignature().getModifiers(shadow.getIWorld()); // if (ResolvedType.hasBridgeModifier(shadowModifiers)) { // shadow.getIWorld().getLint().noJoinpointsForBridgeMethods.signal(new String[]{},getSourceLocation(), // new ISourceLocation[]{shadow.getSourceLocation()}); // } // } // } // } private void warnOnConfusingSig(Shadow shadow) { // Don't do all this processing if we don't need to ! if (!shadow.getIWorld().getLint().unmatchedSuperTypeInCall.isEnabled()) return; // no warnings for declare error/warning if (munger instanceof Checker) return; World world = shadow.getIWorld(); // warning never needed if the declaring type is any UnresolvedType exactDeclaringType = signature.getDeclaringType().getExactType(); ResolvedType shadowDeclaringType = shadow.getSignature().getDeclaringType().resolve(world); if (signature.getDeclaringType().isStar() || ResolvedType.isMissing(exactDeclaringType) || exactDeclaringType.resolve(world).isMissing()) return; // warning not needed if match type couldn't ever be the declaring type if (!shadowDeclaringType.isAssignableFrom(exactDeclaringType.resolve(world))) { return; } // if the method in the declaring type is *not* visible to the // exact declaring type then warning not needed. ResolvedMember rm = shadow.getSignature().resolve(world); // rm can be null in the case where we are binary weaving, and looking at a class with a call to a method in another class, // but because of class incompatibilities, the method does not exist on the target class anymore. // this will be reported elsewhere. if (rm == null) return; int shadowModifiers = rm.getModifiers(); if (!ResolvedType .isVisible( shadowModifiers, shadowDeclaringType, exactDeclaringType.resolve(world))) { return; } if (!signature.getReturnType().matchesStatically(shadow.getSignature().getReturnType().resolve(world))) { // Covariance issue... // The reason we didn't match is that the type pattern for the pointcut (Car) doesn't match the // return type for the specific declaration at the shadow. (FastCar Sub.getCar()) // XXX Put out another XLINT in this case? return; } // PR60015 - Don't report the warning if the declaring type is object and 'this' is an interface if (exactDeclaringType.resolve(world).isInterface() && shadowDeclaringType.equals(world.resolve("java.lang.Object"))) { return; } SignaturePattern nonConfusingPattern = new SignaturePattern( signature.getKind(), signature.getModifiers(), signature.getReturnType(), TypePattern.ANY, signature.getName(), signature.getParameterTypes(), signature.getThrowsPattern(), signature.getAnnotationPattern()); if (nonConfusingPattern .matches(shadow.getSignature(), shadow.getIWorld(),true)) { shadow.getIWorld().getLint().unmatchedSuperTypeInCall.signal( new String[] { shadow.getSignature().getDeclaringType().toString(), signature.getDeclaringType().toString() }, this.getSourceLocation(), new ISourceLocation[] {shadow.getSourceLocation()} ); } } public boolean equals(Object other) { if (!(other instanceof KindedPointcut)) return false; KindedPointcut o = (KindedPointcut)other; return o.kind == this.kind && o.signature.equals(this.signature); } public int hashCode() { int result = 17; result = 37*result + kind.hashCode(); result = 37*result + signature.hashCode(); return result; } public String toString() { StringBuffer buf = new StringBuffer(); buf.append(kind.getSimpleName()); buf.append("("); buf.append(signature.toString()); buf.append(")"); return buf.toString(); } public void postRead(ResolvedType enclosingType) { signature.postRead(enclosingType); } public void write(DataOutputStream s) throws IOException { s.writeByte(Pointcut.KINDED); kind.write(s); signature.write(s); writeLocation(s); } public static Pointcut read(VersionedDataInputStream s, ISourceContext context) throws IOException { Shadow.Kind kind = Shadow.Kind.read(s); SignaturePattern sig = SignaturePattern.read(s, context); KindedPointcut ret = new KindedPointcut(kind, sig); ret.readLocation(context, s); return ret; } // XXX note: there is no namebinding in any kinded pointcut. // still might want to do something for better error messages // We want to do something here to make sure we don't sidestep the parameter // list in capturing type identifiers. public void resolveBindings(IScope scope, Bindings bindings) { if (kind == Shadow.Initialization) { // scope.getMessageHandler().handleMessage( // MessageUtil.error( // "initialization unimplemented in 1.1beta1", // this.getSourceLocation())); } signature = signature.resolveBindings(scope, bindings); if (kind == Shadow.ConstructorExecution) { // Bug fix 60936 if (signature.getDeclaringType() != null) { World world = scope.getWorld(); UnresolvedType exactType = signature.getDeclaringType().getExactType(); if (signature.getKind() == Member.CONSTRUCTOR && !ResolvedType.isMissing(exactType) && exactType.resolve(world).isInterface() && !signature.getDeclaringType().isIncludeSubtypes()) { world.getLint().noInterfaceCtorJoinpoint.signal(exactType.toString(), getSourceLocation()); } } } // no parameterized types if (kind == Shadow.StaticInitialization) { HasThisTypePatternTriedToSneakInSomeGenericOrParameterizedTypePatternMatchingStuffAnywhereVisitor visitor = new HasThisTypePatternTriedToSneakInSomeGenericOrParameterizedTypePatternMatchingStuffAnywhereVisitor(); signature.getDeclaringType().traverse(visitor, null); if (visitor.wellHasItThen/*?*/()) { scope.message(MessageUtil.error(WeaverMessages.format(WeaverMessages.NO_STATIC_INIT_JPS_FOR_PARAMETERIZED_TYPES), getSourceLocation())); } } // no parameterized types in declaring type position if ((kind == Shadow.FieldGet) || (kind == Shadow.FieldSet)) { HasThisTypePatternTriedToSneakInSomeGenericOrParameterizedTypePatternMatchingStuffAnywhereVisitor visitor = new HasThisTypePatternTriedToSneakInSomeGenericOrParameterizedTypePatternMatchingStuffAnywhereVisitor(); signature.getDeclaringType().traverse(visitor, null); if (visitor.wellHasItThen/*?*/()) { scope.message(MessageUtil.error(WeaverMessages.format(WeaverMessages.GET_AND_SET_DONT_SUPPORT_DEC_TYPE_PARAMETERS), getSourceLocation())); } // fields can't have a void type! UnresolvedType returnType = signature.getReturnType().getExactType(); if (returnType == ResolvedType.VOID) { scope.message(MessageUtil.error(WeaverMessages.format(WeaverMessages.FIELDS_CANT_HAVE_VOID_TYPE), getSourceLocation())); } } // no join points for initialization and preinitialization of parameterized types // no throwable parameterized types if ((kind == Shadow.Initialization) || (kind == Shadow.PreInitialization)) { HasThisTypePatternTriedToSneakInSomeGenericOrParameterizedTypePatternMatchingStuffAnywhereVisitor visitor = new HasThisTypePatternTriedToSneakInSomeGenericOrParameterizedTypePatternMatchingStuffAnywhereVisitor(); signature.getDeclaringType().traverse(visitor, null); if (visitor.wellHasItThen/*?*/()) { scope.message(MessageUtil.error(WeaverMessages.format(WeaverMessages.NO_INIT_JPS_FOR_PARAMETERIZED_TYPES), getSourceLocation())); } visitor = new HasThisTypePatternTriedToSneakInSomeGenericOrParameterizedTypePatternMatchingStuffAnywhereVisitor(); signature.getThrowsPattern().traverse(visitor, null); if (visitor.wellHasItThen/*?*/()) { scope.message(MessageUtil.error(WeaverMessages.format(WeaverMessages.NO_GENERIC_THROWABLES), getSourceLocation())); } } // no parameterized types in declaring type position // no throwable parameterized types if ((kind == Shadow.MethodExecution) || (kind == Shadow.ConstructorExecution)) { HasThisTypePatternTriedToSneakInSomeGenericOrParameterizedTypePatternMatchingStuffAnywhereVisitor visitor = new HasThisTypePatternTriedToSneakInSomeGenericOrParameterizedTypePatternMatchingStuffAnywhereVisitor(); signature.getDeclaringType().traverse(visitor, null); if (visitor.wellHasItThen/*?*/()) { scope.message(MessageUtil.error(WeaverMessages.format(WeaverMessages.EXECUTION_DOESNT_SUPPORT_PARAMETERIZED_DECLARING_TYPES), getSourceLocation())); } visitor = new HasThisTypePatternTriedToSneakInSomeGenericOrParameterizedTypePatternMatchingStuffAnywhereVisitor(); signature.getThrowsPattern().traverse(visitor, null); if (visitor.wellHasItThen/*?*/()) { scope.message(MessageUtil.error(WeaverMessages.format(WeaverMessages.NO_GENERIC_THROWABLES), getSourceLocation())); } } // no parameterized types in declaring type position // no throwable parameterized types if ((kind == Shadow.MethodCall) || (kind == Shadow.ConstructorCall)) { HasThisTypePatternTriedToSneakInSomeGenericOrParameterizedTypePatternMatchingStuffAnywhereVisitor visitor = new HasThisTypePatternTriedToSneakInSomeGenericOrParameterizedTypePatternMatchingStuffAnywhereVisitor(); signature.getDeclaringType().traverse(visitor, null); if (visitor.wellHasItThen/*?*/()) { scope.message(MessageUtil.error(WeaverMessages.format(WeaverMessages.CALL_DOESNT_SUPPORT_PARAMETERIZED_DECLARING_TYPES), getSourceLocation())); } visitor = new HasThisTypePatternTriedToSneakInSomeGenericOrParameterizedTypePatternMatchingStuffAnywhereVisitor(); signature.getThrowsPattern().traverse(visitor, null); if (visitor.wellHasItThen/*?*/()) { scope.message(MessageUtil.error(WeaverMessages.format(WeaverMessages.NO_GENERIC_THROWABLES), getSourceLocation())); } if (!scope.getWorld().isJoinpointArrayConstructionEnabled() && kind==Shadow.ConstructorCall && signature.getDeclaringType().isArray()) { scope.message(MessageUtil.warn(WeaverMessages.format(WeaverMessages.NO_NEWARRAY_JOINPOINTS_BY_DEFAULT),getSourceLocation())); } } } protected Test findResidueInternal(Shadow shadow, ExposedState state) { return match(shadow).alwaysTrue() ? Literal.TRUE : Literal.FALSE; } public Pointcut concretize1(ResolvedType inAspect, ResolvedType declaringType, IntMap bindings) { Pointcut ret = new KindedPointcut(kind, signature, bindings.getEnclosingAdvice()); ret.copyLocationFrom(this); return ret; } public Pointcut parameterizeWith(Map typeVariableMap) { Pointcut ret = new KindedPointcut(kind, signature.parameterizeWith(typeVariableMap), munger ); ret.copyLocationFrom(this); return ret; } public Shadow.Kind getKind() { return kind; } public Object accept(PatternNodeVisitor visitor, Object data) { return visitor.visit(this, data); } }
161,502
Bug 161502 UnsupportedOperationException thrown: unable to parameterize unresolved type: Pjava/util/List<+Ljava/lang/Object; >;
Generic parameters (like List<? extends T>) in pointcuts throw UnsupportedOperationException. java.lang.UnsupportedOperationException at org.aspectj.weaver.UnresolvedType.parameterize(UnresolvedType.java: 220) at org.aspectj.weaver.patterns.ExactTypePattern.parameterizeWith (ExactTypePattern.java:244) at org.aspectj.weaver.patterns.SignaturePattern.parameterizeWith (SignaturePattern.java:265) at org.aspectj.weaver.patterns.KindedPointcut.parameterizeWith (KindedPointcut.java:381) at org.aspectj.weaver.bcel.BcelAdvice.parameterizeWith (BcelAdvice.java:93) at org.aspectj.weaver.ResolvedType.getDeclaredAdvice (ResolvedType.java:710) at org.aspectj.weaver.ResolvedType.getDeclaredShadowMungers (ResolvedType.java:739) at org.aspectj.weaver.ResolvedType.collectShadowMungers (ResolvedType.java:575) at org.aspectj.weaver.ResolvedType.collectCrosscuttingMembers (ResolvedType.java:504) at org.aspectj.weaver.CrosscuttingMembersSet.addOrReplaceAspect (CrosscuttingMembersSet.java:68) at org.aspectj.weaver.CrosscuttingMembersSet.addOrReplaceAspect (CrosscuttingMembersSet.java:57) at org.aspectj.weaver.bcel.BcelWeaver.prepareForWeave(BcelWeaver.java: 450) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.weave (AjCompilerAdapter.java:299) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.afterCompiling (AjCompilerAdapter.java:192) at org.aspectj.ajdt.internal.compiler.CompilerAdapter.ajc $afterReturning$org_aspectj_ajdt_internal_compiler_CompilerAdapter$2 $f9cc9ca0(CompilerAdapter.aj:70) at org.aspectj.org.eclipse.jdt.internal.compiler.Compiler.compile (Compiler.java:367) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.performCompilation (AjBuildManager.java:887) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.doBuild (AjBuildManager.java:244) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.batchBuild (AjBuildManager.java:163) at org.aspectj.ajde.internal.CompilerAdapter.compile (CompilerAdapter.java:122) at org.aspectj.ajde.internal.AspectJBuildManager$CompilerThread.run (AspectJBuildManager.java:191) UnsupportedOperationException thrown: unable to parameterize unresolved type: Pjava/util/List<+Ljava/lang/Object;>; To reproduce this exception compile the following code snippet. import java.util.ArrayList; import java.util.List; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; public class Main { public List<? extends Element> getElements() { return new ArrayList<Element>(); } class Element {}; @Aspect static abstract class Base<T> { @Around("call(List<? extends T> *.*(..))") public List<? extends T> elementList(ProceedingJoinPoint thisJoinPoint) { try { return (List<? extends T>)thisJoinPoint.proceed(); } catch (Throwable e) { throw new RuntimeException(e); } } } @Aspect static class Concrete extends Base<Element> {} public static void main(String[] args) { new Main().getElements(); } }
resolved fixed
7b40e7e
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2006-10-24T12:42:57Z"
"2006-10-19T01:06:40Z"
weaver/src/org/aspectj/weaver/patterns/NotAnnotationTypePattern.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.DataOutputStream; import java.io.IOException; import java.util.Map; import org.aspectj.util.FuzzyBoolean; import org.aspectj.weaver.AnnotatedElement; import org.aspectj.weaver.ISourceContext; import org.aspectj.weaver.VersionedDataInputStream; import org.aspectj.weaver.World; public class NotAnnotationTypePattern extends AnnotationTypePattern { AnnotationTypePattern negatedPattern; public NotAnnotationTypePattern(AnnotationTypePattern pattern) { this.negatedPattern = pattern; setLocation(pattern.getSourceContext(), pattern.getStart(), pattern.getEnd()); } /* (non-Javadoc) * @see org.aspectj.weaver.patterns.AnnotationTypePattern#matches(org.aspectj.weaver.AnnotatedElement) */ public FuzzyBoolean matches(AnnotatedElement annotated) { return negatedPattern.matches(annotated).not(); } /* (non-Javadoc) * @see org.aspectj.weaver.patterns.AnnotationTypePattern#resolve(org.aspectj.weaver.World) */ public void resolve(World world) { negatedPattern.resolve(world); } /* (non-Javadoc) * @see org.aspectj.weaver.patterns.AnnotationTypePattern#resolveBindings(org.aspectj.weaver.patterns.IScope, org.aspectj.weaver.patterns.Bindings, boolean) */ public AnnotationTypePattern resolveBindings(IScope scope, Bindings bindings, boolean allowBinding) { negatedPattern = negatedPattern.resolveBindings(scope,bindings,allowBinding); return this; } public AnnotationTypePattern parameterizeWith(Map typeVariableMap) { AnnotationTypePattern newNegatedPattern = negatedPattern.parameterizeWith(typeVariableMap); NotAnnotationTypePattern ret = new NotAnnotationTypePattern(newNegatedPattern); ret.copyLocationFrom(this); return ret; } /* (non-Javadoc) * @see org.aspectj.weaver.patterns.PatternNode#write(java.io.DataOutputStream) */ public void write(DataOutputStream s) throws IOException { s.writeByte(AnnotationTypePattern.NOT); negatedPattern.write(s); writeLocation(s); } public static AnnotationTypePattern read(VersionedDataInputStream s, ISourceContext context) throws IOException { AnnotationTypePattern ret = new NotAnnotationTypePattern(AnnotationTypePattern.read(s,context)); ret.readLocation(context,s); return ret; } public boolean equals(Object obj) { if (!(obj instanceof NotAnnotationTypePattern)) return false; NotAnnotationTypePattern other = (NotAnnotationTypePattern) obj; return other.negatedPattern.equals(negatedPattern); } public int hashCode() { int result = 17 + 37*negatedPattern.hashCode(); return result; } public String toString() { return "!" + negatedPattern.toString(); } public AnnotationTypePattern getNegatedPattern() { return negatedPattern; } public Object accept(PatternNodeVisitor visitor, Object data) { return visitor.visit(this, data); } public Object traverse(PatternNodeVisitor visitor, Object data) { Object ret = accept(visitor,data); negatedPattern.traverse(visitor,ret); return ret; } }
161,502
Bug 161502 UnsupportedOperationException thrown: unable to parameterize unresolved type: Pjava/util/List<+Ljava/lang/Object; >;
Generic parameters (like List<? extends T>) in pointcuts throw UnsupportedOperationException. java.lang.UnsupportedOperationException at org.aspectj.weaver.UnresolvedType.parameterize(UnresolvedType.java: 220) at org.aspectj.weaver.patterns.ExactTypePattern.parameterizeWith (ExactTypePattern.java:244) at org.aspectj.weaver.patterns.SignaturePattern.parameterizeWith (SignaturePattern.java:265) at org.aspectj.weaver.patterns.KindedPointcut.parameterizeWith (KindedPointcut.java:381) at org.aspectj.weaver.bcel.BcelAdvice.parameterizeWith (BcelAdvice.java:93) at org.aspectj.weaver.ResolvedType.getDeclaredAdvice (ResolvedType.java:710) at org.aspectj.weaver.ResolvedType.getDeclaredShadowMungers (ResolvedType.java:739) at org.aspectj.weaver.ResolvedType.collectShadowMungers (ResolvedType.java:575) at org.aspectj.weaver.ResolvedType.collectCrosscuttingMembers (ResolvedType.java:504) at org.aspectj.weaver.CrosscuttingMembersSet.addOrReplaceAspect (CrosscuttingMembersSet.java:68) at org.aspectj.weaver.CrosscuttingMembersSet.addOrReplaceAspect (CrosscuttingMembersSet.java:57) at org.aspectj.weaver.bcel.BcelWeaver.prepareForWeave(BcelWeaver.java: 450) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.weave (AjCompilerAdapter.java:299) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.afterCompiling (AjCompilerAdapter.java:192) at org.aspectj.ajdt.internal.compiler.CompilerAdapter.ajc $afterReturning$org_aspectj_ajdt_internal_compiler_CompilerAdapter$2 $f9cc9ca0(CompilerAdapter.aj:70) at org.aspectj.org.eclipse.jdt.internal.compiler.Compiler.compile (Compiler.java:367) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.performCompilation (AjBuildManager.java:887) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.doBuild (AjBuildManager.java:244) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.batchBuild (AjBuildManager.java:163) at org.aspectj.ajde.internal.CompilerAdapter.compile (CompilerAdapter.java:122) at org.aspectj.ajde.internal.AspectJBuildManager$CompilerThread.run (AspectJBuildManager.java:191) UnsupportedOperationException thrown: unable to parameterize unresolved type: Pjava/util/List<+Ljava/lang/Object;>; To reproduce this exception compile the following code snippet. import java.util.ArrayList; import java.util.List; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; public class Main { public List<? extends Element> getElements() { return new ArrayList<Element>(); } class Element {}; @Aspect static abstract class Base<T> { @Around("call(List<? extends T> *.*(..))") public List<? extends T> elementList(ProceedingJoinPoint thisJoinPoint) { try { return (List<? extends T>)thisJoinPoint.proceed(); } catch (Throwable e) { throw new RuntimeException(e); } } } @Aspect static class Concrete extends Base<Element> {} public static void main(String[] args) { new Main().getElements(); } }
resolved fixed
7b40e7e
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2006-10-24T12:42:57Z"
"2006-10-19T01:06:40Z"
weaver/src/org/aspectj/weaver/patterns/NotPointcut.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.DataOutputStream; import java.io.IOException; import java.util.Map; import org.aspectj.util.FuzzyBoolean; import org.aspectj.weaver.ISourceContext; import org.aspectj.weaver.IntMap; import org.aspectj.weaver.ResolvedType; import org.aspectj.weaver.Shadow; import org.aspectj.weaver.VersionedDataInputStream; import org.aspectj.weaver.ast.Test; public class NotPointcut extends Pointcut { private Pointcut body; public NotPointcut(Pointcut negated) { super(); this.body = negated; this.pointcutKind = NOT; } public NotPointcut(Pointcut pointcut, int startPos) { this(pointcut); setLocation(pointcut.getSourceContext(), startPos, pointcut.getEnd()); } public int couldMatchKinds() { return Shadow.ALL_SHADOW_KINDS_BITS; } public Pointcut getNegatedPointcut() { return body; } public FuzzyBoolean fastMatch(FastMatchInfo type) { return body.fastMatch(type).not(); } protected FuzzyBoolean matchInternal(Shadow shadow) { return body.match(shadow).not(); } public String toString() { return "!" + body.toString(); } public boolean equals(Object other) { if (!(other instanceof NotPointcut)) return false; NotPointcut o = (NotPointcut)other; return o.body.equals(body); } public int hashCode() { return 37*23 + body.hashCode(); } public void resolveBindings(IScope scope, Bindings bindings) { //Bindings old = bindings.copy(); //Bindings newBindings = new Bindings(bindings.size()); body.resolveBindings(scope, null); //newBindings.checkEmpty(scope, "negation does not allow binding"); //bindings.checkEquals(old, scope); } public void write(DataOutputStream s) throws IOException { s.writeByte(Pointcut.NOT); body.write(s); writeLocation(s); } public static Pointcut read(VersionedDataInputStream s, ISourceContext context) throws IOException { NotPointcut ret = new NotPointcut(Pointcut.read(s, context)); ret.readLocation(context, s); return ret; } protected Test findResidueInternal(Shadow shadow, ExposedState state) { return Test.makeNot(body.findResidue(shadow, state)); } public Pointcut concretize1(ResolvedType inAspect, ResolvedType declaringType, IntMap bindings) { Pointcut ret = new NotPointcut(body.concretize(inAspect, declaringType, bindings)); ret.copyLocationFrom(this); return ret; } public Pointcut parameterizeWith(Map typeVariableMap) { Pointcut ret = new NotPointcut(body.parameterizeWith(typeVariableMap)); ret.copyLocationFrom(this); return ret; } public Object accept(PatternNodeVisitor visitor, Object data) { return visitor.visit(this, data); } public Object traverse(PatternNodeVisitor visitor, Object data) { Object ret = accept(visitor,data); this.body.traverse(visitor,ret); return ret; } }
161,502
Bug 161502 UnsupportedOperationException thrown: unable to parameterize unresolved type: Pjava/util/List<+Ljava/lang/Object; >;
Generic parameters (like List<? extends T>) in pointcuts throw UnsupportedOperationException. java.lang.UnsupportedOperationException at org.aspectj.weaver.UnresolvedType.parameterize(UnresolvedType.java: 220) at org.aspectj.weaver.patterns.ExactTypePattern.parameterizeWith (ExactTypePattern.java:244) at org.aspectj.weaver.patterns.SignaturePattern.parameterizeWith (SignaturePattern.java:265) at org.aspectj.weaver.patterns.KindedPointcut.parameterizeWith (KindedPointcut.java:381) at org.aspectj.weaver.bcel.BcelAdvice.parameterizeWith (BcelAdvice.java:93) at org.aspectj.weaver.ResolvedType.getDeclaredAdvice (ResolvedType.java:710) at org.aspectj.weaver.ResolvedType.getDeclaredShadowMungers (ResolvedType.java:739) at org.aspectj.weaver.ResolvedType.collectShadowMungers (ResolvedType.java:575) at org.aspectj.weaver.ResolvedType.collectCrosscuttingMembers (ResolvedType.java:504) at org.aspectj.weaver.CrosscuttingMembersSet.addOrReplaceAspect (CrosscuttingMembersSet.java:68) at org.aspectj.weaver.CrosscuttingMembersSet.addOrReplaceAspect (CrosscuttingMembersSet.java:57) at org.aspectj.weaver.bcel.BcelWeaver.prepareForWeave(BcelWeaver.java: 450) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.weave (AjCompilerAdapter.java:299) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.afterCompiling (AjCompilerAdapter.java:192) at org.aspectj.ajdt.internal.compiler.CompilerAdapter.ajc $afterReturning$org_aspectj_ajdt_internal_compiler_CompilerAdapter$2 $f9cc9ca0(CompilerAdapter.aj:70) at org.aspectj.org.eclipse.jdt.internal.compiler.Compiler.compile (Compiler.java:367) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.performCompilation (AjBuildManager.java:887) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.doBuild (AjBuildManager.java:244) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.batchBuild (AjBuildManager.java:163) at org.aspectj.ajde.internal.CompilerAdapter.compile (CompilerAdapter.java:122) at org.aspectj.ajde.internal.AspectJBuildManager$CompilerThread.run (AspectJBuildManager.java:191) UnsupportedOperationException thrown: unable to parameterize unresolved type: Pjava/util/List<+Ljava/lang/Object;>; To reproduce this exception compile the following code snippet. import java.util.ArrayList; import java.util.List; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; public class Main { public List<? extends Element> getElements() { return new ArrayList<Element>(); } class Element {}; @Aspect static abstract class Base<T> { @Around("call(List<? extends T> *.*(..))") public List<? extends T> elementList(ProceedingJoinPoint thisJoinPoint) { try { return (List<? extends T>)thisJoinPoint.proceed(); } catch (Throwable e) { throw new RuntimeException(e); } } } @Aspect static class Concrete extends Base<Element> {} public static void main(String[] args) { new Main().getElements(); } }
resolved fixed
7b40e7e
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2006-10-24T12:42:57Z"
"2006-10-19T01:06:40Z"
weaver/src/org/aspectj/weaver/patterns/NotTypePattern.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.DataOutputStream; import java.io.IOException; import java.util.Map; import org.aspectj.util.FuzzyBoolean; import org.aspectj.weaver.AjAttribute; import org.aspectj.weaver.ISourceContext; import org.aspectj.weaver.ResolvedType; import org.aspectj.weaver.VersionedDataInputStream; /** * !TypePattern * * <p>any binding to formals is explicitly forbidden for any composite, ! is * just the most obviously wrong case. * * @author Erik Hilsdale * @author Jim Hugunin */ public class NotTypePattern extends TypePattern { private TypePattern negatedPattern; public NotTypePattern(TypePattern pattern) { super(false,false); //??? we override all methods that care about includeSubtypes this.negatedPattern = pattern; setLocation(pattern.getSourceContext(), pattern.getStart(), pattern.getEnd()); } public TypePattern getNegatedPattern() { return negatedPattern; } /* (non-Javadoc) * @see org.aspectj.weaver.patterns.TypePattern#couldEverMatchSameTypesAs(org.aspectj.weaver.patterns.TypePattern) */ protected boolean couldEverMatchSameTypesAs(TypePattern other) { return true; } public FuzzyBoolean matchesInstanceof(ResolvedType type) { return negatedPattern.matchesInstanceof(type).not(); } protected boolean matchesExactly(ResolvedType type) { return (!negatedPattern.matchesExactly(type) && annotationPattern.matches(type).alwaysTrue()); } protected boolean matchesExactly(ResolvedType type, ResolvedType annotatedType) { return (!negatedPattern.matchesExactly(type,annotatedType) && annotationPattern.matches(annotatedType).alwaysTrue()); } public boolean matchesStatically(ResolvedType type) { return !negatedPattern.matchesStatically(type); } public void setAnnotationTypePattern(AnnotationTypePattern annPatt) { super.setAnnotationTypePattern(annPatt); } public void setIsVarArgs(boolean isVarArgs) { negatedPattern.setIsVarArgs(isVarArgs); } public void write(DataOutputStream s) throws IOException { s.writeByte(TypePattern.NOT); negatedPattern.write(s); annotationPattern.write(s); writeLocation(s); } public static TypePattern read(VersionedDataInputStream s, ISourceContext context) throws IOException { TypePattern ret = new NotTypePattern(TypePattern.read(s, context)); if (s.getMajorVersion()>=AjAttribute.WeaverVersionInfo.WEAVER_VERSION_MAJOR_AJ150) { ret.annotationPattern = AnnotationTypePattern.read(s,context); } ret.readLocation(context, s); return ret; } public TypePattern resolveBindings( IScope scope, Bindings bindings, boolean allowBinding, boolean requireExactType) { if (requireExactType) return notExactType(scope); negatedPattern = negatedPattern.resolveBindings(scope, bindings, false, false); return this; } public TypePattern parameterizeWith(Map typeVariableMap) { TypePattern newNegatedPattern = negatedPattern.parameterizeWith(typeVariableMap); NotTypePattern ret = new NotTypePattern(newNegatedPattern); ret.copyLocationFrom(this); return ret; } public String toString() { StringBuffer buff = new StringBuffer(); if (annotationPattern != AnnotationTypePattern.ANY) { buff.append('('); buff.append(annotationPattern.toString()); buff.append(' '); } buff.append('!'); buff.append(negatedPattern); if (annotationPattern != AnnotationTypePattern.ANY) { buff.append(')'); } return buff.toString(); } /* (non-Javadoc) * @see java.lang.Object#equals(java.lang.Object) */ public boolean equals(Object obj) { if (! (obj instanceof NotTypePattern)) return false; return (negatedPattern.equals(((NotTypePattern)obj).negatedPattern)); } /* (non-Javadoc) * @see java.lang.Object#hashCode() */ public int hashCode() { return 17 + 37 * negatedPattern.hashCode(); } public Object accept(PatternNodeVisitor visitor, Object data) { return visitor.visit(this, data); } public Object traverse(PatternNodeVisitor visitor, Object data) { Object ret = accept(visitor,data); negatedPattern.traverse(visitor, ret); return ret; } }
161,502
Bug 161502 UnsupportedOperationException thrown: unable to parameterize unresolved type: Pjava/util/List<+Ljava/lang/Object; >;
Generic parameters (like List<? extends T>) in pointcuts throw UnsupportedOperationException. java.lang.UnsupportedOperationException at org.aspectj.weaver.UnresolvedType.parameterize(UnresolvedType.java: 220) at org.aspectj.weaver.patterns.ExactTypePattern.parameterizeWith (ExactTypePattern.java:244) at org.aspectj.weaver.patterns.SignaturePattern.parameterizeWith (SignaturePattern.java:265) at org.aspectj.weaver.patterns.KindedPointcut.parameterizeWith (KindedPointcut.java:381) at org.aspectj.weaver.bcel.BcelAdvice.parameterizeWith (BcelAdvice.java:93) at org.aspectj.weaver.ResolvedType.getDeclaredAdvice (ResolvedType.java:710) at org.aspectj.weaver.ResolvedType.getDeclaredShadowMungers (ResolvedType.java:739) at org.aspectj.weaver.ResolvedType.collectShadowMungers (ResolvedType.java:575) at org.aspectj.weaver.ResolvedType.collectCrosscuttingMembers (ResolvedType.java:504) at org.aspectj.weaver.CrosscuttingMembersSet.addOrReplaceAspect (CrosscuttingMembersSet.java:68) at org.aspectj.weaver.CrosscuttingMembersSet.addOrReplaceAspect (CrosscuttingMembersSet.java:57) at org.aspectj.weaver.bcel.BcelWeaver.prepareForWeave(BcelWeaver.java: 450) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.weave (AjCompilerAdapter.java:299) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.afterCompiling (AjCompilerAdapter.java:192) at org.aspectj.ajdt.internal.compiler.CompilerAdapter.ajc $afterReturning$org_aspectj_ajdt_internal_compiler_CompilerAdapter$2 $f9cc9ca0(CompilerAdapter.aj:70) at org.aspectj.org.eclipse.jdt.internal.compiler.Compiler.compile (Compiler.java:367) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.performCompilation (AjBuildManager.java:887) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.doBuild (AjBuildManager.java:244) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.batchBuild (AjBuildManager.java:163) at org.aspectj.ajde.internal.CompilerAdapter.compile (CompilerAdapter.java:122) at org.aspectj.ajde.internal.AspectJBuildManager$CompilerThread.run (AspectJBuildManager.java:191) UnsupportedOperationException thrown: unable to parameterize unresolved type: Pjava/util/List<+Ljava/lang/Object;>; To reproduce this exception compile the following code snippet. import java.util.ArrayList; import java.util.List; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; public class Main { public List<? extends Element> getElements() { return new ArrayList<Element>(); } class Element {}; @Aspect static abstract class Base<T> { @Around("call(List<? extends T> *.*(..))") public List<? extends T> elementList(ProceedingJoinPoint thisJoinPoint) { try { return (List<? extends T>)thisJoinPoint.proceed(); } catch (Throwable e) { throw new RuntimeException(e); } } } @Aspect static class Concrete extends Base<Element> {} public static void main(String[] args) { new Main().getElements(); } }
resolved fixed
7b40e7e
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2006-10-24T12:42:57Z"
"2006-10-19T01:06:40Z"
weaver/src/org/aspectj/weaver/patterns/OrAnnotationTypePattern.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.DataOutputStream; import java.io.IOException; import java.util.Map; import org.aspectj.util.FuzzyBoolean; import org.aspectj.weaver.AnnotatedElement; import org.aspectj.weaver.ISourceContext; import org.aspectj.weaver.VersionedDataInputStream; import org.aspectj.weaver.World; public class OrAnnotationTypePattern extends AnnotationTypePattern { private AnnotationTypePattern left; private AnnotationTypePattern right; public OrAnnotationTypePattern(AnnotationTypePattern left, AnnotationTypePattern right) { this.left = left; this.right = right; setLocation(left.getSourceContext(), left.getStart(), right.getEnd()); } public FuzzyBoolean matches(AnnotatedElement annotated) { return left.matches(annotated).or(right.matches(annotated)); } public void resolve(World world) { left.resolve(world); right.resolve(world); } /* (non-Javadoc) * @see org.aspectj.weaver.patterns.AnnotationTypePattern#resolveBindings(org.aspectj.weaver.patterns.IScope, org.aspectj.weaver.patterns.Bindings, boolean) */ public AnnotationTypePattern resolveBindings(IScope scope, Bindings bindings, boolean allowBinding) { left = left.resolveBindings(scope,bindings,allowBinding); right =right.resolveBindings(scope,bindings,allowBinding); return this; } public AnnotationTypePattern parameterizeWith(Map typeVariableMap) { AnnotationTypePattern newLeft = left.parameterizeWith(typeVariableMap); AnnotationTypePattern newRight = right.parameterizeWith(typeVariableMap); OrAnnotationTypePattern ret = new OrAnnotationTypePattern(newLeft,newRight); ret.copyLocationFrom(this); return ret; } 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; } public static AnnotationTypePattern read(VersionedDataInputStream s, ISourceContext context) throws IOException { AnnotationTypePattern p = new OrAnnotationTypePattern( AnnotationTypePattern.read(s,context), AnnotationTypePattern.read(s,context)); p.readLocation(context,s); return p; } public void write(DataOutputStream s) throws IOException { s.writeByte(AnnotationTypePattern.OR); left.write(s); right.write(s); writeLocation(s); } public boolean equals(Object obj) { if (!(obj instanceof OrAnnotationTypePattern)) return false; OrAnnotationTypePattern other = (OrAnnotationTypePattern) obj; return (left.equals(other.left) && right.equals(other.right)); } public int hashCode() { int result = 17; result = result*37 + left.hashCode(); result = result*37 + right.hashCode(); return result; } public String toString() { return "(" + left.toString() + " || " + right.toString() + ")"; } public AnnotationTypePattern getLeft() { return left; } public AnnotationTypePattern getRight() { return right; } }
161,502
Bug 161502 UnsupportedOperationException thrown: unable to parameterize unresolved type: Pjava/util/List<+Ljava/lang/Object; >;
Generic parameters (like List<? extends T>) in pointcuts throw UnsupportedOperationException. java.lang.UnsupportedOperationException at org.aspectj.weaver.UnresolvedType.parameterize(UnresolvedType.java: 220) at org.aspectj.weaver.patterns.ExactTypePattern.parameterizeWith (ExactTypePattern.java:244) at org.aspectj.weaver.patterns.SignaturePattern.parameterizeWith (SignaturePattern.java:265) at org.aspectj.weaver.patterns.KindedPointcut.parameterizeWith (KindedPointcut.java:381) at org.aspectj.weaver.bcel.BcelAdvice.parameterizeWith (BcelAdvice.java:93) at org.aspectj.weaver.ResolvedType.getDeclaredAdvice (ResolvedType.java:710) at org.aspectj.weaver.ResolvedType.getDeclaredShadowMungers (ResolvedType.java:739) at org.aspectj.weaver.ResolvedType.collectShadowMungers (ResolvedType.java:575) at org.aspectj.weaver.ResolvedType.collectCrosscuttingMembers (ResolvedType.java:504) at org.aspectj.weaver.CrosscuttingMembersSet.addOrReplaceAspect (CrosscuttingMembersSet.java:68) at org.aspectj.weaver.CrosscuttingMembersSet.addOrReplaceAspect (CrosscuttingMembersSet.java:57) at org.aspectj.weaver.bcel.BcelWeaver.prepareForWeave(BcelWeaver.java: 450) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.weave (AjCompilerAdapter.java:299) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.afterCompiling (AjCompilerAdapter.java:192) at org.aspectj.ajdt.internal.compiler.CompilerAdapter.ajc $afterReturning$org_aspectj_ajdt_internal_compiler_CompilerAdapter$2 $f9cc9ca0(CompilerAdapter.aj:70) at org.aspectj.org.eclipse.jdt.internal.compiler.Compiler.compile (Compiler.java:367) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.performCompilation (AjBuildManager.java:887) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.doBuild (AjBuildManager.java:244) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.batchBuild (AjBuildManager.java:163) at org.aspectj.ajde.internal.CompilerAdapter.compile (CompilerAdapter.java:122) at org.aspectj.ajde.internal.AspectJBuildManager$CompilerThread.run (AspectJBuildManager.java:191) UnsupportedOperationException thrown: unable to parameterize unresolved type: Pjava/util/List<+Ljava/lang/Object;>; To reproduce this exception compile the following code snippet. import java.util.ArrayList; import java.util.List; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; public class Main { public List<? extends Element> getElements() { return new ArrayList<Element>(); } class Element {}; @Aspect static abstract class Base<T> { @Around("call(List<? extends T> *.*(..))") public List<? extends T> elementList(ProceedingJoinPoint thisJoinPoint) { try { return (List<? extends T>)thisJoinPoint.proceed(); } catch (Throwable e) { throw new RuntimeException(e); } } } @Aspect static class Concrete extends Base<Element> {} public static void main(String[] args) { new Main().getElements(); } }
resolved fixed
7b40e7e
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2006-10-24T12:42:57Z"
"2006-10-19T01:06:40Z"
weaver/src/org/aspectj/weaver/patterns/OrPointcut.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.DataOutputStream; import java.io.IOException; import java.util.Map; import org.aspectj.util.FuzzyBoolean; import org.aspectj.weaver.ISourceContext; import org.aspectj.weaver.IntMap; import org.aspectj.weaver.ResolvedType; import org.aspectj.weaver.Shadow; import org.aspectj.weaver.VersionedDataInputStream; import org.aspectj.weaver.ast.Test; public class OrPointcut extends Pointcut { Pointcut left, right; private int couldMatchKinds; public OrPointcut(Pointcut left, Pointcut right) { super(); this.left = left; this.right = right; setLocation(left.getSourceContext(), left.getStart(), right.getEnd()); this.pointcutKind = OR; this.couldMatchKinds = left.couldMatchKinds() | right.couldMatchKinds(); } public int couldMatchKinds() { return couldMatchKinds; } public FuzzyBoolean fastMatch(FastMatchInfo type) { return left.fastMatch(type).or(right.fastMatch(type)); } protected FuzzyBoolean matchInternal(Shadow shadow) { FuzzyBoolean leftMatch = left.match(shadow); if (leftMatch.alwaysTrue()) return leftMatch; return leftMatch.or(right.match(shadow)); } public String toString() { return "(" + left.toString() + " || " + right.toString() + ")"; } public boolean equals(Object other) { if (!(other instanceof OrPointcut)) return false; OrPointcut o = (OrPointcut)other; return o.left.equals(left) && o.right.equals(right); } public int hashCode() { int result = 31; result = 37*result + left.hashCode(); result = 37*result + right.hashCode(); return result; } /** * @see org.aspectj.weaver.patterns.Pointcut#resolveBindings(IScope, Bindings) */ public void resolveBindings(IScope scope, Bindings bindings) { Bindings old = bindings == null ? null : bindings.copy(); left.resolveBindings(scope, bindings); right.resolveBindings(scope, old); if (bindings != null) bindings.checkEquals(old, scope); } public void write(DataOutputStream s) throws IOException { s.writeByte(Pointcut.OR); left.write(s); right.write(s); writeLocation(s); } public static Pointcut read(VersionedDataInputStream s, ISourceContext context) throws IOException { OrPointcut ret = new OrPointcut(Pointcut.read(s, context), Pointcut.read(s, context)); ret.readLocation(context, s); return ret; } protected Test findResidueInternal(Shadow shadow, ExposedState state) { return Test.makeOr(left.findResidue(shadow, state), right.findResidue(shadow, state)); } public Pointcut concretize1(ResolvedType inAspect, ResolvedType declaringType, IntMap bindings) { Pointcut ret = new OrPointcut(left.concretize(inAspect, declaringType, bindings), right.concretize(inAspect, declaringType, bindings)); ret.copyLocationFrom(this); return ret; } public Pointcut parameterizeWith(Map typeVariableMap) { Pointcut ret = new OrPointcut(left.parameterizeWith(typeVariableMap), right.parameterizeWith(typeVariableMap)); 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; } }
161,502
Bug 161502 UnsupportedOperationException thrown: unable to parameterize unresolved type: Pjava/util/List<+Ljava/lang/Object; >;
Generic parameters (like List<? extends T>) in pointcuts throw UnsupportedOperationException. java.lang.UnsupportedOperationException at org.aspectj.weaver.UnresolvedType.parameterize(UnresolvedType.java: 220) at org.aspectj.weaver.patterns.ExactTypePattern.parameterizeWith (ExactTypePattern.java:244) at org.aspectj.weaver.patterns.SignaturePattern.parameterizeWith (SignaturePattern.java:265) at org.aspectj.weaver.patterns.KindedPointcut.parameterizeWith (KindedPointcut.java:381) at org.aspectj.weaver.bcel.BcelAdvice.parameterizeWith (BcelAdvice.java:93) at org.aspectj.weaver.ResolvedType.getDeclaredAdvice (ResolvedType.java:710) at org.aspectj.weaver.ResolvedType.getDeclaredShadowMungers (ResolvedType.java:739) at org.aspectj.weaver.ResolvedType.collectShadowMungers (ResolvedType.java:575) at org.aspectj.weaver.ResolvedType.collectCrosscuttingMembers (ResolvedType.java:504) at org.aspectj.weaver.CrosscuttingMembersSet.addOrReplaceAspect (CrosscuttingMembersSet.java:68) at org.aspectj.weaver.CrosscuttingMembersSet.addOrReplaceAspect (CrosscuttingMembersSet.java:57) at org.aspectj.weaver.bcel.BcelWeaver.prepareForWeave(BcelWeaver.java: 450) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.weave (AjCompilerAdapter.java:299) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.afterCompiling (AjCompilerAdapter.java:192) at org.aspectj.ajdt.internal.compiler.CompilerAdapter.ajc $afterReturning$org_aspectj_ajdt_internal_compiler_CompilerAdapter$2 $f9cc9ca0(CompilerAdapter.aj:70) at org.aspectj.org.eclipse.jdt.internal.compiler.Compiler.compile (Compiler.java:367) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.performCompilation (AjBuildManager.java:887) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.doBuild (AjBuildManager.java:244) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.batchBuild (AjBuildManager.java:163) at org.aspectj.ajde.internal.CompilerAdapter.compile (CompilerAdapter.java:122) at org.aspectj.ajde.internal.AspectJBuildManager$CompilerThread.run (AspectJBuildManager.java:191) UnsupportedOperationException thrown: unable to parameterize unresolved type: Pjava/util/List<+Ljava/lang/Object;>; To reproduce this exception compile the following code snippet. import java.util.ArrayList; import java.util.List; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; public class Main { public List<? extends Element> getElements() { return new ArrayList<Element>(); } class Element {}; @Aspect static abstract class Base<T> { @Around("call(List<? extends T> *.*(..))") public List<? extends T> elementList(ProceedingJoinPoint thisJoinPoint) { try { return (List<? extends T>)thisJoinPoint.proceed(); } catch (Throwable e) { throw new RuntimeException(e); } } } @Aspect static class Concrete extends Base<Element> {} public static void main(String[] args) { new Main().getElements(); } }
resolved fixed
7b40e7e
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2006-10-24T12:42:57Z"
"2006-10-19T01:06:40Z"
weaver/src/org/aspectj/weaver/patterns/OrTypePattern.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.DataOutputStream; import java.io.IOException; import java.util.Map; import org.aspectj.util.FuzzyBoolean; import org.aspectj.weaver.ISourceContext; import org.aspectj.weaver.ResolvedType; import org.aspectj.weaver.VersionedDataInputStream; /** * left || right * * <p>any binding to formals is explicitly forbidden for any composite by the language * * @author Erik Hilsdale * @author Jim Hugunin */ public class OrTypePattern extends TypePattern { private TypePattern left, right; public OrTypePattern(TypePattern left, TypePattern right) { super(false,false); //??? we override all methods that care about includeSubtypes this.left = left; this.right = right; setLocation(left.getSourceContext(), left.getStart(), right.getEnd()); } public TypePattern getRight() { return right; } public TypePattern getLeft() { return left; } /* (non-Javadoc) * @see org.aspectj.weaver.patterns.TypePattern#couldEverMatchSameTypesAs(org.aspectj.weaver.patterns.TypePattern) */ protected boolean couldEverMatchSameTypesAs(TypePattern other) { return true; // don't dive at the moment... } public FuzzyBoolean matchesInstanceof(ResolvedType type) { return left.matchesInstanceof(type).or(right.matchesInstanceof(type)); } protected boolean matchesExactly(ResolvedType type) { //??? if these had side-effects, this sort-circuit could be a mistake return left.matchesExactly(type) || right.matchesExactly(type); } protected boolean matchesExactly(ResolvedType type, ResolvedType annotatedType) { //??? if these had side-effects, this sort-circuit could be a mistake return left.matchesExactly(type,annotatedType) || right.matchesExactly(type,annotatedType); } public boolean matchesStatically(ResolvedType type) { return left.matchesStatically(type) || right.matchesStatically(type); } public void setIsVarArgs(boolean isVarArgs) { this.isVarArgs = isVarArgs; left.setIsVarArgs(isVarArgs); right.setIsVarArgs(isVarArgs); } public void setAnnotationTypePattern(AnnotationTypePattern annPatt) { if (annPatt == AnnotationTypePattern.ANY) return; if (left.annotationPattern == AnnotationTypePattern.ANY) { left.setAnnotationTypePattern(annPatt); } else { left.setAnnotationTypePattern( new AndAnnotationTypePattern(left.annotationPattern,annPatt)); } if (right.annotationPattern == AnnotationTypePattern.ANY) { right.setAnnotationTypePattern(annPatt); } else { right.setAnnotationTypePattern( new AndAnnotationTypePattern(right.annotationPattern,annPatt)); } } public void write(DataOutputStream s) throws IOException { s.writeByte(TypePattern.OR); left.write(s); right.write(s); writeLocation(s); } public static TypePattern read(VersionedDataInputStream s, ISourceContext context) throws IOException { OrTypePattern ret = new OrTypePattern(TypePattern.read(s, context), TypePattern.read(s, context)); ret.readLocation(context, s); if (ret.left.isVarArgs && ret.right.isVarArgs) ret.isVarArgs = true; return ret; } public TypePattern resolveBindings( IScope scope, Bindings bindings, boolean allowBinding, boolean requireExactType) { if (requireExactType) return notExactType(scope); left = left.resolveBindings(scope, bindings, false, false); right = right.resolveBindings(scope, bindings, false, false); return this; } public TypePattern parameterizeWith(Map typeVariableMap) { TypePattern newLeft = left.parameterizeWith(typeVariableMap); TypePattern newRight = right.parameterizeWith(typeVariableMap); OrTypePattern ret = new OrTypePattern(newLeft,newRight); ret.copyLocationFrom(this); return ret; } public String toString() { StringBuffer buff = new StringBuffer(); if (annotationPattern != AnnotationTypePattern.ANY) { buff.append('('); buff.append(annotationPattern.toString()); buff.append(' '); } buff.append('('); buff.append(left.toString()); buff.append(" || "); buff.append(right.toString()); buff.append(')'); if (annotationPattern != AnnotationTypePattern.ANY) { buff.append(')'); } return buff.toString(); } /* (non-Javadoc) * @see java.lang.Object#equals(java.lang.Object) */ public boolean equals(Object obj) { if (! (obj instanceof OrTypePattern)) return false; OrTypePattern other = (OrTypePattern) obj; return left.equals(other.left) && right.equals(other.right); } /* (non-Javadoc) * @see java.lang.Object#hashCode() */ public int hashCode() { int ret = 17; ret = ret + 37 * left.hashCode(); ret = ret + 37 * right.hashCode(); return ret; } 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; } }
161,502
Bug 161502 UnsupportedOperationException thrown: unable to parameterize unresolved type: Pjava/util/List<+Ljava/lang/Object; >;
Generic parameters (like List<? extends T>) in pointcuts throw UnsupportedOperationException. java.lang.UnsupportedOperationException at org.aspectj.weaver.UnresolvedType.parameterize(UnresolvedType.java: 220) at org.aspectj.weaver.patterns.ExactTypePattern.parameterizeWith (ExactTypePattern.java:244) at org.aspectj.weaver.patterns.SignaturePattern.parameterizeWith (SignaturePattern.java:265) at org.aspectj.weaver.patterns.KindedPointcut.parameterizeWith (KindedPointcut.java:381) at org.aspectj.weaver.bcel.BcelAdvice.parameterizeWith (BcelAdvice.java:93) at org.aspectj.weaver.ResolvedType.getDeclaredAdvice (ResolvedType.java:710) at org.aspectj.weaver.ResolvedType.getDeclaredShadowMungers (ResolvedType.java:739) at org.aspectj.weaver.ResolvedType.collectShadowMungers (ResolvedType.java:575) at org.aspectj.weaver.ResolvedType.collectCrosscuttingMembers (ResolvedType.java:504) at org.aspectj.weaver.CrosscuttingMembersSet.addOrReplaceAspect (CrosscuttingMembersSet.java:68) at org.aspectj.weaver.CrosscuttingMembersSet.addOrReplaceAspect (CrosscuttingMembersSet.java:57) at org.aspectj.weaver.bcel.BcelWeaver.prepareForWeave(BcelWeaver.java: 450) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.weave (AjCompilerAdapter.java:299) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.afterCompiling (AjCompilerAdapter.java:192) at org.aspectj.ajdt.internal.compiler.CompilerAdapter.ajc $afterReturning$org_aspectj_ajdt_internal_compiler_CompilerAdapter$2 $f9cc9ca0(CompilerAdapter.aj:70) at org.aspectj.org.eclipse.jdt.internal.compiler.Compiler.compile (Compiler.java:367) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.performCompilation (AjBuildManager.java:887) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.doBuild (AjBuildManager.java:244) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.batchBuild (AjBuildManager.java:163) at org.aspectj.ajde.internal.CompilerAdapter.compile (CompilerAdapter.java:122) at org.aspectj.ajde.internal.AspectJBuildManager$CompilerThread.run (AspectJBuildManager.java:191) UnsupportedOperationException thrown: unable to parameterize unresolved type: Pjava/util/List<+Ljava/lang/Object;>; To reproduce this exception compile the following code snippet. import java.util.ArrayList; import java.util.List; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; public class Main { public List<? extends Element> getElements() { return new ArrayList<Element>(); } class Element {}; @Aspect static abstract class Base<T> { @Around("call(List<? extends T> *.*(..))") public List<? extends T> elementList(ProceedingJoinPoint thisJoinPoint) { try { return (List<? extends T>)thisJoinPoint.proceed(); } catch (Throwable e) { throw new RuntimeException(e); } } } @Aspect static class Concrete extends Base<Element> {} public static void main(String[] args) { new Main().getElements(); } }
resolved fixed
7b40e7e
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2006-10-24T12:42:57Z"
"2006-10-19T01:06:40Z"
weaver/src/org/aspectj/weaver/patterns/PerCflow.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.DataOutputStream; import java.io.IOException; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Map; import org.aspectj.util.FuzzyBoolean; import org.aspectj.weaver.Advice; import org.aspectj.weaver.AjcMemberMaker; import org.aspectj.weaver.CrosscuttingMembers; import org.aspectj.weaver.ISourceContext; import org.aspectj.weaver.Member; import org.aspectj.weaver.NameMangler; import org.aspectj.weaver.ResolvedMemberImpl; import org.aspectj.weaver.ResolvedType; import org.aspectj.weaver.Shadow; import org.aspectj.weaver.UnresolvedType; import org.aspectj.weaver.VersionedDataInputStream; import org.aspectj.weaver.World; import org.aspectj.weaver.ast.Expr; import org.aspectj.weaver.ast.Test; import org.aspectj.weaver.bcel.BcelAccessForInlineMunger; public class PerCflow extends PerClause { private boolean isBelow; private Pointcut entry; public PerCflow(Pointcut entry, boolean isBelow) { this.entry = entry; this.isBelow = isBelow; } // ----- public Object accept(PatternNodeVisitor visitor, Object data) { return visitor.visit(this,data); } public int couldMatchKinds() { return Shadow.ALL_SHADOW_KINDS_BITS; } public FuzzyBoolean fastMatch(FastMatchInfo type) { return FuzzyBoolean.MAYBE; } protected FuzzyBoolean matchInternal(Shadow shadow) { return FuzzyBoolean.YES; } public void resolveBindings(IScope scope, Bindings bindings) { // assert bindings == null; entry.resolve(scope); } public Pointcut parameterizeWith(Map typeVariableMap) { PerCflow ret = new PerCflow(entry.parameterizeWith(typeVariableMap),isBelow); ret.copyLocationFrom(this); return ret; } protected Test findResidueInternal(Shadow shadow, ExposedState state) { Expr myInstance = Expr.makeCallExpr(AjcMemberMaker.perCflowAspectOfMethod(inAspect), Expr.NONE, inAspect); state.setAspectInstance(myInstance); return Test.makeCall(AjcMemberMaker.perCflowHasAspectMethod(inAspect), Expr.NONE); } public PerClause concretize(ResolvedType inAspect) { PerCflow ret = new PerCflow(entry, isBelow); ret.inAspect = inAspect; if (inAspect.isAbstract()) return ret; Member cflowStackField = new ResolvedMemberImpl( Member.FIELD, inAspect, Modifier.STATIC|Modifier.PUBLIC|Modifier.FINAL, UnresolvedType.forName(NameMangler.CFLOW_STACK_TYPE), NameMangler.PERCFLOW_FIELD_NAME, UnresolvedType.NONE); World world = inAspect.getWorld(); CrosscuttingMembers xcut = inAspect.crosscuttingMembers; Collection previousCflowEntries = xcut.getCflowEntries(); Pointcut concreteEntry = entry.concretize(inAspect, inAspect, 0, null); //IntMap.EMPTY); List innerCflowEntries = new ArrayList(xcut.getCflowEntries()); innerCflowEntries.removeAll(previousCflowEntries); xcut.addConcreteShadowMunger( Advice.makePerCflowEntry(world, concreteEntry, isBelow, cflowStackField, inAspect, innerCflowEntries)); //ATAJ: add a munger to add the aspectOf(..) to the @AJ aspects if (inAspect.isAnnotationStyleAspect() && !inAspect.isAbstract()) { inAspect.crosscuttingMembers.addLateTypeMunger( inAspect.getWorld().makePerClauseAspect(inAspect, getKind()) ); } //ATAJ inline around advice support - don't use a late munger to allow around inling for itself if (inAspect.isAnnotationStyleAspect() && !inAspect.getWorld().isXnoInline()) { inAspect.crosscuttingMembers.addTypeMunger(new BcelAccessForInlineMunger(inAspect)); } return ret; } public void write(DataOutputStream s) throws IOException { PERCFLOW.write(s); entry.write(s); s.writeBoolean(isBelow); writeLocation(s); } public static PerClause readPerClause(VersionedDataInputStream s, ISourceContext context) throws IOException { PerCflow ret = new PerCflow(Pointcut.read(s, context), s.readBoolean()); ret.readLocation(context, s); return ret; } public PerClause.Kind getKind() { return PERCFLOW; } public Pointcut getEntry(){ return entry; } public String toString() { return "percflow(" + inAspect + " on " + entry + ")"; } public String toDeclarationString() { if (isBelow) return "percflowbelow(" + entry + ")"; return "percflow(" + entry + ")"; } public boolean equals(Object other) { if (!(other instanceof PerCflow)) return false; PerCflow pc = (PerCflow)other; return (pc.isBelow && isBelow) && ((pc.inAspect == null) ? (inAspect == null) : pc.inAspect.equals(inAspect)) && ((pc.entry == null) ? (entry == null) : pc.entry.equals(entry)); } public int hashCode() { int result = 17; result = 37*result + (isBelow?0:1); result = 37*result + ((inAspect == null) ? 0 : inAspect.hashCode()); result = 37*result + ((entry == null) ? 0 : entry.hashCode()); return result; } }
161,502
Bug 161502 UnsupportedOperationException thrown: unable to parameterize unresolved type: Pjava/util/List<+Ljava/lang/Object; >;
Generic parameters (like List<? extends T>) in pointcuts throw UnsupportedOperationException. java.lang.UnsupportedOperationException at org.aspectj.weaver.UnresolvedType.parameterize(UnresolvedType.java: 220) at org.aspectj.weaver.patterns.ExactTypePattern.parameterizeWith (ExactTypePattern.java:244) at org.aspectj.weaver.patterns.SignaturePattern.parameterizeWith (SignaturePattern.java:265) at org.aspectj.weaver.patterns.KindedPointcut.parameterizeWith (KindedPointcut.java:381) at org.aspectj.weaver.bcel.BcelAdvice.parameterizeWith (BcelAdvice.java:93) at org.aspectj.weaver.ResolvedType.getDeclaredAdvice (ResolvedType.java:710) at org.aspectj.weaver.ResolvedType.getDeclaredShadowMungers (ResolvedType.java:739) at org.aspectj.weaver.ResolvedType.collectShadowMungers (ResolvedType.java:575) at org.aspectj.weaver.ResolvedType.collectCrosscuttingMembers (ResolvedType.java:504) at org.aspectj.weaver.CrosscuttingMembersSet.addOrReplaceAspect (CrosscuttingMembersSet.java:68) at org.aspectj.weaver.CrosscuttingMembersSet.addOrReplaceAspect (CrosscuttingMembersSet.java:57) at org.aspectj.weaver.bcel.BcelWeaver.prepareForWeave(BcelWeaver.java: 450) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.weave (AjCompilerAdapter.java:299) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.afterCompiling (AjCompilerAdapter.java:192) at org.aspectj.ajdt.internal.compiler.CompilerAdapter.ajc $afterReturning$org_aspectj_ajdt_internal_compiler_CompilerAdapter$2 $f9cc9ca0(CompilerAdapter.aj:70) at org.aspectj.org.eclipse.jdt.internal.compiler.Compiler.compile (Compiler.java:367) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.performCompilation (AjBuildManager.java:887) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.doBuild (AjBuildManager.java:244) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.batchBuild (AjBuildManager.java:163) at org.aspectj.ajde.internal.CompilerAdapter.compile (CompilerAdapter.java:122) at org.aspectj.ajde.internal.AspectJBuildManager$CompilerThread.run (AspectJBuildManager.java:191) UnsupportedOperationException thrown: unable to parameterize unresolved type: Pjava/util/List<+Ljava/lang/Object;>; To reproduce this exception compile the following code snippet. import java.util.ArrayList; import java.util.List; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; public class Main { public List<? extends Element> getElements() { return new ArrayList<Element>(); } class Element {}; @Aspect static abstract class Base<T> { @Around("call(List<? extends T> *.*(..))") public List<? extends T> elementList(ProceedingJoinPoint thisJoinPoint) { try { return (List<? extends T>)thisJoinPoint.proceed(); } catch (Throwable e) { throw new RuntimeException(e); } } } @Aspect static class Concrete extends Base<Element> {} public static void main(String[] args) { new Main().getElements(); } }
resolved fixed
7b40e7e
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2006-10-24T12:42:57Z"
"2006-10-19T01:06:40Z"
weaver/src/org/aspectj/weaver/patterns/PerFromSuper.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.DataOutputStream; import java.io.IOException; import java.util.Map; import org.aspectj.bridge.MessageUtil; import org.aspectj.util.FuzzyBoolean; import org.aspectj.weaver.ISourceContext; import org.aspectj.weaver.ResolvedType; import org.aspectj.weaver.Shadow; import org.aspectj.weaver.VersionedDataInputStream; import org.aspectj.weaver.WeaverMessages; import org.aspectj.weaver.ast.Test; public class PerFromSuper extends PerClause { private PerClause.Kind kind; public PerFromSuper(PerClause.Kind kind) { this.kind = kind; } public Object accept(PatternNodeVisitor visitor, Object data) { return visitor.visit(this,data); } public int couldMatchKinds() { return Shadow.ALL_SHADOW_KINDS_BITS; } public FuzzyBoolean fastMatch(FastMatchInfo type) { throw new RuntimeException("unimplemented"); } protected FuzzyBoolean matchInternal(Shadow shadow) { throw new RuntimeException("unimplemented"); } public void resolveBindings(IScope scope, Bindings bindings) { // this method intentionally left blank } protected Test findResidueInternal(Shadow shadow, ExposedState state) { throw new RuntimeException("unimplemented"); } public PerClause concretize(ResolvedType inAspect) { PerClause p = lookupConcretePerClause(inAspect.getSuperclass()); if (p == null) { inAspect.getWorld().getMessageHandler().handleMessage( MessageUtil.error(WeaverMessages.format(WeaverMessages.MISSING_PER_CLAUSE,inAspect.getSuperclass()), getSourceLocation()) ); return new PerSingleton().concretize(inAspect);// AV: fallback on something else NPE in AJDT } else { if (p.getKind() != kind) { inAspect.getWorld().getMessageHandler().handleMessage( MessageUtil.error(WeaverMessages.format(WeaverMessages.WRONG_PER_CLAUSE,kind,p.getKind()), getSourceLocation()) ); } return p.concretize(inAspect); } } public Pointcut parameterizeWith(Map typeVariableMap) { return this; } public PerClause lookupConcretePerClause(ResolvedType lookupType) { PerClause ret = lookupType.getPerClause(); if (ret == null) return null; if (ret instanceof PerFromSuper) { return lookupConcretePerClause(lookupType.getSuperclass()); } return ret; } public void write(DataOutputStream s) throws IOException { FROMSUPER.write(s); kind.write(s); writeLocation(s); } public static PerClause readPerClause(VersionedDataInputStream s, ISourceContext context) throws IOException { PerFromSuper ret = new PerFromSuper(Kind.read(s)); ret.readLocation(context, s); return ret; } public String toString() { return "perFromSuper(" + kind + ", " + inAspect + ")"; } public String toDeclarationString() { return ""; } public PerClause.Kind getKind() { return kind; } public boolean equals(Object other) { if (!(other instanceof PerFromSuper)) return false; PerFromSuper pc = (PerFromSuper)other; return pc.kind.equals(kind) && ((pc.inAspect == null) ? (inAspect == null) : pc.inAspect.equals(inAspect)); } public int hashCode() { int result = 17; result = 37*result + kind.hashCode(); result = 37*result + ((inAspect == null) ? 0 : inAspect.hashCode()); return result; } }
161,502
Bug 161502 UnsupportedOperationException thrown: unable to parameterize unresolved type: Pjava/util/List<+Ljava/lang/Object; >;
Generic parameters (like List<? extends T>) in pointcuts throw UnsupportedOperationException. java.lang.UnsupportedOperationException at org.aspectj.weaver.UnresolvedType.parameterize(UnresolvedType.java: 220) at org.aspectj.weaver.patterns.ExactTypePattern.parameterizeWith (ExactTypePattern.java:244) at org.aspectj.weaver.patterns.SignaturePattern.parameterizeWith (SignaturePattern.java:265) at org.aspectj.weaver.patterns.KindedPointcut.parameterizeWith (KindedPointcut.java:381) at org.aspectj.weaver.bcel.BcelAdvice.parameterizeWith (BcelAdvice.java:93) at org.aspectj.weaver.ResolvedType.getDeclaredAdvice (ResolvedType.java:710) at org.aspectj.weaver.ResolvedType.getDeclaredShadowMungers (ResolvedType.java:739) at org.aspectj.weaver.ResolvedType.collectShadowMungers (ResolvedType.java:575) at org.aspectj.weaver.ResolvedType.collectCrosscuttingMembers (ResolvedType.java:504) at org.aspectj.weaver.CrosscuttingMembersSet.addOrReplaceAspect (CrosscuttingMembersSet.java:68) at org.aspectj.weaver.CrosscuttingMembersSet.addOrReplaceAspect (CrosscuttingMembersSet.java:57) at org.aspectj.weaver.bcel.BcelWeaver.prepareForWeave(BcelWeaver.java: 450) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.weave (AjCompilerAdapter.java:299) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.afterCompiling (AjCompilerAdapter.java:192) at org.aspectj.ajdt.internal.compiler.CompilerAdapter.ajc $afterReturning$org_aspectj_ajdt_internal_compiler_CompilerAdapter$2 $f9cc9ca0(CompilerAdapter.aj:70) at org.aspectj.org.eclipse.jdt.internal.compiler.Compiler.compile (Compiler.java:367) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.performCompilation (AjBuildManager.java:887) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.doBuild (AjBuildManager.java:244) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.batchBuild (AjBuildManager.java:163) at org.aspectj.ajde.internal.CompilerAdapter.compile (CompilerAdapter.java:122) at org.aspectj.ajde.internal.AspectJBuildManager$CompilerThread.run (AspectJBuildManager.java:191) UnsupportedOperationException thrown: unable to parameterize unresolved type: Pjava/util/List<+Ljava/lang/Object;>; To reproduce this exception compile the following code snippet. import java.util.ArrayList; import java.util.List; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; public class Main { public List<? extends Element> getElements() { return new ArrayList<Element>(); } class Element {}; @Aspect static abstract class Base<T> { @Around("call(List<? extends T> *.*(..))") public List<? extends T> elementList(ProceedingJoinPoint thisJoinPoint) { try { return (List<? extends T>)thisJoinPoint.proceed(); } catch (Throwable e) { throw new RuntimeException(e); } } } @Aspect static class Concrete extends Base<Element> {} public static void main(String[] args) { new Main().getElements(); } }
resolved fixed
7b40e7e
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2006-10-24T12:42:57Z"
"2006-10-19T01:06:40Z"
weaver/src/org/aspectj/weaver/patterns/PerObject.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.DataOutputStream; import java.io.IOException; import java.util.Map; import org.aspectj.util.FuzzyBoolean; import org.aspectj.weaver.Advice; import org.aspectj.weaver.AjcMemberMaker; import org.aspectj.weaver.ISourceContext; import org.aspectj.weaver.PerObjectInterfaceTypeMunger; import org.aspectj.weaver.ResolvedType; import org.aspectj.weaver.ResolvedTypeMunger; import org.aspectj.weaver.Shadow; import org.aspectj.weaver.VersionedDataInputStream; import org.aspectj.weaver.World; import org.aspectj.weaver.ast.Expr; import org.aspectj.weaver.ast.Test; import org.aspectj.weaver.ast.Var; import org.aspectj.weaver.bcel.BcelAccessForInlineMunger; public class PerObject extends PerClause { private boolean isThis; private Pointcut entry; private static final int thisKindSet; private static final int targetKindSet; static { int thisFlags = Shadow.ALL_SHADOW_KINDS_BITS; int targFlags = Shadow.ALL_SHADOW_KINDS_BITS; for (int i = 0; i < Shadow.SHADOW_KINDS.length; i++) { Shadow.Kind kind = Shadow.SHADOW_KINDS[i]; if (kind.neverHasThis()) thisFlags-=kind.bit; if (kind.neverHasTarget()) targFlags-=kind.bit; } thisKindSet = thisFlags; targetKindSet=targFlags; } public PerObject(Pointcut entry, boolean isThis) { this.entry = entry; this.isThis = isThis; } public Object accept(PatternNodeVisitor visitor, Object data) { return visitor.visit(this,data); } public int couldMatchKinds() { return isThis ? thisKindSet : targetKindSet; } // ----- public FuzzyBoolean fastMatch(FastMatchInfo type) { return FuzzyBoolean.MAYBE; } protected FuzzyBoolean matchInternal(Shadow shadow) { //System.err.println("matches " + this + " ? " + shadow + ", " + shadow.hasTarget()); //??? could probably optimize this better by testing could match if (isThis) return FuzzyBoolean.fromBoolean(shadow.hasThis()); else return FuzzyBoolean.fromBoolean(shadow.hasTarget()); } public void resolveBindings(IScope scope, Bindings bindings) { // assert bindings == null; entry.resolve(scope); } public Pointcut parameterizeWith(Map typeVariableMap) { PerObject ret = new PerObject(entry.parameterizeWith(typeVariableMap),isThis); ret.copyLocationFrom(this); return ret; } private Var getVar(Shadow shadow) { return isThis ? shadow.getThisVar() : shadow.getTargetVar(); } protected Test findResidueInternal(Shadow shadow, ExposedState state) { Expr myInstance = Expr.makeCallExpr(AjcMemberMaker.perObjectAspectOfMethod(inAspect), new Expr[] {getVar(shadow)}, inAspect); state.setAspectInstance(myInstance); return Test.makeCall(AjcMemberMaker.perObjectHasAspectMethod(inAspect), new Expr[] { getVar(shadow) }); } public PerClause concretize(ResolvedType inAspect) { PerObject ret = new PerObject(entry, isThis); ret.inAspect = inAspect; if (inAspect.isAbstract()) return ret; World world = inAspect.getWorld(); Pointcut concreteEntry = entry.concretize(inAspect, inAspect, 0, null); //concreteEntry = new AndPointcut(this, concreteEntry); //concreteEntry.state = Pointcut.CONCRETE; inAspect.crosscuttingMembers.addConcreteShadowMunger( Advice.makePerObjectEntry(world, concreteEntry, isThis, inAspect)); // FIXME AV - don't use lateMunger here due to test "inheritance, around advice and abstract pointcuts" // see #75442 thread. Issue with weaving order. ResolvedTypeMunger munger = new PerObjectInterfaceTypeMunger(inAspect, concreteEntry); inAspect.crosscuttingMembers.addLateTypeMunger(world.concreteTypeMunger(munger, inAspect)); //ATAJ: add a munger to add the aspectOf(..) to the @AJ aspects if (inAspect.isAnnotationStyleAspect() && !inAspect.isAbstract()) { inAspect.crosscuttingMembers.addLateTypeMunger( inAspect.getWorld().makePerClauseAspect(inAspect, getKind()) ); } //ATAJ inline around advice support - don't use a late munger to allow around inling for itself if (inAspect.isAnnotationStyleAspect() && !inAspect.getWorld().isXnoInline()) { inAspect.crosscuttingMembers.addTypeMunger(new BcelAccessForInlineMunger(inAspect)); } return ret; } public void write(DataOutputStream s) throws IOException { PEROBJECT.write(s); entry.write(s); s.writeBoolean(isThis); writeLocation(s); } public static PerClause readPerClause(VersionedDataInputStream s, ISourceContext context) throws IOException { PerClause ret = new PerObject(Pointcut.read(s, context), s.readBoolean()); ret.readLocation(context, s); return ret; } public PerClause.Kind getKind() { return PEROBJECT; } public boolean isThis() { return isThis; } public String toString() { return "per" + (isThis ? "this" : "target") + "(" + entry + ")"; } public String toDeclarationString() { return toString(); } public Pointcut getEntry() { return entry; } public boolean equals(Object other) { if (!(other instanceof PerObject)) return false; PerObject pc = (PerObject)other; return (pc.isThis && isThis) && ((pc.inAspect == null) ? (inAspect == null) : pc.inAspect.equals(inAspect)) && ((pc.entry == null) ? (entry == null) : pc.entry.equals(entry)); } public int hashCode() { int result = 17; result = 37*result + (isThis?0:1); result = 37*result + ((inAspect == null) ? 0 : inAspect.hashCode()); result = 37*result + ((entry == null) ? 0 : entry.hashCode()); return result; } }
161,502
Bug 161502 UnsupportedOperationException thrown: unable to parameterize unresolved type: Pjava/util/List<+Ljava/lang/Object; >;
Generic parameters (like List<? extends T>) in pointcuts throw UnsupportedOperationException. java.lang.UnsupportedOperationException at org.aspectj.weaver.UnresolvedType.parameterize(UnresolvedType.java: 220) at org.aspectj.weaver.patterns.ExactTypePattern.parameterizeWith (ExactTypePattern.java:244) at org.aspectj.weaver.patterns.SignaturePattern.parameterizeWith (SignaturePattern.java:265) at org.aspectj.weaver.patterns.KindedPointcut.parameterizeWith (KindedPointcut.java:381) at org.aspectj.weaver.bcel.BcelAdvice.parameterizeWith (BcelAdvice.java:93) at org.aspectj.weaver.ResolvedType.getDeclaredAdvice (ResolvedType.java:710) at org.aspectj.weaver.ResolvedType.getDeclaredShadowMungers (ResolvedType.java:739) at org.aspectj.weaver.ResolvedType.collectShadowMungers (ResolvedType.java:575) at org.aspectj.weaver.ResolvedType.collectCrosscuttingMembers (ResolvedType.java:504) at org.aspectj.weaver.CrosscuttingMembersSet.addOrReplaceAspect (CrosscuttingMembersSet.java:68) at org.aspectj.weaver.CrosscuttingMembersSet.addOrReplaceAspect (CrosscuttingMembersSet.java:57) at org.aspectj.weaver.bcel.BcelWeaver.prepareForWeave(BcelWeaver.java: 450) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.weave (AjCompilerAdapter.java:299) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.afterCompiling (AjCompilerAdapter.java:192) at org.aspectj.ajdt.internal.compiler.CompilerAdapter.ajc $afterReturning$org_aspectj_ajdt_internal_compiler_CompilerAdapter$2 $f9cc9ca0(CompilerAdapter.aj:70) at org.aspectj.org.eclipse.jdt.internal.compiler.Compiler.compile (Compiler.java:367) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.performCompilation (AjBuildManager.java:887) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.doBuild (AjBuildManager.java:244) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.batchBuild (AjBuildManager.java:163) at org.aspectj.ajde.internal.CompilerAdapter.compile (CompilerAdapter.java:122) at org.aspectj.ajde.internal.AspectJBuildManager$CompilerThread.run (AspectJBuildManager.java:191) UnsupportedOperationException thrown: unable to parameterize unresolved type: Pjava/util/List<+Ljava/lang/Object;>; To reproduce this exception compile the following code snippet. import java.util.ArrayList; import java.util.List; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; public class Main { public List<? extends Element> getElements() { return new ArrayList<Element>(); } class Element {}; @Aspect static abstract class Base<T> { @Around("call(List<? extends T> *.*(..))") public List<? extends T> elementList(ProceedingJoinPoint thisJoinPoint) { try { return (List<? extends T>)thisJoinPoint.proceed(); } catch (Throwable e) { throw new RuntimeException(e); } } } @Aspect static class Concrete extends Base<Element> {} public static void main(String[] args) { new Main().getElements(); } }
resolved fixed
7b40e7e
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2006-10-24T12:42:57Z"
"2006-10-19T01:06:40Z"
weaver/src/org/aspectj/weaver/patterns/PerSingleton.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.DataOutputStream; import java.io.IOException; import java.util.Map; import org.aspectj.util.FuzzyBoolean; import org.aspectj.weaver.AjcMemberMaker; import org.aspectj.weaver.ISourceContext; import org.aspectj.weaver.ResolvedType; import org.aspectj.weaver.Shadow; import org.aspectj.weaver.VersionedDataInputStream; import org.aspectj.weaver.ast.Expr; import org.aspectj.weaver.ast.Literal; import org.aspectj.weaver.ast.Test; import org.aspectj.weaver.bcel.BcelAccessForInlineMunger; public class PerSingleton extends PerClause { public PerSingleton() { } public Object accept(PatternNodeVisitor visitor, Object data) { return visitor.visit(this,data); } public int couldMatchKinds() { return Shadow.ALL_SHADOW_KINDS_BITS; } public FuzzyBoolean fastMatch(FastMatchInfo type) { return FuzzyBoolean.YES; } protected FuzzyBoolean matchInternal(Shadow shadow) { return FuzzyBoolean.YES; } public void resolveBindings(IScope scope, Bindings bindings) { // this method intentionally left blank } public Pointcut parameterizeWith(Map typeVariableMap) { return this; } public Test findResidueInternal(Shadow shadow, ExposedState state) { // TODO: the commented code is for slow Aspects.aspectOf() style - keep or remove // // Expr myInstance = // Expr.makeCallExpr(AjcMemberMaker.perSingletonAspectOfMethod(inAspect), // Expr.NONE, inAspect); // // state.setAspectInstance(myInstance); // // // we have no test // // a NoAspectBoundException will be thrown if we need an instance of this // // aspect before we are bound // return Literal.TRUE; // if (!Ajc5MemberMaker.isSlowAspect(inAspect)) { Expr myInstance = Expr.makeCallExpr(AjcMemberMaker.perSingletonAspectOfMethod(inAspect), Expr.NONE, inAspect); state.setAspectInstance(myInstance); // we have no test // a NoAspectBoundException will be thrown if we need an instance of this // aspect before we are bound return Literal.TRUE; // } else { // CallExpr callAspectOf =Expr.makeCallExpr( // Ajc5MemberMaker.perSingletonAspectOfMethod(inAspect), // new Expr[]{ // Expr.makeStringConstantExpr(inAspect.getName(), inAspect), // //FieldGet is using ResolvedType and I don't need that here // new FieldGetOn(Member.ajClassField, shadow.getEnclosingType()) // }, // inAspect // ); // Expr castedCallAspectOf = new CastExpr(callAspectOf, inAspect.getName()); // state.setAspectInstance(castedCallAspectOf); // return Literal.TRUE; // } } public PerClause concretize(ResolvedType inAspect) { PerSingleton ret = new PerSingleton(); ret.copyLocationFrom(this); ret.inAspect = inAspect; //ATAJ: add a munger to add the aspectOf(..) to the @AJ aspects if (inAspect.isAnnotationStyleAspect() && !inAspect.isAbstract()) { //TODO will those change be ok if we add a serializable aspect ? // dig: "can't be Serializable/Cloneable unless -XserializableAspects" if (getKind()==SINGLETON) { // pr149560 inAspect.crosscuttingMembers.addTypeMunger( inAspect.getWorld().makePerClauseAspect(inAspect, getKind()) ); } else { inAspect.crosscuttingMembers.addLateTypeMunger( inAspect.getWorld().makePerClauseAspect(inAspect, getKind()) ); } } //ATAJ inline around advice support if (inAspect.isAnnotationStyleAspect() && !inAspect.getWorld().isXnoInline()) { inAspect.crosscuttingMembers.addTypeMunger(new BcelAccessForInlineMunger(inAspect)); } return ret; } public void write(DataOutputStream s) throws IOException { SINGLETON.write(s); writeLocation(s); } public static PerClause readPerClause(VersionedDataInputStream s, ISourceContext context) throws IOException { PerSingleton ret = new PerSingleton(); ret.readLocation(context, s); return ret; } public PerClause.Kind getKind() { return SINGLETON; } public String toString() { return "persingleton(" + inAspect + ")"; } public String toDeclarationString() { return ""; } public boolean equals(Object other) { if (!(other instanceof PerSingleton)) return false; PerSingleton pc = (PerSingleton)other; return ((pc.inAspect == null) ? (inAspect == null) : pc.inAspect.equals(inAspect)); } public int hashCode() { int result = 17; result = 37*result + ((inAspect == null) ? 0 : inAspect.hashCode()); return result; } }
161,502
Bug 161502 UnsupportedOperationException thrown: unable to parameterize unresolved type: Pjava/util/List<+Ljava/lang/Object; >;
Generic parameters (like List<? extends T>) in pointcuts throw UnsupportedOperationException. java.lang.UnsupportedOperationException at org.aspectj.weaver.UnresolvedType.parameterize(UnresolvedType.java: 220) at org.aspectj.weaver.patterns.ExactTypePattern.parameterizeWith (ExactTypePattern.java:244) at org.aspectj.weaver.patterns.SignaturePattern.parameterizeWith (SignaturePattern.java:265) at org.aspectj.weaver.patterns.KindedPointcut.parameterizeWith (KindedPointcut.java:381) at org.aspectj.weaver.bcel.BcelAdvice.parameterizeWith (BcelAdvice.java:93) at org.aspectj.weaver.ResolvedType.getDeclaredAdvice (ResolvedType.java:710) at org.aspectj.weaver.ResolvedType.getDeclaredShadowMungers (ResolvedType.java:739) at org.aspectj.weaver.ResolvedType.collectShadowMungers (ResolvedType.java:575) at org.aspectj.weaver.ResolvedType.collectCrosscuttingMembers (ResolvedType.java:504) at org.aspectj.weaver.CrosscuttingMembersSet.addOrReplaceAspect (CrosscuttingMembersSet.java:68) at org.aspectj.weaver.CrosscuttingMembersSet.addOrReplaceAspect (CrosscuttingMembersSet.java:57) at org.aspectj.weaver.bcel.BcelWeaver.prepareForWeave(BcelWeaver.java: 450) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.weave (AjCompilerAdapter.java:299) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.afterCompiling (AjCompilerAdapter.java:192) at org.aspectj.ajdt.internal.compiler.CompilerAdapter.ajc $afterReturning$org_aspectj_ajdt_internal_compiler_CompilerAdapter$2 $f9cc9ca0(CompilerAdapter.aj:70) at org.aspectj.org.eclipse.jdt.internal.compiler.Compiler.compile (Compiler.java:367) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.performCompilation (AjBuildManager.java:887) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.doBuild (AjBuildManager.java:244) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.batchBuild (AjBuildManager.java:163) at org.aspectj.ajde.internal.CompilerAdapter.compile (CompilerAdapter.java:122) at org.aspectj.ajde.internal.AspectJBuildManager$CompilerThread.run (AspectJBuildManager.java:191) UnsupportedOperationException thrown: unable to parameterize unresolved type: Pjava/util/List<+Ljava/lang/Object;>; To reproduce this exception compile the following code snippet. import java.util.ArrayList; import java.util.List; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; public class Main { public List<? extends Element> getElements() { return new ArrayList<Element>(); } class Element {}; @Aspect static abstract class Base<T> { @Around("call(List<? extends T> *.*(..))") public List<? extends T> elementList(ProceedingJoinPoint thisJoinPoint) { try { return (List<? extends T>)thisJoinPoint.proceed(); } catch (Throwable e) { throw new RuntimeException(e); } } } @Aspect static class Concrete extends Base<Element> {} public static void main(String[] args) { new Main().getElements(); } }
resolved fixed
7b40e7e
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2006-10-24T12:42:57Z"
"2006-10-19T01:06:40Z"
weaver/src/org/aspectj/weaver/patterns/PerTypeWithin.java
/* ******************************************************************* * Copyright (c) 2005 IBM * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Eclipse Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Andy Clement initial implementation * ******************************************************************/ package org.aspectj.weaver.patterns; import java.io.DataOutputStream; import java.io.IOException; import java.util.Map; import org.aspectj.bridge.IMessage; import org.aspectj.bridge.ISourceLocation; import org.aspectj.bridge.Message; import org.aspectj.util.FuzzyBoolean; import org.aspectj.weaver.Advice; import org.aspectj.weaver.AjcMemberMaker; import org.aspectj.weaver.ISourceContext; import org.aspectj.weaver.Member; import org.aspectj.weaver.PerTypeWithinTargetTypeMunger; import org.aspectj.weaver.ResolvedType; import org.aspectj.weaver.ResolvedTypeMunger; import org.aspectj.weaver.Shadow; import org.aspectj.weaver.VersionedDataInputStream; import org.aspectj.weaver.World; import org.aspectj.weaver.ast.Expr; import org.aspectj.weaver.ast.Literal; import org.aspectj.weaver.ast.Test; import org.aspectj.weaver.bcel.BcelAccessForInlineMunger; // PTWIMPL Represents a parsed pertypewithin() public class PerTypeWithin extends PerClause { private TypePattern typePattern; // Any shadow could be considered within a pertypewithin() type pattern private static final int kindSet = Shadow.ALL_SHADOW_KINDS_BITS; public TypePattern getTypePattern() { return typePattern; } public PerTypeWithin(TypePattern p) { this.typePattern = p; } public Object accept(PatternNodeVisitor visitor, Object data) { return visitor.visit(this,data); } public int couldMatchKinds() { return kindSet; } public Pointcut parameterizeWith(Map typeVariableMap) { PerTypeWithin ret = new PerTypeWithin(typePattern.parameterizeWith(typeVariableMap)); ret.copyLocationFrom(this); return ret; } // ----- public FuzzyBoolean fastMatch(FastMatchInfo info) { if (typePattern.annotationPattern instanceof AnyAnnotationTypePattern) { return isWithinType(info.getType()); } return FuzzyBoolean.MAYBE; } protected FuzzyBoolean matchInternal(Shadow shadow) { ResolvedType enclosingType = shadow.getIWorld().resolve(shadow.getEnclosingType(),true); if (enclosingType.isMissing()) { //PTWIMPL ?? Add a proper message IMessage msg = new Message( "Cant find type pertypewithin matching...", shadow.getSourceLocation(),true,new ISourceLocation[]{getSourceLocation()}); shadow.getIWorld().getMessageHandler().handleMessage(msg); } // See pr106554 - we can't put advice calls in an interface when the advice is defined // in a pertypewithin aspect - the JPs only exist in the static initializer and can't // call the localAspectOf() method. if (enclosingType.isInterface()) return FuzzyBoolean.NO; typePattern.resolve(shadow.getIWorld()); return isWithinType(enclosingType); } public void resolveBindings(IScope scope, Bindings bindings) { typePattern = typePattern.resolveBindings(scope, bindings, false, false); } protected Test findResidueInternal(Shadow shadow, ExposedState state) { Member ptwField = AjcMemberMaker.perTypeWithinField(shadow.getEnclosingType(),inAspect); Expr myInstance = Expr.makeCallExpr(AjcMemberMaker.perTypeWithinLocalAspectOf(shadow.getEnclosingType(),inAspect/*shadow.getEnclosingType()*/), Expr.NONE,inAspect); state.setAspectInstance(myInstance); // this worked at one point //Expr myInstance = Expr.makeFieldGet(ptwField,shadow.getEnclosingType().resolve(shadow.getIWorld()));//inAspect); //state.setAspectInstance(myInstance); // return Test.makeFieldGetCall(ptwField,null,Expr.NONE); // cflowField, cflowCounterIsValidMethod, Expr.NONE // This is what is in the perObject variant of this ... // Expr myInstance = // Expr.makeCallExpr(AjcMemberMaker.perTypeWithinAspectOfMethod(inAspect), // new Expr[] {getVar(shadow)}, inAspect); // state.setAspectInstance(myInstance); // return Test.makeCall(AjcMemberMaker.perTypeWithinHasAspectMethod(inAspect), // new Expr[] { getVar(shadow) }); // return match(shadow).alwaysTrue()?Literal.TRUE:Literal.FALSE; } public PerClause concretize(ResolvedType inAspect) { PerTypeWithin ret = new PerTypeWithin(typePattern); ret.copyLocationFrom(this); ret.inAspect = inAspect; if (inAspect.isAbstract()) return ret; World world = inAspect.getWorld(); SignaturePattern sigpat = new SignaturePattern( Member.STATIC_INITIALIZATION, ModifiersPattern.ANY, TypePattern.ANY, TypePattern.ANY,//typePattern, NamePattern.ANY, TypePatternList.ANY, ThrowsPattern.ANY, AnnotationTypePattern.ANY ); Pointcut staticInitStar = new KindedPointcut(Shadow.StaticInitialization,sigpat); Pointcut withinTp= new WithinPointcut(typePattern); Pointcut andPcut = new AndPointcut(staticInitStar,withinTp); // We want the pointcut to be 'staticinitialization(*) && within(<typepattern>' - // we *cannot* shortcut this to staticinitialization(<typepattern>) because it // doesnt mean the same thing. // This munger will initialize the aspect instance field in the matched type inAspect.crosscuttingMembers.addConcreteShadowMunger(Advice.makePerTypeWithinEntry(world, andPcut, inAspect)); ResolvedTypeMunger munger = new PerTypeWithinTargetTypeMunger(inAspect, ret); inAspect.crosscuttingMembers.addTypeMunger(world.concreteTypeMunger(munger, inAspect)); //ATAJ: add a munger to add the aspectOf(..) to the @AJ aspects if (inAspect.isAnnotationStyleAspect() && !inAspect.isAbstract()) { inAspect.crosscuttingMembers.addLateTypeMunger( inAspect.getWorld().makePerClauseAspect(inAspect, getKind()) ); } //ATAJ inline around advice support - don't use a late munger to allow around inling for itself if (inAspect.isAnnotationStyleAspect() && !inAspect.getWorld().isXnoInline()) { inAspect.crosscuttingMembers.addTypeMunger(new BcelAccessForInlineMunger(inAspect)); } return ret; } public void write(DataOutputStream s) throws IOException { PERTYPEWITHIN.write(s); typePattern.write(s); writeLocation(s); } public static PerClause readPerClause(VersionedDataInputStream s, ISourceContext context) throws IOException { PerClause ret = new PerTypeWithin(TypePattern.read(s, context)); ret.readLocation(context, s); return ret; } public PerClause.Kind getKind() { return PERTYPEWITHIN; } public String toString() { return "pertypewithin("+typePattern+")"; } public String toDeclarationString() { return toString(); } private FuzzyBoolean isWithinType(ResolvedType type) { while (type != null) { if (typePattern.matchesStatically(type)) { return FuzzyBoolean.YES; } type = type.getDeclaringType(); } return FuzzyBoolean.NO; } public boolean equals(Object other) { if (!(other instanceof PerTypeWithin)) return false; PerTypeWithin pc = (PerTypeWithin)other; return ((pc.inAspect == null) ? (inAspect == null) : pc.inAspect.equals(inAspect)) && ((pc.typePattern == null) ? (typePattern == null) : pc.typePattern.equals(typePattern)); } public int hashCode() { int result = 17; result = 37*result + ((inAspect == null) ? 0 : inAspect.hashCode()); result = 37*result + ((typePattern == null) ? 0 : typePattern.hashCode()); return result; } }
161,502
Bug 161502 UnsupportedOperationException thrown: unable to parameterize unresolved type: Pjava/util/List<+Ljava/lang/Object; >;
Generic parameters (like List<? extends T>) in pointcuts throw UnsupportedOperationException. java.lang.UnsupportedOperationException at org.aspectj.weaver.UnresolvedType.parameterize(UnresolvedType.java: 220) at org.aspectj.weaver.patterns.ExactTypePattern.parameterizeWith (ExactTypePattern.java:244) at org.aspectj.weaver.patterns.SignaturePattern.parameterizeWith (SignaturePattern.java:265) at org.aspectj.weaver.patterns.KindedPointcut.parameterizeWith (KindedPointcut.java:381) at org.aspectj.weaver.bcel.BcelAdvice.parameterizeWith (BcelAdvice.java:93) at org.aspectj.weaver.ResolvedType.getDeclaredAdvice (ResolvedType.java:710) at org.aspectj.weaver.ResolvedType.getDeclaredShadowMungers (ResolvedType.java:739) at org.aspectj.weaver.ResolvedType.collectShadowMungers (ResolvedType.java:575) at org.aspectj.weaver.ResolvedType.collectCrosscuttingMembers (ResolvedType.java:504) at org.aspectj.weaver.CrosscuttingMembersSet.addOrReplaceAspect (CrosscuttingMembersSet.java:68) at org.aspectj.weaver.CrosscuttingMembersSet.addOrReplaceAspect (CrosscuttingMembersSet.java:57) at org.aspectj.weaver.bcel.BcelWeaver.prepareForWeave(BcelWeaver.java: 450) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.weave (AjCompilerAdapter.java:299) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.afterCompiling (AjCompilerAdapter.java:192) at org.aspectj.ajdt.internal.compiler.CompilerAdapter.ajc $afterReturning$org_aspectj_ajdt_internal_compiler_CompilerAdapter$2 $f9cc9ca0(CompilerAdapter.aj:70) at org.aspectj.org.eclipse.jdt.internal.compiler.Compiler.compile (Compiler.java:367) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.performCompilation (AjBuildManager.java:887) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.doBuild (AjBuildManager.java:244) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.batchBuild (AjBuildManager.java:163) at org.aspectj.ajde.internal.CompilerAdapter.compile (CompilerAdapter.java:122) at org.aspectj.ajde.internal.AspectJBuildManager$CompilerThread.run (AspectJBuildManager.java:191) UnsupportedOperationException thrown: unable to parameterize unresolved type: Pjava/util/List<+Ljava/lang/Object;>; To reproduce this exception compile the following code snippet. import java.util.ArrayList; import java.util.List; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; public class Main { public List<? extends Element> getElements() { return new ArrayList<Element>(); } class Element {}; @Aspect static abstract class Base<T> { @Around("call(List<? extends T> *.*(..))") public List<? extends T> elementList(ProceedingJoinPoint thisJoinPoint) { try { return (List<? extends T>)thisJoinPoint.proceed(); } catch (Throwable e) { throw new RuntimeException(e); } } } @Aspect static class Concrete extends Base<Element> {} public static void main(String[] args) { new Main().getElements(); } }
resolved fixed
7b40e7e
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2006-10-24T12:42:57Z"
"2006-10-19T01:06:40Z"
weaver/src/org/aspectj/weaver/patterns/Pointcut.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.DataOutputStream; import java.io.IOException; import java.util.Map; import org.aspectj.util.FuzzyBoolean; import org.aspectj.util.TypeSafeEnum; import org.aspectj.weaver.Advice; import org.aspectj.weaver.AdviceKind; import org.aspectj.weaver.BCException; import org.aspectj.weaver.Checker; import org.aspectj.weaver.ISourceContext; import org.aspectj.weaver.IntMap; import org.aspectj.weaver.ResolvedType; import org.aspectj.weaver.Shadow; import org.aspectj.weaver.ShadowMunger; import org.aspectj.weaver.VersionedDataInputStream; import org.aspectj.weaver.World; import org.aspectj.weaver.ast.Literal; import org.aspectj.weaver.ast.Test; import org.aspectj.weaver.bcel.PoliceExtensionUse; /** * The lifecycle of Pointcuts is modeled by Pointcut.State. It has three things: * * <p>Creation -- SYMBOLIC -- then resolve(IScope) -- RESOLVED -- concretize(...) -- CONCRETE * * @author Erik Hilsdale * @author Jim Hugunin * * A day in the life of a pointcut.... - AMC. * ========================================== * * Pointcuts are created by the PatternParser, which is called by ajdt to * parse a pointcut from the PseudoTokens AST node (which in turn are part * of a PointcutDesignator AST node). * * Pointcuts are resolved by ajdt when an AdviceDeclaration or a * PointcutDeclaration has its statements resolved. This happens as * part of completeTypeBindings in the AjLookupEnvironment which is * called after the diet parse phase of the compiler. Named pointcuts, * and references to named pointcuts are instances of ReferencePointcut. * * At the end of the compilation process, the pointcuts are serialized * (write method) into attributes in the class file. * * When the weaver loads the class files, it unpacks the attributes * and deserializes the pointcuts (read). All aspects are added to the * world, by calling addOrReplaceAspect on * the crosscutting members set of the world. When aspects are added or * replaced, the crosscutting members in the aspect are extracted as * ShadowMungers (each holding a pointcut). The ShadowMungers are * concretized, which concretizes the pointcuts. At this stage * ReferencePointcuts are replaced by their declared content. * * During weaving, the weaver processes type by type. It first culls * potentially matching ShadowMungers by calling the fastMatch method * on their pointcuts. Only those that might match make it through to * the next phase. At the next phase, all of the shadows within the * type are created and passed to the pointcut for matching (match). * * When the actual munging happens, matched pointcuts are asked for * their residue (findResidue) - the runtime test if any. Because of * negation, findResidue may be called on pointcuts that could never * match the shadow. * */ public abstract class Pointcut extends PatternNode { public static final class State extends TypeSafeEnum { public State(String name, int key) { super(name, key); } } /** * ATAJ the name of the formal for which we don't want any warning when unbound since * we consider them as implicitly bound. f.e. JoinPoint for @AJ advices */ public String[] m_ignoreUnboundBindingForNames = new String[0]; public static final State SYMBOLIC = new State("symbolic", 0); public static final State RESOLVED = new State("resolved", 1); public static final State CONCRETE = new State("concrete", 2); protected byte pointcutKind; public State state; protected int lastMatchedShadowId; private FuzzyBoolean lastMatchedShadowResult; private String[] typeVariablesInScope = new String[0]; protected boolean hasBeenParameterized = false; /** * Constructor for Pattern. */ public Pointcut() { super(); this.state = SYMBOLIC; } /** * Could I match any shadows in the code defined within this type? */ public abstract FuzzyBoolean fastMatch(FastMatchInfo info); /** * The set of ShadowKinds that this Pointcut could possibly match - * an int whose bits are set according to the Kinds specified in Shadow.java */ public abstract int couldMatchKinds(); public String[] getTypeVariablesInScope() { return typeVariablesInScope; } public void setTypeVariablesInScope(String[] typeVars) { this.typeVariablesInScope = typeVars; } /** * Do I really match this shadow? * XXX implementors need to handle state */ public final FuzzyBoolean match(Shadow shadow) { if (shadow.shadowId == lastMatchedShadowId) return lastMatchedShadowResult; FuzzyBoolean ret; // this next test will prevent a lot of un-needed matching going on.... if (shadow.getKind().isSet(couldMatchKinds())) { ret = matchInternal(shadow); } else { ret = FuzzyBoolean.NO; } lastMatchedShadowId = shadow.shadowId; lastMatchedShadowResult = ret; return ret; } protected abstract FuzzyBoolean matchInternal(Shadow shadow); public static final byte KINDED = 1; public static final byte WITHIN = 2; public static final byte THIS_OR_TARGET = 3; public static final byte ARGS = 4; public static final byte AND = 5; public static final byte OR = 6; public static final byte NOT = 7; public static final byte REFERENCE = 8; public static final byte IF = 9; public static final byte CFLOW = 10; public static final byte WITHINCODE = 12; public static final byte HANDLER = 13; public static final byte IF_TRUE = 14; public static final byte IF_FALSE = 15; public static final byte ANNOTATION = 16; public static final byte ATWITHIN = 17; public static final byte ATWITHINCODE = 18; public static final byte ATTHIS_OR_TARGET = 19; public static final byte NONE = 20; // DO NOT CHANGE OR REORDER THIS SEQUENCE, THIS VALUE CAN BE PUT OUT BY ASPECTJ1.2.1 public static final byte ATARGS = 21; public static final byte USER_EXTENSION = 22; public byte getPointcutKind() { return pointcutKind; } // internal, only called from resolve protected abstract void resolveBindings(IScope scope, Bindings bindings); /** * Returns this pointcut mutated */ public final Pointcut resolve(IScope scope) { assertState(SYMBOLIC); Bindings bindingTable = new Bindings(scope.getFormalCount()); IScope bindingResolutionScope = scope; if (typeVariablesInScope.length > 0) { bindingResolutionScope = new ScopeWithTypeVariables(typeVariablesInScope,scope); } this.resolveBindings(bindingResolutionScope, bindingTable); bindingTable.checkAllBound(bindingResolutionScope); this.state = RESOLVED; return this; } /** * Returns a new pointcut * Only used by test cases */ public final Pointcut concretize(ResolvedType inAspect, ResolvedType declaringType, int arity) { Pointcut ret = concretize(inAspect, declaringType, IntMap.idMap(arity)); // copy the unbound ignore list ret.m_ignoreUnboundBindingForNames = m_ignoreUnboundBindingForNames; return ret; } //XXX this is the signature we're moving to public final Pointcut concretize(ResolvedType inAspect, ResolvedType declaringType, int arity, ShadowMunger advice) { //if (state == CONCRETE) return this; //??? IntMap map = IntMap.idMap(arity); map.setEnclosingAdvice(advice); map.setConcreteAspect(inAspect); return concretize(inAspect, declaringType, map); } public boolean isDeclare(ShadowMunger munger) { if (munger == null) return false; // ??? Is it actually an error if we get a null munger into this method. if (munger instanceof Checker) return true; if (((Advice)munger).getKind().equals(AdviceKind.Softener)) return true; return false; } public final Pointcut concretize(ResolvedType inAspect, ResolvedType declaringType, IntMap bindings) { //!!! add this test -- assertState(RESOLVED); Pointcut ret = this.concretize1(inAspect, declaringType, bindings); if (shouldCopyLocationForConcretize()) ret.copyLocationFrom(this); ret.state = CONCRETE; // copy the unbound ignore list ret.m_ignoreUnboundBindingForNames = m_ignoreUnboundBindingForNames; return ret; } protected boolean shouldCopyLocationForConcretize() { return true; } /** * Resolves and removes ReferencePointcuts, replacing with basic ones * * @param inAspect the aspect to resolve relative to * @param bindings a Map from formal index in the current lexical context * -> formal index in the concrete advice that will run * * This must always return a new Pointcut object (even if the concretized * Pointcut is identical to the resolved one). That behavior is * assumed in many places. * XXX fix implementors to handle state */ protected abstract Pointcut concretize1(ResolvedType inAspect, ResolvedType declaringType, IntMap bindings); //XXX implementors need to handle state /** * This can be called from NotPointcut even for Pointcuts that * don't match the shadow */ public final Test findResidue(Shadow shadow, ExposedState state) { // if (shadow.shadowId == lastMatchedShadowId) return lastMatchedShadowResidue; Test ret = findResidueInternal(shadow,state); // lastMatchedShadowResidue = ret; lastMatchedShadowId = shadow.shadowId; return ret; } protected abstract Test findResidueInternal(Shadow shadow,ExposedState state); //XXX we're not sure whether or not this is needed //XXX currently it's unused we're keeping it around as a stub public void postRead(ResolvedType enclosingType) {} public static Pointcut read(VersionedDataInputStream s, ISourceContext context) throws IOException { byte kind = s.readByte(); Pointcut ret; switch(kind) { case KINDED: ret = KindedPointcut.read(s, context); break; case WITHIN: ret = WithinPointcut.read(s, context); break; case THIS_OR_TARGET: ret = ThisOrTargetPointcut.read(s, context); break; case ARGS: ret = ArgsPointcut.read(s, context); break; case AND: ret = AndPointcut.read(s, context); break; case OR: ret = OrPointcut.read(s, context); break; case NOT: ret = NotPointcut.read(s, context); break; case REFERENCE: ret = ReferencePointcut.read(s, context); break; case IF: ret = IfPointcut.read(s, context); break; case CFLOW: ret = CflowPointcut.read(s, context); break; case WITHINCODE: ret = WithincodePointcut.read(s, context); break; case HANDLER: ret = HandlerPointcut.read(s, context); break; case IF_TRUE: ret = IfPointcut.makeIfTruePointcut(RESOLVED); break; case IF_FALSE: ret = IfPointcut.makeIfFalsePointcut(RESOLVED); break; case ANNOTATION: ret = AnnotationPointcut.read(s, context); break; case ATWITHIN: ret = WithinAnnotationPointcut.read(s, context); break; case ATWITHINCODE: ret = WithinCodeAnnotationPointcut.read(s, context); break; case ATTHIS_OR_TARGET: ret = ThisOrTargetAnnotationPointcut.read(s, context); break; case ATARGS: ret = ArgsAnnotationPointcut.read(s,context); break; case NONE: ret = makeMatchesNothing(RESOLVED); break; default: throw new BCException("unknown kind: " + kind); } ret.state = RESOLVED; ret.pointcutKind = kind; return ret; } public void check(ISourceContext ctx,World world) { // this is a quick visitor... PoliceExtensionUse pointcutPolice = new PoliceExtensionUse(world,this); this.accept(pointcutPolice, null); if (pointcutPolice.synchronizationDesignatorEncountered()) world.setSynchronizationPointcutsInUse(); } //public void prepare(Shadow shadow) {} // ---- test method public static Pointcut fromString(String str) { PatternParser parser = new PatternParser(str); return parser.parsePointcut(); } static class MatchesNothingPointcut extends Pointcut { protected Test findResidueInternal(Shadow shadow, ExposedState state) { return Literal.FALSE; // can only get here if an earlier error occurred } public int couldMatchKinds() { return Shadow.NO_SHADOW_KINDS_BITS; } public FuzzyBoolean fastMatch(FastMatchInfo type) { return FuzzyBoolean.NO; } protected FuzzyBoolean matchInternal(Shadow shadow) { return FuzzyBoolean.NO; } public void resolveBindings(IScope scope, Bindings bindings) { } public void postRead(ResolvedType enclosingType) { } public Pointcut concretize1( ResolvedType inAspect, ResolvedType declaringType, IntMap bindings) { return makeMatchesNothing(state); } public void write(DataOutputStream s) throws IOException { s.writeByte(NONE); } public String toString() { return ""; } public Object accept(PatternNodeVisitor visitor, Object data) { return visitor.visit(this, data); } public Pointcut parameterizeWith(Map typeVariableMap) { return this; } } //public static Pointcut MatchesNothing = new MatchesNothingPointcut(); //??? there could possibly be some good optimizations to be done at this point public static Pointcut makeMatchesNothing(State state) { Pointcut ret = new MatchesNothingPointcut(); ret.state = state; return ret; } public void assertState(State state) { if (this.state != state) { throw new BCException("expected state: " + state + " got: " + this.state); } } public abstract Pointcut parameterizeWith(Map typeVariableMap); }
161,502
Bug 161502 UnsupportedOperationException thrown: unable to parameterize unresolved type: Pjava/util/List<+Ljava/lang/Object; >;
Generic parameters (like List<? extends T>) in pointcuts throw UnsupportedOperationException. java.lang.UnsupportedOperationException at org.aspectj.weaver.UnresolvedType.parameterize(UnresolvedType.java: 220) at org.aspectj.weaver.patterns.ExactTypePattern.parameterizeWith (ExactTypePattern.java:244) at org.aspectj.weaver.patterns.SignaturePattern.parameterizeWith (SignaturePattern.java:265) at org.aspectj.weaver.patterns.KindedPointcut.parameterizeWith (KindedPointcut.java:381) at org.aspectj.weaver.bcel.BcelAdvice.parameterizeWith (BcelAdvice.java:93) at org.aspectj.weaver.ResolvedType.getDeclaredAdvice (ResolvedType.java:710) at org.aspectj.weaver.ResolvedType.getDeclaredShadowMungers (ResolvedType.java:739) at org.aspectj.weaver.ResolvedType.collectShadowMungers (ResolvedType.java:575) at org.aspectj.weaver.ResolvedType.collectCrosscuttingMembers (ResolvedType.java:504) at org.aspectj.weaver.CrosscuttingMembersSet.addOrReplaceAspect (CrosscuttingMembersSet.java:68) at org.aspectj.weaver.CrosscuttingMembersSet.addOrReplaceAspect (CrosscuttingMembersSet.java:57) at org.aspectj.weaver.bcel.BcelWeaver.prepareForWeave(BcelWeaver.java: 450) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.weave (AjCompilerAdapter.java:299) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.afterCompiling (AjCompilerAdapter.java:192) at org.aspectj.ajdt.internal.compiler.CompilerAdapter.ajc $afterReturning$org_aspectj_ajdt_internal_compiler_CompilerAdapter$2 $f9cc9ca0(CompilerAdapter.aj:70) at org.aspectj.org.eclipse.jdt.internal.compiler.Compiler.compile (Compiler.java:367) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.performCompilation (AjBuildManager.java:887) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.doBuild (AjBuildManager.java:244) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.batchBuild (AjBuildManager.java:163) at org.aspectj.ajde.internal.CompilerAdapter.compile (CompilerAdapter.java:122) at org.aspectj.ajde.internal.AspectJBuildManager$CompilerThread.run (AspectJBuildManager.java:191) UnsupportedOperationException thrown: unable to parameterize unresolved type: Pjava/util/List<+Ljava/lang/Object;>; To reproduce this exception compile the following code snippet. import java.util.ArrayList; import java.util.List; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; public class Main { public List<? extends Element> getElements() { return new ArrayList<Element>(); } class Element {}; @Aspect static abstract class Base<T> { @Around("call(List<? extends T> *.*(..))") public List<? extends T> elementList(ProceedingJoinPoint thisJoinPoint) { try { return (List<? extends T>)thisJoinPoint.proceed(); } catch (Throwable e) { throw new RuntimeException(e); } } } @Aspect static class Concrete extends Base<Element> {} public static void main(String[] args) { new Main().getElements(); } }
resolved fixed
7b40e7e
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2006-10-24T12:42:57Z"
"2006-10-19T01:06:40Z"
weaver/src/org/aspectj/weaver/patterns/ReferencePointcut.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the 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.DataOutputStream; import java.io.IOException; import java.lang.reflect.Modifier; import java.util.HashMap; import java.util.Map; import org.aspectj.bridge.IMessage; import org.aspectj.bridge.MessageUtil; import org.aspectj.util.FuzzyBoolean; import org.aspectj.weaver.ISourceContext; import org.aspectj.weaver.IntMap; import org.aspectj.weaver.ResolvedPointcutDefinition; import org.aspectj.weaver.ResolvedType; import org.aspectj.weaver.Shadow; import org.aspectj.weaver.ShadowMunger; import org.aspectj.weaver.TypeVariable; import org.aspectj.weaver.TypeVariableReference; import org.aspectj.weaver.UnresolvedType; import org.aspectj.weaver.VersionedDataInputStream; import org.aspectj.weaver.WeaverMessages; import org.aspectj.weaver.ast.Test; /** */ //XXX needs check that arguments contains no WildTypePatterns public class ReferencePointcut extends Pointcut { public UnresolvedType onType; public TypePattern onTypeSymbolic; public String name; public TypePatternList arguments; /** * if this is non-null then when the pointcut is concretized the result will be parameterized too. */ private Map typeVariableMap; //public ResolvedPointcut binding; public ReferencePointcut(TypePattern onTypeSymbolic, String name, TypePatternList arguments) { this.onTypeSymbolic = onTypeSymbolic; this.name = name; this.arguments = arguments; this.pointcutKind = REFERENCE; } public ReferencePointcut(UnresolvedType onType, String name, TypePatternList arguments) { this.onType = onType; this.name = name; this.arguments = arguments; this.pointcutKind = REFERENCE; } public int couldMatchKinds() { return Shadow.ALL_SHADOW_KINDS_BITS; } //??? do either of these match methods make any sense??? public FuzzyBoolean fastMatch(FastMatchInfo type) { return FuzzyBoolean.MAYBE; } /** * Do I really match this shadow? */ protected FuzzyBoolean matchInternal(Shadow shadow) { return FuzzyBoolean.NO; } public String toString() { StringBuffer buf = new StringBuffer(); if (onType != null) { buf.append(onType); buf.append("."); // for (int i=0, len=fromType.length; i < len; i++) { // buf.append(fromType[i]); // buf.append("."); // } } buf.append(name); buf.append(arguments.toString()); return buf.toString(); } public void write(DataOutputStream s) throws IOException { //XXX ignores onType s.writeByte(Pointcut.REFERENCE); if (onType != null) { s.writeBoolean(true); onType.write(s); } else { s.writeBoolean(false); } s.writeUTF(name); arguments.write(s); writeLocation(s); } public static Pointcut read(VersionedDataInputStream s, ISourceContext context) throws IOException { UnresolvedType onType = null; if (s.readBoolean()) { onType = UnresolvedType.read(s); } ReferencePointcut ret = new ReferencePointcut(onType, s.readUTF(), TypePatternList.read(s, context)); ret.readLocation(context, s); return ret; } public void resolveBindings(IScope scope, Bindings bindings) { if (onTypeSymbolic != null) { onType = onTypeSymbolic.resolveExactType(scope, bindings); // in this case we've already signalled an error if (ResolvedType.isMissing(onType)) return; } ResolvedType searchType; if (onType != null) { searchType = scope.getWorld().resolve(onType); } else { searchType = scope.getEnclosingType(); } if (searchType.isTypeVariableReference()) { searchType = ((TypeVariableReference)searchType).getTypeVariable().getUpperBound().resolve(scope.getWorld()); } arguments.resolveBindings(scope, bindings, true, true); //XXX ensure that arguments has no ..'s in it // check that I refer to a real pointcut declaration and that I match ResolvedPointcutDefinition pointcutDef = searchType.findPointcut(name); // if we're not a static reference, then do a lookup of outers if (pointcutDef == null && onType == null) { while (true) { UnresolvedType declaringType = searchType.getDeclaringType(); if (declaringType == null) break; searchType = declaringType.resolve(scope.getWorld()); pointcutDef = searchType.findPointcut(name); if (pointcutDef != null) { // make this a static reference onType = searchType; break; } } } if (pointcutDef == null) { scope.message(IMessage.ERROR, this, "can't find referenced pointcut " + name); return; } // check visibility if (!pointcutDef.isVisible(scope.getEnclosingType())) { scope.message(IMessage.ERROR, this, "pointcut declaration " + pointcutDef + " is not accessible"); return; } if (Modifier.isAbstract(pointcutDef.getModifiers())) { if (onType != null && !onType.isTypeVariableReference()) { scope.message(IMessage.ERROR, this, "can't make static reference to abstract pointcut"); return; } else if (!searchType.isAbstract()) { scope.message(IMessage.ERROR, this, "can't use abstract pointcut in concrete context"); return; } } ResolvedType[] parameterTypes = scope.getWorld().resolve(pointcutDef.getParameterTypes()); if (parameterTypes.length != arguments.size()) { scope.message(IMessage.ERROR, this, "incompatible number of arguments to pointcut, expected " + parameterTypes.length + " found " + arguments.size()); return; } //if (onType == null) onType = pointcutDef.getDeclaringType(); if (onType != null) { if (onType.isParameterizedType()) { // build a type map mapping type variable names in the generic type to // the type parameters presented typeVariableMap = new HashMap(); ResolvedType underlyingGenericType = ((ResolvedType) onType).getGenericType(); TypeVariable[] tVars = underlyingGenericType.getTypeVariables(); ResolvedType[] typeParams = ((ResolvedType)onType).getResolvedTypeParameters(); for (int i = 0; i < tVars.length; i++) { typeVariableMap.put(tVars[i].getName(),typeParams[i]); } } else if (onType.isGenericType()) { scope.message(MessageUtil.error(WeaverMessages.format(WeaverMessages.CANT_REFERENCE_POINTCUT_IN_RAW_TYPE), getSourceLocation())); } } for (int i=0,len=arguments.size(); i < len; i++) { TypePattern p = arguments.get(i); //we are allowed to bind to pointcuts which use subtypes as this is type safe if (typeVariableMap != null) { p = p.parameterizeWith(typeVariableMap); } if (p == TypePattern.NO) { scope.message(IMessage.ERROR, this, "bad parameter to pointcut reference"); return; } boolean reportProblem = false; if (parameterTypes[i].isTypeVariableReference() && p.getExactType().isTypeVariableReference()) { UnresolvedType One = ((TypeVariableReference)parameterTypes[i]).getTypeVariable().getFirstBound(); UnresolvedType Two = ((TypeVariableReference)p.getExactType()).getTypeVariable().getFirstBound(); reportProblem = !One.resolve(scope.getWorld()).isAssignableFrom(Two.resolve(scope.getWorld())); } else { reportProblem = !p.matchesSubtypes(parameterTypes[i]) && !p.getExactType().equals(UnresolvedType.OBJECT); } if (reportProblem) { scope.message(IMessage.ERROR, p, "incompatible type, expected " + parameterTypes[i].getName() + " found " + p +". Check the type specified in your pointcut"); return; } } } public void postRead(ResolvedType enclosingType) { arguments.postRead(enclosingType); } protected Test findResidueInternal(Shadow shadow, ExposedState state) { throw new RuntimeException("shouldn't happen"); } //??? This is not thread safe, but this class is not designed for multi-threading private boolean concretizing = false; // declaring type is the type that declared the member referencing this pointcut. // If it declares a matching private pointcut, then that pointcut should be used // and not one in a subtype that happens to have the same name. public Pointcut concretize1(ResolvedType searchStart, ResolvedType declaringType, IntMap bindings) { if (concretizing) { //Thread.currentThread().dumpStack(); searchStart.getWorld().getMessageHandler().handleMessage( MessageUtil.error(WeaverMessages.format(WeaverMessages.CIRCULAR_POINTCUT,this), getSourceLocation())); return Pointcut.makeMatchesNothing(Pointcut.CONCRETE); } try { concretizing = true; ResolvedPointcutDefinition pointcutDec; if (onType != null) { searchStart = onType.resolve(searchStart.getWorld()); if (searchStart.isMissing()) { return Pointcut.makeMatchesNothing(Pointcut.CONCRETE); } if (onType.isTypeVariableReference()) { // need to replace on type with the binding for the type variable // in the declaring type if (declaringType.isParameterizedType()) { TypeVariable[] tvs = declaringType.getGenericType().getTypeVariables(); String typeVariableName = ((TypeVariableReference)onType).getTypeVariable().getName(); for (int i = 0; i < tvs.length; i++) { if (tvs[i].getName().equals(typeVariableName)) { ResolvedType realOnType = declaringType.getTypeParameters()[i].resolve(declaringType.getWorld()); onType = realOnType; searchStart = realOnType; break; } } } } } if (declaringType == null) declaringType = searchStart; pointcutDec = declaringType.findPointcut(name); boolean foundMatchingPointcut = (pointcutDec != null && pointcutDec.isPrivate()); if (!foundMatchingPointcut) { pointcutDec = searchStart.findPointcut(name); if (pointcutDec == null) { searchStart.getWorld().getMessageHandler().handleMessage( MessageUtil.error(WeaverMessages.format(WeaverMessages.CANT_FIND_POINTCUT,name,searchStart.getName()), getSourceLocation()) ); return Pointcut.makeMatchesNothing(Pointcut.CONCRETE); } } if (pointcutDec.isAbstract()) { //Thread.currentThread().dumpStack(); ShadowMunger enclosingAdvice = bindings.getEnclosingAdvice(); searchStart.getWorld().showMessage(IMessage.ERROR, WeaverMessages.format(WeaverMessages.ABSTRACT_POINTCUT,pointcutDec), getSourceLocation(), (null == enclosingAdvice) ? null : enclosingAdvice.getSourceLocation()); return Pointcut.makeMatchesNothing(Pointcut.CONCRETE); } //System.err.println("start: " + searchStart); ResolvedType[] parameterTypes = searchStart.getWorld().resolve(pointcutDec.getParameterTypes()); TypePatternList arguments = this.arguments.resolveReferences(bindings); IntMap newBindings = new IntMap(); for (int i=0,len=arguments.size(); i < len; i++) { TypePattern p = arguments.get(i); if (p == TypePattern.NO) continue; // we are allowed to bind to pointcuts which use subtypes as this is type safe // this will be checked in ReferencePointcut.resolveBindings(). Can't check it here // as we don't know about any new parents added via decp. if (p instanceof BindingTypePattern) { newBindings.put(i, ((BindingTypePattern)p).getFormalIndex()); } } if (searchStart.isParameterizedType()) { // build a type map mapping type variable names in the generic type to // the type parameters presented typeVariableMap = new HashMap(); ResolvedType underlyingGenericType = searchStart.getGenericType(); TypeVariable[] tVars = underlyingGenericType.getTypeVariables(); ResolvedType[] typeParams = searchStart.getResolvedTypeParameters(); for (int i = 0; i < tVars.length; i++) { typeVariableMap.put(tVars[i].getName(),typeParams[i]); } } newBindings.copyContext(bindings); newBindings.pushEnclosingDefinition(pointcutDec); try { Pointcut ret = pointcutDec.getPointcut(); if (typeVariableMap != null && !hasBeenParameterized) { ret = ret.parameterizeWith(typeVariableMap); ret.hasBeenParameterized=true; } return ret.concretize(searchStart, declaringType, newBindings); } finally { newBindings.popEnclosingDefinitition(); } } finally { concretizing = false; } } /** * make a version of this pointcut with any refs to typeVariables replaced by their entry in the map. * Tricky thing is, we can't do this at the point in time this method will be called, so we make a * version that will parameterize the pointcut it ultimately resolves to. */ public Pointcut parameterizeWith(Map typeVariableMap) { ReferencePointcut ret = new ReferencePointcut(onType,name,arguments); ret.onTypeSymbolic = onTypeSymbolic; ret.typeVariableMap = typeVariableMap; return ret; } // We want to keep the original source location, not the reference location protected boolean shouldCopyLocationForConcretize() { return false; } public boolean equals(Object other) { if (!(other instanceof ReferencePointcut)) return false; if (this == other) return true; ReferencePointcut o = (ReferencePointcut)other; return o.name.equals(name) && o.arguments.equals(arguments) && ((o.onType == null) ? (onType == null) : o.onType.equals(onType)); } public int hashCode() { int result = 17; result = 37*result + ((onType == null) ? 0 : onType.hashCode()); result = 37*result + arguments.hashCode(); result = 37*result + name.hashCode(); return result; } public Object accept(PatternNodeVisitor visitor, Object data) { return visitor.visit(this, data); } }
161,502
Bug 161502 UnsupportedOperationException thrown: unable to parameterize unresolved type: Pjava/util/List<+Ljava/lang/Object; >;
Generic parameters (like List<? extends T>) in pointcuts throw UnsupportedOperationException. java.lang.UnsupportedOperationException at org.aspectj.weaver.UnresolvedType.parameterize(UnresolvedType.java: 220) at org.aspectj.weaver.patterns.ExactTypePattern.parameterizeWith (ExactTypePattern.java:244) at org.aspectj.weaver.patterns.SignaturePattern.parameterizeWith (SignaturePattern.java:265) at org.aspectj.weaver.patterns.KindedPointcut.parameterizeWith (KindedPointcut.java:381) at org.aspectj.weaver.bcel.BcelAdvice.parameterizeWith (BcelAdvice.java:93) at org.aspectj.weaver.ResolvedType.getDeclaredAdvice (ResolvedType.java:710) at org.aspectj.weaver.ResolvedType.getDeclaredShadowMungers (ResolvedType.java:739) at org.aspectj.weaver.ResolvedType.collectShadowMungers (ResolvedType.java:575) at org.aspectj.weaver.ResolvedType.collectCrosscuttingMembers (ResolvedType.java:504) at org.aspectj.weaver.CrosscuttingMembersSet.addOrReplaceAspect (CrosscuttingMembersSet.java:68) at org.aspectj.weaver.CrosscuttingMembersSet.addOrReplaceAspect (CrosscuttingMembersSet.java:57) at org.aspectj.weaver.bcel.BcelWeaver.prepareForWeave(BcelWeaver.java: 450) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.weave (AjCompilerAdapter.java:299) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.afterCompiling (AjCompilerAdapter.java:192) at org.aspectj.ajdt.internal.compiler.CompilerAdapter.ajc $afterReturning$org_aspectj_ajdt_internal_compiler_CompilerAdapter$2 $f9cc9ca0(CompilerAdapter.aj:70) at org.aspectj.org.eclipse.jdt.internal.compiler.Compiler.compile (Compiler.java:367) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.performCompilation (AjBuildManager.java:887) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.doBuild (AjBuildManager.java:244) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.batchBuild (AjBuildManager.java:163) at org.aspectj.ajde.internal.CompilerAdapter.compile (CompilerAdapter.java:122) at org.aspectj.ajde.internal.AspectJBuildManager$CompilerThread.run (AspectJBuildManager.java:191) UnsupportedOperationException thrown: unable to parameterize unresolved type: Pjava/util/List<+Ljava/lang/Object;>; To reproduce this exception compile the following code snippet. import java.util.ArrayList; import java.util.List; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; public class Main { public List<? extends Element> getElements() { return new ArrayList<Element>(); } class Element {}; @Aspect static abstract class Base<T> { @Around("call(List<? extends T> *.*(..))") public List<? extends T> elementList(ProceedingJoinPoint thisJoinPoint) { try { return (List<? extends T>)thisJoinPoint.proceed(); } catch (Throwable e) { throw new RuntimeException(e); } } } @Aspect static class Concrete extends Base<Element> {} public static void main(String[] args) { new Main().getElements(); } }
resolved fixed
7b40e7e
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2006-10-24T12:42:57Z"
"2006-10-19T01:06:40Z"
weaver/src/org/aspectj/weaver/patterns/SignaturePattern.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the 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.DataOutputStream; import java.io.IOException; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import org.aspectj.bridge.ISourceLocation; import org.aspectj.lang.Signature; import org.aspectj.lang.reflect.FieldSignature; import org.aspectj.lang.reflect.MethodSignature; import org.aspectj.util.FuzzyBoolean; import org.aspectj.weaver.AjAttribute; import org.aspectj.weaver.AjcMemberMaker; import org.aspectj.weaver.AnnotationTargetKind; import org.aspectj.weaver.Constants; import org.aspectj.weaver.ISourceContext; import org.aspectj.weaver.JoinPointSignature; import org.aspectj.weaver.Member; import org.aspectj.weaver.NameMangler; import org.aspectj.weaver.NewFieldTypeMunger; import org.aspectj.weaver.ResolvedMember; import org.aspectj.weaver.ResolvedType; import org.aspectj.weaver.UnresolvedType; import org.aspectj.weaver.VersionedDataInputStream; import org.aspectj.weaver.World; import org.aspectj.weaver.bcel.BcelTypeMunger; public class SignaturePattern extends PatternNode { private Member.Kind kind; private ModifiersPattern modifiers; private TypePattern returnType; private TypePattern declaringType; private NamePattern name; private TypePatternList parameterTypes; private ThrowsPattern throwsPattern; private AnnotationTypePattern annotationPattern; private transient int hashcode = -1; public SignaturePattern(Member.Kind kind, ModifiersPattern modifiers, TypePattern returnType, TypePattern declaringType, NamePattern name, TypePatternList parameterTypes, ThrowsPattern throwsPattern, AnnotationTypePattern annotationPattern) { this.kind = kind; this.modifiers = modifiers; this.returnType = returnType; this.name = name; this.declaringType = declaringType; this.parameterTypes = parameterTypes; this.throwsPattern = throwsPattern; this.annotationPattern = annotationPattern; } public SignaturePattern resolveBindings(IScope scope, Bindings bindings) { if (returnType != null) { returnType = returnType.resolveBindings(scope, bindings, false, false); checkForIncorrectTargetKind(returnType,scope,false); } if (declaringType != null) { declaringType = declaringType.resolveBindings(scope, bindings, false, false); checkForIncorrectTargetKind(declaringType,scope,false); } if (parameterTypes != null) { parameterTypes = parameterTypes.resolveBindings(scope, bindings, false, false); checkForIncorrectTargetKind(parameterTypes,scope,false); } if (throwsPattern != null) { throwsPattern = throwsPattern.resolveBindings(scope, bindings); if (throwsPattern.getForbidden().getTypePatterns().length > 0 || throwsPattern.getRequired().getTypePatterns().length > 0) { checkForIncorrectTargetKind(throwsPattern,scope,false); } } if (annotationPattern != null) { annotationPattern = annotationPattern.resolveBindings(scope,bindings,false); checkForIncorrectTargetKind(annotationPattern,scope,true); } hashcode =-1; return this; } // bug 115252 - adding an xlint warning if the annnotation target type is // wrong. This logic, or similar, may have to be applied elsewhere in the case // of pointcuts which don't go through SignaturePattern.resolveBindings(..) private void checkForIncorrectTargetKind(PatternNode patternNode, IScope scope, boolean targetsOtherThanTypeAllowed) { // return if we're not in java5 mode, if the unmatchedTargetKind Xlint // warning has been turned off, or if the patternNode is * if (!scope.getWorld().isInJava5Mode() || scope.getWorld().getLint().unmatchedTargetKind == null || (patternNode instanceof AnyTypePattern)) { return; } if (patternNode instanceof ExactAnnotationTypePattern) { ResolvedType resolvedType = ((ExactAnnotationTypePattern)patternNode).getAnnotationType().resolve(scope.getWorld()); if (targetsOtherThanTypeAllowed) { AnnotationTargetKind[] targetKinds = resolvedType.getAnnotationTargetKinds(); if (targetKinds == null) return; reportUnmatchedTargetKindMessage(targetKinds,patternNode,scope,true); } else if (!targetsOtherThanTypeAllowed && !resolvedType.canAnnotationTargetType()) { // everything is incorrect since we've already checked whether we have the TYPE target annotation AnnotationTargetKind[] targetKinds = resolvedType.getAnnotationTargetKinds(); if (targetKinds == null) return; reportUnmatchedTargetKindMessage(targetKinds,patternNode,scope,false); } } else { TypePatternVisitor visitor = new TypePatternVisitor(scope,targetsOtherThanTypeAllowed); patternNode.traverse(visitor,null); if (visitor.containedIncorrectTargetKind()) { Set keys = visitor.getIncorrectTargetKinds().keySet(); for (Iterator iter = keys.iterator(); iter.hasNext();) { PatternNode node = (PatternNode)iter.next(); AnnotationTargetKind[] targetKinds = (AnnotationTargetKind[]) visitor.getIncorrectTargetKinds().get(node); reportUnmatchedTargetKindMessage(targetKinds,node,scope,false); } } } } private void reportUnmatchedTargetKindMessage( AnnotationTargetKind[] annotationTargetKinds, PatternNode node, IScope scope, boolean checkMatchesMemberKindName) { StringBuffer targetNames = new StringBuffer("{"); for (int i = 0; i < annotationTargetKinds.length; i++) { AnnotationTargetKind targetKind = annotationTargetKinds[i]; if (checkMatchesMemberKindName && kind.getName().equals(targetKind.getName())) { return; } if (i < (annotationTargetKinds.length - 1)) { targetNames.append("ElementType." + targetKind.getName() + ","); } else { targetNames.append("ElementType." + targetKind.getName() + "}"); } } scope.getWorld().getLint().unmatchedTargetKind.signal(new String[] {node.toString(),targetNames.toString()}, getSourceLocation(), new ISourceLocation[0]); } /** * Class which visits the nodes in the TypePattern tree until an * ExactTypePattern is found. Once this is found it creates a new * ExactAnnotationTypePattern and checks whether the targetKind * (created via the @Target annotation) matches ElementType.TYPE if * this is the only target kind which is allowed, or matches the * signature pattern kind if there is no restriction. */ private class TypePatternVisitor extends AbstractPatternNodeVisitor { private IScope scope; private Map incorrectTargetKinds /* PatternNode -> AnnotationTargetKind[] */ = new HashMap(); private boolean targetsOtherThanTypeAllowed; /** * @param requiredTarget - the signature pattern Kind * @param scope */ public TypePatternVisitor(IScope scope, boolean targetsOtherThanTypeAllowed) { this.scope = scope; this.targetsOtherThanTypeAllowed = targetsOtherThanTypeAllowed; } public Object visit(WildAnnotationTypePattern node, Object data) { node.getTypePattern().accept(this,data); return node; } /** * Do the ExactAnnotationTypePatterns have the incorrect target? */ public Object visit(ExactAnnotationTypePattern node, Object data) { ResolvedType resolvedType = node.getAnnotationType().resolve(scope.getWorld()); if (targetsOtherThanTypeAllowed) { AnnotationTargetKind[] targetKinds = resolvedType.getAnnotationTargetKinds(); if (targetKinds == null) return data; List incorrectTargets = new ArrayList(); for (int i = 0; i < targetKinds.length; i++) { if (targetKinds[i].getName().equals(kind.getName())) { return data; } incorrectTargets.add(targetKinds[i]); } if (incorrectTargets.isEmpty()) return data; AnnotationTargetKind[] kinds = new AnnotationTargetKind[incorrectTargets.size()]; incorrectTargetKinds.put(node,(AnnotationTargetKind[]) incorrectTargets.toArray(kinds)); } else if (!targetsOtherThanTypeAllowed && !resolvedType.canAnnotationTargetType()) { AnnotationTargetKind[] targetKinds = resolvedType.getAnnotationTargetKinds(); if (targetKinds == null) return data; incorrectTargetKinds.put(node,targetKinds); } return data; } public Object visit(ExactTypePattern node, Object data) { ExactAnnotationTypePattern eatp = new ExactAnnotationTypePattern(node.getExactType().resolve(scope.getWorld())); eatp.accept(this,data); return data; } public Object visit(AndTypePattern node, Object data) { node.getLeft().accept(this,data); node.getRight().accept(this,data); return node; } public Object visit(OrTypePattern node, Object data) { node.getLeft().accept(this,data); node.getRight().accept(this,data); return node; } public Object visit(AnyWithAnnotationTypePattern node, Object data) { node.getAnnotationPattern().accept(this,data); return node; } public boolean containedIncorrectTargetKind() { return (incorrectTargetKinds.size() != 0); } public Map getIncorrectTargetKinds() { return incorrectTargetKinds; } } public void postRead(ResolvedType enclosingType) { if (returnType != null) { returnType.postRead(enclosingType); } if (declaringType != null) { declaringType.postRead(enclosingType); } if (parameterTypes != null) { parameterTypes.postRead(enclosingType); } } /** * return a copy of this signature pattern in which every type variable reference * is replaced by the corresponding entry in the map. */ public SignaturePattern parameterizeWith(Map typeVariableMap) { SignaturePattern ret = new SignaturePattern( kind, modifiers, returnType.parameterizeWith(typeVariableMap), declaringType.parameterizeWith(typeVariableMap), name, parameterTypes.parameterizeWith(typeVariableMap), throwsPattern.parameterizeWith(typeVariableMap), annotationPattern.parameterizeWith(typeVariableMap)); ret.copyLocationFrom(this); return ret; } public boolean matches(Member joinPointSignature, World world, boolean allowBridgeMethods) { // fail (or succeed!) fast tests... if (joinPointSignature == null) return false; if (kind != joinPointSignature.getKind()) return false; if (kind == Member.ADVICE) return true; // do the hard work then... boolean subjectMatch = true; Iterator candidateMatches = joinPointSignature.getJoinPointSignatures(world); while(candidateMatches.hasNext()) { JoinPointSignature aSig = (JoinPointSignature) candidateMatches.next(); FuzzyBoolean matchResult = matchesExactly(aSig,world,allowBridgeMethods,subjectMatch); if (matchResult.alwaysTrue()) { return true; } else if (matchResult.alwaysFalse()) { return false; } // if we got a "MAYBE" it's worth looking at the other signatures subjectMatch = false; } return false; } // Does this pattern match this exact signature (no declaring type mucking about // or chasing up the hierarchy) // return YES if it does, NO if it doesn't and no ancester member could match either, // and MAYBE if it doesn't but an ancester member could. private FuzzyBoolean matchesExactly(JoinPointSignature aMember, World inAWorld, boolean allowBridgeMethods,boolean subjectMatch) { // Java5 introduces bridge methods, we match a call to them but nothing else... if (aMember.isBridgeMethod() && !allowBridgeMethods) { return FuzzyBoolean.MAYBE; } // modifiers match on the *subject* if (subjectMatch && !modifiers.matches(aMember.getModifiers())) { return FuzzyBoolean.NO; // if (aMember.isPrivate()) return FuzzyBoolean.NO; // else return FuzzyBoolean.MAYBE; } FuzzyBoolean matchesIgnoringAnnotations = FuzzyBoolean.YES; if (kind == Member.STATIC_INITIALIZATION) { matchesIgnoringAnnotations = matchesExactlyStaticInitialization(aMember, inAWorld); } else if (kind == Member.FIELD) { matchesIgnoringAnnotations = matchesExactlyField(aMember,inAWorld); } else if (kind == Member.METHOD) { matchesIgnoringAnnotations = matchesExactlyMethod(aMember,inAWorld, subjectMatch); } else if (kind == Member.CONSTRUCTOR) { matchesIgnoringAnnotations = matchesExactlyConstructor(aMember, inAWorld); } if (matchesIgnoringAnnotations.alwaysFalse()) return FuzzyBoolean.NO; // annotations match on the *subject* if (subjectMatch && !matchesAnnotations(aMember,inAWorld).alwaysTrue()) { return FuzzyBoolean.NO; } else { return matchesIgnoringAnnotations; } } /** * Matches on declaring type */ private FuzzyBoolean matchesExactlyStaticInitialization(JoinPointSignature aMember,World world) { return FuzzyBoolean.fromBoolean(declaringType.matchesStatically(aMember.getDeclaringType().resolve(world))); } /** * Matches on name, declaring type, field type */ private FuzzyBoolean matchesExactlyField(JoinPointSignature aField, World world) { if (!name.matches(aField.getName())) return FuzzyBoolean.NO; ResolvedType fieldDeclaringType = aField.getDeclaringType().resolve(world); if (!declaringType.matchesStatically(fieldDeclaringType)) { return FuzzyBoolean.MAYBE; } if (!returnType.matchesStatically(aField.getReturnType().resolve(world))) { // looking bad, but there might be parameterization to consider... if (!returnType.matchesStatically(aField.getGenericReturnType().resolve(world))) { // ok, it's bad. return FuzzyBoolean.MAYBE; } } // passed all the guards... return FuzzyBoolean.YES; } /** * Matches on name, declaring type, return type, parameter types, throws types */ private FuzzyBoolean matchesExactlyMethod(JoinPointSignature aMethod, World world, boolean subjectMatch) { if (!name.matches(aMethod.getName())) return FuzzyBoolean.NO; // Check the throws pattern if (subjectMatch && !throwsPattern.matches(aMethod.getExceptions(), world)) return FuzzyBoolean.NO; if (!declaringType.matchesStatically(aMethod.getDeclaringType().resolve(world))) return FuzzyBoolean.MAYBE; if (!returnType.matchesStatically(aMethod.getReturnType().resolve(world))) { // looking bad, but there might be parameterization to consider... if (!returnType.matchesStatically(aMethod.getGenericReturnType().resolve(world))) { // ok, it's bad. return FuzzyBoolean.MAYBE; } } if (!parameterTypes.canMatchSignatureWithNParameters(aMethod.getParameterTypes().length)) return FuzzyBoolean.NO; ResolvedType[] resolvedParameters = world.resolve(aMethod.getParameterTypes()); if (!parameterTypes.matches(resolvedParameters, TypePattern.STATIC).alwaysTrue()) { // It could still be a match based on the generic sig parameter types of a parameterized type if (!parameterTypes.matches(world.resolve(aMethod.getGenericParameterTypes()),TypePattern.STATIC).alwaysTrue()) { return FuzzyBoolean.MAYBE; // It could STILL be a match based on the erasure of the parameter types?? // to be determined via test cases... } } // check that varargs specifications match if (!matchesVarArgs(aMethod,world)) return FuzzyBoolean.MAYBE; // passed all the guards.. return FuzzyBoolean.YES; } /** * match on declaring type, parameter types, throws types */ private FuzzyBoolean matchesExactlyConstructor(JoinPointSignature aConstructor, World world) { if (!declaringType.matchesStatically(aConstructor.getDeclaringType().resolve(world))) return FuzzyBoolean.NO; if (!parameterTypes.canMatchSignatureWithNParameters(aConstructor.getParameterTypes().length)) return FuzzyBoolean.NO; ResolvedType[] resolvedParameters = world.resolve(aConstructor.getParameterTypes()); if (!parameterTypes.matches(resolvedParameters, TypePattern.STATIC).alwaysTrue()) { // It could still be a match based on the generic sig parameter types of a parameterized type if (!parameterTypes.matches(world.resolve(aConstructor.getGenericParameterTypes()),TypePattern.STATIC).alwaysTrue()) { return FuzzyBoolean.MAYBE; // It could STILL be a match based on the erasure of the parameter types?? // to be determined via test cases... } } // check that varargs specifications match if (!matchesVarArgs(aConstructor,world)) return FuzzyBoolean.NO; // Check the throws pattern if (!throwsPattern.matches(aConstructor.getExceptions(), world)) return FuzzyBoolean.NO; // passed all the guards.. return FuzzyBoolean.YES; } /** * We've matched against this method or constructor so far, but without considering * varargs (which has been matched as a simple array thus far). Now we do the additional * checks to see if the parties agree on whether the last parameter is varargs or a * straight array. */ private boolean matchesVarArgs(JoinPointSignature aMethodOrConstructor, World inAWorld) { if (parameterTypes.size() == 0) return true; TypePattern lastPattern = parameterTypes.get(parameterTypes.size()-1); boolean canMatchVarArgsSignature = lastPattern.isStar() || lastPattern.isVarArgs() || (lastPattern == TypePattern.ELLIPSIS); if (aMethodOrConstructor.isVarargsMethod()) { // we have at least one parameter in the pattern list, and the method has a varargs signature if (!canMatchVarArgsSignature) { // XXX - Ideally the shadow would be included in the msg but we don't know it... inAWorld.getLint().cantMatchArrayTypeOnVarargs.signal(aMethodOrConstructor.toString(),getSourceLocation()); return false; } } else { // the method ends with an array type, check that we don't *require* a varargs if (lastPattern.isVarArgs()) return false; } return true; } private FuzzyBoolean matchesAnnotations(ResolvedMember member,World world) { if (member == null) { if (member.getName().startsWith(NameMangler.PREFIX)) { return FuzzyBoolean.NO; } world.getLint().unresolvableMember.signal(member.toString(), getSourceLocation()); return FuzzyBoolean.NO; } annotationPattern.resolve(world); // optimization before we go digging around for annotations on ITDs if (annotationPattern instanceof AnyAnnotationTypePattern) return FuzzyBoolean.YES; // fake members represent ITD'd fields - for their annotations we should go and look up the // relevant member in the original aspect if (member.isAnnotatedElsewhere() && member.getKind()==Member.FIELD) { // FIXME asc duplicate of code in AnnotationPointcut.matchInternal()? same fixmes apply here. ResolvedMember [] mems = member.getDeclaringType().resolve(world).getDeclaredFields(); // FIXME asc should include supers with getInterTypeMungersIncludingSupers? List mungers = member.getDeclaringType().resolve(world).getInterTypeMungers(); for (Iterator iter = mungers.iterator(); iter.hasNext();) { BcelTypeMunger typeMunger = (BcelTypeMunger) iter.next(); if (typeMunger.getMunger() instanceof NewFieldTypeMunger) { ResolvedMember fakerm = typeMunger.getSignature(); ResolvedMember ajcMethod = AjcMemberMaker.interFieldInitializer(fakerm,typeMunger.getAspectType()); ResolvedMember rmm = findMethod(typeMunger.getAspectType(),ajcMethod); if (fakerm.equals(member)) { member = rmm; } } } } if (annotationPattern.matches(member).alwaysTrue()) { return FuzzyBoolean.YES; } else { return FuzzyBoolean.NO; // do NOT look at ancestor members... } } private ResolvedMember findMethod(ResolvedType aspectType, ResolvedMember ajcMethod) { ResolvedMember decMethods[] = aspectType.getDeclaredMethods(); for (int i = 0; i < decMethods.length; i++) { ResolvedMember member = decMethods[i]; if (member.equals(ajcMethod)) return member; } return null; } public boolean declaringTypeMatchAllowingForCovariance(Member member, UnresolvedType shadowDeclaringType, World world,TypePattern returnTypePattern,ResolvedType sigReturn) { ResolvedType onType = shadowDeclaringType.resolve(world); // fastmatch if (declaringType.matchesStatically(onType) && returnTypePattern.matchesStatically(sigReturn)) return true; Collection declaringTypes = member.getDeclaringTypes(world); boolean checkReturnType = true; // XXX Possible enhancement? Doesn't seem to speed things up // if (returnTypePattern.isStar()) { // if (returnTypePattern instanceof WildTypePattern) { // if (((WildTypePattern)returnTypePattern).getDimensions()==0) checkReturnType = false; // } // } // Sometimes that list includes types that don't explicitly declare the member we are after - // they are on the list because their supertype is on the list, that's why we use // lookupMethod rather than lookupMemberNoSupers() for (Iterator i = declaringTypes.iterator(); i.hasNext(); ) { ResolvedType type = (ResolvedType)i.next(); if (declaringType.matchesStatically(type)) { if (!checkReturnType) return true; ResolvedMember rm = type.lookupMethod(member); if (rm==null) rm = type.lookupMethodInITDs(member); // It must be in here, or we have *real* problems if (rm==null) continue; // might be currently looking at the generic type and we need to continue searching in case we hit a parameterized version of this same type... UnresolvedType returnTypeX = rm.getReturnType(); ResolvedType returnType = returnTypeX.resolve(world); if (returnTypePattern.matchesStatically(returnType)) return true; } } return false; } private Collection getDeclaringTypes(Signature sig) { List l = new ArrayList(); Class onType = sig.getDeclaringType(); String memberName = sig.getName(); if (sig instanceof FieldSignature) { Class fieldType = ((FieldSignature)sig).getFieldType(); Class superType = onType; while(superType != null) { try { Field f = (superType.getDeclaredField(memberName)); if (f.getType() == fieldType) { l.add(superType); } } catch (NoSuchFieldException nsf) {} superType = superType.getSuperclass(); } } else if (sig instanceof MethodSignature) { Class[] paramTypes = ((MethodSignature)sig).getParameterTypes(); Class superType = onType; while(superType != null) { try { superType.getDeclaredMethod(memberName,paramTypes); l.add(superType); } catch (NoSuchMethodException nsm) {} superType = superType.getSuperclass(); } } return l; } public NamePattern getName() { return name; } public TypePattern getDeclaringType() { return declaringType; } public Member.Kind getKind() { return kind; } public String toString() { StringBuffer buf = new StringBuffer(); if (annotationPattern != AnnotationTypePattern.ANY) { buf.append(annotationPattern.toString()); buf.append(' '); } if (modifiers != ModifiersPattern.ANY) { buf.append(modifiers.toString()); buf.append(' '); } if (kind == Member.STATIC_INITIALIZATION) { buf.append(declaringType.toString()); buf.append(".<clinit>()");//FIXME AV - bad, cannot be parsed again } else if (kind == Member.HANDLER) { buf.append("handler("); buf.append(parameterTypes.get(0)); buf.append(")"); } else { if (!(kind == Member.CONSTRUCTOR)) { buf.append(returnType.toString()); buf.append(' '); } if (declaringType != TypePattern.ANY) { buf.append(declaringType.toString()); buf.append('.'); } if (kind == Member.CONSTRUCTOR) { buf.append("new"); } else { buf.append(name.toString()); } if (kind == Member.METHOD || kind == Member.CONSTRUCTOR) { buf.append(parameterTypes.toString()); } //FIXME AV - throws is not printed here, weird } return buf.toString(); } public boolean equals(Object other) { if (!(other instanceof SignaturePattern)) return false; SignaturePattern o = (SignaturePattern)other; return o.kind.equals(this.kind) && o.modifiers.equals(this.modifiers) && o.returnType.equals(this.returnType) && o.declaringType.equals(this.declaringType) && o.name.equals(this.name) && o.parameterTypes.equals(this.parameterTypes) && o.throwsPattern.equals(this.throwsPattern) && o.annotationPattern.equals(this.annotationPattern); } public int hashCode() { if (hashcode==-1) { hashcode = 17; hashcode = 37*hashcode + kind.hashCode(); hashcode = 37*hashcode + modifiers.hashCode(); hashcode = 37*hashcode + returnType.hashCode(); hashcode = 37*hashcode + declaringType.hashCode(); hashcode = 37*hashcode + name.hashCode(); hashcode = 37*hashcode + parameterTypes.hashCode(); hashcode = 37*hashcode + throwsPattern.hashCode(); hashcode = 37*hashcode + annotationPattern.hashCode(); } return hashcode; } public void write(DataOutputStream s) throws IOException { kind.write(s); modifiers.write(s); returnType.write(s); declaringType.write(s); name.write(s); parameterTypes.write(s); throwsPattern.write(s); annotationPattern.write(s); writeLocation(s); } public static SignaturePattern read(VersionedDataInputStream s, ISourceContext context) throws IOException { Member.Kind kind = Member.Kind.read(s); ModifiersPattern modifiers = ModifiersPattern.read(s); TypePattern returnType = TypePattern.read(s, context); TypePattern declaringType = TypePattern.read(s, context); NamePattern name = NamePattern.read(s); TypePatternList parameterTypes = TypePatternList.read(s, context); ThrowsPattern throwsPattern = ThrowsPattern.read(s, context); AnnotationTypePattern annotationPattern = AnnotationTypePattern.ANY; if (s.getMajorVersion()>=AjAttribute.WeaverVersionInfo.WEAVER_VERSION_MAJOR_AJ150) { annotationPattern = AnnotationTypePattern.read(s,context); } SignaturePattern ret = new SignaturePattern(kind, modifiers, returnType, declaringType, name, parameterTypes, throwsPattern,annotationPattern); ret.readLocation(context, s); return ret; } /** * @return */ public ModifiersPattern getModifiers() { return modifiers; } /** * @return */ public TypePatternList getParameterTypes() { return parameterTypes; } /** * @return */ public TypePattern getReturnType() { return returnType; } /** * @return */ public ThrowsPattern getThrowsPattern() { return throwsPattern; } /** * return true if last argument in params is an Object[] but the modifiers say this method * was declared with varargs (Object...). We shouldn't be matching if this is the case. */ private boolean matchedArrayAgainstVarArgs(TypePatternList params,int modifiers) { if (params.size()>0 && (modifiers & Constants.ACC_VARARGS)!=0) { // we have at least one parameter in the pattern list, and the method has a varargs signature TypePattern lastPattern = params.get(params.size()-1); if (lastPattern.isArray() && !lastPattern.isVarArgs) return true; } return false; } public AnnotationTypePattern getAnnotationPattern() { return annotationPattern; } public boolean isStarAnnotation() { return annotationPattern == AnnotationTypePattern.ANY; } public Object accept(PatternNodeVisitor visitor, Object data) { return visitor.visit(this, data); } }
161,502
Bug 161502 UnsupportedOperationException thrown: unable to parameterize unresolved type: Pjava/util/List<+Ljava/lang/Object; >;
Generic parameters (like List<? extends T>) in pointcuts throw UnsupportedOperationException. java.lang.UnsupportedOperationException at org.aspectj.weaver.UnresolvedType.parameterize(UnresolvedType.java: 220) at org.aspectj.weaver.patterns.ExactTypePattern.parameterizeWith (ExactTypePattern.java:244) at org.aspectj.weaver.patterns.SignaturePattern.parameterizeWith (SignaturePattern.java:265) at org.aspectj.weaver.patterns.KindedPointcut.parameterizeWith (KindedPointcut.java:381) at org.aspectj.weaver.bcel.BcelAdvice.parameterizeWith (BcelAdvice.java:93) at org.aspectj.weaver.ResolvedType.getDeclaredAdvice (ResolvedType.java:710) at org.aspectj.weaver.ResolvedType.getDeclaredShadowMungers (ResolvedType.java:739) at org.aspectj.weaver.ResolvedType.collectShadowMungers (ResolvedType.java:575) at org.aspectj.weaver.ResolvedType.collectCrosscuttingMembers (ResolvedType.java:504) at org.aspectj.weaver.CrosscuttingMembersSet.addOrReplaceAspect (CrosscuttingMembersSet.java:68) at org.aspectj.weaver.CrosscuttingMembersSet.addOrReplaceAspect (CrosscuttingMembersSet.java:57) at org.aspectj.weaver.bcel.BcelWeaver.prepareForWeave(BcelWeaver.java: 450) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.weave (AjCompilerAdapter.java:299) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.afterCompiling (AjCompilerAdapter.java:192) at org.aspectj.ajdt.internal.compiler.CompilerAdapter.ajc $afterReturning$org_aspectj_ajdt_internal_compiler_CompilerAdapter$2 $f9cc9ca0(CompilerAdapter.aj:70) at org.aspectj.org.eclipse.jdt.internal.compiler.Compiler.compile (Compiler.java:367) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.performCompilation (AjBuildManager.java:887) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.doBuild (AjBuildManager.java:244) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.batchBuild (AjBuildManager.java:163) at org.aspectj.ajde.internal.CompilerAdapter.compile (CompilerAdapter.java:122) at org.aspectj.ajde.internal.AspectJBuildManager$CompilerThread.run (AspectJBuildManager.java:191) UnsupportedOperationException thrown: unable to parameterize unresolved type: Pjava/util/List<+Ljava/lang/Object;>; To reproduce this exception compile the following code snippet. import java.util.ArrayList; import java.util.List; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; public class Main { public List<? extends Element> getElements() { return new ArrayList<Element>(); } class Element {}; @Aspect static abstract class Base<T> { @Around("call(List<? extends T> *.*(..))") public List<? extends T> elementList(ProceedingJoinPoint thisJoinPoint) { try { return (List<? extends T>)thisJoinPoint.proceed(); } catch (Throwable e) { throw new RuntimeException(e); } } } @Aspect static class Concrete extends Base<Element> {} public static void main(String[] args) { new Main().getElements(); } }
resolved fixed
7b40e7e
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2006-10-24T12:42:57Z"
"2006-10-19T01:06:40Z"
weaver/src/org/aspectj/weaver/patterns/ThisOrTargetAnnotationPointcut.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.DataOutputStream; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map; import org.aspectj.bridge.IMessage; import org.aspectj.bridge.MessageUtil; import org.aspectj.util.FuzzyBoolean; import org.aspectj.weaver.ISourceContext; import org.aspectj.weaver.IntMap; import org.aspectj.weaver.ResolvedType; import org.aspectj.weaver.Shadow; import org.aspectj.weaver.ShadowMunger; import org.aspectj.weaver.UnresolvedType; import org.aspectj.weaver.VersionedDataInputStream; import org.aspectj.weaver.WeaverMessages; import org.aspectj.weaver.ast.Literal; import org.aspectj.weaver.ast.Test; import org.aspectj.weaver.ast.Var; /** * @author colyer * * TODO To change the template for this generated type comment go to * Window - Preferences - Java - Code Style - Code Templates */ public class ThisOrTargetAnnotationPointcut extends NameBindingPointcut { private boolean isThis; private boolean alreadyWarnedAboutDEoW = false; private ExactAnnotationTypePattern annotationTypePattern; private ShadowMunger munger; private String declarationText; private static final int thisKindSet; private static final int targetKindSet; static { int thisFlags = Shadow.ALL_SHADOW_KINDS_BITS; int targFlags = Shadow.ALL_SHADOW_KINDS_BITS; for (int i = 0; i < Shadow.SHADOW_KINDS.length; i++) { Shadow.Kind kind = Shadow.SHADOW_KINDS[i]; if (kind.neverHasThis()) thisFlags-=kind.bit; if (kind.neverHasTarget()) targFlags-=kind.bit; } thisKindSet = thisFlags; targetKindSet=targFlags; } /** * */ public ThisOrTargetAnnotationPointcut(boolean isThis, ExactAnnotationTypePattern type) { super(); this.isThis = isThis; this.annotationTypePattern = type; this.pointcutKind = ATTHIS_OR_TARGET; buildDeclarationText(); } public ThisOrTargetAnnotationPointcut(boolean isThis, ExactAnnotationTypePattern type, ShadowMunger munger) { this(isThis,type); this.munger = munger; } public ExactAnnotationTypePattern getAnnotationTypePattern() { return annotationTypePattern; } public int couldMatchKinds() { return isThis ? thisKindSet : targetKindSet; } public Pointcut parameterizeWith(Map typeVariableMap) { ExactAnnotationTypePattern newPattern = (ExactAnnotationTypePattern) this.annotationTypePattern.parameterizeWith(typeVariableMap); if (newPattern.getAnnotationType() instanceof ResolvedType) { verifyRuntimeRetention((ResolvedType)newPattern.getResolvedAnnotationType()); } ThisOrTargetAnnotationPointcut ret = new ThisOrTargetAnnotationPointcut(isThis,(ExactAnnotationTypePattern)annotationTypePattern.parameterizeWith(typeVariableMap)); ret.copyLocationFrom(this); return ret; } /* (non-Javadoc) * @see org.aspectj.weaver.patterns.Pointcut#fastMatch(org.aspectj.weaver.patterns.FastMatchInfo) */ public FuzzyBoolean fastMatch(FastMatchInfo info) { return FuzzyBoolean.MAYBE; } /* (non-Javadoc) * @see org.aspectj.weaver.patterns.Pointcut#match(org.aspectj.weaver.Shadow) */ protected FuzzyBoolean matchInternal(Shadow shadow) { if (!couldMatch(shadow)) return FuzzyBoolean.NO; ResolvedType toMatchAgainst = (isThis ? shadow.getThisType() : shadow.getTargetType() ).resolve(shadow.getIWorld()); annotationTypePattern.resolve(shadow.getIWorld()); if (annotationTypePattern.matchesRuntimeType(toMatchAgainst).alwaysTrue()) { return FuzzyBoolean.YES; } else { // a subtype may match at runtime return FuzzyBoolean.MAYBE; } } public boolean isThis() { return isThis; } /* (non-Javadoc) * @see org.aspectj.weaver.patterns.Pointcut#resolveBindings(org.aspectj.weaver.patterns.IScope, org.aspectj.weaver.patterns.Bindings) */ protected void resolveBindings(IScope scope, Bindings bindings) { if (!scope.getWorld().isInJava5Mode()) { scope.message(MessageUtil.error(WeaverMessages.format( isThis ? WeaverMessages.ATTHIS_ONLY_SUPPORTED_AT_JAVA5_LEVEL : WeaverMessages.ATTARGET_ONLY_SUPPORTED_AT_JAVA5_LEVEL), getSourceLocation())); return; } annotationTypePattern = (ExactAnnotationTypePattern) annotationTypePattern.resolveBindings(scope,bindings,true); // must be either a Var, or an annotation type pattern // if annotationType does not have runtime retention, this is an error if (annotationTypePattern.annotationType == null) { // it's a formal with a binding error return; } ResolvedType rAnnotationType = (ResolvedType) annotationTypePattern.annotationType; if (rAnnotationType.isTypeVariableReference()) return; // we'll deal with this next check when the type var is actually bound... verifyRuntimeRetention(rAnnotationType); } private void verifyRuntimeRetention(ResolvedType rAnnotationType) { if (!(rAnnotationType.isAnnotationWithRuntimeRetention())) { IMessage m = MessageUtil.error( WeaverMessages.format(WeaverMessages.BINDING_NON_RUNTIME_RETENTION_ANNOTATION,rAnnotationType.getName()), getSourceLocation()); rAnnotationType.getWorld().getMessageHandler().handleMessage(m); } } /* (non-Javadoc) * @see org.aspectj.weaver.patterns.Pointcut#concretize1(org.aspectj.weaver.ResolvedType, org.aspectj.weaver.IntMap) */ protected Pointcut concretize1(ResolvedType inAspect, ResolvedType declaringType, IntMap bindings) { if (isDeclare(bindings.getEnclosingAdvice())) { // Enforce rule about which designators are supported in declare if (!alreadyWarnedAboutDEoW) { inAspect.getWorld().showMessage(IMessage.ERROR, WeaverMessages.format(WeaverMessages.THIS_OR_TARGET_IN_DECLARE,isThis?"this":"target"), bindings.getEnclosingAdvice().getSourceLocation(), null); alreadyWarnedAboutDEoW = true; } return Pointcut.makeMatchesNothing(Pointcut.CONCRETE); } ExactAnnotationTypePattern newType = (ExactAnnotationTypePattern) annotationTypePattern.remapAdviceFormals(bindings); ThisOrTargetAnnotationPointcut ret = new ThisOrTargetAnnotationPointcut(isThis, newType, bindings.getEnclosingAdvice()); ret.alreadyWarnedAboutDEoW = alreadyWarnedAboutDEoW; ret.copyLocationFrom(this); return ret; } /* (non-Javadoc) * @see org.aspectj.weaver.patterns.Pointcut#findResidue(org.aspectj.weaver.Shadow, org.aspectj.weaver.patterns.ExposedState) */ /** * The guard here is going to be the hasAnnotation() test - if it gets through (which we cannot determine until runtime) then * we must have a TypeAnnotationAccessVar in place - this means we must *always* have one in place. */ protected Test findResidueInternal(Shadow shadow, ExposedState state) { if (!couldMatch(shadow)) return Literal.FALSE; boolean alwaysMatches = match(shadow).alwaysTrue(); Var var = isThis ? shadow.getThisVar() : shadow.getTargetVar(); Var annVar = null; // Are annotations being bound? UnresolvedType annotationType = annotationTypePattern.annotationType; if (annotationTypePattern instanceof BindingAnnotationTypePattern) { BindingAnnotationTypePattern btp = (BindingAnnotationTypePattern)annotationTypePattern; annotationType = btp.annotationType; annVar = isThis ? shadow.getThisAnnotationVar(annotationType) : shadow.getTargetAnnotationVar(annotationType); if (annVar == null) throw new RuntimeException("Impossible!"); state.set(btp.getFormalIndex(),annVar); } if (alwaysMatches && (annVar == null)) {//change check to verify if its the 'generic' annVar that is being used return Literal.TRUE; } else { ResolvedType rType = annotationType.resolve(shadow.getIWorld()); return Test.makeHasAnnotation(var,rType); } } private boolean couldMatch(Shadow shadow) { return isThis ? shadow.hasThis() : shadow.hasTarget(); } /* (non-Javadoc) * @see org.aspectj.weaver.patterns.NameBindingPointcut#getBindingAnnotationTypePatterns() */ public List getBindingAnnotationTypePatterns() { if (annotationTypePattern instanceof BindingAnnotationTypePattern) { List l = new ArrayList(); l.add(annotationTypePattern); return l; } else return Collections.EMPTY_LIST; } /* (non-Javadoc) * @see org.aspectj.weaver.patterns.NameBindingPointcut#getBindingTypePatterns() */ public List getBindingTypePatterns() { return Collections.EMPTY_LIST; } /* (non-Javadoc) * @see org.aspectj.weaver.patterns.PatternNode#write(java.io.DataOutputStream) */ public void write(DataOutputStream s) throws IOException { s.writeByte(Pointcut.ATTHIS_OR_TARGET); s.writeBoolean(isThis); annotationTypePattern.write(s); writeLocation(s); } public static Pointcut read(VersionedDataInputStream s, ISourceContext context) throws IOException { boolean isThis = s.readBoolean(); AnnotationTypePattern type = AnnotationTypePattern.read(s, context); ThisOrTargetAnnotationPointcut ret = new ThisOrTargetAnnotationPointcut(isThis,(ExactAnnotationTypePattern)type); ret.readLocation(context, s); return ret; } /* (non-Javadoc) * @see java.lang.Object#equals(java.lang.Object) */ public boolean equals(Object obj) { if (!(obj instanceof ThisOrTargetAnnotationPointcut)) return false; ThisOrTargetAnnotationPointcut other = (ThisOrTargetAnnotationPointcut) obj; return ( other.annotationTypePattern.equals(this.annotationTypePattern) && (other.isThis == this.isThis) ); } /* (non-Javadoc) * @see java.lang.Object#hashCode() */ public int hashCode() { return 17 + 37*annotationTypePattern.hashCode() + (isThis ? 49 : 13); } /* (non-Javadoc) * @see java.lang.Object#toString() */ private void buildDeclarationText() { StringBuffer buf = new StringBuffer(); buf.append(isThis ? "@this(" : "@target("); String annPatt = annotationTypePattern.toString(); buf.append(annPatt.startsWith("@") ? annPatt.substring(1) : annPatt); buf.append(")"); this.declarationText = buf.toString(); } public String toString() { return this.declarationText; } public Object accept(PatternNodeVisitor visitor, Object data) { return visitor.visit(this, data); } }
161,502
Bug 161502 UnsupportedOperationException thrown: unable to parameterize unresolved type: Pjava/util/List<+Ljava/lang/Object; >;
Generic parameters (like List<? extends T>) in pointcuts throw UnsupportedOperationException. java.lang.UnsupportedOperationException at org.aspectj.weaver.UnresolvedType.parameterize(UnresolvedType.java: 220) at org.aspectj.weaver.patterns.ExactTypePattern.parameterizeWith (ExactTypePattern.java:244) at org.aspectj.weaver.patterns.SignaturePattern.parameterizeWith (SignaturePattern.java:265) at org.aspectj.weaver.patterns.KindedPointcut.parameterizeWith (KindedPointcut.java:381) at org.aspectj.weaver.bcel.BcelAdvice.parameterizeWith (BcelAdvice.java:93) at org.aspectj.weaver.ResolvedType.getDeclaredAdvice (ResolvedType.java:710) at org.aspectj.weaver.ResolvedType.getDeclaredShadowMungers (ResolvedType.java:739) at org.aspectj.weaver.ResolvedType.collectShadowMungers (ResolvedType.java:575) at org.aspectj.weaver.ResolvedType.collectCrosscuttingMembers (ResolvedType.java:504) at org.aspectj.weaver.CrosscuttingMembersSet.addOrReplaceAspect (CrosscuttingMembersSet.java:68) at org.aspectj.weaver.CrosscuttingMembersSet.addOrReplaceAspect (CrosscuttingMembersSet.java:57) at org.aspectj.weaver.bcel.BcelWeaver.prepareForWeave(BcelWeaver.java: 450) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.weave (AjCompilerAdapter.java:299) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.afterCompiling (AjCompilerAdapter.java:192) at org.aspectj.ajdt.internal.compiler.CompilerAdapter.ajc $afterReturning$org_aspectj_ajdt_internal_compiler_CompilerAdapter$2 $f9cc9ca0(CompilerAdapter.aj:70) at org.aspectj.org.eclipse.jdt.internal.compiler.Compiler.compile (Compiler.java:367) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.performCompilation (AjBuildManager.java:887) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.doBuild (AjBuildManager.java:244) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.batchBuild (AjBuildManager.java:163) at org.aspectj.ajde.internal.CompilerAdapter.compile (CompilerAdapter.java:122) at org.aspectj.ajde.internal.AspectJBuildManager$CompilerThread.run (AspectJBuildManager.java:191) UnsupportedOperationException thrown: unable to parameterize unresolved type: Pjava/util/List<+Ljava/lang/Object;>; To reproduce this exception compile the following code snippet. import java.util.ArrayList; import java.util.List; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; public class Main { public List<? extends Element> getElements() { return new ArrayList<Element>(); } class Element {}; @Aspect static abstract class Base<T> { @Around("call(List<? extends T> *.*(..))") public List<? extends T> elementList(ProceedingJoinPoint thisJoinPoint) { try { return (List<? extends T>)thisJoinPoint.proceed(); } catch (Throwable e) { throw new RuntimeException(e); } } } @Aspect static class Concrete extends Base<Element> {} public static void main(String[] args) { new Main().getElements(); } }
resolved fixed
7b40e7e
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2006-10-24T12:42:57Z"
"2006-10-19T01:06:40Z"
weaver/src/org/aspectj/weaver/patterns/ThisOrTargetPointcut.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.DataOutputStream; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map; import org.aspectj.bridge.IMessage; import org.aspectj.bridge.MessageUtil; import org.aspectj.util.FuzzyBoolean; import org.aspectj.weaver.ISourceContext; import org.aspectj.weaver.IntMap; import org.aspectj.weaver.ResolvedType; import org.aspectj.weaver.Shadow; import org.aspectj.weaver.UnresolvedType; import org.aspectj.weaver.VersionedDataInputStream; import org.aspectj.weaver.WeaverMessages; import org.aspectj.weaver.ast.Literal; import org.aspectj.weaver.ast.Test; import org.aspectj.weaver.ast.Var; // /** * Corresponds to target or this pcd. * * <p>type is initially a WildTypePattern. If it stays that way, it's a this(Foo) * type deal. * however, the resolveBindings method may convert it to a BindingTypePattern, * in which * case, it's a this(foo) type deal. * * @author Erik Hilsdale * @author Jim Hugunin */ public class ThisOrTargetPointcut extends NameBindingPointcut { private boolean isThis; private TypePattern type; private String declarationText; private static final int thisKindSet; private static final int targetKindSet; static { int thisFlags = Shadow.ALL_SHADOW_KINDS_BITS; int targFlags = Shadow.ALL_SHADOW_KINDS_BITS; for (int i = 0; i < Shadow.SHADOW_KINDS.length; i++) { Shadow.Kind kind = Shadow.SHADOW_KINDS[i]; if (kind.neverHasThis()) thisFlags-=kind.bit; if (kind.neverHasTarget()) targFlags-=kind.bit; } thisKindSet = thisFlags; targetKindSet=targFlags; } public boolean isBinding() { return (type instanceof BindingTypePattern); } public ThisOrTargetPointcut(boolean isThis, TypePattern type) { this.isThis = isThis; this.type = type; this.pointcutKind = THIS_OR_TARGET; this.declarationText = (isThis ? "this(" : "target(") + type + ")"; } public TypePattern getType() { return type; } public boolean isThis() { return isThis; } public Pointcut parameterizeWith(Map typeVariableMap) { ThisOrTargetPointcut ret = new ThisOrTargetPointcut(isThis,type.parameterizeWith(typeVariableMap)); ret.copyLocationFrom(this); return ret; } public int couldMatchKinds() { return isThis ? thisKindSet : targetKindSet; } public FuzzyBoolean fastMatch(FastMatchInfo type) { return FuzzyBoolean.MAYBE; } private boolean couldMatch(Shadow shadow) { return isThis ? shadow.hasThis() : shadow.hasTarget(); } protected FuzzyBoolean matchInternal(Shadow shadow) { if (!couldMatch(shadow)) return FuzzyBoolean.NO; UnresolvedType typeToMatch = isThis ? shadow.getThisType() : shadow.getTargetType(); //if (typeToMatch == ResolvedType.MISSING) return FuzzyBoolean.NO; return type.matches(typeToMatch.resolve(shadow.getIWorld()), TypePattern.DYNAMIC);//AVPT was DYNAMIC } public void write(DataOutputStream s) throws IOException { s.writeByte(Pointcut.THIS_OR_TARGET); s.writeBoolean(isThis); type.write(s); writeLocation(s); } public static Pointcut read(VersionedDataInputStream s, ISourceContext context) throws IOException { boolean isThis = s.readBoolean(); TypePattern type = TypePattern.read(s, context); ThisOrTargetPointcut ret = new ThisOrTargetPointcut(isThis, type); ret.readLocation(context, s); return ret; } public void resolveBindings(IScope scope, Bindings bindings) { type = type.resolveBindings(scope, bindings, true, true); // look for parameterized type patterns which are not supported... HasThisTypePatternTriedToSneakInSomeGenericOrParameterizedTypePatternMatchingStuffAnywhereVisitor visitor = new HasThisTypePatternTriedToSneakInSomeGenericOrParameterizedTypePatternMatchingStuffAnywhereVisitor(); type.traverse(visitor, null); if (visitor.wellHasItThen/*?*/()) { scope.message(MessageUtil.error(WeaverMessages.format(WeaverMessages.THIS_AND_TARGET_DONT_SUPPORT_PARAMETERS), getSourceLocation())); } // ??? handle non-formal } public void postRead(ResolvedType enclosingType) { type.postRead(enclosingType); } /* (non-Javadoc) * @see org.aspectj.weaver.patterns.NameBindingPointcut#getBindingAnnotationTypePatterns() */ public List getBindingAnnotationTypePatterns() { return Collections.EMPTY_LIST; } /* (non-Javadoc) * @see org.aspectj.weaver.patterns.NameBindingPointcut#getBindingTypePatterns() */ public List getBindingTypePatterns() { if (type instanceof BindingTypePattern) { List l = new ArrayList(); l.add(type); return l; } else return Collections.EMPTY_LIST; } public boolean equals(Object other) { if (!(other instanceof ThisOrTargetPointcut)) return false; ThisOrTargetPointcut o = (ThisOrTargetPointcut)other; return o.isThis == this.isThis && o.type.equals(this.type); } public int hashCode() { int result = 17; result = 37*result + (isThis ? 0 : 1); result = 37*result + type.hashCode(); return result; } public String toString() { return declarationText; } /** * Residue is the remainder of the pointcut match that couldn't be * performed with the purely static information at compile time and * this method returns the residue of a pointcut at a particular shadow. */ protected Test findResidueInternal(Shadow shadow, ExposedState state) { if (!couldMatch(shadow)) return Literal.FALSE; // if no preference is specified, just say TRUE which means no residue if (type == TypePattern.ANY) return Literal.TRUE; Var var = isThis ? shadow.getThisVar() : shadow.getTargetVar(); return exposeStateForVar(var, type, state, shadow.getIWorld()); } public Pointcut concretize1(ResolvedType inAspect, ResolvedType declaringType, IntMap bindings) { if (isDeclare(bindings.getEnclosingAdvice())) { // Enforce rule about which designators are supported in declare inAspect.getWorld().showMessage(IMessage.ERROR, WeaverMessages.format(WeaverMessages.THIS_OR_TARGET_IN_DECLARE,isThis?"this":"target"), bindings.getEnclosingAdvice().getSourceLocation(), null); return Pointcut.makeMatchesNothing(Pointcut.CONCRETE); } TypePattern newType = type.remapAdviceFormals(bindings); if (inAspect.crosscuttingMembers != null) { inAspect.crosscuttingMembers.exposeType(newType.getExactType()); } Pointcut ret = new ThisOrTargetPointcut(isThis, newType); ret.copyLocationFrom(this); return ret; } public Object accept(PatternNodeVisitor visitor, Object data) { return visitor.visit(this, data); } }
161,502
Bug 161502 UnsupportedOperationException thrown: unable to parameterize unresolved type: Pjava/util/List<+Ljava/lang/Object; >;
Generic parameters (like List<? extends T>) in pointcuts throw UnsupportedOperationException. java.lang.UnsupportedOperationException at org.aspectj.weaver.UnresolvedType.parameterize(UnresolvedType.java: 220) at org.aspectj.weaver.patterns.ExactTypePattern.parameterizeWith (ExactTypePattern.java:244) at org.aspectj.weaver.patterns.SignaturePattern.parameterizeWith (SignaturePattern.java:265) at org.aspectj.weaver.patterns.KindedPointcut.parameterizeWith (KindedPointcut.java:381) at org.aspectj.weaver.bcel.BcelAdvice.parameterizeWith (BcelAdvice.java:93) at org.aspectj.weaver.ResolvedType.getDeclaredAdvice (ResolvedType.java:710) at org.aspectj.weaver.ResolvedType.getDeclaredShadowMungers (ResolvedType.java:739) at org.aspectj.weaver.ResolvedType.collectShadowMungers (ResolvedType.java:575) at org.aspectj.weaver.ResolvedType.collectCrosscuttingMembers (ResolvedType.java:504) at org.aspectj.weaver.CrosscuttingMembersSet.addOrReplaceAspect (CrosscuttingMembersSet.java:68) at org.aspectj.weaver.CrosscuttingMembersSet.addOrReplaceAspect (CrosscuttingMembersSet.java:57) at org.aspectj.weaver.bcel.BcelWeaver.prepareForWeave(BcelWeaver.java: 450) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.weave (AjCompilerAdapter.java:299) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.afterCompiling (AjCompilerAdapter.java:192) at org.aspectj.ajdt.internal.compiler.CompilerAdapter.ajc $afterReturning$org_aspectj_ajdt_internal_compiler_CompilerAdapter$2 $f9cc9ca0(CompilerAdapter.aj:70) at org.aspectj.org.eclipse.jdt.internal.compiler.Compiler.compile (Compiler.java:367) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.performCompilation (AjBuildManager.java:887) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.doBuild (AjBuildManager.java:244) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.batchBuild (AjBuildManager.java:163) at org.aspectj.ajde.internal.CompilerAdapter.compile (CompilerAdapter.java:122) at org.aspectj.ajde.internal.AspectJBuildManager$CompilerThread.run (AspectJBuildManager.java:191) UnsupportedOperationException thrown: unable to parameterize unresolved type: Pjava/util/List<+Ljava/lang/Object;>; To reproduce this exception compile the following code snippet. import java.util.ArrayList; import java.util.List; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; public class Main { public List<? extends Element> getElements() { return new ArrayList<Element>(); } class Element {}; @Aspect static abstract class Base<T> { @Around("call(List<? extends T> *.*(..))") public List<? extends T> elementList(ProceedingJoinPoint thisJoinPoint) { try { return (List<? extends T>)thisJoinPoint.proceed(); } catch (Throwable e) { throw new RuntimeException(e); } } } @Aspect static class Concrete extends Base<Element> {} public static void main(String[] args) { new Main().getElements(); } }
resolved fixed
7b40e7e
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2006-10-24T12:42:57Z"
"2006-10-19T01:06:40Z"
weaver/src/org/aspectj/weaver/patterns/ThrowsPattern.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.DataOutputStream; import java.io.IOException; import java.util.Map; import org.aspectj.weaver.ISourceContext; import org.aspectj.weaver.ResolvedType; import org.aspectj.weaver.UnresolvedType; import org.aspectj.weaver.VersionedDataInputStream; import org.aspectj.weaver.World; public class ThrowsPattern extends PatternNode { private TypePatternList required; private TypePatternList forbidden; public static final ThrowsPattern ANY = new ThrowsPattern(TypePatternList.EMPTY, TypePatternList.EMPTY); public ThrowsPattern(TypePatternList required, TypePatternList forbidden) { this.required = required; this.forbidden = forbidden; } public TypePatternList getRequired() { return required; } public TypePatternList getForbidden() { return forbidden; } public String toString() { if (this == ANY) return ""; String ret = "throws " + required.toString(); if (forbidden.size() > 0) { ret = ret + " !(" + forbidden.toString() + ")"; } return ret; } public boolean equals(Object other) { if (!(other instanceof ThrowsPattern)) return false; ThrowsPattern o = (ThrowsPattern)other; boolean ret = o.required.equals(this.required) && o.forbidden.equals(this.forbidden); return ret; } public int hashCode() { int result = 17; result = 37*result + required.hashCode(); result = 37*result + forbidden.hashCode(); return result; } public ThrowsPattern resolveBindings(IScope scope, Bindings bindings) { if (this == ANY) return this; required = required.resolveBindings(scope, bindings, false, false); forbidden = forbidden.resolveBindings(scope, bindings, false, false); return this; } public ThrowsPattern parameterizeWith(Map/*name -> resolved type*/ typeVariableMap) { ThrowsPattern ret = new ThrowsPattern( required.parameterizeWith(typeVariableMap), forbidden.parameterizeWith(typeVariableMap)); ret.copyLocationFrom(this); return ret; } public boolean matches(UnresolvedType[] tys, World world) { if (this == ANY) return true; //System.out.println("matching: " + this + " with " + Arrays.asList(tys)); ResolvedType[] types = world.resolve(tys); // int len = types.length; for (int j=0, lenj = required.size(); j < lenj; j++) { if (! matchesAny(required.get(j), types)) { return false; } } for (int j=0, lenj = forbidden.size(); j < lenj; j++) { if (matchesAny(forbidden.get(j), types)) { return false; } } return true; } private boolean matchesAny( TypePattern typePattern, ResolvedType[] types) { for (int i = types.length - 1; i >= 0; i--) { if (typePattern.matchesStatically(types[i])) return true; } return false; } public static ThrowsPattern read(VersionedDataInputStream s, ISourceContext context) throws IOException { TypePatternList required = TypePatternList.read(s, context); TypePatternList forbidden = TypePatternList.read(s, context); if (required.size() == 0 && forbidden.size() == 0) return ANY; ThrowsPattern ret = new ThrowsPattern(required, forbidden); //XXXret.readLocation(context, s); return ret; } public void write(DataOutputStream s) throws IOException { required.write(s); forbidden.write(s); //XXXwriteLocation(s); } public Object accept(PatternNodeVisitor visitor, Object data) { return visitor.visit(this, data); } public Object traverse(PatternNodeVisitor visitor, Object data) { Object ret = accept(visitor,data); forbidden.traverse(visitor, data); required.traverse(visitor, data); return ret; } }
161,502
Bug 161502 UnsupportedOperationException thrown: unable to parameterize unresolved type: Pjava/util/List<+Ljava/lang/Object; >;
Generic parameters (like List<? extends T>) in pointcuts throw UnsupportedOperationException. java.lang.UnsupportedOperationException at org.aspectj.weaver.UnresolvedType.parameterize(UnresolvedType.java: 220) at org.aspectj.weaver.patterns.ExactTypePattern.parameterizeWith (ExactTypePattern.java:244) at org.aspectj.weaver.patterns.SignaturePattern.parameterizeWith (SignaturePattern.java:265) at org.aspectj.weaver.patterns.KindedPointcut.parameterizeWith (KindedPointcut.java:381) at org.aspectj.weaver.bcel.BcelAdvice.parameterizeWith (BcelAdvice.java:93) at org.aspectj.weaver.ResolvedType.getDeclaredAdvice (ResolvedType.java:710) at org.aspectj.weaver.ResolvedType.getDeclaredShadowMungers (ResolvedType.java:739) at org.aspectj.weaver.ResolvedType.collectShadowMungers (ResolvedType.java:575) at org.aspectj.weaver.ResolvedType.collectCrosscuttingMembers (ResolvedType.java:504) at org.aspectj.weaver.CrosscuttingMembersSet.addOrReplaceAspect (CrosscuttingMembersSet.java:68) at org.aspectj.weaver.CrosscuttingMembersSet.addOrReplaceAspect (CrosscuttingMembersSet.java:57) at org.aspectj.weaver.bcel.BcelWeaver.prepareForWeave(BcelWeaver.java: 450) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.weave (AjCompilerAdapter.java:299) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.afterCompiling (AjCompilerAdapter.java:192) at org.aspectj.ajdt.internal.compiler.CompilerAdapter.ajc $afterReturning$org_aspectj_ajdt_internal_compiler_CompilerAdapter$2 $f9cc9ca0(CompilerAdapter.aj:70) at org.aspectj.org.eclipse.jdt.internal.compiler.Compiler.compile (Compiler.java:367) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.performCompilation (AjBuildManager.java:887) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.doBuild (AjBuildManager.java:244) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.batchBuild (AjBuildManager.java:163) at org.aspectj.ajde.internal.CompilerAdapter.compile (CompilerAdapter.java:122) at org.aspectj.ajde.internal.AspectJBuildManager$CompilerThread.run (AspectJBuildManager.java:191) UnsupportedOperationException thrown: unable to parameterize unresolved type: Pjava/util/List<+Ljava/lang/Object;>; To reproduce this exception compile the following code snippet. import java.util.ArrayList; import java.util.List; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; public class Main { public List<? extends Element> getElements() { return new ArrayList<Element>(); } class Element {}; @Aspect static abstract class Base<T> { @Around("call(List<? extends T> *.*(..))") public List<? extends T> elementList(ProceedingJoinPoint thisJoinPoint) { try { return (List<? extends T>)thisJoinPoint.proceed(); } catch (Throwable e) { throw new RuntimeException(e); } } } @Aspect static class Concrete extends Base<Element> {} public static void main(String[] args) { new Main().getElements(); } }
resolved fixed
7b40e7e
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2006-10-24T12:42:57Z"
"2006-10-19T01:06:40Z"
weaver/src/org/aspectj/weaver/patterns/TypePattern.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.DataOutputStream; import java.io.IOException; import java.lang.reflect.Modifier; import java.util.Iterator; import java.util.Map; import org.aspectj.bridge.MessageUtil; import org.aspectj.util.FuzzyBoolean; import org.aspectj.weaver.BCException; import org.aspectj.weaver.ISourceContext; import org.aspectj.weaver.IntMap; import org.aspectj.weaver.ResolvedType; import org.aspectj.weaver.TypeVariableReference; import org.aspectj.weaver.UnresolvedType; import org.aspectj.weaver.VersionedDataInputStream; import org.aspectj.weaver.WeaverMessages; import org.aspectj.weaver.World; /** * On creation, type pattern only contains WildTypePattern nodes, not BindingType or ExactType. * * <p>Then we call resolveBindings() during compilation * During concretization of enclosing pointcuts, we call remapAdviceFormals * * @author Erik Hilsdale * @author Jim Hugunin */ public abstract class TypePattern extends PatternNode { public static class MatchKind { private String name; public MatchKind(String name) { this.name = name; } public String toString() { return name; } } public static final MatchKind STATIC = new MatchKind("STATIC"); public static final MatchKind DYNAMIC = new MatchKind("DYNAMIC"); public static final TypePattern ELLIPSIS = new EllipsisTypePattern(); public static final TypePattern ANY = new AnyTypePattern(); public static final TypePattern NO = new NoTypePattern(); protected boolean includeSubtypes; protected boolean isVarArgs = false; protected AnnotationTypePattern annotationPattern = AnnotationTypePattern.ANY; protected TypePatternList typeParameters = TypePatternList.EMPTY; protected TypePattern(boolean includeSubtypes,boolean isVarArgs,TypePatternList typeParams) { this.includeSubtypes = includeSubtypes; this.isVarArgs = isVarArgs; this.typeParameters = (typeParams == null ? TypePatternList.EMPTY : typeParams); } protected TypePattern(boolean includeSubtypes, boolean isVarArgs) { this(includeSubtypes,isVarArgs,null); } public AnnotationTypePattern getAnnotationPattern() { return annotationPattern; } public boolean isVarArgs() { return isVarArgs; } public boolean isStarAnnotation() { return annotationPattern == AnnotationTypePattern.ANY; } public boolean isArray() { return false; } protected TypePattern(boolean includeSubtypes) { this(includeSubtypes,false); } public void setAnnotationTypePattern(AnnotationTypePattern annPatt) { this.annotationPattern = annPatt; } public void setTypeParameters(TypePatternList typeParams) { this.typeParameters = typeParams; } public TypePatternList getTypeParameters() { return this.typeParameters; } public void setIsVarArgs(boolean isVarArgs) { this.isVarArgs = isVarArgs; } // answer conservatively... protected boolean couldEverMatchSameTypesAs(TypePattern other) { if (this.includeSubtypes || other.includeSubtypes) return true; if (this.annotationPattern != AnnotationTypePattern.ANY) return true; if (other.annotationPattern != AnnotationTypePattern.ANY) return true; return false; } //XXX non-final for Not, && and || public boolean matchesStatically(ResolvedType type) { if (includeSubtypes) { return matchesSubtypes(type); } else { return matchesExactly(type); } } public abstract FuzzyBoolean matchesInstanceof(ResolvedType type); public final FuzzyBoolean matches(ResolvedType type, MatchKind kind) { FuzzyBoolean typeMatch = null; //??? This is part of gracefully handling missing references if (type.isMissing()) return FuzzyBoolean.NO; if (kind == STATIC) { // typeMatch = FuzzyBoolean.fromBoolean(matchesStatically(type)); // return typeMatch.and(annotationPattern.matches(type)); return FuzzyBoolean.fromBoolean(matchesStatically(type)); } else if (kind == DYNAMIC) { //System.err.println("matching: " + this + " with " + type); // typeMatch = matchesInstanceof(type); //System.err.println(" got: " + ret); // return typeMatch.and(annotationPattern.matches(type)); return matchesInstanceof(type); } else { throw new IllegalArgumentException("kind must be DYNAMIC or STATIC"); } } protected abstract boolean matchesExactly(ResolvedType type); protected abstract boolean matchesExactly(ResolvedType type, ResolvedType annotatedType); protected boolean matchesSubtypes(ResolvedType type) { //System.out.println("matching: " + this + " to " + type); if (matchesExactly(type)) { //System.out.println(" true"); return true; } // pr124808 Iterator typesIterator = null; if (type.isTypeVariableReference()) { typesIterator = ((TypeVariableReference)type).getTypeVariable().getFirstBound().resolve(type.getWorld()).getDirectSupertypes(); } else { typesIterator = type.getDirectSupertypes(); } // FuzzyBoolean ret = FuzzyBoolean.NO; // ??? -eh for (Iterator i = typesIterator; i.hasNext(); ) { ResolvedType superType = (ResolvedType)i.next(); // TODO asc generics, temporary whilst matching isnt aware.. //if (superType.isParameterizedType()) superType = superType.getRawType().resolve(superType.getWorld()); if (matchesSubtypes(superType,type)) return true; } return false; } protected boolean matchesSubtypes(ResolvedType superType, ResolvedType annotatedType) { //System.out.println("matching: " + this + " to " + type); if (matchesExactly(superType,annotatedType)) { //System.out.println(" true"); return true; } // FuzzyBoolean ret = FuzzyBoolean.NO; // ??? -eh for (Iterator i = superType.getDirectSupertypes(); i.hasNext(); ) { ResolvedType superSuperType = (ResolvedType)i.next(); if (matchesSubtypes(superSuperType,annotatedType)) return true; } return false; } public UnresolvedType resolveExactType(IScope scope, Bindings bindings) { TypePattern p = resolveBindings(scope, bindings, false, true); if (!(p instanceof ExactTypePattern)) return ResolvedType.MISSING; return ((ExactTypePattern)p).getType(); } public UnresolvedType getExactType() { if (this instanceof ExactTypePattern) return ((ExactTypePattern)this).getType(); else return ResolvedType.MISSING; } protected TypePattern notExactType(IScope s) { s.getMessageHandler().handleMessage(MessageUtil.error( WeaverMessages.format(WeaverMessages.EXACT_TYPE_PATTERN_REQD), getSourceLocation())); return NO; } // public boolean assertExactType(IMessageHandler m) { // if (this instanceof ExactTypePattern) return true; // // //XXX should try harder to avoid multiple errors for one problem // m.handleMessage(MessageUtil.error("exact type pattern required", getSourceLocation())); // return false; // } /** * This can modify in place, or return a new TypePattern if the type changes. */ public TypePattern resolveBindings(IScope scope, Bindings bindings, boolean allowBinding, boolean requireExactType) { annotationPattern = annotationPattern.resolveBindings(scope,bindings,allowBinding); return this; } public void resolve(World world) { annotationPattern.resolve(world); } /** * return a version of this type pattern in which all type variable references have been * replaced by their corresponding entry in the map. */ public abstract TypePattern parameterizeWith(Map typeVariableMap); public void postRead(ResolvedType enclosingType) { } public boolean isStar() { return false; } /** * This is called during concretization of pointcuts, it is used by BindingTypePattern * to return a new BindingTypePattern with a formal index appropiate for the advice, * rather than for the lexical declaration, i.e. this handles transforamtions through * named pointcuts. * <pre> * pointcut foo(String name): args(name); * --&gt; This makes a BindingTypePattern(0) pointing to the 0th formal * * before(Foo f, String n): this(f) && foo(n) { ... } * --&gt; when resolveReferences is called on the args from the above, it * will return a BindingTypePattern(1) * * before(Foo f): this(f) && foo(*) { ... } * --&gt; when resolveReferences is called on the args from the above, it * will return an ExactTypePattern(String) * </pre> */ public TypePattern remapAdviceFormals(IntMap bindings) { return this; } public static final byte WILD = 1; public static final byte EXACT = 2; public static final byte BINDING = 3; public static final byte ELLIPSIS_KEY = 4; public static final byte ANY_KEY = 5; public static final byte NOT = 6; public static final byte OR = 7; public static final byte AND = 8; public static final byte NO_KEY = 9; public static final byte ANY_WITH_ANNO = 10; public static final byte HAS_MEMBER = 11; public static TypePattern read(VersionedDataInputStream s, ISourceContext context) throws IOException { byte key = s.readByte(); switch(key) { case WILD: return WildTypePattern.read(s, context); case EXACT: return ExactTypePattern.read(s, context); case BINDING: return BindingTypePattern.read(s, context); case ELLIPSIS_KEY: return ELLIPSIS; case ANY_KEY: return ANY; case NO_KEY: return NO; case NOT: return NotTypePattern.read(s, context); case OR: return OrTypePattern.read(s, context); case AND: return AndTypePattern.read(s, context); case ANY_WITH_ANNO: return AnyWithAnnotationTypePattern.read(s,context); case HAS_MEMBER: return HasMemberTypePattern.read(s,context); } throw new BCException("unknown TypePattern kind: " + key); } public boolean isIncludeSubtypes() { return includeSubtypes; } } class EllipsisTypePattern extends TypePattern { /** * Constructor for EllipsisTypePattern. * @param includeSubtypes */ public EllipsisTypePattern() { super(false,false,new TypePatternList()); } /* (non-Javadoc) * @see org.aspectj.weaver.patterns.TypePattern#couldEverMatchSameTypesAs(org.aspectj.weaver.patterns.TypePattern) */ protected boolean couldEverMatchSameTypesAs(TypePattern other) { return true; } /** * @see org.aspectj.weaver.patterns.TypePattern#matchesExactly(IType) */ protected boolean matchesExactly(ResolvedType type) { return false; } protected boolean matchesExactly(ResolvedType type, ResolvedType annotatedType) { return false; } /** * @see org.aspectj.weaver.patterns.TypePattern#matchesInstanceof(IType) */ public FuzzyBoolean matchesInstanceof(ResolvedType type) { return FuzzyBoolean.NO; } /** * @see org.aspectj.weaver.patterns.PatternNode#write(DataOutputStream) */ public void write(DataOutputStream s) throws IOException { s.writeByte(ELLIPSIS_KEY); } public String toString() { return ".."; } /* (non-Javadoc) * @see java.lang.Object#equals(java.lang.Object) */ public boolean equals(Object obj) { return (obj instanceof EllipsisTypePattern); } /* (non-Javadoc) * @see java.lang.Object#hashCode() */ public int hashCode() { return 17 * 37; } public Object accept(PatternNodeVisitor visitor, Object data) { return visitor.visit(this, data); } public TypePattern parameterizeWith(Map typeVariableMap) { return this; } } class AnyTypePattern extends TypePattern { /** * Constructor for EllipsisTypePattern. * @param includeSubtypes */ public AnyTypePattern() { super(false,false,new TypePatternList()); } /* (non-Javadoc) * @see org.aspectj.weaver.patterns.TypePattern#couldEverMatchSameTypesAs(org.aspectj.weaver.patterns.TypePattern) */ protected boolean couldEverMatchSameTypesAs(TypePattern other) { return true; } /** * @see org.aspectj.weaver.patterns.TypePattern#matchesExactly(IType) */ protected boolean matchesExactly(ResolvedType type) { return true; } protected boolean matchesExactly(ResolvedType type, ResolvedType annotatedType) { return true; } /** * @see org.aspectj.weaver.patterns.TypePattern#matchesInstanceof(IType) */ public FuzzyBoolean matchesInstanceof(ResolvedType type) { return FuzzyBoolean.YES; } /** * @see org.aspectj.weaver.patterns.PatternNode#write(DataOutputStream) */ public void write(DataOutputStream s) throws IOException { s.writeByte(ANY_KEY); } /** * @see org.aspectj.weaver.patterns.TypePattern#matches(IType, MatchKind) */ // public FuzzyBoolean matches(IType type, MatchKind kind) { // return FuzzyBoolean.YES; // } /** * @see org.aspectj.weaver.patterns.TypePattern#matchesSubtypes(IType) */ protected boolean matchesSubtypes(ResolvedType type) { return true; } public boolean isStar() { return true; } public String toString() { return "*"; } public boolean equals(Object obj) { return (obj instanceof AnyTypePattern); } public int hashCode() { return 37; } public Object accept(PatternNodeVisitor visitor, Object data) { return visitor.visit(this, data); } public TypePattern parameterizeWith(Map arg0) { return this; } } /** * This type represents a type pattern of '*' but with an annotation specified, * e.g. '@Color *' */ class AnyWithAnnotationTypePattern extends TypePattern { public AnyWithAnnotationTypePattern(AnnotationTypePattern atp) { super(false,false); annotationPattern = atp; } public Object accept(PatternNodeVisitor visitor, Object data) { return visitor.visit(this,data); } protected boolean couldEverMatchSameTypesAs(TypePattern other) { return true; } protected boolean matchesExactly(ResolvedType type) { annotationPattern.resolve(type.getWorld()); return annotationPattern.matches(type).alwaysTrue(); } protected boolean matchesExactly(ResolvedType type, ResolvedType annotatedType) { annotationPattern.resolve(type.getWorld()); return annotationPattern.matches(annotatedType).alwaysTrue(); } public FuzzyBoolean matchesInstanceof(ResolvedType type) { if (Modifier.isFinal(type.getModifiers())) { return FuzzyBoolean.fromBoolean(matchesExactly(type)); } return FuzzyBoolean.MAYBE; } public TypePattern parameterizeWith(Map typeVariableMap) { AnyWithAnnotationTypePattern ret = new AnyWithAnnotationTypePattern(this.annotationPattern.parameterizeWith(typeVariableMap)); ret.copyLocationFrom(this); return ret; } public void write(DataOutputStream s) throws IOException { s.writeByte(TypePattern.ANY_WITH_ANNO); annotationPattern.write(s); writeLocation(s); } public static TypePattern read(VersionedDataInputStream s,ISourceContext c) throws IOException { AnnotationTypePattern annPatt = AnnotationTypePattern.read(s,c); AnyWithAnnotationTypePattern ret = new AnyWithAnnotationTypePattern(annPatt); ret.readLocation(c, s); return ret; } // public FuzzyBoolean matches(IType type, MatchKind kind) { // return FuzzyBoolean.YES; // } protected boolean matchesSubtypes(ResolvedType type) { return true; } public boolean isStar() { return false; } public String toString() { return annotationPattern+" *"; } public boolean equals(Object obj) { if (!(obj instanceof AnyWithAnnotationTypePattern)) return false; AnyWithAnnotationTypePattern awatp = (AnyWithAnnotationTypePattern) obj; return (annotationPattern.equals(awatp.annotationPattern)); } public int hashCode() { return annotationPattern.hashCode(); } } class NoTypePattern extends TypePattern { public NoTypePattern() { super(false,false,new TypePatternList()); } /* (non-Javadoc) * @see org.aspectj.weaver.patterns.TypePattern#couldEverMatchSameTypesAs(org.aspectj.weaver.patterns.TypePattern) */ protected boolean couldEverMatchSameTypesAs(TypePattern other) { return false; } /** * @see org.aspectj.weaver.patterns.TypePattern#matchesExactly(IType) */ protected boolean matchesExactly(ResolvedType type) { return false; } protected boolean matchesExactly(ResolvedType type, ResolvedType annotatedType) { return false; } /** * @see org.aspectj.weaver.patterns.TypePattern#matchesInstanceof(IType) */ public FuzzyBoolean matchesInstanceof(ResolvedType type) { return FuzzyBoolean.NO; } /** * @see org.aspectj.weaver.patterns.PatternNode#write(DataOutputStream) */ public void write(DataOutputStream s) throws IOException { s.writeByte(NO_KEY); } /** * @see org.aspectj.weaver.patterns.TypePattern#matches(IType, MatchKind) */ // public FuzzyBoolean matches(IType type, MatchKind kind) { // return FuzzyBoolean.YES; // } /** * @see org.aspectj.weaver.patterns.TypePattern#matchesSubtypes(IType) */ protected boolean matchesSubtypes(ResolvedType type) { return false; } public boolean isStar() { return false; } public String toString() { return "<nothing>"; }//FIXME AV - bad! toString() cannot be parsed back (not idempotent) /* (non-Javadoc) * @see java.lang.Object#equals(java.lang.Object) */ public boolean equals(Object obj) { return (obj instanceof NoTypePattern); } /* (non-Javadoc) * @see java.lang.Object#hashCode() */ public int hashCode() { return 17 * 37 * 37; } public Object accept(PatternNodeVisitor visitor, Object data) { return visitor.visit(this, data); } public TypePattern parameterizeWith(Map arg0) { return this; } }
161,502
Bug 161502 UnsupportedOperationException thrown: unable to parameterize unresolved type: Pjava/util/List<+Ljava/lang/Object; >;
Generic parameters (like List<? extends T>) in pointcuts throw UnsupportedOperationException. java.lang.UnsupportedOperationException at org.aspectj.weaver.UnresolvedType.parameterize(UnresolvedType.java: 220) at org.aspectj.weaver.patterns.ExactTypePattern.parameterizeWith (ExactTypePattern.java:244) at org.aspectj.weaver.patterns.SignaturePattern.parameterizeWith (SignaturePattern.java:265) at org.aspectj.weaver.patterns.KindedPointcut.parameterizeWith (KindedPointcut.java:381) at org.aspectj.weaver.bcel.BcelAdvice.parameterizeWith (BcelAdvice.java:93) at org.aspectj.weaver.ResolvedType.getDeclaredAdvice (ResolvedType.java:710) at org.aspectj.weaver.ResolvedType.getDeclaredShadowMungers (ResolvedType.java:739) at org.aspectj.weaver.ResolvedType.collectShadowMungers (ResolvedType.java:575) at org.aspectj.weaver.ResolvedType.collectCrosscuttingMembers (ResolvedType.java:504) at org.aspectj.weaver.CrosscuttingMembersSet.addOrReplaceAspect (CrosscuttingMembersSet.java:68) at org.aspectj.weaver.CrosscuttingMembersSet.addOrReplaceAspect (CrosscuttingMembersSet.java:57) at org.aspectj.weaver.bcel.BcelWeaver.prepareForWeave(BcelWeaver.java: 450) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.weave (AjCompilerAdapter.java:299) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.afterCompiling (AjCompilerAdapter.java:192) at org.aspectj.ajdt.internal.compiler.CompilerAdapter.ajc $afterReturning$org_aspectj_ajdt_internal_compiler_CompilerAdapter$2 $f9cc9ca0(CompilerAdapter.aj:70) at org.aspectj.org.eclipse.jdt.internal.compiler.Compiler.compile (Compiler.java:367) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.performCompilation (AjBuildManager.java:887) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.doBuild (AjBuildManager.java:244) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.batchBuild (AjBuildManager.java:163) at org.aspectj.ajde.internal.CompilerAdapter.compile (CompilerAdapter.java:122) at org.aspectj.ajde.internal.AspectJBuildManager$CompilerThread.run (AspectJBuildManager.java:191) UnsupportedOperationException thrown: unable to parameterize unresolved type: Pjava/util/List<+Ljava/lang/Object;>; To reproduce this exception compile the following code snippet. import java.util.ArrayList; import java.util.List; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; public class Main { public List<? extends Element> getElements() { return new ArrayList<Element>(); } class Element {}; @Aspect static abstract class Base<T> { @Around("call(List<? extends T> *.*(..))") public List<? extends T> elementList(ProceedingJoinPoint thisJoinPoint) { try { return (List<? extends T>)thisJoinPoint.proceed(); } catch (Throwable e) { throw new RuntimeException(e); } } } @Aspect static class Concrete extends Base<Element> {} public static void main(String[] args) { new Main().getElements(); } }
resolved fixed
7b40e7e
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2006-10-24T12:42:57Z"
"2006-10-19T01:06:40Z"
weaver/src/org/aspectj/weaver/patterns/TypePatternList.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.DataOutputStream; import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Map; import org.aspectj.util.FuzzyBoolean; import org.aspectj.weaver.ISourceContext; import org.aspectj.weaver.IntMap; import org.aspectj.weaver.ResolvedType; import org.aspectj.weaver.UnresolvedType; import org.aspectj.weaver.VersionedDataInputStream; public class TypePatternList extends PatternNode { private TypePattern[] typePatterns; int ellipsisCount = 0; public static final TypePatternList EMPTY = new TypePatternList(new TypePattern[] {}); public static final TypePatternList ANY = new TypePatternList(new TypePattern[] {new EllipsisTypePattern()}); //can't use TypePattern.ELLIPSIS because of circular static dependency that introduces public TypePatternList() { typePatterns = new TypePattern[0]; ellipsisCount = 0; } public TypePatternList(TypePattern[] arguments) { this.typePatterns = arguments; for (int i=0; i<arguments.length; i++) { if (arguments[i] == TypePattern.ELLIPSIS) ellipsisCount++; } } public TypePatternList(List l) { this((TypePattern[]) l.toArray(new TypePattern[l.size()])); } public int size() { return typePatterns.length; } public TypePattern get(int index) { return typePatterns[index]; } public String toString() { StringBuffer buf = new StringBuffer(); buf.append("("); for (int i=0, len=typePatterns.length; i < len; i++) { TypePattern type = typePatterns[i]; if (i > 0) buf.append(", "); if (type == TypePattern.ELLIPSIS) { buf.append(".."); } else { buf.append(type.toString()); } } buf.append(")"); return buf.toString(); } /* * return true iff this pattern could ever match a signature with the * given number of parameters */ public boolean canMatchSignatureWithNParameters(int numParams) { if (ellipsisCount == 0) { return numParams == size(); } else { return (size() -ellipsisCount) <= numParams; } } //XXX shares much code with WildTypePattern and with NamePattern /** * When called with TypePattern.STATIC this will always return either * FuzzyBoolean.YES or FuzzyBoolean.NO. * * When called with TypePattern.DYNAMIC this could return MAYBE if * at runtime it would be possible for arguments of the given static * types to dynamically match this, but it is not known for certain. * * This method will never return FuzzyBoolean.NEVER */ public FuzzyBoolean matches(ResolvedType[] types, TypePattern.MatchKind kind) { int nameLength = types.length; int patternLength = typePatterns.length; int nameIndex = 0; int patternIndex = 0; if (ellipsisCount == 0) { if (nameLength != patternLength) return FuzzyBoolean.NO; FuzzyBoolean finalReturn = FuzzyBoolean.YES; while (patternIndex < patternLength) { FuzzyBoolean ret = typePatterns[patternIndex++].matches(types[nameIndex++], kind); if (ret == FuzzyBoolean.NO) return ret; if (ret == FuzzyBoolean.MAYBE) finalReturn = ret; } return finalReturn; } else if (ellipsisCount == 1) { if (nameLength < patternLength-1) return FuzzyBoolean.NO; FuzzyBoolean finalReturn = FuzzyBoolean.YES; while (patternIndex < patternLength) { TypePattern p = typePatterns[patternIndex++]; if (p == TypePattern.ELLIPSIS) { nameIndex = nameLength - (patternLength-patternIndex); } else { FuzzyBoolean ret = p.matches(types[nameIndex++], kind); if (ret == FuzzyBoolean.NO) return ret; if (ret == FuzzyBoolean.MAYBE) finalReturn = ret; } } return finalReturn; } else { // System.err.print("match(" + arguments + ", " + types + ") -> "); FuzzyBoolean b = outOfStar(typePatterns, types, 0, 0, patternLength - ellipsisCount, nameLength, ellipsisCount, kind); // System.err.println(b); return b; } } private static FuzzyBoolean outOfStar(final TypePattern[] pattern, final ResolvedType[] target, int pi, int ti, int pLeft, int tLeft, final int starsLeft, TypePattern.MatchKind kind) { if (pLeft > tLeft) return FuzzyBoolean.NO; FuzzyBoolean finalReturn = FuzzyBoolean.YES; while (true) { // invariant: if (tLeft > 0) then (ti < target.length && pi < pattern.length) if (tLeft == 0) return finalReturn; if (pLeft == 0) { if (starsLeft > 0) { return finalReturn; } else { return FuzzyBoolean.NO; } } if (pattern[pi] == TypePattern.ELLIPSIS) { return inStar(pattern, target, pi+1, ti, pLeft, tLeft, starsLeft-1, kind); } FuzzyBoolean ret = pattern[pi].matches(target[ti], kind); if (ret == FuzzyBoolean.NO) return ret; if (ret == FuzzyBoolean.MAYBE) finalReturn = ret; pi++; ti++; pLeft--; tLeft--; } } private static FuzzyBoolean inStar(final TypePattern[] pattern, final ResolvedType[] target, int pi, int ti, final int pLeft, int tLeft, int starsLeft, TypePattern.MatchKind kind) { // invariant: pLeft > 0, so we know we'll run out of stars and find a real char in pattern TypePattern patternChar = pattern[pi]; while (patternChar == TypePattern.ELLIPSIS) { starsLeft--; patternChar = pattern[++pi]; } while (true) { // invariant: if (tLeft > 0) then (ti < target.length) if (pLeft > tLeft) return FuzzyBoolean.NO; FuzzyBoolean ff = patternChar.matches(target[ti], kind); if (ff.maybeTrue()) { FuzzyBoolean xx = outOfStar(pattern, target, pi+1, ti+1, pLeft-1, tLeft-1, starsLeft, kind); if (xx.maybeTrue()) return ff.and(xx); } ti++; tLeft--; } } /** * Return a version of this type pattern list in which all type variable references * are replaced by their corresponding entry in the map * @param typeVariableMap * @return */ public TypePatternList parameterizeWith(Map typeVariableMap) { TypePattern[] parameterizedPatterns = new TypePattern[typePatterns.length]; for (int i = 0; i < parameterizedPatterns.length; i++) { parameterizedPatterns[i] = typePatterns[i].parameterizeWith(typeVariableMap); } return new TypePatternList(parameterizedPatterns); } public TypePatternList resolveBindings(IScope scope, Bindings bindings, boolean allowBinding, boolean requireExactType) { for (int i=0; i<typePatterns.length; i++) { TypePattern p = typePatterns[i]; if (p != null) { typePatterns[i] = typePatterns[i].resolveBindings(scope, bindings, allowBinding, requireExactType); } } return this; } public TypePatternList resolveReferences(IntMap bindings) { int len = typePatterns.length; TypePattern[] ret = new TypePattern[len]; for (int i=0; i < len; i++) { ret[i] = typePatterns[i].remapAdviceFormals(bindings); } return new TypePatternList(ret); } public void postRead(ResolvedType enclosingType) { for (int i=0; i<typePatterns.length; i++) { TypePattern p = typePatterns[i]; p.postRead(enclosingType); } } public boolean equals(Object other) { if (!(other instanceof TypePatternList)) return false; TypePatternList o = (TypePatternList)other; int len = o.typePatterns.length; if (len != this.typePatterns.length) return false; for (int i=0; i<len; i++) { if (!this.typePatterns[i].equals(o.typePatterns[i])) return false; } return true; } public int hashCode() { int result = 41; for (int i = 0, len = typePatterns.length; i < len; i++) { result = 37*result + typePatterns[i].hashCode(); } return result; } public static TypePatternList read(VersionedDataInputStream s, ISourceContext context) throws IOException { short len = s.readShort(); TypePattern[] arguments = new TypePattern[len]; for (int i=0; i<len; i++) { arguments[i] = TypePattern.read(s, context); } TypePatternList ret = new TypePatternList(arguments); ret.readLocation(context, s); return ret; } public void write(DataOutputStream s) throws IOException { s.writeShort(typePatterns.length); for (int i=0; i<typePatterns.length; i++) { typePatterns[i].write(s); } writeLocation(s); } public TypePattern[] getTypePatterns() { return typePatterns; } public Collection getExactTypes() { ArrayList ret = new ArrayList(); for (int i=0; i<typePatterns.length; i++) { UnresolvedType t = typePatterns[i].getExactType(); if (!ResolvedType.isMissing(t)) ret.add(t); } return ret; } public Object accept(PatternNodeVisitor visitor, Object data) { return visitor.visit(this, data); } public Object traverse(PatternNodeVisitor visitor, Object data) { Object ret = accept(visitor,data); for (int i = 0; i < typePatterns.length; i++) { typePatterns[i].traverse(visitor,ret); } return ret; } public boolean areAllExactWithNoSubtypesAllowed() { for (int i = 0; i < typePatterns.length; i++) { TypePattern array_element = typePatterns[i]; if (!(array_element instanceof ExactTypePattern)) { return false; } else { ExactTypePattern etp = (ExactTypePattern) array_element; if (etp.isIncludeSubtypes()) return false; } } return true; } public String[] maybeGetCleanNames() { String[] theParamNames = new String[typePatterns.length]; for (int i = 0; i < typePatterns.length; i++) { TypePattern string = typePatterns[i]; if (!(string instanceof ExactTypePattern)) return null; theParamNames[i] = ((ExactTypePattern)string).getExactType().getName(); } return theParamNames; } }
161,502
Bug 161502 UnsupportedOperationException thrown: unable to parameterize unresolved type: Pjava/util/List<+Ljava/lang/Object; >;
Generic parameters (like List<? extends T>) in pointcuts throw UnsupportedOperationException. java.lang.UnsupportedOperationException at org.aspectj.weaver.UnresolvedType.parameterize(UnresolvedType.java: 220) at org.aspectj.weaver.patterns.ExactTypePattern.parameterizeWith (ExactTypePattern.java:244) at org.aspectj.weaver.patterns.SignaturePattern.parameterizeWith (SignaturePattern.java:265) at org.aspectj.weaver.patterns.KindedPointcut.parameterizeWith (KindedPointcut.java:381) at org.aspectj.weaver.bcel.BcelAdvice.parameterizeWith (BcelAdvice.java:93) at org.aspectj.weaver.ResolvedType.getDeclaredAdvice (ResolvedType.java:710) at org.aspectj.weaver.ResolvedType.getDeclaredShadowMungers (ResolvedType.java:739) at org.aspectj.weaver.ResolvedType.collectShadowMungers (ResolvedType.java:575) at org.aspectj.weaver.ResolvedType.collectCrosscuttingMembers (ResolvedType.java:504) at org.aspectj.weaver.CrosscuttingMembersSet.addOrReplaceAspect (CrosscuttingMembersSet.java:68) at org.aspectj.weaver.CrosscuttingMembersSet.addOrReplaceAspect (CrosscuttingMembersSet.java:57) at org.aspectj.weaver.bcel.BcelWeaver.prepareForWeave(BcelWeaver.java: 450) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.weave (AjCompilerAdapter.java:299) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.afterCompiling (AjCompilerAdapter.java:192) at org.aspectj.ajdt.internal.compiler.CompilerAdapter.ajc $afterReturning$org_aspectj_ajdt_internal_compiler_CompilerAdapter$2 $f9cc9ca0(CompilerAdapter.aj:70) at org.aspectj.org.eclipse.jdt.internal.compiler.Compiler.compile (Compiler.java:367) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.performCompilation (AjBuildManager.java:887) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.doBuild (AjBuildManager.java:244) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.batchBuild (AjBuildManager.java:163) at org.aspectj.ajde.internal.CompilerAdapter.compile (CompilerAdapter.java:122) at org.aspectj.ajde.internal.AspectJBuildManager$CompilerThread.run (AspectJBuildManager.java:191) UnsupportedOperationException thrown: unable to parameterize unresolved type: Pjava/util/List<+Ljava/lang/Object;>; To reproduce this exception compile the following code snippet. import java.util.ArrayList; import java.util.List; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; public class Main { public List<? extends Element> getElements() { return new ArrayList<Element>(); } class Element {}; @Aspect static abstract class Base<T> { @Around("call(List<? extends T> *.*(..))") public List<? extends T> elementList(ProceedingJoinPoint thisJoinPoint) { try { return (List<? extends T>)thisJoinPoint.proceed(); } catch (Throwable e) { throw new RuntimeException(e); } } } @Aspect static class Concrete extends Base<Element> {} public static void main(String[] args) { new Main().getElements(); } }
resolved fixed
7b40e7e
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2006-10-24T12:42:57Z"
"2006-10-19T01:06:40Z"
weaver/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.DataOutputStream; import java.io.IOException; import java.util.Map; import org.aspectj.bridge.IMessage; import org.aspectj.bridge.MessageUtil; import org.aspectj.util.FuzzyBoolean; import org.aspectj.weaver.AnnotatedElement; import org.aspectj.weaver.BCException; import org.aspectj.weaver.ISourceContext; import org.aspectj.weaver.ResolvedType; import org.aspectj.weaver.VersionedDataInputStream; import org.aspectj.weaver.WeaverMessages; import org.aspectj.weaver.World; /** * @author colyer * * TODO To change the template for this generated type comment go to * Window - Preferences - Java - Code Style - Code Templates */ public class WildAnnotationTypePattern extends AnnotationTypePattern { private TypePattern typePattern; private boolean resolved = false; /** * */ public WildAnnotationTypePattern(TypePattern typePattern) { super(); this.typePattern = typePattern; 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) */ public FuzzyBoolean matches(AnnotatedElement annotated) { if (!resolved) { throw new IllegalStateException("Can't match on an unresolved annotation type pattern"); } // 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) */ public void resolve(World world) { // nothing to do... resolved = true; } /** * This can modify in place, or return a new TypePattern if the type changes. */ 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; } ExactAnnotationTypePattern eatp = new ExactAnnotationTypePattern(et.getExactType().resolve(scope.getWorld())); eatp.copyLocationFrom(this); return eatp; } else { return this; } } public AnnotationTypePattern parameterizeWith(Map typeVariableMap) { WildAnnotationTypePattern ret = new WildAnnotationTypePattern(typePattern.parameterizeWith(typeVariableMap)); ret.copyLocationFrom(this); ret.resolved = resolved; return ret; } private static final byte VERSION = 1; // rev if ser. form changes /* (non-Javadoc) * @see org.aspectj.weaver.patterns.PatternNode#write(java.io.DataOutputStream) */ public void write(DataOutputStream s) throws IOException { s.writeByte(AnnotationTypePattern.WILD); s.writeByte(VERSION); typePattern.write(s); writeLocation(s); } public static AnnotationTypePattern read(VersionedDataInputStream s,ISourceContext context) throws IOException { AnnotationTypePattern 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); return ret; } /* (non-Javadoc) * @see java.lang.Object#equals(java.lang.Object) */ public boolean equals(Object obj) { if (!(obj instanceof WildAnnotationTypePattern)) return false; WildAnnotationTypePattern other = (WildAnnotationTypePattern) obj; return other.typePattern.equals(typePattern); } /* (non-Javadoc) * @see java.lang.Object#hashCode() */ public int hashCode() { return 17 + 37*typePattern.hashCode(); } /* (non-Javadoc) * @see java.lang.Object#toString() */ public String toString() { return "@(" + typePattern.toString() + ")"; } public Object accept(PatternNodeVisitor visitor, Object data) { return visitor.visit(this, data); } }
161,502
Bug 161502 UnsupportedOperationException thrown: unable to parameterize unresolved type: Pjava/util/List<+Ljava/lang/Object; >;
Generic parameters (like List<? extends T>) in pointcuts throw UnsupportedOperationException. java.lang.UnsupportedOperationException at org.aspectj.weaver.UnresolvedType.parameterize(UnresolvedType.java: 220) at org.aspectj.weaver.patterns.ExactTypePattern.parameterizeWith (ExactTypePattern.java:244) at org.aspectj.weaver.patterns.SignaturePattern.parameterizeWith (SignaturePattern.java:265) at org.aspectj.weaver.patterns.KindedPointcut.parameterizeWith (KindedPointcut.java:381) at org.aspectj.weaver.bcel.BcelAdvice.parameterizeWith (BcelAdvice.java:93) at org.aspectj.weaver.ResolvedType.getDeclaredAdvice (ResolvedType.java:710) at org.aspectj.weaver.ResolvedType.getDeclaredShadowMungers (ResolvedType.java:739) at org.aspectj.weaver.ResolvedType.collectShadowMungers (ResolvedType.java:575) at org.aspectj.weaver.ResolvedType.collectCrosscuttingMembers (ResolvedType.java:504) at org.aspectj.weaver.CrosscuttingMembersSet.addOrReplaceAspect (CrosscuttingMembersSet.java:68) at org.aspectj.weaver.CrosscuttingMembersSet.addOrReplaceAspect (CrosscuttingMembersSet.java:57) at org.aspectj.weaver.bcel.BcelWeaver.prepareForWeave(BcelWeaver.java: 450) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.weave (AjCompilerAdapter.java:299) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.afterCompiling (AjCompilerAdapter.java:192) at org.aspectj.ajdt.internal.compiler.CompilerAdapter.ajc $afterReturning$org_aspectj_ajdt_internal_compiler_CompilerAdapter$2 $f9cc9ca0(CompilerAdapter.aj:70) at org.aspectj.org.eclipse.jdt.internal.compiler.Compiler.compile (Compiler.java:367) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.performCompilation (AjBuildManager.java:887) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.doBuild (AjBuildManager.java:244) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.batchBuild (AjBuildManager.java:163) at org.aspectj.ajde.internal.CompilerAdapter.compile (CompilerAdapter.java:122) at org.aspectj.ajde.internal.AspectJBuildManager$CompilerThread.run (AspectJBuildManager.java:191) UnsupportedOperationException thrown: unable to parameterize unresolved type: Pjava/util/List<+Ljava/lang/Object;>; To reproduce this exception compile the following code snippet. import java.util.ArrayList; import java.util.List; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; public class Main { public List<? extends Element> getElements() { return new ArrayList<Element>(); } class Element {}; @Aspect static abstract class Base<T> { @Around("call(List<? extends T> *.*(..))") public List<? extends T> elementList(ProceedingJoinPoint thisJoinPoint) { try { return (List<? extends T>)thisJoinPoint.proceed(); } catch (Throwable e) { throw new RuntimeException(e); } } } @Aspect static class Concrete extends Base<Element> {} public static void main(String[] args) { new Main().getElements(); } }
resolved fixed
7b40e7e
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2006-10-24T12:42:57Z"
"2006-10-19T01:06:40Z"
weaver/src/org/aspectj/weaver/patterns/WildTypePattern.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the 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.DataOutputStream; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.StringTokenizer; import org.aspectj.bridge.IMessage; import org.aspectj.bridge.ISourceLocation; import org.aspectj.bridge.Message; import org.aspectj.bridge.MessageUtil; import org.aspectj.util.FileUtil; import org.aspectj.util.FuzzyBoolean; import org.aspectj.weaver.AjAttribute; import org.aspectj.weaver.BCException; import org.aspectj.weaver.BoundedReferenceType; import org.aspectj.weaver.IHasPosition; import org.aspectj.weaver.ISourceContext; import org.aspectj.weaver.ReferenceType; import org.aspectj.weaver.ResolvedType; import org.aspectj.weaver.TypeFactory; import org.aspectj.weaver.TypeVariable; import org.aspectj.weaver.TypeVariableReference; import org.aspectj.weaver.UnresolvedType; import org.aspectj.weaver.UnresolvedTypeVariableReferenceType; import org.aspectj.weaver.VersionedDataInputStream; import org.aspectj.weaver.WeaverMessages; import org.aspectj.weaver.World; /** * The PatternParser always creates WildTypePatterns for type patterns in pointcut * expressions (apart from *, which is sometimes directly turned into TypePattern.ANY). * resolveBindings() tries to work out what we've really got and turn it into a type * pattern that we can use for matching. This will normally be either an ExactTypePattern * or a WildTypePattern. * * Here's how the process pans out for various generic and parameterized patterns: * (see GenericsWildTypePatternResolvingTestCase) * * Foo where Foo exists and is generic * Parser creates WildTypePattern namePatterns={Foo} * resolveBindings resolves Foo to RT(Foo - raw) * return ExactTypePattern(LFoo;) * * Foo<String> where Foo exists and String meets the bounds * Parser creates WildTypePattern namePatterns = {Foo}, typeParameters=WTP{String} * resolveBindings resolves typeParameters to ExactTypePattern(String) * resolves Foo to RT(Foo) * returns ExactTypePattern(PFoo<String>; - parameterized) * * Foo<Str*> where Foo exists and takes one bound * Parser creates WildTypePattern namePatterns = {Foo}, typeParameters=WTP{Str*} * resolveBindings resolves typeParameters to WTP{Str*} * resolves Foo to RT(Foo) * returns WildTypePattern(name = Foo, typeParameters = WTP{Str*} isGeneric=false) * * Fo*<String> * Parser creates WildTypePattern namePatterns = {Fo*}, typeParameters=WTP{String} * resolveBindings resolves typeParameters to ETP{String} * returns WildTypePattern(name = Fo*, typeParameters = ETP{String} isGeneric=false) * * * Foo<?> * * Foo<? extends Number> * * Foo<? extends Number+> * * Foo<? super Number> * */ public class WildTypePattern extends TypePattern { private static final String GENERIC_WILDCARD_CHARACTER = "?"; private NamePattern[] namePatterns; int ellipsisCount; String[] importedPrefixes; String[] knownMatches; int dim; // SECRETAPI - just for testing, turns off boundschecking temporarily... public static boolean boundscheckingoff = false; // these next three are set if the type pattern is constrained by extends or super clauses, in which case the // namePatterns must have length 1 // TODO AMC: read/write/resolve of these fields TypePattern upperBound; // extends Foo TypePattern[] additionalInterfaceBounds; // extends Foo & A,B,C TypePattern lowerBound; // super Foo // if we have type parameters, these fields indicate whether we should be a generic type pattern or a parameterized // type pattern. We can only tell during resolve bindings. private boolean isGeneric = true; WildTypePattern(NamePattern[] namePatterns, boolean includeSubtypes, int dim, boolean isVarArgs, TypePatternList typeParams) { super(includeSubtypes,isVarArgs,typeParams); this.namePatterns = namePatterns; this.dim = dim; ellipsisCount = 0; for (int i=0; i<namePatterns.length; i++) { if (namePatterns[i] == NamePattern.ELLIPSIS) ellipsisCount++; } setLocation(namePatterns[0].getSourceContext(), namePatterns[0].getStart(), namePatterns[namePatterns.length-1].getEnd()); } public WildTypePattern(List names, boolean includeSubtypes, int dim) { this((NamePattern[])names.toArray(new NamePattern[names.size()]), includeSubtypes, dim,false,TypePatternList.EMPTY); } public WildTypePattern(List names, boolean includeSubtypes, int dim, int endPos) { this(names, includeSubtypes, dim); this.end = endPos; } public WildTypePattern(List names, boolean includeSubtypes, int dim, int endPos, boolean isVarArg) { this(names, includeSubtypes, dim); this.end = endPos; this.isVarArgs = isVarArg; } public WildTypePattern( List names, boolean includeSubtypes, int dim, int endPos, boolean isVarArg, TypePatternList typeParams, TypePattern upperBound, TypePattern[] additionalInterfaceBounds, TypePattern lowerBound) { this((NamePattern[])names.toArray(new NamePattern[names.size()]),includeSubtypes,dim,isVarArg,typeParams); this.end = endPos; this.upperBound = upperBound; this.lowerBound = lowerBound; this.additionalInterfaceBounds = additionalInterfaceBounds; } public WildTypePattern( List names, boolean includeSubtypes, int dim, int endPos, boolean isVarArg, TypePatternList typeParams) { this((NamePattern[])names.toArray(new NamePattern[names.size()]),includeSubtypes,dim,isVarArg,typeParams); this.end = endPos; } public NamePattern[] getNamePatterns() { return namePatterns; } public TypePattern getUpperBound() { return upperBound; } public TypePattern getLowerBound() { return lowerBound; } public TypePattern[] getAdditionalIntefaceBounds() { return additionalInterfaceBounds; } // called by parser after parsing a type pattern, must bump dim as well as setting flag public void setIsVarArgs(boolean isVarArgs) { this.isVarArgs = isVarArgs; if (isVarArgs) this.dim += 1; } /* (non-Javadoc) * @see org.aspectj.weaver.patterns.TypePattern#couldEverMatchSameTypesAs(org.aspectj.weaver.patterns.TypePattern) */ protected boolean couldEverMatchSameTypesAs(TypePattern other) { if (super.couldEverMatchSameTypesAs(other)) return true; // false is necessary but not sufficient UnresolvedType otherType = other.getExactType(); if (!ResolvedType.isMissing(otherType)) { if (namePatterns.length > 0) { if (!namePatterns[0].matches(otherType.getName())) return false; } } if (other instanceof WildTypePattern) { WildTypePattern owtp = (WildTypePattern) other; String mySimpleName = namePatterns[0].maybeGetSimpleName(); String yourSimpleName = owtp.namePatterns[0].maybeGetSimpleName(); if (mySimpleName != null && yourSimpleName != null) { return (mySimpleName.startsWith(yourSimpleName) || yourSimpleName.startsWith(mySimpleName)); } } return true; } //XXX inefficient implementation // we don't know whether $ characters are from nested types, or were // part of the declared type name (generated code often uses $s in type // names). More work required on our part to get this right... public static char[][] splitNames(String s, boolean convertDollar) { List ret = new ArrayList(); int startIndex = 0; while (true) { int breakIndex = s.indexOf('.', startIndex); // what about / if (convertDollar && (breakIndex == -1)) breakIndex = s.indexOf('$', startIndex); // we treat $ like . here if (breakIndex == -1) break; char[] name = s.substring(startIndex, breakIndex).toCharArray(); ret.add(name); startIndex = breakIndex+1; } ret.add(s.substring(startIndex).toCharArray()); return (char[][])ret.toArray(new char[ret.size()][]); } /** * @see org.aspectj.weaver.TypePattern#matchesExactly(IType) */ protected boolean matchesExactly(ResolvedType type) { return matchesExactly(type,type); } protected boolean matchesExactly(ResolvedType type, ResolvedType annotatedType) { String targetTypeName = type.getName(); //System.err.println("match: " + targetTypeName + ", " + knownMatches); //Arrays.asList(importedPrefixes)); // Ensure the annotation pattern is resolved annotationPattern.resolve(type.getWorld()); return matchesExactlyByName(targetTypeName,type.isAnonymous(),type.isNested()) && matchesParameters(type,STATIC) && matchesBounds(type,STATIC) && annotationPattern.matches(annotatedType).alwaysTrue(); } // we've matched against the base (or raw) type, but if this type pattern specifies parameters or // type variables we need to make sure we match against them too private boolean matchesParameters(ResolvedType aType, MatchKind staticOrDynamic) { if (!isGeneric && typeParameters.size() > 0) { if(!aType.isParameterizedType()) return false; // we have to match type parameters return typeParameters.matches(aType.getResolvedTypeParameters(), staticOrDynamic).alwaysTrue(); } return true; } // we've matched against the base (or raw) type, but if this type pattern specifies bounds because // it is a ? extends or ? super deal then we have to match them too. private boolean matchesBounds(ResolvedType aType, MatchKind staticOrDynamic) { if (upperBound == null && aType.getUpperBound() != null) { // for upper bound, null can also match against Object - but anything else and we're out. if (!aType.getUpperBound().getName().equals(UnresolvedType.OBJECT.getName())) { return false; } } if (lowerBound == null && aType.getLowerBound() != null) return false; if (upperBound != null) { // match ? extends if (aType.isGenericWildcard() && aType.isSuper()) return false; if (aType.getUpperBound() == null) return false; return upperBound.matches((ResolvedType)aType.getUpperBound(),staticOrDynamic).alwaysTrue(); } if (lowerBound != null) { // match ? super if (!(aType.isGenericWildcard() && aType.isSuper())) return false; return lowerBound.matches((ResolvedType)aType.getLowerBound(),staticOrDynamic).alwaysTrue(); } return true; } /** * Used in conjunction with checks on 'isStar()' to tell you if this pattern represents '*' or '*[]' which are * different ! */ public int getDimensions() { return dim; } public boolean isArray() { return dim > 1; } /** * @param targetTypeName * @return */ private boolean matchesExactlyByName(String targetTypeName, boolean isAnonymous, boolean isNested) { // we deal with parameter matching separately... if (targetTypeName.indexOf('<') != -1) { targetTypeName = targetTypeName.substring(0,targetTypeName.indexOf('<')); } // we deal with bounds matching separately too... if (targetTypeName.startsWith(GENERIC_WILDCARD_CHARACTER)) { targetTypeName = GENERIC_WILDCARD_CHARACTER; } //XXX hack if (knownMatches == null && importedPrefixes == null) { return innerMatchesExactly(targetTypeName,isAnonymous, isNested); } if (isNamePatternStar()) { // we match if the dimensions match int numDimensionsInTargetType = 0; if (dim > 0) { int index; while((index = targetTypeName.indexOf('[')) != -1) { numDimensionsInTargetType++; targetTypeName = targetTypeName.substring(index+1); } if (numDimensionsInTargetType == dim) { return true; } else { return false; } } } // if our pattern is length 1, then known matches are exact matches // if it's longer than that, then known matches are prefixes of a sort if (namePatterns.length == 1) { if (isAnonymous) { // we've already ruled out "*", and no other name pattern should match an anonymous type return false; } for (int i=0, len=knownMatches.length; i < len; i++) { if (knownMatches[i].equals(targetTypeName)) return true; } } else { for (int i=0, len=knownMatches.length; i < len; i++) { String knownPrefix = knownMatches[i] + "$"; if (targetTypeName.startsWith(knownPrefix)) { int pos = lastIndexOfDotOrDollar(knownMatches[i]); if (innerMatchesExactly(targetTypeName.substring(pos+1),isAnonymous,isNested)) { return true; } } } } // if any prefixes match, strip the prefix and check that the rest matches // assumes that prefixes have a dot at the end for (int i=0, len=importedPrefixes.length; i < len; i++) { String prefix = importedPrefixes[i]; //System.err.println("prefix match? " + prefix + " to " + targetTypeName); if (targetTypeName.startsWith(prefix)) { if (innerMatchesExactly(targetTypeName.substring(prefix.length()),isAnonymous,isNested)) { return true; } } } return innerMatchesExactly(targetTypeName,isAnonymous,isNested); } private int lastIndexOfDotOrDollar(String string) { int dot = string.lastIndexOf('.'); int dollar = string.lastIndexOf('$'); return Math.max(dot, dollar); } private boolean innerMatchesExactly(String targetTypeName, boolean isAnonymous, boolean isNested) { //??? doing this everytime is not very efficient char[][] names = splitNames(targetTypeName,isNested); return innerMatchesExactly(names, isAnonymous); } private boolean innerMatchesExactly(char[][] names, boolean isAnonymous) { int namesLength = names.length; int patternsLength = namePatterns.length; int namesIndex = 0; int patternsIndex = 0; if ((!namePatterns[patternsLength-1].isAny()) && isAnonymous) return false; if (ellipsisCount == 0) { if (namesLength != patternsLength) return false; while (patternsIndex < patternsLength) { if (!namePatterns[patternsIndex++].matches(names[namesIndex++])) { return false; } } return true; } else if (ellipsisCount == 1) { if (namesLength < patternsLength-1) return false; while (patternsIndex < patternsLength) { NamePattern p = namePatterns[patternsIndex++]; if (p == NamePattern.ELLIPSIS) { namesIndex = namesLength - (patternsLength-patternsIndex); } else { if (!p.matches(names[namesIndex++])) { return false; } } } return true; } else { // System.err.print("match(\"" + Arrays.asList(namePatterns) + "\", \"" + Arrays.asList(names) + "\") -> "); boolean b = outOfStar(namePatterns, names, 0, 0, patternsLength - ellipsisCount, namesLength, ellipsisCount); // System.err.println(b); return b; } } private static boolean outOfStar(final NamePattern[] pattern, final char[][] target, int pi, int ti, int pLeft, int tLeft, final int starsLeft) { if (pLeft > tLeft) return false; while (true) { // invariant: if (tLeft > 0) then (ti < target.length && pi < pattern.length) if (tLeft == 0) return true; if (pLeft == 0) { return (starsLeft > 0); } if (pattern[pi] == NamePattern.ELLIPSIS) { return inStar(pattern, target, pi+1, ti, pLeft, tLeft, starsLeft-1); } if (! pattern[pi].matches(target[ti])) { return false; } pi++; ti++; pLeft--; tLeft--; } } private static boolean inStar(final NamePattern[] pattern, final char[][] target, int pi, int ti, final int pLeft, int tLeft, int starsLeft) { // invariant: pLeft > 0, so we know we'll run out of stars and find a real char in pattern // of course, we probably can't parse multiple ..'s in a row, but this keeps the algorithm // exactly parallel with that in NamePattern NamePattern patternChar = pattern[pi]; while (patternChar == NamePattern.ELLIPSIS) { starsLeft--; patternChar = pattern[++pi]; } while (true) { // invariant: if (tLeft > 0) then (ti < target.length) if (pLeft > tLeft) return false; if (patternChar.matches(target[ti])) { if (outOfStar(pattern, target, pi+1, ti+1, pLeft-1, tLeft-1, starsLeft)) return true; } ti++; tLeft--; } } /** * @see org.aspectj.weaver.TypePattern#matchesInstanceof(IType) */ public FuzzyBoolean matchesInstanceof(ResolvedType type) { //XXX hack to let unmatched types just silently remain so if (maybeGetSimpleName() != null) return FuzzyBoolean.NO; type.getWorld().getMessageHandler().handleMessage( new Message("can't do instanceof matching on patterns with wildcards", IMessage.ERROR, null, getSourceLocation())); return FuzzyBoolean.NO; } public NamePattern extractName() { if (isIncludeSubtypes() || isVarArgs() || isArray() || (typeParameters.size() > 0)) { // we can't extract a name, the pattern is something like Foo+ and therefore // it is not ok to treat Foo as a method name! return null; } //System.err.println("extract from : " + Arrays.asList(namePatterns)); int len = namePatterns.length; if (len ==1 && !annotationPattern.isAny()) return null; // can't extract NamePattern ret = namePatterns[len-1]; NamePattern[] newNames = new NamePattern[len-1]; System.arraycopy(namePatterns, 0, newNames, 0, len-1); namePatterns = newNames; //System.err.println(" left : " + Arrays.asList(namePatterns)); return ret; } /** * Method maybeExtractName. * @param string * @return boolean */ public boolean maybeExtractName(String string) { int len = namePatterns.length; NamePattern ret = namePatterns[len-1]; String simple = ret.maybeGetSimpleName(); if (simple != null && simple.equals(string)) { extractName(); return true; } return false; } /** * If this type pattern has no '.' or '*' in it, then * return a simple string * * otherwise, this will return null; */ public String maybeGetSimpleName() { if (namePatterns.length == 1) { return namePatterns[0].maybeGetSimpleName(); } return null; } /** * If this type pattern has no '*' or '..' in it */ public String maybeGetCleanName() { if (namePatterns.length == 0) { throw new RuntimeException("bad name: " + namePatterns); } //System.out.println("get clean: " + this); StringBuffer buf = new StringBuffer(); for (int i=0, len=namePatterns.length; i < len; i++) { NamePattern p = namePatterns[i]; String simpleName = p.maybeGetSimpleName(); if (simpleName == null) return null; if (i > 0) buf.append("."); buf.append(simpleName); } //System.out.println(buf); return buf.toString(); } public TypePattern parameterizeWith(Map typeVariableMap) { NamePattern[] newNamePatterns = new NamePattern[namePatterns.length]; for(int i=0; i<namePatterns.length;i++) { newNamePatterns[i] = namePatterns[i]; } if (newNamePatterns.length == 1) { String simpleName = newNamePatterns[0].maybeGetSimpleName(); if (simpleName != null) { if (typeVariableMap.containsKey(simpleName)) { String newName = ((ReferenceType)typeVariableMap.get(simpleName)).getName().replace('$','.'); StringTokenizer strTok = new StringTokenizer(newName,"."); newNamePatterns = new NamePattern[strTok.countTokens()]; int index = 0; while(strTok.hasMoreTokens()) { newNamePatterns[index++] = new NamePattern(strTok.nextToken()); } } } } WildTypePattern ret = new WildTypePattern( newNamePatterns, includeSubtypes, dim, isVarArgs, typeParameters.parameterizeWith(typeVariableMap) ); ret.annotationPattern = this.annotationPattern.parameterizeWith(typeVariableMap); if (additionalInterfaceBounds == null) { ret.additionalInterfaceBounds = null; } else { ret.additionalInterfaceBounds = new TypePattern[additionalInterfaceBounds.length]; for (int i = 0; i < additionalInterfaceBounds.length; i++) { ret.additionalInterfaceBounds[i] = additionalInterfaceBounds[i].parameterizeWith(typeVariableMap); } } ret.upperBound = upperBound != null ? upperBound.parameterizeWith(typeVariableMap) : null; ret.lowerBound = lowerBound != null ? lowerBound.parameterizeWith(typeVariableMap) : null; ret.isGeneric = isGeneric; ret.knownMatches = knownMatches; ret.importedPrefixes = importedPrefixes; ret.copyLocationFrom(this); return ret; } /** * Need to determine if I'm really a pattern or a reference to a formal * * We may wish to further optimize the case of pattern vs. non-pattern * * We will be replaced by what we return */ public TypePattern resolveBindings(IScope scope, Bindings bindings, boolean allowBinding, boolean requireExactType) { if (isNamePatternStar()) { TypePattern anyPattern = maybeResolveToAnyPattern(scope, bindings, allowBinding, requireExactType); if (anyPattern != null) { if (requireExactType) { scope.getWorld().getMessageHandler().handleMessage( MessageUtil.error(WeaverMessages.format(WeaverMessages.WILDCARD_NOT_ALLOWED), getSourceLocation())); return NO; } else { return anyPattern; } } } TypePattern bindingTypePattern = maybeResolveToBindingTypePattern(scope, bindings, allowBinding, requireExactType); if (bindingTypePattern != null) return bindingTypePattern; annotationPattern = annotationPattern.resolveBindings(scope,bindings,allowBinding); // resolve any type parameters if (typeParameters!=null && typeParameters.size()>0) { typeParameters.resolveBindings(scope,bindings,allowBinding,requireExactType); isGeneric = false; } // resolve any bounds if (upperBound != null) upperBound = upperBound.resolveBindings(scope, bindings, allowBinding, requireExactType); if (lowerBound != null) lowerBound = lowerBound.resolveBindings(scope, bindings, allowBinding, requireExactType); // amc - additional interface bounds only needed if we support type vars again. String fullyQualifiedName = maybeGetCleanName(); if (fullyQualifiedName != null) { return resolveBindingsFromFullyQualifiedTypeName(fullyQualifiedName, scope, bindings, allowBinding, requireExactType); } else { if (requireExactType) { scope.getWorld().getMessageHandler().handleMessage( MessageUtil.error(WeaverMessages.format(WeaverMessages.WILDCARD_NOT_ALLOWED), getSourceLocation())); return NO; } importedPrefixes = scope.getImportedPrefixes(); knownMatches = preMatch(scope.getImportedNames()); return this; // pattern contains wildcards so can't be resolved to an ExactTypePattern... //XXX need to implement behavior for Lint.invalidWildcardTypeName } } private TypePattern maybeResolveToAnyPattern(IScope scope, Bindings bindings, boolean allowBinding, boolean requireExactType) { // If there is an annotation specified we have to // use a special variant of Any TypePattern called // AnyWithAnnotation if (annotationPattern == AnnotationTypePattern.ANY) { if (dim == 0 && !isVarArgs && upperBound == null && lowerBound == null && (additionalInterfaceBounds == null || additionalInterfaceBounds.length==0)) { // pr72531 return TypePattern.ANY; //??? loses source location } } else { annotationPattern = annotationPattern.resolveBindings(scope,bindings,allowBinding); AnyWithAnnotationTypePattern ret = new AnyWithAnnotationTypePattern(annotationPattern); ret.setLocation(sourceContext,start,end); return ret; } return null; // can't resolve to a simple "any" pattern } private TypePattern maybeResolveToBindingTypePattern(IScope scope, Bindings bindings, boolean allowBinding, boolean requireExactType) { String simpleName = maybeGetSimpleName(); if (simpleName != null) { FormalBinding formalBinding = scope.lookupFormal(simpleName); if (formalBinding != null) { if (bindings == null) { scope.message(IMessage.ERROR, this, "negation doesn't allow binding"); return this; } if (!allowBinding) { scope.message(IMessage.ERROR, this, "name binding only allowed in target, this, and args pcds"); return this; } BindingTypePattern binding = new BindingTypePattern(formalBinding,isVarArgs); binding.copyLocationFrom(this); bindings.register(binding, scope); return binding; } } return null; // not possible to resolve to a binding type pattern } private TypePattern resolveBindingsFromFullyQualifiedTypeName(String fullyQualifiedName, IScope scope, Bindings bindings, boolean allowBinding, boolean requireExactType) { String originalName = fullyQualifiedName; ResolvedType resolvedTypeInTheWorld = null; UnresolvedType type; //System.out.println("resolve: " + cleanName); //??? this loop has too many inefficiencies to count resolvedTypeInTheWorld = lookupTypeInWorldIncludingPrefixes(scope.getWorld(), fullyQualifiedName, scope.getImportedPrefixes()); if (resolvedTypeInTheWorld.isGenericWildcard()) { type = resolvedTypeInTheWorld; } else { type = lookupTypeInScope(scope, fullyQualifiedName, this); } if ((type instanceof ResolvedType) && ((ResolvedType)type).isMissing()) { return resolveBindingsForMissingType(resolvedTypeInTheWorld, originalName, scope, bindings, allowBinding, requireExactType); } else { return resolveBindingsForExactType(scope,type,fullyQualifiedName,requireExactType); } } private UnresolvedType lookupTypeInScope(IScope scope, String typeName, IHasPosition location) { UnresolvedType type = null; while (ResolvedType.isMissing(type = scope.lookupType(typeName, location))) { int lastDot = typeName.lastIndexOf('.'); if (lastDot == -1) break; typeName = typeName.substring(0, lastDot) + '$' + typeName.substring(lastDot+1); } return type; } /** * Searches the world for the ResolvedType with the given typeName. If one * isn't found then for each of the supplied prefixes, it prepends the typeName * with the prefix and searches the world for the ResolvedType with this new name. * If one still isn't found then a MissingResolvedTypeWithKnownSignature is * returned with the originally requested typeName (this ensures the typeName * makes sense). */ private ResolvedType lookupTypeInWorldIncludingPrefixes(World world, String typeName, String[] prefixes) { ResolvedType ret = lookupTypeInWorld(world, typeName); if (!ret.isMissing()) return ret; ResolvedType retWithPrefix = ret; int counter = 0; while (retWithPrefix.isMissing() && (counter < prefixes.length)) { retWithPrefix = lookupTypeInWorld(world,prefixes[counter] + typeName); counter++; } if (!retWithPrefix.isMissing()) return retWithPrefix; return ret; } private ResolvedType lookupTypeInWorld(World world, String typeName) { UnresolvedType ut = UnresolvedType.forName(typeName); ResolvedType ret = world.resolve(ut,true); while (ret.isMissing()) { int lastDot = typeName.lastIndexOf('.'); if (lastDot == -1) break; typeName = typeName.substring(0, lastDot) + '$' + typeName.substring(lastDot+1); ret = world.resolve(UnresolvedType.forName(typeName),true); } return ret; } private TypePattern resolveBindingsForExactType(IScope scope, UnresolvedType aType, String fullyQualifiedName,boolean requireExactType) { TypePattern ret = null; if (aType.isTypeVariableReference()) { // we have to set the bounds on it based on the bounds of this pattern ret = resolveBindingsForTypeVariable(scope, (UnresolvedTypeVariableReferenceType) aType); } else if (typeParameters.size()>0) { ret = resolveParameterizedType(scope, aType, requireExactType); } else if (upperBound != null || lowerBound != null) { // this must be a generic wildcard with bounds ret = resolveGenericWildcard(scope, aType); } else { if (dim != 0) aType = UnresolvedType.makeArray(aType, dim); ret = new ExactTypePattern(aType,includeSubtypes,isVarArgs); } ret.setAnnotationTypePattern(annotationPattern); ret.copyLocationFrom(this); return ret; } private TypePattern resolveGenericWildcard(IScope scope, UnresolvedType aType) { if (!aType.getSignature().equals(GENERIC_WILDCARD_CHARACTER)) throw new IllegalStateException("Can only have bounds for a generic wildcard"); boolean canBeExact = true; if ((upperBound != null) && ResolvedType.isMissing(upperBound.getExactType())) canBeExact = false; if ((lowerBound != null) && ResolvedType.isMissing(lowerBound.getExactType())) canBeExact = false; if (canBeExact) { ResolvedType type = null; if (upperBound != null) { if (upperBound.isIncludeSubtypes()) { canBeExact = false; } else { ReferenceType upper = (ReferenceType) upperBound.getExactType().resolve(scope.getWorld()); type = new BoundedReferenceType(upper,true,scope.getWorld()); } } else { if (lowerBound.isIncludeSubtypes()) { canBeExact = false; } else { ReferenceType lower = (ReferenceType) lowerBound.getExactType().resolve(scope.getWorld()); type = new BoundedReferenceType(lower,false,scope.getWorld()); } } if (canBeExact) { // might have changed if we find out include subtypes is set on one of the bounds... return new ExactTypePattern(type,includeSubtypes,isVarArgs); } } // we weren't able to resolve to an exact type pattern... // leave as wild type pattern importedPrefixes = scope.getImportedPrefixes(); knownMatches = preMatch(scope.getImportedNames()); return this; } private TypePattern resolveParameterizedType(IScope scope, UnresolvedType aType, boolean requireExactType) { ResolvedType rt = aType.resolve(scope.getWorld()); if (!verifyTypeParameters(rt,scope,requireExactType)) return TypePattern.NO; // messages already isued // Only if the type is exact *and* the type parameters are exact should we create an // ExactTypePattern for this WildTypePattern if (typeParameters.areAllExactWithNoSubtypesAllowed()) { TypePattern[] typePats = typeParameters.getTypePatterns(); UnresolvedType[] typeParameterTypes = new UnresolvedType[typePats.length]; for (int i = 0; i < typeParameterTypes.length; i++) { typeParameterTypes[i] = ((ExactTypePattern)typePats[i]).getExactType(); } // rt could be a parameterized type 156058 if (rt.isParameterizedType()) { rt = rt.getGenericType(); } ResolvedType type = TypeFactory.createParameterizedType(rt, typeParameterTypes, scope.getWorld()); if (isGeneric) type = type.getGenericType(); // UnresolvedType tx = UnresolvedType.forParameterizedTypes(aType,typeParameterTypes); // UnresolvedType type = scope.getWorld().resolve(tx,true); if (dim != 0) type = ResolvedType.makeArray(type, dim); return new ExactTypePattern(type,includeSubtypes,isVarArgs); } else { // AMC... just leave it as a wild type pattern then? importedPrefixes = scope.getImportedPrefixes(); knownMatches = preMatch(scope.getImportedNames()); return this; } } private TypePattern resolveBindingsForMissingType(ResolvedType typeFoundInWholeWorldSearch, String nameWeLookedFor, IScope scope, Bindings bindings, boolean allowBinding, boolean requireExactType) { if (requireExactType) { if (!allowBinding) { scope.getWorld().getMessageHandler().handleMessage( MessageUtil.error(WeaverMessages.format(WeaverMessages.CANT_BIND_TYPE,nameWeLookedFor), getSourceLocation())); } else if (scope.getWorld().getLint().invalidAbsoluteTypeName.isEnabled()) { scope.getWorld().getLint().invalidAbsoluteTypeName.signal(nameWeLookedFor, getSourceLocation()); } return NO; } else if (scope.getWorld().getLint().invalidAbsoluteTypeName.isEnabled()) { // Only put the lint warning out if we can't find it in the world if (typeFoundInWholeWorldSearch.isMissing()) { scope.getWorld().getLint().invalidAbsoluteTypeName.signal(nameWeLookedFor, getSourceLocation()); } } importedPrefixes = scope.getImportedPrefixes(); knownMatches = preMatch(scope.getImportedNames()); return this; } /** * We resolved the type to a type variable declared in the pointcut designator. * Now we have to create either an exact type pattern or a wild type pattern for it, * with upper and lower bounds set accordingly. * XXX none of this stuff gets serialized yet * @param scope * @param tvrType * @return */ private TypePattern resolveBindingsForTypeVariable(IScope scope, UnresolvedTypeVariableReferenceType tvrType) { Bindings emptyBindings = new Bindings(0); if (upperBound != null) { upperBound = upperBound.resolveBindings(scope, emptyBindings, false, false); } if (lowerBound != null) { lowerBound = lowerBound.resolveBindings(scope, emptyBindings, false, false); } if (additionalInterfaceBounds != null) { TypePattern[] resolvedIfBounds = new TypePattern[additionalInterfaceBounds.length]; for (int i = 0; i < resolvedIfBounds.length; i++) { resolvedIfBounds[i] = additionalInterfaceBounds[i].resolveBindings(scope, emptyBindings, false, false); } additionalInterfaceBounds = resolvedIfBounds; } if ( upperBound == null && lowerBound == null && additionalInterfaceBounds == null) { // no bounds to worry about... ResolvedType rType = tvrType.resolve(scope.getWorld()); if (dim != 0) rType = ResolvedType.makeArray(rType, dim); return new ExactTypePattern(rType,includeSubtypes,isVarArgs); } else { // we have to set bounds on the TypeVariable held by tvrType before resolving it boolean canCreateExactTypePattern = true; if (upperBound != null && ResolvedType.isMissing(upperBound.getExactType())) canCreateExactTypePattern = false; if (lowerBound != null && ResolvedType.isMissing(lowerBound.getExactType())) canCreateExactTypePattern = false; if (additionalInterfaceBounds != null) { for (int i = 0; i < additionalInterfaceBounds.length; i++) { if (ResolvedType.isMissing(additionalInterfaceBounds[i].getExactType())) canCreateExactTypePattern = false; } } if (canCreateExactTypePattern) { TypeVariable tv = tvrType.getTypeVariable(); if (upperBound != null) tv.setUpperBound(upperBound.getExactType()); if (lowerBound != null) tv.setLowerBound(lowerBound.getExactType()); if (additionalInterfaceBounds != null) { UnresolvedType[] ifBounds = new UnresolvedType[additionalInterfaceBounds.length]; for (int i = 0; i < ifBounds.length; i++) { ifBounds[i] = additionalInterfaceBounds[i].getExactType(); } tv.setAdditionalInterfaceBounds(ifBounds); } ResolvedType rType = tvrType.resolve(scope.getWorld()); if (dim != 0) rType = ResolvedType.makeArray(rType, dim); return new ExactTypePattern(rType,includeSubtypes,isVarArgs); } return this; // leave as wild type pattern then } } /** * When this method is called, we have resolved the base type to an exact type. * We also have a set of type patterns for the parameters. * Time to perform some basic checks: * - can the base type be parameterized? (is it generic) * - can the type parameter pattern list match the number of parameters on the base type * - do all parameter patterns meet the bounds of the respective type variables * If any of these checks fail, a warning message is issued and we return false. * @return */ private boolean verifyTypeParameters(ResolvedType baseType,IScope scope, boolean requireExactType) { ResolvedType genericType = baseType.getGenericType(); if (genericType == null) { // issue message "does not match because baseType.getName() is not generic" scope.message(MessageUtil.warn( WeaverMessages.format(WeaverMessages.NOT_A_GENERIC_TYPE,baseType.getName()), getSourceLocation())); return false; } int minRequiredTypeParameters = typeParameters.size(); boolean foundEllipsis = false; TypePattern[] typeParamPatterns = typeParameters.getTypePatterns(); for (int i = 0; i < typeParamPatterns.length; i++) { if (typeParamPatterns[i] instanceof WildTypePattern) { WildTypePattern wtp = (WildTypePattern) typeParamPatterns[i]; if (wtp.ellipsisCount > 0) { foundEllipsis = true; minRequiredTypeParameters--; } } } TypeVariable[] tvs = genericType.getTypeVariables(); if ((tvs.length < minRequiredTypeParameters) || (!foundEllipsis && minRequiredTypeParameters != tvs.length)) { // issue message "does not match because wrong no of type params" String msg = WeaverMessages.format(WeaverMessages.INCORRECT_NUMBER_OF_TYPE_ARGUMENTS, genericType.getName(),new Integer(tvs.length)); if (requireExactType) scope.message(MessageUtil.error(msg,getSourceLocation())); else scope.message(MessageUtil.warn(msg,getSourceLocation())); return false; } // now check that each typeParameter pattern, if exact, matches the bounds // of the type variable. // pr133307 - delay verification until type binding completion, these next few lines replace // the call to checkBoundsOK if (!boundscheckingoff) { VerifyBoundsForTypePattern verification = new VerifyBoundsForTypePattern(scope,genericType,requireExactType,typeParameters,getSourceLocation()); scope.getWorld().getCrosscuttingMembersSet().recordNecessaryCheck(verification); } // return checkBoundsOK(scope,genericType,requireExactType); return true; } /** * By capturing the verification in this class, rather than performing it in verifyTypeParameters(), * we can cope with situations where the interactions between generics and declare parents would * otherwise cause us problems. For example, if verifying as we go along we may report a problem * which would have been fixed by a declare parents that we haven't looked at yet. If we * create and store a verification object, we can verify this later when the type system is * considered 'complete' */ static class VerifyBoundsForTypePattern implements IVerificationRequired { private IScope scope; private ResolvedType genericType; private boolean requireExactType; private TypePatternList typeParameters = TypePatternList.EMPTY; private ISourceLocation sLoc; public VerifyBoundsForTypePattern(IScope scope, ResolvedType genericType, boolean requireExactType, TypePatternList typeParameters, ISourceLocation sLoc) { this.scope = scope; this.genericType = genericType; this.requireExactType = requireExactType; this.typeParameters = typeParameters; this.sLoc = sLoc; } public void verify() { TypeVariable[] tvs = genericType.getTypeVariables(); TypePattern[] typeParamPatterns = typeParameters.getTypePatterns(); if (typeParameters.areAllExactWithNoSubtypesAllowed()) { for (int i = 0; i < tvs.length; i++) { UnresolvedType ut = typeParamPatterns[i].getExactType(); boolean continueCheck = true; // FIXME asc dont like this but ok temporary measure. If the type parameter // is itself a type variable (from the generic aspect) then assume it'll be // ok... (see pr112105) Want to break this? Run GenericAspectK test. if (ut.isTypeVariableReference()) { continueCheck = false; } //System.err.println("Verifying "+ut.getName()+" meets bounds for "+tvs[i]); if (continueCheck && !tvs[i].canBeBoundTo(ut.resolve(scope.getWorld()))) { // issue message that type parameter does not meet specification String parameterName = ut.getName(); if (ut.isTypeVariableReference()) parameterName = ((TypeVariableReference)ut).getTypeVariable().getDisplayName(); String msg = WeaverMessages.format( WeaverMessages.VIOLATES_TYPE_VARIABLE_BOUNDS, parameterName, new Integer(i+1), tvs[i].getDisplayName(), genericType.getName()); if (requireExactType) scope.message(MessageUtil.error(msg,sLoc)); else scope.message(MessageUtil.warn(msg,sLoc)); } } } } } // pr133307 - moved to verification object // public boolean checkBoundsOK(IScope scope,ResolvedType genericType,boolean requireExactType) { // if (boundscheckingoff) return true; // TypeVariable[] tvs = genericType.getTypeVariables(); // TypePattern[] typeParamPatterns = typeParameters.getTypePatterns(); // if (typeParameters.areAllExactWithNoSubtypesAllowed()) { // for (int i = 0; i < tvs.length; i++) { // UnresolvedType ut = typeParamPatterns[i].getExactType(); // boolean continueCheck = true; // // FIXME asc dont like this but ok temporary measure. If the type parameter // // is itself a type variable (from the generic aspect) then assume it'll be // // ok... (see pr112105) Want to break this? Run GenericAspectK test. // if (ut.isTypeVariableReference()) { // continueCheck = false; // } // // if (continueCheck && // !tvs[i].canBeBoundTo(ut.resolve(scope.getWorld()))) { // // issue message that type parameter does not meet specification // String parameterName = ut.getName(); // if (ut.isTypeVariableReference()) parameterName = ((TypeVariableReference)ut).getTypeVariable().getDisplayName(); // String msg = // WeaverMessages.format( // WeaverMessages.VIOLATES_TYPE_VARIABLE_BOUNDS, // parameterName, // new Integer(i+1), // tvs[i].getDisplayName(), // genericType.getName()); // if (requireExactType) scope.message(MessageUtil.error(msg,getSourceLocation())); // else scope.message(MessageUtil.warn(msg,getSourceLocation())); // return false; // } // } // } // return true; // } public boolean isStar() { boolean annPatternStar = annotationPattern == AnnotationTypePattern.ANY; return (isNamePatternStar() && annPatternStar); } private boolean isNamePatternStar() { return namePatterns.length == 1 && namePatterns[0].isAny(); } /** * returns those possible matches which I match exactly the last element of */ private String[] preMatch(String[] possibleMatches) { //if (namePatterns.length != 1) return CollectionUtil.NO_STRINGS; List ret = new ArrayList(); for (int i=0, len=possibleMatches.length; i < len; i++) { char[][] names = splitNames(possibleMatches[i],true); //??? not most efficient if (namePatterns[0].matches(names[names.length-1])) { ret.add(possibleMatches[i]); continue; } if (possibleMatches[i].indexOf("$") != -1) { names = splitNames(possibleMatches[i],false); //??? not most efficient if (namePatterns[0].matches(names[names.length-1])) { ret.add(possibleMatches[i]); } } } return (String[])ret.toArray(new String[ret.size()]); } // public void postRead(ResolvedType enclosingType) { // this.importedPrefixes = enclosingType.getImportedPrefixes(); // this.knownNames = prematch(enclosingType.getImportedNames()); // } public String toString() { StringBuffer buf = new StringBuffer(); if (annotationPattern != AnnotationTypePattern.ANY) { buf.append('('); buf.append(annotationPattern.toString()); buf.append(' '); } for (int i=0, len=namePatterns.length; i < len; i++) { NamePattern name = namePatterns[i]; if (name == null) { buf.append("."); } else { if (i > 0) buf.append("."); buf.append(name.toString()); } } if (upperBound != null) { buf.append(" extends "); buf.append(upperBound.toString()); } if (lowerBound != null) { buf.append(" super "); buf.append(lowerBound.toString()); } if (typeParameters!=null && typeParameters.size()!=0) { buf.append("<"); buf.append(typeParameters.toString()); buf.append(">"); } if (includeSubtypes) buf.append('+'); if (isVarArgs) buf.append("..."); if (annotationPattern != AnnotationTypePattern.ANY) { buf.append(')'); } return buf.toString(); } public boolean equals(Object other) { if (!(other instanceof WildTypePattern)) return false; WildTypePattern o = (WildTypePattern)other; int len = o.namePatterns.length; if (len != this.namePatterns.length) return false; if (this.includeSubtypes != o.includeSubtypes) return false; if (this.dim != o.dim) return false; if (this.isVarArgs != o.isVarArgs) return false; if (this.upperBound != null) { if (o.upperBound == null) return false; if (!this.upperBound.equals(o.upperBound)) return false; } else { if (o.upperBound != null) return false; } if (this.lowerBound != null) { if (o.lowerBound == null) return false; if (!this.lowerBound.equals(o.lowerBound)) return false; } else { if (o.lowerBound != null) return false; } if (!typeParameters.equals(o.typeParameters)) return false; for (int i=0; i < len; i++) { if (!o.namePatterns[i].equals(this.namePatterns[i])) return false; } return (o.annotationPattern.equals(this.annotationPattern)); } public int hashCode() { int result = 17; for (int i = 0, len = namePatterns.length; i < len; i++) { result = 37*result + namePatterns[i].hashCode(); } result = 37*result + annotationPattern.hashCode(); if (upperBound != null) result = 37*result + upperBound.hashCode(); if (lowerBound != null) result = 37*result + lowerBound.hashCode(); return result; } private static final byte VERSION = 1; // rev on change /** * @see org.aspectj.weaver.patterns.PatternNode#write(DataOutputStream) */ public void write(DataOutputStream s) throws IOException { s.writeByte(TypePattern.WILD); s.writeByte(VERSION); s.writeShort(namePatterns.length); for (int i = 0; i < namePatterns.length; i++) { namePatterns[i].write(s); } s.writeBoolean(includeSubtypes); s.writeInt(dim); s.writeBoolean(isVarArgs); typeParameters.write(s); // ! change from M2 //??? storing this information with every type pattern is wasteful of .class // file size. Storing it on enclosing types would be more efficient FileUtil.writeStringArray(knownMatches, s); FileUtil.writeStringArray(importedPrefixes, s); writeLocation(s); annotationPattern.write(s); // generics info, new in M3 s.writeBoolean(isGeneric); s.writeBoolean(upperBound != null); if (upperBound != null) upperBound.write(s); s.writeBoolean(lowerBound != null); if (lowerBound != null) lowerBound.write(s); s.writeInt(additionalInterfaceBounds == null ? 0 : additionalInterfaceBounds.length); if (additionalInterfaceBounds != null) { for (int i = 0; i < additionalInterfaceBounds.length; i++) { additionalInterfaceBounds[i].write(s); } } } public static TypePattern read(VersionedDataInputStream s, ISourceContext context) throws IOException { if (s.getMajorVersion()>=AjAttribute.WeaverVersionInfo.WEAVER_VERSION_MAJOR_AJ150) { return readTypePattern150(s,context); } else { return readTypePatternOldStyle(s,context); } } public static TypePattern readTypePattern150(VersionedDataInputStream s, ISourceContext context) throws IOException { byte version = s.readByte(); if (version > VERSION) { throw new BCException("WildTypePattern was written by a more recent version of AspectJ, cannot read"); } int len = s.readShort(); NamePattern[] namePatterns = new NamePattern[len]; for (int i=0; i < len; i++) { namePatterns[i] = NamePattern.read(s); } boolean includeSubtypes = s.readBoolean(); int dim = s.readInt(); boolean varArg = s.readBoolean(); TypePatternList typeParams = TypePatternList.read(s, context); WildTypePattern ret = new WildTypePattern(namePatterns, includeSubtypes, dim, varArg,typeParams); ret.knownMatches = FileUtil.readStringArray(s); ret.importedPrefixes = FileUtil.readStringArray(s); ret.readLocation(context, s); ret.setAnnotationTypePattern(AnnotationTypePattern.read(s,context)); // generics info, new in M3 ret.isGeneric = s.readBoolean(); if (s.readBoolean()) { ret.upperBound = TypePattern.read(s,context); } if (s.readBoolean()) { ret.lowerBound = TypePattern.read(s,context); } int numIfBounds = s.readInt(); if (numIfBounds > 0) { ret.additionalInterfaceBounds = new TypePattern[numIfBounds]; for (int i = 0; i < numIfBounds; i++) { ret.additionalInterfaceBounds[i] = TypePattern.read(s,context); } } return ret; } public static TypePattern readTypePatternOldStyle(VersionedDataInputStream s, ISourceContext context) throws IOException { int len = s.readShort(); NamePattern[] namePatterns = new NamePattern[len]; for (int i=0; i < len; i++) { namePatterns[i] = NamePattern.read(s); } boolean includeSubtypes = s.readBoolean(); int dim = s.readInt(); WildTypePattern ret = new WildTypePattern(namePatterns, includeSubtypes, dim, false,null); ret.knownMatches = FileUtil.readStringArray(s); ret.importedPrefixes = FileUtil.readStringArray(s); ret.readLocation(context, s); return ret; } public Object accept(PatternNodeVisitor visitor, Object data) { return visitor.visit(this, data); } }
161,502
Bug 161502 UnsupportedOperationException thrown: unable to parameterize unresolved type: Pjava/util/List<+Ljava/lang/Object; >;
Generic parameters (like List<? extends T>) in pointcuts throw UnsupportedOperationException. java.lang.UnsupportedOperationException at org.aspectj.weaver.UnresolvedType.parameterize(UnresolvedType.java: 220) at org.aspectj.weaver.patterns.ExactTypePattern.parameterizeWith (ExactTypePattern.java:244) at org.aspectj.weaver.patterns.SignaturePattern.parameterizeWith (SignaturePattern.java:265) at org.aspectj.weaver.patterns.KindedPointcut.parameterizeWith (KindedPointcut.java:381) at org.aspectj.weaver.bcel.BcelAdvice.parameterizeWith (BcelAdvice.java:93) at org.aspectj.weaver.ResolvedType.getDeclaredAdvice (ResolvedType.java:710) at org.aspectj.weaver.ResolvedType.getDeclaredShadowMungers (ResolvedType.java:739) at org.aspectj.weaver.ResolvedType.collectShadowMungers (ResolvedType.java:575) at org.aspectj.weaver.ResolvedType.collectCrosscuttingMembers (ResolvedType.java:504) at org.aspectj.weaver.CrosscuttingMembersSet.addOrReplaceAspect (CrosscuttingMembersSet.java:68) at org.aspectj.weaver.CrosscuttingMembersSet.addOrReplaceAspect (CrosscuttingMembersSet.java:57) at org.aspectj.weaver.bcel.BcelWeaver.prepareForWeave(BcelWeaver.java: 450) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.weave (AjCompilerAdapter.java:299) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.afterCompiling (AjCompilerAdapter.java:192) at org.aspectj.ajdt.internal.compiler.CompilerAdapter.ajc $afterReturning$org_aspectj_ajdt_internal_compiler_CompilerAdapter$2 $f9cc9ca0(CompilerAdapter.aj:70) at org.aspectj.org.eclipse.jdt.internal.compiler.Compiler.compile (Compiler.java:367) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.performCompilation (AjBuildManager.java:887) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.doBuild (AjBuildManager.java:244) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.batchBuild (AjBuildManager.java:163) at org.aspectj.ajde.internal.CompilerAdapter.compile (CompilerAdapter.java:122) at org.aspectj.ajde.internal.AspectJBuildManager$CompilerThread.run (AspectJBuildManager.java:191) UnsupportedOperationException thrown: unable to parameterize unresolved type: Pjava/util/List<+Ljava/lang/Object;>; To reproduce this exception compile the following code snippet. import java.util.ArrayList; import java.util.List; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; public class Main { public List<? extends Element> getElements() { return new ArrayList<Element>(); } class Element {}; @Aspect static abstract class Base<T> { @Around("call(List<? extends T> *.*(..))") public List<? extends T> elementList(ProceedingJoinPoint thisJoinPoint) { try { return (List<? extends T>)thisJoinPoint.proceed(); } catch (Throwable e) { throw new RuntimeException(e); } } } @Aspect static class Concrete extends Base<Element> {} public static void main(String[] args) { new Main().getElements(); } }
resolved fixed
7b40e7e
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2006-10-24T12:42:57Z"
"2006-10-19T01:06:40Z"
weaver/src/org/aspectj/weaver/patterns/WithinAnnotationPointcut.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.DataOutputStream; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map; import org.aspectj.bridge.ISourceLocation; import org.aspectj.bridge.MessageUtil; import org.aspectj.util.FuzzyBoolean; import org.aspectj.weaver.BCException; import org.aspectj.weaver.ISourceContext; import org.aspectj.weaver.IntMap; import org.aspectj.weaver.ResolvedType; import org.aspectj.weaver.Shadow; import org.aspectj.weaver.ShadowMunger; import org.aspectj.weaver.UnresolvedType; import org.aspectj.weaver.VersionedDataInputStream; import org.aspectj.weaver.WeaverMessages; import org.aspectj.weaver.ast.Literal; import org.aspectj.weaver.ast.Test; import org.aspectj.weaver.ast.Var; /** * @author colyer * * TODO To change the template for this generated type comment go to * Window - Preferences - Java - Code Style - Code Templates */ public class WithinAnnotationPointcut extends NameBindingPointcut { private AnnotationTypePattern annotationTypePattern; private ShadowMunger munger; private String declarationText; /** * */ public WithinAnnotationPointcut(AnnotationTypePattern type) { super(); this.annotationTypePattern = type; this.pointcutKind = ATWITHIN; buildDeclarationText(); } public WithinAnnotationPointcut(AnnotationTypePattern type, ShadowMunger munger) { this(type); this.munger = munger; this.pointcutKind = ATWITHIN; } public AnnotationTypePattern getAnnotationTypePattern() { return annotationTypePattern; } public int couldMatchKinds() { return Shadow.ALL_SHADOW_KINDS_BITS; } public Pointcut parameterizeWith(Map typeVariableMap) { WithinAnnotationPointcut ret = new WithinAnnotationPointcut(this.annotationTypePattern.parameterizeWith(typeVariableMap)); ret.copyLocationFrom(this); return ret; } /* (non-Javadoc) * @see org.aspectj.weaver.patterns.Pointcut#fastMatch(org.aspectj.weaver.patterns.FastMatchInfo) */ public FuzzyBoolean fastMatch(FastMatchInfo info) { return annotationTypePattern.fastMatches(info.getType()); } /* (non-Javadoc) * @see org.aspectj.weaver.patterns.Pointcut#match(org.aspectj.weaver.Shadow) */ protected FuzzyBoolean matchInternal(Shadow shadow) { ResolvedType enclosingType = shadow.getIWorld().resolve(shadow.getEnclosingType(),true); if (enclosingType.isMissing()) { shadow.getIWorld().getLint().cantFindType.signal( new String[] {WeaverMessages.format(WeaverMessages.CANT_FIND_TYPE_WITHINPCD, shadow.getEnclosingType().getName())}, shadow.getSourceLocation(), new ISourceLocation[]{getSourceLocation()}); // IMessage msg = new Message( // WeaverMessages.format(WeaverMessages.CANT_FIND_TYPE_WITHINPCD, // shadow.getEnclosingType().getName()), // shadow.getSourceLocation(),true,new ISourceLocation[]{getSourceLocation()}); // shadow.getIWorld().getMessageHandler().handleMessage(msg); } annotationTypePattern.resolve(shadow.getIWorld()); return annotationTypePattern.matches(enclosingType); } /* (non-Javadoc) * @see org.aspectj.weaver.patterns.Pointcut#resolveBindings(org.aspectj.weaver.patterns.IScope, org.aspectj.weaver.patterns.Bindings) */ protected void resolveBindings(IScope scope, Bindings bindings) { if (!scope.getWorld().isInJava5Mode()) { scope.message(MessageUtil.error(WeaverMessages.format(WeaverMessages.ATWITHIN_ONLY_SUPPORTED_AT_JAVA5_LEVEL), getSourceLocation())); return; } annotationTypePattern = (ExactAnnotationTypePattern) annotationTypePattern.resolveBindings(scope,bindings,true); // must be either a Var, or an annotation type pattern } /* (non-Javadoc) * @see org.aspectj.weaver.patterns.Pointcut#concretize1(org.aspectj.weaver.ResolvedType, org.aspectj.weaver.IntMap) */ protected Pointcut concretize1(ResolvedType inAspect, ResolvedType declaringType, IntMap bindings) { ExactAnnotationTypePattern newType = (ExactAnnotationTypePattern) annotationTypePattern.remapAdviceFormals(bindings); Pointcut ret = new WithinAnnotationPointcut(newType, bindings.getEnclosingAdvice()); ret.copyLocationFrom(this); return ret; } /* (non-Javadoc) * @see org.aspectj.weaver.patterns.Pointcut#findResidue(org.aspectj.weaver.Shadow, org.aspectj.weaver.patterns.ExposedState) */ protected Test findResidueInternal(Shadow shadow, ExposedState state) { if (annotationTypePattern instanceof BindingAnnotationTypePattern) { BindingAnnotationTypePattern btp = (BindingAnnotationTypePattern)annotationTypePattern; UnresolvedType annotationType = btp.annotationType; Var var = shadow.getWithinAnnotationVar(annotationType); // This should not happen, we shouldn't have gotten this far // if we weren't going to find the annotation if (var == null) throw new BCException("Impossible! annotation=["+annotationType+ "] shadow=["+shadow+" at "+shadow.getSourceLocation()+ "] pointcut is at ["+getSourceLocation()+"]"); state.set(btp.getFormalIndex(),var); } return match(shadow).alwaysTrue() ? Literal.TRUE : Literal.FALSE; } /* (non-Javadoc) * @see org.aspectj.weaver.patterns.NameBindingPointcut#getBindingAnnotationTypePatterns() */ public List getBindingAnnotationTypePatterns() { if (annotationTypePattern instanceof BindingAnnotationTypePattern) { List l = new ArrayList(); l.add(annotationTypePattern); return l; } else return Collections.EMPTY_LIST; } /* (non-Javadoc) * @see org.aspectj.weaver.patterns.NameBindingPointcut#getBindingTypePatterns() */ public List getBindingTypePatterns() { return Collections.EMPTY_LIST; } /* (non-Javadoc) * @see org.aspectj.weaver.patterns.PatternNode#write(java.io.DataOutputStream) */ public void write(DataOutputStream s) throws IOException { s.writeByte(Pointcut.ATWITHIN); annotationTypePattern.write(s); writeLocation(s); } public static Pointcut read(VersionedDataInputStream s, ISourceContext context) throws IOException { AnnotationTypePattern type = AnnotationTypePattern.read(s, context); WithinAnnotationPointcut ret = new WithinAnnotationPointcut((ExactAnnotationTypePattern)type); ret.readLocation(context, s); return ret; } /* (non-Javadoc) * @see java.lang.Object#equals(java.lang.Object) */ public boolean equals(Object obj) { if (!(obj instanceof WithinAnnotationPointcut)) return false; WithinAnnotationPointcut other = (WithinAnnotationPointcut) obj; return other.annotationTypePattern.equals(this.annotationTypePattern); } /* (non-Javadoc) * @see java.lang.Object#hashCode() */ public int hashCode() { return 17 + 19*annotationTypePattern.hashCode(); } /* (non-Javadoc) * @see java.lang.Object#toString() */ private void buildDeclarationText() { StringBuffer buf = new StringBuffer(); buf.append("@within("); String annPatt = annotationTypePattern.toString(); buf.append(annPatt.startsWith("@") ? annPatt.substring(1) : annPatt); buf.append(")"); this.declarationText = buf.toString(); } public String toString() { return this.declarationText; } public Object accept(PatternNodeVisitor visitor, Object data) { return visitor.visit(this, data); } }
161,502
Bug 161502 UnsupportedOperationException thrown: unable to parameterize unresolved type: Pjava/util/List<+Ljava/lang/Object; >;
Generic parameters (like List<? extends T>) in pointcuts throw UnsupportedOperationException. java.lang.UnsupportedOperationException at org.aspectj.weaver.UnresolvedType.parameterize(UnresolvedType.java: 220) at org.aspectj.weaver.patterns.ExactTypePattern.parameterizeWith (ExactTypePattern.java:244) at org.aspectj.weaver.patterns.SignaturePattern.parameterizeWith (SignaturePattern.java:265) at org.aspectj.weaver.patterns.KindedPointcut.parameterizeWith (KindedPointcut.java:381) at org.aspectj.weaver.bcel.BcelAdvice.parameterizeWith (BcelAdvice.java:93) at org.aspectj.weaver.ResolvedType.getDeclaredAdvice (ResolvedType.java:710) at org.aspectj.weaver.ResolvedType.getDeclaredShadowMungers (ResolvedType.java:739) at org.aspectj.weaver.ResolvedType.collectShadowMungers (ResolvedType.java:575) at org.aspectj.weaver.ResolvedType.collectCrosscuttingMembers (ResolvedType.java:504) at org.aspectj.weaver.CrosscuttingMembersSet.addOrReplaceAspect (CrosscuttingMembersSet.java:68) at org.aspectj.weaver.CrosscuttingMembersSet.addOrReplaceAspect (CrosscuttingMembersSet.java:57) at org.aspectj.weaver.bcel.BcelWeaver.prepareForWeave(BcelWeaver.java: 450) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.weave (AjCompilerAdapter.java:299) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.afterCompiling (AjCompilerAdapter.java:192) at org.aspectj.ajdt.internal.compiler.CompilerAdapter.ajc $afterReturning$org_aspectj_ajdt_internal_compiler_CompilerAdapter$2 $f9cc9ca0(CompilerAdapter.aj:70) at org.aspectj.org.eclipse.jdt.internal.compiler.Compiler.compile (Compiler.java:367) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.performCompilation (AjBuildManager.java:887) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.doBuild (AjBuildManager.java:244) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.batchBuild (AjBuildManager.java:163) at org.aspectj.ajde.internal.CompilerAdapter.compile (CompilerAdapter.java:122) at org.aspectj.ajde.internal.AspectJBuildManager$CompilerThread.run (AspectJBuildManager.java:191) UnsupportedOperationException thrown: unable to parameterize unresolved type: Pjava/util/List<+Ljava/lang/Object;>; To reproduce this exception compile the following code snippet. import java.util.ArrayList; import java.util.List; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; public class Main { public List<? extends Element> getElements() { return new ArrayList<Element>(); } class Element {}; @Aspect static abstract class Base<T> { @Around("call(List<? extends T> *.*(..))") public List<? extends T> elementList(ProceedingJoinPoint thisJoinPoint) { try { return (List<? extends T>)thisJoinPoint.proceed(); } catch (Throwable e) { throw new RuntimeException(e); } } } @Aspect static class Concrete extends Base<Element> {} public static void main(String[] args) { new Main().getElements(); } }
resolved fixed
7b40e7e
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2006-10-24T12:42:57Z"
"2006-10-19T01:06:40Z"
weaver/src/org/aspectj/weaver/patterns/WithinCodeAnnotationPointcut.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.DataOutputStream; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map; import org.aspectj.bridge.MessageUtil; import org.aspectj.util.FuzzyBoolean; import org.aspectj.weaver.AnnotatedElement; import org.aspectj.weaver.BCException; import org.aspectj.weaver.ISourceContext; import org.aspectj.weaver.IntMap; import org.aspectj.weaver.Member; import org.aspectj.weaver.NameMangler; import org.aspectj.weaver.ResolvedMember; import org.aspectj.weaver.ResolvedType; import org.aspectj.weaver.Shadow; import org.aspectj.weaver.ShadowMunger; import org.aspectj.weaver.UnresolvedType; import org.aspectj.weaver.VersionedDataInputStream; import org.aspectj.weaver.WeaverMessages; import org.aspectj.weaver.ast.Literal; import org.aspectj.weaver.ast.Test; import org.aspectj.weaver.ast.Var; /** * @author colyer * * TODO To change the template for this generated type comment go to * Window - Preferences - Java - Code Style - Code Templates */ public class WithinCodeAnnotationPointcut extends NameBindingPointcut { private ExactAnnotationTypePattern annotationTypePattern; private ShadowMunger munger = null; // only set after concretization private String declarationText; private static final int matchedShadowKinds; static { int flags = Shadow.ALL_SHADOW_KINDS_BITS; for (int i = 0; i < Shadow.SHADOW_KINDS.length; i++) { if (Shadow.SHADOW_KINDS[i].isEnclosingKind()) flags -= Shadow.SHADOW_KINDS[i].bit; } matchedShadowKinds=flags; } public WithinCodeAnnotationPointcut(ExactAnnotationTypePattern type) { super(); this.annotationTypePattern = type; this.pointcutKind = Pointcut.ATWITHINCODE; buildDeclarationText(); } public WithinCodeAnnotationPointcut(ExactAnnotationTypePattern type, ShadowMunger munger) { this(type); this.munger = munger; this.pointcutKind = Pointcut.ATWITHINCODE; } public ExactAnnotationTypePattern getAnnotationTypePattern() { return annotationTypePattern; } public int couldMatchKinds() { return matchedShadowKinds; } public Pointcut parameterizeWith(Map typeVariableMap) { WithinCodeAnnotationPointcut ret = new WithinCodeAnnotationPointcut((ExactAnnotationTypePattern)this.annotationTypePattern.parameterizeWith(typeVariableMap)); ret.copyLocationFrom(this); return ret; } /* (non-Javadoc) * @see org.aspectj.weaver.patterns.Pointcut#fastMatch(org.aspectj.weaver.patterns.FastMatchInfo) */ public FuzzyBoolean fastMatch(FastMatchInfo info) { return FuzzyBoolean.MAYBE; } /* (non-Javadoc) * @see org.aspectj.weaver.patterns.Pointcut#match(org.aspectj.weaver.Shadow) */ protected FuzzyBoolean matchInternal(Shadow shadow) { AnnotatedElement toMatchAgainst = null; Member member = shadow.getEnclosingCodeSignature(); ResolvedMember rMember = member.resolve(shadow.getIWorld()); if (rMember == null) { if (member.getName().startsWith(NameMangler.PREFIX)) { return FuzzyBoolean.NO; } shadow.getIWorld().getLint().unresolvableMember.signal(member.toString(), getSourceLocation()); return FuzzyBoolean.NO; } annotationTypePattern.resolve(shadow.getIWorld()); return annotationTypePattern.matches(rMember); } /* (non-Javadoc) * @see org.aspectj.weaver.patterns.Pointcut#resolveBindings(org.aspectj.weaver.patterns.IScope, org.aspectj.weaver.patterns.Bindings) */ protected void resolveBindings(IScope scope, Bindings bindings) { if (!scope.getWorld().isInJava5Mode()) { scope.message(MessageUtil.error(WeaverMessages.format(WeaverMessages.ATWITHINCODE_ONLY_SUPPORTED_AT_JAVA5_LEVEL), getSourceLocation())); return; } annotationTypePattern = (ExactAnnotationTypePattern) annotationTypePattern.resolveBindings(scope,bindings,true); // must be either a Var, or an annotation type pattern } /* (non-Javadoc) * @see org.aspectj.weaver.patterns.Pointcut#concretize1(org.aspectj.weaver.ResolvedType, org.aspectj.weaver.IntMap) */ protected Pointcut concretize1(ResolvedType inAspect, ResolvedType declaringType, IntMap bindings) { ExactAnnotationTypePattern newType = (ExactAnnotationTypePattern) annotationTypePattern.remapAdviceFormals(bindings); Pointcut ret = new WithinCodeAnnotationPointcut(newType, bindings.getEnclosingAdvice()); ret.copyLocationFrom(this); return ret; } /* (non-Javadoc) * @see org.aspectj.weaver.patterns.Pointcut#findResidue(org.aspectj.weaver.Shadow, org.aspectj.weaver.patterns.ExposedState) */ protected Test findResidueInternal(Shadow shadow, ExposedState state) { if (annotationTypePattern instanceof BindingAnnotationTypePattern) { BindingAnnotationTypePattern btp = (BindingAnnotationTypePattern)annotationTypePattern; UnresolvedType annotationType = btp.annotationType; Var var = shadow.getWithinCodeAnnotationVar(annotationType); // This should not happen, we shouldn't have gotten this far // if we weren't going to find the annotation if (var == null) throw new BCException("Impossible! annotation=["+annotationType+ "] shadow=["+shadow+" at "+shadow.getSourceLocation()+ "] pointcut is at ["+getSourceLocation()+"]"); state.set(btp.getFormalIndex(),var); } if (matchInternal(shadow).alwaysTrue()) return Literal.TRUE; else return Literal.FALSE; } /* (non-Javadoc) * @see org.aspectj.weaver.patterns.NameBindingPointcut#getBindingAnnotationTypePatterns() */ public List getBindingAnnotationTypePatterns() { if (annotationTypePattern instanceof BindingAnnotationTypePattern) { List l = new ArrayList(); l.add(annotationTypePattern); return l; } else return Collections.EMPTY_LIST; } /* (non-Javadoc) * @see org.aspectj.weaver.patterns.NameBindingPointcut#getBindingTypePatterns() */ public List getBindingTypePatterns() { return Collections.EMPTY_LIST; } /* (non-Javadoc) * @see org.aspectj.weaver.patterns.PatternNode#write(java.io.DataOutputStream) */ public void write(DataOutputStream s) throws IOException { s.writeByte(Pointcut.ATWITHINCODE); annotationTypePattern.write(s); writeLocation(s); } public static Pointcut read(VersionedDataInputStream s, ISourceContext context) throws IOException { AnnotationTypePattern type = AnnotationTypePattern.read(s, context); WithinCodeAnnotationPointcut ret = new WithinCodeAnnotationPointcut((ExactAnnotationTypePattern)type); ret.readLocation(context, s); return ret; } public boolean equals(Object other) { if (!(other instanceof WithinCodeAnnotationPointcut)) return false; WithinCodeAnnotationPointcut o = (WithinCodeAnnotationPointcut)other; return o.annotationTypePattern.equals(this.annotationTypePattern); } public int hashCode() { int result = 17; result = 23*result + annotationTypePattern.hashCode(); return result; } private void buildDeclarationText() { StringBuffer buf = new StringBuffer(); buf.append("@withincode("); String annPatt = annotationTypePattern.toString(); buf.append(annPatt.startsWith("@") ? annPatt.substring(1) : annPatt); buf.append(")"); this.declarationText = buf.toString(); } public String toString() { return this.declarationText; } public Object accept(PatternNodeVisitor visitor, Object data) { return visitor.visit(this, data); } }
161,502
Bug 161502 UnsupportedOperationException thrown: unable to parameterize unresolved type: Pjava/util/List<+Ljava/lang/Object; >;
Generic parameters (like List<? extends T>) in pointcuts throw UnsupportedOperationException. java.lang.UnsupportedOperationException at org.aspectj.weaver.UnresolvedType.parameterize(UnresolvedType.java: 220) at org.aspectj.weaver.patterns.ExactTypePattern.parameterizeWith (ExactTypePattern.java:244) at org.aspectj.weaver.patterns.SignaturePattern.parameterizeWith (SignaturePattern.java:265) at org.aspectj.weaver.patterns.KindedPointcut.parameterizeWith (KindedPointcut.java:381) at org.aspectj.weaver.bcel.BcelAdvice.parameterizeWith (BcelAdvice.java:93) at org.aspectj.weaver.ResolvedType.getDeclaredAdvice (ResolvedType.java:710) at org.aspectj.weaver.ResolvedType.getDeclaredShadowMungers (ResolvedType.java:739) at org.aspectj.weaver.ResolvedType.collectShadowMungers (ResolvedType.java:575) at org.aspectj.weaver.ResolvedType.collectCrosscuttingMembers (ResolvedType.java:504) at org.aspectj.weaver.CrosscuttingMembersSet.addOrReplaceAspect (CrosscuttingMembersSet.java:68) at org.aspectj.weaver.CrosscuttingMembersSet.addOrReplaceAspect (CrosscuttingMembersSet.java:57) at org.aspectj.weaver.bcel.BcelWeaver.prepareForWeave(BcelWeaver.java: 450) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.weave (AjCompilerAdapter.java:299) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.afterCompiling (AjCompilerAdapter.java:192) at org.aspectj.ajdt.internal.compiler.CompilerAdapter.ajc $afterReturning$org_aspectj_ajdt_internal_compiler_CompilerAdapter$2 $f9cc9ca0(CompilerAdapter.aj:70) at org.aspectj.org.eclipse.jdt.internal.compiler.Compiler.compile (Compiler.java:367) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.performCompilation (AjBuildManager.java:887) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.doBuild (AjBuildManager.java:244) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.batchBuild (AjBuildManager.java:163) at org.aspectj.ajde.internal.CompilerAdapter.compile (CompilerAdapter.java:122) at org.aspectj.ajde.internal.AspectJBuildManager$CompilerThread.run (AspectJBuildManager.java:191) UnsupportedOperationException thrown: unable to parameterize unresolved type: Pjava/util/List<+Ljava/lang/Object;>; To reproduce this exception compile the following code snippet. import java.util.ArrayList; import java.util.List; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; public class Main { public List<? extends Element> getElements() { return new ArrayList<Element>(); } class Element {}; @Aspect static abstract class Base<T> { @Around("call(List<? extends T> *.*(..))") public List<? extends T> elementList(ProceedingJoinPoint thisJoinPoint) { try { return (List<? extends T>)thisJoinPoint.proceed(); } catch (Throwable e) { throw new RuntimeException(e); } } } @Aspect static class Concrete extends Base<Element> {} public static void main(String[] args) { new Main().getElements(); } }
resolved fixed
7b40e7e
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2006-10-24T12:42:57Z"
"2006-10-19T01:06:40Z"
weaver/src/org/aspectj/weaver/patterns/WithinPointcut.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the 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.DataOutputStream; import java.io.IOException; import java.util.Map; import org.aspectj.bridge.ISourceLocation; import org.aspectj.bridge.MessageUtil; import org.aspectj.util.FuzzyBoolean; import org.aspectj.weaver.ISourceContext; import org.aspectj.weaver.IntMap; import org.aspectj.weaver.ResolvedType; import org.aspectj.weaver.Shadow; import org.aspectj.weaver.VersionedDataInputStream; import org.aspectj.weaver.WeaverMessages; import org.aspectj.weaver.ast.Literal; import org.aspectj.weaver.ast.Test; public class WithinPointcut extends Pointcut { private TypePattern typePattern; public WithinPointcut(TypePattern type) { this.typePattern = type; this.pointcutKind = WITHIN; } public TypePattern getTypePattern() { return typePattern; } private FuzzyBoolean isWithinType(ResolvedType type) { while (type != null) { if (typePattern.matchesStatically(type)) { return FuzzyBoolean.YES; } type = type.getDeclaringType(); } return FuzzyBoolean.NO; } public int couldMatchKinds() { return Shadow.ALL_SHADOW_KINDS_BITS; } public Pointcut parameterizeWith(Map typeVariableMap) { WithinPointcut ret = new WithinPointcut(this.typePattern.parameterizeWith(typeVariableMap)); ret.copyLocationFrom(this); return ret; } public FuzzyBoolean fastMatch(FastMatchInfo info) { if (typePattern.annotationPattern instanceof AnyAnnotationTypePattern) { return isWithinType(info.getType()); } return FuzzyBoolean.MAYBE; } protected FuzzyBoolean matchInternal(Shadow shadow) { ResolvedType enclosingType = shadow.getIWorld().resolve(shadow.getEnclosingType(),true); if (enclosingType.isMissing()) { shadow.getIWorld().getLint().cantFindType.signal( new String[] {WeaverMessages.format(WeaverMessages.CANT_FIND_TYPE_WITHINPCD, shadow.getEnclosingType().getName())}, shadow.getSourceLocation(), new ISourceLocation[]{getSourceLocation()}); // IMessage msg = new Message( // WeaverMessages.format(WeaverMessages.CANT_FIND_TYPE_WITHINPCD, // shadow.getEnclosingType().getName()), // shadow.getSourceLocation(),true,new ISourceLocation[]{getSourceLocation()}); // shadow.getIWorld().getMessageHandler().handleMessage(msg); } typePattern.resolve(shadow.getIWorld()); return isWithinType(enclosingType); } public void write(DataOutputStream s) throws IOException { s.writeByte(Pointcut.WITHIN); typePattern.write(s); writeLocation(s); } public static Pointcut read(VersionedDataInputStream s, ISourceContext context) throws IOException { TypePattern type = TypePattern.read(s, context); WithinPointcut ret = new WithinPointcut(type); ret.readLocation(context, s); return ret; } public void resolveBindings(IScope scope, Bindings bindings) { typePattern = typePattern.resolveBindings(scope, bindings, false, false); // look for parameterized type patterns which are not supported... HasThisTypePatternTriedToSneakInSomeGenericOrParameterizedTypePatternMatchingStuffAnywhereVisitor visitor = new HasThisTypePatternTriedToSneakInSomeGenericOrParameterizedTypePatternMatchingStuffAnywhereVisitor(); typePattern.traverse(visitor, null); if (visitor.wellHasItThen/*?*/()) { scope.message(MessageUtil.error(WeaverMessages.format(WeaverMessages.WITHIN_PCD_DOESNT_SUPPORT_PARAMETERS), getSourceLocation())); } } public void postRead(ResolvedType enclosingType) { typePattern.postRead(enclosingType); } public boolean couldEverMatchSameJoinPointsAs(WithinPointcut other) { return typePattern.couldEverMatchSameTypesAs(other.typePattern); } public boolean equals(Object other) { if (!(other instanceof WithinPointcut)) return false; WithinPointcut o = (WithinPointcut)other; return o.typePattern.equals(this.typePattern); } public int hashCode() { int result = 43; result = 37*result + typePattern.hashCode(); return result; } public String toString() { return "within(" + typePattern + ")"; } protected Test findResidueInternal(Shadow shadow, ExposedState state) { return match(shadow).alwaysTrue() ? Literal.TRUE : Literal.FALSE; } public Pointcut concretize1(ResolvedType inAspect, ResolvedType declaringType, IntMap bindings) { Pointcut ret = new WithinPointcut(typePattern); ret.copyLocationFrom(this); return ret; } public Object accept(PatternNodeVisitor visitor, Object data) { return visitor.visit(this, data); } }
161,502
Bug 161502 UnsupportedOperationException thrown: unable to parameterize unresolved type: Pjava/util/List<+Ljava/lang/Object; >;
Generic parameters (like List<? extends T>) in pointcuts throw UnsupportedOperationException. java.lang.UnsupportedOperationException at org.aspectj.weaver.UnresolvedType.parameterize(UnresolvedType.java: 220) at org.aspectj.weaver.patterns.ExactTypePattern.parameterizeWith (ExactTypePattern.java:244) at org.aspectj.weaver.patterns.SignaturePattern.parameterizeWith (SignaturePattern.java:265) at org.aspectj.weaver.patterns.KindedPointcut.parameterizeWith (KindedPointcut.java:381) at org.aspectj.weaver.bcel.BcelAdvice.parameterizeWith (BcelAdvice.java:93) at org.aspectj.weaver.ResolvedType.getDeclaredAdvice (ResolvedType.java:710) at org.aspectj.weaver.ResolvedType.getDeclaredShadowMungers (ResolvedType.java:739) at org.aspectj.weaver.ResolvedType.collectShadowMungers (ResolvedType.java:575) at org.aspectj.weaver.ResolvedType.collectCrosscuttingMembers (ResolvedType.java:504) at org.aspectj.weaver.CrosscuttingMembersSet.addOrReplaceAspect (CrosscuttingMembersSet.java:68) at org.aspectj.weaver.CrosscuttingMembersSet.addOrReplaceAspect (CrosscuttingMembersSet.java:57) at org.aspectj.weaver.bcel.BcelWeaver.prepareForWeave(BcelWeaver.java: 450) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.weave (AjCompilerAdapter.java:299) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.afterCompiling (AjCompilerAdapter.java:192) at org.aspectj.ajdt.internal.compiler.CompilerAdapter.ajc $afterReturning$org_aspectj_ajdt_internal_compiler_CompilerAdapter$2 $f9cc9ca0(CompilerAdapter.aj:70) at org.aspectj.org.eclipse.jdt.internal.compiler.Compiler.compile (Compiler.java:367) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.performCompilation (AjBuildManager.java:887) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.doBuild (AjBuildManager.java:244) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.batchBuild (AjBuildManager.java:163) at org.aspectj.ajde.internal.CompilerAdapter.compile (CompilerAdapter.java:122) at org.aspectj.ajde.internal.AspectJBuildManager$CompilerThread.run (AspectJBuildManager.java:191) UnsupportedOperationException thrown: unable to parameterize unresolved type: Pjava/util/List<+Ljava/lang/Object;>; To reproduce this exception compile the following code snippet. import java.util.ArrayList; import java.util.List; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; public class Main { public List<? extends Element> getElements() { return new ArrayList<Element>(); } class Element {}; @Aspect static abstract class Base<T> { @Around("call(List<? extends T> *.*(..))") public List<? extends T> elementList(ProceedingJoinPoint thisJoinPoint) { try { return (List<? extends T>)thisJoinPoint.proceed(); } catch (Throwable e) { throw new RuntimeException(e); } } } @Aspect static class Concrete extends Base<Element> {} public static void main(String[] args) { new Main().getElements(); } }
resolved fixed
7b40e7e
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2006-10-24T12:42:57Z"
"2006-10-19T01:06:40Z"
weaver/src/org/aspectj/weaver/patterns/WithincodePointcut.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.DataOutputStream; import java.io.IOException; import java.util.Map; import org.aspectj.bridge.MessageUtil; import org.aspectj.util.FuzzyBoolean; import org.aspectj.weaver.ISourceContext; import org.aspectj.weaver.IntMap; import org.aspectj.weaver.ResolvedType; import org.aspectj.weaver.Shadow; import org.aspectj.weaver.VersionedDataInputStream; import org.aspectj.weaver.WeaverMessages; import org.aspectj.weaver.ast.Literal; import org.aspectj.weaver.ast.Test; public class WithincodePointcut extends Pointcut { private SignaturePattern signature; private static final int matchedShadowKinds; static { int flags = Shadow.ALL_SHADOW_KINDS_BITS; for (int i = 0; i < Shadow.SHADOW_KINDS.length; i++) { if (Shadow.SHADOW_KINDS[i].isEnclosingKind()) flags -= Shadow.SHADOW_KINDS[i].bit; } // these next two are needed for inlining of field initializers flags|=Shadow.ConstructorExecution.bit; flags|=Shadow.Initialization.bit; matchedShadowKinds = flags; } public WithincodePointcut(SignaturePattern signature) { this.signature = signature; this.pointcutKind = WITHINCODE; } public SignaturePattern getSignature() { return signature; } public int couldMatchKinds() { return matchedShadowKinds; } public Pointcut parameterizeWith(Map typeVariableMap) { WithincodePointcut ret = new WithincodePointcut(signature.parameterizeWith(typeVariableMap)); ret.copyLocationFrom(this); return ret; } public FuzzyBoolean fastMatch(FastMatchInfo type) { return FuzzyBoolean.MAYBE; } protected FuzzyBoolean matchInternal(Shadow shadow) { //This will not match code in local or anonymous classes as if //they were withincode of the outer signature return FuzzyBoolean.fromBoolean( signature.matches(shadow.getEnclosingCodeSignature(), shadow.getIWorld(), false)); } public void write(DataOutputStream s) throws IOException { s.writeByte(Pointcut.WITHINCODE); signature.write(s); writeLocation(s); } public static Pointcut read(VersionedDataInputStream s, ISourceContext context) throws IOException { WithincodePointcut ret = new WithincodePointcut(SignaturePattern.read(s, context)); ret.readLocation(context, s); return ret; } public void resolveBindings(IScope scope, Bindings bindings) { signature = signature.resolveBindings(scope, bindings); // look for inappropriate use of parameterized types and tell user... HasThisTypePatternTriedToSneakInSomeGenericOrParameterizedTypePatternMatchingStuffAnywhereVisitor visitor = new HasThisTypePatternTriedToSneakInSomeGenericOrParameterizedTypePatternMatchingStuffAnywhereVisitor(); signature.getDeclaringType().traverse(visitor, null); if (visitor.wellHasItThen/*?*/()) { scope.message(MessageUtil.error(WeaverMessages.format(WeaverMessages.WITHINCODE_DOESNT_SUPPORT_PARAMETERIZED_DECLARING_TYPES), getSourceLocation())); } visitor = new HasThisTypePatternTriedToSneakInSomeGenericOrParameterizedTypePatternMatchingStuffAnywhereVisitor(); signature.getThrowsPattern().traverse(visitor, null); if (visitor.wellHasItThen/*?*/()) { scope.message(MessageUtil.error(WeaverMessages.format(WeaverMessages.NO_GENERIC_THROWABLES), getSourceLocation())); } } public void postRead(ResolvedType enclosingType) { signature.postRead(enclosingType); } public boolean equals(Object other) { if (!(other instanceof WithincodePointcut)) return false; WithincodePointcut o = (WithincodePointcut)other; return o.signature.equals(this.signature); } public int hashCode() { int result = 43; result = 37*result + signature.hashCode(); return result; } public String toString() { return "withincode(" + signature + ")"; } protected Test findResidueInternal(Shadow shadow, ExposedState state) { return match(shadow).alwaysTrue() ? Literal.TRUE : Literal.FALSE; } public Pointcut concretize1(ResolvedType inAspect, ResolvedType declaringType, IntMap bindings) { Pointcut ret = new WithincodePointcut(signature); ret.copyLocationFrom(this); return ret; } public Object accept(PatternNodeVisitor visitor, Object data) { return visitor.visit(this, data); } }
164,288
Bug 164288 Can no longer compile JDK 1.5 projects with apsectj for JDeveloper
I am working with AspectJ 1.5.2 in JDeveloper and have found that it is not possible to convince the compiler to use JDK 5 constructs. It appears that there is a method on AjcBuildOptions called getJavaOptionsMap() which is currently implemented to return null in all cases. In CompilerAdapter.configureBuildOptions areound line 358 the code tried to access this object to access whether to use JDK 5 constructs or not. Since the return value is always null the project is never properly configured. I notice that the only other implementation of the root interface is CoreBuildOption which appears to directly return a structure from the eclipse class JavaProject. It would appear that this interface is breaking the rules on abstraction, is this the correct read on the situation? If so the solution would either be to implement a CoreBuildOption class to correctly work with the ADJE project adapter class or alter the code in Compiler adapter to correct use the properties in project adapter. I think that the latter is probably the best as BuildOption assumes a depedency on Eclipse which shouldn't be there. We do currently have customer, one in nato, who are currently having to work around this issue so it would be good to get it resolve for 1.5.3 if possible But I know I am a bit late for that now do to a lost email.
resolved fixed
c54fa62
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2006-11-17T13:45:52Z"
"2006-11-13T09:26:40Z"
ajde/src/org/aspectj/ajde/BuildOptionsAdapter.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 * AMC 01.20.2003 extended for AspectJ 1.1 compiler options * ******************************************************************/ package org.aspectj.ajde; import java.util.Map; import java.util.Set; /** * When a particular option is not set its documented default is used. */ public interface BuildOptionsAdapter { // Version constants public static final String VERSION_13 = "1.3"; public static final String VERSION_14 = "1.4"; public static final String VERSION_15 = "1.5"; public static final String VERSION_16 = "1.6"; // Warning constants public static final String WARN_CONSTRUCTOR_NAME = "constructorName"; public static final String WARN_PACKAGE_DEFAULT_METHOD = "packageDefaultMethod"; public static final String WARN_DEPRECATION = "deprecation"; public static final String WARN_MASKED_CATCH_BLOCKS = "maskedCatchBlocks"; public static final String WARN_UNUSED_LOCALS = "unusedLocals"; public static final String WARN_UNUSED_ARGUMENTS = "unusedArguments"; public static final String WARN_UNUSED_IMPORTS = "unusedImports"; public static final String WARN_SYNTHETIC_ACCESS = "syntheticAccess"; public static final String WARN_ASSERT_IDENITIFIER = "assertIdentifier"; public static final String WARN_NLS = "nonExternalisedString"; // Debug constants public static final String DEBUG_SOURCE = "source"; public static final String DEBUG_LINES = "lines"; public static final String DEBUG_VARS = "vars"; public static final String DEBUG_ALL = "all"; /** * This map shortcuts any other Java-specific options that would get set by return * values from the other methods. * * @return a map of all the java-specific options, null if individual options will be passed */ public Map getJavaOptionsMap(); // /** // * Use javac to generate .class files. The default is "false". // * From -usejavac // * @deprecated Not supported from AspectJ 1.1 onwards // */ // public boolean getUseJavacMode(); // // /** // * Only relevant with Use Javac or Preprocess modes. Specify where to place // * intermediate .java files. The default is "workingdir". // * From -workingdir // * @deprecated Not supported from AspectJ 1.1 onwards // */ // public String getWorkingOutputPath(); // /** // * Generate regular Java code into the Working OutputPath. Don't try to generate // * any .class files. The default is "false". // * From -source // * @deprecated Not supported from AspectJ 1.1 onwards // */ // public boolean getPreprocessMode(); // /** * Specify character encoding used by source files. The default is the current * JVM's default. * From -encoding */ public String getCharacterEncoding(); // /** // * Support assertions as defined in JLS-1.4. The default is "false". // * @deprecated Use getComplianceLevel instead // */ // public boolean getSourceOnePointFourMode(); // /** * Run compiles incrementally. * @since AspectJ 1.1 */ public boolean getIncrementalMode(); // /** // * Be extra-lenient in interpreting the Java specification. The default is "false", // * i.e. "regular" mode. // * From -lenient // * @deprecated Not supported from AspectJ 1.1 onwards // */ // public boolean getLenientSpecMode(); // /** // * Be extra-strict in interpreting the Java specification. The default is "false", // * i.e. "regular" mode. // * From -strict // * @deprecated Not supported from AspectJ 1.1 onwards // */ // public boolean getStrictSpecMode(); // // /** // * Make the use of some features from pre-1.0 versions of AspectJ be warnings to ease // * porting of old code. The default is "false". // * From -porting // * @deprecated Not supported from AspectJ 1.1 onwards // */ // public boolean getPortingMode(); /** * The non-standard, typically prefaced with -X when used with a command line compiler. * The default is no non-standard options. */ public String getNonStandardOptions(); // ---------------------------------- // New options added for AspectJ 1.1 from this point onwards /** * JDK Compliance level to be used by the compiler, either * VERSION_13 or VERSION_14. * From -1.3 / -1.4 */ public String getComplianceLevel(); /** * Source compatibility level, either VERSION_13 or VERSION_14. * From -source (eclipse option) */ public String getSourceCompatibilityLevel(); /** * Optional warnings, empty List is equivalent to -warn:none, * returning null uses eclipse compiler default settings * From -warn:xxx,yyy */ public Set getWarnings(); /** * Debug level. DEBUG_ALL == {SOURCE, LINES, VARS}. * Empty list is equivalent to -g:none, returning * non uses eclipse compiler default settings * From -g:xxx */ public Set getDebugLevel(); /** * No errors generated for unresolved imports * From -noImportError */ public boolean getNoImportError(); /** * Preserve all unused local variables (for debug) * From -preserveAllLocals */ public boolean getPreserveAllLocals(); }
164,288
Bug 164288 Can no longer compile JDK 1.5 projects with apsectj for JDeveloper
I am working with AspectJ 1.5.2 in JDeveloper and have found that it is not possible to convince the compiler to use JDK 5 constructs. It appears that there is a method on AjcBuildOptions called getJavaOptionsMap() which is currently implemented to return null in all cases. In CompilerAdapter.configureBuildOptions areound line 358 the code tried to access this object to access whether to use JDK 5 constructs or not. Since the return value is always null the project is never properly configured. I notice that the only other implementation of the root interface is CoreBuildOption which appears to directly return a structure from the eclipse class JavaProject. It would appear that this interface is breaking the rules on abstraction, is this the correct read on the situation? If so the solution would either be to implement a CoreBuildOption class to correctly work with the ADJE project adapter class or alter the code in Compiler adapter to correct use the properties in project adapter. I think that the latter is probably the best as BuildOption assumes a depedency on Eclipse which shouldn't be there. We do currently have customer, one in nato, who are currently having to work around this issue so it would be good to get it resolve for 1.5.3 if possible But I know I am a bit late for that now do to a lost email.
resolved fixed
c54fa62
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2006-11-17T13:45:52Z"
"2006-11-13T09:26:40Z"
ajde/src/org/aspectj/ajde/internal/CompilerAdapter.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC), * 2003 Contributors. * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Eclipse Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Xerox/PARC initial implementation * AMC 01.20.2003 extended to support new AspectJ 1.1 options, * bugzilla #29769 * ******************************************************************/ package org.aspectj.ajde.internal; import java.io.File; import java.util.*; import org.aspectj.ajde.*; import org.aspectj.ajdt.ajc.*; import org.aspectj.ajdt.internal.core.builder.*; import org.aspectj.bridge.*; import org.aspectj.bridge.context.CompilationAndWeavingContext; import org.aspectj.util.LangUtil; //import org.eclipse.core.runtime.OperationCanceledException; import org.aspectj.org.eclipse.jdt.internal.compiler.impl.CompilerOptions; public class CompilerAdapter { private static final Set DEFAULT__AJDE_WARNINGS; static { DEFAULT__AJDE_WARNINGS = new HashSet(); DEFAULT__AJDE_WARNINGS.add(BuildOptionsAdapter.WARN_ASSERT_IDENITIFIER); DEFAULT__AJDE_WARNINGS.add(BuildOptionsAdapter.WARN_CONSTRUCTOR_NAME); DEFAULT__AJDE_WARNINGS.add(BuildOptionsAdapter.WARN_DEPRECATION); DEFAULT__AJDE_WARNINGS.add(BuildOptionsAdapter.WARN_MASKED_CATCH_BLOCKS); DEFAULT__AJDE_WARNINGS.add(BuildOptionsAdapter.WARN_PACKAGE_DEFAULT_METHOD); DEFAULT__AJDE_WARNINGS.add(BuildOptionsAdapter.WARN_UNUSED_IMPORTS); // DEFAULT__AJDE_WARNINGS.put(BuildOptionsAdapter.WARN_); // DEFAULT__AJDE_WARNINGS.put(BuildOptionsAdapter.WARN_); } // private Map optionsMap; private AjBuildManager buildManager = null; private IMessageHandler messageHandler = null; private BuildNotifierAdapter currNotifier = null; private boolean initialized = false; private boolean structureDirty = true; // set to false in incremental mode to re-do initial build private boolean nextBuild = false; public CompilerAdapter() { super(); } public void nextBuildFresh() { if (nextBuild) { nextBuild = false; } } public void requestCompileExit() { if (currNotifier != null) { currNotifier.cancelBuild(); } else { signalText("unable to cancel build process"); } } public boolean isStructureDirty() { return structureDirty; } public void setStructureDirty(boolean structureDirty) { this.structureDirty = structureDirty; } public boolean compile(String configFile, BuildProgressMonitor progressMonitor, boolean buildModel) { if (configFile == null) { Ajde.getDefault().getErrorHandler().handleError("Tried to build null config file."); } init(); try { CompilationAndWeavingContext.reset(); AjBuildConfig buildConfig = genBuildConfig(configFile); if (buildConfig == null) { return false; } buildConfig.setGenerateModelMode(buildModel); currNotifier = new BuildNotifierAdapter(progressMonitor, buildManager); buildManager.setProgressListener(currNotifier); boolean incrementalEnabled = buildConfig.isIncrementalMode() || buildConfig.isIncrementalFileMode(); boolean successfulBuild; if (incrementalEnabled && nextBuild) { successfulBuild = buildManager.incrementalBuild(buildConfig, messageHandler); } else { if (incrementalEnabled) { nextBuild = incrementalEnabled; } successfulBuild = buildManager.batchBuild(buildConfig, messageHandler); } IncrementalStateManager.recordSuccessfulBuild(configFile,buildManager.getState()); return successfulBuild; // } catch (OperationCanceledException ce) { // Ajde.getDefault().getErrorHandler().handleWarning( // "build cancelled by user"); // return false; } catch (AbortException e) { final IMessage message = e.getIMessage(); if (message == null) { signalThrown(e); } else { String messageText = message.getMessage() + "\n" + CompilationAndWeavingContext.getCurrentContext(); Ajde.getDefault().getErrorHandler().handleError(messageText, message.getThrown()); } return false; } catch (Throwable t) { signalThrown(t); return false; } } /** * Generate AjBuildConfig from the local configFile parameter * plus global project and build options. * Errors signalled using signal... methods. * @param configFile * @return null if invalid configuration, * corresponding AjBuildConfig otherwise */ public AjBuildConfig genBuildConfig(String configFilePath) { init(); File configFile = new File(configFilePath); if (!configFile.exists()) { Ajde.getDefault().getErrorHandler().handleError( "Config file \"" + configFile + "\" does not exist." ); return null; } String[] args = new String[] { "@" + configFile.getAbsolutePath() }; CountingMessageHandler handler = CountingMessageHandler.makeCountingMessageHandler(messageHandler); BuildArgParser parser = new BuildArgParser(handler); AjBuildConfig config = new AjBuildConfig(); parser.populateBuildConfig(config, args, false, configFile); configureBuildOptions(config,Ajde.getDefault().getBuildManager().getBuildOptions(),handler); configureProjectOptions(config, Ajde.getDefault().getProjectProperties()); // !!! not what the API intended // // -- get globals, treat as defaults used if no local values // AjBuildConfig global = new AjBuildConfig(); // // AMC refactored into two methods to populate buildConfig from buildOptions and // // project properties - bugzilla 29769. // BuildOptionsAdapter buildOptions // = Ajde.getDefault().getBuildManager().getBuildOptions(); // if (!configureBuildOptions(/* global */ config, buildOptions, handler)) { // return null; // } // ProjectPropertiesAdapter projectOptions = // Ajde.getDefault().getProjectProperties(); // configureProjectOptions(global, projectOptions); // config.installGlobals(global); ISourceLocation location = null; if (config.getConfigFile() != null) { location = new SourceLocation(config.getConfigFile(), 0); } String message = parser.getOtherMessages(true); if (null != message) { IMessage m = new Message(message, IMessage.ERROR, null, location); handler.handleMessage(m); } // always force model generation in AJDE config.setGenerateModelMode(true); if (Ajde.getDefault().getBuildManager().getBuildOptions().getJavaOptionsMap() != null) { config.getOptions().set(Ajde.getDefault().getBuildManager().getBuildOptions().getJavaOptionsMap()); } return config; // return fixupBuildConfig(config); } // /** // * Fix up build configuration just before using to compile. // * This should be delegated to a BuildAdapter callback (XXX) // * for implementation-specific value checks // * (e.g., to force use of project classpath rather // * than local config classpath). // * This implementation does no checks and returns local. // * @param local the AjBuildConfig generated to validate // * @param global // * @param buildOptions // * @param projectOptions // * @return null if unable to fix problems or fixed AjBuildConfig if no errors // * // */ // protected AjBuildConfig fixupBuildConfig(AjBuildConfig local) { // if (Ajde.getDefault().getBuildManager().getBuildOptions().getJavaOptionsMap() != null) { // local.getJavaOptions().putAll(Ajde.getDefault().getBuildManager().getBuildOptions().getJavaOptionsMap()); // } // return local; // } // /** signal error text to user */ // protected void signalError(String text) { // } // /** signal warning text to user */ // protected void signalWarning(String text) { // // } /** signal text to user */ protected void signalText(String text) { Ajde.getDefault().getIdeUIAdapter().displayStatusInformation(text); } /** signal Throwable to user (summary in GUI, trace to stdout). */ protected void signalThrown(Throwable t) { // nothing to error handler? String text = LangUtil.unqualifiedClassName(t) + " thrown: " + t.getMessage(); Ajde.getDefault().getErrorHandler().handleError(text, t); } /** * Populate options in a build configuration, using the Ajde BuildOptionsAdapter. * Added by AMC 01.20.2003, bugzilla #29769 */ private boolean configureBuildOptions( AjBuildConfig config, BuildOptionsAdapter options, IMessageHandler handler) { LangUtil.throwIaxIfNull(options, "options"); LangUtil.throwIaxIfNull(config, "config"); Map optionsToSet = new HashMap(); LangUtil.throwIaxIfNull(optionsToSet, "javaOptions"); checkNotAskedForJava6Compliance(options); if (options.getSourceCompatibilityLevel() != null && options.getSourceCompatibilityLevel().equals(CompilerOptions.VERSION_1_5)) { optionsToSet.put(CompilerOptions.OPTION_Compliance, CompilerOptions.VERSION_1_5); optionsToSet.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_1_5); } else if (options.getSourceCompatibilityLevel() != null && options.getSourceCompatibilityLevel().equals(CompilerOptions.VERSION_1_4)) { optionsToSet.put(CompilerOptions.OPTION_Compliance, CompilerOptions.VERSION_1_4); optionsToSet.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_1_4); } String enc = options.getCharacterEncoding(); if (!LangUtil.isEmpty(enc)) { optionsToSet.put(CompilerOptions.OPTION_Encoding, enc ); } String compliance = options.getComplianceLevel(); if (!LangUtil.isEmpty(compliance)) { String version = CompilerOptions.VERSION_1_4; if ( compliance.equals( BuildOptionsAdapter.VERSION_13 ) ) { version = CompilerOptions.VERSION_1_3; } optionsToSet.put(CompilerOptions.OPTION_Compliance, version ); optionsToSet.put(CompilerOptions.OPTION_Source, version ); } String sourceLevel = options.getSourceCompatibilityLevel(); if (!LangUtil.isEmpty(sourceLevel)) { String slVersion = CompilerOptions.VERSION_1_4; if ( sourceLevel.equals( BuildOptionsAdapter.VERSION_13 ) ) { slVersion = CompilerOptions.VERSION_1_3; } // never set a lower source level than compliance level // Mik: prepended with 1.5 check if (sourceLevel.equals(CompilerOptions.VERSION_1_5)) { optionsToSet.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_1_5); } else { if (optionsToSet.containsKey(CompilerOptions.OPTION_Compliance)) { String setCompliance = (String) optionsToSet.get(CompilerOptions.OPTION_Compliance); if ( ! (setCompliance.equals(CompilerOptions.VERSION_1_4 ) && slVersion.equals(CompilerOptions.VERSION_1_3)) ) { optionsToSet.put(CompilerOptions.OPTION_Source, slVersion); } } } } Set warnings = options.getWarnings(); if (!LangUtil.isEmpty(warnings)) { // turn off all warnings disableWarnings( optionsToSet ); // then selectively enable those in the set enableWarnings( optionsToSet, warnings ); } else if (warnings == null) { // set default warnings on... enableWarnings( optionsToSet, DEFAULT__AJDE_WARNINGS); } Set debugOptions = options.getDebugLevel(); if (!LangUtil.isEmpty(debugOptions)) { // default is all options on, so just need to selectively // disable boolean sourceLine = false; boolean varAttr = false; boolean lineNo = false; Iterator it = debugOptions.iterator(); while (it.hasNext()){ String debug = (String) it.next(); if ( debug.equals( BuildOptionsAdapter.DEBUG_ALL )) { sourceLine = true; varAttr = true; lineNo = true; } else if ( debug.equals( BuildOptionsAdapter.DEBUG_LINES )) { lineNo = true; } else if ( debug.equals( BuildOptionsAdapter.DEBUG_SOURCE )) { sourceLine = true; } else if ( debug.equals( BuildOptionsAdapter.DEBUG_VARS)) { varAttr = true; } } if (sourceLine) optionsToSet.put(CompilerOptions.OPTION_SourceFileAttribute, CompilerOptions.GENERATE); if (varAttr) optionsToSet.put(CompilerOptions.OPTION_LocalVariableAttribute, CompilerOptions.GENERATE); if (lineNo) optionsToSet.put(CompilerOptions.OPTION_LineNumberAttribute, CompilerOptions.GENERATE); } //XXX we can't turn off import errors in 3.0 stream // if ( options.getNoImportError() ) { // javaOptions.put( CompilerOptions.OPTION_ReportInvalidImport, // CompilerOptions.WARNING); // } if ( options.getPreserveAllLocals() ) { optionsToSet.put( CompilerOptions.OPTION_PreserveUnusedLocal, CompilerOptions.PRESERVE); } if ( !config.isIncrementalMode() && options.getIncrementalMode() ) { config.setIncrementalMode(true); } Map jom = options.getJavaOptionsMap(); if (jom!=null) { String version = (String)jom.get(CompilerOptions.OPTION_Compliance); if (version!=null && version.equals(CompilerOptions.VERSION_1_5)) { config.setBehaveInJava5Way(true); } } config.getOptions().set(optionsToSet); String toAdd = options.getNonStandardOptions(); return LangUtil.isEmpty(toAdd) ? true : configureNonStandardOptions( config, toAdd, handler ); // ignored: lenient, porting, preprocess, strict, usejavac, workingdir } /** * Check that the user hasn't specified Java 6 for the compliance, source and * target levels. If they have then an error is thrown. */ private void checkNotAskedForJava6Compliance(BuildOptionsAdapter options) { // bug 164384 - Throwing an IMessage.ERRROR rather than an IMessage.ABORT // means that we'll continue to try to compile the code. This means that // the user may see other errors (for example, if they're using annotations // then they'll get errors saying that they require 5.0 compliance). // Throwing IMessage.ABORT would prevent this, however, 'abort' is really // for compiler exceptions. String compliance = options.getComplianceLevel(); if (!LangUtil.isEmpty(compliance) && compliance.equals(BuildOptionsAdapter.VERSION_16)){ String msg = "Java 6.0 compliance level is unsupported"; IMessage m = new Message(msg, IMessage.ERROR, null, null); messageHandler.handleMessage(m); return; } String source = options.getSourceCompatibilityLevel(); if (!LangUtil.isEmpty(source) && source.equals(BuildOptionsAdapter.VERSION_16)){ String msg = "Java 6.0 source level is unsupported"; IMessage m = new Message(msg, IMessage.ERROR, null, null); messageHandler.handleMessage(m); return; } Map javaOptions = options.getJavaOptionsMap(); if (javaOptions != null){ String version = (String)javaOptions.get(CompilerOptions.OPTION_Compliance); String sourceVersion = (String)javaOptions.get(CompilerOptions.OPTION_Source); String targetVersion = (String)javaOptions.get(CompilerOptions.OPTION_TargetPlatform); if (version!=null && version.equals(BuildOptionsAdapter.VERSION_16)) { String msg = "Java 6.0 compliance level is unsupported"; IMessage m = new Message(msg, IMessage.ERROR, null, null); messageHandler.handleMessage(m); } else if (sourceVersion!=null && sourceVersion.equals(BuildOptionsAdapter.VERSION_16)) { String msg = "Java 6.0 source level is unsupported"; IMessage m = new Message(msg, IMessage.ERROR, null, null); messageHandler.handleMessage(m); } else if (targetVersion!=null && targetVersion.equals(BuildOptionsAdapter.VERSION_16)) { String msg = "Java 6.0 target level is unsupported"; IMessage m = new Message(msg, IMessage.ERROR, null, null); messageHandler.handleMessage(m); } } } /** * Helper method for configureBuildOptions */ private static void disableWarnings( Map options ) { options.put( CompilerOptions.OPTION_ReportOverridingPackageDefaultMethod, CompilerOptions.IGNORE); options.put( CompilerOptions.OPTION_ReportMethodWithConstructorName, CompilerOptions.IGNORE); options.put( CompilerOptions.OPTION_ReportDeprecation, CompilerOptions.IGNORE); options.put( CompilerOptions.OPTION_ReportHiddenCatchBlock, CompilerOptions.IGNORE); options.put( CompilerOptions.OPTION_ReportUnusedLocal, CompilerOptions.IGNORE); options.put( CompilerOptions.OPTION_ReportUnusedParameter, CompilerOptions.IGNORE); options.put( CompilerOptions.OPTION_ReportSyntheticAccessEmulation, CompilerOptions.IGNORE); options.put( CompilerOptions.OPTION_ReportNonExternalizedStringLiteral, CompilerOptions.IGNORE); options.put( CompilerOptions.OPTION_ReportAssertIdentifier, CompilerOptions.IGNORE); options.put( CompilerOptions.OPTION_ReportUnusedImport, CompilerOptions.IGNORE); } /** * Helper method for configureBuildOptions */ private static void enableWarnings( Map options, Set warnings ) { Iterator it = warnings.iterator(); while (it.hasNext() ) { String thisWarning = (String) it.next(); if ( thisWarning.equals( BuildOptionsAdapter.WARN_ASSERT_IDENITIFIER )) { options.put( CompilerOptions.OPTION_ReportAssertIdentifier, CompilerOptions.WARNING ); } else if ( thisWarning.equals( BuildOptionsAdapter.WARN_CONSTRUCTOR_NAME )) { options.put( CompilerOptions.OPTION_ReportMethodWithConstructorName, CompilerOptions.WARNING ); } else if ( thisWarning.equals( BuildOptionsAdapter.WARN_DEPRECATION )) { options.put( CompilerOptions.OPTION_ReportDeprecation, CompilerOptions.WARNING ); } else if ( thisWarning.equals( BuildOptionsAdapter.WARN_MASKED_CATCH_BLOCKS )) { options.put( CompilerOptions.OPTION_ReportHiddenCatchBlock, CompilerOptions.WARNING ); } else if ( thisWarning.equals( BuildOptionsAdapter.WARN_PACKAGE_DEFAULT_METHOD )) { options.put( CompilerOptions.OPTION_ReportOverridingPackageDefaultMethod, CompilerOptions.WARNING ); } else if ( thisWarning.equals( BuildOptionsAdapter.WARN_SYNTHETIC_ACCESS )) { options.put( CompilerOptions.OPTION_ReportSyntheticAccessEmulation, CompilerOptions.WARNING ); } else if ( thisWarning.equals( BuildOptionsAdapter.WARN_UNUSED_ARGUMENTS )) { options.put( CompilerOptions.OPTION_ReportUnusedParameter, CompilerOptions.WARNING ); } else if ( thisWarning.equals( BuildOptionsAdapter.WARN_UNUSED_IMPORTS )) { options.put( CompilerOptions.OPTION_ReportUnusedImport, CompilerOptions.WARNING ); } else if ( thisWarning.equals( BuildOptionsAdapter.WARN_UNUSED_LOCALS )) { options.put( CompilerOptions.OPTION_ReportUnusedLocal, CompilerOptions.WARNING ); } else if ( thisWarning.equals( BuildOptionsAdapter.WARN_NLS )) { options.put( CompilerOptions.OPTION_ReportNonExternalizedStringLiteral, CompilerOptions.WARNING ); } } } /** Local helper method for splitting option strings */ private static List tokenizeString(String str) { List tokens = new ArrayList(); StringTokenizer tok = new StringTokenizer(str); while ( tok.hasMoreTokens() ) { tokens.add(tok.nextToken()); } return tokens; } /** * Helper method for configure build options. * This reads all command-line options specified * in the non-standard options text entry and * sets any corresponding unset values in config. * @return false if config failed */ private static boolean configureNonStandardOptions( AjBuildConfig config, String nonStdOptions, IMessageHandler messageHandler ) { if (LangUtil.isEmpty(nonStdOptions)) { return true; } // Break a string into a string array of non-standard options. // Allows for one option to include a ' '. i.e. assuming it has been quoted, it // won't accidentally get treated as a pair of options (can be needed for xlint props file option) List tokens = new ArrayList(); int ind = nonStdOptions.indexOf('\"'); int ind2 = nonStdOptions.indexOf('\"',ind+1); if ((ind > -1) && (ind2 > -1)) { // dont tokenize within double quotes String pre = nonStdOptions.substring(0,ind); String quoted = nonStdOptions.substring(ind+1,ind2); String post = nonStdOptions.substring(ind2+1,nonStdOptions.length()); tokens.addAll(tokenizeString(pre)); tokens.add(quoted); tokens.addAll(tokenizeString(post)); } else { tokens.addAll(tokenizeString(nonStdOptions)); } String[] args = (String[])tokens.toArray(new String[]{}); // set the non-standard options in an alternate build config // (we don't want to lose the settings we already have) CountingMessageHandler counter = CountingMessageHandler.makeCountingMessageHandler(messageHandler); AjBuildConfig altConfig = AjdtCommand.genBuildConfig(args, counter); if (counter.hasErrors()) { return false; } // copy globals where local is not set config.installGlobals(altConfig); return true; } /** * Add new options from the ProjectPropertiesAdapter to the configuration. * <ul> * <li>New list entries are added if not duplicates in, * for classpath, aspectpath, injars, inpath and sourceroots</li> * <li>Set only one new entry for output dir or output jar * only if there is no output dir/jar entry in the config</li> * </ul> * Subsequent changes to the ProjectPropertiesAdapter will not affect * the configuration. * <p>Added by AMC 01.20.2003, bugzilla #29769 */ private void configureProjectOptions( AjBuildConfig config, ProjectPropertiesAdapter properties ) { // XXX no error handling in copying project properties // Handle regular classpath String propcp = properties.getClasspath(); if (!LangUtil.isEmpty(propcp)) { StringTokenizer st = new StringTokenizer(propcp, File.pathSeparator); List configClasspath = config.getClasspath(); ArrayList toAdd = new ArrayList(); while (st.hasMoreTokens()) { String entry = st.nextToken(); if (!configClasspath.contains(entry)) { toAdd.add(entry); } } if (0 < toAdd.size()) { ArrayList both = new ArrayList(configClasspath.size() + toAdd.size()); both.addAll(configClasspath); both.addAll(toAdd); config.setClasspath(both); Ajde.getDefault().logEvent("building with classpath: " + both); } } // Handle boot classpath propcp = properties.getBootClasspath(); if (!LangUtil.isEmpty(propcp)) { StringTokenizer st = new StringTokenizer(propcp, File.pathSeparator); List configClasspath = config.getBootclasspath(); ArrayList toAdd = new ArrayList(); while (st.hasMoreTokens()) { String entry = st.nextToken(); if (!configClasspath.contains(entry)) { toAdd.add(entry); } } if (0 < toAdd.size()) { ArrayList both = new ArrayList(configClasspath.size() + toAdd.size()); both.addAll(configClasspath); both.addAll(toAdd); config.setBootclasspath(both); Ajde.getDefault().logEvent("building with boot classpath: " + both); } } // set outputdir and outputjar only if both not set if ((null == config.getOutputDir() && (null == config.getOutputJar()))) { String outPath = properties.getOutputPath(); if (!LangUtil.isEmpty(outPath)) { config.setOutputDir(new File(outPath)); } String outJar = properties.getOutJar(); if (!LangUtil.isEmpty(outJar)) { config.setOutputJar(new File( outJar ) ); } } // set compilation result destination manager if not set OutputLocationManager outputLocationManager = properties.getOutputLocationManager(); if (config.getCompilationResultDestinationManager() == null && outputLocationManager != null) { config.setCompilationResultDestinationManager(new OutputLocationAdapter(outputLocationManager)); } join(config.getSourceRoots(), properties.getSourceRoots()); join(config.getInJars(), properties.getInJars()); join(config.getInpath(),properties.getInpath()); config.setSourcePathResources(properties.getSourcePathResources()); join(config.getAspectpath(), properties.getAspectPath()); } void join(Collection target, Collection source) { // XXX dup Util if ((null == target) || (null == source)) { return; } for (Iterator iter = source.iterator(); iter.hasNext();) { Object next = iter.next(); if (! target.contains(next)) { target.add(next); } } } private void init() { if (!initialized) { // XXX plug into AJDE initialization // Ajde.getDefault().setErrorHandler(new DebugErrorHandler()); if (Ajde.getDefault().getMessageHandler() != null) { this.messageHandler = Ajde.getDefault().getMessageHandler(); } else { this.messageHandler = new AjdeMessageHandler(); } buildManager = new AjBuildManager(messageHandler); buildManager.environmentSupportsIncrementalCompilation(true); // XXX need to remove the properties file each time! initialized = true; } } public void setState(AjState buildState) { buildManager.setState(buildState); buildManager.setStructureModel(buildState.getStructureModel()); } public IMessageHandler getMessageHandler() { if (messageHandler == null) { init(); } return messageHandler; } public boolean wasFullBuild() { return buildManager.wasFullBuild(); } }
164,288
Bug 164288 Can no longer compile JDK 1.5 projects with apsectj for JDeveloper
I am working with AspectJ 1.5.2 in JDeveloper and have found that it is not possible to convince the compiler to use JDK 5 constructs. It appears that there is a method on AjcBuildOptions called getJavaOptionsMap() which is currently implemented to return null in all cases. In CompilerAdapter.configureBuildOptions areound line 358 the code tried to access this object to access whether to use JDK 5 constructs or not. Since the return value is always null the project is never properly configured. I notice that the only other implementation of the root interface is CoreBuildOption which appears to directly return a structure from the eclipse class JavaProject. It would appear that this interface is breaking the rules on abstraction, is this the correct read on the situation? If so the solution would either be to implement a CoreBuildOption class to correctly work with the ADJE project adapter class or alter the code in Compiler adapter to correct use the properties in project adapter. I think that the latter is probably the best as BuildOption assumes a depedency on Eclipse which shouldn't be there. We do currently have customer, one in nato, who are currently having to work around this issue so it would be good to get it resolve for 1.5.3 if possible But I know I am a bit late for that now do to a lost email.
resolved fixed
c54fa62
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2006-11-17T13:45:52Z"
"2006-11-13T09:26:40Z"
ajde/testsrc/org/aspectj/ajde/BuildConfigurationTests.java
/********************************************************************** Copyright (c) 2003 IBM Corporation and others. All rights reserved. This program and the accompanying materials are made available under the terms of the Eclipse Public License v1.0 which accompanies this distribution, and is available at http://www.eclipse.org/legal/epl-v10.html Contributors: Adrian Colyer - initial version ... **********************************************************************/ package org.aspectj.ajde; import java.io.File; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import junit.framework.TestSuite; import org.aspectj.ajde.NullIdeTaskListManager.SourceLineTask; import org.aspectj.ajde.internal.CompilerAdapter; import org.aspectj.ajde.ui.UserPreferencesAdapter; import org.aspectj.ajde.ui.internal.AjcBuildOptions; import org.aspectj.ajde.ui.internal.UserPreferencesStore; import org.aspectj.ajdt.internal.core.builder.AjBuildConfig; import org.aspectj.org.eclipse.jdt.internal.compiler.impl.CompilerOptions; import org.aspectj.util.LangUtil; /** * Tests that a correctly populated AjBuildConfig object is created * in reponse to the setting in BuildOptionsAdapter and * ProjectPropretiesAdapter */ public class BuildConfigurationTests extends AjdeTestCase { private CompilerAdapter compilerAdapter; private AjBuildConfig buildConfig = null; private AjcBuildOptions buildOptions = null; private UserPreferencesAdapter preferencesAdapter = null; private NullIdeProperties projectProperties = null; private NullIdeTaskListManager taskListManager; private static final String configFile = AjdeTests.testDataPath("examples/figures-coverage/all.lst"); public BuildConfigurationTests( String name ) { super( name ); } public static void main(String[] args) { junit.swingui.TestRunner.run(BuildConfigurationTests.class); } public static TestSuite suite() { TestSuite result = new TestSuite(); result.addTestSuite(BuildConfigurationTests.class); return result; } // The tests... public void testCharacterEncoding() { buildOptions.setCharacterEncoding( "UTF-8" ); buildConfig = compilerAdapter.genBuildConfig( configFile ); assertTrue(configFile + " failed", null != buildConfig); Map options = buildConfig.getOptions().getMap(); String encoding = (String) options.get( CompilerOptions.OPTION_Encoding ); assertEquals( "character encoding", "UTF-8", encoding ); } public void testComplianceLevel() { buildOptions.setComplianceLevel( BuildOptionsAdapter.VERSION_14 ); buildConfig = compilerAdapter.genBuildConfig( configFile ); assertTrue(configFile + " failed", null != buildConfig); Map options = buildConfig.getOptions().getMap(); String compliance = (String) options.get(CompilerOptions.OPTION_Compliance); String sourceLevel = (String) options.get(CompilerOptions.OPTION_Source); assertEquals( "compliance level", CompilerOptions.VERSION_1_4, compliance); assertEquals( "source level", CompilerOptions.VERSION_1_4, sourceLevel ); } public void testCompilanceLevelJava6() { buildOptions.setComplianceLevel( BuildOptionsAdapter.VERSION_16 ); buildConfig = compilerAdapter.genBuildConfig( configFile ); assertTrue(configFile + " failed", null != buildConfig); Map options = buildConfig.getOptions().getMap(); String compliance = (String) options.get(CompilerOptions.OPTION_Compliance); String sourceLevel = (String) options.get(CompilerOptions.OPTION_Source); if (Ajde.getDefault().compilerIsJava6Compatible()) { assertEquals("expected compliance level to be 1.6 but found " + compliance, "1.6", compliance); assertEquals("expected source level to be 1.6 but found " + sourceLevel, "1.6", sourceLevel ); assertTrue("expected to 'behaveInJava5Way' but aren't",buildConfig.getBehaveInJava5Way()); } else { List l = taskListManager.getSourceLineTasks(); String expectedError = "Java 6.0 compliance level is unsupported"; String found = ((SourceLineTask)l.get(0)).getContainedMessage().getMessage(); assertEquals("Expected 'Java 6.0 compliance level is unsupported'" + " error message but found " + found ,expectedError,found); } } public void testSourceCompatibilityLevelJava6() { buildOptions.setSourceCompatibilityLevel(BuildOptionsAdapter.VERSION_16 ); buildConfig = compilerAdapter.genBuildConfig( configFile ); assertTrue(configFile + " failed", null != buildConfig); Map options = buildConfig.getOptions().getMap(); String compliance = (String) options.get(CompilerOptions.OPTION_Compliance); String sourceLevel = (String) options.get(CompilerOptions.OPTION_Source); if (Ajde.getDefault().compilerIsJava6Compatible()) { assertEquals("expected compliance level to be 1.6 but found " + compliance, "1.6", compliance); assertEquals("expected source level to be 1.6 but found " + sourceLevel, "1.6", sourceLevel ); assertTrue("expected to 'behaveInJava5Way' but aren't",buildConfig.getBehaveInJava5Way()); } else { List l = taskListManager.getSourceLineTasks(); String expectedError = "Java 6.0 source level is unsupported"; String found = ((SourceLineTask)l.get(0)).getContainedMessage().getMessage(); assertEquals("Expected 'Java 6.0 compliance level is unsupported'" + " error message but found " + found ,expectedError,found); } } public void testSourceCompatibilityLevel() { buildOptions.setComplianceLevel( BuildOptionsAdapter.VERSION_13); buildOptions.setSourceCompatibilityLevel( BuildOptionsAdapter.VERSION_14); buildConfig = compilerAdapter.genBuildConfig( configFile ); assertTrue(configFile + " failed", null != buildConfig); Map options = buildConfig.getOptions().getMap(); String compliance = (String) options.get(CompilerOptions.OPTION_Compliance); String sourceLevel = (String) options.get(CompilerOptions.OPTION_Source); assertEquals( "compliance level", CompilerOptions.VERSION_1_3, compliance); assertEquals( "source level", CompilerOptions.VERSION_1_4, sourceLevel ); } public void testSourceIncompatibilityLevel() { // this config should "fail" and leave source level at 1.4 buildOptions.setComplianceLevel( BuildOptionsAdapter.VERSION_14); buildOptions.setSourceCompatibilityLevel( BuildOptionsAdapter.VERSION_13); buildConfig = compilerAdapter.genBuildConfig( configFile ); assertTrue(configFile + " failed", null != buildConfig); Map options = buildConfig.getOptions().getMap(); String compliance = (String) options.get(CompilerOptions.OPTION_Compliance); String sourceLevel = (String) options.get(CompilerOptions.OPTION_Source); assertEquals( "compliance level", CompilerOptions.VERSION_1_4, compliance); assertEquals( "source level", CompilerOptions.VERSION_1_4, sourceLevel ); } public void testNullWarnings() { buildOptions.setWarnings( null ); buildConfig = compilerAdapter.genBuildConfig( configFile ); assertTrue(configFile + " failed", null != buildConfig); Map options = buildConfig.getOptions().getMap(); // this should leave us with the default warnings assertOptionEquals( "report overriding package default", options, CompilerOptions.OPTION_ReportOverridingPackageDefaultMethod, CompilerOptions.WARNING); assertOptionEquals( "report method with cons name", options, CompilerOptions.OPTION_ReportMethodWithConstructorName, CompilerOptions.WARNING); assertOptionEquals( "report deprecation", options, CompilerOptions.OPTION_ReportDeprecation, CompilerOptions.WARNING); assertOptionEquals( "report hidden catch block", options, CompilerOptions.OPTION_ReportHiddenCatchBlock, CompilerOptions.WARNING); assertOptionEquals( "report unused local", options, CompilerOptions.OPTION_ReportUnusedLocal, CompilerOptions.IGNORE); assertOptionEquals( "report unused param", options, CompilerOptions.OPTION_ReportUnusedParameter, CompilerOptions.IGNORE); assertOptionEquals( "report synthectic access", options, CompilerOptions.OPTION_ReportSyntheticAccessEmulation, CompilerOptions.IGNORE); assertOptionEquals( "report non-externalized string literal", options, CompilerOptions.OPTION_ReportNonExternalizedStringLiteral, CompilerOptions.IGNORE); assertOptionEquals( "report assert identifer", options, CompilerOptions.OPTION_ReportAssertIdentifier, CompilerOptions.WARNING); } // public void testEmptyWarnings() { // buildOptions.setWarnings( new HashSet() ); // buildConfig = compilerAdapter.genBuildConfig( configFile ); // Map options = buildConfig.getJavaOptions(); // // // this should leave us with the user specifiable warnings // // turned off // assertOptionEquals( "report overriding package default", // options, // CompilerOptions.OPTION_ReportOverridingPackageDefaultMethod, // CompilerOptions.WARNING); // assertOptionEquals( "report method with cons name", // options, // CompilerOptions.OPTION_ReportMethodWithConstructorName, // CompilerOptions.WARNING); // assertOptionEquals( "report deprecation", // options, // CompilerOptions.OPTION_ReportDeprecation, // CompilerOptions.WARNING); // assertOptionEquals( "report hidden catch block", // options, // CompilerOptions.OPTION_ReportHiddenCatchBlock, // CompilerOptions.WARNING); // assertOptionEquals( "report unused local", // options, // CompilerOptions.OPTION_ReportUnusedLocal, // CompilerOptions.WARNING); // assertOptionEquals( "report unused param", // options, // CompilerOptions.OPTION_ReportUnusedParameter, // CompilerOptions.WARNING); // assertOptionEquals( "report synthectic access", // options, // CompilerOptions.OPTION_ReportSyntheticAccessEmulation, // CompilerOptions.WARNING); // assertOptionEquals( "report non-externalized string literal", // options, // CompilerOptions.OPTION_ReportNonExternalizedStringLiteral, // CompilerOptions.WARNING); // assertOptionEquals( "report assert identifer", // options, // CompilerOptions.OPTION_ReportAssertIdentifier, // CompilerOptions.WARNING); // } public void testSetOfWarnings() { HashSet warnings = new HashSet(); warnings.add( BuildOptionsAdapter.WARN_ASSERT_IDENITIFIER ); warnings.add( BuildOptionsAdapter.WARN_CONSTRUCTOR_NAME ); warnings.add( BuildOptionsAdapter.WARN_DEPRECATION ); warnings.add( BuildOptionsAdapter.WARN_MASKED_CATCH_BLOCKS ); warnings.add( BuildOptionsAdapter.WARN_PACKAGE_DEFAULT_METHOD ); warnings.add( BuildOptionsAdapter.WARN_SYNTHETIC_ACCESS ); warnings.add( BuildOptionsAdapter.WARN_UNUSED_ARGUMENTS ); warnings.add( BuildOptionsAdapter.WARN_UNUSED_IMPORTS ); warnings.add( BuildOptionsAdapter.WARN_UNUSED_LOCALS ); warnings.add( BuildOptionsAdapter.WARN_NLS ); buildOptions.setWarnings( warnings ); buildConfig = compilerAdapter.genBuildConfig( configFile ); assertTrue(configFile + " failed", null != buildConfig); Map options = buildConfig.getOptions().getMap(); // this should leave us with all the user specifiable warnings // turned on assertOptionEquals( "report overriding package default", options, CompilerOptions.OPTION_ReportOverridingPackageDefaultMethod, CompilerOptions.WARNING); assertOptionEquals( "report method with cons name", options, CompilerOptions.OPTION_ReportMethodWithConstructorName, CompilerOptions.WARNING); assertOptionEquals( "report deprecation", options, CompilerOptions.OPTION_ReportDeprecation, CompilerOptions.WARNING); assertOptionEquals( "report hidden catch block", options, CompilerOptions.OPTION_ReportHiddenCatchBlock, CompilerOptions.WARNING); assertOptionEquals( "report unused local", options, CompilerOptions.OPTION_ReportUnusedLocal, CompilerOptions.WARNING); assertOptionEquals( "report unused param", options, CompilerOptions.OPTION_ReportUnusedParameter, CompilerOptions.WARNING); assertOptionEquals( "report synthectic access", options, CompilerOptions.OPTION_ReportSyntheticAccessEmulation, CompilerOptions.WARNING); assertOptionEquals( "report non-externalized string literal", options, CompilerOptions.OPTION_ReportNonExternalizedStringLiteral, CompilerOptions.WARNING); assertOptionEquals( "report assert identifer", options, CompilerOptions.OPTION_ReportAssertIdentifier, CompilerOptions.WARNING); } public void testNoDebugOptions() { buildOptions.setDebugLevel( null ); buildConfig = compilerAdapter.genBuildConfig( configFile ); assertTrue(configFile + " failed", null != buildConfig); Map options = buildConfig.getOptions().getMap(); // this should leave us with the default debug settings assertOptionEquals( "debug source", options, CompilerOptions.OPTION_SourceFileAttribute, CompilerOptions.GENERATE); assertOptionEquals( "debug lines", options, CompilerOptions.OPTION_LineNumberAttribute, CompilerOptions.GENERATE); assertOptionEquals( "debug vars", options, CompilerOptions.OPTION_LocalVariableAttribute, CompilerOptions.GENERATE); } public void testEmptyDebugOptions() { buildOptions.setDebugLevel( new HashSet() ); buildConfig = compilerAdapter.genBuildConfig( configFile ); assertTrue(configFile + " failed", null != buildConfig); Map options = buildConfig.getOptions().getMap(); // this should leave us with the default debug assertOptionEquals( "debug source", options, CompilerOptions.OPTION_SourceFileAttribute, CompilerOptions.GENERATE); assertOptionEquals( "debug lines", options, CompilerOptions.OPTION_LineNumberAttribute, CompilerOptions.GENERATE); assertOptionEquals( "debug vars", options, CompilerOptions.OPTION_LocalVariableAttribute, CompilerOptions.GENERATE); } public void testDebugAll() { HashSet debugOpts = new HashSet(); debugOpts.add( BuildOptionsAdapter.DEBUG_ALL ); buildOptions.setDebugLevel( debugOpts ); buildConfig = compilerAdapter.genBuildConfig( configFile ); assertTrue(configFile + " failed", null != buildConfig); Map options = buildConfig.getOptions().getMap(); // this should leave us with all debug on assertOptionEquals( "debug source", options, CompilerOptions.OPTION_SourceFileAttribute, CompilerOptions.GENERATE); assertOptionEquals( "debug lines", options, CompilerOptions.OPTION_LineNumberAttribute, CompilerOptions.GENERATE); assertOptionEquals( "debug vars", options, CompilerOptions.OPTION_LocalVariableAttribute, CompilerOptions.GENERATE); } public void testDebugSet() { HashSet debugOpts = new HashSet(); debugOpts.add( BuildOptionsAdapter.DEBUG_SOURCE ); debugOpts.add( BuildOptionsAdapter.DEBUG_VARS ); buildOptions.setDebugLevel( debugOpts ); buildConfig = compilerAdapter.genBuildConfig( configFile ); assertTrue(configFile + " failed", null != buildConfig); Map options = buildConfig.getOptions().getMap(); // this should leave us with all debug on assertOptionEquals( "debug source", options, CompilerOptions.OPTION_SourceFileAttribute, CompilerOptions.GENERATE); assertOptionEquals( "debug lines", options, CompilerOptions.OPTION_LineNumberAttribute, CompilerOptions.GENERATE); assertOptionEquals( "debug vars", options, CompilerOptions.OPTION_LocalVariableAttribute, CompilerOptions.GENERATE); } public void testNoImport() { buildOptions.setNoImportError( true ); buildConfig = compilerAdapter.genBuildConfig( configFile ); assertTrue(configFile + " failed", null != buildConfig); // Map options = buildConfig.getJavaOptions(); // String noImport = (String) options.get( CompilerOptions.OPTION_ReportInvalidImport ); // assertEquals( "no import", CompilerOptions.WARNING, noImport ); // buildOptions.setNoImportError( false ); } public void testPreserveAllLocals() { buildOptions.setPreserveAllLocals( true ); buildConfig = compilerAdapter.genBuildConfig( configFile ); assertTrue(configFile + " failed", null != buildConfig); Map options = buildConfig.getOptions().getMap(); String preserve = (String) options.get( CompilerOptions.OPTION_PreserveUnusedLocal ); assertEquals( "preserve unused", CompilerOptions.PRESERVE, preserve ); } public void testNonStandardOptions() { buildOptions.setNonStandardOptions( "-XterminateAfterCompilation" ); buildConfig = compilerAdapter.genBuildConfig( configFile ); assertTrue(configFile + " failed", null != buildConfig); assertTrue( "XterminateAfterCompilation", buildConfig.isTerminateAfterCompilation() ); buildOptions.setNonStandardOptions( "-XserializableAspects" ); buildConfig = compilerAdapter.genBuildConfig( configFile ); assertTrue( "XserializableAspects", buildConfig.isXserializableAspects() ); buildOptions.setNonStandardOptions( "-XnoInline" ); buildConfig = compilerAdapter.genBuildConfig( configFile ); assertTrue( "XnoInline", buildConfig.isXnoInline()); buildOptions.setNonStandardOptions( "-Xlint" ); buildConfig = compilerAdapter.genBuildConfig( configFile ); assertEquals( "Xlint", AjBuildConfig.AJLINT_DEFAULT, buildConfig.getLintMode()); buildOptions.setNonStandardOptions( "-Xlint:error" ); buildConfig = compilerAdapter.genBuildConfig( configFile ); assertEquals( "Xlint", AjBuildConfig.AJLINT_ERROR, buildConfig.getLintMode()); // XXX test for lintfile // buildOptions.setNonStandardOptions( "-Xlintfile testdata/AspectJBuildManagerTest/lint.properties" ); // buildConfig = compilerAdapter.genBuildConfig( configFile ); // assertEquals( "Xlintfile", new File( "testdata/AspectJBuildManagerTest/lint.properties" ).getAbsolutePath(), // buildConfig.getLintSpecFile().toString()); // and a few options thrown in at once buildOptions.setNonStandardOptions( "-Xlint -XnoInline -XserializableAspects" ); buildConfig = compilerAdapter.genBuildConfig( configFile ); assertTrue(configFile + " failed", null != buildConfig); assertEquals( "Xlint", AjBuildConfig.AJLINT_DEFAULT, buildConfig.getLintMode()); assertTrue( "XnoInline", buildConfig.isXnoInline()); assertTrue( "XserializableAspects", buildConfig.isXserializableAspects() ); } public void testSourceRoots() { Set roots = new HashSet(); projectProperties.setSourceRoots( roots ); buildConfig = compilerAdapter.genBuildConfig( configFile ); assertTrue(configFile + " failed", null != buildConfig); List configRoots = buildConfig.getSourceRoots(); assertTrue( "no source dirs", configRoots.isEmpty() ); File f = new File( AjdeTests.testDataPath("examples/figures/figures-coverage" )); roots.add( f ); buildConfig = compilerAdapter.genBuildConfig( configFile ); assertTrue(configFile + " failed", null != buildConfig); List configRoots2 = buildConfig.getSourceRoots(); assertTrue( "one source dir", configRoots2.size() == 1 ); assertTrue( "source dir", configRoots2.contains(f) ); File f2 = new File( AjdeTests.testDataPath("examples/figures/figures-demo")); roots.add( f2 ); buildConfig = compilerAdapter.genBuildConfig( configFile ); assertTrue(configFile + " failed", null != buildConfig); List configRoots3 = buildConfig.getSourceRoots(); assertTrue( "two source dirs", configRoots3.size() == 2 ); assertTrue( "source dir 1", configRoots3.contains(f) ); assertTrue( "source dir 2", configRoots3.contains(f2) ); } public void testInJars() { Set jars = new HashSet(); projectProperties.setInJars( jars ); buildConfig = compilerAdapter.genBuildConfig( configFile ); assertTrue(configFile + " failed", null != buildConfig); List inJars = buildConfig.getInJars(); assertTrue( "no in jars", inJars.isEmpty() ); File f = new File( "jarone.jar" ); jars.add( f ); buildConfig = compilerAdapter.genBuildConfig( configFile ); assertTrue(configFile + " failed", null != buildConfig); List inJars2 = buildConfig.getInJars(); assertTrue( "one in jar", inJars2.size() == 1 ); assertTrue( "in jar", inJars2.contains(f) ); File f2 = new File( "jartwo.jar" ); jars.add( f2 ); buildConfig = compilerAdapter.genBuildConfig( configFile ); List inJars3 = buildConfig.getInJars(); assertTrue( "two in jars", inJars3.size() == 2 ); assertTrue( "in jar 1", inJars3.contains(f) ); assertTrue( "in jar 2", inJars3.contains(f2) ); } public void testAspectPath() { Set aspects = new HashSet(); projectProperties.setAspectPath( aspects ); buildConfig = compilerAdapter.genBuildConfig( configFile ); assertTrue(configFile + " failed", null != buildConfig); List aPath = buildConfig.getAspectpath(); assertTrue( "no aspect path", aPath.isEmpty() ); File f = new File( "jarone.jar" ); aspects.add( f ); buildConfig = compilerAdapter.genBuildConfig( configFile ); assertTrue(configFile + " failed", null != buildConfig); List aPath2 = buildConfig.getAspectpath(); assertEquals("aspectpath", 1, aPath2.size()); assertTrue( "1 aspectpath", aPath2.contains(f) ); File f2 = new File( "jartwo.jar" ); aspects.add( f2 ); buildConfig = compilerAdapter.genBuildConfig( configFile ); assertTrue(configFile + " failed", null != buildConfig); List aPath3 = buildConfig.getAspectpath(); assertTrue( "two jars in path", aPath3.size() == 2 ); assertTrue( "1 aspectpath", aPath3.contains(f) ); assertTrue( "2 aspectpath", aPath3.contains(f2) ); } public void testOutJar() { String outJar = "mybuild.jar"; projectProperties.setOutJar( outJar ); buildConfig = compilerAdapter.genBuildConfig( configFile ); assertTrue(configFile + " failed", null != buildConfig); assertNotNull("output jar", buildConfig.getOutputJar()); assertEquals( "out jar", outJar, buildConfig.getOutputJar().toString() ); } public void testXHasMember() { buildOptions.setNonStandardOptions("-XhasMember"); buildConfig = compilerAdapter.genBuildConfig( configFile ); assertTrue(configFile + " failed", null != buildConfig); assertTrue( "XhasMember", buildConfig.isXHasMemberEnabled() ); } protected void setUp() throws Exception { preferencesAdapter = new UserPreferencesStore(false); buildOptions = new AjcBuildOptions(preferencesAdapter); compilerAdapter = new CompilerAdapter(); projectProperties = new NullIdeProperties( "" ); taskListManager = new NullIdeTaskListManager(); ErrorHandler handler = new NullIdeErrorHandler(); try { Ajde.init( null, taskListManager, null, projectProperties, buildOptions, null, null, handler); } catch (Throwable t) { String s = "Unable to initialize AJDE " + LangUtil.renderException(t); assertTrue(s, false); } } protected void tearDown() throws Exception { super.tearDown(); preferencesAdapter = null; buildOptions = null; compilerAdapter = null; projectProperties = null; taskListManager = null; } private void assertOptionEquals( String reason, Map options, String optionName, String value) { String mapValue = (String) options.get(optionName); assertEquals( reason, value, mapValue ); } }
165,148
Bug 165148 [ltw] Unnecessary exceptions during concretization of aspects in aop.xml
Due to the mechanism used in ConcreteAspectCodeGen I see a lot of unnecessary exceptions created. The problem is rather than looking up a type to confirm it doesn't exist before defining it, the code uses a resolve() to check if it exists and resolve attempts to build it if it isnt there. Because the classloader will never find an aop.xml defined type (the class doesn't exist anywhere on the classpath), a spurious exception is created and sometimes traced (if collecting a trace). I'm going to change the code to do a lookup, that is all that is really necessary.
resolved fixed
e8d2556
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2006-11-20T13:20:41Z"
"2006-11-20T13:40:00Z"
loadtime/src/org/aspectj/weaver/loadtime/ConcreteAspectCodeGen.java
/******************************************************************************* * Copyright (c) 2005 Contributors. * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Eclipse Public License v1.0 * which accompanies this distribution and is available at * http://eclipse.org/legal/epl-v10.html * * Contributors: * Alexandre Vasseur initial implementation *******************************************************************************/ package org.aspectj.weaver.loadtime; import org.aspectj.apache.bcel.Constants; import org.aspectj.apache.bcel.classfile.JavaClass; import org.aspectj.apache.bcel.generic.InstructionConstants; import org.aspectj.apache.bcel.generic.InstructionList; import org.aspectj.apache.bcel.generic.ObjectType; import org.aspectj.apache.bcel.generic.Type; import org.aspectj.apache.bcel.generic.annotation.AnnotationGen; import org.aspectj.apache.bcel.generic.annotation.ElementNameValuePairGen; import org.aspectj.apache.bcel.generic.annotation.ElementValueGen; import org.aspectj.apache.bcel.generic.annotation.SimpleElementValueGen; import org.aspectj.bridge.IMessage; import org.aspectj.bridge.Message; import org.aspectj.weaver.AnnotationX; import org.aspectj.weaver.ResolvedMember; import org.aspectj.weaver.ResolvedType; import org.aspectj.weaver.UnresolvedType; import org.aspectj.weaver.World; import org.aspectj.weaver.bcel.BcelPerClauseAspectAdder; import org.aspectj.weaver.bcel.BcelWorld; import org.aspectj.weaver.bcel.LazyClassGen; import org.aspectj.weaver.bcel.LazyMethodGen; import org.aspectj.weaver.loadtime.definition.Definition; import org.aspectj.weaver.patterns.PerClause; import org.aspectj.weaver.patterns.PerSingleton; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; /** * Generates bytecode for concrete-aspect * <p/> * The concrete aspect is @AspectJ code generated. As it is build during aop.xml definitions registration * we perform the type munging for perclause ie aspectOf artifact directly, instead of waiting for it * to go thru the weaver (that we are in the middle of configuring). * * @author <a href="mailto:alex AT gnilux DOT com">Alexandre Vasseur</a> */ public class ConcreteAspectCodeGen { private final static String[] EMPTY_STRINGS = new String[0]; private final static Type[] EMPTY_TYPES = new Type[0]; /** * Concrete aspect definition we build for */ private final Definition.ConcreteAspect m_concreteAspect; /** * World for which we build for */ private final World m_world; /** * Set to true when all is checks are verified */ private boolean m_isValid = false; /** * The parent aspect, not concretized */ private ResolvedType m_parent; /** * Aspect perClause, used for direct munging of aspectOf artifacts */ private PerClause m_perClause; /** * Create a new compiler for a concrete aspect * * @param concreteAspect * @param world */ ConcreteAspectCodeGen(Definition.ConcreteAspect concreteAspect, World world) { m_concreteAspect = concreteAspect; m_world = world; } /** * Checks that concrete aspect is valid * * @return true if ok, false otherwise */ public boolean validate() { if (!(m_world instanceof BcelWorld)) { reportError("Internal error: world must be of type BcelWorld"); return false; } // name must be undefined so far ResolvedType current = m_world.resolve(m_concreteAspect.name, true); if (!current.isMissing()) { reportError("Attempt to concretize but chosen aspect name already defined: " + stringify()); return false; } // it can happen that extends is null, for precedence only declaration if (m_concreteAspect.extend == null && m_concreteAspect.precedence != null) { if (m_concreteAspect.pointcuts.isEmpty()) { m_isValid = true; m_perClause = new PerSingleton(); m_parent = null; return true;// no need to checks more in that special case } else { reportError("Attempt to use nested pointcuts without extends clause: "+stringify()); return false; } } m_parent = m_world.resolve(m_concreteAspect.extend, true); // handle inner classes if (m_parent.isMissing()) { // fallback on inner class lookup mechanism String fixedName = m_concreteAspect.extend; int hasDot = fixedName.lastIndexOf('.'); while (hasDot > 0) { char[] fixedNameChars = fixedName.toCharArray(); fixedNameChars[hasDot] = '$'; fixedName = new String(fixedNameChars); hasDot = fixedName.lastIndexOf('.'); m_parent = m_world.resolve(UnresolvedType.forName(fixedName), true); if (!m_parent.isMissing()) { break; } } } if (m_parent.isMissing()) { reportError("Cannot find m_parent aspect for: " + stringify()); return false; } // extends must be abstract if (!m_parent.isAbstract()) { reportError("Attempt to concretize a non-abstract aspect: " + stringify()); return false; } // m_parent must be aspect if (!m_parent.isAspect()) { reportError("Attempt to concretize a non aspect: " + stringify()); return false; } // must have all abstractions defined List elligibleAbstractions = new ArrayList(); Collection abstractMethods = getOutstandingAbstractMethods(m_parent); for (Iterator iter = abstractMethods.iterator(); iter.hasNext();) { ResolvedMember method = (ResolvedMember) iter.next(); if ("()V".equals(method.getSignature())) { String n = method.getName(); if (n.startsWith("ajc$pointcut")) { // Allow for the abstract pointcut being from a code style aspect compiled with -1.5 (see test for 128744) n = n.substring(14); n = n.substring(0,n.indexOf("$")); elligibleAbstractions.add(n); } else if (hasPointcutAnnotation(method)) { elligibleAbstractions.add(method.getName()); } else { // error, an outstanding abstract method that can't be concretized in XML reportError("Abstract method '" + method.toString() + "' cannot be concretized in XML: " + stringify()); return false; } } else { if (method.getName().startsWith("ajc$pointcut") || hasPointcutAnnotation(method)) { // it may be a pointcut but it doesn't meet the requirements for XML concretization reportError("Abstract method '" + method.toString() + "' cannot be concretized as a pointcut (illegal signature, must have no arguments, must return void): " + stringify()); return false; } else { // error, an outstanding abstract method that can't be concretized in XML reportError("Abstract method '" + method.toString() + "' cannot be concretized in XML: " + stringify()); return false; } } } List pointcutNames = new ArrayList(); for (Iterator it = m_concreteAspect.pointcuts.iterator(); it.hasNext();) { Definition.Pointcut abstractPc = (Definition.Pointcut) it.next(); pointcutNames.add(abstractPc.name); } for (Iterator it = elligibleAbstractions.iterator(); it.hasNext();) { String elligiblePc = (String) it.next(); if (!pointcutNames.contains(elligiblePc)) { reportError("Abstract pointcut '" + elligiblePc + "' not configured: " + stringify()); return false; } } m_perClause = m_parent.getPerClause(); m_isValid = true; return m_isValid; } private Collection getOutstandingAbstractMethods(ResolvedType type) { Map collector = new HashMap(); // let's get to the top of the hierarchy and then walk down ... recording abstract methods then removing // them if they get defined further down the hierarchy getOutstandingAbstractMethodsHelper(type,collector); return collector.values(); } // We are trying to determine abstract methods left over at the bottom of a hierarchy that have not been // concretized. private void getOutstandingAbstractMethodsHelper(ResolvedType type,Map collector) { if (type==null) return; // Get to the top if (type!=null && !type.equals(ResolvedType.OBJECT)) { if (type.getSuperclass()!=null) getOutstandingAbstractMethodsHelper(type.getSuperclass(),collector); } ResolvedMember[] rms = type.getDeclaredMethods(); if (rms!=null) { for (int i = 0; i < rms.length; i++) { ResolvedMember member = rms[i]; String key = member.getName()+member.getSignature(); if (member.isAbstract()) { collector.put(key,member); } else { collector.remove(key); } } } } /** * Rebuild the XML snip that defines this concrete aspect, for log error purpose * * @return string repr. */ private String stringify() { StringBuffer sb = new StringBuffer("<concrete-aspect name='"); sb.append(m_concreteAspect.name); sb.append("' extends='"); sb.append(m_concreteAspect.extend); sb.append("'/> in aop.xml"); return sb.toString(); } private boolean hasPointcutAnnotation(ResolvedMember member) { AnnotationX[] as = member.getAnnotations(); if (as==null || as.length==0) return false; for (int i = 0; i < as.length; i++) { if (as[i].getTypeSignature().equals("Lorg/aspectj/lang/annotation/Pointcut;")) { return true; } } return false; } public String getClassName () { return m_concreteAspect.name; } /** * Build the bytecode for the concrete aspect * * @return concrete aspect bytecode */ public byte[] getBytes() { if (!m_isValid) { throw new RuntimeException("Must validate first"); } //TODO AV - abstract away from BCEL... // @Aspect //inherit clause from m_parent // @DeclarePrecedence("....") // if any // public class xxxName [extends xxxExtends] { // [@Pointcut(xxxExpression-n) // public void xxxName-n() {}] // } // @Aspect public class ... LazyClassGen cg = new LazyClassGen( m_concreteAspect.name.replace('.', '/'), (m_parent==null)?"java/lang/Object":m_parent.getName().replace('.', '/'), null,//TODO AV - we could point to the aop.xml that defines it and use JSR-45 Modifier.PUBLIC + Constants.ACC_SUPER, EMPTY_STRINGS, m_world ); AnnotationGen ag = new AnnotationGen( new ObjectType("org/aspectj/lang/annotation/Aspect"), Collections.EMPTY_LIST, true, cg.getConstantPoolGen() ); cg.addAnnotation(ag.getAnnotation()); if (m_concreteAspect.precedence != null) { SimpleElementValueGen svg = new SimpleElementValueGen( ElementValueGen.STRING, cg.getConstantPoolGen(), m_concreteAspect.precedence ); List elems = new ArrayList(); elems.add(new ElementNameValuePairGen("value", svg, cg.getConstantPoolGen())); AnnotationGen agprec = new AnnotationGen( new ObjectType("org/aspectj/lang/annotation/DeclarePrecedence"), elems, true, cg.getConstantPoolGen() ); cg.addAnnotation(agprec.getAnnotation()); } // default constructor LazyMethodGen init = new LazyMethodGen( Modifier.PUBLIC, Type.VOID, "<init>", EMPTY_TYPES, EMPTY_STRINGS, cg ); InstructionList cbody = init.getBody(); cbody.append(InstructionConstants.ALOAD_0); cbody.append(cg.getFactory().createInvoke( (m_parent==null)?"java/lang/Object":m_parent.getName().replace('.', '/'), "<init>", Type.VOID, EMPTY_TYPES, Constants.INVOKESPECIAL )); cbody.append(InstructionConstants.RETURN); cg.addMethodGen(init); for (Iterator it = m_concreteAspect.pointcuts.iterator(); it.hasNext();) { Definition.Pointcut abstractPc = (Definition.Pointcut) it.next(); LazyMethodGen mg = new LazyMethodGen( Modifier.PUBLIC,//TODO AV - respect visibility instead of opening up? Type.VOID, abstractPc.name, EMPTY_TYPES, EMPTY_STRINGS, cg ); SimpleElementValueGen svg = new SimpleElementValueGen( ElementValueGen.STRING, cg.getConstantPoolGen(), abstractPc.expression ); List elems = new ArrayList(); elems.add(new ElementNameValuePairGen("value", svg, cg.getConstantPoolGen())); AnnotationGen mag = new AnnotationGen( new ObjectType("org/aspectj/lang/annotation/Pointcut"), elems, true, cg.getConstantPoolGen() ); AnnotationX max = new AnnotationX(mag.getAnnotation(), m_world); mg.addAnnotation(max); InstructionList body = mg.getBody(); body.append(InstructionConstants.RETURN); cg.addMethodGen(mg); } // handle the perClause BcelPerClauseAspectAdder perClauseMunger = new BcelPerClauseAspectAdder( ResolvedType.forName(m_concreteAspect.name).resolve(m_world), m_perClause.getKind() ); perClauseMunger.forceMunge(cg, false); //TODO AV - unsafe cast // register the fresh new class into the world repository as it does not exist on the classpath anywhere JavaClass jc = cg.getJavaClass((BcelWorld) m_world); ((BcelWorld) m_world).addSourceObjectType(jc); return jc.getBytes(); } /** * Error reporting * * @param message */ private void reportError(String message) { m_world.getMessageHandler().handleMessage(new Message(message, IMessage.ERROR, null, null)); } }
170,102
Bug 170102 iajc Ant task doesn't support all warn options
The iajc Ant task currently supports only a few of the options provided by the ajc compiler. It would be nice if it could support them all so that builds done using the Ant task generate the same errors/warnings as the ones done within the Eclipse IDE.
resolved fixed
5336603
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2007-01-11T08:43:18Z"
"2007-01-10T17:26:40Z"
taskdefs/src/org/aspectj/tools/ant/taskdefs/AjcTask.java
/* ******************************************************************* * Copyright (c) 2001-2001 Xerox Corporation, * 2002 Palo Alto Research Center, Incorporated (PARC) * 2003-2004 Contributors. * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Eclipse Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Xerox/PARC initial implementation * Wes Isberg 2003-2004 changes * ******************************************************************/ package org.aspectj.tools.ant.taskdefs; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.StringTokenizer; import org.apache.tools.ant.AntClassLoader; import org.apache.tools.ant.BuildException; import org.apache.tools.ant.Location; import org.apache.tools.ant.Project; import org.apache.tools.ant.taskdefs.Copy; import org.apache.tools.ant.taskdefs.Delete; import org.apache.tools.ant.taskdefs.Execute; import org.apache.tools.ant.taskdefs.Expand; import org.apache.tools.ant.taskdefs.Javac; import org.apache.tools.ant.taskdefs.LogStreamHandler; import org.apache.tools.ant.taskdefs.MatchingTask; import org.apache.tools.ant.taskdefs.Mkdir; import org.apache.tools.ant.taskdefs.PumpStreamHandler; import org.apache.tools.ant.taskdefs.Zip; import org.apache.tools.ant.taskdefs.compilers.DefaultCompilerAdapter; import org.apache.tools.ant.types.Commandline; import org.apache.tools.ant.types.CommandlineJava; import org.apache.tools.ant.types.FileSet; import org.apache.tools.ant.types.Path; import org.apache.tools.ant.types.PatternSet; import org.apache.tools.ant.types.Reference; import org.apache.tools.ant.types.ZipFileSet; import org.apache.tools.ant.util.TaskLogger; import org.aspectj.bridge.AbortException; import org.aspectj.bridge.IMessage; import org.aspectj.bridge.IMessageHandler; import org.aspectj.bridge.IMessageHolder; import org.aspectj.bridge.MessageHandler; import org.aspectj.bridge.MessageUtil; import org.aspectj.bridge.IMessage.Kind; import org.aspectj.tools.ajc.Main; import org.aspectj.util.FileUtil; import org.aspectj.util.LangUtil; /** * This runs the AspectJ 1.1 compiler, * supporting all the command-line options. * In 1.1.1, ajc copies resources from input jars, * but you can copy resources from the source directories * using sourceRootCopyFilter. * When not forking, things will be copied as needed * for each iterative compile, * but when forking things are only copied at the * completion of a successful compile. * <p> * See the development environment guide for * usage documentation. * * @since AspectJ 1.1, Ant 1.5 */ public class AjcTask extends MatchingTask { /* * This task mainly converts ant specification for ajc, * verbosely ignoring improper input. * It also has some special features for non-obvious clients: * (1) Javac compiler adapter supported in * <code>setupAjc(AjcTask, Javac, File)</code> * and * <code>readArguments(String[])</code>; * (2) testing is supported by * (a) permitting the same specification to be re-run * with added flags (settings once made cannot be * removed); and * (b) permitting recycling the task with * <code>reset()</code> (untested). * * The parts that do more than convert ant specs are * (a) code for forking; * (b) code for copying resources. * * If you maintain/upgrade this task, keep in mind: * (1) changes to the semantics of ajc (new options, new * values permitted, etc.) will have to be reflected here. * (2) the clients: * the iajc ant script, Javac compiler adapter, * maven clients of iajc, and testing code. */ // XXX move static methods after static initializer /** * This method extracts javac arguments to ajc, * and add arguments to make ajc behave more like javac * in copying resources. * <p> * Pass ajc-specific options using compilerarg sub-element: * <pre> * &lt;javac srcdir="src"> * &lt;compilerarg compiler="..." line="-argfile src/args.lst"/> * &lt;javac> * </pre> * Some javac arguments are not supported in this component (yet): * <pre> * String memoryInitialSize; * boolean includeAntRuntime = true; * boolean includeJavaRuntime = false; * </pre> * Other javac arguments are not supported in ajc 1.1: * <pre> * boolean optimize; * String forkedExecutable; * FacadeTaskHelper facade; * boolean depend; * String debugLevel; * Path compileSourcepath; * </pre> * @param javac the Javac command to implement (not null) * @param ajc the AjcTask to adapt (not null) * @param destDir the File class destination directory (may be null) * @return null if no error, or String error otherwise */ public String setupAjc(Javac javac) { if (null == javac) { return "null javac"; } AjcTask ajc = this; // no null checks b/c AjcTask handles null input gracefully ajc.setProject(javac.getProject()); ajc.setLocation(javac.getLocation()); ajc.setTaskName("javac-iajc"); ajc.setDebug(javac.getDebug()); ajc.setDeprecation(javac.getDeprecation()); ajc.setFailonerror(javac.getFailonerror()); final boolean fork = javac.isForkedJavac(); ajc.setFork(fork); if (fork) { ajc.setMaxmem(javac.getMemoryMaximumSize()); } ajc.setNowarn(javac.getNowarn()); ajc.setListFileArgs(javac.getListfiles()); ajc.setVerbose(javac.getVerbose()); ajc.setTarget(javac.getTarget()); ajc.setSource(javac.getSource()); ajc.setEncoding(javac.getEncoding()); File javacDestDir = javac.getDestdir(); if (null != javacDestDir) { ajc.setDestdir(javacDestDir); // filter requires dest dir // mimic Javac task's behavior in copying resources, ajc.setSourceRootCopyFilter("**/CVS/*,**/*.java,**/*.aj"); } ajc.setBootclasspath(javac.getBootclasspath()); ajc.setExtdirs(javac.getExtdirs()); ajc.setClasspath(javac.getClasspath()); // ignore srcDir -- all files picked up in recalculated file list // ajc.setSrcDir(javac.getSrcdir()); ajc.addFiles(javac.getFileList()); // arguments can override the filter, add to paths, override options ajc.readArguments(javac.getCurrentCompilerArgs()); return null; } /** * Find aspectjtools.jar on the task or system classpath. * Accept <code>aspectj{-}tools{...}.jar</code> * mainly to support build systems using maven-style * re-naming * (e.g., <code>aspectj-tools-1.1.0.jar</code>. * Note that we search the task classpath first, * though an entry on the system classpath would be loaded first, * because it seems more correct as the more specific one. * @return readable File for aspectjtools.jar, or null if not found. */ public static File findAspectjtoolsJar() { File result = null; ClassLoader loader = AjcTask.class.getClassLoader(); if (loader instanceof AntClassLoader) { AntClassLoader taskLoader = (AntClassLoader) loader; String cp = taskLoader.getClasspath(); String[] cps = LangUtil.splitClasspath(cp); for (int i = 0; (i < cps.length) && (null == result); i++) { result = isAspectjtoolsjar(cps[i]); } } if (null == result) { final Path classpath = Path.systemClasspath; final String[] paths = classpath.list(); for (int i = 0; (i < paths.length) && (null == result); i++) { result = isAspectjtoolsjar(paths[i]); } } return (null == result? null : result.getAbsoluteFile()); } /** @return File if readable jar with aspectj tools name, or null */ private static File isAspectjtoolsjar(String path) { if (null == path) { return null; } final String prefix = "aspectj"; final String infix = "tools"; final String altInfix = "-tools"; final String suffix = ".jar"; final int prefixLength = 7; // prefix.length(); final int minLength = 16; // prefixLength + infix.length() + suffix.length(); if (!path.endsWith(suffix)) { return null; } int loc = path.lastIndexOf(prefix); if ((-1 != loc) && ((loc + minLength) <= path.length())) { String rest = path.substring(loc+prefixLength); if (-1 != rest.indexOf(File.pathSeparator)) { return null; } if (rest.startsWith(infix) || rest.startsWith(altInfix)) { File result = new File(path); if (result.canRead() && result.isFile()) { return result; } } } return null; } /** * Maximum length (in chars) of command line * before converting to an argfile when forking */ private static final int MAX_COMMANDLINE = 4096; private static final File DEFAULT_DESTDIR = new File(".") { public String toString() { return "(no destination dir specified)"; } }; /** do not throw BuildException on fail/abort message with usage */ private static final String USAGE_SUBSTRING = "AspectJ-specific options"; /** valid -X[...] options other than -Xlint variants */ private static final List VALID_XOPTIONS; /** valid warning (-warn:[...]) variants */ private static final List VALID_WARNINGS; /** valid debugging (-g:[...]) variants */ private static final List VALID_DEBUG; /** * -Xlint variants (error, warning, ignore) * @see org.aspectj.weaver.Lint */ private static final List VALID_XLINT; public static final String COMMAND_EDITOR_NAME = AjcTask.class.getName() + ".COMMAND_EDITOR"; static final String[] TARGET_INPUTS = new String [] { "1.1", "1.2", "1.3", "1.4", "1.5" }; static final String[] SOURCE_INPUTS = new String [] { "1.3", "1.4", "1.5" }; static final String[] COMPLIANCE_INPUTS = new String [] { "-1.3", "-1.4", "-1.5" }; private static final ICommandEditor COMMAND_EDITOR; static { // many now deprecated: reweavable* String[] xs = new String[] { "serializableAspects", "incrementalFile", "lazyTjp", "reweavable", "reweavable:compress", "notReweavable", "noInline", "terminateAfterCompilation","hasMember", "ajruntimetarget:1.2", "ajruntimetarget:1.5", "addSerialVersionUID" //, "targetNearSource", "OcodeSize", }; VALID_XOPTIONS = Collections.unmodifiableList(Arrays.asList(xs)); xs = new String[] {"constructorName", "packageDefaultMethod", "deprecation", "maskedCatchBlocks", "unusedLocals", "unusedArguments", "unusedImports", "syntheticAccess", "assertIdentifier", "none" }; VALID_WARNINGS = Collections.unmodifiableList(Arrays.asList(xs)); xs = new String[] {"none", "lines", "vars", "source" }; VALID_DEBUG = Collections.unmodifiableList(Arrays.asList(xs)); xs = new String[] { "error", "warning", "ignore"}; VALID_XLINT = Collections.unmodifiableList(Arrays.asList(xs)); ICommandEditor editor = null; try { String editorClassName = System.getProperty(COMMAND_EDITOR_NAME); if (null != editorClassName) { ClassLoader cl = AjcTask.class.getClassLoader(); Class editorClass = cl.loadClass(editorClassName); editor = (ICommandEditor) editorClass.newInstance(); } } catch (Throwable t) { System.err.println("Warning: unable to load command editor"); t.printStackTrace(System.err); } COMMAND_EDITOR = editor; } // ---------------------------- state and Ant interface thereto private boolean verbose; private boolean listFileArgs; private boolean failonerror; private boolean fork; private String maxMem; private TaskLogger logger; // ------- single entries dumped into cmd protected GuardedCommand cmd; // ------- lists resolved in addListArgs() at execute() time private Path srcdir; private Path injars; private Path inpath; private Path classpath; private Path bootclasspath; private Path forkclasspath; private Path extdirs; private Path aspectpath; private Path argfiles; private List ignored; private Path sourceRoots; private File xweaveDir; private String xdoneSignal; // ----- added by adapter - integrate better? private List /* File */ adapterFiles; private String[] adapterArguments; private IMessageHolder messageHolder; private ICommandEditor commandEditor; // -------- resource-copying /** true if copying injar non-.class files to the output jar */ private boolean copyInjars; private boolean copyInpath; /** non-null if copying all source root files but the filtered ones */ private String sourceRootCopyFilter; /** non-null if copying all inpath dir files but the filtered ones */ private String inpathDirCopyFilter; /** directory sink for classes */ private File destDir; /** zip file sink for classes */ private File outjar; /** track whether we've supplied any temp outjar */ private boolean outjarFixedup; /** * When possibly copying resources to the output jar, * pass ajc a fake output jar to copy from, * so we don't change the modification time of the output jar * when copying injars/inpath into the actual outjar. */ private File tmpOutjar; private boolean executing; /** non-null only while executing in same vm */ private Main main; /** true only when executing in other vm */ private boolean executingInOtherVM; /** true if -incremental */ private boolean inIncrementalMode; /** true if -XincrementalFile (i.e, setTagFile)*/ private boolean inIncrementalFileMode; /** log command in non-verbose mode */ private boolean logCommand; /** used when forking */ private CommandlineJava javaCmd = new CommandlineJava(); // also note MatchingTask grabs source files... public AjcTask() { reset(); } /** to use this same Task more than once (testing) */ public void reset() { // XXX possible to reset MatchingTask? // need declare for "all fields initialized in ..." adapterArguments = null; adapterFiles = new ArrayList(); argfiles = null; executing = false; aspectpath = null; bootclasspath = null; classpath = null; cmd = new GuardedCommand(); copyInjars = false; copyInpath = false; destDir = DEFAULT_DESTDIR; executing = false; executingInOtherVM = false; extdirs = null; failonerror = true; // non-standard default forkclasspath = null; inIncrementalMode = false; inIncrementalFileMode = false; ignored = new ArrayList(); injars = null; inpath = null; listFileArgs = false; maxMem = null; messageHolder = null; outjar = null; sourceRootCopyFilter = null; inpathDirCopyFilter = null; sourceRoots = null; srcdir = null; tmpOutjar = null; verbose = false; xweaveDir = null; xdoneSignal = null; logCommand = false; javaCmd = new CommandlineJava(); } protected void ignore(String ignored) { this.ignored.add(ignored + " at " + getLocation()); } //---------------------- option values // used by entries with internal commas protected String validCommaList(String list, List valid, String label) { return validCommaList(list, valid, label, valid.size()); } protected String validCommaList(String list, List valid, String label, int max) { StringBuffer result = new StringBuffer(); StringTokenizer st = new StringTokenizer(list, ","); int num = 0; while (st.hasMoreTokens()) { String token = st.nextToken().trim(); num++; if (num > max) { ignore("too many entries for -" + label + ": " + token); break; } if (!valid.contains(token)) { ignore("bad commaList entry for -" + label + ": " + token); } else { if (0 < result.length()) { result.append(","); } result.append(token); } } return (0 == result.length() ? null : result.toString()); } public void setIncremental(boolean incremental) { cmd.addFlag("-incremental", incremental); inIncrementalMode = incremental; } public void setLogCommand(boolean logCommand) { this.logCommand = logCommand; } public void setHelp(boolean help) { cmd.addFlag("-help", help); } public void setVersion(boolean version) { cmd.addFlag("-version", version); } public void setXTerminateAfterCompilation(boolean b) { cmd.addFlag("-XterminateAfterCompilation", b); } public void setXReweavable(boolean reweavable) { cmd.addFlag("-Xreweavable",reweavable); } public void setXJoinpoints(String optionalJoinpoints) { cmd.addFlag("-Xjoinpoints:"+optionalJoinpoints,true); } public void setXNoWeave(boolean b) { if (logger!=null) logger.warning("the noweave option is no longer required and is being ignored"); } public void setNoWeave(boolean b) { if (logger!=null) logger.warning("the noweave option is no longer required and is being ignored"); } public void setXNotReweavable(boolean notReweavable) { cmd.addFlag("-XnotReweavable",notReweavable); } public void setXaddSerialVersionUID(boolean addUID) { cmd.addFlag("-XaddSerialVersionUID",addUID); } public void setXNoInline(boolean noInline) { cmd.addFlag("-XnoInline",noInline); } public void setShowWeaveInfo(boolean showweaveinfo) { cmd.addFlag("-showWeaveInfo",showweaveinfo); } public void setNowarn(boolean nowarn) { cmd.addFlag("-nowarn", nowarn); } public void setDeprecation(boolean deprecation) { cmd.addFlag("-deprecation", deprecation); } public void setWarn(String warnings) { warnings = validCommaList(warnings, VALID_WARNINGS, "warn"); cmd.addFlag("-warn:" + warnings, (null != warnings)); } public void setDebug(boolean debug) { cmd.addFlag("-g", debug); } public void setDebugLevel(String level) { level = validCommaList(level, VALID_DEBUG, "g"); cmd.addFlag("-g:" + level, (null != level)); } public void setEmacssym(boolean emacssym) { cmd.addFlag("-emacssym", emacssym); } public void setCrossrefs(boolean on) { cmd.addFlag("-crossrefs", on); } /** * -Xlint - set default level of -Xlint messages to warning * (same as </code>-Xlint:warning</code>) */ public void setXlintwarnings(boolean xlintwarnings) { cmd.addFlag("-Xlint", xlintwarnings); } /** -Xlint:{error|warning|info} - set default level for -Xlint messages * @param xlint the String with one of error, warning, ignored */ public void setXlint(String xlint) { xlint = validCommaList(xlint, VALID_XLINT, "Xlint", 1); cmd.addFlag("-Xlint:" + xlint, (null != xlint)); } /** * -Xlintfile {lint.properties} - enable or disable specific forms * of -Xlint messages based on a lint properties file * (default is * <code>org/aspectj/weaver/XLintDefault.properties</code>) * @param xlintFile the File with lint properties */ public void setXlintfile(File xlintFile) { cmd.addFlagged("-Xlintfile", xlintFile.getAbsolutePath()); } public void setPreserveAllLocals(boolean preserveAllLocals) { cmd.addFlag("-preserveAllLocals", preserveAllLocals); } public void setNoImportError(boolean noImportError) { cmd.addFlag("-warn:-unusedImport", noImportError); } public void setEncoding(String encoding) { cmd.addFlagged("-encoding", encoding); } public void setLog(File file) { cmd.addFlagged("-log", file.getAbsolutePath()); } public void setProceedOnError(boolean proceedOnError) { cmd.addFlag("-proceedOnError", proceedOnError); } public void setVerbose(boolean verbose) { cmd.addFlag("-verbose", verbose); this.verbose = verbose; } public void setListFileArgs(boolean listFileArgs) { this.listFileArgs = listFileArgs; } public void setReferenceInfo(boolean referenceInfo) { cmd.addFlag("-referenceInfo", referenceInfo); } public void setTime(boolean time) { cmd.addFlag("-time", time); } public void setNoExit(boolean noExit) { cmd.addFlag("-noExit", noExit); } public void setFailonerror(boolean failonerror) { this.failonerror = failonerror; } /** * @return true if fork was set */ public boolean isForked() { return fork; } public void setFork(boolean fork) { this.fork = fork; } public void setMaxmem(String maxMem) { this.maxMem = maxMem; } /** support for nested &lt;jvmarg&gt; elements */ public Commandline.Argument createJvmarg() { return this.javaCmd.createVmArgument(); } // ---------------- public void setTagFile(File file) { inIncrementalMode = true; cmd.addFlagged(Main.CommandController.TAG_FILE_OPTION, file.getAbsolutePath()); inIncrementalFileMode = true; } public void setOutjar(File file) { if (DEFAULT_DESTDIR != destDir) { String e = "specifying both output jar (" + file + ") and destination dir (" + destDir + ")"; throw new BuildException(e); } outjar = file; outjarFixedup = false; tmpOutjar = null; } public void setOutxml(boolean outxml) { cmd.addFlag("-outxml",outxml); } public void setOutxmlfile(String name) { cmd.addFlagged("-outxmlfile", name); } public void setDestdir(File dir) { if (null != outjar) { String e = "specifying both output jar (" + outjar + ") and destination dir (" + dir + ")"; throw new BuildException(e); } cmd.addFlagged("-d", dir.getAbsolutePath()); destDir = dir; } /** * @param input a String in TARGET_INPUTS */ public void setTarget(String input) { String ignore = cmd.addOption("-target", TARGET_INPUTS, input); if (null != ignore) { ignore(ignore); } } /** * Language compliance level. * If not set explicitly, eclipse default holds. * @param input a String in COMPLIANCE_INPUTS */ public void setCompliance(String input) { String ignore = cmd.addOption(null, COMPLIANCE_INPUTS, input); if (null != ignore) { ignore(ignore); } } /** * Source compliance level. * If not set explicitly, eclipse default holds. * @param input a String in SOURCE_INPUTS */ public void setSource(String input) { String ignore = cmd.addOption("-source", SOURCE_INPUTS, input); if (null != ignore) { ignore(ignore); } } /** * Flag to copy all non-.class contents of injars * to outjar after compile completes. * Requires both injars and outjar. * @param doCopy */ public void setCopyInjars(boolean doCopy){ ignore("copyInJars"); log("copyInjars not required since 1.1.1.\n", Project.MSG_WARN); //this.copyInjars = doCopy; } /** * Option to copy all files from * all source root directories * except those specified here. * If this is specified and sourceroots are specified, * then this will copy all files except * those specified in the filter pattern. * Requires sourceroots. * * @param filter a String acceptable as an excludes * filter for an Ant Zip fileset. */ public void setSourceRootCopyFilter(String filter){ this.sourceRootCopyFilter = filter; } /** * Option to copy all files from * all inpath directories * except the files specified here. * If this is specified and inpath directories are specified, * then this will copy all files except * those specified in the filter pattern. * Requires inpath. * If the input does not contain "**\/*.class", then * this prepends it, to avoid overwriting woven classes * with unwoven input. * @param filter a String acceptable as an excludes * filter for an Ant Zip fileset. */ public void setInpathDirCopyFilter(String filter){ if (null != filter) { if (-1 == filter.indexOf("**/*.class")) { filter = "**/*.class," + filter; } } this.inpathDirCopyFilter = filter; } public void setX(String input) { // ajc-only eajc-also docDone StringTokenizer tokens = new StringTokenizer(input, ",", false); while (tokens.hasMoreTokens()) { String token = tokens.nextToken().trim(); if (1 < token.length()) { // new special case: allow -Xset:anything if (VALID_XOPTIONS.contains(token) || token.indexOf("set:")==0 || token.indexOf("joinpoints:")==0) { cmd.addFlag("-X" + token, true); } else { ignore("-X" + token); } } } } public void setXDoneSignal(String doneSignal) { this.xdoneSignal = doneSignal; } /** direct API for testing */ public void setMessageHolder(IMessageHolder holder) { this.messageHolder = holder; } /** * Setup custom message handling. * @param className the String fully-qualified-name of a class * reachable from this object's class loader, * implementing IMessageHolder, and * having a public no-argument constructor. * @throws BuildException if unable to create instance of className */ public void setMessageHolderClass(String className) { try { Class mclass = Class.forName(className); IMessageHolder holder = (IMessageHolder) mclass.newInstance(); setMessageHolder(holder); } catch (Throwable t) { String m = "unable to instantiate message holder: " + className; throw new BuildException(m, t); } } /** direct API for testing */ public void setCommandEditor(ICommandEditor editor) { this.commandEditor = editor; } /** * Setup command-line filter. * To do this staticly, define the environment variable * <code>org.aspectj.tools.ant.taskdefs.AjcTask.COMMAND_EDITOR</code> * with the <code>className</code> parameter. * @param className the String fully-qualified-name of a class * reachable from this object's class loader, * implementing ICommandEditor, and * having a public no-argument constructor. * @throws BuildException if unable to create instance of className */ public void setCommandEditorClass(String className) { // skip Ant interface? try { Class mclass = Class.forName(className); setCommandEditor((ICommandEditor) mclass.newInstance()); } catch (Throwable t) { String m = "unable to instantiate command editor: " + className; throw new BuildException(m, t); } } //---------------------- Path lists /** * Add path elements to source path and return result. * Elements are added even if they do not exist. * @param source the Path to add to - may be null * @param toAdd the Path to add - may be null * @return the (never-null) Path that results */ protected Path incPath(Path source, Path toAdd) { if (null == source) { source = new Path(project); } if (null != toAdd) { source.append(toAdd); } return source; } public void setSourcerootsref(Reference ref) { createSourceRoots().setRefid(ref); } public void setSourceRoots(Path roots) { sourceRoots = incPath(sourceRoots, roots); } public Path createSourceRoots() { if (sourceRoots == null) { sourceRoots = new Path(project); } return sourceRoots.createPath(); } public void setXWeaveDir(File file) { if ((null != file) && file.isDirectory() && file.canRead()) { xweaveDir = file; } } public void setInjarsref(Reference ref) { createInjars().setRefid(ref); } public void setInpathref(Reference ref) { createInpath().setRefid(ref); } public void setInjars(Path path) { injars = incPath(injars, path); } public void setInpath(Path path) { inpath = incPath(inpath,path); } public Path createInjars() { if (injars == null) { injars = new Path(project); } return injars.createPath(); } public Path createInpath() { if (inpath == null) { inpath = new Path(project); } return inpath.createPath(); } public void setClasspath(Path path) { classpath = incPath(classpath, path); } public void setClasspathref(Reference classpathref) { createClasspath().setRefid(classpathref); } public Path createClasspath() { if (classpath == null) { classpath = new Path(project); } return classpath.createPath(); } public void setBootclasspath(Path path) { bootclasspath = incPath(bootclasspath, path); } public void setBootclasspathref(Reference bootclasspathref) { createBootclasspath().setRefid(bootclasspathref); } public Path createBootclasspath() { if (bootclasspath == null) { bootclasspath = new Path(project); } return bootclasspath.createPath(); } public void setForkclasspath(Path path) { forkclasspath = incPath(forkclasspath, path); } public void setForkclasspathref(Reference forkclasspathref) { createForkclasspath().setRefid(forkclasspathref); } public Path createForkclasspath() { if (forkclasspath == null) { forkclasspath = new Path(project); } return forkclasspath.createPath(); } public void setExtdirs(Path path) { extdirs = incPath(extdirs, path); } public void setExtdirsref(Reference ref) { createExtdirs().setRefid(ref); } public Path createExtdirs() { if (extdirs == null) { extdirs = new Path(project); } return extdirs.createPath(); } public void setAspectpathref(Reference ref) { createAspectpath().setRefid(ref); } public void setAspectpath(Path path) { aspectpath = incPath(aspectpath, path); } public Path createAspectpath() { if (aspectpath == null) { aspectpath = new Path(project); } return aspectpath.createPath(); } public void setSrcDir(Path path) { srcdir = incPath(srcdir, path); } public Path createSrc() { return createSrcdir(); } public Path createSrcdir() { if (srcdir == null) { srcdir = new Path(project); } return srcdir.createPath(); } /** @return true if in incremental mode (command-line or file) */ public boolean isInIncrementalMode() { return inIncrementalMode; } /** @return true if in incremental file mode */ public boolean isInIncrementalFileMode() { return inIncrementalFileMode; } public void setArgfilesref(Reference ref) { createArgfiles().setRefid(ref); } public void setArgfiles(Path path) { // ajc-only eajc-also docDone argfiles = incPath(argfiles, path); } public Path createArgfiles() { if (argfiles == null) { argfiles = new Path(project); } return argfiles.createPath(); } // ------------------------------ run /** * Compile using ajc per settings. * @exception BuildException if the compilation has problems * or if there were compiler errors and failonerror is true. */ public void execute() throws BuildException { this.logger = new TaskLogger(this); if (executing) { throw new IllegalStateException("already executing"); } else { executing = true; } setupOptions(); verifyOptions(); try { String[] args = makeCommand(); if (logCommand) { log("ajc " + Arrays.asList(args)); } else { logVerbose("ajc " + Arrays.asList(args)); } if (!fork) { executeInSameVM(args); } else { // when forking, Adapter handles failonerror executeInOtherVM(args); } } catch (BuildException e) { throw e; } catch (Throwable x) { this.logger.error(Main.renderExceptionForUser(x)); throw new BuildException("IGNORE -- See " + LangUtil.unqualifiedClassName(x) + " rendered to ant logger"); } finally { executing = false; if (null != tmpOutjar) { tmpOutjar.delete(); } } } /** * Halt processing. * This tells main in the same vm to quit. * It fails when running in forked mode. * @return true if not in forked mode * and main has quit or been told to quit */ public boolean quit() { if (executingInOtherVM) { return false; } Main me = main; if (null != me) { me.quit(); } return true; } // package-private for testing String[] makeCommand() { ArrayList result = new ArrayList(); if (0 < ignored.size()) { for (Iterator iter = ignored.iterator(); iter.hasNext();) { logVerbose("ignored: " + iter.next()); } } // when copying resources, use temp jar for class output // then copy temp jar contents and resources to output jar if ((null != outjar) && !outjarFixedup) { if (copyInjars || copyInpath || (null != sourceRootCopyFilter) || (null != inpathDirCopyFilter)) { String path = outjar.getAbsolutePath(); int len = FileUtil.zipSuffixLength(path); path = path.substring(0, path.length()-len) + ".tmp.jar"; tmpOutjar = new File(path); } if (null == tmpOutjar) { cmd.addFlagged("-outjar", outjar.getAbsolutePath()); } else { cmd.addFlagged("-outjar", tmpOutjar.getAbsolutePath()); } outjarFixedup = true; } result.addAll(cmd.extractArguments()); addListArgs(result); String[] command = (String[]) result.toArray(new String[0]); if (null != commandEditor) { command = commandEditor.editCommand(command); } else if (null != COMMAND_EDITOR) { command = COMMAND_EDITOR.editCommand(command); } return command; } /** * Create any pseudo-options required to implement * some of the macro options * @throws BuildException if options conflict */ protected void setupOptions() { if (null != xweaveDir) { if (DEFAULT_DESTDIR != destDir) { throw new BuildException("weaveDir forces destdir"); } if (null != outjar) { throw new BuildException("weaveDir forces outjar"); } if (null != injars) { throw new BuildException("weaveDir incompatible with injars now"); } if (null != inpath) { throw new BuildException("weaveDir incompatible with inpath now"); } File injar = zipDirectory(xweaveDir); setInjars(new Path(getProject(), injar.getAbsolutePath())); setDestdir(xweaveDir); } } protected File zipDirectory(File dir) { File tempDir = new File("."); try { tempDir = File.createTempFile("AjcTest", ".tmp"); tempDir.mkdirs(); tempDir.deleteOnExit(); // XXX remove zip explicitly.. } catch (IOException e) { // ignore } // File result = new File(tempDir, String filename = "AjcTask-" + System.currentTimeMillis() + ".zip"; File result = new File(filename); Zip zip = new Zip(); zip.setProject(getProject()); zip.setDestFile(result); zip.setTaskName(getTaskName() + " - zip"); FileSet fileset = new FileSet(); fileset.setDir(dir); zip.addFileset(fileset); zip.execute(); Delete delete = new Delete(); delete.setProject(getProject()); delete.setTaskName(getTaskName() + " - delete"); delete.setDir(dir); delete.execute(); Mkdir mkdir = new Mkdir(); mkdir.setProject(getProject()); mkdir.setTaskName(getTaskName() + " - mkdir"); mkdir.setDir(dir); mkdir.execute(); return result; } /** * @throw BuildException if options conflict */ protected void verifyOptions() { StringBuffer sb = new StringBuffer(); if (fork && isInIncrementalMode() && !isInIncrementalFileMode()) { sb.append("can fork incremental only using tag file.\n"); } if (((null != inpathDirCopyFilter) || (null != sourceRootCopyFilter)) && (null == outjar) && (DEFAULT_DESTDIR == destDir)) { final String REQ = " requires dest dir or output jar.\n"; if (null == inpathDirCopyFilter) { sb.append("sourceRootCopyFilter"); } else if (null == sourceRootCopyFilter) { sb.append("inpathDirCopyFilter"); } else { sb.append("sourceRootCopyFilter and inpathDirCopyFilter"); } sb.append(REQ); } if (0 < sb.length()) { throw new BuildException(sb.toString()); } } /** * Run the compile in the same VM by * loading the compiler (Main), * setting up any message holders, * doing the compile, * and converting abort/failure and error messages * to BuildException, as appropriate. * @throws BuildException if abort or failure messages * or if errors and failonerror. * */ protected void executeInSameVM(String[] args) { if (null != maxMem) { log("maxMem ignored unless forked: " + maxMem, Project.MSG_WARN); } IMessageHolder holder = messageHolder; int numPreviousErrors; if (null == holder) { MessageHandler mhandler = new MessageHandler(true); final IMessageHandler delegate; delegate = new AntMessageHandler(this.logger,this.verbose, false); mhandler.setInterceptor(delegate); holder = mhandler; numPreviousErrors = 0; } else { numPreviousErrors = holder.numMessages(IMessage.ERROR, true); } { Main newmain = new Main(); newmain.setHolder(holder); newmain.setCompletionRunner(new Runnable() { public void run() { doCompletionTasks(); } }); if (null != main) { MessageUtil.fail(holder, "still running prior main"); return; } main = newmain; } main.runMain(args, false); if (failonerror) { int errs = holder.numMessages(IMessage.ERROR, false); errs -= numPreviousErrors; if (0 < errs) { String m = errs + " errors"; MessageUtil.print(System.err, holder, "", MessageUtil.MESSAGE_ALL, MessageUtil.PICK_ERROR, true); throw new BuildException(m); } } // Throw BuildException if there are any fail or abort // messages. // The BuildException message text has a list of class names // for the exceptions found in the messages, or the // number of fail/abort messages found if there were // no exceptions for any of the fail/abort messages. // The interceptor message handler should have already // printed the messages, including any stack traces. // HACK: this ignores the Usage message { IMessage[] fails = holder.getMessages(IMessage.FAIL, true); if (!LangUtil.isEmpty(fails)) { StringBuffer sb = new StringBuffer(); String prefix = "fail due to "; int numThrown = 0; for (int i = 0; i < fails.length; i++) { String message = fails[i].getMessage(); if (LangUtil.isEmpty(message)) { message = "<no message>"; } else if (-1 != message.indexOf(USAGE_SUBSTRING)) { continue; } Throwable t = fails[i].getThrown(); if (null != t) { numThrown++; sb.append(prefix); sb.append(LangUtil.unqualifiedClassName(t.getClass())); String thrownMessage = t.getMessage(); if (!LangUtil.isEmpty(thrownMessage)) { sb.append(" \"" + thrownMessage + "\""); } } sb.append("\"" + message + "\""); prefix = ", "; } if (0 < sb.length()) { sb.append(" (" + numThrown + " exceptions)"); throw new BuildException(sb.toString()); } } } } /** * Execute in a separate VM. * Differences from normal same-VM execution: * <ul> * <li>ignores any message holder {class} set</li> * <li>No resource-copying between interative runs</li> * <li>failonerror fails when process interface fails * to return negative values</li> * </ul> * @param args String[] of the complete compiler command to execute * * @see DefaultCompilerAdapter#executeExternalCompile(String[], int) * @throws BuildException if ajc aborts (negative value) * or if failonerror and there were compile errors. */ protected void executeInOtherVM(String[] args) { javaCmd.setClassname(org.aspectj.tools.ajc.Main.class.getName()); final Path vmClasspath = javaCmd.createClasspath(getProject()); { File aspectjtools = null; int vmClasspathSize = vmClasspath.size(); if ((null != forkclasspath) && (0 != forkclasspath.size())) { vmClasspath.addExisting(forkclasspath); } else { aspectjtools = findAspectjtoolsJar(); if (null != aspectjtools) { vmClasspath.createPathElement().setLocation(aspectjtools); } } int newVmClasspathSize = vmClasspath.size(); if (vmClasspathSize == newVmClasspathSize) { String m = "unable to find aspectjtools to fork - "; if (null != aspectjtools) { m += "tried " + aspectjtools.toString(); } else if (null != forkclasspath) { m += "tried " + forkclasspath.toString(); } else { m += "define forkclasspath or put aspectjtools on classpath"; } throw new BuildException(m); } } if (null != maxMem) { javaCmd.setMaxmemory(maxMem); } File tempFile = null; int numArgs = args.length; args = GuardedCommand.limitTo(args, MAX_COMMANDLINE, getLocation()); if (args.length != numArgs) { tempFile = new File(args[1]); } try { boolean setMessageHolderOnForking = (this.messageHolder != null); String[] javaArgs = javaCmd.getCommandline(); String[] both = new String[javaArgs.length + args.length + (setMessageHolderOnForking ? 2 : 0)]; System.arraycopy(javaArgs,0,both,0,javaArgs.length); System.arraycopy(args,0,both,javaArgs.length,args.length); if (setMessageHolderOnForking) { both[both.length - 2] = "-messageHolder"; both[both.length - 1] = this.messageHolder.getClass().getName(); } // try to use javaw instead on windows if (both[0].endsWith("java.exe")) { String path = both[0]; path = path.substring(0, path.length()-4); path = path + "w.exe"; File javaw = new File(path); if (javaw.canRead() && javaw.isFile()) { both[0] = path; } } logVerbose("forking " + Arrays.asList(both)); int result = execInOtherVM(both); if (0 > result) { throw new BuildException("failure[" + result + "] running ajc"); } else if (failonerror && (0 < result)) { throw new BuildException("compile errors: " + result); } // when forking, do completion only at end and when successful doCompletionTasks(); } finally { if (null != tempFile) { tempFile.delete(); } } } /** * Execute in another process using the same JDK * and the base directory of the project. XXX correct? * @param args * @return */ protected int execInOtherVM(String[] args) { try { Project project = getProject(); PumpStreamHandler handler = new LogStreamHandler(this, verbose ? Project.MSG_VERBOSE : Project.MSG_INFO, Project.MSG_WARN); // replace above two lines with what follows as an aid to debugging when running the unit tests.... // LogStreamHandler handler = new LogStreamHandler(this, // Project.MSG_INFO, Project.MSG_WARN) { // // ByteArrayOutputStream baos = new ByteArrayOutputStream(); // /* (non-Javadoc) // * @see org.apache.tools.ant.taskdefs.PumpStreamHandler#createProcessOutputPump(java.io.InputStream, java.io.OutputStream) // */ // protected void createProcessErrorPump(InputStream is, // OutputStream os) { // super.createProcessErrorPump(is, baos); // } // // /* (non-Javadoc) // * @see org.apache.tools.ant.taskdefs.LogStreamHandler#stop() // */ // public void stop() { // byte[] written = baos.toByteArray(); // System.err.print(new String(written)); // super.stop(); // } // }; Execute exe = new Execute(handler); exe.setAntRun(project); exe.setWorkingDirectory(project.getBaseDir()); exe.setCommandline(args); try { if (executingInOtherVM) { String s = "already running in other vm?"; throw new BuildException(s, location); } executingInOtherVM = true; exe.execute(); } finally { executingInOtherVM = false; } return exe.getExitValue(); } catch (IOException e) { String m = "Error executing command " + Arrays.asList(args); throw new BuildException(m, e, location); } } // ------------------------------ setup and reporting /** @return null if path null or empty, String rendition otherwise */ protected static void addFlaggedPath(String flag, Path path, List list) { if (!LangUtil.isEmpty(flag) && ((null != path) && (0 < path.size()))) { list.add(flag); list.add(path.toString()); } } /** * Add to list any path or plural arguments. */ protected void addListArgs(List list) throws BuildException { addFlaggedPath("-classpath", classpath, list); addFlaggedPath("-bootclasspath", bootclasspath, list); addFlaggedPath("-extdirs", extdirs, list); addFlaggedPath("-aspectpath", aspectpath, list); addFlaggedPath("-injars", injars, list); addFlaggedPath("-inpath", inpath, list); addFlaggedPath("-sourceroots", sourceRoots, list); if (argfiles != null) { String[] files = argfiles.list(); for (int i = 0; i < files.length; i++) { File argfile = project.resolveFile(files[i]); if (check(argfile, files[i], false, location)) { list.add("-argfile"); list.add(argfile.getAbsolutePath()); } } } if (srcdir != null) { // todo: ignore any srcdir if any argfiles and no explicit includes String[] dirs = srcdir.list(); for (int i = 0; i < dirs.length; i++) { File dir = project.resolveFile(dirs[i]); check(dir, dirs[i], true, location); // relies on compiler to prune non-source files String[] files = getDirectoryScanner(dir).getIncludedFiles(); for (int j = 0; j < files.length; j++) { File file = new File(dir, files[j]); if (FileUtil.hasSourceSuffix(file)) { list.add(file.getAbsolutePath()); } } } } if (0 < adapterFiles.size()) { for (Iterator iter = adapterFiles.iterator(); iter.hasNext();) { File file = (File) iter.next(); if (file.canRead() && FileUtil.hasSourceSuffix(file)) { list.add(file.getAbsolutePath()); } else { this.logger.warning("skipping file: " + file); } } } } /** * Throw BuildException unless file is valid. * @param file the File to check * @param name the symbolic name to print on error * @param isDir if true, verify file is a directory * @param loc the Location used to create sensible BuildException * @return * @throws BuildException unless file valid */ protected final boolean check(File file, String name, boolean isDir, Location loc) { loc = loc != null ? loc : location; if (file == null) { throw new BuildException(name + " is null!", loc); } if (!file.exists()) { throw new BuildException(file + " doesn't exist!", loc); } if (isDir ^ file.isDirectory()) { String e = file + " should" + (isDir ? "" : "n't") + " be a directory!"; throw new BuildException(e, loc); } return true; } /** * Called when compile or incremental compile is completing, * this completes the output jar or directory * by copying resources if requested. * Note: this is a callback run synchronously by the compiler. * That means exceptions thrown here are caught by Main.run(..) * and passed to the message handler. */ protected void doCompletionTasks() { if (!executing) { throw new IllegalStateException("should be executing"); } if (null != outjar) { completeOutjar(); } else { completeDestdir(); } if (null != xdoneSignal) { MessageUtil.info(messageHolder, xdoneSignal); } } /** * Complete the destination directory * by copying resources from the source root directories * (if the filter is specified) * and non-.class files from the input jars * (if XCopyInjars is enabled). */ private void completeDestdir() { if (!copyInjars && (null == sourceRootCopyFilter) && (null == inpathDirCopyFilter)) { return; } else if ((destDir == DEFAULT_DESTDIR) || !destDir.canWrite()) { String s = "unable to copy resources to destDir: " + destDir; throw new BuildException(s); } final Project project = getProject(); if (copyInjars) { // XXXX remove as unused since 1.1.1 if (null != inpath) { log("copyInjars does not support inpath.\n", Project.MSG_WARN); } String taskName = getTaskName() + " - unzip"; String[] paths = injars.list(); if (!LangUtil.isEmpty(paths)) { PatternSet patternSet = new PatternSet(); patternSet.setProject(project); patternSet.setIncludes("**/*"); patternSet.setExcludes("**/*.class"); for (int i = 0; i < paths.length; i++) { Expand unzip = new Expand(); unzip.setProject(project); unzip.setTaskName(taskName); unzip.setDest(destDir); unzip.setSrc(new File(paths[i])); unzip.addPatternset(patternSet); unzip.execute(); } } } if ((null != sourceRootCopyFilter) && (null != sourceRoots)) { String[] paths = sourceRoots.list(); if (!LangUtil.isEmpty(paths)) { Copy copy = new Copy(); copy.setProject(project); copy.setTodir(destDir); for (int i = 0; i < paths.length; i++) { FileSet fileSet = new FileSet(); fileSet.setDir(new File(paths[i])); fileSet.setIncludes("**/*"); fileSet.setExcludes(sourceRootCopyFilter); copy.addFileset(fileSet); } copy.execute(); } } if ((null != inpathDirCopyFilter) && (null != inpath)) { String[] paths = inpath.list(); if (!LangUtil.isEmpty(paths)) { Copy copy = new Copy(); copy.setProject(project); copy.setTodir(destDir); boolean gotDir = false; for (int i = 0; i < paths.length; i++) { File inpathDir = new File(paths[i]); if (inpathDir.isDirectory() && inpathDir.canRead()) { if (!gotDir) { gotDir = true; } FileSet fileSet = new FileSet(); fileSet.setDir(inpathDir); fileSet.setIncludes("**/*"); fileSet.setExcludes(inpathDirCopyFilter); copy.addFileset(fileSet); } } if (gotDir) { copy.execute(); } } } } /** * Complete the output jar * by copying resources from the source root directories * if the filter is specified. * and non-.class files from the input jars if enabled. */ private void completeOutjar() { if (((null == tmpOutjar) || !tmpOutjar.canRead()) || (!copyInjars && (null == sourceRootCopyFilter) && (null == inpathDirCopyFilter))) { return; } Zip zip = new Zip(); Project project = getProject(); zip.setProject(project); zip.setTaskName(getTaskName() + " - zip"); zip.setDestFile(outjar); ZipFileSet zipfileset = new ZipFileSet(); zipfileset.setProject(project); zipfileset.setSrc(tmpOutjar); zipfileset.setIncludes("**/*.class"); zip.addZipfileset(zipfileset); if (copyInjars) { String[] paths = injars.list(); if (!LangUtil.isEmpty(paths)) { for (int i = 0; i < paths.length; i++) { File jarFile = new File(paths[i]); zipfileset = new ZipFileSet(); zipfileset.setProject(project); zipfileset.setSrc(jarFile); zipfileset.setIncludes("**/*"); zipfileset.setExcludes("**/*.class"); zip.addZipfileset(zipfileset); } } } if ((null != sourceRootCopyFilter) && (null != sourceRoots)) { String[] paths = sourceRoots.list(); if (!LangUtil.isEmpty(paths)) { for (int i = 0; i < paths.length; i++) { File srcRoot = new File(paths[i]); FileSet fileset = new FileSet(); fileset.setProject(project); fileset.setDir(srcRoot); fileset.setIncludes("**/*"); fileset.setExcludes(sourceRootCopyFilter); zip.addFileset(fileset); } } } if ((null != inpathDirCopyFilter) && (null != inpath)) { String[] paths = inpath.list(); if (!LangUtil.isEmpty(paths)) { for (int i = 0; i < paths.length; i++) { File inpathDir = new File(paths[i]); if (inpathDir.isDirectory() && inpathDir.canRead()) { FileSet fileset = new FileSet(); fileset.setProject(project); fileset.setDir(inpathDir); fileset.setIncludes("**/*"); fileset.setExcludes(inpathDirCopyFilter); zip.addFileset(fileset); } } } } zip.execute(); } // -------------------------- compiler adapter interface extras /** * Add specified source files. */ void addFiles(File[] paths) { for (int i = 0; i < paths.length; i++) { addFile(paths[i]); } } /** * Add specified source file. */ void addFile(File path) { if (null != path) { adapterFiles.add(path); } } /** * Read arguments in as if from a command line, * mainly to support compiler adapter compilerarg subelement. * * @param args the String[] of arguments to read */ public void readArguments(String[] args) { // XXX slow, stupid, unmaintainable if ((null == args) || (0 == args.length)) { return; } /** String[] wrapper with increment, error reporting */ class Args { final String[] args; int index = 0; Args(String[] args) { this.args = args; // not null or empty } boolean hasNext() { return index < args.length; } String next() { String err = null; if (!hasNext()) { err = "need arg for flag " + args[args.length-1]; } else { String s = args[index++]; if (null == s) { err = "null value"; } else { s = s.trim(); if (0 == s.trim().length()) { err = "no value"; } else { return s; } } } err += " at [" + index + "] of " + Arrays.asList(args); throw new BuildException(err); } } // class Args Args in = new Args(args); String flag; while (in.hasNext()) { flag = in.next(); if ("-1.3".equals(flag)) { setCompliance(flag); } else if ("-1.4".equals(flag)) { setCompliance(flag); } else if ("-1.5".equals(flag)) { setCompliance("1.5"); } else if ("-argfile".equals(flag)) { setArgfiles(new Path(project, in.next())); } else if ("-aspectpath".equals(flag)) { setAspectpath(new Path(project, in.next())); } else if ("-classpath".equals(flag)) { setClasspath(new Path(project, in.next())); } else if ("-extdirs".equals(flag)) { setExtdirs(new Path(project, in.next())); } else if ("-Xcopyinjars".equals(flag)) { setCopyInjars(true); // ignored - will be flagged by setter } else if ("-g".equals(flag)) { setDebug(true); } else if (flag.startsWith("-g:")) { setDebugLevel(flag.substring(2)); } else if ("-deprecation".equals(flag)) { setDeprecation(true); } else if ("-d".equals(flag)) { setDestdir(new File(in.next())); } else if ("-crossrefs".equals(flag)) { setCrossrefs(true); } else if ("-emacssym".equals(flag)) { setEmacssym(true); } else if ("-encoding".equals(flag)) { setEncoding(in.next()); } else if ("-Xfailonerror".equals(flag)) { setFailonerror(true); } else if ("-fork".equals(flag)) { setFork(true); } else if ("-forkclasspath".equals(flag)) { setForkclasspath(new Path(project, in.next())); } else if ("-help".equals(flag)) { setHelp(true); } else if ("-incremental".equals(flag)) { setIncremental(true); } else if ("-injars".equals(flag)) { setInjars(new Path(project, in.next())); } else if ("-inpath".equals(flag)) { setInpath(new Path(project,in.next())); } else if ("-Xlistfileargs".equals(flag)) { setListFileArgs(true); } else if ("-Xmaxmem".equals(flag)) { setMaxmem(in.next()); } else if ("-Xmessageholderclass".equals(flag)) { setMessageHolderClass(in.next()); } else if ("-noexit".equals(flag)) { setNoExit(true); } else if ("-noimport".equals(flag)) { setNoExit(true); } else if ("-noExit".equals(flag)) { setNoExit(true); } else if ("-noImportError".equals(flag)) { setNoImportError(true); } else if ("-noWarn".equals(flag)) { setNowarn(true); } else if ("-noexit".equals(flag)) { setNoExit(true); } else if ("-outjar".equals(flag)) { setOutjar(new File(in.next())); } else if ("-outxml".equals(flag)) { setOutxml(true); } else if ("-outxmlfile".equals(flag)) { setOutxmlfile(in.next()); } else if ("-preserveAllLocals".equals(flag)) { setPreserveAllLocals(true); } else if ("-proceedOnError".equals(flag)) { setProceedOnError(true); } else if ("-referenceInfo".equals(flag)) { setReferenceInfo(true); } else if ("-source".equals(flag)) { setSource(in.next()); } else if ("-Xsourcerootcopyfilter".equals(flag)) { setSourceRootCopyFilter(in.next()); } else if ("-sourceroots".equals(flag)) { setSourceRoots(new Path(project, in.next())); } else if ("-Xsrcdir".equals(flag)) { setSrcDir(new Path(project, in.next())); } else if ("-Xtagfile".equals(flag)) { setTagFile(new File(in.next())); } else if ("-target".equals(flag)) { setTarget(in.next()); } else if ("-time".equals(flag)) { setTime(true); } else if ("-time".equals(flag)) { setTime(true); } else if ("-verbose".equals(flag)) { setVerbose(true); } else if ("-showWeaveInfo".equals(flag)) { setShowWeaveInfo(true); } else if ("-version".equals(flag)) { setVersion(true); } else if ("-warn".equals(flag)) { setWarn(in.next()); } else if (flag.startsWith("-warn:")) { setWarn(flag.substring(6)); } else if ("-Xlint".equals(flag)) { setXlintwarnings(true); } else if (flag.startsWith("-Xlint:")) { setXlint(flag.substring(7)); } else if ("-Xlintfile".equals(flag)) { setXlintfile(new File(in.next())); } else if ("-XterminateAfterCompilation".equals(flag)) { setXTerminateAfterCompilation(true); } else if ("-Xreweavable".equals(flag)) { setXReweavable(true); } else if ("-XnotReweavable".equals(flag)) { setXNotReweavable(true); } else if (flag.startsWith("@")) { File file = new File(flag.substring(1)); if (file.canRead()) { setArgfiles(new Path(project, file.getPath())); } else { ignore(flag); } } else { File file = new File(flag); if (file.isFile() && file.canRead() && FileUtil.hasSourceSuffix(file)) { addFile(file); } else { ignore(flag); } } } } protected void logVerbose(String text) { if (this.verbose) { this.logger.info(text); } else { this.logger.verbose(text); } } /** * Commandline wrapper that * only permits addition of non-empty values * and converts to argfile form if necessary. */ public static class GuardedCommand { Commandline command; //int size; static boolean isEmpty(String s) { return ((null == s) || (0 == s.trim().length())); } GuardedCommand() { command = new Commandline(); } void addFlag(String flag, boolean doAdd) { if (doAdd && !isEmpty(flag)) { command.createArgument().setValue(flag); //size += 1 + flag.length(); } } /** @return null if added or ignoreString otherwise */ String addOption(String prefix, String[] validOptions, String input) { if (isEmpty(input)) { return null; } for (int i = 0; i < validOptions.length; i++) { if (input.equals(validOptions[i])) { if (isEmpty(prefix)) { addFlag(input, true); } else { addFlagged(prefix, input); } return null; } } return (null == prefix ? input : prefix + " " + input); } void addFlagged(String flag, String argument) { if (!isEmpty(flag) && !isEmpty(argument)) { command.addArguments(new String[] {flag, argument}); //size += 1 + flag.length() + argument.length(); } } // private void addFile(File file) { // if (null != file) { // String path = file.getAbsolutePath(); // addFlag(path, true); // } // } List extractArguments() { ArrayList result = new ArrayList(); String[] cmds = command.getArguments(); if (!LangUtil.isEmpty(cmds)) { result.addAll(Arrays.asList(cmds)); } return result; } /** * Adjust args for size if necessary by creating * an argument file, which should be deleted by the client * after the compiler run has completed. * @param max the int maximum length of the command line (in char) * @return the temp File for the arguments (if generated), * for deletion when done. * @throws IllegalArgumentException if max is negative */ static String[] limitTo(String[] args, int max, Location location) { if (max < 0) { throw new IllegalArgumentException("negative max: " + max); } // sigh - have to count anyway for now int size = 0; for (int i = 0; (i < args.length) && (size < max); i++) { size += 1 + (null == args[i] ? 0 : args[i].length()); } if (size <= max) { return args; } File tmpFile = null; PrintWriter out = null; // adapted from DefaultCompilerAdapter.executeExternalCompile try { String userDirName = System.getProperty("user.dir"); File userDir = new File(userDirName); tmpFile = File.createTempFile("argfile", "", userDir); out = new PrintWriter(new FileWriter(tmpFile)); for (int i = 0; i < args.length; i++) { out.println(args[i]); } out.flush(); return new String[] {"-argfile", tmpFile.getAbsolutePath()}; } catch (IOException e) { throw new BuildException("Error creating temporary file", e, location); } finally { if (out != null) { try {out.close();} catch (Throwable t) {} } } } } private static class AntMessageHandler implements IMessageHandler { private TaskLogger logger; private final boolean taskLevelVerbose; private final boolean handledMessage; public AntMessageHandler(TaskLogger logger, boolean taskVerbose, boolean handledMessage) { this.logger = logger; this.taskLevelVerbose = taskVerbose; this.handledMessage = handledMessage; } /* (non-Javadoc) * @see org.aspectj.bridge.IMessageHandler#handleMessage(org.aspectj.bridge.IMessage) */ public boolean handleMessage(IMessage message) throws AbortException { Kind messageKind = message.getKind(); String messageText = message.toString(); if (messageKind == IMessage.ABORT) { this.logger.error(messageText); } else if (messageKind == IMessage.DEBUG) { this.logger.debug(messageText); } else if (messageKind == IMessage.ERROR) { this.logger.error(messageText); } else if (messageKind == IMessage.FAIL){ this.logger.error(messageText); } else if (messageKind == IMessage.INFO) { if (this.taskLevelVerbose) { this.logger.info(messageText); } else { this.logger.verbose(messageText); } } else if (messageKind == IMessage.WARNING) { this.logger.warning(messageText); } else if (messageKind == IMessage.WEAVEINFO) { this.logger.info(messageText); } else if (messageKind == IMessage.TASKTAG) { // ignore } else { throw new BuildException("Unknown message kind from AspectJ compiler: " + messageKind.toString()); } return handledMessage; } /* (non-Javadoc) * @see org.aspectj.bridge.IMessageHandler#isIgnoring(org.aspectj.bridge.IMessage.Kind) */ public boolean isIgnoring(Kind kind) { return false; } /* (non-Javadoc) * @see org.aspectj.bridge.IMessageHandler#dontIgnore(org.aspectj.bridge.IMessage.Kind) */ public void dontIgnore(Kind kind) { } /* (non-Javadoc) * @see org.aspectj.bridge.IMessageHandler#ignore(org.aspectj.bridge.IMessage.Kind) */ public void ignore(Kind kind) { } } }
171,667
Bug 171667 When ordering a Clean with Build Automatico I receive the error below.
When executing an Clean Project in Eclipse with Automatic Building I receive the error below. line from the top stack, e.g. "SomeFile.jara:243" java.lang.NullPointerException at org.aspectj.ajdt.internal.compiler.problem.AjProblemReporter.methodMustOverride(AjProblemReporter.java:380) at org.aspectj.org.eclipse.jdt.internal.compiler.ast.MethodDeclaration.resolveStatements(MethodDeclaration.java:153) at org.aspectj.org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration.resolve(AbstractMethodDeclaration.java:400) at org.aspectj.org.eclipse.jdt.internal.compiler.ast.TypeDe ... pter.java:107) at org.aspectj.ajde.internal.AspectJBuildManager$CompilerThread.run(AspectJBuildManager.java:191) NullPointerException thrown: null
resolved fixed
4177bed
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2007-02-16T10:02:27Z"
"2007-01-25T15:46: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.Iterator; import java.util.List; import org.aspectj.ajdt.internal.compiler.ast.AspectDeclaration; 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.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.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.problem.ProblemReporter; import org.aspectj.util.FuzzyBoolean; import org.aspectj.weaver.AjcMemberMaker; import org.aspectj.weaver.ConcreteTypeMunger; 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); } 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(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 != Ignore && DUMP_STACK) { Thread.dumpStack(); } super.handle( problemId, problemArguments, 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) { MethodBinding binding = method.binding; // 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(); ResolvedMember rm = AjcMemberMaker.interMethod(sig,m.getAspectType(), sig.getDeclaringType().resolve(factory.getWorld()).isInterface()); if (ResolvedType.matches(rm,possiblyErroneousRm)) { // match, so dont need to report a problem! return; } } supertypeToLookAt = supertypeToLookAt.getSuperclass(); } // report the error... super.methodMustOverride(method); } 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 = (Object) 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 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!=null && 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; } } 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)) 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); 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();} } }
175,039
Bug 175039 ArrayIndexOutOfBoundException Bug with Nested Type in TypeParameters
I debugged this stack trace from load-time weaving (ajcore files are also available). I found that the signature argument to TypeFactory.createTypeFromSignature(String) is Pjava/lang/Enum<Ljavax/jws/soap/SOAPBinding$ParameterStyle;>; but the method is erroneously using an empty array of parameters, because it thinks the $ relates to the generic type, not the parameter. It should be fairly easy to reproduce with a test case and to fix with a patch - I'll look at it some more tonight or this week. java.lang.ArrayIndexOutOfBoundsException at org.aspectj.weaver.ResolvedType.getMemberParameterizationMap(ResolvedType.java:698) at org.aspectj.weaver.ReferenceType.getDeclaredInterfaces(ReferenceType.java:406) at org.aspectj.weaver.ResolvedType.getDirectSupertypes(ResolvedType.java:65) at org.aspectj.weaver.patterns.TypePattern.matchesSubtypes(TypePattern.java:182) at org.aspectj.weaver.patterns.TypePattern.matchesSubtypes(TypePattern.java:169) at org.aspectj.weaver.patterns.TypePattern.matchesStatically(TypePattern.java:119) at org.aspectj.weaver.loadtime.ClassLoaderWeavingAdaptor.accept(ClassLoaderWeavingAdaptor.java:621) at org.aspectj.weaver.tools.WeavingAdaptor.weaveClass(WeavingAdaptor.java:253) at org.aspectj.weaver.loadtime.Aj.preProcess(Aj.java:78) at org.aspectj.weaver.loadtime.ClassPreProcessorAgentAdapter.transform(ClassPreProcessorAgentAdapter.java:52) at sun.instrument.TransformerManager.transform(TransformerManager.java:122) at sun.instrument.InstrumentationImpl.transform(InstrumentationImpl.java:155) at java.lang.ClassLoader.defineClass(Ljava.lang.String;[BIILjava.security.ProtectionDomain;)Ljava.lang.Class;(Unknown Source) at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:124) at java.net.URLClassLoader.defineClass(URLClassLoader.java:260) at java.net.URLClassLoader.access$100(URLClassLoader.java:56) at java.net.URLClassLoader$1.run(URLClassLoader.java:195) at java.net.URLClassLoader.findClass(URLClassLoader.java:188) at java.lang.ClassLoader.loadClass(Ljava.lang.String;Z)Ljava.lang.Class;(Unknown Source) at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:268) at java.lang.ClassLoader.loadClass(Ljava.lang.String;)Ljava.lang.Class;(Unknown Source) at java.lang.ClassLoader.loadClassFromNative(Ljava.lang.String;)Ljava.lang.Class;(Unknown Source) at java.lang.Class.forName(Ljava.lang.String;ZLjava.lang.ClassLoader;)Ljava.lang.Class;(Unknown Source) at jrockit.reflect.MemberAccess.getClassFromFieldDesc(Ljava.lang.String;ILjava.lang.ClassLoader;)Ljava.lang.Class;(Unknown Source) at jrockit.reflect.MemberAccess.getReturnClassFromMethodDesc(Ljava.lang.String;Ljava.lang.ClassLoader;)Ljava.lang.Class;(Unknown Source)
resolved fixed
579ec14
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2007-03-06T09:59:56Z"
"2007-02-21T20:33:20Z"
weaver/src/org/aspectj/weaver/TypeFactory.java
/* ******************************************************************* * Copyright (c) 2005 Contributors. * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Eclipse Public License v1.0 * which accompanies this distribution and is available at * http://eclipse.org/legal/epl-v10.html * * Contributors: * Adrian Colyer Initial implementation * ******************************************************************/ package org.aspectj.weaver; import java.util.ArrayList; import java.util.List; import org.aspectj.weaver.UnresolvedType.TypeKind; /** * @author colyer * */ public class TypeFactory { /** * Create a parameterized version of a generic type. * @param aGenericType * @param someTypeParameters note, in the case of an inner type of a parameterized type, * this parameter may legitimately be null * @param inAWorld * @return */ public static ReferenceType createParameterizedType( ResolvedType aBaseType, UnresolvedType[] someTypeParameters, World inAWorld ) { ResolvedType baseType = aBaseType; if (!aBaseType.isGenericType()) { // try and find the generic type... if (someTypeParameters != null && someTypeParameters.length>0) { if (!aBaseType.isRawType()) throw new IllegalStateException("Expecting raw type, not: "+aBaseType); baseType = baseType.getGenericType(); if (baseType == null) throw new IllegalStateException("Raw type does not have generic type set"); } // else if someTypeParameters is null, then the base type is allowed to be non-generic, it's an inner } ResolvedType[] resolvedParameters = inAWorld.resolve(someTypeParameters); ReferenceType pType = new ReferenceType(baseType,resolvedParameters,inAWorld); // pType.setSourceContext(aBaseType.getSourceContext()); return (ReferenceType) pType.resolve(inAWorld); } /** * Create an *unresolved* parameterized version of a generic type. */ public static UnresolvedType createUnresolvedParameterizedType(String sig,String erasuresig,UnresolvedType[] arguments) { return new UnresolvedType(sig,erasuresig,arguments); } public static ReferenceType createRawType( ResolvedType aBaseType, World inAWorld ) { if (aBaseType.isRawType()) return (ReferenceType) aBaseType; if (!aBaseType.isGenericType()) { if (!aBaseType.isRawType()) throw new IllegalStateException("Expecting generic type"); } ReferenceType rType = new ReferenceType(aBaseType,inAWorld); //rType.setSourceContext(aBaseType.getSourceContext()); return (ReferenceType) rType.resolve(inAWorld); } /** * Creates a sensible unresolvedtype from some signature, for example: * signature = LIGuard<TT;>; * bound = toString=IGuard<T> sig=PIGuard<TT;>; sigErasure=LIGuard; kind=parameterized */ private static UnresolvedType convertSigToType(String aSignature) { UnresolvedType bound = null; int startOfParams = aSignature.indexOf('<'); if (startOfParams==-1) { bound = UnresolvedType.forSignature(aSignature); } else { int endOfParams = aSignature.lastIndexOf('>'); String signatureErasure = "L" + aSignature.substring(1,startOfParams) + ";"; UnresolvedType[] typeParams = createTypeParams(aSignature.substring(startOfParams +1, endOfParams)); bound = new UnresolvedType("P"+aSignature.substring(1),signatureErasure,typeParams); } return bound; } /** * Used by UnresolvedType.read, creates a type from a full signature. * @param signature * @return */ public static UnresolvedType createTypeFromSignature(String signature) { if (signature.equals(ResolvedType.MISSING_NAME)) return ResolvedType.MISSING; char firstChar = signature.charAt(0); if (firstChar=='P') { // parameterized type, calculate signature erasure and type parameters // (see pr122458) It is possible for a parameterized type to have *no* type parameters visible in its signature. // This happens for an inner type of a parameterized type which simply inherits the type parameters // of its parent. In this case it is parameterized but theres no < in the signature. int startOfParams = signature.indexOf('<'); if (startOfParams==-1) { // Should be an inner type of a parameterized type - could assert there is a '$' in the signature.... String signatureErasure = "L" + signature.substring(1); UnresolvedType[] typeParams = new UnresolvedType[0]; return new UnresolvedType(signature,signatureErasure,typeParams); } else { int endOfParams = locateMatchingEndBracket(signature,startOfParams);//signature.lastIndexOf('>'); StringBuffer erasureSig = new StringBuffer(signature); while (startOfParams!=-1) { erasureSig.delete(startOfParams,endOfParams+1); startOfParams = locateFirstBracket(erasureSig); if (startOfParams!=-1) endOfParams = locateMatchingEndBracket(erasureSig,startOfParams); } String signatureErasure = "L" + erasureSig.toString().substring(1); // the type parameters of interest are only those that apply to the 'last type' in the signature // if the signature is 'PMyInterface<String>$MyOtherType;' then there are none... String lastType = null; int nestedTypePosition = signature.indexOf("$"); if (nestedTypePosition!=-1) lastType = signature.substring(nestedTypePosition+1); else lastType = new String(signature); startOfParams = lastType.indexOf("<"); endOfParams = locateMatchingEndBracket(lastType,startOfParams); UnresolvedType[] typeParams = UnresolvedType.NONE; if (startOfParams!=-1) { typeParams = createTypeParams(lastType.substring(startOfParams +1, endOfParams)); } return new UnresolvedType(signature,signatureErasure,typeParams); } // can't replace above with convertSigToType - leads to stackoverflow } else if (signature.equals("?")){ UnresolvedType ret = UnresolvedType.SOMETHING; ret.typeKind = TypeKind.WILDCARD; return ret; } else if(firstChar=='+') { // ? extends ... UnresolvedType ret = new UnresolvedType(signature); ret.typeKind = TypeKind.WILDCARD; // UnresolvedType bound1 = UnresolvedType.forSignature(signature.substring(1)); // UnresolvedType bound2 = convertSigToType(signature.substring(1)); ret.setUpperBound(convertSigToType(signature.substring(1))); return ret; } else if (firstChar=='-') { // ? super ... // UnresolvedType bound = UnresolvedType.forSignature(signature.substring(1)); // UnresolvedType bound2 = convertSigToType(signature.substring(1)); UnresolvedType ret = new UnresolvedType(signature); ret.typeKind = TypeKind.WILDCARD; ret.setLowerBound(convertSigToType(signature.substring(1))); return ret; } else if (firstChar=='T') { String typeVariableName = signature.substring(1); if (typeVariableName.endsWith(";")) { typeVariableName = typeVariableName.substring(0, typeVariableName.length() -1); } return new UnresolvedTypeVariableReferenceType(new TypeVariable(typeVariableName)); } else if (firstChar=='[') { int dims = 0; while (signature.charAt(dims)=='[') dims++; UnresolvedType componentType = createTypeFromSignature(signature.substring(dims)); return new UnresolvedType(signature, signature.substring(0,dims)+componentType.getErasureSignature()); } else if (signature.length()==1) { // could be a primitive switch (firstChar) { case 'V': return ResolvedType.VOID; case 'Z': return ResolvedType.BOOLEAN; case 'B': return ResolvedType.BYTE; case 'C': return ResolvedType.CHAR; case 'D': return ResolvedType.DOUBLE; case 'F': return ResolvedType.FLOAT; case 'I': return ResolvedType.INT; case 'J': return ResolvedType.LONG; case 'S': return ResolvedType.SHORT; } } return new UnresolvedType(signature); } private static int locateMatchingEndBracket(String signature, int startOfParams) { if (startOfParams==-1) return -1; int count =1; int idx = startOfParams; while (count>0 && idx<signature.length()) { idx++; if (signature.charAt(idx)=='<') count++; if (signature.charAt(idx)=='>') count--; } return idx; } private static int locateMatchingEndBracket(StringBuffer signature, int startOfParams) { if (startOfParams==-1) return -1; int count =1; int idx = startOfParams; while (count>0 && idx<signature.length()) { idx++; if (signature.charAt(idx)=='<') count++; if (signature.charAt(idx)=='>') count--; } return idx; } private static int locateFirstBracket(StringBuffer signature) { int idx = 0; while (idx<signature.length()) { if (signature.charAt(idx)=='<') return idx; idx++; } return -1; } private static UnresolvedType[] createTypeParams(String typeParameterSpecification) { String remainingToProcess = typeParameterSpecification; List types = new ArrayList(); while(!remainingToProcess.equals("")) { int endOfSig = 0; int anglies = 0; boolean sigFound = false; for (endOfSig = 0; (endOfSig < remainingToProcess.length()) && !sigFound; endOfSig++) { char thisChar = remainingToProcess.charAt(endOfSig); switch(thisChar) { case '<' : anglies++; break; case '>' : anglies--; break; case ';' : if (anglies == 0) { sigFound = true; break; } } } types.add(createTypeFromSignature(remainingToProcess.substring(0,endOfSig))); remainingToProcess = remainingToProcess.substring(endOfSig); } UnresolvedType[] typeParams = new UnresolvedType[types.size()]; types.toArray(typeParams); return typeParams; } }
175,039
Bug 175039 ArrayIndexOutOfBoundException Bug with Nested Type in TypeParameters
I debugged this stack trace from load-time weaving (ajcore files are also available). I found that the signature argument to TypeFactory.createTypeFromSignature(String) is Pjava/lang/Enum<Ljavax/jws/soap/SOAPBinding$ParameterStyle;>; but the method is erroneously using an empty array of parameters, because it thinks the $ relates to the generic type, not the parameter. It should be fairly easy to reproduce with a test case and to fix with a patch - I'll look at it some more tonight or this week. java.lang.ArrayIndexOutOfBoundsException at org.aspectj.weaver.ResolvedType.getMemberParameterizationMap(ResolvedType.java:698) at org.aspectj.weaver.ReferenceType.getDeclaredInterfaces(ReferenceType.java:406) at org.aspectj.weaver.ResolvedType.getDirectSupertypes(ResolvedType.java:65) at org.aspectj.weaver.patterns.TypePattern.matchesSubtypes(TypePattern.java:182) at org.aspectj.weaver.patterns.TypePattern.matchesSubtypes(TypePattern.java:169) at org.aspectj.weaver.patterns.TypePattern.matchesStatically(TypePattern.java:119) at org.aspectj.weaver.loadtime.ClassLoaderWeavingAdaptor.accept(ClassLoaderWeavingAdaptor.java:621) at org.aspectj.weaver.tools.WeavingAdaptor.weaveClass(WeavingAdaptor.java:253) at org.aspectj.weaver.loadtime.Aj.preProcess(Aj.java:78) at org.aspectj.weaver.loadtime.ClassPreProcessorAgentAdapter.transform(ClassPreProcessorAgentAdapter.java:52) at sun.instrument.TransformerManager.transform(TransformerManager.java:122) at sun.instrument.InstrumentationImpl.transform(InstrumentationImpl.java:155) at java.lang.ClassLoader.defineClass(Ljava.lang.String;[BIILjava.security.ProtectionDomain;)Ljava.lang.Class;(Unknown Source) at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:124) at java.net.URLClassLoader.defineClass(URLClassLoader.java:260) at java.net.URLClassLoader.access$100(URLClassLoader.java:56) at java.net.URLClassLoader$1.run(URLClassLoader.java:195) at java.net.URLClassLoader.findClass(URLClassLoader.java:188) at java.lang.ClassLoader.loadClass(Ljava.lang.String;Z)Ljava.lang.Class;(Unknown Source) at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:268) at java.lang.ClassLoader.loadClass(Ljava.lang.String;)Ljava.lang.Class;(Unknown Source) at java.lang.ClassLoader.loadClassFromNative(Ljava.lang.String;)Ljava.lang.Class;(Unknown Source) at java.lang.Class.forName(Ljava.lang.String;ZLjava.lang.ClassLoader;)Ljava.lang.Class;(Unknown Source) at jrockit.reflect.MemberAccess.getClassFromFieldDesc(Ljava.lang.String;ILjava.lang.ClassLoader;)Ljava.lang.Class;(Unknown Source) at jrockit.reflect.MemberAccess.getReturnClassFromMethodDesc(Ljava.lang.String;Ljava.lang.ClassLoader;)Ljava.lang.Class;(Unknown Source)
resolved fixed
579ec14
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2007-03-06T09:59:56Z"
"2007-02-21T20:33:20Z"
weaver/testsrc/org/aspectj/weaver/TypeXTestCase.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Eclipse Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * PARC initial implementation * ******************************************************************/ package org.aspectj.weaver; import junit.framework.TestCase; import org.aspectj.testing.util.TestUtil; import org.aspectj.util.LangUtil; import org.aspectj.weaver.bcel.BcelWorld; /** * This is a test case for all the portions of UnresolvedType that don't require a world. */ public class TypeXTestCase extends TestCase { public TypeXTestCase(String name) { super(name); } public void testUnresolvedTypes() { // basic equality String[] testNames = new String[] {"int", "long", "int[]", "boolean[][]", "java.lang.String", "java.lang.String[]", "void" }; String[] testSigs = new String[] {"I", "J", "[I", "[[Z", "Ljava/lang/String;", "[Ljava/lang/String;", "V" }; String[] componentNames = new String[] {null, null, "int", "boolean[]", null, "java.lang.String", null }; int[] sizes = new int[] {1, 2, 1, 1, 1, 1, 0}; boolean[] isPrimitive = new boolean[] { true, true, false, false, false, false, true }; nameSignatureTest(testNames, testSigs); arrayTest(UnresolvedType.forNames(testNames), componentNames); arrayTest(UnresolvedType.forSignatures(testSigs), componentNames); sizeTest(UnresolvedType.forNames(testNames), sizes); sizeTest(UnresolvedType.forSignatures(testSigs), sizes); isPrimitiveTest(UnresolvedType.forSignatures(testSigs), isPrimitive); } public void testNameAndSigWithInners() { UnresolvedType t = UnresolvedType.forName("java.util.Map$Entry"); assertEquals(t.getName(), "java.util.Map$Entry"); assertEquals(t.getSignature(), "Ljava/util/Map$Entry;"); assertEquals(t.getOutermostType(), UnresolvedType.forName("java.util.Map")); assertEquals(UnresolvedType.forName("java.util.Map").getOutermostType(), UnresolvedType.forName("java.util.Map")); } public void testNameAndSigWithParameters() { UnresolvedType t = UnresolvedType.forName("java.util.List<java.lang.String>"); assertEquals(t.getName(),"java.util.List<java.lang.String>"); assertEquals(t.getSignature(),"Pjava/util/List<Ljava/lang/String;>;"); t = UnresolvedType.forSignature("Pjava/util/List<Ljava/lang/String;>;"); assertEquals(t.getName(),"java.util.List<java.lang.String>"); assertEquals(t.getSignature(),"Pjava/util/List<Ljava/lang/String;>;"); t = UnresolvedType.forName("java.util.Map<java.util.String,java.util.List<java.lang.Integer>>"); assertEquals(t.getName(),"java.util.Map<java.util.String,java.util.List<java.lang.Integer>>"); assertEquals(t.getSignature(),"Pjava/util/Map<Ljava/util/String;Pjava/util/List<Ljava/lang/Integer;>;>;"); t = UnresolvedType.forSignature("Pjava/util/Map<Ljava/util/String;Pjava/util/List<Ljava/lang/Integer;>;>;"); assertEquals(t.getName(),"java.util.Map<java.util.String,java.util.List<java.lang.Integer>>"); assertEquals(t.getSignature(),"Pjava/util/Map<Ljava/util/String;Pjava/util/List<Ljava/lang/Integer;>;>;"); } /** * Verify UnresolvedType signature processing creates the right kind of UnresolvedType's from a signature. * * For example, calling UnresolvedType.dump() for * "Ljava/util/Map<Ljava/util/List<Ljava/lang/String;>;Ljava/lang/String;>;" * results in: * UnresolvedType: signature=Ljava/util/Map<Ljava/util/List<Ljava/lang/String;>;Ljava/lang/String;>; parameterized=true #params=2 * UnresolvedType: signature=Ljava/util/List<Ljava/lang/String;>; parameterized=true #params=1 * UnresolvedType: signature=Ljava/lang/String; parameterized=false #params=0 * UnresolvedType: signature=Ljava/lang/String; parameterized=false #params=0 */ public void testTypexGenericSignatureProcessing() { UnresolvedType tx = null; tx = UnresolvedType.forSignature("Pjava/util/Set<Ljava/lang/String;>;"); checkTX(tx,true,1); tx = UnresolvedType.forSignature("Pjava/util/Set<Pjava/util/List<Ljava/lang/String;>;>;"); checkTX(tx,true,1); tx = UnresolvedType.forSignature("Pjava/util/Map<Pjava/util/List<Ljava/lang/String;>;Ljava/lang/String;>;"); checkTX(tx,true,2); checkTX(tx.getTypeParameters()[0],true,1); checkTX(tx.getTypeParameters()[1],false,0); // System.err.println(tx.dump()); } public void testTypeXForParameterizedTypes() { if (LangUtil.is15VMOrGreater()) { // no funny types pre 1.5 World world = new BcelWorld(); UnresolvedType stringType = UnresolvedType.forName("java/lang/String"); ResolvedType listOfStringType = TypeFactory.createParameterizedType( UnresolvedType.forName("java/util/List").resolve(world), new UnresolvedType[] {stringType}, world); assertEquals("1 type param",1,listOfStringType.typeParameters.length); assertEquals(stringType,listOfStringType.typeParameters[0]); assertTrue(listOfStringType.isParameterizedType()); assertFalse(listOfStringType.isGenericType()); } } private void checkTX(UnresolvedType tx,boolean shouldBeParameterized,int numberOfTypeParameters) { assertTrue("Expected parameterization flag to be "+shouldBeParameterized,tx.isParameterizedType()==shouldBeParameterized); if (numberOfTypeParameters==0) { UnresolvedType[] params = tx.getTypeParameters(); assertTrue("Expected 0 type parameters but found "+params.length,params==null || params.length==0); } else { assertTrue("Expected #type parameters to be "+numberOfTypeParameters,tx.getTypeParameters().length==numberOfTypeParameters); } } private void isPrimitiveTest(UnresolvedType[] types, boolean[] isPrimitives) { for (int i = 0, len = types.length; i < len; i++) { UnresolvedType type = types[i]; boolean b = isPrimitives[i]; assertEquals(type + " is primitive: ", b, type.isPrimitiveType()); } } private void sizeTest(UnresolvedType[] types, int[] sizes) { for (int i = 0, len = types.length; i < len; i++) { UnresolvedType type = types[i]; int size = sizes[i]; assertEquals("size of " + type + ": ", size, type.getSize()); } } private void arrayTest(UnresolvedType[] types, String[] components) { for (int i = 0, len = types.length; i < len; i++) { UnresolvedType type = types[i]; String component = components[i]; assertEquals(type + " is array: ", component != null, type.isArray()); if (component != null) assertEquals(type + " componentType: ", component, type.getComponentType().getName()); } } private void nameSignatureTest(String[] ns, String[] ss) { for (int i = 0, len = ns.length; i < len; i++) { String n = ns[i]; String s = ss[i]; UnresolvedType tn = UnresolvedType.forName(n); UnresolvedType ts = UnresolvedType.forSignature(s); assertEquals("forName(n).getName()", n, tn.getName()); assertEquals("forSignature(s).getSignature()", s, ts.getSignature()); assertEquals("forName(n).getSignature()", s, tn.getSignature()); assertEquals("forSignature(n).getName()", n, ts.getName()); TestUtil.assertCommutativeEquals(tn, tn, true); TestUtil.assertCommutativeEquals(ts, ts, true); TestUtil.assertCommutativeEquals(tn, ts, true); for (int j = 0; j < len; j++) { if (i == j) continue; UnresolvedType tn1 = UnresolvedType.forName(ns[j]); UnresolvedType ts1 = UnresolvedType.forSignature(ss[j]); TestUtil.assertCommutativeEquals(tn, tn1, false); TestUtil.assertCommutativeEquals(ts, tn1, false); TestUtil.assertCommutativeEquals(tn, ts1, false); TestUtil.assertCommutativeEquals(ts, ts1, false); } } } }
206,732
Bug 206732 [itds] Problem with ITDs appearing to be applied twice (and clashing) for binary types
As reported by Josh on the mailing list: I have the following 2 files: Advised.aj: package bugs; public class Advised {} aspect ITD { public void Advised.f() {} } Ref.aj: package notbugs; import bugs.Advised; public class Ref { public void g() { new Advised().f(); } } I am attempting to build Advised.aj into a jar, and refer to it from Ref.aj, using the following ant build.xml: <?xml version="1.0"?> <project name="Bugs" basedir="C:\workplace\imds\Bugs" xmlns:aj="antlib:org.aspectj"> <taskdef uri="antlib:org.aspectj" resource="org/aspectj/antlib.xml" classpath="./aspectjtools.jar"/> <target name="clean"> <delete dir="bugs" includes="**/*.class"/> <delete dir="notbugs" includes="**/*.class"/> </target> <target name="task1"> <aj:iajc srcdir="." destdir="." source="1.5" target="1.5"> <classpath location=".\aspectjrt.jar"/> <include name="bugs/Advised.aj"/> </aj:iajc> </target> <target name="task2"> <aj:iajc source="1.5" target="1.5" srcdir="."> <classpath location=".\aspectjrt.jar"/> <aspectpath location="."/> <include name="notbugs/Ref.aj"/> </aj:iajc> </target> </project> From within Eclipse, there are no build errors because this is all one project. On the command line, however, once I execute ant task2, I get the following marvelous error message which suggests that ajc is trying to ITD f into a class it already ITDd f into before: [aj:iajc] error at C:\workplace\imds\Bugs\bugs\Advised.aj:5::77 inter-type declaration from bugs.ITD conflicts with existing member: void bugs.Advised.f() [aj:iajc] MessageHolder: (8 info) (1 error) [aj:iajc] [error 0]: error at C:\workplace\imds\Bugs\bugs\Advised.aj:5::77 inter-type declaration from bugs.ITD conflicts with existing member: void bugs.Advised.f() Let me also say that in my real use-case, the jar produced by task1 will contain aspects that should apply to clients thereof, and as such, that jar should indeed be in the aspectpath (not the classpath) for task2 (unless I am seriously misunderstanding something). How to stop this duplicate attempt to ITD? Josh --- Josh is correct that using aspectpath will pull in the aspects for application to other types, the problem is that when pulling in type Advised, we reapply known ITDs and it clashes with the one added in the original build of the type. Two possible fixes that I am looking at: - don't reapply the ITDs (they are added to ensure type system is consistent) to binary types pulled in from the aspectpath - recognize the ITD is clashing with a member previously applied through the same ITD I am not sure we can determine it came from the aspectpath at the point the clash is detected. I have option (2) already implemented, but I'll try a little more with option 1 before giving up ;)
resolved fixed
797ec4d
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2007-10-18T11:03:05Z"
"2007-10-18T09:33:20Z"
weaver/src/org/aspectj/weaver/ResolvedType.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the 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.List; import java.util.Map; import java.util.Set; import org.aspectj.bridge.IMessage; import org.aspectj.bridge.ISourceLocation; import org.aspectj.bridge.Message; import org.aspectj.bridge.MessageUtil; import org.aspectj.util.FuzzyBoolean; import org.aspectj.weaver.patterns.Declare; import org.aspectj.weaver.patterns.PerClause; public abstract class ResolvedType extends UnresolvedType implements AnnotatedElement { public static final ResolvedType[] EMPTY_RESOLVED_TYPE_ARRAY = new ResolvedType[0]; public static final String PARAMETERIZED_TYPE_IDENTIFIER = "P"; private ResolvedType[] resolvedTypeParams; private String binaryPath; protected World world; protected ResolvedType(String signature, World world) { super(signature); this.world = world; } protected ResolvedType(String signature, String signatureErasure, World world) { super(signature,signatureErasure); this.world = world; } // ---- things that don't require a world /** * Returns an iterator through ResolvedType objects representing all the direct * supertypes of this type. That is, through the superclass, if any, and * all declared interfaces. */ public final Iterator getDirectSupertypes() { Iterator ifacesIterator = Iterators.array(getDeclaredInterfaces()); ResolvedType superclass = getSuperclass(); if (superclass == null) { return ifacesIterator; } else { return Iterators.snoc(ifacesIterator, superclass); } } public abstract ResolvedMember[] getDeclaredFields(); public abstract ResolvedMember[] getDeclaredMethods(); public abstract ResolvedType[] getDeclaredInterfaces(); public abstract ResolvedMember[] getDeclaredPointcuts(); /** * Returns a ResolvedType object representing the superclass of this type, or null. * If this represents a java.lang.Object, a primitive type, or void, this * method returns null. */ public abstract ResolvedType getSuperclass(); /** * Returns the modifiers for this type. * <p/> * See {@link Class#getModifiers()} for a description * of the weirdness of this methods on primitives and arrays. * * @param world the {@link World} in which the lookup is made. * @return an int representing the modifiers for this type * @see java.lang.reflect.Modifier */ public abstract int getModifiers(); // return true if this resolved type couldn't be found (but we know it's name maybe) public boolean isMissing() { return false; } // FIXME asc I wonder if in some circumstances MissingWithKnownSignature should not be considered // 'really' missing as some code can continue based solely on the signature public static boolean isMissing (UnresolvedType unresolved) { if (unresolved instanceof ResolvedType) { ResolvedType resolved = (ResolvedType)unresolved; return resolved.isMissing(); } else return (unresolved == MISSING); } public ResolvedType[] getAnnotationTypes() { return EMPTY_RESOLVED_TYPE_ARRAY; } public final UnresolvedType getSuperclass(World world) { return getSuperclass(); } // This set contains pairs of types whose signatures are concatenated // together, this means with a fast lookup we can tell if two types // are equivalent. static Set validBoxing = new HashSet(); static { validBoxing.add("Ljava/lang/Byte;B"); validBoxing.add("Ljava/lang/Character;C"); validBoxing.add("Ljava/lang/Double;D"); validBoxing.add("Ljava/lang/Float;F"); validBoxing.add("Ljava/lang/Integer;I"); validBoxing.add("Ljava/lang/Long;J"); validBoxing.add("Ljava/lang/Short;S"); validBoxing.add("Ljava/lang/Boolean;Z"); validBoxing.add("BLjava/lang/Byte;"); validBoxing.add("CLjava/lang/Character;"); validBoxing.add("DLjava/lang/Double;"); validBoxing.add("FLjava/lang/Float;"); validBoxing.add("ILjava/lang/Integer;"); validBoxing.add("JLjava/lang/Long;"); validBoxing.add("SLjava/lang/Short;"); validBoxing.add("ZLjava/lang/Boolean;"); } // utilities public ResolvedType getResolvedComponentType() { return null; } public World getWorld() { return world; } // ---- things from object public final boolean equals(Object other) { if (other instanceof ResolvedType) { return this == other; } else { return super.equals(other); } } // ---- difficult things /** * returns an iterator through all of the fields of this type, in order * for checking from JVM spec 2ed 5.4.3.2. This means that the order is * <p/> * <ul><li> fields from current class </li> * <li> recur into direct superinterfaces </li> * <li> recur into superclass </li> * </ul> * <p/> * We keep a hashSet of interfaces that we've visited so we don't spiral * out into 2^n land. */ public Iterator getFields() { final Iterators.Filter dupFilter = Iterators.dupFilter(); Iterators.Getter typeGetter = new Iterators.Getter() { public Iterator get(Object o) { return dupFilter.filter( ((ResolvedType)o).getDirectSupertypes()); } }; Iterators.Getter fieldGetter = new Iterators.Getter() { public Iterator get(Object o) { return Iterators.array(((ResolvedType)o).getDeclaredFields()); } }; return Iterators.mapOver( Iterators.recur(this, typeGetter), fieldGetter); } /** * returns an iterator through all of the methods of this type, in order * for checking from JVM spec 2ed 5.4.3.3. This means that the order is * <p/> * <ul><li> methods from current class </li> * <li> recur into superclass, all the way up, not touching interfaces </li> * <li> recur into all superinterfaces, in some unspecified order </li> * </ul> * <p/> * We keep a hashSet of interfaces that we've visited so we don't spiral * out into 2^n land. * NOTE: Take a look at the javadoc on getMethodsWithoutIterator() to see if * you are sensitive to a quirk in getMethods() */ public Iterator getMethods() { final Iterators.Filter dupFilter = Iterators.dupFilter(); Iterators.Getter ifaceGetter = new Iterators.Getter() { public Iterator get(Object o) { return dupFilter.filter( Iterators.array(((ResolvedType)o).getDeclaredInterfaces()) ); } }; Iterators.Getter methodGetter = new Iterators.Getter() { public Iterator get(Object o) { return Iterators.array(((ResolvedType)o).getDeclaredMethods()); } }; return Iterators.mapOver( Iterators.append( new Iterator() { ResolvedType curr = ResolvedType.this; public boolean hasNext() { return curr != null; } public Object next() { ResolvedType ret = curr; curr = curr.getSuperclass(); return ret; } public void remove() { throw new UnsupportedOperationException(); } }, Iterators.recur(this, ifaceGetter)), methodGetter); } /** * Return a list of methods, first those declared on this class, then those declared on the superclass (recurse) and then those declared * on the superinterfaces. The getMethods() call above doesn't quite work the same as it will (through the iterator) return methods * declared on *this* class twice, once at the start and once at the end - I couldn't debug that problem, so created this alternative. */ public List getMethodsWithoutIterator(boolean includeITDs, boolean allowMissing) { List methods = new ArrayList(); Set knowninterfaces = new HashSet(); addAndRecurse(knowninterfaces,methods,this,includeITDs,allowMissing); return methods; } private void addAndRecurse(Set knowninterfaces,List collector, ResolvedType rtx, boolean includeITDs, boolean allowMissing) { collector.addAll(Arrays.asList(rtx.getDeclaredMethods())); // Add the methods declared on this type // now add all the inter-typed members too if (includeITDs && rtx.interTypeMungers != null) { for (Iterator i = interTypeMungers.iterator(); i.hasNext();) { ConcreteTypeMunger tm = (ConcreteTypeMunger) i.next(); ResolvedMember rm = tm.getSignature(); if (rm != null) { // new parent type munger can have null signature... collector.add(tm.getSignature()); } } } if (!rtx.equals(ResolvedType.OBJECT)) { ResolvedType superType = rtx.getSuperclass(); if (superType != null && !superType.isMissing()) { addAndRecurse(knowninterfaces,collector,superType,includeITDs,allowMissing); // Recurse if we aren't at the top } } ResolvedType[] interfaces = rtx.getDeclaredInterfaces(); // Go through the interfaces on the way back down for (int i = 0; i < interfaces.length; i++) { ResolvedType iface = interfaces[i]; // we need to know if it is an interface from Parent kind munger // as those are used for @AJ ITD and we precisely want to skip those boolean shouldSkip = false; for (int j = 0; j < rtx.interTypeMungers.size(); j++) { ConcreteTypeMunger munger = (ConcreteTypeMunger) rtx.interTypeMungers.get(j); if (munger.getMunger()!=null && munger.getMunger().getKind() == ResolvedTypeMunger.Parent && ((NewParentTypeMunger)munger.getMunger()).getNewParent().equals(iface) // pr171953 ) { shouldSkip = true; break; } } if (!shouldSkip && !knowninterfaces.contains(iface)) { // Dont do interfaces more than once knowninterfaces.add(iface); if (allowMissing && iface.isMissing()) { if (iface instanceof MissingResolvedTypeWithKnownSignature) { ((MissingResolvedTypeWithKnownSignature)iface).raiseWarningOnMissingInterfaceWhilstFindingMethods(); } } else { addAndRecurse(knowninterfaces,collector,iface,includeITDs,allowMissing); } } } } public ResolvedType[] getResolvedTypeParameters() { if (resolvedTypeParams == null) { resolvedTypeParams = world.resolve(typeParameters); } return resolvedTypeParams; } /** * described in JVM spec 2ed 5.4.3.2 */ public ResolvedMember lookupField(Member m) { return lookupMember(m, getFields()); } /** * described in JVM spec 2ed 5.4.3.3. * Doesnt check ITDs. */ public ResolvedMember lookupMethod(Member m) { return lookupMember(m, getMethods()); } public ResolvedMember lookupMethodInITDs(Member m) { if (interTypeMungers != null) { for (Iterator i = interTypeMungers.iterator(); i.hasNext();) { ConcreteTypeMunger tm = (ConcreteTypeMunger) i.next(); if (matches(tm.getSignature(), m)) { return tm.getSignature(); } } } return null; } /** * return null if not found */ private ResolvedMember lookupMember(Member m, Iterator i) { while (i.hasNext()) { ResolvedMember f = (ResolvedMember) i.next(); if (matches(f, m)) return f; if (f.hasBackingGenericMember() && m.getName().equals(f.getName())) { // might be worth checking the method behind the parameterized method (see pr137496) if (matches(f.getBackingGenericMember(),m)) return f; } } return null; //ResolvedMember.Missing; //throw new BCException("can't find " + m); } /** * return null if not found */ private ResolvedMember lookupMember(Member m, ResolvedMember[] a) { for (int i = 0; i < a.length; i++) { ResolvedMember f = a[i]; if (matches(f, m)) return f; } return null; } /** * Looks for the first member in the hierarchy matching aMember. This method * differs from lookupMember(Member) in that it takes into account parameters * which are type variables - which clearly an unresolved Member cannot do since * it does not know anything about type variables. */ public ResolvedMember lookupResolvedMember(ResolvedMember aMember,boolean allowMissing) { Iterator toSearch = null; ResolvedMember found = null; if ((aMember.getKind() == Member.METHOD) || (aMember.getKind() == Member.CONSTRUCTOR)) { toSearch = getMethodsWithoutIterator(true,allowMissing).iterator(); } else { if (aMember.getKind() != Member.FIELD) throw new IllegalStateException("I didn't know you would look for members of kind " + aMember.getKind()); toSearch = getFields(); } while(toSearch.hasNext()) { ResolvedMemberImpl candidate = (ResolvedMemberImpl) toSearch.next(); if (candidate.matches(aMember)) { found = candidate; break; } } return found; } public static boolean matches(Member m1, Member m2) { if (m1 == null) return m2 == null; if (m2 == null) return false; // Check the names boolean equalNames = m1.getName().equals(m2.getName()); if (!equalNames) return false; // Check the signatures boolean equalSignatures = m1.getSignature().equals(m2.getSignature()); if (equalSignatures) return true; // If they aren't the same, we need to allow for covariance ... where one sig might be ()LCar; and // the subsig might be ()LFastCar; - where FastCar is a subclass of Car boolean equalCovariantSignatures = m1.getParameterSignature().equals(m2.getParameterSignature()); if (equalCovariantSignatures) return true; return false; } public static boolean conflictingSignature(Member m1, Member m2) { if (m1 == null || m2 == null) return false; if (!m1.getName().equals(m2.getName())) { return false; } if (m1.getKind() != m2.getKind()) { return false; } if (m1.getKind() == Member.FIELD) { return m1.getDeclaringType().equals(m2.getDeclaringType()); } else if (m1.getKind() == Member.POINTCUT) { return true; } UnresolvedType[] p1 = m1.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 getPointcuts() { final Iterators.Filter dupFilter = Iterators.dupFilter(); // same order as fields Iterators.Getter typeGetter = new Iterators.Getter() { public Iterator get(Object o) { return dupFilter.filter( ((ResolvedType)o).getDirectSupertypes()); } }; Iterators.Getter pointcutGetter = new Iterators.Getter() { public Iterator get(Object o) { //System.err.println("getting for " + o); return Iterators.array(((ResolvedType)o).getDeclaredPointcuts()); } }; return Iterators.mapOver( Iterators.recur(this, typeGetter), pointcutGetter); } public ResolvedPointcutDefinition findPointcut(String name) { //System.err.println("looking for pointcuts " + this); for (Iterator i = getPointcuts(); i.hasNext(); ) { ResolvedPointcutDefinition f = (ResolvedPointcutDefinition) i.next(); //System.err.println(f); if (name.equals(f.getName())) { return f; } } // pr120521 if (!getOutermostType().equals(this)) { ResolvedType outerType = getOutermostType().resolve(world); ResolvedPointcutDefinition rpd = outerType.findPointcut(name); return rpd; } return null; // should we throw an exception here? } // all about collecting CrosscuttingMembers //??? collecting data-structure, shouldn't really be a field public CrosscuttingMembers crosscuttingMembers; public CrosscuttingMembers collectCrosscuttingMembers(boolean shouldConcretizeIfNeeded) { crosscuttingMembers = new CrosscuttingMembers(this,shouldConcretizeIfNeeded); crosscuttingMembers.setPerClause(getPerClause()); crosscuttingMembers.addShadowMungers(collectShadowMungers()); crosscuttingMembers.addTypeMungers(getTypeMungers()); //FIXME AV - skip but needed ?? or ?? crosscuttingMembers.addLateTypeMungers(getLateTypeMungers()); crosscuttingMembers.addDeclares(collectDeclares(!this.doesNotExposeShadowMungers())); crosscuttingMembers.addPrivilegedAccesses(getPrivilegedAccesses()); //System.err.println("collected cc members: " + this + ", " + collectDeclares()); return crosscuttingMembers; } public final Collection collectDeclares(boolean includeAdviceLike) { if (! this.isAspect() ) return Collections.EMPTY_LIST; ArrayList ret = new ArrayList(); //if (this.isAbstract()) { // for (Iterator i = getDeclares().iterator(); i.hasNext();) { // Declare dec = (Declare) i.next(); // if (!dec.isAdviceLike()) ret.add(dec); // } // // if (!includeAdviceLike) return ret; if (!this.isAbstract()) { //ret.addAll(getDeclares()); final Iterators.Filter dupFilter = Iterators.dupFilter(); Iterators.Getter typeGetter = new Iterators.Getter() { public Iterator get(Object o) { return dupFilter.filter( ((ResolvedType)o).getDirectSupertypes()); } }; Iterator typeIterator = Iterators.recur(this, typeGetter); while (typeIterator.hasNext()) { ResolvedType ty = (ResolvedType) typeIterator.next(); //System.out.println("super: " + ty + ", " + ); for (Iterator i = ty.getDeclares().iterator(); i.hasNext();) { Declare dec = (Declare) i.next(); if (dec.isAdviceLike()) { if (includeAdviceLike) ret.add(dec); } else { ret.add(dec); } } } } return ret; } private final Collection collectShadowMungers() { if (! this.isAspect() || this.isAbstract() || this.doesNotExposeShadowMungers()) return Collections.EMPTY_LIST; ArrayList acc = new ArrayList(); final Iterators.Filter dupFilter = Iterators.dupFilter(); Iterators.Getter typeGetter = new Iterators.Getter() { public Iterator get(Object o) { return dupFilter.filter( ((ResolvedType)o).getDirectSupertypes()); } }; Iterator typeIterator = Iterators.recur(this, typeGetter); while (typeIterator.hasNext()) { ResolvedType ty = (ResolvedType) typeIterator.next(); acc.addAll(ty.getDeclaredShadowMungers()); } return acc; } protected boolean doesNotExposeShadowMungers() { return false; } public PerClause getPerClause() { return null; } protected Collection getDeclares() { return Collections.EMPTY_LIST; } protected Collection getTypeMungers() { return Collections.EMPTY_LIST; } protected Collection getPrivilegedAccesses() { return Collections.EMPTY_LIST; } // ---- useful things public final boolean isInterface() { return Modifier.isInterface(getModifiers()); } public final boolean isAbstract() { return Modifier.isAbstract(getModifiers()); } public boolean isClass() { return false; } public boolean isAspect() { return false; } public boolean isAnnotationStyleAspect() { return false; } /** * Note: Only overridden by Name subtype. */ public boolean isEnum() { return false; } /** * Note: Only overridden by Name subtype. */ public boolean isAnnotation() { return false; } public boolean isAnonymous() { return false; } public boolean isNested() { return false; } /** * Note: Only overridden by Name subtype */ public void addAnnotation(AnnotationX annotationX) { throw new RuntimeException("ResolvedType.addAnnotation() should never be called"); } /** * Note: Only overridden by Name subtype */ public AnnotationX[] getAnnotations() { throw new RuntimeException("ResolvedType.getAnnotations() should never be called"); } /** * Note: Only overridden by ReferenceType subtype */ public boolean canAnnotationTargetType() { return false; } /** * Note: Only overridden by ReferenceType subtype */ public AnnotationTargetKind[] getAnnotationTargetKinds() { return null; } /** * Note: Only overridden by Name subtype. */ public boolean isAnnotationWithRuntimeRetention() { return false; } public boolean isSynthetic() { return signature.indexOf("$ajc") != -1; } public final boolean isFinal() { return Modifier.isFinal(getModifiers()); } protected Map /*Type variable name -> UnresolvedType*/ getMemberParameterizationMap() { if (!isParameterizedType()) return Collections.EMPTY_MAP; TypeVariable[] tvs = getGenericType().getTypeVariables(); Map parameterizationMap = new HashMap(); for (int i = 0; i < tvs.length; i++) { parameterizationMap.put(tvs[i].getName(), typeParameters[i]); } return parameterizationMap; } public Collection getDeclaredAdvice() { List l = new ArrayList(); ResolvedMember[] methods = getDeclaredMethods(); if (isParameterizedType()) methods = getGenericType().getDeclaredMethods(); Map typeVariableMap = getAjMemberParameterizationMap(); for (int i=0, len = methods.length; i < len; i++) { ShadowMunger munger = methods[i].getAssociatedShadowMunger(); if (munger != null) { if (ajMembersNeedParameterization()) { //munger.setPointcut(munger.getPointcut().parameterizeWith(typeVariableMap)); munger = munger.parameterizeWith(this,typeVariableMap); if (munger instanceof Advice) { Advice advice = (Advice) munger; // update to use the parameterized signature... UnresolvedType[] ptypes = methods[i].getGenericParameterTypes() ; UnresolvedType[] newPTypes = new UnresolvedType[ptypes.length]; for (int j = 0; j < ptypes.length; j++) { if (ptypes[j] instanceof TypeVariableReferenceType) { TypeVariableReferenceType tvrt = (TypeVariableReferenceType) ptypes[j]; if (typeVariableMap.containsKey(tvrt.getTypeVariable().getName())) { newPTypes[j] = (UnresolvedType) typeVariableMap.get(tvrt.getTypeVariable().getName()); } else { newPTypes[j] = ptypes[j]; } } else { newPTypes[j] = ptypes[j]; } } advice.setBindingParameterTypes(newPTypes); } } munger.setDeclaringType(this); l.add(munger); } } return l; } public Collection getDeclaredShadowMungers() { Collection c = getDeclaredAdvice(); return c; } // ---- only for testing! public ResolvedMember[] getDeclaredJavaFields() { return filterInJavaVisible(getDeclaredFields()); } public ResolvedMember[] getDeclaredJavaMethods() { return filterInJavaVisible(getDeclaredMethods()); } public ShadowMunger[] getDeclaredShadowMungersArray() { List l = (List) getDeclaredShadowMungers(); return (ShadowMunger[]) l.toArray(new ShadowMunger[l.size()]); } private ResolvedMember[] filterInJavaVisible(ResolvedMember[] ms) { List l = new ArrayList(); for (int i=0, len = ms.length; i < len; i++) { if (! ms[i].isAjSynthetic() && ms[i].getAssociatedShadowMunger() == null) { l.add(ms[i]); } } return (ResolvedMember[]) l.toArray(new ResolvedMember[l.size()]); } public abstract ISourceContext getSourceContext(); // ---- fields public static final ResolvedType[] NONE = new ResolvedType[0]; public static final Primitive BYTE = new Primitive("B", 1, 0); public static final Primitive CHAR = new Primitive("C", 1, 1); public static final Primitive DOUBLE = new Primitive("D", 2, 2); public static final Primitive FLOAT = new Primitive("F", 1, 3); public static final Primitive INT = new Primitive("I", 1, 4); public static final Primitive LONG = new Primitive("J", 2, 5); public static final Primitive SHORT = new Primitive("S", 1, 6); public static final Primitive VOID = new Primitive("V", 0, 8); public static final Primitive BOOLEAN = new Primitive("Z", 1, 7); public static final Missing MISSING = new Missing(); /** Reset the static state in the primitive types */ public static void resetPrimitives() { BYTE.world=null; CHAR.world=null; DOUBLE.world=null; FLOAT.world=null; INT.world=null; LONG.world=null; SHORT.world=null; VOID.world=null; BOOLEAN.world=null; } // ---- types public static ResolvedType makeArray(ResolvedType type, int dim) { if (dim == 0) return type; ResolvedType array = new Array("[" + type.getSignature(),"["+type.getErasureSignature(),type.getWorld(),type); return makeArray(array,dim-1); } static class Array extends ResolvedType { ResolvedType componentType; // Sometimes the erasure is different, eg. [TT; and [Ljava/lang/Object; Array(String sig, String erasureSig,World world, ResolvedType componentType) { super(sig,erasureSig, world); this.componentType = componentType; } public final ResolvedMember[] getDeclaredFields() { return ResolvedMember.NONE; } public final ResolvedMember[] getDeclaredMethods() { // ??? should this return clone? Probably not... // If it ever does, here is the code: // ResolvedMember cloneMethod = // new ResolvedMember(Member.METHOD,this,Modifier.PUBLIC,UnresolvedType.OBJECT,"clone",new UnresolvedType[]{}); // return new ResolvedMember[]{cloneMethod}; return ResolvedMember.NONE; } public final ResolvedType[] getDeclaredInterfaces() { return new ResolvedType[] { world.getCoreType(CLONEABLE), world.getCoreType(SERIALIZABLE) }; } public final ResolvedMember[] getDeclaredPointcuts() { return ResolvedMember.NONE; } public boolean hasAnnotation(UnresolvedType ofType) { return false; } public final ResolvedType getSuperclass() { return world.getCoreType(OBJECT); } public final boolean isAssignableFrom(ResolvedType o) { if (! o.isArray()) return false; if (o.getComponentType().isPrimitiveType()) { return o.equals(this); } else { return getComponentType().resolve(world).isAssignableFrom(o.getComponentType().resolve(world)); } } public boolean isAssignableFrom(ResolvedType o, boolean allowMissing) { return isAssignableFrom(o); } public final boolean isCoerceableFrom(ResolvedType o) { if (o.equals(UnresolvedType.OBJECT) || o.equals(UnresolvedType.SERIALIZABLE) || o.equals(UnresolvedType.CLONEABLE)) { return true; } if (! o.isArray()) return false; if (o.getComponentType().isPrimitiveType()) { return o.equals(this); } else { return getComponentType().resolve(world).isCoerceableFrom(o.getComponentType().resolve(world)); } } public final int getModifiers() { int mask = Modifier.PUBLIC | Modifier.PRIVATE | Modifier.PROTECTED; return (componentType.getModifiers() & mask) | Modifier.FINAL; } public UnresolvedType getComponentType() { return componentType; } public ResolvedType getResolvedComponentType() { return componentType; } public ISourceContext getSourceContext() { return getResolvedComponentType().getSourceContext(); } } static class Primitive extends ResolvedType { private int size; private int index; Primitive(String signature, int size, int index) { super(signature, null); this.size = size; this.index = index; this.typeKind=TypeKind.PRIMITIVE; } public final int getSize() { return size; } public final int getModifiers() { return Modifier.PUBLIC | Modifier.FINAL; } public final boolean isPrimitiveType() { return true; } public boolean hasAnnotation(UnresolvedType ofType) { return false; } public final boolean isAssignableFrom(ResolvedType other) { if (!other.isPrimitiveType()) { if (!world.isInJava5Mode()) return false; return validBoxing.contains(this.getSignature()+other.getSignature()); } return assignTable[((Primitive)other).index][index]; } public final boolean isAssignableFrom(ResolvedType other, boolean allowMissing) { return isAssignableFrom(other); } public final boolean isCoerceableFrom(ResolvedType other) { if (this == other) return true; if (! other.isPrimitiveType()) return false; if (index > 6 || ((Primitive)other).index > 6) return false; return true; } public ResolvedType resolve(World world) { this.world = world; return super.resolve(world); } public final boolean needsNoConversionFrom(ResolvedType other) { if (! other.isPrimitiveType()) return false; return noConvertTable[((Primitive)other).index][index]; } private static final boolean[][] assignTable = {// to: B C D F I J S V Z from { true , true , true , true , true , true , true , false, false }, // B { false, true , true , true , true , true , false, false, false }, // C { false, false, true , false, false, false, false, false, false }, // D { false, false, true , true , false, false, false, false, false }, // F { false, false, true , true , true , true , false, false, false }, // I { false, false, true , true , false, true , false, false, false }, // J { false, false, true , true , true , true , true , false, false }, // S { false, false, false, false, false, false, false, true , false }, // V { false, false, false, false, false, false, false, false, true }, // Z }; private static final boolean[][] noConvertTable = {// to: B C D F I J S V Z from { true , true , false, false, true , false, true , false, false }, // B { false, true , false, false, true , false, false, false, false }, // C { false, false, true , false, false, false, false, false, false }, // D { false, false, false, true , false, false, false, false, false }, // F { false, false, false, false, true , false, false, false, false }, // I { false, false, false, false, false, true , false, false, false }, // J { false, false, false, false, true , false, true , false, false }, // S { false, false, false, false, false, false, false, true , false }, // V { false, false, false, false, false, false, false, false, true }, // Z }; // ---- public final ResolvedMember[] getDeclaredFields() { return ResolvedMember.NONE; } public final ResolvedMember[] getDeclaredMethods() { return ResolvedMember.NONE; } public final ResolvedType[] getDeclaredInterfaces() { return ResolvedType.NONE; } public final ResolvedMember[] getDeclaredPointcuts() { return ResolvedMember.NONE; } public final ResolvedType getSuperclass() { return null; } public ISourceContext getSourceContext() { return null; } } static class Missing extends ResolvedType { Missing() { super(MISSING_NAME, null); } // public final String toString() { // return "<missing>"; // } public final String getName() { return MISSING_NAME; } public final boolean isMissing() { return true; } public boolean hasAnnotation(UnresolvedType ofType) { return false; } public final ResolvedMember[] getDeclaredFields() { return ResolvedMember.NONE; } public final ResolvedMember[] getDeclaredMethods() { return ResolvedMember.NONE; } public final ResolvedType[] getDeclaredInterfaces() { return ResolvedType.NONE; } public final ResolvedMember[] getDeclaredPointcuts() { return ResolvedMember.NONE; } public final ResolvedType getSuperclass() { return null; } public final int getModifiers() { return 0; } public final boolean isAssignableFrom(ResolvedType other) { return false; } public final boolean isAssignableFrom(ResolvedType other, boolean allowMissing) { return false; } public final boolean isCoerceableFrom(ResolvedType other) { return false; } public boolean needsNoConversionFrom(ResolvedType other) { return false; } public ISourceContext getSourceContext() { return null; } } /** * Look up a member, takes into account any ITDs on this type. * return null if not found */ public ResolvedMember lookupMemberNoSupers(Member member) { ResolvedMember ret = lookupDirectlyDeclaredMemberNoSupers(member); if (ret == null && interTypeMungers != null) { for (Iterator i = interTypeMungers.iterator(); i.hasNext();) { ConcreteTypeMunger tm = (ConcreteTypeMunger) i.next(); if (matches(tm.getSignature(), member)) { return tm.getSignature(); } } } return ret; } public ResolvedMember lookupMemberWithSupersAndITDs(Member member) { ResolvedMember ret = lookupMemberNoSupers(member); if (ret != null) return ret; ResolvedType supert = getSuperclass(); 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 interTypeMungers = new ArrayList(0); public List getInterTypeMungers() { return interTypeMungers; } public List getInterTypeParentMungers() { List l = new ArrayList(); for (Iterator iter = interTypeMungers.iterator(); iter.hasNext();) { ConcreteTypeMunger element = (ConcreteTypeMunger) iter.next(); if (element.getMunger() instanceof NewParentTypeMunger) l.add(element); } return l; } /** * ??? This method is O(N*M) where N = number of methods and M is number of * inter-type declarations in my super */ public List getInterTypeMungersIncludingSupers() { ArrayList ret = new ArrayList(); collectInterTypeMungers(ret); return ret; } public List getInterTypeParentMungersIncludingSupers() { ArrayList ret = new ArrayList(); collectInterTypeParentMungers(ret); return ret; } private void collectInterTypeParentMungers(List collector) { for (Iterator iter = getDirectSupertypes(); iter.hasNext();) { ResolvedType superType = (ResolvedType) iter.next(); superType.collectInterTypeParentMungers(collector); } collector.addAll(getInterTypeParentMungers()); } protected void collectInterTypeMungers(List collector) { for (Iterator iter = getDirectSupertypes(); iter.hasNext();) { ResolvedType superType = (ResolvedType) iter.next(); superType.collectInterTypeMungers(collector); } outer: for (Iterator iter1 = collector.iterator(); iter1.hasNext();) { ConcreteTypeMunger superMunger = (ConcreteTypeMunger) iter1.next(); if ( superMunger.getSignature() == null) continue; if ( !superMunger.getSignature().isAbstract()) continue; for (Iterator iter = getInterTypeMungers().iterator(); iter.hasNext();) { ConcreteTypeMunger myMunger = (ConcreteTypeMunger) iter.next(); if (conflictingSignature(myMunger.getSignature(), superMunger.getSignature())) { iter1.remove(); continue outer; } } if (!superMunger.getSignature().isPublic()) continue; for (Iterator iter = getMethods(); iter.hasNext(); ) { ResolvedMember method = (ResolvedMember)iter.next(); if (conflictingSignature(method, superMunger.getSignature())) { iter1.remove(); continue outer; } } } collector.addAll(getInterTypeMungers()); } /** * Check: * 1) That we don't have any abstract type mungers unless this type is abstract. * 2) That an abstract ITDM on an interface is declared public. (Compiler limitation) (PR70794) */ public void checkInterTypeMungers() { if (isAbstract()) return; boolean itdProblem = false; for (Iterator iter = getInterTypeMungersIncludingSupers().iterator(); iter.hasNext();) { ConcreteTypeMunger munger = (ConcreteTypeMunger) iter.next(); itdProblem = checkAbstractDeclaration(munger) || itdProblem; // Rule 2 } if (itdProblem) return; // If the rules above are broken, return right now for (Iterator iter = getInterTypeMungersIncludingSupers().iterator(); iter.hasNext();) { ConcreteTypeMunger munger = (ConcreteTypeMunger) iter.next(); if (munger.getSignature() != null && munger.getSignature().isAbstract()) { // Rule 1 if (munger.getMunger().getKind() == ResolvedTypeMunger.MethodDelegate) { ;//ignore for @AJ ITD as munger.getSignature() is the interface method hence abstract } else { world.getMessageHandler().handleMessage( new Message("must implement abstract inter-type declaration: " + munger.getSignature(), "", IMessage.ERROR, getSourceLocation(), null, new ISourceLocation[] { getMungerLocation(munger) })); } } } } /** * See PR70794. This method checks that if an abstract inter-type method declaration is made on * an interface then it must also be public. * This is a compiler limitation that could be made to work in the future (if someone * provides a worthwhile usecase) * * @return indicates if the munger failed the check */ private boolean checkAbstractDeclaration(ConcreteTypeMunger munger) { if (munger.getMunger()!=null && (munger.getMunger() instanceof NewMethodTypeMunger)) { ResolvedMember itdMember = munger.getSignature(); ResolvedType onType = itdMember.getDeclaringType().resolve(world); if (onType.isInterface() && itdMember.isAbstract() && !itdMember.isPublic()) { world.getMessageHandler().handleMessage( new Message(WeaverMessages.format(WeaverMessages.ITD_ABSTRACT_MUST_BE_PUBLIC_ON_INTERFACE,munger.getSignature(),onType),"", Message.ERROR,getSourceLocation(),null, new ISourceLocation[]{getMungerLocation(munger)}) ); return true; } } return false; } /** * Get a source location for the munger. * Until intertype mungers remember where they came from, the source location * for the munger itself is null. In these cases use the * source location for the aspect containing the ITD. */ private ISourceLocation getMungerLocation(ConcreteTypeMunger munger) { ISourceLocation sloc = munger.getSourceLocation(); if (sloc == null) { sloc = munger.getAspectType().getSourceLocation(); } return sloc; } /** * Returns a ResolvedType object representing the declaring type of this type, or * null if this type does not represent a non-package-level-type. * <p/> * <strong>Warning</strong>: This is guaranteed to work for all member types. * For anonymous/local types, the only guarantee is given in JLS 13.1, where * it guarantees that if you call getDeclaringType() repeatedly, you will eventually * get the top-level class, but it does not say anything about classes in between. * * @return the declaring UnresolvedType object, or null. */ public ResolvedType getDeclaringType() { if (isArray()) return null; String name = getName(); int lastDollar = name.lastIndexOf('$'); while (lastDollar >0) { // allow for classes starting '$' (pr120474) ResolvedType ret = world.resolve(UnresolvedType.forName(name.substring(0, lastDollar)), true); if (!ResolvedType.isMissing(ret)) return ret; lastDollar = name.lastIndexOf('$', lastDollar-1); } return null; } public static boolean isVisible(int modifiers, ResolvedType targetType, ResolvedType fromType) { //System.err.println("mod: " + modifiers + ", " + targetType + " and " + fromType); if (Modifier.isPublic(modifiers)) { return true; } else if (Modifier.isPrivate(modifiers)) { return targetType.getOutermostType().equals(fromType.getOutermostType()); } else if (Modifier.isProtected(modifiers)) { return samePackage(targetType, fromType) || targetType.isAssignableFrom(fromType); } else { // package-visible return samePackage(targetType, fromType); } } public static boolean hasBridgeModifier(int modifiers) { return (modifiers & Constants.ACC_BRIDGE)!=0; } private static boolean samePackage( ResolvedType targetType, ResolvedType fromType) { String p1 = targetType.getPackageName(); String p2 = fromType.getPackageName(); if (p1 == null) return p2 == null; if (p2 == null) return false; return p1.equals(p2); } /** * Checks if the generic type for 'this' and the generic type for 'other' are the same - * it can be passed raw or parameterized versions and will just compare the underlying * generic type. */ private boolean genericTypeEquals(ResolvedType other) { ResolvedType rt = other; if (rt.isParameterizedType() || rt.isRawType()) rt.getGenericType(); if (( (isParameterizedType() || isRawType()) && getGenericType().equals(rt)) || (this.equals(other))) return true; return false; } /** * Look up the actual occurence of a particular type in the hierarchy for * 'this' type. The input is going to be a generic type, and the caller * wants to know if it was used in its RAW or a PARAMETERIZED form in this * hierarchy. * * returns null if it can't be found. */ public ResolvedType discoverActualOccurrenceOfTypeInHierarchy(ResolvedType lookingFor) { if (!lookingFor.isGenericType()) throw new BCException("assertion failed: method should only be called with generic type, but "+lookingFor+" is "+lookingFor.typeKind); if (this.equals(ResolvedType.OBJECT)) return null; if (genericTypeEquals(lookingFor)) return this; ResolvedType superT = getSuperclass(); if (superT.genericTypeEquals(lookingFor)) return superT; ResolvedType[] superIs = getDeclaredInterfaces(); for (int i = 0; i < superIs.length; i++) { ResolvedType superI = superIs[i]; if (superI.genericTypeEquals(lookingFor)) return superI; ResolvedType checkTheSuperI = superI.discoverActualOccurrenceOfTypeInHierarchy(lookingFor); if (checkTheSuperI!=null) return checkTheSuperI; } return superT.discoverActualOccurrenceOfTypeInHierarchy(lookingFor); } /** * Called for all type mungers but only does something if they share type variables * with a generic type which they target. When this happens this routine will check * for the target type in the target hierarchy and 'bind' any type parameters as * appropriate. For example, for the ITD "List<T> I<T>.x" against a type like this: * "class A implements I<String>" this routine will return a parameterized form of * the ITD "List<String> I.x" */ public ConcreteTypeMunger fillInAnyTypeParameters(ConcreteTypeMunger munger) { boolean debug = false; ResolvedMember member = munger.getSignature(); if (munger.isTargetTypeParameterized()) { if (debug) System.err.println("Processing attempted parameterization of "+munger+" targetting type "+this); if (debug) System.err.println(" This type is "+this+" ("+typeKind+")"); // need to tailor this munger instance for the particular target... if (debug) System.err.println(" Signature that needs parameterizing: "+member); // Retrieve the generic type ResolvedType onType = world.resolve(member.getDeclaringType()).getGenericType(); member.resolve(world); // Ensure all parts of the member are resolved if (debug) System.err.println(" Actual target ontype: "+onType+" ("+onType.typeKind+")"); // quickly find the targettype in the type hierarchy for this type (it will be either RAW or PARAMETERIZED) ResolvedType actualTarget = discoverActualOccurrenceOfTypeInHierarchy(onType); if (actualTarget==null) throw new BCException("assertion failed: asked "+this+" for occurrence of "+onType+" in its hierarchy??"); // only bind the tvars if its a parameterized type or the raw type (in which case they collapse to bounds) - don't do it for generic types ;) if (!actualTarget.isGenericType()) { if (debug) System.err.println("Occurrence in "+this+" is actually "+actualTarget+" ("+actualTarget.typeKind+")"); // parameterize the signature // ResolvedMember newOne = member.parameterizedWith(actualTarget.getTypeParameters(),onType,actualTarget.isParameterizedType()); } //if (!actualTarget.isRawType()) munger = munger.parameterizedFor(actualTarget); if (debug) System.err.println("New sig: "+munger.getSignature()); if (debug) System.err.println("====================================="); } return munger; } public void addInterTypeMunger(ConcreteTypeMunger munger) { ResolvedMember sig = munger.getSignature(); if (sig == null || munger.getMunger() == null || munger.getMunger().getKind() == ResolvedTypeMunger.PrivilegedAccess) { interTypeMungers.add(munger); return; } ConcreteTypeMunger originalMunger = munger; // we will use the 'parameterized' ITD for all the comparisons but we say the original // one passed in actually matched as it will be added to the intertype member finder // for the target type. It is possible we only want to do this if a generic type // is discovered and the tvar is collapsed to a bound? munger = fillInAnyTypeParameters(munger); sig = munger.getSignature(); // possibly changed when type parms filled in //System.err.println("add: " + munger + " to " + this.getClassName() + " with " + interTypeMungers); if (sig.getKind() == Member.METHOD) { if (!compareToExistingMembers(munger, getMethodsWithoutIterator(false,true) /*getMethods()*/)) return; if (this.isInterface()) { if (!compareToExistingMembers(munger, Arrays.asList(world.getCoreType(OBJECT).getDeclaredMethods()).iterator())) return; } } else if (sig.getKind() == Member.FIELD) { if (!compareToExistingMembers(munger, Arrays.asList(getDeclaredFields()).iterator())) return; } else { if (!compareToExistingMembers(munger, Arrays.asList(getDeclaredMethods()).iterator())) return; } // now compare to existingMungers for (Iterator i = interTypeMungers.iterator(); i.hasNext(); ) { ConcreteTypeMunger existingMunger = (ConcreteTypeMunger)i.next(); if (conflictingSignature(existingMunger.getSignature(), munger.getSignature())) { //System.err.println("match " + munger + " with " + existingMunger); if (isVisible(munger.getSignature().getModifiers(), munger.getAspectType(), existingMunger.getAspectType())) { //System.err.println(" is visible"); int c = compareMemberPrecedence(sig, existingMunger.getSignature()); if (c == 0) { c = getWorld().compareByPrecedenceAndHierarchy(munger.getAspectType(), existingMunger.getAspectType()); } //System.err.println(" compare: " + c); if (c < 0) { // the existing munger dominates the new munger checkLegalOverride(munger.getSignature(), existingMunger.getSignature()); return; } else if (c > 0) { // the new munger dominates the existing one checkLegalOverride(existingMunger.getSignature(), munger.getSignature()); i.remove(); break; } else { interTypeConflictError(munger, existingMunger); interTypeConflictError(existingMunger, munger); return; } } } } //System.err.println("adding: " + munger + " to " + this); // we are adding the parameterized form of the ITD to the list of // mungers. Within it, the munger knows the original declared // signature for the ITD so it can be retrieved. interTypeMungers.add(munger); } private boolean compareToExistingMembers(ConcreteTypeMunger munger, List existingMembersList) { return compareToExistingMembers(munger,existingMembersList.iterator()); } //??? returning too soon private boolean compareToExistingMembers(ConcreteTypeMunger munger, Iterator existingMembers) { ResolvedMember sig = munger.getSignature(); while (existingMembers.hasNext()) { ResolvedMember existingMember = (ResolvedMember)existingMembers.next(); // don't worry about clashing with bridge methods if (existingMember.isBridgeMethod()) continue; //System.err.println("Comparing munger: "+sig+" with member "+existingMember); if (conflictingSignature(existingMember, munger.getSignature())) { //System.err.println("conflict: existingMember=" + existingMember + " typeMunger=" + munger); //System.err.println(munger.getSourceLocation() + ", " + munger.getSignature() + ", " + munger.getSignature().getSourceLocation()); if (isVisible(existingMember.getModifiers(), this, munger.getAspectType())) { int c = compareMemberPrecedence(sig, existingMember); //System.err.println(" c: " + c); if (c < 0) { // existingMember dominates munger checkLegalOverride(munger.getSignature(), existingMember); return false; } else if (c > 0) { // munger dominates existingMember checkLegalOverride(existingMember, munger.getSignature()); //interTypeMungers.add(munger); //??? might need list of these overridden abstracts continue; } else { // bridge methods can differ solely in return type. // FIXME this whole method seems very hokey - unaware of covariance/varargs/bridging - it // could do with a rewrite ! boolean sameReturnTypes = (existingMember.getReturnType().equals(sig.getReturnType())); if (sameReturnTypes) getWorld().getMessageHandler().handleMessage( MessageUtil.error(WeaverMessages.format(WeaverMessages.ITD_MEMBER_CONFLICT,munger.getAspectType().getName(), existingMember), munger.getSourceLocation()) ); } } else if (isDuplicateMemberWithinTargetType(existingMember,this,sig)) { getWorld().getMessageHandler().handleMessage( MessageUtil.error(WeaverMessages.format(WeaverMessages.ITD_MEMBER_CONFLICT,munger.getAspectType().getName(), existingMember), munger.getSourceLocation()) ); ; } //return; } } return true; } // we know that the member signature matches, but that the member in the target type is not visible to the aspect. // this may still be disallowed if it would result in two members within the same declaring type with the same // signature AND more than one of them is concrete AND they are both visible within the target type. private boolean isDuplicateMemberWithinTargetType(ResolvedMember existingMember, ResolvedType targetType,ResolvedMember itdMember) { if ( (existingMember.isAbstract() || itdMember.isAbstract())) return false; UnresolvedType declaringType = existingMember.getDeclaringType(); if (!targetType.equals(declaringType)) return false; // now have to test that itdMember is visible from targetType if (itdMember.isPrivate()) return false; if (itdMember.isPublic()) return true; // must be in same package to be visible then... if (!targetType.getPackageName().equals(itdMember.getDeclaringType().getPackageName())) return false; // trying to put two members with the same signature into the exact same type..., and both visible in that type. return true; } /** * @return true if the override is legal * note: calling showMessage with two locations issues TWO messages, not ONE message * with an additional source location. */ public boolean checkLegalOverride(ResolvedMember parent, ResolvedMember child) { //System.err.println("check: " + child.getDeclaringType() + " overrides " + parent.getDeclaringType()); if (Modifier.isFinal(parent.getModifiers())) { world.showMessage(Message.ERROR, WeaverMessages.format(WeaverMessages.CANT_OVERRIDE_FINAL_MEMBER,parent), child.getSourceLocation(),null); return false; } boolean incompatibleReturnTypes = false; // In 1.5 mode, allow for covariance on return type if (world.isInJava5Mode() && parent.getKind()==Member.METHOD) { // Look at the generic types when doing this comparison ResolvedType rtParentReturnType = parent.getGenericReturnType().resolve(world); ResolvedType rtChildReturnType = child.getGenericReturnType().resolve(world); incompatibleReturnTypes = !rtParentReturnType.isAssignableFrom(rtChildReturnType); if (incompatibleReturnTypes) { incompatibleReturnTypes = !rtParentReturnType.isAssignableFrom(rtChildReturnType); } } else { incompatibleReturnTypes =!parent.getReturnType().equals(child.getReturnType()); } if (incompatibleReturnTypes) { world.showMessage(IMessage.ERROR, WeaverMessages.format(WeaverMessages.ITD_RETURN_TYPE_MISMATCH,parent,child), child.getSourceLocation(), parent.getSourceLocation()); return false; } if (parent.getKind() == Member.POINTCUT) { UnresolvedType[] pTypes = parent.getParameterTypes(); UnresolvedType[] cTypes = child.getParameterTypes(); if (!Arrays.equals(pTypes, cTypes)) { world.showMessage(IMessage.ERROR, WeaverMessages.format(WeaverMessages.ITD_PARAM_TYPE_MISMATCH,parent,child), child.getSourceLocation(), parent.getSourceLocation()); return false; } } //System.err.println("check: " + child.getModifiers() + " more visible " + parent.getModifiers()); if (isMoreVisible(parent.getModifiers(), child.getModifiers())) { world.showMessage(IMessage.ERROR, WeaverMessages.format(WeaverMessages.ITD_VISIBILITY_REDUCTION,parent,child), child.getSourceLocation(), parent.getSourceLocation()); return false; } // check declared exceptions ResolvedType[] childExceptions = world.resolve(child.getExceptions()); ResolvedType[] parentExceptions = world.resolve(parent.getExceptions()); ResolvedType runtimeException = world.resolve("java.lang.RuntimeException"); ResolvedType error = world.resolve("java.lang.Error"); outer: for (int i = 0, leni = childExceptions.length; i < leni; i++) { //System.err.println("checking: " + childExceptions[i]); if (runtimeException.isAssignableFrom(childExceptions[i])) continue; if (error.isAssignableFrom(childExceptions[i])) continue; for (int j = 0, lenj = parentExceptions.length; j < lenj; j++) { if (parentExceptions[j].isAssignableFrom(childExceptions[i])) continue outer; } // this message is now better handled my MethodVerifier in JDT core. // world.showMessage(IMessage.ERROR, // WeaverMessages.format(WeaverMessages.ITD_DOESNT_THROW,childExceptions[i].getName()), // child.getSourceLocation(), null); return false; } if (parent.isStatic() && !child.isStatic()) { world.showMessage(IMessage.ERROR, WeaverMessages.format(WeaverMessages.ITD_OVERRIDDEN_STATIC,child,parent), child.getSourceLocation(),null); return false; } else if (child.isStatic() && !parent.isStatic()) { world.showMessage(IMessage.ERROR, WeaverMessages.format(WeaverMessages.ITD_OVERIDDING_STATIC,child,parent), child.getSourceLocation(),null); return false; } return true; } private int compareMemberPrecedence(ResolvedMember m1, ResolvedMember m2) { //if (!m1.getReturnType().equals(m2.getReturnType())) return 0; // need to allow for the special case of 'clone' - which is like abstract but is // not marked abstract. The code below this next line seems to make assumptions // about what will have gotten through the compiler based on the normal // java rules. clone goes against these... if (m2.isProtected() && m2.getName().charAt(0)=='c') { UnresolvedType declaring = m2.getDeclaringType(); if (declaring!=null) { if (declaring.getName().equals("java.lang.Object") && m2.getName().equals("clone")) return +1; } } if (Modifier.isAbstract(m1.getModifiers())) return -1; if (Modifier.isAbstract(m2.getModifiers())) return +1; if (m1.getDeclaringType().equals(m2.getDeclaringType())) return 0; ResolvedType t1 = m1.getDeclaringType().resolve(world); ResolvedType t2 = m2.getDeclaringType().resolve(world); if (t1.isAssignableFrom(t2)) { return -1; } if (t2.isAssignableFrom(t1)) { return +1; } return 0; } public static boolean isMoreVisible(int m1, int m2) { if (Modifier.isPrivate(m1)) return false; if (isPackage(m1)) return Modifier.isPrivate(m2); if (Modifier.isProtected(m1)) return /* private package */ (Modifier.isPrivate(m2) || isPackage(m2)); if (Modifier.isPublic(m1)) return /* private package protected */ ! Modifier.isPublic(m2); throw new RuntimeException("bad modifier: " + m1); } private static boolean isPackage(int i) { return (0 == (i & (Modifier.PUBLIC | Modifier.PRIVATE | Modifier.PROTECTED))); } private void interTypeConflictError( ConcreteTypeMunger m1, ConcreteTypeMunger m2) { //XXX this works only if we ignore separate compilation issues //XXX dual errors possible if (this instanceof BcelObjectType) return; //System.err.println("conflict at " + m2.getSourceLocation()); getWorld().showMessage(IMessage.ERROR, WeaverMessages.format(WeaverMessages.ITD_CONFLICT,m1.getAspectType().getName(), m2.getSignature(),m2.getAspectType().getName()), m2.getSourceLocation(), getSourceLocation()); } public ResolvedMember lookupSyntheticMember(Member member) { //??? horribly inefficient //for (Iterator i = //System.err.println("lookup " + member + " in " + interTypeMungers); for (Iterator i = interTypeMungers.iterator(); i.hasNext(); ) { ConcreteTypeMunger m = (ConcreteTypeMunger)i.next(); ResolvedMember ret = m.getMatchingSyntheticMember(member); if (ret != null) { //System.err.println(" found: " + ret); return ret; } } // Handling members for the new array join point if (world.isJoinpointArrayConstructionEnabled() && this.isArray()) { if (member.getKind()==Member.CONSTRUCTOR) { ResolvedMemberImpl ret = new ResolvedMemberImpl(Member.CONSTRUCTOR,this,Modifier.PUBLIC, ResolvedType.VOID,"<init>",world.resolve(member.getParameterTypes())); return ret; } } // if (this.getSuperclass() != ResolvedType.OBJECT && this.getSuperclass() != null) { // return getSuperclass().lookupSyntheticMember(member); // } return null; } public void clearInterTypeMungers() { if (isRawType()) getGenericType().clearInterTypeMungers(); interTypeMungers = new ArrayList(); } public boolean isTopmostImplementor(ResolvedType interfaceType) { if (isInterface()) return false; if (!interfaceType.isAssignableFrom(this,true)) return false; // check that I'm truly the topmost implementor if (this.getSuperclass().isMissing()) return true; // we don't know anything about supertype, and it can't be exposed to weaver if (interfaceType.isAssignableFrom(this.getSuperclass(),true)) { return false; } return true; } public ResolvedType getTopmostImplementor(ResolvedType interfaceType) { if (isInterface()) return null; if (!interfaceType.isAssignableFrom(this)) return null; // Check if my super class is an implementor? ResolvedType higherType = this.getSuperclass().getTopmostImplementor(interfaceType); if (higherType!=null) return higherType; return this; } private ResolvedType findHigher(ResolvedType other) { if (this == other) return this; for(Iterator i = other.getDirectSupertypes(); i.hasNext(); ) { ResolvedType rtx = (ResolvedType)i.next(); boolean b = this.isAssignableFrom(rtx); if (b) return rtx; } return null; } public List getExposedPointcuts() { List ret = new ArrayList(); if (getSuperclass() != null) ret.addAll(getSuperclass().getExposedPointcuts()); for (Iterator i = Arrays.asList(getDeclaredInterfaces()).iterator(); i.hasNext(); ) { ResolvedType t = (ResolvedType)i.next(); addPointcutsResolvingConflicts(ret, Arrays.asList(t.getDeclaredPointcuts()), false); } addPointcutsResolvingConflicts(ret, Arrays.asList(getDeclaredPointcuts()), true); for (Iterator i = ret.iterator(); i.hasNext(); ) { ResolvedPointcutDefinition inherited = (ResolvedPointcutDefinition)i.next(); // System.err.println("looking at: " + inherited + " in " + this); // System.err.println(" " + inherited.isAbstract() + " in " + this.isAbstract()); if (inherited.isAbstract()) { if (!this.isAbstract()) { getWorld().showMessage(IMessage.ERROR, WeaverMessages.format(WeaverMessages.POINCUT_NOT_CONCRETE,inherited,this.getName()), inherited.getSourceLocation(), this.getSourceLocation()); } } } return ret; } private void addPointcutsResolvingConflicts(List acc, List added, boolean isOverriding) { for (Iterator i = added.iterator(); i.hasNext();) { ResolvedPointcutDefinition toAdd = (ResolvedPointcutDefinition) i.next(); //System.err.println("adding: " + toAdd); for (Iterator j = acc.iterator(); j.hasNext();) { ResolvedPointcutDefinition existing = (ResolvedPointcutDefinition) j.next(); if (existing == toAdd) continue; if (!isVisible(existing.getModifiers(), existing.getDeclaringType().resolve(getWorld()), this)) { continue; } if (conflictingSignature(existing, toAdd)) { if (isOverriding) { checkLegalOverride(existing, toAdd); j.remove(); } else { getWorld().showMessage( IMessage.ERROR, WeaverMessages.format(WeaverMessages.CONFLICTING_INHERITED_POINTCUTS,this.getName() + toAdd.getSignature()), existing.getSourceLocation(), toAdd.getSourceLocation()); j.remove(); } } } acc.add(toAdd); } } public ISourceLocation getSourceLocation() { return null; } public boolean isExposedToWeaver() { return false; } public WeaverStateInfo getWeaverState() { return null; } /** * Overridden by ReferenceType to return a sensible answer for parameterized and raw types. * * @return */ public ResolvedType getGenericType() { if (!(isParameterizedType() || isRawType())) throw new BCException("The type "+getBaseName()+" is not parameterized or raw - it has no generic type"); return null; } /** * overriden by ReferenceType to return the gsig for a generic type * @return */ public String getGenericSignature() { return ""; } public ResolvedType parameterizedWith(UnresolvedType[] typeParameters) { if (!(isGenericType() || isParameterizedType())) return this; return TypeFactory.createParameterizedType(this.getGenericType(), typeParameters, getWorld()); } /** * Iff I am a parameterized type, and any of my parameters are type variable * references, return a version with those type parameters replaced in accordance * with the passed bindings. */ public UnresolvedType parameterize(Map typeBindings) { if (!isParameterizedType()) return this;//throw new IllegalStateException("Can't parameterize a type that is not a parameterized type"); boolean workToDo = false; for (int i = 0; i < typeParameters.length; i++) { if (typeParameters[i].isTypeVariableReference() || (typeParameters[i] instanceof BoundedReferenceType)) { workToDo = true; } } if (!workToDo) { return this; } else { UnresolvedType[] newTypeParams = new UnresolvedType[typeParameters.length]; for (int i = 0; i < newTypeParams.length; i++) { newTypeParams[i] = typeParameters[i]; if (newTypeParams[i].isTypeVariableReference()) { TypeVariableReferenceType tvrt = (TypeVariableReferenceType) newTypeParams[i]; UnresolvedType binding = (UnresolvedType) typeBindings.get(tvrt.getTypeVariable().getName()); if (binding != null) newTypeParams[i] = binding; } else if (newTypeParams[i] instanceof BoundedReferenceType) { BoundedReferenceType brType = (BoundedReferenceType)newTypeParams[i]; newTypeParams[i] = brType.parameterize(typeBindings); // brType.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); } } /** * Types may have pointcuts just as they have methods and fields. */ public ResolvedPointcutDefinition findPointcut(String name, World world) { throw new UnsupportedOperationException("Not yet implemenented"); } /** * @return true if assignable to java.lang.Exception */ public boolean isException() { return (world.getCoreType(UnresolvedType.JAVA_LANG_EXCEPTION).isAssignableFrom(this)); } /** * @return true if it is an exception and it is a checked one, false otherwise. */ public boolean isCheckedException() { if (!isException()) return false; if (world.getCoreType(UnresolvedType.RUNTIME_EXCEPTION).isAssignableFrom(this)) return false; return true; } /** * Determines if variables of this type could be assigned values of another * with lots of help. * java.lang.Object is convertable from all types. * A primitive type is convertable from X iff it's assignable from X. * A reference type is convertable from X iff it's coerceable from X. * In other words, X isConvertableFrom Y iff the compiler thinks that _some_ value of Y * could be assignable to a variable of type X without loss of precision. * * @param other the other type * @param world the {@link World} in which the possible assignment should be checked. * @return true iff variables of this type could be assigned values of other with possible conversion */ public final boolean isConvertableFrom(ResolvedType other) { // // version from TypeX // if (this.equals(OBJECT)) return true; // if (this.isPrimitiveType() || other.isPrimitiveType()) return this.isAssignableFrom(other); // return this.isCoerceableFrom(other); // // version from ResolvedTypeX if (this.equals(OBJECT)) return true; if (world.isInJava5Mode()) { if (this.isPrimitiveType()^other.isPrimitiveType()) { // If one is primitive and the other isnt if (validBoxing.contains(this.getSignature()+other.getSignature())) return true; } } if (this.isPrimitiveType() || other.isPrimitiveType()) return this.isAssignableFrom(other); return this.isCoerceableFrom(other); } /** * Determines if the variables of this type could be assigned values * of another type without casting. This still allows for assignment conversion * as per JLS 2ed 5.2. For object types, this means supertypeOrEqual(THIS, OTHER). * * @param other the other type * @param world the {@link World} in which the possible assignment should be checked. * @return true iff variables of this type could be assigned values of other without casting * @throws NullPointerException if other is null */ public abstract boolean isAssignableFrom(ResolvedType other); public abstract boolean isAssignableFrom(ResolvedType other, boolean allowMissing); /** * Determines if values of another type could possibly be cast to * this type. The rules followed are from JLS 2ed 5.5, "Casting Conversion". * <p/> * <p> This method should be commutative, i.e., for all UnresolvedType a, b and all World w: * <p/> * <blockquote><pre> * a.isCoerceableFrom(b, w) == b.isCoerceableFrom(a, w) * </pre></blockquote> * * @param other the other type * @param world the {@link World} in which the possible coersion should be checked. * @return true iff values of other could possibly be cast to this type. * @throws NullPointerException if other is null. */ public abstract boolean isCoerceableFrom(ResolvedType other); public boolean needsNoConversionFrom(ResolvedType o) { return isAssignableFrom(o); } /** * Implemented by ReferenceTypes */ public String getSignatureForAttribute() { throw new RuntimeException("Cannot ask this type "+this+" for a generic sig attribute"); } private FuzzyBoolean parameterizedWithAMemberTypeVariable = FuzzyBoolean.MAYBE; /** * return true if the parameterization of this type includes a member type variable. Member * type variables occur in generic methods/ctors. */ public boolean isParameterizedWithAMemberTypeVariable() { // MAYBE means we haven't worked it out yet... if (parameterizedWithAMemberTypeVariable==FuzzyBoolean.MAYBE) { // if there are no type parameters then we cant be... if (typeParameters==null || typeParameters.length==0) { parameterizedWithAMemberTypeVariable = FuzzyBoolean.NO; return false; } for (int i = 0; i < typeParameters.length; i++) { UnresolvedType aType = (ResolvedType)typeParameters[i]; if (aType.isTypeVariableReference() && // assume the worst - if its definetly not a type declared one, it could be anything ((TypeVariableReference)aType).getTypeVariable().getDeclaringElementKind()!=TypeVariable.TYPE) { parameterizedWithAMemberTypeVariable = FuzzyBoolean.YES; return true; } if (aType.isParameterizedType()) { boolean b = aType.isParameterizedWithAMemberTypeVariable(); if (b) { parameterizedWithAMemberTypeVariable = FuzzyBoolean.YES; return true; } } if (aType.isGenericWildcard()) { if (aType.isExtends()) { boolean b = false; UnresolvedType upperBound = aType.getUpperBound(); if (upperBound.isParameterizedType()) { b = upperBound.isParameterizedWithAMemberTypeVariable(); } else if (upperBound.isTypeVariableReference() && ((TypeVariableReference)upperBound).getTypeVariable().getDeclaringElementKind()==TypeVariable.METHOD) { b = true; } if (b) { parameterizedWithAMemberTypeVariable = FuzzyBoolean.YES; return true; } // FIXME asc need to check additional interface bounds } if (aType.isSuper()) { boolean b = false; UnresolvedType lowerBound = aType.getLowerBound(); if (lowerBound.isParameterizedType()) { b = lowerBound.isParameterizedWithAMemberTypeVariable(); } else if (lowerBound.isTypeVariableReference() && ((TypeVariableReference)lowerBound).getTypeVariable().getDeclaringElementKind()==TypeVariable.METHOD) { b = true; } if (b) { parameterizedWithAMemberTypeVariable = FuzzyBoolean.YES; return true; } } } } parameterizedWithAMemberTypeVariable=FuzzyBoolean.NO; } return parameterizedWithAMemberTypeVariable.alwaysTrue(); } protected boolean ajMembersNeedParameterization() { if (isParameterizedType()) return true; if (getSuperclass() != null) return getSuperclass().ajMembersNeedParameterization(); return false; } protected Map getAjMemberParameterizationMap() { Map myMap = getMemberParameterizationMap(); if (myMap.size() == 0) { // might extend a parameterized aspect that we also need to consider... if (getSuperclass() != null) return getSuperclass().getAjMemberParameterizationMap(); } return myMap; } 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; } }
211,674
Bug 211674 [ataspectj] after throwing annotation style is too sensitive to parameter positions
Reported on the list by Ashley Williams: Having converted my aspects to use the @AspectJ style, I'm now getting a strange error message when a compile my tracing aspect,. First here is the section of code: @Pointcut("execution(@Tracing * *(..)) && @annotation(tracing)") void annotatedMethods(Tracing tracing) { } @AfterThrowing(pointcut = "annotatedMethods(tracing)", throwing = "t") public void logException(JoinPoint thisJoinPoint, Tracing tracing, Throwable t) { Level level = Level.toLevel(tracing.level()); if (logger.isEnabledFor(level)) { logger.log(level, formatter.formatSignatureThrowing(thisJoinPoint), t); } } So I am matching on all methods annotated with @Tracing and logging the subclass of Throwable that may have been thrown. However when I run my test case i get the following error: java.lang.VerifyError: (class: com/db/abfo/tracing/PojoOne, method: calculate signature: ()V) catch_type not a subclass of Throwable This used to work when I used the aspectj after throwing language extention form: pointcut annotatedMethods(Tracing tracing) : execution(@Tracing * *(..)) && @annotation(tracing); after(Tracing tracing) throwing(Throwable t) : annotatedMethods(tracing) { Level level = tracing.level().getLevel(); if (logger.isEnabledFor(level)) { logger.log(level, formatter.formatSignatureThrowing(thisJoinPoint), t); } }
resolved fixed
9de03b7
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2007-12-02T09:24:51Z"
"2007-12-01T17:26:40Z"
tests/bugs154/pr211674/Test.java
211,674
Bug 211674 [ataspectj] after throwing annotation style is too sensitive to parameter positions
Reported on the list by Ashley Williams: Having converted my aspects to use the @AspectJ style, I'm now getting a strange error message when a compile my tracing aspect,. First here is the section of code: @Pointcut("execution(@Tracing * *(..)) && @annotation(tracing)") void annotatedMethods(Tracing tracing) { } @AfterThrowing(pointcut = "annotatedMethods(tracing)", throwing = "t") public void logException(JoinPoint thisJoinPoint, Tracing tracing, Throwable t) { Level level = Level.toLevel(tracing.level()); if (logger.isEnabledFor(level)) { logger.log(level, formatter.formatSignatureThrowing(thisJoinPoint), t); } } So I am matching on all methods annotated with @Tracing and logging the subclass of Throwable that may have been thrown. However when I run my test case i get the following error: java.lang.VerifyError: (class: com/db/abfo/tracing/PojoOne, method: calculate signature: ()V) catch_type not a subclass of Throwable This used to work when I used the aspectj after throwing language extention form: pointcut annotatedMethods(Tracing tracing) : execution(@Tracing * *(..)) && @annotation(tracing); after(Tracing tracing) throwing(Throwable t) : annotatedMethods(tracing) { Level level = tracing.level().getLevel(); if (logger.isEnabledFor(level)) { logger.log(level, formatter.formatSignatureThrowing(thisJoinPoint), t); } }
resolved fixed
9de03b7
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2007-12-02T09:24:51Z"
"2007-12-01T17:26:40Z"
tests/bugs154/pr211674/Test2.java
211,674
Bug 211674 [ataspectj] after throwing annotation style is too sensitive to parameter positions
Reported on the list by Ashley Williams: Having converted my aspects to use the @AspectJ style, I'm now getting a strange error message when a compile my tracing aspect,. First here is the section of code: @Pointcut("execution(@Tracing * *(..)) && @annotation(tracing)") void annotatedMethods(Tracing tracing) { } @AfterThrowing(pointcut = "annotatedMethods(tracing)", throwing = "t") public void logException(JoinPoint thisJoinPoint, Tracing tracing, Throwable t) { Level level = Level.toLevel(tracing.level()); if (logger.isEnabledFor(level)) { logger.log(level, formatter.formatSignatureThrowing(thisJoinPoint), t); } } So I am matching on all methods annotated with @Tracing and logging the subclass of Throwable that may have been thrown. However when I run my test case i get the following error: java.lang.VerifyError: (class: com/db/abfo/tracing/PojoOne, method: calculate signature: ()V) catch_type not a subclass of Throwable This used to work when I used the aspectj after throwing language extention form: pointcut annotatedMethods(Tracing tracing) : execution(@Tracing * *(..)) && @annotation(tracing); after(Tracing tracing) throwing(Throwable t) : annotatedMethods(tracing) { Level level = tracing.level().getLevel(); if (logger.isEnabledFor(level)) { logger.log(level, formatter.formatSignatureThrowing(thisJoinPoint), t); } }
resolved fixed
9de03b7
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2007-12-02T09:24:51Z"
"2007-12-01T17:26:40Z"
tests/src/org/aspectj/systemtest/ajc154/Ajc154Tests.java
/******************************************************************************* * Copyright (c) 2006 IBM * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Andy Clement - initial API and implementation *******************************************************************************/ package org.aspectj.systemtest.ajc154; import java.io.File; import java.util.HashSet; import java.util.Set; import org.aspectj.apache.bcel.classfile.ConstantPool; import org.aspectj.apache.bcel.classfile.JavaClass; import org.aspectj.apache.bcel.classfile.LineNumberTable; import org.aspectj.apache.bcel.classfile.Method; import org.aspectj.apache.bcel.generic.ConstantPoolGen; import org.aspectj.apache.bcel.generic.MethodGen; import org.aspectj.apache.bcel.util.ClassPath; import org.aspectj.apache.bcel.util.SyntheticRepository; import org.aspectj.testing.XMLBasedAjcTestCase; import org.aspectj.weaver.patterns.PatternParser; import org.aspectj.weaver.tools.ContextBasedMatcher; import org.aspectj.weaver.tools.FuzzyBoolean; import org.aspectj.weaver.tools.MatchingContext; import org.aspectj.weaver.tools.PointcutDesignatorHandler; import junit.framework.Test; /** * These are tests for AspectJ1.5.4 */ public class Ajc154Tests extends org.aspectj.testing.XMLBasedAjcTestCase { // public void testNewDesignatorsReferencePointcuts_pr205907() { // BeanDesignatorHandler beanHandler = new BeanDesignatorHandler(); // Set set = new HashSet(); // set.add(beanHandler); // PatternParser.setTestDesignators(set); // //parser.registerPointcutDesignatorHandler(beanHandler); // runTest("new pointcut designators in a reference pointcut"); // } public void testNPEWithMissingAtAspectAnnotationInPointcutLibrary_pr162539_1() { runTest("NPE with missing @aspect annotation in pointcut library - 1"); } public void testNPEWithMissingAtAspectAnnotationInPointcutLibrary_pr162539_2() { runTest("NPE with missing @aspect annotation in pointcut library - 2"); } public void testWrongNumberOfTypeParameters_pr176991() { runTest("wrong number of type parameters");} public void testArgNamesDoesNotWork_pr148381_1() { runTest("argNames does not work - simple");} public void testArgNamesDoesNotWork_pr148381_2() { runTest("argNames does not work - error1");} public void testArgNamesDoesNotWork_pr148381_3() { runTest("argNames does not work - error2");} public void testArgNamesDoesNotWork_pr148381_4() { runTest("argNames does not work - error3");} //public void testAsteriskInAtPointcut_pr209051() { runTest("asterisk in at aj pointcut");} public void testDecpProblemWhenTargetAlreadyImplements_pr169432_1() { runTest("declare parents problem when target already implements interface - 1");} public void testDecpProblemWhenTargetAlreadyImplements_pr169432_2() { runTest("declare parents problem when target already implements interface - 2");} public void testDecpProblemWhenTargetAlreadyImplements_pr169432_3() { runTest("declare parents problem when target already implements interface - 3");} public void testVariousLtwAroundProblems_pr209019_1() { runTest("various issues with ltw and around advice - 1"); } public void testVariousLtwAroundProblems_pr209019_2() { runTest("various issues with ltw and around advice - 2"); } public void testVariousLtwAroundProblems_pr209019_3() { runTest("various issues with ltw and around advice - 3"); } public void testVariousLtwAroundProblems_pr209019_4() { runTest("various issues with ltw and around advice - 4"); } public void testAbstractAnnotationStylePointcutWithContext_pr202088() { runTest("abstract annotation style pointcut with context");} public void testNoErrorForAtDecpInNormalClass_pr169428() { runTest( "no error for atDecp in normal class");} public void testJarsZipsNonStandardSuffix_pr186673() { runTest("jars and zips with non-standard suffix");} //public void testGenericTypeParameterizedWithArrayType_pr167197() { runTest("generic type parameterized with array type");} public void testItdOnGenericInnerInterface_pr203646() { runTest("npe with itd on inner generic interface");} public void testItdOnGenericInnerInterface_pr203646_A() { runTest("npe with itd on inner generic interface - exampleA");} public void testItdOnGenericInnerInterface_pr203646_B() { runTest("npe with itd on inner generic interface - exampleB");} public void testItdOnGenericInnerInterface_pr203646_C() { runTest("npe with itd on inner generic interface - exampleC");} public void testItdOnGenericInnerInterface_pr203646_D() { runTest("npe with itd on inner generic interface - exampleD");} // public void testItdOnGenericInnerInterface_pr203646_E() { runTest("npe with itd on inner generic interface - exampleE");} // needs parser change public void testItdOnGenericInnerInterface_pr203646_F() { runTest("npe with itd on inner generic interface - exampleF");} public void testItdOnGenericInnerInterface_pr203646_G() { runTest("npe with itd on inner generic interface - exampleG");} public void testItdClashForTypesFromAspectPath_pr206732() { runTest("itd clash for types from aspectpath"); } // public void testAnnotationStyleAndMultiplePackages_pr197719() { runTest("annotation style syntax and cross package extension"); } /** Complex test that attempts to damage a class like a badly behaved bytecode transformer would and checks if AspectJ can cope. */ public void testCopingWithGarbage_pr175806_1() throws ClassNotFoundException { // Compile the program we are going to mess with runTest("coping with bad tables"); // Load up the class and the method 'main' we are interested in JavaClass jc = getClassFrom(ajc.getSandboxDirectory(),"A"); Method[] meths = jc.getMethods(); Method oneWeWant = null; for (int i = 0; i < meths.length && oneWeWant==null; i++) { Method method = meths[i]; if (method.getName().equals("main")) oneWeWant = meths[i]; } /** * For the main method: Stack=2, Locals=3, Args_size=1 0: iconst_5 1: istore_1 2: ldc #18; //String 3 4: astore_2 5: getstatic #24; //Field java/lang/System.out:Ljava/io/PrintStream; 8: aload_2 9: invokevirtual #30; //Method java/io/PrintStream.println:(Ljava/lang/String;)V 12: goto 23 15: pop 16: getstatic #24; //Field java/lang/System.out:Ljava/io/PrintStream; 19: iload_1 20: invokevirtual #33; //Method java/io/PrintStream.println:(I)V 23: return Exception table: from to target type 2 15 15 Class java/lang/Exception LineNumberTable: line 4: 0 line 6: 2 line 7: 5 line 8: 15 line 9: 16 line 11: 23 LocalVariableTable: Start Length Slot Name Signature 0 24 0 argv [Ljava/lang/String; 2 22 1 i I 5 10 2 s Ljava/lang/String; */ ConstantPool cp = oneWeWant.getConstantPool(); ConstantPoolGen cpg = new ConstantPoolGen(cp); // Damage the line number table, entry 2 (Line7:5) so it points to an invalid (not on an instruction boundary) position of 6 oneWeWant.getLineNumberTable().getLineNumberTable()[2].setStartPC(6); // Should be 'rounded down' when transforming it into a MethodGen, new position will be '5' // System.out.println("BEFORE\n"+oneWeWant.getLineNumberTable().toString()); MethodGen toTransform = new MethodGen(oneWeWant,"A",cpg,false); LineNumberTable lnt = toTransform.getMethod().getLineNumberTable(); assertTrue("Should have been 'rounded down' to position 5 but is "+lnt.getLineNumberTable()[2].getStartPC(), lnt.getLineNumberTable()[2].getStartPC()==5); // System.out.println("AFTER\n"+lnt.toString()); } public void testCopingWithGarbage_pr175806_2() throws ClassNotFoundException { // Compile the program we are going to mess with runTest("coping with bad tables"); // Load up the class and the method 'main' we are interested in JavaClass jc = getClassFrom(ajc.getSandboxDirectory(),"A"); Method[] meths = jc.getMethods(); Method oneWeWant = null; for (int i = 0; i < meths.length && oneWeWant==null; i++) { Method method = meths[i]; if (method.getName().equals("main")) oneWeWant = meths[i]; } // see previous test for dump of main method ConstantPool cp = oneWeWant.getConstantPool(); ConstantPoolGen cpg = new ConstantPoolGen(cp); // Damage the local variable table, entry 2 (" 2 22 1 i I") so it points to an invalid start pc of 3 oneWeWant.getLocalVariableTable().getLocalVariable(1).setStartPC(3); // Should be 'rounded down' when transforming it into a MethodGen, new position will be '2' // This next line will go BANG with an NPE if we don't correctly round the start pc down to 2 MethodGen toTransform = new MethodGen(oneWeWant,"A",cpg,true); } public void testGenericAspectGenericPointcut_pr174449() { runTest("problem with generic aspect and generic pointcut");} public void testGenericAspectGenericPointcut_noinline_pr174449() { runTest("problem with generic aspect and generic pointcut - noinline");} public void testGenericMethodsAndOrdering_ok_pr171953_2() { runTest("problem with generic methods and ordering - ok");} public void testGenericMethodsAndOrdering_bad_pr171953_2() { runTest("problem with generic methods and ordering - bad");} public void testItdAndJoinpointSignatureCollection_ok_pr171953() { runTest("problem with itd and join point signature collection - ok");} public void testItdAndJoinpointSignatureCollection_bad_pr171953() { runTest("problem with itd and join point signature collection - bad");} public void testGenericMethodsAndItds_pr171952() { runTest("generic methods and ITDs");} //public void testUsingDecpAnnotationWithoutAspectAnnotation_pr169428() { runTest("using decp annotation without aspect annotation");} public void testItdsParameterizedParameters_pr170467() { runTest("itds and parameterized parameters");} public void testComplexGenerics_pr168044() { runTest("complex generics - 1");} public void testIncorrectlyMarkingFieldTransient_pr168063() { runTest("incorrectly marking field transient");} public void testInheritedAnnotations_pr169706() { runTest("inherited annotations");} public void testGenericFieldNPE_pr165885() { runTest("generic field npe");} public void testIncorrectOptimizationOfIstore_pr166084() { runTest("incorrect optimization of istore"); } public void testDualParameterizationsNotAllowed_pr165631() { runTest("dual parameterizations not allowed"); } public void testSuppressWarnings1_pr166238() { runTest("Suppress warnings1"); } public void testSuppressWarnings2_pr166238() { runTest("Suppress warnings2"); } public void testNullReturnedFromGetField_pr172107() { runTest("null returned from getField()"); } ///////////////////////////////////////// public static Test suite() { return XMLBasedAjcTestCase.loadSuite(Ajc154Tests.class); } protected File getSpecFile() { return new File("../tests/src/org/aspectj/systemtest/ajc154/ajc154.xml"); } public SyntheticRepository createRepos(File cpentry) { ClassPath cp = new ClassPath(cpentry+File.pathSeparator+System.getProperty("java.class.path")); return SyntheticRepository.getInstance(cp); } protected JavaClass getClassFrom(File where,String clazzname) throws ClassNotFoundException { SyntheticRepository repos = createRepos(where); return repos.loadClass(clazzname); } // --- private class BeanDesignatorHandler implements PointcutDesignatorHandler { private String askedToParse; public boolean simulateDynamicTest = false; public String getDesignatorName() { return "bean"; } /* (non-Javadoc) * @see org.aspectj.weaver.tools.PointcutDesignatorHandler#parse(java.lang.String) */ public ContextBasedMatcher parse(String expression) { this.askedToParse = expression; return new BeanPointcutExpression(expression,this.simulateDynamicTest); } public String getExpressionLastAskedToParse() { return this.askedToParse; } } private class BeanPointcutExpression implements ContextBasedMatcher { private final String beanNamePattern; private final boolean simulateDynamicTest; public BeanPointcutExpression(String beanNamePattern, boolean simulateDynamicTest) { this.beanNamePattern = beanNamePattern; this.simulateDynamicTest = simulateDynamicTest; } public boolean couldMatchJoinPointsInType(Class aClass) { return true; } /* (non-Javadoc) * @see org.aspectj.weaver.tools.ContextBasedMatcher#couldMatchJoinPointsInType(java.lang.Class) */ public boolean couldMatchJoinPointsInType(Class aClass, MatchingContext context) { if (this.beanNamePattern.equals(context.getBinding("beanName"))) { return true; } else { return false; } } /* (non-Javadoc) * @see org.aspectj.weaver.tools.ContextBasedMatcher#mayNeedDynamicTest() */ public boolean mayNeedDynamicTest() { return this.simulateDynamicTest; } public FuzzyBoolean matchesStatically(MatchingContext matchContext) { if (this.simulateDynamicTest) return FuzzyBoolean.MAYBE; if (this.beanNamePattern.equals(matchContext.getBinding("beanName"))) { return FuzzyBoolean.YES; } else { return FuzzyBoolean.NO; } } /* (non-Javadoc) * @see org.aspectj.weaver.tools.ContextBasedMatcher#matchesDynamically(org.aspectj.weaver.tools.MatchingContext) */ public boolean matchesDynamically(MatchingContext matchContext) { return this.beanNamePattern.equals(matchContext.getBinding("beanName")); } } }
203,384
Bug 203384 AST: Type information not exposed on itmd, itfd...
The Types: org/aspectj/org/eclipse/jdt/core/dom/InterTypeFieldDeclaration.java org/aspectj/org/eclipse/jdt/core/dom/InterTypeMethodDeclaration.java Which can be returned by visiting the AjAST tree do not expose the name of the type on which the method or field is added. I require this information in the project I'm currently working on, and would appreciate if it was added.
resolved fixed
114db35
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2008-01-22T18:48:29Z"
"2007-09-14T00:33:20Z"
org.aspectj.ajdt.core/src/org/aspectj/org/eclipse/jdt/core/dom/AjASTConverter.java
/******************************************************************************* * Copyright (c) 2000, 2005 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.aspectj.org.eclipse.jdt.core.dom; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import org.aspectj.ajdt.internal.compiler.ast.AdviceDeclaration; import org.aspectj.ajdt.internal.compiler.ast.AspectDeclaration; import org.aspectj.ajdt.internal.compiler.ast.DeclareDeclaration; import org.aspectj.ajdt.internal.compiler.ast.InterTypeConstructorDeclaration; import org.aspectj.ajdt.internal.compiler.ast.InterTypeDeclaration; import org.aspectj.ajdt.internal.compiler.ast.InterTypeFieldDeclaration; import org.aspectj.ajdt.internal.compiler.ast.InterTypeMethodDeclaration; import org.aspectj.ajdt.internal.compiler.ast.PointcutDeclaration; import org.aspectj.org.eclipse.jdt.core.compiler.CategorizedProblem; import org.aspectj.org.eclipse.jdt.core.compiler.CharOperation; import org.aspectj.org.eclipse.jdt.core.compiler.IProblem; import org.aspectj.org.eclipse.jdt.core.compiler.InvalidInputException; import org.aspectj.org.eclipse.jdt.core.dom.Modifier.ModifierKeyword; 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.ForeachStatement; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.JavadocArgumentExpression; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.JavadocFieldReference; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.JavadocMessageSend; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.LocalDeclaration; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.ParameterizedQualifiedTypeReference; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.ParameterizedSingleTypeReference; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.QualifiedTypeReference; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.SingleTypeReference; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.StringLiteralConcatenation; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.TypeReference; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.Wildcard; import org.aspectj.org.eclipse.jdt.internal.compiler.classfmt.ClassFileConstants; import org.aspectj.org.eclipse.jdt.internal.compiler.env.IGenericType; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.BlockScope; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.ExtraCompilerModifiers; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.TypeConstants; import org.aspectj.org.eclipse.jdt.internal.compiler.parser.Scanner; import org.aspectj.org.eclipse.jdt.internal.compiler.parser.TerminalTokens; import org.aspectj.weaver.AdviceKind; import org.aspectj.weaver.patterns.Declare; import org.aspectj.weaver.patterns.DeclareAnnotation; import org.aspectj.weaver.patterns.DeclareErrorOrWarning; import org.aspectj.weaver.patterns.DeclareParents; import org.aspectj.weaver.patterns.DeclarePrecedence; import org.aspectj.weaver.patterns.DeclareSoft; import org.aspectj.weaver.patterns.PatternNode; import org.aspectj.weaver.patterns.SignaturePattern; import org.aspectj.weaver.patterns.TypePattern; import org.eclipse.core.runtime.IProgressMonitor; /** * Internal class for converting internal compiler ASTs into public ASTs. */ public class AjASTConverter extends ASTConverter { public AjASTConverter(Map options, boolean resolveBindings, IProgressMonitor monitor) { super(options,resolveBindings,monitor); } public ASTNode convert(AdviceDeclaration adviceDeclaration){ // ajh02: method added org.aspectj.org.eclipse.jdt.core.dom.AdviceDeclaration adviceDecl = null; if (adviceDeclaration.kind.equals(AdviceKind.Before)){ adviceDecl = new org.aspectj.org.eclipse.jdt.core.dom.BeforeAdviceDeclaration(this.ast); } else if (adviceDeclaration.kind.equals(AdviceKind.After)){ adviceDecl = new org.aspectj.org.eclipse.jdt.core.dom.AfterAdviceDeclaration(this.ast); } else if (adviceDeclaration.kind.equals(AdviceKind.AfterThrowing)){ adviceDecl = new AfterThrowingAdviceDeclaration(this.ast); if (adviceDeclaration.extraArgument != null) { SingleVariableDeclaration throwing = convert(adviceDeclaration.extraArgument); ((AfterThrowingAdviceDeclaration)adviceDecl).setThrowing(throwing); } } else if (adviceDeclaration.kind.equals(AdviceKind.AfterReturning)){ adviceDecl = new AfterReturningAdviceDeclaration(this.ast); if (adviceDeclaration.extraArgument != null) { SingleVariableDeclaration returning = convert(adviceDeclaration.extraArgument); ((AfterReturningAdviceDeclaration)adviceDecl).setReturning(returning); } } else if (adviceDeclaration.kind.equals(AdviceKind.Around)){ adviceDecl = new AroundAdviceDeclaration(this.ast); // set the returnType org.aspectj.org.eclipse.jdt.internal.compiler.ast.TypeReference typeReference = adviceDeclaration.returnType; if (typeReference != null) { Type returnType = convertType(typeReference); // get the positions of the right parenthesis setTypeForAroundAdviceDeclaration((AroundAdviceDeclaration)adviceDecl, returnType); } org.aspectj.org.eclipse.jdt.internal.compiler.ast.TypeParameter[] typeParameters = adviceDeclaration.typeParameters(); if (typeParameters != null) { switch(this.ast.apiLevel) { case AST.JLS2_INTERNAL : adviceDecl.setFlags(adviceDecl.getFlags() | ASTNode.MALFORMED); break; case AST.JLS3 : for (int i = 0, max = typeParameters.length; i < max; i++) { ((AroundAdviceDeclaration)adviceDecl).typeParameters().add(convert(typeParameters[i])); } } } } // set its javadoc, parameters, throws, pointcut and body org.aspectj.weaver.patterns.Pointcut pointcut = adviceDeclaration.pointcutDesignator.getPointcut(); adviceDecl.setPointcut(convert(pointcut)); org.aspectj.org.eclipse.jdt.internal.compiler.ast.TypeReference[] thrownExceptions = adviceDeclaration.thrownExceptions; if (thrownExceptions != null) { int thrownExceptionsLength = thrownExceptions.length; for (int i = 0; i < thrownExceptionsLength; i++) { adviceDecl.thrownExceptions().add(convert(thrownExceptions[i])); } } org.aspectj.org.eclipse.jdt.internal.compiler.ast.Argument[] parameters = adviceDeclaration.arguments; if (parameters != null) { int parametersLength = parameters.length; for (int i = 0; i < parametersLength; i++) { adviceDecl.parameters().add(convert(parameters[i])); } } int start = adviceDeclaration.sourceStart; int end = retrieveIdentifierEndPosition(start, adviceDeclaration.sourceEnd); int declarationSourceStart = adviceDeclaration.declarationSourceStart; int declarationSourceEnd = adviceDeclaration.bodyEnd; adviceDecl.setSourceRange(declarationSourceStart, declarationSourceEnd - declarationSourceStart + 1); int closingPosition = retrieveRightBraceOrSemiColonPosition(adviceDeclaration.bodyEnd + 1, adviceDeclaration.declarationSourceEnd); if (closingPosition != -1) { int startPosition = adviceDecl.getStartPosition(); adviceDecl.setSourceRange(startPosition, closingPosition - startPosition + 1); org.aspectj.org.eclipse.jdt.internal.compiler.ast.Statement[] statements = adviceDeclaration.statements; start = retrieveStartBlockPosition(adviceDeclaration.sourceStart, declarationSourceEnd); end = retrieveEndBlockPosition(adviceDeclaration.sourceStart, adviceDeclaration.declarationSourceEnd); Block block = null; if (start != -1 && end != -1) { /* * start or end can be equal to -1 if we have an interface's method. */ block = new Block(this.ast); block.setSourceRange(start, end - start + 1); adviceDecl.setBody(block); } if (block != null && statements != null) { int statementsLength = statements == null ? 0 : statements.length; for (int i = 0; i < statementsLength; i++) { if (statements[i] instanceof org.aspectj.org.eclipse.jdt.internal.compiler.ast.LocalDeclaration) { checkAndAddMultipleLocalDeclaration(statements, i, block.statements()); } else { block.statements().add(convert(statements[i])); } } } if (block != null) { adviceDecl.setFlags(adviceDecl.getFlags() | ASTNode.MALFORMED); } } else { // syntax error in this advice declaration start = retrieveStartBlockPosition(adviceDeclaration.sourceStart, declarationSourceEnd); end = adviceDeclaration.bodyEnd; // try to get the best end position IProblem[] problems = adviceDeclaration.compilationResult().problems; if (problems != null) { for (int i = 0, max = adviceDeclaration.compilationResult().problemCount; i < max; i++) { IProblem currentProblem = problems[i]; if (currentProblem.getSourceStart() == start && currentProblem.getID() == IProblem.ParsingErrorInsertToComplete) { end = currentProblem.getSourceEnd(); break; } } } int startPosition = adviceDecl.getStartPosition(); adviceDecl.setSourceRange(startPosition, end - startPosition + 1); if (start != -1 && end != -1) { /* * start or end can be equal to -1 if we have an interface's method. */ Block block = new Block(this.ast); block.setSourceRange(start, end - start + 1); adviceDecl.setBody(block); } } // The javadoc comment is now got from list store in compilation unit declaration if (this.resolveBindings) { recordNodes(adviceDecl, adviceDeclaration); //if (adviceDecl.resolveBinding() != null) { //// ajh02: what is resolveBinding()? // convert(adviceDeclaration.javadoc, adviceDecl); //} } else { convert(adviceDeclaration.javadoc, adviceDecl); } return adviceDecl; } public ASTNode convert(org.aspectj.org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration methodDeclaration) { checkCanceled(); if (methodDeclaration instanceof org.aspectj.org.eclipse.jdt.internal.compiler.ast.AnnotationMethodDeclaration) { return convert((org.aspectj.org.eclipse.jdt.internal.compiler.ast.AnnotationMethodDeclaration) methodDeclaration); } MethodDeclaration methodDecl = new MethodDeclaration(this.ast); boolean isConstructor = methodDeclaration.isConstructor(); methodDecl.setConstructor(isConstructor); ////////////////// ajh02: added. ugh, polymorphism! Where are you! if (methodDeclaration instanceof DeclareDeclaration){ return convert((DeclareDeclaration)methodDeclaration); } else if (methodDeclaration instanceof InterTypeFieldDeclaration){ return convert((InterTypeFieldDeclaration) methodDeclaration); } else if (methodDeclaration instanceof InterTypeMethodDeclaration){ methodDecl = new org.aspectj.org.eclipse.jdt.core.dom.InterTypeMethodDeclaration(this.ast); } else if (methodDeclaration instanceof InterTypeConstructorDeclaration){ methodDecl = new org.aspectj.org.eclipse.jdt.core.dom.InterTypeMethodDeclaration(this.ast); methodDecl.setConstructor(true); } else if (methodDeclaration instanceof PointcutDeclaration){ return convert((PointcutDeclaration) methodDeclaration); } else if (methodDeclaration instanceof AdviceDeclaration){ return convert((AdviceDeclaration)methodDeclaration); } ///////////////////////// // set modifiers after checking whether we're an itd, otherwise // the modifiers are not set on the correct object. setModifiers(methodDecl, methodDeclaration); // for ITD's use the declaredSelector final SimpleName methodName = new SimpleName(this.ast); if (methodDeclaration instanceof InterTypeDeclaration) { InterTypeDeclaration itd = (InterTypeDeclaration) methodDeclaration; methodName.internalSetIdentifier(new String(itd.getDeclaredSelector())); } else { methodName.internalSetIdentifier(new String(methodDeclaration.selector)); } int start = methodDeclaration.sourceStart; int end = retrieveIdentifierEndPosition(start, methodDeclaration.sourceEnd); methodName.setSourceRange(start, end - start + 1); methodDecl.setName(methodName); org.aspectj.org.eclipse.jdt.internal.compiler.ast.TypeReference[] thrownExceptions = methodDeclaration.thrownExceptions; if (thrownExceptions != null) { int thrownExceptionsLength = thrownExceptions.length; for (int i = 0; i < thrownExceptionsLength; i++) { methodDecl.thrownExceptions().add(convert(thrownExceptions[i])); } } org.aspectj.org.eclipse.jdt.internal.compiler.ast.Argument[] parameters = methodDeclaration.arguments; if (parameters != null) { int parametersLength = parameters.length; for (int i = 0; i < parametersLength; i++) { methodDecl.parameters().add(convert(parameters[i])); } } org.aspectj.org.eclipse.jdt.internal.compiler.ast.ExplicitConstructorCall explicitConstructorCall = null; if (isConstructor) { org.aspectj.org.eclipse.jdt.internal.compiler.ast.ConstructorDeclaration constructorDeclaration = (org.aspectj.org.eclipse.jdt.internal.compiler.ast.ConstructorDeclaration) methodDeclaration; explicitConstructorCall = constructorDeclaration.constructorCall; switch(this.ast.apiLevel) { case AST.JLS2_INTERNAL : // set the return type to VOID PrimitiveType returnType = new PrimitiveType(this.ast); returnType.setPrimitiveTypeCode(PrimitiveType.VOID); returnType.setSourceRange(methodDeclaration.sourceStart, 0); methodDecl.internalSetReturnType(returnType); break; case AST.JLS3 : methodDecl.setReturnType2(null); } } else if (methodDeclaration instanceof org.aspectj.org.eclipse.jdt.internal.compiler.ast.MethodDeclaration) { org.aspectj.org.eclipse.jdt.internal.compiler.ast.MethodDeclaration method = (org.aspectj.org.eclipse.jdt.internal.compiler.ast.MethodDeclaration) methodDeclaration; org.aspectj.org.eclipse.jdt.internal.compiler.ast.TypeReference typeReference = method.returnType; if (typeReference != null) { Type returnType = convertType(typeReference); // get the positions of the right parenthesis int rightParenthesisPosition = retrieveEndOfRightParenthesisPosition(end, method.bodyEnd); int extraDimensions = retrieveExtraDimension(rightParenthesisPosition, method.bodyEnd); methodDecl.setExtraDimensions(extraDimensions); setTypeForMethodDeclaration(methodDecl, returnType, extraDimensions); } } int declarationSourceStart = methodDeclaration.declarationSourceStart; int declarationSourceEnd = methodDeclaration.bodyEnd; methodDecl.setSourceRange(declarationSourceStart, declarationSourceEnd - declarationSourceStart + 1); int closingPosition = retrieveRightBraceOrSemiColonPosition(methodDeclaration.bodyEnd + 1, methodDeclaration.declarationSourceEnd); if (closingPosition != -1) { int startPosition = methodDecl.getStartPosition(); methodDecl.setSourceRange(startPosition, closingPosition - startPosition + 1); org.aspectj.org.eclipse.jdt.internal.compiler.ast.Statement[] statements = methodDeclaration.statements; start = retrieveStartBlockPosition(methodDeclaration.sourceStart, declarationSourceEnd); end = retrieveEndBlockPosition(methodDeclaration.sourceStart, methodDeclaration.declarationSourceEnd); Block block = null; if (start != -1 && end != -1) { /* * start or end can be equal to -1 if we have an interface's method. */ block = new Block(this.ast); block.setSourceRange(start, end - start + 1); methodDecl.setBody(block); } if (block != null && (statements != null || explicitConstructorCall != null)) { if (explicitConstructorCall != null && explicitConstructorCall.accessMode != org.aspectj.org.eclipse.jdt.internal.compiler.ast.ExplicitConstructorCall.ImplicitSuper) { block.statements().add(super.convert(explicitConstructorCall)); } int statementsLength = statements == null ? 0 : statements.length; for (int i = 0; i < statementsLength; i++) { if (statements[i] instanceof org.aspectj.org.eclipse.jdt.internal.compiler.ast.LocalDeclaration) { checkAndAddMultipleLocalDeclaration(statements, i, block.statements()); } else { block.statements().add(convert(statements[i])); } } } if (block != null && (Modifier.isAbstract(methodDecl.getModifiers()) || Modifier.isNative(methodDecl.getModifiers()))) { methodDecl.setFlags(methodDecl.getFlags() | ASTNode.MALFORMED); } } else { // syntax error in this method declaration if (!methodDeclaration.isNative() && !methodDeclaration.isAbstract()) { start = retrieveStartBlockPosition(methodDeclaration.sourceStart, declarationSourceEnd); end = methodDeclaration.bodyEnd; // try to get the best end position IProblem[] problems = methodDeclaration.compilationResult().problems; if (problems != null) { for (int i = 0, max = methodDeclaration.compilationResult().problemCount; i < max; i++) { IProblem currentProblem = problems[i]; if (currentProblem.getSourceStart() == start && currentProblem.getID() == IProblem.ParsingErrorInsertToComplete) { end = currentProblem.getSourceEnd(); break; } } } int startPosition = methodDecl.getStartPosition(); methodDecl.setSourceRange(startPosition, end - startPosition + 1); if (start != -1 && end != -1) { /* * start or end can be equal to -1 if we have an interface's method. */ Block block = new Block(this.ast); block.setSourceRange(start, end - start + 1); methodDecl.setBody(block); } } } org.aspectj.org.eclipse.jdt.internal.compiler.ast.TypeParameter[] typeParameters = methodDeclaration.typeParameters(); if (typeParameters != null) { switch(this.ast.apiLevel) { case AST.JLS2_INTERNAL : methodDecl.setFlags(methodDecl.getFlags() | ASTNode.MALFORMED); break; case AST.JLS3 : for (int i = 0, max = typeParameters.length; i < max; i++) { methodDecl.typeParameters().add(convert(typeParameters[i])); } } } // The javadoc comment is now got from list store in compilation unit declaration if (this.resolveBindings) { recordNodes(methodDecl, methodDeclaration); recordNodes(methodName, methodDeclaration); if (methodDecl.resolveBinding() != null) { convert(methodDeclaration.javadoc, methodDecl); } } else { convert(methodDeclaration.javadoc, methodDecl); } return methodDecl; } public ASTNode convert(DeclareDeclaration declareDecl) { checkCanceled(); // is this line needed? org.aspectj.org.eclipse.jdt.core.dom.DeclareDeclaration declareDeclaration = null; Declare declare = declareDecl.declareDecl; if (declare instanceof DeclareAnnotation) { DeclareAnnotation da = (DeclareAnnotation)declare; if (da.getKind().equals(DeclareAnnotation.AT_TYPE)) { declareDeclaration = new DeclareAtTypeDeclaration(this.ast); ((DeclareAtTypeDeclaration)declareDeclaration).setPatternNode(convert(da.getTypePattern())); SimpleName annotationName = new SimpleName(this.ast); annotationName.internalSetIdentifier(new String(da.getAnnotationString())); ((DeclareAtTypeDeclaration)declareDeclaration).setAnnotationName(annotationName); } else if (da.getKind().equals(DeclareAnnotation.AT_CONSTRUCTOR)) { declareDeclaration = new DeclareAtConstructorDeclaration(this.ast); ((DeclareAtConstructorDeclaration)declareDeclaration).setPatternNode(convert(da.getSignaturePattern())); SimpleName annotationName = new SimpleName(this.ast); annotationName.internalSetIdentifier(new String(da.getAnnotationString())); ((DeclareAtConstructorDeclaration)declareDeclaration).setAnnotationName(annotationName); } else if (da.getKind().equals(DeclareAnnotation.AT_FIELD)) { declareDeclaration = new DeclareAtFieldDeclaration(this.ast); ((DeclareAtFieldDeclaration)declareDeclaration).setPatternNode(convert(da.getSignaturePattern())); SimpleName annotationName = new SimpleName(this.ast); annotationName.internalSetIdentifier(new String(da.getAnnotationString())); ((DeclareAtFieldDeclaration)declareDeclaration).setAnnotationName(annotationName); } else if (da.getKind().equals(DeclareAnnotation.AT_METHOD)) { declareDeclaration = new DeclareAtMethodDeclaration(this.ast); ((DeclareAtMethodDeclaration)declareDeclaration).setPatternNode(convert(da.getSignaturePattern())); SimpleName annotationName = new SimpleName(this.ast); annotationName.internalSetIdentifier(new String(da.getAnnotationString())); ((DeclareAtMethodDeclaration)declareDeclaration).setAnnotationName(annotationName); } } else if (declare instanceof DeclareErrorOrWarning){ DeclareErrorOrWarning deow = (DeclareErrorOrWarning)declare; if (deow.isError()) { declareDeclaration = new DeclareErrorDeclaration(this.ast); ((DeclareErrorDeclaration)declareDeclaration).setPointcut(convert(deow.getPointcut())); StringLiteral message = new StringLiteral(this.ast); message.setEscapedValue(updateString(deow.getMessage())); ((DeclareErrorDeclaration)declareDeclaration).setMessage(message); } else { declareDeclaration = new DeclareWarningDeclaration(this.ast); ((DeclareWarningDeclaration)declareDeclaration).setPointcut(convert(deow.getPointcut())); StringLiteral message = new StringLiteral(this.ast); message.setEscapedValue(updateString(deow.getMessage())); ((DeclareWarningDeclaration)declareDeclaration).setMessage(message); } } else if (declare instanceof DeclareParents) { DeclareParents dp = (DeclareParents)declare; declareDeclaration = new org.aspectj.org.eclipse.jdt.core.dom.DeclareParentsDeclaration(this.ast,dp.isExtends()); org.aspectj.org.eclipse.jdt.core.dom.PatternNode pNode = convert(dp.getChild()); if (pNode instanceof org.aspectj.org.eclipse.jdt.core.dom.TypePattern) { ((DeclareParentsDeclaration)declareDeclaration).setChildTypePattern((org.aspectj.org.eclipse.jdt.core.dom.TypePattern)pNode); } TypePattern[] weaverTypePatterns = dp.getParents().getTypePatterns(); List typePatterns = ((DeclareParentsDeclaration)declareDeclaration).parentTypePatterns(); for (int i = 0; i < weaverTypePatterns.length; i++) { typePatterns.add(convert(weaverTypePatterns[i])); } } else if (declare instanceof DeclarePrecedence) { declareDeclaration = new org.aspectj.org.eclipse.jdt.core.dom.DeclarePrecedenceDeclaration(this.ast); DeclarePrecedence dp = (DeclarePrecedence)declare; TypePattern[] weaverTypePatterns = dp.getPatterns().getTypePatterns(); List typePatterns = ((DeclarePrecedenceDeclaration)declareDeclaration).typePatterns(); for (int i = 0; i < weaverTypePatterns.length; i++) { typePatterns.add(convert(weaverTypePatterns[i])); } } else if (declare instanceof DeclareSoft) { declareDeclaration = new DeclareSoftDeclaration(this.ast); DeclareSoft ds = (DeclareSoft)declare; ((DeclareSoftDeclaration)declareDeclaration).setPointcut(convert(ds.getPointcut())); org.aspectj.org.eclipse.jdt.core.dom.PatternNode pNode = convert(ds.getException()); if (pNode instanceof org.aspectj.org.eclipse.jdt.core.dom.TypePattern) { ((DeclareSoftDeclaration)declareDeclaration).setTypePattern((org.aspectj.org.eclipse.jdt.core.dom.TypePattern)pNode); } } declareDeclaration.setSourceRange(declareDecl.declarationSourceStart, declareDecl.declarationSourceEnd - declareDecl.declarationSourceStart + 1); return declareDeclaration; } private String updateString(String message) { StringBuffer sb = new StringBuffer(message); int nextQuote = sb.toString().indexOf("\""); while (nextQuote != -1) { sb.insert(nextQuote,"\\"); nextQuote = sb.toString().indexOf("\""); } int nextNewLine = sb.toString().indexOf("\n"); while (nextNewLine != -1) { sb.insert(nextNewLine,"\\"); nextNewLine = sb.toString().indexOf("\n"); } if(!sb.toString().startsWith("\"")) { sb.insert(0,"\""); } if(!sb.toString().endsWith("\"")) { sb.insert(sb.toString().length(),"\""); } return sb.toString(); } public ASTNode convert(InterTypeFieldDeclaration fieldDecl) { // ajh02: method added checkCanceled(); // ajh02: is this line needed? VariableDeclarationFragment variableDeclarationFragment = convertToVariableDeclarationFragment(fieldDecl); final org.aspectj.org.eclipse.jdt.core.dom.InterTypeFieldDeclaration fieldDeclaration = new org.aspectj.org.eclipse.jdt.core.dom.InterTypeFieldDeclaration(this.ast); fieldDeclaration.fragments().add(variableDeclarationFragment); IVariableBinding binding = null; if (this.resolveBindings) { recordNodes(variableDeclarationFragment, fieldDecl); binding = variableDeclarationFragment.resolveBinding(); } fieldDeclaration.setSourceRange(fieldDecl.declarationSourceStart, fieldDecl.declarationSourceEnd - fieldDecl.declarationSourceStart + 1); Type type = convertType(fieldDecl.returnType); setTypeForField(fieldDeclaration, type, variableDeclarationFragment.getExtraDimensions()); setModifiers(fieldDeclaration, fieldDecl); if (!(this.resolveBindings && binding == null)) { convert(fieldDecl.javadoc, fieldDeclaration); } return fieldDeclaration; } public ASTNode convert(PointcutDeclaration pointcutDeclaration) { // ajh02: method added checkCanceled(); org.aspectj.org.eclipse.jdt.core.dom.PointcutDeclaration pointcutDecl = new org.aspectj.org.eclipse.jdt.core.dom.PointcutDeclaration(this.ast); setModifiers(pointcutDecl, pointcutDeclaration); final SimpleName pointcutName = new SimpleName(this.ast); pointcutName.internalSetIdentifier(new String(pointcutDeclaration.selector)); int start = pointcutDeclaration.sourceStart; int end = retrieveIdentifierEndPosition(start, pointcutDeclaration.sourceEnd); pointcutName.setSourceRange(start, end - start + 1); pointcutDecl.setSourceRange(pointcutDeclaration.declarationSourceStart, (pointcutDeclaration.bodyEnd - pointcutDeclaration.declarationSourceStart + 1)); pointcutDecl.setName(pointcutName); if (pointcutDeclaration.pointcutDesignator != null){ pointcutDecl.setDesignator((org.aspectj.org.eclipse.jdt.core.dom.PointcutDesignator)convert(pointcutDeclaration.pointcutDesignator.getPointcut())); } else { pointcutDecl.setDesignator(new org.aspectj.org.eclipse.jdt.core.dom.DefaultPointcut(this.ast,pointcutDeclaration.toString())); } org.aspectj.org.eclipse.jdt.internal.compiler.ast.Argument[] parameters = pointcutDeclaration.arguments; if (parameters != null) { int parametersLength = parameters.length; for (int i = 0; i < parametersLength; i++) { pointcutDecl.parameters().add(convert(parameters[i])); } } // The javadoc comment is now got from list store in compilation unit declaration if (this.resolveBindings) { recordNodes(pointcutDecl, pointcutDeclaration); recordNodes(pointcutName, pointcutDeclaration); } else { convert(pointcutDeclaration.javadoc, pointcutDecl); } return pointcutDecl; } public org.aspectj.org.eclipse.jdt.core.dom.PointcutDesignator convert(org.aspectj.weaver.patterns.Pointcut pointcut){ // ajh02: this could do with being seperate methods // rather than a huge if.elseif..elseif.. thing org.aspectj.org.eclipse.jdt.core.dom.PointcutDesignator pointcutDesi = null; if (pointcut instanceof org.aspectj.weaver.patterns.ReferencePointcut){ pointcutDesi = new org.aspectj.org.eclipse.jdt.core.dom.ReferencePointcut(this.ast); final SimpleName pointcutName = new SimpleName(this.ast); int start = pointcut.getStart(); int end = retrieveIdentifierEndPosition(start, pointcut.getEnd()); pointcutName.setSourceRange(start, end - start + 1); pointcutName.internalSetIdentifier(((org.aspectj.weaver.patterns.ReferencePointcut)pointcut).name); ((org.aspectj.org.eclipse.jdt.core.dom.ReferencePointcut)pointcutDesi).setName(pointcutName); } else if (pointcut instanceof org.aspectj.weaver.patterns.NotPointcut) { pointcutDesi = new org.aspectj.org.eclipse.jdt.core.dom.NotPointcut(this.ast); final org.aspectj.org.eclipse.jdt.core.dom.PointcutDesignator body = convert(((org.aspectj.weaver.patterns.NotPointcut)pointcut).getNegatedPointcut()); ((org.aspectj.org.eclipse.jdt.core.dom.NotPointcut)pointcutDesi).setBody(body); } else if (pointcut instanceof org.aspectj.weaver.patterns.PerObject) { pointcutDesi = new org.aspectj.org.eclipse.jdt.core.dom.PerObject(this.ast); final org.aspectj.org.eclipse.jdt.core.dom.PointcutDesignator body = convert(((org.aspectj.weaver.patterns.PerObject)pointcut).getEntry()); ((org.aspectj.org.eclipse.jdt.core.dom.PerObject)pointcutDesi).setBody(body); } else if (pointcut instanceof org.aspectj.weaver.patterns.PerCflow) { pointcutDesi = new org.aspectj.org.eclipse.jdt.core.dom.PerCflow(this.ast); final org.aspectj.org.eclipse.jdt.core.dom.PointcutDesignator body = convert(((org.aspectj.weaver.patterns.PerCflow)pointcut).getEntry()); ((org.aspectj.org.eclipse.jdt.core.dom.PerCflow)pointcutDesi).setBody(body); } else if (pointcut instanceof org.aspectj.weaver.patterns.PerTypeWithin) { pointcutDesi = new org.aspectj.org.eclipse.jdt.core.dom.PerTypeWithin(this.ast); // should set its type pattern here } else if (pointcut instanceof org.aspectj.weaver.patterns.CflowPointcut) { pointcutDesi = new org.aspectj.org.eclipse.jdt.core.dom.CflowPointcut(this.ast); final org.aspectj.org.eclipse.jdt.core.dom.PointcutDesignator body = convert(((org.aspectj.weaver.patterns.CflowPointcut)pointcut).getEntry()); ((org.aspectj.org.eclipse.jdt.core.dom.CflowPointcut)pointcutDesi).setBody(body); ((org.aspectj.org.eclipse.jdt.core.dom.CflowPointcut)pointcutDesi).setIsCflowBelow(((org.aspectj.weaver.patterns.CflowPointcut)pointcut).isCflowBelow()); } else if (pointcut instanceof org.aspectj.weaver.patterns.AndPointcut) { pointcutDesi = new org.aspectj.org.eclipse.jdt.core.dom.AndPointcut(this.ast); final org.aspectj.org.eclipse.jdt.core.dom.PointcutDesignator left = convert(((org.aspectj.weaver.patterns.AndPointcut)pointcut).getLeft()); final org.aspectj.org.eclipse.jdt.core.dom.PointcutDesignator right = convert(((org.aspectj.weaver.patterns.AndPointcut)pointcut).getRight()); ((org.aspectj.org.eclipse.jdt.core.dom.AndPointcut)pointcutDesi).setLeft(left); ((org.aspectj.org.eclipse.jdt.core.dom.AndPointcut)pointcutDesi).setRight(right); } else if (pointcut instanceof org.aspectj.weaver.patterns.OrPointcut) { pointcutDesi = new org.aspectj.org.eclipse.jdt.core.dom.OrPointcut(this.ast); final org.aspectj.org.eclipse.jdt.core.dom.PointcutDesignator left = convert(((org.aspectj.weaver.patterns.OrPointcut)pointcut).getLeft()); final org.aspectj.org.eclipse.jdt.core.dom.PointcutDesignator right = convert(((org.aspectj.weaver.patterns.OrPointcut)pointcut).getRight()); ((org.aspectj.org.eclipse.jdt.core.dom.OrPointcut)pointcutDesi).setLeft(left); ((org.aspectj.org.eclipse.jdt.core.dom.OrPointcut)pointcutDesi).setRight(right); } else { // ajh02: default stub until I make all the concrete PointcutDesignator types pointcutDesi = new org.aspectj.org.eclipse.jdt.core.dom.DefaultPointcut(this.ast,pointcut.toString()); } pointcutDesi.setSourceRange(pointcut.getStart(),(pointcut.getEnd() - pointcut.getStart() + 1)); return pointcutDesi; } public org.aspectj.org.eclipse.jdt.core.dom.PatternNode convert(PatternNode patternNode){ // this is a stub to be used until dom classes have been created for // the different weaver TypePattern's org.aspectj.org.eclipse.jdt.core.dom.PatternNode pNode = null; if (patternNode instanceof TypePattern) { TypePattern typePat = (TypePattern)patternNode; pNode = new DefaultTypePattern(this.ast,typePat.toString()); pNode.setSourceRange(typePat.getStart(),(typePat.getEnd() - typePat.getStart() + 1)); } else if (patternNode instanceof SignaturePattern) { SignaturePattern sigPat = (SignaturePattern)patternNode; pNode = new org.aspectj.org.eclipse.jdt.core.dom.SignaturePattern(this.ast,sigPat.toString()); pNode.setSourceRange(sigPat.getStart(),(sigPat.getEnd() - sigPat.getStart() + 1)); } return pNode; } public ASTNode convert(org.aspectj.org.eclipse.jdt.internal.compiler.ast.AnnotationMethodDeclaration annotationTypeMemberDeclaration) { checkCanceled(); if (this.ast.apiLevel == AST.JLS2_INTERNAL) { return null; } AnnotationTypeMemberDeclaration annotationTypeMemberDeclaration2 = new AnnotationTypeMemberDeclaration(this.ast); setModifiers(annotationTypeMemberDeclaration2, annotationTypeMemberDeclaration); final SimpleName methodName = new SimpleName(this.ast); methodName.internalSetIdentifier(new String(annotationTypeMemberDeclaration.selector)); int start = annotationTypeMemberDeclaration.sourceStart; int end = retrieveIdentifierEndPosition(start, annotationTypeMemberDeclaration.sourceEnd); methodName.setSourceRange(start, end - start + 1); annotationTypeMemberDeclaration2.setName(methodName); org.aspectj.org.eclipse.jdt.internal.compiler.ast.TypeReference typeReference = annotationTypeMemberDeclaration.returnType; if (typeReference != null) { Type returnType = convertType(typeReference); setTypeForMethodDeclaration(annotationTypeMemberDeclaration2, returnType, 0); } int declarationSourceStart = annotationTypeMemberDeclaration.declarationSourceStart; int declarationSourceEnd = annotationTypeMemberDeclaration.bodyEnd; annotationTypeMemberDeclaration2.setSourceRange(declarationSourceStart, declarationSourceEnd - declarationSourceStart + 1); // The javadoc comment is now got from list store in compilation unit declaration convert(annotationTypeMemberDeclaration.javadoc, annotationTypeMemberDeclaration2); org.aspectj.org.eclipse.jdt.internal.compiler.ast.Expression memberValue = annotationTypeMemberDeclaration.defaultValue; if (memberValue != null) { annotationTypeMemberDeclaration2.setDefault(super.convert(memberValue)); } if (this.resolveBindings) { recordNodes(annotationTypeMemberDeclaration2, annotationTypeMemberDeclaration); recordNodes(methodName, annotationTypeMemberDeclaration); annotationTypeMemberDeclaration2.resolveBinding(); } return annotationTypeMemberDeclaration2; } public SingleVariableDeclaration convert(org.aspectj.org.eclipse.jdt.internal.compiler.ast.Argument argument) { SingleVariableDeclaration variableDecl = new SingleVariableDeclaration(this.ast); setModifiers(variableDecl, argument); final SimpleName name = new SimpleName(this.ast); name.internalSetIdentifier(new String(argument.name)); int start = argument.sourceStart; int nameEnd = argument.sourceEnd; name.setSourceRange(start, nameEnd - start + 1); variableDecl.setName(name); final int typeSourceEnd = argument.type.sourceEnd; final int extraDimensions = retrieveExtraDimension(nameEnd + 1, typeSourceEnd); variableDecl.setExtraDimensions(extraDimensions); final boolean isVarArgs = argument.isVarArgs(); if (isVarArgs && extraDimensions == 0) { // remove the ellipsis from the type source end argument.type.sourceEnd = retrieveEllipsisStartPosition(argument.type.sourceStart, typeSourceEnd); } Type type = convertType(argument.type); int typeEnd = type.getStartPosition() + type.getLength() - 1; int rightEnd = Math.max(typeEnd, argument.declarationSourceEnd); /* * There is extra work to do to set the proper type positions * See PR http://bugs.eclipse.org/bugs/show_bug.cgi?id=23284 */ if (isVarArgs) { setTypeForSingleVariableDeclaration(variableDecl, type, extraDimensions + 1); if (extraDimensions != 0) { variableDecl.setFlags(variableDecl.getFlags() | ASTNode.MALFORMED); } } else { setTypeForSingleVariableDeclaration(variableDecl, type, extraDimensions); } variableDecl.setSourceRange(argument.declarationSourceStart, rightEnd - argument.declarationSourceStart + 1); if (isVarArgs) { switch(this.ast.apiLevel) { case AST.JLS2_INTERNAL : variableDecl.setFlags(variableDecl.getFlags() | ASTNode.MALFORMED); break; case AST.JLS3 : variableDecl.setVarargs(true); } } if (this.resolveBindings) { recordNodes(name, argument); recordNodes(variableDecl, argument); variableDecl.resolveBinding(); } return variableDecl; } // public Annotation convert(org.aspectj.org.eclipse.jdt.internal.compiler.ast.Annotation annotation) { // if (annotation instanceof org.aspectj.org.eclipse.jdt.internal.compiler.ast.SingleMemberAnnotation) { // return convert((org.aspectj.org.eclipse.jdt.internal.compiler.ast.SingleMemberAnnotation) annotation); // } else if (annotation instanceof org.aspectj.org.eclipse.jdt.internal.compiler.ast.MarkerAnnotation) { // org.aspectj.org.eclipse.jdt.internal.compiler.ast.MarkerAnnotation ma = // (org.aspectj.org.eclipse.jdt.internal.compiler.ast.MarkerAnnotation) annotation; // return convert( ma);//(org.aspectj.org.eclipse.jdt.internal.compiler.ast.MarkerAnnotation) annotation); // } else { // return convert((org.aspectj.org.eclipse.jdt.internal.compiler.ast.NormalAnnotation) annotation); // } // } // public ArrayCreation convert(org.aspectj.org.eclipse.jdt.internal.compiler.ast.ArrayAllocationExpression expression) { // ArrayCreation arrayCreation = new ArrayCreation(this.ast); // if (this.resolveBindings) { // recordNodes(arrayCreation, expression); // } // arrayCreation.setSourceRange(expression.sourceStart, expression.sourceEnd - expression.sourceStart + 1); // org.aspectj.org.eclipse.jdt.internal.compiler.ast.Expression[] dimensions = expression.dimensions; // // int dimensionsLength = dimensions.length; // for (int i = 0; i < dimensionsLength; i++) { // if (dimensions[i] != null) { // Expression dimension = convert(dimensions[i]); // if (this.resolveBindings) { // recordNodes(dimension, dimensions[i]); // } // arrayCreation.dimensions().add(dimension); // } // } // Type type = convertType(expression.type); // if (this.resolveBindings) { // recordNodes(type, expression.type); // } // ArrayType arrayType = null; // if (type.isArrayType()) { // arrayType = (ArrayType) type; // } else { // arrayType = this.ast.newArrayType(type, dimensionsLength); // if (this.resolveBindings) { // completeRecord(arrayType, expression); // } // int start = type.getStartPosition(); // int end = type.getStartPosition() + type.getLength(); // int previousSearchStart = end; // ArrayType componentType = (ArrayType) type.getParent(); // for (int i = 0; i < dimensionsLength; i++) { // previousSearchStart = retrieveRightBracketPosition(previousSearchStart + 1, this.compilationUnitSourceLength); // componentType.setSourceRange(start, previousSearchStart - start + 1); // componentType = (ArrayType) componentType.getParent(); // } // } // arrayCreation.setType(arrayType); // if (this.resolveBindings) { // recordNodes(arrayType, expression); // } // if (expression.initializer != null) { // arrayCreation.setInitializer(convert(expression.initializer)); // } // return arrayCreation; // } public ArrayInitializer convert(org.aspectj.org.eclipse.jdt.internal.compiler.ast.ArrayInitializer expression) { ArrayInitializer arrayInitializer = new ArrayInitializer(this.ast); if (this.resolveBindings) { recordNodes(arrayInitializer, expression); } arrayInitializer.setSourceRange(expression.sourceStart, expression.sourceEnd - expression.sourceStart + 1); org.aspectj.org.eclipse.jdt.internal.compiler.ast.Expression[] expressions = expression.expressions; if (expressions != null) { int length = expressions.length; for (int i = 0; i < length; i++) { Expression expr = super.convert(expressions[i]); if (this.resolveBindings) { recordNodes(expr, expressions[i]); } arrayInitializer.expressions().add(expr); } } return arrayInitializer; } // public ArrayAccess convert(org.aspectj.org.eclipse.jdt.internal.compiler.ast.ArrayReference reference) { // ArrayAccess arrayAccess = new ArrayAccess(this.ast); // if (this.resolveBindings) { // recordNodes(arrayAccess, reference); // } // arrayAccess.setSourceRange(reference.sourceStart, reference.sourceEnd - reference.sourceStart + 1); // arrayAccess.setArray(convert(reference.receiver)); // arrayAccess.setIndex(convert(reference.position)); // return arrayAccess; // } // public AssertStatement convert(org.aspectj.org.eclipse.jdt.internal.compiler.ast.AssertStatement statement) { // AssertStatement assertStatement = new AssertStatement(this.ast); // int end = statement.assertExpression.sourceEnd + 1; // assertStatement.setExpression(convert(statement.assertExpression)); // org.aspectj.org.eclipse.jdt.internal.compiler.ast.Expression exceptionArgument = statement.exceptionArgument; // if (exceptionArgument != null) { // end = exceptionArgument.sourceEnd + 1; // assertStatement.setMessage(convert(exceptionArgument)); // } // int start = statement.sourceStart; // int sourceEnd = retrieveEndingSemiColonPosition(end, this.compilationUnitSourceLength); // assertStatement.setSourceRange(start, sourceEnd - start + 1); // return assertStatement; // } // public Assignment convert(org.aspectj.org.eclipse.jdt.internal.compiler.ast.Assignment expression) { // Assignment assignment = new Assignment(this.ast); // if (this.resolveBindings) { // recordNodes(assignment, expression); // } // Expression lhs = convert(expression.lhs); // assignment.setLeftHandSide(lhs); // assignment.setOperator(Assignment.Operator.ASSIGN); // assignment.setRightHandSide(convert(expression.expression)); // int start = lhs.getStartPosition(); // assignment.setSourceRange(start, expression.sourceEnd - start + 1); // return assignment; // } /* * Internal use only * Used to convert class body declarations */ public TypeDeclaration convert(org.aspectj.org.eclipse.jdt.internal.compiler.ast.ASTNode[] nodes) { final TypeDeclaration typeDecl = TypeDeclaration.getTypeDeclaration(this.ast); typeDecl.setInterface(false); int nodesLength = nodes.length; for (int i = 0; i < nodesLength; i++) { org.aspectj.org.eclipse.jdt.internal.compiler.ast.ASTNode node = nodes[i]; if (node instanceof org.aspectj.org.eclipse.jdt.internal.compiler.ast.Initializer) { org.aspectj.org.eclipse.jdt.internal.compiler.ast.Initializer oldInitializer = (org.aspectj.org.eclipse.jdt.internal.compiler.ast.Initializer) node; Initializer initializer = new Initializer(this.ast); initializer.setBody(convert(oldInitializer.block)); setModifiers(initializer, oldInitializer); initializer.setSourceRange(oldInitializer.declarationSourceStart, oldInitializer.sourceEnd - oldInitializer.declarationSourceStart + 1); // setJavaDocComment(initializer); // initializer.setJavadoc(convert(oldInitializer.javadoc)); convert(oldInitializer.javadoc, initializer); typeDecl.bodyDeclarations().add(initializer); } else if (node instanceof org.aspectj.org.eclipse.jdt.internal.compiler.ast.FieldDeclaration) { org.aspectj.org.eclipse.jdt.internal.compiler.ast.FieldDeclaration fieldDeclaration = (org.aspectj.org.eclipse.jdt.internal.compiler.ast.FieldDeclaration) node; if (i > 0 && (nodes[i - 1] instanceof org.aspectj.org.eclipse.jdt.internal.compiler.ast.FieldDeclaration) && ((org.aspectj.org.eclipse.jdt.internal.compiler.ast.FieldDeclaration)nodes[i - 1]).declarationSourceStart == fieldDeclaration.declarationSourceStart) { // we have a multiple field declaration // We retrieve the existing fieldDeclaration to add the new VariableDeclarationFragment FieldDeclaration currentFieldDeclaration = (FieldDeclaration) typeDecl.bodyDeclarations().get(typeDecl.bodyDeclarations().size() - 1); currentFieldDeclaration.fragments().add(convertToVariableDeclarationFragment(fieldDeclaration)); } else { // we can create a new FieldDeclaration typeDecl.bodyDeclarations().add(convertToFieldDeclaration(fieldDeclaration)); } } else if(node instanceof org.aspectj.org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration) { AbstractMethodDeclaration nextMethodDeclaration = (AbstractMethodDeclaration) node; if (!nextMethodDeclaration.isDefaultConstructor() && !nextMethodDeclaration.isClinit()) { typeDecl.bodyDeclarations().add(convert(nextMethodDeclaration)); } } else if(node instanceof org.aspectj.org.eclipse.jdt.internal.compiler.ast.TypeDeclaration) { org.aspectj.org.eclipse.jdt.internal.compiler.ast.TypeDeclaration nextMemberDeclaration = (org.aspectj.org.eclipse.jdt.internal.compiler.ast.TypeDeclaration) node; ASTNode nextMemberDeclarationNode = convert(nextMemberDeclaration); if (nextMemberDeclarationNode == null) { typeDecl.setFlags(typeDecl.getFlags() | ASTNode.MALFORMED); } else { typeDecl.bodyDeclarations().add(nextMemberDeclarationNode); } } } return typeDecl; } // public Expression convert(org.aspectj.org.eclipse.jdt.internal.compiler.ast.BinaryExpression expression) { // InfixExpression infixExpression = new InfixExpression(this.ast); // if (this.resolveBindings) { // this.recordNodes(infixExpression, expression); // } // // int expressionOperatorID = (expression.bits & org.aspectj.org.eclipse.jdt.internal.compiler.ast.ASTNode.OperatorMASK) >> org.aspectj.org.eclipse.jdt.internal.compiler.ast.ASTNode.OperatorSHIFT; // switch (expressionOperatorID) { // case org.aspectj.org.eclipse.jdt.internal.compiler.ast.OperatorIds.EQUAL_EQUAL : // infixExpression.setOperator(InfixExpression.Operator.EQUALS); // break; // case org.aspectj.org.eclipse.jdt.internal.compiler.ast.OperatorIds.LESS_EQUAL : // infixExpression.setOperator(InfixExpression.Operator.LESS_EQUALS); // break; // case org.aspectj.org.eclipse.jdt.internal.compiler.ast.OperatorIds.GREATER_EQUAL : // infixExpression.setOperator(InfixExpression.Operator.GREATER_EQUALS); // break; // case org.aspectj.org.eclipse.jdt.internal.compiler.ast.OperatorIds.NOT_EQUAL : // infixExpression.setOperator(InfixExpression.Operator.NOT_EQUALS); // break; // case org.aspectj.org.eclipse.jdt.internal.compiler.ast.OperatorIds.LEFT_SHIFT : // infixExpression.setOperator(InfixExpression.Operator.LEFT_SHIFT); // break; // case org.aspectj.org.eclipse.jdt.internal.compiler.ast.OperatorIds.RIGHT_SHIFT : // infixExpression.setOperator(InfixExpression.Operator.RIGHT_SHIFT_SIGNED); // break; // case org.aspectj.org.eclipse.jdt.internal.compiler.ast.OperatorIds.UNSIGNED_RIGHT_SHIFT : // infixExpression.setOperator(InfixExpression.Operator.RIGHT_SHIFT_UNSIGNED); // break; // case org.aspectj.org.eclipse.jdt.internal.compiler.ast.OperatorIds.OR_OR : // infixExpression.setOperator(InfixExpression.Operator.CONDITIONAL_OR); // break; // case org.aspectj.org.eclipse.jdt.internal.compiler.ast.OperatorIds.AND_AND : // infixExpression.setOperator(InfixExpression.Operator.CONDITIONAL_AND); // break; // case org.aspectj.org.eclipse.jdt.internal.compiler.ast.OperatorIds.PLUS : // infixExpression.setOperator(InfixExpression.Operator.PLUS); // break; // case org.aspectj.org.eclipse.jdt.internal.compiler.ast.OperatorIds.MINUS : // infixExpression.setOperator(InfixExpression.Operator.MINUS); // break; // case org.aspectj.org.eclipse.jdt.internal.compiler.ast.OperatorIds.REMAINDER : // infixExpression.setOperator(InfixExpression.Operator.REMAINDER); // break; // case org.aspectj.org.eclipse.jdt.internal.compiler.ast.OperatorIds.XOR : // infixExpression.setOperator(InfixExpression.Operator.XOR); // break; // case org.aspectj.org.eclipse.jdt.internal.compiler.ast.OperatorIds.AND : // infixExpression.setOperator(InfixExpression.Operator.AND); // break; // case org.aspectj.org.eclipse.jdt.internal.compiler.ast.OperatorIds.MULTIPLY : // infixExpression.setOperator(InfixExpression.Operator.TIMES); // break; // case org.aspectj.org.eclipse.jdt.internal.compiler.ast.OperatorIds.OR : // infixExpression.setOperator(InfixExpression.Operator.OR); // break; // case org.aspectj.org.eclipse.jdt.internal.compiler.ast.OperatorIds.DIVIDE : // infixExpression.setOperator(InfixExpression.Operator.DIVIDE); // break; // case org.aspectj.org.eclipse.jdt.internal.compiler.ast.OperatorIds.GREATER : // infixExpression.setOperator(InfixExpression.Operator.GREATER); // break; // case org.aspectj.org.eclipse.jdt.internal.compiler.ast.OperatorIds.LESS : // infixExpression.setOperator(InfixExpression.Operator.LESS); // } // // if (expression.left instanceof org.aspectj.org.eclipse.jdt.internal.compiler.ast.BinaryExpression // && ((expression.left.bits & org.aspectj.org.eclipse.jdt.internal.compiler.ast.ASTNode.ParenthesizedMASK) == 0)) { // // create an extended string literal equivalent => use the extended operands list // infixExpression.extendedOperands().add(convert(expression.right)); // org.aspectj.org.eclipse.jdt.internal.compiler.ast.Expression leftOperand = expression.left; // org.aspectj.org.eclipse.jdt.internal.compiler.ast.Expression rightOperand = null; // do { // rightOperand = ((org.aspectj.org.eclipse.jdt.internal.compiler.ast.BinaryExpression) leftOperand).right; // if ((((leftOperand.bits & org.aspectj.org.eclipse.jdt.internal.compiler.ast.ASTNode.OperatorMASK) >> org.aspectj.org.eclipse.jdt.internal.compiler.ast.ASTNode.OperatorSHIFT) != expressionOperatorID // && ((leftOperand.bits & org.aspectj.org.eclipse.jdt.internal.compiler.ast.ASTNode.ParenthesizedMASK) == 0)) // || ((rightOperand instanceof org.aspectj.org.eclipse.jdt.internal.compiler.ast.BinaryExpression // && ((rightOperand.bits & org.aspectj.org.eclipse.jdt.internal.compiler.ast.ASTNode.OperatorMASK) >> org.aspectj.org.eclipse.jdt.internal.compiler.ast.ASTNode.OperatorSHIFT) != expressionOperatorID) // && ((rightOperand.bits & org.aspectj.org.eclipse.jdt.internal.compiler.ast.ASTNode.ParenthesizedMASK) == 0))) { // List extendedOperands = infixExpression.extendedOperands(); // InfixExpression temp = new InfixExpression(this.ast); // if (this.resolveBindings) { // this.recordNodes(temp, expression); // } // temp.setOperator(getOperatorFor(expressionOperatorID)); // Expression leftSide = convert(leftOperand); // temp.setLeftOperand(leftSide); // temp.setSourceRange(leftSide.getStartPosition(), leftSide.getLength()); // int size = extendedOperands.size(); // for (int i = 0; i < size - 1; i++) { // Expression expr = temp; // temp = new InfixExpression(this.ast); // // if (this.resolveBindings) { // this.recordNodes(temp, expression); // } // temp.setLeftOperand(expr); // temp.setOperator(getOperatorFor(expressionOperatorID)); // temp.setSourceRange(expr.getStartPosition(), expr.getLength()); // } // infixExpression = temp; // for (int i = 0; i < size; i++) { // Expression extendedOperand = (Expression) extendedOperands.remove(size - 1 - i); // temp.setRightOperand(extendedOperand); // int startPosition = temp.getLeftOperand().getStartPosition(); // temp.setSourceRange(startPosition, extendedOperand.getStartPosition() + extendedOperand.getLength() - startPosition); // if (temp.getLeftOperand().getNodeType() == ASTNode.INFIX_EXPRESSION) { // temp = (InfixExpression) temp.getLeftOperand(); // } // } // int startPosition = infixExpression.getLeftOperand().getStartPosition(); // infixExpression.setSourceRange(startPosition, expression.sourceEnd - startPosition + 1); // if (this.resolveBindings) { // this.recordNodes(infixExpression, expression); // } // return infixExpression; // } // infixExpression.extendedOperands().add(0, convert(rightOperand)); // leftOperand = ((org.aspectj.org.eclipse.jdt.internal.compiler.ast.BinaryExpression) leftOperand).left; // } while (leftOperand instanceof org.aspectj.org.eclipse.jdt.internal.compiler.ast.BinaryExpression && ((leftOperand.bits & org.aspectj.org.eclipse.jdt.internal.compiler.ast.ASTNode.ParenthesizedMASK) == 0)); // Expression leftExpression = convert(leftOperand); // infixExpression.setLeftOperand(leftExpression); // infixExpression.setRightOperand((Expression)infixExpression.extendedOperands().remove(0)); // int startPosition = leftExpression.getStartPosition(); // infixExpression.setSourceRange(startPosition, expression.sourceEnd - startPosition + 1); // return infixExpression; // } else if (expression.left instanceof StringLiteralConcatenation // && ((expression.left.bits & org.aspectj.org.eclipse.jdt.internal.compiler.ast.ASTNode.ParenthesizedMASK) == 0)) { // StringLiteralConcatenation literal = (StringLiteralConcatenation) expression.left; // final org.aspectj.org.eclipse.jdt.internal.compiler.ast.Expression[] stringLiterals = literal.literals; // infixExpression.setLeftOperand(convert(stringLiterals[0])); // infixExpression.setRightOperand(convert(stringLiterals[1])); // for (int i = 2; i < literal.counter; i++) { // infixExpression.extendedOperands().add(convert(stringLiterals[i])); // } // infixExpression.extendedOperands().add(convert(expression.right)); // int startPosition = literal.sourceStart; // infixExpression.setSourceRange(startPosition, expression.sourceEnd - startPosition + 1); // return infixExpression; // } // Expression leftExpression = convert(expression.left); // infixExpression.setLeftOperand(leftExpression); // infixExpression.setRightOperand(convert(expression.right)); // int startPosition = leftExpression.getStartPosition(); // infixExpression.setSourceRange(startPosition, expression.sourceEnd - startPosition + 1); // return infixExpression; // } public Block convert(org.aspectj.org.eclipse.jdt.internal.compiler.ast.Block statement) { Block block = new Block(this.ast); if (statement.sourceEnd > 0) { block.setSourceRange(statement.sourceStart, statement.sourceEnd - statement.sourceStart + 1); } org.aspectj.org.eclipse.jdt.internal.compiler.ast.Statement[] statements = statement.statements; if (statements != null) { int statementsLength = statements.length; for (int i = 0; i < statementsLength; i++) { if (statements[i] instanceof org.aspectj.org.eclipse.jdt.internal.compiler.ast.LocalDeclaration) { checkAndAddMultipleLocalDeclaration(statements, i, block.statements()); } else { block.statements().add(convert(statements[i])); } } } return block; } public BreakStatement convert(org.aspectj.org.eclipse.jdt.internal.compiler.ast.BreakStatement statement) { BreakStatement breakStatement = new BreakStatement(this.ast); breakStatement.setSourceRange(statement.sourceStart, statement.sourceEnd - statement.sourceStart + 1); if (statement.label != null) { final SimpleName name = new SimpleName(this.ast); name.internalSetIdentifier(new String(statement.label)); retrieveIdentifierAndSetPositions(statement.sourceStart, statement.sourceEnd, name); breakStatement.setLabel(name); } retrieveSemiColonPosition(breakStatement); return breakStatement; } // public SwitchCase convert(org.aspectj.org.eclipse.jdt.internal.compiler.ast.CaseStatement statement) { // SwitchCase switchCase = new SwitchCase(this.ast); // org.aspectj.org.eclipse.jdt.internal.compiler.ast.Expression constantExpression = statement.constantExpression; // if (constantExpression == null) { // switchCase.setExpression(null); // } else { // switchCase.setExpression(convert(constantExpression)); // } // switchCase.setSourceRange(statement.sourceStart, statement.sourceEnd - statement.sourceStart + 1); // retrieveColonPosition(switchCase); // return switchCase; // } // public CastExpression convert(org.aspectj.org.eclipse.jdt.internal.compiler.ast.CastExpression expression) { // CastExpression castExpression = new CastExpression(this.ast); // castExpression.setSourceRange(expression.sourceStart, expression.sourceEnd - expression.sourceStart + 1); // org.aspectj.org.eclipse.jdt.internal.compiler.ast.Expression type = expression.type; // trimWhiteSpacesAndComments(type); // if (type instanceof org.aspectj.org.eclipse.jdt.internal.compiler.ast.TypeReference ) { // castExpression.setType(convertType((org.aspectj.org.eclipse.jdt.internal.compiler.ast.TypeReference)type)); // } else if (type instanceof org.aspectj.org.eclipse.jdt.internal.compiler.ast.NameReference) { // castExpression.setType(convertToType((org.aspectj.org.eclipse.jdt.internal.compiler.ast.NameReference)type)); // } // castExpression.setExpression(convert(expression.expression)); // if (this.resolveBindings) { // recordNodes(castExpression, expression); // } // return castExpression; // } public CharacterLiteral convert(org.aspectj.org.eclipse.jdt.internal.compiler.ast.CharLiteral expression) { int length = expression.sourceEnd - expression.sourceStart + 1; int sourceStart = expression.sourceStart; CharacterLiteral literal = new CharacterLiteral(this.ast); if (this.resolveBindings) { this.recordNodes(literal, expression); } literal.internalSetEscapedValue(new String(this.compilationUnitSource, sourceStart, length)); literal.setSourceRange(sourceStart, length); removeLeadingAndTrailingCommentsFromLiteral(literal); return literal; } public Expression convert(org.aspectj.org.eclipse.jdt.internal.compiler.ast.ClassLiteralAccess expression) { TypeLiteral typeLiteral = new TypeLiteral(this.ast); if (this.resolveBindings) { this.recordNodes(typeLiteral, expression); } typeLiteral.setSourceRange(expression.sourceStart, expression.sourceEnd - expression.sourceStart + 1); typeLiteral.setType(convertType(expression.type)); return typeLiteral; } public CompilationUnit convert(org.aspectj.org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration unit, char[] source) { this.compilationUnitSource = source; this.compilationUnitSourceLength = source.length; this.scanner.setSource(source, unit.compilationResult); CompilationUnit compilationUnit = new CompilationUnit(this.ast); // Parse comments int[][] comments = unit.comments; if (comments != null) { buildCommentsTable(compilationUnit, comments); } // handle the package declaration immediately // There is no node corresponding to the package declaration if (this.resolveBindings) { recordNodes(compilationUnit, unit); } if (unit.currentPackage != null) { PackageDeclaration packageDeclaration = convertPackage(unit); compilationUnit.setPackage(packageDeclaration); } org.aspectj.org.eclipse.jdt.internal.compiler.ast.ImportReference[] imports = unit.imports; if (imports != null) { int importLength = imports.length; for (int i = 0; i < importLength; i++) { compilationUnit.imports().add(convertImport(imports[i])); } } org.aspectj.org.eclipse.jdt.internal.compiler.ast.TypeDeclaration[] types = unit.types; if (types != null) { int typesLength = types.length; for (int i = 0; i < typesLength; i++) { org.aspectj.org.eclipse.jdt.internal.compiler.ast.TypeDeclaration declaration = types[i]; if (CharOperation.equals(declaration.name, TypeConstants.PACKAGE_INFO_NAME)) { continue; } ASTNode type = convert(declaration); if (type == null) { compilationUnit.setFlags(compilationUnit.getFlags() | ASTNode.MALFORMED); } else { compilationUnit.types().add(type); } } } compilationUnit.setSourceRange(unit.sourceStart, unit.sourceEnd - unit.sourceStart + 1); int problemLength = unit.compilationResult.problemCount; if (problemLength != 0) { CategorizedProblem[] resizedProblems = null; final CategorizedProblem[] problems = unit.compilationResult.getProblems(); final int realProblemLength=problems.length; if (realProblemLength == problemLength) { resizedProblems = problems; } else { System.arraycopy(problems, 0, (resizedProblems = new CategorizedProblem[realProblemLength]), 0, realProblemLength); } ASTSyntaxErrorPropagator syntaxErrorPropagator = new ASTSyntaxErrorPropagator(resizedProblems); compilationUnit.accept(syntaxErrorPropagator); compilationUnit.setProblems(resizedProblems); } if (this.resolveBindings) { lookupForScopes(); } compilationUnit.initCommentMapper(this.scanner); return compilationUnit; } // public Assignment convert(org.aspectj.org.eclipse.jdt.internal.compiler.ast.CompoundAssignment expression) { // Assignment assignment = new Assignment(this.ast); // Expression lhs = convert(expression.lhs); // assignment.setLeftHandSide(lhs); // int start = lhs.getStartPosition(); // assignment.setSourceRange(start, expression.sourceEnd - start + 1); // switch (expression.operator) { // case org.aspectj.org.eclipse.jdt.internal.compiler.ast.OperatorIds.PLUS : // assignment.setOperator(Assignment.Operator.PLUS_ASSIGN); // break; // case org.aspectj.org.eclipse.jdt.internal.compiler.ast.OperatorIds.MINUS : // assignment.setOperator(Assignment.Operator.MINUS_ASSIGN); // break; // case org.aspectj.org.eclipse.jdt.internal.compiler.ast.OperatorIds.MULTIPLY : // assignment.setOperator(Assignment.Operator.TIMES_ASSIGN); // break; // case org.aspectj.org.eclipse.jdt.internal.compiler.ast.OperatorIds.DIVIDE : // assignment.setOperator(Assignment.Operator.DIVIDE_ASSIGN); // break; // case org.aspectj.org.eclipse.jdt.internal.compiler.ast.OperatorIds.AND : // assignment.setOperator(Assignment.Operator.BIT_AND_ASSIGN); // break; // case org.aspectj.org.eclipse.jdt.internal.compiler.ast.OperatorIds.OR : // assignment.setOperator(Assignment.Operator.BIT_OR_ASSIGN); // break; // case org.aspectj.org.eclipse.jdt.internal.compiler.ast.OperatorIds.XOR : // assignment.setOperator(Assignment.Operator.BIT_XOR_ASSIGN); // break; // case org.aspectj.org.eclipse.jdt.internal.compiler.ast.OperatorIds.REMAINDER : // assignment.setOperator(Assignment.Operator.REMAINDER_ASSIGN); // break; // case org.aspectj.org.eclipse.jdt.internal.compiler.ast.OperatorIds.LEFT_SHIFT : // assignment.setOperator(Assignment.Operator.LEFT_SHIFT_ASSIGN); // break; // case org.aspectj.org.eclipse.jdt.internal.compiler.ast.OperatorIds.RIGHT_SHIFT : // assignment.setOperator(Assignment.Operator.RIGHT_SHIFT_SIGNED_ASSIGN); // break; // case org.aspectj.org.eclipse.jdt.internal.compiler.ast.OperatorIds.UNSIGNED_RIGHT_SHIFT : // assignment.setOperator(Assignment.Operator.RIGHT_SHIFT_UNSIGNED_ASSIGN); // break; // } // assignment.setRightHandSide(convert(expression.expression)); // if (this.resolveBindings) { // recordNodes(assignment, expression); // } // return assignment; // } // public ConditionalExpression convert(org.aspectj.org.eclipse.jdt.internal.compiler.ast.ConditionalExpression expression) { // ConditionalExpression conditionalExpression = new ConditionalExpression(this.ast); // if (this.resolveBindings) { // recordNodes(conditionalExpression, expression); // } // conditionalExpression.setSourceRange(expression.sourceStart, expression.sourceEnd - expression.sourceStart + 1); // conditionalExpression.setExpression(convert(expression.condition)); // conditionalExpression.setThenExpression(convert(expression.valueIfTrue)); // conditionalExpression.setElseExpression(convert(expression.valueIfFalse)); // return conditionalExpression; // } // public Statement convert(org.aspectj.org.eclipse.jdt.internal.compiler.ast.ExplicitConstructorCall statement) { // Statement newStatement; // int sourceStart = statement.sourceStart; // if (statement.isSuperAccess() || statement.isSuper()) { // SuperConstructorInvocation superConstructorInvocation = new SuperConstructorInvocation(this.ast); // if (statement.qualification != null) { // superConstructorInvocation.setExpression(convert(statement.qualification)); // } // org.aspectj.org.eclipse.jdt.internal.compiler.ast.Expression[] arguments = statement.arguments; // if (arguments != null) { // int length = arguments.length; // for (int i = 0; i < length; i++) { // superConstructorInvocation.arguments().add(convert(arguments[i])); // } // } // if (statement.typeArguments != null) { // if (sourceStart > statement.typeArgumentsSourceStart) { // sourceStart = statement.typeArgumentsSourceStart; // } // switch(this.ast.apiLevel) { // case AST.JLS2_INTERNAL : // superConstructorInvocation.setFlags(superConstructorInvocation.getFlags() | ASTNode.MALFORMED); // break; // case AST.JLS3 : // for (int i = 0, max = statement.typeArguments.length; i < max; i++) { // superConstructorInvocation.typeArguments().add(convertType(statement.typeArguments[i])); // } // break; // } // } // newStatement = superConstructorInvocation; // } else { // ConstructorInvocation constructorInvocation = new ConstructorInvocation(this.ast); // org.aspectj.org.eclipse.jdt.internal.compiler.ast.Expression[] arguments = statement.arguments; // if (arguments != null) { // int length = arguments.length; // for (int i = 0; i < length; i++) { // constructorInvocation.arguments().add(convert(arguments[i])); // } // } // if (statement.typeArguments != null) { // if (sourceStart > statement.typeArgumentsSourceStart) { // sourceStart = statement.typeArgumentsSourceStart; // } // switch(this.ast.apiLevel) { // case AST.JLS2_INTERNAL : // constructorInvocation.setFlags(constructorInvocation.getFlags() | ASTNode.MALFORMED); // break; // case AST.JLS3 : // for (int i = 0, max = statement.typeArguments.length; i < max; i++) { // constructorInvocation.typeArguments().add(convertType(statement.typeArguments[i])); // } // break; // } // } // if (statement.qualification != null) { // // this is an error // constructorInvocation.setFlags(constructorInvocation.getFlags() | ASTNode.MALFORMED); // } // newStatement = constructorInvocation; // } // newStatement.setSourceRange(sourceStart, statement.sourceEnd - sourceStart + 1); // retrieveSemiColonPosition(newStatement); // if (this.resolveBindings) { // recordNodes(newStatement, statement); // } // return newStatement; // } // public Expression convert(org.aspectj.org.eclipse.jdt.internal.compiler.ast.Expression expression) { // if ((expression.bits & org.aspectj.org.eclipse.jdt.internal.compiler.ast.ASTNode.ParenthesizedMASK) != 0) { // return convertToParenthesizedExpression(expression); // } // if (expression instanceof org.aspectj.org.eclipse.jdt.internal.compiler.ast.Annotation) { // return convert((org.aspectj.org.eclipse.jdt.internal.compiler.ast.Annotation) expression); // } // if (expression instanceof org.aspectj.org.eclipse.jdt.internal.compiler.ast.CastExpression) { // return convert((org.aspectj.org.eclipse.jdt.internal.compiler.ast.CastExpression) expression); // } // // switch between all types of expression // if (expression instanceof org.aspectj.org.eclipse.jdt.internal.compiler.ast.ArrayAllocationExpression) { // return convert((org.aspectj.org.eclipse.jdt.internal.compiler.ast.ArrayAllocationExpression) expression); // } // if (expression instanceof org.aspectj.org.eclipse.jdt.internal.compiler.ast.QualifiedAllocationExpression) { // return convert((org.aspectj.org.eclipse.jdt.internal.compiler.ast.QualifiedAllocationExpression) expression); // } // if (expression instanceof org.aspectj.org.eclipse.jdt.internal.compiler.ast.AllocationExpression) { // return convert((org.aspectj.org.eclipse.jdt.internal.compiler.ast.AllocationExpression) expression); // } // if (expression instanceof org.aspectj.org.eclipse.jdt.internal.compiler.ast.ArrayInitializer) { // return convert((org.aspectj.org.eclipse.jdt.internal.compiler.ast.ArrayInitializer) expression); // } // if (expression instanceof org.aspectj.org.eclipse.jdt.internal.compiler.ast.PrefixExpression) { // return convert((org.aspectj.org.eclipse.jdt.internal.compiler.ast.PrefixExpression) expression); // } // if (expression instanceof org.aspectj.org.eclipse.jdt.internal.compiler.ast.PostfixExpression) { // return convert((org.aspectj.org.eclipse.jdt.internal.compiler.ast.PostfixExpression) expression); // } // if (expression instanceof org.aspectj.org.eclipse.jdt.internal.compiler.ast.CompoundAssignment) { // return convert((org.aspectj.org.eclipse.jdt.internal.compiler.ast.CompoundAssignment) expression); // } // if (expression instanceof org.aspectj.org.eclipse.jdt.internal.compiler.ast.Assignment) { // return convert((org.aspectj.org.eclipse.jdt.internal.compiler.ast.Assignment) expression); // } // if (expression instanceof org.aspectj.org.eclipse.jdt.internal.compiler.ast.ClassLiteralAccess) { // return convert((org.aspectj.org.eclipse.jdt.internal.compiler.ast.ClassLiteralAccess) expression); // } // if (expression instanceof org.aspectj.org.eclipse.jdt.internal.compiler.ast.FalseLiteral) { // return convert((org.aspectj.org.eclipse.jdt.internal.compiler.ast.FalseLiteral) expression); // } // if (expression instanceof org.aspectj.org.eclipse.jdt.internal.compiler.ast.TrueLiteral) { // return convert((org.aspectj.org.eclipse.jdt.internal.compiler.ast.TrueLiteral) expression); // } // if (expression instanceof org.aspectj.org.eclipse.jdt.internal.compiler.ast.NullLiteral) { // return convert((org.aspectj.org.eclipse.jdt.internal.compiler.ast.NullLiteral) expression); // } // if (expression instanceof org.aspectj.org.eclipse.jdt.internal.compiler.ast.CharLiteral) { // return convert((org.aspectj.org.eclipse.jdt.internal.compiler.ast.CharLiteral) expression); // } // if (expression instanceof org.aspectj.org.eclipse.jdt.internal.compiler.ast.DoubleLiteral) { // return convert((org.aspectj.org.eclipse.jdt.internal.compiler.ast.DoubleLiteral) expression); // } // if (expression instanceof org.aspectj.org.eclipse.jdt.internal.compiler.ast.FloatLiteral) { // return convert((org.aspectj.org.eclipse.jdt.internal.compiler.ast.FloatLiteral) expression); // } // if (expression instanceof org.aspectj.org.eclipse.jdt.internal.compiler.ast.IntLiteralMinValue) { // return convert((org.aspectj.org.eclipse.jdt.internal.compiler.ast.IntLiteralMinValue) expression); // } // if (expression instanceof org.aspectj.org.eclipse.jdt.internal.compiler.ast.IntLiteral) { // return convert((org.aspectj.org.eclipse.jdt.internal.compiler.ast.IntLiteral) expression); // } // if (expression instanceof org.aspectj.org.eclipse.jdt.internal.compiler.ast.LongLiteralMinValue) { // return convert((org.aspectj.org.eclipse.jdt.internal.compiler.ast.LongLiteralMinValue) expression); // } // if (expression instanceof org.aspectj.org.eclipse.jdt.internal.compiler.ast.LongLiteral) { // return convert((org.aspectj.org.eclipse.jdt.internal.compiler.ast.LongLiteral) expression); // } // if (expression instanceof StringLiteralConcatenation) { // return convert((StringLiteralConcatenation) expression); // } // if (expression instanceof org.aspectj.org.eclipse.jdt.internal.compiler.ast.ExtendedStringLiteral) { // return convert((org.aspectj.org.eclipse.jdt.internal.compiler.ast.ExtendedStringLiteral) expression); // } // if (expression instanceof org.aspectj.org.eclipse.jdt.internal.compiler.ast.StringLiteral) { // return convert((org.aspectj.org.eclipse.jdt.internal.compiler.ast.StringLiteral) expression); // } // if (expression instanceof org.aspectj.org.eclipse.jdt.internal.compiler.ast.AND_AND_Expression) { // return convert((org.aspectj.org.eclipse.jdt.internal.compiler.ast.AND_AND_Expression) expression); // } // if (expression instanceof org.aspectj.org.eclipse.jdt.internal.compiler.ast.OR_OR_Expression) { // return convert((org.aspectj.org.eclipse.jdt.internal.compiler.ast.OR_OR_Expression) expression); // } // if (expression instanceof org.aspectj.org.eclipse.jdt.internal.compiler.ast.EqualExpression) { // return convert((org.aspectj.org.eclipse.jdt.internal.compiler.ast.EqualExpression) expression); // } // if (expression instanceof org.aspectj.org.eclipse.jdt.internal.compiler.ast.BinaryExpression) { // return convert((org.aspectj.org.eclipse.jdt.internal.compiler.ast.BinaryExpression) expression); // } // if (expression instanceof org.aspectj.org.eclipse.jdt.internal.compiler.ast.InstanceOfExpression) { // return convert((org.aspectj.org.eclipse.jdt.internal.compiler.ast.InstanceOfExpression) expression); // } // if (expression instanceof org.aspectj.org.eclipse.jdt.internal.compiler.ast.UnaryExpression) { // return convert((org.aspectj.org.eclipse.jdt.internal.compiler.ast.UnaryExpression) expression); // } // if (expression instanceof org.aspectj.org.eclipse.jdt.internal.compiler.ast.ConditionalExpression) { // return convert((org.aspectj.org.eclipse.jdt.internal.compiler.ast.ConditionalExpression) expression); // } // if (expression instanceof org.aspectj.org.eclipse.jdt.internal.compiler.ast.MessageSend) { // return convert((org.aspectj.org.eclipse.jdt.internal.compiler.ast.MessageSend) expression); // } // if (expression instanceof org.aspectj.org.eclipse.jdt.internal.compiler.ast.Reference) { // return convert((org.aspectj.org.eclipse.jdt.internal.compiler.ast.Reference) expression); // } // if (expression instanceof org.aspectj.org.eclipse.jdt.internal.compiler.ast.TypeReference) { // return convert((org.aspectj.org.eclipse.jdt.internal.compiler.ast.TypeReference) expression); // } // return null; // } public StringLiteral convert(org.aspectj.org.eclipse.jdt.internal.compiler.ast.ExtendedStringLiteral expression) { expression.computeConstant(); StringLiteral literal = new StringLiteral(this.ast); if (this.resolveBindings) { this.recordNodes(literal, expression); } literal.setLiteralValue(expression.constant.stringValue()); literal.setSourceRange(expression.sourceStart, expression.sourceEnd - expression.sourceStart + 1); return literal; } public BooleanLiteral convert(org.aspectj.org.eclipse.jdt.internal.compiler.ast.FalseLiteral expression) { final BooleanLiteral literal = new BooleanLiteral(this.ast); literal.setBooleanValue(false); if (this.resolveBindings) { this.recordNodes(literal, expression); } literal.setSourceRange(expression.sourceStart, expression.sourceEnd - expression.sourceStart + 1); return literal; } public Expression convert(org.aspectj.org.eclipse.jdt.internal.compiler.ast.FieldReference reference) { if (reference.receiver.isSuper()) { final SuperFieldAccess superFieldAccess = new SuperFieldAccess(this.ast); if (this.resolveBindings) { recordNodes(superFieldAccess, reference); } if (reference.receiver instanceof org.aspectj.org.eclipse.jdt.internal.compiler.ast.QualifiedSuperReference) { Name qualifier = convert((org.aspectj.org.eclipse.jdt.internal.compiler.ast.QualifiedSuperReference) reference.receiver); superFieldAccess.setQualifier(qualifier); if (this.resolveBindings) { recordNodes(qualifier, reference.receiver); } } final SimpleName simpleName = new SimpleName(this.ast); simpleName.internalSetIdentifier(new String(reference.token)); int sourceStart = (int)(reference.nameSourcePosition>>>32); int length = (int)(reference.nameSourcePosition & 0xFFFFFFFF) - sourceStart + 1; simpleName.setSourceRange(sourceStart, length); superFieldAccess.setName(simpleName); if (this.resolveBindings) { recordNodes(simpleName, reference); } superFieldAccess.setSourceRange(reference.receiver.sourceStart, reference.sourceEnd - reference.receiver.sourceStart + 1); return superFieldAccess; } else { final FieldAccess fieldAccess = new FieldAccess(this.ast); if (this.resolveBindings) { recordNodes(fieldAccess, reference); } Expression receiver = super.convert(reference.receiver); fieldAccess.setExpression(receiver); final SimpleName simpleName = new SimpleName(this.ast); simpleName.internalSetIdentifier(new String(reference.token)); int sourceStart = (int)(reference.nameSourcePosition>>>32); int length = (int)(reference.nameSourcePosition & 0xFFFFFFFF) - sourceStart + 1; simpleName.setSourceRange(sourceStart, length); fieldAccess.setName(simpleName); if (this.resolveBindings) { recordNodes(simpleName, reference); } fieldAccess.setSourceRange(receiver.getStartPosition(), reference.sourceEnd - receiver.getStartPosition() + 1); return fieldAccess; } } public NumberLiteral convert(org.aspectj.org.eclipse.jdt.internal.compiler.ast.FloatLiteral expression) { int length = expression.sourceEnd - expression.sourceStart + 1; int sourceStart = expression.sourceStart; NumberLiteral literal = new NumberLiteral(this.ast); literal.internalSetToken(new String(this.compilationUnitSource, sourceStart, length)); if (this.resolveBindings) { this.recordNodes(literal, expression); } literal.setSourceRange(sourceStart, length); removeLeadingAndTrailingCommentsFromLiteral(literal); return literal; } public Statement convert(ForeachStatement statement) { switch(this.ast.apiLevel) { case AST.JLS2_INTERNAL : return createFakeEmptyStatement(statement); case AST.JLS3 : EnhancedForStatement enhancedForStatement = new EnhancedForStatement(this.ast); enhancedForStatement.setParameter(convertToSingleVariableDeclaration(statement.elementVariable)); enhancedForStatement.setExpression(super.convert(statement.collection)); enhancedForStatement.setBody(convert(statement.action)); int start = statement.sourceStart; int end = statement.sourceEnd; enhancedForStatement.setSourceRange(start, end - start + 1); return enhancedForStatement; default: return createFakeEmptyStatement(statement); } } public ForStatement convert(org.aspectj.org.eclipse.jdt.internal.compiler.ast.ForStatement statement) { ForStatement forStatement = new ForStatement(this.ast); forStatement.setSourceRange(statement.sourceStart, statement.sourceEnd - statement.sourceStart + 1); org.aspectj.org.eclipse.jdt.internal.compiler.ast.Statement[] initializations = statement.initializations; if (initializations != null) { // we know that we have at least one initialization if (initializations[0] instanceof org.aspectj.org.eclipse.jdt.internal.compiler.ast.LocalDeclaration) { VariableDeclarationExpression variableDeclarationExpression = convertToVariableDeclarationExpression((org.aspectj.org.eclipse.jdt.internal.compiler.ast.LocalDeclaration) initializations[0]); int initializationsLength = initializations.length; for (int i = 1; i < initializationsLength; i++) { variableDeclarationExpression.fragments().add(convertToVariableDeclarationFragment((org.aspectj.org.eclipse.jdt.internal.compiler.ast.LocalDeclaration)initializations[i])); } if (initializationsLength != 1) { int start = variableDeclarationExpression.getStartPosition(); int end = ((org.aspectj.org.eclipse.jdt.internal.compiler.ast.LocalDeclaration) initializations[initializationsLength - 1]).declarationSourceEnd; variableDeclarationExpression.setSourceRange(start, end - start + 1); } forStatement.initializers().add(variableDeclarationExpression); } else { int initializationsLength = initializations.length; for (int i = 0; i < initializationsLength; i++) { Expression initializer = convertToExpression(initializations[i]); if (initializer != null) { forStatement.initializers().add(initializer); } else { forStatement.setFlags(forStatement.getFlags() | ASTNode.MALFORMED); } } } } if (statement.condition != null) { forStatement.setExpression(super.convert(statement.condition)); } org.aspectj.org.eclipse.jdt.internal.compiler.ast.Statement[] increments = statement.increments; if (increments != null) { int incrementsLength = increments.length; for (int i = 0; i < incrementsLength; i++) { forStatement.updaters().add(convertToExpression(increments[i])); } } forStatement.setBody(convert(statement.action)); return forStatement; } public IfStatement convert(org.aspectj.org.eclipse.jdt.internal.compiler.ast.IfStatement statement) { IfStatement ifStatement = new IfStatement(this.ast); ifStatement.setSourceRange(statement.sourceStart, statement.sourceEnd - statement.sourceStart + 1); ifStatement.setExpression(super.convert(statement.condition)); ifStatement.setThenStatement(convert(statement.thenStatement)); if (statement.elseStatement != null) { ifStatement.setElseStatement(convert(statement.elseStatement)); } return ifStatement; } public InstanceofExpression convert(org.aspectj.org.eclipse.jdt.internal.compiler.ast.InstanceOfExpression expression) { InstanceofExpression instanceOfExpression = new InstanceofExpression(this.ast); if (this.resolveBindings) { recordNodes(instanceOfExpression, expression); } Expression leftExpression = super.convert(expression.expression); instanceOfExpression.setLeftOperand(leftExpression); instanceOfExpression.setRightOperand(convertType(expression.type)); int startPosition = leftExpression.getStartPosition(); instanceOfExpression.setSourceRange(startPosition, expression.sourceEnd - startPosition + 1); return instanceOfExpression; } public NumberLiteral convert(org.aspectj.org.eclipse.jdt.internal.compiler.ast.IntLiteral expression) { int length = expression.sourceEnd - expression.sourceStart + 1; int sourceStart = expression.sourceStart; final NumberLiteral literal = new NumberLiteral(this.ast); literal.internalSetToken(new String(this.compilationUnitSource, sourceStart, length)); if (this.resolveBindings) { this.recordNodes(literal, expression); } literal.setSourceRange(sourceStart, length); removeLeadingAndTrailingCommentsFromLiteral(literal); return literal; } public NumberLiteral convert(org.aspectj.org.eclipse.jdt.internal.compiler.ast.IntLiteralMinValue expression) { int length = expression.sourceEnd - expression.sourceStart + 1; int sourceStart = expression.sourceStart; NumberLiteral literal = new NumberLiteral(this.ast); literal.internalSetToken(new String(this.compilationUnitSource, sourceStart, length)); if (this.resolveBindings) { this.recordNodes(literal, expression); } literal.setSourceRange(sourceStart, length); removeLeadingAndTrailingCommentsFromLiteral(literal); return literal; } public void convert(org.aspectj.org.eclipse.jdt.internal.compiler.ast.Javadoc javadoc, BodyDeclaration bodyDeclaration) { if (bodyDeclaration.getJavadoc() == null) { if (javadoc != null) { if (this.commentMapper == null || !this.commentMapper.hasSameTable(this.commentsTable)) { this.commentMapper = new DefaultCommentMapper(this.commentsTable); } Comment comment = this.commentMapper.getComment(javadoc.sourceStart); if (comment != null && comment.isDocComment() && comment.getParent() == null) { Javadoc docComment = (Javadoc) comment; if (this.resolveBindings) { recordNodes(docComment, javadoc); // resolve member and method references binding Iterator tags = docComment.tags().listIterator(); while (tags.hasNext()) { recordNodes(javadoc, (TagElement) tags.next()); } } bodyDeclaration.setJavadoc(docComment); } } } } public void convert(org.aspectj.org.eclipse.jdt.internal.compiler.ast.Javadoc javadoc, PackageDeclaration packageDeclaration) { if (ast.apiLevel == AST.JLS3 && packageDeclaration.getJavadoc() == null) { if (javadoc != null) { if (this.commentMapper == null || !this.commentMapper.hasSameTable(this.commentsTable)) { this.commentMapper = new DefaultCommentMapper(this.commentsTable); } Comment comment = this.commentMapper.getComment(javadoc.sourceStart); if (comment != null && comment.isDocComment() && comment.getParent() == null) { Javadoc docComment = (Javadoc) comment; if (this.resolveBindings) { recordNodes(docComment, javadoc); // resolve member and method references binding Iterator tags = docComment.tags().listIterator(); while (tags.hasNext()) { recordNodes(javadoc, (TagElement) tags.next()); } } packageDeclaration.setJavadoc(docComment); } } } } public LabeledStatement convert(org.aspectj.org.eclipse.jdt.internal.compiler.ast.LabeledStatement statement) { LabeledStatement labeledStatement = new LabeledStatement(this.ast); labeledStatement.setSourceRange(statement.sourceStart, statement.sourceEnd - statement.sourceStart + 1); org.aspectj.org.eclipse.jdt.internal.compiler.ast.Statement body = statement.statement; labeledStatement.setBody(convert(body)); final SimpleName name = new SimpleName(this.ast); name.internalSetIdentifier(new String(statement.label)); retrieveIdentifierAndSetPositions(statement.sourceStart, statement.sourceEnd, name); labeledStatement.setLabel(name); return labeledStatement; } public InfixExpression convert(StringLiteralConcatenation expression) { expression.computeConstant(); final InfixExpression infixExpression = new InfixExpression(this.ast); infixExpression.setOperator(InfixExpression.Operator.PLUS); org.aspectj.org.eclipse.jdt.internal.compiler.ast.Expression[] stringLiterals = expression.literals; infixExpression.setLeftOperand(super.convert(stringLiterals[0])); infixExpression.setRightOperand(super.convert(stringLiterals[1])); for (int i = 2; i < expression.counter; i++) { infixExpression.extendedOperands().add(super.convert(stringLiterals[i])); } if (this.resolveBindings) { this.recordNodes(infixExpression, expression); } infixExpression.setSourceRange(expression.sourceStart, expression.sourceEnd - expression.sourceStart + 1); return infixExpression; } public NormalAnnotation convert(org.aspectj.org.eclipse.jdt.internal.compiler.ast.NormalAnnotation annotation) { final NormalAnnotation normalAnnotation = new NormalAnnotation(this.ast); setTypeNameForAnnotation(annotation, normalAnnotation); org.aspectj.org.eclipse.jdt.internal.compiler.ast.MemberValuePair[] memberValuePairs = annotation.memberValuePairs; if (memberValuePairs != null) { for (int i = 0, max = memberValuePairs.length; i < max; i++) { normalAnnotation.values().add(convert(memberValuePairs[i])); } } int start = annotation.sourceStart; int end = annotation.declarationSourceEnd; normalAnnotation.setSourceRange(start, end - start + 1); if (this.resolveBindings) { recordNodes(normalAnnotation, annotation); } return normalAnnotation; } public NullLiteral convert(org.aspectj.org.eclipse.jdt.internal.compiler.ast.NullLiteral expression) { final NullLiteral literal = new NullLiteral(this.ast); if (this.resolveBindings) { this.recordNodes(literal, expression); } literal.setSourceRange(expression.sourceStart, expression.sourceEnd - expression.sourceStart + 1); return literal; } public Expression convert(org.aspectj.org.eclipse.jdt.internal.compiler.ast.OR_OR_Expression expression) { final InfixExpression infixExpression = new InfixExpression(this.ast); if (this.resolveBindings) { recordNodes(infixExpression, expression); } Expression leftExpression = super.convert(expression.left); infixExpression.setLeftOperand(leftExpression); infixExpression.setRightOperand(super.convert(expression.right)); infixExpression.setOperator(InfixExpression.Operator.CONDITIONAL_OR); int sourceStart = leftExpression.getStartPosition(); infixExpression.setSourceRange(sourceStart, expression.sourceEnd - sourceStart + 1); return infixExpression; } public PostfixExpression convert(org.aspectj.org.eclipse.jdt.internal.compiler.ast.PostfixExpression expression) { final PostfixExpression postfixExpression = new PostfixExpression(this.ast); if (this.resolveBindings) { recordNodes(postfixExpression, expression); } postfixExpression.setSourceRange(expression.sourceStart, expression.sourceEnd - expression.sourceStart + 1); postfixExpression.setOperand(super.convert(expression.lhs)); switch (expression.operator) { case org.aspectj.org.eclipse.jdt.internal.compiler.ast.OperatorIds.PLUS : postfixExpression.setOperator(PostfixExpression.Operator.INCREMENT); break; case org.aspectj.org.eclipse.jdt.internal.compiler.ast.OperatorIds.MINUS : postfixExpression.setOperator(PostfixExpression.Operator.DECREMENT); break; } return postfixExpression; } public PrefixExpression convert(org.aspectj.org.eclipse.jdt.internal.compiler.ast.PrefixExpression expression) { final PrefixExpression prefixExpression = new PrefixExpression(this.ast); if (this.resolveBindings) { recordNodes(prefixExpression, expression); } prefixExpression.setSourceRange(expression.sourceStart, expression.sourceEnd - expression.sourceStart + 1); prefixExpression.setOperand(super.convert(expression.lhs)); switch (expression.operator) { case org.aspectj.org.eclipse.jdt.internal.compiler.ast.OperatorIds.PLUS : prefixExpression.setOperator(PrefixExpression.Operator.INCREMENT); break; case org.aspectj.org.eclipse.jdt.internal.compiler.ast.OperatorIds.MINUS : prefixExpression.setOperator(PrefixExpression.Operator.DECREMENT); break; } return prefixExpression; } public Expression convert(org.aspectj.org.eclipse.jdt.internal.compiler.ast.QualifiedAllocationExpression allocation) { final ClassInstanceCreation classInstanceCreation = new ClassInstanceCreation(this.ast); if (allocation.enclosingInstance != null) { classInstanceCreation.setExpression(super.convert(allocation.enclosingInstance)); } switch(this.ast.apiLevel) { case AST.JLS2_INTERNAL : classInstanceCreation.internalSetName(convert(allocation.type)); break; case AST.JLS3 : classInstanceCreation.setType(convertType(allocation.type)); } org.aspectj.org.eclipse.jdt.internal.compiler.ast.Expression[] arguments = allocation.arguments; if (arguments != null) { int length = arguments.length; for (int i = 0; i < length; i++) { Expression argument = super.convert(arguments[i]); if (this.resolveBindings) { recordNodes(argument, arguments[i]); } classInstanceCreation.arguments().add(argument); } } if (allocation.typeArguments != null) { switch(this.ast.apiLevel) { case AST.JLS2_INTERNAL : classInstanceCreation.setFlags(classInstanceCreation.getFlags() | ASTNode.MALFORMED); break; case AST.JLS3 : for (int i = 0, max = allocation.typeArguments.length; i < max; i++) { classInstanceCreation.typeArguments().add(convertType(allocation.typeArguments[i])); } } } if (allocation.anonymousType != null) { int declarationSourceStart = allocation.sourceStart; classInstanceCreation.setSourceRange(declarationSourceStart, allocation.anonymousType.bodyEnd - declarationSourceStart + 1); final AnonymousClassDeclaration anonymousClassDeclaration = new AnonymousClassDeclaration(this.ast); int start = retrieveStartBlockPosition(allocation.anonymousType.sourceEnd, allocation.anonymousType.bodyEnd); anonymousClassDeclaration.setSourceRange(start, allocation.anonymousType.bodyEnd - start + 1); classInstanceCreation.setAnonymousClassDeclaration(anonymousClassDeclaration); buildBodyDeclarations(allocation.anonymousType, anonymousClassDeclaration); if (this.resolveBindings) { recordNodes(classInstanceCreation, allocation.anonymousType); recordNodes(anonymousClassDeclaration, allocation.anonymousType); anonymousClassDeclaration.resolveBinding(); } return classInstanceCreation; } else { final int start = allocation.sourceStart; classInstanceCreation.setSourceRange(start, allocation.sourceEnd - start + 1); if (this.resolveBindings) { recordNodes(classInstanceCreation, allocation); } removeTrailingCommentFromExpressionEndingWithAParen(classInstanceCreation); return classInstanceCreation; } } public Name convert(org.aspectj.org.eclipse.jdt.internal.compiler.ast.QualifiedNameReference nameReference) { return setQualifiedNameNameAndSourceRanges(nameReference.tokens, nameReference.sourcePositions, nameReference); } public Name convert(org.aspectj.org.eclipse.jdt.internal.compiler.ast.QualifiedSuperReference reference) { return convert(reference.qualification); } public ThisExpression convert(org.aspectj.org.eclipse.jdt.internal.compiler.ast.QualifiedThisReference reference) { final ThisExpression thisExpression = new ThisExpression(this.ast); thisExpression.setSourceRange(reference.sourceStart, reference.sourceEnd - reference.sourceStart + 1); thisExpression.setQualifier(convert(reference.qualification)); if (this.resolveBindings) { recordNodes(thisExpression, reference); recordPendingThisExpressionScopeResolution(thisExpression); } return thisExpression; } public Expression convert(org.aspectj.org.eclipse.jdt.internal.compiler.ast.Reference reference) { if (reference instanceof org.aspectj.org.eclipse.jdt.internal.compiler.ast.NameReference) { return super.convert((org.aspectj.org.eclipse.jdt.internal.compiler.ast.NameReference) reference); } if (reference instanceof org.aspectj.org.eclipse.jdt.internal.compiler.ast.ThisReference) { return convert((org.aspectj.org.eclipse.jdt.internal.compiler.ast.ThisReference) reference); } if (reference instanceof org.aspectj.org.eclipse.jdt.internal.compiler.ast.ArrayReference) { return super.convert((org.aspectj.org.eclipse.jdt.internal.compiler.ast.ArrayReference) reference); } if (reference instanceof org.aspectj.org.eclipse.jdt.internal.compiler.ast.FieldReference) { return convert((org.aspectj.org.eclipse.jdt.internal.compiler.ast.FieldReference) reference); } return null; // cannot be reached } public ReturnStatement convert(org.aspectj.org.eclipse.jdt.internal.compiler.ast.ReturnStatement statement) { final ReturnStatement returnStatement = new ReturnStatement(this.ast); returnStatement.setSourceRange(statement.sourceStart, statement.sourceEnd - statement.sourceStart + 1); if (statement.expression != null) { returnStatement.setExpression(super.convert(statement.expression)); } retrieveSemiColonPosition(returnStatement); return returnStatement; } public SingleMemberAnnotation convert(org.aspectj.org.eclipse.jdt.internal.compiler.ast.SingleMemberAnnotation annotation) { final SingleMemberAnnotation singleMemberAnnotation = new SingleMemberAnnotation(this.ast); setTypeNameForAnnotation(annotation, singleMemberAnnotation); singleMemberAnnotation.setValue(super.convert(annotation.memberValue)); int start = annotation.sourceStart; int end = annotation.declarationSourceEnd; singleMemberAnnotation.setSourceRange(start, end - start + 1); if (this.resolveBindings) { recordNodes(singleMemberAnnotation, annotation); } return singleMemberAnnotation; } public SimpleName convert(org.aspectj.org.eclipse.jdt.internal.compiler.ast.SingleNameReference nameReference) { final SimpleName name = new SimpleName(this.ast); name.internalSetIdentifier(new String(nameReference.token)); if (this.resolveBindings) { recordNodes(name, nameReference); } name.setSourceRange(nameReference.sourceStart, nameReference.sourceEnd - nameReference.sourceStart + 1); return name; } public Statement convert(org.aspectj.org.eclipse.jdt.internal.compiler.ast.Statement statement) { if (statement instanceof ForeachStatement) { return convert((ForeachStatement) statement); } if (statement instanceof org.aspectj.org.eclipse.jdt.internal.compiler.ast.LocalDeclaration) { return convertToVariableDeclarationStatement((org.aspectj.org.eclipse.jdt.internal.compiler.ast.LocalDeclaration)statement); } if (statement instanceof org.aspectj.org.eclipse.jdt.internal.compiler.ast.AssertStatement) { return super.convert((org.aspectj.org.eclipse.jdt.internal.compiler.ast.AssertStatement) statement); } if (statement instanceof org.aspectj.org.eclipse.jdt.internal.compiler.ast.Block) { return convert((org.aspectj.org.eclipse.jdt.internal.compiler.ast.Block) statement); } if (statement instanceof org.aspectj.org.eclipse.jdt.internal.compiler.ast.BreakStatement) { return super.convert((org.aspectj.org.eclipse.jdt.internal.compiler.ast.BreakStatement) statement); } if (statement instanceof org.aspectj.org.eclipse.jdt.internal.compiler.ast.ContinueStatement) { return super.convert((org.aspectj.org.eclipse.jdt.internal.compiler.ast.ContinueStatement) statement); } if (statement instanceof org.aspectj.org.eclipse.jdt.internal.compiler.ast.CaseStatement) { return super.convert((org.aspectj.org.eclipse.jdt.internal.compiler.ast.CaseStatement) statement); } if (statement instanceof org.aspectj.org.eclipse.jdt.internal.compiler.ast.DoStatement) { return super.convert((org.aspectj.org.eclipse.jdt.internal.compiler.ast.DoStatement) statement); } if (statement instanceof org.aspectj.org.eclipse.jdt.internal.compiler.ast.EmptyStatement) { return super.convert((org.aspectj.org.eclipse.jdt.internal.compiler.ast.EmptyStatement) statement); } if (statement instanceof org.aspectj.org.eclipse.jdt.internal.compiler.ast.ExplicitConstructorCall) { return super.convert((org.aspectj.org.eclipse.jdt.internal.compiler.ast.ExplicitConstructorCall) statement); } if (statement instanceof org.aspectj.org.eclipse.jdt.internal.compiler.ast.ForStatement) { return convert((org.aspectj.org.eclipse.jdt.internal.compiler.ast.ForStatement) statement); } if (statement instanceof org.aspectj.org.eclipse.jdt.internal.compiler.ast.IfStatement) { return convert((org.aspectj.org.eclipse.jdt.internal.compiler.ast.IfStatement) statement); } if (statement instanceof org.aspectj.org.eclipse.jdt.internal.compiler.ast.LabeledStatement) { return convert((org.aspectj.org.eclipse.jdt.internal.compiler.ast.LabeledStatement) statement); } if (statement instanceof org.aspectj.org.eclipse.jdt.internal.compiler.ast.ReturnStatement) { return convert((org.aspectj.org.eclipse.jdt.internal.compiler.ast.ReturnStatement) statement); } if (statement instanceof org.aspectj.org.eclipse.jdt.internal.compiler.ast.SwitchStatement) { return convert((org.aspectj.org.eclipse.jdt.internal.compiler.ast.SwitchStatement) statement); } if (statement instanceof org.aspectj.org.eclipse.jdt.internal.compiler.ast.SynchronizedStatement) { return convert((org.aspectj.org.eclipse.jdt.internal.compiler.ast.SynchronizedStatement) statement); } if (statement instanceof org.aspectj.org.eclipse.jdt.internal.compiler.ast.ThrowStatement) { return convert((org.aspectj.org.eclipse.jdt.internal.compiler.ast.ThrowStatement) statement); } if (statement instanceof org.aspectj.org.eclipse.jdt.internal.compiler.ast.TryStatement) { return convert((org.aspectj.org.eclipse.jdt.internal.compiler.ast.TryStatement) statement); } if (statement instanceof org.aspectj.org.eclipse.jdt.internal.compiler.ast.TypeDeclaration) { ASTNode result = convert((org.aspectj.org.eclipse.jdt.internal.compiler.ast.TypeDeclaration) statement); if (result == null) { return createFakeEmptyStatement(statement); } switch(result.getNodeType()) { case ASTNode.ENUM_DECLARATION: switch(this.ast.apiLevel) { case AST.JLS2_INTERNAL : return createFakeEmptyStatement(statement); case AST.JLS3 : final TypeDeclarationStatement typeDeclarationStatement = new TypeDeclarationStatement(this.ast); typeDeclarationStatement.setDeclaration((EnumDeclaration) result); AbstractTypeDeclaration typeDecl = typeDeclarationStatement.getDeclaration(); typeDeclarationStatement.setSourceRange(typeDecl.getStartPosition(), typeDecl.getLength()); return typeDeclarationStatement; } break; case ASTNode.ANNOTATION_TYPE_DECLARATION : switch(this.ast.apiLevel) { case AST.JLS2_INTERNAL : return createFakeEmptyStatement(statement); case AST.JLS3 : TypeDeclarationStatement typeDeclarationStatement = new TypeDeclarationStatement(this.ast); typeDeclarationStatement.setDeclaration((AnnotationTypeDeclaration) result); AbstractTypeDeclaration typeDecl = typeDeclarationStatement.getDeclaration(); typeDeclarationStatement.setSourceRange(typeDecl.getStartPosition(), typeDecl.getLength()); return typeDeclarationStatement; } break; default: TypeDeclaration typeDeclaration = (TypeDeclaration) result; if (typeDeclaration == null) { return createFakeEmptyStatement(statement); } else { TypeDeclarationStatement typeDeclarationStatement = new TypeDeclarationStatement(this.ast); typeDeclarationStatement.setDeclaration(typeDeclaration); switch(this.ast.apiLevel) { case AST.JLS2_INTERNAL : TypeDeclaration typeDecl = typeDeclarationStatement.internalGetTypeDeclaration(); typeDeclarationStatement.setSourceRange(typeDecl.getStartPosition(), typeDecl.getLength()); break; case AST.JLS3 : AbstractTypeDeclaration typeDeclAST3 = typeDeclarationStatement.getDeclaration(); typeDeclarationStatement.setSourceRange(typeDeclAST3.getStartPosition(), typeDeclAST3.getLength()); break; } return typeDeclarationStatement; } } } if (statement instanceof org.aspectj.org.eclipse.jdt.internal.compiler.ast.WhileStatement) { return super.convert((org.aspectj.org.eclipse.jdt.internal.compiler.ast.WhileStatement) statement); } if (statement instanceof org.aspectj.org.eclipse.jdt.internal.compiler.ast.Expression) { final Expression expr = super.convert((org.aspectj.org.eclipse.jdt.internal.compiler.ast.Expression) statement); final ExpressionStatement stmt = new ExpressionStatement(this.ast); stmt.setExpression(expr); stmt.setSourceRange(expr.getStartPosition(), expr.getLength()); retrieveSemiColonPosition(stmt); return stmt; } return createFakeEmptyStatement(statement); } public Expression convert(org.aspectj.org.eclipse.jdt.internal.compiler.ast.StringLiteral expression) { if (expression instanceof StringLiteralConcatenation) { return convert((StringLiteralConcatenation) expression); } int length = expression.sourceEnd - expression.sourceStart + 1; int sourceStart = expression.sourceStart; StringLiteral literal = new StringLiteral(this.ast); if (this.resolveBindings) { this.recordNodes(literal, expression); } literal.internalSetEscapedValue(new String(this.compilationUnitSource, sourceStart, length)); literal.setSourceRange(expression.sourceStart, expression.sourceEnd - expression.sourceStart + 1); return literal; } public SwitchStatement convert(org.aspectj.org.eclipse.jdt.internal.compiler.ast.SwitchStatement statement) { SwitchStatement switchStatement = new SwitchStatement(this.ast); switchStatement.setSourceRange(statement.sourceStart, statement.sourceEnd - statement.sourceStart + 1); switchStatement.setExpression(super.convert(statement.expression)); org.aspectj.org.eclipse.jdt.internal.compiler.ast.Statement[] statements = statement.statements; if (statements != null) { int statementsLength = statements.length; for (int i = 0; i < statementsLength; i++) { switchStatement.statements().add(convert(statements[i])); } } return switchStatement; } public SynchronizedStatement convert(org.aspectj.org.eclipse.jdt.internal.compiler.ast.SynchronizedStatement statement) { SynchronizedStatement synchronizedStatement = new SynchronizedStatement(this.ast); synchronizedStatement.setSourceRange(statement.sourceStart, statement.sourceEnd - statement.sourceStart + 1); synchronizedStatement.setBody(convert(statement.block)); synchronizedStatement.setExpression(super.convert(statement.expression)); return synchronizedStatement; } public Expression convert(org.aspectj.org.eclipse.jdt.internal.compiler.ast.ThisReference reference) { if (reference.isImplicitThis()) { // There is no source associated with an implicit this return null; } else if (reference instanceof org.aspectj.org.eclipse.jdt.internal.compiler.ast.QualifiedSuperReference) { return convert((org.aspectj.org.eclipse.jdt.internal.compiler.ast.QualifiedSuperReference) reference); } else if (reference instanceof org.aspectj.org.eclipse.jdt.internal.compiler.ast.QualifiedThisReference) { return convert((org.aspectj.org.eclipse.jdt.internal.compiler.ast.QualifiedThisReference) reference); } else { ThisExpression thisExpression = new ThisExpression(this.ast); thisExpression.setSourceRange(reference.sourceStart, reference.sourceEnd - reference.sourceStart + 1); if (this.resolveBindings) { recordNodes(thisExpression, reference); recordPendingThisExpressionScopeResolution(thisExpression); } return thisExpression; } } public ThrowStatement convert(org.aspectj.org.eclipse.jdt.internal.compiler.ast.ThrowStatement statement) { final ThrowStatement throwStatement = new ThrowStatement(this.ast); throwStatement.setSourceRange(statement.sourceStart, statement.sourceEnd - statement.sourceStart + 1); throwStatement.setExpression(super.convert(statement.exception)); retrieveSemiColonPosition(throwStatement); return throwStatement; } public BooleanLiteral convert(org.aspectj.org.eclipse.jdt.internal.compiler.ast.TrueLiteral expression) { final BooleanLiteral literal = new BooleanLiteral(this.ast); literal.setBooleanValue(true); if (this.resolveBindings) { this.recordNodes(literal, expression); } literal.setSourceRange(expression.sourceStart, expression.sourceEnd - expression.sourceStart + 1); return literal; } public TryStatement convert(org.aspectj.org.eclipse.jdt.internal.compiler.ast.TryStatement statement) { final TryStatement tryStatement = new TryStatement(this.ast); tryStatement.setSourceRange(statement.sourceStart, statement.sourceEnd - statement.sourceStart + 1); tryStatement.setBody(convert(statement.tryBlock)); org.aspectj.org.eclipse.jdt.internal.compiler.ast.Argument[] catchArguments = statement.catchArguments; if (catchArguments != null) { int catchArgumentsLength = catchArguments.length; org.aspectj.org.eclipse.jdt.internal.compiler.ast.Block[] catchBlocks = statement.catchBlocks; int start = statement.tryBlock.sourceEnd; for (int i = 0; i < catchArgumentsLength; i++) { CatchClause catchClause = new CatchClause(this.ast); int catchClauseSourceStart = retrieveStartingCatchPosition(start, catchArguments[i].sourceStart); catchClause.setSourceRange(catchClauseSourceStart, catchBlocks[i].sourceEnd - catchClauseSourceStart + 1); catchClause.setBody(convert(catchBlocks[i])); catchClause.setException(convert(catchArguments[i])); tryStatement.catchClauses().add(catchClause); start = catchBlocks[i].sourceEnd; } } if (statement.finallyBlock != null) { tryStatement.setFinally(convert(statement.finallyBlock)); } return tryStatement; } public ASTNode convert(org.aspectj.org.eclipse.jdt.internal.compiler.ast.TypeDeclaration typeDeclaration) { switch (org.aspectj.org.eclipse.jdt.internal.compiler.ast.TypeDeclaration.kind(typeDeclaration.modifiers)) { case org.aspectj.org.eclipse.jdt.internal.compiler.ast.TypeDeclaration.ENUM_DECL : if (this.ast.apiLevel == AST.JLS2_INTERNAL) { return null; } else { return convertToEnumDeclaration(typeDeclaration); } case org.aspectj.org.eclipse.jdt.internal.compiler.ast.TypeDeclaration.ANNOTATION_TYPE_DECL : if (this.ast.apiLevel == AST.JLS2_INTERNAL) { return null; } else { return convertToAnnotationDeclaration(typeDeclaration); } } checkCanceled(); TypeDeclaration typeDecl = TypeDeclaration.getTypeDeclaration(this.ast); //////////////// ajh02: added if (typeDeclaration instanceof AspectDeclaration){ org.aspectj.weaver.patterns.PerClause perClause = ((AspectDeclaration)typeDeclaration).perClause; boolean isPrivileged = ((AspectDeclaration)typeDeclaration).isPrivileged; if (perClause == null){ typeDecl = new org.aspectj.org.eclipse.jdt.core.dom.AspectDeclaration(this.ast,null, isPrivileged); } else { typeDecl = new org.aspectj.org.eclipse.jdt.core.dom.AspectDeclaration(this.ast,convert(perClause), isPrivileged); } } /////////////////////////////// if (typeDeclaration.modifiersSourceStart != -1) { setModifiers(typeDecl, typeDeclaration); } typeDecl.setInterface(org.aspectj.org.eclipse.jdt.internal.compiler.ast.TypeDeclaration.kind(typeDeclaration.modifiers) == org.aspectj.org.eclipse.jdt.internal.compiler.ast.TypeDeclaration.INTERFACE_DECL); final SimpleName typeName = new SimpleName(this.ast); typeName.internalSetIdentifier(new String(typeDeclaration.name)); typeName.setSourceRange(typeDeclaration.sourceStart, typeDeclaration.sourceEnd - typeDeclaration.sourceStart + 1); typeDecl.setName(typeName); typeDecl.setSourceRange(typeDeclaration.declarationSourceStart, typeDeclaration.bodyEnd - typeDeclaration.declarationSourceStart + 1); // need to set the superclass and super interfaces here since we cannot distinguish them at // the type references level. if (typeDeclaration.superclass != null) { switch(this.ast.apiLevel) { case AST.JLS2_INTERNAL : typeDecl.internalSetSuperclass(convert(typeDeclaration.superclass)); break; case AST.JLS3 : typeDecl.setSuperclassType(convertType(typeDeclaration.superclass)); break; } } org.aspectj.org.eclipse.jdt.internal.compiler.ast.TypeReference[] superInterfaces = typeDeclaration.superInterfaces; if (superInterfaces != null) { switch(this.ast.apiLevel) { case AST.JLS2_INTERNAL : for (int index = 0, length = superInterfaces.length; index < length; index++) { typeDecl.internalSuperInterfaces().add(convert(superInterfaces[index])); } break; case AST.JLS3 : for (int index = 0, length = superInterfaces.length; index < length; index++) { typeDecl.superInterfaceTypes().add(convertType(superInterfaces[index])); } } } org.aspectj.org.eclipse.jdt.internal.compiler.ast.TypeParameter[] typeParameters = typeDeclaration.typeParameters; if (typeParameters != null) { switch(this.ast.apiLevel) { case AST.JLS2_INTERNAL : typeDecl.setFlags(typeDecl.getFlags() | ASTNode.MALFORMED); break; case AST.JLS3 : for (int index = 0, length = typeParameters.length; index < length; index++) { typeDecl.typeParameters().add(convert(typeParameters[index])); } } } buildBodyDeclarations(typeDeclaration, typeDecl); if (this.resolveBindings) { recordNodes(typeDecl, typeDeclaration); recordNodes(typeName, typeDeclaration); typeDecl.resolveBinding(); } return typeDecl; } public TypeParameter convert(org.aspectj.org.eclipse.jdt.internal.compiler.ast.TypeParameter typeParameter) { final TypeParameter typeParameter2 = new TypeParameter(this.ast); final SimpleName simpleName = new SimpleName(this.ast); simpleName.internalSetIdentifier(new String(typeParameter.name)); int start = typeParameter.sourceStart; int end = typeParameter.sourceEnd; simpleName.setSourceRange(start, end - start + 1); typeParameter2.setName(simpleName); final TypeReference superType = typeParameter.type; end = typeParameter.declarationSourceEnd; if (superType != null) { Type type = convertType(superType); typeParameter2.typeBounds().add(type); end = type.getStartPosition() + type.getLength() - 1; } TypeReference[] bounds = typeParameter.bounds; if (bounds != null) { Type type = null; for (int index = 0, length = bounds.length; index < length; index++) { type = convertType(bounds[index]); typeParameter2.typeBounds().add(type); end = type.getStartPosition() + type.getLength() - 1; } } start = typeParameter.declarationSourceStart; end = retrieveClosingAngleBracketPosition(end); typeParameter2.setSourceRange(start, end - start + 1); if (this.resolveBindings) { recordName(simpleName, typeParameter); recordNodes(typeParameter2, typeParameter); typeParameter2.resolveBinding(); } return typeParameter2; } public Name convert(org.aspectj.org.eclipse.jdt.internal.compiler.ast.TypeReference typeReference) { char[][] typeName = typeReference.getTypeName(); int length = typeName.length; if (length > 1) { // QualifiedName org.aspectj.org.eclipse.jdt.internal.compiler.ast.QualifiedTypeReference qualifiedTypeReference = (org.aspectj.org.eclipse.jdt.internal.compiler.ast.QualifiedTypeReference) typeReference; final long[] positions = qualifiedTypeReference.sourcePositions; return setQualifiedNameNameAndSourceRanges(typeName, positions, typeReference); } else { final SimpleName name = new SimpleName(this.ast); name.internalSetIdentifier(new String(typeName[0])); name.setSourceRange(typeReference.sourceStart, typeReference.sourceEnd - typeReference.sourceStart + 1); if (this.resolveBindings) { recordNodes(name, typeReference); } return name; } } protected FieldDeclaration convertToFieldDeclaration(org.aspectj.org.eclipse.jdt.internal.compiler.ast.FieldDeclaration fieldDecl) { VariableDeclarationFragment variableDeclarationFragment = convertToVariableDeclarationFragment(fieldDecl); final FieldDeclaration fieldDeclaration = new FieldDeclaration(this.ast); fieldDeclaration.fragments().add(variableDeclarationFragment); IVariableBinding binding = null; if (this.resolveBindings) { recordNodes(variableDeclarationFragment, fieldDecl); binding = variableDeclarationFragment.resolveBinding(); } fieldDeclaration.setSourceRange(fieldDecl.declarationSourceStart, fieldDecl.declarationEnd - fieldDecl.declarationSourceStart + 1); Type type = convertType(fieldDecl.type); setTypeForField(fieldDeclaration, type, variableDeclarationFragment.getExtraDimensions()); setModifiers(fieldDeclaration, fieldDecl); if (!(this.resolveBindings && binding == null)) { convert(fieldDecl.javadoc, fieldDeclaration); } return fieldDeclaration; } // public ParenthesizedExpression convertToParenthesizedExpression(org.aspectj.org.eclipse.jdt.internal.compiler.ast.Expression expression) { // final ParenthesizedExpression parenthesizedExpression = new ParenthesizedExpression(this.ast); // if (this.resolveBindings) { // recordNodes(parenthesizedExpression, expression); // } // parenthesizedExpression.setSourceRange(expression.sourceStart, expression.sourceEnd - expression.sourceStart + 1); // adjustSourcePositionsForParent(expression); // trimWhiteSpacesAndComments(expression); // // decrement the number of parenthesis // int numberOfParenthesis = (expression.bits & org.aspectj.org.eclipse.jdt.internal.compiler.ast.ASTNode.ParenthesizedMASK) >> org.aspectj.org.eclipse.jdt.internal.compiler.ast.ASTNode.ParenthesizedSHIFT; // expression.bits &= ~org.aspectj.org.eclipse.jdt.internal.compiler.ast.ASTNode.ParenthesizedMASK; // expression.bits |= (numberOfParenthesis - 1) << org.aspectj.org.eclipse.jdt.internal.compiler.ast.ASTNode.ParenthesizedSHIFT; // parenthesizedExpression.setExpression(convert(expression)); // return parenthesizedExpression; // } // public Type convertToType(org.aspectj.org.eclipse.jdt.internal.compiler.ast.NameReference reference) { // Name name = convert(reference); // final SimpleType type = new SimpleType(this.ast); // type.setName(name); // type.setSourceRange(name.getStartPosition(), name.getLength()); // if (this.resolveBindings) { // this.recordNodes(type, reference); // } // return type; // } protected VariableDeclarationExpression convertToVariableDeclarationExpression(org.aspectj.org.eclipse.jdt.internal.compiler.ast.LocalDeclaration localDeclaration) { final VariableDeclarationFragment variableDeclarationFragment = convertToVariableDeclarationFragment(localDeclaration); final VariableDeclarationExpression variableDeclarationExpression = new VariableDeclarationExpression(this.ast); variableDeclarationExpression.fragments().add(variableDeclarationFragment); if (this.resolveBindings) { recordNodes(variableDeclarationFragment, localDeclaration); } variableDeclarationExpression.setSourceRange(localDeclaration.declarationSourceStart, localDeclaration.declarationSourceEnd - localDeclaration.declarationSourceStart + 1); Type type = convertType(localDeclaration.type); setTypeForVariableDeclarationExpression(variableDeclarationExpression, type, variableDeclarationFragment.getExtraDimensions()); if (localDeclaration.modifiersSourceStart != -1) { setModifiers(variableDeclarationExpression, localDeclaration); } return variableDeclarationExpression; } protected SingleVariableDeclaration convertToSingleVariableDeclaration(LocalDeclaration localDeclaration) { final SingleVariableDeclaration variableDecl = new SingleVariableDeclaration(this.ast); setModifiers(variableDecl, localDeclaration); final SimpleName name = new SimpleName(this.ast); name.internalSetIdentifier(new String(localDeclaration.name)); int start = localDeclaration.sourceStart; int nameEnd = localDeclaration.sourceEnd; name.setSourceRange(start, nameEnd - start + 1); variableDecl.setName(name); final int extraDimensions = retrieveExtraDimension(nameEnd + 1, localDeclaration.type.sourceEnd); variableDecl.setExtraDimensions(extraDimensions); Type type = convertType(localDeclaration.type); int typeEnd = type.getStartPosition() + type.getLength() - 1; int rightEnd = Math.max(typeEnd, localDeclaration.declarationSourceEnd); /* * There is extra work to do to set the proper type positions * See PR http://bugs.eclipse.org/bugs/show_bug.cgi?id=23284 */ setTypeForSingleVariableDeclaration(variableDecl, type, extraDimensions); variableDecl.setSourceRange(localDeclaration.declarationSourceStart, rightEnd - localDeclaration.declarationSourceStart + 1); if (this.resolveBindings) { recordNodes(name, localDeclaration); recordNodes(variableDecl, localDeclaration); variableDecl.resolveBinding(); } return variableDecl; } protected VariableDeclarationFragment convertToVariableDeclarationFragment(InterTypeFieldDeclaration fieldDeclaration) { // ajh02: method added final VariableDeclarationFragment variableDeclarationFragment = new VariableDeclarationFragment(this.ast); final SimpleName name = new SimpleName(this.ast); name.internalSetIdentifier(new String(fieldDeclaration.getDeclaredSelector())); name.setSourceRange(fieldDeclaration.sourceStart, fieldDeclaration.sourceEnd - fieldDeclaration.sourceStart + 1); variableDeclarationFragment.setName(name); int start = fieldDeclaration.sourceEnd; if (fieldDeclaration.initialization != null) { final Expression expression = super.convert(fieldDeclaration.initialization); variableDeclarationFragment.setInitializer(expression); start = expression.getStartPosition() + expression.getLength(); } int end = retrievePositionBeforeNextCommaOrSemiColon(start, fieldDeclaration.declarationSourceEnd); if (end == -1) { variableDeclarationFragment.setSourceRange(fieldDeclaration.sourceStart, fieldDeclaration.declarationSourceEnd - fieldDeclaration.sourceStart + 1); variableDeclarationFragment.setFlags(variableDeclarationFragment.getFlags() | ASTNode.MALFORMED); } else { variableDeclarationFragment.setSourceRange(fieldDeclaration.sourceStart, end - fieldDeclaration.sourceStart + 1); } variableDeclarationFragment.setExtraDimensions(retrieveExtraDimension(fieldDeclaration.sourceEnd + 1, fieldDeclaration.declarationSourceEnd )); if (this.resolveBindings) { recordNodes(name, fieldDeclaration); recordNodes(variableDeclarationFragment, fieldDeclaration); variableDeclarationFragment.resolveBinding(); } return variableDeclarationFragment; } protected VariableDeclarationFragment convertToVariableDeclarationFragment(org.aspectj.org.eclipse.jdt.internal.compiler.ast.FieldDeclaration fieldDeclaration) { final VariableDeclarationFragment variableDeclarationFragment = new VariableDeclarationFragment(this.ast); final SimpleName name = new SimpleName(this.ast); name.internalSetIdentifier(new String(fieldDeclaration.name)); name.setSourceRange(fieldDeclaration.sourceStart, fieldDeclaration.sourceEnd - fieldDeclaration.sourceStart + 1); variableDeclarationFragment.setName(name); int start = fieldDeclaration.sourceEnd; if (fieldDeclaration.initialization != null) { final Expression expression = super.convert(fieldDeclaration.initialization); variableDeclarationFragment.setInitializer(expression); start = expression.getStartPosition() + expression.getLength(); } int end = retrievePositionBeforeNextCommaOrSemiColon(start, fieldDeclaration.declarationSourceEnd); if (end == -1) { variableDeclarationFragment.setSourceRange(fieldDeclaration.sourceStart, fieldDeclaration.declarationSourceEnd - fieldDeclaration.sourceStart + 1); variableDeclarationFragment.setFlags(variableDeclarationFragment.getFlags() | ASTNode.MALFORMED); } else { variableDeclarationFragment.setSourceRange(fieldDeclaration.sourceStart, end - fieldDeclaration.sourceStart + 1); } variableDeclarationFragment.setExtraDimensions(retrieveExtraDimension(fieldDeclaration.sourceEnd + 1, fieldDeclaration.declarationSourceEnd )); if (this.resolveBindings) { recordNodes(name, fieldDeclaration); recordNodes(variableDeclarationFragment, fieldDeclaration); variableDeclarationFragment.resolveBinding(); } return variableDeclarationFragment; } protected VariableDeclarationFragment convertToVariableDeclarationFragment(org.aspectj.org.eclipse.jdt.internal.compiler.ast.LocalDeclaration localDeclaration) { final VariableDeclarationFragment variableDeclarationFragment = new VariableDeclarationFragment(this.ast); final SimpleName name = new SimpleName(this.ast); name.internalSetIdentifier(new String(localDeclaration.name)); name.setSourceRange(localDeclaration.sourceStart, localDeclaration.sourceEnd - localDeclaration.sourceStart + 1); variableDeclarationFragment.setName(name); int start = localDeclaration.sourceEnd; if (localDeclaration.initialization != null) { final Expression expression = super.convert(localDeclaration.initialization); variableDeclarationFragment.setInitializer(expression); start = expression.getStartPosition() + expression.getLength(); } int end = retrievePositionBeforeNextCommaOrSemiColon(start, localDeclaration.declarationSourceEnd); if (end == -1) { if (localDeclaration.initialization != null) { variableDeclarationFragment.setSourceRange(localDeclaration.sourceStart, localDeclaration.initialization.sourceEnd - localDeclaration.sourceStart + 1); } else { variableDeclarationFragment.setSourceRange(localDeclaration.sourceStart, localDeclaration.sourceEnd - localDeclaration.sourceStart + 1); } } else { variableDeclarationFragment.setSourceRange(localDeclaration.sourceStart, end - localDeclaration.sourceStart + 1); } variableDeclarationFragment.setExtraDimensions(retrieveExtraDimension(localDeclaration.sourceEnd + 1, this.compilationUnitSourceLength)); if (this.resolveBindings) { recordNodes(variableDeclarationFragment, localDeclaration); recordNodes(name, localDeclaration); variableDeclarationFragment.resolveBinding(); } return variableDeclarationFragment; } protected VariableDeclarationStatement convertToVariableDeclarationStatement(org.aspectj.org.eclipse.jdt.internal.compiler.ast.LocalDeclaration localDeclaration) { final VariableDeclarationFragment variableDeclarationFragment = convertToVariableDeclarationFragment(localDeclaration); final VariableDeclarationStatement variableDeclarationStatement = new VariableDeclarationStatement(this.ast); variableDeclarationStatement.fragments().add(variableDeclarationFragment); if (this.resolveBindings) { recordNodes(variableDeclarationFragment, localDeclaration); } variableDeclarationStatement.setSourceRange(localDeclaration.declarationSourceStart, localDeclaration.declarationSourceEnd - localDeclaration.declarationSourceStart + 1); Type type = convertType(localDeclaration.type); setTypeForVariableDeclarationStatement(variableDeclarationStatement, type, variableDeclarationFragment.getExtraDimensions()); if (localDeclaration.modifiersSourceStart != -1) { setModifiers(variableDeclarationStatement, localDeclaration); } return variableDeclarationStatement; } public Type convertType(TypeReference typeReference) { if (typeReference instanceof Wildcard) { final Wildcard wildcard = (Wildcard) typeReference; final WildcardType wildcardType = new WildcardType(this.ast); if (wildcard.bound != null) { final Type bound = convertType(wildcard.bound); wildcardType.setBound(bound, wildcard.kind == Wildcard.EXTENDS); int start = wildcard.sourceStart; wildcardType.setSourceRange(start, bound.getStartPosition() + bound.getLength() - start); } else { final int start = wildcard.sourceStart; final int end = wildcard.sourceEnd; wildcardType.setSourceRange(start, end - start + 1); } if (this.resolveBindings) { recordNodes(wildcardType, typeReference); } return wildcardType; } Type type = null; int sourceStart = -1; int length = 0; int dimensions = typeReference.dimensions(); if (typeReference instanceof org.aspectj.org.eclipse.jdt.internal.compiler.ast.SingleTypeReference) { // this is either an ArrayTypeReference or a SingleTypeReference char[] name = ((org.aspectj.org.eclipse.jdt.internal.compiler.ast.SingleTypeReference) typeReference).getTypeName()[0]; sourceStart = typeReference.sourceStart; length = typeReference.sourceEnd - typeReference.sourceStart + 1; // need to find out if this is an array type of primitive types or not if (isPrimitiveType(name)) { int end = retrieveEndOfElementTypeNamePosition(sourceStart, sourceStart + length); if (end == -1) { end = sourceStart + length - 1; } final PrimitiveType primitiveType = new PrimitiveType(this.ast); primitiveType.setPrimitiveTypeCode(getPrimitiveTypeCode(name)); primitiveType.setSourceRange(sourceStart, end - sourceStart + 1); type = primitiveType; } else if (typeReference instanceof ParameterizedSingleTypeReference) { ParameterizedSingleTypeReference parameterizedSingleTypeReference = (ParameterizedSingleTypeReference) typeReference; final SimpleName simpleName = new SimpleName(this.ast); simpleName.internalSetIdentifier(new String(name)); int end = retrieveEndOfElementTypeNamePosition(sourceStart, sourceStart + length); if (end == -1) { end = sourceStart + length - 1; } simpleName.setSourceRange(sourceStart, end - sourceStart + 1); switch(this.ast.apiLevel) { case AST.JLS2_INTERNAL : SimpleType simpleType = new SimpleType(this.ast); simpleType.setName(simpleName); simpleType.setFlags(simpleType.getFlags() | ASTNode.MALFORMED); simpleType.setSourceRange(sourceStart, end - sourceStart + 1); type = simpleType; if (this.resolveBindings) { this.recordNodes(simpleName, typeReference); } break; case AST.JLS3 : simpleType = new SimpleType(this.ast); simpleType.setName(simpleName); simpleType.setSourceRange(simpleName.getStartPosition(), simpleName.getLength()); final ParameterizedType parameterizedType = new ParameterizedType(this.ast); parameterizedType.setType(simpleType); type = parameterizedType; TypeReference[] typeArguments = parameterizedSingleTypeReference.typeArguments; if (typeArguments != null) { Type type2 = null; for (int i = 0, max = typeArguments.length; i < max; i++) { type2 = convertType(typeArguments[i]); ((ParameterizedType) type).typeArguments().add(type2); end = type2.getStartPosition() + type2.getLength() - 1; } end = retrieveClosingAngleBracketPosition(end + 1); type.setSourceRange(sourceStart, end - sourceStart + 1); } else { type.setSourceRange(sourceStart, end - sourceStart + 1); } if (this.resolveBindings) { this.recordNodes(simpleName, typeReference); this.recordNodes(simpleType, typeReference); } } } else { final SimpleName simpleName = new SimpleName(this.ast); simpleName.internalSetIdentifier(new String(name)); // we need to search for the starting position of the first brace in order to set the proper length // PR http://dev.eclipse.org/bugs/show_bug.cgi?id=10759 int end = retrieveEndOfElementTypeNamePosition(sourceStart, sourceStart + length); if (end == -1) { end = sourceStart + length - 1; } simpleName.setSourceRange(sourceStart, end - sourceStart + 1); final SimpleType simpleType = new SimpleType(this.ast); simpleType.setName(simpleName); type = simpleType; type.setSourceRange(sourceStart, end - sourceStart + 1); type = simpleType; if (this.resolveBindings) { this.recordNodes(simpleName, typeReference); } } if (dimensions != 0) { type = this.ast.newArrayType(type, dimensions); type.setSourceRange(sourceStart, length); ArrayType subarrayType = (ArrayType) type; int index = dimensions - 1; while (index > 0) { subarrayType = (ArrayType) subarrayType.getComponentType(); int end = retrieveProperRightBracketPosition(index, sourceStart); subarrayType.setSourceRange(sourceStart, end - sourceStart + 1); index--; } if (this.resolveBindings) { // store keys for inner types completeRecord((ArrayType) type, typeReference); } } } else { if (typeReference instanceof ParameterizedQualifiedTypeReference) { ParameterizedQualifiedTypeReference parameterizedQualifiedTypeReference = (ParameterizedQualifiedTypeReference) typeReference; char[][] tokens = parameterizedQualifiedTypeReference.tokens; TypeReference[][] typeArguments = parameterizedQualifiedTypeReference.typeArguments; long[] positions = parameterizedQualifiedTypeReference.sourcePositions; sourceStart = (int)(positions[0]>>>32); switch(this.ast.apiLevel) { case AST.JLS2_INTERNAL : { char[][] name = ((org.aspectj.org.eclipse.jdt.internal.compiler.ast.QualifiedTypeReference) typeReference).getTypeName(); int nameLength = name.length; sourceStart = (int)(positions[0]>>>32); length = (int)(positions[nameLength - 1] & 0xFFFFFFFF) - sourceStart + 1; Name qualifiedName = this.setQualifiedNameNameAndSourceRanges(name, positions, typeReference); final SimpleType simpleType = new SimpleType(this.ast); simpleType.setName(qualifiedName); simpleType.setSourceRange(sourceStart, length); type = simpleType; } break; case AST.JLS3 : if (typeArguments != null) { int numberOfEnclosingType = 0; int startingIndex = 0; int endingIndex = 0; for (int i = 0, max = typeArguments.length; i < max; i++) { if (typeArguments[i] != null) { numberOfEnclosingType++; } else if (numberOfEnclosingType == 0) { endingIndex++; } } Name name = null; if (endingIndex - startingIndex == 0) { final SimpleName simpleName = new SimpleName(this.ast); simpleName.internalSetIdentifier(new String(tokens[startingIndex])); recordPendingNameScopeResolution(simpleName); int start = (int)(positions[startingIndex]>>>32); int end = (int) positions[startingIndex]; simpleName.setSourceRange(start, end - start + 1); simpleName.index = 1; name = simpleName; if (this.resolveBindings) { recordNodes(simpleName, typeReference); } } else { name = this.setQualifiedNameNameAndSourceRanges(tokens, positions, endingIndex, typeReference); } SimpleType simpleType = new SimpleType(this.ast); simpleType.setName(name); int start = (int)(positions[startingIndex]>>>32); int end = (int) positions[endingIndex]; simpleType.setSourceRange(start, end - start + 1); ParameterizedType parameterizedType = new ParameterizedType(this.ast); parameterizedType.setType(simpleType); if (this.resolveBindings) { recordNodes(simpleType, typeReference); recordNodes(parameterizedType, typeReference); } start = simpleType.getStartPosition(); end = start + simpleType.getLength() - 1; for (int i = 0, max = typeArguments[endingIndex].length; i < max; i++) { final Type type2 = convertType(typeArguments[endingIndex][i]); parameterizedType.typeArguments().add(type2); end = type2.getStartPosition() + type2.getLength() - 1; } int indexOfEnclosingType = 1; parameterizedType.index = indexOfEnclosingType; end = retrieveClosingAngleBracketPosition(end + 1); length = end + 1; parameterizedType.setSourceRange(start, end - start + 1); startingIndex = endingIndex + 1; Type currentType = parameterizedType; while(startingIndex < typeArguments.length) { SimpleName simpleName = new SimpleName(this.ast); simpleName.internalSetIdentifier(new String(tokens[startingIndex])); simpleName.index = startingIndex + 1; start = (int)(positions[startingIndex]>>>32); end = (int) positions[startingIndex]; simpleName.setSourceRange(start, end - start + 1); recordPendingNameScopeResolution(simpleName); QualifiedType qualifiedType = new QualifiedType(this.ast); qualifiedType.setQualifier(currentType); qualifiedType.setName(simpleName); if (this.resolveBindings) { recordNodes(simpleName, typeReference); recordNodes(qualifiedType, typeReference); } start = currentType.getStartPosition(); end = simpleName.getStartPosition() + simpleName.getLength() - 1; qualifiedType.setSourceRange(start, end - start + 1); indexOfEnclosingType++; if (typeArguments[startingIndex] != null) { qualifiedType.index = indexOfEnclosingType; ParameterizedType parameterizedType2 = new ParameterizedType(this.ast); parameterizedType2.setType(qualifiedType); parameterizedType2.index = indexOfEnclosingType; if (this.resolveBindings) { recordNodes(parameterizedType2, typeReference); } for (int i = 0, max = typeArguments[startingIndex].length; i < max; i++) { final Type type2 = convertType(typeArguments[startingIndex][i]); parameterizedType2.typeArguments().add(type2); end = type2.getStartPosition() + type2.getLength() - 1; } end = retrieveClosingAngleBracketPosition(end + 1); length = end + 1; parameterizedType2.setSourceRange(start, end - start + 1); currentType = parameterizedType2; } else { currentType = qualifiedType; qualifiedType.index = indexOfEnclosingType; } startingIndex++; } if (this.resolveBindings) { this.recordNodes(currentType, typeReference); } type = currentType; length -= sourceStart; } } } else { char[][] name = ((org.aspectj.org.eclipse.jdt.internal.compiler.ast.QualifiedTypeReference) typeReference).getTypeName(); int nameLength = name.length; long[] positions = ((org.aspectj.org.eclipse.jdt.internal.compiler.ast.QualifiedTypeReference) typeReference).sourcePositions; sourceStart = (int)(positions[0]>>>32); length = (int)(positions[nameLength - 1] & 0xFFFFFFFF) - sourceStart + 1; final Name qualifiedName = this.setQualifiedNameNameAndSourceRanges(name, positions, typeReference); final SimpleType simpleType = new SimpleType(this.ast); simpleType.setName(qualifiedName); type = simpleType; type.setSourceRange(sourceStart, length); } if (dimensions != 0) { type = this.ast.newArrayType(type, dimensions); if (this.resolveBindings) { completeRecord((ArrayType) type, typeReference); } int end = retrieveEndOfDimensionsPosition(sourceStart+length, this.compilationUnitSourceLength); if (end != -1) { type.setSourceRange(sourceStart, end - sourceStart + 1); } else { type.setSourceRange(sourceStart, length); } ArrayType subarrayType = (ArrayType) type; int index = dimensions - 1; while (index > 0) { subarrayType = (ArrayType) subarrayType.getComponentType(); end = retrieveProperRightBracketPosition(index, sourceStart); subarrayType.setSourceRange(sourceStart, end - sourceStart + 1); index--; } } } if (this.resolveBindings) { this.recordNodes(type, typeReference); } return type; } protected Comment createComment(int[] positions) { // Create comment node Comment comment = null; int start = positions[0]; int end = positions[1]; if (positions[1]>0) { // Javadoc comments have positive end position Javadoc docComment = this.docParser.parse(positions); if (docComment == null) return null; comment = docComment; } else { end = -end; if (positions[0]>0) { // Block comment have positive start position comment = new BlockComment(this.ast); } else { // Line comment have negative start and end position start = -start; comment = new LineComment(this.ast); } comment.setSourceRange(start, end - start); } return comment; } protected Statement createFakeEmptyStatement(org.aspectj.org.eclipse.jdt.internal.compiler.ast.Statement statement) { EmptyStatement emptyStatement = new EmptyStatement(this.ast); emptyStatement.setFlags(emptyStatement.getFlags() | ASTNode.MALFORMED); int start = statement.sourceStart; int end = statement.sourceEnd; emptyStatement.setSourceRange(start, end - start + 1); return emptyStatement; } /** * @return a new modifier */ private Modifier createModifier(ModifierKeyword keyword) { final Modifier modifier = new Modifier(this.ast); modifier.setKeyword(keyword); int start = this.scanner.getCurrentTokenStartPosition(); int end = this.scanner.getCurrentTokenEndPosition(); modifier.setSourceRange(start, end - start + 1); return modifier; } protected InfixExpression.Operator getOperatorFor(int operatorID) { switch (operatorID) { case org.aspectj.org.eclipse.jdt.internal.compiler.ast.OperatorIds.EQUAL_EQUAL : return InfixExpression.Operator.EQUALS; case org.aspectj.org.eclipse.jdt.internal.compiler.ast.OperatorIds.LESS_EQUAL : return InfixExpression.Operator.LESS_EQUALS; case org.aspectj.org.eclipse.jdt.internal.compiler.ast.OperatorIds.GREATER_EQUAL : return InfixExpression.Operator.GREATER_EQUALS; case org.aspectj.org.eclipse.jdt.internal.compiler.ast.OperatorIds.NOT_EQUAL : return InfixExpression.Operator.NOT_EQUALS; case org.aspectj.org.eclipse.jdt.internal.compiler.ast.OperatorIds.LEFT_SHIFT : return InfixExpression.Operator.LEFT_SHIFT; case org.aspectj.org.eclipse.jdt.internal.compiler.ast.OperatorIds.RIGHT_SHIFT : return InfixExpression.Operator.RIGHT_SHIFT_SIGNED; case org.aspectj.org.eclipse.jdt.internal.compiler.ast.OperatorIds.UNSIGNED_RIGHT_SHIFT : return InfixExpression.Operator.RIGHT_SHIFT_UNSIGNED; case org.aspectj.org.eclipse.jdt.internal.compiler.ast.OperatorIds.OR_OR : return InfixExpression.Operator.CONDITIONAL_OR; case org.aspectj.org.eclipse.jdt.internal.compiler.ast.OperatorIds.AND_AND : return InfixExpression.Operator.CONDITIONAL_AND; case org.aspectj.org.eclipse.jdt.internal.compiler.ast.OperatorIds.PLUS : return InfixExpression.Operator.PLUS; case org.aspectj.org.eclipse.jdt.internal.compiler.ast.OperatorIds.MINUS : return InfixExpression.Operator.MINUS; case org.aspectj.org.eclipse.jdt.internal.compiler.ast.OperatorIds.REMAINDER : return InfixExpression.Operator.REMAINDER; case org.aspectj.org.eclipse.jdt.internal.compiler.ast.OperatorIds.XOR : return InfixExpression.Operator.XOR; case org.aspectj.org.eclipse.jdt.internal.compiler.ast.OperatorIds.AND : return InfixExpression.Operator.AND; case org.aspectj.org.eclipse.jdt.internal.compiler.ast.OperatorIds.MULTIPLY : return InfixExpression.Operator.TIMES; case org.aspectj.org.eclipse.jdt.internal.compiler.ast.OperatorIds.OR : return InfixExpression.Operator.OR; case org.aspectj.org.eclipse.jdt.internal.compiler.ast.OperatorIds.DIVIDE : return InfixExpression.Operator.DIVIDE; case org.aspectj.org.eclipse.jdt.internal.compiler.ast.OperatorIds.GREATER : return InfixExpression.Operator.GREATER; case org.aspectj.org.eclipse.jdt.internal.compiler.ast.OperatorIds.LESS : return InfixExpression.Operator.LESS; } return null; } protected PrimitiveType.Code getPrimitiveTypeCode(char[] name) { switch(name[0]) { case 'i' : if (name.length == 3 && name[1] == 'n' && name[2] == 't') { return PrimitiveType.INT; } break; case 'l' : if (name.length == 4 && name[1] == 'o' && name[2] == 'n' && name[3] == 'g') { return PrimitiveType.LONG; } break; case 'd' : if (name.length == 6 && name[1] == 'o' && name[2] == 'u' && name[3] == 'b' && name[4] == 'l' && name[5] == 'e') { return PrimitiveType.DOUBLE; } break; case 'f' : if (name.length == 5 && name[1] == 'l' && name[2] == 'o' && name[3] == 'a' && name[4] == 't') { return PrimitiveType.FLOAT; } break; case 'b' : if (name.length == 4 && name[1] == 'y' && name[2] == 't' && name[3] == 'e') { return PrimitiveType.BYTE; } else if (name.length == 7 && name[1] == 'o' && name[2] == 'o' && name[3] == 'l' && name[4] == 'e' && name[5] == 'a' && name[6] == 'n') { return PrimitiveType.BOOLEAN; } break; case 'c' : if (name.length == 4 && name[1] == 'h' && name[2] == 'a' && name[3] == 'r') { return PrimitiveType.CHAR; } break; case 's' : if (name.length == 5 && name[1] == 'h' && name[2] == 'o' && name[3] == 'r' && name[4] == 't') { return PrimitiveType.SHORT; } break; case 'v' : if (name.length == 4 && name[1] == 'o' && name[2] == 'i' && name[3] == 'd') { return PrimitiveType.VOID; } } return null; // cannot be reached } protected boolean isPrimitiveType(char[] name) { switch(name[0]) { case 'i' : if (name.length == 3 && name[1] == 'n' && name[2] == 't') { return true; } return false; case 'l' : if (name.length == 4 && name[1] == 'o' && name[2] == 'n' && name[3] == 'g') { return true; } return false; case 'd' : if (name.length == 6 && name[1] == 'o' && name[2] == 'u' && name[3] == 'b' && name[4] == 'l' && name[5] == 'e') { return true; } return false; case 'f' : if (name.length == 5 && name[1] == 'l' && name[2] == 'o' && name[3] == 'a' && name[4] == 't') { return true; } return false; case 'b' : if (name.length == 4 && name[1] == 'y' && name[2] == 't' && name[3] == 'e') { return true; } else if (name.length == 7 && name[1] == 'o' && name[2] == 'o' && name[3] == 'l' && name[4] == 'e' && name[5] == 'a' && name[6] == 'n') { return true; } return false; case 'c' : if (name.length == 4 && name[1] == 'h' && name[2] == 'a' && name[3] == 'r') { return true; } return false; case 's' : if (name.length == 5 && name[1] == 'h' && name[2] == 'o' && name[3] == 'r' && name[4] == 't') { return true; } return false; case 'v' : if (name.length == 4 && name[1] == 'o' && name[2] == 'i' && name[3] == 'd') { return true; } return false; } return false; } private void lookupForScopes() { if (this.pendingNameScopeResolution != null) { for (Iterator iterator = this.pendingNameScopeResolution.iterator(); iterator.hasNext(); ) { Name name = (Name) iterator.next(); this.ast.getBindingResolver().recordScope(name, lookupScope(name)); } } if (this.pendingThisExpressionScopeResolution != null) { for (Iterator iterator = this.pendingThisExpressionScopeResolution.iterator(); iterator.hasNext(); ) { ThisExpression thisExpression = (ThisExpression) iterator.next(); this.ast.getBindingResolver().recordScope(thisExpression, lookupScope(thisExpression)); } } } private BlockScope lookupScope(ASTNode node) { ASTNode currentNode = node; while(currentNode != null &&!(currentNode instanceof MethodDeclaration) && !(currentNode instanceof Initializer) && !(currentNode instanceof FieldDeclaration)) { currentNode = currentNode.getParent(); } if (currentNode == null) { return null; } if (currentNode instanceof Initializer) { Initializer initializer = (Initializer) currentNode; while(!(currentNode instanceof AbstractTypeDeclaration)) { currentNode = currentNode.getParent(); } if (currentNode instanceof TypeDeclaration || currentNode instanceof EnumDeclaration || currentNode instanceof AnnotationTypeDeclaration) { org.aspectj.org.eclipse.jdt.internal.compiler.ast.TypeDeclaration typeDecl = (org.aspectj.org.eclipse.jdt.internal.compiler.ast.TypeDeclaration) this.ast.getBindingResolver().getCorrespondingNode(currentNode); if ((initializer.getModifiers() & Modifier.STATIC) != 0) { return typeDecl.staticInitializerScope; } else { return typeDecl.initializerScope; } } } else if (currentNode instanceof FieldDeclaration) { FieldDeclaration fieldDeclaration = (FieldDeclaration) currentNode; while(!(currentNode instanceof AbstractTypeDeclaration)) { currentNode = currentNode.getParent(); } if (currentNode instanceof TypeDeclaration || currentNode instanceof EnumDeclaration || currentNode instanceof AnnotationTypeDeclaration) { org.aspectj.org.eclipse.jdt.internal.compiler.ast.TypeDeclaration typeDecl = (org.aspectj.org.eclipse.jdt.internal.compiler.ast.TypeDeclaration) this.ast.getBindingResolver().getCorrespondingNode(currentNode); if ((fieldDeclaration.getModifiers() & Modifier.STATIC) != 0) { return typeDecl.staticInitializerScope; } else { return typeDecl.initializerScope; } } } AbstractMethodDeclaration abstractMethodDeclaration = (AbstractMethodDeclaration) this.ast.getBindingResolver().getCorrespondingNode(currentNode); return abstractMethodDeclaration.scope; } protected void recordName(Name name, org.aspectj.org.eclipse.jdt.internal.compiler.ast.ASTNode compilerNode) { if (compilerNode != null) { recordNodes(name, compilerNode); if (compilerNode instanceof org.aspectj.org.eclipse.jdt.internal.compiler.ast.TypeReference) { org.aspectj.org.eclipse.jdt.internal.compiler.ast.TypeReference typeRef = (org.aspectj.org.eclipse.jdt.internal.compiler.ast.TypeReference) compilerNode; if (name.isQualifiedName()) { SimpleName simpleName = null; while (name.isQualifiedName()) { simpleName = ((QualifiedName) name).getName(); recordNodes(simpleName, typeRef); name = ((QualifiedName) name).getQualifier(); recordNodes(name, typeRef); } } } } } protected void recordNodes(ASTNode node, org.aspectj.org.eclipse.jdt.internal.compiler.ast.ASTNode oldASTNode) { this.ast.getBindingResolver().store(node, oldASTNode); } protected void recordNodes(org.aspectj.org.eclipse.jdt.internal.compiler.ast.Javadoc javadoc, TagElement tagElement) { Iterator fragments = tagElement.fragments().listIterator(); while (fragments.hasNext()) { ASTNode node = (ASTNode) fragments.next(); if (node.getNodeType() == ASTNode.MEMBER_REF) { MemberRef memberRef = (MemberRef) node; Name name = memberRef.getName(); // get compiler node and record nodes int start = name.getStartPosition(); org.aspectj.org.eclipse.jdt.internal.compiler.ast.ASTNode compilerNode = javadoc.getNodeStartingAt(start); if (compilerNode!= null) { recordNodes(name, compilerNode); recordNodes(node, compilerNode); } // Replace qualifier to have all nodes recorded if (memberRef.getQualifier() != null) { org.aspectj.org.eclipse.jdt.internal.compiler.ast.TypeReference typeRef = null; if (compilerNode instanceof JavadocFieldReference) { org.aspectj.org.eclipse.jdt.internal.compiler.ast.Expression expression = ((JavadocFieldReference)compilerNode).receiver; if (expression instanceof org.aspectj.org.eclipse.jdt.internal.compiler.ast.TypeReference) { typeRef = (org.aspectj.org.eclipse.jdt.internal.compiler.ast.TypeReference) expression; } } else if (compilerNode instanceof JavadocMessageSend) { org.aspectj.org.eclipse.jdt.internal.compiler.ast.Expression expression = ((JavadocMessageSend)compilerNode).receiver; if (expression instanceof org.aspectj.org.eclipse.jdt.internal.compiler.ast.TypeReference) { typeRef = (org.aspectj.org.eclipse.jdt.internal.compiler.ast.TypeReference) expression; } } if (typeRef != null) { recordName(memberRef.getQualifier(), typeRef); } } } else if (node.getNodeType() == ASTNode.METHOD_REF) { MethodRef methodRef = (MethodRef) node; Name name = methodRef.getName(); // get compiler node and record nodes int start = name.getStartPosition(); // get compiler node and record nodes org.aspectj.org.eclipse.jdt.internal.compiler.ast.ASTNode compilerNode = javadoc.getNodeStartingAt(start); // record nodes if (compilerNode != null) { recordNodes(methodRef, compilerNode); // get type ref org.aspectj.org.eclipse.jdt.internal.compiler.ast.TypeReference typeRef = null; if (compilerNode instanceof org.aspectj.org.eclipse.jdt.internal.compiler.ast.JavadocAllocationExpression) { typeRef = ((org.aspectj.org.eclipse.jdt.internal.compiler.ast.JavadocAllocationExpression)compilerNode).type; if (typeRef != null) recordNodes(name, compilerNode); } else if (compilerNode instanceof org.aspectj.org.eclipse.jdt.internal.compiler.ast.JavadocMessageSend) { org.aspectj.org.eclipse.jdt.internal.compiler.ast.Expression expression = ((org.aspectj.org.eclipse.jdt.internal.compiler.ast.JavadocMessageSend)compilerNode).receiver; if (expression instanceof org.aspectj.org.eclipse.jdt.internal.compiler.ast.TypeReference) { typeRef = (org.aspectj.org.eclipse.jdt.internal.compiler.ast.TypeReference) expression; } // TODO (frederic) remove following line to fix bug https://bugs.eclipse.org/bugs/show_bug.cgi?id=62650 recordNodes(name, compilerNode); } // record name and qualifier if (typeRef != null && methodRef.getQualifier() != null) { recordName(methodRef.getQualifier(), typeRef); } } // Resolve parameters Iterator parameters = methodRef.parameters().listIterator(); while (parameters.hasNext()) { MethodRefParameter param = (MethodRefParameter) parameters.next(); org.aspectj.org.eclipse.jdt.internal.compiler.ast.Expression expression = (org.aspectj.org.eclipse.jdt.internal.compiler.ast.Expression) javadoc.getNodeStartingAt(param.getStartPosition()); if (expression != null) { recordNodes(param, expression); if (expression instanceof JavadocArgumentExpression) { JavadocArgumentExpression argExpr = (JavadocArgumentExpression) expression; org.aspectj.org.eclipse.jdt.internal.compiler.ast.TypeReference typeRef = argExpr.argument.type; if (this.ast.apiLevel >= AST.JLS3) param.setVarargs(argExpr.argument.isVarArgs()); recordNodes(param.getType(), typeRef); if (param.getType().isSimpleType()) { recordName(((SimpleType)param.getType()).getName(), typeRef); } else if (param.getType().isArrayType()) { Type type = ((ArrayType) param.getType()).getElementType(); recordNodes(type, typeRef); if (type.isSimpleType()) { recordName(((SimpleType)type).getName(), typeRef); } } } } } } else if (node.getNodeType() == ASTNode.SIMPLE_NAME || node.getNodeType() == ASTNode.QUALIFIED_NAME) { org.aspectj.org.eclipse.jdt.internal.compiler.ast.ASTNode compilerNode = javadoc.getNodeStartingAt(node.getStartPosition()); recordName((Name) node, compilerNode); } else if (node.getNodeType() == ASTNode.TAG_ELEMENT) { // resolve member and method references binding recordNodes(javadoc, (TagElement) node); } } } protected void recordPendingNameScopeResolution(Name name) { if (this.pendingNameScopeResolution == null) { this.pendingNameScopeResolution = new HashSet(); } this.pendingNameScopeResolution.add(name); } protected void recordPendingThisExpressionScopeResolution(ThisExpression thisExpression) { if (this.pendingThisExpressionScopeResolution == null) { this.pendingThisExpressionScopeResolution = new HashSet(); } this.pendingThisExpressionScopeResolution.add(thisExpression); } /** * Remove whitespaces and comments before and after the expression. */ private void trimWhiteSpacesAndComments(org.aspectj.org.eclipse.jdt.internal.compiler.ast.Expression expression) { int start = expression.sourceStart; int end = expression.sourceEnd; int token; int trimLeftPosition = expression.sourceStart; int trimRightPosition = expression.sourceEnd; boolean first = true; Scanner removeBlankScanner = this.ast.scanner; try { removeBlankScanner.setSource(this.compilationUnitSource); removeBlankScanner.resetTo(start, end); while (true) { token = removeBlankScanner.getNextToken(); switch (token) { case TerminalTokens.TokenNameCOMMENT_JAVADOC : case TerminalTokens.TokenNameCOMMENT_LINE : case TerminalTokens.TokenNameCOMMENT_BLOCK : if (first) { trimLeftPosition = removeBlankScanner.currentPosition; } break; case TerminalTokens.TokenNameWHITESPACE : if (first) { trimLeftPosition = removeBlankScanner.currentPosition; } break; case TerminalTokens.TokenNameEOF : expression.sourceStart = trimLeftPosition; expression.sourceEnd = trimRightPosition; return; default : /* * if we find something else than a whitespace or a comment, * then we reset the trimRigthPosition to the expression * source end. */ trimRightPosition = removeBlankScanner.currentPosition - 1; first = false; } } } catch (InvalidInputException e){ // ignore } } protected int retrieveEndingSemiColonPosition(int start, int end) { int count = 0; this.scanner.resetTo(start, end); try { int token; while ((token = this.scanner.getNextToken()) != TerminalTokens.TokenNameEOF) { switch(token) { case TerminalTokens.TokenNameSEMICOLON: if (count == 0) { return this.scanner.currentPosition - 1; } break; case TerminalTokens.TokenNameLBRACE : count++; break; case TerminalTokens.TokenNameRBRACE : count--; break; case TerminalTokens.TokenNameLPAREN : count++; break; case TerminalTokens.TokenNameRPAREN : count--; break; case TerminalTokens.TokenNameLBRACKET : count++; break; case TerminalTokens.TokenNameRBRACKET : count--; } } } catch(InvalidInputException e) { // ignore } return -1; } /** * This method is used to retrieve the ending position for a type declaration when the dimension is right after the type * name. * For example: * int[] i; => return 5, but int i[] => return -1; * @return int the dimension found */ protected int retrieveEndOfDimensionsPosition(int start, int end) { this.scanner.resetTo(start, end); int foundPosition = -1; try { int token; while ((token = this.scanner.getNextToken()) != TerminalTokens.TokenNameEOF) { switch(token) { case TerminalTokens.TokenNameLBRACKET: case TerminalTokens.TokenNameCOMMENT_BLOCK: case TerminalTokens.TokenNameCOMMENT_JAVADOC: case TerminalTokens.TokenNameCOMMENT_LINE: break; case TerminalTokens.TokenNameRBRACKET://166 foundPosition = this.scanner.currentPosition - 1; break; default: return foundPosition; } } } catch(InvalidInputException e) { // ignore } return foundPosition; } /** * This method is used to retrieve the position just before the left bracket. * @return int the dimension found, -1 if none */ protected int retrieveEndOfElementTypeNamePosition(int start, int end) { this.scanner.resetTo(start, end); try { int token; while ((token = this.scanner.getNextToken()) != TerminalTokens.TokenNameEOF) { switch(token) { case TerminalTokens.TokenNameIdentifier: case TerminalTokens.TokenNamebyte: case TerminalTokens.TokenNamechar: case TerminalTokens.TokenNamedouble: case TerminalTokens.TokenNamefloat: case TerminalTokens.TokenNameint: case TerminalTokens.TokenNamelong: case TerminalTokens.TokenNameshort: case TerminalTokens.TokenNameboolean: return this.scanner.currentPosition - 1; } } } catch(InvalidInputException e) { // ignore } return -1; } /** * This method is used to retrieve the position after the right parenthesis. * @return int the position found */ protected int retrieveEndOfRightParenthesisPosition(int start, int end) { this.scanner.resetTo(start, end); try { int token; while ((token = this.scanner.getNextToken()) != TerminalTokens.TokenNameEOF) { switch(token) { case TerminalTokens.TokenNameRPAREN: return this.scanner.currentPosition; } } } catch(InvalidInputException e) { // ignore } return -1; } /** * This method is used to retrieve the array dimension declared after the * name of a local or a field declaration. * For example: * int i, j[] = null, k[][] = {{}}; * It should return 0 for i, 1 for j and 2 for k. * @return int the dimension found */ protected int retrieveExtraDimension(int start, int end) { this.scanner.resetTo(start, end); int dimensions = 0; try { int token; while ((token = this.scanner.getNextToken()) != TerminalTokens.TokenNameEOF) { switch(token) { case TerminalTokens.TokenNameLBRACKET: case TerminalTokens.TokenNameCOMMENT_BLOCK: case TerminalTokens.TokenNameCOMMENT_JAVADOC: case TerminalTokens.TokenNameCOMMENT_LINE: break; case TerminalTokens.TokenNameRBRACKET://166 dimensions++; break; default: return dimensions; } } } catch(InvalidInputException e) { // ignore } return dimensions; } protected void retrieveIdentifierAndSetPositions(int start, int end, Name name) { this.scanner.resetTo(start, end); int token; try { while((token = this.scanner.getNextToken()) != TerminalTokens.TokenNameEOF) { if (token == TerminalTokens.TokenNameIdentifier) { int startName = this.scanner.startPosition; int endName = this.scanner.currentPosition - 1; name.setSourceRange(startName, endName - startName + 1); return; } } } catch(InvalidInputException e) { // ignore } } /** * This method is used to retrieve the start position of the block. * @return int the dimension found, -1 if none */ protected int retrieveIdentifierEndPosition(int start, int end) { this.scanner.resetTo(start, end); try { int token; while ((token = this.scanner.getNextToken()) != TerminalTokens.TokenNameEOF) { switch(token) { case TerminalTokens.TokenNameIdentifier://110 return this.scanner.getCurrentTokenEndPosition(); } } } catch(InvalidInputException e) { // ignore } return -1; } /** * This method is used to retrieve position before the next comma or semi-colon. * @return int the position found. */ protected int retrievePositionBeforeNextCommaOrSemiColon(int start, int end) { this.scanner.resetTo(start, end); int braceCounter = 0; try { int token; while ((token = this.scanner.getNextToken()) != TerminalTokens.TokenNameEOF) { switch(token) { case TerminalTokens.TokenNameLBRACE : braceCounter++; break; case TerminalTokens.TokenNameRBRACE : braceCounter--; break; case TerminalTokens.TokenNameLPAREN : braceCounter++; break; case TerminalTokens.TokenNameRPAREN : braceCounter--; break; case TerminalTokens.TokenNameLBRACKET : braceCounter++; break; case TerminalTokens.TokenNameRBRACKET : braceCounter--; break; case TerminalTokens.TokenNameCOMMA : case TerminalTokens.TokenNameSEMICOLON : if (braceCounter == 0) { return this.scanner.startPosition - 1; } } } } catch(InvalidInputException e) { // ignore } return -1; } protected int retrieveProperRightBracketPosition(int bracketNumber, int start) { this.scanner.resetTo(start, this.compilationUnitSourceLength); try { int token, count = 0; while ((token = this.scanner.getNextToken()) != TerminalTokens.TokenNameEOF) { switch(token) { case TerminalTokens.TokenNameRBRACKET: count++; if (count == bracketNumber) { return this.scanner.currentPosition - 1; } } } } catch(InvalidInputException e) { // ignore } return -1; } /** * This method is used to retrieve position before the next right brace or semi-colon. * @return int the position found. */ protected int retrieveRightBraceOrSemiColonPosition(int start, int end) { this.scanner.resetTo(start, end); try { int token; while ((token = this.scanner.getNextToken()) != TerminalTokens.TokenNameEOF) { switch(token) { case TerminalTokens.TokenNameRBRACE : return this.scanner.currentPosition - 1; case TerminalTokens.TokenNameSEMICOLON : return this.scanner.currentPosition - 1; } } } catch(InvalidInputException e) { // ignore } return -1; } /** * This method is used to retrieve position before the next right brace or semi-colon. * @return int the position found. */ protected int retrieveRightBrace(int start, int end) { this.scanner.resetTo(start, end); try { int token; while ((token = this.scanner.getNextToken()) != TerminalTokens.TokenNameEOF) { switch(token) { case TerminalTokens.TokenNameRBRACE : return this.scanner.currentPosition - 1; } } } catch(InvalidInputException e) { // ignore } return -1; } /** * This method is used to retrieve the position of the right bracket. * @return int the dimension found, -1 if none */ protected int retrieveRightBracketPosition(int start, int end) { this.scanner.resetTo(start, end); try { int token; while ((token = this.scanner.getNextToken()) != TerminalTokens.TokenNameEOF) { switch(token) { case TerminalTokens.TokenNameRBRACKET: return this.scanner.currentPosition - 1; } } } catch(InvalidInputException e) { // ignore } return -1; } /* * This method is used to set the right end position for expression * statement. The actual AST nodes don't include the trailing semicolon. * This method fixes the length of the corresponding node. */ protected void retrieveSemiColonPosition(ASTNode node) { int start = node.getStartPosition(); int length = node.getLength(); int end = start + length; int count = 0; this.scanner.resetTo(end, this.compilationUnitSourceLength); try { int token; while ((token = this.scanner.getNextToken()) != TerminalTokens.TokenNameEOF) { switch(token) { case TerminalTokens.TokenNameSEMICOLON: if (count == 0) { node.setSourceRange(start, this.scanner.currentPosition - start); return; } break; case TerminalTokens.TokenNameLBRACE : count++; break; case TerminalTokens.TokenNameRBRACE : count--; break; case TerminalTokens.TokenNameLPAREN : count++; break; case TerminalTokens.TokenNameRPAREN : count--; break; case TerminalTokens.TokenNameLBRACKET : count++; break; case TerminalTokens.TokenNameRBRACKET : count--; } } } catch(InvalidInputException e) { // ignore } } /** * This method is used to retrieve the start position of the block. * @return int the dimension found, -1 if none */ protected int retrieveStartBlockPosition(int start, int end) { this.scanner.resetTo(start, end); try { int token; while ((token = this.scanner.getNextToken()) != TerminalTokens.TokenNameEOF) { switch(token) { case TerminalTokens.TokenNameLBRACE://110 return this.scanner.startPosition; } } } catch(InvalidInputException e) { // ignore } return -1; } /** * This method is used to retrieve the starting position of the catch keyword. * @return int the dimension found, -1 if none */ protected int retrieveStartingCatchPosition(int start, int end) { this.scanner.resetTo(start, end); try { int token; while ((token = this.scanner.getNextToken()) != TerminalTokens.TokenNameEOF) { switch(token) { case TerminalTokens.TokenNamecatch://225 return this.scanner.startPosition; } } } catch(InvalidInputException e) { // ignore } return -1; } public void setAST(AST ast) { this.ast = ast; this.docParser = new DocCommentParser(this.ast, this.scanner, this.insideComments); } protected void setModifiers(AnnotationTypeDeclaration typeDecl, org.aspectj.org.eclipse.jdt.internal.compiler.ast.TypeDeclaration typeDeclaration) { this.scanner.resetTo(typeDeclaration.declarationSourceStart, typeDeclaration.sourceStart); this.setModifiers(typeDecl, typeDeclaration.annotations); } protected void setModifiers(AnnotationTypeMemberDeclaration annotationTypeMemberDecl, org.aspectj.org.eclipse.jdt.internal.compiler.ast.AnnotationMethodDeclaration annotationTypeMemberDeclaration) { this.scanner.resetTo(annotationTypeMemberDeclaration.declarationSourceStart, annotationTypeMemberDeclaration.sourceStart); this.setModifiers(annotationTypeMemberDecl, annotationTypeMemberDeclaration.annotations); } /** * @param bodyDeclaration */ protected void setModifiers(BodyDeclaration bodyDeclaration, org.aspectj.org.eclipse.jdt.internal.compiler.ast.Annotation[] annotations) { try { int token; int indexInAnnotations = 0; while ((token = this.scanner.getNextToken()) != TerminalTokens.TokenNameEOF) { IExtendedModifier modifier = null; switch(token) { case TerminalTokens.TokenNameabstract: modifier = createModifier(Modifier.ModifierKeyword.ABSTRACT_KEYWORD); break; case TerminalTokens.TokenNamepublic: modifier = createModifier(Modifier.ModifierKeyword.PUBLIC_KEYWORD); break; case TerminalTokens.TokenNamestatic: modifier = createModifier(Modifier.ModifierKeyword.STATIC_KEYWORD); break; case TerminalTokens.TokenNameprotected: modifier = createModifier(Modifier.ModifierKeyword.PROTECTED_KEYWORD); break; case TerminalTokens.TokenNameprivate: modifier = createModifier(Modifier.ModifierKeyword.PRIVATE_KEYWORD); break; case TerminalTokens.TokenNamefinal: modifier = createModifier(Modifier.ModifierKeyword.FINAL_KEYWORD); break; case TerminalTokens.TokenNamenative: modifier = createModifier(Modifier.ModifierKeyword.NATIVE_KEYWORD); break; case TerminalTokens.TokenNamesynchronized: modifier = createModifier(Modifier.ModifierKeyword.SYNCHRONIZED_KEYWORD); break; case TerminalTokens.TokenNametransient: modifier = createModifier(Modifier.ModifierKeyword.TRANSIENT_KEYWORD); break; case TerminalTokens.TokenNamevolatile: modifier = createModifier(Modifier.ModifierKeyword.VOLATILE_KEYWORD); break; case TerminalTokens.TokenNamestrictfp: modifier = createModifier(Modifier.ModifierKeyword.STRICTFP_KEYWORD); break; case TerminalTokens.TokenNameAT : // we have an annotation if (annotations != null && indexInAnnotations < annotations.length) { org.aspectj.org.eclipse.jdt.internal.compiler.ast.Annotation annotation = annotations[indexInAnnotations++]; modifier = super.convert(annotation); this.scanner.resetTo(annotation.declarationSourceEnd + 1, this.compilationUnitSourceLength); } break; case TerminalTokens.TokenNameCOMMENT_BLOCK : case TerminalTokens.TokenNameCOMMENT_LINE : case TerminalTokens.TokenNameCOMMENT_JAVADOC : break; default : return; } if (modifier != null) { bodyDeclaration.modifiers().add(modifier); } } } catch(InvalidInputException e) { // ignore } } protected void setModifiers(EnumDeclaration enumDeclaration, org.aspectj.org.eclipse.jdt.internal.compiler.ast.TypeDeclaration enumDeclaration2) { this.scanner.resetTo(enumDeclaration2.declarationSourceStart, enumDeclaration2.sourceStart); this.setModifiers(enumDeclaration, enumDeclaration2.annotations); } protected void setModifiers(EnumConstantDeclaration enumConstantDeclaration, org.aspectj.org.eclipse.jdt.internal.compiler.ast.FieldDeclaration fieldDeclaration) { switch(this.ast.apiLevel) { case AST.JLS2_INTERNAL : enumConstantDeclaration.internalSetModifiers(fieldDeclaration.modifiers & ExtraCompilerModifiers.AccJustFlag); if (fieldDeclaration.annotations != null) { enumConstantDeclaration.setFlags(enumConstantDeclaration.getFlags() | ASTNode.MALFORMED); } break; case AST.JLS3 : this.scanner.resetTo(fieldDeclaration.declarationSourceStart, fieldDeclaration.sourceStart); this.setModifiers(enumConstantDeclaration, fieldDeclaration.annotations); } } /** * @param fieldDeclaration * @param fieldDecl */ protected void setModifiers(FieldDeclaration fieldDeclaration, org.aspectj.org.eclipse.jdt.internal.compiler.ast.FieldDeclaration fieldDecl) { switch(this.ast.apiLevel) { case AST.JLS2_INTERNAL : fieldDeclaration.internalSetModifiers(fieldDecl.modifiers & ExtraCompilerModifiers.AccJustFlag); if (fieldDecl.annotations != null) { fieldDeclaration.setFlags(fieldDeclaration.getFlags() | ASTNode.MALFORMED); } break; case AST.JLS3 : this.scanner.resetTo(fieldDecl.declarationSourceStart, fieldDecl.sourceStart); this.setModifiers(fieldDeclaration, fieldDecl.annotations); } } protected void setModifiers(org.aspectj.org.eclipse.jdt.core.dom.InterTypeFieldDeclaration fieldDeclaration, InterTypeFieldDeclaration fieldDecl) { // ajh02: method added switch(this.ast.apiLevel) { case AST.JLS2_INTERNAL : fieldDeclaration.internalSetModifiers(fieldDecl.declaredModifiers & ExtraCompilerModifiers.AccJustFlag); if (fieldDecl.annotations != null) { fieldDeclaration.setFlags(fieldDeclaration.getFlags() | ASTNode.MALFORMED); } break; case AST.JLS3 : this.scanner.resetTo(fieldDecl.declarationSourceStart, fieldDecl.sourceStart); this.setModifiers(fieldDeclaration, fieldDecl.annotations); } } /** * @param initializer * @param oldInitializer */ protected void setModifiers(Initializer initializer, org.aspectj.org.eclipse.jdt.internal.compiler.ast.Initializer oldInitializer) { switch(this.ast.apiLevel) { case AST.JLS2_INTERNAL: initializer.internalSetModifiers(oldInitializer.modifiers & ExtraCompilerModifiers.AccJustFlag); if (oldInitializer.annotations != null) { initializer.setFlags(initializer.getFlags() | ASTNode.MALFORMED); } break; case AST.JLS3 : this.scanner.resetTo(oldInitializer.declarationSourceStart, oldInitializer.bodyStart); this.setModifiers(initializer, oldInitializer.annotations); } } /** * @param methodDecl * @param methodDeclaration */ protected void setModifiers(MethodDeclaration methodDecl, AbstractMethodDeclaration methodDeclaration) { switch(this.ast.apiLevel) { case AST.JLS2_INTERNAL : if (methodDeclaration instanceof InterTypeDeclaration) { methodDecl.internalSetModifiers(((InterTypeDeclaration)methodDeclaration).declaredModifiers & ExtraCompilerModifiers.AccJustFlag); } else { methodDecl.internalSetModifiers(methodDeclaration.modifiers & ExtraCompilerModifiers.AccJustFlag); } if (methodDeclaration.annotations != null) { methodDecl.setFlags(methodDecl.getFlags() | ASTNode.MALFORMED); } break; case AST.JLS3 : this.scanner.resetTo(methodDeclaration.declarationSourceStart, methodDeclaration.sourceStart); this.setModifiers(methodDecl, methodDeclaration.annotations); } } protected void setModifiers(org.aspectj.org.eclipse.jdt.core.dom.PointcutDeclaration pointcutDecl, PointcutDeclaration pointcutDeclaration) { // ajh02: method added switch(this.ast.apiLevel) { case AST.JLS2_INTERNAL : pointcutDecl.internalSetModifiers(pointcutDeclaration.modifiers & ExtraCompilerModifiers.AccJustFlag); if (pointcutDeclaration.annotations != null) { pointcutDecl.setFlags(pointcutDecl.getFlags() | ASTNode.MALFORMED); } break; case AST.JLS3 : this.scanner.resetTo(pointcutDeclaration.declarationSourceStart, pointcutDeclaration.sourceStart); this.setModifiers(pointcutDecl, pointcutDeclaration.annotations); } } /** * @param variableDecl * @param argument */ protected void setModifiers(SingleVariableDeclaration variableDecl, Argument argument) { switch(this.ast.apiLevel) { case AST.JLS2_INTERNAL : variableDecl.internalSetModifiers(argument.modifiers & ExtraCompilerModifiers.AccJustFlag); if (argument.annotations != null) { variableDecl.setFlags(variableDecl.getFlags() | ASTNode.MALFORMED); } break; case AST.JLS3 : this.scanner.resetTo(argument.declarationSourceStart, argument.sourceStart); org.aspectj.org.eclipse.jdt.internal.compiler.ast.Annotation[] annotations = argument.annotations; int indexInAnnotations = 0; try { int token; while ((token = this.scanner.getNextToken()) != TerminalTokens.TokenNameEOF) { IExtendedModifier modifier = null; switch(token) { case TerminalTokens.TokenNameabstract: modifier = createModifier(Modifier.ModifierKeyword.ABSTRACT_KEYWORD); break; case TerminalTokens.TokenNamepublic: modifier = createModifier(Modifier.ModifierKeyword.PUBLIC_KEYWORD); break; case TerminalTokens.TokenNamestatic: modifier = createModifier(Modifier.ModifierKeyword.STATIC_KEYWORD); break; case TerminalTokens.TokenNameprotected: modifier = createModifier(Modifier.ModifierKeyword.PROTECTED_KEYWORD); break; case TerminalTokens.TokenNameprivate: modifier = createModifier(Modifier.ModifierKeyword.PRIVATE_KEYWORD); break; case TerminalTokens.TokenNamefinal: modifier = createModifier(Modifier.ModifierKeyword.FINAL_KEYWORD); break; case TerminalTokens.TokenNamenative: modifier = createModifier(Modifier.ModifierKeyword.NATIVE_KEYWORD); break; case TerminalTokens.TokenNamesynchronized: modifier = createModifier(Modifier.ModifierKeyword.SYNCHRONIZED_KEYWORD); break; case TerminalTokens.TokenNametransient: modifier = createModifier(Modifier.ModifierKeyword.TRANSIENT_KEYWORD); break; case TerminalTokens.TokenNamevolatile: modifier = createModifier(Modifier.ModifierKeyword.VOLATILE_KEYWORD); break; case TerminalTokens.TokenNamestrictfp: modifier = createModifier(Modifier.ModifierKeyword.STRICTFP_KEYWORD); break; case TerminalTokens.TokenNameAT : // we have an annotation if (annotations != null && indexInAnnotations < annotations.length) { org.aspectj.org.eclipse.jdt.internal.compiler.ast.Annotation annotation = annotations[indexInAnnotations++]; modifier = super.convert(annotation); this.scanner.resetTo(annotation.declarationSourceEnd + 1, this.compilationUnitSourceLength); } break; case TerminalTokens.TokenNameCOMMENT_BLOCK : case TerminalTokens.TokenNameCOMMENT_LINE : case TerminalTokens.TokenNameCOMMENT_JAVADOC : break; default : return; } if (modifier != null) { variableDecl.modifiers().add(modifier); } } } catch(InvalidInputException e) { // ignore } } } protected void setModifiers(SingleVariableDeclaration variableDecl, LocalDeclaration localDeclaration) { switch(this.ast.apiLevel) { case AST.JLS2_INTERNAL : variableDecl.internalSetModifiers(localDeclaration.modifiers & ExtraCompilerModifiers.AccJustFlag); if (localDeclaration.annotations != null) { variableDecl.setFlags(variableDecl.getFlags() | ASTNode.MALFORMED); } break; case AST.JLS3 : this.scanner.resetTo(localDeclaration.declarationSourceStart, localDeclaration.sourceStart); org.aspectj.org.eclipse.jdt.internal.compiler.ast.Annotation[] annotations = localDeclaration.annotations; int indexInAnnotations = 0; try { int token; while ((token = this.scanner.getNextToken()) != TerminalTokens.TokenNameEOF) { IExtendedModifier modifier = null; switch(token) { case TerminalTokens.TokenNameabstract: modifier = createModifier(Modifier.ModifierKeyword.ABSTRACT_KEYWORD); break; case TerminalTokens.TokenNamepublic: modifier = createModifier(Modifier.ModifierKeyword.PUBLIC_KEYWORD); break; case TerminalTokens.TokenNamestatic: modifier = createModifier(Modifier.ModifierKeyword.STATIC_KEYWORD); break; case TerminalTokens.TokenNameprotected: modifier = createModifier(Modifier.ModifierKeyword.PROTECTED_KEYWORD); break; case TerminalTokens.TokenNameprivate: modifier = createModifier(Modifier.ModifierKeyword.PRIVATE_KEYWORD); break; case TerminalTokens.TokenNamefinal: modifier = createModifier(Modifier.ModifierKeyword.FINAL_KEYWORD); break; case TerminalTokens.TokenNamenative: modifier = createModifier(Modifier.ModifierKeyword.NATIVE_KEYWORD); break; case TerminalTokens.TokenNamesynchronized: modifier = createModifier(Modifier.ModifierKeyword.SYNCHRONIZED_KEYWORD); break; case TerminalTokens.TokenNametransient: modifier = createModifier(Modifier.ModifierKeyword.TRANSIENT_KEYWORD); break; case TerminalTokens.TokenNamevolatile: modifier = createModifier(Modifier.ModifierKeyword.VOLATILE_KEYWORD); break; case TerminalTokens.TokenNamestrictfp: modifier = createModifier(Modifier.ModifierKeyword.STRICTFP_KEYWORD); break; case TerminalTokens.TokenNameAT : // we have an annotation if (annotations != null && indexInAnnotations < annotations.length) { org.aspectj.org.eclipse.jdt.internal.compiler.ast.Annotation annotation = annotations[indexInAnnotations++]; modifier = super.convert(annotation); this.scanner.resetTo(annotation.declarationSourceEnd + 1, this.compilationUnitSourceLength); } break; case TerminalTokens.TokenNameCOMMENT_BLOCK : case TerminalTokens.TokenNameCOMMENT_LINE : case TerminalTokens.TokenNameCOMMENT_JAVADOC : break; default : return; } if (modifier != null) { variableDecl.modifiers().add(modifier); } } } catch(InvalidInputException e) { // ignore } } } /** * @param typeDecl * @param typeDeclaration */ protected void setModifiers(TypeDeclaration typeDecl, org.aspectj.org.eclipse.jdt.internal.compiler.ast.TypeDeclaration typeDeclaration) { switch(this.ast.apiLevel) { case AST.JLS2_INTERNAL : int modifiers = typeDeclaration.modifiers; modifiers &= ~ClassFileConstants.AccInterface; // remove AccInterface flags modifiers &= ExtraCompilerModifiers.AccJustFlag; typeDecl.internalSetModifiers(modifiers); if (typeDeclaration.annotations != null) { typeDecl.setFlags(typeDecl.getFlags() | ASTNode.MALFORMED); } break; case AST.JLS3 : this.scanner.resetTo(typeDeclaration.declarationSourceStart, typeDeclaration.sourceStart); this.setModifiers(typeDecl, typeDeclaration.annotations); } } /** * @param variableDeclarationExpression * @param localDeclaration */ protected void setModifiers(VariableDeclarationExpression variableDeclarationExpression, LocalDeclaration localDeclaration) { switch(this.ast.apiLevel) { case AST.JLS2_INTERNAL : int modifiers = localDeclaration.modifiers & ExtraCompilerModifiers.AccJustFlag; modifiers &= ~ExtraCompilerModifiers.AccBlankFinal; variableDeclarationExpression.internalSetModifiers(modifiers); if (localDeclaration.annotations != null) { variableDeclarationExpression.setFlags(variableDeclarationExpression.getFlags() | ASTNode.MALFORMED); } break; case AST.JLS3 : this.scanner.resetTo(localDeclaration.declarationSourceStart, localDeclaration.sourceStart); org.aspectj.org.eclipse.jdt.internal.compiler.ast.Annotation[] annotations = localDeclaration.annotations; int indexInAnnotations = 0; try { int token; while ((token = this.scanner.getNextToken()) != TerminalTokens.TokenNameEOF) { IExtendedModifier modifier = null; switch(token) { case TerminalTokens.TokenNameabstract: modifier = createModifier(Modifier.ModifierKeyword.ABSTRACT_KEYWORD); break; case TerminalTokens.TokenNamepublic: modifier = createModifier(Modifier.ModifierKeyword.PUBLIC_KEYWORD); break; case TerminalTokens.TokenNamestatic: modifier = createModifier(Modifier.ModifierKeyword.STATIC_KEYWORD); break; case TerminalTokens.TokenNameprotected: modifier = createModifier(Modifier.ModifierKeyword.PROTECTED_KEYWORD); break; case TerminalTokens.TokenNameprivate: modifier = createModifier(Modifier.ModifierKeyword.PRIVATE_KEYWORD); break; case TerminalTokens.TokenNamefinal: modifier = createModifier(Modifier.ModifierKeyword.FINAL_KEYWORD); break; case TerminalTokens.TokenNamenative: modifier = createModifier(Modifier.ModifierKeyword.NATIVE_KEYWORD); break; case TerminalTokens.TokenNamesynchronized: modifier = createModifier(Modifier.ModifierKeyword.SYNCHRONIZED_KEYWORD); break; case TerminalTokens.TokenNametransient: modifier = createModifier(Modifier.ModifierKeyword.TRANSIENT_KEYWORD); break; case TerminalTokens.TokenNamevolatile: modifier = createModifier(Modifier.ModifierKeyword.VOLATILE_KEYWORD); break; case TerminalTokens.TokenNamestrictfp: modifier = createModifier(Modifier.ModifierKeyword.STRICTFP_KEYWORD); break; case TerminalTokens.TokenNameAT : // we have an annotation if (annotations != null && indexInAnnotations < annotations.length) { org.aspectj.org.eclipse.jdt.internal.compiler.ast.Annotation annotation = annotations[indexInAnnotations++]; modifier = super.convert(annotation); this.scanner.resetTo(annotation.declarationSourceEnd + 1, this.compilationUnitSourceLength); } break; case TerminalTokens.TokenNameCOMMENT_BLOCK : case TerminalTokens.TokenNameCOMMENT_LINE : case TerminalTokens.TokenNameCOMMENT_JAVADOC : break; default : return; } if (modifier != null) { variableDeclarationExpression.modifiers().add(modifier); } } } catch(InvalidInputException e) { // ignore } } } /** * @param variableDeclarationStatement * @param localDeclaration */ protected void setModifiers(VariableDeclarationStatement variableDeclarationStatement, LocalDeclaration localDeclaration) { switch(this.ast.apiLevel) { case AST.JLS2_INTERNAL : int modifiers = localDeclaration.modifiers & ExtraCompilerModifiers.AccJustFlag; modifiers &= ~ExtraCompilerModifiers.AccBlankFinal; variableDeclarationStatement.internalSetModifiers(modifiers); if (localDeclaration.annotations != null) { variableDeclarationStatement.setFlags(variableDeclarationStatement.getFlags() | ASTNode.MALFORMED); } break; case AST.JLS3 : this.scanner.resetTo(localDeclaration.declarationSourceStart, localDeclaration.sourceStart); org.aspectj.org.eclipse.jdt.internal.compiler.ast.Annotation[] annotations = localDeclaration.annotations; int indexInAnnotations = 0; try { int token; while ((token = this.scanner.getNextToken()) != TerminalTokens.TokenNameEOF) { IExtendedModifier modifier = null; switch(token) { case TerminalTokens.TokenNameabstract: modifier = createModifier(Modifier.ModifierKeyword.ABSTRACT_KEYWORD); break; case TerminalTokens.TokenNamepublic: modifier = createModifier(Modifier.ModifierKeyword.PUBLIC_KEYWORD); break; case TerminalTokens.TokenNamestatic: modifier = createModifier(Modifier.ModifierKeyword.STATIC_KEYWORD); break; case TerminalTokens.TokenNameprotected: modifier = createModifier(Modifier.ModifierKeyword.PROTECTED_KEYWORD); break; case TerminalTokens.TokenNameprivate: modifier = createModifier(Modifier.ModifierKeyword.PRIVATE_KEYWORD); break; case TerminalTokens.TokenNamefinal: modifier = createModifier(Modifier.ModifierKeyword.FINAL_KEYWORD); break; case TerminalTokens.TokenNamenative: modifier = createModifier(Modifier.ModifierKeyword.NATIVE_KEYWORD); break; case TerminalTokens.TokenNamesynchronized: modifier = createModifier(Modifier.ModifierKeyword.SYNCHRONIZED_KEYWORD); break; case TerminalTokens.TokenNametransient: modifier = createModifier(Modifier.ModifierKeyword.TRANSIENT_KEYWORD); break; case TerminalTokens.TokenNamevolatile: modifier = createModifier(Modifier.ModifierKeyword.VOLATILE_KEYWORD); break; case TerminalTokens.TokenNamestrictfp: modifier = createModifier(Modifier.ModifierKeyword.STRICTFP_KEYWORD); break; case TerminalTokens.TokenNameAT : // we have an annotation if (annotations != null && indexInAnnotations < annotations.length) { org.aspectj.org.eclipse.jdt.internal.compiler.ast.Annotation annotation = annotations[indexInAnnotations++]; modifier = super.convert(annotation); this.scanner.resetTo(annotation.declarationSourceEnd + 1, this.compilationUnitSourceLength); } break; case TerminalTokens.TokenNameCOMMENT_BLOCK : case TerminalTokens.TokenNameCOMMENT_LINE : case TerminalTokens.TokenNameCOMMENT_JAVADOC : break; default : return; } if (modifier != null) { variableDeclarationStatement.modifiers().add(modifier); } } } catch(InvalidInputException e) { // ignore } } } protected QualifiedName setQualifiedNameNameAndSourceRanges(char[][] typeName, long[] positions, org.aspectj.org.eclipse.jdt.internal.compiler.ast.ASTNode node) { int length = typeName.length; final SimpleName firstToken = new SimpleName(this.ast); firstToken.internalSetIdentifier(new String(typeName[0])); firstToken.index = 1; int start0 = (int)(positions[0]>>>32); int start = start0; int end = (int)(positions[0] & 0xFFFFFFFF); firstToken.setSourceRange(start, end - start + 1); final SimpleName secondToken = new SimpleName(this.ast); secondToken.internalSetIdentifier(new String(typeName[1])); secondToken.index = 2; start = (int)(positions[1]>>>32); end = (int)(positions[1] & 0xFFFFFFFF); secondToken.setSourceRange(start, end - start + 1); QualifiedName qualifiedName = new QualifiedName(this.ast); qualifiedName.setQualifier(firstToken); qualifiedName.setName(secondToken); if (this.resolveBindings) { recordNodes(qualifiedName, node); recordPendingNameScopeResolution(qualifiedName); recordNodes(firstToken, node); recordNodes(secondToken, node); recordPendingNameScopeResolution(firstToken); recordPendingNameScopeResolution(secondToken); } qualifiedName.index = 2; qualifiedName.setSourceRange(start0, end - start0 + 1); SimpleName newPart = null; for (int i = 2; i < length; i++) { newPart = new SimpleName(this.ast); newPart.internalSetIdentifier(new String(typeName[i])); newPart.index = i + 1; start = (int)(positions[i]>>>32); end = (int)(positions[i] & 0xFFFFFFFF); newPart.setSourceRange(start, end - start + 1); QualifiedName qualifiedName2 = new QualifiedName(this.ast); qualifiedName2.setQualifier(qualifiedName); qualifiedName2.setName(newPart); qualifiedName = qualifiedName2; qualifiedName.index = newPart.index; qualifiedName.setSourceRange(start0, end - start0 + 1); if (this.resolveBindings) { recordNodes(qualifiedName, node); recordNodes(newPart, node); recordPendingNameScopeResolution(qualifiedName); recordPendingNameScopeResolution(newPart); } } QualifiedName name = qualifiedName; if (this.resolveBindings) { recordNodes(name, node); recordPendingNameScopeResolution(name); } return name; } protected QualifiedName setQualifiedNameNameAndSourceRanges(char[][] typeName, long[] positions, int endingIndex, org.aspectj.org.eclipse.jdt.internal.compiler.ast.ASTNode node) { int length = endingIndex + 1; final SimpleName firstToken = new SimpleName(this.ast); firstToken.internalSetIdentifier(new String(typeName[0])); firstToken.index = 1; int start0 = (int)(positions[0]>>>32); int start = start0; int end = (int) positions[0]; firstToken.setSourceRange(start, end - start + 1); final SimpleName secondToken = new SimpleName(this.ast); secondToken.internalSetIdentifier(new String(typeName[1])); secondToken.index = 2; start = (int)(positions[1]>>>32); end = (int) positions[1]; secondToken.setSourceRange(start, end - start + 1); QualifiedName qualifiedName = new QualifiedName(this.ast); qualifiedName.setQualifier(firstToken); qualifiedName.setName(secondToken); if (this.resolveBindings) { recordNodes(qualifiedName, node); recordPendingNameScopeResolution(qualifiedName); recordNodes(firstToken, node); recordNodes(secondToken, node); recordPendingNameScopeResolution(firstToken); recordPendingNameScopeResolution(secondToken); } qualifiedName.index = 2; qualifiedName.setSourceRange(start0, end - start0 + 1); SimpleName newPart = null; for (int i = 2; i < length; i++) { newPart = new SimpleName(this.ast); newPart.internalSetIdentifier(new String(typeName[i])); newPart.index = i + 1; start = (int)(positions[i]>>>32); end = (int) positions[i]; newPart.setSourceRange(start, end - start + 1); QualifiedName qualifiedName2 = new QualifiedName(this.ast); qualifiedName2.setQualifier(qualifiedName); qualifiedName2.setName(newPart); qualifiedName = qualifiedName2; qualifiedName.index = newPart.index; qualifiedName.setSourceRange(start0, end - start0 + 1); if (this.resolveBindings) { recordNodes(qualifiedName, node); recordNodes(newPart, node); recordPendingNameScopeResolution(qualifiedName); recordPendingNameScopeResolution(newPart); } } if (newPart == null && this.resolveBindings) { recordNodes(qualifiedName, node); recordPendingNameScopeResolution(qualifiedName); } return qualifiedName; } protected void setTypeNameForAnnotation(org.aspectj.org.eclipse.jdt.internal.compiler.ast.Annotation compilerAnnotation, Annotation annotation) { TypeReference typeReference = compilerAnnotation.type; if (typeReference instanceof QualifiedTypeReference) { QualifiedTypeReference qualifiedTypeReference = (QualifiedTypeReference) typeReference; char[][] tokens = qualifiedTypeReference.tokens; long[] positions = qualifiedTypeReference.sourcePositions; // QualifiedName annotation.setTypeName(setQualifiedNameNameAndSourceRanges(tokens, positions, typeReference)); } else { SingleTypeReference singleTypeReference = (SingleTypeReference) typeReference; final SimpleName name = new SimpleName(this.ast); name.internalSetIdentifier(new String(singleTypeReference.token)); int start = singleTypeReference.sourceStart; int end = singleTypeReference.sourceEnd; name.setSourceRange(start, end - start + 1); annotation.setTypeName(name); if (this.resolveBindings) { recordNodes(name, typeReference); } } } protected void setTypeForField(FieldDeclaration fieldDeclaration, Type type, int extraDimension) { if (extraDimension != 0) { if (type.isArrayType()) { ArrayType arrayType = (ArrayType) type; int remainingDimensions = arrayType.getDimensions() - extraDimension; if (remainingDimensions == 0) { // the dimensions are after the name so the type of the fieldDeclaration is a simpleType Type elementType = arrayType.getElementType(); // cut the child loose from its parent (without creating garbage) elementType.setParent(null, null); this.ast.getBindingResolver().updateKey(type, elementType); fieldDeclaration.setType(elementType); } else { int start = type.getStartPosition(); ArrayType subarrayType = arrayType; int index = extraDimension; while (index > 0) { subarrayType = (ArrayType) subarrayType.getComponentType(); index--; } int end = retrieveProperRightBracketPosition(remainingDimensions, start); subarrayType.setSourceRange(start, end - start + 1); // cut the child loose from its parent (without creating garbage) subarrayType.setParent(null, null); fieldDeclaration.setType(subarrayType); updateInnerPositions(subarrayType, remainingDimensions); this.ast.getBindingResolver().updateKey(type, subarrayType); } } else { fieldDeclaration.setType(type); } } else { if (type.isArrayType()) { // update positions of the component types of the array type int dimensions = ((ArrayType) type).getDimensions(); updateInnerPositions(type, dimensions); } fieldDeclaration.setType(type); } } protected void setTypeForAroundAdviceDeclaration(AroundAdviceDeclaration adviceDeclaration, Type type) { // ajh02: method added switch(this.ast.apiLevel) { case AST.JLS2_INTERNAL : adviceDeclaration.internalSetReturnType(type); break; case AST.JLS3 : adviceDeclaration.setReturnType2(type); break; } } protected void setTypeForMethodDeclaration(MethodDeclaration methodDeclaration, Type type, int extraDimension) { if (extraDimension != 0) { if (type.isArrayType()) { ArrayType arrayType = (ArrayType) type; int remainingDimensions = arrayType.getDimensions() - extraDimension; if (remainingDimensions == 0) { // the dimensions are after the name so the type of the fieldDeclaration is a simpleType Type elementType = arrayType.getElementType(); // cut the child loose from its parent (without creating garbage) elementType.setParent(null, null); this.ast.getBindingResolver().updateKey(type, elementType); switch(this.ast.apiLevel) { case AST.JLS2_INTERNAL : methodDeclaration.internalSetReturnType(elementType); break; case AST.JLS3 : methodDeclaration.setReturnType2(elementType); break; } } else { int start = type.getStartPosition(); ArrayType subarrayType = arrayType; int index = extraDimension; while (index > 0) { subarrayType = (ArrayType) subarrayType.getComponentType(); index--; } int end = retrieveProperRightBracketPosition(remainingDimensions, start); subarrayType.setSourceRange(start, end - start + 1); // cut the child loose from its parent (without creating garbage) subarrayType.setParent(null, null); updateInnerPositions(subarrayType, remainingDimensions); switch(this.ast.apiLevel) { case AST.JLS2_INTERNAL : methodDeclaration.internalSetReturnType(subarrayType); break; case AST.JLS3 : methodDeclaration.setReturnType2(subarrayType); break; } this.ast.getBindingResolver().updateKey(type, subarrayType); } } else { switch(this.ast.apiLevel) { case AST.JLS2_INTERNAL : methodDeclaration.internalSetReturnType(type); break; case AST.JLS3 : methodDeclaration.setReturnType2(type); break; } } } else { switch(this.ast.apiLevel) { case AST.JLS2_INTERNAL : methodDeclaration.internalSetReturnType(type); break; case AST.JLS3 : methodDeclaration.setReturnType2(type); break; } } } protected void setTypeForMethodDeclaration(AnnotationTypeMemberDeclaration annotationTypeMemberDeclaration, Type type, int extraDimension) { annotationTypeMemberDeclaration.setType(type); } protected void setTypeForSingleVariableDeclaration(SingleVariableDeclaration singleVariableDeclaration, Type type, int extraDimension) { if (extraDimension != 0) { if (type.isArrayType()) { ArrayType arrayType = (ArrayType) type; int remainingDimensions = arrayType.getDimensions() - extraDimension; if (remainingDimensions == 0) { // the dimensions are after the name so the type of the fieldDeclaration is a simpleType Type elementType = arrayType.getElementType(); // cut the child loose from its parent (without creating garbage) elementType.setParent(null, null); this.ast.getBindingResolver().updateKey(type, elementType); singleVariableDeclaration.setType(elementType); } else { int start = type.getStartPosition(); ArrayType subarrayType = arrayType; int index = extraDimension; while (index > 0) { subarrayType = (ArrayType) subarrayType.getComponentType(); index--; } int end = retrieveProperRightBracketPosition(remainingDimensions, start); subarrayType.setSourceRange(start, end - start + 1); // cut the child loose from its parent (without creating garbage) subarrayType.setParent(null, null); updateInnerPositions(subarrayType, remainingDimensions); singleVariableDeclaration.setType(subarrayType); this.ast.getBindingResolver().updateKey(type, subarrayType); } } else { singleVariableDeclaration.setType(type); } } else { singleVariableDeclaration.setType(type); } } protected void setTypeForVariableDeclarationExpression(VariableDeclarationExpression variableDeclarationExpression, Type type, int extraDimension) { if (extraDimension != 0) { if (type.isArrayType()) { ArrayType arrayType = (ArrayType) type; int remainingDimensions = arrayType.getDimensions() - extraDimension; if (remainingDimensions == 0) { // the dimensions are after the name so the type of the fieldDeclaration is a simpleType Type elementType = arrayType.getElementType(); // cut the child loose from its parent (without creating garbage) elementType.setParent(null, null); this.ast.getBindingResolver().updateKey(type, elementType); variableDeclarationExpression.setType(elementType); } else { int start = type.getStartPosition(); ArrayType subarrayType = arrayType; int index = extraDimension; while (index > 0) { subarrayType = (ArrayType) subarrayType.getComponentType(); index--; } int end = retrieveProperRightBracketPosition(remainingDimensions, start); subarrayType.setSourceRange(start, end - start + 1); // cut the child loose from its parent (without creating garbage) subarrayType.setParent(null, null); updateInnerPositions(subarrayType, remainingDimensions); variableDeclarationExpression.setType(subarrayType); this.ast.getBindingResolver().updateKey(type, subarrayType); } } else { variableDeclarationExpression.setType(type); } } else { variableDeclarationExpression.setType(type); } } protected void setTypeForVariableDeclarationStatement(VariableDeclarationStatement variableDeclarationStatement, Type type, int extraDimension) { if (extraDimension != 0) { if (type.isArrayType()) { ArrayType arrayType = (ArrayType) type; int remainingDimensions = arrayType.getDimensions() - extraDimension; if (remainingDimensions == 0) { // the dimensions are after the name so the type of the fieldDeclaration is a simpleType Type elementType = arrayType.getElementType(); // cut the child loose from its parent (without creating garbage) elementType.setParent(null, null); this.ast.getBindingResolver().updateKey(type, elementType); variableDeclarationStatement.setType(elementType); } else { int start = type.getStartPosition(); ArrayType subarrayType = arrayType; int index = extraDimension; while (index > 0) { subarrayType = (ArrayType) subarrayType.getComponentType(); index--; } int end = retrieveProperRightBracketPosition(remainingDimensions, start); subarrayType.setSourceRange(start, end - start + 1); // cut the child loose from its parent (without creating garbage) subarrayType.setParent(null, null); updateInnerPositions(subarrayType, remainingDimensions); variableDeclarationStatement.setType(subarrayType); this.ast.getBindingResolver().updateKey(type, subarrayType); } } else { variableDeclarationStatement.setType(type); } } else { variableDeclarationStatement.setType(type); } } protected void updateInnerPositions(Type type, int dimensions) { if (dimensions > 1) { // need to set positions for intermediate array type see 42839 int start = type.getStartPosition(); Type currentComponentType = ((ArrayType) type).getComponentType(); int searchedDimension = dimensions - 1; int rightBracketEndPosition = start; while (currentComponentType.isArrayType()) { rightBracketEndPosition = retrieveProperRightBracketPosition(searchedDimension, start); currentComponentType.setSourceRange(start, rightBracketEndPosition - start + 1); currentComponentType = ((ArrayType) currentComponentType).getComponentType(); searchedDimension--; } } } }
203,384
Bug 203384 AST: Type information not exposed on itmd, itfd...
The Types: org/aspectj/org/eclipse/jdt/core/dom/InterTypeFieldDeclaration.java org/aspectj/org/eclipse/jdt/core/dom/InterTypeMethodDeclaration.java Which can be returned by visiting the AjAST tree do not expose the name of the type on which the method or field is added. I require this information in the project I'm currently working on, and would appreciate if it was added.
resolved fixed
114db35
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2008-01-22T18:48:29Z"
"2007-09-14T00:33:20Z"
org.aspectj.ajdt.core/src/org/aspectj/org/eclipse/jdt/core/dom/InterTypeFieldDeclaration.java
/******************************************************************************* * Copyright (c) 2000, 2005 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.aspectj.org.eclipse.jdt.core.dom; /** * InterTypeFieldDeclaration DOM AST node. * has: * everything FieldDeclarations have * * Refused Bequest: * has the variableDeclarationFragments list * it redundantly inherits from FieldDeclaration * as fields can be declared like "int b; int a = b = 5;" * but ITD fields can't. * Note: * should also have the name of the type it was declared on! * @author ajh02 */ public class InterTypeFieldDeclaration extends FieldDeclaration { InterTypeFieldDeclaration(AST ast) { super(ast); } ASTNode clone0(AST target) { InterTypeFieldDeclaration result = new InterTypeFieldDeclaration(target); result.setSourceRange(this.getStartPosition(), this.getLength()); result.setJavadoc( (Javadoc) ASTNode.copySubtree(target, getJavadoc())); if (this.ast.apiLevel == AST.JLS2_INTERNAL) { result.internalSetModifiers(getModifiers()); } if (this.ast.apiLevel >= AST.JLS3) { result.modifiers().addAll(ASTNode.copySubtrees(target, modifiers())); } result.setType((Type) getType().clone(target)); result.fragments().addAll( ASTNode.copySubtrees(target, fragments())); return result; } void accept0(ASTVisitor visitor) { if (visitor instanceof AjASTVisitor) { boolean visitChildren = ((AjASTVisitor)visitor).visit(this); if (visitChildren) { // visit children in normal left to right reading order acceptChild(visitor, getJavadoc()); if (this.ast.apiLevel >= AST.JLS3) { acceptChildren(visitor, this.modifiers); } acceptChild(visitor, getType()); acceptChildren(visitor, this.variableDeclarationFragments); } ((AjASTVisitor)visitor).endVisit(this); } } }
203,384
Bug 203384 AST: Type information not exposed on itmd, itfd...
The Types: org/aspectj/org/eclipse/jdt/core/dom/InterTypeFieldDeclaration.java org/aspectj/org/eclipse/jdt/core/dom/InterTypeMethodDeclaration.java Which can be returned by visiting the AjAST tree do not expose the name of the type on which the method or field is added. I require this information in the project I'm currently working on, and would appreciate if it was added.
resolved fixed
114db35
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2008-01-22T18:48:29Z"
"2007-09-14T00:33:20Z"
org.aspectj.ajdt.core/src/org/aspectj/org/eclipse/jdt/core/dom/InterTypeMethodDeclaration.java
/******************************************************************************* * Copyright (c) 2000, 2005 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.aspectj.org.eclipse.jdt.core.dom; import org.aspectj.org.eclipse.jdt.core.dom.AST; import org.aspectj.org.eclipse.jdt.core.dom.ASTNode; import org.aspectj.org.eclipse.jdt.core.dom.ASTVisitor; import org.aspectj.org.eclipse.jdt.core.dom.Block; import org.aspectj.org.eclipse.jdt.core.dom.Javadoc; import org.aspectj.org.eclipse.jdt.core.dom.Type; /** * InterTypeMethodDeclaration DOM AST node. * has: * everything MethodDeclarations have * * Note: * should also have the name of the type it's declared on! * @author ajh02 */ public class InterTypeMethodDeclaration extends MethodDeclaration { InterTypeMethodDeclaration(AST ast) { super(ast); } /* (omit javadoc for this method) * Method declared on ASTNode. */ ASTNode clone0(AST target) { InterTypeMethodDeclaration result = new InterTypeMethodDeclaration(target); result.setSourceRange(this.getStartPosition(), this.getLength()); result.setJavadoc( (Javadoc) ASTNode.copySubtree(target, getJavadoc())); if (this.ast.apiLevel == AST.JLS2_INTERNAL) { result.internalSetModifiers(getModifiers()); result.setReturnType( (Type) ASTNode.copySubtree(target, getReturnType())); } if (this.ast.apiLevel >= AST.JLS3) { result.modifiers().addAll(ASTNode.copySubtrees(target, modifiers())); result.typeParameters().addAll( ASTNode.copySubtrees(target, typeParameters())); result.setReturnType2( (Type) ASTNode.copySubtree(target, getReturnType2())); } result.setConstructor(isConstructor()); result.setExtraDimensions(getExtraDimensions()); result.setName((SimpleName) getName().clone(target)); result.parameters().addAll( ASTNode.copySubtrees(target, parameters())); result.thrownExceptions().addAll( ASTNode.copySubtrees(target, thrownExceptions())); result.setBody( (Block) ASTNode.copySubtree(target, getBody())); return result; } /* (omit javadoc for this method) * Method declared on ASTNode. */ void accept0(ASTVisitor visitor) { if (visitor instanceof AjASTVisitor) { AjASTVisitor ajvis = (AjASTVisitor)visitor; boolean visitChildren = ajvis.visit(this); if (visitChildren) { // visit children in normal left to right reading order acceptChild(ajvis, getJavadoc()); if (this.ast.apiLevel == AST.JLS2_INTERNAL) { acceptChild(ajvis, getReturnType()); } else { acceptChildren(ajvis, this.modifiers); acceptChildren(ajvis, (NodeList)this.typeParameters()); acceptChild(ajvis, getReturnType2()); } // n.b. visit return type even for constructors acceptChild(ajvis, getName()); acceptChildren(ajvis, this.parameters); acceptChildren(ajvis, (NodeList)this.thrownExceptions()); acceptChild(ajvis, getBody()); } ajvis.endVisit(this); } } }
210,848
Bug 210848 Fix javadoc for ProceedingJoinPoint.proceed(Object[])
null
resolved fixed
b4715bc
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2008-02-21T01:05:35Z"
"2007-11-24T21:33:20Z"
runtime/src/org/aspectj/lang/ProceedingJoinPoint.java
/******************************************************************************* * Copyright (c) 2005 Contributors. * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Eclipse Public License v1.0 * which accompanies this distribution and is available at * http://eclipse.org/legal/epl-v10.html * * Contributors: * initial implementation Alexandre Vasseur *******************************************************************************/ package org.aspectj.lang; import org.aspectj.runtime.internal.AroundClosure; /** * ProceedingJoinPoint exposes the proceed(..) method in order to support around advice in @AJ aspects * * @author <a href="mailto:alex AT gnilux DOT com">Alexandre Vasseur</a> */ public interface ProceedingJoinPoint extends JoinPoint { /** * The joinpoint needs to know about its closure so that proceed can delegate to closure.run() * <p/> * This internal method should not be called directly, and won't be visible to the end-user when * packed in a jar (synthetic method) * * @param arc */ void set$AroundClosure(AroundClosure arc); /** * Proceed with the next advice or target method invocation * * @return * @throws Throwable */ public Object proceed() throws Throwable; /** * Proceed with the next advice or target method invocation * <p/> * The given args Object[] must be in the same order and size as the advice signature but * without the actual joinpoint instance * * @param args * @return * @throws Throwable */ public Object proceed(Object[] args) throws Throwable; }
220,172
Bug 220172 [compiler] NullpointerException during compile
null
resolved fixed
5beab0e
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2008-02-25T21:39:45Z"
"2008-02-25T11:46:40Z"
weaver/src/org/aspectj/weaver/Shadow.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Eclipse Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * PARC initial implementation * ******************************************************************/ package org.aspectj.weaver; import java.io.DataInputStream; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Set; import org.aspectj.asm.IRelationship; import org.aspectj.bridge.IMessage; import org.aspectj.bridge.ISourceLocation; import org.aspectj.bridge.Message; import org.aspectj.bridge.MessageUtil; import org.aspectj.bridge.WeaveMessage; import org.aspectj.lang.JoinPoint; import org.aspectj.util.PartialOrder; import org.aspectj.util.TypeSafeEnum; import org.aspectj.weaver.ast.Var; import org.aspectj.weaver.bcel.BcelAdvice; /* * The superclass of anything representing a the shadow of a join point. A shadow represents * some bit of code, and encompasses both entry and exit from that code. All shadows have a kind * and a signature. */ public abstract class Shadow { // every Shadow has a unique id, doesn't matter if it wraps... private static int nextShadowID = 100; // easier to spot than zero. private final Kind kind; private final Member signature; private Member matchingSignature; private ResolvedMember resolvedSignature; protected final Shadow enclosingShadow; protected List mungers = Collections.EMPTY_LIST; public int shadowId = nextShadowID++; // every time we build a shadow, it gets a new id // ---- protected Shadow(Kind kind, Member signature, Shadow enclosingShadow) { this.kind = kind; this.signature = signature; this.enclosingShadow = enclosingShadow; } // ---- public abstract World getIWorld(); public List /*ShadowMunger*/ getMungers() { return mungers; } /** * could this(*) pcd ever match */ public final boolean hasThis() { if (getKind().neverHasThis()) { return false; } else if (getKind().isEnclosingKind()) { return !getSignature().isStatic(); } else if (enclosingShadow == null) { return false; } else { return enclosingShadow.hasThis(); } } /** * the type of the this object here * * @throws IllegalStateException if there is no this here */ public final UnresolvedType getThisType() { if (!hasThis()) throw new IllegalStateException("no this"); if (getKind().isEnclosingKind()) { return getSignature().getDeclaringType(); } else { return enclosingShadow.getThisType(); } } /** * a var referencing this * * @throws IllegalStateException if there is no target here */ public abstract Var getThisVar(); /** * could target(*) pcd ever match */ public final boolean hasTarget() { if (getKind().neverHasTarget()) { return false; } else if (getKind().isTargetSameAsThis()) { return hasThis(); } else { return !getSignature().isStatic(); } } /** * the type of the target object here * * @throws IllegalStateException if there is no target here */ public final UnresolvedType getTargetType() { if (!hasTarget()) throw new IllegalStateException("no target"); return getSignature().getDeclaringType(); } /** * a var referencing the target * * @throws IllegalStateException if there is no target here */ public abstract Var getTargetVar(); public UnresolvedType[] getArgTypes() { if (getKind() == FieldSet) return new UnresolvedType[] { getSignature().getReturnType() }; return getSignature().getParameterTypes(); } public boolean isShadowForArrayConstructionJoinpoint() { return (getKind()==ConstructorCall && signature.getDeclaringType().isArray()); } public boolean isShadowForMonitor() { return (getKind()==SynchronizationLock || getKind()==SynchronizationUnlock); } // will return the right length array of ints depending on how many dimensions the array has public ResolvedType[] getArgumentTypesForArrayConstructionShadow() { String s = signature.getDeclaringType().getSignature(); int pos = s.indexOf("["); int dims = 1; while (pos<s.length()) { pos++; if (pos<s.length()) dims+=(s.charAt(pos)=='['?1:0); } if (dims==1) return new ResolvedType[]{ResolvedType.INT}; ResolvedType[] someInts = new ResolvedType[dims]; for (int i = 0; i < dims;i++) someInts[i] = ResolvedType.INT; return someInts; } public UnresolvedType[] getGenericArgTypes() { if (isShadowForArrayConstructionJoinpoint()) { return getArgumentTypesForArrayConstructionShadow(); } if (isShadowForMonitor()) { return UnresolvedType.ARRAY_WITH_JUST_OBJECT; } if (getKind() == FieldSet) return new UnresolvedType[] { getResolvedSignature().getGenericReturnType() }; return getResolvedSignature().getGenericParameterTypes(); } public UnresolvedType getArgType(int arg) { if (getKind() == FieldSet) return getSignature().getReturnType(); return getSignature().getParameterTypes()[arg]; } public int getArgCount() { if (getKind() == FieldSet) return 1; return getSignature() .getParameterTypes().length; } /** * Return name of the argument at position 'i' at this shadow. This does not * make sense for all shadows - but can be useful in the case of, for example, * method-execution. * @return null if it cannot be determined */ public String getArgName(int i,World w) { String [] names = getSignature().getParameterNames(w); if (names==null || i>=names.length) return null; return names[i]; } public abstract UnresolvedType getEnclosingType(); public abstract Var getArgVar(int i); public abstract Var getThisJoinPointVar(); public abstract Var getThisJoinPointStaticPartVar(); public abstract Var getThisEnclosingJoinPointStaticPartVar(); // annotation variables public abstract Var getKindedAnnotationVar(UnresolvedType forAnnotationType); public abstract Var getWithinAnnotationVar(UnresolvedType forAnnotationType); public abstract Var getWithinCodeAnnotationVar(UnresolvedType forAnnotationType); public abstract Var getThisAnnotationVar(UnresolvedType forAnnotationType); public abstract Var getTargetAnnotationVar(UnresolvedType forAnnotationType); public abstract Var getArgAnnotationVar(int i, UnresolvedType forAnnotationType); public abstract Member getEnclosingCodeSignature(); /** returns the kind of shadow this is, representing what happens under this shadow */ public Kind getKind() { return kind; } /** returns the signature of the thing under this shadow */ public Member getSignature() { return signature; } /** * returns the signature of the thing under this shadow, with * any synthetic arguments removed */ public Member getMatchingSignature() { return matchingSignature != null ? matchingSignature : signature; } public void setMatchingSignature(Member member) { this.matchingSignature = member; } /** * returns the resolved signature of the thing under this shadow * */ public ResolvedMember getResolvedSignature() { if (resolvedSignature == null) { resolvedSignature = signature.resolve(getIWorld()); } return resolvedSignature; } public UnresolvedType getReturnType() { if (kind == ConstructorCall) return getSignature().getDeclaringType(); else if (kind == FieldSet) return ResolvedType.VOID; else if (kind == SynchronizationLock || kind==SynchronizationUnlock) return ResolvedType.VOID; return getResolvedSignature().getGenericReturnType(); } /** * These names are the ones that will be returned by thisJoinPoint.getKind() * Those need to be documented somewhere */ public static final Kind MethodCall = new Kind(JoinPoint.METHOD_CALL, 1, true); public static final Kind ConstructorCall = new Kind(JoinPoint.CONSTRUCTOR_CALL, 2, true); public static final Kind MethodExecution = new Kind(JoinPoint.METHOD_EXECUTION, 3, false); public static final Kind ConstructorExecution = new Kind(JoinPoint.CONSTRUCTOR_EXECUTION, 4, false); public static final Kind FieldGet = new Kind(JoinPoint.FIELD_GET, 5, true); public static final Kind FieldSet = new Kind(JoinPoint.FIELD_SET, 6, true); public static final Kind StaticInitialization = new Kind(JoinPoint.STATICINITIALIZATION, 7, false); public static final Kind PreInitialization = new Kind(JoinPoint.PREINITIALIZATION, 8, false); public static final Kind AdviceExecution = new Kind(JoinPoint.ADVICE_EXECUTION, 9, false); public static final Kind Initialization = new Kind(JoinPoint.INITIALIZATION, 10, false); public static final Kind ExceptionHandler = new Kind(JoinPoint.EXCEPTION_HANDLER, 11, true); public static final Kind SynchronizationLock = new Kind(JoinPoint.SYNCHRONIZATION_LOCK, 12, true); public static final Kind SynchronizationUnlock= new Kind(JoinPoint.SYNCHRONIZATION_UNLOCK, 13, true); // Bits here are 1<<(Kind.getKey()) - and unfortunately keys didn't start at zero so bits here start at 2 public static final int MethodCallBit = 0x002; public static final int ConstructorCallBit = 0x004; public static final int MethodExecutionBit = 0x008; public static final int ConstructorExecutionBit = 0x010; public static final int FieldGetBit = 0x020; public static final int FieldSetBit = 0x040; public static final int StaticInitializationBit = 0x080; public static final int PreInitializationBit = 0x100; public static final int AdviceExecutionBit = 0x200; public static final int InitializationBit = 0x400; public static final int ExceptionHandlerBit = 0x800; public static final int SynchronizationLockBit =0x1000; public static final int SynchronizationUnlockBit=0x2000; public static final int MAX_SHADOW_KIND = 13; public static final Kind[] SHADOW_KINDS = new Kind[] { MethodCall, ConstructorCall, MethodExecution, ConstructorExecution, FieldGet, FieldSet, StaticInitialization, PreInitialization, AdviceExecution, Initialization, ExceptionHandler,SynchronizationLock,SynchronizationUnlock }; public static final int ALL_SHADOW_KINDS_BITS; public static final int NO_SHADOW_KINDS_BITS; static { ALL_SHADOW_KINDS_BITS = 0x3ffe; NO_SHADOW_KINDS_BITS = 0x0000; } /** * Return count of how many bits set in the supplied parameter. */ public static int howMany(int i) { int count = 0; for (int j = 0; j <SHADOW_KINDS.length; j++) { if ((i&SHADOW_KINDS[j].bit)!=0) count++; } return count; } /** A type-safe enum representing the kind of shadows */ public static final class Kind extends TypeSafeEnum { // private boolean argsOnStack; //XXX unused public int bit; public Kind(String name, int key, boolean argsOnStack) { super(name, key); bit = 1<<key; // this.argsOnStack = argsOnStack; } public String toLegalJavaIdentifier() { return getName().replace('-', '_'); } public boolean argsOnStack() { return !isTargetSameAsThis(); } // !!! this is false for handlers! public boolean allowsExtraction() { return true; } public boolean isSet(int i) { return (i&bit)!=0; } // XXX revisit along with removal of priorities public boolean hasHighPriorityExceptions() { return !isTargetSameAsThis(); } private final static int hasReturnValueFlag = MethodCallBit | ConstructorCallBit | MethodExecutionBit | FieldGetBit | AdviceExecutionBit; /** * These shadow kinds have return values that can be bound in * after returning(Dooberry doo) advice. * @return */ public boolean hasReturnValue() { return (bit&hasReturnValueFlag)!=0; } private final static int isEnclosingKindFlag = MethodExecutionBit | ConstructorExecutionBit | AdviceExecutionBit | StaticInitializationBit | InitializationBit; /** * These are all the shadows that contains other shadows within them and * are often directly associated with methods. */ public boolean isEnclosingKind() { return (bit&isEnclosingKindFlag)!=0; } private final static int isTargetSameAsThisFlag = MethodExecutionBit | ConstructorExecutionBit | StaticInitializationBit | PreInitializationBit | AdviceExecutionBit | InitializationBit; public boolean isTargetSameAsThis() { return (bit&isTargetSameAsThisFlag)!=0; } private final static int neverHasTargetFlag= ConstructorCallBit | ExceptionHandlerBit | PreInitializationBit | StaticInitializationBit | SynchronizationLockBit | SynchronizationUnlockBit; public boolean neverHasTarget() { return (bit&neverHasTargetFlag)!=0; } private final static int neverHasThisFlag= PreInitializationBit | StaticInitializationBit; public boolean neverHasThis() { return (bit&neverHasThisFlag)!=0; } public String getSimpleName() { int dash = getName().lastIndexOf('-'); if (dash == -1) return getName(); else return getName().substring(dash+1); } public static Kind read(DataInputStream s) throws IOException { int key = s.readByte(); switch(key) { case 1: return MethodCall; case 2: return ConstructorCall; case 3: return MethodExecution; case 4: return ConstructorExecution; case 5: return FieldGet; case 6: return FieldSet; case 7: return StaticInitialization; case 8: return PreInitialization; case 9: return AdviceExecution; case 10: return Initialization; case 11: return ExceptionHandler; case 12: return SynchronizationLock; case 13: return SynchronizationUnlock; } throw new BCException("unknown kind: " + key); } } /** * Only does the check if the munger requires it (@AJ aspects don't) * * @param munger * @return */ protected boolean checkMunger(ShadowMunger munger) { if (munger.mustCheckExceptions()) { for (Iterator i = munger.getThrownExceptions().iterator(); i.hasNext(); ) { if (!checkCanThrow(munger, (ResolvedType)i.next() )) return false; } } return true; } protected boolean checkCanThrow(ShadowMunger munger, ResolvedType resolvedTypeX) { if (getKind() == ExceptionHandler) { //XXX much too lenient rules here, need to walk up exception handlers return true; } if (!isDeclaredException(resolvedTypeX, getSignature())) { getIWorld().showMessage(IMessage.ERROR, WeaverMessages.format(WeaverMessages.CANT_THROW_CHECKED,resolvedTypeX,this), // from advice in \'" + munger. + "\'", getSourceLocation(), munger.getSourceLocation()); } return true; } private boolean isDeclaredException( ResolvedType resolvedTypeX, Member member) { ResolvedType[] excs = getIWorld().resolve(member.getExceptions(getIWorld())); for (int i=0, len=excs.length; i < len; i++) { if (excs[i].isAssignableFrom(resolvedTypeX)) return true; } return false; } public void addMunger(ShadowMunger munger) { if (checkMunger(munger)) { if (mungers==Collections.EMPTY_LIST) mungers = new ArrayList(); this.mungers.add(munger); } } public final void implement() { sortMungers(); if (mungers == null) return; prepareForMungers(); implementMungers(); } private void sortMungers() { List sorted = PartialOrder.sort(mungers); // Bunch of code to work out whether to report xlints for advice that isn't ordered at this Joinpoint possiblyReportUnorderedAdvice(sorted); if (sorted == null) { // this means that we have circular dependencies for (Iterator i = mungers.iterator(); i.hasNext(); ) { ShadowMunger m = (ShadowMunger)i.next(); getIWorld().getMessageHandler().handleMessage( MessageUtil.error( WeaverMessages.format(WeaverMessages.CIRCULAR_DEPENDENCY,this), m.getSourceLocation())); } } mungers = sorted; } // not quite optimal... but the xlint is ignore by default private void possiblyReportUnorderedAdvice(List sorted) { if (sorted!=null && getIWorld().getLint().unorderedAdviceAtShadow.isEnabled() && mungers.size()>1) { // Stores a set of strings of the form 'aspect1:aspect2' which indicates there is no // precedence specified between the two aspects at this shadow. Set clashingAspects = new HashSet(); int max = mungers.size(); // Compare every pair of advice mungers for (int i = max-1; i >=0; i--) { for (int j=0; j<i; j++) { Object a = mungers.get(i); Object b = mungers.get(j); // Make sure they are the right type if (a instanceof BcelAdvice && b instanceof BcelAdvice) { BcelAdvice adviceA = (BcelAdvice)a; BcelAdvice adviceB = (BcelAdvice)b; if (!adviceA.concreteAspect.equals(adviceB.concreteAspect)) { AdviceKind adviceKindA = adviceA.getKind(); AdviceKind adviceKindB = adviceB.getKind(); // make sure they are the nice ones (<6) and not any synthetic advice ones we // create to support other features of the language. if (adviceKindA.getKey()<(byte)6 && adviceKindB.getKey()<(byte)6 && adviceKindA.getPrecedence() == adviceKindB.getPrecedence()) { // Ask the world if it knows about precedence between these Integer order = getIWorld().getPrecedenceIfAny( adviceA.concreteAspect, adviceB.concreteAspect); if (order!=null && order.equals(new Integer(0))) { String key = adviceA.getDeclaringAspect()+":"+adviceB.getDeclaringAspect(); String possibleExistingKey = adviceB.getDeclaringAspect()+":"+adviceA.getDeclaringAspect(); if (!clashingAspects.contains(possibleExistingKey)) clashingAspects.add(key); } } } } } } for (Iterator iter = clashingAspects.iterator(); iter.hasNext();) { String element = (String) iter.next(); String aspect1 = element.substring(0,element.indexOf(":")); String aspect2 = element.substring(element.indexOf(":")+1); getIWorld().getLint().unorderedAdviceAtShadow.signal( new String[]{this.toString(),aspect1,aspect2}, this.getSourceLocation(),null); } } } /** Prepare the shadow for implementation. After this is done, the shadow * should be in such a position that each munger simply needs to be implemented. */ protected void prepareForMungers() { throw new RuntimeException("Generic shadows cannot be prepared"); } /* * Ensure we report a nice source location - particular in the case * where the source info is missing (binary weave). */ private String beautifyLocation(ISourceLocation isl) { StringBuffer nice = new StringBuffer(); if (isl==null || isl.getSourceFile()==null || isl.getSourceFile().getName().indexOf("no debug info available")!=-1) { nice.append("no debug info available"); } else { // can't use File.getName() as this fails when a Linux box encounters a path created on Windows and vice-versa int takeFrom = isl.getSourceFile().getPath().lastIndexOf('/'); if (takeFrom == -1) { takeFrom = isl.getSourceFile().getPath().lastIndexOf('\\'); } 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(); } /* * Report a message about the advice weave that has occurred. Some messing about * to make it pretty ! This code is just asking for an NPE to occur ... */ private void reportWeavingMessage(ShadowMunger munger) { Advice advice = (Advice)munger; AdviceKind aKind = advice.getKind(); // Only report on interesting advice kinds ... if (aKind == null || advice.getConcreteAspect()==null) { // We suspect someone is programmatically driving the weaver // (e.g. IdWeaveTestCase in the weaver testcases) return; } if (!( aKind.equals(AdviceKind.Before) || aKind.equals(AdviceKind.After) || aKind.equals(AdviceKind.AfterReturning) || aKind.equals(AdviceKind.AfterThrowing) || aKind.equals(AdviceKind.Around) || aKind.equals(AdviceKind.Softener))) return; // 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 (this.kind==Shadow.SynchronizationUnlock) { if (advice.lastReportedMonitorExitJoinpointLocation==null) { // this is the first time through, let's continue... advice.lastReportedMonitorExitJoinpointLocation = getSourceLocation(); } else { if (areTheSame(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=getSourceLocation(); } } String description = advice.getKind().toString(); String advisedType = this.getEnclosingType().getName(); String advisingType= advice.getConcreteAspect().getName(); Message msg = null; if (advice.getKind().equals(AdviceKind.Softener)) { msg = WeaveMessage.constructWeavingMessage( WeaveMessage.WEAVEMESSAGE_SOFTENS, new String[]{advisedType,beautifyLocation(getSourceLocation()), advisingType,beautifyLocation(munger.getSourceLocation())}, advisedType, advisingType); } else { boolean runtimeTest = ((BcelAdvice)advice).hasDynamicTests(); String joinPointDescription = this.toString(); msg = WeaveMessage.constructWeavingMessage(WeaveMessage.WEAVEMESSAGE_ADVISES, new String[]{ joinPointDescription, advisedType, beautifyLocation(getSourceLocation()), description, advisingType,beautifyLocation(munger.getSourceLocation()), (runtimeTest?" [with runtime test]":"")}, advisedType, advisingType); // Boolean.toString(runtimeTest)}); } getIWorld().getMessageHandler().handleMessage(msg); } 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()); } public IRelationship.Kind determineRelKind(ShadowMunger munger) { AdviceKind ak = ((Advice)munger).getKind(); if (ak.getKey()==AdviceKind.Before.getKey()) return IRelationship.Kind.ADVICE_BEFORE; else if (ak.getKey()==AdviceKind.After.getKey()) return IRelationship.Kind.ADVICE_AFTER; else if (ak.getKey()==AdviceKind.AfterThrowing.getKey()) return IRelationship.Kind.ADVICE_AFTERTHROWING; else if (ak.getKey()==AdviceKind.AfterReturning.getKey()) return IRelationship.Kind.ADVICE_AFTERRETURNING; else if (ak.getKey()==AdviceKind.Around.getKey()) return IRelationship.Kind.ADVICE_AROUND; else if (ak.getKey()==AdviceKind.CflowEntry.getKey() || ak.getKey()==AdviceKind.CflowBelowEntry.getKey() || ak.getKey()==AdviceKind.InterInitializer.getKey() || ak.getKey()==AdviceKind.PerCflowEntry.getKey() || ak.getKey()==AdviceKind.PerCflowBelowEntry.getKey() || ak.getKey()==AdviceKind.PerThisEntry.getKey() || ak.getKey()==AdviceKind.PerTargetEntry.getKey() || ak.getKey()==AdviceKind.Softener.getKey() || ak.getKey()==AdviceKind.PerTypeWithinEntry.getKey()) { //System.err.println("Dont want a message about this: "+ak); return null; } throw new RuntimeException("Shadow.determineRelKind: What the hell is it? "+ak); } /** Actually implement the (non-empty) mungers associated with this shadow */ private void implementMungers() { World world = getIWorld(); for (Iterator iter = mungers.iterator(); iter.hasNext();) { ShadowMunger munger = (ShadowMunger) iter.next(); munger.implementOn(this); if (world.getCrossReferenceHandler() != null) { world.getCrossReferenceHandler().addCrossReference( munger.getSourceLocation(), // What is being applied this.getSourceLocation(), // Where is it being applied determineRelKind(munger), // What kind of advice? ((BcelAdvice)munger).hasDynamicTests() // Is a runtime test being stuffed in the code? ); } // TAG: WeavingMessage if (!getIWorld().getMessageHandler().isIgnoring(IMessage.WEAVEINFO)) { reportWeavingMessage(munger); } if (world.getModel() != null) { //System.err.println("munger: " + munger + " on " + this); AsmRelationshipProvider.getDefault().adviceMunger(world.getModel(), this, munger); } } } public String makeReflectiveFactoryString() { return null; //XXX } public abstract ISourceLocation getSourceLocation(); // ---- utility public String toString() { return getKind() + "(" + getSignature() + ")"; // + getSourceLines(); } public String toResolvedString(World world) { return getKind() + "(" + world.resolve(getSignature()).toGenericString() + ")"; } /** * Convert a bit array for the shadow kinds into a set of them... should only * be used for testing - mainline code should do bit manipulation! */ public static Set toSet(int i) { Set results = new HashSet(); for (int j = 0; j < Shadow.SHADOW_KINDS.length; j++) { Kind k = Shadow.SHADOW_KINDS[j]; if (k.isSet(i)) results.add(k); } return results; } }
220,430
Bug 220430 mixup in retrieving the right class in Java15AnnotationFinder
null
resolved fixed
9bbdb41
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2008-02-26T21:03:19Z"
"2008-02-26T18:20:00Z"
weaver5/java5-src/org/aspectj/weaver/reflect/Java15AnnotationFinder.java
/* ******************************************************************* * Copyright (c) 2005 Contributors. * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Eclipse Public License v1.0 * which accompanies this distribution and is available at * http://eclipse.org/legal/epl-v10.html * * Contributors: * Adrian Colyer Initial implementation * ******************************************************************/ package org.aspectj.weaver.reflect; import java.lang.annotation.Annotation; import java.lang.reflect.AccessibleObject; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.Member; import java.lang.reflect.Method; import java.util.Collections; import java.util.HashSet; import java.util.Set; import org.aspectj.apache.bcel.classfile.AnnotationDefault; import org.aspectj.apache.bcel.classfile.Attribute; import org.aspectj.apache.bcel.classfile.JavaClass; import org.aspectj.apache.bcel.classfile.LocalVariable; import org.aspectj.apache.bcel.classfile.LocalVariableTable; import org.aspectj.apache.bcel.util.NonCachingClassLoaderRepository; import org.aspectj.apache.bcel.util.Repository; import org.aspectj.weaver.AnnotationX; import org.aspectj.weaver.ResolvedType; import org.aspectj.weaver.UnresolvedType; import org.aspectj.weaver.World; /** * Find the given annotation (if present) on the given object * */ public class Java15AnnotationFinder implements AnnotationFinder, ArgNameFinder { private Repository bcelRepository; private ClassLoader classLoader; private World world; // must have no-arg constructor for reflective construction public Java15AnnotationFinder() { } public void setClassLoader(ClassLoader aLoader) { // TODO: No easy way to ask the world factory for the right kind of repository so // default to the safe one! (pr160674) this.bcelRepository = new NonCachingClassLoaderRepository(aLoader); this.classLoader = aLoader; } public void setWorld(World aWorld) { this.world = aWorld; } /* (non-Javadoc) * @see org.aspectj.weaver.reflect.AnnotationFinder#getAnnotation(org.aspectj.weaver.ResolvedType, java.lang.Object) */ public Object getAnnotation(ResolvedType annotationType, Object onObject) { try { Class<? extends Annotation> annotationClass = (Class<? extends Annotation>) Class.forName(annotationType.getName(),false,classLoader); if (onObject.getClass().isAnnotationPresent(annotationClass)) { return onObject.getClass().getAnnotation(annotationClass); } } catch (ClassNotFoundException ex) { // just return null } return null; } public Object getAnnotationFromClass(ResolvedType annotationType, Class aClass) { try { Class<? extends Annotation> annotationClass = (Class<? extends Annotation>) Class.forName(annotationType.getName(),false,classLoader); if (aClass.isAnnotationPresent(annotationClass)) { return aClass.getAnnotation(annotationClass); } } catch (ClassNotFoundException ex) { // just return null } return null; } public Object getAnnotationFromMember(ResolvedType annotationType, Member aMember) { if (!(aMember instanceof AccessibleObject)) return null; AccessibleObject ao = (AccessibleObject) aMember; try { Class annotationClass = Class.forName(annotationType.getName(),false,classLoader); if (ao.isAnnotationPresent(annotationClass)) { return ao.getAnnotation(annotationClass); } } catch (ClassNotFoundException ex) { // just return null } return null; } public AnnotationX getAnnotationOfType(UnresolvedType ofType,Member onMember) { if (!(onMember instanceof AccessibleObject)) return null; // here we really want both the runtime visible AND the class visible annotations // so we bail out to Bcel and then chuck away the JavaClass so that we don't hog // memory. try { JavaClass jc = bcelRepository.loadClass(onMember.getDeclaringClass()); org.aspectj.apache.bcel.classfile.annotation.Annotation[] anns = new org.aspectj.apache.bcel.classfile.annotation.Annotation[0]; if (onMember instanceof Method) { org.aspectj.apache.bcel.classfile.Method bcelMethod = jc.getMethod((Method)onMember); if (bcelMethod == null) { System.err.println("Unexpected problem in Java15AnnotationFinder: cannot retrieve annotations on method '"+onMember.getName()+"' in class '"+jc.getClassName()+"'"); } else { anns = bcelMethod.getAnnotations(); } } else if (onMember instanceof Constructor) { org.aspectj.apache.bcel.classfile.Method bcelCons = jc.getMethod((Constructor)onMember); anns = bcelCons.getAnnotations(); } else if (onMember instanceof Field) { org.aspectj.apache.bcel.classfile.Field bcelField = jc.getField((Field)onMember); anns = bcelField.getAnnotations(); } // the answer is cached and we don't want to hold on to memory bcelRepository.clear(); if (anns == null) anns = new org.aspectj.apache.bcel.classfile.annotation.Annotation[0]; // convert to our Annotation type for (int i=0;i<anns.length;i++) { if (anns[i].getTypeSignature().equals(ofType.getSignature())) { return new AnnotationX(anns[i],world); } } return null; } catch (ClassNotFoundException cnfEx) { // just use reflection then } return null; } public String getAnnotationDefaultValue(Member onMember) { try { JavaClass jc = bcelRepository.loadClass(onMember.getDeclaringClass()); if (onMember instanceof Method) { org.aspectj.apache.bcel.classfile.Method bcelMethod = jc.getMethod((Method)onMember); if (bcelMethod == null) { System.err.println("Unexpected problem in Java15AnnotationFinder: cannot retrieve annotations on method '"+onMember.getName()+"' in class '"+jc.getClassName()+"'"); } else { Attribute[] attrs = bcelMethod.getAttributes(); for (int i = 0; i < attrs.length; i++) { Attribute attribute = attrs[i]; if (attribute.getName().equals("AnnotationDefault")) { AnnotationDefault def = (AnnotationDefault)attribute; return def.getElementValue().stringifyValue(); } } return null; } } } catch (ClassNotFoundException cnfEx) { // just use reflection then } return null; } public Set getAnnotations(Member onMember) { if (!(onMember instanceof AccessibleObject)) return Collections.EMPTY_SET; // here we really want both the runtime visible AND the class visible annotations // so we bail out to Bcel and then chuck away the JavaClass so that we don't hog // memory. try { JavaClass jc = bcelRepository.loadClass(onMember.getDeclaringClass()); org.aspectj.apache.bcel.classfile.annotation.Annotation[] anns = new org.aspectj.apache.bcel.classfile.annotation.Annotation[0]; if (onMember instanceof Method) { org.aspectj.apache.bcel.classfile.Method bcelMethod = jc.getMethod((Method)onMember); if (bcelMethod == null) { System.err.println("Unexpected problem in Java15AnnotationFinder: cannot retrieve annotations on method '"+onMember.getName()+"' in class '"+jc.getClassName()+"'"); } else { anns = bcelMethod.getAnnotations(); } } else if (onMember instanceof Constructor) { org.aspectj.apache.bcel.classfile.Method bcelCons = jc.getMethod((Constructor)onMember); anns = bcelCons.getAnnotations(); } else if (onMember instanceof Field) { org.aspectj.apache.bcel.classfile.Field bcelField = jc.getField((Field)onMember); anns = bcelField.getAnnotations(); } // the answer is cached and we don't want to hold on to memory bcelRepository.clear(); if (anns == null) anns = new org.aspectj.apache.bcel.classfile.annotation.Annotation[0]; // convert to our Annotation type Set<ResolvedType> annSet = new HashSet<ResolvedType>(); for (int i = 0; i < anns.length; i++) { annSet.add(world.resolve(UnresolvedType.forSignature(anns[i].getTypeSignature()))); } return annSet; } catch (ClassNotFoundException cnfEx) { // just use reflection then } AccessibleObject ao = (AccessibleObject) onMember; Annotation[] anns = ao.getDeclaredAnnotations(); Set<UnresolvedType> annSet = new HashSet<UnresolvedType>(); for (int i = 0; i < anns.length; i++) { annSet.add(UnresolvedType.forName(anns[i].annotationType().getName()).resolve(world)); } return annSet; } public ResolvedType[] getAnnotations(Class forClass, World inWorld) { // here we really want both the runtime visible AND the class visible annotations // so we bail out to Bcel and then chuck away the JavaClass so that we don't hog // memory. try { JavaClass jc = bcelRepository.loadClass(forClass); org.aspectj.apache.bcel.classfile.annotation.Annotation[] anns =jc.getAnnotations(); bcelRepository.clear(); if (anns == null) return new ResolvedType[0]; ResolvedType[] ret = new ResolvedType[anns.length]; for (int i = 0; i < ret.length; i++) { ret[i] = inWorld.resolve(UnresolvedType.forSignature(anns[i].getTypeSignature())); } return ret; } catch (ClassNotFoundException cnfEx) { // just use reflection then } Annotation[] classAnnotations = forClass.getAnnotations(); ResolvedType[] ret = new ResolvedType[classAnnotations.length]; for (int i = 0; i < classAnnotations.length; i++) { ret[i] = inWorld.resolve(classAnnotations[i].annotationType().getName()); } return ret; } public String[] getParameterNames(Member forMember) { if (!(forMember instanceof AccessibleObject)) return null; try { JavaClass jc = bcelRepository.loadClass(forMember.getDeclaringClass()); LocalVariableTable lvt = null; int numVars = 0; if (forMember instanceof Method) { org.aspectj.apache.bcel.classfile.Method bcelMethod = jc.getMethod((Method)forMember); lvt = bcelMethod.getLocalVariableTable(); numVars = bcelMethod.getArgumentTypes().length; } else if (forMember instanceof Constructor) { org.aspectj.apache.bcel.classfile.Method bcelCons = jc.getMethod((Constructor)forMember); lvt = bcelCons.getLocalVariableTable(); numVars = bcelCons.getArgumentTypes().length; } return getParameterNamesFromLVT(lvt,numVars); } catch (ClassNotFoundException cnfEx) { ; // no luck } return null; } private String[] getParameterNamesFromLVT(LocalVariableTable lvt, int numVars) { LocalVariable[] vars = lvt.getLocalVariableTable(); if (vars.length < numVars) { // basic error, we can't get the names... return null; } String[] ret = new String[numVars]; for(int i = 0; i < numVars; i++) { ret[i] = vars[i+1].getName(); } return ret; } public static final ResolvedType[][] NO_PARAMETER_ANNOTATIONS = new ResolvedType[][]{}; public ResolvedType[][] getParameterAnnotationTypes(Member onMember) { if (!(onMember instanceof AccessibleObject)) return NO_PARAMETER_ANNOTATIONS; // here we really want both the runtime visible AND the class visible annotations // so we bail out to Bcel and then chuck away the JavaClass so that we don't hog // memory. try { JavaClass jc = bcelRepository.loadClass(onMember.getDeclaringClass()); org.aspectj.apache.bcel.classfile.annotation.Annotation[][] anns = null; if (onMember instanceof Method) { org.aspectj.apache.bcel.classfile.Method bcelMethod = jc.getMethod((Method)onMember); anns = bcelMethod.getParameterAnnotations(); } else if (onMember instanceof Constructor) { org.aspectj.apache.bcel.classfile.Method bcelCons = jc.getMethod((Constructor)onMember); anns = bcelCons.getParameterAnnotations(); } else if (onMember instanceof Field) { anns = null; } // the answer is cached and we don't want to hold on to memory bcelRepository.clear(); if (anns == null) return NO_PARAMETER_ANNOTATIONS; ResolvedType[][] result = new ResolvedType[anns.length][]; // CACHING?? for (int i=0;i<anns.length;i++) { if (anns[i]!=null) { result[i] = new ResolvedType[anns[i].length]; for (int j=0;j<anns[i].length;j++) { result[i][j] = world.resolve(UnresolvedType.forSignature(anns[i][j].getTypeSignature())); } } } return result; } catch (ClassNotFoundException cnfEx) { // just use reflection then } // reflection... AccessibleObject ao = (AccessibleObject) onMember; Annotation[][] anns = null; if (onMember instanceof Method) { anns = ((Method)ao).getParameterAnnotations(); } else if (onMember instanceof Constructor) { anns = ((Constructor)ao).getParameterAnnotations(); } else if (onMember instanceof Field) { anns = null; } if (anns == null) return NO_PARAMETER_ANNOTATIONS; ResolvedType[][] result = new ResolvedType[anns.length][]; // CACHING?? for (int i=0;i<anns.length;i++) { if (anns[i]!=null) { result[i] = new ResolvedType[anns[i].length]; for (int j=0;j<anns[i].length;j++) { result[i][j] = UnresolvedType.forName(anns[i][j].annotationType().getName()).resolve(world); } } } return result; } }
219,830
Bug 219830 java.lang.NullPointerException in Java15AnnotationFinder when using SWT
I receive the following Exception when running SWT with AspjectJ load time weaving through the Spring Framework. The lines around org.aspectj.weaver.reflect.Java15AnnotationFinder.getAnnotations(Java15AnnotationFinder.java:123) are as follows: for (int i = 0; i < anns.length; i++) { annSet.add(world.resolve(UnresolvedType.forSignature(anns[i].getTypeSignature()))); } When using the debugger, I see "world" as a null value. Attached is a stripped down Eclipse project that generates the error during startup. My runtime arguments are as follows: -javaagent:${resource_loc:/AspectJBug/lib/spring-agent.jar} -------------------------------------------- [AppClassLoader@19d819d8] abort trouble in: final class org.eclipse.swt.awt.SWT_AWT$10 extends java.lang.Object implements java.lang.Runnable: private final java.awt.Frame val$frame [Synthetic] void <init>(java.awt.Frame): ALOAD_0 // Lorg/eclipse/swt/awt/SWT_AWT$10; this (line 274) INVOKESPECIAL java.lang.Object.<init> ()V constructor-execution(void org.eclipse.swt.awt.SWT_AWT$10.<init>(java.awt.Frame)) | ALOAD_0 // Lorg/eclipse/swt/awt/SWT_AWT$10; this (line 1) | ALOAD_1 | PUTFIELD org.eclipse.swt.awt.SWT_AWT$10.val$frame Ljava/awt/Frame; | RETURN constructor-execution(void org.eclipse.swt.awt.SWT_AWT$10.<init>(java.awt.Frame)) end void <init>(java.awt.Frame) public void run(): method-execution(void org.eclipse.swt.awt.SWT_AWT$10.run()) | catch java.lang.Throwable -> E0 | | LDC "sun.awt.windows.WComponentPeer" (line 277) | | method-call(java.lang.Class java.lang.Class.forName(java.lang.String)) | | | INVOKESTATIC java.lang.Class.forName (Ljava/lang/String;)Ljava/lang/Class; | | method-call(java.lang.Class java.lang.Class.forName(java.lang.String)) | | ASTORE_1 | | ALOAD_1 // Ljava/lang/Class; clazz (line 278) | | LDC "winGraphicsConfig" | | method-call(java.lang.reflect.Field java.lang.Class.getDeclaredField(java.lang.String)) | | | INVOKEVIRTUAL java.lang.Class.getDeclaredField (Ljava/lang/String;)Ljava/lang/reflect/Field; | | method-call(java.lang.reflect.Field java.lang.Class.getDeclaredField(java.lang.String)) | | ASTORE_2 | | ALOAD_2 // Ljava/lang/reflect/Field; field (line 279) | | ICONST_1 | | method-call(void java.lang.reflect.Field.setAccessible(boolean)) | | | INVOKEVIRTUAL java.lang.reflect.Field.setAccessible (Z)V | | method-call(void java.lang.reflect.Field.setAccessible(boolean)) | | ALOAD_2 // Ljava/lang/reflect/Field; field (line 280) | | ALOAD_0 // Lorg/eclipse/swt/awt/SWT_AWT$10; this | | GETFIELD org.eclipse.swt.awt.SWT_AWT$10.val$frame Ljava/awt/Frame; | | method-call(java.awt.peer.ComponentPeer java.awt.Frame.getPeer()) | | | INVOKEVIRTUAL java.awt.Frame.getPeer ()Ljava/awt/peer/ComponentPeer; | | method-call(java.awt.peer.ComponentPeer java.awt.Frame.getPeer()) | | ALOAD_0 // Lorg/eclipse/swt/awt/SWT_AWT$10; this | | GETFIELD org.eclipse.swt.awt.SWT_AWT$10.val$frame Ljava/awt/Frame; | | INVOKEVIRTUAL java.awt.Frame.getGraphicsConfiguration ()Ljava/awt/GraphicsConfiguration; | | INVOKEVIRTUAL java.lang.reflect.Field.set (Ljava/lang/Object;Ljava/lang/Object;)V | catch java.lang.Throwable -> E0 | GOTO L0 | E0: POP (line 281) | L0: RETURN (line 282) method-execution(void org.eclipse.swt.awt.SWT_AWT$10.run()) end public void run() end final class org.eclipse.swt.awt.SWT_AWT$10 -- (NullPointerException) null null java.lang.NullPointerException at org.aspectj.weaver.reflect.Java15AnnotationFinder.getAnnotations(Java15AnnotationFinder.java:123) at org.aspectj.weaver.reflect.ReflectionBasedResolvedMemberImpl.unpackAnnotations(ReflectionBasedResolvedMemberImpl.java:174) at org.aspectj.weaver.reflect.ReflectionBasedResolvedMemberImpl.hasAnnotation(ReflectionBasedResolvedMemberImpl.java:158) at org.aspectj.weaver.patterns.ExactAnnotationTypePattern.matches(ExactAnnotationTypePattern.java:82) at org.aspectj.weaver.patterns.AnnotationPointcut.matchInternal(AnnotationPointcut.java:151) at org.aspectj.weaver.patterns.Pointcut.match(Pointcut.java:146) at org.aspectj.weaver.patterns.AndPointcut.matchInternal(AndPointcut.java:52) at org.aspectj.weaver.patterns.Pointcut.match(Pointcut.java:146) at org.aspectj.weaver.ShadowMunger.match(ShadowMunger.java:75) at org.aspectj.weaver.Advice.match(Advice.java:112) at org.aspectj.weaver.bcel.BcelAdvice.match(BcelAdvice.java:118) at org.aspectj.weaver.bcel.BcelClassWeaver.match(BcelClassWeaver.java:2811) at org.aspectj.weaver.bcel.BcelClassWeaver.matchInvokeInstruction(BcelClassWeaver.java:2773) at org.aspectj.weaver.bcel.BcelClassWeaver.match(BcelClassWeaver.java:2506) at org.aspectj.weaver.bcel.BcelClassWeaver.match(BcelClassWeaver.java:2332) at org.aspectj.weaver.bcel.BcelClassWeaver.weave(BcelClassWeaver.java:494) at org.aspectj.weaver.bcel.BcelClassWeaver.weave(BcelClassWeaver.java:119) at org.aspectj.weaver.bcel.BcelWeaver.weave(BcelWeaver.java:1651) at org.aspectj.weaver.bcel.BcelWeaver.weaveWithoutDump(BcelWeaver.java:1602) at org.aspectj.weaver.bcel.BcelWeaver.weaveAndNotify(BcelWeaver.java:1380) at org.aspectj.weaver.bcel.BcelWeaver.weave(BcelWeaver.java:1200) at org.aspectj.weaver.tools.WeavingAdaptor.getWovenBytes(WeavingAdaptor.java:360) at org.aspectj.weaver.tools.WeavingAdaptor.weaveClass(WeavingAdaptor.java:262) at org.aspectj.weaver.loadtime.Aj.preProcess(Aj.java:78) at org.aspectj.weaver.loadtime.ClassPreProcessorAgentAdapter.transform(ClassPreProcessorAgentAdapter.java:52) at org.springframework.context.weaving.AspectJWeavingEnabler$AspectJClassBypassingClassFileTransformerDecorator.transform(AspectJWeavingEnabler.java:84) at sun.instrument.TransformerManager.transform(TransformerManager.java:141) at sun.instrument.InstrumentationImpl.transform(InstrumentationImpl.java:174) at java.lang.ClassLoader.defineClassImpl(Native Method) at java.lang.ClassLoader.defineClass(ClassLoader.java:228) at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:148) at java.net.URLClassLoader.defineClass(URLClassLoader.java:557) at java.net.URLClassLoader.access$400(URLClassLoader.java:120) at java.net.URLClassLoader$ClassFinder.run(URLClassLoader.java:962) at java.security.AccessController.doPrivileged(AccessController.java:275) at java.net.URLClassLoader.findClass(URLClassLoader.java:488) at java.lang.ClassLoader.loadClass(ClassLoader.java:607) at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:327) at java.lang.ClassLoader.loadClass(ClassLoader.java:573) at org.eclipse.swt.awt.SWT_AWT.new_Frame(SWT_AWT.java:274) Feb 21, 2008 12:09:23 PM org.aspectj.weaver.tools.Jdk14Trace error SEVERE: org/eclipse/swt/awt/SWT_AWT$10 java.lang.NullPointerException at org.aspectj.weaver.reflect.Java15AnnotationFinder.getAnnotations(Java15AnnotationFinder.java:123) at org.aspectj.weaver.reflect.ReflectionBasedResolvedMemberImpl.unpackAnnotations(ReflectionBasedResolvedMemberImpl.java:174) at org.aspectj.weaver.reflect.ReflectionBasedResolvedMemberImpl.hasAnnotation(ReflectionBasedResolvedMemberImpl.java:158) at org.aspectj.weaver.patterns.ExactAnnotationTypePattern.matches(ExactAnnotationTypePattern.java:82) at org.aspectj.weaver.patterns.AnnotationPointcut.matchInternal(AnnotationPointcut.java:151) at org.aspectj.weaver.patterns.Pointcut.match(Pointcut.java:146) at org.aspectj.weaver.patterns.AndPointcut.matchInternal(AndPointcut.java:52) at org.aspectj.weaver.patterns.Pointcut.match(Pointcut.java:146) at org.aspectj.weaver.ShadowMunger.match(ShadowMunger.java:75) at org.aspectj.weaver.Advice.match(Advice.java:112) at org.aspectj.weaver.bcel.BcelAdvice.match(BcelAdvice.java:118) at org.aspectj.weaver.bcel.BcelClassWeaver.match(BcelClassWeaver.java:2811) at org.aspectj.weaver.bcel.BcelClassWeaver.matchInvokeInstruction(BcelClassWeaver.java:2773) at org.aspectj.weaver.bcel.BcelClassWeaver.match(BcelClassWeaver.java:2506) at org.aspectj.weaver.bcel.BcelClassWeaver.match(BcelClassWeaver.java:2332) at org.aspectj.weaver.bcel.BcelClassWeaver.weave(BcelClassWeaver.java:494) at org.aspectj.weaver.bcel.BcelClassWeaver.weave(BcelClassWeaver.java:119) at org.aspectj.weaver.bcel.BcelWeaver.weave(BcelWeaver.java:1651) at org.aspectj.weaver.bcel.BcelWeaver.weaveWithoutDump(BcelWeaver.java:1602) at org.aspectj.weaver.bcel.BcelWeaver.weaveAndNotify(BcelWeaver.java:1380) at org.aspectj.weaver.bcel.BcelWeaver.weave(BcelWeaver.java:1200) at org.aspectj.weaver.tools.WeavingAdaptor.getWovenBytes(WeavingAdaptor.java:360) at org.aspectj.weaver.tools.WeavingAdaptor.weaveClass(WeavingAdaptor.java:262) at org.aspectj.weaver.loadtime.Aj.preProcess(Aj.java:78) at org.aspectj.weaver.loadtime.ClassPreProcessorAgentAdapter.transform(ClassPreProcessorAgentAdapter.java:52) at org.springframework.context.weaving.AspectJWeavingEnabler$AspectJClassBypassingClassFileTransformerDecorator.transform(AspectJWeavingEnabler.java:84) at sun.instrument.TransformerManager.transform(TransformerManager.java:141) at sun.instrument.InstrumentationImpl.transform(InstrumentationImpl.java:174) at java.lang.ClassLoader.defineClassImpl(Native Method) at java.lang.ClassLoader.defineClass(ClassLoader.java:228) at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:148) at java.net.URLClassLoader.defineClass(URLClassLoader.java:557) at java.net.URLClassLoader.access$400(URLClassLoader.java:120) at java.net.URLClassLoader$ClassFinder.run(URLClassLoader.java:962) at java.security.AccessController.doPrivileged(AccessController.java:275) at java.net.URLClassLoader.findClass(URLClassLoader.java:488) at java.lang.ClassLoader.loadClass(ClassLoader.java:607) at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:327) at java.lang.ClassLoader.loadClass(ClassLoader.java:573) at org.eclipse.swt.awt.SWT_AWT.new_Frame(SWT_AWT.java:274)
resolved fixed
1bbe6f9
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2008-02-26T23:54:38Z"
"2008-02-21T18:53:20Z"
weaver5/java5-src/org/aspectj/weaver/reflect/Java15ReflectionBasedReferenceTypeDelegate.java
/* ******************************************************************* * Copyright (c) 2005 Contributors. * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Eclipse Public License v1.0 * which accompanies this distribution and is available at * http://eclipse.org/legal/epl-v10.html * * Contributors: * Adrian Colyer Initial implementation * ******************************************************************/ package org.aspectj.weaver.reflect; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.lang.reflect.Type; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.reflect.AjType; import org.aspectj.lang.reflect.AjTypeSystem; import org.aspectj.lang.reflect.Pointcut; import org.aspectj.weaver.AnnotationX; import org.aspectj.weaver.ReferenceType; import org.aspectj.weaver.ResolvedMember; import org.aspectj.weaver.ResolvedPointcutDefinition; import org.aspectj.weaver.ResolvedType; import org.aspectj.weaver.TypeVariable; import org.aspectj.weaver.TypeVariableReferenceType; import org.aspectj.weaver.UnresolvedType; import org.aspectj.weaver.World; import org.aspectj.weaver.tools.PointcutParameter; /** * @author colyer * Provides Java 5 behaviour in reflection based delegates (overriding * 1.4 behaviour from superclass where appropriate) */ public class Java15ReflectionBasedReferenceTypeDelegate extends ReflectionBasedReferenceTypeDelegate { private AjType<?> myType; private ResolvedType[] annotations; private ResolvedMember[] pointcuts; private ResolvedMember[] methods; private ResolvedMember[] fields; private TypeVariable[] typeVariables; private ResolvedType superclass; private ResolvedType[] superInterfaces; private String genericSignature = null; private JavaLangTypeToResolvedTypeConverter typeConverter; private Java15AnnotationFinder annotationFinder = null; private ArgNameFinder argNameFinder = null; public Java15ReflectionBasedReferenceTypeDelegate() {} @Override public void initialize(ReferenceType aType, Class aClass, ClassLoader classLoader, World aWorld) { super.initialize(aType, aClass, classLoader, aWorld); myType = AjTypeSystem.getAjType(aClass); annotationFinder = new Java15AnnotationFinder(); argNameFinder = annotationFinder; annotationFinder.setClassLoader(this.classLoader); this.typeConverter = new JavaLangTypeToResolvedTypeConverter(aWorld); } public ReferenceType buildGenericType() { return (ReferenceType) UnresolvedType.forGenericTypeVariables( getResolvedTypeX().getSignature(), getTypeVariables()).resolve(getWorld()); } public AnnotationX[] getAnnotations() { // AMC - we seem not to need to implement this method... //throw new UnsupportedOperationException("getAnnotations on Java15ReflectionBasedReferenceTypeDelegate is not implemented yet"); // FIXME is this the right implementation in the reflective case? return super.getAnnotations(); } public ResolvedType[] getAnnotationTypes() { if (annotations == null) { annotations = annotationFinder.getAnnotations(getBaseClass(), getWorld()); } return annotations; } public boolean hasAnnotation(UnresolvedType ofType) { ResolvedType[] myAnns = getAnnotationTypes(); ResolvedType toLookFor = ofType.resolve(getWorld()); for (int i = 0; i < myAnns.length; i++) { if (myAnns[i] == toLookFor) return true; } return false; } // use the MAP to ensure that any aj-synthetic fields are filtered out public ResolvedMember[] getDeclaredFields() { if (fields == null) { Field[] reflectFields = this.myType.getDeclaredFields(); this.fields = new ResolvedMember[reflectFields.length]; for (int i = 0; i < reflectFields.length; i++) { this.fields[i] = createGenericFieldMember(reflectFields[i]); } } return fields; } public String getDeclaredGenericSignature() { if (this.genericSignature == null && isGeneric()) { } return genericSignature; } public ResolvedType[] getDeclaredInterfaces() { if (superInterfaces == null) { Type[] genericInterfaces = getBaseClass().getGenericInterfaces(); this.superInterfaces = typeConverter.fromTypes(genericInterfaces); } return superInterfaces; } // If the superclass is null, return Object - same as bcel does public ResolvedType getSuperclass() { if (superclass == null && getBaseClass()!=Object.class) {// superclass of Object is null Type t = this.getBaseClass().getGenericSuperclass(); if (t!=null) superclass = typeConverter.fromType(t); if (t==null) superclass = getWorld().resolve(UnresolvedType.OBJECT); } return superclass; } public TypeVariable[] getTypeVariables() { TypeVariable[] workInProgressSetOfVariables = (TypeVariable[])getResolvedTypeX().getWorld().getTypeVariablesCurrentlyBeingProcessed(getBaseClass()); if (workInProgressSetOfVariables!=null) { return workInProgressSetOfVariables; } if (this.typeVariables == null) { java.lang.reflect.TypeVariable[] tVars = this.getBaseClass().getTypeParameters(); this.typeVariables = new TypeVariable[tVars.length]; // basic initialization for (int i = 0; i < tVars.length; i++) { typeVariables[i] = new TypeVariable(tVars[i].getName()); } // stash it this.getResolvedTypeX().getWorld().recordTypeVariablesCurrentlyBeingProcessed(getBaseClass(),typeVariables); // now fill in the details... for (int i = 0; i < tVars.length; i++) { TypeVariableReferenceType tvrt = ((TypeVariableReferenceType) typeConverter.fromType(tVars[i])); TypeVariable tv = tvrt.getTypeVariable(); typeVariables[i].setUpperBound(tv.getUpperBound()); typeVariables[i].setAdditionalInterfaceBounds(tv.getAdditionalInterfaceBounds()); typeVariables[i].setDeclaringElement(tv.getDeclaringElement()); typeVariables[i].setDeclaringElementKind(tv.getDeclaringElementKind()); typeVariables[i].setRank(tv.getRank()); typeVariables[i].setLowerBound(tv.getLowerBound()); } this.getResolvedTypeX().getWorld().forgetTypeVariablesCurrentlyBeingProcessed(getBaseClass()); } return this.typeVariables; } // overrides super method since by using the MAP we can filter out advice // methods that really shouldn't be seen in this list public ResolvedMember[] getDeclaredMethods() { if (methods == null) { Method[] reflectMethods = this.myType.getDeclaredMethods(); Constructor[] reflectCons = this.myType.getDeclaredConstructors(); this.methods = new ResolvedMember[reflectMethods.length + reflectCons.length]; for (int i = 0; i < reflectMethods.length; i++) { this.methods[i] = createGenericMethodMember(reflectMethods[i]); } for (int i = 0; i < reflectCons.length; i++) { this.methods[i + reflectMethods.length] = createGenericConstructorMember(reflectCons[i]); } } return methods; } /** * Returns the generic type, regardless of the resolvedType we 'know about' */ public ResolvedType getGenericResolvedType() { ResolvedType rt = getResolvedTypeX(); if (rt.isParameterizedType() || rt.isRawType()) return rt.getGenericType(); return rt; } private ResolvedMember createGenericMethodMember(Method forMethod) { ReflectionBasedResolvedMemberImpl ret = new ReflectionBasedResolvedMemberImpl(org.aspectj.weaver.Member.METHOD, getGenericResolvedType(), forMethod.getModifiers(), typeConverter.fromType(forMethod.getReturnType()), forMethod.getName(), typeConverter.fromTypes(forMethod.getParameterTypes()), typeConverter.fromTypes(forMethod.getExceptionTypes()), forMethod ); ret.setAnnotationFinder(this.annotationFinder); ret.setGenericSignatureInformationProvider(new Java15GenericSignatureInformationProvider(this.getWorld())); return ret; } private ResolvedMember createGenericConstructorMember(Constructor forConstructor) { ReflectionBasedResolvedMemberImpl ret = new ReflectionBasedResolvedMemberImpl(org.aspectj.weaver.Member.METHOD, getGenericResolvedType(), forConstructor.getModifiers(), // to return what BCEL returns the return type is void ResolvedType.VOID,//getGenericResolvedType(), "<init>", typeConverter.fromTypes(forConstructor.getParameterTypes()), typeConverter.fromTypes(forConstructor.getExceptionTypes()), forConstructor ); ret.setAnnotationFinder(this.annotationFinder); ret.setGenericSignatureInformationProvider(new Java15GenericSignatureInformationProvider(this.getWorld())); return ret; } private ResolvedMember createGenericFieldMember(Field forField) { ReflectionBasedResolvedMemberImpl ret = new ReflectionBasedResolvedMemberImpl( org.aspectj.weaver.Member.FIELD, getGenericResolvedType(), forField.getModifiers(), typeConverter.fromType(forField.getType()), forField.getName(), new UnresolvedType[0], forField); ret.setAnnotationFinder(this.annotationFinder); ret.setGenericSignatureInformationProvider(new Java15GenericSignatureInformationProvider(this.getWorld())); return ret; } public ResolvedMember[] getDeclaredPointcuts() { if (pointcuts == null) { Pointcut[] pcs = this.myType.getDeclaredPointcuts(); pointcuts = new ResolvedMember[pcs.length]; InternalUseOnlyPointcutParser parser = null; World world = getWorld(); if (world instanceof ReflectionWorld) { parser = new InternalUseOnlyPointcutParser(classLoader,(ReflectionWorld)getWorld()); } else { parser = new InternalUseOnlyPointcutParser(classLoader); } // phase 1, create legitimate entries in pointcuts[] before we attempt to resolve *any* of the pointcuts // resolution can sometimes cause us to recurse, and this two stage process allows us to cope with that for (int i = 0; i < pcs.length; i++) { AjType<?>[] ptypes = pcs[i].getParameterTypes(); UnresolvedType[] weaverPTypes = new UnresolvedType[ptypes.length]; for (int j = 0; j < weaverPTypes.length; j++) { weaverPTypes[j] = this.typeConverter.fromType(ptypes[j].getJavaClass()) ; } pointcuts[i] = new DeferredResolvedPointcutDefinition(getResolvedTypeX(),pcs[i].getModifiers(),pcs[i].getName(),weaverPTypes); } // phase 2, now go back round and resolve in-place all of the pointcuts PointcutParameter[][] parameters = new PointcutParameter[pcs.length][]; for (int i = 0; i < pcs.length; i++) { AjType<?>[] ptypes = pcs[i].getParameterTypes(); String[] pnames = pcs[i].getParameterNames(); if (pnames.length != ptypes.length) { pnames = tryToDiscoverParameterNames(pcs[i]); if (pnames == null || (pnames.length != ptypes.length)) { throw new IllegalStateException("Required parameter names not available when parsing pointcut " + pcs[i].getName() + " in type " + getResolvedTypeX().getName()); } } parameters[i] = new PointcutParameter[ptypes.length]; for (int j = 0; j < parameters[i].length; j++) { parameters[i][j] = parser.createPointcutParameter(pnames[j],ptypes[j].getJavaClass()); } String pcExpr = pcs[i].getPointcutExpression().toString(); org.aspectj.weaver.patterns.Pointcut pc = parser.resolvePointcutExpression(pcExpr,getBaseClass(),parameters[i]); ((ResolvedPointcutDefinition)pointcuts[i]).setParameterNames(pnames); ((ResolvedPointcutDefinition)pointcuts[i]).setPointcut(pc); } // phase 3, now concretize them all for (int i = 0; i < pointcuts.length; i++) { ResolvedPointcutDefinition rpd = (ResolvedPointcutDefinition) pointcuts[i]; rpd.setPointcut(parser.concretizePointcutExpression(rpd.getPointcut(), getBaseClass(), parameters[i])); } } return pointcuts; } // for @AspectJ pointcuts compiled by javac only... private String[] tryToDiscoverParameterNames(Pointcut pcut) { Method[] ms = pcut.getDeclaringType().getJavaClass().getDeclaredMethods(); for(Method m : ms) { if (m.getName().equals(pcut.getName())) { return argNameFinder.getParameterNames(m); } } return null; } public boolean isAnnotation() { return getBaseClass().isAnnotation(); } public boolean isAnnotationStyleAspect() { return getBaseClass().isAnnotationPresent(Aspect.class); } public boolean isAnnotationWithRuntimeRetention() { if (!isAnnotation()) return false; if (getBaseClass().isAnnotationPresent(Retention.class)) { Retention retention = (Retention) getBaseClass().getAnnotation(Retention.class); RetentionPolicy policy = retention.value(); return policy == RetentionPolicy.RUNTIME; } else { return false; } } public boolean isAspect() { return this.myType.isAspect(); } public boolean isEnum() { return getBaseClass().isEnum(); } public boolean isGeneric() { //return false; // for now return getBaseClass().getTypeParameters().length > 0; } @Override public boolean isAnonymous() { return this.myClass.isAnonymousClass(); } }
220,686
Bug 220686 unsynchronized access to WeakHashMap
null
resolved fixed
caf8960
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2008-02-28T20:50:38Z"
"2008-02-28T00:53:20Z"
weaver/src/org/aspectj/weaver/World.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * 2005 Contributors * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Eclipse Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * PARC initial implementation * Adrian Colyer, Andy Clement, overhaul for generics * ******************************************************************/ package org.aspectj.weaver; import java.lang.ref.ReferenceQueue; import java.lang.ref.SoftReference; import java.lang.ref.WeakReference; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.WeakHashMap; import org.aspectj.asm.IHierarchy; import org.aspectj.bridge.IMessageHandler; import org.aspectj.bridge.ISourceLocation; import org.aspectj.bridge.Message; import org.aspectj.bridge.MessageUtil; import org.aspectj.bridge.IMessage.Kind; import org.aspectj.bridge.context.PinpointingMessageHandler; import org.aspectj.weaver.UnresolvedType.TypeKind; import org.aspectj.weaver.bcel.BcelObjectType; import org.aspectj.weaver.patterns.DeclarePrecedence; import org.aspectj.weaver.patterns.PerClause; import org.aspectj.weaver.patterns.Pointcut; import org.aspectj.weaver.reflect.ReflectionBasedReferenceTypeDelegate; import org.aspectj.weaver.tools.Trace; import org.aspectj.weaver.tools.TraceFactory; /** * A World is a collection of known types and crosscutting members. */ public abstract class World implements Dump.INode { /** handler for any messages produced during resolution etc. */ private IMessageHandler messageHandler = IMessageHandler.SYSTEM_ERR; /** handler for cross-reference information produced during the weaving process */ private ICrossReferenceHandler xrefHandler = null; /** Currently 'active' scope in which to lookup (resolve) typevariable references */ private TypeVariableDeclaringElement typeVariableLookupScope; /** The heart of the world, a map from type signatures to resolved types */ protected TypeMap typeMap = new TypeMap(this); // Signature to ResolvedType // see pr145963 /** Should we create the hierarchy for binary classes and aspects*/ public static boolean createInjarHierarchy = true; /** Calculator for working out aspect precedence */ private AspectPrecedenceCalculator precedenceCalculator; /** All of the type and shadow mungers known to us */ private CrosscuttingMembersSet crosscuttingMembersSet = new CrosscuttingMembersSet(this); /** Model holds ASM relationships */ private IHierarchy model = null; /** for processing Xlint messages */ private Lint lint = new Lint(this); /** XnoInline option setting passed down to weaver */ private boolean XnoInline; /** XlazyTjp option setting passed down to weaver */ private boolean XlazyTjp; /** XhasMember option setting passed down to weaver */ private boolean XhasMember = false; /** Xpinpoint controls whether we put out developer info showing the source of messages */ private boolean Xpinpoint = false; /** When behaving in a Java 5 way autoboxing is considered */ private boolean behaveInJava5Way = false; /** Determines if this world could be used for multiple compiles */ private boolean incrementalCompileCouldFollow = false; /** The level of the aspectjrt.jar the code we generate needs to run on */ private String targetAspectjRuntimeLevel = Constants.RUNTIME_LEVEL_DEFAULT; /** Flags for the new joinpoints that are 'optional' */ private boolean optionalJoinpoint_ArrayConstruction = false; // Command line flag: "-Xjoinpoints:arrayconstruction" private boolean optionalJoinpoint_Synchronization = false; // Command line flag: "-Xjoinpoints:synchronization" private boolean addSerialVerUID = false; private Properties extraConfiguration = null; private boolean checkedAdvancedConfiguration=false; private boolean synchronizationPointcutsInUse = false; // Xset'table options private boolean fastDelegateSupportEnabled = isASMAround; private boolean runMinimalMemory = false; private boolean shouldPipelineCompilation = true; protected boolean bcelRepositoryCaching = xsetBCEL_REPOSITORY_CACHING_DEFAULT.equalsIgnoreCase("true"); private boolean completeBinaryTypes = false; public boolean forDEBUG_structuralChangesCode = false; public boolean forDEBUG_bridgingCode = false; private static Trace trace = TraceFactory.getTraceFactory().getTrace(World.class); // Records whether ASM is around ... so we might use it for delegates protected static boolean isASMAround = false; private long errorThreshold; private long warningThreshold; // static { // try { // Class c = Class.forName("org.aspectj.org.objectweb.asm.ClassVisitor"); // isASMAround = true; // } catch (ClassNotFoundException cnfe) { // isASMAround = false; // } // } /** * A list of RuntimeExceptions containing full stack information for every * type we couldn't find. */ private List dumpState_cantFindTypeExceptions = null; /** * Play God. * On the first day, God created the primitive types and put them in the type * map. */ protected World() { super(); if (trace.isTraceEnabled()) trace.enter("<init>", this); Dump.registerNode(this.getClass(),this); typeMap.put("B", ResolvedType.BYTE); typeMap.put("S", ResolvedType.SHORT); typeMap.put("I", ResolvedType.INT); typeMap.put("J", ResolvedType.LONG); typeMap.put("F", ResolvedType.FLOAT); typeMap.put("D", ResolvedType.DOUBLE); typeMap.put("C", ResolvedType.CHAR); typeMap.put("Z", ResolvedType.BOOLEAN); typeMap.put("V", ResolvedType.VOID); precedenceCalculator = new AspectPrecedenceCalculator(this); if (trace.isTraceEnabled()) trace.exit("<init>"); } /** * Dump processing when a fatal error occurs */ public void accept (Dump.IVisitor visitor) { // visitor.visitObject("Extra configuration:"); // visitor.visitList(extraConfiguration.); visitor.visitObject("Shadow mungers:"); visitor.visitList(crosscuttingMembersSet.getShadowMungers()); visitor.visitObject("Type mungers:"); visitor.visitList(crosscuttingMembersSet.getTypeMungers()); visitor.visitObject("Late Type mungers:"); visitor.visitList(crosscuttingMembersSet.getLateTypeMungers()); if (dumpState_cantFindTypeExceptions!=null) { visitor.visitObject("Cant find type problems:"); visitor.visitList(dumpState_cantFindTypeExceptions); dumpState_cantFindTypeExceptions = null; } } // ============================================================================= // T Y P E R E S O L U T I O N // ============================================================================= /** * Resolve a type that we require to be present in the world */ public ResolvedType resolve(UnresolvedType ty) { return resolve(ty, false); } /** * Attempt to resolve a type - the source location gives you some context in which * resolution is taking place. In the case of an error where we can't find the * type - we can then at least report why (source location) we were trying to resolve it. */ public ResolvedType resolve(UnresolvedType ty,ISourceLocation isl) { ResolvedType ret = resolve(ty,true); if (ResolvedType.isMissing(ty)) { //IMessage msg = null; getLint().cantFindType.signal(WeaverMessages.format(WeaverMessages.CANT_FIND_TYPE,ty.getName()),isl); //if (isl!=null) { //msg = MessageUtil.error(WeaverMessages.format(WeaverMessages.CANT_FIND_TYPE,ty.getName()),isl); //} else { //msg = MessageUtil.error(WeaverMessages.format(WeaverMessages.CANT_FIND_TYPE,ty.getName())); //} //messageHandler.handleMessage(msg); } return ret; } /** * Convenience method for resolving an array of unresolved types * in one hit. Useful for e.g. resolving type parameters in signatures. */ public ResolvedType[] resolve(UnresolvedType[] types) { if (types == null) return new ResolvedType[0]; ResolvedType[] ret = new ResolvedType[types.length]; for (int i=0; i<types.length; i++) { ret[i] = resolve(types[i]); } return ret; } /** * Resolve a type. This the hub of type resolution. The resolved type is added * to the type map by signature. */ public ResolvedType resolve(UnresolvedType ty, boolean allowMissing) { // special resolution processing for already resolved types. if (ty instanceof ResolvedType) { ResolvedType rty = (ResolvedType) ty; rty = resolve(rty); return rty; } // dispatch back to the type variable reference to resolve its constituent parts // don't do this for other unresolved types otherwise you'll end up in a loop if (ty.isTypeVariableReference()) { return ty.resolve(this); } // if we've already got a resolved type for the signature, just return it // after updating the world String signature = ty.getSignature(); ResolvedType ret = typeMap.get(signature); if (ret != null) { ret.world = this; // Set the world for the RTX return ret; } else if ( signature.equals("?") || signature.equals("*")) { // might be a problem here, not sure '?' should make it to here as a signature, the // proper signature for wildcard '?' is '*' // fault in generic wildcard, can't be done earlier because of init issues ResolvedType something = new BoundedReferenceType("?","Ljava/lang/Object",this); typeMap.put("?",something); return something; } // no existing resolved type, create one if (ty.isArray()) { ResolvedType componentType = resolve(ty.getComponentType(),allowMissing); //String brackets = signature.substring(0,signature.lastIndexOf("[")+1); ret = new ResolvedType.Array(signature, "["+componentType.getErasureSignature(), this, componentType); } else { ret = resolveToReferenceType(ty,allowMissing); if (!allowMissing && ret.isMissing()) { ret = handleRequiredMissingTypeDuringResolution(ty); } if (completeBinaryTypes) { completeBinaryType(ret); } } // Pulling in the type may have already put the right entry in the map if (typeMap.get(signature)==null && !ret.isMissing()) { typeMap.put(signature, ret); } return ret; } /** * Called when a type is resolved - enables its type hierarchy to be finished off before we * proceed */ protected void completeBinaryType(ResolvedType ret) {} /** * Return true if the classloader relating to this world is definetly the one that will * define the specified class. Return false otherwise or we don't know for certain. */ public boolean isLocallyDefined(String classname) { return false; } /** * We tried to resolve a type and couldn't find it... */ private ResolvedType handleRequiredMissingTypeDuringResolution(UnresolvedType ty) { // defer the message until someone asks a question of the type that we can't answer // just from the signature. // MessageUtil.error(messageHandler, // WeaverMessages.format(WeaverMessages.CANT_FIND_TYPE,ty.getName())); if (dumpState_cantFindTypeExceptions==null) { dumpState_cantFindTypeExceptions = new ArrayList(); } dumpState_cantFindTypeExceptions.add(new RuntimeException("Can't find type "+ty.getName())); return new MissingResolvedTypeWithKnownSignature(ty.getSignature(),this); } /** * Some TypeFactory operations create resolved types directly, but these won't be * in the typeMap - this resolution process puts them there. Resolved types are * also told their world which is needed for the special autoboxing resolved types. */ public ResolvedType resolve(ResolvedType ty) { if (ty.isTypeVariableReference()) return ty; // until type variables have proper sigs... ResolvedType resolved = typeMap.get(ty.getSignature()); if (resolved == null) { typeMap.put(ty.getSignature(), ty); resolved = ty; } resolved.world = this; return resolved; } /** * Convenience method for finding a type by name and resolving it in one step. */ public ResolvedType resolve(String name) { // trace.enter("resolve", this, new Object[] {name}); ResolvedType ret = resolve(UnresolvedType.forName(name)); // trace.exit("resolve", ret); return ret; } public ResolvedType resolve(String name,boolean allowMissing) { return resolve(UnresolvedType.forName(name),allowMissing); } private ResolvedType currentlyResolvingBaseType; /** * Resolve to a ReferenceType - simple, raw, parameterized, or generic. * Raw, parameterized, and generic versions of a type share a delegate. */ private final ResolvedType resolveToReferenceType(UnresolvedType ty,boolean allowMissing) { if (ty.isParameterizedType()) { // ======= parameterized types ================ ResolvedType rt = resolveGenericTypeFor(ty,allowMissing); if (rt.isMissing()) return rt; ReferenceType genericType = (ReferenceType)rt; currentlyResolvingBaseType = genericType; ReferenceType parameterizedType = TypeFactory.createParameterizedType(genericType, ty.typeParameters, this); currentlyResolvingBaseType = null; return parameterizedType; } else if (ty.isGenericType()) { // ======= generic types ====================== ReferenceType genericType = (ReferenceType)resolveGenericTypeFor(ty,false); return genericType; } else if (ty.isGenericWildcard()) { // ======= generic wildcard types ============= return resolveGenericWildcardFor(ty); } else { // ======= simple and raw types =============== String erasedSignature = ty.getErasureSignature(); ReferenceType simpleOrRawType = new ReferenceType(erasedSignature, this); if (ty.needsModifiableDelegate()) simpleOrRawType.setNeedsModifiableDelegate(true); ReferenceTypeDelegate delegate = resolveDelegate(simpleOrRawType); // 117854 // if (delegate == null) return ResolvedType.MISSING; if (delegate == null) return new MissingResolvedTypeWithKnownSignature(ty.getSignature(),erasedSignature,this);//ResolvedType.MISSING; if (delegate.isGeneric() && behaveInJava5Way) { // ======== raw type =========== simpleOrRawType.typeKind = TypeKind.RAW; ReferenceType genericType = makeGenericTypeFrom(delegate,simpleOrRawType); // name = ReferenceType.fromTypeX(UnresolvedType.forRawTypeNames(ty.getName()),this); simpleOrRawType.setDelegate(delegate); genericType.setDelegate(delegate); simpleOrRawType.setGenericType(genericType); return simpleOrRawType; } else { // ======== simple type ========= simpleOrRawType.setDelegate(delegate); return simpleOrRawType; } } } /** * Attempt to resolve a type that should be a generic type. */ public ResolvedType resolveGenericTypeFor(UnresolvedType anUnresolvedType, boolean allowMissing) { // Look up the raw type by signature String rawSignature = anUnresolvedType.getRawType().getSignature(); ResolvedType rawType = (ResolvedType) typeMap.get(rawSignature); if (rawType==null) { rawType = resolve(UnresolvedType.forSignature(rawSignature),allowMissing); typeMap.put(rawSignature,rawType); } if (rawType.isMissing()) return rawType; // Does the raw type know its generic form? (It will if we created the // raw type from a source type, it won't if its been created just through // being referenced, e.g. java.util.List ResolvedType genericType = rawType.getGenericType(); // There is a special case to consider here (testGenericsBang_pr95993 highlights it) // You may have an unresolvedType for a parameterized type but it // is backed by a simple type rather than a generic type. This occurs for // inner types of generic types that inherit their enclosing types // type variables. if (rawType.isSimpleType() && (anUnresolvedType.typeParameters==null || anUnresolvedType.typeParameters.length==0)) { rawType.world = this; return rawType; } if (genericType != null) { genericType.world = this; return genericType; } else { // Fault in the generic that underpins the raw type ;) ReferenceTypeDelegate delegate = resolveDelegate((ReferenceType)rawType); ReferenceType genericRefType = makeGenericTypeFrom(delegate,((ReferenceType)rawType)); ((ReferenceType)rawType).setGenericType(genericRefType); genericRefType.setDelegate(delegate); ((ReferenceType)rawType).setDelegate(delegate); return genericRefType; } } private ReferenceType makeGenericTypeFrom(ReferenceTypeDelegate delegate, ReferenceType rawType) { String genericSig = delegate.getDeclaredGenericSignature(); if (genericSig != null) { return new ReferenceType( UnresolvedType.forGenericTypeSignature(rawType.getSignature(),delegate.getDeclaredGenericSignature()),this); } else { return new ReferenceType( UnresolvedType.forGenericTypeVariables(rawType.getSignature(), delegate.getTypeVariables()),this); } } /** * Go from an unresolved generic wildcard (represented by UnresolvedType) to a resolved version (BoundedReferenceType). */ private ReferenceType resolveGenericWildcardFor(UnresolvedType aType) { BoundedReferenceType ret = null; // FIXME asc doesnt take account of additional interface bounds (e.g. ? super R & Serializable - can you do that?) if (aType.isExtends()) { ReferenceType upperBound = (ReferenceType)resolve(aType.getUpperBound()); ret = new BoundedReferenceType(upperBound,true,this); } else if (aType.isSuper()) { ReferenceType lowerBound = (ReferenceType) resolve(aType.getLowerBound()); ret = new BoundedReferenceType(lowerBound,false,this); } else { // must be ? on its own! } return ret; } /** * Find the ReferenceTypeDelegate behind this reference type so that it can * fulfill its contract. */ protected abstract ReferenceTypeDelegate resolveDelegate(ReferenceType ty); /** * Special resolution for "core" types like OBJECT. These are resolved just like * any other type, but if they are not found it is more serious and we issue an * error message immediately. */ public ResolvedType getCoreType(UnresolvedType tx) { ResolvedType coreTy = resolve(tx,true); if (coreTy.isMissing()) { MessageUtil.error(messageHandler, WeaverMessages.format(WeaverMessages.CANT_FIND_CORE_TYPE,tx.getName())); } return coreTy; } /** * Lookup a type by signature, if not found then build one and put it in the * map. */ public ReferenceType lookupOrCreateName(UnresolvedType ty) { String signature = ty.getSignature(); ReferenceType ret = lookupBySignature(signature); if (ret == null) { ret = ReferenceType.fromTypeX(ty, this); typeMap.put(signature, ret); } return ret; } /** * Lookup a reference type in the world by its signature. Returns * null if not found. */ public ReferenceType lookupBySignature(String signature) { return (ReferenceType) typeMap.get(signature); } // ============================================================================= // T Y P E R E S O L U T I O N -- E N D // ============================================================================= /** * Member resolution is achieved by resolving the declaring type and then * looking up the member in the resolved declaring type. */ public ResolvedMember resolve(Member member) { ResolvedType declaring = member.getDeclaringType().resolve(this); if (declaring.isRawType()) declaring = declaring.getGenericType(); ResolvedMember ret; if (member.getKind() == Member.FIELD) { ret = declaring.lookupField(member); } else { ret = declaring.lookupMethod(member); } if (ret != null) return ret; return declaring.lookupSyntheticMember(member); } // Methods for creating various cross-cutting members... // =========================================================== /** * Create an advice shadow munger from the given advice attribute */ public abstract Advice createAdviceMunger( AjAttribute.AdviceAttribute attribute, Pointcut pointcut, Member signature); /** * Create an advice shadow munger for the given advice kind */ public final Advice createAdviceMunger( AdviceKind kind, Pointcut p, Member signature, int extraParameterFlags, IHasSourceLocation loc) { AjAttribute.AdviceAttribute attribute = new AjAttribute.AdviceAttribute(kind, p, extraParameterFlags, loc.getStart(), loc.getEnd(), loc.getSourceContext()); return createAdviceMunger(attribute, p, signature); } public abstract ConcreteTypeMunger makeCflowStackFieldAdder(ResolvedMember cflowField); public abstract ConcreteTypeMunger makeCflowCounterFieldAdder(ResolvedMember cflowField); /** * Register a munger for perclause @AJ aspect so that we add aspectOf(..) to them as needed * @see org.aspectj.weaver.bcel.BcelWorld#makePerClauseAspect(ResolvedType, org.aspectj.weaver.patterns.PerClause.Kind) */ public abstract ConcreteTypeMunger makePerClauseAspect(ResolvedType aspect, PerClause.Kind kind); public abstract ConcreteTypeMunger concreteTypeMunger(ResolvedTypeMunger munger, ResolvedType aspectType); /** * Same signature as org.aspectj.util.PartialOrder.PartialComparable.compareTo */ public int compareByPrecedence(ResolvedType aspect1, ResolvedType aspect2) { return precedenceCalculator.compareByPrecedence(aspect1, aspect2); } public Integer getPrecedenceIfAny(ResolvedType aspect1, ResolvedType aspect2) { return precedenceCalculator.getPrecedenceIfAny(aspect1, aspect2); } /** * compares by precedence with the additional rule that a super-aspect is * sorted before its sub-aspects */ public int compareByPrecedenceAndHierarchy(ResolvedType aspect1, ResolvedType aspect2) { return precedenceCalculator.compareByPrecedenceAndHierarchy(aspect1, aspect2); } // simple property getter and setters // =========================================================== /** * Nobody should hold onto a copy of this message handler, or setMessageHandler won't * work right. */ public IMessageHandler getMessageHandler() { return messageHandler; } public void setMessageHandler(IMessageHandler messageHandler) { if (this.isInPinpointMode()) { this.messageHandler = new PinpointingMessageHandler(messageHandler); } else { this.messageHandler = messageHandler; } } /** * convenenience method for creating and issuing messages via the message handler - * if you supply two locations you will get two messages. */ public void showMessage( Kind kind, String message, ISourceLocation loc1, ISourceLocation loc2) { if (loc1 != null) { messageHandler.handleMessage(new Message(message, kind, null, loc1)); if (loc2 != null) { messageHandler.handleMessage(new Message(message, kind, null, loc2)); } } else { messageHandler.handleMessage(new Message(message, kind, null, loc2)); } } public boolean debug (String message) { return MessageUtil.debug(messageHandler,message); } public void setCrossReferenceHandler(ICrossReferenceHandler xrefHandler) { this.xrefHandler = xrefHandler; } /** * Get the cross-reference handler for the world, may be null. */ public ICrossReferenceHandler getCrossReferenceHandler() { return this.xrefHandler; } public void setTypeVariableLookupScope(TypeVariableDeclaringElement scope) { this.typeVariableLookupScope = scope; } public TypeVariableDeclaringElement getTypeVariableLookupScope() { return typeVariableLookupScope; } public List getDeclareParents() { return crosscuttingMembersSet.getDeclareParents(); } public List getDeclareAnnotationOnTypes() { return crosscuttingMembersSet.getDeclareAnnotationOnTypes(); } public List getDeclareAnnotationOnFields() { return crosscuttingMembersSet.getDeclareAnnotationOnFields(); } public List getDeclareAnnotationOnMethods() { return crosscuttingMembersSet.getDeclareAnnotationOnMethods(); } public List getDeclareSoft() { return crosscuttingMembersSet.getDeclareSofts(); } public CrosscuttingMembersSet getCrosscuttingMembersSet() { return crosscuttingMembersSet; } public IHierarchy getModel() { return model; } public void setModel(IHierarchy model) { this.model = model; } public Lint getLint() { return lint; } public void setLint(Lint lint) { this.lint = lint; } public boolean isXnoInline() { return XnoInline; } public void setXnoInline(boolean xnoInline) { XnoInline = xnoInline; } public boolean isXlazyTjp() { return XlazyTjp; } public void setXlazyTjp(boolean b) { XlazyTjp = b; } public boolean isHasMemberSupportEnabled() { return XhasMember; } public void setXHasMemberSupportEnabled(boolean b) { XhasMember = b; } public boolean isInPinpointMode() { return Xpinpoint; } public void setPinpointMode(boolean b) { this.Xpinpoint = b; } public void setBehaveInJava5Way(boolean b) { behaveInJava5Way = b; } /** * Set the error and warning threashold which can be taken from * CompilerOptions (see bug 129282) * * @param errorThreshold * @param warningThreshold */ public void setErrorAndWarningThreshold(long errorThreshold, long warningThreshold) { this.errorThreshold = errorThreshold; this.warningThreshold = warningThreshold; } /** * @return true if ignoring the UnusedDeclaredThrownException and false if * this compiler option is set to error or warning */ public boolean isIgnoringUnusedDeclaredThrownException() { // the 0x800000 is CompilerOptions.UnusedDeclaredThrownException // which is ASTNode.bit24 if((this.errorThreshold & 0x800000) != 0 || (this.warningThreshold & 0x800000) != 0) return false; return true; } public void performExtraConfiguration(String config) { if (config==null) return; // Bunch of name value pairs to split extraConfiguration = new Properties(); int pos =-1; while ((pos=config.indexOf(","))!=-1) { String nvpair = config.substring(0,pos); int pos2 = nvpair.indexOf("="); if (pos2!=-1) { String n = nvpair.substring(0,pos2); String v = nvpair.substring(pos2+1); extraConfiguration.setProperty(n,v); } config = config.substring(pos+1); } if (config.length()>0) { int pos2 = config.indexOf("="); if (pos2!=-1) { String n = config.substring(0,pos2); String v = config.substring(pos2+1); extraConfiguration.setProperty(n,v); } } ensureAdvancedConfigurationProcessed(); } /** * may return null */ public Properties getExtraConfiguration() { return extraConfiguration; } public final static String xsetWEAVE_JAVA_PACKAGES = "weaveJavaPackages"; // default false - controls LTW public final static String xsetWEAVE_JAVAX_PACKAGES = "weaveJavaxPackages"; // default false - controls LTW public final static String xsetCAPTURE_ALL_CONTEXT = "captureAllContext"; // default false public final static String xsetACTIVATE_LIGHTWEIGHT_DELEGATES = "activateLightweightDelegates"; // default true public final static String xsetRUN_MINIMAL_MEMORY ="runMinimalMemory"; // default true public final static String xsetDEBUG_STRUCTURAL_CHANGES_CODE = "debugStructuralChangesCode"; // default false public final static String xsetDEBUG_BRIDGING = "debugBridging"; // default false public final static String xsetBCEL_REPOSITORY_CACHING = "bcelRepositoryCaching"; public final static String xsetPIPELINE_COMPILATION = "pipelineCompilation"; public final static String xsetPIPELINE_COMPILATION_DEFAULT = "true"; public final static String xsetCOMPLETE_BINARY_TYPES = "completeBinaryTypes"; public final static String xsetCOMPLETE_BINARY_TYPES_DEFAULT = "false"; public final static String xsetBCEL_REPOSITORY_CACHING_DEFAULT = "true"; public boolean isInJava5Mode() { return behaveInJava5Way; } public void setTargetAspectjRuntimeLevel(String s) { targetAspectjRuntimeLevel = s; } public void setOptionalJoinpoints(String jps) { if (jps==null) return; if (jps.indexOf("arrayconstruction")!=-1) optionalJoinpoint_ArrayConstruction = true; if (jps.indexOf("synchronization")!=-1) optionalJoinpoint_Synchronization = true; } public boolean isJoinpointArrayConstructionEnabled() { return optionalJoinpoint_ArrayConstruction; } public boolean isJoinpointSynchronizationEnabled() { return optionalJoinpoint_Synchronization; } public String getTargetAspectjRuntimeLevel() { return targetAspectjRuntimeLevel; } public boolean isTargettingAspectJRuntime12() { boolean b = false; // pr116679 if (!isInJava5Mode()) b=true; else b = getTargetAspectjRuntimeLevel().equals(org.aspectj.weaver.Constants.RUNTIME_LEVEL_12); //System.err.println("Asked if targetting runtime 1.2 , returning: "+b); return b; } /* * Map of types in the world, can have 'references' to expendable ones which * can be garbage collected to recover memory. * An expendable type is a reference type that is not exposed to the weaver (ie * just pulled in for type resolution purposes). */ protected static class TypeMap { private static boolean debug = false; // Strategy for entries in the expendable map public static int DONT_USE_REFS = 0; // Hang around forever public static int USE_WEAK_REFS = 1; // Collected asap public static int USE_SOFT_REFS = 2; // Collected when short on memory // SECRETAPI - Can switch to a policy of choice ;) public static int policy = USE_SOFT_REFS; // Map of types that never get thrown away private Map /* String -> ResolvedType */ tMap = new HashMap(); // Map of types that may be ejected from the cache if we need space private Map expendableMap = new WeakHashMap(); private World w; // profiling tools... private boolean memoryProfiling = false; private int maxExpendableMapSize = -1; private int collectedTypes = 0; private ReferenceQueue rq = new ReferenceQueue(); private static Trace trace = TraceFactory.getTraceFactory().getTrace(World.TypeMap.class); TypeMap(World w) { if (trace.isTraceEnabled()) trace.enter("<init>",this,w); this.w = w; memoryProfiling = false;// !w.getMessageHandler().isIgnoring(Message.INFO); if (trace.isTraceEnabled()) trace.exit("<init>"); } /** * Add a new type into the map, the key is the type signature. * Some types do *not* go in the map, these are ones involving * *member* type variables. The reason is that when all you have is the * signature which gives you a type variable name, you cannot * guarantee you are using the type variable in the same way * as someone previously working with a similarly * named type variable. So, these do not go into the map: * - TypeVariableReferenceType. * - ParameterizedType where a member type variable is involved. * - BoundedReferenceType when one of the bounds is a type variable. * * definition: "member type variables" - a tvar declared on a generic * method/ctor as opposed to those you see declared on a generic type. */ public ResolvedType put(String key, ResolvedType type) { if (type.isParameterizedType() && type.isParameterizedWithAMemberTypeVariable()) { if (debug) System.err.println("Not putting a parameterized type that utilises member declared type variables into the typemap: key="+key+" type="+type); return type; } if (type.isTypeVariableReference()) { if (debug) System.err.println("Not putting a type variable reference type into the typemap: key="+key+" type="+type); return type; } // this test should be improved - only avoid putting them in if one of the // bounds is a member type variable if (type instanceof BoundedReferenceType) { if (debug) System.err.println("Not putting a bounded reference type into the typemap: key="+key+" type="+type); return type; } if (type instanceof MissingResolvedTypeWithKnownSignature) { if (debug) System.err.println("Not putting a missing type into the typemap: key="+key+" type="+type); return type; } if ((type instanceof ReferenceType) && (((ReferenceType)type).getDelegate()==null) && w.isExpendable(type)) { if (debug) System.err.println("Not putting expendable ref type with null delegate into typemap: key="+key+" type="+type); return type; } if (w.isExpendable(type)) { // Dont use reference queue for tracking if not profiling... if (policy==USE_WEAK_REFS) { if (memoryProfiling) expendableMap.put(key,new WeakReference(type,rq)); else expendableMap.put(key,new WeakReference(type)); } else if (policy==USE_SOFT_REFS) { if (memoryProfiling) expendableMap.put(key,new SoftReference(type,rq)); else expendableMap.put(key,new SoftReference(type)); } else { expendableMap.put(key,type); } if (memoryProfiling && expendableMap.size()>maxExpendableMapSize) { maxExpendableMapSize = expendableMap.size(); } return type; } else { return (ResolvedType) tMap.put(key,type); } } public void report() { if (!memoryProfiling) return; checkq(); w.getMessageHandler().handleMessage(MessageUtil.info("MEMORY: world expendable type map reached maximum size of #"+maxExpendableMapSize+" entries")); w.getMessageHandler().handleMessage(MessageUtil.info("MEMORY: types collected through garbage collection #"+collectedTypes+" entries")); } public void checkq() { if (!memoryProfiling) return; while (rq.poll()!=null) collectedTypes++; } /** * Lookup a type by its signature, always look * in the real map before the expendable map */ public ResolvedType get(String key) { checkq(); ResolvedType ret = (ResolvedType) tMap.get(key); if (ret == null) { if (policy==USE_WEAK_REFS) { WeakReference ref = (WeakReference)expendableMap.get(key); if (ref != null) { ret = (ResolvedType) ref.get(); } } else if (policy==USE_SOFT_REFS) { SoftReference ref = (SoftReference)expendableMap.get(key); if (ref != null) { ret = (ResolvedType) ref.get(); } } else { return (ResolvedType)expendableMap.get(key); } } return ret; } /** Remove a type from the map */ public ResolvedType remove(String key) { ResolvedType ret = (ResolvedType) tMap.remove(key); if (ret == null) { if (policy==USE_WEAK_REFS) { WeakReference wref = (WeakReference)expendableMap.remove(key); if (wref!=null) ret = (ResolvedType)wref.get(); } else if (policy==USE_SOFT_REFS) { SoftReference wref = (SoftReference)expendableMap.remove(key); if (wref!=null) ret = (ResolvedType)wref.get(); } else { ret = (ResolvedType)expendableMap.remove(key); } } return ret; } public String toString() { StringBuffer sb = new StringBuffer(); sb.append("types:\n"); sb.append(dumpthem(tMap)); sb.append("expendables:\n"); sb.append(dumpthem(expendableMap)); return sb.toString(); } private String dumpthem(Map m) { StringBuffer sb = new StringBuffer(); int otherTypes = 0; int bcelDel = 0; int refDel = 0; for (Iterator iter = m.entrySet().iterator(); iter.hasNext();) { Map.Entry entry = (Map.Entry) iter.next(); Object val = entry.getValue(); if (val instanceof WeakReference) { val = ((WeakReference)val).get(); } else if (val instanceof SoftReference) { val = ((SoftReference)val).get(); } sb.append(entry.getKey()+"="+val).append("\n"); if (val instanceof ReferenceType) { ReferenceType refType = (ReferenceType)val; if (refType.getDelegate() instanceof BcelObjectType) { bcelDel++; } else if (refType.getDelegate() instanceof ReflectionBasedReferenceTypeDelegate) { refDel++; } else { otherTypes++; } } else { otherTypes++; } } sb.append("# BCEL = "+bcelDel+", # REF = "+refDel+", # Other = "+otherTypes); return sb.toString(); } public int totalSize() { return tMap.size()+expendableMap.size(); } public int hardSize() { return tMap.size(); } public ResolvedType[] getAllTypes() { List/*ResolvedType*/ results = new ArrayList(); collectTypes(expendableMap, results); collectTypes(tMap, results); return (ResolvedType[]) results.toArray(new ResolvedType[results.size()]); } private void collectTypes(Map map, List/*ResolvedType*/ results) { for (Iterator iterator = map.keySet().iterator(); iterator.hasNext();) { String key = (String) iterator.next(); ResolvedType type = get((String)key); if (type!=null) results.add(type); else System.err.println("null!:"+key); } } } /** Reference types we don't intend to weave may be ejected from * the cache if we need the space. */ protected boolean isExpendable(ResolvedType type) { return ( !type.equals(UnresolvedType.OBJECT) && (type != null) && (!type.isExposedToWeaver()) && (!type.isPrimitiveType()) ); } /** * This class is used to compute and store precedence relationships between * aspects. */ private static class AspectPrecedenceCalculator { private World world; private Map cachedResults; public AspectPrecedenceCalculator(World forSomeWorld) { this.world = forSomeWorld; this.cachedResults = new HashMap(); } /** * Ask every declare precedence in the world to order the two aspects. * If more than one declare precedence gives an ordering, and the orderings * conflict, then that's an error. */ public int compareByPrecedence(ResolvedType firstAspect, ResolvedType secondAspect) { PrecedenceCacheKey key = new PrecedenceCacheKey(firstAspect,secondAspect); if (cachedResults.containsKey(key)) { return ((Integer) cachedResults.get(key)).intValue(); } else { int order = 0; DeclarePrecedence orderer = null; // Records the declare precedence statement that gives the first ordering for (Iterator i = world.getCrosscuttingMembersSet().getDeclareDominates().iterator(); i.hasNext(); ) { DeclarePrecedence d = (DeclarePrecedence)i.next(); int thisOrder = d.compare(firstAspect, secondAspect); if (thisOrder != 0) { if (orderer==null) orderer = d; if (order != 0 && order != thisOrder) { ISourceLocation[] isls = new ISourceLocation[2]; isls[0]=orderer.getSourceLocation(); isls[1]=d.getSourceLocation(); Message m = new Message("conflicting declare precedence orderings for aspects: "+ firstAspect.getName()+" and "+secondAspect.getName(),null,true,isls); world.getMessageHandler().handleMessage(m); } else { order = thisOrder; } } } cachedResults.put(key, new Integer(order)); return order; } } public Integer getPrecedenceIfAny(ResolvedType aspect1,ResolvedType aspect2) { return (Integer)cachedResults.get(new PrecedenceCacheKey(aspect1,aspect2)); } public int compareByPrecedenceAndHierarchy(ResolvedType firstAspect, ResolvedType secondAspect) { if (firstAspect.equals(secondAspect)) return 0; int ret = compareByPrecedence(firstAspect, secondAspect); if (ret != 0) return ret; if (firstAspect.isAssignableFrom(secondAspect)) return -1; else if (secondAspect.isAssignableFrom(firstAspect)) return +1; return 0; } private static class PrecedenceCacheKey { public ResolvedType aspect1; public ResolvedType aspect2; public PrecedenceCacheKey(ResolvedType a1, ResolvedType a2) { this.aspect1 = a1; this.aspect2 = a2; } public boolean equals(Object obj) { if (!(obj instanceof PrecedenceCacheKey)) return false; PrecedenceCacheKey other = (PrecedenceCacheKey) obj; return (aspect1 == other.aspect1 && aspect2 == other.aspect2); } public int hashCode() { return aspect1.hashCode() + aspect2.hashCode(); } } } public void validateType(UnresolvedType type) { } // --- with java5 we can get into a recursive mess if we aren't careful when resolving types (*cough* java.lang.Enum) --- // --- this first map is for java15 delegates which may try and recursively access the same type variables. // --- I would rather stash this against a reference type - but we don't guarantee referencetypes are unique for // so we can't :( private Map workInProgress1 = new HashMap(); public TypeVariable[] getTypeVariablesCurrentlyBeingProcessed(Class baseClass) { return (TypeVariable[])workInProgress1.get(baseClass); } public void recordTypeVariablesCurrentlyBeingProcessed(Class baseClass, TypeVariable[] typeVariables) { workInProgress1.put(baseClass,typeVariables); } public void forgetTypeVariablesCurrentlyBeingProcessed(Class baseClass) { workInProgress1.remove(baseClass); } public void setAddSerialVerUID(boolean b) { addSerialVerUID=b;} public boolean isAddSerialVerUID() { return addSerialVerUID;} /** be careful calling this - pr152257 */ public void flush() { typeMap.expendableMap.clear(); } public void ensureAdvancedConfigurationProcessed() { // Check *once* whether the user has switched asm support off if (!checkedAdvancedConfiguration) { Properties p = getExtraConfiguration(); if (p!=null) { if (isASMAround) { // dont bother if its not... String s = p.getProperty(xsetACTIVATE_LIGHTWEIGHT_DELEGATES,"true"); fastDelegateSupportEnabled = s.equalsIgnoreCase("true"); if (!fastDelegateSupportEnabled) getMessageHandler().handleMessage(MessageUtil.info("[activateLightweightDelegates=false] Disabling optimization to use lightweight delegates for non-woven types")); } String s = p.getProperty(xsetBCEL_REPOSITORY_CACHING,xsetBCEL_REPOSITORY_CACHING_DEFAULT); bcelRepositoryCaching = s.equalsIgnoreCase("true"); if (!bcelRepositoryCaching) { getMessageHandler().handleMessage(MessageUtil.info("[bcelRepositoryCaching=false] AspectJ will not use a bcel cache for class information")); } s = p.getProperty(xsetPIPELINE_COMPILATION,xsetPIPELINE_COMPILATION_DEFAULT); shouldPipelineCompilation = s.equalsIgnoreCase("true"); s = p.getProperty(xsetCOMPLETE_BINARY_TYPES,xsetCOMPLETE_BINARY_TYPES_DEFAULT); completeBinaryTypes = s.equalsIgnoreCase("true"); if (completeBinaryTypes) { getMessageHandler().handleMessage(MessageUtil.info("[completeBinaryTypes=true] Completion of binary types activated")); } s = p.getProperty(xsetRUN_MINIMAL_MEMORY,"false"); runMinimalMemory = s.equalsIgnoreCase("true"); // if (runMinimalMemory) // getMessageHandler().handleMessage(MessageUtil.info("[runMinimalMemory=true] Optimizing bcel processing (and cost of performance) to use less memory")); s = p.getProperty(xsetDEBUG_STRUCTURAL_CHANGES_CODE,"false"); forDEBUG_structuralChangesCode = s.equalsIgnoreCase("true"); s = p.getProperty(xsetDEBUG_BRIDGING,"false"); forDEBUG_bridgingCode = s.equalsIgnoreCase("true"); } checkedAdvancedConfiguration=true; } } public boolean isRunMinimalMemory() { ensureAdvancedConfigurationProcessed(); return runMinimalMemory; } public boolean shouldPipelineCompilation() { ensureAdvancedConfigurationProcessed(); return shouldPipelineCompilation; } public void setFastDelegateSupport(boolean b) { if (b && !isASMAround) { throw new BCException("Unable to activate fast delegate support, ASM classes cannot be found"); } fastDelegateSupportEnabled = b; } public boolean isFastDelegateSupportEnabled() { return false; // ASM not currently being used // ensureAdvancedConfigurationProcessed(); // return fastDelegateSupportEnabled; } public void setIncrementalCompileCouldFollow(boolean b) {incrementalCompileCouldFollow = b;} public boolean couldIncrementalCompileFollow() {return incrementalCompileCouldFollow;} public void setSynchronizationPointcutsInUse() { if (trace.isTraceEnabled()) trace.enter("setSynchronizationPointcutsInUse", this); synchronizationPointcutsInUse =true; if (trace.isTraceEnabled()) trace.exit("setSynchronizationPointcutsInUse"); } public boolean areSynchronizationPointcutsInUse() {return synchronizationPointcutsInUse;} public boolean isASMAround() { return isASMAround; } public ResolvedType[] getAllTypes() { return typeMap.getAllTypes(); } }
193,348
Bug 193348 NPE on attempt to compile
I can't really pinpoint any code that trigger this. It happens on for an incremental, and only some of the time. If I do a full build of the project then I do not get the error and all seems to work. ---- java.lang.NullPointerException at org.aspectj.weaver.bcel.BcelWeaver.raiseUnboundFormalError(BcelWeaver.java:833) at org.aspectj.weaver.bcel.BcelWeaver.validateSingleBranch(BcelWeaver.java:688) at org.aspectj.weaver.bcel.BcelWeaver.validateBindings(BcelWeaver.java:627) at org.aspectj.weaver.bcel.BcelWeaver.rewritePointcuts(BcelWeaver.java:556) at org.aspectj.weaver.bcel.BcelWeaver.prepareForWeave(BcelWeaver.java:484) at org.aspectj.ajd ... oBuildJob.run(AutoBuildJob.java:235) at org.eclipse.core.internal.jobs.Worker.run(Worker.java:55) Compile error: NullPointerException thrown: null
resolved fixed
a31b3de
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2008-03-10T18:09:16Z"
"2007-06-19T16:20:00Z"
weaver/src/org/aspectj/weaver/bcel/BcelWeaver.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Eclipse Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * PARC initial implementation * Alexandre Vasseur support for @AJ aspects * ******************************************************************/ package org.aspectj.weaver.bcel; import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileFilter; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.Enumeration; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.jar.Attributes; import java.util.jar.JarEntry; import java.util.jar.JarFile; import java.util.jar.Manifest; import java.util.jar.Attributes.Name; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; import java.util.zip.ZipOutputStream; import org.aspectj.apache.bcel.classfile.ClassParser; import org.aspectj.apache.bcel.classfile.JavaClass; import org.aspectj.asm.AsmManager; import org.aspectj.bridge.IMessage; import org.aspectj.bridge.IProgressListener; import org.aspectj.bridge.ISourceLocation; import org.aspectj.bridge.Message; import org.aspectj.bridge.MessageUtil; import org.aspectj.bridge.SourceLocation; import org.aspectj.bridge.WeaveMessage; import org.aspectj.bridge.context.CompilationAndWeavingContext; import org.aspectj.bridge.context.ContextToken; import org.aspectj.util.FileUtil; import org.aspectj.util.FuzzyBoolean; import org.aspectj.weaver.Advice; import org.aspectj.weaver.AnnotationOnTypeMunger; import org.aspectj.weaver.AnnotationX; import org.aspectj.weaver.AsmRelationshipProvider; import org.aspectj.weaver.BCException; import org.aspectj.weaver.ConcreteTypeMunger; import org.aspectj.weaver.CrosscuttingMembersSet; import org.aspectj.weaver.CustomMungerFactory; import org.aspectj.weaver.IClassFileProvider; import org.aspectj.weaver.IWeaveRequestor; import org.aspectj.weaver.IWeaver; import org.aspectj.weaver.NewParentTypeMunger; import org.aspectj.weaver.ReferenceType; import org.aspectj.weaver.ReferenceTypeDelegate; import org.aspectj.weaver.ResolvedTypeMunger; import org.aspectj.weaver.ResolvedType; import org.aspectj.weaver.Shadow; import org.aspectj.weaver.ShadowMunger; import org.aspectj.weaver.UnresolvedType; import org.aspectj.weaver.WeaverMessages; import org.aspectj.weaver.WeaverMetrics; import org.aspectj.weaver.WeaverStateInfo; import org.aspectj.weaver.World; import org.aspectj.weaver.patterns.AndPointcut; import org.aspectj.weaver.patterns.BindingAnnotationTypePattern; import org.aspectj.weaver.patterns.BindingTypePattern; import org.aspectj.weaver.patterns.CflowPointcut; import org.aspectj.weaver.patterns.ConcreteCflowPointcut; import org.aspectj.weaver.patterns.DeclareAnnotation; import org.aspectj.weaver.patterns.DeclareParents; import org.aspectj.weaver.patterns.FastMatchInfo; import org.aspectj.weaver.patterns.IfPointcut; import org.aspectj.weaver.patterns.KindedPointcut; import org.aspectj.weaver.patterns.NameBindingPointcut; import org.aspectj.weaver.patterns.NotPointcut; import org.aspectj.weaver.patterns.OrPointcut; import org.aspectj.weaver.patterns.Pointcut; import org.aspectj.weaver.patterns.PointcutRewriter; import org.aspectj.weaver.patterns.WithinPointcut; import org.aspectj.weaver.tools.Trace; import org.aspectj.weaver.tools.TraceFactory; public class BcelWeaver implements IWeaver { private BcelWorld world; private CrosscuttingMembersSet xcutSet; private IProgressListener progressListener = null; private double progressMade; private double progressPerClassFile; private boolean inReweavableMode = false; private static Trace trace = TraceFactory.getTraceFactory().getTrace(BcelWeaver.class); public BcelWeaver(BcelWorld world) { super(); if (trace.isTraceEnabled()) trace.enter("<init>",this,world); WeaverMetrics.reset(); this.world = world; this.xcutSet = world.getCrosscuttingMembersSet(); if (trace.isTraceEnabled()) trace.exit("<init>"); } public BcelWeaver() { this(new BcelWorld()); } // ---- fields // private Map sourceJavaClasses = new HashMap(); /* String -> UnwovenClassFile */ private List addedClasses = new ArrayList(); /* List<UnovenClassFile> */ private List deletedTypenames = new ArrayList(); /* List<String> */ // private Map resources = new HashMap(); /* String -> UnwovenClassFile */ private Manifest manifest = null; private boolean needToReweaveWorld = false; private boolean isBatchWeave = true; private List shadowMungerList = null; // setup by prepareForWeave private List typeMungerList = null; // setup by prepareForWeave private List lateTypeMungerList = null; // setup by prepareForWeave private List declareParentsList = null; // setup by prepareForWeave private ZipOutputStream zipOutputStream; private CustomMungerFactory customMungerFactory; // ---- // only called for testing public void setShadowMungers(List l) { shadowMungerList = l; } /** * Add the given aspect to the weaver. * The type is resolved to support DOT for static inner classes as well as DOLLAR * * @param aspectName * @return aspect */ public ResolvedType addLibraryAspect(String aspectName) { if (trace.isTraceEnabled()) trace.enter("addLibraryAspect",this,aspectName); // 1 - resolve as is UnresolvedType unresolvedT = UnresolvedType.forName(aspectName); unresolvedT.setNeedsModifiableDelegate(true); ResolvedType type = world.resolve(unresolvedT, true); if (type.isMissing()) { // fallback on inner class lookup mechanism String fixedName = aspectName; int hasDot = fixedName.lastIndexOf('.'); while (hasDot > 0) { //System.out.println("BcelWeaver.addLibraryAspect " + fixedName); char[] fixedNameChars = fixedName.toCharArray(); fixedNameChars[hasDot] = '$'; fixedName = new String(fixedNameChars); hasDot = fixedName.lastIndexOf('.'); UnresolvedType ut = UnresolvedType.forName(fixedName); ut.setNeedsModifiableDelegate(true); type = world.resolve(ut, true); if (!type.isMissing()) { break; } } } //System.out.println("type: " + type + " for " + aspectName); if (type.isAspect()) { // Bug 119657 ensure we use the unwoven aspect WeaverStateInfo wsi = type.getWeaverState(); if (wsi != null && wsi.isReweavable()) { BcelObjectType classType = getClassType(type.getName()); JavaClass wovenJavaClass = classType.getJavaClass(); JavaClass unwovenJavaClass = Utility.makeJavaClass(wovenJavaClass.getFileName(), wsi.getUnwovenClassFileData(wovenJavaClass.getBytes())); world.storeClass(unwovenJavaClass); classType.setJavaClass(unwovenJavaClass); // classType.setJavaClass(Utility.makeJavaClass(classType.getJavaClass().getFileName(), wsi.getUnwovenClassFileData(classType.getJavaClass().getBytes()))); } //TODO AV - happens to reach that a lot of time: for each type flagged reweavable X for each aspect in the weaverstate //=> mainly for nothing for LTW - pbly for something in incremental build... xcutSet.addOrReplaceAspect(type); if (trace.isTraceEnabled()) trace.exit("addLibraryAspect",type); return type; } else { // FIXME AV - better warning upon no such aspect from aop.xml RuntimeException ex = new RuntimeException("Cannot register non aspect: " + type.getName() + " , " + aspectName); if (trace.isTraceEnabled()) trace.exit("addLibraryAspect",ex); throw ex; } } /** * * @param inFile File path to class directory or zip/jar class archive * @throws IOException */ public void addLibraryJarFile(File inFile) throws IOException { List addedAspects = null; if (inFile.isDirectory()) { addedAspects = addAspectsFromDirectory(inFile); } else { addedAspects = addAspectsFromJarFile(inFile); } for (Iterator i = addedAspects.iterator(); i.hasNext();) { ResolvedType aspectX = (ResolvedType) i.next(); xcutSet.addOrReplaceAspect(aspectX); } } private List addAspectsFromJarFile(File inFile) throws FileNotFoundException, IOException { ZipInputStream inStream = new ZipInputStream(new FileInputStream(inFile)); //??? buffered List addedAspects = new ArrayList(); while (true) { ZipEntry entry = inStream.getNextEntry(); if (entry == null) break; if (entry.isDirectory() || !entry.getName().endsWith(".class")) { continue; } // FIXME ASC performance? of this alternative soln. ClassParser parser = new ClassParser(new ByteArrayInputStream(FileUtil.readAsByteArray(inStream)), entry.getName()); JavaClass jc = parser.parse(); inStream.closeEntry(); ResolvedType type = world.addSourceObjectType(jc).getResolvedTypeX(); type.setBinaryPath(inFile.getAbsolutePath()); if (type.isAspect()) { addedAspects.add(type); } } inStream.close(); return addedAspects; } private List addAspectsFromDirectory(File dir) throws FileNotFoundException, IOException{ List addedAspects = new ArrayList(); File[] classFiles = FileUtil.listFiles(dir,new FileFilter(){ public boolean accept(File pathname) { return pathname.getName().endsWith(".class"); } }); for (int i = 0; i < classFiles.length; i++) { FileInputStream fis = new FileInputStream(classFiles[i]); byte[] bytes = FileUtil.readAsByteArray(fis); addIfAspect(bytes,classFiles[i].getAbsolutePath(),addedAspects); fis.close(); } return addedAspects; } private void addIfAspect(byte[] bytes, String name, List toList) throws IOException { ClassParser parser = new ClassParser(new ByteArrayInputStream(bytes),name); JavaClass jc = parser.parse(); ResolvedType type = world.addSourceObjectType(jc).getResolvedTypeX(); String typeName = type.getName().replace('.', File.separatorChar); int end = name.indexOf(typeName); String binaryPath = name.substring(0,end-1); type.setBinaryPath(binaryPath); if (type.isAspect()) { toList.add(type); } } // // The ANT copy task should be used to copy resources across. // private final static boolean CopyResourcesFromInpathDirectoriesToOutput=false; /** * Add any .class files in the directory to the outdir. Anything other than .class files in * the directory (or its subdirectories) are considered resources and are also copied. * */ public List addDirectoryContents(File inFile,File outDir) throws IOException { List addedClassFiles = new ArrayList(); // Get a list of all files (i.e. everything that isnt a directory) File[] files = FileUtil.listFiles(inFile,new FileFilter() { public boolean accept(File f) { boolean accept = !f.isDirectory(); return accept; } }); // For each file, add it either as a real .class file or as a resource for (int i = 0; i < files.length; i++) { addedClassFiles.add(addClassFile(files[i],inFile,outDir)); } return addedClassFiles; } /** Adds all class files in the jar */ public List addJarFile(File inFile, File outDir, boolean canBeDirectory){ // System.err.println("? addJarFile(" + inFile + ", " + outDir + ")"); List addedClassFiles = new ArrayList(); needToReweaveWorld = true; JarFile inJar = null; try { // Is this a directory we are looking at? if (inFile.isDirectory() && canBeDirectory) { addedClassFiles.addAll(addDirectoryContents(inFile,outDir)); } else { inJar = new JarFile(inFile); addManifest(inJar.getManifest()); Enumeration entries = inJar.entries(); while (entries.hasMoreElements()) { JarEntry entry = (JarEntry)entries.nextElement(); InputStream inStream = inJar.getInputStream(entry); byte[] bytes = FileUtil.readAsByteArray(inStream); String filename = entry.getName(); // System.out.println("? addJarFile() filename='" + filename + "'"); UnwovenClassFile classFile = new UnwovenClassFile(new File(outDir, filename).getAbsolutePath(), bytes); if (filename.endsWith(".class")) { this.addClassFile(classFile); addedClassFiles.add(classFile); } // else if (!entry.isDirectory()) { // // /* bug-44190 Copy meta-data */ // addResource(filename,classFile); // } inStream.close(); } inJar.close(); } } catch (FileNotFoundException ex) { IMessage message = new Message( "Could not find input jar file " + inFile.getPath() + ", ignoring", new SourceLocation(inFile,0), false); world.getMessageHandler().handleMessage(message); } catch (IOException ex) { IMessage message = new Message( "Could not read input jar file " + inFile.getPath() + "(" + ex.getMessage() + ")", new SourceLocation(inFile,0), true); world.getMessageHandler().handleMessage(message); } finally { if (inJar != null) { try {inJar.close();} catch (IOException ex) { IMessage message = new Message( "Could not close input jar file " + inFile.getPath() + "(" + ex.getMessage() + ")", new SourceLocation(inFile,0), true); world.getMessageHandler().handleMessage(message); } } } return addedClassFiles; } // public void addResource(String name, File inPath, File outDir) throws IOException { // // /* Eliminate CVS files. Relative paths use "/" */ // if (!name.startsWith("CVS/") && (-1 == name.indexOf("/CVS/")) && !name.endsWith("/CVS")) { //// System.err.println("? addResource('" + name + "')"); //// BufferedInputStream inStream = new BufferedInputStream(new FileInputStream(inPath)); //// byte[] bytes = new byte[(int)inPath.length()]; //// inStream.read(bytes); //// inStream.close(); // byte[] bytes = FileUtil.readAsByteArray(inPath); // UnwovenClassFile resourceFile = new UnwovenClassFile(new File(outDir, name).getAbsolutePath(), bytes); // addResource(name,resourceFile); // } // } public boolean needToReweaveWorld() { return needToReweaveWorld; } /** Should be addOrReplace */ public void addClassFile(UnwovenClassFile classFile) { addedClasses.add(classFile); // if (null != sourceJavaClasses.put(classFile.getClassName(), classFile)) { //// throw new RuntimeException(classFile.getClassName()); // } world.addSourceObjectType(classFile.getJavaClass()); } public UnwovenClassFile addClassFile(File classFile, File inPathDir, File outDir) throws IOException { FileInputStream fis = new FileInputStream(classFile); byte[] bytes = FileUtil.readAsByteArray(fis); // String relativePath = files[i].getPath(); // ASSERT: files[i].getAbsolutePath().startsWith(inFile.getAbsolutePath() // or we are in trouble... String filename = classFile.getAbsolutePath().substring( inPathDir.getAbsolutePath().length()+1); UnwovenClassFile ucf = new UnwovenClassFile(new File(outDir,filename).getAbsolutePath(),bytes); if (filename.endsWith(".class")) { // System.err.println("BCELWeaver: processing class from input directory "+classFile); this.addClassFile(ucf); } fis.close(); return ucf; } public void deleteClassFile(String typename) { deletedTypenames.add(typename); // sourceJavaClasses.remove(typename); world.deleteSourceObjectType(UnresolvedType.forName(typename)); } // public void addResource (String name, UnwovenClassFile resourceFile) { // /* bug-44190 Change error to warning and copy first resource */ // if (!resources.containsKey(name)) { // resources.put(name, resourceFile); // } // else { // world.showMessage(IMessage.WARNING, "duplicate resource: '" + name + "'", // null, null); // } // } // ---- weave preparation public void setIsBatchWeave(boolean b) { isBatchWeave=b; } public void prepareForWeave() { if (trace.isTraceEnabled()) trace.enter("prepareForWeave",this); needToReweaveWorld = xcutSet.hasChangedSinceLastReset(); CflowPointcut.clearCaches(); // update mungers for (Iterator i = addedClasses.iterator(); i.hasNext(); ) { UnwovenClassFile jc = (UnwovenClassFile)i.next(); String name = jc.getClassName(); ResolvedType type = world.resolve(name); //System.err.println("added: " + type + " aspect? " + type.isAspect()); if (type.isAspect()) { needToReweaveWorld |= xcutSet.addOrReplaceAspect(type); } } for (Iterator i = deletedTypenames.iterator(); i.hasNext(); ) { String name = (String)i.next(); if (xcutSet.deleteAspect(UnresolvedType.forName(name))) needToReweaveWorld = true; } shadowMungerList = xcutSet.getShadowMungers(); // world.debug("shadow mungers=" + shadowMungerList); rewritePointcuts(shadowMungerList); // Sometimes an error occurs during rewriting pointcuts (for example, if ambiguous bindings // are detected) - we ought to fail the prepare when this happens because continuing with // inconsistent pointcuts could lead to problems typeMungerList = xcutSet.getTypeMungers(); lateTypeMungerList = xcutSet.getLateTypeMungers(); declareParentsList = xcutSet.getDeclareParents(); addCustomMungers(); // The ordering here used to be based on a string compare on toString() for the two mungers - // that breaks for the @AJ style where advice names aren't programmatically generated. So we // have changed the sorting to be based on source location in the file - this is reliable, in // the case of source locations missing, we assume they are 'sorted' - i.e. the order in // which they were added to the collection is correct, this enables the @AJ stuff to work properly. // When @AJ processing starts filling in source locations for mungers, this code may need // a bit of alteration... Collections.sort( shadowMungerList, new Comparator() { public int compare(Object o1, Object o2) { ShadowMunger sm1 = (ShadowMunger)o1; ShadowMunger sm2 = (ShadowMunger)o2; if (sm1.getSourceLocation()==null) return (sm2.getSourceLocation()==null?0:1); if (sm2.getSourceLocation()==null) return -1; return (sm2.getSourceLocation().getOffset()-sm1.getSourceLocation().getOffset()); } }); if (inReweavableMode) world.showMessage(IMessage.INFO, WeaverMessages.format(WeaverMessages.REWEAVABLE_MODE), null, null); if (trace.isTraceEnabled()) trace.exit("prepareForWeave"); } private void addCustomMungers() { if (customMungerFactory != null) { for (Iterator i = addedClasses.iterator(); i.hasNext();) { UnwovenClassFile jc = (UnwovenClassFile) i.next(); String name = jc.getClassName(); ResolvedType type = world.resolve(name); if (type.isAspect()) { Collection/*ShadowMunger*/ shadowMungers = customMungerFactory.createCustomShadowMungers(type); if (shadowMungers != null) { shadowMungerList.addAll(shadowMungers); } Collection/*ConcreteTypeMunger*/ typeMungers = customMungerFactory .createCustomTypeMungers(type); if (typeMungers != null) typeMungerList.addAll(typeMungers); } } } } public void setCustomMungerFactory(CustomMungerFactory factory) { customMungerFactory = factory; } /* * Rewrite all of the pointcuts in the world into their most efficient * form for subsequent matching. Also ensure that if pc1.equals(pc2) * then pc1 == pc2 (for non-binding pcds) by making references all * point to the same instance. * Since pointcuts remember their match decision on the last shadow, * this makes matching faster when many pointcuts share common elements, * or even when one single pointcut has one common element (which can * be a side-effect of DNF rewriting). */ private void rewritePointcuts(List/*ShadowMunger*/ shadowMungers) { PointcutRewriter rewriter = new PointcutRewriter(); for (Iterator iter = shadowMungers.iterator(); iter.hasNext();) { ShadowMunger munger = (ShadowMunger) iter.next(); Pointcut p = munger.getPointcut(); Pointcut newP = rewriter.rewrite(p); // validateBindings now whilst we still have around the pointcut // that resembles what the user actually wrote in their program // text. if (munger instanceof Advice) { Advice advice = (Advice) munger; if (advice.getSignature() != null) { final int numFormals; final String names[]; // If the advice is being concretized in a @AJ aspect *and* the advice was declared in // an @AJ aspect (it could have been inherited from a code style aspect) then // evaluate the alternative set of formals. pr125699 if (advice.getConcreteAspect().isAnnotationStyleAspect() && advice.getDeclaringAspect()!=null && advice.getDeclaringAspect().resolve(world).isAnnotationStyleAspect()) { numFormals = advice.getBaseParameterCount(); int numArgs = advice.getSignature().getParameterTypes().length; if (numFormals > 0) { names = advice.getSignature().getParameterNames(world); validateBindings(newP,p,numArgs,names); } } else { numFormals = advice.getBaseParameterCount(); if (numFormals > 0) { names = advice.getBaseParameterNames(world); validateBindings(newP,p,numFormals,names); } } } } munger.setPointcut(newP); } // now that we have optimized individual pointcuts, optimize // across the set of pointcuts.... // Use a map from key based on pc equality, to value based on // pc identity. Map/*<Pointcut,Pointcut>*/ pcMap = new HashMap(); for (Iterator iter = shadowMungers.iterator(); iter.hasNext();) { ShadowMunger munger = (ShadowMunger) iter.next(); Pointcut p = munger.getPointcut(); munger.setPointcut(shareEntriesFromMap(p,pcMap)); } } private Pointcut shareEntriesFromMap(Pointcut p,Map pcMap) { // some things cant be shared... if (p instanceof NameBindingPointcut) return p; if (p instanceof IfPointcut) return p; if (p instanceof ConcreteCflowPointcut) return p; if (p instanceof AndPointcut) { AndPointcut apc = (AndPointcut) p; Pointcut left = shareEntriesFromMap(apc.getLeft(),pcMap); Pointcut right = shareEntriesFromMap(apc.getRight(),pcMap); return new AndPointcut(left,right); } else if (p instanceof OrPointcut) { OrPointcut opc = (OrPointcut) p; Pointcut left = shareEntriesFromMap(opc.getLeft(),pcMap); Pointcut right = shareEntriesFromMap(opc.getRight(),pcMap); return new OrPointcut(left,right); } else if (p instanceof NotPointcut) { NotPointcut npc = (NotPointcut) p; Pointcut not = shareEntriesFromMap(npc.getNegatedPointcut(),pcMap); return new NotPointcut(not); } else { // primitive pcd if (pcMap.containsKey(p)) { // based on equality return (Pointcut) pcMap.get(p); // same instance (identity) } else { pcMap.put(p,p); return p; } } } // userPointcut is the pointcut that the user wrote in the program text. // dnfPointcut is the same pointcut rewritten in DNF // numFormals is the number of formal parameters in the pointcut // if numFormals > 0 then every branch of a disjunction must bind each formal once and only once. // in addition, the left and right branches of a disjunction must hold on join point kinds in // common. private void validateBindings(Pointcut dnfPointcut, Pointcut userPointcut, int numFormals, String[] names) { if (numFormals == 0) return; // nothing to check if (dnfPointcut.couldMatchKinds()==Shadow.NO_SHADOW_KINDS_BITS) return; // cant have problems if you dont match! if (dnfPointcut instanceof OrPointcut) { OrPointcut orBasedDNFPointcut = (OrPointcut) dnfPointcut; Pointcut[] leftBindings = new Pointcut[numFormals]; Pointcut[] rightBindings = new Pointcut[numFormals]; validateOrBranch(orBasedDNFPointcut,userPointcut,numFormals,names,leftBindings,rightBindings); } else { Pointcut[] bindings = new Pointcut[numFormals]; validateSingleBranch(dnfPointcut, userPointcut, numFormals, names,bindings); } } private void validateOrBranch(OrPointcut pc, Pointcut userPointcut, int numFormals, String[] names, Pointcut[] leftBindings, Pointcut[] rightBindings) { Pointcut left = pc.getLeft(); Pointcut right = pc.getRight(); if (left instanceof OrPointcut) { Pointcut[] newRightBindings = new Pointcut[numFormals]; validateOrBranch((OrPointcut)left,userPointcut,numFormals,names,leftBindings,newRightBindings); } else { if (left.couldMatchKinds()!=Shadow.NO_SHADOW_KINDS_BITS) validateSingleBranch(left, userPointcut, numFormals, names, leftBindings); } if (right instanceof OrPointcut) { Pointcut[] newLeftBindings = new Pointcut[numFormals]; validateOrBranch((OrPointcut)right,userPointcut,numFormals,names,newLeftBindings,rightBindings); } else { if (right.couldMatchKinds()!=Shadow.NO_SHADOW_KINDS_BITS) validateSingleBranch(right, userPointcut, numFormals, names, rightBindings); } int kindsInCommon = left.couldMatchKinds() & right.couldMatchKinds(); if (kindsInCommon!=Shadow.NO_SHADOW_KINDS_BITS && couldEverMatchSameJoinPoints(left,right)) { // we know that every branch binds every formal, so there is no ambiguity // if each branch binds it in exactly the same way... List ambiguousNames = new ArrayList(); for (int i = 0; i < numFormals; i++) { if (leftBindings[i] == null) { if (rightBindings[i] != null) { ambiguousNames.add(names[i]); } } else if (!leftBindings[i].equals(rightBindings[i])) { ambiguousNames.add(names[i]); } } if (!ambiguousNames.isEmpty()) raiseAmbiguityInDisjunctionError(userPointcut,ambiguousNames); } } // pc is a pointcut that does not contain any disjunctions // check that every formal is bound (negation doesn't count). // we know that numFormals > 0 or else we would not be called private void validateSingleBranch(Pointcut pc, Pointcut userPointcut, int numFormals, String[] names, Pointcut[] bindings) { boolean[] foundFormals = new boolean[numFormals]; for (int i = 0; i < foundFormals.length; i++) { foundFormals[i] = false; } validateSingleBranchRecursion(pc, userPointcut, foundFormals, names, bindings); for (int i = 0; i < foundFormals.length; i++) { if (!foundFormals[i]) { boolean ignore = false; // ATAJ soften the unbound error for implicit bindings like JoinPoint in @AJ style for (int j = 0; j < userPointcut.m_ignoreUnboundBindingForNames.length; j++) { if (names[i] != null && names[i].equals(userPointcut.m_ignoreUnboundBindingForNames[j])) { ignore = true; break; } } if (!ignore) { raiseUnboundFormalError(names[i],userPointcut); } } } } // each formal must appear exactly once private void validateSingleBranchRecursion(Pointcut pc, Pointcut userPointcut, boolean[] foundFormals, String[] names, Pointcut[] bindings) { if (pc instanceof NotPointcut) { // nots can only appear at leaves in DNF NotPointcut not = (NotPointcut) pc; if (not.getNegatedPointcut() instanceof NameBindingPointcut) { NameBindingPointcut nnbp = (NameBindingPointcut) not.getNegatedPointcut(); if (!nnbp.getBindingAnnotationTypePatterns().isEmpty() && !nnbp.getBindingTypePatterns().isEmpty()) raiseNegationBindingError(userPointcut); } } else if (pc instanceof AndPointcut) { AndPointcut and = (AndPointcut) pc; validateSingleBranchRecursion(and.getLeft(), userPointcut,foundFormals,names,bindings); validateSingleBranchRecursion(and.getRight(),userPointcut,foundFormals,names,bindings); } else if (pc instanceof NameBindingPointcut) { List/*BindingTypePattern*/ btps = ((NameBindingPointcut)pc).getBindingTypePatterns(); for (Iterator iter = btps.iterator(); iter.hasNext();) { BindingTypePattern btp = (BindingTypePattern) iter.next(); int index = btp.getFormalIndex(); bindings[index] = pc; if (foundFormals[index]) { raiseAmbiguousBindingError(names[index],userPointcut); } else { foundFormals[index] = true; } } List/*BindingAnnotationTypePattern*/ baps = ((NameBindingPointcut)pc).getBindingAnnotationTypePatterns(); for (Iterator iter = baps.iterator(); iter.hasNext();) { BindingAnnotationTypePattern bap = (BindingAnnotationTypePattern) iter.next(); int index = bap.getFormalIndex(); bindings[index] = pc; if (foundFormals[index]) { raiseAmbiguousBindingError(names[index],userPointcut); } else { foundFormals[index] = true; } } } else if (pc instanceof ConcreteCflowPointcut) { ConcreteCflowPointcut cfp = (ConcreteCflowPointcut) pc; int[] slots = cfp.getUsedFormalSlots(); for (int i = 0; i < slots.length; i++) { bindings[slots[i]] = cfp; if (foundFormals[slots[i]]) { raiseAmbiguousBindingError(names[slots[i]],userPointcut); } else { foundFormals[slots[i]] = true; } } } } // By returning false from this method, we are allowing binding of the same // variable on either side of an or. // Be conservative :- have to consider overriding, varargs, autoboxing, // the effects of itds (on within for example), interfaces, the fact that // join points can have multiple signatures and so on. private boolean couldEverMatchSameJoinPoints(Pointcut left, Pointcut right) { if (left instanceof OrPointcut) { OrPointcut leftOrPointcut = (OrPointcut)left; if (couldEverMatchSameJoinPoints(leftOrPointcut.getLeft(),right)) return true; if (couldEverMatchSameJoinPoints(leftOrPointcut.getRight(),right)) return true; return false; } if (right instanceof OrPointcut) { OrPointcut rightOrPointcut = (OrPointcut)right; if (couldEverMatchSameJoinPoints(left,rightOrPointcut.getLeft())) return true; if (couldEverMatchSameJoinPoints(left,rightOrPointcut.getRight())) return true; return false; } // look for withins WithinPointcut leftWithin = (WithinPointcut) findFirstPointcutIn(left,WithinPointcut.class); WithinPointcut rightWithin = (WithinPointcut) findFirstPointcutIn(right,WithinPointcut.class); if ((leftWithin != null) && (rightWithin != null)) { if (!leftWithin.couldEverMatchSameJoinPointsAs(rightWithin)) return false; } // look for kinded KindedPointcut leftKind = (KindedPointcut) findFirstPointcutIn(left,KindedPointcut.class); KindedPointcut rightKind = (KindedPointcut) findFirstPointcutIn(right,KindedPointcut.class); if ((leftKind != null) && (rightKind != null)) { if (!leftKind.couldEverMatchSameJoinPointsAs(rightKind)) return false; } return true; } private Pointcut findFirstPointcutIn(Pointcut toSearch, Class toLookFor) { if (toSearch instanceof NotPointcut) return null; if (toLookFor.isInstance(toSearch)) return toSearch; if (toSearch instanceof AndPointcut) { AndPointcut apc = (AndPointcut) toSearch; Pointcut left = findFirstPointcutIn(apc.getLeft(),toLookFor); if (left != null) return left; return findFirstPointcutIn(apc.getRight(),toLookFor); } return null; } /** * @param userPointcut */ private void raiseNegationBindingError(Pointcut userPointcut) { world.showMessage(IMessage.ERROR, WeaverMessages.format(WeaverMessages.NEGATION_DOESNT_ALLOW_BINDING), userPointcut.getSourceContext().makeSourceLocation(userPointcut),null); } /** * @param name * @param userPointcut */ private void raiseAmbiguousBindingError(String name, Pointcut userPointcut) { world.showMessage(IMessage.ERROR, WeaverMessages.format(WeaverMessages.AMBIGUOUS_BINDING, name), userPointcut.getSourceContext().makeSourceLocation(userPointcut),null); } /** * @param userPointcut */ private void raiseAmbiguityInDisjunctionError(Pointcut userPointcut, List names) { StringBuffer formalNames = new StringBuffer(names.get(0).toString()); for (int i = 1; i < names.size(); i++) { formalNames.append(", "); formalNames.append(names.get(i)); } world.showMessage(IMessage.ERROR, WeaverMessages.format(WeaverMessages.AMBIGUOUS_BINDING_IN_OR,formalNames), userPointcut.getSourceContext().makeSourceLocation(userPointcut),null); } /** * @param name * @param userPointcut */ private void raiseUnboundFormalError(String name, Pointcut userPointcut) { world.showMessage(IMessage.ERROR, WeaverMessages.format(WeaverMessages.UNBOUND_FORMAL, name), userPointcut.getSourceContext().makeSourceLocation(userPointcut),null); } // public void dumpUnwoven(File file) throws IOException { // BufferedOutputStream os = FileUtil.makeOutputStream(file); // this.zipOutputStream = new ZipOutputStream(os); // dumpUnwoven(); // /* BUG 40943*/ // dumpResourcesToOutJar(); // zipOutputStream.close(); //this flushes and closes the acutal file // } // // // public void dumpUnwoven() throws IOException { // Collection filesToDump = new HashSet(sourceJavaClasses.values()); // for (Iterator i = filesToDump.iterator(); i.hasNext(); ) { // UnwovenClassFile classFile = (UnwovenClassFile)i.next(); // dumpUnchanged(classFile); // } // } // public void dumpResourcesToOutPath() throws IOException { //// System.err.println("? dumpResourcesToOutPath() resources=" + resources.keySet()); // Iterator i = resources.keySet().iterator(); // while (i.hasNext()) { // UnwovenClassFile res = (UnwovenClassFile)resources.get(i.next()); // dumpUnchanged(res); // } // //resources = new HashMap(); // } // /* BUG #40943 */ // public void dumpResourcesToOutJar() throws IOException { //// System.err.println("? dumpResourcesToOutJar() resources=" + resources.keySet()); // Iterator i = resources.keySet().iterator(); // while (i.hasNext()) { // String name = (String)i.next(); // UnwovenClassFile res = (UnwovenClassFile)resources.get(name); // writeZipEntry(name,res.getBytes()); // } // resources = new HashMap(); // } // // // halfway house for when the jar is managed outside of the weaver, but the resources // // to be copied are known in the weaver. // public void dumpResourcesToOutJar(ZipOutputStream zos) throws IOException { // this.zipOutputStream = zos; // dumpResourcesToOutJar(); // } public void addManifest (Manifest newManifest) { // System.out.println("? addManifest() newManifest=" + newManifest); if (manifest == null) { manifest = newManifest; } } public static final String MANIFEST_NAME = "META-INF/MANIFEST.MF"; private static final String WEAVER_MANIFEST_VERSION = "1.0"; private static final Attributes.Name CREATED_BY = new Name("Created-By"); private static final String WEAVER_CREATED_BY = "AspectJ Compiler"; public Manifest getManifest (boolean shouldCreate) { if (manifest == null && shouldCreate) { manifest = new Manifest(); Attributes attributes = manifest.getMainAttributes(); attributes.put(Name.MANIFEST_VERSION,WEAVER_MANIFEST_VERSION); attributes.put(CREATED_BY,WEAVER_CREATED_BY); } return manifest; } // ---- weaving // Used by some test cases only... public Collection weave(File file) throws IOException { OutputStream os = FileUtil.makeOutputStream(file); this.zipOutputStream = new ZipOutputStream(os); prepareForWeave(); Collection c = weave( new IClassFileProvider() { public boolean isApplyAtAspectJMungersOnly() { return false; } public Iterator getClassFileIterator() { return addedClasses.iterator(); } public IWeaveRequestor getRequestor() { return new IWeaveRequestor() { public void acceptResult(UnwovenClassFile result) { try { writeZipEntry(result.filename, result.bytes); } catch(IOException ex) {} } public void processingReweavableState() {} public void addingTypeMungers() {} public void weavingAspects() {} public void weavingClasses() {} public void weaveCompleted() {} }; } }); // /* BUG 40943*/ // dumpResourcesToOutJar(); zipOutputStream.close(); //this flushes and closes the acutal file return c; } // public Collection weave() throws IOException { // prepareForWeave(); // Collection filesToWeave; // // if (needToReweaveWorld) { // filesToWeave = sourceJavaClasses.values(); // } else { // filesToWeave = addedClasses; // } // // Collection wovenClassNames = new ArrayList(); // world.showMessage(IMessage.INFO, "might need to weave " + filesToWeave + // "(world=" + needToReweaveWorld + ")", null, null); // // // //System.err.println("typeMungers: " + typeMungerList); // // prepareToProcessReweavableState(); // // clear all state from files we'll be reweaving // for (Iterator i = filesToWeave.iterator(); i.hasNext(); ) { // UnwovenClassFile classFile = (UnwovenClassFile)i.next(); // String className = classFile.getClassName(); // BcelObjectType classType = getClassType(className); // processReweavableStateIfPresent(className, classType); // } // // // // //XXX this isn't quite the right place for this... // for (Iterator i = filesToWeave.iterator(); i.hasNext(); ) { // UnwovenClassFile classFile = (UnwovenClassFile)i.next(); // String className = classFile.getClassName(); // addTypeMungers(className); // } // // // first weave into aspects // for (Iterator i = filesToWeave.iterator(); i.hasNext(); ) { // UnwovenClassFile classFile = (UnwovenClassFile)i.next(); // String className = classFile.getClassName(); // BcelObjectType classType = BcelWorld.getBcelObjectType(world.resolve(className)); // if (classType.isAspect()) { // weave(classFile, classType); // wovenClassNames.add(className); // } // } // // // then weave into non-aspects // for (Iterator i = filesToWeave.iterator(); i.hasNext(); ) { // UnwovenClassFile classFile = (UnwovenClassFile)i.next(); // String className = classFile.getClassName(); // BcelObjectType classType = BcelWorld.getBcelObjectType(world.resolve(className)); // if (! classType.isAspect()) { // weave(classFile, classType); // wovenClassNames.add(className); // } // } // // if (zipOutputStream != null && !needToReweaveWorld) { // Collection filesToDump = new HashSet(sourceJavaClasses.values()); // filesToDump.removeAll(filesToWeave); // for (Iterator i = filesToDump.iterator(); i.hasNext(); ) { // UnwovenClassFile classFile = (UnwovenClassFile)i.next(); // dumpUnchanged(classFile); // } // } // // addedClasses = new ArrayList(); // deletedTypenames = new ArrayList(); // // return wovenClassNames; // } // variation of "weave" that sources class files from an external source. public Collection weave(IClassFileProvider input) throws IOException { if (trace.isTraceEnabled()) trace.enter("weave",this,input); ContextToken weaveToken = CompilationAndWeavingContext.enteringPhase(CompilationAndWeavingContext.WEAVING, ""); Collection wovenClassNames = new ArrayList(); IWeaveRequestor requestor = input.getRequestor(); for (Iterator i = input.getClassFileIterator(); i.hasNext(); ) { UnwovenClassFile classFile = (UnwovenClassFile)i.next(); if (AsmManager.isCreatingModel() && !isBatchWeave) { // remove all relationships where this file being woven is the target of the relationship AsmManager.getDefault().removeRelationshipsTargettingThisType(classFile.getClassName()); } } // Go through the types and ensure any 'damaged' during compile time are repaired prior to weaving for (Iterator i = input.getClassFileIterator(); i.hasNext(); ) { UnwovenClassFile classFile = (UnwovenClassFile)i.next(); String className = classFile.getClassName(); ResolvedType theType = world.resolve(className); if (theType!=null) { BcelObjectType classType = BcelWorld.getBcelObjectType(theType); if (classType!=null) classType.ensureDelegateConsistent(); } } // special case for AtAspectJMungerOnly - see #113587 if (input.isApplyAtAspectJMungersOnly()) { ContextToken atAspectJMungersOnly = CompilationAndWeavingContext.enteringPhase(CompilationAndWeavingContext.PROCESSING_ATASPECTJTYPE_MUNGERS_ONLY, ""); requestor.weavingAspects(); ContextToken aspectToken = CompilationAndWeavingContext.enteringPhase(CompilationAndWeavingContext.WEAVING_ASPECTS, ""); for (Iterator i = input.getClassFileIterator(); i.hasNext(); ) { UnwovenClassFile classFile = (UnwovenClassFile)i.next(); String className = classFile.getClassName(); ResolvedType theType = world.resolve(className); if (theType.isAnnotationStyleAspect()) { BcelObjectType classType = BcelWorld.getBcelObjectType(theType); if (classType==null) { throw new BCException("Can't find bcel delegate for "+className+" type="+theType.getClass()); } LazyClassGen clazz = classType.getLazyClassGen(); BcelPerClauseAspectAdder selfMunger = new BcelPerClauseAspectAdder(theType, theType.getPerClause().getKind()); selfMunger.forceMunge(clazz, true); classType.finishedWith(); UnwovenClassFile[] newClasses = getClassFilesFor(clazz); for (int news = 0; news < newClasses.length; news++) { requestor.acceptResult(newClasses[news]); } wovenClassNames.add(classFile.getClassName()); } } requestor.weaveCompleted(); CompilationAndWeavingContext.leavingPhase(atAspectJMungersOnly); return wovenClassNames; } requestor.processingReweavableState(); ContextToken reweaveToken = CompilationAndWeavingContext.enteringPhase(CompilationAndWeavingContext.PROCESSING_REWEAVABLE_STATE,""); prepareToProcessReweavableState(); // clear all state from files we'll be reweaving for (Iterator i = input.getClassFileIterator(); i.hasNext(); ) { UnwovenClassFile classFile = (UnwovenClassFile)i.next(); String className = classFile.getClassName(); BcelObjectType classType = getClassType(className); // null return from getClassType() means the delegate is an eclipse source type - so // there *cant* be any reweavable state... (he bravely claimed...) if (classType !=null) { ContextToken tok = CompilationAndWeavingContext.enteringPhase(CompilationAndWeavingContext.PROCESSING_REWEAVABLE_STATE, className); processReweavableStateIfPresent(className, classType); CompilationAndWeavingContext.leavingPhase(tok); } } CompilationAndWeavingContext.leavingPhase(reweaveToken); ContextToken typeMungingToken = CompilationAndWeavingContext.enteringPhase(CompilationAndWeavingContext.PROCESSING_TYPE_MUNGERS,""); requestor.addingTypeMungers(); // We process type mungers in two groups, first mungers that change the type // hierarchy, then 'normal' ITD type mungers. // Process the types in a predictable order (rather than the order encountered). // For class A, the order is superclasses of A then superinterfaces of A // (and this mechanism is applied recursively) List typesToProcess = new ArrayList(); for (Iterator iter = input.getClassFileIterator(); iter.hasNext();) { UnwovenClassFile clf = (UnwovenClassFile) iter.next(); typesToProcess.add(clf.getClassName()); } while (typesToProcess.size()>0) { weaveParentsFor(typesToProcess,(String)typesToProcess.get(0)); } for (Iterator i = input.getClassFileIterator(); i.hasNext(); ) { UnwovenClassFile classFile = (UnwovenClassFile)i.next(); String className = classFile.getClassName(); addNormalTypeMungers(className); } CompilationAndWeavingContext.leavingPhase(typeMungingToken); requestor.weavingAspects(); ContextToken aspectToken = CompilationAndWeavingContext.enteringPhase(CompilationAndWeavingContext.WEAVING_ASPECTS, ""); // first weave into aspects for (Iterator i = input.getClassFileIterator(); i.hasNext(); ) { UnwovenClassFile classFile = (UnwovenClassFile)i.next(); String className = classFile.getClassName(); ResolvedType theType = world.resolve(className); if (theType.isAspect()) { BcelObjectType classType = BcelWorld.getBcelObjectType(theType); if (classType==null) { // Sometimes.. if the Bcel Delegate couldn't be found then a problem occurred at compile time - on // a previous compiler run. In this case I assert the delegate will still be an EclipseSourceType // and we can ignore the problem here (the original compile error will be reported again from // the eclipse source type) - pr113531 ReferenceTypeDelegate theDelegate = ((ReferenceType)theType).getDelegate(); if (theDelegate.getClass().getName().endsWith("EclipseSourceType")) continue; throw new BCException("Can't find bcel delegate for "+className+" type="+theType.getClass()); } weaveAndNotify(classFile, classType,requestor); wovenClassNames.add(className); } } CompilationAndWeavingContext.leavingPhase(aspectToken); requestor.weavingClasses(); ContextToken classToken = CompilationAndWeavingContext.enteringPhase(CompilationAndWeavingContext.WEAVING_CLASSES, ""); // then weave into non-aspects for (Iterator i = input.getClassFileIterator(); i.hasNext(); ) { UnwovenClassFile classFile = (UnwovenClassFile)i.next(); String className = classFile.getClassName(); ResolvedType theType = world.resolve(className); if (!theType.isAspect()) { BcelObjectType classType = BcelWorld.getBcelObjectType(theType); if (classType==null) { // bug 119882 - see above comment for bug 113531 ReferenceTypeDelegate theDelegate = ((ReferenceType)theType).getDelegate(); // TODO urgh - put a method on the interface to check this, string compare is hideous if (theDelegate.getClass().getName().endsWith("EclipseSourceType")) continue; throw new BCException("Can't find bcel delegate for "+className+" type="+theType.getClass()); } weaveAndNotify(classFile, classType, requestor); wovenClassNames.add(className); } } CompilationAndWeavingContext.leavingPhase(classToken); addedClasses = new ArrayList(); deletedTypenames = new ArrayList(); requestor.weaveCompleted(); CompilationAndWeavingContext.leavingPhase(weaveToken); if (trace.isTraceEnabled()) trace.exit("weave",wovenClassNames); return wovenClassNames; } public void allWeavingComplete() { warnOnUnmatchedAdvice(); } /** * In 1.5 mode and with XLint:adviceDidNotMatch enabled, put out messages for any * mungers that did not match anything. */ private void warnOnUnmatchedAdvice() { class AdviceLocation { private int lineNo; private UnresolvedType inAspect; public AdviceLocation(BcelAdvice advice) { this.lineNo = advice.getSourceLocation().getLine(); this.inAspect = advice.getDeclaringAspect(); } public boolean equals(Object obj) { if (!(obj instanceof AdviceLocation)) return false; AdviceLocation other = (AdviceLocation) obj; if (this.lineNo != other.lineNo) return false; if (!this.inAspect.equals(other.inAspect)) return false; return true; } public int hashCode() { return 37 + 17*lineNo + 17*inAspect.hashCode(); }; } // FIXME asc Should be factored out into Xlint code and done automatically for all xlint messages, ideally. // if a piece of advice hasn't matched anywhere and we are in -1.5 mode, put out a warning if (world.isInJava5Mode() && world.getLint().adviceDidNotMatch.isEnabled()) { List l = world.getCrosscuttingMembersSet().getShadowMungers(); Set alreadyWarnedLocations = new HashSet(); for (Iterator iter = l.iterator(); iter.hasNext();) { ShadowMunger element = (ShadowMunger) iter.next(); if (element instanceof BcelAdvice) { // This will stop us incorrectly reporting deow Checkers BcelAdvice ba = (BcelAdvice)element; if (!ba.hasMatchedSomething()) { // Because we implement some features of AJ itself by creating our own kind of mungers, you sometimes // find that ba.getSignature() is not a BcelMethod - for example it might be a cflow entry munger. if (ba.getSignature()!=null) { // check we haven't already warned on this advice and line // (cflow creates multiple mungers for the same advice) AdviceLocation loc = new AdviceLocation(ba); if (alreadyWarnedLocations.contains(loc)) { continue; } else { alreadyWarnedLocations.add(loc); } if (!(ba.getSignature() instanceof BcelMethod) || !Utility.isSuppressing((AnnotationX[])ba.getSignature().getAnnotations(),"adviceDidNotMatch")) { world.getLint().adviceDidNotMatch.signal(ba.getDeclaringAspect().toString(), new SourceLocation(element.getSourceLocation().getSourceFile(),element.getSourceLocation().getLine()));//element.getSourceLocation()); } } } } } } } /** * 'typeToWeave' is one from the 'typesForWeaving' list. This routine ensures we process * supertypes (classes/interfaces) of 'typeToWeave' that are in the * 'typesForWeaving' list before 'typeToWeave' itself. 'typesToWeave' is then removed from * the 'typesForWeaving' list. * * Note: Future gotcha in here ... when supplying partial hierarchies, this algorithm may * break down. If you have a hierarchy A>B>C and only give A and C to the weaver, it * may choose to weave them in either order - but you'll probably have other problems if * you are supplying partial hierarchies like that ! */ private void weaveParentsFor(List typesForWeaving,String typeToWeave) { // Look at the supertype first ResolvedType rtx = world.resolve(typeToWeave); ResolvedType superType = rtx.getSuperclass(); if (superType!=null && typesForWeaving.contains(superType.getName())) { weaveParentsFor(typesForWeaving,superType.getName()); } // Then look at the superinterface list ResolvedType[] interfaceTypes = rtx.getDeclaredInterfaces(); for (int i = 0; i < interfaceTypes.length; i++) { ResolvedType rtxI = interfaceTypes[i]; if (typesForWeaving.contains(rtxI.getName())) { weaveParentsFor(typesForWeaving,rtxI.getName()); } } ContextToken tok = CompilationAndWeavingContext.enteringPhase(CompilationAndWeavingContext.PROCESSING_DECLARE_PARENTS,rtx.getName()); weaveParentTypeMungers(rtx); // Now do this type CompilationAndWeavingContext.leavingPhase(tok); typesForWeaving.remove(typeToWeave); // and remove it from the list of those to process } public void prepareToProcessReweavableState() { } public void processReweavableStateIfPresent(String className, BcelObjectType classType) { // If the class is marked reweavable, check any aspects around when it was built are in this world WeaverStateInfo wsi = classType.getWeaverState(); if (wsi!=null && wsi.isReweavable()) { // Check all necessary types are around! world.showMessage(IMessage.INFO, WeaverMessages.format(WeaverMessages.PROCESSING_REWEAVABLE,className,classType.getSourceLocation().getSourceFile()), null,null); Set aspectsPreviouslyInWorld = wsi.getAspectsAffectingType(); if (aspectsPreviouslyInWorld!=null) { // keep track of them just to ensure unique missing aspect error reporting Set alreadyConfirmedReweavableState = new HashSet(); for (Iterator iter = aspectsPreviouslyInWorld.iterator(); iter.hasNext();) { String requiredTypeName = (String) iter.next(); if (!alreadyConfirmedReweavableState.contains(requiredTypeName)) { ResolvedType rtx = world.resolve(UnresolvedType.forName(requiredTypeName),true); boolean exists = !rtx.isMissing(); if (!exists) { world.showMessage(IMessage.ERROR, WeaverMessages.format(WeaverMessages.MISSING_REWEAVABLE_TYPE,requiredTypeName,className), classType.getSourceLocation(), null); } else { // weaved in aspect that are not declared in aop.xml trigger an error for now // may cause headhache for LTW and packaged lib without aop.xml in // see #104218 if(!xcutSet.containsAspect(rtx)){ world.showMessage( IMessage.ERROR, WeaverMessages.format( WeaverMessages.REWEAVABLE_ASPECT_NOT_REGISTERED, requiredTypeName, className ), null, null ); } else if (!world.getMessageHandler().isIgnoring(IMessage.INFO)) world.showMessage(IMessage.INFO, WeaverMessages.format(WeaverMessages.VERIFIED_REWEAVABLE_TYPE,requiredTypeName,rtx.getSourceLocation().getSourceFile()), null,null); alreadyConfirmedReweavableState.add(requiredTypeName); } } } } // old: //classType.setJavaClass(Utility.makeJavaClass(classType.getJavaClass().getFileName(), wsi.getUnwovenClassFileData())); // new: reweavable default with clever diff classType.setJavaClass(Utility.makeJavaClass(classType.getJavaClass().getFileName(), wsi.getUnwovenClassFileData(classType.getJavaClass().getBytes()))); // } else { // classType.resetState(); } } private void weaveAndNotify(UnwovenClassFile classFile, BcelObjectType classType, IWeaveRequestor requestor) throws IOException { trace.enter("weaveAndNotify",this,new Object[] {classFile,classType,requestor}); ContextToken tok = CompilationAndWeavingContext.enteringPhase(CompilationAndWeavingContext.WEAVING_TYPE, classType.getResolvedTypeX().getName()); LazyClassGen clazz = weaveWithoutDump(classFile,classType); classType.finishedWith(); //clazz is null if the classfile was unchanged by weaving... if (clazz != null) { UnwovenClassFile[] newClasses = getClassFilesFor(clazz); for (int i = 0; i < newClasses.length; i++) { requestor.acceptResult(newClasses[i]); } } else { requestor.acceptResult(classFile); } classType.weavingCompleted(); CompilationAndWeavingContext.leavingPhase(tok); trace.exit("weaveAndNotify"); } /** helper method - will return NULL if the underlying delegate is an EclipseSourceType and not a BcelObjectType */ public BcelObjectType getClassType(String forClass) { return BcelWorld.getBcelObjectType(world.resolve(forClass)); } public void addParentTypeMungers(String typeName) { weaveParentTypeMungers(world.resolve(typeName)); } public void addNormalTypeMungers(String typeName) { weaveNormalTypeMungers(world.resolve(typeName)); } public UnwovenClassFile[] getClassFilesFor(LazyClassGen clazz) { List childClasses = clazz.getChildClasses(world); UnwovenClassFile[] ret = new UnwovenClassFile[1 + childClasses.size()]; ret[0] = new UnwovenClassFile(clazz.getFileName(),clazz.getJavaClassBytesIncludingReweavable(world)); int index = 1; for (Iterator iter = childClasses.iterator(); iter.hasNext();) { UnwovenClassFile.ChildClass element = (UnwovenClassFile.ChildClass) iter.next(); UnwovenClassFile childClass = new UnwovenClassFile(clazz.getFileName() + "$" + element.name, element.bytes); ret[index++] = childClass; } return ret; } /** * Weaves new parents and annotations onto a type ("declare parents" and "declare @type") * * Algorithm: * 1. First pass, do parents then do annotations. During this pass record: * - any parent mungers that don't match but have a non-wild annotation type pattern * - any annotation mungers that don't match * 2. Multiple subsequent passes which go over the munger lists constructed in the first * pass, repeatedly applying them until nothing changes. * FIXME asc confirm that algorithm is optimal ?? */ public void weaveParentTypeMungers(ResolvedType onType) { if (onType.isRawType()) onType = onType.getGenericType(); onType.clearInterTypeMungers(); List decpToRepeat = new ArrayList(); boolean aParentChangeOccurred = false; boolean anAnnotationChangeOccurred = false; // First pass - apply all decp mungers for (Iterator i = declareParentsList.iterator(); i.hasNext(); ) { DeclareParents decp = (DeclareParents)i.next(); boolean typeChanged = applyDeclareParents(decp,onType); if (typeChanged) { aParentChangeOccurred = true; } else { decpToRepeat.add(decp); } } // Still first pass - apply all dec @type mungers for (Iterator i = xcutSet.getDeclareAnnotationOnTypes().iterator();i.hasNext();) { DeclareAnnotation decA = (DeclareAnnotation)i.next(); boolean typeChanged = applyDeclareAtType(decA,onType,true); if (typeChanged) { anAnnotationChangeOccurred = true; } } while ((aParentChangeOccurred || anAnnotationChangeOccurred) && !decpToRepeat.isEmpty()) { anAnnotationChangeOccurred = aParentChangeOccurred = false; List decpToRepeatNextTime = new ArrayList(); for (Iterator iter = decpToRepeat.iterator(); iter.hasNext();) { DeclareParents decp = (DeclareParents) iter.next(); boolean typeChanged = applyDeclareParents(decp,onType); if (typeChanged) { aParentChangeOccurred = true; } else { decpToRepeatNextTime.add(decp); } } for (Iterator iter = xcutSet.getDeclareAnnotationOnTypes().iterator(); iter.hasNext();) { DeclareAnnotation decA = (DeclareAnnotation) iter.next(); boolean typeChanged = applyDeclareAtType(decA,onType,false); if (typeChanged) { anAnnotationChangeOccurred = true; } } decpToRepeat = decpToRepeatNextTime; } } /** * Apply a declare @type - return true if we change the type */ private boolean applyDeclareAtType(DeclareAnnotation decA, ResolvedType onType,boolean reportProblems) { boolean didSomething = false; if (decA.matches(onType)) { if (onType.hasAnnotation(decA.getAnnotationX().getSignature())) { // Could put out a lint here for an already annotated type ... // if (reportProblems) { // world.getLint().elementAlreadyAnnotated.signal( // new String[]{onType.toString(),decA.getAnnotationTypeX().toString()}, // onType.getSourceLocation(),new ISourceLocation[]{decA.getSourceLocation()}); // } return false; } AnnotationX annoX = decA.getAnnotationX(); // check the annotation is suitable for the target boolean problemReported = verifyTargetIsOK(decA, onType, annoX,reportProblems); if (!problemReported) { AsmRelationshipProvider.getDefault().addDeclareAnnotationRelationship(decA.getSourceLocation(),onType.getSourceLocation()); // TAG: WeavingMessage if (!getWorld().getMessageHandler().isIgnoring(IMessage.WEAVEINFO)){ getWorld().getMessageHandler().handleMessage( WeaveMessage.constructWeavingMessage(WeaveMessage.WEAVEMESSAGE_ANNOTATES, new String[]{ onType.toString(), Utility.beautifyLocation(onType.getSourceLocation()), decA.getAnnotationString(), "type", decA.getAspect().toString(), Utility.beautifyLocation(decA.getSourceLocation()) })); } didSomething = true; ResolvedTypeMunger newAnnotationTM = new AnnotationOnTypeMunger(annoX); newAnnotationTM.setSourceLocation(decA.getSourceLocation()); onType.addInterTypeMunger(new BcelTypeMunger(newAnnotationTM,decA.getAspect().resolve(world))); decA.copyAnnotationTo(onType); } } return didSomething; } /** * Checks for an @target() on the annotation and if found ensures it allows the annotation * to be attached to the target type that matched. */ private boolean verifyTargetIsOK(DeclareAnnotation decA, ResolvedType onType, AnnotationX annoX,boolean outputProblems) { boolean problemReported = false; if (annoX.specifiesTarget()) { if ( (onType.isAnnotation() && !annoX.allowedOnAnnotationType()) || (!annoX.allowedOnRegularType())) { if (outputProblems) { if (decA.isExactPattern()) { world.getMessageHandler().handleMessage(MessageUtil.error( WeaverMessages.format(WeaverMessages.INCORRECT_TARGET_FOR_DECLARE_ANNOTATION, onType.getName(),annoX.stringify(),annoX.getValidTargets()),decA.getSourceLocation())); } else { if (world.getLint().invalidTargetForAnnotation.isEnabled()) { world.getLint().invalidTargetForAnnotation.signal( new String[]{onType.getName(),annoX.stringify(),annoX.getValidTargets()},decA.getSourceLocation(),new ISourceLocation[]{onType.getSourceLocation()}); } } } problemReported = true; } } return problemReported; } /** * Apply a single declare parents - return true if we change the type */ private boolean applyDeclareParents(DeclareParents p, ResolvedType onType) { boolean didSomething = false; List newParents = p.findMatchingNewParents(onType,true); if (!newParents.isEmpty()) { didSomething=true; BcelObjectType classType = BcelWorld.getBcelObjectType(onType); //System.err.println("need to do declare parents for: " + onType); for (Iterator j = newParents.iterator(); j.hasNext(); ) { ResolvedType newParent = (ResolvedType)j.next(); // We set it here so that the imminent matching for ITDs can succeed - we // still haven't done the necessary changes to the class file itself // (like transform super calls) - that is done in BcelTypeMunger.mungeNewParent() classType.addParent(newParent); ResolvedTypeMunger newParentMunger = new NewParentTypeMunger(newParent); newParentMunger.setSourceLocation(p.getSourceLocation()); onType.addInterTypeMunger(new BcelTypeMunger(newParentMunger, xcutSet.findAspectDeclaringParents(p))); } } return didSomething; } public void weaveNormalTypeMungers(ResolvedType onType) { ContextToken tok = CompilationAndWeavingContext.enteringPhase(CompilationAndWeavingContext.PROCESSING_TYPE_MUNGERS, onType.getName()); if (onType.isRawType() || onType.isParameterizedType()) onType = onType.getGenericType(); for (Iterator i = typeMungerList.iterator(); i.hasNext(); ) { ConcreteTypeMunger m = (ConcreteTypeMunger)i.next(); if (!m.isLateMunger() && m.matches(onType)) { onType.addInterTypeMunger(m); } } CompilationAndWeavingContext.leavingPhase(tok); } // exposed for ClassLoader dynamic weaving public LazyClassGen weaveWithoutDump(UnwovenClassFile classFile, BcelObjectType classType) throws IOException { return weave(classFile, classType, false); } // non-private for testing LazyClassGen weave(UnwovenClassFile classFile, BcelObjectType classType) throws IOException { LazyClassGen ret = weave(classFile, classType, true); if (progressListener != null) { progressMade += progressPerClassFile; progressListener.setProgress(progressMade); progressListener.setText("woven: " + classFile.getFilename()); } return ret; } private LazyClassGen weave(UnwovenClassFile classFile, BcelObjectType classType, boolean dump) throws IOException { if (classType.isSynthetic()) { // Don't touch synthetic classes if (dump) dumpUnchanged(classFile); return null; } List shadowMungers = fastMatch(shadowMungerList, classType.getResolvedTypeX()); List typeMungers = classType.getResolvedTypeX().getInterTypeMungers(); classType.getResolvedTypeX().checkInterTypeMungers(); // Decide if we need to do actual weaving for this class boolean mightNeedToWeave = shadowMungers.size() > 0 || typeMungers.size() > 0 || classType.isAspect() || world.getDeclareAnnotationOnMethods().size()>0 || world.getDeclareAnnotationOnFields().size()>0; // May need bridge methods if on 1.5 and something in our hierarchy is affected by ITDs boolean mightNeedBridgeMethods = world.isInJava5Mode() && !classType.isInterface() && classType.getResolvedTypeX().getInterTypeMungersIncludingSupers().size()>0; LazyClassGen clazz = null; if (mightNeedToWeave || mightNeedBridgeMethods) { clazz = classType.getLazyClassGen(); //System.err.println("got lazy gen: " + clazz + ", " + clazz.getWeaverState()); try { boolean isChanged = false; if (mightNeedToWeave) isChanged = BcelClassWeaver.weave(world, clazz, shadowMungers, typeMungers, lateTypeMungerList); if (mightNeedBridgeMethods) isChanged = BcelClassWeaver.calculateAnyRequiredBridgeMethods(world,clazz) || isChanged; if (isChanged) { if (dump) dump(classFile, clazz); return clazz; } } catch (RuntimeException re) { String classDebugInfo = null; try { classDebugInfo = clazz.toLongString(); } catch (Exception e) { // recover from crash whilst producing debug string classDebugInfo = clazz.getClassName(); } String messageText = "trouble in: \n" + classDebugInfo; getWorld().getMessageHandler().handleMessage( new Message(messageText,IMessage.ABORT,re,null) ); } catch (Error re) { String classDebugInfo = null; try { classDebugInfo = clazz.toLongString(); } catch (Exception e) { // recover from crash whilst producing debug string classDebugInfo = clazz.getClassName(); } String messageText = "trouble in: \n" + classDebugInfo; getWorld().getMessageHandler().handleMessage( new Message(messageText,IMessage.ABORT,re,null) ); } } // this is very odd return behavior trying to keep everyone happy if (dump) { dumpUnchanged(classFile); return clazz; } else { // ATAJ: the class was not weaved, but since it gets there early it may have new generated inner classes // attached to it to support LTW perX aspectOf support (see BcelPerClauseAspectAdder) // that aggressively defines the inner <aspect>$mayHaveAspect interface. if (clazz != null && !clazz.getChildClasses(world).isEmpty()) { return clazz; } return null; } } // ---- writing private void dumpUnchanged(UnwovenClassFile classFile) throws IOException { if (zipOutputStream != null) { writeZipEntry(getEntryName(classFile.getJavaClass().getClassName()), classFile.getBytes()); } else { classFile.writeUnchangedBytes(); } } private String getEntryName(String className) { //XXX what does bcel's getClassName do for inner names return className.replace('.', '/') + ".class"; } private void dump(UnwovenClassFile classFile, LazyClassGen clazz) throws IOException { if (zipOutputStream != null) { String mainClassName = classFile.getJavaClass().getClassName(); writeZipEntry(getEntryName(mainClassName), clazz.getJavaClass(world).getBytes()); if (!clazz.getChildClasses(world).isEmpty()) { for (Iterator i = clazz.getChildClasses(world).iterator(); i.hasNext();) { UnwovenClassFile.ChildClass c = (UnwovenClassFile.ChildClass) i.next(); writeZipEntry(getEntryName(mainClassName + "$" + c.name), c.bytes); } } } else { classFile.writeWovenBytes( clazz.getJavaClass(world).getBytes(), clazz.getChildClasses(world) ); } } private void writeZipEntry(String name, byte[] bytes) throws IOException { ZipEntry newEntry = new ZipEntry(name); //??? get compression scheme right zipOutputStream.putNextEntry(newEntry); zipOutputStream.write(bytes); zipOutputStream.closeEntry(); } private List fastMatch(List list, ResolvedType type) { if (list == null) return Collections.EMPTY_LIST; // here we do the coarsest grained fast match with no kind constraints // this will remove all obvious non-matches and see if we need to do any weaving FastMatchInfo info = new FastMatchInfo(type, null); List result = new ArrayList(); Iterator iter = list.iterator(); while (iter.hasNext()) { ShadowMunger munger = (ShadowMunger)iter.next(); FuzzyBoolean fb = munger.getPointcut().fastMatch(info); WeaverMetrics.recordFastMatchTypeResult(fb); // Could pass: munger.getPointcut().toString(),info if (fb.maybeTrue()) { result.add(munger); } } return result; } public void setProgressListener(IProgressListener listener, double previousProgress, double progressPerClassFile) { progressListener = listener; this.progressMade = previousProgress; this.progressPerClassFile = progressPerClassFile; } public void setReweavableMode(boolean xNotReweavable) { if (trace.isTraceEnabled()) trace.enter("setReweavableMode",this,xNotReweavable); inReweavableMode = !xNotReweavable; WeaverStateInfo.setReweavableModeDefaults(!xNotReweavable,false,true); BcelClassWeaver.setReweavableMode(!xNotReweavable); if (trace.isTraceEnabled()) trace.exit("setReweavableMode"); } public boolean isReweavable() { return inReweavableMode; } public World getWorld() { return world; } public void tidyUp() { if (trace.isTraceEnabled()) trace.enter("tidyUp",this); shadowMungerList = null; // setup by prepareForWeave typeMungerList = null; // setup by prepareForWeave lateTypeMungerList = null; // setup by prepareForWeave declareParentsList = null; // setup by prepareForWeave if (trace.isTraceEnabled()) trace.exit("tidyUp"); } }
222,437
Bug 222437 MANIFEST.MF copying is not always reliable
Sometimes an AJDT project gets into a state where it has a meta-inf/manifest.mf - and this file fails to make it out to the destination folder.
resolved fixed
906c849
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2008-03-12T17:51:13Z"
"2008-03-12T16:40:00Z"
org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/core/builder/AjBuildManager.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Eclipse Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * PARC initial implementation * ******************************************************************/ package org.aspectj.ajdt.internal.core.builder; import java.io.BufferedOutputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileFilter; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.OutputStream; import java.io.PrintStream; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Set; import java.util.jar.Attributes; import java.util.jar.JarFile; import java.util.jar.JarInputStream; import java.util.jar.JarOutputStream; import java.util.jar.Manifest; import java.util.zip.ZipEntry; import org.aspectj.ajdt.internal.compiler.AjCompilerAdapter; import org.aspectj.ajdt.internal.compiler.AjPipeliningCompilerAdapter; import org.aspectj.ajdt.internal.compiler.IBinarySourceProvider; import org.aspectj.ajdt.internal.compiler.ICompilerAdapter; import org.aspectj.ajdt.internal.compiler.ICompilerAdapterFactory; import org.aspectj.ajdt.internal.compiler.IIntermediateResultsRequestor; import org.aspectj.ajdt.internal.compiler.IOutputClassFileNameProvider; import org.aspectj.ajdt.internal.compiler.InterimCompilationResult; import org.aspectj.ajdt.internal.compiler.lookup.AjLookupEnvironment; import org.aspectj.ajdt.internal.compiler.lookup.AnonymousClassPublisher; import org.aspectj.ajdt.internal.compiler.lookup.EclipseFactory; import org.aspectj.ajdt.internal.compiler.problem.AjProblemReporter; import org.aspectj.asm.AsmManager; import org.aspectj.asm.IHierarchy; import org.aspectj.asm.IProgramElement; import org.aspectj.asm.internal.ProgramElement; import org.aspectj.bridge.AbortException; import org.aspectj.bridge.CountingMessageHandler; import org.aspectj.bridge.ILifecycleAware; import org.aspectj.bridge.IMessage; import org.aspectj.bridge.IMessageHandler; import org.aspectj.bridge.IProgressListener; import org.aspectj.bridge.Message; import org.aspectj.bridge.MessageUtil; import org.aspectj.bridge.SourceLocation; import org.aspectj.bridge.Version; import org.aspectj.bridge.context.CompilationAndWeavingContext; import org.aspectj.bridge.context.ContextFormatter; import org.aspectj.bridge.context.ContextToken; import org.aspectj.org.eclipse.jdt.core.compiler.CharOperation; import org.aspectj.org.eclipse.jdt.core.compiler.IProblem; import org.aspectj.org.eclipse.jdt.internal.compiler.ClassFile; import org.aspectj.org.eclipse.jdt.internal.compiler.CompilationResult; import org.aspectj.org.eclipse.jdt.internal.compiler.DefaultErrorHandlingPolicies; import org.aspectj.org.eclipse.jdt.internal.compiler.ICompilerRequestor; import org.aspectj.org.eclipse.jdt.internal.compiler.IProblemFactory; import org.aspectj.org.eclipse.jdt.internal.compiler.batch.ClasspathLocation; import org.aspectj.org.eclipse.jdt.internal.compiler.batch.CompilationUnit; import org.aspectj.org.eclipse.jdt.internal.compiler.batch.FileSystem; import org.aspectj.org.eclipse.jdt.internal.compiler.env.ICompilationUnit; import org.aspectj.org.eclipse.jdt.internal.compiler.env.INameEnvironment; import org.aspectj.org.eclipse.jdt.internal.compiler.impl.CompilerOptions; import org.aspectj.org.eclipse.jdt.internal.compiler.parser.Parser; import org.aspectj.org.eclipse.jdt.internal.compiler.problem.AbortCompilation; import org.aspectj.org.eclipse.jdt.internal.compiler.problem.DefaultProblemFactory; import org.aspectj.tools.ajc.Main; import org.aspectj.util.FileUtil; import org.aspectj.weaver.CustomMungerFactory; import org.aspectj.weaver.Dump; import org.aspectj.weaver.ResolvedType; import org.aspectj.weaver.World; import org.aspectj.weaver.bcel.BcelWeaver; import org.aspectj.weaver.bcel.BcelWorld; import org.aspectj.weaver.bcel.UnwovenClassFile; import org.eclipse.core.runtime.OperationCanceledException; public class AjBuildManager implements IOutputClassFileNameProvider,IBinarySourceProvider,ICompilerAdapterFactory { private static final String CROSSREFS_FILE_NAME = "build.lst"; private static final String CANT_WRITE_RESULT = "unable to write compilation result"; private static final String MANIFEST_NAME = "META-INF/MANIFEST.MF"; public static boolean COPY_INPATH_DIR_RESOURCES = false; // AJDT doesn't want this check, so Main enables it. private static boolean DO_RUNTIME_VERSION_CHECK = false; // If runtime version check fails, warn or fail? (unset?) static final boolean FAIL_IF_RUNTIME_NOT_FOUND = false; private static final FileFilter binarySourceFilter = new FileFilter() { public boolean accept(File f) { return f.getName().endsWith(".class"); }}; /** * This builder is static so that it can be subclassed and reset. However, note * that there is only one builder present, so if two extendsion reset it, only * the latter will get used. */ public static AsmHierarchyBuilder asmHierarchyBuilder = new AsmHierarchyBuilder(); static { CompilationAndWeavingContext.setMultiThreaded(false); CompilationAndWeavingContext.registerFormatter( CompilationAndWeavingContext.BATCH_BUILD, new AjBuildContexFormatter()); CompilationAndWeavingContext.registerFormatter( CompilationAndWeavingContext.INCREMENTAL_BUILD, new AjBuildContexFormatter()); } private IProgressListener progressListener = null; private boolean environmentSupportsIncrementalCompilation = false; private int compiledCount; private int sourceFileCount; private JarOutputStream zos; private boolean batchCompile = true; private INameEnvironment environment; private Map /* String -> List<UCF>*/ binarySourcesForTheNextCompile = new HashMap(); // FIXME asc should this really be in here? private IHierarchy structureModel; public AjBuildConfig buildConfig; private boolean ignoreOutxml; private boolean wasFullBuild = true; // true if last build was a full build rather than an incremental build AjState state = new AjState(this); /** * Enable check for runtime version, used only by Ant/command-line Main. * @param main Main unused except to limit to non-null clients. */ public static void enableRuntimeVersionCheck(Main caller) { DO_RUNTIME_VERSION_CHECK = null != caller; } public BcelWeaver getWeaver() { return state.getWeaver();} public BcelWorld getBcelWorld() { return state.getBcelWorld();} public CountingMessageHandler handler; private CustomMungerFactory customMungerFactory; public AjBuildManager(IMessageHandler holder) { super(); this.handler = CountingMessageHandler.makeCountingMessageHandler(holder); } public void environmentSupportsIncrementalCompilation(boolean itDoes) { this.environmentSupportsIncrementalCompilation = itDoes; } /** @return true if we should generate a model as a side-effect */ public boolean doGenerateModel() { return buildConfig.isGenerateModelMode(); } public boolean batchBuild( AjBuildConfig buildConfig, IMessageHandler baseHandler) throws IOException, AbortException { return doBuild(buildConfig, baseHandler, true); } public boolean incrementalBuild( AjBuildConfig buildConfig, IMessageHandler baseHandler) throws IOException, AbortException { return doBuild(buildConfig, baseHandler, false); } /** @throws AbortException if check for runtime fails */ protected boolean doBuild( AjBuildConfig buildConfig, IMessageHandler baseHandler, boolean batch) throws IOException, AbortException { boolean ret = true; batchCompile = batch; wasFullBuild = batch; if (baseHandler instanceof ILifecycleAware) { ((ILifecycleAware)baseHandler).buildStarting(!batch); } CompilationAndWeavingContext.reset(); int phase = batch ? CompilationAndWeavingContext.BATCH_BUILD : CompilationAndWeavingContext.INCREMENTAL_BUILD; ContextToken ct = CompilationAndWeavingContext.enteringPhase(phase ,buildConfig); try { if (batch) { this.state = new AjState(this); } this.state.setCouldBeSubsequentIncrementalBuild(this.environmentSupportsIncrementalCompilation); boolean canIncremental = state.prepareForNextBuild(buildConfig); if (!canIncremental && !batch) { // retry as batch? CompilationAndWeavingContext.leavingPhase(ct); if (state.listenerDefined()) state.getListener().recordDecision("Falling back to batch compilation"); return doBuild(buildConfig, baseHandler, true); } this.handler = CountingMessageHandler.makeCountingMessageHandler(baseHandler); if (DO_RUNTIME_VERSION_CHECK) { String check = checkRtJar(buildConfig); if (check != null) { if (FAIL_IF_RUNTIME_NOT_FOUND) { MessageUtil.error(handler, check); CompilationAndWeavingContext.leavingPhase(ct); return false; } else { MessageUtil.warn(handler, check); } } } // if (batch) { setBuildConfig(buildConfig); //} if (batch || !AsmManager.attemptIncrementalModelRepairs) { // if (buildConfig.isEmacsSymMode() || buildConfig.isGenerateModelMode()) { setupModel(buildConfig); // } } if (batch) { initBcelWorld(handler); } if (handler.hasErrors()) { CompilationAndWeavingContext.leavingPhase(ct); return false; } if (buildConfig.getOutputJar() != null) { if (!openOutputStream(buildConfig.getOutputJar())) { CompilationAndWeavingContext.leavingPhase(ct); return false; } } if (batch) { // System.err.println("XXXX batch: " + buildConfig.getFiles()); if (buildConfig.isEmacsSymMode() || buildConfig.isGenerateModelMode()) { getWorld().setModel(AsmManager.getDefault().getHierarchy()); // in incremental build, only get updated model? } binarySourcesForTheNextCompile = state.getBinaryFilesToCompile(true); performCompilation(buildConfig.getFiles()); state.clearBinarySourceFiles(); // we don't want these hanging around... if (handler.hasErrors()) { CompilationAndWeavingContext.leavingPhase(ct); if (AsmManager.isReporting()) AsmManager.getDefault().reportModelInfo("After a failed batch build"); return false; } if (AsmManager.isReporting()) AsmManager.getDefault().reportModelInfo("After a batch build"); } else { // done already? // if (buildConfig.isEmacsSymMode() || buildConfig.isGenerateModelMode()) { // bcelWorld.setModel(StructureModelManager.INSTANCE.getStructureModel()); // } // System.err.println("XXXX start inc "); binarySourcesForTheNextCompile = state.getBinaryFilesToCompile(true); List files = state.getFilesToCompile(true); if (buildConfig.isEmacsSymMode() || buildConfig.isGenerateModelMode()) if (AsmManager.attemptIncrementalModelRepairs) AsmManager.getDefault().processDelta(files,state.getAddedFiles(),state.getDeletedFiles()); boolean hereWeGoAgain = !(files.isEmpty() && binarySourcesForTheNextCompile.isEmpty()); for (int i = 0; (i < 5) && hereWeGoAgain; i++) { if (state.listenerDefined()) state.getListener().recordInformation("Starting incremental compilation loop "+(i+1)+" of possibly 5"); // System.err.println("XXXX inc: " + files); performCompilation(files); if (handler.hasErrors() || (progressListener!=null && progressListener.isCancelledRequested())) { CompilationAndWeavingContext.leavingPhase(ct); return false; } if (state.requiresFullBatchBuild()) { if (state.listenerDefined()) state.getListener().recordInformation(" Dropping back to full build"); return batchBuild(buildConfig, baseHandler); } binarySourcesForTheNextCompile = state.getBinaryFilesToCompile(false); files = state.getFilesToCompile(false); hereWeGoAgain = !(files.isEmpty() && binarySourcesForTheNextCompile.isEmpty()); // TODO Andy - Needs some thought here... // I think here we might want to pass empty addedFiles/deletedFiles as they were // dealt with on the first call to processDelta - we are going through this loop // again because in compiling something we found something else we needed to // rebuild. But what case causes this? if (hereWeGoAgain) { if (buildConfig.isEmacsSymMode() || buildConfig.isGenerateModelMode()) if (AsmManager.attemptIncrementalModelRepairs) AsmManager.getDefault().processDelta(files,state.getAddedFiles(),state.getDeletedFiles()); } } if (!files.isEmpty()) { CompilationAndWeavingContext.leavingPhase(ct); return batchBuild(buildConfig, baseHandler); } else { if (AsmManager.isReporting()) AsmManager.getDefault().reportModelInfo("After an incremental build"); } } // XXX not in Mik's incremental if (buildConfig.isEmacsSymMode()) { new org.aspectj.ajdt.internal.core.builder.EmacsStructureModelManager().externalizeModel(); } // for bug 113554: support ajsym file generation for command line builds if (buildConfig.isGenerateCrossRefsMode()) { File configFileProxy = new File(buildConfig.getOutputDir(),CROSSREFS_FILE_NAME); AsmManager.getDefault().writeStructureModel(configFileProxy.getAbsolutePath()); } // have to tell state we succeeded or next is not incremental state.successfulCompile(buildConfig,batch); copyResourcesToDestination(); if (buildConfig.getOutxmlName() != null) { writeOutxmlFile(); } /*boolean weaved = *///weaveAndGenerateClassFiles(); // if not weaved, then no-op build, no model changes // but always returns true // XXX weaved not in Mik's incremental if (buildConfig.isGenerateModelMode()) { AsmManager.getDefault().fireModelUpdated(); } CompilationAndWeavingContext.leavingPhase(ct); } finally { if (baseHandler instanceof ILifecycleAware) { ((ILifecycleAware)baseHandler).buildFinished(!batch); } if (zos != null) { closeOutputStream(buildConfig.getOutputJar()); } ret = !handler.hasErrors(); if (getBcelWorld()!=null) getBcelWorld().tidyUp(); if (getWeaver()!=null) getWeaver().tidyUp(); // bug 59895, don't release reference to handler as may be needed by a nested call //handler = null; } return ret; } private String stringifyList(List l) { if (l==null) return ""; StringBuffer sb = new StringBuffer(); sb.append("{"); for (Iterator iter = l.iterator(); iter.hasNext();) { Object el = (Object) iter.next(); sb.append(el); if (iter.hasNext()) sb.append(","); } sb.append("}"); return sb.toString(); } private boolean openOutputStream(File outJar) { try { OutputStream os = FileUtil.makeOutputStream(buildConfig.getOutputJar()); zos = new JarOutputStream(os,getWeaver().getManifest(true)); } catch (IOException ex) { IMessage message = new Message("Unable to open outjar " + outJar.getPath() + "(" + ex.getMessage() + ")", new SourceLocation(outJar,0), true); handler.handleMessage(message); return false; } return true; } private void closeOutputStream(File outJar) { try { if (zos != null) zos.close(); zos = null; /* Ensure we don't write an incomplete JAR bug-71339 */ if (handler.hasErrors()) { outJar.delete(); } } catch (IOException ex) { IMessage message = new Message("Unable to write outjar " + outJar.getPath() + "(" + ex.getMessage() + ")", new SourceLocation(outJar,0), true); handler.handleMessage(message); } } private void copyResourcesToDestination() throws IOException { // resources that we need to copy are contained in the injars and inpath only for (Iterator i = buildConfig.getInJars().iterator(); i.hasNext(); ) { File inJar = (File)i.next(); copyResourcesFromJarFile(inJar); } for (Iterator i = buildConfig.getInpath().iterator(); i.hasNext(); ) { File inPathElement = (File)i.next(); if (inPathElement.isDirectory()) { copyResourcesFromDirectory(inPathElement); } else { copyResourcesFromJarFile(inPathElement); } } if (buildConfig.getSourcePathResources() != null) { for (Iterator i = buildConfig.getSourcePathResources().keySet().iterator(); i.hasNext(); ) { String resource = (String)i.next(); File from = (File)buildConfig.getSourcePathResources().get(resource); copyResourcesFromFile(from,resource,from); } } writeManifest(); } private void copyResourcesFromJarFile(File jarFile) throws IOException { JarInputStream inStream = null; try { inStream = new JarInputStream(new FileInputStream(jarFile)); while (true) { ZipEntry entry = inStream.getNextEntry(); if (entry == null) break; String filename = entry.getName(); // System.out.println("? copyResourcesFromJarFile() filename='" + filename +"'"); if (!entry.isDirectory() && acceptResource(filename)) { byte[] bytes = FileUtil.readAsByteArray(inStream); writeResource(filename,bytes,jarFile); } inStream.closeEntry(); } } finally { if (inStream != null) inStream.close(); } } private void copyResourcesFromDirectory(File dir) throws IOException { if (!COPY_INPATH_DIR_RESOURCES) return; // Get a list of all files (i.e. everything that isnt a directory) File[] files = FileUtil.listFiles(dir,new FileFilter() { public boolean accept(File f) { boolean accept = !(f.isDirectory() || f.getName().endsWith(".class")) ; return accept; } }); // For each file, add it either as a real .class file or as a resource for (int i = 0; i < files.length; i++) { // ASSERT: files[i].getAbsolutePath().startsWith(inFile.getAbsolutePath() // or we are in trouble... String filename = files[i].getAbsolutePath().substring( dir.getAbsolutePath().length()+1); copyResourcesFromFile(files[i],filename,dir); } } private void copyResourcesFromFile(File f,String filename,File src) throws IOException { if (!acceptResource(filename)) return; FileInputStream fis = null; try { fis = new FileInputStream(f); byte[] bytes = FileUtil.readAsByteArray(fis); // String relativePath = files[i].getPath(); writeResource(filename,bytes,src); } finally { if (fis != null) fis.close(); } } private void writeResource(String filename, byte[] content, File srcLocation) throws IOException { if (state.hasResource(filename)) { IMessage msg = new Message("duplicate resource: '" + filename + "'", IMessage.WARNING, null, new SourceLocation(srcLocation,0)); handler.handleMessage(msg); return; } if (filename.equals(buildConfig.getOutxmlName())) { ignoreOutxml = true; IMessage msg = new Message("-outxml/-outxmlfile option ignored because resource already exists: '" + filename + "'", IMessage.WARNING, null, new SourceLocation(srcLocation,0)); handler.handleMessage(msg); } if (zos != null) { ZipEntry newEntry = new ZipEntry(filename); //??? get compression scheme right zos.putNextEntry(newEntry); zos.write(content); zos.closeEntry(); } else { File destDir = buildConfig.getOutputDir(); if (buildConfig.getCompilationResultDestinationManager() != null) { destDir = buildConfig.getCompilationResultDestinationManager().getOutputLocationForResource(srcLocation); } try { OutputStream fos = FileUtil.makeOutputStream(new File(destDir,filename)); fos.write(content); fos.close(); } catch (FileNotFoundException fnfe) { IMessage msg = new Message("unable to copy resource to output folder: '" + filename + "' - reason: "+fnfe.getMessage(), IMessage.ERROR, null, new SourceLocation(srcLocation,0)); handler.handleMessage(msg); } } state.recordResource(filename); } /* * If we are writing to an output directory copy the manifest but only * if we already have one */ private void writeManifest () throws IOException { Manifest manifest = getWeaver().getManifest(false); if (manifest != null && zos == null) { File outputDir = buildConfig.getOutputDir(); if (buildConfig.getCompilationResultDestinationManager() != null) { // Manifests are only written if we have a jar on the inpath. Therefore, // we write the manifest to the defaultOutputLocation because this is // where we sent the classes that were on the inpath outputDir = buildConfig.getCompilationResultDestinationManager().getDefaultOutputLocation(); } if (outputDir == null) return; OutputStream fos = FileUtil.makeOutputStream(new File(outputDir,MANIFEST_NAME)); manifest.write(fos); fos.close(); } } private boolean acceptResource(String resourceName) { if ( (resourceName.startsWith("CVS/")) || (resourceName.indexOf("/CVS/") != -1) || (resourceName.endsWith("/CVS")) || (resourceName.endsWith(".class")) || (resourceName.startsWith(".svn/")) || (resourceName.indexOf("/.svn/")!=-1) || (resourceName.endsWith("/.svn")) || (resourceName.toUpperCase().equals(MANIFEST_NAME)) ) { return false; } else { return true; } } private void writeOutxmlFile () throws IOException { if (ignoreOutxml) return; String filename = buildConfig.getOutxmlName(); // System.err.println("? AjBuildManager.writeOutxmlFile() outxml=" + filename); Map outputDirsAndAspects = findOutputDirsForAspects(); Set outputDirs = outputDirsAndAspects.entrySet(); for (Iterator iterator = outputDirs.iterator(); iterator.hasNext();) { Map.Entry entry = (Map.Entry) iterator.next(); File outputDir = (File) entry.getKey(); List aspects = (List) entry.getValue(); ByteArrayOutputStream baos = getOutxmlContents(aspects); if (zos != null) { ZipEntry newEntry = new ZipEntry(filename); zos.putNextEntry(newEntry); zos.write(baos.toByteArray()); zos.closeEntry(); } else { OutputStream fos = FileUtil.makeOutputStream(new File(outputDir, filename)); fos.write(baos.toByteArray()); fos.close(); } } } private ByteArrayOutputStream getOutxmlContents(List aspectNames) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); PrintStream ps = new PrintStream(baos); ps.println("<aspectj>"); ps.println("<aspects>"); if (aspectNames != null) { for (Iterator i = aspectNames.iterator(); i.hasNext();) { String name = (String) i.next(); ps.println("<aspect name=\"" + name + "\"/>"); } } ps.println("</aspects>"); ps.println("</aspectj>"); ps.println(); ps.close(); return baos; } /** * Returns a map where the keys are File objects corresponding to * all the output directories and the values are a list of aspects * which are sent to that ouptut directory */ private Map /* File --> List (String) */findOutputDirsForAspects() { Map outputDirsToAspects = new HashMap(); Map aspectNamesToFileNames = state.getAspectNamesToFileNameMap(); if (buildConfig.getCompilationResultDestinationManager() == null || buildConfig.getCompilationResultDestinationManager().getAllOutputLocations().size() == 1) { // we only have one output directory...which simplifies things File outputDir = buildConfig.getOutputDir(); if (buildConfig.getCompilationResultDestinationManager() != null) { outputDir = buildConfig.getCompilationResultDestinationManager().getDefaultOutputLocation(); } List aspectNames = new ArrayList(); if (aspectNamesToFileNames != null) { Set keys = aspectNamesToFileNames.keySet(); for (Iterator iterator = keys.iterator(); iterator.hasNext();) { String name = (String) iterator.next(); aspectNames.add(name); } } outputDirsToAspects.put(outputDir, aspectNames); } else { List outputDirs = buildConfig.getCompilationResultDestinationManager().getAllOutputLocations(); for (Iterator iterator = outputDirs.iterator(); iterator.hasNext();) { File outputDir = (File) iterator.next(); outputDirsToAspects.put(outputDir,new ArrayList()); } Set entrySet = aspectNamesToFileNames.entrySet(); for (Iterator iterator = entrySet.iterator(); iterator.hasNext();) { Map.Entry entry = (Map.Entry) iterator.next(); String aspectName = (String) entry.getKey(); char[] fileName = (char[]) entry.getValue(); File outputDir = buildConfig.getCompilationResultDestinationManager() .getOutputLocationForClass(new File(new String(fileName))); if(!outputDirsToAspects.containsKey(outputDir)) { outputDirsToAspects.put(outputDir,new ArrayList()); } ((List)outputDirsToAspects.get(outputDir)).add(aspectName); } } return outputDirsToAspects; } // public static void dumprels() { // IRelationshipMap irm = AsmManager.getDefault().getRelationshipMap(); // int ctr = 1; // Set entries = irm.getEntries(); // for (Iterator iter = entries.iterator(); iter.hasNext();) { // String hid = (String) iter.next(); // List rels = irm.get(hid); // for (Iterator iterator = rels.iterator(); iterator.hasNext();) { // IRelationship ir = (IRelationship) iterator.next(); // List targets = ir.getTargets(); // for (Iterator iterator2 = targets.iterator(); // iterator2.hasNext(); // ) { // String thid = (String) iterator2.next(); // System.err.println("Hid:"+(ctr++)+":(targets="+targets.size()+") "+hid+" ("+ir.getName()+") "+thid); // } // } // } // } /** * Responsible for managing the ASM model between builds. Contains the policy for * maintaining the persistance of elements in the model. * * This code is driven before each 'fresh' (batch) build to create * a new model. */ private void setupModel(AjBuildConfig config) { AsmManager.setCreatingModel(config.isEmacsSymMode() || config.isGenerateModelMode()); if (!AsmManager.isCreatingModel()) return; AsmManager.getDefault().createNewASM(); // AsmManager.getDefault().getRelationshipMap().clear(); IHierarchy model = AsmManager.getDefault().getHierarchy(); String rootLabel = "<root>"; IProgramElement.Kind kind = IProgramElement.Kind.FILE_JAVA; if (buildConfig.getConfigFile() != null) { rootLabel = buildConfig.getConfigFile().getName(); model.setConfigFile(buildConfig.getConfigFile().getAbsolutePath()); kind = IProgramElement.Kind.FILE_LST; } model.setRoot(new ProgramElement(rootLabel, kind, new ArrayList())); model.setFileMap(new HashMap()); setStructureModel(model); state.setStructureModel(model); state.setRelationshipMap(AsmManager.getDefault().getRelationshipMap()); } // // private void dumplist(List l) { // System.err.println("---- "+l.size()); // for (int i =0 ;i<l.size();i++) System.err.println(i+"\t "+l.get(i)); // } // private void accumulateFileNodes(IProgramElement ipe,List store) { // if (ipe.getKind()==IProgramElement.Kind.FILE_JAVA || // ipe.getKind()==IProgramElement.Kind.FILE_ASPECTJ) { // if (!ipe.getName().equals("<root>")) { // store.add(ipe); // return; // } // } // for (Iterator i = ipe.getChildren().iterator();i.hasNext();) { // accumulateFileNodes((IProgramElement)i.next(),store); // } // } //LTODO delegate to BcelWeaver? // XXX hideous, should not be Object public void setCustomMungerFactory(Object o) { customMungerFactory = (CustomMungerFactory)o; } public Object getCustomMungerFactory() { return customMungerFactory; } /** init only on initial batch compile? no file-specific options */ private void initBcelWorld(IMessageHandler handler) throws IOException { List cp = buildConfig.getFullClasspath(); // pr145693 //buildConfig.getBootclasspath(); //cp.addAll(buildConfig.getClasspath()); BcelWorld bcelWorld = new BcelWorld(cp, handler, null); bcelWorld.setBehaveInJava5Way(buildConfig.getBehaveInJava5Way()); bcelWorld.setAddSerialVerUID(buildConfig.isAddSerialVerUID()); bcelWorld.performExtraConfiguration(buildConfig.getXconfigurationInfo()); bcelWorld.setTargetAspectjRuntimeLevel(buildConfig.getTargetAspectjRuntimeLevel()); bcelWorld.setOptionalJoinpoints(buildConfig.getXJoinpoints()); bcelWorld.setXnoInline(buildConfig.isXnoInline()); bcelWorld.setXlazyTjp(buildConfig.isXlazyTjp()); bcelWorld.setXHasMemberSupportEnabled(buildConfig.isXHasMemberEnabled()); bcelWorld.setPinpointMode(buildConfig.isXdevPinpoint()); bcelWorld.setErrorAndWarningThreshold(buildConfig.getOptions().errorThreshold,buildConfig.getOptions().warningThreshold); BcelWeaver bcelWeaver = new BcelWeaver(bcelWorld); bcelWeaver.setCustomMungerFactory(customMungerFactory); state.setWorld(bcelWorld); state.setWeaver(bcelWeaver); state.clearBinarySourceFiles(); if (buildConfig.getLintMode().equals(AjBuildConfig.AJLINT_DEFAULT)) { bcelWorld.getLint().loadDefaultProperties(); } else { bcelWorld.getLint().setAll(buildConfig.getLintMode()); } if (buildConfig.getLintSpecFile() != null) { bcelWorld.getLint().setFromProperties(buildConfig.getLintSpecFile()); } for (Iterator i = buildConfig.getAspectpath().iterator(); i.hasNext();) { File f = (File) i.next(); if (!f.exists()) { IMessage message = new Message("invalid aspectpath entry: "+f.getName(),null,true); handler.handleMessage(message); } else { bcelWeaver.addLibraryJarFile(f); } } // String lintMode = buildConfig.getLintMode(); File outputDir = buildConfig.getOutputDir(); if (outputDir == null && buildConfig.getCompilationResultDestinationManager() != null) { // send all output from injars and inpath to the default output location // (will also later send the manifest there too) outputDir = buildConfig.getCompilationResultDestinationManager().getDefaultOutputLocation(); } // ??? incremental issues for (Iterator i = buildConfig.getInJars().iterator(); i.hasNext();) { File inJar = (File) i.next(); List unwovenClasses = bcelWeaver.addJarFile(inJar, outputDir, false); state.recordBinarySource(inJar.getPath(), unwovenClasses); } for (Iterator i = buildConfig.getInpath().iterator(); i.hasNext(); ) { File inPathElement = (File)i.next(); if (!inPathElement.isDirectory()) { // its a jar file on the inpath // the weaver method can actually handle dirs, but we don't call it, see next block List unwovenClasses = bcelWeaver.addJarFile(inPathElement,outputDir,true); state.recordBinarySource(inPathElement.getPath(),unwovenClasses); } else { // add each class file in an in-dir individually, this gives us the best error reporting // (they are like 'source' files then), and enables a cleaner incremental treatment of // class file changes in indirs. File[] binSrcs = FileUtil.listFiles(inPathElement, binarySourceFilter); for (int j = 0; j < binSrcs.length; j++) { UnwovenClassFile ucf = bcelWeaver.addClassFile(binSrcs[j], inPathElement, outputDir); List ucfl = new ArrayList(); ucfl.add(ucf); state.recordBinarySource(binSrcs[j].getPath(),ucfl); } } } bcelWeaver.setReweavableMode(buildConfig.isXNotReweavable()); //check for org.aspectj.runtime.JoinPoint ResolvedType joinPoint = bcelWorld.resolve("org.aspectj.lang.JoinPoint"); if (joinPoint.isMissing()) { IMessage message = new Message("classpath error: unable to find org.aspectj.lang.JoinPoint (check that aspectjrt.jar is in your classpath)", null, true); handler.handleMessage(message); } } public World getWorld() { return getBcelWorld(); } void addAspectClassFilesToWeaver(List addedClassFiles) throws IOException { for (Iterator i = addedClassFiles.iterator(); i.hasNext(); ) { UnwovenClassFile classFile = (UnwovenClassFile) i.next(); getWeaver().addClassFile(classFile); } } // public boolean weaveAndGenerateClassFiles() throws IOException { // handler.handleMessage(MessageUtil.info("weaving")); // if (progressListener != null) progressListener.setText("weaving aspects"); // bcelWeaver.setProgressListener(progressListener, 0.5, 0.5/state.addedClassFiles.size()); // //!!! doesn't provide intermediate progress during weaving // // XXX add all aspects even during incremental builds? // addAspectClassFilesToWeaver(state.addedClassFiles); // if (buildConfig.isNoWeave()) { // if (buildConfig.getOutputJar() != null) { // bcelWeaver.dumpUnwoven(buildConfig.getOutputJar()); // } else { // bcelWeaver.dumpUnwoven(); // bcelWeaver.dumpResourcesToOutPath(); // } // } else { // if (buildConfig.getOutputJar() != null) { // bcelWeaver.weave(buildConfig.getOutputJar()); // } else { // bcelWeaver.weave(); // bcelWeaver.dumpResourcesToOutPath(); // } // } // if (progressListener != null) progressListener.setProgress(1.0); // return true; // //return messageAdapter.getErrorCount() == 0; //!javaBuilder.notifier.anyErrors(); // } public FileSystem getLibraryAccess(String[] classpaths, String[] filenames) { String defaultEncoding = buildConfig.getOptions().defaultEncoding; if ("".equals(defaultEncoding)) //$NON-NLS-1$ defaultEncoding = null; //$NON-NLS-1$ // Bug 46671: We need an array as long as the number of elements in the classpath - *even though* not every // element of the classpath is likely to be a directory. If we ensure every element of the array is set to // only look for BINARY, then we make sure that for any classpath element that is a directory, we won't build // a classpathDirectory object that will attempt to look for source when it can't find binary. // int[] classpathModes = new int[classpaths.length]; // for (int i =0 ;i<classpaths.length;i++) classpathModes[i]=ClasspathDirectory.BINARY; return new FileSystem(classpaths, filenames, defaultEncoding,ClasspathLocation.BINARY); } public IProblemFactory getProblemFactory() { return new DefaultProblemFactory(Locale.getDefault()); } /* * Build the set of compilation source units */ public CompilationUnit[] getCompilationUnits(String[] filenames, String[] encodings) { int fileCount = filenames.length; CompilationUnit[] units = new CompilationUnit[fileCount]; // HashtableOfObject knownFileNames = new HashtableOfObject(fileCount); String defaultEncoding = buildConfig.getOptions().defaultEncoding; if ("".equals(defaultEncoding)) //$NON-NLS-1$ defaultEncoding = null; //$NON-NLS-1$ for (int i = 0; i < fileCount; i++) { String encoding = encodings[i]; if (encoding == null) encoding = defaultEncoding; units[i] = new CompilationUnit(null, filenames[i], encoding); } return units; } public String extractDestinationPathFromSourceFile(CompilationResult result) { ICompilationUnit compilationUnit = result.compilationUnit; if (compilationUnit != null) { char[] fileName = compilationUnit.getFileName(); int lastIndex = CharOperation.lastIndexOf(java.io.File.separatorChar, fileName); if (lastIndex == -1) { return System.getProperty("user.dir"); //$NON-NLS-1$ } return new String(CharOperation.subarray(fileName, 0, lastIndex)); } return System.getProperty("user.dir"); //$NON-NLS-1$ } public void performCompilation(List files) { if (progressListener != null) { compiledCount=0; sourceFileCount = files.size(); progressListener.setText("compiling source files"); } //System.err.println("got files: " + files); String[] filenames = new String[files.size()]; String[] encodings = new String[files.size()]; //System.err.println("filename: " + this.filenames); for (int i=0; i < files.size(); i++) { filenames[i] = ((File)files.get(i)).getPath(); } List cps = buildConfig.getFullClasspath(); Dump.saveFullClasspath(cps); String[] classpaths = new String[cps.size()]; for (int i=0; i < cps.size(); i++) { classpaths[i] = (String)cps.get(i); } //System.out.println("compiling"); environment = getLibraryAccess(classpaths, filenames); //if (!state.getClassNameToFileMap().isEmpty()) { // see pr133532 (disabled to state can be used to answer questions) environment = new StatefulNameEnvironment(environment, state.getClassNameToFileMap(),state); //} org.aspectj.ajdt.internal.compiler.CompilerAdapter.setCompilerAdapterFactory(this); org.aspectj.org.eclipse.jdt.internal.compiler.Compiler compiler = new org.aspectj.org.eclipse.jdt.internal.compiler.Compiler(environment, DefaultErrorHandlingPolicies.proceedWithAllProblems(), buildConfig.getOptions().getMap(), getBatchRequestor(), getProblemFactory()); CompilerOptions options = compiler.options; options.produceReferenceInfo = true; //TODO turn off when not needed try { compiler.compile(getCompilationUnits(filenames, encodings)); } catch (OperationCanceledException oce) { handler.handleMessage(new Message("build cancelled:"+oce.getMessage(),IMessage.WARNING,null,null)); } // cleanup org.aspectj.ajdt.internal.compiler.CompilerAdapter.setCompilerAdapterFactory(null); AnonymousClassPublisher.aspectOf().setAnonymousClassCreationListener(null); environment.cleanup(); environment = null; } /* * Answer the component to which will be handed back compilation results from the compiler */ public IIntermediateResultsRequestor getInterimResultRequestor() { return new IIntermediateResultsRequestor() { public void acceptResult(InterimCompilationResult result) { if (progressListener != null) { compiledCount++; progressListener.setProgress((compiledCount/2.0)/sourceFileCount); progressListener.setText("compiled: " + result.fileName()); } state.noteResult(result); if (progressListener!=null && progressListener.isCancelledRequested()) { throw new AbortCompilation(true, new OperationCanceledException("Compilation cancelled as requested")); } } }; } public ICompilerRequestor getBatchRequestor() { return new ICompilerRequestor() { public void acceptResult(CompilationResult unitResult) { // end of compile, must now write the results to the output destination // this is either a jar file or a file in a directory if (!(unitResult.hasErrors() && !proceedOnError())) { Collection classFiles = unitResult.compiledTypes.values(); boolean shouldAddAspectName = (buildConfig.getOutxmlName() != null); for (Iterator iter = classFiles.iterator(); iter.hasNext();) { ClassFile classFile = (ClassFile) iter.next(); String filename = new String(classFile.fileName()); String classname = filename.replace('/', '.'); filename = filename.replace('/', File.separatorChar) + ".class"; try { if (buildConfig.getOutputJar() == null) { writeDirectoryEntry(unitResult, classFile,filename); } else { writeZipEntry(classFile,filename); } if (shouldAddAspectName) addAspectName(classname, unitResult.getFileName()); } catch (IOException ex) { IMessage message = EclipseAdapterUtils.makeErrorMessage( new String(unitResult.fileName), CANT_WRITE_RESULT, ex); handler.handleMessage(message); } } unitResult.compiledTypes.clear(); // free up references to AjClassFile instances } if (unitResult.hasProblems() || unitResult.hasTasks()) { IProblem[] problems = unitResult.getAllProblems(); for (int i=0; i < problems.length; i++) { IMessage message = EclipseAdapterUtils.makeMessage(unitResult.compilationUnit, problems[i],getBcelWorld()); handler.handleMessage(message); } } } private void writeDirectoryEntry( CompilationResult unitResult, ClassFile classFile, String filename) throws IOException { File destinationPath = buildConfig.getOutputDir(); if (buildConfig.getCompilationResultDestinationManager() != null) { destinationPath = buildConfig.getCompilationResultDestinationManager().getOutputLocationForClass(new File(new String(unitResult.fileName))); } String outFile; if (destinationPath == null) { outFile = new File(filename).getName(); outFile = new File(extractDestinationPathFromSourceFile(unitResult), outFile).getPath(); } else { outFile = new File(destinationPath, filename).getPath(); } BufferedOutputStream os = FileUtil.makeOutputStream(new File(outFile)); os.write(classFile.getBytes()); os.close(); } private void writeZipEntry(ClassFile classFile, String name) throws IOException { name = name.replace(File.separatorChar,'/'); ZipEntry newEntry = new ZipEntry(name); //??? get compression scheme right zos.putNextEntry(newEntry); zos.write(classFile.getBytes()); zos.closeEntry(); } private void addAspectName (String name, char[] fileContainingAspect) { BcelWorld world = getBcelWorld(); ResolvedType type = world.resolve(name); // System.err.println("? writeAspectName() type=" + type); if (type.isAspect()) { if (state.getAspectNamesToFileNameMap() == null) { state.initializeAspectNamesToFileNameMap(); } if (!state.getAspectNamesToFileNameMap().containsKey(name)) { state.getAspectNamesToFileNameMap().put(name, fileContainingAspect); } } } }; } protected boolean proceedOnError() { return buildConfig.getProceedOnError(); } // public void noteClassFiles(AjCompiler.InterimResult result) { // if (result == null) return; // CompilationResult unitResult = result.result; // String sourceFileName = result.fileName(); // if (!(unitResult.hasErrors() && !proceedOnError())) { // List unwovenClassFiles = new ArrayList(); // Enumeration classFiles = unitResult.compiledTypes.elements(); // while (classFiles.hasMoreElements()) { // ClassFile classFile = (ClassFile) classFiles.nextElement(); // String filename = new String(classFile.fileName()); // filename = filename.replace('/', File.separatorChar) + ".class"; // // File destinationPath = buildConfig.getOutputDir(); // if (destinationPath == null) { // filename = new File(filename).getName(); // filename = new File(extractDestinationPathFromSourceFile(unitResult), filename).getPath(); // } else { // filename = new File(destinationPath, filename).getPath(); // } // // //System.out.println("classfile: " + filename); // unwovenClassFiles.add(new UnwovenClassFile(filename, classFile.getBytes())); // } // state.noteClassesFromFile(unitResult, sourceFileName, unwovenClassFiles); //// System.out.println("file: " + sourceFileName); //// for (int i=0; i < unitResult.simpleNameReferences.length; i++) { //// System.out.println("simple: " + new String(unitResult.simpleNameReferences[i])); //// } //// for (int i=0; i < unitResult.qualifiedReferences.length; i++) { //// System.out.println("qualified: " + //// new String(CharOperation.concatWith(unitResult.qualifiedReferences[i], '/'))); //// } // } else { // state.noteClassesFromFile(null, sourceFileName, Collections.EMPTY_LIST); // } // } // private void setBuildConfig(AjBuildConfig buildConfig) { this.buildConfig = buildConfig; if (!this.environmentSupportsIncrementalCompilation) { this.environmentSupportsIncrementalCompilation = (buildConfig.isIncrementalMode() || buildConfig.isIncrementalFileMode()); } handler.reset(); } String makeClasspathString(AjBuildConfig buildConfig) { if (buildConfig == null || buildConfig.getFullClasspath() == null) return ""; StringBuffer buf = new StringBuffer(); boolean first = true; for (Iterator it = buildConfig.getFullClasspath().iterator(); it.hasNext(); ) { if (first) { first = false; } else { buf.append(File.pathSeparator); } buf.append(it.next().toString()); } return buf.toString(); } /** * This will return null if aspectjrt.jar is present and has the correct version. * Otherwise it will return a string message indicating the problem. */ private String checkRtJar(AjBuildConfig buildConfig) { // omitting dev info if (Version.text.equals(Version.DEVELOPMENT)) { // in the development version we can't do this test usefully // MessageUtil.info(holder, "running development version of aspectj compiler"); return null; } if (buildConfig == null || buildConfig.getFullClasspath() == null) return "no classpath specified"; String ret = null; for (Iterator it = buildConfig.getFullClasspath().iterator(); it.hasNext(); ) { File p = new File( (String)it.next() ); // pr112830, allow variations on aspectjrt.jar of the form aspectjrtXXXXXX.jar if (p.isFile() && p.getName().startsWith("aspectjrt") && p.getName().endsWith(".jar")) { try { String version = null; Manifest manifest = new JarFile(p).getManifest(); if (manifest == null) { ret = "no manifest found in " + p.getAbsolutePath() + ", expected " + Version.text; continue; } Attributes attr = manifest.getAttributes("org/aspectj/lang/"); if (null != attr) { version = attr.getValue(Attributes.Name.IMPLEMENTATION_VERSION); if (null != version) { version = version.trim(); } } // assume that users of development aspectjrt.jar know what they're doing if (Version.DEVELOPMENT.equals(version)) { // MessageUtil.info(holder, // "running with development version of aspectjrt.jar in " + // p.getAbsolutePath()); return null; } else if (!Version.text.equals(version)) { ret = "bad version number found in " + p.getAbsolutePath() + " expected " + Version.text + " found " + version; continue; } } catch (IOException ioe) { ret = "bad jar file found in " + p.getAbsolutePath() + " error: " + ioe; } return null; // this is the "OK" return value! } else { // might want to catch other classpath errors } } if (ret != null) return ret; // last error found in potentially matching jars... return "couldn't find aspectjrt.jar on classpath, checked: " + makeClasspathString(buildConfig); } public String toString() { StringBuffer buf = new StringBuffer(); buf.append("AjBuildManager("); buf.append(")"); return buf.toString(); } public void setStructureModel(IHierarchy structureModel) { this.structureModel = structureModel; } /** * Returns null if there is no structure model */ public IHierarchy getStructureModel() { return structureModel; } public IProgressListener getProgressListener() { return progressListener; } public void setProgressListener(IProgressListener progressListener) { this.progressListener = progressListener; } /* (non-Javadoc) * @see org.aspectj.ajdt.internal.compiler.AjCompiler.IOutputClassFileNameProvider#getOutputClassFileName(char[]) */ public String getOutputClassFileName(char[] eclipseClassFileName, CompilationResult result) { String filename = new String(eclipseClassFileName); filename = filename.replace('/', File.separatorChar) + ".class"; File destinationPath = buildConfig.getOutputDir(); if (buildConfig.getCompilationResultDestinationManager() != null) { File f = new File(new String(result.getFileName())); destinationPath = buildConfig.getCompilationResultDestinationManager().getOutputLocationForClass(f); } String outFile; if (destinationPath == null) { outFile = new File(filename).getName(); outFile = new File(extractDestinationPathFromSourceFile(result), outFile).getPath(); } else { outFile = new File(destinationPath, filename).getPath(); } return outFile; } /* (non-Javadoc) * @see org.eclipse.jdt.internal.compiler.ICompilerAdapterFactory#getAdapter(org.eclipse.jdt.internal.compiler.Compiler) */ public ICompilerAdapter getAdapter(org.aspectj.org.eclipse.jdt.internal.compiler.Compiler forCompiler) { // complete compiler config and return a suitable adapter... populateCompilerOptionsFromLintSettings(forCompiler); AjProblemReporter pr = new AjProblemReporter(DefaultErrorHandlingPolicies.proceedWithAllProblems(), forCompiler.options, getProblemFactory()); forCompiler.problemReporter = pr; AjLookupEnvironment le = new AjLookupEnvironment(forCompiler, forCompiler.options, pr, environment); EclipseFactory factory = new EclipseFactory(le,this); le.factory = factory; pr.factory = factory; forCompiler.lookupEnvironment = le; forCompiler.parser = new Parser( pr, forCompiler.options.parseLiteralExpressionsAsConstants); if (getBcelWorld().shouldPipelineCompilation()) { IMessage message = MessageUtil.info("Pipelining compilation"); handler.handleMessage(message); return new AjPipeliningCompilerAdapter(forCompiler,batchCompile,getBcelWorld(),getWeaver(), factory, getInterimResultRequestor(), progressListener, this, // IOutputFilenameProvider this, // IBinarySourceProvider state.getBinarySourceMap(), buildConfig.isTerminateAfterCompilation(), buildConfig.getProceedOnError(), buildConfig.isNoAtAspectJAnnotationProcessing(), state); } else { return new AjCompilerAdapter(forCompiler,batchCompile,getBcelWorld(),getWeaver(), factory, getInterimResultRequestor(), progressListener, this, // IOutputFilenameProvider this, // IBinarySourceProvider state.getBinarySourceMap(), buildConfig.isTerminateAfterCompilation(), buildConfig.getProceedOnError(), buildConfig.isNoAtAspectJAnnotationProcessing(), state); } } /** * Some AspectJ lint options need to be known about in the compiler. This is * how we pass them over... * @param forCompiler */ private void populateCompilerOptionsFromLintSettings(org.aspectj.org.eclipse.jdt.internal.compiler.Compiler forCompiler) { BcelWorld world = this.state.getBcelWorld(); IMessage.Kind swallowedExceptionKind = world.getLint().swallowedExceptionInCatchBlock.getKind(); Map optionsMap = new HashMap(); optionsMap.put(CompilerOptions.OPTION_ReportSwallowedExceptionInCatchBlock, swallowedExceptionKind == null ? "ignore" : swallowedExceptionKind.toString()); forCompiler.options.set(optionsMap); } /* (non-Javadoc) * @see org.aspectj.ajdt.internal.compiler.IBinarySourceProvider#getBinarySourcesForThisWeave() */ public Map getBinarySourcesForThisWeave() { return binarySourcesForTheNextCompile; } public static AsmHierarchyBuilder getAsmHierarchyBuilder() { return asmHierarchyBuilder; } /** * Override the the default hierarchy builder. */ public static void setAsmHierarchyBuilder(AsmHierarchyBuilder newBuilder) { asmHierarchyBuilder = newBuilder; } public AjState getState() { return state; } public void setState(AjState buildState) { state = buildState; } private static class AjBuildContexFormatter implements ContextFormatter { public String formatEntry(int phaseId, Object data) { StringBuffer sb = new StringBuffer(); if (phaseId == CompilationAndWeavingContext.BATCH_BUILD) { sb.append("batch building "); } else { sb.append("incrementally building "); } AjBuildConfig config = (AjBuildConfig) data; List classpath = config.getClasspath(); sb.append("with classpath: "); for (Iterator iter = classpath.iterator(); iter.hasNext();) { sb.append(iter.next().toString()); sb.append(File.pathSeparator); } return sb.toString(); } } public boolean wasFullBuild() { return wasFullBuild; } }
222,987
Bug 222987 More NPEs in Java15AnnotationFinder
null
resolved fixed
6c54db9
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2008-03-20T15:48:59Z"
"2008-03-17T18:53:20Z"
weaver5/java5-src/org/aspectj/weaver/reflect/Java15AnnotationFinder.java
/* ******************************************************************* * Copyright (c) 2005 Contributors. * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Eclipse Public License v1.0 * which accompanies this distribution and is available at * http://eclipse.org/legal/epl-v10.html * * Contributors: * Adrian Colyer Initial implementation * ******************************************************************/ package org.aspectj.weaver.reflect; import java.lang.annotation.Annotation; import java.lang.reflect.AccessibleObject; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.Member; import java.lang.reflect.Method; import java.util.Collections; import java.util.HashSet; import java.util.Set; import org.aspectj.apache.bcel.classfile.AnnotationDefault; import org.aspectj.apache.bcel.classfile.Attribute; import org.aspectj.apache.bcel.classfile.JavaClass; import org.aspectj.apache.bcel.classfile.LocalVariable; import org.aspectj.apache.bcel.classfile.LocalVariableTable; import org.aspectj.apache.bcel.util.NonCachingClassLoaderRepository; import org.aspectj.apache.bcel.util.Repository; import org.aspectj.weaver.AnnotationX; import org.aspectj.weaver.ResolvedType; import org.aspectj.weaver.UnresolvedType; import org.aspectj.weaver.World; /** * Find the given annotation (if present) on the given object * */ public class Java15AnnotationFinder implements AnnotationFinder, ArgNameFinder { private Repository bcelRepository; private ClassLoader classLoader; private World world; // must have no-arg constructor for reflective construction public Java15AnnotationFinder() { } public void setClassLoader(ClassLoader aLoader) { // TODO: No easy way to ask the world factory for the right kind of repository so // default to the safe one! (pr160674) this.bcelRepository = new NonCachingClassLoaderRepository(aLoader); this.classLoader = aLoader; } public void setWorld(World aWorld) { this.world = aWorld; } /* (non-Javadoc) * @see org.aspectj.weaver.reflect.AnnotationFinder#getAnnotation(org.aspectj.weaver.ResolvedType, java.lang.Object) */ public Object getAnnotation(ResolvedType annotationType, Object onObject) { try { Class<? extends Annotation> annotationClass = (Class<? extends Annotation>) Class.forName(annotationType.getName(),false,classLoader); if (onObject.getClass().isAnnotationPresent(annotationClass)) { return onObject.getClass().getAnnotation(annotationClass); } } catch (ClassNotFoundException ex) { // just return null } return null; } public Object getAnnotationFromClass(ResolvedType annotationType, Class aClass) { try { Class<? extends Annotation> annotationClass = (Class<? extends Annotation>) Class.forName(annotationType.getName(),false,classLoader); if (aClass.isAnnotationPresent(annotationClass)) { return aClass.getAnnotation(annotationClass); } } catch (ClassNotFoundException ex) { // just return null } return null; } public Object getAnnotationFromMember(ResolvedType annotationType, Member aMember) { if (!(aMember instanceof AccessibleObject)) return null; AccessibleObject ao = (AccessibleObject) aMember; try { Class annotationClass = Class.forName(annotationType.getName(),false,classLoader); if (ao.isAnnotationPresent(annotationClass)) { return ao.getAnnotation(annotationClass); } } catch (ClassNotFoundException ex) { // just return null } return null; } public AnnotationX getAnnotationOfType(UnresolvedType ofType,Member onMember) { if (!(onMember instanceof AccessibleObject)) return null; // here we really want both the runtime visible AND the class visible annotations // so we bail out to Bcel and then chuck away the JavaClass so that we don't hog // memory. try { JavaClass jc = bcelRepository.loadClass(onMember.getDeclaringClass()); org.aspectj.apache.bcel.classfile.annotation.Annotation[] anns = new org.aspectj.apache.bcel.classfile.annotation.Annotation[0]; if (onMember instanceof Method) { org.aspectj.apache.bcel.classfile.Method bcelMethod = jc.getMethod((Method)onMember); if (bcelMethod == null) { // pr220430 //System.err.println("Unexpected problem in Java15AnnotationFinder: cannot retrieve annotations on method '"+onMember.getName()+"' in class '"+jc.getClassName()+"'"); } else { anns = bcelMethod.getAnnotations(); } } else if (onMember instanceof Constructor) { org.aspectj.apache.bcel.classfile.Method bcelCons = jc.getMethod((Constructor)onMember); anns = bcelCons.getAnnotations(); } else if (onMember instanceof Field) { org.aspectj.apache.bcel.classfile.Field bcelField = jc.getField((Field)onMember); anns = bcelField.getAnnotations(); } // the answer is cached and we don't want to hold on to memory bcelRepository.clear(); if (anns == null) anns = new org.aspectj.apache.bcel.classfile.annotation.Annotation[0]; // convert to our Annotation type for (int i=0;i<anns.length;i++) { if (anns[i].getTypeSignature().equals(ofType.getSignature())) { return new AnnotationX(anns[i],world); } } return null; } catch (ClassNotFoundException cnfEx) { // just use reflection then } return null; } public String getAnnotationDefaultValue(Member onMember) { try { JavaClass jc = bcelRepository.loadClass(onMember.getDeclaringClass()); if (onMember instanceof Method) { org.aspectj.apache.bcel.classfile.Method bcelMethod = jc.getMethod((Method)onMember); if (bcelMethod == null) { // pr220430 // System.err.println("Unexpected problem in Java15AnnotationFinder: cannot retrieve annotations on method '"+onMember.getName()+"' in class '"+jc.getClassName()+"'"); } else { Attribute[] attrs = bcelMethod.getAttributes(); for (int i = 0; i < attrs.length; i++) { Attribute attribute = attrs[i]; if (attribute.getName().equals("AnnotationDefault")) { AnnotationDefault def = (AnnotationDefault)attribute; return def.getElementValue().stringifyValue(); } } return null; } } } catch (ClassNotFoundException cnfEx) { // just use reflection then } return null; } public Set getAnnotations(Member onMember) { if (!(onMember instanceof AccessibleObject)) return Collections.EMPTY_SET; // here we really want both the runtime visible AND the class visible annotations // so we bail out to Bcel and then chuck away the JavaClass so that we don't hog // memory. try { JavaClass jc = bcelRepository.loadClass(onMember.getDeclaringClass()); org.aspectj.apache.bcel.classfile.annotation.Annotation[] anns = new org.aspectj.apache.bcel.classfile.annotation.Annotation[0]; if (onMember instanceof Method) { org.aspectj.apache.bcel.classfile.Method bcelMethod = jc.getMethod((Method)onMember); if (bcelMethod == null) { // fallback on reflection - see pr220430 // System.err.println("Unexpected problem in Java15AnnotationFinder: cannot retrieve annotations on method '"+onMember.getName()+"' in class '"+jc.getClassName()+"'"); } else { anns = bcelMethod.getAnnotations(); } } else if (onMember instanceof Constructor) { org.aspectj.apache.bcel.classfile.Method bcelCons = jc.getMethod((Constructor)onMember); anns = bcelCons.getAnnotations(); } else if (onMember instanceof Field) { org.aspectj.apache.bcel.classfile.Field bcelField = jc.getField((Field)onMember); anns = bcelField.getAnnotations(); } // the answer is cached and we don't want to hold on to memory bcelRepository.clear(); if (anns == null) anns = new org.aspectj.apache.bcel.classfile.annotation.Annotation[0]; // convert to our Annotation type Set<ResolvedType> annSet = new HashSet<ResolvedType>(); for (int i = 0; i < anns.length; i++) { annSet.add(world.resolve(UnresolvedType.forSignature(anns[i].getTypeSignature()))); } return annSet; } catch (ClassNotFoundException cnfEx) { // just use reflection then } AccessibleObject ao = (AccessibleObject) onMember; Annotation[] anns = ao.getDeclaredAnnotations(); Set<UnresolvedType> annSet = new HashSet<UnresolvedType>(); for (int i = 0; i < anns.length; i++) { annSet.add(UnresolvedType.forName(anns[i].annotationType().getName()).resolve(world)); } return annSet; } public ResolvedType[] getAnnotations(Class forClass, World inWorld) { // here we really want both the runtime visible AND the class visible annotations // so we bail out to Bcel and then chuck away the JavaClass so that we don't hog // memory. try { JavaClass jc = bcelRepository.loadClass(forClass); org.aspectj.apache.bcel.classfile.annotation.Annotation[] anns =jc.getAnnotations(); bcelRepository.clear(); if (anns == null) return new ResolvedType[0]; ResolvedType[] ret = new ResolvedType[anns.length]; for (int i = 0; i < ret.length; i++) { ret[i] = inWorld.resolve(UnresolvedType.forSignature(anns[i].getTypeSignature())); } return ret; } catch (ClassNotFoundException cnfEx) { // just use reflection then } Annotation[] classAnnotations = forClass.getAnnotations(); ResolvedType[] ret = new ResolvedType[classAnnotations.length]; for (int i = 0; i < classAnnotations.length; i++) { ret[i] = inWorld.resolve(classAnnotations[i].annotationType().getName()); } return ret; } public String[] getParameterNames(Member forMember) { if (!(forMember instanceof AccessibleObject)) return null; try { JavaClass jc = bcelRepository.loadClass(forMember.getDeclaringClass()); LocalVariableTable lvt = null; int numVars = 0; if (forMember instanceof Method) { org.aspectj.apache.bcel.classfile.Method bcelMethod = jc.getMethod((Method)forMember); lvt = bcelMethod.getLocalVariableTable(); numVars = bcelMethod.getArgumentTypes().length; } else if (forMember instanceof Constructor) { org.aspectj.apache.bcel.classfile.Method bcelCons = jc.getMethod((Constructor)forMember); lvt = bcelCons.getLocalVariableTable(); numVars = bcelCons.getArgumentTypes().length; } return getParameterNamesFromLVT(lvt,numVars); } catch (ClassNotFoundException cnfEx) { ; // no luck } return null; } private String[] getParameterNamesFromLVT(LocalVariableTable lvt, int numVars) { LocalVariable[] vars = lvt.getLocalVariableTable(); if (vars.length < numVars) { // basic error, we can't get the names... return null; } String[] ret = new String[numVars]; for(int i = 0; i < numVars; i++) { ret[i] = vars[i+1].getName(); } return ret; } public static final ResolvedType[][] NO_PARAMETER_ANNOTATIONS = new ResolvedType[][]{}; public ResolvedType[][] getParameterAnnotationTypes(Member onMember) { if (!(onMember instanceof AccessibleObject)) return NO_PARAMETER_ANNOTATIONS; // here we really want both the runtime visible AND the class visible annotations // so we bail out to Bcel and then chuck away the JavaClass so that we don't hog // memory. try { JavaClass jc = bcelRepository.loadClass(onMember.getDeclaringClass()); org.aspectj.apache.bcel.classfile.annotation.Annotation[][] anns = null; if (onMember instanceof Method) { org.aspectj.apache.bcel.classfile.Method bcelMethod = jc.getMethod((Method)onMember); if (bcelMethod == null) { // pr220430 //System.err.println("Unexpected problem in Java15AnnotationFinder: cannot retrieve annotations on method '"+onMember.getName()+"' in class '"+jc.getClassName()+"'"); } else { anns = bcelMethod.getParameterAnnotations(); } } else if (onMember instanceof Constructor) { org.aspectj.apache.bcel.classfile.Method bcelCons = jc.getMethod((Constructor)onMember); anns = bcelCons.getParameterAnnotations(); } else if (onMember instanceof Field) { anns = null; } // the answer is cached and we don't want to hold on to memory bcelRepository.clear(); if (anns == null) return NO_PARAMETER_ANNOTATIONS; ResolvedType[][] result = new ResolvedType[anns.length][]; // CACHING?? for (int i=0;i<anns.length;i++) { if (anns[i]!=null) { result[i] = new ResolvedType[anns[i].length]; for (int j=0;j<anns[i].length;j++) { result[i][j] = world.resolve(UnresolvedType.forSignature(anns[i][j].getTypeSignature())); } } } return result; } catch (ClassNotFoundException cnfEx) { // just use reflection then } // reflection... AccessibleObject ao = (AccessibleObject) onMember; Annotation[][] anns = null; if (onMember instanceof Method) { anns = ((Method)ao).getParameterAnnotations(); } else if (onMember instanceof Constructor) { anns = ((Constructor)ao).getParameterAnnotations(); } else if (onMember instanceof Field) { anns = null; } if (anns == null) return NO_PARAMETER_ANNOTATIONS; ResolvedType[][] result = new ResolvedType[anns.length][]; // CACHING?? for (int i=0;i<anns.length;i++) { if (anns[i]!=null) { result[i] = new ResolvedType[anns[i].length]; for (int j=0;j<anns[i].length;j++) { result[i][j] = UnresolvedType.forName(anns[i][j].annotationType().getName()).resolve(world); } } } return result; } }
163,802
Bug 163802 Compilation error
Hello, I had several times aspectj compiler errors when compiling some normal java class file (not refering any aspect nor concerned by an aspect) but in a aspectJ project. Bug goes away after cleaning project. Here is the error reported for my class java.lang.NullPointerException at org.aspectj.weaver.ResolvedType.collectInterTypeMungers(ResolvedType.java:1158) at org.aspectj.weaver.ResolvedType.collectInterTypeMungers(ResolvedType.java:1158) at org.aspectj.weaver.ResolvedType.getInterTypeMungersIncludingSupers(ResolvedType.java:1135) at org.aspectj.weaver.ResolvedType.checkInterTypeMungers(ResolvedType.java:1202) at org.aspectj.ajdt.internal.compiler.lookup.AjLookupEnvironment.weaveInt ... Adapter.java:102) at org.aspectj.ajde.internal.AspectJBuildManager$CompilerThread.run(AspectJBuildManager.java:191) NullPointerException thrown: null It occurs with plugin configuration: com.ibm.icu (3.4.5) "International Components for Unicode for Java (ICU4J)" [Active] com.ibm.icu.source (3.4.5) "International Components for Unicode for Java (ICU4J) source plug-in" [Resolved] com.jcraft.jsch (0.1.28) "JSch" [Resolved] net.sf.fjep.fatjar (0.0.24) "Fat Jar Plug-in" [Resolved] org.apache.ant (1.6.5) "Apache Ant" [Resolved] org.apache.lucene (1.4.103.v20060601) "Apache Lucene" [Resolved] org.aspectj.ajde (1.5.3.200610201049) "AspectJ" [Active] org.aspectj.runtime (1.5.3.200610201049) "AspectJ Runtime" [Resolved] org.aspectj.weaver (1.5.3.200610201049) "AspectJ Weaver" [Resolved] org.eclipse.ajdt.core (1.4.1.200611071030) "AspectJ Development Tools Core" [Active] org.eclipse.ajdt.examples (1.4.1.200611071030) "AspectJ Examples" [Resolved] org.eclipse.ajdt.pde.build (1.4.1.200611071030) "AspectJ Plug-in Development Environment Build Support" [Resolved] org.eclipse.ajdt.source (1.4.1.200611071030) "pluginName" [Resolved] org.eclipse.ajdt.ui (1.4.1.200611071030) "AspectJ Development Tools UI" [Active] org.eclipse.ant.core (3.1.100.v20060531) "Ant Build Tool Core" [Resolved] org.eclipse.ant.ui (3.2.1.r321_v20060828) "Ant UI" [Resolved] org.eclipse.aspectj (1.4.1.200611071030) "AspectJ Development Tools" [Resolved] org.eclipse.compare (3.2.1.M20060711) "Compare Support" [Active] org.eclipse.contribution.visualiser (2.2.0.200611071030) "Visualiser Plug-in" [Resolved] org.eclipse.contribution.xref.core (1.4.1.200611071030) "Cross Reference Core Plugin" [Active] org.eclipse.contribution.xref.ui (1.4.1.200611071030) "Cross Reference UI Plugin" [Active] org.eclipse.core.boot (3.1.100.v20060603) "Core Boot" [Resolved] org.eclipse.core.commands (3.2.0.I20060605-1400) "Commands" [Resolved] org.eclipse.core.contenttype (3.2.0.v20060603) "Eclipse Content Mechanism" [Active] org.eclipse.core.expressions (3.2.1.r321_v20060721) "Expression Language" [Active] org.eclipse.core.filebuffers (3.2.1.r321_v20060721) "File Buffers" [Active] org.eclipse.core.filesystem (1.0.0.v20060603) "Core File Systems" [Resolved] org.eclipse.core.filesystem.macosx (1.0.0.v20060603) "Core File System for Macintosh" [Resolved] org.eclipse.core.jobs (3.2.0.v20060603) "Eclipse Jobs Mechanism" [Active] org.eclipse.core.resources (3.2.1.R32x_v20060914) "Core Resource Management" [Active] org.eclipse.core.resources.compatibility (3.2.0.v20060603) "Core Resource Management Compatibility Fragment" [Resolved] org.eclipse.core.runtime (3.2.0.v20060603) "Core Runtime" [Active] org.eclipse.core.runtime.compatibility (3.1.100.v20060603) "Core Runtime Plug-in Compatibility" [Active] org.eclipse.core.runtime.compatibility.auth (3.2.0.v20060601) "Authorization Compatibility Plug-in" [Active] org.eclipse.core.runtime.compatibility.registry (3.2.1.R32x_v20060907) "Eclipse Registry Compatibility Fragment" [Resolved] org.eclipse.core.variables (3.1.100.v20060605) "Core Variables" [Active] org.eclipse.debug.core (3.2.1.v20060823) "Debug Core" [Active] org.eclipse.debug.ui (3.2.1.v20060823) "Debug UI" [Active] org.eclipse.equinox.common (3.2.0.v20060603) "Common Eclipse Runtime" [Active] org.eclipse.equinox.preferences (3.2.1.R32x_v20060717) "Eclipse Preferences Mechanism" [Active] org.eclipse.equinox.registry (3.2.1.R32x_v20060814) "Extension Registry Support" [Active] org.eclipse.help (3.2.1.R321_v20060920) "Help System Core" [Active] org.eclipse.help.appserver (3.1.100.v20060602) "Help Application Server" [Resolved] org.eclipse.help.base (3.2.1.R321_v20060822) "Help System Base" [Resolved] org.eclipse.help.ui (3.2.0.v20060602) "Help System UI" [Resolved] org.eclipse.help.webapp (3.2.1.R321_v20060803) "Help System Webapp" [Resolved] org.eclipse.jdt (3.2.1.r321_v20060823) "Eclipse Java Development Tools" [Resolved] org.eclipse.jdt.apt.core (3.2.1.R32x_v20060822-2100) "Java Annotation Processing Core" [Active] org.eclipse.jdt.apt.ui (3.2.1.R32x_v20060822-2100) "Java Annotation Processing UI" [Resolved] org.eclipse.jdt.core (3.2.1.v_677_R32x) "Java Development Tools Core" [Active] org.eclipse.jdt.core.manipulation (1.0.1.r321_v20060721) "Java Code Manipulation Functionality" [Resolved] org.eclipse.jdt.debug (3.2.1.r321_v20060731) "JDI Debug Model" [Active] org.eclipse.jdt.debug.ui (3.2.1.r321_v20060918) "JDI Debug UI" [Active] org.eclipse.jdt.doc.isv (3.2.1.r321_v20060907) "Eclipse JDT Plug-in Developer Guide" [Resolved] org.eclipse.jdt.doc.user (3.2.0.v20060605-1400) "Eclipse Java Development User Guide" [Resolved] org.eclipse.jdt.junit (3.2.1.r321_v20060810) "Java Development Tools JUnit support" [Active] org.eclipse.jdt.junit.runtime (3.2.1.r321_v20060721) "Java Development Tools JUnit runtime support" [Resolved] org.eclipse.jdt.junit4.runtime (1.0.1.r321_v20060905) "Java Development Tools JUnit4 runtime support" [Resolved] org.eclipse.jdt.launching (3.2.1.r321_v20060731) "Java Development Tools Launching Support" [Active] org.eclipse.jdt.launching.macosx (3.1.100.v20060605) "Mac OS X Launcher" [Active] org.eclipse.jdt.source (3.2.1.r321_v20060905-R4CM1Znkvre9wC-) "Eclipse Java Development Tools SDK" [Resolved] org.eclipse.jdt.source.macosx.carbon.ppc (3.2.1.r321_v20060905-R4CM1Znkvre9wC-) "Eclipse Java Development Tools SDK" [Resolved] org.eclipse.jdt.ui (3.2.1.r321_v20060907) "Java Development Tools UI" [Active] org.eclipse.jface (3.2.1.M20060908-1000) "JFace" [Resolved] org.eclipse.jface.databinding (1.0.0.I20060605-1400) "JFace Data Binding" [Resolved] org.eclipse.jface.text (3.2.1.r321_v20060810) "JFace Text" [Resolved] org.eclipse.ltk.core.refactoring (3.2.1.r321_v20060823) "Refactoring Core" [Active] org.eclipse.ltk.ui.refactoring (3.2.1.r321_v20060726) "Refactoring UI" [Active] org.eclipse.osgi.services (3.1.100.v20060601) "OSGi Release 3 Services" [Resolved] org.eclipse.osgi.util (3.1.100.v20060601) "OSGi R3 Utility Classes" [Resolved] org.eclipse.pde (3.2.1.v20060810-0800) "Eclipse Plug-in Development Environment" [Resolved] org.eclipse.pde.build (3.2.1.r321_v20060823) "Plug-in Development Environment Build Support" [Resolved] org.eclipse.pde.core (3.2.1.v20060915-0800) "Plug-in Development Core" [Resolved] org.eclipse.pde.doc.user (3.2.1.v20060816-0800) "Eclipse Plug-in Development User Guide" [Resolved] org.eclipse.pde.junit.runtime (3.2.0.v20060605) "PDE JUnit Plug-in Test" [Resolved] org.eclipse.pde.runtime (3.2.0.v20060605) "Plug-in Development Environment Runtime" [Resolved] org.eclipse.pde.source (3.2.1.r321_v20060823-6vYLLdQ3Nk8DrFG) "Eclipse Plug-in Development Environment Developer Resources" [Resolved] org.eclipse.pde.ui (3.2.1.v20060816-0800) "Plug-in Development UI" [Resolved] org.eclipse.platform (3.2.0.v20060601) "Eclipse Platform" [Resolved] org.eclipse.platform.doc.isv (3.2.1.r321_v2006030) "Eclipse Platform Plug-in Developer Guide" [Resolved] org.eclipse.platform.doc.user (3.2.1.R32x_v200608101155) "Eclipse Workbench User Guide" [Resolved] org.eclipse.platform.source (3.2.1.r321_v20060921-b_XVA-INSQSyMtx) "Eclipse Platform Plug-in Developer Resources" [Resolved] org.eclipse.platform.source.macosx.carbon.ppc (3.2.1.r321_v20060921-b_XVA-INSQSyMtx) "Eclipse Platform Plug-in Developer Resources" [Resolved] org.eclipse.rcp (3.2.0.v20060605) "Eclipse RCP" [Resolved] org.eclipse.rcp.source (3.2.1.r321_v20060801-2ekW2BxmcpPUOoq) "Eclipse RCP Plug-in Developer Resources" [Resolved] org.eclipse.rcp.source.macosx.carbon.ppc (3.2.1.r321_v20060801-2ekW2BxmcpPUOoq) "Eclipse RCP Plug-in Developer Resources" [Resolved] org.eclipse.sdk (3.2.1.r321_v20060705) "Eclipse Project SDK" [Resolved] org.eclipse.search (3.2.1.r321_v20060726) "Search Support" [Resolved] org.eclipse.swt (3.2.1.v3235e) "Standard Widget Toolkit" [Resolved] org.eclipse.swt.carbon.macosx (3.2.1.v3235) "Standard Widget Toolkit for Mac OS X (Carbon)" [Resolved] org.eclipse.team.core (3.2.1.M20060711) "Team Support Core" [Active] org.eclipse.team.cvs.core (3.2.1.M200608161750) "CVS Team Provider Core" [Active] org.eclipse.team.cvs.ssh (3.2.0.I200606011710) "CVS SSH Core" [Resolved] org.eclipse.team.cvs.ssh2 (3.2.0.I200606051140) "CVS SSH2" [Active] org.eclipse.team.cvs.ui (3.2.1.M20060831) "CVS Team Provider UI" [Active] org.eclipse.team.ui (3.2.1.M200608151725) "Team Support UI" [Active] org.eclipse.text (3.2.0.v20060605-1400) "Text" [Resolved] org.eclipse.tomcat (4.1.130.v20060601) "Tomcat Wrapper" [Resolved] org.eclipse.ui (3.2.1.M20060913-0800) "Eclipse UI" [Active] org.eclipse.ui.browser (3.2.0.v20060602) "Browser Support" [Active] org.eclipse.ui.carbon (3.2.0.I20060605-1400) "Eclipse UI MacOS X Enhancements" [Resolved] org.eclipse.ui.cheatsheets (3.2.1.R321_v20060720) "Cheat Sheets" [Resolved] org.eclipse.ui.console (3.1.100.v20060605) "Console" [Active] org.eclipse.ui.editors (3.2.1.r321_v20060721) "Default Text Editor" [Active] org.eclipse.ui.externaltools (3.1.101.r321_v20060802) "External Tools" [Active] org.eclipse.ui.forms (3.2.0.v20060602) "Eclipse Forms" [Active] org.eclipse.ui.ide (3.2.1.M20060915-1030) "Eclipse IDE UI" [Active] org.eclipse.ui.intro (3.2.1.R321_v20060810) "Welcome Framework" [Resolved] org.eclipse.ui.intro.universal (3.2.1.R321_v20060905) "Universal Welcome" [Resolved] org.eclipse.ui.navigator (3.2.1.M20060913-0800) "Common Navigator View" [Resolved] org.eclipse.ui.navigator.resources (3.2.1.M20060906-0800b) "Navigator Workbench Components" [Resolved] org.eclipse.ui.presentations.r21 (3.2.0.I20060605-1400) "R21 Presentation Plug-in" [Resolved] org.eclipse.ui.views (3.2.1.M20060906-0800) "Views" [Active] org.eclipse.ui.views.properties.tabbed (3.2.1.M20060830-0800) "Tabbed Properties View" [Resolved] org.eclipse.ui.workbench (3.2.1.M20060906-0800) "Workbench" [Active] org.eclipse.ui.workbench.compatibility (3.2.0.I20060605-1400) "Workbench Compatibility" [Resolved] org.eclipse.ui.workbench.texteditor (3.2.0.v20060605-1400) "Text Editor Framework" [Active] org.eclipse.update.configurator (3.2.1.v20092006) "Install/Update Configurator" [Active] org.eclipse.update.core (3.2.1.v20092006) "Install/Update Core" [Active] org.eclipse.update.scheduler (3.2.1.v20092006) "Automatic Updates Scheduler" [Active] org.eclipse.update.ui (3.2.1.v20092006) "Install/Update UI" [Resolved] org.junit (3.8.1) "JUnit Testing Framework" [Resolved] org.junit4 (4.1.0.1) "JUnit Testing Framework Version 4" [Resolved] sf.eclipse.javacc (1.5.5) "JavaCC Plug-in" [Active] system.bundle (3.2.1.R32x_v20060919) "OSGi System Bundle" [Active]
resolved fixed
fe99e6b
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2008-03-21T01:43:30Z"
"2006-11-08T12:46:40Z"
weaver/src/org/aspectj/weaver/ResolvedType.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the 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.List; import java.util.Map; import java.util.Set; import org.aspectj.bridge.IMessage; import org.aspectj.bridge.ISourceLocation; import org.aspectj.bridge.Message; import org.aspectj.bridge.MessageUtil; import org.aspectj.util.FuzzyBoolean; import org.aspectj.weaver.patterns.Declare; import org.aspectj.weaver.patterns.PerClause; public abstract class ResolvedType extends UnresolvedType implements AnnotatedElement { public static final ResolvedType[] EMPTY_RESOLVED_TYPE_ARRAY = new ResolvedType[0]; public static final String PARAMETERIZED_TYPE_IDENTIFIER = "P"; // Set 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; protected ResolvedType(String signature, World world) { super(signature); this.world = world; } protected ResolvedType(String signature, String signatureErasure, World world) { super(signature,signatureErasure); this.world = world; } // ---- things that don't require a world /** * Returns an iterator through ResolvedType objects representing all the direct * supertypes of this type. That is, through the superclass, if any, and * all declared interfaces. */ public final Iterator getDirectSupertypes() { Iterator ifacesIterator = Iterators.array(getDeclaredInterfaces()); ResolvedType superclass = getSuperclass(); if (superclass == null) { return ifacesIterator; } else { return Iterators.snoc(ifacesIterator, superclass); } } public abstract ResolvedMember[] getDeclaredFields(); public abstract ResolvedMember[] getDeclaredMethods(); public abstract ResolvedType[] getDeclaredInterfaces(); public abstract ResolvedMember[] getDeclaredPointcuts(); /** * Returns a ResolvedType object representing the superclass of this type, or null. * If this represents a java.lang.Object, a primitive type, or void, this * method returns null. */ public abstract ResolvedType getSuperclass(); /** * Returns the modifiers for this type. * <p/> * See {@link Class#getModifiers()} for a description * of the weirdness of this methods on primitives and arrays. * * @param world the {@link World} in which the lookup is made. * @return an int representing the modifiers for this type * @see java.lang.reflect.Modifier */ public abstract int getModifiers(); // return true if this resolved type couldn't be found (but we know it's name maybe) public boolean isMissing() { return false; } // FIXME asc I wonder if in some circumstances MissingWithKnownSignature should not be considered // 'really' missing as some code can continue based solely on the signature public static boolean isMissing (UnresolvedType unresolved) { if (unresolved instanceof ResolvedType) { ResolvedType resolved = (ResolvedType)unresolved; return resolved.isMissing(); } else return (unresolved == MISSING); } public ResolvedType[] getAnnotationTypes() { return EMPTY_RESOLVED_TYPE_ARRAY; } public AnnotationX 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. static Set validBoxing = new HashSet(); static { validBoxing.add("Ljava/lang/Byte;B"); validBoxing.add("Ljava/lang/Character;C"); validBoxing.add("Ljava/lang/Double;D"); validBoxing.add("Ljava/lang/Float;F"); validBoxing.add("Ljava/lang/Integer;I"); validBoxing.add("Ljava/lang/Long;J"); validBoxing.add("Ljava/lang/Short;S"); validBoxing.add("Ljava/lang/Boolean;Z"); validBoxing.add("BLjava/lang/Byte;"); validBoxing.add("CLjava/lang/Character;"); validBoxing.add("DLjava/lang/Double;"); validBoxing.add("FLjava/lang/Float;"); validBoxing.add("ILjava/lang/Integer;"); validBoxing.add("JLjava/lang/Long;"); validBoxing.add("SLjava/lang/Short;"); validBoxing.add("ZLjava/lang/Boolean;"); } // utilities public ResolvedType getResolvedComponentType() { return null; } public World getWorld() { return world; } // ---- things from object public final boolean equals(Object other) { if (other instanceof ResolvedType) { return this == other; } else { return super.equals(other); } } // ---- difficult things /** * returns an iterator through all of the fields of this type, in order * for checking from JVM spec 2ed 5.4.3.2. This means that the order is * <p/> * <ul><li> fields from current class </li> * <li> recur into direct superinterfaces </li> * <li> recur into superclass </li> * </ul> * <p/> * We keep a hashSet of interfaces that we've visited so we don't spiral * out into 2^n land. */ public Iterator getFields() { final Iterators.Filter dupFilter = Iterators.dupFilter(); Iterators.Getter typeGetter = new Iterators.Getter() { public Iterator get(Object o) { return dupFilter.filter( ((ResolvedType)o).getDirectSupertypes()); } }; Iterators.Getter fieldGetter = new Iterators.Getter() { public Iterator get(Object o) { return Iterators.array(((ResolvedType)o).getDeclaredFields()); } }; return Iterators.mapOver( Iterators.recur(this, typeGetter), fieldGetter); } /** * returns an iterator through all of the methods of this type, in order * for checking from JVM spec 2ed 5.4.3.3. This means that the order is * <p/> * <ul><li> methods from current class </li> * <li> recur into superclass, all the way up, not touching interfaces </li> * <li> recur into all superinterfaces, in some unspecified order </li> * </ul> * <p/> * We keep a hashSet of interfaces that we've visited so we don't spiral * out into 2^n land. * NOTE: Take a look at the javadoc on getMethodsWithoutIterator() to see if * you are sensitive to a quirk in getMethods() */ public Iterator getMethods() { final Iterators.Filter dupFilter = Iterators.dupFilter(); Iterators.Getter ifaceGetter = new Iterators.Getter() { public Iterator get(Object o) { return dupFilter.filter( Iterators.array(((ResolvedType)o).getDeclaredInterfaces()) ); } }; Iterators.Getter methodGetter = new Iterators.Getter() { public Iterator get(Object o) { return Iterators.array(((ResolvedType)o).getDeclaredMethods()); } }; return Iterators.mapOver( Iterators.append( new Iterator() { ResolvedType curr = ResolvedType.this; public boolean hasNext() { return curr != null; } public Object next() { ResolvedType ret = curr; curr = curr.getSuperclass(); return ret; } public void remove() { throw new UnsupportedOperationException(); } }, Iterators.recur(this, ifaceGetter)), methodGetter); } /** * Return a list of methods, first those declared on this class, then those declared on the superclass (recurse) and then those declared * on the superinterfaces. The getMethods() call above doesn't quite work the same as it will (through the iterator) return methods * declared on *this* class twice, once at the start and once at the end - I couldn't debug that problem, so created this alternative. */ public List getMethodsWithoutIterator(boolean includeITDs, boolean allowMissing) { List methods = new ArrayList(); Set knowninterfaces = new HashSet(); addAndRecurse(knowninterfaces,methods,this,includeITDs,allowMissing); return methods; } private void addAndRecurse(Set knowninterfaces,List collector, ResolvedType rtx, boolean includeITDs, boolean allowMissing) { collector.addAll(Arrays.asList(rtx.getDeclaredMethods())); // Add the methods declared on this type // now add all the inter-typed members too if (includeITDs && rtx.interTypeMungers != null) { for (Iterator i = interTypeMungers.iterator(); i.hasNext();) { ConcreteTypeMunger tm = (ConcreteTypeMunger) i.next(); ResolvedMember rm = tm.getSignature(); if (rm != null) { // new parent type munger can have null signature... collector.add(tm.getSignature()); } } } if (!rtx.equals(ResolvedType.OBJECT)) { ResolvedType superType = rtx.getSuperclass(); if (superType != null && !superType.isMissing()) { addAndRecurse(knowninterfaces,collector,superType,includeITDs,allowMissing); // Recurse if we aren't at the top } } ResolvedType[] interfaces = rtx.getDeclaredInterfaces(); // Go through the interfaces on the way back down for (int i = 0; i < interfaces.length; i++) { ResolvedType iface = interfaces[i]; // we need to know if it is an interface from Parent kind munger // as those are used for @AJ ITD and we precisely want to skip those boolean shouldSkip = false; for (int j = 0; j < rtx.interTypeMungers.size(); j++) { ConcreteTypeMunger munger = (ConcreteTypeMunger) rtx.interTypeMungers.get(j); if (munger.getMunger()!=null && munger.getMunger().getKind() == ResolvedTypeMunger.Parent && ((NewParentTypeMunger)munger.getMunger()).getNewParent().equals(iface) // pr171953 ) { shouldSkip = true; break; } } if (!shouldSkip && !knowninterfaces.contains(iface)) { // Dont do interfaces more than once knowninterfaces.add(iface); if (allowMissing && iface.isMissing()) { if (iface instanceof MissingResolvedTypeWithKnownSignature) { ((MissingResolvedTypeWithKnownSignature)iface).raiseWarningOnMissingInterfaceWhilstFindingMethods(); } } else { addAndRecurse(knowninterfaces,collector,iface,includeITDs,allowMissing); } } } } public ResolvedType[] getResolvedTypeParameters() { if (resolvedTypeParams == null) { resolvedTypeParams = world.resolve(typeParameters); } return resolvedTypeParams; } /** * described in JVM spec 2ed 5.4.3.2 */ public ResolvedMember lookupField(Member m) { return lookupMember(m, getFields()); } /** * described in JVM spec 2ed 5.4.3.3. * Doesnt check ITDs. */ public ResolvedMember lookupMethod(Member m) { return lookupMember(m, getMethods()); } public ResolvedMember lookupMethodInITDs(Member m) { if (interTypeMungers != null) { for (Iterator i = interTypeMungers.iterator(); i.hasNext();) { ConcreteTypeMunger tm = (ConcreteTypeMunger) i.next(); if (matches(tm.getSignature(), m)) { return tm.getSignature(); } } } return null; } /** * return null if not found */ private ResolvedMember lookupMember(Member m, Iterator i) { while (i.hasNext()) { ResolvedMember f = (ResolvedMember) i.next(); if (matches(f, m)) return f; if (f.hasBackingGenericMember() && m.getName().equals(f.getName())) { // might be worth checking the method behind the parameterized method (see pr137496) if (matches(f.getBackingGenericMember(),m)) return f; } } return null; //ResolvedMember.Missing; //throw new BCException("can't find " + m); } /** * return null if not found */ private ResolvedMember lookupMember(Member m, ResolvedMember[] a) { for (int i = 0; i < a.length; i++) { ResolvedMember f = a[i]; if (matches(f, m)) return f; } return null; } /** * Looks for the first member in the hierarchy matching aMember. This method * differs from lookupMember(Member) in that it takes into account parameters * which are type variables - which clearly an unresolved Member cannot do since * it does not know anything about type variables. */ public ResolvedMember lookupResolvedMember(ResolvedMember aMember,boolean allowMissing) { Iterator toSearch = null; ResolvedMember found = null; if ((aMember.getKind() == Member.METHOD) || (aMember.getKind() == Member.CONSTRUCTOR)) { toSearch = getMethodsWithoutIterator(true,allowMissing).iterator(); } else { if (aMember.getKind() != Member.FIELD) throw new IllegalStateException("I didn't know you would look for members of kind " + aMember.getKind()); toSearch = getFields(); } while(toSearch.hasNext()) { ResolvedMemberImpl candidate = (ResolvedMemberImpl) toSearch.next(); if (candidate.matches(aMember)) { found = candidate; break; } } return found; } public static boolean matches(Member m1, Member m2) { if (m1 == null) return m2 == null; if (m2 == null) return false; // Check the names boolean equalNames = m1.getName().equals(m2.getName()); if (!equalNames) return false; // Check the signatures boolean equalSignatures = m1.getSignature().equals(m2.getSignature()); if (equalSignatures) return true; // If they aren't the same, we need to allow for covariance ... where one sig might be ()LCar; and // the subsig might be ()LFastCar; - where FastCar is a subclass of Car boolean equalCovariantSignatures = m1.getParameterSignature().equals(m2.getParameterSignature()); if (equalCovariantSignatures) return true; return false; } public static boolean conflictingSignature(Member m1, Member m2) { if (m1 == null || m2 == null) return false; if (!m1.getName().equals(m2.getName())) { return false; } if (m1.getKind() != m2.getKind()) { return false; } if (m1.getKind() == Member.FIELD) { return m1.getDeclaringType().equals(m2.getDeclaringType()); } else if (m1.getKind() == Member.POINTCUT) { return true; } UnresolvedType[] p1 = m1.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 getPointcuts() { final Iterators.Filter dupFilter = Iterators.dupFilter(); // same order as fields Iterators.Getter typeGetter = new Iterators.Getter() { public Iterator get(Object o) { return dupFilter.filter( ((ResolvedType)o).getDirectSupertypes()); } }; Iterators.Getter pointcutGetter = new Iterators.Getter() { public Iterator get(Object o) { //System.err.println("getting for " + o); return Iterators.array(((ResolvedType)o).getDeclaredPointcuts()); } }; return Iterators.mapOver( Iterators.recur(this, typeGetter), pointcutGetter); } public ResolvedPointcutDefinition findPointcut(String name) { //System.err.println("looking for pointcuts " + this); for (Iterator i = getPointcuts(); i.hasNext(); ) { ResolvedPointcutDefinition f = (ResolvedPointcutDefinition) i.next(); //System.err.println(f); if (name.equals(f.getName())) { return f; } } // pr120521 if (!getOutermostType().equals(this)) { ResolvedType outerType = getOutermostType().resolve(world); ResolvedPointcutDefinition rpd = outerType.findPointcut(name); return rpd; } return null; // should we throw an exception here? } // all about collecting CrosscuttingMembers //??? collecting data-structure, shouldn't really be a field public CrosscuttingMembers crosscuttingMembers; public CrosscuttingMembers collectCrosscuttingMembers(boolean shouldConcretizeIfNeeded) { crosscuttingMembers = new CrosscuttingMembers(this,shouldConcretizeIfNeeded); crosscuttingMembers.setPerClause(getPerClause()); crosscuttingMembers.addShadowMungers(collectShadowMungers()); // 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 Collection collectTypeMungers() { if (! this.isAspect() ) return Collections.EMPTY_LIST; ArrayList ret = new ArrayList(); //if (this.isAbstract()) { // for (Iterator i = getDeclares().iterator(); i.hasNext();) { // Declare dec = (Declare) i.next(); // if (!dec.isAdviceLike()) ret.add(dec); // } // // if (!includeAdviceLike) return ret; if (!this.isAbstract()) { final Iterators.Filter dupFilter = Iterators.dupFilter(); Iterators.Getter typeGetter = new Iterators.Getter() { public Iterator get(Object o) { return dupFilter.filter( ((ResolvedType)o).getDirectSupertypes()); } }; Iterator typeIterator = Iterators.recur(this, typeGetter); while (typeIterator.hasNext()) { ResolvedType ty = (ResolvedType) typeIterator.next(); for (Iterator i = ty.getTypeMungers().iterator(); i.hasNext();) { ConcreteTypeMunger dec = (ConcreteTypeMunger) i.next(); ret.add(dec); } } } return ret; } public final Collection collectDeclares(boolean includeAdviceLike) { if (! this.isAspect() ) return Collections.EMPTY_LIST; ArrayList ret = new ArrayList(); //if (this.isAbstract()) { // for (Iterator i = getDeclares().iterator(); i.hasNext();) { // Declare dec = (Declare) i.next(); // if (!dec.isAdviceLike()) ret.add(dec); // } // // if (!includeAdviceLike) return ret; if (!this.isAbstract()) { //ret.addAll(getDeclares()); final Iterators.Filter dupFilter = Iterators.dupFilter(); Iterators.Getter typeGetter = new Iterators.Getter() { public Iterator get(Object o) { return dupFilter.filter( ((ResolvedType)o).getDirectSupertypes()); } }; Iterator typeIterator = Iterators.recur(this, typeGetter); while (typeIterator.hasNext()) { ResolvedType ty = (ResolvedType) typeIterator.next(); //System.out.println("super: " + ty + ", " + ); for (Iterator i = ty.getDeclares().iterator(); i.hasNext();) { Declare dec = (Declare) i.next(); if (dec.isAdviceLike()) { if (includeAdviceLike) ret.add(dec); } else { ret.add(dec); } } } } return ret; } private final Collection collectShadowMungers() { if (! this.isAspect() || this.isAbstract() || this.doesNotExposeShadowMungers()) return Collections.EMPTY_LIST; ArrayList acc = new ArrayList(); final Iterators.Filter dupFilter = Iterators.dupFilter(); Iterators.Getter typeGetter = new Iterators.Getter() { public Iterator get(Object o) { return dupFilter.filter( ((ResolvedType)o).getDirectSupertypes()); } }; Iterator typeIterator = Iterators.recur(this, typeGetter); while (typeIterator.hasNext()) { ResolvedType ty = (ResolvedType) typeIterator.next(); acc.addAll(ty.getDeclaredShadowMungers()); } return acc; } protected boolean doesNotExposeShadowMungers() { return false; } public PerClause getPerClause() { return null; } protected Collection getDeclares() { return Collections.EMPTY_LIST; } protected Collection getTypeMungers() { return Collections.EMPTY_LIST; } protected Collection getPrivilegedAccesses() { return Collections.EMPTY_LIST; } // ---- useful things public final boolean isInterface() { return Modifier.isInterface(getModifiers()); } public final boolean isAbstract() { return Modifier.isAbstract(getModifiers()); } public boolean isClass() { return false; } public boolean isAspect() { return false; } public boolean isAnnotationStyleAspect() { return false; } /** * Note: Only overridden by Name subtype. */ public boolean isEnum() { return false; } /** * Note: Only overridden by Name subtype. */ public boolean isAnnotation() { return false; } public boolean isAnonymous() { return false; } public boolean isNested() { return false; } /** * Note: Only overridden by Name subtype */ public void addAnnotation(AnnotationX annotationX) { throw new RuntimeException("ResolvedType.addAnnotation() should never be called"); } /** * Note: Only overridden by Name subtype */ public AnnotationX[] getAnnotations() { throw new RuntimeException("ResolvedType.getAnnotations() should never be called"); } /** * Note: Only overridden by ReferenceType subtype */ public boolean canAnnotationTargetType() { return false; } /** * Note: Only overridden by ReferenceType subtype */ public AnnotationTargetKind[] getAnnotationTargetKinds() { return null; } /** * Note: Only overridden by Name subtype. */ public boolean isAnnotationWithRuntimeRetention() { return false; } public boolean isSynthetic() { return signature.indexOf("$ajc") != -1; } public final boolean isFinal() { return Modifier.isFinal(getModifiers()); } protected Map /*Type variable name -> UnresolvedType*/ getMemberParameterizationMap() { if (!isParameterizedType()) return Collections.EMPTY_MAP; TypeVariable[] tvs = getGenericType().getTypeVariables(); Map parameterizationMap = new HashMap(); for (int i = 0; i < tvs.length; i++) { parameterizationMap.put(tvs[i].getName(), typeParameters[i]); } return parameterizationMap; } public Collection getDeclaredAdvice() { List l = new ArrayList(); ResolvedMember[] methods = getDeclaredMethods(); if (isParameterizedType()) methods = getGenericType().getDeclaredMethods(); Map typeVariableMap = getAjMemberParameterizationMap(); for (int i=0, len = methods.length; i < len; i++) { ShadowMunger munger = methods[i].getAssociatedShadowMunger(); if (munger != null) { if (ajMembersNeedParameterization()) { //munger.setPointcut(munger.getPointcut().parameterizeWith(typeVariableMap)); munger = munger.parameterizeWith(this,typeVariableMap); if (munger instanceof Advice) { Advice advice = (Advice) munger; // update to use the parameterized signature... UnresolvedType[] ptypes = methods[i].getGenericParameterTypes() ; UnresolvedType[] newPTypes = new UnresolvedType[ptypes.length]; for (int j = 0; j < ptypes.length; j++) { if (ptypes[j] instanceof TypeVariableReferenceType) { TypeVariableReferenceType tvrt = (TypeVariableReferenceType) ptypes[j]; if (typeVariableMap.containsKey(tvrt.getTypeVariable().getName())) { newPTypes[j] = (UnresolvedType) typeVariableMap.get(tvrt.getTypeVariable().getName()); } else { newPTypes[j] = ptypes[j]; } } else { newPTypes[j] = ptypes[j]; } } advice.setBindingParameterTypes(newPTypes); } } munger.setDeclaringType(this); l.add(munger); } } return l; } public Collection getDeclaredShadowMungers() { Collection c = getDeclaredAdvice(); return c; } // ---- only for testing! public ResolvedMember[] getDeclaredJavaFields() { return filterInJavaVisible(getDeclaredFields()); } public ResolvedMember[] getDeclaredJavaMethods() { return filterInJavaVisible(getDeclaredMethods()); } public ShadowMunger[] getDeclaredShadowMungersArray() { List l = (List) getDeclaredShadowMungers(); return (ShadowMunger[]) l.toArray(new ShadowMunger[l.size()]); } private ResolvedMember[] filterInJavaVisible(ResolvedMember[] ms) { List l = new ArrayList(); for (int i=0, len = ms.length; i < len; i++) { if (! ms[i].isAjSynthetic() && ms[i].getAssociatedShadowMunger() == null) { l.add(ms[i]); } } return (ResolvedMember[]) l.toArray(new ResolvedMember[l.size()]); } public abstract ISourceContext getSourceContext(); // ---- fields public static final ResolvedType[] NONE = new ResolvedType[0]; public static final Primitive BYTE = new Primitive("B", 1, 0); public static final Primitive CHAR = new Primitive("C", 1, 1); public static final Primitive DOUBLE = new Primitive("D", 2, 2); public static final Primitive FLOAT = new Primitive("F", 1, 3); public static final Primitive INT = new Primitive("I", 1, 4); public static final Primitive LONG = new Primitive("J", 2, 5); public static final Primitive SHORT = new Primitive("S", 1, 6); public static final Primitive VOID = new Primitive("V", 0, 8); public static final Primitive BOOLEAN = new Primitive("Z", 1, 7); public static final Missing MISSING = new Missing(); /** Reset the static state in the primitive types */ public static void resetPrimitives() { BYTE.world=null; CHAR.world=null; DOUBLE.world=null; FLOAT.world=null; INT.world=null; LONG.world=null; SHORT.world=null; VOID.world=null; BOOLEAN.world=null; } // ---- types public static ResolvedType makeArray(ResolvedType type, int dim) { if (dim == 0) return type; ResolvedType array = new ArrayReferenceType("[" + type.getSignature(),"["+type.getErasureSignature(),type.getWorld(),type); return makeArray(array,dim-1); } static class Array extends ResolvedType { ResolvedType componentType; // Sometimes the erasure is different, eg. [TT; and [Ljava/lang/Object; Array(String sig, String erasureSig,World world, ResolvedType componentType) { super(sig,erasureSig, world); this.componentType = componentType; } public final ResolvedMember[] getDeclaredFields() { return ResolvedMember.NONE; } public final ResolvedMember[] getDeclaredMethods() { // ??? should this return clone? Probably not... // If it ever does, here is the code: // ResolvedMember cloneMethod = // new ResolvedMember(Member.METHOD,this,Modifier.PUBLIC,UnresolvedType.OBJECT,"clone",new UnresolvedType[]{}); // return new ResolvedMember[]{cloneMethod}; return ResolvedMember.NONE; } public final ResolvedType[] getDeclaredInterfaces() { return new ResolvedType[] { world.getCoreType(CLONEABLE), world.getCoreType(SERIALIZABLE) }; } public final ResolvedMember[] getDeclaredPointcuts() { return ResolvedMember.NONE; } public boolean hasAnnotation(UnresolvedType ofType) { return false; } public final ResolvedType getSuperclass() { return world.getCoreType(OBJECT); } public final boolean isAssignableFrom(ResolvedType o) { if (! o.isArray()) return false; if (o.getComponentType().isPrimitiveType()) { return o.equals(this); } else { return getComponentType().resolve(world).isAssignableFrom(o.getComponentType().resolve(world)); } } public boolean isAssignableFrom(ResolvedType o, boolean allowMissing) { return isAssignableFrom(o); } public final boolean isCoerceableFrom(ResolvedType o) { if (o.equals(UnresolvedType.OBJECT) || o.equals(UnresolvedType.SERIALIZABLE) || o.equals(UnresolvedType.CLONEABLE)) { return true; } if (! o.isArray()) return false; if (o.getComponentType().isPrimitiveType()) { return o.equals(this); } else { return getComponentType().resolve(world).isCoerceableFrom(o.getComponentType().resolve(world)); } } public final int getModifiers() { int mask = Modifier.PUBLIC | Modifier.PRIVATE | Modifier.PROTECTED; return (componentType.getModifiers() & mask) | Modifier.FINAL; } public UnresolvedType getComponentType() { return componentType; } public ResolvedType getResolvedComponentType() { return componentType; } public ISourceContext getSourceContext() { return getResolvedComponentType().getSourceContext(); } } static class Primitive extends ResolvedType { private int size; private int index; Primitive(String signature, int size, int index) { super(signature, null); this.size = size; this.index = index; this.typeKind=TypeKind.PRIMITIVE; } public final int getSize() { return size; } public final int getModifiers() { return Modifier.PUBLIC | Modifier.FINAL; } public final boolean isPrimitiveType() { return true; } public boolean hasAnnotation(UnresolvedType ofType) { return false; } public final boolean isAssignableFrom(ResolvedType other) { if (!other.isPrimitiveType()) { if (!world.isInJava5Mode()) return false; return validBoxing.contains(this.getSignature()+other.getSignature()); } return assignTable[((Primitive)other).index][index]; } public final boolean isAssignableFrom(ResolvedType other, boolean allowMissing) { return isAssignableFrom(other); } public final boolean isCoerceableFrom(ResolvedType other) { if (this == other) return true; if (! other.isPrimitiveType()) return false; if (index > 6 || ((Primitive)other).index > 6) return false; return true; } public ResolvedType resolve(World world) { this.world = world; return super.resolve(world); } public final boolean needsNoConversionFrom(ResolvedType other) { if (! other.isPrimitiveType()) return false; return noConvertTable[((Primitive)other).index][index]; } private static final boolean[][] assignTable = {// to: B C D F I J S V Z from { true , true , true , true , true , true , true , false, false }, // B { false, true , true , true , true , true , false, false, false }, // C { false, false, true , false, false, false, false, false, false }, // D { false, false, true , true , false, false, false, false, false }, // F { false, false, true , true , true , true , false, false, false }, // I { false, false, true , true , false, true , false, false, false }, // J { false, false, true , true , true , true , true , false, false }, // S { false, false, false, false, false, false, false, true , false }, // V { false, false, false, false, false, false, false, false, true }, // Z }; private static final boolean[][] noConvertTable = {// to: B C D F I J S V Z from { true , true , false, false, true , false, true , false, false }, // B { false, true , false, false, true , false, false, false, false }, // C { false, false, true , false, false, false, false, false, false }, // D { false, false, false, true , false, false, false, false, false }, // F { false, false, false, false, true , false, false, false, false }, // I { false, false, false, false, false, true , false, false, false }, // J { false, false, false, false, true , false, true , false, false }, // S { false, false, false, false, false, false, false, true , false }, // V { false, false, false, false, false, false, false, false, true }, // Z }; // ---- public final ResolvedMember[] getDeclaredFields() { return ResolvedMember.NONE; } public final ResolvedMember[] getDeclaredMethods() { return ResolvedMember.NONE; } public final ResolvedType[] getDeclaredInterfaces() { return ResolvedType.NONE; } public final ResolvedMember[] getDeclaredPointcuts() { return ResolvedMember.NONE; } public final ResolvedType getSuperclass() { return null; } public ISourceContext getSourceContext() { return null; } } static class Missing extends ResolvedType { Missing() { super(MISSING_NAME, null); } // public final String toString() { // return "<missing>"; // } public final String getName() { return MISSING_NAME; } public final boolean isMissing() { return true; } public boolean hasAnnotation(UnresolvedType ofType) { return false; } public final ResolvedMember[] getDeclaredFields() { return ResolvedMember.NONE; } public final ResolvedMember[] getDeclaredMethods() { return ResolvedMember.NONE; } public final ResolvedType[] getDeclaredInterfaces() { return ResolvedType.NONE; } public final ResolvedMember[] getDeclaredPointcuts() { return ResolvedMember.NONE; } public final ResolvedType getSuperclass() { return null; } public final int getModifiers() { return 0; } public final boolean isAssignableFrom(ResolvedType other) { return false; } public final boolean isAssignableFrom(ResolvedType other, boolean allowMissing) { return false; } public final boolean isCoerceableFrom(ResolvedType other) { return false; } public boolean needsNoConversionFrom(ResolvedType other) { return false; } public ISourceContext getSourceContext() { return null; } } /** * Look up a member, takes into account any ITDs on this type. * return null if not found */ public ResolvedMember lookupMemberNoSupers(Member member) { ResolvedMember ret = lookupDirectlyDeclaredMemberNoSupers(member); if (ret == null && interTypeMungers != null) { for (Iterator i = interTypeMungers.iterator(); i.hasNext();) { ConcreteTypeMunger tm = (ConcreteTypeMunger) i.next(); if (matches(tm.getSignature(), member)) { return tm.getSignature(); } } } return ret; } public ResolvedMember lookupMemberWithSupersAndITDs(Member member) { ResolvedMember ret = lookupMemberNoSupers(member); if (ret != null) return ret; ResolvedType supert = getSuperclass(); 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 interTypeMungers = new ArrayList(0); public List getInterTypeMungers() { return interTypeMungers; } public List getInterTypeParentMungers() { List l = new ArrayList(); for (Iterator iter = interTypeMungers.iterator(); iter.hasNext();) { ConcreteTypeMunger element = (ConcreteTypeMunger) iter.next(); if (element.getMunger() instanceof NewParentTypeMunger) l.add(element); } return l; } /** * ??? This method is O(N*M) where N = number of methods and M is number of * inter-type declarations in my super */ public List getInterTypeMungersIncludingSupers() { ArrayList ret = new ArrayList(); collectInterTypeMungers(ret); return ret; } public List getInterTypeParentMungersIncludingSupers() { ArrayList ret = new ArrayList(); collectInterTypeParentMungers(ret); return ret; } private void collectInterTypeParentMungers(List collector) { for (Iterator iter = getDirectSupertypes(); iter.hasNext();) { ResolvedType superType = (ResolvedType) iter.next(); superType.collectInterTypeParentMungers(collector); } collector.addAll(getInterTypeParentMungers()); } protected void collectInterTypeMungers(List collector) { for (Iterator iter = getDirectSupertypes(); iter.hasNext();) { ResolvedType superType = (ResolvedType) iter.next(); superType.collectInterTypeMungers(collector); } outer: for (Iterator iter1 = collector.iterator(); iter1.hasNext();) { ConcreteTypeMunger superMunger = (ConcreteTypeMunger) iter1.next(); if ( superMunger.getSignature() == null) continue; if ( !superMunger.getSignature().isAbstract()) continue; for (Iterator iter = getInterTypeMungers().iterator(); iter.hasNext();) { ConcreteTypeMunger myMunger = (ConcreteTypeMunger) iter.next(); if (conflictingSignature(myMunger.getSignature(), superMunger.getSignature())) { iter1.remove(); continue outer; } } if (!superMunger.getSignature().isPublic()) continue; for (Iterator iter = getMethods(); iter.hasNext(); ) { ResolvedMember method = (ResolvedMember)iter.next(); if (conflictingSignature(method, superMunger.getSignature())) { iter1.remove(); continue outer; } } } collector.addAll(getInterTypeMungers()); } /** * Check: * 1) That we don't have any abstract type mungers unless this type is abstract. * 2) That an abstract ITDM on an interface is declared public. (Compiler limitation) (PR70794) */ public void checkInterTypeMungers() { if (isAbstract()) return; boolean itdProblem = false; for (Iterator iter = getInterTypeMungersIncludingSupers().iterator(); iter.hasNext();) { ConcreteTypeMunger munger = (ConcreteTypeMunger) iter.next(); itdProblem = checkAbstractDeclaration(munger) || itdProblem; // Rule 2 } if (itdProblem) return; // If the rules above are broken, return right now for (Iterator iter = getInterTypeMungersIncludingSupers().iterator(); iter.hasNext();) { ConcreteTypeMunger munger = (ConcreteTypeMunger) iter.next(); if (munger.getSignature() != null && munger.getSignature().isAbstract()) { // Rule 1 if (munger.getMunger().getKind() == ResolvedTypeMunger.MethodDelegate) { ;//ignore for @AJ ITD as munger.getSignature() is the interface method hence abstract } else { world.getMessageHandler().handleMessage( new Message("must implement abstract inter-type declaration: " + munger.getSignature(), "", IMessage.ERROR, getSourceLocation(), null, new ISourceLocation[] { getMungerLocation(munger) })); } } } } /** * See PR70794. This method checks that if an abstract inter-type method declaration is made on * an interface then it must also be public. * This is a compiler limitation that could be made to work in the future (if someone * provides a worthwhile usecase) * * @return indicates if the munger failed the check */ private boolean checkAbstractDeclaration(ConcreteTypeMunger munger) { if (munger.getMunger()!=null && (munger.getMunger() instanceof NewMethodTypeMunger)) { ResolvedMember itdMember = munger.getSignature(); ResolvedType onType = itdMember.getDeclaringType().resolve(world); if (onType.isInterface() && itdMember.isAbstract() && !itdMember.isPublic()) { world.getMessageHandler().handleMessage( new Message(WeaverMessages.format(WeaverMessages.ITD_ABSTRACT_MUST_BE_PUBLIC_ON_INTERFACE,munger.getSignature(),onType),"", Message.ERROR,getSourceLocation(),null, new ISourceLocation[]{getMungerLocation(munger)}) ); return true; } } return false; } /** * Get a source location for the munger. * Until intertype mungers remember where they came from, the source location * for the munger itself is null. In these cases use the * source location for the aspect containing the ITD. */ private ISourceLocation getMungerLocation(ConcreteTypeMunger munger) { ISourceLocation sloc = munger.getSourceLocation(); if (sloc == null) { sloc = munger.getAspectType().getSourceLocation(); } return sloc; } /** * Returns a ResolvedType object representing the declaring type of this type, or * null if this type does not represent a non-package-level-type. * <p/> * <strong>Warning</strong>: This is guaranteed to work for all member types. * For anonymous/local types, the only guarantee is given in JLS 13.1, where * it guarantees that if you call getDeclaringType() repeatedly, you will eventually * get the top-level class, but it does not say anything about classes in between. * * @return the declaring UnresolvedType object, or null. */ public ResolvedType getDeclaringType() { if (isArray()) return null; String name = getName(); int lastDollar = name.lastIndexOf('$'); while (lastDollar >0) { // allow for classes starting '$' (pr120474) ResolvedType ret = world.resolve(UnresolvedType.forName(name.substring(0, lastDollar)), true); if (!ResolvedType.isMissing(ret)) return ret; lastDollar = name.lastIndexOf('$', lastDollar-1); } return null; } public static boolean isVisible(int modifiers, ResolvedType targetType, ResolvedType fromType) { //System.err.println("mod: " + modifiers + ", " + targetType + " and " + fromType); if (Modifier.isPublic(modifiers)) { return true; } else if (Modifier.isPrivate(modifiers)) { return targetType.getOutermostType().equals(fromType.getOutermostType()); } else if (Modifier.isProtected(modifiers)) { return samePackage(targetType, fromType) || targetType.isAssignableFrom(fromType); } else { // package-visible return samePackage(targetType, fromType); } } public static boolean hasBridgeModifier(int modifiers) { return (modifiers & Constants.ACC_BRIDGE)!=0; } private static boolean samePackage( ResolvedType targetType, ResolvedType fromType) { String p1 = targetType.getPackageName(); String p2 = fromType.getPackageName(); if (p1 == null) return p2 == null; if (p2 == null) return false; return p1.equals(p2); } /** * Checks if the generic type for 'this' and the generic type for 'other' are the same - * it can be passed raw or parameterized versions and will just compare the underlying * generic type. */ private boolean genericTypeEquals(ResolvedType other) { ResolvedType rt = other; if (rt.isParameterizedType() || rt.isRawType()) rt.getGenericType(); if (( (isParameterizedType() || isRawType()) && getGenericType().equals(rt)) || (this.equals(other))) return true; return false; } /** * Look up the actual occurence of a particular type in the hierarchy for * 'this' type. The input is going to be a generic type, and the caller * wants to know if it was used in its RAW or a PARAMETERIZED form in this * hierarchy. * * returns null if it can't be found. */ public ResolvedType discoverActualOccurrenceOfTypeInHierarchy(ResolvedType lookingFor) { if (!lookingFor.isGenericType()) throw new BCException("assertion failed: method should only be called with generic type, but "+lookingFor+" is "+lookingFor.typeKind); if (this.equals(ResolvedType.OBJECT)) return null; if (genericTypeEquals(lookingFor)) return this; ResolvedType superT = getSuperclass(); if (superT.genericTypeEquals(lookingFor)) return superT; ResolvedType[] superIs = getDeclaredInterfaces(); for (int i = 0; i < superIs.length; i++) { ResolvedType superI = superIs[i]; if (superI.genericTypeEquals(lookingFor)) return superI; ResolvedType checkTheSuperI = superI.discoverActualOccurrenceOfTypeInHierarchy(lookingFor); if (checkTheSuperI!=null) return checkTheSuperI; } return superT.discoverActualOccurrenceOfTypeInHierarchy(lookingFor); } /** * Called for all type mungers but only does something if they share type variables * with a generic type which they target. When this happens this routine will check * for the target type in the target hierarchy and 'bind' any type parameters as * appropriate. For example, for the ITD "List<T> I<T>.x" against a type like this: * "class A implements I<String>" this routine will return a parameterized form of * the ITD "List<String> I.x" */ public ConcreteTypeMunger fillInAnyTypeParameters(ConcreteTypeMunger munger) { boolean debug = false; ResolvedMember member = munger.getSignature(); if (munger.isTargetTypeParameterized()) { if (debug) System.err.println("Processing attempted parameterization of "+munger+" targetting type "+this); if (debug) System.err.println(" This type is "+this+" ("+typeKind+")"); // need to tailor this munger instance for the particular target... if (debug) System.err.println(" Signature that needs parameterizing: "+member); // Retrieve the generic type ResolvedType onType = world.resolve(member.getDeclaringType()).getGenericType(); member.resolve(world); // Ensure all parts of the member are resolved if (debug) System.err.println(" Actual target ontype: "+onType+" ("+onType.typeKind+")"); // quickly find the targettype in the type hierarchy for this type (it will be either RAW or PARAMETERIZED) ResolvedType actualTarget = discoverActualOccurrenceOfTypeInHierarchy(onType); if (actualTarget==null) throw new BCException("assertion failed: asked "+this+" for occurrence of "+onType+" in its hierarchy??"); // only bind the tvars if its a parameterized type or the raw type (in which case they collapse to bounds) - don't do it for generic types ;) if (!actualTarget.isGenericType()) { if (debug) System.err.println("Occurrence in "+this+" is actually "+actualTarget+" ("+actualTarget.typeKind+")"); // parameterize the signature // ResolvedMember newOne = member.parameterizedWith(actualTarget.getTypeParameters(),onType,actualTarget.isParameterizedType()); } //if (!actualTarget.isRawType()) munger = munger.parameterizedFor(actualTarget); if (debug) System.err.println("New sig: "+munger.getSignature()); if (debug) System.err.println("====================================="); } return munger; } public void addInterTypeMunger(ConcreteTypeMunger munger) { ResolvedMember sig = munger.getSignature(); if (sig == null || munger.getMunger() == null || munger.getMunger().getKind() == ResolvedTypeMunger.PrivilegedAccess) { interTypeMungers.add(munger); return; } ConcreteTypeMunger originalMunger = munger; // we will use the 'parameterized' ITD for all the comparisons but we say the original // one passed in actually matched as it will be added to the intertype member finder // for the target type. It is possible we only want to do this if a generic type // is discovered and the tvar is collapsed to a bound? munger = fillInAnyTypeParameters(munger); sig = munger.getSignature(); // possibly changed when type parms filled in //System.err.println("add: " + munger + " to " + this.getClassName() + " with " + interTypeMungers); if (sig.getKind() == Member.METHOD) { if (!compareToExistingMembers(munger, getMethodsWithoutIterator(false,true) /*getMethods()*/)) return; if (this.isInterface()) { if (!compareToExistingMembers(munger, Arrays.asList(world.getCoreType(OBJECT).getDeclaredMethods()).iterator())) return; } } else if (sig.getKind() == Member.FIELD) { if (!compareToExistingMembers(munger, Arrays.asList(getDeclaredFields()).iterator())) return; } else { if (!compareToExistingMembers(munger, Arrays.asList(getDeclaredMethods()).iterator())) return; } // now compare to existingMungers for (Iterator i = interTypeMungers.iterator(); i.hasNext(); ) { ConcreteTypeMunger existingMunger = (ConcreteTypeMunger)i.next(); if (conflictingSignature(existingMunger.getSignature(), munger.getSignature())) { //System.err.println("match " + munger + " with " + existingMunger); if (isVisible(munger.getSignature().getModifiers(), munger.getAspectType(), existingMunger.getAspectType())) { //System.err.println(" is visible"); int c = compareMemberPrecedence(sig, existingMunger.getSignature()); if (c == 0) { c = getWorld().compareByPrecedenceAndHierarchy(munger.getAspectType(), existingMunger.getAspectType()); } //System.err.println(" compare: " + c); if (c < 0) { // the existing munger dominates the new munger checkLegalOverride(munger.getSignature(), existingMunger.getSignature()); return; } else if (c > 0) { // the new munger dominates the existing one checkLegalOverride(existingMunger.getSignature(), munger.getSignature()); i.remove(); break; } else { interTypeConflictError(munger, existingMunger); interTypeConflictError(existingMunger, munger); return; } } } } //System.err.println("adding: " + munger + " to " + this); // we are adding the parameterized form of the ITD to the list of // mungers. Within it, the munger knows the original declared // signature for the ITD so it can be retrieved. interTypeMungers.add(munger); } private boolean compareToExistingMembers(ConcreteTypeMunger munger, List existingMembersList) { return compareToExistingMembers(munger,existingMembersList.iterator()); } //??? returning too soon private boolean compareToExistingMembers(ConcreteTypeMunger munger, Iterator existingMembers) { ResolvedMember sig = munger.getSignature(); 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 // } while (existingMembers.hasNext()) { ResolvedMember existingMember = (ResolvedMember)existingMembers.next(); // don't worry about clashing with bridge methods if (existingMember.isBridgeMethod()) continue; //System.err.println("Comparing munger: "+sig+" with member "+existingMember); if (conflictingSignature(existingMember, munger.getSignature())) { //System.err.println("conflict: existingMember=" + existingMember + " typeMunger=" + munger); //System.err.println(munger.getSourceLocation() + ", " + munger.getSignature() + ", " + munger.getSignature().getSourceLocation()); if (isVisible(existingMember.getModifiers(), this, munger.getAspectType())) { int c = compareMemberPrecedence(sig, existingMember); //System.err.println(" c: " + c); if (c < 0) { // existingMember dominates munger checkLegalOverride(munger.getSignature(), existingMember); return false; } else if (c > 0) { // munger dominates existingMember checkLegalOverride(existingMember, munger.getSignature()); //interTypeMungers.add(munger); //??? might need list of these overridden abstracts continue; } else { // bridge methods can differ solely in return type. // FIXME this whole method seems very hokey - unaware of covariance/varargs/bridging - it // could do with a rewrite ! boolean sameReturnTypes = (existingMember.getReturnType().equals(sig.getReturnType())); if (sameReturnTypes) { // 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 mungersAffectingThisType = wsi.getTypeMungers(declaringRt); if (mungersAffectingThisType!=null) { for (Iterator iterator = mungersAffectingThisType.iterator(); iterator.hasNext() && !isDuplicateOfPreviousITD;) { ConcreteTypeMunger ctMunger = (ConcreteTypeMunger) 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(munger.getAspectType())) { isDuplicateOfPreviousITD=true; } } } } if (!isDuplicateOfPreviousITD) { getWorld().getMessageHandler().handleMessage( MessageUtil.error(WeaverMessages.format(WeaverMessages.ITD_MEMBER_CONFLICT,munger.getAspectType().getName(), existingMember), munger.getSourceLocation()) ); } } } } else if (isDuplicateMemberWithinTargetType(existingMember,this,sig)) { getWorld().getMessageHandler().handleMessage( MessageUtil.error(WeaverMessages.format(WeaverMessages.ITD_MEMBER_CONFLICT,munger.getAspectType().getName(), existingMember), munger.getSourceLocation()) ); ; } //return; } } return true; } // we know that the member signature matches, but that the member in the target type is not visible to the aspect. // this may still be disallowed if it would result in two members within the same declaring type with the same // signature AND more than one of them is concrete AND they are both visible within the target type. private boolean isDuplicateMemberWithinTargetType(ResolvedMember existingMember, ResolvedType targetType,ResolvedMember itdMember) { if ( (existingMember.isAbstract() || itdMember.isAbstract())) return false; UnresolvedType declaringType = existingMember.getDeclaringType(); if (!targetType.equals(declaringType)) return false; // now have to test that itdMember is visible from targetType if (itdMember.isPrivate()) return false; if (itdMember.isPublic()) return true; // must be in same package to be visible then... if (!targetType.getPackageName().equals(itdMember.getDeclaringType().getPackageName())) return false; // trying to put two members with the same signature into the exact same type..., and both visible in that type. return true; } /** * @return true if the override is legal * note: calling showMessage with two locations issues TWO messages, not ONE message * with an additional source location. */ public boolean checkLegalOverride(ResolvedMember parent, ResolvedMember child) { //System.err.println("check: " + child.getDeclaringType() + " overrides " + parent.getDeclaringType()); if (Modifier.isFinal(parent.getModifiers())) { world.showMessage(Message.ERROR, WeaverMessages.format(WeaverMessages.CANT_OVERRIDE_FINAL_MEMBER,parent), child.getSourceLocation(),null); return false; } boolean incompatibleReturnTypes = false; // In 1.5 mode, allow for covariance on return type if (world.isInJava5Mode() && parent.getKind()==Member.METHOD) { // Look at the generic types when doing this comparison ResolvedType rtParentReturnType = parent.getGenericReturnType().resolve(world); ResolvedType rtChildReturnType = child.getGenericReturnType().resolve(world); incompatibleReturnTypes = !rtParentReturnType.isAssignableFrom(rtChildReturnType); if (incompatibleReturnTypes) { incompatibleReturnTypes = !rtParentReturnType.isAssignableFrom(rtChildReturnType); } } else { incompatibleReturnTypes =!parent.getReturnType().equals(child.getReturnType()); } if (incompatibleReturnTypes) { world.showMessage(IMessage.ERROR, WeaverMessages.format(WeaverMessages.ITD_RETURN_TYPE_MISMATCH,parent,child), child.getSourceLocation(), parent.getSourceLocation()); return false; } if (parent.getKind() == Member.POINTCUT) { UnresolvedType[] pTypes = parent.getParameterTypes(); UnresolvedType[] cTypes = child.getParameterTypes(); if (!Arrays.equals(pTypes, cTypes)) { world.showMessage(IMessage.ERROR, WeaverMessages.format(WeaverMessages.ITD_PARAM_TYPE_MISMATCH,parent,child), child.getSourceLocation(), parent.getSourceLocation()); return false; } } //System.err.println("check: " + child.getModifiers() + " more visible " + parent.getModifiers()); if (isMoreVisible(parent.getModifiers(), child.getModifiers())) { world.showMessage(IMessage.ERROR, WeaverMessages.format(WeaverMessages.ITD_VISIBILITY_REDUCTION,parent,child), child.getSourceLocation(), parent.getSourceLocation()); return false; } // check declared exceptions ResolvedType[] childExceptions = world.resolve(child.getExceptions()); ResolvedType[] parentExceptions = world.resolve(parent.getExceptions()); ResolvedType runtimeException = world.resolve("java.lang.RuntimeException"); ResolvedType error = world.resolve("java.lang.Error"); outer: for (int i = 0, leni = childExceptions.length; i < leni; i++) { //System.err.println("checking: " + childExceptions[i]); if (runtimeException.isAssignableFrom(childExceptions[i])) continue; if (error.isAssignableFrom(childExceptions[i])) continue; for (int j = 0, lenj = parentExceptions.length; j < lenj; j++) { if (parentExceptions[j].isAssignableFrom(childExceptions[i])) continue outer; } // this message is now better handled my MethodVerifier in JDT core. // world.showMessage(IMessage.ERROR, // WeaverMessages.format(WeaverMessages.ITD_DOESNT_THROW,childExceptions[i].getName()), // child.getSourceLocation(), null); return false; } if (parent.isStatic() && !child.isStatic()) { world.showMessage(IMessage.ERROR, WeaverMessages.format(WeaverMessages.ITD_OVERRIDDEN_STATIC,child,parent), child.getSourceLocation(),null); return false; } else if (child.isStatic() && !parent.isStatic()) { world.showMessage(IMessage.ERROR, WeaverMessages.format(WeaverMessages.ITD_OVERIDDING_STATIC,child,parent), child.getSourceLocation(),null); return false; } return true; } private int compareMemberPrecedence(ResolvedMember m1, ResolvedMember m2) { //if (!m1.getReturnType().equals(m2.getReturnType())) return 0; // need to allow for the special case of 'clone' - which is like abstract but is // not marked abstract. The code below this next line seems to make assumptions // about what will have gotten through the compiler based on the normal // java rules. clone goes against these... if (m2.isProtected() && m2.getName().charAt(0)=='c') { UnresolvedType declaring = m2.getDeclaringType(); if (declaring!=null) { if (declaring.getName().equals("java.lang.Object") && m2.getName().equals("clone")) return +1; } } if (Modifier.isAbstract(m1.getModifiers())) return -1; if (Modifier.isAbstract(m2.getModifiers())) return +1; if (m1.getDeclaringType().equals(m2.getDeclaringType())) return 0; ResolvedType t1 = m1.getDeclaringType().resolve(world); ResolvedType t2 = m2.getDeclaringType().resolve(world); if (t1.isAssignableFrom(t2)) { return -1; } if (t2.isAssignableFrom(t1)) { return +1; } return 0; } public static boolean isMoreVisible(int m1, int m2) { if (Modifier.isPrivate(m1)) return false; if (isPackage(m1)) return Modifier.isPrivate(m2); if (Modifier.isProtected(m1)) return /* private package */ (Modifier.isPrivate(m2) || isPackage(m2)); if (Modifier.isPublic(m1)) return /* private package protected */ ! Modifier.isPublic(m2); throw new RuntimeException("bad modifier: " + m1); } private static boolean isPackage(int i) { return (0 == (i & (Modifier.PUBLIC | Modifier.PRIVATE | Modifier.PROTECTED))); } private void interTypeConflictError( ConcreteTypeMunger m1, ConcreteTypeMunger m2) { //XXX this works only if we ignore separate compilation issues //XXX dual errors possible if (this instanceof BcelObjectType) return; //System.err.println("conflict at " + m2.getSourceLocation()); getWorld().showMessage(IMessage.ERROR, WeaverMessages.format(WeaverMessages.ITD_CONFLICT,m1.getAspectType().getName(), m2.getSignature(),m2.getAspectType().getName()), m2.getSourceLocation(), getSourceLocation()); } public ResolvedMember lookupSyntheticMember(Member member) { //??? horribly inefficient //for (Iterator i = //System.err.println("lookup " + member + " in " + interTypeMungers); for (Iterator i = interTypeMungers.iterator(); i.hasNext(); ) { ConcreteTypeMunger m = (ConcreteTypeMunger)i.next(); ResolvedMember ret = m.getMatchingSyntheticMember(member); if (ret != null) { //System.err.println(" found: " + ret); return ret; } } // Handling members for the new array join point if (world.isJoinpointArrayConstructionEnabled() && this.isArray()) { if (member.getKind()==Member.CONSTRUCTOR) { ResolvedMemberImpl ret = new ResolvedMemberImpl(Member.CONSTRUCTOR,this,Modifier.PUBLIC, ResolvedType.VOID,"<init>",world.resolve(member.getParameterTypes())); return ret; } } // if (this.getSuperclass() != ResolvedType.OBJECT && this.getSuperclass() != null) { // return getSuperclass().lookupSyntheticMember(member); // } return null; } public void clearInterTypeMungers() { if (isRawType()) getGenericType().clearInterTypeMungers(); interTypeMungers = new ArrayList(); } public boolean isTopmostImplementor(ResolvedType interfaceType) { if (isInterface()) return false; if (!interfaceType.isAssignableFrom(this,true)) return false; // check that I'm truly the topmost implementor if (this.getSuperclass().isMissing()) return true; // we don't know anything about supertype, and it can't be exposed to weaver if (interfaceType.isAssignableFrom(this.getSuperclass(),true)) { return false; } return true; } public ResolvedType getTopmostImplementor(ResolvedType interfaceType) { if (isInterface()) return null; if (!interfaceType.isAssignableFrom(this)) return null; // Check if my super class is an implementor? ResolvedType higherType = this.getSuperclass().getTopmostImplementor(interfaceType); if (higherType!=null) return higherType; return this; } private ResolvedType findHigher(ResolvedType other) { if (this == other) return this; for(Iterator i = other.getDirectSupertypes(); i.hasNext(); ) { ResolvedType rtx = (ResolvedType)i.next(); boolean b = this.isAssignableFrom(rtx); if (b) return rtx; } return null; } public List getExposedPointcuts() { List ret = new ArrayList(); if (getSuperclass() != null) ret.addAll(getSuperclass().getExposedPointcuts()); for (Iterator i = Arrays.asList(getDeclaredInterfaces()).iterator(); i.hasNext(); ) { ResolvedType t = (ResolvedType)i.next(); addPointcutsResolvingConflicts(ret, Arrays.asList(t.getDeclaredPointcuts()), false); } addPointcutsResolvingConflicts(ret, Arrays.asList(getDeclaredPointcuts()), true); for (Iterator i = ret.iterator(); i.hasNext(); ) { ResolvedPointcutDefinition inherited = (ResolvedPointcutDefinition)i.next(); // System.err.println("looking at: " + inherited + " in " + this); // System.err.println(" " + inherited.isAbstract() + " in " + this.isAbstract()); if (inherited.isAbstract()) { if (!this.isAbstract()) { getWorld().showMessage(IMessage.ERROR, WeaverMessages.format(WeaverMessages.POINCUT_NOT_CONCRETE,inherited,this.getName()), inherited.getSourceLocation(), this.getSourceLocation()); } } } return ret; } private void addPointcutsResolvingConflicts(List acc, List added, boolean isOverriding) { for (Iterator i = added.iterator(); i.hasNext();) { ResolvedPointcutDefinition toAdd = (ResolvedPointcutDefinition) i.next(); //System.err.println("adding: " + toAdd); for (Iterator j = acc.iterator(); j.hasNext();) { ResolvedPointcutDefinition existing = (ResolvedPointcutDefinition) j.next(); if (existing == toAdd) continue; if (!isVisible(existing.getModifiers(), existing.getDeclaringType().resolve(getWorld()), this)) { continue; } if (conflictingSignature(existing, toAdd)) { if (isOverriding) { checkLegalOverride(existing, toAdd); j.remove(); } else { getWorld().showMessage( IMessage.ERROR, WeaverMessages.format(WeaverMessages.CONFLICTING_INHERITED_POINTCUTS,this.getName() + toAdd.getSignature()), existing.getSourceLocation(), toAdd.getSourceLocation()); j.remove(); } } } acc.add(toAdd); } } public ISourceLocation getSourceLocation() { return null; } public boolean isExposedToWeaver() { return false; } public WeaverStateInfo getWeaverState() { return null; } /** * Overridden by ReferenceType to return a sensible answer for parameterized and raw types. * * @return */ public ResolvedType getGenericType() { if (!(isParameterizedType() || isRawType())) throw new BCException("The type "+getBaseName()+" is not parameterized or raw - it has no generic type"); return null; } /** * overriden by ReferenceType to return the gsig for a generic type * @return */ public String getGenericSignature() { return ""; } public ResolvedType parameterizedWith(UnresolvedType[] typeParameters) { if (!(isGenericType() || isParameterizedType())) return this; return TypeFactory.createParameterizedType(this.getGenericType(), typeParameters, getWorld()); } /** * Iff I am a parameterized type, and any of my parameters are type variable * references, return a version with those type parameters replaced in accordance * with the passed bindings. */ public UnresolvedType parameterize(Map typeBindings) { if (!isParameterizedType()) return this;//throw new IllegalStateException("Can't parameterize a type that is not a parameterized type"); boolean workToDo = false; for (int i = 0; i < typeParameters.length; i++) { if (typeParameters[i].isTypeVariableReference() || (typeParameters[i] instanceof BoundedReferenceType)) { workToDo = true; } } if (!workToDo) { return this; } else { UnresolvedType[] newTypeParams = new UnresolvedType[typeParameters.length]; for (int i = 0; i < newTypeParams.length; i++) { newTypeParams[i] = typeParameters[i]; if (newTypeParams[i].isTypeVariableReference()) { TypeVariableReferenceType tvrt = (TypeVariableReferenceType) newTypeParams[i]; UnresolvedType binding = (UnresolvedType) typeBindings.get(tvrt.getTypeVariable().getName()); if (binding != null) newTypeParams[i] = binding; } else if (newTypeParams[i] instanceof BoundedReferenceType) { BoundedReferenceType brType = (BoundedReferenceType)newTypeParams[i]; newTypeParams[i] = brType.parameterize(typeBindings); // brType.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); } } /** * Types may have pointcuts just as they have methods and fields. */ public ResolvedPointcutDefinition findPointcut(String name, World world) { throw new UnsupportedOperationException("Not yet implemenented"); } /** * @return true if assignable to java.lang.Exception */ public boolean isException() { return (world.getCoreType(UnresolvedType.JAVA_LANG_EXCEPTION).isAssignableFrom(this)); } /** * @return true if it is an exception and it is a checked one, false otherwise. */ public boolean isCheckedException() { if (!isException()) return false; if (world.getCoreType(UnresolvedType.RUNTIME_EXCEPTION).isAssignableFrom(this)) return false; return true; } /** * Determines if variables of this type could be assigned values of another * with lots of help. * java.lang.Object is convertable from all types. * A primitive type is convertable from X iff it's assignable from X. * A reference type is convertable from X iff it's coerceable from X. * In other words, X isConvertableFrom Y iff the compiler thinks that _some_ value of Y * could be assignable to a variable of type X without loss of precision. * * @param other the other type * @param world the {@link World} in which the possible assignment should be checked. * @return true iff variables of this type could be assigned values of other with possible conversion */ public final boolean isConvertableFrom(ResolvedType other) { // // version from TypeX // if (this.equals(OBJECT)) return true; // if (this.isPrimitiveType() || other.isPrimitiveType()) return this.isAssignableFrom(other); // return this.isCoerceableFrom(other); // // version from ResolvedTypeX if (this.equals(OBJECT)) return true; if (world.isInJava5Mode()) { if (this.isPrimitiveType()^other.isPrimitiveType()) { // If one is primitive and the other isnt if (validBoxing.contains(this.getSignature()+other.getSignature())) return true; } } if (this.isPrimitiveType() || other.isPrimitiveType()) return this.isAssignableFrom(other); return this.isCoerceableFrom(other); } /** * Determines if the variables of this type could be assigned values * of another type without casting. This still allows for assignment conversion * as per JLS 2ed 5.2. For object types, this means supertypeOrEqual(THIS, OTHER). * * @param other the other type * @param world the {@link World} in which the possible assignment should be checked. * @return true iff variables of this type could be assigned values of other without casting * @throws NullPointerException if other is null */ public abstract boolean isAssignableFrom(ResolvedType other); public abstract boolean isAssignableFrom(ResolvedType other, boolean allowMissing); /** * Determines if values of another type could possibly be cast to * this type. The rules followed are from JLS 2ed 5.5, "Casting Conversion". * <p/> * <p> This method should be commutative, i.e., for all UnresolvedType a, b and all World w: * <p/> * <blockquote><pre> * a.isCoerceableFrom(b, w) == b.isCoerceableFrom(a, w) * </pre></blockquote> * * @param other the other type * @param world the {@link World} in which the possible coersion should be checked. * @return true iff values of other could possibly be cast to this type. * @throws NullPointerException if other is null. */ public abstract boolean isCoerceableFrom(ResolvedType other); public boolean needsNoConversionFrom(ResolvedType o) { return isAssignableFrom(o); } /** * Implemented by ReferenceTypes */ public String getSignatureForAttribute() { throw new RuntimeException("Cannot ask this type "+this+" for a generic sig attribute"); } private FuzzyBoolean parameterizedWithAMemberTypeVariable = FuzzyBoolean.MAYBE; /** * return true if the parameterization of this type includes a member type variable. Member * type variables occur in generic methods/ctors. */ public boolean isParameterizedWithAMemberTypeVariable() { // MAYBE means we haven't worked it out yet... if (parameterizedWithAMemberTypeVariable==FuzzyBoolean.MAYBE) { // if there are no type parameters then we cant be... if (typeParameters==null || typeParameters.length==0) { parameterizedWithAMemberTypeVariable = FuzzyBoolean.NO; return false; } for (int i = 0; i < typeParameters.length; i++) { UnresolvedType aType = (ResolvedType)typeParameters[i]; if (aType.isTypeVariableReference() && // assume the worst - if its definetly not a type declared one, it could be anything ((TypeVariableReference)aType).getTypeVariable().getDeclaringElementKind()!=TypeVariable.TYPE) { parameterizedWithAMemberTypeVariable = FuzzyBoolean.YES; return true; } if (aType.isParameterizedType()) { boolean b = aType.isParameterizedWithAMemberTypeVariable(); if (b) { parameterizedWithAMemberTypeVariable = FuzzyBoolean.YES; return true; } } if (aType.isGenericWildcard()) { if (aType.isExtends()) { boolean b = false; UnresolvedType upperBound = aType.getUpperBound(); if (upperBound.isParameterizedType()) { b = upperBound.isParameterizedWithAMemberTypeVariable(); } else if (upperBound.isTypeVariableReference() && ((TypeVariableReference)upperBound).getTypeVariable().getDeclaringElementKind()==TypeVariable.METHOD) { b = true; } if (b) { parameterizedWithAMemberTypeVariable = FuzzyBoolean.YES; return true; } // FIXME asc need to check additional interface bounds } if (aType.isSuper()) { boolean b = false; UnresolvedType lowerBound = aType.getLowerBound(); if (lowerBound.isParameterizedType()) { b = lowerBound.isParameterizedWithAMemberTypeVariable(); } else if (lowerBound.isTypeVariableReference() && ((TypeVariableReference)lowerBound).getTypeVariable().getDeclaringElementKind()==TypeVariable.METHOD) { b = true; } if (b) { parameterizedWithAMemberTypeVariable = FuzzyBoolean.YES; return true; } } } } parameterizedWithAMemberTypeVariable=FuzzyBoolean.NO; } return parameterizedWithAMemberTypeVariable.alwaysTrue(); } protected boolean ajMembersNeedParameterization() { if (isParameterizedType()) return true; if (getSuperclass() != null) return getSuperclass().ajMembersNeedParameterization(); return false; } protected Map getAjMemberParameterizationMap() { Map myMap = getMemberParameterizationMap(); if (myMap.size() == 0) { // might extend a parameterized aspect that we also need to consider... if (getSuperclass() != null) return getSuperclass().getAjMemberParameterizationMap(); } return myMap; } 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; } }
184,447
Bug 184447 AjLookupEnvironment.java:519
Build ID: Eclipse SDK Version: 3.2.2 M20070212-1330 Steps To Reproduce: This occured repeatedly when I saved a .aj file or a .java file that was boing advised. A restart of eclipse made it go away and it has not happen again so I don't know how reproduce it. Sorry. AJDT version 1.4.2.200703020612 More information: java.lang.NullPointerException at org.aspectj.ajdt.internal.compiler.lookup.AjLookupEnvironment.doDeclareAnnotations(AjLookupEnvironment.java:803) at org.aspectj.ajdt.internal.compiler.lookup.AjLookupEnvironment.weaveInterTypeDeclarations(AjLookupEnvironment.java:592) at org.aspectj.ajdt.internal.compiler.lookup.AjLookupEnvironment.weaveInterTypeDeclarations(AjLookupEnvironment.java:519) at org.aspectj.ajdt.internal.compiler.lookup.AjLookupE ... AutoBuildJob.run(AutoBuildJob.java:217) at org.eclipse.core.internal.jobs.Worker.run(Worker.java:58) Compile error: NullPointerException thrown: null
resolved fixed
8ce9dcf
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2008-03-21T18:14:28Z"
"2007-04-27T16:06:40Z"
org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/compiler/lookup/AjLookupEnvironment.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.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import org.aspectj.ajdt.internal.compiler.ast.AspectDeclaration; import org.aspectj.ajdt.internal.compiler.ast.PointcutDeclaration; import org.aspectj.asm.AsmManager; import org.aspectj.bridge.IMessage; 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.org.eclipse.jdt.core.compiler.CharOperation; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.Annotation; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.NormalAnnotation; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.QualifiedTypeReference; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.SingleTypeReference; 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.env.AccessRestriction; import org.aspectj.org.eclipse.jdt.internal.compiler.env.IBinaryType; import org.aspectj.org.eclipse.jdt.internal.compiler.env.INameEnvironment; import org.aspectj.org.eclipse.jdt.internal.compiler.impl.CompilerOptions; import org.aspectj.org.eclipse.jdt.internal.compiler.impl.ITypeRequestor; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.BinaryTypeBinding; 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.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.PackageBinding; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.ParameterizedTypeBinding; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.ReferenceBinding; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.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.weaver.AnnotationX; import org.aspectj.weaver.AsmRelationshipProvider; import org.aspectj.weaver.ConcreteTypeMunger; import org.aspectj.weaver.FakeAnnotation; import org.aspectj.weaver.ReferenceType; import org.aspectj.weaver.ReferenceTypeDelegate; import org.aspectj.weaver.ResolvedMember; import org.aspectj.weaver.ResolvedType; import org.aspectj.weaver.TypeVariable; import org.aspectj.weaver.UnresolvedType; import org.aspectj.weaver.WeaverMessages; import org.aspectj.weaver.WeaverStateInfo; import org.aspectj.weaver.World; import org.aspectj.weaver.bcel.BcelObjectType; import org.aspectj.weaver.bcel.LazyClassGen; import org.aspectj.weaver.patterns.DeclareAnnotation; import org.aspectj.weaver.patterns.DeclareParents; /** * Overrides the default eclipse LookupEnvironment for two purposes. * * 1. To provide some additional phases to <code>completeTypeBindings</code> * that weave declare parents and inter-type declarations at the correct time. * * 2. To intercept the loading of new binary types to ensure the they will have * declare parents and inter-type declarations woven when appropriate. * * @author Jim Hugunin */ public class AjLookupEnvironment extends LookupEnvironment implements AnonymousClassCreationListener { public EclipseFactory factory = null; // private boolean builtInterTypesAndPerClauses = false; private List pendingTypesToWeave = new ArrayList(); // Q: What are dangerousInterfaces? // A: An interface is considered dangerous if an ITD has been made upon it and that ITD // requires the top most implementors of the interface to be woven *and yet* the aspect // responsible for the ITD is not in the 'world'. // Q: Err, how can that happen? // A: When a type is on the inpath, it is 'processed' when completing type bindings. At this // point we look at any type mungers it was affected by previously (stored in the weaver // state info attribute). Effectively we are working with a type munger and yet may not have its // originating aspect in the world. This is a problem if, for example, the aspect supplied // a 'body' for a method targetting an interface - since the top most implementors should // be woven by the munger from the aspect. When this happens we store the interface name here // in the map - if we later process a type that is the topMostImplementor of a dangerous // interface then we put out an error message. /** interfaces targetted by ITDs that have to be implemented by accessing the topMostImplementor * of the interface, yet the aspect where the ITD originated is not in the world */ private Map dangerousInterfaces = new HashMap(); public AjLookupEnvironment( ITypeRequestor typeRequestor, CompilerOptions options, ProblemReporter problemReporter, INameEnvironment nameEnvironment) { super(typeRequestor, options, problemReporter, nameEnvironment); } //??? duplicates some of super's code public void completeTypeBindings() { AsmManager.setCompletingTypeBindings(true); ContextToken completeTypeBindingsToken = CompilationAndWeavingContext.enteringPhase(CompilationAndWeavingContext.COMPLETING_TYPE_BINDINGS, ""); // builtInterTypesAndPerClauses = false; //pendingTypesToWeave = new ArrayList(); stepCompleted = BUILD_TYPE_HIERARCHY; for (int i = lastCompletedUnitIndex + 1; i <= lastUnitIndex; i++) { ContextToken tok = CompilationAndWeavingContext.enteringPhase(CompilationAndWeavingContext.CHECK_AND_SET_IMPORTS, units[i].compilationResult.fileName); units[i].scope.checkAndSetImports(); CompilationAndWeavingContext.leavingPhase(tok); } stepCompleted = CHECK_AND_SET_IMPORTS; for (int i = lastCompletedUnitIndex + 1; i <= lastUnitIndex; i++) { ContextToken tok = CompilationAndWeavingContext.enteringPhase(CompilationAndWeavingContext.CONNECTING_TYPE_HIERARCHY, units[i].compilationResult.fileName); units[i].scope.connectTypeHierarchy(); CompilationAndWeavingContext.leavingPhase(tok); } stepCompleted = CONNECT_TYPE_HIERARCHY; for (int i = lastCompletedUnitIndex + 1; i <= lastUnitIndex; i++) { ContextToken tok = CompilationAndWeavingContext.enteringPhase(CompilationAndWeavingContext.BUILDING_FIELDS_AND_METHODS, units[i].compilationResult.fileName); units[i].scope.checkParameterizedTypes(); units[i].scope.buildFieldsAndMethods(); CompilationAndWeavingContext.leavingPhase(tok); } // would like to gather up all TypeDeclarations at this point and put them in the factory for (int i = lastCompletedUnitIndex + 1; i <= lastUnitIndex; i++) { SourceTypeBinding[] b = units[i].scope.topLevelTypes; for (int j = 0; j < b.length; j++) { factory.addSourceTypeBinding(b[j],units[i]); } } // We won't find out about anonymous types until later though, so register to be // told about them when they turn up. AnonymousClassPublisher.aspectOf().setAnonymousClassCreationListener(this); // need to build inter-type declarations for all AspectDeclarations at this point // this MUST be done in order from super-types to subtypes List typesToProcess = new ArrayList(); for (int i=lastCompletedUnitIndex+1; i<=lastUnitIndex; i++) { CompilationUnitScope cus = units[i].scope; SourceTypeBinding[] stbs = cus.topLevelTypes; for (int j=0; j<stbs.length; j++) { SourceTypeBinding stb = stbs[j]; typesToProcess.add(stb); } } factory.getWorld().getCrosscuttingMembersSet().reset(); while (typesToProcess.size()>0) { // removes types from the list as they are processed... collectAllITDsAndDeclares((SourceTypeBinding)typesToProcess.get(0),typesToProcess); } factory.finishTypeMungers(); // now do weaving Collection typeMungers = factory.getTypeMungers(); Collection declareParents = factory.getDeclareParents(); Collection declareAnnotationOnTypes = factory.getDeclareAnnotationOnTypes(); doPendingWeaves(); // We now have some list of types to process, and we are about to apply the type mungers. // There can be situations where the order of types passed to the compiler causes the // output from the compiler to vary - THIS IS BAD. For example, if we have class A // and class B extends A. Also, an aspect that 'declare parents: A+ implements Serializable' // then depending on whether we see A first, we may or may not make B serializable. // The fix is to process them in the right order, ensuring that for a type we process its // supertypes and superinterfaces first. This algorithm may have problems with: // - partial hierarchies (e.g. suppose types A,B,C are in a hierarchy and A and C are to be woven but not B) // - weaving that brings new types in for processing (see pendingTypesToWeave.add() calls) after we thought // we had the full list. // // but these aren't common cases (he bravely said...) boolean typeProcessingOrderIsImportant = declareParents.size()>0 || declareAnnotationOnTypes.size()>0; //DECAT if (typeProcessingOrderIsImportant) { typesToProcess = new ArrayList(); for (int i=lastCompletedUnitIndex+1; i<=lastUnitIndex; i++) { CompilationUnitScope cus = units[i].scope; SourceTypeBinding[] stbs = cus.topLevelTypes; for (int j=0; j<stbs.length; j++) { SourceTypeBinding stb = stbs[j]; typesToProcess.add(stb); } } while (typesToProcess.size()>0) { // A side effect of weaveIntertypes() is that the processed type is removed from the collection weaveIntertypes(typesToProcess,(SourceTypeBinding)typesToProcess.get(0),typeMungers,declareParents,declareAnnotationOnTypes); } } else { // Order isn't important for (int i = lastCompletedUnitIndex + 1; i <= lastUnitIndex; i++) { //System.err.println("Working on "+new String(units[i].getFileName())); weaveInterTypeDeclarations(units[i].scope, typeMungers, declareParents,declareAnnotationOnTypes); } } for (int i = lastCompletedUnitIndex +1; i<=lastUnitIndex; i++) { SourceTypeBinding[] b = units[i].scope.topLevelTypes; for (int j = 0; j < b.length; j++) { verifyAnyTypeParametersMeetBounds(b[j]); } } for (int i = lastCompletedUnitIndex + 1; i <= lastUnitIndex; i++) { SourceTypeBinding[] b = units[i].scope.topLevelTypes; for (int j = 0; j < b.length; j++) { ContextToken tok = CompilationAndWeavingContext.enteringPhase(CompilationAndWeavingContext.RESOLVING_POINTCUT_DECLARATIONS, b[j].sourceName); resolvePointcutDeclarations(b[j].scope); CompilationAndWeavingContext.leavingPhase(tok); } } for (int i = lastCompletedUnitIndex + 1; i <= lastUnitIndex; i++) { SourceTypeBinding[] b = units[i].scope.topLevelTypes; for (int j = 0; j < b.length; j++) { ContextToken tok = CompilationAndWeavingContext.enteringPhase(CompilationAndWeavingContext.ADDING_DECLARE_WARNINGS_AND_ERRORS, b[j].sourceName); addAdviceLikeDeclares(b[j].scope); CompilationAndWeavingContext.leavingPhase(tok); } } for (int i = lastCompletedUnitIndex + 1; i <= lastUnitIndex; i++) { units[i] = null; // release unnecessary reference to the parsed unit } stepCompleted = BUILD_FIELDS_AND_METHODS; lastCompletedUnitIndex = lastUnitIndex; AsmManager.setCompletingTypeBindings(false); factory.getWorld().getCrosscuttingMembersSet().verify(); CompilationAndWeavingContext.leavingPhase(completeTypeBindingsToken); } /** * For any given sourcetypebinding, this method checks that if it is a parameterized aspect that * the type parameters specified for any supertypes meet the bounds for the generic type * variables. */ private void verifyAnyTypeParametersMeetBounds(SourceTypeBinding sourceType) { ResolvedType onType = factory.fromEclipse(sourceType); if (onType.isAspect()) { ResolvedType superType = factory.fromEclipse(sourceType.superclass); // Don't need to check if it was used in its RAW form or isnt generic if (superType.isGenericType() || superType.isParameterizedType()) { TypeVariable[] typeVariables = superType.getTypeVariables(); UnresolvedType[] typeParams = superType.getTypeParameters(); if (typeVariables!=null && typeParams!=null) { for (int i = 0; i < typeVariables.length; i++) { boolean ok = typeVariables[i].canBeBoundTo(typeParams[i].resolve(factory.getWorld())); if (!ok) { // the supplied parameter violates the bounds // Type {0} does not meet the specification for type parameter {1} ({2}) in generic type {3} String msg = WeaverMessages.format( WeaverMessages.VIOLATES_TYPE_VARIABLE_BOUNDS, typeParams[i], new Integer(i+1), typeVariables[i].getDisplayName(), superType.getGenericType().getName()); factory.getWorld().getMessageHandler().handleMessage(MessageUtil.error(msg,onType.getSourceLocation())); } } } } } } public void doSupertypesFirst(ReferenceBinding rb,Collection yetToProcess) { if (rb instanceof SourceTypeBinding) { if (yetToProcess.contains(rb)) { collectAllITDsAndDeclares((SourceTypeBinding)rb, yetToProcess); } } else if (rb instanceof ParameterizedTypeBinding) { // If its a PTB we need to pull the SourceTypeBinding out of it. ParameterizedTypeBinding ptb = (ParameterizedTypeBinding)rb; if (ptb.type instanceof SourceTypeBinding && yetToProcess.contains(ptb.type)) { collectAllITDsAndDeclares((SourceTypeBinding)ptb.type, yetToProcess); } } } /** * Find all the ITDs and Declares, but it is important we do this from the supertypes * down to the subtypes. * @param sourceType * @param yetToProcess */ private void collectAllITDsAndDeclares(SourceTypeBinding sourceType, Collection yetToProcess) { // Look at the supertype first ContextToken tok = CompilationAndWeavingContext.enteringPhase(CompilationAndWeavingContext.COLLECTING_ITDS_AND_DECLARES, sourceType.sourceName); yetToProcess.remove(sourceType); // look out our direct supertype doSupertypesFirst(sourceType.superclass(),yetToProcess); // now check our membertypes (pr119570) ReferenceBinding[] memberTypes = sourceType.memberTypes; for (int i = 0, length = memberTypes.length; i < length; i++) { SourceTypeBinding rb = (SourceTypeBinding)memberTypes[i]; if (!rb.superclass().equals(sourceType)) doSupertypesFirst(rb.superclass(),yetToProcess); } buildInterTypeAndPerClause(sourceType.scope); addCrosscuttingStructures(sourceType.scope); CompilationAndWeavingContext.leavingPhase(tok); } /** * Weave the parents and intertype decls into a given type. This method looks at the * supertype and superinterfaces for the specified type and recurses to weave those first * if they are in the full list of types we are going to process during this compile... it stops recursing * the first time it hits a type we aren't going to process during this compile. This could cause problems * if you supply 'pieces' of a hierarchy, i.e. the bottom and the top, but not the middle - but what the hell * are you doing if you do that? */ private void weaveIntertypes(List typesToProcess,SourceTypeBinding typeToWeave,Collection typeMungers, Collection declareParents,Collection declareAnnotationOnTypes) { // Look at the supertype first ReferenceBinding superType = typeToWeave.superclass(); if (typesToProcess.contains(superType) && superType instanceof SourceTypeBinding) { //System.err.println("Recursing to supertype "+new String(superType.getFileName())); weaveIntertypes(typesToProcess,(SourceTypeBinding)superType,typeMungers,declareParents,declareAnnotationOnTypes); } // Then look at the superinterface list ReferenceBinding[] interfaceTypes = typeToWeave.superInterfaces(); for (int i = 0; i < interfaceTypes.length; i++) { ReferenceBinding binding = interfaceTypes[i]; if (typesToProcess.contains(binding) && binding instanceof SourceTypeBinding) { //System.err.println("Recursing to superinterface "+new String(binding.getFileName())); weaveIntertypes(typesToProcess,(SourceTypeBinding)binding,typeMungers,declareParents,declareAnnotationOnTypes); } } weaveInterTypeDeclarations(typeToWeave,typeMungers,declareParents,declareAnnotationOnTypes,false); typesToProcess.remove(typeToWeave); } private void doPendingWeaves() { for (Iterator i = pendingTypesToWeave.iterator(); i.hasNext(); ) { SourceTypeBinding t = (SourceTypeBinding)i.next(); ContextToken tok = CompilationAndWeavingContext.enteringPhase(CompilationAndWeavingContext.WEAVING_INTERTYPE_DECLARATIONS, t.sourceName); weaveInterTypeDeclarations(t); CompilationAndWeavingContext.leavingPhase(tok); } pendingTypesToWeave.clear(); } private void addAdviceLikeDeclares(ClassScope s) { TypeDeclaration dec = s.referenceContext; if (dec instanceof AspectDeclaration) { ResolvedType typeX = factory.fromEclipse(dec.binding); factory.getWorld().getCrosscuttingMembersSet().addAdviceLikeDeclares(typeX); } SourceTypeBinding sourceType = s.referenceContext.binding; ReferenceBinding[] memberTypes = sourceType.memberTypes; for (int i = 0, length = memberTypes.length; i < length; i++) { addAdviceLikeDeclares(((SourceTypeBinding) memberTypes[i]).scope); } } private void addCrosscuttingStructures(ClassScope s) { TypeDeclaration dec = s.referenceContext; if (dec instanceof AspectDeclaration) { ResolvedType typeX = factory.fromEclipse(dec.binding); factory.getWorld().getCrosscuttingMembersSet().addOrReplaceAspect(typeX,false); if (typeX.getSuperclass().isAspect() && !typeX.getSuperclass().isExposedToWeaver()) { factory.getWorld().getCrosscuttingMembersSet().addOrReplaceAspect(typeX.getSuperclass(),false); } } SourceTypeBinding sourceType = s.referenceContext.binding; ReferenceBinding[] memberTypes = sourceType.memberTypes; for (int i = 0, length = memberTypes.length; i < length; i++) { addCrosscuttingStructures(((SourceTypeBinding) memberTypes[i]).scope); } } private void resolvePointcutDeclarations(ClassScope s) { TypeDeclaration dec = s.referenceContext; SourceTypeBinding sourceType = s.referenceContext.binding; boolean hasPointcuts = false; AbstractMethodDeclaration[] methods = dec.methods; boolean initializedMethods = false; if (methods != null) { for (int i=0; i < methods.length; i++) { if (methods[i] instanceof PointcutDeclaration) { hasPointcuts = true; if (!initializedMethods) { sourceType.methods(); //force initialization initializedMethods = true; } ((PointcutDeclaration)methods[i]).resolvePointcut(s); } } } if (hasPointcuts || dec instanceof AspectDeclaration || couldBeAnnotationStyleAspectDeclaration(dec)) { ReferenceType name = (ReferenceType)factory.fromEclipse(sourceType); EclipseSourceType eclipseSourceType = (EclipseSourceType)name.getDelegate(); eclipseSourceType.checkPointcutDeclarations(); } ReferenceBinding[] memberTypes = sourceType.memberTypes; for (int i = 0, length = memberTypes.length; i < length; i++) { resolvePointcutDeclarations(((SourceTypeBinding) memberTypes[i]).scope); } } /** * Return true if the declaration has @Aspect annotation. Called 'couldBe' rather than * 'is' because someone else may have defined an annotation called Aspect - we can't * verify the full name (including package name) because it may not have been resolved * just yet and rather going through expensive resolution when we dont have to, this * gives us a cheap check that tells us whether to bother. */ private boolean couldBeAnnotationStyleAspectDeclaration(TypeDeclaration dec) { Annotation[] annotations = dec.annotations; boolean couldBeAtAspect = false; if (annotations != null) { for (int i = 0; i < annotations.length && !couldBeAtAspect; i++) { if (annotations[i].toString().equals("@Aspect")) couldBeAtAspect=true; } } return couldBeAtAspect; } private void buildInterTypeAndPerClause(ClassScope s) { TypeDeclaration dec = s.referenceContext; if (dec instanceof AspectDeclaration) { ((AspectDeclaration)dec).buildInterTypeAndPerClause(s); } SourceTypeBinding sourceType = s.referenceContext.binding; // test classes don't extend aspects if (sourceType.superclass != null) { ResolvedType parent = factory.fromEclipse(sourceType.superclass); if (parent.isAspect() && !isAspect(dec)) { factory.showMessage(IMessage.ERROR, "class \'" + new String(sourceType.sourceName) + "\' can not extend aspect \'" + parent.getName() + "\'", factory.fromEclipse(sourceType).getSourceLocation(), null); } } ReferenceBinding[] memberTypes = sourceType.memberTypes; for (int i = 0, length = memberTypes.length; i < length; i++) { buildInterTypeAndPerClause(((SourceTypeBinding) memberTypes[i]).scope); } } private boolean isAspect(TypeDeclaration decl) { if ((decl instanceof AspectDeclaration)) { return true; } else if (decl.annotations == null) { return false; } else { for (int i = 0; i < decl.annotations.length; i++) { Annotation ann = decl.annotations[i]; if (ann.type instanceof SingleTypeReference) { if (CharOperation.equals("Aspect".toCharArray(),((SingleTypeReference)ann.type).token)) return true; } else if (ann.type instanceof QualifiedTypeReference) { QualifiedTypeReference qtr = (QualifiedTypeReference) ann.type; if (qtr.tokens.length != 5) return false; if (!CharOperation.equals("org".toCharArray(),qtr.tokens[0])) return false; if (!CharOperation.equals("aspectj".toCharArray(),qtr.tokens[1])) return false; if (!CharOperation.equals("lang".toCharArray(),qtr.tokens[2])) return false; if (!CharOperation.equals("annotation".toCharArray(),qtr.tokens[3])) return false; if (!CharOperation.equals("Aspect".toCharArray(),qtr.tokens[4])) return false; return true; } } } return false; } private void weaveInterTypeDeclarations(CompilationUnitScope unit, Collection typeMungers, Collection declareParents, Collection declareAnnotationOnTypes) { for (int i = 0, length = unit.topLevelTypes.length; i < length; i++) { weaveInterTypeDeclarations(unit.topLevelTypes[i], typeMungers, declareParents, declareAnnotationOnTypes,false); } } private void weaveInterTypeDeclarations(SourceTypeBinding sourceType) { if (!factory.areTypeMungersFinished()) { if (!pendingTypesToWeave.contains(sourceType)) pendingTypesToWeave.add(sourceType); } else { weaveInterTypeDeclarations(sourceType, factory.getTypeMungers(), factory.getDeclareParents(), factory.getDeclareAnnotationOnTypes(),true); } } private void weaveInterTypeDeclarations(SourceTypeBinding sourceType, Collection typeMungers, Collection declareParents, Collection declareAnnotationOnTypes, boolean skipInners) { ContextToken tok = CompilationAndWeavingContext.enteringPhase(CompilationAndWeavingContext.WEAVING_INTERTYPE_DECLARATIONS, sourceType.sourceName); ResolvedType onType = factory.fromEclipse(sourceType); // AMC we shouldn't need this when generic sigs are fixed?? if (onType.isRawType()) onType = onType.getGenericType(); WeaverStateInfo info = onType.getWeaverState(); // this test isnt quite right - there will be a case where we fail to flag a problem // with a 'dangerous interface' because the type is reweavable when we should have // because the type wasn't going to be rewoven... if that happens, we should perhaps // move this test and dangerous interface processing to the end of this method and // make it conditional on whether any of the typeMungers passed into here actually // matched this type. if (info != null && !info.isOldStyle() && !info.isReweavable()) { processTypeMungersFromExistingWeaverState(sourceType,onType); CompilationAndWeavingContext.leavingPhase(tok); return; } // Check if the type we are looking at is the topMostImplementor of a dangerous interface - // report a problem if it is. for (Iterator i = dangerousInterfaces.entrySet().iterator(); i.hasNext();) { Map.Entry entry = (Map.Entry) i.next(); ResolvedType interfaceType = (ResolvedType)entry.getKey(); if (onType.isTopmostImplementor(interfaceType)) { factory.showMessage(IMessage.ERROR, onType + ": " + entry.getValue(), onType.getSourceLocation(), null); } } boolean needOldStyleWarning = (info != null && info.isOldStyle()); onType.clearInterTypeMungers(); // FIXME asc perf Could optimize here, after processing the expected set of types we may bring // binary types that are not exposed to the weaver, there is no need to attempt declare parents // or declare annotation really - unless we want to report the not-exposed to weaver // messages... List decpToRepeat = new ArrayList(); List decaToRepeat = new ArrayList(); boolean anyNewParents = false; boolean anyNewAnnotations = false; // first pass // try and apply all decps - if they match, then great. If they don't then // check if they are starred-annotation patterns. If they are not starred // annotation patterns then they might match later...remember that... for (Iterator i = declareParents.iterator(); i.hasNext();) { DeclareParents decp = (DeclareParents)i.next(); boolean didSomething = doDeclareParents(decp, sourceType); if (didSomething) { anyNewParents = true; } else { if (!decp.getChild().isStarAnnotation()) decpToRepeat.add(decp); } } for (Iterator i = declareAnnotationOnTypes.iterator(); i.hasNext();) { DeclareAnnotation deca = (DeclareAnnotation)i.next(); boolean didSomething = doDeclareAnnotations(deca, sourceType,true); if (didSomething) { anyNewAnnotations = true; } else { if (!deca.getTypePattern().isStar()) decaToRepeat.add(deca); } } // now lets loop over and over until we have done all we can while ((anyNewAnnotations || anyNewParents) && (!decpToRepeat.isEmpty() || !decaToRepeat.isEmpty())) { anyNewParents = anyNewAnnotations = false; List forRemoval = new ArrayList(); for (Iterator i = decpToRepeat.iterator(); i.hasNext();) { DeclareParents decp = (DeclareParents)i.next(); boolean didSomething = doDeclareParents(decp, sourceType); if (didSomething) { anyNewParents = true; forRemoval.add(decp); } } decpToRepeat.removeAll(forRemoval); forRemoval = new ArrayList(); for (Iterator i = declareAnnotationOnTypes.iterator(); i.hasNext();) { DeclareAnnotation deca = (DeclareAnnotation)i.next(); boolean didSomething = doDeclareAnnotations(deca, sourceType,false); if (didSomething) { anyNewAnnotations = true; forRemoval.add(deca); } } decaToRepeat.removeAll(forRemoval); } for (Iterator i = typeMungers.iterator(); i.hasNext();) { EclipseTypeMunger munger = (EclipseTypeMunger) i.next(); if (munger.matches(onType)) { if (needOldStyleWarning) { factory.showMessage(IMessage.WARNING, "The class for " + onType + " should be recompiled with ajc-1.1.1 for best results", onType.getSourceLocation(), null); needOldStyleWarning = false; } onType.addInterTypeMunger(munger); } } onType.checkInterTypeMungers(); for (Iterator i = onType.getInterTypeMungers().iterator(); i.hasNext();) { EclipseTypeMunger munger = (EclipseTypeMunger) i.next(); //System.out.println("applying: " + munger + " to " + new String(sourceType.sourceName)); munger.munge(sourceType,onType); } // Call if you would like to do source weaving of declare @method/@constructor // at source time... no need to do this as it can't impact anything, but left here for // future generations to enjoy. Method source is commented out at the end of this module // doDeclareAnnotationOnMethods(); // Call if you would like to do source weaving of declare @field // at source time... no need to do this as it can't impact anything, but left here for // future generations to enjoy. Method source is commented out at the end of this module // doDeclareAnnotationOnFields(); if (skipInners) { CompilationAndWeavingContext.leavingPhase(tok); return; } ReferenceBinding[] memberTypes = sourceType.memberTypes; for (int i = 0, length = memberTypes.length; i < length; i++) { if (memberTypes[i] instanceof SourceTypeBinding) { weaveInterTypeDeclarations((SourceTypeBinding) memberTypes[i], typeMungers, declareParents,declareAnnotationOnTypes, false); } } CompilationAndWeavingContext.leavingPhase(tok); } /** * Called when we discover we are weaving intertype declarations on some type that has * an existing 'WeaverStateInfo' object - this is typically some previously woven type * that has been passed on the inpath. * * sourceType and onType are the 'same type' - the former is the 'Eclipse' version and * the latter is the 'Weaver' version. */ private void processTypeMungersFromExistingWeaverState(SourceTypeBinding sourceType,ResolvedType onType) { Collection previouslyAppliedMungers = onType.getWeaverState().getTypeMungers(onType); for (Iterator i = previouslyAppliedMungers.iterator(); i.hasNext(); ) { ConcreteTypeMunger m = (ConcreteTypeMunger)i.next(); EclipseTypeMunger munger = factory.makeEclipseTypeMunger(m); if (munger.munge(sourceType,onType)) { if (onType.isInterface() && munger.getMunger().needsAccessToTopmostImplementor()) { if (!onType.getWorld().getCrosscuttingMembersSet().containsAspect(munger.getAspectType())) { dangerousInterfaces.put(onType, "implementors of "+onType+" must be woven by "+munger.getAspectType()); } } } } } private boolean doDeclareParents(DeclareParents declareParents, SourceTypeBinding sourceType) { ContextToken tok = CompilationAndWeavingContext.enteringPhase(CompilationAndWeavingContext.PROCESSING_DECLARE_PARENTS, sourceType.sourceName); ResolvedType resolvedSourceType = factory.fromEclipse(sourceType); List newParents = declareParents.findMatchingNewParents(resolvedSourceType,false); if (!newParents.isEmpty()) { for (Iterator i = newParents.iterator(); i.hasNext(); ) { ResolvedType parent = (ResolvedType)i.next(); if (dangerousInterfaces.containsKey(parent)) { ResolvedType onType = factory.fromEclipse(sourceType); factory.showMessage(IMessage.ERROR, onType + ": " + dangerousInterfaces.get(parent), onType.getSourceLocation(), null); } if (Modifier.isFinal(parent.getModifiers())) { factory.showMessage(IMessage.ERROR,"cannot extend final class " + parent.getClassName(),declareParents.getSourceLocation(),null); } else { // do not actually do it if the type isn't exposed - this will correctly reported as a problem elsewhere if (!resolvedSourceType.isExposedToWeaver()) return false; AsmRelationshipProvider.getDefault().addDeclareParentsRelationship(declareParents.getSourceLocation(),factory.fromEclipse(sourceType), newParents); addParent(sourceType, parent); } } CompilationAndWeavingContext.leavingPhase(tok); return true; } CompilationAndWeavingContext.leavingPhase(tok); return false; } private String stringifyTargets(long bits) { if ((bits & TagBits.AnnotationTargetMASK)==0) return ""; Set s = new HashSet(); if ((bits&TagBits.AnnotationForAnnotationType)!=0) s.add("ANNOTATION_TYPE"); if ((bits&TagBits.AnnotationForConstructor)!=0) s.add("CONSTRUCTOR"); if ((bits&TagBits.AnnotationForField)!=0) s.add("FIELD"); if ((bits&TagBits.AnnotationForLocalVariable)!=0) s.add("LOCAL_VARIABLE"); if ((bits&TagBits.AnnotationForMethod)!=0) s.add("METHOD"); if ((bits&TagBits.AnnotationForPackage)!=0) s.add("PACKAGE"); if ((bits&TagBits.AnnotationForParameter)!=0) s.add("PARAMETER"); if ((bits&TagBits.AnnotationForType)!=0) s.add("TYPE"); StringBuffer sb = new StringBuffer(); sb.append("{"); for (Iterator iter = s.iterator(); iter.hasNext();) { String element = (String) iter.next(); sb.append(element); if (iter.hasNext()) sb.append(","); } sb.append("}"); return sb.toString(); } private boolean doDeclareAnnotations(DeclareAnnotation decA, SourceTypeBinding sourceType,boolean reportProblems) { ResolvedType rtx = factory.fromEclipse(sourceType); if (!decA.matches(rtx)) return false; if (!rtx.isExposedToWeaver()) return false; ContextToken tok = CompilationAndWeavingContext.enteringPhase(CompilationAndWeavingContext.PROCESSING_DECLARE_ANNOTATIONS, sourceType.sourceName); // Get the annotation specified in the declare UnresolvedType aspectType = decA.getAspect(); if (aspectType instanceof ReferenceType) { ReferenceType rt = (ReferenceType) aspectType; if (rt.isParameterizedType() || rt.isRawType()) { aspectType = rt.getGenericType(); } } TypeBinding tb = factory.makeTypeBinding(aspectType); // Hideousness follows: // There are multiple situations to consider here and they relate to the combinations of // where the annotation is coming from and where the annotation is going to be put: // // 1. Straight full build, all from source - the annotation is from a dec@type and // is being put on some type. Both types are real SourceTypeBindings. WORKS // 2. Incremental build, changing the affected type - the annotation is from a // dec@type in a BinaryTypeBinding (so has to be accessed via bcel) and the // affected type is a real SourceTypeBinding. Mostly works (pr128665) // 3. ? SourceTypeBinding stb = (SourceTypeBinding)tb; Annotation[] toAdd = null; long abits = 0; // Might have to retrieve the annotation through BCEL and construct an eclipse one for it. if (stb instanceof BinaryTypeBinding) { ReferenceType rt = (ReferenceType)factory.fromEclipse(stb); ResolvedMember[] methods = rt.getDeclaredMethods(); ResolvedMember decaMethod = null; String nameToLookFor = decA.getAnnotationMethod(); for (int i = 0; i < methods.length; i++) { if (methods[i].getName().equals(nameToLookFor)) {decaMethod = methods[i];break;} } if (decaMethod!=null) { // could assert this ... AnnotationX[] axs = decaMethod.getAnnotations(); toAdd = new Annotation[1]; toAdd[0] = createAnnotationFromBcelAnnotation(axs[0],decaMethod.getSourceLocation().getOffset(),factory); // BUG BUG BUG - We dont test these abits are correct, in fact we'll be very lucky if they are. // What does that mean? It means on an incremental compile you might get away with an // annotation that isn't allowed on a type being put on a type. abits = toAdd[0].resolvedType.getAnnotationTagBits(); } } else { // much nicer, its a real SourceTypeBinding so we can stay in eclipse land MethodBinding[] mbs = stb.getMethods(decA.getAnnotationMethod().toCharArray()); abits = mbs[0].getAnnotationTagBits(); // ensure resolved TypeDeclaration typeDecl = ((SourceTypeBinding)mbs[0].declaringClass).scope.referenceContext; AbstractMethodDeclaration methodDecl = typeDecl.declarationOf(mbs[0]); toAdd = methodDecl.annotations; // this is what to add toAdd[0] = createAnnotationCopy(toAdd[0]); if (toAdd[0].resolvedType!=null) // pr148536 abits = toAdd[0].resolvedType.getAnnotationTagBits(); } if (sourceType instanceof BinaryTypeBinding) { // In this case we can't access the source type binding to add a new annotation, so let's put something // on the weaver type temporarily ResolvedType theTargetType = factory.fromEclipse(sourceType); TypeBinding theAnnotationType = toAdd[0].resolvedType; String sig = new String(theAnnotationType.signature()); UnresolvedType bcelAnnotationType = UnresolvedType.forSignature(sig); String name = bcelAnnotationType.getName(); if (theTargetType.hasAnnotation(bcelAnnotationType)) { CompilationAndWeavingContext.leavingPhase(tok); return false; } // FIXME asc tidy up this code that duplicates whats below! // Simple checks on the bits boolean giveupnow = false; if (((abits & TagBits.AnnotationTargetMASK)!=0)) { if ( isAnnotationTargettingSomethingOtherThanAnnotationOrNormal(abits)) { // error will have been already reported giveupnow = true; } else if ( (sourceType.isAnnotationType() && (abits & TagBits.AnnotationForAnnotationType)==0) || (!sourceType.isAnnotationType() && (abits & TagBits.AnnotationForType)==0) ) { if (reportProblems) { if (decA.isExactPattern()) { factory.showMessage(IMessage.ERROR, WeaverMessages.format(WeaverMessages.INCORRECT_TARGET_FOR_DECLARE_ANNOTATION,rtx.getName(),toAdd[0].type,stringifyTargets(abits)), decA.getSourceLocation(), null); } // dont put out the lint - the weaving process will do that // else { // if (factory.getWorld().getLint().invalidTargetForAnnotation.isEnabled()) { // factory.getWorld().getLint().invalidTargetForAnnotation.signal(new String[]{rtx.getName(),toAdd[0].type.toString(),stringifyTargets(abits)},decA.getSourceLocation(),null); // } // } } giveupnow=true; } } if (giveupnow) { CompilationAndWeavingContext.leavingPhase(tok); return false; } theTargetType.addAnnotation(new AnnotationX(new FakeAnnotation(name,sig,(abits & TagBits.AnnotationRuntimeRetention)!=0),factory.getWorld())); CompilationAndWeavingContext.leavingPhase(tok); return true; } Annotation currentAnnotations[] = sourceType.scope.referenceContext.annotations; if (currentAnnotations!=null) for (int i = 0; i < currentAnnotations.length; i++) { Annotation annotation = currentAnnotations[i]; String a = CharOperation.toString(annotation.type.getTypeName()); String b = CharOperation.toString(toAdd[0].type.getTypeName()); // FIXME asc we have a lint for attempting to add an annotation twice to a method, // we could put it out here *if* we can resolve the problem of errors coming out // multiple times if we have cause to loop through here if (a.equals(b)) { CompilationAndWeavingContext.leavingPhase(tok); return false; } } if (((abits & TagBits.AnnotationTargetMASK)!=0)) { if ( (abits & (TagBits.AnnotationForAnnotationType | TagBits.AnnotationForType))==0) { // this means it specifies something other than annotation or normal type - error will have been already reported, just resolution process above CompilationAndWeavingContext.leavingPhase(tok); return false; } if ( (sourceType.isAnnotationType() && (abits & TagBits.AnnotationForAnnotationType)==0) || (!sourceType.isAnnotationType() && (abits & TagBits.AnnotationForType)==0) ) { if (reportProblems) { if (decA.isExactPattern()) { factory.showMessage(IMessage.ERROR, WeaverMessages.format(WeaverMessages.INCORRECT_TARGET_FOR_DECLARE_ANNOTATION,rtx.getName(),toAdd[0].type,stringifyTargets(abits)), decA.getSourceLocation(), null); } // dont put out the lint - the weaving process will do that // else { // if (factory.getWorld().getLint().invalidTargetForAnnotation.isEnabled()) { // factory.getWorld().getLint().invalidTargetForAnnotation.signal(new String[]{rtx.getName(),toAdd[0].type.toString(),stringifyTargets(abits)},decA.getSourceLocation(),null); // } // } } CompilationAndWeavingContext.leavingPhase(tok); return false; } } // Build a new array of annotations // remember the current set (rememberAnnotations only does something the first time it is called for a type) sourceType.scope.referenceContext.rememberAnnotations(); AsmRelationshipProvider.getDefault().addDeclareAnnotationRelationship(decA.getSourceLocation(),rtx.getSourceLocation()); Annotation abefore[] = sourceType.scope.referenceContext.annotations; Annotation[] newset = new Annotation[toAdd.length+(abefore==null?0:abefore.length)]; System.arraycopy(toAdd,0,newset,0,toAdd.length); if (abefore!=null) { System.arraycopy(abefore,0,newset,toAdd.length,abefore.length); } sourceType.scope.referenceContext.annotations = newset; CompilationAndWeavingContext.leavingPhase(tok); return true; } /** * Transform an annotation from its AJ form to an eclipse form. We *DONT* care about the * values of the annotation. that is because it is only being stuck on a type during * type completion to allow for other constructs (decps, decas) that might be looking for it - * when the class actually gets to disk it wont have this new annotation on it and during * weave time we will do the right thing copying across values too. */ private static Annotation createAnnotationFromBcelAnnotation(AnnotationX annX,int pos, EclipseFactory factory) { String name = annX.getTypeName(); TypeBinding tb = factory.makeTypeBinding(annX.getSignature()); String theName = annX.getSignature().getBaseName(); char[][] typeName = CharOperation.splitOn('.',name.replace('$','.').toCharArray()); //pr149293 - not bulletproof... long[] positions = new long[typeName.length]; for (int i = 0; i < positions.length; i++) positions[i]=pos; TypeReference annType = new QualifiedTypeReference(typeName,positions); NormalAnnotation ann = new NormalAnnotation(annType,pos); ann.resolvedType=tb; // yuck - is this OK in all cases? // We don't need membervalues... // Expression pcExpr = new StringLiteral(pointcutExpression.toCharArray(),pos,pos); // MemberValuePair[] mvps = new MemberValuePair[2]; // mvps[0] = new MemberValuePair("value".toCharArray(),pos,pos,pcExpr); // Expression argNamesExpr = new StringLiteral(argNames.toCharArray(),pos,pos); // mvps[1] = new MemberValuePair("argNames".toCharArray(),pos,pos,argNamesExpr); // ann.memberValuePairs = mvps; return ann; } /** Create a copy of an annotation, not deep but deep enough so we don't copy across fields that will get us into trouble like 'recipient' */ private static Annotation createAnnotationCopy(Annotation ann) { NormalAnnotation ann2 = new NormalAnnotation(ann.type,ann.sourceStart); ann2.memberValuePairs = ann.memberValuePairs(); ann2.resolvedType = ann.resolvedType; ann2.bits = ann.bits; return ann2; // String name = annX.getTypeName(); // TypeBinding tb = factory.makeTypeBinding(annX.getSignature()); // String theName = annX.getSignature().getBaseName(); // char[][] typeName = CharOperation.splitOn('.',name.replace('$','.').toCharArray()); //pr149293 - not bulletproof... // long[] positions = new long[typeName.length]; // for (int i = 0; i < positions.length; i++) positions[i]=pos; // TypeReference annType = new QualifiedTypeReference(typeName,positions); // NormalAnnotation ann = new NormalAnnotation(annType,pos); // ann.resolvedType=tb; // yuck - is this OK in all cases? // // We don't need membervalues... //// Expression pcExpr = new StringLiteral(pointcutExpression.toCharArray(),pos,pos); //// MemberValuePair[] mvps = new MemberValuePair[2]; //// mvps[0] = new MemberValuePair("value".toCharArray(),pos,pos,pcExpr); //// Expression argNamesExpr = new StringLiteral(argNames.toCharArray(),pos,pos); //// mvps[1] = new MemberValuePair("argNames".toCharArray(),pos,pos,argNamesExpr); //// ann.memberValuePairs = mvps; // return ann; } private boolean isAnnotationTargettingSomethingOtherThanAnnotationOrNormal(long abits) { return (abits & (TagBits.AnnotationForAnnotationType | TagBits.AnnotationForType))==0; } private void reportDeclareParentsMessage(WeaveMessage.WeaveMessageKind wmk,SourceTypeBinding sourceType,ResolvedType parent) { if (!factory.getWorld().getMessageHandler().isIgnoring(IMessage.WEAVEINFO)) { String filename = new String(sourceType.getFileName()); int takefrom = filename.lastIndexOf('/'); if (takefrom == -1 ) takefrom = filename.lastIndexOf('\\'); filename = filename.substring(takefrom+1); factory.getWorld().getMessageHandler().handleMessage( WeaveMessage.constructWeavingMessage(wmk, new String[]{CharOperation.toString(sourceType.compoundName), filename, parent.getClassName(), getShortname(parent.getSourceLocation().getSourceFile().getPath())})); } } private String getShortname(String path) { int takefrom = path.lastIndexOf('/'); if (takefrom == -1) { takefrom = path.lastIndexOf('\\'); } return path.substring(takefrom+1); } private void addParent(SourceTypeBinding sourceType, ResolvedType parent) { ReferenceBinding parentBinding = (ReferenceBinding)factory.makeTypeBinding(parent); if (parentBinding == null) return; // The parent is missing, it will be reported elsewhere. sourceType.rememberTypeHierarchy(); if (parentBinding.isClass()) { sourceType.superclass = parentBinding; // this used to be true, but I think I've fixed it now, decp is done at weave time! // TAG: WeavingMessage DECLARE PARENTS: EXTENDS // Compiler restriction: Can't do EXTENDS at weave time // So, only see this message if doing a source compilation // reportDeclareParentsMessage(WeaveMessage.WEAVEMESSAGE_DECLAREPARENTSEXTENDS,sourceType,parent); } else { ReferenceBinding[] oldI = sourceType.superInterfaces; ReferenceBinding[] newI; if (oldI == null) { newI = new ReferenceBinding[1]; newI[0] = parentBinding; } else { int n = oldI.length; newI = new ReferenceBinding[n+1]; System.arraycopy(oldI, 0, newI, 0, n); newI[n] = parentBinding; } sourceType.superInterfaces = newI; // warnOnAddedInterface(factory.fromEclipse(sourceType),parent); // now reported at weave time... // this used to be true, but I think I've fixed it now, decp is done at weave time! // TAG: WeavingMessage DECLARE PARENTS: IMPLEMENTS // This message will come out of BcelTypeMunger.munge if doing a binary weave // reportDeclareParentsMessage(WeaveMessage.WEAVEMESSAGE_DECLAREPARENTSIMPLEMENTS,sourceType,parent); } // also add it to the bcel delegate if there is one if (sourceType instanceof BinaryTypeBinding) { ResolvedType onType = factory.fromEclipse(sourceType); ReferenceType rt = (ReferenceType)onType; ReferenceTypeDelegate rtd = rt.getDelegate(); if (rtd instanceof BcelObjectType) { ((BcelObjectType)rtd).addParent(parent); } } } public void warnOnAddedInterface (ResolvedType type, ResolvedType parent) { World world = factory.getWorld(); ResolvedType serializable = world.getCoreType(UnresolvedType.SERIALIZABLE); if (serializable.isAssignableFrom(type) && !serializable.isAssignableFrom(parent) && !LazyClassGen.hasSerialVersionUIDField(type)) { world.getLint().needsSerialVersionUIDField.signal( new String[] { type.getName().toString(), "added interface " + parent.getName().toString() }, null, null); } } private List pendingTypesToFinish = new ArrayList(); boolean inBinaryTypeCreationAndWeaving = false; boolean processingTheQueue = false; public BinaryTypeBinding createBinaryTypeFrom( IBinaryType binaryType, PackageBinding packageBinding, boolean needFieldsAndMethods, AccessRestriction accessRestriction) { if (inBinaryTypeCreationAndWeaving) { BinaryTypeBinding ret = super.createBinaryTypeFrom( binaryType, packageBinding, needFieldsAndMethods, accessRestriction); pendingTypesToFinish.add(ret); return ret; } inBinaryTypeCreationAndWeaving = true; try { BinaryTypeBinding ret = super.createBinaryTypeFrom( binaryType, packageBinding, needFieldsAndMethods, accessRestriction); factory.getWorld().validateType(factory.fromBinding(ret)); // if you need the bytes to pass to validate, here they are:((ClassFileReader)binaryType).getReferenceBytes() weaveInterTypeDeclarations(ret); return ret; } finally { inBinaryTypeCreationAndWeaving = false; // Start processing the list... if (pendingTypesToFinish.size()>0) { processingTheQueue = true; while (!pendingTypesToFinish.isEmpty()) { BinaryTypeBinding nextVictim = (BinaryTypeBinding)pendingTypesToFinish.remove(0); // During this call we may recurse into this method and add // more entries to the pendingTypesToFinish list. weaveInterTypeDeclarations(nextVictim); } processingTheQueue = false; } } } /** * Callback driven when the compiler detects an anonymous type during block resolution. * We need to add it to the weaver so that we don't trip up later. * @param aBinding */ public void anonymousTypeBindingCreated(LocalTypeBinding aBinding) { factory.addSourceTypeBinding(aBinding,null); } } // commented out, supplied as info on how to manipulate annotations in an eclipse world // // public void doDeclareAnnotationOnMethods() { // Do the declare annotation on fields/methods/ctors //Collection daoms = factory.getDeclareAnnotationOnMethods(); //if (daoms!=null && daoms.size()>0 && !(sourceType instanceof BinaryTypeBinding)) { // System.err.println("Going through the methods on "+sourceType.debugName()+" looking for DECA matches"); // // We better take a look through them... // for (Iterator iter = daoms.iterator(); iter.hasNext();) { // DeclareAnnotation element = (DeclareAnnotation) iter.next(); // System.err.println("Looking for anything that might match "+element+" on "+sourceType.debugName()+" "+getType(sourceType.compoundName).debugName()+" "+(sourceType instanceof BinaryTypeBinding)); // // ReferenceBinding rbb = getType(sourceType.compoundName); // // fix me if we ever uncomment this code... should iterate the other way round, over the methods then over the decas // sourceType.methods(); // MethodBinding sourceMbs[] = sourceType.methods; // for (int i = 0; i < sourceMbs.length; i++) { // MethodBinding sourceMb = sourceMbs[i]; // MethodBinding mbbbb = ((SourceTypeBinding)rbb).getExactMethod(sourceMb.selector,sourceMb.parameters); // boolean isCtor = sourceMb.selector[0]=='<'; // // if ((element.isDeclareAtConstuctor() ^ !isCtor)) { // System.err.println("Checking "+sourceMb+" ... declaringclass="+sourceMb.declaringClass.debugName()+" rbb="+rbb.debugName()+" "+sourceMb.declaringClass.equals(rbb)); // // ResolvedMember rm = null; // rm = EclipseFactory.makeResolvedMember(mbbbb); // if (element.matches(rm,factory.getWorld())) { // System.err.println("MATCH"); // // // Determine the set of annotations that are currently on the method // ReferenceBinding rb = getType(sourceType.compoundName); //// TypeBinding tb = factory.makeTypeBinding(decA.getAspect()); // MethodBinding mb = ((SourceTypeBinding)rb).getExactMethod(sourceMb.selector,sourceMb.parameters); // //long abits = mbs[0].getAnnotationTagBits(); // ensure resolved // TypeDeclaration typeDecl = ((SourceTypeBinding)sourceMb.declaringClass).scope.referenceContext; // AbstractMethodDeclaration methodDecl = typeDecl.declarationOf(sourceMb); // Annotation[] currentlyHas = methodDecl.annotations; // this is what to add // //abits = toAdd[0].resolvedType.getAnnotationTagBits(); // // // Determine the annotations to add to that method // TypeBinding tb = factory.makeTypeBinding(element.getAspect()); // MethodBinding[] aspectMbs = ((SourceTypeBinding)tb).getMethods(element.getAnnotationMethod().toCharArray()); // long abits = aspectMbs[0].getAnnotationTagBits(); // ensure resolved // TypeDeclaration typeDecl2 = ((SourceTypeBinding)aspectMbs[0].declaringClass).scope.referenceContext; // AbstractMethodDeclaration methodDecl2 = typeDecl2.declarationOf(aspectMbs[0]); // Annotation[] toAdd = methodDecl2.annotations; // this is what to add // // abits = toAdd[0].resolvedType.getAnnotationTagBits(); //System.err.println("Has: "+currentlyHas+" toAdd: "+toAdd); // // // fix me? should check if it already has the annotation // //Annotation abefore[] = sourceType.scope.referenceContext.annotations; // Annotation[] newset = new Annotation[(currentlyHas==null?0:currentlyHas.length)+1]; // System.arraycopy(toAdd,0,newset,0,toAdd.length); // if (currentlyHas!=null) { // System.arraycopy(currentlyHas,0,newset,1,currentlyHas.length); // } // methodDecl.annotations = newset; // System.err.println("New set on "+CharOperation.charToString(sourceMb.selector)+" is "+newset); // } else // System.err.println("NO MATCH"); // } // } // } //} //} // commented out, supplied as info on how to manipulate annotations in an eclipse world // // public void doDeclareAnnotationOnFields() { // Collection daofs = factory.getDeclareAnnotationOnFields(); // if (daofs!=null && daofs.size()>0 && !(sourceType instanceof BinaryTypeBinding)) { // System.err.println("Going through the fields on "+sourceType.debugName()+" looking for DECA matches"); // // We better take a look through them... // for (Iterator iter = daofs.iterator(); iter.hasNext();) { // DeclareAnnotation element = (DeclareAnnotation) iter.next(); // System.err.println("Processing deca "+element+" on "+sourceType.debugName()+" "+getType(sourceType.compoundName).debugName()+" "+(sourceType instanceof BinaryTypeBinding)); // // ReferenceBinding rbb = getType(sourceType.compoundName); // // fix me? should iterate the other way round, over the methods then over the decas // sourceType.fields(); // resolve the bloody things // FieldBinding sourceFbs[] = sourceType.fields; // for (int i = 0; i < sourceFbs.length; i++) { // FieldBinding sourceFb = sourceFbs[i]; // //FieldBinding fbbbb = ((SourceTypeBinding)rbb).getgetExactMethod(sourceMb.selector,sourceMb.parameters); // // System.err.println("Checking "+sourceFb+" ... declaringclass="+sourceFb.declaringClass.debugName()+" rbb="+rbb.debugName()); // // ResolvedMember rm = null; // rm = EclipseFactory.makeResolvedMember(sourceFb); // if (element.matches(rm,factory.getWorld())) { // System.err.println("MATCH"); // // // Determine the set of annotations that are currently on the field // ReferenceBinding rb = getType(sourceType.compoundName); //// TypeBinding tb = factory.makeTypeBinding(decA.getAspect()); // FieldBinding fb = ((SourceTypeBinding)rb).getField(sourceFb.name,true); // //long abits = mbs[0].getAnnotationTagBits(); // ensure resolved // TypeDeclaration typeDecl = ((SourceTypeBinding)sourceFb.declaringClass).scope.referenceContext; // FieldDeclaration fd = typeDecl.declarationOf(sourceFb); // //AbstractMethodDeclaration methodDecl = typeDecl.declarationOf(sourceMb); // Annotation[] currentlyHas = fd.annotations; // this is what to add // //abits = toAdd[0].resolvedType.getAnnotationTagBits(); // // // Determine the annotations to add to that method // TypeBinding tb = factory.makeTypeBinding(element.getAspect()); // MethodBinding[] aspectMbs = ((SourceTypeBinding)tb).getMethods(element.getAnnotationMethod().toCharArray()); // long abits = aspectMbs[0].getAnnotationTagBits(); // ensure resolved // TypeDeclaration typeDecl2 = ((SourceTypeBinding)aspectMbs[0].declaringClass).scope.referenceContext; // AbstractMethodDeclaration methodDecl2 = typeDecl2.declarationOf(aspectMbs[0]); // Annotation[] toAdd = methodDecl2.annotations; // this is what to add // // abits = toAdd[0].resolvedType.getAnnotationTagBits(); //System.err.println("Has: "+currentlyHas+" toAdd: "+toAdd); // // // fix me? check if it already has the annotation // // // //Annotation abefore[] = sourceType.scope.referenceContext.annotations; // Annotation[] newset = new Annotation[(currentlyHas==null?0:currentlyHas.length)+1]; // System.arraycopy(toAdd,0,newset,0,toAdd.length); // if (currentlyHas!=null) { // System.arraycopy(currentlyHas,0,newset,1,currentlyHas.length); // } // fd.annotations = newset; // System.err.println("New set on "+CharOperation.charToString(sourceFb.name)+" is "+newset); // } else // System.err.println("NO MATCH"); // } // // } // }
224,962
Bug 224962 AjcTask doesn't work with Java6
Although support for Java6 has been added in the last milestone, you can't use it from ant because AjcTask doesn't recognize the "source=1.6" and "target=1.6" parameters. It's easy to fix by modifying AjcTask.java and adding the missing constants: static final String[] TARGET_INPUTS = new String [] { "1.1", "1.2", "1.3", "1.4", "1.5", "1.6" }; static final String[] SOURCE_INPUTS = new String [] { "1.3", "1.4", "1.5", "1.6" }; static final String[] COMPLIANCE_INPUTS = new String [] { "-1.3", "-1.4", "-1.5", "-1.6" }; Thanks.
resolved fixed
6bdb87d
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
"2008-04-01T04:48:31Z"
"2008-03-31T19:00:00Z"
taskdefs/src/org/aspectj/tools/ant/taskdefs/AjcTask.java
/* ******************************************************************* * Copyright (c) 2001-2001 Xerox Corporation, * 2002 Palo Alto Research Center, Incorporated (PARC) * 2003-2004 Contributors. * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Eclipse Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Xerox/PARC initial implementation * Wes Isberg 2003-2004 changes * ******************************************************************/ package org.aspectj.tools.ant.taskdefs; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.StringTokenizer; import org.apache.tools.ant.AntClassLoader; import org.apache.tools.ant.BuildException; import org.apache.tools.ant.Location; import org.apache.tools.ant.Project; import org.apache.tools.ant.taskdefs.Copy; import org.apache.tools.ant.taskdefs.Delete; import org.apache.tools.ant.taskdefs.Execute; import org.apache.tools.ant.taskdefs.Expand; import org.apache.tools.ant.taskdefs.Javac; import org.apache.tools.ant.taskdefs.LogStreamHandler; import org.apache.tools.ant.taskdefs.MatchingTask; import org.apache.tools.ant.taskdefs.Mkdir; import org.apache.tools.ant.taskdefs.PumpStreamHandler; import org.apache.tools.ant.taskdefs.Zip; import org.apache.tools.ant.taskdefs.compilers.DefaultCompilerAdapter; import org.apache.tools.ant.types.Commandline; import org.apache.tools.ant.types.CommandlineJava; import org.apache.tools.ant.types.FileSet; import org.apache.tools.ant.types.Path; import org.apache.tools.ant.types.PatternSet; import org.apache.tools.ant.types.Reference; import org.apache.tools.ant.types.ZipFileSet; import org.apache.tools.ant.util.TaskLogger; import org.aspectj.bridge.AbortException; import org.aspectj.bridge.IMessage; import org.aspectj.bridge.IMessageHandler; import org.aspectj.bridge.IMessageHolder; import org.aspectj.bridge.MessageHandler; import org.aspectj.bridge.MessageUtil; import org.aspectj.bridge.IMessage.Kind; import org.aspectj.tools.ajc.Main; import org.aspectj.util.FileUtil; import org.aspectj.util.LangUtil; /** * This runs the AspectJ 1.1 compiler, * supporting all the command-line options. * In 1.1.1, ajc copies resources from input jars, * but you can copy resources from the source directories * using sourceRootCopyFilter. * When not forking, things will be copied as needed * for each iterative compile, * but when forking things are only copied at the * completion of a successful compile. * <p> * See the development environment guide for * usage documentation. * * @since AspectJ 1.1, Ant 1.5 */ public class AjcTask extends MatchingTask { /* * This task mainly converts ant specification for ajc, * verbosely ignoring improper input. * It also has some special features for non-obvious clients: * (1) Javac compiler adapter supported in * <code>setupAjc(AjcTask, Javac, File)</code> * and * <code>readArguments(String[])</code>; * (2) testing is supported by * (a) permitting the same specification to be re-run * with added flags (settings once made cannot be * removed); and * (b) permitting recycling the task with * <code>reset()</code> (untested). * * The parts that do more than convert ant specs are * (a) code for forking; * (b) code for copying resources. * * If you maintain/upgrade this task, keep in mind: * (1) changes to the semantics of ajc (new options, new * values permitted, etc.) will have to be reflected here. * (2) the clients: * the iajc ant script, Javac compiler adapter, * maven clients of iajc, and testing code. */ // XXX move static methods after static initializer /** * This method extracts javac arguments to ajc, * and add arguments to make ajc behave more like javac * in copying resources. * <p> * Pass ajc-specific options using compilerarg sub-element: * <pre> * &lt;javac srcdir="src"> * &lt;compilerarg compiler="..." line="-argfile src/args.lst"/> * &lt;javac> * </pre> * Some javac arguments are not supported in this component (yet): * <pre> * String memoryInitialSize; * boolean includeAntRuntime = true; * boolean includeJavaRuntime = false; * </pre> * Other javac arguments are not supported in ajc 1.1: * <pre> * boolean optimize; * String forkedExecutable; * FacadeTaskHelper facade; * boolean depend; * String debugLevel; * Path compileSourcepath; * </pre> * @param javac the Javac command to implement (not null) * @param ajc the AjcTask to adapt (not null) * @param destDir the File class destination directory (may be null) * @return null if no error, or String error otherwise */ public String setupAjc(Javac javac) { if (null == javac) { return "null javac"; } AjcTask ajc = this; // no null checks b/c AjcTask handles null input gracefully ajc.setProject(javac.getProject()); ajc.setLocation(javac.getLocation()); ajc.setTaskName("javac-iajc"); ajc.setDebug(javac.getDebug()); ajc.setDeprecation(javac.getDeprecation()); ajc.setFailonerror(javac.getFailonerror()); final boolean fork = javac.isForkedJavac(); ajc.setFork(fork); if (fork) { ajc.setMaxmem(javac.getMemoryMaximumSize()); } ajc.setNowarn(javac.getNowarn()); ajc.setListFileArgs(javac.getListfiles()); ajc.setVerbose(javac.getVerbose()); ajc.setTarget(javac.getTarget()); ajc.setSource(javac.getSource()); ajc.setEncoding(javac.getEncoding()); File javacDestDir = javac.getDestdir(); if (null != javacDestDir) { ajc.setDestdir(javacDestDir); // filter requires dest dir // mimic Javac task's behavior in copying resources, ajc.setSourceRootCopyFilter("**/CVS/*,**/*.java,**/*.aj"); } ajc.setBootclasspath(javac.getBootclasspath()); ajc.setExtdirs(javac.getExtdirs()); ajc.setClasspath(javac.getClasspath()); // ignore srcDir -- all files picked up in recalculated file list // ajc.setSrcDir(javac.getSrcdir()); ajc.addFiles(javac.getFileList()); // arguments can override the filter, add to paths, override options ajc.readArguments(javac.getCurrentCompilerArgs()); return null; } /** * Find aspectjtools.jar on the task or system classpath. * Accept <code>aspectj{-}tools{...}.jar</code> * mainly to support build systems using maven-style * re-naming * (e.g., <code>aspectj-tools-1.1.0.jar</code>. * Note that we search the task classpath first, * though an entry on the system classpath would be loaded first, * because it seems more correct as the more specific one. * @return readable File for aspectjtools.jar, or null if not found. */ public static File findAspectjtoolsJar() { File result = null; ClassLoader loader = AjcTask.class.getClassLoader(); if (loader instanceof AntClassLoader) { AntClassLoader taskLoader = (AntClassLoader) loader; String cp = taskLoader.getClasspath(); String[] cps = LangUtil.splitClasspath(cp); for (int i = 0; (i < cps.length) && (null == result); i++) { result = isAspectjtoolsjar(cps[i]); } } if (null == result) { final Path classpath = Path.systemClasspath; final String[] paths = classpath.list(); for (int i = 0; (i < paths.length) && (null == result); i++) { result = isAspectjtoolsjar(paths[i]); } } return (null == result? null : result.getAbsoluteFile()); } /** @return File if readable jar with aspectj tools name, or null */ private static File isAspectjtoolsjar(String path) { if (null == path) { return null; } final String prefix = "aspectj"; final String infix = "tools"; final String altInfix = "-tools"; final String suffix = ".jar"; final int prefixLength = 7; // prefix.length(); final int minLength = 16; // prefixLength + infix.length() + suffix.length(); if (!path.endsWith(suffix)) { return null; } int loc = path.lastIndexOf(prefix); if ((-1 != loc) && ((loc + minLength) <= path.length())) { String rest = path.substring(loc+prefixLength); if (-1 != rest.indexOf(File.pathSeparator)) { return null; } if (rest.startsWith(infix) || rest.startsWith(altInfix)) { File result = new File(path); if (result.canRead() && result.isFile()) { return result; } } } return null; } /** * Maximum length (in chars) of command line * before converting to an argfile when forking */ private static final int MAX_COMMANDLINE = 4096; private static final File DEFAULT_DESTDIR = new File(".") { public String toString() { return "(no destination dir specified)"; } }; /** do not throw BuildException on fail/abort message with usage */ private static final String USAGE_SUBSTRING = "AspectJ-specific options"; /** valid -X[...] options other than -Xlint variants */ private static final List VALID_XOPTIONS; /** valid warning (-warn:[...]) variants */ private static final List VALID_WARNINGS; /** valid debugging (-g:[...]) variants */ private static final List VALID_DEBUG; /** * -Xlint variants (error, warning, ignore) * @see org.aspectj.weaver.Lint */ private static final List VALID_XLINT; public static final String COMMAND_EDITOR_NAME = AjcTask.class.getName() + ".COMMAND_EDITOR"; static final String[] TARGET_INPUTS = new String [] { "1.1", "1.2", "1.3", "1.4", "1.5" }; static final String[] SOURCE_INPUTS = new String [] { "1.3", "1.4", "1.5" }; static final String[] COMPLIANCE_INPUTS = new String [] { "-1.3", "-1.4", "-1.5" }; private static final ICommandEditor COMMAND_EDITOR; static { // many now deprecated: reweavable* String[] xs = new String[] { "serializableAspects", "incrementalFile", "lazyTjp", "reweavable", "reweavable:compress", "notReweavable", "noInline", "terminateAfterCompilation","hasMember", "ajruntimetarget:1.2", "ajruntimetarget:1.5", "addSerialVersionUID" //, "targetNearSource", "OcodeSize", }; VALID_XOPTIONS = Collections.unmodifiableList(Arrays.asList(xs)); xs = new String[] { "constructorName", "packageDefaultMethod", "deprecation", "maskedCatchBlocks", "unusedLocals", "unusedArguments", "unusedImports", "syntheticAccess", "assertIdentifier", "allDeprecation","allJavadoc","charConcat","conditionAssign", "emptyBlock", "fieldHiding", "finally", "indirectStatic", "intfNonInherited", "javadoc", "localHiding", "nls", "noEffectAssign", "pkgDefaultMethod", "semicolon", "unqualifiedField", "unusedPrivate", "unusedThrown", "uselessTypeCheck", "specialParamHiding", "staticReceiver", "syntheticAccess", "none" }; VALID_WARNINGS = Collections.unmodifiableList(Arrays.asList(xs)); xs = new String[] {"none", "lines", "vars", "source" }; VALID_DEBUG = Collections.unmodifiableList(Arrays.asList(xs)); xs = new String[] { "error", "warning", "ignore"}; VALID_XLINT = Collections.unmodifiableList(Arrays.asList(xs)); ICommandEditor editor = null; try { String editorClassName = System.getProperty(COMMAND_EDITOR_NAME); if (null != editorClassName) { ClassLoader cl = AjcTask.class.getClassLoader(); Class editorClass = cl.loadClass(editorClassName); editor = (ICommandEditor) editorClass.newInstance(); } } catch (Throwable t) { System.err.println("Warning: unable to load command editor"); t.printStackTrace(System.err); } COMMAND_EDITOR = editor; } // ---------------------------- state and Ant interface thereto private boolean verbose; private boolean listFileArgs; private boolean failonerror; private boolean fork; private String maxMem; private TaskLogger logger; // ------- single entries dumped into cmd protected GuardedCommand cmd; // ------- lists resolved in addListArgs() at execute() time private Path srcdir; private Path injars; private Path inpath; private Path classpath; private Path bootclasspath; private Path forkclasspath; private Path extdirs; private Path aspectpath; private Path argfiles; private List ignored; private Path sourceRoots; private File xweaveDir; private String xdoneSignal; // ----- added by adapter - integrate better? private List /* File */ adapterFiles; private String[] adapterArguments; private IMessageHolder messageHolder; private ICommandEditor commandEditor; // -------- resource-copying /** true if copying injar non-.class files to the output jar */ private boolean copyInjars; private boolean copyInpath; /** non-null if copying all source root files but the filtered ones */ private String sourceRootCopyFilter; /** non-null if copying all inpath dir files but the filtered ones */ private String inpathDirCopyFilter; /** directory sink for classes */ private File destDir; /** zip file sink for classes */ private File outjar; /** track whether we've supplied any temp outjar */ private boolean outjarFixedup; /** * When possibly copying resources to the output jar, * pass ajc a fake output jar to copy from, * so we don't change the modification time of the output jar * when copying injars/inpath into the actual outjar. */ private File tmpOutjar; private boolean executing; /** non-null only while executing in same vm */ private Main main; /** true only when executing in other vm */ private boolean executingInOtherVM; /** true if -incremental */ private boolean inIncrementalMode; /** true if -XincrementalFile (i.e, setTagFile)*/ private boolean inIncrementalFileMode; /** log command in non-verbose mode */ private boolean logCommand; /** used when forking */ private CommandlineJava javaCmd = new CommandlineJava(); // also note MatchingTask grabs source files... public AjcTask() { reset(); } /** to use this same Task more than once (testing) */ public void reset() { // XXX possible to reset MatchingTask? // need declare for "all fields initialized in ..." adapterArguments = null; adapterFiles = new ArrayList(); argfiles = null; executing = false; aspectpath = null; bootclasspath = null; classpath = null; cmd = new GuardedCommand(); copyInjars = false; copyInpath = false; destDir = DEFAULT_DESTDIR; executing = false; executingInOtherVM = false; extdirs = null; failonerror = true; // non-standard default forkclasspath = null; inIncrementalMode = false; inIncrementalFileMode = false; ignored = new ArrayList(); injars = null; inpath = null; listFileArgs = false; maxMem = null; messageHolder = null; outjar = null; sourceRootCopyFilter = null; inpathDirCopyFilter = null; sourceRoots = null; srcdir = null; tmpOutjar = null; verbose = false; xweaveDir = null; xdoneSignal = null; logCommand = false; javaCmd = new CommandlineJava(); } protected void ignore(String ignored) { this.ignored.add(ignored + " at " + getLocation()); } //---------------------- option values // used by entries with internal commas protected String validCommaList(String list, List valid, String label) { return validCommaList(list, valid, label, valid.size()); } protected String validCommaList(String list, List valid, String label, int max) { StringBuffer result = new StringBuffer(); StringTokenizer st = new StringTokenizer(list, ","); int num = 0; while (st.hasMoreTokens()) { String token = st.nextToken().trim(); num++; if (num > max) { ignore("too many entries for -" + label + ": " + token); break; } if (!valid.contains(token)) { ignore("bad commaList entry for -" + label + ": " + token); } else { if (0 < result.length()) { result.append(","); } result.append(token); } } return (0 == result.length() ? null : result.toString()); } public void setIncremental(boolean incremental) { cmd.addFlag("-incremental", incremental); inIncrementalMode = incremental; } public void setLogCommand(boolean logCommand) { this.logCommand = logCommand; } public void setHelp(boolean help) { cmd.addFlag("-help", help); } public void setVersion(boolean version) { cmd.addFlag("-version", version); } public void setXTerminateAfterCompilation(boolean b) { cmd.addFlag("-XterminateAfterCompilation", b); } public void setXReweavable(boolean reweavable) { cmd.addFlag("-Xreweavable",reweavable); } public void setXJoinpoints(String optionalJoinpoints) { cmd.addFlag("-Xjoinpoints:"+optionalJoinpoints,true); } public void setXNoWeave(boolean b) { if (logger!=null) logger.warning("the noweave option is no longer required and is being ignored"); } public void setNoWeave(boolean b) { if (logger!=null) logger.warning("the noweave option is no longer required and is being ignored"); } public void setXNotReweavable(boolean notReweavable) { cmd.addFlag("-XnotReweavable",notReweavable); } public void setXaddSerialVersionUID(boolean addUID) { cmd.addFlag("-XaddSerialVersionUID",addUID); } public void setXNoInline(boolean noInline) { cmd.addFlag("-XnoInline",noInline); } public void setShowWeaveInfo(boolean showweaveinfo) { cmd.addFlag("-showWeaveInfo",showweaveinfo); } public void setNowarn(boolean nowarn) { cmd.addFlag("-nowarn", nowarn); } public void setDeprecation(boolean deprecation) { cmd.addFlag("-deprecation", deprecation); } public void setWarn(String warnings) { warnings = validCommaList(warnings, VALID_WARNINGS, "warn"); cmd.addFlag("-warn:" + warnings, (null != warnings)); } public void setDebug(boolean debug) { cmd.addFlag("-g", debug); } public void setDebugLevel(String level) { level = validCommaList(level, VALID_DEBUG, "g"); cmd.addFlag("-g:" + level, (null != level)); } public void setEmacssym(boolean emacssym) { cmd.addFlag("-emacssym", emacssym); } public void setCrossrefs(boolean on) { cmd.addFlag("-crossrefs", on); } /** * -Xlint - set default level of -Xlint messages to warning * (same as </code>-Xlint:warning</code>) */ public void setXlintwarnings(boolean xlintwarnings) { cmd.addFlag("-Xlint", xlintwarnings); } /** -Xlint:{error|warning|info} - set default level for -Xlint messages * @param xlint the String with one of error, warning, ignored */ public void setXlint(String xlint) { xlint = validCommaList(xlint, VALID_XLINT, "Xlint", 1); cmd.addFlag("-Xlint:" + xlint, (null != xlint)); } /** * -Xlintfile {lint.properties} - enable or disable specific forms * of -Xlint messages based on a lint properties file * (default is * <code>org/aspectj/weaver/XLintDefault.properties</code>) * @param xlintFile the File with lint properties */ public void setXlintfile(File xlintFile) { cmd.addFlagged("-Xlintfile", xlintFile.getAbsolutePath()); } public void setPreserveAllLocals(boolean preserveAllLocals) { cmd.addFlag("-preserveAllLocals", preserveAllLocals); } public void setNoImportError(boolean noImportError) { cmd.addFlag("-warn:-unusedImport", noImportError); } public void setEncoding(String encoding) { cmd.addFlagged("-encoding", encoding); } public void setLog(File file) { cmd.addFlagged("-log", file.getAbsolutePath()); } public void setProceedOnError(boolean proceedOnError) { cmd.addFlag("-proceedOnError", proceedOnError); } public void setVerbose(boolean verbose) { cmd.addFlag("-verbose", verbose); this.verbose = verbose; } public void setListFileArgs(boolean listFileArgs) { this.listFileArgs = listFileArgs; } public void setReferenceInfo(boolean referenceInfo) { cmd.addFlag("-referenceInfo", referenceInfo); } public void setTime(boolean time) { cmd.addFlag("-time", time); } public void setNoExit(boolean noExit) { cmd.addFlag("-noExit", noExit); } public void setFailonerror(boolean failonerror) { this.failonerror = failonerror; } /** * @return true if fork was set */ public boolean isForked() { return fork; } public void setFork(boolean fork) { this.fork = fork; } public void setMaxmem(String maxMem) { this.maxMem = maxMem; } /** support for nested &lt;jvmarg&gt; elements */ public Commandline.Argument createJvmarg() { return this.javaCmd.createVmArgument(); } // ---------------- public void setTagFile(File file) { inIncrementalMode = true; cmd.addFlagged(Main.CommandController.TAG_FILE_OPTION, file.getAbsolutePath()); inIncrementalFileMode = true; } public void setOutjar(File file) { if (DEFAULT_DESTDIR != destDir) { String e = "specifying both output jar (" + file + ") and destination dir (" + destDir + ")"; throw new BuildException(e); } outjar = file; outjarFixedup = false; tmpOutjar = null; } public void setOutxml(boolean outxml) { cmd.addFlag("-outxml",outxml); } public void setOutxmlfile(String name) { cmd.addFlagged("-outxmlfile", name); } public void setDestdir(File dir) { if (null != outjar) { String e = "specifying both output jar (" + outjar + ") and destination dir (" + dir + ")"; throw new BuildException(e); } cmd.addFlagged("-d", dir.getAbsolutePath()); destDir = dir; } /** * @param input a String in TARGET_INPUTS */ public void setTarget(String input) { String ignore = cmd.addOption("-target", TARGET_INPUTS, input); if (null != ignore) { ignore(ignore); } } /** * Language compliance level. * If not set explicitly, eclipse default holds. * @param input a String in COMPLIANCE_INPUTS */ public void setCompliance(String input) { String ignore = cmd.addOption(null, COMPLIANCE_INPUTS, input); if (null != ignore) { ignore(ignore); } } /** * Source compliance level. * If not set explicitly, eclipse default holds. * @param input a String in SOURCE_INPUTS */ public void setSource(String input) { String ignore = cmd.addOption("-source", SOURCE_INPUTS, input); if (null != ignore) { ignore(ignore); } } /** * Flag to copy all non-.class contents of injars * to outjar after compile completes. * Requires both injars and outjar. * @param doCopy */ public void setCopyInjars(boolean doCopy){ ignore("copyInJars"); log("copyInjars not required since 1.1.1.\n", Project.MSG_WARN); //this.copyInjars = doCopy; } /** * Option to copy all files from * all source root directories * except those specified here. * If this is specified and sourceroots are specified, * then this will copy all files except * those specified in the filter pattern. * Requires sourceroots. * * @param filter a String acceptable as an excludes * filter for an Ant Zip fileset. */ public void setSourceRootCopyFilter(String filter){ this.sourceRootCopyFilter = filter; } /** * Option to copy all files from * all inpath directories * except the files specified here. * If this is specified and inpath directories are specified, * then this will copy all files except * those specified in the filter pattern. * Requires inpath. * If the input does not contain "**\/*.class", then * this prepends it, to avoid overwriting woven classes * with unwoven input. * @param filter a String acceptable as an excludes * filter for an Ant Zip fileset. */ public void setInpathDirCopyFilter(String filter){ if (null != filter) { if (-1 == filter.indexOf("**/*.class")) { filter = "**/*.class," + filter; } } this.inpathDirCopyFilter = filter; } public void setX(String input) { // ajc-only eajc-also docDone StringTokenizer tokens = new StringTokenizer(input, ",", false); while (tokens.hasMoreTokens()) { String token = tokens.nextToken().trim(); if (1 < token.length()) { // new special case: allow -Xset:anything if (VALID_XOPTIONS.contains(token) || token.indexOf("set:")==0 || token.indexOf("joinpoints:")==0) { cmd.addFlag("-X" + token, true); } else { ignore("-X" + token); } } } } public void setXDoneSignal(String doneSignal) { this.xdoneSignal = doneSignal; } /** direct API for testing */ public void setMessageHolder(IMessageHolder holder) { this.messageHolder = holder; } /** * Setup custom message handling. * @param className the String fully-qualified-name of a class * reachable from this object's class loader, * implementing IMessageHolder, and * having a public no-argument constructor. * @throws BuildException if unable to create instance of className */ public void setMessageHolderClass(String className) { try { Class mclass = Class.forName(className); IMessageHolder holder = (IMessageHolder) mclass.newInstance(); setMessageHolder(holder); } catch (Throwable t) { String m = "unable to instantiate message holder: " + className; throw new BuildException(m, t); } } /** direct API for testing */ public void setCommandEditor(ICommandEditor editor) { this.commandEditor = editor; } /** * Setup command-line filter. * To do this staticly, define the environment variable * <code>org.aspectj.tools.ant.taskdefs.AjcTask.COMMAND_EDITOR</code> * with the <code>className</code> parameter. * @param className the String fully-qualified-name of a class * reachable from this object's class loader, * implementing ICommandEditor, and * having a public no-argument constructor. * @throws BuildException if unable to create instance of className */ public void setCommandEditorClass(String className) { // skip Ant interface? try { Class mclass = Class.forName(className); setCommandEditor((ICommandEditor) mclass.newInstance()); } catch (Throwable t) { String m = "unable to instantiate command editor: " + className; throw new BuildException(m, t); } } //---------------------- Path lists /** * Add path elements to source path and return result. * Elements are added even if they do not exist. * @param source the Path to add to - may be null * @param toAdd the Path to add - may be null * @return the (never-null) Path that results */ protected Path incPath(Path source, Path toAdd) { if (null == source) { source = new Path(project); } if (null != toAdd) { source.append(toAdd); } return source; } public void setSourcerootsref(Reference ref) { createSourceRoots().setRefid(ref); } public void setSourceRoots(Path roots) { sourceRoots = incPath(sourceRoots, roots); } public Path createSourceRoots() { if (sourceRoots == null) { sourceRoots = new Path(project); } return sourceRoots.createPath(); } public void setXWeaveDir(File file) { if ((null != file) && file.isDirectory() && file.canRead()) { xweaveDir = file; } } public void setInjarsref(Reference ref) { createInjars().setRefid(ref); } public void setInpathref(Reference ref) { createInpath().setRefid(ref); } public void setInjars(Path path) { injars = incPath(injars, path); } public void setInpath(Path path) { inpath = incPath(inpath,path); } public Path createInjars() { if (injars == null) { injars = new Path(project); } return injars.createPath(); } public Path createInpath() { if (inpath == null) { inpath = new Path(project); } return inpath.createPath(); } public void setClasspath(Path path) { classpath = incPath(classpath, path); } public void setClasspathref(Reference classpathref) { createClasspath().setRefid(classpathref); } public Path createClasspath() { if (classpath == null) { classpath = new Path(project); } return classpath.createPath(); } public void setBootclasspath(Path path) { bootclasspath = incPath(bootclasspath, path); } public void setBootclasspathref(Reference bootclasspathref) { createBootclasspath().setRefid(bootclasspathref); } public Path createBootclasspath() { if (bootclasspath == null) { bootclasspath = new Path(project); } return bootclasspath.createPath(); } public void setForkclasspath(Path path) { forkclasspath = incPath(forkclasspath, path); } public void setForkclasspathref(Reference forkclasspathref) { createForkclasspath().setRefid(forkclasspathref); } public Path createForkclasspath() { if (forkclasspath == null) { forkclasspath = new Path(project); } return forkclasspath.createPath(); } public void setExtdirs(Path path) { extdirs = incPath(extdirs, path); } public void setExtdirsref(Reference ref) { createExtdirs().setRefid(ref); } public Path createExtdirs() { if (extdirs == null) { extdirs = new Path(project); } return extdirs.createPath(); } public void setAspectpathref(Reference ref) { createAspectpath().setRefid(ref); } public void setAspectpath(Path path) { aspectpath = incPath(aspectpath, path); } public Path createAspectpath() { if (aspectpath == null) { aspectpath = new Path(project); } return aspectpath.createPath(); } public void setSrcDir(Path path) { srcdir = incPath(srcdir, path); } public Path createSrc() { return createSrcdir(); } public Path createSrcdir() { if (srcdir == null) { srcdir = new Path(project); } return srcdir.createPath(); } /** @return true if in incremental mode (command-line or file) */ public boolean isInIncrementalMode() { return inIncrementalMode; } /** @return true if in incremental file mode */ public boolean isInIncrementalFileMode() { return inIncrementalFileMode; } public void setArgfilesref(Reference ref) { createArgfiles().setRefid(ref); } public void setArgfiles(Path path) { // ajc-only eajc-also docDone argfiles = incPath(argfiles, path); } public Path createArgfiles() { if (argfiles == null) { argfiles = new Path(project); } return argfiles.createPath(); } // ------------------------------ run /** * Compile using ajc per settings. * @exception BuildException if the compilation has problems * or if there were compiler errors and failonerror is true. */ public void execute() throws BuildException { this.logger = new TaskLogger(this); if (executing) { throw new IllegalStateException("already executing"); } else { executing = true; } setupOptions(); verifyOptions(); try { String[] args = makeCommand(); if (logCommand) { log("ajc " + Arrays.asList(args)); } else { logVerbose("ajc " + Arrays.asList(args)); } if (!fork) { executeInSameVM(args); } else { // when forking, Adapter handles failonerror executeInOtherVM(args); } } catch (BuildException e) { throw e; } catch (Throwable x) { this.logger.error(Main.renderExceptionForUser(x)); throw new BuildException("IGNORE -- See " + LangUtil.unqualifiedClassName(x) + " rendered to ant logger"); } finally { executing = false; if (null != tmpOutjar) { tmpOutjar.delete(); } } } /** * Halt processing. * This tells main in the same vm to quit. * It fails when running in forked mode. * @return true if not in forked mode * and main has quit or been told to quit */ public boolean quit() { if (executingInOtherVM) { return false; } Main me = main; if (null != me) { me.quit(); } return true; } // package-private for testing String[] makeCommand() { ArrayList result = new ArrayList(); if (0 < ignored.size()) { for (Iterator iter = ignored.iterator(); iter.hasNext();) { logVerbose("ignored: " + iter.next()); } } // when copying resources, use temp jar for class output // then copy temp jar contents and resources to output jar if ((null != outjar) && !outjarFixedup) { if (copyInjars || copyInpath || (null != sourceRootCopyFilter) || (null != inpathDirCopyFilter)) { String path = outjar.getAbsolutePath(); int len = FileUtil.zipSuffixLength(path); path = path.substring(0, path.length()-len) + ".tmp.jar"; tmpOutjar = new File(path); } if (null == tmpOutjar) { cmd.addFlagged("-outjar", outjar.getAbsolutePath()); } else { cmd.addFlagged("-outjar", tmpOutjar.getAbsolutePath()); } outjarFixedup = true; } result.addAll(cmd.extractArguments()); addListArgs(result); String[] command = (String[]) result.toArray(new String[0]); if (null != commandEditor) { command = commandEditor.editCommand(command); } else if (null != COMMAND_EDITOR) { command = COMMAND_EDITOR.editCommand(command); } return command; } /** * Create any pseudo-options required to implement * some of the macro options * @throws BuildException if options conflict */ protected void setupOptions() { if (null != xweaveDir) { if (DEFAULT_DESTDIR != destDir) { throw new BuildException("weaveDir forces destdir"); } if (null != outjar) { throw new BuildException("weaveDir forces outjar"); } if (null != injars) { throw new BuildException("weaveDir incompatible with injars now"); } if (null != inpath) { throw new BuildException("weaveDir incompatible with inpath now"); } File injar = zipDirectory(xweaveDir); setInjars(new Path(getProject(), injar.getAbsolutePath())); setDestdir(xweaveDir); } } protected File zipDirectory(File dir) { File tempDir = new File("."); try { tempDir = File.createTempFile("AjcTest", ".tmp"); tempDir.mkdirs(); tempDir.deleteOnExit(); // XXX remove zip explicitly.. } catch (IOException e) { // ignore } // File result = new File(tempDir, String filename = "AjcTask-" + System.currentTimeMillis() + ".zip"; File result = new File(filename); Zip zip = new Zip(); zip.setProject(getProject()); zip.setDestFile(result); zip.setTaskName(getTaskName() + " - zip"); FileSet fileset = new FileSet(); fileset.setDir(dir); zip.addFileset(fileset); zip.execute(); Delete delete = new Delete(); delete.setProject(getProject()); delete.setTaskName(getTaskName() + " - delete"); delete.setDir(dir); delete.execute(); Mkdir mkdir = new Mkdir(); mkdir.setProject(getProject()); mkdir.setTaskName(getTaskName() + " - mkdir"); mkdir.setDir(dir); mkdir.execute(); return result; } /** * @throw BuildException if options conflict */ protected void verifyOptions() { StringBuffer sb = new StringBuffer(); if (fork && isInIncrementalMode() && !isInIncrementalFileMode()) { sb.append("can fork incremental only using tag file.\n"); } if (((null != inpathDirCopyFilter) || (null != sourceRootCopyFilter)) && (null == outjar) && (DEFAULT_DESTDIR == destDir)) { final String REQ = " requires dest dir or output jar.\n"; if (null == inpathDirCopyFilter) { sb.append("sourceRootCopyFilter"); } else if (null == sourceRootCopyFilter) { sb.append("inpathDirCopyFilter"); } else { sb.append("sourceRootCopyFilter and inpathDirCopyFilter"); } sb.append(REQ); } if (0 < sb.length()) { throw new BuildException(sb.toString()); } } /** * Run the compile in the same VM by * loading the compiler (Main), * setting up any message holders, * doing the compile, * and converting abort/failure and error messages * to BuildException, as appropriate. * @throws BuildException if abort or failure messages * or if errors and failonerror. * */ protected void executeInSameVM(String[] args) { if (null != maxMem) { log("maxMem ignored unless forked: " + maxMem, Project.MSG_WARN); } IMessageHolder holder = messageHolder; int numPreviousErrors; if (null == holder) { MessageHandler mhandler = new MessageHandler(true); final IMessageHandler delegate; delegate = new AntMessageHandler(this.logger,this.verbose, false); mhandler.setInterceptor(delegate); holder = mhandler; numPreviousErrors = 0; } else { numPreviousErrors = holder.numMessages(IMessage.ERROR, true); } { Main newmain = new Main(); newmain.setHolder(holder); newmain.setCompletionRunner(new Runnable() { public void run() { doCompletionTasks(); } }); if (null != main) { MessageUtil.fail(holder, "still running prior main"); return; } main = newmain; } main.runMain(args, false); if (failonerror) { int errs = holder.numMessages(IMessage.ERROR, false); errs -= numPreviousErrors; if (0 < errs) { String m = errs + " errors"; MessageUtil.print(System.err, holder, "", MessageUtil.MESSAGE_ALL, MessageUtil.PICK_ERROR, true); throw new BuildException(m); } } // Throw BuildException if there are any fail or abort // messages. // The BuildException message text has a list of class names // for the exceptions found in the messages, or the // number of fail/abort messages found if there were // no exceptions for any of the fail/abort messages. // The interceptor message handler should have already // printed the messages, including any stack traces. // HACK: this ignores the Usage message { IMessage[] fails = holder.getMessages(IMessage.FAIL, true); if (!LangUtil.isEmpty(fails)) { StringBuffer sb = new StringBuffer(); String prefix = "fail due to "; int numThrown = 0; for (int i = 0; i < fails.length; i++) { String message = fails[i].getMessage(); if (LangUtil.isEmpty(message)) { message = "<no message>"; } else if (-1 != message.indexOf(USAGE_SUBSTRING)) { continue; } Throwable t = fails[i].getThrown(); if (null != t) { numThrown++; sb.append(prefix); sb.append(LangUtil.unqualifiedClassName(t.getClass())); String thrownMessage = t.getMessage(); if (!LangUtil.isEmpty(thrownMessage)) { sb.append(" \"" + thrownMessage + "\""); } } sb.append("\"" + message + "\""); prefix = ", "; } if (0 < sb.length()) { sb.append(" (" + numThrown + " exceptions)"); throw new BuildException(sb.toString()); } } } } /** * Execute in a separate VM. * Differences from normal same-VM execution: * <ul> * <li>ignores any message holder {class} set</li> * <li>No resource-copying between interative runs</li> * <li>failonerror fails when process interface fails * to return negative values</li> * </ul> * @param args String[] of the complete compiler command to execute * * @see DefaultCompilerAdapter#executeExternalCompile(String[], int) * @throws BuildException if ajc aborts (negative value) * or if failonerror and there were compile errors. */ protected void executeInOtherVM(String[] args) { javaCmd.setClassname(org.aspectj.tools.ajc.Main.class.getName()); final Path vmClasspath = javaCmd.createClasspath(getProject()); { File aspectjtools = null; int vmClasspathSize = vmClasspath.size(); if ((null != forkclasspath) && (0 != forkclasspath.size())) { vmClasspath.addExisting(forkclasspath); } else { aspectjtools = findAspectjtoolsJar(); if (null != aspectjtools) { vmClasspath.createPathElement().setLocation(aspectjtools); } } int newVmClasspathSize = vmClasspath.size(); if (vmClasspathSize == newVmClasspathSize) { String m = "unable to find aspectjtools to fork - "; if (null != aspectjtools) { m += "tried " + aspectjtools.toString(); } else if (null != forkclasspath) { m += "tried " + forkclasspath.toString(); } else { m += "define forkclasspath or put aspectjtools on classpath"; } throw new BuildException(m); } } if (null != maxMem) { javaCmd.setMaxmemory(maxMem); } File tempFile = null; int numArgs = args.length; args = GuardedCommand.limitTo(args, MAX_COMMANDLINE, getLocation()); if (args.length != numArgs) { tempFile = new File(args[1]); } try { boolean setMessageHolderOnForking = (this.messageHolder != null); String[] javaArgs = javaCmd.getCommandline(); String[] both = new String[javaArgs.length + args.length + (setMessageHolderOnForking ? 2 : 0)]; System.arraycopy(javaArgs,0,both,0,javaArgs.length); System.arraycopy(args,0,both,javaArgs.length,args.length); if (setMessageHolderOnForking) { both[both.length - 2] = "-messageHolder"; both[both.length - 1] = this.messageHolder.getClass().getName(); } // try to use javaw instead on windows if (both[0].endsWith("java.exe")) { String path = both[0]; path = path.substring(0, path.length()-4); path = path + "w.exe"; File javaw = new File(path); if (javaw.canRead() && javaw.isFile()) { both[0] = path; } } logVerbose("forking " + Arrays.asList(both)); int result = execInOtherVM(both); if (0 > result) { throw new BuildException("failure[" + result + "] running ajc"); } else if (failonerror && (0 < result)) { throw new BuildException("compile errors: " + result); } // when forking, do completion only at end and when successful doCompletionTasks(); } finally { if (null != tempFile) { tempFile.delete(); } } } /** * Execute in another process using the same JDK * and the base directory of the project. XXX correct? * @param args * @return */ protected int execInOtherVM(String[] args) { try { Project project = getProject(); PumpStreamHandler handler = new LogStreamHandler(this, verbose ? Project.MSG_VERBOSE : Project.MSG_INFO, Project.MSG_WARN); // replace above two lines with what follows as an aid to debugging when running the unit tests.... // LogStreamHandler handler = new LogStreamHandler(this, // Project.MSG_INFO, Project.MSG_WARN) { // // ByteArrayOutputStream baos = new ByteArrayOutputStream(); // /* (non-Javadoc) // * @see org.apache.tools.ant.taskdefs.PumpStreamHandler#createProcessOutputPump(java.io.InputStream, java.io.OutputStream) // */ // protected void createProcessErrorPump(InputStream is, // OutputStream os) { // super.createProcessErrorPump(is, baos); // } // // /* (non-Javadoc) // * @see org.apache.tools.ant.taskdefs.LogStreamHandler#stop() // */ // public void stop() { // byte[] written = baos.toByteArray(); // System.err.print(new String(written)); // super.stop(); // } // }; Execute exe = new Execute(handler); exe.setAntRun(project); exe.setWorkingDirectory(project.getBaseDir()); exe.setCommandline(args); try { if (executingInOtherVM) { String s = "already running in other vm?"; throw new BuildException(s, location); } executingInOtherVM = true; exe.execute(); } finally { executingInOtherVM = false; } return exe.getExitValue(); } catch (IOException e) { String m = "Error executing command " + Arrays.asList(args); throw new BuildException(m, e, location); } } // ------------------------------ setup and reporting /** @return null if path null or empty, String rendition otherwise */ protected static void addFlaggedPath(String flag, Path path, List list) { if (!LangUtil.isEmpty(flag) && ((null != path) && (0 < path.size()))) { list.add(flag); list.add(path.toString()); } } /** * Add to list any path or plural arguments. */ protected void addListArgs(List list) throws BuildException { addFlaggedPath("-classpath", classpath, list); addFlaggedPath("-bootclasspath", bootclasspath, list); addFlaggedPath("-extdirs", extdirs, list); addFlaggedPath("-aspectpath", aspectpath, list); addFlaggedPath("-injars", injars, list); addFlaggedPath("-inpath", inpath, list); addFlaggedPath("-sourceroots", sourceRoots, list); if (argfiles != null) { String[] files = argfiles.list(); for (int i = 0; i < files.length; i++) { File argfile = project.resolveFile(files[i]); if (check(argfile, files[i], false, location)) { list.add("-argfile"); list.add(argfile.getAbsolutePath()); } } } if (srcdir != null) { // todo: ignore any srcdir if any argfiles and no explicit includes String[] dirs = srcdir.list(); for (int i = 0; i < dirs.length; i++) { File dir = project.resolveFile(dirs[i]); check(dir, dirs[i], true, location); // relies on compiler to prune non-source files String[] files = getDirectoryScanner(dir).getIncludedFiles(); for (int j = 0; j < files.length; j++) { File file = new File(dir, files[j]); if (FileUtil.hasSourceSuffix(file)) { list.add(file.getAbsolutePath()); } } } } if (0 < adapterFiles.size()) { for (Iterator iter = adapterFiles.iterator(); iter.hasNext();) { File file = (File) iter.next(); if (file.canRead() && FileUtil.hasSourceSuffix(file)) { list.add(file.getAbsolutePath()); } else { this.logger.warning("skipping file: " + file); } } } } /** * Throw BuildException unless file is valid. * @param file the File to check * @param name the symbolic name to print on error * @param isDir if true, verify file is a directory * @param loc the Location used to create sensible BuildException * @return * @throws BuildException unless file valid */ protected final boolean check(File file, String name, boolean isDir, Location loc) { loc = loc != null ? loc : location; if (file == null) { throw new BuildException(name + " is null!", loc); } if (!file.exists()) { throw new BuildException(file + " doesn't exist!", loc); } if (isDir ^ file.isDirectory()) { String e = file + " should" + (isDir ? "" : "n't") + " be a directory!"; throw new BuildException(e, loc); } return true; } /** * Called when compile or incremental compile is completing, * this completes the output jar or directory * by copying resources if requested. * Note: this is a callback run synchronously by the compiler. * That means exceptions thrown here are caught by Main.run(..) * and passed to the message handler. */ protected void doCompletionTasks() { if (!executing) { throw new IllegalStateException("should be executing"); } if (null != outjar) { completeOutjar(); } else { completeDestdir(); } if (null != xdoneSignal) { MessageUtil.info(messageHolder, xdoneSignal); } } /** * Complete the destination directory * by copying resources from the source root directories * (if the filter is specified) * and non-.class files from the input jars * (if XCopyInjars is enabled). */ private void completeDestdir() { if (!copyInjars && (null == sourceRootCopyFilter) && (null == inpathDirCopyFilter)) { return; } else if ((destDir == DEFAULT_DESTDIR) || !destDir.canWrite()) { String s = "unable to copy resources to destDir: " + destDir; throw new BuildException(s); } final Project project = getProject(); if (copyInjars) { // XXXX remove as unused since 1.1.1 if (null != inpath) { log("copyInjars does not support inpath.\n", Project.MSG_WARN); } String taskName = getTaskName() + " - unzip"; String[] paths = injars.list(); if (!LangUtil.isEmpty(paths)) { PatternSet patternSet = new PatternSet(); patternSet.setProject(project); patternSet.setIncludes("**/*"); patternSet.setExcludes("**/*.class"); for (int i = 0; i < paths.length; i++) { Expand unzip = new Expand(); unzip.setProject(project); unzip.setTaskName(taskName); unzip.setDest(destDir); unzip.setSrc(new File(paths[i])); unzip.addPatternset(patternSet); unzip.execute(); } } } if ((null != sourceRootCopyFilter) && (null != sourceRoots)) { String[] paths = sourceRoots.list(); if (!LangUtil.isEmpty(paths)) { Copy copy = new Copy(); copy.setProject(project); copy.setTodir(destDir); for (int i = 0; i < paths.length; i++) { FileSet fileSet = new FileSet(); fileSet.setDir(new File(paths[i])); fileSet.setIncludes("**/*"); fileSet.setExcludes(sourceRootCopyFilter); copy.addFileset(fileSet); } copy.execute(); } } if ((null != inpathDirCopyFilter) && (null != inpath)) { String[] paths = inpath.list(); if (!LangUtil.isEmpty(paths)) { Copy copy = new Copy(); copy.setProject(project); copy.setTodir(destDir); boolean gotDir = false; for (int i = 0; i < paths.length; i++) { File inpathDir = new File(paths[i]); if (inpathDir.isDirectory() && inpathDir.canRead()) { if (!gotDir) { gotDir = true; } FileSet fileSet = new FileSet(); fileSet.setDir(inpathDir); fileSet.setIncludes("**/*"); fileSet.setExcludes(inpathDirCopyFilter); copy.addFileset(fileSet); } } if (gotDir) { copy.execute(); } } } } /** * Complete the output jar * by copying resources from the source root directories * if the filter is specified. * and non-.class files from the input jars if enabled. */ private void completeOutjar() { if (((null == tmpOutjar) || !tmpOutjar.canRead()) || (!copyInjars && (null == sourceRootCopyFilter) && (null == inpathDirCopyFilter))) { return; } Zip zip = new Zip(); Project project = getProject(); zip.setProject(project); zip.setTaskName(getTaskName() + " - zip"); zip.setDestFile(outjar); ZipFileSet zipfileset = new ZipFileSet(); zipfileset.setProject(project); zipfileset.setSrc(tmpOutjar); zipfileset.setIncludes("**/*.class"); zip.addZipfileset(zipfileset); if (copyInjars) { String[] paths = injars.list(); if (!LangUtil.isEmpty(paths)) { for (int i = 0; i < paths.length; i++) { File jarFile = new File(paths[i]); zipfileset = new ZipFileSet(); zipfileset.setProject(project); zipfileset.setSrc(jarFile); zipfileset.setIncludes("**/*"); zipfileset.setExcludes("**/*.class"); zip.addZipfileset(zipfileset); } } } if ((null != sourceRootCopyFilter) && (null != sourceRoots)) { String[] paths = sourceRoots.list(); if (!LangUtil.isEmpty(paths)) { for (int i = 0; i < paths.length; i++) { File srcRoot = new File(paths[i]); FileSet fileset = new FileSet(); fileset.setProject(project); fileset.setDir(srcRoot); fileset.setIncludes("**/*"); fileset.setExcludes(sourceRootCopyFilter); zip.addFileset(fileset); } } } if ((null != inpathDirCopyFilter) && (null != inpath)) { String[] paths = inpath.list(); if (!LangUtil.isEmpty(paths)) { for (int i = 0; i < paths.length; i++) { File inpathDir = new File(paths[i]); if (inpathDir.isDirectory() && inpathDir.canRead()) { FileSet fileset = new FileSet(); fileset.setProject(project); fileset.setDir(inpathDir); fileset.setIncludes("**/*"); fileset.setExcludes(inpathDirCopyFilter); zip.addFileset(fileset); } } } } zip.execute(); } // -------------------------- compiler adapter interface extras /** * Add specified source files. */ void addFiles(File[] paths) { for (int i = 0; i < paths.length; i++) { addFile(paths[i]); } } /** * Add specified source file. */ void addFile(File path) { if (null != path) { adapterFiles.add(path); } } /** * Read arguments in as if from a command line, * mainly to support compiler adapter compilerarg subelement. * * @param args the String[] of arguments to read */ public void readArguments(String[] args) { // XXX slow, stupid, unmaintainable if ((null == args) || (0 == args.length)) { return; } /** String[] wrapper with increment, error reporting */ class Args { final String[] args; int index = 0; Args(String[] args) { this.args = args; // not null or empty } boolean hasNext() { return index < args.length; } String next() { String err = null; if (!hasNext()) { err = "need arg for flag " + args[args.length-1]; } else { String s = args[index++]; if (null == s) { err = "null value"; } else { s = s.trim(); if (0 == s.trim().length()) { err = "no value"; } else { return s; } } } err += " at [" + index + "] of " + Arrays.asList(args); throw new BuildException(err); } } // class Args Args in = new Args(args); String flag; while (in.hasNext()) { flag = in.next(); if ("-1.3".equals(flag)) { setCompliance(flag); } else if ("-1.4".equals(flag)) { setCompliance(flag); } else if ("-1.5".equals(flag)) { setCompliance("1.5"); } else if ("-argfile".equals(flag)) { setArgfiles(new Path(project, in.next())); } else if ("-aspectpath".equals(flag)) { setAspectpath(new Path(project, in.next())); } else if ("-classpath".equals(flag)) { setClasspath(new Path(project, in.next())); } else if ("-extdirs".equals(flag)) { setExtdirs(new Path(project, in.next())); } else if ("-Xcopyinjars".equals(flag)) { setCopyInjars(true); // ignored - will be flagged by setter } else if ("-g".equals(flag)) { setDebug(true); } else if (flag.startsWith("-g:")) { setDebugLevel(flag.substring(2)); } else if ("-deprecation".equals(flag)) { setDeprecation(true); } else if ("-d".equals(flag)) { setDestdir(new File(in.next())); } else if ("-crossrefs".equals(flag)) { setCrossrefs(true); } else if ("-emacssym".equals(flag)) { setEmacssym(true); } else if ("-encoding".equals(flag)) { setEncoding(in.next()); } else if ("-Xfailonerror".equals(flag)) { setFailonerror(true); } else if ("-fork".equals(flag)) { setFork(true); } else if ("-forkclasspath".equals(flag)) { setForkclasspath(new Path(project, in.next())); } else if ("-help".equals(flag)) { setHelp(true); } else if ("-incremental".equals(flag)) { setIncremental(true); } else if ("-injars".equals(flag)) { setInjars(new Path(project, in.next())); } else if ("-inpath".equals(flag)) { setInpath(new Path(project,in.next())); } else if ("-Xlistfileargs".equals(flag)) { setListFileArgs(true); } else if ("-Xmaxmem".equals(flag)) { setMaxmem(in.next()); } else if ("-Xmessageholderclass".equals(flag)) { setMessageHolderClass(in.next()); } else if ("-noexit".equals(flag)) { setNoExit(true); } else if ("-noimport".equals(flag)) { setNoExit(true); } else if ("-noExit".equals(flag)) { setNoExit(true); } else if ("-noImportError".equals(flag)) { setNoImportError(true); } else if ("-noWarn".equals(flag)) { setNowarn(true); } else if ("-noexit".equals(flag)) { setNoExit(true); } else if ("-outjar".equals(flag)) { setOutjar(new File(in.next())); } else if ("-outxml".equals(flag)) { setOutxml(true); } else if ("-outxmlfile".equals(flag)) { setOutxmlfile(in.next()); } else if ("-preserveAllLocals".equals(flag)) { setPreserveAllLocals(true); } else if ("-proceedOnError".equals(flag)) { setProceedOnError(true); } else if ("-referenceInfo".equals(flag)) { setReferenceInfo(true); } else if ("-source".equals(flag)) { setSource(in.next()); } else if ("-Xsourcerootcopyfilter".equals(flag)) { setSourceRootCopyFilter(in.next()); } else if ("-sourceroots".equals(flag)) { setSourceRoots(new Path(project, in.next())); } else if ("-Xsrcdir".equals(flag)) { setSrcDir(new Path(project, in.next())); } else if ("-Xtagfile".equals(flag)) { setTagFile(new File(in.next())); } else if ("-target".equals(flag)) { setTarget(in.next()); } else if ("-time".equals(flag)) { setTime(true); } else if ("-time".equals(flag)) { setTime(true); } else if ("-verbose".equals(flag)) { setVerbose(true); } else if ("-showWeaveInfo".equals(flag)) { setShowWeaveInfo(true); } else if ("-version".equals(flag)) { setVersion(true); } else if ("-warn".equals(flag)) { setWarn(in.next()); } else if (flag.startsWith("-warn:")) { setWarn(flag.substring(6)); } else if ("-Xlint".equals(flag)) { setXlintwarnings(true); } else if (flag.startsWith("-Xlint:")) { setXlint(flag.substring(7)); } else if ("-Xlintfile".equals(flag)) { setXlintfile(new File(in.next())); } else if ("-XterminateAfterCompilation".equals(flag)) { setXTerminateAfterCompilation(true); } else if ("-Xreweavable".equals(flag)) { setXReweavable(true); } else if ("-XnotReweavable".equals(flag)) { setXNotReweavable(true); } else if (flag.startsWith("@")) { File file = new File(flag.substring(1)); if (file.canRead()) { setArgfiles(new Path(project, file.getPath())); } else { ignore(flag); } } else { File file = new File(flag); if (file.isFile() && file.canRead() && FileUtil.hasSourceSuffix(file)) { addFile(file); } else { ignore(flag); } } } } protected void logVerbose(String text) { if (this.verbose) { this.logger.info(text); } else { this.logger.verbose(text); } } /** * Commandline wrapper that * only permits addition of non-empty values * and converts to argfile form if necessary. */ public static class GuardedCommand { Commandline command; //int size; static boolean isEmpty(String s) { return ((null == s) || (0 == s.trim().length())); } GuardedCommand() { command = new Commandline(); } void addFlag(String flag, boolean doAdd) { if (doAdd && !isEmpty(flag)) { command.createArgument().setValue(flag); //size += 1 + flag.length(); } } /** @return null if added or ignoreString otherwise */ String addOption(String prefix, String[] validOptions, String input) { if (isEmpty(input)) { return null; } for (int i = 0; i < validOptions.length; i++) { if (input.equals(validOptions[i])) { if (isEmpty(prefix)) { addFlag(input, true); } else { addFlagged(prefix, input); } return null; } } return (null == prefix ? input : prefix + " " + input); } void addFlagged(String flag, String argument) { if (!isEmpty(flag) && !isEmpty(argument)) { command.addArguments(new String[] {flag, argument}); //size += 1 + flag.length() + argument.length(); } } // private void addFile(File file) { // if (null != file) { // String path = file.getAbsolutePath(); // addFlag(path, true); // } // } List extractArguments() { ArrayList result = new ArrayList(); String[] cmds = command.getArguments(); if (!LangUtil.isEmpty(cmds)) { result.addAll(Arrays.asList(cmds)); } return result; } /** * Adjust args for size if necessary by creating * an argument file, which should be deleted by the client * after the compiler run has completed. * @param max the int maximum length of the command line (in char) * @return the temp File for the arguments (if generated), * for deletion when done. * @throws IllegalArgumentException if max is negative */ static String[] limitTo(String[] args, int max, Location location) { if (max < 0) { throw new IllegalArgumentException("negative max: " + max); } // sigh - have to count anyway for now int size = 0; for (int i = 0; (i < args.length) && (size < max); i++) { size += 1 + (null == args[i] ? 0 : args[i].length()); } if (size <= max) { return args; } File tmpFile = null; PrintWriter out = null; // adapted from DefaultCompilerAdapter.executeExternalCompile try { String userDirName = System.getProperty("user.dir"); File userDir = new File(userDirName); tmpFile = File.createTempFile("argfile", "", userDir); out = new PrintWriter(new FileWriter(tmpFile)); for (int i = 0; i < args.length; i++) { out.println(args[i]); } out.flush(); return new String[] {"-argfile", tmpFile.getAbsolutePath()}; } catch (IOException e) { throw new BuildException("Error creating temporary file", e, location); } finally { if (out != null) { try {out.close();} catch (Throwable t) {} } } } } private static class AntMessageHandler implements IMessageHandler { private TaskLogger logger; private final boolean taskLevelVerbose; private final boolean handledMessage; public AntMessageHandler(TaskLogger logger, boolean taskVerbose, boolean handledMessage) { this.logger = logger; this.taskLevelVerbose = taskVerbose; this.handledMessage = handledMessage; } /* (non-Javadoc) * @see org.aspectj.bridge.IMessageHandler#handleMessage(org.aspectj.bridge.IMessage) */ public boolean handleMessage(IMessage message) throws AbortException { Kind messageKind = message.getKind(); String messageText = message.toString(); if (messageKind == IMessage.ABORT) { this.logger.error(messageText); } else if (messageKind == IMessage.DEBUG) { this.logger.debug(messageText); } else if (messageKind == IMessage.ERROR) { this.logger.error(messageText); } else if (messageKind == IMessage.FAIL){ this.logger.error(messageText); } else if (messageKind == IMessage.INFO) { if (this.taskLevelVerbose) { this.logger.info(messageText); } else { this.logger.verbose(messageText); } } else if (messageKind == IMessage.WARNING) { this.logger.warning(messageText); } else if (messageKind == IMessage.WEAVEINFO) { this.logger.info(messageText); } else if (messageKind == IMessage.TASKTAG) { // ignore } else { throw new BuildException("Unknown message kind from AspectJ compiler: " + messageKind.toString()); } return handledMessage; } /* (non-Javadoc) * @see org.aspectj.bridge.IMessageHandler#isIgnoring(org.aspectj.bridge.IMessage.Kind) */ public boolean isIgnoring(Kind kind) { return false; } /* (non-Javadoc) * @see org.aspectj.bridge.IMessageHandler#dontIgnore(org.aspectj.bridge.IMessage.Kind) */ public void dontIgnore(Kind kind) { } /* (non-Javadoc) * @see org.aspectj.bridge.IMessageHandler#ignore(org.aspectj.bridge.IMessage.Kind) */ public void ignore(Kind kind) { } } }