issue_id
int64 2.03k
426k
| title
stringlengths 9
251
| body
stringlengths 1
32.8k
⌀ | status
stringclasses 6
values | after_fix_sha
stringlengths 7
7
| project_name
stringclasses 6
values | repo_url
stringclasses 6
values | repo_name
stringclasses 6
values | language
stringclasses 1
value | issue_url
null | before_fix_sha
null | pull_url
null | commit_datetime
timestamp[us, tz=UTC] | report_datetime
timestamp[us, tz=UTC] | updated_file
stringlengths 2
187
| file_content
stringlengths 0
368k
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
152,589 |
Bug 152589 [pipeline] adding a whitespace results in adviceDidNotMatch warning
| null |
resolved fixed
|
9664058
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-08-03T07:23:55Z | 2006-08-02T14:46:40Z |
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.tools.ajc.Ajc;
/**
* 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
}
/**
* 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 only one but reports "+EclipseFactory.debug_mungerCount,EclipseFactory.debug_mungerCount==1);
alter("PR141956","inc1");
build("PR141956");
assertTrue("Should be only one but reports "+EclipseFactory.debug_mungerCount,EclipseFactory.debug_mungerCount==1);
alter("PR141956","inc1");
build("PR141956");
assertTrue("Should be only one but reports "+EclipseFactory.debug_mungerCount,EclipseFactory.debug_mungerCount==1);
alter("PR141956","inc1");
build("PR141956");
assertTrue("Should be only one but reports "+EclipseFactory.debug_mungerCount,EclipseFactory.debug_mungerCount==1);
}
// 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() {
configureNonStandardCompileOptions("-Xlint:warning");
initialiseProject("PR133117");
build("PR133117");
assertTrue("There should only be one xlint warning message reported:\n"
+MyTaskListManager.getWarningMessages(),
MyTaskListManager.getWarningMessages().size()==1);
alter("PR133117","inc1");
build("PR133117");
List warnings = MyTaskListManager.getWarningMessages();
List noGuardWarnings = new ArrayList();
for (Iterator iter = warnings.iterator(); iter.hasNext();) {
IMessage element = (IMessage) iter.next();
if (element.getMessage().indexOf("Xlint:noGuardForLazyTjp") != -1) {
noGuardWarnings.add(element);
}
}
assertTrue("There should only be two Xlint:noGuardForLazyTjp warning message reported:\n"
+noGuardWarnings,noGuardWarnings.size() == 2);
}
public void testPr131505() {
configureNonStandardCompileOptions("-outxml");
initialiseProject("PR131505");
build("PR131505");
checkWasFullBuild();
// aop.xml file shouldn't contain any aspects
checkXMLAspectCount("PR131505","",0);
// add a new aspect A which should be included in the aop.xml file
alter("PR131505","inc1");
build("PR131505");
checkWasFullBuild();
checkXMLAspectCount("PR131505","",1);
checkXMLAspectCount("PR131505","A",1);
// make changes to the class file which shouldn't affect the contents
// of the aop.xml file
alter("PR131505","inc2");
build("PR131505");
checkWasntFullBuild();
checkXMLAspectCount("PR131505","",1);
checkXMLAspectCount("PR131505","A",1);
// add another new aspect A1 which should also be included in the aop.xml file
// ...there should be no duplicate entries in the file
alter("PR131505","inc3");
build("PR131505");
checkWasFullBuild();
checkXMLAspectCount("PR131505","",2);
checkXMLAspectCount("PR131505","A1",1);
checkXMLAspectCount("PR131505","A",1);
// delete aspect A1 which meanss that aop.xml file should only contain A
File a1 = new File(getWorkingDir().getAbsolutePath()
+ File.separatorChar + "PR131505" + File.separatorChar + "A1.aj");
a1.delete();
build("PR131505");
checkWasFullBuild();
checkXMLAspectCount("PR131505","",1);
checkXMLAspectCount("PR131505","A1",0);
checkXMLAspectCount("PR131505","A",1);
// add another aspect called A which is in a different package, both A
// and pkg.A should be included in the aop.xml file
alter("PR131505","inc4");
build("PR131505");
checkWasFullBuild();
checkXMLAspectCount("PR131505","",2);
checkXMLAspectCount("PR131505","A",1);
checkXMLAspectCount("PR131505","pkg.A",1);
}
public void testPr136585() {
initialiseProject("PR136585");
build("PR136585");
alter("PR136585","inc1");
build("PR136585");
assertTrue("There should be no errors reported:\n"+MyTaskListManager.getErrorMessages(),
MyTaskListManager.getErrorMessages().isEmpty());
}
public void testPr133532() {
initialiseProject("PR133532");
build("PR133532");
alter("PR133532","inc1");
build("PR133532");
alter("PR133532","inc2");
build("PR133532");
assertTrue("There should be no errors reported:\n"+MyTaskListManager.getErrorMessages(),
MyTaskListManager.getErrorMessages().isEmpty());
}
public void testPr133532_2() {
initialiseProject("pr133532_2");
build("pr133532_2");
alter("pr133532_2","inc2");
build("pr133532_2");
assertTrue("There should be no errors reported:\n"+MyTaskListManager.getErrorMessages(),
MyTaskListManager.getErrorMessages().isEmpty());
String decisions = AjdeInteractionTestbed.MyStateListener.getDecisions();
String expect="Need to recompile 'A.aj'";
assertTrue("Couldn't find build decision: '"+expect+"' in the list of decisions made:\n"+decisions,
decisions.indexOf(expect)!=-1);
}
public void testPr134541() {
initialiseProject("PR134541");
build("PR134541");
assertEquals("[Xlint:adviceDidNotMatch] should be associated with line 5",5,
((IMessage)MyTaskListManager.getWarningMessages().get(0)).getSourceLocation().getLine());
alter("PR134541","inc1");
build("PR134541");
if (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);
}
// --- 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.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);
}
}
|
151,991 |
Bug 151991 Missing copyright/license in recently added modules
|
BuildModuleTests does not test for licenses in ajdoc, loadtime, loadtime5, weaver5. When I added the necessary logic there were a couple of failures. Could the owners please step forward ... epl-cpl-ibm|parc|xerox|others LICENSE FAIL: C:\workspaces\org.aspectj-Restructure\weaver5\java5-src\org\aspectj\weaver\reflect\DeferredResolvedPointcutDefinition.java epl-cpl-ibm|parc|xerox|others COPYRIGHT FAIL: C:\workspaces\org.aspectj-Restructure\weaver5\java5-src\org\aspectj\weaver\reflect\DeferredResolvedPointcutDefinition.java epl-cpl-ibm|parc|xerox|others LICENSE FAIL: C:\workspaces\org.aspectj-Restructure\weaver5\java5-src\org\aspectj\weaver\reflect\InternalUseOnlyPointcutParser.java epl-cpl-ibm|parc|xerox|others COPYRIGHT FAIL: C:\workspaces\org.aspectj-Restructure\weaver5\java5-src\org\aspectj\weaver\reflect\InternalUseOnlyPointcutParser.java Total passed: 7 failed: 2 I also noticed the following messages. Does anyone know what they mean? BuildModuleTest: Define "run.build.tests" as a system property to run tests to build run-all-junit-tests (this is the only warning) class org.aspectj.internal.build.BuildModuleTest.testNoDuplicates() incomplete error building module weaver at org.aspectj.internal.tools.ant.taskdefs.BuildModule.build(BuildModule.java:145) at org.aspectj.internal.tools.ant.taskdefs.BuildModule.execute(BuildModule.java:117) at org.aspectj.internal.build.BuildModuleTest.doTask(BuildModuleTest.java:445) at org.aspectj.internal.build.BuildModuleTest.testNoDuplicates(BuildModuleTest.java:178) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:585) at junit.framework.TestCase.runTest(TestCase.java:154) at junit.framework.TestCase.runBare(TestCase.java:127) at junit.framework.TestResult$1.protect(TestResult.java:106) at junit.framework.TestResult.runProtected(TestResult.java:124)Module at junit.framework.TestResult.run(TestResult.java:109) at junit.framework.TestCase.run(TestCase.java:118) at junit.framework.TestSuite.runTest(TestSuite.java:208) at junit.framework.TestSuite.run(TestSuite.java:203) at junit.framework.TestSuite.runTest(TestSuite.java:208) at junit.framework.TestSuite.run(TestSuite.java:203) at org.eclipse.jdt.internal.junit.runner.junit3.JUnit3TestReference.run(JUnit3TestReference.java:128) at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:460) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:673) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:386) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:196)
|
resolved fixed
|
7aa6cfe
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-08-03T15:51:04Z | 2006-07-27T14:20:00Z |
build/testsrc/org/aspectj/build/BuildModuleTests.java
|
package org.aspectj.build;
/* *******************************************************************
* 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
* ******************************************************************/
// default package
import org.aspectj.internal.tools.ant.taskdefs.Checklics;
import org.aspectj.internal.tools.build.Builder;
import org.aspectj.internal.tools.build.Util;
import org.aspectj.internal.tools.build.UtilsTest;
import org.aspectj.internal.build.BuildModuleTest;
import org.aspectj.internal.build.ModulesTest;
import java.io.File;
import java.io.FileFilter;
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 junit.framework.*;
/**
* Master suite for build module
* and test of all source directories for correct licenses and known file types.
*/
public class BuildModuleTests extends TestCase {
/** if true, then replace old headers with new first */
private static final boolean replacing = false; // XXX never to enable again...
/** replace commented out below - if any replace failed, halt all */
private static boolean replaceFailed = false;
private static final String BASE_DIR = ".." + File.separator;
private static final String[] JDT_SOURCE_DIRS = new String[] {};
public static Test suite() {
TestSuite suite = new TestSuite("Build module tests");
suite.addTestSuite(BuildModuleTests.class);
suite.addTestSuite(BuildModuleTest.class);
suite.addTestSuite(ModulesTest.class);
suite.addTestSuite(UtilsTest.class);
return suite;
}
/** @return String tag of license if not default */
public static String getLicense(String module) {
return null; // use permissive default
}
final static List SOURCE_NAMES = Collections.unmodifiableList(
Arrays.asList(new String[]{"src", "testsrc", "java5-src", "aspectj-src"}));
/**
* @param moduleDir
* @return
*/
private static File[] findSourceRoots(File moduleDir) {
ArrayList result = new ArrayList();
for (Iterator iter = SOURCE_NAMES.iterator(); iter.hasNext();) {
String name = (String) iter.next();
File srcDir = new File(moduleDir, name);
if (srcDir.canRead() && srcDir.isDirectory()) {
result.add(srcDir);
}
}
return (File[]) result.toArray(new File[0]);
}
public BuildModuleTests(String name) { super(name); }
public void testSuffixList() {
if (!UnknownFileCheck.STATIC_ERRORS.isEmpty()) {
fail("" + UnknownFileCheck.STATIC_ERRORS);
}
}
public void testLicense_ajbrowser() {
checkLicense("ajbrowser");
}
public void testLicense_ajde() {
checkLicense("ajde");
}
public void testLicense_aspectj5rt() {
checkLicense("aspectj5rt");
}
public void testLicense_asm() {
checkLicense("asm");
}
public void testLicense_bridge() {
checkLicense("bridge");
}
public void testLicense_build() {
checkLicense("build");
}
public void testLicense_org_aspectj_ajdt_core() {
checkLicense("org.aspectj.ajdt.core");
}
public void testLicense_org_aspectj_lib() {
checkLicense("org.aspectj.lib");
}
public void testLicense_org_eclipse_jdt_core() {
final String mod = "org.eclipse.jdt.core";
final String pre = BASE_DIR + mod + File.separator;
for (int i = 0; i < JDT_SOURCE_DIRS.length; i++) {
checkSourceDirectory(new File(pre + JDT_SOURCE_DIRS[i]), mod);
}
}
public void testLicense_runtime() {
checkLicense("runtime");
}
public void testLicense_taskdefs() {
checkLicense("taskdefs");
}
public void testLicense_testing() {
checkLicense("testing");
}
public void testLicense_testing_client() {
checkLicense("testing-client");
}
public void testLicense_testing_drivers() {
checkLicense("testing-drivers");
}
public void testLicense_testing_util() {
checkLicense("testing-util");
}
public void testLicense_util() {
checkLicense("util");
}
public void testLicense_weaver() {
String module = "weaver";
checkSourceDirectory(new File(Util.path(new String[] {"..", module, "src"})), module);
checkSourceDirectory(new File(Util.path(new String[] {"..", module, "testsrc", "org"})), module);
}
void checkLicense(String module) {
File moduleDir = new File(Util.path("..", module));
File[] srcDirs = findSourceRoots(moduleDir);
for (int i = 0; i < srcDirs.length; i++) {
checkSourceDirectory(srcDirs[i], module);
}
}
void checkSourceDirectory(File srcDir, String module) {
final String label = "source dir " + srcDir + " (module " + module + ")";
assertTrue(label, (srcDir.exists() && srcDir.isDirectory()));
String license = getLicense(module);
// if (replacing) {
// if (replacing && true) {
// throw new Error("replacing done - code left for other replaces");
// }
// assertTrue("aborting - replace failed", !replaceFailed);
// // do the replace
// int fails = Checklics.runDirect(moduleDir.getPath(), "replace-headers");
// replaceFailed = (0 != fails);
// assertTrue(!replaceFailed);
// license = Checklics.CPL_IBM_PARC_XEROX_TAG;
// }
int fails = Checklics.runDirect(srcDir.getPath(), license, true);
if (0 != fails) {
if (replacing) {
BuildModuleTests.replaceFailed = true;
}
assertTrue(label + " fails", !BuildModuleTests.replaceFailed);
}
// separate check to verify all file types (suffixes) are known
if (!"testsrc".equals(srcDir.getName())) {
ArrayList unknownFiles = new ArrayList();
UnknownFileCheck.SINGLETON.unknownFiles(srcDir, unknownFiles);
if (!unknownFiles.isEmpty()) {
String s = "unknown files (see readme-build-module.html to "
+ "update Builder.properties resource patterns): ";
fail(s + unknownFiles);
}
}
}
/**
* Check tree for files not managed by the build system
* (either source files or managed as resources).
* This should pick up situations where new kinds of resources are added
* to the tree without updating the build script patterns to pick them
* up.
* @see Builder#BINARY_SOURCE_PATTERN
* @see Builder#RESOURCE_PATTERN
* @see org.aspectj.util.FileUtil#SOURCE_SUFFIXES
*/
static class UnknownFileCheck implements FileFilter {
private static final UnknownFileCheck SINGLETON = new UnknownFileCheck();
private static final ArrayList STATIC_ERRORS = new ArrayList();
// Builder.BINARY_SOURCE_PATTERN and Builder.RESOURCE_PATTERN
public static final List KNOWN_SUFFIXES;
static {
List suffixes = new ArrayList();
// sources from org.aspectj.util.FileUtil.SOURCE_SUFFIXES
suffixes.add(".aj");
suffixes.add(".java");
// just because we know...
suffixes.add(".html");
// others from Builder
final String input = Builder.BINARY_SOURCE_PATTERN
+ "," + Builder.RESOURCE_PATTERN;
StringTokenizer st = new StringTokenizer(input, ",");
while (st.hasMoreTokens()) {
String token = st.nextToken().trim();
if (0 == token.length()) {
continue;
}
if (token.startsWith("**/*.")) {
token = token.substring(4);
} else if (token.startsWith("*.")) {
token = token.substring(1);
} else {
String s = input + " at \"" + token + "\"";
STATIC_ERRORS.add("unable to read pattern: " + s);
}
suffixes.add(token);
}
KNOWN_SUFFIXES = Collections.unmodifiableList(suffixes);
}
private UnknownFileCheck() {
}
/**
* Return true if input File file is a valid path to a directory
* or to a file
* which is not hidden (starts with .)
* and does not have a known suffix.
* Caller is responsible for pruning CVS directories
* @return true iff unknown or a directory
*/
public boolean accept(File file) {
if (null == file) {
return false;
}
if (file.isDirectory()) {
return file.canRead();
}
String name = file.getName();
if ("CVS".equals(name) || name.startsWith(".")) {
return false;
}
// to do not accepting uppercase suffixes...
for (Iterator iter = KNOWN_SUFFIXES.iterator(); iter.hasNext();) {
String suffix = (String) iter.next();
if (name.endsWith(suffix)) {
return false;
}
}
return true;
}
void unknownFiles(File dir, ArrayList results) {
File[] files = dir.listFiles(this);
for (int j = 0; j < files.length; j++) {
File file = files[j];
if (file.isDirectory()) {
String name = file.getName();
if (!("CVS".equals(name))) {
unknownFiles(file, results);
}
} else {
results.add(file);
}
}
}
}
}
|
152,631 |
Bug 152631 Problem with decp on an aspect using cflow
|
This occurs in the AspectJ build in AJDT from August 1 but not from July 31: java.lang.NullPointerException at org.aspectj.weaver.bcel.BcelTypeMunger.enforceDecpRule1_abstractMethodsImplemented(BcelTypeMunger.java:250) at org.aspectj.weaver.bcel.BcelTypeMunger.mungeNewParent(BcelTypeMunger.java:194) at org.aspectj.weaver.bcel.BcelTypeMunger.munge(BcelTypeMunger.java:106) at org.aspectj.weaver.bcel.BcelClassWeaver.weave(BcelClassWeaver.java:454) at org.aspectj.weaver.bcel.BcelClassWeaver.weave(BcelClassWeaver.java:119) at org.aspectj.weaver.bcel.BcelWeaver.weave(BcelWeaver.java:1597) at org.aspectj.weaver.bcel.BcelWeaver.weaveWithoutDump(BcelWeaver.java:1548) at org.aspectj.weaver.bcel.BcelWeaver.weaveAndNotify(BcelWeaver.java:1328) at org.aspectj.weaver.bcel.BcelWeaver.weave(BcelWeaver.java:1124) at org.aspectj.ajdt.internal.compiler.AjPipeliningCompilerAdapter.weaveQueuedEntries(AjPipeliningCompilerAdapter.java:451) at org.aspectj.ajdt.internal.compiler.AjPipeliningCompilerAdapter.queueForWeaving(AjPipeliningCompilerAdapter.java:389) at org.aspectj.ajdt.internal.compiler.AjPipeliningCompilerAdapter.afterProcessing(AjPipeliningCompilerAdapter.java:377) at org.aspectj.ajdt.internal.compiler.CompilerAdapter.ajc$after$org_aspectj_ajdt_internal_compiler_CompilerAdapter$5$6b855184(CompilerAdapter.aj:98) at org.aspectj.org.eclipse.jdt.internal.compiler.Compiler.process(Compiler.java:533) at org.aspectj.org.eclipse.jdt.internal.compiler.Compiler.compile(Compiler.java:329) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.performCompilation(AjBuildManager.java:891) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.doBuild(AjBuildManager.java:246) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.batchBuild(AjBuildManager.java:165) at org.aspectj.ajde.internal.CompilerAdapter.compile(CompilerAdapter.java:122) at org.aspectj.ajde.internal.AspectJBuildManager$CompilerThread.run(AspectJBuildManager.java:191) trouble in:public class glassbox.agent.ErrorContainmentTest$ErrorMockAspect extends java.lang.Object implements glassbox.agent.api.NotSerializable: private static Throwable ajc$initFailureCause [Synthetic] public static final glassbox.agent.ErrorContainmentTest$ErrorMockAspect ajc$perSingletonInstance [Synthetic] static void <clinit>(): catch java.lang.Throwable -> E0 | INVOKESTATIC glassbox.agent.ErrorContainmentTest$ErrorMockAspect.ajc$postClinit ()V (line 60) catch java.lang.Throwable -> E0 GOTO L0 E0: ASTORE_0 ALOAD_0 PUTSTATIC glassbox.agent.ErrorContainmentTest$ErrorMockAspect.ajc$initFailureCause Ljava/lang/Throwable; L0: RETURN end static void <clinit>() void <init>(): ALOAD_0 // Lglassbox/agent/ErrorContainmentTest$ErrorMockAspect; this (line 60) INVOKESPECIAL java.lang.Object.<init> ()V RETURN end void <init>() public void ajc$before$glassbox_agent_ErrorContainmentTest$ErrorMockAspect$1$9589fc() AdviceAttribute(before, (scope() && call(* hook1())), 0, 1670) : NEW java.lang.RuntimeException (line 64) DUP LDC "rte" INVOKESPECIAL java.lang.RuntimeException.<init> (Ljava/lang/String;)V ATHROW end public void ajc$before$glassbox_agent_ErrorContainmentTest$ErrorMockAspect$1$9589fc() public void ajc$before$glassbox_agent_ErrorContainmentTest$ErrorMockAspect$2$f75db3e2() AdviceAttribute(before, execution(* glassbox.agent.ErrorContainmentTest.hook5()), 0, 1764) : NEW java.lang.RuntimeException (line 67) DUP LDC "rte" INVOKESPECIAL java.lang.RuntimeException.<init> (Ljava/lang/String;)V ATHROW end public void ajc$before$glassbox_agent_ErrorContainmentTest$ErrorMockAspect$2$f75db3e2() public void ajc$around$glassbox_agent_ErrorContainmentTest$ErrorMockAspect$3$a3a17d(org.aspectj.runtime.internal.AroundClosure) AdviceAttribute(around, (scope() && call(* hook2())), 1, 1913) : NEW java.lang.Error (line 71) DUP LDC "foo" INVOKESPECIAL java.lang.Error.<init> (Ljava/lang/String;)V ATHROW end public void ajc$around$glassbox_agent_ErrorContainmentTest$ErrorMockAspect$3$a3a17d(org.aspectj.runtime.internal.AroundClosure) static void ajc$around$glassbox_agent_ErrorContainmentTest$ErrorMockAspect$3$a3a17dproceed(org.aspectj.runtime.internal.AroundClosure) throws java.lang.Throwable org.aspectj.weaver.AjAttribute$AjSynthetic@19a01f9 : ALOAD_0 // Lglassbox/agent/ErrorContainmentTest$ErrorMockAspect; this (line 1) ICONST_0 ANEWARRAY java.lang.Object INVOKEVIRTUAL org.aspectj.runtime.internal.AroundClosure.run ([Ljava/lang/Object;)Ljava/lang/Object; INVOKESTATIC org.aspectj.runtime.internal.Conversions.voidValue (Ljava/lang/Object;)Ljava/lang/Object; RETURN end static void ajc$around$glassbox_agent_ErrorContainmentTest$ErrorMockAspect$3$a3a17dproceed(org.aspectj.runtime.internal.AroundClosure) throws java.lang.Throwable public void ajc$after$glassbox_agent_ErrorContainmentTest$ErrorMockAspect$4$bfd07f() AdviceAttribute(after, (scope() && call(* hook4())), 0, 1991) : NEW org.aspectj.lang.SoftException (line 74) DUP ACONST_NULL INVOKESPECIAL org.aspectj.lang.SoftException.<init> (Ljava/lang/Throwable;)V ATHROW end public void ajc$after$glassbox_agent_ErrorContainmentTest$ErrorMockAspect$4$bfd07f() public void ajc$before$glassbox_agent_ErrorContainmentTest$ErrorMockAspect$5$e5bddfdc() AdviceAttribute(before, logErrorInTest(), 0, 2446) : GETSTATIC glassbox.agent.ErrorContainmentTest.logCount I (line 84) ICONST_1 IADD PUTSTATIC glassbox.agent.ErrorContainmentTest.logCount I RETURN (line 85) end public void ajc$before$glassbox_agent_ErrorContainmentTest$ErrorMockAspect$5$e5bddfdc() public void ajc$before$glassbox_agent_ErrorContainmentTest$ErrorMockAspect$6$16ecfe62() AdviceAttribute(before, (adviceexecution(* *) && (within(glassbox.util.logging.api.LogManagement) && (cflow(logError()) && cflow((execution(* testLoggingError(..)) && within(glassbox.agent.ErrorContainmentTest)))))), 0, 2506) : GETSTATIC java.lang.System.err Ljava/io/PrintStream; (line 87) LDC "match" INVOKEVIRTUAL java.io.PrintStream.println (Ljava/lang/String;)V RETURN (line 88) end public void ajc$before$glassbox_agent_ErrorContainmentTest$ErrorMockAspect$6$16ecfe62() public void ajc$before$glassbox_agent_ErrorContainmentTest$ErrorMockAspect$7$e9ae8482() AdviceAttribute(before, (adviceexecution(* *) && (within(glassbox.util.logging.api.LogManagement) && cflow((execution(* testLoggingError(..)) && within(glassbox.agent.ErrorContainmentTest))))), 0, 2721) : GETSTATIC java.lang.System.err Ljava/io/PrintStream; (line 90) LDC "match in test" INVOKEVIRTUAL java.io.PrintStream.println (Ljava/lang/String;)V RETURN (line 91) end public void ajc$before$glassbox_agent_ErrorContainmentTest$ErrorMockAspect$7$e9ae8482() public void ajc$before$glassbox_agent_ErrorContainmentTest$ErrorMockAspect$8$c6ac5351() AdviceAttribute(before, (adviceexecution(* *) && (within(glassbox.util.logging.api.LogManagement) && cflow(logError()))), 0, 2923) : GETSTATIC java.lang.System.err Ljava/io/PrintStream; (line 93) LDC "match in log" INVOKEVIRTUAL java.io.PrintStream.println (Ljava/lang/String;)V RETURN (line 94) end public void ajc$before$glassbox_agent_ErrorContainmentTest$ErrorMockAspect$8$c6ac5351() public void ajc$before$glassbox_agent_ErrorContainmentTest$ErrorMockAspect$9$16ecfe62() AdviceAttribute(before, (adviceexecution(* *) && (within(glassbox.util.logging.api.LogManagement) && (cflow(logError()) && cflow((execution(* testLoggingError(..)) && within(glassbox.agent.ErrorContainmentTest)))))), 0, 3069) : GETSTATIC glassbox.agent.ErrorContainmentTest.recursiveThrows I (line 96) ICONST_1 IADD PUTSTATIC glassbox.agent.ErrorContainmentTest.recursiveThrows I GETSTATIC glassbox.agent.ErrorContainmentTest.recursiveThrows I (line 97) ICONST_2 IF_ICMPGE L0 NEW java.lang.RuntimeException (line 98) DUP LDC "recursive logging failure" INVOKESPECIAL java.lang.RuntimeException.<init> (Ljava/lang/String;)V ATHROW L0: RETURN (line 100) end public void ajc$before$glassbox_agent_ErrorContainmentTest$ErrorMockAspect$9$16ecfe62() public static glassbox.agent.ErrorContainmentTest$ErrorMockAspect aspectOf() org.aspectj.weaver.AjAttribute$AjSynthetic@3cd8fe : GETSTATIC glassbox.agent.ErrorContainmentTest$ErrorMockAspect.ajc$perSingletonInstance Lglassbox/agent/ErrorContainmentTest$ErrorMockAspect; (line 1) IFNONNULL L0 NEW org.aspectj.lang.NoAspectBoundException DUP LDC "glassbox_agent_ErrorContainmentTest$ErrorMockAspect" GETSTATIC glassbox.agent.ErrorContainmentTest$ErrorMockAspect.ajc$initFailureCause Ljava/lang/Throwable; INVOKESPECIAL org.aspectj.lang.NoAspectBoundException.<init> (Ljava/lang/String;Ljava/lang/Throwable;)V ATHROW L0: GETSTATIC glassbox.agent.ErrorContainmentTest$ErrorMockAspect.ajc$perSingletonInstance Lglassbox/agent/ErrorContainmentTest$ErrorMockAspect; ARETURN end public static glassbox.agent.ErrorContainmentTest$ErrorMockAspect aspectOf() public static boolean hasAspect() org.aspectj.weaver.AjAttribute$AjSynthetic@1bd4f6 : GETSTATIC glassbox.agent.ErrorContainmentTest$ErrorMockAspect.ajc$perSingletonInstance Lglassbox/agent/ErrorContainmentTest$ErrorMockAspect; (line 1) IFNULL L0 ICONST_1 IRETURN L0: ICONST_0 IRETURN end public static boolean hasAspect() private static void ajc$postClinit() org.aspectj.weaver.AjAttribute$AjSynthetic@1febf91 : NEW glassbox.agent.ErrorContainmentTest$ErrorMockAspect (line 1) DUP INVOKESPECIAL glassbox.agent.ErrorContainmentTest$ErrorMockAspect.<init> ()V PUTSTATIC glassbox.agent.ErrorContainmentTest$ErrorMockAspect.ajc$perSingletonInstance Lglassbox/agent/ErrorContainmentTest$ErrorMockAspect; RETURN end private static void ajc$postClinit() end public class glassbox.agent.ErrorContainmentTest$ErrorMockAspect when type munging with (BcelTypeMunger ResolvedTypeMunger(Parent, null)) when weaving aspects when weaving when batch building BuildConfig[C:\devel\glassbox\.metadata\.plugins\org.eclipse.ajdt.core\glassboxMonitor.generated.lst] #Files=107 The source is: public class ErrorContainmentTest extends TestCase { ... static aspect ErrorMockAspect implements NotSerializable { ... I will try to narrow this down if the problem isn't obvious.
|
resolved fixed
|
ff2377a
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-08-04T10:29:04Z | 2006-08-02T17:33:20Z |
tests/bugs153/pr152631/EMA.java
| |
152,631 |
Bug 152631 Problem with decp on an aspect using cflow
|
This occurs in the AspectJ build in AJDT from August 1 but not from July 31: java.lang.NullPointerException at org.aspectj.weaver.bcel.BcelTypeMunger.enforceDecpRule1_abstractMethodsImplemented(BcelTypeMunger.java:250) at org.aspectj.weaver.bcel.BcelTypeMunger.mungeNewParent(BcelTypeMunger.java:194) at org.aspectj.weaver.bcel.BcelTypeMunger.munge(BcelTypeMunger.java:106) at org.aspectj.weaver.bcel.BcelClassWeaver.weave(BcelClassWeaver.java:454) at org.aspectj.weaver.bcel.BcelClassWeaver.weave(BcelClassWeaver.java:119) at org.aspectj.weaver.bcel.BcelWeaver.weave(BcelWeaver.java:1597) at org.aspectj.weaver.bcel.BcelWeaver.weaveWithoutDump(BcelWeaver.java:1548) at org.aspectj.weaver.bcel.BcelWeaver.weaveAndNotify(BcelWeaver.java:1328) at org.aspectj.weaver.bcel.BcelWeaver.weave(BcelWeaver.java:1124) at org.aspectj.ajdt.internal.compiler.AjPipeliningCompilerAdapter.weaveQueuedEntries(AjPipeliningCompilerAdapter.java:451) at org.aspectj.ajdt.internal.compiler.AjPipeliningCompilerAdapter.queueForWeaving(AjPipeliningCompilerAdapter.java:389) at org.aspectj.ajdt.internal.compiler.AjPipeliningCompilerAdapter.afterProcessing(AjPipeliningCompilerAdapter.java:377) at org.aspectj.ajdt.internal.compiler.CompilerAdapter.ajc$after$org_aspectj_ajdt_internal_compiler_CompilerAdapter$5$6b855184(CompilerAdapter.aj:98) at org.aspectj.org.eclipse.jdt.internal.compiler.Compiler.process(Compiler.java:533) at org.aspectj.org.eclipse.jdt.internal.compiler.Compiler.compile(Compiler.java:329) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.performCompilation(AjBuildManager.java:891) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.doBuild(AjBuildManager.java:246) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.batchBuild(AjBuildManager.java:165) at org.aspectj.ajde.internal.CompilerAdapter.compile(CompilerAdapter.java:122) at org.aspectj.ajde.internal.AspectJBuildManager$CompilerThread.run(AspectJBuildManager.java:191) trouble in:public class glassbox.agent.ErrorContainmentTest$ErrorMockAspect extends java.lang.Object implements glassbox.agent.api.NotSerializable: private static Throwable ajc$initFailureCause [Synthetic] public static final glassbox.agent.ErrorContainmentTest$ErrorMockAspect ajc$perSingletonInstance [Synthetic] static void <clinit>(): catch java.lang.Throwable -> E0 | INVOKESTATIC glassbox.agent.ErrorContainmentTest$ErrorMockAspect.ajc$postClinit ()V (line 60) catch java.lang.Throwable -> E0 GOTO L0 E0: ASTORE_0 ALOAD_0 PUTSTATIC glassbox.agent.ErrorContainmentTest$ErrorMockAspect.ajc$initFailureCause Ljava/lang/Throwable; L0: RETURN end static void <clinit>() void <init>(): ALOAD_0 // Lglassbox/agent/ErrorContainmentTest$ErrorMockAspect; this (line 60) INVOKESPECIAL java.lang.Object.<init> ()V RETURN end void <init>() public void ajc$before$glassbox_agent_ErrorContainmentTest$ErrorMockAspect$1$9589fc() AdviceAttribute(before, (scope() && call(* hook1())), 0, 1670) : NEW java.lang.RuntimeException (line 64) DUP LDC "rte" INVOKESPECIAL java.lang.RuntimeException.<init> (Ljava/lang/String;)V ATHROW end public void ajc$before$glassbox_agent_ErrorContainmentTest$ErrorMockAspect$1$9589fc() public void ajc$before$glassbox_agent_ErrorContainmentTest$ErrorMockAspect$2$f75db3e2() AdviceAttribute(before, execution(* glassbox.agent.ErrorContainmentTest.hook5()), 0, 1764) : NEW java.lang.RuntimeException (line 67) DUP LDC "rte" INVOKESPECIAL java.lang.RuntimeException.<init> (Ljava/lang/String;)V ATHROW end public void ajc$before$glassbox_agent_ErrorContainmentTest$ErrorMockAspect$2$f75db3e2() public void ajc$around$glassbox_agent_ErrorContainmentTest$ErrorMockAspect$3$a3a17d(org.aspectj.runtime.internal.AroundClosure) AdviceAttribute(around, (scope() && call(* hook2())), 1, 1913) : NEW java.lang.Error (line 71) DUP LDC "foo" INVOKESPECIAL java.lang.Error.<init> (Ljava/lang/String;)V ATHROW end public void ajc$around$glassbox_agent_ErrorContainmentTest$ErrorMockAspect$3$a3a17d(org.aspectj.runtime.internal.AroundClosure) static void ajc$around$glassbox_agent_ErrorContainmentTest$ErrorMockAspect$3$a3a17dproceed(org.aspectj.runtime.internal.AroundClosure) throws java.lang.Throwable org.aspectj.weaver.AjAttribute$AjSynthetic@19a01f9 : ALOAD_0 // Lglassbox/agent/ErrorContainmentTest$ErrorMockAspect; this (line 1) ICONST_0 ANEWARRAY java.lang.Object INVOKEVIRTUAL org.aspectj.runtime.internal.AroundClosure.run ([Ljava/lang/Object;)Ljava/lang/Object; INVOKESTATIC org.aspectj.runtime.internal.Conversions.voidValue (Ljava/lang/Object;)Ljava/lang/Object; RETURN end static void ajc$around$glassbox_agent_ErrorContainmentTest$ErrorMockAspect$3$a3a17dproceed(org.aspectj.runtime.internal.AroundClosure) throws java.lang.Throwable public void ajc$after$glassbox_agent_ErrorContainmentTest$ErrorMockAspect$4$bfd07f() AdviceAttribute(after, (scope() && call(* hook4())), 0, 1991) : NEW org.aspectj.lang.SoftException (line 74) DUP ACONST_NULL INVOKESPECIAL org.aspectj.lang.SoftException.<init> (Ljava/lang/Throwable;)V ATHROW end public void ajc$after$glassbox_agent_ErrorContainmentTest$ErrorMockAspect$4$bfd07f() public void ajc$before$glassbox_agent_ErrorContainmentTest$ErrorMockAspect$5$e5bddfdc() AdviceAttribute(before, logErrorInTest(), 0, 2446) : GETSTATIC glassbox.agent.ErrorContainmentTest.logCount I (line 84) ICONST_1 IADD PUTSTATIC glassbox.agent.ErrorContainmentTest.logCount I RETURN (line 85) end public void ajc$before$glassbox_agent_ErrorContainmentTest$ErrorMockAspect$5$e5bddfdc() public void ajc$before$glassbox_agent_ErrorContainmentTest$ErrorMockAspect$6$16ecfe62() AdviceAttribute(before, (adviceexecution(* *) && (within(glassbox.util.logging.api.LogManagement) && (cflow(logError()) && cflow((execution(* testLoggingError(..)) && within(glassbox.agent.ErrorContainmentTest)))))), 0, 2506) : GETSTATIC java.lang.System.err Ljava/io/PrintStream; (line 87) LDC "match" INVOKEVIRTUAL java.io.PrintStream.println (Ljava/lang/String;)V RETURN (line 88) end public void ajc$before$glassbox_agent_ErrorContainmentTest$ErrorMockAspect$6$16ecfe62() public void ajc$before$glassbox_agent_ErrorContainmentTest$ErrorMockAspect$7$e9ae8482() AdviceAttribute(before, (adviceexecution(* *) && (within(glassbox.util.logging.api.LogManagement) && cflow((execution(* testLoggingError(..)) && within(glassbox.agent.ErrorContainmentTest))))), 0, 2721) : GETSTATIC java.lang.System.err Ljava/io/PrintStream; (line 90) LDC "match in test" INVOKEVIRTUAL java.io.PrintStream.println (Ljava/lang/String;)V RETURN (line 91) end public void ajc$before$glassbox_agent_ErrorContainmentTest$ErrorMockAspect$7$e9ae8482() public void ajc$before$glassbox_agent_ErrorContainmentTest$ErrorMockAspect$8$c6ac5351() AdviceAttribute(before, (adviceexecution(* *) && (within(glassbox.util.logging.api.LogManagement) && cflow(logError()))), 0, 2923) : GETSTATIC java.lang.System.err Ljava/io/PrintStream; (line 93) LDC "match in log" INVOKEVIRTUAL java.io.PrintStream.println (Ljava/lang/String;)V RETURN (line 94) end public void ajc$before$glassbox_agent_ErrorContainmentTest$ErrorMockAspect$8$c6ac5351() public void ajc$before$glassbox_agent_ErrorContainmentTest$ErrorMockAspect$9$16ecfe62() AdviceAttribute(before, (adviceexecution(* *) && (within(glassbox.util.logging.api.LogManagement) && (cflow(logError()) && cflow((execution(* testLoggingError(..)) && within(glassbox.agent.ErrorContainmentTest)))))), 0, 3069) : GETSTATIC glassbox.agent.ErrorContainmentTest.recursiveThrows I (line 96) ICONST_1 IADD PUTSTATIC glassbox.agent.ErrorContainmentTest.recursiveThrows I GETSTATIC glassbox.agent.ErrorContainmentTest.recursiveThrows I (line 97) ICONST_2 IF_ICMPGE L0 NEW java.lang.RuntimeException (line 98) DUP LDC "recursive logging failure" INVOKESPECIAL java.lang.RuntimeException.<init> (Ljava/lang/String;)V ATHROW L0: RETURN (line 100) end public void ajc$before$glassbox_agent_ErrorContainmentTest$ErrorMockAspect$9$16ecfe62() public static glassbox.agent.ErrorContainmentTest$ErrorMockAspect aspectOf() org.aspectj.weaver.AjAttribute$AjSynthetic@3cd8fe : GETSTATIC glassbox.agent.ErrorContainmentTest$ErrorMockAspect.ajc$perSingletonInstance Lglassbox/agent/ErrorContainmentTest$ErrorMockAspect; (line 1) IFNONNULL L0 NEW org.aspectj.lang.NoAspectBoundException DUP LDC "glassbox_agent_ErrorContainmentTest$ErrorMockAspect" GETSTATIC glassbox.agent.ErrorContainmentTest$ErrorMockAspect.ajc$initFailureCause Ljava/lang/Throwable; INVOKESPECIAL org.aspectj.lang.NoAspectBoundException.<init> (Ljava/lang/String;Ljava/lang/Throwable;)V ATHROW L0: GETSTATIC glassbox.agent.ErrorContainmentTest$ErrorMockAspect.ajc$perSingletonInstance Lglassbox/agent/ErrorContainmentTest$ErrorMockAspect; ARETURN end public static glassbox.agent.ErrorContainmentTest$ErrorMockAspect aspectOf() public static boolean hasAspect() org.aspectj.weaver.AjAttribute$AjSynthetic@1bd4f6 : GETSTATIC glassbox.agent.ErrorContainmentTest$ErrorMockAspect.ajc$perSingletonInstance Lglassbox/agent/ErrorContainmentTest$ErrorMockAspect; (line 1) IFNULL L0 ICONST_1 IRETURN L0: ICONST_0 IRETURN end public static boolean hasAspect() private static void ajc$postClinit() org.aspectj.weaver.AjAttribute$AjSynthetic@1febf91 : NEW glassbox.agent.ErrorContainmentTest$ErrorMockAspect (line 1) DUP INVOKESPECIAL glassbox.agent.ErrorContainmentTest$ErrorMockAspect.<init> ()V PUTSTATIC glassbox.agent.ErrorContainmentTest$ErrorMockAspect.ajc$perSingletonInstance Lglassbox/agent/ErrorContainmentTest$ErrorMockAspect; RETURN end private static void ajc$postClinit() end public class glassbox.agent.ErrorContainmentTest$ErrorMockAspect when type munging with (BcelTypeMunger ResolvedTypeMunger(Parent, null)) when weaving aspects when weaving when batch building BuildConfig[C:\devel\glassbox\.metadata\.plugins\org.eclipse.ajdt.core\glassboxMonitor.generated.lst] #Files=107 The source is: public class ErrorContainmentTest extends TestCase { ... static aspect ErrorMockAspect implements NotSerializable { ... I will try to narrow this down if the problem isn't obvious.
|
resolved fixed
|
ff2377a
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-08-04T10:29:04Z | 2006-08-02T17:33:20Z |
tests/src/org/aspectj/systemtest/ajc153/Ajc153Tests.java
|
/*******************************************************************************
* Copyright (c) 2006 IBM
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Andy Clement - initial API and implementation
*******************************************************************************/
package org.aspectj.systemtest.ajc153;
import java.io.File;
import junit.framework.Test;
import org.aspectj.testing.Utils;
import org.aspectj.testing.XMLBasedAjcTestCase;
public class Ajc153Tests extends org.aspectj.testing.XMLBasedAjcTestCase {
//public void testGenericsProblem_pr151978() { runTest("generics problem");}
//public void testMissingLineNumbersInStacktraceBefore_pr145442() { runTest("missing line numbers in stacktrace before");}
//public void testMissingLineNumbersInStacktraceAfter_pr145442() { runTest("missing line numbers in stacktrace after");}
//public void testMissingLineNumbersInStacktraceAround_pr145442() { runTest("missing line numbers in stacktrace around");}
// public void testArgnamesAndJavac_pr148381() { runTest("argNames and javac");}
// public void testCFlowXMLAspectLTW_pr149096() { runTest("cflow xml concrete aspect"); }
// public void testAmbiguousBinding_pr121805() { runTest("ambiguous binding");}
public void testGenericInheritanceDecp_pr150095() { runTest("generics, inheritance and decp");}
public void testIllegalStateException_pr148737() { runTest("illegalstateexception for non generic type");}
public void testAtajInheritance_pr149305_1() { runTest("ataj inheritance - 1");}
public void testAtajInheritance_pr149305_2() { runTest("ataj inheritance - 2");}
public void testAtajInheritance_pr149305_3() { runTest("ataj inheritance - 3");}
public void testVerificationFailureForAspectOf_pr148693() {
runTest("verification problem"); // build the code
Utils.verifyClass(ajc,"mypackage.MyAspect"); // verify it <<< BRAND NEW VERIFY UTILITY FOR EVERYONE TO TRY ;)
}
public void testIncorrectAnnotationValue_pr148537() { runTest("incorrect annotation value");}
public void testVerifyErrNoTypeCflowField_pr145693_1() { runTest("verifyErrNoTypeCflowField"); }
public void testVerifyErrInpathNoTypeCflowField_pr145693_2() { runTest("verifyErrInpathNoTypeCflowField"); }
public void testCpathNoTypeCflowField_pr145693_3() { runTest("cpathNoTypeCflowField"); }
// public void testVisibilityProblem_pr149071() { runTest("visibility problem");}
// public void testAdviceNotWovenAspectPath_pr147841() { runTest("advice not woven on aspectpath");}
public void testGenericSignatures_pr148409() { runTest("generic signature problem"); }
// public void testBrokenIfArgsCflowAtAj_pr145018() { runTest("ataj crashing with cflow, if and args");}
public void testCantFindType_pr149322_01() {runTest("can't find type on interface call 1");}
public void testCantFindType_pr149322_02() {runTest("can't find type on interface call 2");}
public void testCantFindType_pr149322_03() {runTest("can't find type on interface call 3");}
public void testMatchVolatileField_pr150671() {runTest("match volatile field");};
public void testDuplicateJVMTIAgents_pr151938() {runTest("Duplicate JVMTI agents");};
/////////////////////////////////////////
public static Test suite() {
return XMLBasedAjcTestCase.loadSuite(Ajc153Tests.class);
}
protected File getSpecFile() {
return new File("../tests/src/org/aspectj/systemtest/ajc153/ajc153.xml");
}
}
|
152,631 |
Bug 152631 Problem with decp on an aspect using cflow
|
This occurs in the AspectJ build in AJDT from August 1 but not from July 31: java.lang.NullPointerException at org.aspectj.weaver.bcel.BcelTypeMunger.enforceDecpRule1_abstractMethodsImplemented(BcelTypeMunger.java:250) at org.aspectj.weaver.bcel.BcelTypeMunger.mungeNewParent(BcelTypeMunger.java:194) at org.aspectj.weaver.bcel.BcelTypeMunger.munge(BcelTypeMunger.java:106) at org.aspectj.weaver.bcel.BcelClassWeaver.weave(BcelClassWeaver.java:454) at org.aspectj.weaver.bcel.BcelClassWeaver.weave(BcelClassWeaver.java:119) at org.aspectj.weaver.bcel.BcelWeaver.weave(BcelWeaver.java:1597) at org.aspectj.weaver.bcel.BcelWeaver.weaveWithoutDump(BcelWeaver.java:1548) at org.aspectj.weaver.bcel.BcelWeaver.weaveAndNotify(BcelWeaver.java:1328) at org.aspectj.weaver.bcel.BcelWeaver.weave(BcelWeaver.java:1124) at org.aspectj.ajdt.internal.compiler.AjPipeliningCompilerAdapter.weaveQueuedEntries(AjPipeliningCompilerAdapter.java:451) at org.aspectj.ajdt.internal.compiler.AjPipeliningCompilerAdapter.queueForWeaving(AjPipeliningCompilerAdapter.java:389) at org.aspectj.ajdt.internal.compiler.AjPipeliningCompilerAdapter.afterProcessing(AjPipeliningCompilerAdapter.java:377) at org.aspectj.ajdt.internal.compiler.CompilerAdapter.ajc$after$org_aspectj_ajdt_internal_compiler_CompilerAdapter$5$6b855184(CompilerAdapter.aj:98) at org.aspectj.org.eclipse.jdt.internal.compiler.Compiler.process(Compiler.java:533) at org.aspectj.org.eclipse.jdt.internal.compiler.Compiler.compile(Compiler.java:329) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.performCompilation(AjBuildManager.java:891) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.doBuild(AjBuildManager.java:246) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.batchBuild(AjBuildManager.java:165) at org.aspectj.ajde.internal.CompilerAdapter.compile(CompilerAdapter.java:122) at org.aspectj.ajde.internal.AspectJBuildManager$CompilerThread.run(AspectJBuildManager.java:191) trouble in:public class glassbox.agent.ErrorContainmentTest$ErrorMockAspect extends java.lang.Object implements glassbox.agent.api.NotSerializable: private static Throwable ajc$initFailureCause [Synthetic] public static final glassbox.agent.ErrorContainmentTest$ErrorMockAspect ajc$perSingletonInstance [Synthetic] static void <clinit>(): catch java.lang.Throwable -> E0 | INVOKESTATIC glassbox.agent.ErrorContainmentTest$ErrorMockAspect.ajc$postClinit ()V (line 60) catch java.lang.Throwable -> E0 GOTO L0 E0: ASTORE_0 ALOAD_0 PUTSTATIC glassbox.agent.ErrorContainmentTest$ErrorMockAspect.ajc$initFailureCause Ljava/lang/Throwable; L0: RETURN end static void <clinit>() void <init>(): ALOAD_0 // Lglassbox/agent/ErrorContainmentTest$ErrorMockAspect; this (line 60) INVOKESPECIAL java.lang.Object.<init> ()V RETURN end void <init>() public void ajc$before$glassbox_agent_ErrorContainmentTest$ErrorMockAspect$1$9589fc() AdviceAttribute(before, (scope() && call(* hook1())), 0, 1670) : NEW java.lang.RuntimeException (line 64) DUP LDC "rte" INVOKESPECIAL java.lang.RuntimeException.<init> (Ljava/lang/String;)V ATHROW end public void ajc$before$glassbox_agent_ErrorContainmentTest$ErrorMockAspect$1$9589fc() public void ajc$before$glassbox_agent_ErrorContainmentTest$ErrorMockAspect$2$f75db3e2() AdviceAttribute(before, execution(* glassbox.agent.ErrorContainmentTest.hook5()), 0, 1764) : NEW java.lang.RuntimeException (line 67) DUP LDC "rte" INVOKESPECIAL java.lang.RuntimeException.<init> (Ljava/lang/String;)V ATHROW end public void ajc$before$glassbox_agent_ErrorContainmentTest$ErrorMockAspect$2$f75db3e2() public void ajc$around$glassbox_agent_ErrorContainmentTest$ErrorMockAspect$3$a3a17d(org.aspectj.runtime.internal.AroundClosure) AdviceAttribute(around, (scope() && call(* hook2())), 1, 1913) : NEW java.lang.Error (line 71) DUP LDC "foo" INVOKESPECIAL java.lang.Error.<init> (Ljava/lang/String;)V ATHROW end public void ajc$around$glassbox_agent_ErrorContainmentTest$ErrorMockAspect$3$a3a17d(org.aspectj.runtime.internal.AroundClosure) static void ajc$around$glassbox_agent_ErrorContainmentTest$ErrorMockAspect$3$a3a17dproceed(org.aspectj.runtime.internal.AroundClosure) throws java.lang.Throwable org.aspectj.weaver.AjAttribute$AjSynthetic@19a01f9 : ALOAD_0 // Lglassbox/agent/ErrorContainmentTest$ErrorMockAspect; this (line 1) ICONST_0 ANEWARRAY java.lang.Object INVOKEVIRTUAL org.aspectj.runtime.internal.AroundClosure.run ([Ljava/lang/Object;)Ljava/lang/Object; INVOKESTATIC org.aspectj.runtime.internal.Conversions.voidValue (Ljava/lang/Object;)Ljava/lang/Object; RETURN end static void ajc$around$glassbox_agent_ErrorContainmentTest$ErrorMockAspect$3$a3a17dproceed(org.aspectj.runtime.internal.AroundClosure) throws java.lang.Throwable public void ajc$after$glassbox_agent_ErrorContainmentTest$ErrorMockAspect$4$bfd07f() AdviceAttribute(after, (scope() && call(* hook4())), 0, 1991) : NEW org.aspectj.lang.SoftException (line 74) DUP ACONST_NULL INVOKESPECIAL org.aspectj.lang.SoftException.<init> (Ljava/lang/Throwable;)V ATHROW end public void ajc$after$glassbox_agent_ErrorContainmentTest$ErrorMockAspect$4$bfd07f() public void ajc$before$glassbox_agent_ErrorContainmentTest$ErrorMockAspect$5$e5bddfdc() AdviceAttribute(before, logErrorInTest(), 0, 2446) : GETSTATIC glassbox.agent.ErrorContainmentTest.logCount I (line 84) ICONST_1 IADD PUTSTATIC glassbox.agent.ErrorContainmentTest.logCount I RETURN (line 85) end public void ajc$before$glassbox_agent_ErrorContainmentTest$ErrorMockAspect$5$e5bddfdc() public void ajc$before$glassbox_agent_ErrorContainmentTest$ErrorMockAspect$6$16ecfe62() AdviceAttribute(before, (adviceexecution(* *) && (within(glassbox.util.logging.api.LogManagement) && (cflow(logError()) && cflow((execution(* testLoggingError(..)) && within(glassbox.agent.ErrorContainmentTest)))))), 0, 2506) : GETSTATIC java.lang.System.err Ljava/io/PrintStream; (line 87) LDC "match" INVOKEVIRTUAL java.io.PrintStream.println (Ljava/lang/String;)V RETURN (line 88) end public void ajc$before$glassbox_agent_ErrorContainmentTest$ErrorMockAspect$6$16ecfe62() public void ajc$before$glassbox_agent_ErrorContainmentTest$ErrorMockAspect$7$e9ae8482() AdviceAttribute(before, (adviceexecution(* *) && (within(glassbox.util.logging.api.LogManagement) && cflow((execution(* testLoggingError(..)) && within(glassbox.agent.ErrorContainmentTest))))), 0, 2721) : GETSTATIC java.lang.System.err Ljava/io/PrintStream; (line 90) LDC "match in test" INVOKEVIRTUAL java.io.PrintStream.println (Ljava/lang/String;)V RETURN (line 91) end public void ajc$before$glassbox_agent_ErrorContainmentTest$ErrorMockAspect$7$e9ae8482() public void ajc$before$glassbox_agent_ErrorContainmentTest$ErrorMockAspect$8$c6ac5351() AdviceAttribute(before, (adviceexecution(* *) && (within(glassbox.util.logging.api.LogManagement) && cflow(logError()))), 0, 2923) : GETSTATIC java.lang.System.err Ljava/io/PrintStream; (line 93) LDC "match in log" INVOKEVIRTUAL java.io.PrintStream.println (Ljava/lang/String;)V RETURN (line 94) end public void ajc$before$glassbox_agent_ErrorContainmentTest$ErrorMockAspect$8$c6ac5351() public void ajc$before$glassbox_agent_ErrorContainmentTest$ErrorMockAspect$9$16ecfe62() AdviceAttribute(before, (adviceexecution(* *) && (within(glassbox.util.logging.api.LogManagement) && (cflow(logError()) && cflow((execution(* testLoggingError(..)) && within(glassbox.agent.ErrorContainmentTest)))))), 0, 3069) : GETSTATIC glassbox.agent.ErrorContainmentTest.recursiveThrows I (line 96) ICONST_1 IADD PUTSTATIC glassbox.agent.ErrorContainmentTest.recursiveThrows I GETSTATIC glassbox.agent.ErrorContainmentTest.recursiveThrows I (line 97) ICONST_2 IF_ICMPGE L0 NEW java.lang.RuntimeException (line 98) DUP LDC "recursive logging failure" INVOKESPECIAL java.lang.RuntimeException.<init> (Ljava/lang/String;)V ATHROW L0: RETURN (line 100) end public void ajc$before$glassbox_agent_ErrorContainmentTest$ErrorMockAspect$9$16ecfe62() public static glassbox.agent.ErrorContainmentTest$ErrorMockAspect aspectOf() org.aspectj.weaver.AjAttribute$AjSynthetic@3cd8fe : GETSTATIC glassbox.agent.ErrorContainmentTest$ErrorMockAspect.ajc$perSingletonInstance Lglassbox/agent/ErrorContainmentTest$ErrorMockAspect; (line 1) IFNONNULL L0 NEW org.aspectj.lang.NoAspectBoundException DUP LDC "glassbox_agent_ErrorContainmentTest$ErrorMockAspect" GETSTATIC glassbox.agent.ErrorContainmentTest$ErrorMockAspect.ajc$initFailureCause Ljava/lang/Throwable; INVOKESPECIAL org.aspectj.lang.NoAspectBoundException.<init> (Ljava/lang/String;Ljava/lang/Throwable;)V ATHROW L0: GETSTATIC glassbox.agent.ErrorContainmentTest$ErrorMockAspect.ajc$perSingletonInstance Lglassbox/agent/ErrorContainmentTest$ErrorMockAspect; ARETURN end public static glassbox.agent.ErrorContainmentTest$ErrorMockAspect aspectOf() public static boolean hasAspect() org.aspectj.weaver.AjAttribute$AjSynthetic@1bd4f6 : GETSTATIC glassbox.agent.ErrorContainmentTest$ErrorMockAspect.ajc$perSingletonInstance Lglassbox/agent/ErrorContainmentTest$ErrorMockAspect; (line 1) IFNULL L0 ICONST_1 IRETURN L0: ICONST_0 IRETURN end public static boolean hasAspect() private static void ajc$postClinit() org.aspectj.weaver.AjAttribute$AjSynthetic@1febf91 : NEW glassbox.agent.ErrorContainmentTest$ErrorMockAspect (line 1) DUP INVOKESPECIAL glassbox.agent.ErrorContainmentTest$ErrorMockAspect.<init> ()V PUTSTATIC glassbox.agent.ErrorContainmentTest$ErrorMockAspect.ajc$perSingletonInstance Lglassbox/agent/ErrorContainmentTest$ErrorMockAspect; RETURN end private static void ajc$postClinit() end public class glassbox.agent.ErrorContainmentTest$ErrorMockAspect when type munging with (BcelTypeMunger ResolvedTypeMunger(Parent, null)) when weaving aspects when weaving when batch building BuildConfig[C:\devel\glassbox\.metadata\.plugins\org.eclipse.ajdt.core\glassboxMonitor.generated.lst] #Files=107 The source is: public class ErrorContainmentTest extends TestCase { ... static aspect ErrorMockAspect implements NotSerializable { ... I will try to narrow this down if the problem isn't obvious.
|
resolved fixed
|
ff2377a
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-08-04T10:29:04Z | 2006-08-02T17:33:20Z |
weaver/src/org/aspectj/weaver/bcel/BcelTypeMunger.java
|
/* *******************************************************************
* Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC).
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Eclipse Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* PARC initial implementation
* Alexandre Vasseur @AspectJ ITDs
* ******************************************************************/
package org.aspectj.weaver.bcel;
import java.lang.reflect.Modifier;
import java.util.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().getKind() == ResolvedTypeMunger.Method) {
ResolvedMember sig = m.getSignature();
if (!Modifier.isAbstract(sig.getModifiers())) {
// If the ITD shares a type variable with some target type, we need to tailor it for that
// type
if (m.isTargetTypeParameterized()) {
ResolvedType genericOnType = getWorld().resolve(sig.getDeclaringType()).getGenericType();
m = m.parameterizedFor(newParent.discoverActualOccurrenceOfTypeInHierarchy(genericOnType));
sig = m.getSignature(); // possible sig change when type parameters filled in
}
if (ResolvedType
.matches(
AjcMemberMaker.interMethod(
sig,m.getAspectType(),sig.getDeclaringType().resolve(weaver.getWorld()).isInterface()),o)) {
satisfiedByITD = true;
}
}
} else if (m.getMunger().getKind() == ResolvedTypeMunger.MethodDelegate) {
satisfiedByITD = true;//AV - that should be enough, no need to check more
}
}
if (!satisfiedByITD) {
error(weaver,
"The type " + newParentTarget.getName() + " must implement the inherited abstract method "+o.getDeclaringType()+"."+o.getName()+o.getParameterSignature(),
newParentTarget.getType().getSourceLocation(),new ISourceLocation[]{o.getSourceLocation(),mungerLoc});
ruleCheckingSucceeded=false;
}
}
}
}
}
return ruleCheckingSucceeded;
}
/**
* Rule 2. Can't extend final types
*/
private boolean enforceDecpRule2_cantExtendFinalClass(BcelClassWeaver weaver, ISourceLocation mungerLoc,
LazyClassGen newParentTarget, ResolvedType newParent) {
if (newParent.isFinal()) {
error(weaver,"Cannot make type "+newParentTarget.getName()+" extend final class "+newParent.getName(),
newParentTarget.getType().getSourceLocation(),
new ISourceLocation[]{mungerLoc});
return false;
}
return true;
}
/**
* Rule 3. Can't narrow visibility of methods when overriding
*/
private boolean enforceDecpRule3_visibilityChanges(BcelClassWeaver weaver, ResolvedType newParent, ResolvedMember superMethod, LazyMethodGen subMethod) {
boolean cont = true;
if (superMethod.isPublic()) {
if (subMethod.isProtected() || subMethod.isDefault() || subMethod.isPrivate()) {
weaver.getWorld().getMessageHandler().handleMessage(MessageUtil.error(
"Cannot reduce the visibility of the inherited method '"+superMethod+"' from "+newParent.getName(),
superMethod.getSourceLocation()));
cont=false;
}
} else if (superMethod.isProtected()) {
if (subMethod.isDefault() || subMethod.isPrivate()) {
weaver.getWorld().getMessageHandler().handleMessage(MessageUtil.error(
"Cannot reduce the visibility of the inherited method '"+superMethod+"' from "+newParent.getName(),
superMethod.getSourceLocation()));
cont=false;
}
} else if (superMethod.isDefault()) {
if (subMethod.isPrivate()) {
weaver.getWorld().getMessageHandler().handleMessage(MessageUtil.error(
"Cannot reduce the visibility of the inherited method '"+superMethod+"' from "+newParent.getName(),
superMethod.getSourceLocation()));
cont=false;
}
}
return cont;
}
/**
* Rule 4. Can't have incompatible return types
*/
private boolean enforceDecpRule4_compatibleReturnTypes(BcelClassWeaver weaver, ResolvedMember superMethod, LazyMethodGen subMethod) {
boolean cont = true;
String superReturnTypeSig = superMethod.getReturnType().getSignature();
String subReturnTypeSig = subMethod.getReturnType().getSignature();
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;
}
}
|
152,835 |
Bug 152835 ArrayIndexOutOfBoundsException in EclipseAdapterUtils.makeLocationContext
|
Got the following exception during startup of Eclipse java.lang.ArrayIndexOutOfBoundsException at org.aspectj.ajdt.internal.core.builder.EclipseAdapterUtils.makeLocationContext(EclipseAdapterUtils.java:65) at org.aspectj.ajdt.internal.core.builder.EclipseAdapterUtils.makeSourceLocation(EclipseAdapterUtils.java:121) at org.aspectj.ajdt.internal.core.builder.EclipseAdapterUtils.makeMessage(EclipseAdapterUtils.java:130) at org.aspectj.ajdt.internal.core.builder.AjBuildManager$4.acceptResult(AjBuildManager.java:959) at org.aspectj.ajdt.internal.compiler.AjPipeliningCompilerAdapter.acceptResult(AjPipeliningCompilerAdapter.java:402) at org.aspectj.ajdt.internal.compiler.AjPipeliningCompilerAdapter.afterProcessing(AjPipeliningCompilerAdapter.java:375) at org.aspectj.ajdt.internal.compiler.CompilerAdapter.ajc$after$org_aspectj_ajdt_internal_compiler_CompilerAdapter$5$6b855184(CompilerAdapter.aj:98) at org.aspectj.org.eclipse.jdt.internal.compiler.Compiler.process(Compiler.java:533) at org.aspectj.org.eclipse.jdt.internal.compiler.Compiler.compile(Compiler.java:329) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.performCompilation(AjBuildManager.java:891) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.doBuild(AjBuildManager.java:246) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.batchBuild(AjBuildManager.java:165) at org.aspectj.ajde.internal.CompilerAdapter.compile(CompilerAdapter.java:122) at org.aspectj.ajde.internal.AspectJBuildManager$CompilerThread.run(AspectJBuildManager.java:191) ArrayIndexOutOfBoundsException thrown: -2
|
resolved fixed
|
908b405
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-08-04T11:02:38Z | 2006-08-04T11:13:20Z |
org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/core/builder/EclipseAdapterUtils.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:
* PARC initial implementation
* ******************************************************************/
package org.aspectj.ajdt.internal.core.builder;
import java.io.File;
import org.aspectj.bridge.IMessage;
import org.aspectj.bridge.ISourceLocation;
import org.aspectj.bridge.Message;
import org.aspectj.bridge.SourceLocation;
import org.aspectj.org.eclipse.jdt.core.compiler.IProblem;
import org.aspectj.org.eclipse.jdt.internal.compiler.env.ICompilationUnit;
/**
*
*/
public class EclipseAdapterUtils {
//XXX some cut-and-paste from eclipse sources
public static String makeLocationContext(ICompilationUnit compilationUnit, IProblem problem) {
//extra from the source the innacurate token
//and "highlight" it using some underneath ^^^^^
//put some context around too.
//this code assumes that the font used in the console is fixed size
//sanity .....
int startPosition = problem.getSourceStart();
int endPosition = problem.getSourceEnd();
if ((startPosition > endPosition)
|| ((startPosition <= 0) && (endPosition <= 0))
|| compilationUnit==null)
//return Util.bind("problem.noSourceInformation"); //$NON-NLS-1$
return "(no source information available)";
final char SPACE = '\u0020';
final char MARK = '^';
final char TAB = '\t';
char[] source = compilationUnit.getContents();
//the next code tries to underline the token.....
//it assumes (for a good display) that token source does not
//contain any \r \n. This is false on statements !
//(the code still works but the display is not optimal !)
//compute the how-much-char we are displaying around the inaccurate token
int begin = startPosition >= source.length ? source.length - 1 : startPosition;
int relativeStart = 0;
int end = endPosition >= source.length ? source.length - 1 : endPosition;
int relativeEnd = 0;
label : for (relativeStart = 0;; relativeStart++) {
if (begin == 0)
break label;
if ((source[begin - 1] == '\n') || (source[begin - 1] == '\r'))
break label;
begin--;
}
label : for (relativeEnd = 0;; relativeEnd++) {
if ((end + 1) >= source.length)
break label;
if ((source[end + 1] == '\r') || (source[end + 1] == '\n')) {
break label;
}
end++;
}
//extract the message form the source
char[] extract = new char[end - begin + 1];
System.arraycopy(source, begin, extract, 0, extract.length);
char c;
//remove all SPACE and TAB that begin the error message...
int trimLeftIndex = 0;
while ( (((c = extract[trimLeftIndex++]) == TAB) || (c == SPACE)) && trimLeftIndex<extract.length ) { };
if (trimLeftIndex>=extract.length) return new String(extract)+"\n";
System.arraycopy(
extract,
trimLeftIndex - 1,
extract = new char[extract.length - trimLeftIndex + 1],
0,
extract.length);
relativeStart -= trimLeftIndex;
//buffer spaces and tabs in order to reach the error position
int pos = 0;
char[] underneath = new char[extract.length]; // can't be bigger
for (int i = 0; i <= relativeStart; i++) {
if (extract[i] == TAB) {
underneath[pos++] = TAB;
} else {
underneath[pos++] = SPACE;
}
}
//mark the error position
for (int i = startPosition + trimLeftIndex; // AMC if we took stuff off the start, take it into account!
i <= (endPosition >= source.length ? source.length - 1 : endPosition);
i++)
underneath[pos++] = MARK;
//resize underneathto remove 'null' chars
System.arraycopy(underneath, 0, underneath = new char[pos], 0, pos);
return new String(extract) + "\n" + new String(underneath); //$NON-NLS-2$ //$NON-NLS-1$
}
/**
* Extract source location file, start and end lines, and context.
* Column is not extracted correctly.
* @return ISourceLocation with correct file and lines but not column.
*/
public static ISourceLocation makeSourceLocation(ICompilationUnit unit, IProblem problem) {
int line = problem.getSourceLineNumber();
File file = new File(new String(problem.getOriginatingFileName()));
String context = makeLocationContext(unit, problem);
// XXX 0 column is wrong but recoverable from makeLocationContext
return new SourceLocation(file, line, line, 0, context);
}
/**
* Extract message text and source location, including context.
*/
public static IMessage makeMessage(ICompilationUnit unit, IProblem problem) {
ISourceLocation sourceLocation = makeSourceLocation(unit, problem);
IProblem[] seeAlso = problem.seeAlso();
ISourceLocation[] seeAlsoLocations = new ISourceLocation[seeAlso.length];
for (int i = 0; i < seeAlso.length; i++) {
seeAlsoLocations[i] = new SourceLocation(new File(new String(seeAlso[i].getOriginatingFileName())),
seeAlso[i].getSourceLineNumber());
}
// We transform messages from AJ types to eclipse IProblems
// and back to AJ types. During their time as eclipse problems,
// we remember whether the message originated from a declare
// in the extraDetails.
String extraDetails = problem.getSupplementaryMessageInfo();
boolean declared = false;
if (extraDetails!=null && extraDetails.endsWith("[deow=true]")) {
declared = true;
extraDetails = extraDetails.substring(0,extraDetails.length()-"[deow=true]".length());
}
// If the 'problem' represents a TO DO kind of thing then use the message kind that
// represents this so AJDT sees it correctly.
IMessage.Kind kind;
if (problem.getID()==IProblem.Task) {
kind=IMessage.TASKTAG;
} else {
if (problem.isError()) { kind = IMessage.ERROR; }
else { kind = IMessage.WARNING; }
}
IMessage msg = new Message(problem.getMessage(),
extraDetails,
kind,
sourceLocation,
null,
seeAlsoLocations,
declared,
problem.getID(),
problem.getSourceStart(),problem.getSourceEnd());
return msg;
}
public static IMessage makeErrorMessage(ICompilationUnit unit, String text, Exception ex) {
ISourceLocation loc = new SourceLocation(new File(new String(unit.getFileName())),
0,0,0,"");
IMessage msg = new Message(text,IMessage.ERROR,ex,loc);
return msg;
}
public static IMessage makeErrorMessage(String srcFile, String text, Exception ex) {
ISourceLocation loc = new SourceLocation(new File(srcFile),
0,0,0,"");
IMessage msg = new Message(text,IMessage.ERROR,ex,loc);
return msg;
}
private EclipseAdapterUtils() {
}
}
|
152,873 |
Bug 152873 Optimize shouldWeaveAnnotationStyleAspect with Patch
| null |
resolved fixed
|
f239f2a
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-08-08T07:59:54Z | 2006-08-04T19:33:20Z |
testing/newsrc/org/aspectj/testing/AntSpec.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.testing;
import org.aspectj.tools.ajc.AjcTestCase;
import org.apache.tools.ant.Project;
import org.apache.tools.ant.ProjectHelper;
import org.apache.tools.ant.DefaultLogger;
import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.BuildEvent;
import org.apache.tools.ant.types.Path;
import java.io.File;
import java.util.StringTokenizer;
/**
* Element that allow to run an abritrary Ant target in a sandbox.
* <p/>
* Such a spec is used in a "<ajc-test><ant file="myAnt.xml" [target="..."] [verbose="true"]/> XML element.
* The "target" is optional. If not set, default myAnt.xml target is used.
* The "file" file is looked up from the <ajc-test dir="..."/> attribute.
* If "verbose" is set to "true", the ant -v output is piped, else nothing is reported except errors.
* <p/>
* The called Ant target benefits from 2 implicit variables:
* "${aj.sandbox}" points to the test current sandbox folder.
* "aj.path" is an Ant refid on the classpath formed with the sandbox folder + ltw + the AjcTestCase classpath
* (ie usually aspectjrt, junit, and testing infra)
* <p/>
* Element "<stdout><line text="..">" and "<stderr><line text="..">" can be used. For now a full match
* is performed on the output of the runned target only (not the whole Ant invocation). This is experimental
* and advised to use a "<junit>" task instead or a "<java>" whose main that throws some exception upon failure.
*
*
* @author <a href="mailto:alex AT gnilux DOT com">Alexandre Vasseur</a>
*/
public class AntSpec implements ITestStep {
private final static String DEFAULT_LTW_CLASSPATH_ENTRIES =
".." + File.separator + "asm/bin"
+ File.pathSeparator + ".." + File.separator + "bridge/bin"
+ File.pathSeparator + ".." + File.separator + "loadtime/bin"
+ File.pathSeparator + ".." + File.separator + "loadtime5/bin"
+ File.pathSeparator + ".." + File.separator + "weaver/bin"
+ File.pathSeparator + ".." + File.separator + "lib/bcel/bcel.jar";
private boolean m_verbose = false;
private AjcTest m_ajcTest;
private OutputSpec m_stdErrSpec;
private OutputSpec m_stdOutSpec;
private String m_antFile;
private String m_antTarget;
public void execute(AjcTestCase inTestCase) {
final String failMessage = "test \"" + m_ajcTest.getTitle() + "\" failed: ";
File buildFile = new File(m_ajcTest.getDir() + File.separatorChar + m_antFile);
if (!buildFile.exists()) {
AjcTestCase.fail(failMessage + "no such Ant file " + buildFile.getAbsolutePath());
}
Project p = new Project();
final StringBuffer stdout = new StringBuffer();
final StringBuffer stderr = new StringBuffer();
try {
// read the Ant file
p.init();
p.setUserProperty("ant.file", buildFile.getAbsolutePath());
// setup aj.sandbox
p.setUserProperty("aj.sandbox", inTestCase.getSandboxDirectory().getAbsolutePath());
// setup aj.dir "modules" folder
p.setUserProperty("aj.root", new File("..").getAbsolutePath());
// create the test implicit path aj.path that contains the sandbox + regular test infra path
Path path = new Path(p, inTestCase.getSandboxDirectory().getAbsolutePath());
populatePath(path, DEFAULT_LTW_CLASSPATH_ENTRIES);
populatePath(path, AjcTestCase.DEFAULT_CLASSPATH_ENTRIES);
p.addReference("aj.path", path);
ProjectHelper helper = ProjectHelper.getProjectHelper();
helper.parse(p, buildFile);
// use default target if no target specified
if (m_antTarget == null) {
m_antTarget = p.getDefaultTarget();
}
// make sure we listen for failure
DefaultLogger consoleLogger = new DefaultLogger() {
public void buildFinished(BuildEvent event) {
super.buildFinished(event);
if (event.getException() != null) {
AjcTestCase.fail(failMessage + "failure " + event.getException());
}
}
public void targetFinished(BuildEvent event) {
super.targetFinished(event);
if (event.getException() != null) {
AjcTestCase.fail(failMessage + "failure in '" + event.getTarget() + "' " + event.getException());
}
}
public void messageLogged(BuildEvent event) {
super.messageLogged(event);
if (event.getTarget() != null && event.getPriority() >= Project.MSG_INFO && m_antTarget.equals(event.getTarget().getName())) {
if (event.getException() == null) {
stdout.append(event.getMessage()).append('\n');
} else {
stderr.append(event.getMessage());
}
}
}
};
consoleLogger.setErrorPrintStream(System.err);
consoleLogger.setOutputPrintStream(System.out);
consoleLogger.setMessageOutputLevel(m_verbose?Project.MSG_VERBOSE:Project.MSG_ERR);
p.addBuildListener(consoleLogger);
} catch (Throwable t) {
AjcTestCase.fail(failMessage + "invalid Ant script :" + t.toString());
}
try {
p.fireBuildStarted();
p.executeTarget(m_antTarget);
p.fireBuildFinished(null);
} catch (BuildException e) {
p.fireBuildFinished(e);
} catch (Throwable t) {
AjcTestCase.fail(failMessage + "error when invoking target :" + t.toString());
}
// match lines
//TODO AV experimental: requires full match so rather useless.
// if someone needs it, we ll have to impl a "include / exclude" stuff
if (m_stdOutSpec != null)
m_stdOutSpec.matchAgainst(stdout.toString());
// match lines
if (m_stdErrSpec != null)
m_stdErrSpec.matchAgainst(stdout.toString());
}
public void addStdErrSpec(OutputSpec spec) {
if (m_stdErrSpec!=null)
throw new UnsupportedOperationException("only one 'stderr' allowed in 'ant'");
m_stdErrSpec = spec;
}
public void addStdOutSpec(OutputSpec spec) {
if (m_stdOutSpec!=null)
throw new UnsupportedOperationException("only one 'stdout' allowed in 'ant'");
m_stdOutSpec = spec;
}
public void setVerbose(String verbose) {
if (verbose != null && "true".equalsIgnoreCase(verbose)) {
m_verbose = true;
}
}
public void setFile(String file) {
m_antFile = file;
}
public void setTarget(String target) {
m_antTarget = target;
}
public void addExpectedMessage(ExpectedMessageSpec message) {
throw new UnsupportedOperationException("don't use 'message' in 'ant' specs.");
}
public void setBaseDir(String dir) {
;
}
public void setTest(AjcTest test) {
m_ajcTest = test;
}
private static void populatePath(Path path, String pathEntries) {
StringTokenizer st = new StringTokenizer(pathEntries, File.pathSeparator);
while (st.hasMoreTokens()) {
path.setPath(new File(st.nextToken()).getAbsolutePath());
}
}
}
|
152,873 |
Bug 152873 Optimize shouldWeaveAnnotationStyleAspect with Patch
| null |
resolved fixed
|
f239f2a
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-08-08T07:59:54Z | 2006-08-04T19:33:20Z |
tests/java5/ataspectj/ataspectj/bugs/NotAspect.java
| |
152,873 |
Bug 152873 Optimize shouldWeaveAnnotationStyleAspect with Patch
| null |
resolved fixed
|
f239f2a
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-08-08T07:59:54Z | 2006-08-04T19:33:20Z |
tests/src/org/aspectj/systemtest/ajc150/ataspectj/AtAjLTWTests.java
|
/*******************************************************************************
* Copyright (c) 2005 Contributors.
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Eclipse Public License v1.0
* which accompanies this distribution and is available at
* http://eclipse.org/legal/epl-v10.html
*
* Contributors:
* Alexandre Vasseur initial implementation
*******************************************************************************/
package org.aspectj.systemtest.ajc150.ataspectj;
import java.io.File;
import java.io.FilenameFilter;
import junit.framework.Test;
import org.aspectj.testing.XMLBasedAjcTestCase;
import org.aspectj.util.FileUtil;
/**
* @author <a href="mailto:alex AT gnilux DOT com">Alexandre Vasseur</a>
*/
public class AtAjLTWTests extends XMLBasedAjcTestCase {
public static Test suite() {
return XMLBasedAjcTestCase.loadSuite(org.aspectj.systemtest.ajc150.ataspectj.AtAjLTWTests.class);
}
protected File getSpecFile() {
return new File("../tests/src/org/aspectj/systemtest/ajc150/ataspectj/ltw.xml");
}
public void testRunThemAllWithJavacCompiledAndLTW() {
runTest("RunThemAllWithJavacCompiledAndLTW");
}
public void testAjcLTWPerClauseTest_XterminateAfterCompilation() {
runTest("AjcLTW PerClauseTest -XterminateAfterCompilation");
}
public void testAjcLTWPerClauseTest_Xreweavable() {
runTest("AjcLTW PerClauseTest -Xreweavable");
}
public void testJavaCAjcLTWPerClauseTest() {
runTest("JavaCAjcLTW PerClauseTest");
}
public void testAjcLTWAroundInlineMungerTest_XterminateAfterCompilation() {
runTest("AjcLTW AroundInlineMungerTest -XterminateAfterCompilation");
}
public void testAjcLTWAroundInlineMungerTest_Xreweavable() {
runTest("AjcLTW AroundInlineMungerTest");
}
public void testAjcLTWAroundInlineMungerTest() {
runTest("AjcLTW AroundInlineMungerTest");
}
public void testAjcLTWAroundInlineMungerTest_XnoInline_Xreweavable() {
runTest("AjcLTW AroundInlineMungerTest -XnoInline -Xreweavable");
}
public void testAjcLTWAroundInlineMungerTest2() {
runTest("AjcLTW AroundInlineMungerTest2");
}
public void testLTWDumpNone() {
runTest("LTW DumpTest none");
File f = new File("_ajdump/ataspectj/DumpTest.class");
assertFalse(f.exists());
f = new File("_ajdump/_before/ataspectj/DumpTestTheDump.class");
assertFalse(f.exists());
f = new File("_ajdump/ataspectj/DumpTestTheDump.class");
assertFalse(f.exists());
}
public void testLTWDump() {
runTest("LTW DumpTest");
File f = new File("_ajdump/ataspectj/DumpTest.class");
assertFalse(f.exists());
f = new File("_ajdump/_before/ataspectj/DumpTestTheDump.class");
assertFalse(f.exists());
f = new File("_ajdump/ataspectj/DumpTestTheDump.class");
assertTrue(f.exists());
// tidy up...
f = new File("_ajdump");
FileUtil.deleteContents(f);
f.delete();
}
public void testLTWDumpBeforeAndAfter() {
runTest("LTW DumpTest before and after");
// before
File f = new File("_ajdump/_before/com/foo/bar");
CountingFilenameFilter cff = new CountingFilenameFilter();
f.listFiles(cff);
assertEquals("Expected dump file in " + f.getAbsolutePath(),1,cff.getCount());
// after
f = new File("_ajdump/com/foo/bar");
cff = new CountingFilenameFilter();
f.listFiles(cff);
assertEquals("Expected dump file in " + f.getAbsolutePath(),1,cff.getCount());
// tidy up...
f = new File("_ajdump");
FileUtil.deleteContents(f);
f.delete();
}
public void testLTWDumpClosure() {
runTest("LTW DumpTest closure");
File f = new File("_ajdump/ataspectj/DumpTestTheDump$AjcClosure1.class");
assertTrue("Missing dump file " + f.getAbsolutePath(),f.exists());
// tidy up...
f = new File("_ajdump");
FileUtil.deleteContents(f);
f.delete();
}
public void testLTWDumpProxy() {
runTest("LTW DumpTest proxy");
// The working directory is different because this test must be forked
File dir = new File("../tests/java5/ataspectj");
File f = new File(dir,"_ajdump/_before");
CountingFilenameFilter cff = new CountingFilenameFilter();
f.listFiles(cff);
assertEquals("Expected dump file in " + f.getAbsolutePath(),1,cff.getCount());
f = new File(dir,"_ajdump");
cff = new CountingFilenameFilter();
f.listFiles(cff);
assertEquals(1,cff.getCount());
// tidy up...
f = new File(dir,"_ajdump");
FileUtil.deleteContents(f);
f.delete();
}
public void testAjcAspect1LTWAspect2_Xreweavable() {
runTest("Ajc Aspect1 LTW Aspect2 -Xreweavable");
}
public void testLTWLogSilent() {
runTest("LTW Log silent");
}
public void testLTWLogVerbose() {
runTest("LTW Log verbose");
}
public void testLTWLogVerboseAndShow() {
runTest("LTW Log verbose and showWeaveInfo");
}
public void testLTWLogMessageHandlerClass() {
runTest("LTW Log messageHandlerClass");
}
public void testLTWUnweavable() {
// actually test that we do LTW proxy and jit classes
runTest("LTW Unweavable");
}
public void testLTWDecp() {
runTest("LTW Decp");
}
public void testLTWDecp2() {
runTest("LTW Decp2");
}
public void testCompileTimeAspectsDeclaredToLTWWeaver() {
runTest("Compile time aspects declared to ltw weaver");
}
public void testConcreteAtAspect() {
runTest("Concrete@Aspect");
}
public void testConcreteAspect() {
runTest("ConcreteAspect");
}
public void testConcretePrecedenceAspect() {
runTest("ConcretePrecedenceAspect");
}
public void testAspectOfWhenAspectNotInInclude() {
runTest("AspectOfWhenAspectNotInInclude");
}
public void testAppContainer() {
runTest("AppContainer");
}
public void testCflowBelowStack() {
runTest("CflowBelowStack");
}
private static class CountingFilenameFilter implements FilenameFilter {
private int count;
public boolean accept(File dir, String name) {
if (name.endsWith(".class")) count++;
return false;
}
public int getCount() {
return count;
}
}
}
|
152,873 |
Bug 152873 Optimize shouldWeaveAnnotationStyleAspect with Patch
| null |
resolved fixed
|
f239f2a
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-08-08T07:59:54Z | 2006-08-04T19:33: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;
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;
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.visitString("Shadow mungers:");
visitor.visitList(crosscuttingMembersSet.getShadowMungers());
visitor.visitString("Type mungers:");
visitor.visitList(crosscuttingMembersSet.getTypeMungers());
visitor.visitString("Late Type mungers:");
visitor.visitList(crosscuttingMembersSet.getLateTypeMungers());
if (dumpState_cantFindTypeExceptions!=null) {
visitor.visitString("Cant find type problems:");
visitor.visitList(dumpState_cantFindTypeExceptions);
dumpState_cantFindTypeExceptions = null;
}
}
// =============================================================================
// T Y P E R E S O L U T I O N
// =============================================================================
/**
* Resolve a type that we require to be present in the world
*/
public ResolvedType resolve(UnresolvedType ty) {
return resolve(ty, false);
}
/**
* Attempt to resolve a type - the source location gives you some context in which
* resolution is taking place. In the case of an error where we can't find the
* type - we can then at least report why (source location) we were trying to resolve it.
*/
public ResolvedType resolve(UnresolvedType ty,ISourceLocation isl) {
ResolvedType ret = resolve(ty,true);
if (ResolvedType.isMissing(ty)) {
//IMessage msg = null;
getLint().cantFindType.signal(WeaverMessages.format(WeaverMessages.CANT_FIND_TYPE,ty.getName()),isl);
//if (isl!=null) {
//msg = MessageUtil.error(WeaverMessages.format(WeaverMessages.CANT_FIND_TYPE,ty.getName()),isl);
//} else {
//msg = MessageUtil.error(WeaverMessages.format(WeaverMessages.CANT_FIND_TYPE,ty.getName()));
//}
//messageHandler.handleMessage(msg);
}
return ret;
}
/**
* Convenience method for resolving an array of unresolved types
* in one hit. Useful for e.g. resolving type parameters in signatures.
*/
public ResolvedType[] resolve(UnresolvedType[] types) {
if (types == null) return new ResolvedType[0];
ResolvedType[] ret = new ResolvedType[types.length];
for (int i=0; i<types.length; i++) {
ret[i] = resolve(types[i]);
}
return ret;
}
/**
* Resolve a type. This the hub of type resolution. The resolved type is added
* to the type map by signature.
*/
public ResolvedType resolve(UnresolvedType ty, boolean allowMissing) {
// special resolution processing for already resolved types.
if (ty instanceof ResolvedType) {
ResolvedType rty = (ResolvedType) ty;
rty = resolve(rty);
return rty;
}
// dispatch back to the type variable reference to resolve its constituent parts
// don't do this for other unresolved types otherwise you'll end up in a loop
if (ty.isTypeVariableReference()) {
return ty.resolve(this);
}
// if we've already got a resolved type for the signature, just return it
// after updating the world
String signature = ty.getSignature();
ResolvedType ret = typeMap.get(signature);
if (ret != null) {
ret.world = this; // Set the world for the RTX
return ret;
} else if ( signature.equals("?") || signature.equals("*")) {
// might be a problem here, not sure '?' should make it to here as a signature, the
// proper signature for wildcard '?' is '*'
// fault in generic wildcard, can't be done earlier because of init issues
ResolvedType something = new BoundedReferenceType("?","Ljava/lang/Object",this);
typeMap.put("?",something);
return something;
}
// no existing resolved type, create one
if (ty.isArray()) {
ResolvedType componentType = resolve(ty.getComponentType(),allowMissing);
//String brackets = signature.substring(0,signature.lastIndexOf("[")+1);
ret = new ResolvedType.Array(signature, "["+componentType.getErasureSignature(),
this,
componentType);
} else {
ret = resolveToReferenceType(ty);
if (!allowMissing && ret.isMissing()) {
ret = handleRequiredMissingTypeDuringResolution(ty);
}
}
// Pulling in the type may have already put the right entry in the map
if (typeMap.get(signature)==null && !ret.isMissing()) {
typeMap.put(signature, ret);
}
return ret;
}
/**
* We tried to resolve a type and couldn't find it...
*/
private ResolvedType handleRequiredMissingTypeDuringResolution(UnresolvedType ty) {
// defer the message until someone asks a question of the type that we can't answer
// just from the signature.
// MessageUtil.error(messageHandler,
// WeaverMessages.format(WeaverMessages.CANT_FIND_TYPE,ty.getName()));
if (dumpState_cantFindTypeExceptions==null) {
dumpState_cantFindTypeExceptions = new ArrayList();
}
dumpState_cantFindTypeExceptions.add(new RuntimeException("Can't find type "+ty.getName()));
return new MissingResolvedTypeWithKnownSignature(ty.getSignature(),this);
}
/**
* Some TypeFactory operations create resolved types directly, but these won't be
* in the typeMap - this resolution process puts them there. Resolved types are
* also told their world which is needed for the special autoboxing resolved types.
*/
public ResolvedType resolve(ResolvedType ty) {
if (ty.isTypeVariableReference()) return ty; // until type variables have proper sigs...
ResolvedType resolved = typeMap.get(ty.getSignature());
if (resolved == null) {
typeMap.put(ty.getSignature(), ty);
resolved = ty;
}
resolved.world = this;
return resolved;
}
/**
* Convenience method for finding a type by name and resolving it in one step.
*/
public ResolvedType resolve(String name) {
// 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) {
if (ty.isParameterizedType()) {
// ======= parameterized types ================
ReferenceType genericType = (ReferenceType)resolveGenericTypeFor(ty,false);
currentlyResolvingBaseType = genericType;
ReferenceType parameterizedType =
TypeFactory.createParameterizedType(genericType, ty.typeParameters, this);
currentlyResolvingBaseType = null;
return parameterizedType;
} else if (ty.isGenericType()) {
// ======= generic types ======================
ReferenceType genericType = (ReferenceType)resolveGenericTypeFor(ty,false);
return genericType;
} else if (ty.isGenericWildcard()) {
// ======= generic wildcard types =============
return resolveGenericWildcardFor(ty);
} else {
// ======= simple and raw types ===============
String erasedSignature = ty.getErasureSignature();
ReferenceType simpleOrRawType = new ReferenceType(erasedSignature, this);
if (ty.needsModifiableDelegate()) simpleOrRawType.setNeedsModifiableDelegate(true);
ReferenceTypeDelegate delegate = resolveDelegate(simpleOrRawType);
// 117854
// if (delegate == null) return ResolvedType.MISSING;
if (delegate == null) return new MissingResolvedTypeWithKnownSignature(ty.getSignature(),erasedSignature,this);//ResolvedType.MISSING;
if (delegate.isGeneric() && behaveInJava5Way) {
// ======== raw type ===========
simpleOrRawType.typeKind = TypeKind.RAW;
ReferenceType genericType = makeGenericTypeFrom(delegate,simpleOrRawType);
// name = ReferenceType.fromTypeX(UnresolvedType.forRawTypeNames(ty.getName()),this);
simpleOrRawType.setDelegate(delegate);
genericType.setDelegate(delegate);
simpleOrRawType.setGenericType(genericType);
return simpleOrRawType;
} else {
// ======== simple type =========
simpleOrRawType.setDelegate(delegate);
return simpleOrRawType;
}
}
}
/**
* Attempt to resolve a type that should be a generic type.
*/
public ResolvedType resolveGenericTypeFor(UnresolvedType anUnresolvedType, boolean allowMissing) {
// Look up the raw type by signature
String rawSignature = anUnresolvedType.getRawType().getSignature();
ResolvedType rawType = (ResolvedType) typeMap.get(rawSignature);
if (rawType==null) {
rawType = resolve(UnresolvedType.forSignature(rawSignature),false);
typeMap.put(rawSignature,rawType);
}
// Does the raw type know its generic form? (It will if we created the
// raw type from a source type, it won't if its been created just through
// being referenced, e.g. java.util.List
ResolvedType genericType = rawType.getGenericType();
// There is a special case to consider here (testGenericsBang_pr95993 highlights it)
// You may have an unresolvedType for a parameterized type but it
// is backed by a simple type rather than a generic type. This occurs for
// inner types of generic types that inherit their enclosing types
// type variables.
if (rawType.isSimpleType() && (anUnresolvedType.typeParameters==null || anUnresolvedType.typeParameters.length==0)) {
rawType.world = this;
return rawType;
}
if (genericType != null) {
genericType.world = this;
return genericType;
} else {
// Fault in the generic that underpins the raw type ;)
ReferenceTypeDelegate delegate = resolveDelegate((ReferenceType)rawType);
ReferenceType genericRefType = makeGenericTypeFrom(delegate,((ReferenceType)rawType));
((ReferenceType)rawType).setGenericType(genericRefType);
genericRefType.setDelegate(delegate);
((ReferenceType)rawType).setDelegate(delegate);
return genericRefType;
}
}
private ReferenceType makeGenericTypeFrom(ReferenceTypeDelegate delegate, ReferenceType rawType) {
String genericSig = delegate.getDeclaredGenericSignature();
if (genericSig != null) {
return new ReferenceType(
UnresolvedType.forGenericTypeSignature(rawType.getSignature(),delegate.getDeclaredGenericSignature()),this);
} else {
return new ReferenceType(
UnresolvedType.forGenericTypeVariables(rawType.getSignature(), delegate.getTypeVariables()),this);
}
}
/**
* Go from an unresolved generic wildcard (represented by UnresolvedType) to a resolved version (BoundedReferenceType).
*/
private ReferenceType resolveGenericWildcardFor(UnresolvedType aType) {
BoundedReferenceType ret = null;
// FIXME asc doesnt take account of additional interface bounds (e.g. ? super R & Serializable - can you do that?)
if (aType.isExtends()) {
ReferenceType upperBound = (ReferenceType)resolve(aType.getUpperBound());
ret = new BoundedReferenceType(upperBound,true,this);
} else if (aType.isSuper()) {
ReferenceType lowerBound = (ReferenceType) resolve(aType.getLowerBound());
ret = new BoundedReferenceType(lowerBound,false,this);
} else {
// must be ? on its own!
}
return ret;
}
/**
* Find the ReferenceTypeDelegate behind this reference type so that it can
* fulfill its contract.
*/
protected abstract ReferenceTypeDelegate resolveDelegate(ReferenceType ty);
/**
* Special resolution for "core" types like OBJECT. These are resolved just like
* any other type, but if they are not found it is more serious and we issue an
* error message immediately.
*/
public ResolvedType getCoreType(UnresolvedType tx) {
ResolvedType coreTy = resolve(tx,true);
if (coreTy.isMissing()) {
MessageUtil.error(messageHandler,
WeaverMessages.format(WeaverMessages.CANT_FIND_CORE_TYPE,tx.getName()));
}
return coreTy;
}
/**
* Lookup a type by signature, if not found then build one and put it in the
* map.
*/
public ReferenceType lookupOrCreateName(UnresolvedType ty) {
String signature = ty.getSignature();
ReferenceType ret = lookupBySignature(signature);
if (ret == null) {
ret = ReferenceType.fromTypeX(ty, this);
typeMap.put(signature, ret);
}
return ret;
}
/**
* Lookup a reference type in the world by its signature. Returns
* null if not found.
*/
public ReferenceType lookupBySignature(String signature) {
return (ReferenceType) typeMap.get(signature);
}
// =============================================================================
// T Y P E R E S O L U T I O N -- E N D
// =============================================================================
/**
* Member resolution is achieved by resolving the declaring type and then
* looking up the member in the resolved declaring type.
*/
public ResolvedMember resolve(Member member) {
ResolvedType declaring = member.getDeclaringType().resolve(this);
if (declaring.isRawType()) declaring = declaring.getGenericType();
ResolvedMember ret;
if (member.getKind() == Member.FIELD) {
ret = declaring.lookupField(member);
} else {
ret = declaring.lookupMethod(member);
}
if (ret != null) return ret;
return declaring.lookupSyntheticMember(member);
}
// Methods for creating various cross-cutting members...
// ===========================================================
/**
* Create an advice shadow munger from the given advice attribute
*/
public abstract Advice createAdviceMunger(
AjAttribute.AdviceAttribute attribute,
Pointcut pointcut,
Member signature);
/**
* Create an advice shadow munger for the given advice kind
*/
public final Advice createAdviceMunger(
AdviceKind kind,
Pointcut p,
Member signature,
int extraParameterFlags,
IHasSourceLocation loc)
{
AjAttribute.AdviceAttribute attribute =
new AjAttribute.AdviceAttribute(kind, p, extraParameterFlags, loc.getStart(), loc.getEnd(), loc.getSourceContext());
return createAdviceMunger(attribute, p, signature);
}
public abstract ConcreteTypeMunger makeCflowStackFieldAdder(ResolvedMember cflowField);
public abstract ConcreteTypeMunger makeCflowCounterFieldAdder(ResolvedMember cflowField);
/**
* Register a munger for perclause @AJ aspect so that we add aspectOf(..) to them as needed
* @see org.aspectj.weaver.bcel.BcelWorld#makePerClauseAspect(ResolvedType, org.aspectj.weaver.patterns.PerClause.Kind)
*/
public abstract ConcreteTypeMunger makePerClauseAspect(ResolvedType aspect, PerClause.Kind kind);
public abstract ConcreteTypeMunger concreteTypeMunger(ResolvedTypeMunger munger, ResolvedType aspectType);
/**
* Same signature as org.aspectj.util.PartialOrder.PartialComparable.compareTo
*/
public int compareByPrecedence(ResolvedType aspect1, ResolvedType aspect2) {
return precedenceCalculator.compareByPrecedence(aspect1, aspect2);
}
public Integer getPrecedenceIfAny(ResolvedType aspect1, ResolvedType aspect2) {
return precedenceCalculator.getPrecedenceIfAny(aspect1, aspect2);
}
/**
* compares by precedence with the additional rule that a super-aspect is
* sorted before its sub-aspects
*/
public int compareByPrecedenceAndHierarchy(ResolvedType aspect1, ResolvedType aspect2) {
return precedenceCalculator.compareByPrecedenceAndHierarchy(aspect1, aspect2);
}
// simple property getter and setters
// ===========================================================
/**
* Nobody should hold onto a copy of this message handler, or setMessageHandler won't
* work right.
*/
public IMessageHandler getMessageHandler() {
return messageHandler;
}
public void setMessageHandler(IMessageHandler messageHandler) {
if (this.isInPinpointMode()) {
this.messageHandler = new PinpointingMessageHandler(messageHandler);
} else {
this.messageHandler = messageHandler;
}
}
/**
* convenenience method for creating and issuing messages via the message handler -
* if you supply two locations you will get two messages.
*/
public void showMessage(
Kind kind,
String message,
ISourceLocation loc1,
ISourceLocation loc2)
{
if (loc1 != null) {
messageHandler.handleMessage(new Message(message, kind, null, loc1));
if (loc2 != null) {
messageHandler.handleMessage(new Message(message, kind, null, loc2));
}
} else {
messageHandler.handleMessage(new Message(message, kind, null, loc2));
}
}
public 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);
}
}
}
/**
* may return null
*/
public Properties getExtraConfiguration() {
return extraConfiguration;
}
public final static String xsetCAPTURE_ALL_CONTEXT = "captureAllContext"; // default false
public final static String xsetACTIVATE_LIGHTWEIGHT_DELEGATES = "activateLightweightDelegates"; // default true
public final static String xsetRUN_MINIMAL_MEMORY ="runMinimalMemory"; // default true
public final static String xsetDEBUG_STRUCTURAL_CHANGES_CODE = "debugStructuralChangesCode"; // default false
public final static String xsetDEBUG_BRIDGING = "debugBridging"; // default false
public final static String xsetPIPELINE_COMPILATION = "pipelineCompilation"; // default true
public final static String xsetPIPELINE_COMPILATION_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();
}
}
/** 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(xsetPIPELINE_COMPILATION,xsetPIPELINE_COMPILATION_DEFAULT);
shouldPipelineCompilation = s.equalsIgnoreCase("true");
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() {
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;}
}
|
152,873 |
Bug 152873 Optimize shouldWeaveAnnotationStyleAspect with Patch
| null |
resolved fixed
|
f239f2a
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-08-08T07:59:54Z | 2006-08-04T19:33:20Z |
weaver/src/org/aspectj/weaver/tools/IsAtAspectAnnotationVisitor.java
| |
152,873 |
Bug 152873 Optimize shouldWeaveAnnotationStyleAspect with Patch
| null |
resolved fixed
|
f239f2a
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-08-08T07:59:54Z | 2006-08-04T19:33:20Z |
weaver/src/org/aspectj/weaver/tools/WeavingAdaptor.java
|
/* *******************************************************************
* Copyright (c) 2004 IBM Corporation
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Eclipse Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Matthew Webster, Adrian Colyer,
* Martin Lippert initial implementation
* ******************************************************************/
package org.aspectj.weaver.tools;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.StringTokenizer;
import org.aspectj.bridge.AbortException;
import org.aspectj.bridge.IMessage;
import org.aspectj.bridge.IMessageHandler;
import org.aspectj.bridge.Message;
import org.aspectj.bridge.MessageUtil;
import org.aspectj.bridge.MessageWriter;
import org.aspectj.bridge.Version;
import org.aspectj.bridge.IMessage.Kind;
import org.aspectj.util.FileUtil;
import org.aspectj.util.LangUtil;
import org.aspectj.weaver.IClassFileProvider;
import org.aspectj.weaver.IWeaveRequestor;
import org.aspectj.weaver.ResolvedType;
import org.aspectj.weaver.bcel.BcelObjectType;
import org.aspectj.weaver.bcel.BcelWeaver;
import org.aspectj.weaver.bcel.BcelWorld;
import org.aspectj.weaver.bcel.UnwovenClassFile;
import org.aspectj.weaver.bcel.Utility;
/**
* This adaptor allows the AspectJ compiler to be embedded in an existing
* system to facilitate load-time weaving. It provides an interface for a
* weaving class loader to provide a classpath to be woven by a set of
* aspects. A callback is supplied to allow a class loader to define classes
* generated by the compiler during the weaving process.
* <p>
* A weaving class loader should create a <code>WeavingAdaptor</code> before
* any classes are defined, typically during construction. The set of aspects
* passed to the adaptor is fixed for the lifetime of the adaptor although the
* classpath can be augmented. A system property can be set to allow verbose
* weaving messages to be written to the console.
*
*/
public class WeavingAdaptor {
/**
* System property used to turn on verbose weaving messages
*/
public static final String WEAVING_ADAPTOR_VERBOSE = "aj.weaving.verbose";
public static final String SHOW_WEAVE_INFO_PROPERTY = "org.aspectj.weaver.showWeaveInfo";
protected boolean enabled = true;
protected boolean verbose = getVerbose();
protected BcelWorld bcelWorld;
protected BcelWeaver weaver;
private IMessageHandler messageHandler;
private WeavingAdaptorMessageHandler messageHolder;
protected GeneratedClassHandler generatedClassHandler;
protected Map generatedClasses = new HashMap(); /* String -> UnwovenClassFile */
protected BcelObjectType delegateForCurrentClass; // lazily initialized, should be used to prevent parsing bytecode multiple times
private static Trace trace = TraceFactory.getTraceFactory().getTrace(WeavingAdaptor.class);
protected WeavingAdaptor () {
}
/**
* Construct a WeavingAdaptor with a reference to a weaving class loader. The
* adaptor will automatically search the class loader hierarchy to resolve
* classes. The adaptor will also search the hierarchy for WeavingClassLoader
* instances to determine the set of aspects to be used ofr weaving.
* @param loader instance of <code>ClassLoader</code>
*/
public WeavingAdaptor (WeavingClassLoader loader) {
// System.err.println("? WeavingAdaptor.<init>(" + loader +"," + aspectURLs.length + ")");
generatedClassHandler = loader;
init(getFullClassPath((ClassLoader)loader),getFullAspectPath((ClassLoader)loader/*,aspectURLs*/));
}
/**
* Construct a WeavingAdator with a reference to a
* <code>GeneratedClassHandler</code>, a full search path for resolving
* classes and a complete set of aspects. The search path must include
* classes loaded by the class loader constructing the WeavingAdaptor and
* all its parents in the hierarchy.
* @param handler <code>GeneratedClassHandler</code>
* @param classURLs the URLs from which to resolve classes
* @param aspectURLs the aspects used to weave classes defined by this class loader
*/
public WeavingAdaptor (GeneratedClassHandler handler, URL[] classURLs, URL[] aspectURLs) {
// System.err.println("? WeavingAdaptor.<init>()");
generatedClassHandler = handler;
init(FileUtil.makeClasspath(classURLs),FileUtil.makeClasspath(aspectURLs));
}
private List getFullClassPath (ClassLoader loader) {
List list = new LinkedList();
for (; loader != null; loader = loader.getParent()) {
if (loader instanceof URLClassLoader) {
URL[] urls = ((URLClassLoader)loader).getURLs();
list.addAll(0,FileUtil.makeClasspath(urls));
}
else {
warn("cannot determine classpath");
}
}
list.addAll(0,makeClasspath(System.getProperty("sun.boot.class.path")));
return list;
}
private List getFullAspectPath (ClassLoader loader) {
List list = new LinkedList();
for (; loader != null; loader = loader.getParent()) {
if (loader instanceof WeavingClassLoader) {
URL[] urls = ((WeavingClassLoader)loader).getAspectURLs();
list.addAll(0,FileUtil.makeClasspath(urls));
}
}
return list;
}
private static boolean getVerbose () {
return Boolean.getBoolean(WEAVING_ADAPTOR_VERBOSE);
}
private void init(List classPath, List aspectPath) {
createMessageHandler();
info("using classpath: " + classPath);
info("using aspectpath: " + aspectPath);
bcelWorld = new BcelWorld(classPath,messageHandler,null);
bcelWorld.setXnoInline(false);
bcelWorld.getLint().loadDefaultProperties();
if (LangUtil.is15VMOrGreater()) {
bcelWorld.setBehaveInJava5Way(true);
}
weaver = new BcelWeaver(bcelWorld);
registerAspectLibraries(aspectPath);
}
protected void createMessageHandler() {
messageHolder = new WeavingAdaptorMessageHandler(new PrintWriter(System.err));
messageHandler = messageHolder;
if (verbose) messageHandler.dontIgnore(IMessage.INFO);
if (Boolean.getBoolean(SHOW_WEAVE_INFO_PROPERTY)) messageHandler.dontIgnore(IMessage.WEAVEINFO);
info("AspectJ Weaver Version " + Version.text + " built on " + Version.time_text); //$NON-NLS-1$
}
protected IMessageHandler getMessageHandler () {
return messageHandler;
}
protected void setMessageHandler (IMessageHandler mh) {
if (messageHolder != null) {
messageHolder.flushMessages();
messageHolder = null;
}
messageHandler = mh;
bcelWorld.setMessageHandler(mh);
}
/**
* Appends URL to path used by the WeavingAdptor to resolve classes
* @param url to be appended to search path
*/
public void addURL(URL url) {
File libFile = new File(url.getPath());
try {
weaver.addLibraryJarFile(libFile);
}
catch (IOException ex) {
warn("bad library: '" + libFile + "'");
}
}
/**
* Weave a class using aspects previously supplied to the adaptor.
* @param name the name of the class
* @param bytes the class bytes
* @return the woven bytes
* @exception IOException weave failed
*/
public byte[] weaveClass (String name, byte[] bytes) throws IOException {
if (enabled) {
try {
delegateForCurrentClass=null;
if (trace.isTraceEnabled()) trace.enter("weaveClass",this,new Object[] {name,bytes});
if (shouldWeave(name, bytes)) {
info("weaving '" + name + "'");
bytes = getWovenBytes(name, bytes);
} else if (shouldWeaveAnnotationStyleAspect(name, bytes)) {
// an @AspectJ aspect needs to be at least munged by the aspectOf munger
info("weaving '" + name + "'");
bytes = getAtAspectJAspectBytes(name, bytes);
}
else {
info("not weaving '" + name + "'");
}
if (trace.isTraceEnabled()) trace.exit("weaveClass",bytes);
} finally {
delegateForCurrentClass=null;
}
}
return bytes;
}
/**
* @param name
* @return true if should weave (but maybe we still need to munge it for @AspectJ aspectof support)
*/
private boolean shouldWeave (String name, byte[] bytes) {
name = name.replace('/','.');
boolean b = !generatedClasses.containsKey(name) && shouldWeaveName(name);
return b && accept(name, bytes);
// && shouldWeaveAnnotationStyleAspect(name);
// // we recall shouldWeaveAnnotationStyleAspect as we need to add aspectOf methods for @Aspect anyway
// //FIXME AV - this is half ok as the aspect will be weaved by others. In theory if the aspect
// // is excluded from include/exclude config we should only weave late type mungers for aspectof
// return b && (accept(name) || shouldWeaveAnnotationStyleAspect(name));
}
//ATAJ
protected boolean accept(String name, byte[] bytes) {
return true;
}
protected boolean shouldDump(String name, boolean before) {
return false;
}
private boolean shouldWeaveName (String name) {
boolean should =
!((name.startsWith("org.aspectj.")
|| name.startsWith("java.")
|| name.startsWith("javax."))
//|| name.startsWith("$Proxy")//JDK proxies//FIXME AV is that 1.3 proxy ? fe. ataspect.$Proxy0 is a java5 proxy...
|| name.startsWith("sun.reflect."));//JDK reflect
return should;
}
/**
* We allow @AJ aspect weaving so that we can add aspectOf() as part of the weaving
* (and not part of the source compilation)
*
* @param name
* @param bytes bytecode (from classloader), allow to NOT lookup stuff on disk again during resolve
* @return true if @Aspect
*/
private boolean shouldWeaveAnnotationStyleAspect(String name, byte[] bytes) {
// AV: instead of doing resolve that would lookup stuff on disk thru BCEL ClassLoaderRepository
// we reuse bytes[] here to do a fast lookup for @Aspect annotation
ensureDelegateInitialized(name,bytes);
return (delegateForCurrentClass.isAnnotationStyleAspect());
}
protected void ensureDelegateInitialized(String name,byte[] bytes) {
if (delegateForCurrentClass==null)
delegateForCurrentClass = ((BcelWorld)weaver.getWorld()).addSourceObjectType(Utility.makeJavaClass(name, bytes));
}
/**
* Weave a set of bytes defining a class.
* @param name the name of the class being woven
* @param bytes the bytes that define the class
* @return byte[] the woven bytes for the class
* @throws IOException
*/
private byte[] getWovenBytes(String name, byte[] bytes) throws IOException {
WeavingClassFileProvider wcp = new WeavingClassFileProvider(name,bytes);
weaver.weave(wcp);
return wcp.getBytes();
}
/**
* Weave a set of bytes defining a class for only what is needed to turn @AspectJ aspect
* in a usefull form ie with aspectOf method - see #113587
* @param name the name of the class being woven
* @param bytes the bytes that define the class
* @return byte[] the woven bytes for the class
* @throws IOException
*/
private byte[] getAtAspectJAspectBytes(String name, byte[] bytes) throws IOException {
WeavingClassFileProvider wcp = new WeavingClassFileProvider(name,bytes);
wcp.setApplyAtAspectJMungersOnly();
weaver.weave(wcp);
return wcp.getBytes();
}
private void registerAspectLibraries(List aspectPath) {
// System.err.println("? WeavingAdaptor.registerAspectLibraries(" + aspectPath + ")");
for (Iterator i = aspectPath.iterator(); i.hasNext();) {
String libName = (String)i.next();
addAspectLibrary(libName);
}
weaver.prepareForWeave();
}
/*
* Register an aspect library with this classloader for use during
* weaving. This class loader will also return (unmodified) any of the
* classes in the library in response to a <code>findClass()</code> request.
* The library is not required to be on the weavingClasspath given when this
* classloader was constructed.
* @param aspectLibraryJarFile a jar file representing an aspect library
* @throws IOException
*/
private void addAspectLibrary(String aspectLibraryName) {
File aspectLibrary = new File(aspectLibraryName);
if (aspectLibrary.isDirectory()
|| (FileUtil.isZipFile(aspectLibrary))) {
try {
info("adding aspect library: '" + aspectLibrary + "'");
weaver.addLibraryJarFile(aspectLibrary);
} catch (IOException ex) {
error("exception adding aspect library: '" + ex + "'");
}
} else {
error("bad aspect library: '" + aspectLibrary + "'");
}
}
private static List makeClasspath(String cp) {
List ret = new ArrayList();
if (cp != null) {
StringTokenizer tok = new StringTokenizer(cp,File.pathSeparator);
while (tok.hasMoreTokens()) {
ret.add(tok.nextToken());
}
}
return ret;
}
protected boolean info (String message) {
return MessageUtil.info(messageHandler,message);
}
protected boolean warn (String message) {
return MessageUtil.warn(messageHandler,message);
}
protected boolean warn (String message, Throwable th) {
return messageHandler.handleMessage(new Message(message, IMessage.WARNING, th, null));
}
protected boolean error (String message) {
return MessageUtil.error(messageHandler,message);
}
protected String getContextId () {
return "WeavingAdaptor";
}
/**
* Dump the given bytcode in _dump/... (dev mode)
*
* @param name
* @param b
* @param before whether we are dumping before weaving
* @throws Throwable
*/
protected void dump(String name, byte[] b, boolean before) {
String dirName = "_ajdump";
if (before) dirName = dirName + File.separator + "_before";
String className = name.replace('.', '/');
final File dir;
if (className.indexOf('/') > 0) {
dir = new File(dirName + File.separator + className.substring(0, className.lastIndexOf('/')));
} else {
dir = new File(dirName);
}
dir.mkdirs();
String fileName = dirName + File.separator + className + ".class";
try {
// System.out.println("WeavingAdaptor.dump() fileName=" + new File(fileName).getAbsolutePath());
FileOutputStream os = new FileOutputStream(fileName);
os.write(b);
os.close();
}
catch (IOException ex) {
warn("unable to dump class " + name + " in directory " + dirName,ex);
}
}
/**
* Processes messages arising from weaver operations.
* Tell weaver to abort on any message more severe than warning.
*/
protected class WeavingAdaptorMessageHandler extends MessageWriter {
private Set ignoring = new HashSet();
private IMessage.Kind failKind;
private boolean accumulating = true;
private List messages = new ArrayList();
public WeavingAdaptorMessageHandler (PrintWriter writer) {
super(writer,true);
ignore(IMessage.WEAVEINFO);
ignore(IMessage.INFO);
this.failKind = IMessage.ERROR;
}
public boolean handleMessage(IMessage message) throws AbortException {
addMessage(message);
boolean result = super.handleMessage(message);
if (0 <= message.getKind().compareTo(failKind)) {
throw new AbortException(message);
}
return true;
}
public boolean isIgnoring (Kind kind) {
return ((null != kind) && (ignoring.contains(kind)));
}
/**
* Set a message kind to be ignored from now on
*/
public void ignore (IMessage.Kind kind) {
if ((null != kind) && (!ignoring.contains(kind))) {
ignoring.add(kind);
}
}
/**
* Remove a message kind from the list of those ignored from now on.
*/
public void dontIgnore (IMessage.Kind kind) {
if (null != kind) {
ignoring.remove(kind);
if (kind.equals(IMessage.INFO)) accumulating = false;
}
}
private void addMessage (IMessage message) {
if (accumulating && isIgnoring(message.getKind())) {
messages.add(message);
}
}
public void flushMessages () {
for (Iterator iter = messages.iterator(); iter.hasNext();) {
IMessage message = (IMessage)iter.next();
super.handleMessage(message);
}
accumulating = false;
messages.clear();
}
protected String render(IMessage message) {
return "[" + getContextId() + "] " + super.render(message);
}
}
private class WeavingClassFileProvider implements IClassFileProvider {
private UnwovenClassFile unwovenClass;
private List unwovenClasses = new ArrayList(); /* List<UnovenClassFile> */
private UnwovenClassFile wovenClass;
private boolean isApplyAtAspectJMungersOnly = false;
public WeavingClassFileProvider (String name, byte[] bytes) {
ensureDelegateInitialized(name, bytes);
this.unwovenClass = new UnwovenClassFile(name,delegateForCurrentClass.getResolvedTypeX().getName(),bytes);
this.unwovenClasses.add(unwovenClass);
if (shouldDump(name.replace('/', '.'),true)) {
dump(name, bytes, true);
}
}
public void setApplyAtAspectJMungersOnly() {
isApplyAtAspectJMungersOnly = true;
}
public boolean isApplyAtAspectJMungersOnly() {
return isApplyAtAspectJMungersOnly;
}
public byte[] getBytes () {
if (wovenClass != null) return wovenClass.getBytes();
else return unwovenClass.getBytes();
}
public Iterator getClassFileIterator() {
return unwovenClasses.iterator();
}
public IWeaveRequestor getRequestor() {
return new IWeaveRequestor() {
public void acceptResult(UnwovenClassFile result) {
if (wovenClass == null) {
wovenClass = result;
String name = result.getClassName();
if (shouldDump(name.replace('/', '.'), false)) {
dump(name, result.getBytes(), false);
}
}
/* Classes generated by weaver e.g. around closure advice */
else {
String className = result.getClassName();
generatedClasses.put(className,result);
generatedClasses.put(wovenClass.getClassName(),result);
generatedClassHandler.acceptClass(className,result.getBytes());
}
}
public void processingReweavableState() { }
public void addingTypeMungers() {}
public void weavingAspects() {}
public void weavingClasses() {}
public void weaveCompleted() {
ResolvedType.resetPrimitives();
if (delegateForCurrentClass!=null) delegateForCurrentClass.weavingCompleted();
ResolvedType.resetPrimitives();
//bcelWorld.discardType(typeBeingProcessed.getResolvedTypeX()); // work in progress
}
};
}
}
}
|
152,979 |
Bug 152979 Optimization: Reference Use and URL Caching in ClassLoader Repository
|
I have found that a lot of memory can get pinned by the BCEL ClassLoaderRepository. For example, on a test configuration of Glassbox with WebLogic over 40 megabytes were pinned in memory due to this loader. (*) I also notice that some of the time spent with loading and parsing redundant classes for shared weaving configuration could be reduced by having a global cache of bytes for URL's instead, i.e., the ClassLoaderRepository is local to a loader, so even if the same class on disk is resolved multiple times in different loaders, it isn't read from cache. This latter issue will be reduced if loading types from a parent loader use reflection delegates instead but BCEL still has to be used for aspects on <1.5 VM's... The attached patch has some metrics in it to measure what's happening and it also uses SoftReferences to cache without pinning the reference types and uses a two-step look up process to maintain a global URL cache. When I run this on WebLogic 9.2 with Glassbox and view their admin console and some smaller apps I get this output: BCEL repository total load time: 7733 ms, in url: 6029 ms for 1427 url cache hits = 1683 missEvicted = 0 missUrlEvicted= 0 all misses = 1427, loader hits = 0 On Tomcat 5.5 with some different sample apps: BCEL repository total load time: 4945 ms, in url: 4319 ms for 636 url cache hits = 548 missEvicted = 0 missUrlEvicted= 190 all misses= 446, loader hits = 3 So at least in my configuration the URL-based cache is quite effective (with almost a 50% hit rate) whereas the loader-based cache provides little value. From what I've seen, it's worth considering not even using the loader-based BCEL cache at all but others may have configurations where it helps. (*) This test was on a development build of AspectJ which I had modified so that the LTWWorld evicts classes after loading
|
resolved fixed
|
387c3ac
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-08-08T11:26:28Z | 2006-08-07T14:13:20Z |
bcel-builder/src/org/aspectj/apache/bcel/util/ClassLoaderRepository.java
|
package org.aspectj.apache.bcel.util;
/* ====================================================================
* The Apache Software License, Version 1.1
*
* Copyright (c) 2001 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The names "Apache" and "Apache Software Foundation" and
* "Apache BCEL" must not be used to endorse or promote products
* derived from this software without prior written permission. For
* written permission, please contact [email protected].
*
* 5. Products derived from this software may not be called "Apache",
* "Apache BCEL", nor may "Apache" appear in their name, without
* prior written permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
import java.io.IOException;
import java.io.InputStream;
import java.util.WeakHashMap;
import org.aspectj.apache.bcel.classfile.ClassParser;
import org.aspectj.apache.bcel.classfile.JavaClass;
/**
* The repository maintains information about which classes have
* been loaded.
*
* It loads its data from the ClassLoader implementation
* passed into its constructor.
*
* @see org.aspectj.apache.bcel.Repository
*
* @version $Id: ClassLoaderRepository.java,v 1.5 2006/03/10 13:29:05 aclement Exp $
* @author <A HREF="mailto:[email protected]">M. Dahm</A>
* @author David Dixon-Peugh
*/
public class ClassLoaderRepository
implements Repository
{
private java.lang.ClassLoader loader;
private WeakHashMap loadedClasses =
new WeakHashMap(); // CLASSNAME X JAVACLASS
public ClassLoaderRepository( java.lang.ClassLoader loader ) {
this.loader = loader;
}
/**
* Store a new JavaClass into this Repository.
*/
public void storeClass( JavaClass clazz ) {
loadedClasses.put( clazz.getClassName(),
clazz );
clazz.setRepository( this );
}
/**
* Remove class from repository
*/
public void removeClass(JavaClass clazz) {
loadedClasses.remove(clazz.getClassName());
}
/**
* Find an already defined JavaClass.
*/
public JavaClass findClass( String className ) {
if ( loadedClasses.containsKey( className )) {
return (JavaClass) loadedClasses.get( className );
} else {
return null;
}
}
/**
* Lookup a JavaClass object from the Class Name provided.
*/
public JavaClass loadClass( String className )
throws ClassNotFoundException
{
String classFile = className.replace('.', '/');
JavaClass RC = findClass( className );
if (RC != null) { return RC; }
try {
InputStream is =
loader.getResourceAsStream( classFile + ".class" );
if(is == null) {
throw new ClassNotFoundException(className + " not found.");
}
ClassParser parser = new ClassParser( is, className );
RC = parser.parse();
storeClass( RC );
return RC;
} catch (IOException e) {
throw new ClassNotFoundException( e.toString() );
}
}
public JavaClass loadClass(Class clazz) throws ClassNotFoundException {
return loadClass(clazz.getName());
}
/** Clear all entries from cache.
*/
public void clear() {
loadedClasses.clear();
}
}
|
152,979 |
Bug 152979 Optimization: Reference Use and URL Caching in ClassLoader Repository
|
I have found that a lot of memory can get pinned by the BCEL ClassLoaderRepository. For example, on a test configuration of Glassbox with WebLogic over 40 megabytes were pinned in memory due to this loader. (*) I also notice that some of the time spent with loading and parsing redundant classes for shared weaving configuration could be reduced by having a global cache of bytes for URL's instead, i.e., the ClassLoaderRepository is local to a loader, so even if the same class on disk is resolved multiple times in different loaders, it isn't read from cache. This latter issue will be reduced if loading types from a parent loader use reflection delegates instead but BCEL still has to be used for aspects on <1.5 VM's... The attached patch has some metrics in it to measure what's happening and it also uses SoftReferences to cache without pinning the reference types and uses a two-step look up process to maintain a global URL cache. When I run this on WebLogic 9.2 with Glassbox and view their admin console and some smaller apps I get this output: BCEL repository total load time: 7733 ms, in url: 6029 ms for 1427 url cache hits = 1683 missEvicted = 0 missUrlEvicted= 0 all misses = 1427, loader hits = 0 On Tomcat 5.5 with some different sample apps: BCEL repository total load time: 4945 ms, in url: 4319 ms for 636 url cache hits = 548 missEvicted = 0 missUrlEvicted= 190 all misses= 446, loader hits = 3 So at least in my configuration the URL-based cache is quite effective (with almost a 50% hit rate) whereas the loader-based cache provides little value. From what I've seen, it's worth considering not even using the loader-based BCEL cache at all but others may have configurations where it helps. (*) This test was on a development build of AspectJ which I had modified so that the LTWWorld evicts classes after loading
|
resolved fixed
|
387c3ac
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-08-08T11:26:28Z | 2006-08-07T14:13:20Z |
bcel-builder/testsrc/org/aspectj/apache/bcel/classfile/tests/AllTests.java
|
/* *******************************************************************
* Copyright (c) 2004 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 {date}
* ******************************************************************/
package org.aspectj.apache.bcel.classfile.tests;
import junit.framework.Test;
import junit.framework.TestSuite;
import org.aspectj.apache.bcel.classfile.tests.AnnotationAccessFlagTest;
import org.aspectj.apache.bcel.classfile.tests.AnnotationDefaultAttributeTest;
import org.aspectj.apache.bcel.classfile.tests.ElementValueGenTest;
import org.aspectj.apache.bcel.classfile.tests.EnclosingMethodAttributeTest;
import org.aspectj.apache.bcel.classfile.tests.EnumAccessFlagTest;
import org.aspectj.apache.bcel.classfile.tests.FieldAnnotationsTest;
import org.aspectj.apache.bcel.classfile.tests.GeneratingAnnotatedClassesTest;
import org.aspectj.apache.bcel.classfile.tests.LocalVariableTypeTableTest;
import org.aspectj.apache.bcel.classfile.tests.MethodAnnotationsTest;
import org.aspectj.apache.bcel.classfile.tests.RuntimeVisibleAnnotationAttributeTest;
import org.aspectj.apache.bcel.classfile.tests.RuntimeVisibleParameterAnnotationAttributeTest;
import org.aspectj.apache.bcel.classfile.tests.VarargsTest;
public class AllTests {
public static Test suite() {
TestSuite suite = new TestSuite("Tests for BCEL Java5 support");
//$JUnit-BEGIN$
suite.addTestSuite(RuntimeVisibleParameterAnnotationAttributeTest.class);
suite.addTestSuite(AnnotationDefaultAttributeTest.class);
suite.addTestSuite(EnclosingMethodAttributeTest.class);
suite.addTestSuite(MethodAnnotationsTest.class);
suite.addTestSuite(RuntimeVisibleAnnotationAttributeTest.class);
suite.addTestSuite(EnumAccessFlagTest.class);
suite.addTestSuite(LocalVariableTypeTableTest.class);
suite.addTestSuite(VarargsTest.class);
suite.addTestSuite(AnnotationAccessFlagTest.class);
suite.addTestSuite(ElementValueGenTest.class);
suite.addTestSuite(FieldAnnotationsTest.class);
suite.addTestSuite(AnnotationGenTest.class);
suite.addTestSuite(ParameterAnnotationsTest.class);
suite.addTestSuite(GeneratingAnnotatedClassesTest.class);
suite.addTestSuite(TypeAnnotationsTest.class);
suite.addTestSuite(UtilTests.class);
suite.addTestSuite(GenericSignatureParsingTest.class);
suite.addTestSuite(GenericsErasureTesting.class);
suite.addTestSuite(AnonymousClassTest.class);
//$JUnit-END$
return suite;
}
}
|
152,979 |
Bug 152979 Optimization: Reference Use and URL Caching in ClassLoader Repository
|
I have found that a lot of memory can get pinned by the BCEL ClassLoaderRepository. For example, on a test configuration of Glassbox with WebLogic over 40 megabytes were pinned in memory due to this loader. (*) I also notice that some of the time spent with loading and parsing redundant classes for shared weaving configuration could be reduced by having a global cache of bytes for URL's instead, i.e., the ClassLoaderRepository is local to a loader, so even if the same class on disk is resolved multiple times in different loaders, it isn't read from cache. This latter issue will be reduced if loading types from a parent loader use reflection delegates instead but BCEL still has to be used for aspects on <1.5 VM's... The attached patch has some metrics in it to measure what's happening and it also uses SoftReferences to cache without pinning the reference types and uses a two-step look up process to maintain a global URL cache. When I run this on WebLogic 9.2 with Glassbox and view their admin console and some smaller apps I get this output: BCEL repository total load time: 7733 ms, in url: 6029 ms for 1427 url cache hits = 1683 missEvicted = 0 missUrlEvicted= 0 all misses = 1427, loader hits = 0 On Tomcat 5.5 with some different sample apps: BCEL repository total load time: 4945 ms, in url: 4319 ms for 636 url cache hits = 548 missEvicted = 0 missUrlEvicted= 190 all misses= 446, loader hits = 3 So at least in my configuration the URL-based cache is quite effective (with almost a 50% hit rate) whereas the loader-based cache provides little value. From what I've seen, it's worth considering not even using the loader-based BCEL cache at all but others may have configurations where it helps. (*) This test was on a development build of AspectJ which I had modified so that the LTWWorld evicts classes after loading
|
resolved fixed
|
387c3ac
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-08-08T11:26:28Z | 2006-08-07T14:13:20Z |
bcel-builder/testsrc/org/aspectj/apache/bcel/classfile/tests/ClassloaderRepositoryTest.java
| |
152,388 |
Bug 152388 NPE in MessageUtil.addExtraSourceLocations
|
I get this message from an error in a recent dev build of AspectJ with load-time weaving. I don't know how there is a null source location associated with this message, but either it shouldn't be there or MessageUtil line 806 should use this patch: Index: src/org/aspectj/bridge/MessageUtil.java =================================================================== RCS file: /home/technology/org.aspectj/modules/bridge/src/org/aspectj/bridge/MessageUtil.java,v retrieving revision 1.11 diff -u -r1.11 MessageUtil.java --- src/org/aspectj/bridge/MessageUtil.java 1 Jun 2006 09:36:37 -0000 1.11 +++ src/org/aspectj/bridge/MessageUtil.java 31 Jul 2006 22:32:16 -0000 @@ -803,7 +803,7 @@ writer.println(baseMessage); for (Iterator iter = message.getExtraSourceLocations().iterator(); iter.hasNext();) { ISourceLocation element = (ISourceLocation) iter.next(); - writer.print("\tsee also: " + element.toString()); + writer.print("\tsee also: " + element); if (iter.hasNext()) { writer.println(); } NPE follows: java.lang.NullPointerException at org.aspectj.bridge.MessageUtil.addExtraSourceLocations(MessageUtil.java:806) at org.aspectj.bridge.MessageUtil.renderMessage(MessageUtil.java:793) at org.aspectj.bridge.Message.toString(Message.java:177) at org.aspectj.bridge.MessageWriter.render(MessageWriter.java:73) at org.aspectj.weaver.tools.WeavingAdaptor$WeavingAdaptorMessageHandler.render(WeavingAdaptor.java:471) at org.aspectj.bridge.MessageWriter.handleMessage(MessageWriter.java:41) at org.aspectj.weaver.tools.WeavingAdaptor$WeavingAdaptorMessageHandler.handleMessage(WeavingAdaptor.java:425) at org.aspectj.weaver.bcel.BcelTypeMunger.error(BcelTypeMunger.java:378) at org.aspectj.weaver.bcel.BcelTypeMunger.enforceDecpRule1_abstractMethodsImplemented(BcelTypeMunger.java:273) at org.aspectj.weaver.bcel.BcelTypeMunger.mungeNewParent(BcelTypeMunger.java:194) at org.aspectj.weaver.bcel.BcelTypeMunger.munge(BcelTypeMunger.java:106) at org.aspectj.weaver.bcel.BcelClassWeaver.weave(BcelClassWeaver.java:450) at org.aspectj.weaver.bcel.BcelClassWeaver.weave(BcelClassWeaver.java:115) at org.aspectj.weaver.bcel.BcelWeaver.weave(BcelWeaver.java:1613) at org.aspectj.weaver.bcel.BcelWeaver.weaveWithoutDump(BcelWeaver.java:1564) at org.aspectj.weaver.bcel.BcelWeaver.weaveAndNotify(BcelWeaver.java:1341) at org.aspectj.weaver.bcel.BcelWeaver.weave(BcelWeaver.java:1163) at org.aspectj.weaver.tools.WeavingAdaptor.getWovenBytes(WeavingAdaptor.java:288) at org.aspectj.weaver.tools.WeavingAdaptor.weaveClass(WeavingAdaptor.java:214) at org.aspectj.weaver.loadtime.Aj.preProcess(Aj.java:76) at org.aspectj.ext.ltw13.ClassPreProcessorAdapter.preProcess(ClassPreProcessorAdapter.java:65) at org.codehaus.aspectwerkz.hook.impl.ClassPreProcessorHelper.defineClass0Pre(ClassPreProcessorHelper.java:107) at java.lang.ClassLoader.defineClass(ClassLoader.java:539) ... NOTE: I'm using Alex Vasseur's adaptor to invoke AspectJ LTW from a 1.4 VM, but with recursion protection added. I don't think that should change the expected behavior of Aj.
|
resolved fixed
|
a38edd3
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-08-08T13:48:32Z | 2006-07-31T23:53:20Z |
bridge/src/org/aspectj/bridge/MessageUtil.java
|
/* *******************************************************************
* Copyright (c) 1999-2001 Xerox Corporation,
* 2002 Palo Alto Research Center, Incorporated (PARC).
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Eclipse Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Xerox/PARC initial implementation
* ******************************************************************/
package org.aspectj.bridge;
import java.io.*;
import java.util.*;
import org.aspectj.bridge.IMessage.Kind;
import org.aspectj.util.*;
/**
* Convenience API's for constructing, printing, and sending messages.
*/
public class MessageUtil {
// ------ some constant, content-less messages
// no variants for "info" or "debug", which should always have content
public static final IMessage ABORT_NOTHING_TO_RUN
= new Message("aborting - nothing to run", IMessage.ABORT, null, null);
public static final IMessage FAIL_INCOMPLETE
= new Message("run not completed", IMessage.FAIL, null, null);
public static final IMessage ABORT_NOMESSAGE
= new Message("", IMessage.ABORT, null, null);
public static final IMessage FAIL_NOMESSAGE
= new Message("", IMessage.FAIL, null, null);
public static final IMessage ERROR_NOMESSAGE
= new Message("", IMessage.ERROR, null, null);
public static final IMessage WARNING_NOMESSAGE
= new Message("", IMessage.WARNING, null, null);
/** handle abort message (ignored if handler is null) */
public static boolean abort(IMessageHandler handler, String message) {
return ((null != handler)
&& handler.handleMessage(abort(message)));
}
/** create and handle exception message (ignored if handler is null) */
public static boolean abort(IMessageHandler handler, String message, Throwable t) {
if (handler != null) return handler.handleMessage(abort(message, t));
return false;
}
/** create and handle fail message (ignored if handler is null) */
public static boolean fail(IMessageHandler handler, String message) {
return ((null != handler)
&& handler.handleMessage(fail(message)));
}
/** create and handle fail message from reader (ignored if handler is null) */
public static boolean fail(IMessageHandler handler, String message, LineReader reader) {
return ((null != handler)
&& handler.handleMessage(fail(message, reader)));
}
/** create and handle fail message (ignored if handler is null) */
public static boolean fail(IMessageHandler handler, String message, Throwable thrown) {
return ((null != handler)
&& handler.handleMessage(fail(message, thrown)));
}
/** create and handle error message (ignored if handler is null) */
public static boolean error(IMessageHandler handler, String message) {
return ((null != handler)
&& handler.handleMessage(error(message)));
}
/** create and handle warn message (ignored if handler is null) */
public static boolean warn(IMessageHandler handler, String message) {
return ((null != handler)
&& handler.handleMessage(warn(message)));
}
/** create and handle debug message (ignored if handler is null) */
public static boolean debug(IMessageHandler handler, String message) {
return ((null != handler)
&& handler.handleMessage(debug(message)));
}
/** create and handle info message (ignored if handler is null) */
public static boolean info(IMessageHandler handler, String message) {
return ((null != handler)
&& handler.handleMessage(info(message)));
}
/** @return ABORT_NOMESSAGE if message is empty or IMessage otherwise */ //
public static IMessage abort(String message) {
if (LangUtil.isEmpty(message)) {
return ABORT_NOMESSAGE;
} else {
return new Message(message, IMessage.ABORT, null, null);
}
}
/** @return abort IMessage with thrown and message o
* ABORT_NOMESSAGE if both are empty/null */ //
public static IMessage abort(String message, Throwable thrown) {
if (!LangUtil.isEmpty(message)) {
return new Message(message, IMessage.ABORT, thrown, null);
} else if (null == thrown) {
return ABORT_NOMESSAGE;
} else {
return new Message(thrown.getMessage(), IMessage.ABORT, thrown, null);
}
}
/** @return FAIL_NOMESSAGE if message is empty or IMessage otherwise */
public static IMessage fail(String message) {
if (LangUtil.isEmpty(message)) {
return FAIL_NOMESSAGE;
} else {
return fail(message, (LineReader) null);
}
}
/**
* Create fail message.
* If message is empty but thrown is not, use thrown.getMessage() as the message.
* If message is empty and thrown is null, return FAIL_NOMESSAGE.
* @return FAIL_NOMESSAGE if thrown is null and message is empty
* or IMessage FAIL with message and thrown otherwise
*/
public static IMessage fail(String message, Throwable thrown) {
if (LangUtil.isEmpty(message)) {
if (null == thrown) {
return FAIL_NOMESSAGE;
} else {
return new Message(thrown.getMessage(), IMessage.FAIL, thrown, null);
}
} else {
return new Message(message, IMessage.FAIL, thrown, null);
}
}
/**
* @return IMessage with IMessage.Kind FAIL and message as text
* and soure location from reader
*/
public static IMessage fail(String message, LineReader reader) {
ISourceLocation loc = null;
if (null == reader) {
loc = ISourceLocation.EMPTY;
} else {
int line = (null == reader ? 0 : reader.getLineNumber());
if (0 < line) {
line = 0;
}
loc = new SourceLocation(reader.getFile(), line, line, 0);
}
return new Message(message, IMessage.FAIL, null, loc);
}
/** @return ERROR_NOMESSAGE if message is empty or IMessage otherwise */ //
public static IMessage error(String message, ISourceLocation location) {
if (LangUtil.isEmpty(message)) {
return ERROR_NOMESSAGE;
} else {
return new Message(message, IMessage.ERROR, null, location);
}
}
/** @return WARNING_NOMESSAGE if message is empty or IMessage otherwise */ //
public static IMessage warn(String message, ISourceLocation location) {
if (LangUtil.isEmpty(message)) {
return WARNING_NOMESSAGE;
} else {
return new Message(message, IMessage.WARNING, null, location);
}
}
/** @return ERROR_NOMESSAGE if message is empty or IMessage otherwise */ //
public static IMessage error(String message) {
if (LangUtil.isEmpty(message)) {
return ERROR_NOMESSAGE;
} else {
return new Message(message, IMessage.ERROR, null, null);
}
}
/** @return WARNING_NOMESSAGE if message is empty or IMessage otherwise */ //
public static IMessage warn(String message) {
if (LangUtil.isEmpty(message)) {
return WARNING_NOMESSAGE;
} else {
return new Message(message, IMessage.WARNING, null, null);
}
}
/** @return IMessage.DEBUG message with message content */
public static IMessage debug(String message) {
return new Message(message, IMessage.DEBUG, null, null);
}
/** @return IMessage.INFO message with message content */
public static IMessage info(String message) {
return new Message(message, IMessage.INFO, null, null);
}
/** @return ISourceLocation with the current File/line of the reader */
public static ISourceLocation makeSourceLocation(LineReader reader) {
LangUtil.throwIaxIfNull(reader, "reader");
int line = reader.getLineNumber();
if (0 < line) {
line = 0;
}
return new SourceLocation(reader.getFile(), line, line, 0);
}
// ------------------------ printing messages
/**
* Print total counts message to the print stream, starting each on a new line
* @param messageHolder
* @param out
*/
public static void printMessageCounts(PrintStream out, IMessageHolder messageHolder) {
if ((null == out) || (null == messageHolder)) {
return;
}
printMessageCounts(out, messageHolder, "");
}
public static void printMessageCounts(PrintStream out, IMessageHolder holder, String prefix) {
out.println(prefix + "MessageHolder: " + MessageUtil.renderCounts(holder));
}
/**
* Print all message to the print stream, starting each on a new line
* @param messageHolder
* @param out
* @see #print(PrintStream, String, IMessageHolder, IMessageRenderer, IMessageHandler)
*/
public static void print(PrintStream out, IMessageHolder messageHolder) {
print(out, messageHolder, (String) null, (IMessageRenderer) null, (IMessageHandler) null);
}
/**
* Print all message to the print stream, starting each on a new line,
* with a prefix.
* @param messageHolder
* @param out
* @see #print(PrintStream, String, IMessageHolder, IMessageRenderer, IMessageHandler)
*/
public static void print(PrintStream out, IMessageHolder holder, String prefix) {
print(out, holder, prefix, (IMessageRenderer) null, (IMessageHandler) null);
}
/**
* Print all message to the print stream, starting each on a new line,
* with a prefix and using a renderer.
* @param messageHolder
* @param out
* @param renderer IMessageRender to render result - use MESSAGE_LINE if null
* @see #print(PrintStream, String, IMessageHolder, IMessageRenderer, IMessageHandler)
*/
public static void print(PrintStream out, IMessageHolder holder, String prefix,
IMessageRenderer renderer) {
print(out, holder, prefix, renderer, (IMessageHandler) null);
}
/**
* Print all message to the print stream, starting each on a new line,
* with a prefix and using a renderer.
* The first line renders a summary: {prefix}MessageHolder: {summary}
* Each message line has the following form:
* <pre>{prefix}[{kind} {index}]: {rendering}</pre>
* (where "{index}" (length 3) is the position within
* the set of like-kinded messages, ignoring selector omissions.
* Renderers are free to render multi-line output.
* @param out the PrintStream sink - return silently if null
* @param messageHolder the IMessageHolder with the messages to print
* @param renderer IMessageRender to render result - use MESSAGE_ALL if null
* @param selector IMessageHandler to select messages to render - if null, do all non-null
*/
public static void print(PrintStream out, IMessageHolder holder, String prefix,
IMessageRenderer renderer, IMessageHandler selector) {
print(out, holder, prefix, renderer, selector, true);
}
public static void print(PrintStream out, IMessageHolder holder, String prefix,
IMessageRenderer renderer, IMessageHandler selector, boolean printSummary) {
if ((null == out) || (null == holder)) {
return;
}
if (null == renderer) {
renderer = MESSAGE_ALL;
}
if (null == selector) {
selector = PICK_ALL;
}
if (printSummary) {
out.println(prefix + "MessageHolder: " + MessageUtil.renderCounts(holder));
}
for (Iterator iter = IMessage.KINDS.iterator(); iter.hasNext();) {
IMessage.Kind kind = (IMessage.Kind) iter.next();
if (!selector.isIgnoring(kind)) {
IMessage[] messages = holder.getMessages(kind, IMessageHolder.EQUAL);
for (int i = 0; i < messages.length; i++) {
if (selector.handleMessage(messages[i])) {
String label = (null == prefix
? ""
: prefix + "[" + kind + " " + LangUtil.toSizedString(i, 3) + "]: ");
out.println(label + renderer.renderToString(messages[i]));
}
}
}
}
}
public static String toShortString(IMessage message) {
if (null == message) {
return "null";
}
String m = message.getMessage();
Throwable t = message.getThrown();
return (message.getKind() + (null == m ? "" : ": " + m)
+ (null == t ? "" : ": " + LangUtil.unqualifiedClassName(t)));
}
/** @return int number of message of this kind (optionally or greater) in list */
public static int numMessages(List messages, Kind kind, boolean orGreater) {
if (LangUtil.isEmpty(messages)) {
return 0;
}
IMessageHandler selector = makeSelector(kind, orGreater, null);
IMessage[] result = visitMessages(messages, selector, true, false);
return result.length;
}
/**
* Select all messages in holder except those of the same
* kind (optionally or greater).
* If kind is null, then all messages are rejected,
* so an empty list is returned.
* @return unmodifiable list of specified IMessage
*/
public static IMessage[] getMessagesExcept(IMessageHolder holder,
final IMessage.Kind kind, final boolean orGreater) {
if ((null == holder) || (null == kind)) {
return new IMessage[0];
}
IMessageHandler selector = new IMessageHandler(){
public boolean handleMessage(IMessage message) {
IMessage.Kind test = message.getKind();
return (!(orGreater
? kind.isSameOrLessThan(test)
: kind == test));
}
public boolean isIgnoring(Kind kind) {
return false;
}
public void dontIgnore(IMessage.Kind kind) {
;
}
};
return visitMessages(holder, selector, true, false);
}
/** @return unmodifiable list of IMessage complying with parameters */
public static List getMessages(IMessageHolder holder,
IMessage.Kind kind, boolean orGreater, String infix) { // XXX untested
if (null == holder) {
return Collections.EMPTY_LIST;
}
if ((null == kind) && LangUtil.isEmpty(infix)) {
return holder.getUnmodifiableListView();
}
IMessageHandler selector = makeSelector(kind, orGreater, infix);
IMessage[] messages = visitMessages(holder, selector, true, false);
if (LangUtil.isEmpty(messages)) {
return Collections.EMPTY_LIST;
}
return Collections.unmodifiableList(Arrays.asList(messages));
}
/**
* Extract messages of type kind from the input list.
*
* @param messages if null, return EMPTY_LIST
* @param kind if null, return messages
* @see MessageHandler#getMessages(Kind)
*/
public static List getMessages(List messages, IMessage.Kind kind) {
if (null == messages) {
return Collections.EMPTY_LIST;
}
if (null == kind) {
return messages;
}
ArrayList result = new ArrayList();
for (Iterator iter = messages.iterator(); iter.hasNext();) {
IMessage element = (IMessage) iter.next();
if (kind == element.getKind()) {
result.add(element);
}
}
if (0 == result.size()) {
return Collections.EMPTY_LIST;
}
return result;
}
/**
* Map to the kind of messages associated with this string key.
* @param kind the String representing the kind of message (IMessage.Kind.toString())
* @return Kind the associated IMessage.Kind, or null if not found
*/
public static IMessage.Kind getKind(String kind) {
if (null != kind) {
kind = kind.toLowerCase();
for (Iterator iter = IMessage.KINDS.iterator(); iter.hasNext();) {
IMessage.Kind k = (IMessage.Kind) iter.next();
if (kind.equals(k.toString())) {
return k;
}
}
}
return null;
}
/**
* Run visitor over the set of messages in holder,
* optionally accumulating those accepted by the visitor
*/
public static IMessage[] visitMessages(IMessageHolder holder,
IMessageHandler visitor, boolean accumulate, boolean abortOnFail) {
if (null == holder) {
return IMessage.RA_IMessage;
} else {
return visitMessages(holder.getUnmodifiableListView(), visitor, accumulate, abortOnFail);
}
}
/**
* Run visitor over the set of messages in holder,
* optionally accumulating those accepted by the visitor
*/
public static IMessage[] visitMessages(IMessage[] messages,
IMessageHandler visitor, boolean accumulate, boolean abortOnFail) {
if (LangUtil.isEmpty(messages)) {
return IMessage.RA_IMessage;
} else {
return visitMessages(Arrays.asList(messages), visitor, accumulate, abortOnFail);
}
}
/**
* Run visitor over a collection of messages,
* optionally accumulating those accepted by the visitor
* @param messages if null or empty, return IMessage.RA_IMessage
* @param visitor run visitor.handleMessage(message) on each
* message - if null and messages not empty, IllegalArgumentException
* @param accumulate if true, then return accepted IMessage[]
* @param abortOnFail if true and visitor returns false, stop visiting
* @return IMessage.RA_IMessage if collection is empty, if not accumulate,
* or if visitor accepted no IMessage,
* or IMessage[] of accepted messages otherwise
* @throws IllegalArgumentException if any in collection are not instanceof IMessage
*/
public static IMessage[] visitMessages(Collection /*IMessage*/ messages,
IMessageHandler visitor, final boolean accumulate, final boolean abortOnFail) {
if (LangUtil.isEmpty(messages)) {
return IMessage.RA_IMessage;
}
LangUtil.throwIaxIfNull(visitor, "visitor");
ArrayList result = (accumulate ? new ArrayList() : null);
for (Iterator iter = messages.iterator(); iter.hasNext();) {
Object o = iter.next();
LangUtil.throwIaxIfFalse(o instanceof IMessage, "expected IMessage, got " + o);
IMessage m = (IMessage) o;
if (visitor.handleMessage(m)) {
if (accumulate) {
result.add(m);
}
} else if (abortOnFail) {
break;
}
}
if (!accumulate || (0 == result.size())) {
return IMessage.RA_IMessage;
} else {
return (IMessage[]) result.toArray(IMessage.RA_IMessage);
}
}
/**
* Make an IMessageHandler that handles IMessage if they have the right kind
* (or greater) and contain some infix String.
* @param kind the IMessage.Kind required of the message
* @param orGreater if true, also accept messages with greater kinds, as
* defined by IMessage.Kind.COMPARATOR
* @param infix the String text to require in the message - may be null or empty
* to accept any message with the specified kind.
* @return IMessageHandler selector that works to param specs
*/
public static IMessageHandler makeSelector(IMessage.Kind kind, boolean orGreater, String infix) {
if (!orGreater && LangUtil.isEmpty(infix)) {
if (kind == IMessage.ABORT) {
return PICK_ABORT;
} else if (kind == IMessage.DEBUG) {
return PICK_DEBUG;
} else if (kind == IMessage.DEBUG) {
return PICK_DEBUG;
} else if (kind == IMessage.ERROR) {
return PICK_ERROR;
} else if (kind == IMessage.FAIL) {
return PICK_FAIL;
} else if (kind == IMessage.INFO) {
return PICK_INFO;
} else if (kind == IMessage.WARNING) {
return PICK_WARNING;
}
}
return new KindSelector(kind, orGreater, infix);
}
// ------------------ visitors to select messages
public static final IMessageHandler PICK_ALL = new KindSelector((IMessage.Kind) null);
public static final IMessageHandler PICK_ABORT = new KindSelector(IMessage.ABORT);
public static final IMessageHandler PICK_DEBUG = new KindSelector(IMessage.DEBUG);
public static final IMessageHandler PICK_ERROR = new KindSelector(IMessage.ERROR);
public static final IMessageHandler PICK_FAIL = new KindSelector(IMessage.FAIL);
public static final IMessageHandler PICK_INFO = new KindSelector(IMessage.INFO);
public static final IMessageHandler PICK_WARNING = new KindSelector(IMessage.WARNING);
public static final IMessageHandler PICK_ABORT_PLUS = new KindSelector(IMessage.ABORT, true);
public static final IMessageHandler PICK_DEBUG_PLUS = new KindSelector(IMessage.DEBUG, true);
public static final IMessageHandler PICK_ERROR_PLUS = new KindSelector(IMessage.ERROR, true);
public static final IMessageHandler PICK_FAIL_PLUS = new KindSelector(IMessage.FAIL, true);
public static final IMessageHandler PICK_INFO_PLUS = new KindSelector(IMessage.INFO, true);
public static final IMessageHandler PICK_WARNING_PLUS = new KindSelector(IMessage.WARNING, true);
/** implementation for PICK_... constants */
private static class KindSelector implements IMessageHandler {
final IMessage.Kind sought;
final boolean floor;
final String infix;
KindSelector(IMessage.Kind sought) {
this(sought, false);
}
KindSelector(IMessage.Kind sought, boolean floor) {
this(sought, floor, null);
}
KindSelector(IMessage.Kind sought, boolean floor, String infix) {
this.sought = sought;
this.floor = floor;
this.infix = (LangUtil.isEmpty(infix) ? null : infix);
}
/** @return false if this message is null,
* of true if we seek any kind (null)
* or if this has the exact kind we seek
* and this has any text sought
*/
public boolean handleMessage(IMessage message) {
return ((null != message) && !isIgnoring(message.getKind())
&& textIn(message));
}
/** @return true if handleMessage would return false for a message of this kind */
public boolean isIgnoring(IMessage.Kind kind) {
if (!floor) {
return ((null != sought) && (sought != kind));
} else if (null == sought) {
return false;
} else {
return (0 < IMessage.Kind.COMPARATOR.compare(sought, kind));
}
}
public void dontIgnore(IMessage.Kind kind) {
;
}
private boolean textIn(IMessage message) {
if (null == infix) {
return true;
}
String text = message.getMessage();
return ((null != message) && (-1 != text.indexOf(infix)));
}
}
// ------------------ components to render messages
/** parameterize rendering behavior for messages */
public static interface IMessageRenderer {
String renderToString(IMessage message);
}
/** render message more verbosely if it is worse */
public static final IMessageRenderer MESSAGE_SCALED = new IMessageRenderer() {
public String toString() { return "MESSAGE_SCALED"; }
public String renderToString(IMessage message) {
if (null == message) {
return "((IMessage) null)";
}
IMessage.Kind kind = message.getKind();
int level = 3;
if ((kind == IMessage.ABORT) || (kind == IMessage.FAIL)) {
level = 1;
} else if ((kind == IMessage.ERROR) || (kind == IMessage.WARNING)) {
level = 2;
} else {
level = 3;
}
String result = null;
switch (level) {
case (1) :
result = MESSAGE_TOSTRING.renderToString(message);
break;
case (2) :
result = MESSAGE_LINE.renderToString(message);
break;
case (3) :
result = MESSAGE_SHORT.renderToString(message);
break;
}
Throwable thrown = message.getThrown();
if (null != thrown) {
if (level == 3) {
result += "Thrown: \n" + LangUtil.renderExceptionShort(thrown);
} else {
result += "Thrown: \n" + LangUtil.renderException(thrown);
}
}
return result;
}
};
/** render message as label, i.e., less than 33 char */
public static final IMessageRenderer MESSAGE_LABEL = new IMessageRenderer() {
public String toString() { return "MESSAGE_LABEL"; }
public String renderToString(IMessage message) {
if (null == message) {
return "((IMessage) null)";
}
return renderMessageLine(message, 5, 5, 32);
}
};
/** render message as label, i.e., less than 33 char, with no source location */
public static final IMessageRenderer MESSAGE_LABEL_NOLOC = new IMessageRenderer() {
public String toString() { return "MESSAGE_LABEL_NOLOC"; }
public String renderToString(IMessage message) {
if (null == message) {
return "((IMessage) null)";
}
return renderMessageLine(message, 10, 0, 32);
}
};
/** render message as line, i.e., less than 75 char, no internal line sep */
public static final IMessageRenderer MESSAGE_LINE = new IMessageRenderer() {
public String toString() { return "MESSAGE_LINE"; }
public String renderToString(IMessage message) {
if (null == message) {
return "((IMessage) null)";
}
return renderMessageLine(message, 8, 2, 74);
}
};
/** render message as line, i.e., less than 75 char, no internal line sep,
* trying to trim text as needed to end with a full source location */
public static final IMessageRenderer MESSAGE_LINE_FORCE_LOC = new IMessageRenderer() {
public String toString() { return "MESSAGE_LINE_FORCE_LOC"; }
public String renderToString(IMessage message) {
if (null == message) {
return "((IMessage) null)";
}
return renderMessageLine(message, 2, 40, 74);
}
};
/** render message without restriction, up to 10K, including throwable */
public static final IMessageRenderer MESSAGE_ALL = new IMessageRenderer() {
public String toString() { return "MESSAGE_ALL"; }
public String renderToString(IMessage message) {
return renderMessage(message);
}
};
// /** render message without restriction, up to 10K, including (but eliding) throwable */
// public static final IMessageRenderer MESSAGE_ALL_ELIDED= new IMessageRenderer() {
// public String toString() { return "MESSAGE_ALL_ELIDED"; }
// public String renderToString(IMessage message) {
// return renderMessage(message, true);
// }
// };
/** render message without restriction, except any Throwable thrown */
public static final IMessageRenderer MESSAGE_MOST = new IMessageRenderer() {
public String toString() { return "MESSAGE_MOST"; }
public String renderToString(IMessage message) {
if (null == message) {
return "((IMessage) null)";
}
return renderMessageLine(message, 1, 1, 10000);
}
};
/** render message as wide line, i.e., less than 256 char, no internal line sep,
* except any Throwable thrown
*/
public static final IMessageRenderer MESSAGE_WIDELINE = new IMessageRenderer() {
public String toString() { return "MESSAGE_WIDELINE"; }
public String renderToString(IMessage message) {
if (null == message) {
return "((IMessage) null)";
}
return renderMessageLine(message, 8, 2, 255); // XXX revert to 256
}
};
/** render message using its toString() or "((IMessage) null)" */
public static final IMessageRenderer MESSAGE_TOSTRING = new IMessageRenderer() {
public String toString() { return "MESSAGE_TOSTRING"; }
public String renderToString(IMessage message) {
if (null == message) {
return "((IMessage) null)";
}
return message.toString();
}
};
/** render message using toShortString(IMessage)" */
public static final IMessageRenderer MESSAGE_SHORT = new IMessageRenderer() {
public String toString() { return "MESSAGE_SHORT"; }
public String renderToString(IMessage message) {
return toShortString(message);
}
};
/**
* This renders IMessage as String, ignoring empty elements
* and eliding any thrown stack traces.
* @return "((IMessage) null)" if null or String rendering otherwise,
* including everything (esp. throwable stack trace)
* @see renderSourceLocation(ISourceLocation loc)
*/
public static String renderMessage(IMessage message) {
return renderMessage(message, true);
}
/**
* This renders IMessage as String, ignoring empty elements
* and eliding any thrown.
* @return "((IMessage) null)" if null or String rendering otherwise,
* including everything (esp. throwable stack trace)
* @see renderSourceLocation(ISourceLocation loc)
*/
public static String renderMessage(IMessage message, boolean elide) {
if (null == message) {
return "((IMessage) null)";
}
ISourceLocation loc = message.getSourceLocation();
String locString = (null == loc ? "" : " at " + loc);
String result = message.getKind() + locString + " " + message.getMessage();
Throwable thrown = message.getThrown();
if (thrown != null) {
result += " -- " + LangUtil.renderExceptionShort(thrown);
result += "\n" + LangUtil.renderException(thrown, elide);
}
if (message.getExtraSourceLocations().isEmpty()) {
return result;
}
else {
return addExtraSourceLocations(message, result);
}
}
public static String addExtraSourceLocations(
IMessage message,
String baseMessage)
{
StringWriter buf = new StringWriter();
PrintWriter writer = new PrintWriter(buf);
writer.println(baseMessage);
for (Iterator iter = message.getExtraSourceLocations().iterator(); iter.hasNext();) {
ISourceLocation element = (ISourceLocation) iter.next();
writer.print("\tsee also: " + element.toString());
if (iter.hasNext()) {
writer.println();
}
}
try { buf.close(); }
catch (IOException ioe) {}
return buf.getBuffer().toString();
}
/**
* Render ISourceLocation to String, ignoring empty elements
* (null or ISourceLocation.NO_FILE or ISourceLocation.NO_COLUMN
* (though implementations may return 0 from getColumn() when
* passed NO_COLUMN as input)).
* @return "((ISourceLocation) null)" if null or String rendering
* <pre>{file:}line{:column}</pre>
*
*/
public static String renderSourceLocation(ISourceLocation loc) {
if (null == loc) {
return "((ISourceLocation) null)";
}
StringBuffer sb = new StringBuffer();
File sourceFile = loc.getSourceFile();
if (sourceFile != ISourceLocation.NO_FILE) {
sb.append(sourceFile.getPath());
sb.append(":");
}
int line = loc.getLine();
sb.append("" + line);
int column = loc.getColumn();
if (column != ISourceLocation.NO_COLUMN) {
sb.append(":" + column);
}
return sb.toString();
}
/**
* Render message in a line.
* IMessage.Kind is always printed, then any unqualified exception class,
* then the remainder of text and location according to their relative scale,
* all to fit in max characters or less.
* This does not render thrown except for the unqualified class name
* @param max the number of characters - forced to 32..10000
* @param textScale relative proportion to spend on message and/or exception
* message, relative to source location - if 0, message is suppressed
* @param locScale relative proportion to spend on source location
* suppressed if 0
* @return "((IMessage) null)" or message per spec
*/
public static String renderMessageLine(
IMessage message,
int textScale,
int locScale,
int max) {
if (null == message) {
return "((IMessage) null)";
}
if (max < 32) {
max = 32;
} else if (max > 10000) {
max = 10000;
}
if (0 > textScale) {
textScale = -textScale;
}
if (0 > locScale) {
locScale = -locScale;
}
String text = message.getMessage();
Throwable thrown = message.getThrown();
ISourceLocation sl = message.getSourceLocation();
IMessage.Kind kind = message.getKind();
StringBuffer result = new StringBuffer();
result.append(kind.toString());
result.append(": ");
if (null != thrown) {
result.append(LangUtil.unqualifiedClassName(thrown) + " ");
if ((null == text) || ("".equals(text))) {
text = thrown.getMessage();
}
}
if (0 == textScale) {
text = "";
} else if ((null != text) && (null != thrown)) {
// decide between message and exception text?
String s = thrown.getMessage();
if ((null != s) && (0 < s.length())) {
text += " - " + s;
}
}
String loc = "";
if ((0 != locScale) && (null != sl)) {
File f = sl.getSourceFile();
if (f == ISourceLocation.NO_FILE) {
f = null;
}
if (null != f) {
loc = f.getName();
}
int line = sl.getLine();
int col = sl.getColumn();
int end = sl.getEndLine();
if ((0 == line) && (0 == col) && (0 == end)) {
// ignore numbers if default
} else {
loc += ":" + line + (col == 0 ? "" : ":" + col);
if (line != end) { // XXX consider suppressing nonstandard...
loc += ":" + end;
}
}
if (!LangUtil.isEmpty(loc)) {
loc = "@[" + loc; // matching "]" added below after clipping
}
}
// now budget between text and loc
float totalScale = locScale + textScale;
float remainder = max - result.length() - 4;
if ((remainder > 0) && (0 < totalScale)) {
int textSize = (int) (remainder * textScale/totalScale);
int locSize = (int) (remainder * locScale/totalScale);
// adjust for underutilization
int extra = locSize - loc.length();
if (0 < extra) {
locSize = loc.length();
textSize += extra;
}
extra = textSize - text.length();
if (0 < extra) {
textSize = text.length();
if (locSize < loc.length()) {
locSize += extra;
}
}
if (locSize > loc.length()) {
locSize = loc.length();
}
if (textSize > text.length()) {
textSize = text.length();
}
if (0 < textSize) {
result.append(text.substring(0, textSize));
}
if (0 < locSize) {
if (0 < textSize) {
result.append(" ");
}
result.append(loc.substring(0, locSize) + "]");
}
}
return result.toString();
}
/** @return String of the form "{(# {type}) }.." for message kinds, skipping 0 */
public static String renderCounts(IMessageHolder holder) {
if (0 == holder.numMessages(null, false)) {
return "(0 messages)";
}
StringBuffer sb = new StringBuffer();
for (Iterator iter = IMessage.KINDS.iterator(); iter.hasNext();) {
IMessage.Kind kind = (IMessage.Kind) iter.next();
int num = holder.numMessages(kind, false);
if (0 < num) {
sb.append(" (" + num + " " + kind + ") ");
}
}
return sb.toString();
}
/**
* Factory for handler adapted to PrintStream
* XXX weak - only handles println(String)
* @param handler the IMessageHandler sink for the messages generated
* @param kind the IMessage.Kind of message to create
* @param overage the OuputStream for text not captured by the handler
* (if null, System.out used)
* @throws IllegalArgumentException if kind or handler is null
*/
public static PrintStream handlerPrintStream(final IMessageHandler handler,
final IMessage.Kind kind, final OutputStream overage, final String prefix) {
LangUtil.throwIaxIfNull(handler, "handler");
LangUtil.throwIaxIfNull(kind, "kind");
class HandlerPrintStream extends PrintStream {
HandlerPrintStream() {
super(null == overage ? System.out : overage);
}
public void println() {
println("");
}
public void println(Object o) {
println(null == o ? "null" : o.toString());
}
public void println(String input) {
String textMessage = (null == prefix ? input : prefix + input);
IMessage m = new Message(textMessage, kind, null, null);
handler.handleMessage(m);
}
}
return new HandlerPrintStream();
}
/** utility class */
private MessageUtil() {}
/**
* Handle all messages in the second handler using the first
* @param handler the IMessageHandler sink for all messages in source
* @param holder the IMessageHolder source for all messages to handle
* @param fastFail if true, stop on first failure
* @return false if any sink.handleMessage(..) failed
*/
public static boolean handleAll(
IMessageHandler sink,
IMessageHolder source,
boolean fastFail) {
return handleAll(sink, source, null, true, fastFail);
}
/**
* Handle messages in the second handler using the first
* @param handler the IMessageHandler sink for all messages in source
* @param holder the IMessageHolder source for all messages to handle
* @param kind the IMessage.Kind to select, if not null
* @param orGreater if true, also accept greater kinds
* @param fastFail if true, stop on first failure
* @return false if any sink.handleMessage(..) failed
*/
public static boolean handleAll(
IMessageHandler sink,
IMessageHolder source,
IMessage.Kind kind,
boolean orGreater,
boolean fastFail) {
LangUtil.throwIaxIfNull(sink, "sink");
LangUtil.throwIaxIfNull(source, "source");
return handleAll(sink, source.getMessages(kind, orGreater), fastFail);
}
/**
* Handle messages in the second handler using the first
* if they are NOT of this kind (optionally, or greater).
* If you pass null as the kind, then all messages are
* ignored and this returns true.
* @param handler the IMessageHandler sink for all messages in source
* @param holder the IMessageHolder source for all messages to handle
* @param kind the IMessage.Kind to reject, if not null
* @param orGreater if true, also reject greater kinds
* @param fastFail if true, stop on first failure
* @return false if any sink.handleMessage(..) failed
*/
public static boolean handleAllExcept(
IMessageHandler sink,
IMessageHolder source,
IMessage.Kind kind,
boolean orGreater,
boolean fastFail) {
LangUtil.throwIaxIfNull(sink, "sink");
LangUtil.throwIaxIfNull(source, "source");
if (null == kind) {
return true;
}
IMessage[] messages = getMessagesExcept(source, kind, orGreater);
return handleAll(sink, messages, fastFail);
}
/**
* Handle messages in the sink.
* @param handler the IMessageHandler sink for all messages in source
* @param sources the IMessage[] messages to handle
* @param fastFail if true, stop on first failure
* @return false if any sink.handleMessage(..) failed
* @throws IllegalArgumentException if sink is null
*/
public static boolean handleAll(
IMessageHandler sink,
IMessage[] sources,
boolean fastFail) {
LangUtil.throwIaxIfNull(sink, "sink");
if (LangUtil.isEmpty(sources)) {
return true;
}
boolean result = true;
for (int i = 0; i < sources.length; i++) {
if (!sink.handleMessage(sources[i])) {
if (fastFail) {
return false;
}
if (result) {
result = false;
}
}
}
return result;
}
}
|
152,161 |
Bug 152161 Contribution: Support -Xset in Load-Time Weaving Configuration
|
I needed this to try out a setting in the pipelined compilation (-Xset:runMinimalMemory=true) ... I was able to verify that it parsed and set an option correctly in the debugger. I also have included a test that sets all the currently available options.
|
resolved fixed
|
039be68
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-08-08T13:50:57Z | 2006-07-28T15:20:00Z |
loadtime/src/org/aspectj/weaver/loadtime/ClassLoaderWeavingAdaptor.java
|
/*******************************************************************************
* Copyright (c) 2005 Contributors.
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Eclipse Public License v1.0
* which accompanies this distribution and is available at
* http://eclipse.org/legal/epl-v10.html
*
* Contributors:
* Alexandre Vasseur initial implementation
* David Knibb weaving context enhancments
*******************************************************************************/
package org.aspectj.weaver.loadtime;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.URL;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Properties;
import java.util.StringTokenizer;
import org.aspectj.asm.IRelationship;
import org.aspectj.bridge.AbortException;
import org.aspectj.bridge.ISourceLocation;
import org.aspectj.util.LangUtil;
import org.aspectj.weaver.ICrossReferenceHandler;
import org.aspectj.weaver.Lint;
import org.aspectj.weaver.ResolvedType;
import org.aspectj.weaver.UnresolvedType;
import org.aspectj.weaver.World;
import org.aspectj.weaver.Lint.Kind;
import org.aspectj.weaver.bcel.BcelWeaver;
import org.aspectj.weaver.loadtime.definition.Definition;
import org.aspectj.weaver.loadtime.definition.DocumentParser;
import org.aspectj.weaver.ltw.LTWWorld;
import org.aspectj.weaver.patterns.PatternParser;
import org.aspectj.weaver.patterns.TypePattern;
import org.aspectj.weaver.tools.GeneratedClassHandler;
import org.aspectj.weaver.tools.Trace;
import org.aspectj.weaver.tools.TraceFactory;
import org.aspectj.weaver.tools.WeavingAdaptor;
/**
* @author <a href="mailto:alex AT gnilux DOT com">Alexandre Vasseur</a>
*/
public class ClassLoaderWeavingAdaptor extends WeavingAdaptor {
private final static String AOP_XML = "META-INF/aop.xml";
private boolean initialized;
private List m_dumpTypePattern = new ArrayList();
private boolean m_dumpBefore = false;
private List m_includeTypePattern = new ArrayList();
private List m_excludeTypePattern = new ArrayList();
private List m_includeStartsWith = new ArrayList();
private List m_excludeStartsWith = new ArrayList();
private List m_aspectExcludeTypePattern = new ArrayList();
private List m_aspectExcludeStartsWith = new ArrayList();
private List m_aspectIncludeTypePattern = new ArrayList();
private List m_aspectIncludeStartsWith = new ArrayList();
private StringBuffer namespace;
private IWeavingContext weavingContext;
private static Trace trace = TraceFactory.getTraceFactory().getTrace(ClassLoaderWeavingAdaptor.class);
public ClassLoaderWeavingAdaptor() {
super();
if (trace.isTraceEnabled()) trace.enter("<init>",this);
if (trace.isTraceEnabled()) trace.exit("<init>");
}
/**
* We don't need a reference to the class loader and using it during
* construction can cause problems with recursion. It also makes sense
* to supply the weaving context during initialization to.
* @deprecated
*/
public ClassLoaderWeavingAdaptor(final ClassLoader deprecatedLoader, final IWeavingContext deprecatedContext) {
super();
if (trace.isTraceEnabled()) trace.enter("<init>",this,new Object[] { deprecatedLoader, deprecatedContext });
if (trace.isTraceEnabled()) trace.exit("<init>");
}
protected void initialize (final ClassLoader classLoader, IWeavingContext context) {
//super(null);// at this stage we don't have yet a generatedClassHandler to define to the VM the closures
if (initialized) return;
if (trace.isTraceEnabled()) trace.enter("initialize",this,new Object[] { classLoader, context });
this.weavingContext = context;
if (weavingContext == null) {
weavingContext = new DefaultWeavingContext(classLoader);
}
createMessageHandler();
this.generatedClassHandler = new GeneratedClassHandler() {
/**
* Callback when we need to define a Closure in the JVM
*
* @param name
* @param bytes
*/
public void acceptClass(String name, byte[] bytes) {
try {
if (shouldDump(name.replace('/', '.'), false)) {
dump(name, bytes, false);
}
} catch (Throwable throwable) {
throwable.printStackTrace();
}
defineClass(classLoader, name, bytes);// could be done lazily using the hook
}
};
List definitions = parseDefinitions(classLoader);
if (!enabled) {
if (trace.isTraceEnabled()) trace.exit("initialize",enabled);
return;
}
bcelWorld = new LTWWorld(
classLoader, getMessageHandler(), new ICrossReferenceHandler() {
public void addCrossReference(ISourceLocation from, ISourceLocation to, IRelationship.Kind kind, boolean runtimeTest) {
;// for tools only
}
}
);
// //TODO this AJ code will call
// //org.aspectj.apache.bcel.Repository.setRepository(this);
// //ie set some static things
// //==> bogus as Bcel is expected to be
// org.aspectj.apache.bcel.Repository.setRepository(new ClassLoaderRepository(loader));
weaver = new BcelWeaver(bcelWorld);
// register the definitions
registerDefinitions(weaver, classLoader, definitions);
if (enabled) {
//bcelWorld.setResolutionLoader(loader.getParent());//(ClassLoader)null);//
// after adding aspects
weaver.prepareForWeave();
}
else {
bcelWorld = null;
weaver = null;
}
initialized = true;
if (trace.isTraceEnabled()) trace.exit("initialize",enabled);
}
/**
* Load and cache the aop.xml/properties according to the classloader visibility rules
*
* @param weaver
* @param loader
*/
private List parseDefinitions(final ClassLoader loader) {
List definitions = new ArrayList();
try {
info("register classloader " + getClassLoaderName(loader));
//TODO av underoptimized: we will parse each XML once per CL that see it
//TODO av dev mode needed ? TBD -Daj5.def=...
if (ClassLoader.getSystemClassLoader().equals(loader)) {
String file = System.getProperty("aj5.def", null);
if (file != null) {
info("using (-Daj5.def) " + file);
definitions.add(DocumentParser.parse((new File(file)).toURL()));
}
}
String resourcePath = System.getProperty("org.aspectj.weaver.loadtime.configuration",AOP_XML);
StringTokenizer st = new StringTokenizer(resourcePath,";");
while(st.hasMoreTokens()){
Enumeration xmls = weavingContext.getResources(st.nextToken());
// System.out.println("? registerDefinitions: found-aop.xml=" + xmls.hasMoreElements() + ", loader=" + loader);
while (xmls.hasMoreElements()) {
URL xml = (URL) xmls.nextElement();
info("using configuration " + weavingContext.getFile(xml));
definitions.add(DocumentParser.parse(xml));
}
}
if (definitions.isEmpty()) {
enabled = false;// will allow very fast skip in shouldWeave()
info("no configuration found. Disabling weaver for class loader " + getClassLoaderName(loader));
}
} catch (Exception e) {
enabled = false;// will allow very fast skip in shouldWeave()
warn("parse definitions failed",e);
}
return definitions;
}
private void registerDefinitions(final BcelWeaver weaver, final ClassLoader loader, List definitions) {
try {
registerOptions(weaver, loader, definitions);
registerAspectExclude(weaver, loader, definitions);
registerAspectInclude(weaver, loader, definitions);
registerAspects(weaver, loader, definitions);
registerIncludeExclude(weaver, loader, definitions);
registerDump(weaver, loader, definitions);
} catch (Exception e) {
enabled = false;// will allow very fast skip in shouldWeave()
warn("register definition failed",(e instanceof AbortException)?null:e);
}
}
private String getClassLoaderName (ClassLoader loader) {
return weavingContext.getClassLoaderName();
}
/**
* Configure the weaver according to the option directives
* TODO av - don't know if it is that good to reuse, since we only allow a small subset of options in LTW
*
* @param weaver
* @param loader
* @param definitions
*/
private void registerOptions(final BcelWeaver weaver, final ClassLoader loader, final List definitions) {
StringBuffer allOptions = new StringBuffer();
for (Iterator iterator = definitions.iterator(); iterator.hasNext();) {
Definition definition = (Definition) iterator.next();
allOptions.append(definition.getWeaverOptions()).append(' ');
}
Options.WeaverOption weaverOption = Options.parse(allOptions.toString(), loader, getMessageHandler());
// configure the weaver and world
// AV - code duplicates AspectJBuilder.initWorldAndWeaver()
World world = weaver.getWorld();
setMessageHandler(weaverOption.messageHandler);
world.setXlazyTjp(weaverOption.lazyTjp);
world.setXHasMemberSupportEnabled(weaverOption.hasMember);
world.setOptionalJoinpoints(weaverOption.optionalJoinpoints);
world.setPinpointMode(weaverOption.pinpoint);
weaver.setReweavableMode(weaverOption.notReWeavable);
world.setXnoInline(weaverOption.noInline);
// AMC - autodetect as per line below, needed for AtAjLTWTests.testLTWUnweavable
world.setBehaveInJava5Way(LangUtil.is15VMOrGreater());
world.setAddSerialVerUID(weaverOption.addSerialVersionUID);
/* First load defaults */
bcelWorld.getLint().loadDefaultProperties();
/* Second overlay LTW defaults */
bcelWorld.getLint().adviceDidNotMatch.setKind(null);
/* Third load user file using -Xlintfile so that -Xlint wins */
if (weaverOption.lintFile != null) {
InputStream resource = null;
try {
resource = loader.getResourceAsStream(weaverOption.lintFile);
Exception failure = null;
if (resource != null) {
try {
Properties properties = new Properties();
properties.load(resource);
world.getLint().setFromProperties(properties);
} catch (IOException e) {
failure = e;
}
}
if (failure != null || resource == null) {
warn("Cannot access resource for -Xlintfile:"+weaverOption.lintFile,failure);
// world.getMessageHandler().handleMessage(new Message(
// "Cannot access resource for -Xlintfile:"+weaverOption.lintFile,
// IMessage.WARNING,
// failure,
// null));
}
} finally {
try { resource.close(); } catch (Throwable t) {;}
}
}
/* Fourth override with -Xlint */
if (weaverOption.lint != null) {
if (weaverOption.lint.equals("default")) {//FIXME should be AjBuildConfig.AJLINT_DEFAULT but yetanother deps..
bcelWorld.getLint().loadDefaultProperties();
} else {
bcelWorld.getLint().setAll(weaverOption.lint);
}
}
//TODO proceedOnError option
}
private void registerAspectExclude(final BcelWeaver weaver, final ClassLoader loader, final List definitions) {
String fastMatchInfo = null;
for (Iterator iterator = definitions.iterator(); iterator.hasNext();) {
Definition definition = (Definition) iterator.next();
for (Iterator iterator1 = definition.getAspectExcludePatterns().iterator(); iterator1.hasNext();) {
String exclude = (String) iterator1.next();
TypePattern excludePattern = new PatternParser(exclude).parseTypePattern();
m_aspectExcludeTypePattern.add(excludePattern);
fastMatchInfo = looksLikeStartsWith(exclude);
if (fastMatchInfo != null) {
m_aspectExcludeStartsWith.add(fastMatchInfo);
}
}
}
}
private void registerAspectInclude(final BcelWeaver weaver, final ClassLoader loader, final List definitions) {
String fastMatchInfo = null;
for (Iterator iterator = definitions.iterator(); iterator.hasNext();) {
Definition definition = (Definition) iterator.next();
for (Iterator iterator1 = definition.getAspectIncludePatterns().iterator(); iterator1.hasNext();) {
String include = (String) iterator1.next();
TypePattern includePattern = new PatternParser(include).parseTypePattern();
m_aspectIncludeTypePattern.add(includePattern);
fastMatchInfo = looksLikeStartsWith(include);
if (fastMatchInfo != null) {
m_aspectIncludeStartsWith.add(fastMatchInfo);
}
}
}
}
protected void lint (String name, String[] infos) {
Lint lint = bcelWorld.getLint();
Kind kind = lint.getLintKind(name);
kind.signal(infos,null,null);
}
protected String getContextId () {
return weavingContext.getId();
}
/**
* Register the aspect, following include / exclude rules
*
* @param weaver
* @param loader
* @param definitions
*/
private void registerAspects(final BcelWeaver weaver, final ClassLoader loader, final List definitions) {
if (trace.isTraceEnabled()) trace.enter("registerAspects",this, new Object[] { weaver, loader, definitions} );
//TODO: the exclude aspect allow to exclude aspect defined upper in the CL hierarchy - is it what we want ??
// if not, review the getResource so that we track which resource is defined by which CL
//iterate aspectClassNames
//exclude if in any of the exclude list
for (Iterator iterator = definitions.iterator(); iterator.hasNext();) {
Definition definition = (Definition) iterator.next();
for (Iterator aspects = definition.getAspectClassNames().iterator(); aspects.hasNext();) {
String aspectClassName = (String) aspects.next();
if (acceptAspect(aspectClassName)) {
info("register aspect " + aspectClassName);
// System.err.println("? ClassLoaderWeavingAdaptor.registerAspects() aspectName=" + aspectClassName + ", loader=" + loader + ", bundle=" + weavingContext.getClassLoaderName());
/*ResolvedType aspect = */weaver.addLibraryAspect(aspectClassName);
//generate key for SC
if(namespace==null){
namespace=new StringBuffer(aspectClassName);
}else{
namespace = namespace.append(";"+aspectClassName);
}
}
else {
// warn("aspect excluded: " + aspectClassName);
lint("aspectExcludedByConfiguration", new String[] { aspectClassName, getClassLoaderName(loader) });
}
}
}
//iterate concreteAspects
//exclude if in any of the exclude list - note that the user defined name matters for that to happen
for (Iterator iterator = definitions.iterator(); iterator.hasNext();) {
Definition definition = (Definition) iterator.next();
for (Iterator aspects = definition.getConcreteAspects().iterator(); aspects.hasNext();) {
Definition.ConcreteAspect concreteAspect = (Definition.ConcreteAspect) aspects.next();
if (acceptAspect(concreteAspect.name)) {
ConcreteAspectCodeGen gen = new ConcreteAspectCodeGen(concreteAspect, weaver.getWorld());
if (!gen.validate()) {
error("Concrete-aspect '"+concreteAspect.name+"' could not be registered");
break;
}
this.generatedClassHandler.acceptClass(
concreteAspect.name,
gen.getBytes()
);
/*ResolvedType aspect = */weaver.addLibraryAspect(concreteAspect.name);
//generate key for SC
if(namespace==null){
namespace=new StringBuffer(concreteAspect.name);
}else{
namespace = namespace.append(";"+concreteAspect.name);
}
}
}
}
// System.out.println("ClassLoaderWeavingAdaptor.registerAspects() classloader=" + weavingContext.getClassLoaderName() + ", namespace=" + namespace);
/* We didn't register any aspects so disable the adaptor */
if (namespace == null) {
enabled = false;
info("no aspects registered. Disabling weaver for class loader " + getClassLoaderName(loader));
}
if (trace.isTraceEnabled()) trace.exit("registerAspects",enabled);
}
/**
* Register the include / exclude filters
* We duplicate simple patterns in startWith filters that will allow faster matching without ResolvedType
*
* @param weaver
* @param loader
* @param definitions
*/
private void registerIncludeExclude(final BcelWeaver weaver, final ClassLoader loader, final List definitions) {
String fastMatchInfo = null;
for (Iterator iterator = definitions.iterator(); iterator.hasNext();) {
Definition definition = (Definition) iterator.next();
for (Iterator iterator1 = definition.getIncludePatterns().iterator(); iterator1.hasNext();) {
String include = (String) iterator1.next();
TypePattern includePattern = new PatternParser(include).parseTypePattern();
m_includeTypePattern.add(includePattern);
fastMatchInfo = looksLikeStartsWith(include);
if (fastMatchInfo != null) {
m_includeStartsWith.add(fastMatchInfo);
}
}
for (Iterator iterator1 = definition.getExcludePatterns().iterator(); iterator1.hasNext();) {
String exclude = (String) iterator1.next();
TypePattern excludePattern = new PatternParser(exclude).parseTypePattern();
m_excludeTypePattern.add(excludePattern);
fastMatchInfo = looksLikeStartsWith(exclude);
if (fastMatchInfo != null) {
m_excludeStartsWith.add(fastMatchInfo);
}
}
}
}
/**
* Checks if the type pattern can be handled as a startswith check
*
* TODO AV - enhance to support "char.sss" ie FQN direclty (match iff equals)
* we could also add support for "*..*charss" endsWith style?
*
* @param typePattern
* @return null if not possible, or the startWith sequence to test against
*/
private String looksLikeStartsWith(String typePattern) {
if (typePattern.indexOf('@') >= 0
|| typePattern.indexOf('+') >= 0
|| typePattern.indexOf(' ') >= 0
|| typePattern.charAt(typePattern.length()-1) != '*') {
return null;
}
// now must looks like with "charsss..*" or "cha.rss..*" etc
// note that "*" and "*..*" won't be fast matched
// and that "charsss.*" will not neither
int length = typePattern.length();
if (typePattern.endsWith("..*") && length > 3) {
if (typePattern.indexOf("..") == length-3 // no ".." before last sequence
&& typePattern.indexOf('*') == length-1) { // no "*" before last sequence
return typePattern.substring(0, length-2).replace('$', '.');
// ie "charsss." or "char.rss." etc
}
}
return null;
}
/**
* Register the dump filter
*
* @param weaver
* @param loader
* @param definitions
*/
private void registerDump(final BcelWeaver weaver, final ClassLoader loader, final List definitions) {
for (Iterator iterator = definitions.iterator(); iterator.hasNext();) {
Definition definition = (Definition) iterator.next();
for (Iterator iterator1 = definition.getDumpPatterns().iterator(); iterator1.hasNext();) {
String dump = (String) iterator1.next();
TypePattern pattern = new PatternParser(dump).parseTypePattern();
m_dumpTypePattern.add(pattern);
}
if (definition.shouldDumpBefore()) {
m_dumpBefore = true;
}
}
}
protected boolean accept(String className, byte[] bytes) {
// avoid ResolvedType if not needed
if (m_excludeTypePattern.isEmpty() && m_includeTypePattern.isEmpty()) {
return true;
}
// still try to avoid ResolvedType if we have simple patterns
String fastClassName = className.replace('/', '.').replace('$', '.');
for (int i = 0; i < m_excludeStartsWith.size(); i++) {
if (fastClassName.startsWith((String)m_excludeStartsWith.get(i))) {
return false;
}
}
/*
* Bug 120363
* If we have an exclude pattern that cannot be matched using "starts with"
* then we cannot fast accept
*/
if (m_excludeTypePattern.isEmpty()) {
boolean fastAccept = false;//defaults to false if no fast include
for (int i = 0; i < m_includeStartsWith.size(); i++) {
fastAccept = fastClassName.startsWith((String)m_includeStartsWith.get(i));
if (fastAccept) {
break;
}
}
}
// needs further analysis
// TODO AV - needs refactoring
// during LTW this calling resolve at that stage is BAD as we do have the bytecode from the classloader hook
// but still go thru resolve that will do a getResourcesAsStream on disk
// this is also problematic for jit stub which are not on disk - as often underlying infra
// does returns null or some other info for getResourceAsStream (f.e. WLS 9 CR248491)
// Instead I parse the given bytecode. But this also means it will be parsed again in
// new WeavingClassFileProvider() from WeavingAdaptor.getWovenBytes()...
ensureDelegateInitialized(className,bytes);
ResolvedType classInfo = delegateForCurrentClass.getResolvedTypeX();//BAD: weaver.getWorld().resolve(UnresolvedType.forName(className), true);
//exclude are "AND"ed
for (Iterator iterator = m_excludeTypePattern.iterator(); iterator.hasNext();) {
TypePattern typePattern = (TypePattern) iterator.next();
if (typePattern.matchesStatically(classInfo)) {
// exclude match - skip
return false;
}
}
//include are "OR"ed
boolean accept = true;//defaults to true if no include
for (Iterator iterator = m_includeTypePattern.iterator(); iterator.hasNext();) {
TypePattern typePattern = (TypePattern) iterator.next();
accept = typePattern.matchesStatically(classInfo);
if (accept) {
break;
}
// goes on if this include did not match ("OR"ed)
}
return accept;
}
//FIXME we don't use include/exclude of others aop.xml
//this can be nice but very dangerous as well to change that
private boolean acceptAspect(String aspectClassName) {
// avoid ResolvedType if not needed
if (m_aspectExcludeTypePattern.isEmpty() && m_aspectIncludeTypePattern.isEmpty()) {
return true;
}
// still try to avoid ResolvedType if we have simple patterns
// EXCLUDE: if one match then reject
String fastClassName = aspectClassName.replace('/', '.').replace('.', '$');
for (int i = 0; i < m_aspectExcludeStartsWith.size(); i++) {
if (fastClassName.startsWith((String)m_aspectExcludeStartsWith.get(i))) {
return false;
}
}
//INCLUDE: if one match then accept
for (int i = 0; i < m_aspectIncludeStartsWith.size(); i++) {
if (fastClassName.startsWith((String)m_aspectIncludeStartsWith.get(i))) {
return true;
}
}
// needs further analysis
ResolvedType classInfo = weaver.getWorld().resolve(UnresolvedType.forName(aspectClassName), true);
//exclude are "AND"ed
for (Iterator iterator = m_aspectExcludeTypePattern.iterator(); iterator.hasNext();) {
TypePattern typePattern = (TypePattern) iterator.next();
if (typePattern.matchesStatically(classInfo)) {
// exclude match - skip
return false;
}
}
//include are "OR"ed
boolean accept = true;//defaults to true if no include
for (Iterator iterator = m_aspectIncludeTypePattern.iterator(); iterator.hasNext();) {
TypePattern typePattern = (TypePattern) iterator.next();
accept = typePattern.matchesStatically(classInfo);
if (accept) {
break;
}
// goes on if this include did not match ("OR"ed)
}
return accept;
}
protected boolean shouldDump(String className, boolean before) {
// Don't dump before weaving unless asked to
if (before && !m_dumpBefore) {
return false;
}
// avoid ResolvedType if not needed
if (m_dumpTypePattern.isEmpty()) {
return false;
}
//TODO AV - optimize for className.startWith only
ResolvedType classInfo = weaver.getWorld().resolve(UnresolvedType.forName(className), true);
//dump
for (Iterator iterator = m_dumpTypePattern.iterator(); iterator.hasNext();) {
TypePattern typePattern = (TypePattern) iterator.next();
if (typePattern.matchesStatically(classInfo)) {
// dump match
return true;
}
}
return false;
}
/*
* shared classes methods
*/
/**
* @return Returns the key.
*/
public String getNamespace() {
// System.out.println("ClassLoaderWeavingAdaptor.getNamespace() classloader=" + weavingContext.getClassLoaderName() + ", namespace=" + namespace);
if(namespace==null) return "";
else return new String(namespace);
}
/**
* Check to see if any classes are stored in the generated classes cache.
* Then flush the cache if it is not empty
* @param className TODO
* @return true if a class has been generated and is stored in the cache
*/
public boolean generatedClassesExistFor (String className) {
// System.err.println("? ClassLoaderWeavingAdaptor.generatedClassesExist() classname=" + className + ", size=" + generatedClasses);
if (className == null) return !generatedClasses.isEmpty();
else return generatedClasses.containsKey(className);
}
/**
* Flush the generated classes cache
*/
public void flushGeneratedClasses() {
// System.err.println("? ClassLoaderWeavingAdaptor.flushGeneratedClasses() generatedClasses=" + generatedClasses);
generatedClasses = new HashMap();
}
private void defineClass(ClassLoader loader, String name, byte[] bytes) {
if (trace.isTraceEnabled()) trace.enter("defineClass",this,new Object[] {loader,name,bytes});
Object clazz = null;
info("generating class '" + name + "'");
try {
//TODO av protection domain, and optimize
Method defineClass = ClassLoader.class.getDeclaredMethod(
"defineClass", new Class[] { String.class,
bytes.getClass(), int.class, int.class });
defineClass.setAccessible(true);
clazz = defineClass.invoke(loader, new Object[] { name, bytes,
new Integer(0), new Integer(bytes.length) });
} catch (InvocationTargetException e) {
if (e.getTargetException() instanceof LinkageError) {
warn("define generated class failed",e.getTargetException());
//is already defined (happens for X$ajcMightHaveAspect interfaces since aspects are reweaved)
// TODO maw I don't think this is OK and
} else {
warn("define generated class failed",e.getTargetException());
}
} catch (Exception e) {
warn("define generated class failed",e);
}
if (trace.isTraceEnabled()) trace.exit("defineClass",clazz);
}
}
|
152,161 |
Bug 152161 Contribution: Support -Xset in Load-Time Weaving Configuration
|
I needed this to try out a setting in the pipelined compilation (-Xset:runMinimalMemory=true) ... I was able to verify that it parsed and set an option correctly in the debugger. I also have included a test that sets all the currently available options.
|
resolved fixed
|
039be68
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-08-08T13:50:57Z | 2006-07-28T15:20:00Z |
loadtime/src/org/aspectj/weaver/loadtime/Options.java
|
/*******************************************************************************
* Copyright (c) 2005 Contributors.
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Eclipse Public License v1.0
* which accompanies this distribution and is available at
* http://eclipse.org/legal/epl-v10.html
*
* Contributors:
* Alexandre Vasseur initial implementation
*******************************************************************************/
package org.aspectj.weaver.loadtime;
import org.aspectj.bridge.IMessage;
import org.aspectj.bridge.IMessageHandler;
import org.aspectj.bridge.Message;
import org.aspectj.util.LangUtil;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
/**
* A class that hanldes LTW options.
* Note: AV - I choosed to not reuse AjCompilerOptions and alike since those implies too many dependancies on
* jdt and ajdt modules.
*
* @author <a href="mailto:alex AT gnilux DOT com">Alexandre Vasseur</a>
*/
public class Options {
private final static String OPTION_15 = "-1.5";
private final static String OPTION_lazyTjp = "-XlazyTjp";
private final static String OPTION_noWarn = "-nowarn";
private final static String OPTION_noWarnNone = "-warn:none";
private final static String OPTION_proceedOnError = "-proceedOnError";
private final static String OPTION_verbose = "-verbose";
private final static String OPTION_reweavable = "-Xreweavable";//notReweavable is default for LTW
private final static String OPTION_noinline = "-Xnoinline";
private final static String OPTION_addSerialVersionUID = "-XaddSerialVersionUID";
private final static String OPTION_hasMember = "-XhasMember";
private final static String OPTION_pinpoint = "-Xdev:pinpoint";
private final static String OPTION_showWeaveInfo = "-showWeaveInfo";
private final static String OPTIONVALUED_messageHandler = "-XmessageHandlerClass:";
private static final String OPTIONVALUED_Xlintfile = "-Xlintfile:";
private static final String OPTIONVALUED_Xlint = "-Xlint:";
private static final String OPTIONVALUED_joinpoints = "-Xjoinpoints:";
public static WeaverOption parse(String options, ClassLoader laoder, IMessageHandler imh) {
WeaverOption weaverOption = new WeaverOption(imh);
if (LangUtil.isEmpty(options)) {
return weaverOption;
}
// the first option wins
List flags = LangUtil.anySplit(options, " ");
Collections.reverse(flags);
// do a first round on the message handler since it will report the options themselves
for (Iterator iterator = flags.iterator(); iterator.hasNext();) {
String arg = (String) iterator.next();
if (arg.startsWith(OPTIONVALUED_messageHandler)) {
if (arg.length() > OPTIONVALUED_messageHandler.length()) {
String handlerClass = arg.substring(OPTIONVALUED_messageHandler.length()).trim();
try {
Class handler = Class.forName(handlerClass, false, laoder);
weaverOption.messageHandler = ((IMessageHandler) handler.newInstance());
} catch (Throwable t) {
weaverOption.messageHandler.handleMessage(
new Message(
"Cannot instantiate message handler " + handlerClass,
IMessage.ERROR,
t,
null
)
);
}
}
}
}
// configure the other options
for (Iterator iterator = flags.iterator(); iterator.hasNext();) {
String arg = (String) iterator.next();
if (arg.equals(OPTION_15)) {
weaverOption.java5 = true;
} else if (arg.equalsIgnoreCase(OPTION_lazyTjp)) {
weaverOption.lazyTjp = true;
} else if (arg.equalsIgnoreCase(OPTION_noinline)) {
weaverOption.noInline = true;
} else if (arg.equalsIgnoreCase(OPTION_addSerialVersionUID)) {
weaverOption.addSerialVersionUID=true;
} else if (arg.equalsIgnoreCase(OPTION_noWarn) || arg.equalsIgnoreCase(OPTION_noWarnNone)) {
weaverOption.noWarn = true;
} else if (arg.equalsIgnoreCase(OPTION_proceedOnError)) {
weaverOption.proceedOnError = true;
} else if (arg.equalsIgnoreCase(OPTION_reweavable)) {
weaverOption.notReWeavable = false;
} else if (arg.equalsIgnoreCase(OPTION_showWeaveInfo)) {
weaverOption.showWeaveInfo = true;
} else if (arg.equalsIgnoreCase(OPTION_hasMember)) {
weaverOption.hasMember = true;
} else if (arg.startsWith(OPTIONVALUED_joinpoints)) {
if (arg.length()>OPTIONVALUED_joinpoints.length())
weaverOption.optionalJoinpoints = arg.substring(OPTIONVALUED_joinpoints.length()).trim();
} else if (arg.equalsIgnoreCase(OPTION_verbose)) {
weaverOption.verbose = true;
} else if (arg.equalsIgnoreCase(OPTION_pinpoint)) {
weaverOption.pinpoint = true;
} else if (arg.startsWith(OPTIONVALUED_messageHandler)) {
;// handled in first round
} else if (arg.startsWith(OPTIONVALUED_Xlintfile)) {
if (arg.length() > OPTIONVALUED_Xlintfile.length()) {
weaverOption.lintFile = arg.substring(OPTIONVALUED_Xlintfile.length()).trim();
}
} else if (arg.startsWith(OPTIONVALUED_Xlint)) {
if (arg.length() > OPTIONVALUED_Xlint.length()) {
weaverOption.lint = arg.substring(OPTIONVALUED_Xlint.length()).trim();
}
} else {
weaverOption.messageHandler.handleMessage(
new Message(
"Cannot configure weaver with option '" + arg + "': unknown option",
IMessage.WARNING,
null,
null
)
);
}
}
// refine message handler configuration
if (weaverOption.noWarn) {
weaverOption.messageHandler.dontIgnore(IMessage.WARNING);
}
if (weaverOption.verbose) {
weaverOption.messageHandler.dontIgnore(IMessage.INFO);
}
if (weaverOption.showWeaveInfo) {
weaverOption.messageHandler.dontIgnore(IMessage.WEAVEINFO);
}
return weaverOption;
}
public static class WeaverOption {
boolean java5;
boolean lazyTjp;
boolean hasMember;
String optionalJoinpoints;
boolean noWarn;
boolean proceedOnError;
boolean verbose;
boolean notReWeavable = true;//default to notReweavable for LTW (faster)
boolean noInline;
boolean addSerialVersionUID;
boolean showWeaveInfo;
boolean pinpoint;
IMessageHandler messageHandler;
String lint;
String lintFile;
public WeaverOption(IMessageHandler imh) {
// messageHandler = new DefaultMessageHandler();//default
this.messageHandler = imh;
}
}
}
|
152,161 |
Bug 152161 Contribution: Support -Xset in Load-Time Weaving Configuration
|
I needed this to try out a setting in the pipelined compilation (-Xset:runMinimalMemory=true) ... I was able to verify that it parsed and set an option correctly in the debugger. I also have included a test that sets all the currently available options.
|
resolved fixed
|
039be68
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-08-08T13:50:57Z | 2006-07-28T15:20:00Z |
tests/src/org/aspectj/systemtest/ajc150/ltw/LTWTests.java
|
/*******************************************************************************
* Copyright (c) 2005 Contributors.
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Eclipse Public License v1.0
* which accompanies this distribution and is available at
* http://eclipse.org/legal/epl-v10.html
*
* Contributors:
* Matthew Webster initial implementation
*******************************************************************************/
package org.aspectj.systemtest.ajc150.ltw;
import java.io.File;
import java.util.Enumeration;
import java.util.Properties;
import junit.framework.Test;
import org.aspectj.testing.XMLBasedAjcTestCase;
import org.aspectj.weaver.tools.WeavingAdaptor;
public class LTWTests extends org.aspectj.testing.XMLBasedAjcTestCase {
public static Test suite() {
return XMLBasedAjcTestCase.loadSuite(LTWTests.class);
}
protected File getSpecFile() {
return new File("../tests/src/org/aspectj/systemtest/ajc150/ltw/ltw.xml");
}
public void test001(){
runTest("Ensure 1st aspect is rewoven when weaving 2nd aspect");
}
public void testOutxmlFile (){
runTest("Ensure valid aop.xml file is generated");
}
public void testOutxmlJar (){
runTest("Ensure valid aop.xml is generated for -outjar");
}
public void testNoAopxml(){
setSystemProperty(WeavingAdaptor.WEAVING_ADAPTOR_VERBOSE,"true");
runTest("Ensure no weaving without visible aop.xml");
}
public void testDefineConcreteAspect(){
runTest("Define concrete sub-aspect using aop.xml");
}
public void testDeclareAbstractAspect(){
// setSystemProperty(WeavingAdaptor.WEAVING_ADAPTOR_VERBOSE,"true");
// setSystemProperty(WeavingAdaptor.SHOW_WEAVE_INFO_PROPERTY,"true");
runTest("Use abstract aspect for ITD using aop.xml");
}
public void testAspectsInclude () {
runTest("Ensure a subset of inherited aspects is used for weaving");
}
public void testAspectsIncludeWithLintWarning () {
runTest("Ensure weaver lint warning issued when an aspect is not used for weaving");
}
public void testXlintfileEmpty () {
runTest("Empty Xlint.properties file");
}
public void testXlintfileMissing () {
runTest("Warning with missing Xlint.properties file");
}
public void testXlintWarningAdviceDidNotMatchSuppressed () {
runTest("Warning when advice doesn't match suppressed for LTW");
}
public void testXlintfile () {
runTest("Override suppressing of warning when advice doesn't match using -Xlintfile");
}
public void testXlintDefault () {
runTest("Warning when advice doesn't match using -Xlint:default");
}
public void testXlintWarning () {
runTest("Override suppressing of warning when advice doesn't match using -Xlint:warning");
}
public void testNonstandardJarFiles() {
runTest("Nonstandard jar file extensions");
}
public void testOddzipOnClasspath() {
runTest("Odd zip on classpath");
}
public void testJ14LTWWithXML() {
runTest("JDK14 LTW with XML");
}
public void testJ14LTWWithASPECTPATH() {
runTest("JDK14 LTW with ASPECTPATH");
}
// separate bugzilla patch has this one... commented out
// public void testSeparateCompilationDeclareParentsCall() {
// runTest("Separate compilation with ltw: declare parents and call");
// }
//
// public void testChildAspectDoesntWeaveParentDeclareParentsCall() {
// setSystemProperty(WeavingAdaptor.WEAVING_ADAPTOR_VERBOSE,"true");
// setSystemProperty(WeavingAdaptor.SHOW_WEAVE_INFO_PROPERTY,"true");
// runTest("Child loader aspect won't weave parent loader: declare parents and call");
// }
/*
* Allow system properties to be set and restored
* TODO maw move to XMLBasedAjcTestCase or RunSpec
*/
private final static String NULL = "null";
private Properties savedProperties;
protected void setSystemProperty (String key, String value) {
Properties systemProperties = System.getProperties();
copyProperty(key,systemProperties,savedProperties);
systemProperties.setProperty(key,value);
}
private static void copyProperty (String key, Properties from, Properties to) {
String value = from.getProperty(key,NULL);
to.setProperty(key,value);
}
protected void setUp() throws Exception {
super.setUp();
savedProperties = new Properties();
}
protected void tearDown() throws Exception {
super.tearDown();
/* Restore system properties */
Properties systemProperties = System.getProperties();
for (Enumeration enu = savedProperties.keys(); enu.hasMoreElements(); ) {
String key = (String)enu.nextElement();
String value = savedProperties.getProperty(key);
if (value == NULL) systemProperties.remove(key);
else systemProperties.setProperty(key,value);
}
}
}
|
148,219 |
Bug 148219 Wrong warning is reported
|
I used ajdt_1.3.1_for_eclipse_3.1.zip on Eclipse 3.1.2. Below is my aspectj code. public aspect MyMessages { pointcut getResourceString(String key): args(key, ..) && call (* CommonPlugin.getResourceString(String, ..)); String around(String key):getResourceString(key) { return key; } } The warning message is The parameter key is never read. See my screenshot.
|
resolved fixed
|
07c2189
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-08-08T15:37:36Z | 2006-06-22T15:26:40Z |
org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/compiler/problem/AjProblemReporter.java
|
/* *******************************************************************
* Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC).
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Eclipse Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* PARC initial implementation
* ******************************************************************/
package org.aspectj.ajdt.internal.compiler.problem;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.lang.reflect.Modifier;
import java.util.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.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;
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();}
}
}
|
148,219 |
Bug 148219 Wrong warning is reported
|
I used ajdt_1.3.1_for_eclipse_3.1.zip on Eclipse 3.1.2. Below is my aspectj code. public aspect MyMessages { pointcut getResourceString(String key): args(key, ..) && call (* CommonPlugin.getResourceString(String, ..)); String around(String key):getResourceString(key) { return key; } } The warning message is The parameter key is never read. See my screenshot.
|
resolved fixed
|
07c2189
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-08-08T15:37:36Z | 2006-06-22T15:26:40Z |
tests/bugs153/PR148219/MyMessages.java
| |
148,219 |
Bug 148219 Wrong warning is reported
|
I used ajdt_1.3.1_for_eclipse_3.1.zip on Eclipse 3.1.2. Below is my aspectj code. public aspect MyMessages { pointcut getResourceString(String key): args(key, ..) && call (* CommonPlugin.getResourceString(String, ..)); String around(String key):getResourceString(key) { return key; } } The warning message is The parameter key is never read. See my screenshot.
|
resolved fixed
|
07c2189
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-08-08T15:37:36Z | 2006-06-22T15:26:40Z |
tests/src/org/aspectj/systemtest/ajc153/Ajc153Tests.java
|
/*******************************************************************************
* Copyright (c) 2006 IBM
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Andy Clement - initial API and implementation
*******************************************************************************/
package org.aspectj.systemtest.ajc153;
import java.io.File;
import junit.framework.Test;
import org.aspectj.testing.Utils;
import org.aspectj.testing.XMLBasedAjcTestCase;
import org.aspectj.weaver.bcel.Utility;
public class Ajc153Tests extends org.aspectj.testing.XMLBasedAjcTestCase {
//public void testGenericsProblem_pr151978() { runTest("generics problem");}
//public void testMissingLineNumbersInStacktraceBefore_pr145442() { runTest("missing line numbers in stacktrace before");}
//public void testMissingLineNumbersInStacktraceAfter_pr145442() { runTest("missing line numbers in stacktrace after");}
//public void testMissingLineNumbersInStacktraceAround_pr145442() { runTest("missing line numbers in stacktrace around");}
// public void testArgnamesAndJavac_pr148381() { runTest("argNames and javac");}
// public void testCFlowXMLAspectLTW_pr149096() { runTest("cflow xml concrete aspect"); }
// public void testAmbiguousBinding_pr121805() { runTest("ambiguous binding");}
public void 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 testVisibilityProblem_pr149071() { runTest("visibility problem");}
// public void testAdviceNotWovenAspectPath_pr147841() { runTest("advice not woven on aspectpath");}
public void testGenericSignatures_pr148409() { runTest("generic signature problem"); }
// public void testBrokenIfArgsCflowAtAj_pr145018() { runTest("ataj crashing with cflow, if and args");}
public void testCantFindType_pr149322_01() {runTest("can't find type on interface call 1");}
public void testCantFindType_pr149322_02() {runTest("can't find type on interface call 2");}
public void testCantFindType_pr149322_03() {runTest("can't find type on interface call 3");}
public void 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 static Test suite() {
return XMLBasedAjcTestCase.loadSuite(Ajc153Tests.class);
}
protected File getSpecFile() {
return new File("../tests/src/org/aspectj/systemtest/ajc153/ajc153.xml");
}
}
|
153,535 |
Bug 153535 Bug in reflection delegate signature for array of object type
|
The following problem is interesting because the advice weaves correctly with Java 1.5 LTW and also using Java 1.4 with build-time weaving. However, the following call pointcut isn't matching the expected call site in Java 1.4 load-time weaving (*). Pointcut: private pointcut inExecQuery() : (within(uk.ltd.getahead.dwr.impl.ExecuteQuery) || within(uk.ltd.getahead.dwr.ExecuteQuery)); public pointcut dwrQuery(Method method, Object receiver, Object[] params) : inExecQuery() && withincode(* execute(..)) && call(* Method.invoke(..)) && args(receiver, params) && target(method); protected pointcut monitorEnd() : dwrQuery(*, *, *); Matching call site: Object reply = method.invoke(object, params); I've tracked it down to failing to find the method in ResolvedType.matches. On line 405: "m1.getSignature()"= "(Ljava/lang/Object;[Ljava.lang.Object;)Ljava/lang/Object;" "m2.getSignature()"= "(Ljava/lang/Object;[Ljava/lang/Object;)Ljava/lang/Object;" Note the difference between . and / ^ ^ It looks to me like the signature for array types in the reflection delegate is erroneously using . instead of /. I have attached a patch to the ReflectionBasedReferenceTypeDelegateTest that isolates this unexpected signature return. Hopefully you agree that this is not correct. If not, some more information follows. Here's the stack trace where the match fails: ResolvedType.matches(Member, Member) line: 405 ReferenceType(ResolvedType).lookupMember(Member, Iterator) line: 347 ReferenceType(ResolvedType).lookupMethod(Member) line: 326 LTWWorld(World).resolve(Member) line: 504 MemberImpl.resolve(World) line: 93 JoinPointSignatureIterator.addSignaturesUpToFirstDefiningMember() line: 109 JoinPointSignatureIterator.<init>(Member, World) line: 51 MemberImpl.getJoinPointSignatures(World) line: 943 SignaturePattern.matches(Member, World, boolean) line: 286 KindedPointcut.matchInternal(Shadow) line: 106 KindedPointcut(Pointcut).match(Shadow) line: 146 AndPointcut.matchInternal(Shadow) line: 53 AndPointcut(Pointcut).match(Shadow) line: 146 AndPointcut.matchInternal(Shadow) line: 51 AndPointcut(Pointcut).match(Shadow) line: 146 AndPointcut.matchInternal(Shadow) line: 51 AndPointcut(Pointcut).match(Shadow) line: 146 AndPointcut.matchInternal(Shadow) line: 51 AndPointcut(Pointcut).match(Shadow) line: 146 OrPointcut.matchInternal(Shadow) line: 50 OrPointcut(Pointcut).match(Shadow) line: 146 BcelAdvice(ShadowMunger).match(Shadow, World) line: 71 BcelAdvice(Advice).match(Shadow, World) line: 112 BcelAdvice.match(Shadow, World) line: 107 BcelClassWeaver.match(BcelShadow, List) line: 2806 BcelClassWeaver.matchInvokeInstruction(LazyMethodGen, InstructionHandle, InvokeInstruction, BcelShadow, List) line: 2768 BcelClassWeaver.match(LazyMethodGen, InstructionHandle, BcelShadow, List) line: 2506 BcelClassWeaver.match(LazyMethodGen) line: 2332 BcelClassWeaver.weave() line: 494 BcelClassWeaver.weave(BcelWorld, LazyClassGen, List, List, List) line: 119 BcelWeaver.weave(UnwovenClassFile, BcelObjectType, boolean) line: 1613 BcelWeaver.weaveWithoutDump(UnwovenClassFile, BcelObjectType) line: 1564 BcelWeaver.weaveAndNotify(UnwovenClassFile, BcelObjectType, IWeaveRequestor) line: 1341 BcelWeaver.weave(IClassFileProvider) line: 1163 ClassLoaderWeavingAdaptor(WeavingAdaptor).getWovenBytes(String, byte[]) line: 319 ClassLoaderWeavingAdaptor(WeavingAdaptor).weaveClass(String, byte[]) line: 225 Aj.preProcess(String, byte[], ClassLoader) line: 77 ClassPreProcessorAdapter.preProcess(String, byte[], ClassLoader) line: 67 ClassPreProcessorHelper.defineClass0Pre(ClassLoader, String, byte[], int, int, ProtectionDomain) line: 107 WebappClassLoader(ClassLoader).defineClass(String, byte[], int, int, ProtectionDomain) line: 539 WebappClassLoader(SecureClassLoader).defineClass(String, byte[], int, int, CodeSource) line: 123 WebappClassLoader.findClassInternal(String) line: 1786 WebappClassLoader.findClass(String) line: 1048 WebappClassLoader.loadClass(String, boolean) line: 1506 WebappClassLoader.loadClass(String) line: 1385 WebappClassLoader(ClassLoader).loadClassInternal(String) line: 302 Class.forName0(String, boolean, ClassLoader) line: not available [native method] Class.forName(String) line: 141 InitializeLog.setWarnLogging(String) line: 121 InitializeLog.initializeLogging() line: 96 ContextLoaderServlet.init() line: 13 ContextLoaderServlet(GenericServlet).init(ServletConfig) line: 212 StandardWrapper.loadServlet() line: 879 StandardWrapper.load() line: 767 StandardContext.loadOnStartup(Container[]) line: 3483 StandardContext.start() line: 3709 StandardHost(ContainerBase).addChildInternal(Container) line: 776 StandardHost(ContainerBase).addChild(Container) line: 759 StandardHost.addChild(Container) line: 537 StandardHostDeployer.install(String, URL) line: 260 StandardHost.install(String, URL) line: 730 HostConfig.deployWARs(File, String[]) line: 558 HostConfig.deployApps() line: 373 HostConfig.start() line: 784 HostConfig.lifecycleEvent(LifecycleEvent) line: 330 LifecycleSupport.fireLifecycleEvent(String, Object) line: 119 StandardHost(ContainerBase).start() line: 1155 StandardHost.start() line: 696 StandardEngine(ContainerBase).start() line: 1147 StandardEngine.start() line: 310 StandardService.start() line: 449 StandardServer.start() line: 2212 Catalina.start() line: 458 Catalina.execute() line: 345 Catalina.process(String[]) line: 129 NativeMethodAccessorImpl.invoke0(Method, Object, Object[]) line: not available [native method] NativeMethodAccessorImpl.invoke(Object, Object[]) line: 39 DelegatingMethodAccessorImpl.invoke(Object, Object[]) line: 25 Method.invoke(Object, Object[]) line: 324 Bootstrap.main(String[]) line: 150 I'm using a modified version of Alex Vasseur's LTW plugin for a Java 1.4 VM although I haven't tested on the JRockIt plugin for a 1.4 VM: my guess is that this would fail there too.
|
resolved fixed
|
82e3e13
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-08-15T11:51:21Z | 2006-08-11T07:06:40Z |
weaver/src/org/aspectj/weaver/reflect/ReflectionWorld.java
|
/* *******************************************************************
* Copyright (c) 2005 Contributors.
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Eclipse Public License v1.0
* which accompanies this distribution and is available at
* http://eclipse.org/legal/epl-v10.html
*
* Contributors:
* Adrian Colyer Initial implementation
* ******************************************************************/
package org.aspectj.weaver.reflect;
import org.aspectj.bridge.AbortException;
import org.aspectj.bridge.IMessage;
import org.aspectj.bridge.IMessageHandler;
import org.aspectj.util.LangUtil;
import org.aspectj.weaver.Advice;
import org.aspectj.weaver.BCException;
import org.aspectj.weaver.ConcreteTypeMunger;
import org.aspectj.weaver.Member;
import org.aspectj.weaver.ReferenceType;
import org.aspectj.weaver.ReferenceTypeDelegate;
import org.aspectj.weaver.ResolvedMember;
import org.aspectj.weaver.ResolvedType;
import org.aspectj.weaver.ResolvedTypeMunger;
import org.aspectj.weaver.UnresolvedType;
import org.aspectj.weaver.World;
import org.aspectj.weaver.AjAttribute.AdviceAttribute;
import org.aspectj.weaver.patterns.Pointcut;
import org.aspectj.weaver.patterns.PerClause.Kind;
/**
* A ReflectionWorld is used solely for purposes of type resolution based on
* the runtime classpath (java.lang.reflect). It does not support weaving operations
* (creation of mungers etc..).
*
*/
public class ReflectionWorld extends World implements IReflectionWorld {
private ClassLoader classLoader;
private AnnotationFinder annotationFinder;
private ReflectionWorld() {
super();
this.setMessageHandler(new ExceptionBasedMessageHandler());
setBehaveInJava5Way(LangUtil.is15VMOrGreater());
this.classLoader = ReflectionWorld.class.getClassLoader();
this.annotationFinder = makeAnnotationFinderIfAny(classLoader, this);
}
public ReflectionWorld(ClassLoader aClassLoader) {
super();
this.setMessageHandler(new ExceptionBasedMessageHandler());
setBehaveInJava5Way(LangUtil.is15VMOrGreater());
this.classLoader = aClassLoader;
this.annotationFinder = makeAnnotationFinderIfAny(classLoader, this);
}
public static AnnotationFinder makeAnnotationFinderIfAny(ClassLoader loader, World world) {
AnnotationFinder annotationFinder = null;
try {
if (LangUtil.is15VMOrGreater()) {
Class java15AnnotationFinder = Class.forName("org.aspectj.weaver.reflect.Java15AnnotationFinder");
annotationFinder = (AnnotationFinder) java15AnnotationFinder.newInstance();
annotationFinder.setClassLoader(loader);
annotationFinder.setWorld(world);
}
} catch(ClassNotFoundException ex) {
// must be on 1.4 or earlier
} catch(IllegalAccessException ex) {
// not so good
throw new BCException("AspectJ internal error",ex);
} catch(InstantiationException ex) {
throw new BCException("AspectJ internal error",ex);
}
return annotationFinder;
}
public ClassLoader getClassLoader() {
return this.classLoader;
}
public AnnotationFinder getAnnotationFinder() {
return this.annotationFinder;
}
/* (non-Javadoc)
* @see org.aspectj.weaver.reflect.IReflectionWorld#resolve(java.lang.Class)
*/
public ResolvedType resolve(Class aClass) {
return resolve(this, aClass);
}
public static ResolvedType resolve(World world, Class aClass) {
// classes that represent arrays return a class name that is the signature of the array type, ho-hum...
String className = aClass.getName();
if (aClass.isArray()) {
return world.resolve(UnresolvedType.forSignature(className));
}
else{
return world.resolve(className);
}
}
/* (non-Javadoc)
* @see org.aspectj.weaver.World#resolveDelegate(org.aspectj.weaver.ReferenceType)
*/
protected ReferenceTypeDelegate resolveDelegate(ReferenceType ty) {
return ReflectionBasedReferenceTypeDelegateFactory.createDelegate(ty, this, this.classLoader);
}
/* (non-Javadoc)
* @see org.aspectj.weaver.World#createAdviceMunger(org.aspectj.weaver.AjAttribute.AdviceAttribute, org.aspectj.weaver.patterns.Pointcut, org.aspectj.weaver.Member)
*/
public Advice createAdviceMunger(AdviceAttribute attribute,
Pointcut pointcut, Member signature) {
throw new UnsupportedOperationException("Cannot create advice munger in ReflectionWorld");
}
/* (non-Javadoc)
* @see org.aspectj.weaver.World#makeCflowStackFieldAdder(org.aspectj.weaver.ResolvedMember)
*/
public ConcreteTypeMunger makeCflowStackFieldAdder(ResolvedMember cflowField) {
throw new UnsupportedOperationException("Cannot create cflow stack in ReflectionWorld");
}
/* (non-Javadoc)
* @see org.aspectj.weaver.World#makeCflowCounterFieldAdder(org.aspectj.weaver.ResolvedMember)
*/
public ConcreteTypeMunger makeCflowCounterFieldAdder(
ResolvedMember cflowField) {
throw new UnsupportedOperationException("Cannot create cflow counter in ReflectionWorld");
}
/* (non-Javadoc)
* @see org.aspectj.weaver.World#makePerClauseAspect(org.aspectj.weaver.ResolvedType, org.aspectj.weaver.patterns.PerClause.Kind)
*/
public ConcreteTypeMunger makePerClauseAspect(ResolvedType aspect, Kind kind) {
throw new UnsupportedOperationException("Cannot create per clause in ReflectionWorld");
}
/* (non-Javadoc)
* @see org.aspectj.weaver.World#concreteTypeMunger(org.aspectj.weaver.ResolvedTypeMunger, org.aspectj.weaver.ResolvedType)
*/
public ConcreteTypeMunger concreteTypeMunger(ResolvedTypeMunger munger,
ResolvedType aspectType) {
throw new UnsupportedOperationException("Cannot create type munger in ReflectionWorld");
}
public static class ReflectionWorldException extends RuntimeException {
private static final long serialVersionUID = -3432261918302793005L;
public ReflectionWorldException(String message) {
super(message);
}
}
private static class ExceptionBasedMessageHandler implements IMessageHandler {
public boolean handleMessage(IMessage message) throws AbortException {
throw new ReflectionWorldException(message.toString());
}
public boolean isIgnoring(org.aspectj.bridge.IMessage.Kind kind) {
if (kind == IMessage.INFO) {
return true;
} else {
return false;
}
}
public void dontIgnore(org.aspectj.bridge.IMessage.Kind kind) {
// empty
}
}
}
|
153,535 |
Bug 153535 Bug in reflection delegate signature for array of object type
|
The following problem is interesting because the advice weaves correctly with Java 1.5 LTW and also using Java 1.4 with build-time weaving. However, the following call pointcut isn't matching the expected call site in Java 1.4 load-time weaving (*). Pointcut: private pointcut inExecQuery() : (within(uk.ltd.getahead.dwr.impl.ExecuteQuery) || within(uk.ltd.getahead.dwr.ExecuteQuery)); public pointcut dwrQuery(Method method, Object receiver, Object[] params) : inExecQuery() && withincode(* execute(..)) && call(* Method.invoke(..)) && args(receiver, params) && target(method); protected pointcut monitorEnd() : dwrQuery(*, *, *); Matching call site: Object reply = method.invoke(object, params); I've tracked it down to failing to find the method in ResolvedType.matches. On line 405: "m1.getSignature()"= "(Ljava/lang/Object;[Ljava.lang.Object;)Ljava/lang/Object;" "m2.getSignature()"= "(Ljava/lang/Object;[Ljava/lang/Object;)Ljava/lang/Object;" Note the difference between . and / ^ ^ It looks to me like the signature for array types in the reflection delegate is erroneously using . instead of /. I have attached a patch to the ReflectionBasedReferenceTypeDelegateTest that isolates this unexpected signature return. Hopefully you agree that this is not correct. If not, some more information follows. Here's the stack trace where the match fails: ResolvedType.matches(Member, Member) line: 405 ReferenceType(ResolvedType).lookupMember(Member, Iterator) line: 347 ReferenceType(ResolvedType).lookupMethod(Member) line: 326 LTWWorld(World).resolve(Member) line: 504 MemberImpl.resolve(World) line: 93 JoinPointSignatureIterator.addSignaturesUpToFirstDefiningMember() line: 109 JoinPointSignatureIterator.<init>(Member, World) line: 51 MemberImpl.getJoinPointSignatures(World) line: 943 SignaturePattern.matches(Member, World, boolean) line: 286 KindedPointcut.matchInternal(Shadow) line: 106 KindedPointcut(Pointcut).match(Shadow) line: 146 AndPointcut.matchInternal(Shadow) line: 53 AndPointcut(Pointcut).match(Shadow) line: 146 AndPointcut.matchInternal(Shadow) line: 51 AndPointcut(Pointcut).match(Shadow) line: 146 AndPointcut.matchInternal(Shadow) line: 51 AndPointcut(Pointcut).match(Shadow) line: 146 AndPointcut.matchInternal(Shadow) line: 51 AndPointcut(Pointcut).match(Shadow) line: 146 OrPointcut.matchInternal(Shadow) line: 50 OrPointcut(Pointcut).match(Shadow) line: 146 BcelAdvice(ShadowMunger).match(Shadow, World) line: 71 BcelAdvice(Advice).match(Shadow, World) line: 112 BcelAdvice.match(Shadow, World) line: 107 BcelClassWeaver.match(BcelShadow, List) line: 2806 BcelClassWeaver.matchInvokeInstruction(LazyMethodGen, InstructionHandle, InvokeInstruction, BcelShadow, List) line: 2768 BcelClassWeaver.match(LazyMethodGen, InstructionHandle, BcelShadow, List) line: 2506 BcelClassWeaver.match(LazyMethodGen) line: 2332 BcelClassWeaver.weave() line: 494 BcelClassWeaver.weave(BcelWorld, LazyClassGen, List, List, List) line: 119 BcelWeaver.weave(UnwovenClassFile, BcelObjectType, boolean) line: 1613 BcelWeaver.weaveWithoutDump(UnwovenClassFile, BcelObjectType) line: 1564 BcelWeaver.weaveAndNotify(UnwovenClassFile, BcelObjectType, IWeaveRequestor) line: 1341 BcelWeaver.weave(IClassFileProvider) line: 1163 ClassLoaderWeavingAdaptor(WeavingAdaptor).getWovenBytes(String, byte[]) line: 319 ClassLoaderWeavingAdaptor(WeavingAdaptor).weaveClass(String, byte[]) line: 225 Aj.preProcess(String, byte[], ClassLoader) line: 77 ClassPreProcessorAdapter.preProcess(String, byte[], ClassLoader) line: 67 ClassPreProcessorHelper.defineClass0Pre(ClassLoader, String, byte[], int, int, ProtectionDomain) line: 107 WebappClassLoader(ClassLoader).defineClass(String, byte[], int, int, ProtectionDomain) line: 539 WebappClassLoader(SecureClassLoader).defineClass(String, byte[], int, int, CodeSource) line: 123 WebappClassLoader.findClassInternal(String) line: 1786 WebappClassLoader.findClass(String) line: 1048 WebappClassLoader.loadClass(String, boolean) line: 1506 WebappClassLoader.loadClass(String) line: 1385 WebappClassLoader(ClassLoader).loadClassInternal(String) line: 302 Class.forName0(String, boolean, ClassLoader) line: not available [native method] Class.forName(String) line: 141 InitializeLog.setWarnLogging(String) line: 121 InitializeLog.initializeLogging() line: 96 ContextLoaderServlet.init() line: 13 ContextLoaderServlet(GenericServlet).init(ServletConfig) line: 212 StandardWrapper.loadServlet() line: 879 StandardWrapper.load() line: 767 StandardContext.loadOnStartup(Container[]) line: 3483 StandardContext.start() line: 3709 StandardHost(ContainerBase).addChildInternal(Container) line: 776 StandardHost(ContainerBase).addChild(Container) line: 759 StandardHost.addChild(Container) line: 537 StandardHostDeployer.install(String, URL) line: 260 StandardHost.install(String, URL) line: 730 HostConfig.deployWARs(File, String[]) line: 558 HostConfig.deployApps() line: 373 HostConfig.start() line: 784 HostConfig.lifecycleEvent(LifecycleEvent) line: 330 LifecycleSupport.fireLifecycleEvent(String, Object) line: 119 StandardHost(ContainerBase).start() line: 1155 StandardHost.start() line: 696 StandardEngine(ContainerBase).start() line: 1147 StandardEngine.start() line: 310 StandardService.start() line: 449 StandardServer.start() line: 2212 Catalina.start() line: 458 Catalina.execute() line: 345 Catalina.process(String[]) line: 129 NativeMethodAccessorImpl.invoke0(Method, Object, Object[]) line: not available [native method] NativeMethodAccessorImpl.invoke(Object, Object[]) line: 39 DelegatingMethodAccessorImpl.invoke(Object, Object[]) line: 25 Method.invoke(Object, Object[]) line: 324 Bootstrap.main(String[]) line: 150 I'm using a modified version of Alex Vasseur's LTW plugin for a Java 1.4 VM although I haven't tested on the JRockIt plugin for a 1.4 VM: my guess is that this would fail there too.
|
resolved fixed
|
82e3e13
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-08-15T11:51:21Z | 2006-08-11T07:06:40Z |
weaver/testsrc/org/aspectj/weaver/reflect/ReflectionBasedReferenceTypeDelegateTest.java
|
/* *******************************************************************
* Copyright (c) 2005 Contributors.
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Eclipse Public License v1.0
* which accompanies this distribution and is available at
* http://eclipse.org/legal/epl-v10.html
*
* Contributors:
* Adrian Colyer Initial implementation
* ******************************************************************/
package org.aspectj.weaver.reflect;
import java.util.HashSet;
import java.util.Set;
import junit.framework.TestCase;
import org.aspectj.bridge.IMessageHandler;
import org.aspectj.weaver.ReferenceType;
import org.aspectj.weaver.ResolvedMember;
import org.aspectj.weaver.ResolvedType;
import org.aspectj.weaver.UnresolvedType;
import org.aspectj.weaver.bcel.BcelWorld;
public class ReflectionBasedReferenceTypeDelegateTest extends TestCase {
protected ReflectionWorld world;
private ResolvedType objectType;
private ResolvedType classType;
public void testIsAspect() {
assertFalse(objectType.isAspect());
}
public void testIsAnnotationStyleAspect() {
assertFalse(objectType.isAnnotationStyleAspect());
}
public void testIsInterface() {
assertFalse(objectType.isInterface());
assertTrue(world.resolve("java.io.Serializable").isInterface());
}
public void testIsEnum() {
assertFalse(objectType.isEnum());
}
public void testIsAnnotation() {
assertFalse(objectType.isAnnotation());
}
public void testIsAnnotationWithRuntimeRetention() {
assertFalse(objectType.isAnnotationWithRuntimeRetention());
}
public void testIsClass() {
assertTrue(objectType.isClass());
assertFalse(world.resolve("java.io.Serializable").isClass());
}
public void testIsGeneric() {
assertFalse(objectType.isGenericType());
}
public void testIsExposedToWeaver() {
assertFalse(objectType.isExposedToWeaver());
}
public void testHasAnnotation() {
assertFalse(objectType.hasAnnotation(UnresolvedType.forName("Foo")));
}
public void testGetAnnotations() {
assertEquals("no entries",0,objectType.getAnnotations().length);
}
public void testGetAnnotationTypes() {
assertEquals("no entries",0,objectType.getAnnotationTypes().length);
}
public void testGetTypeVariables() {
assertEquals("no entries",0,objectType.getTypeVariables().length);
}
public void testGetPerClause() {
assertNull(objectType.getPerClause());
}
public void testGetModifiers() {
assertEquals(Object.class.getModifiers(),objectType.getModifiers());
}
public void testGetSuperclass() {
assertTrue("Superclass of object should be null, but it is: "+objectType.getSuperclass(),objectType.getSuperclass()==null);
assertEquals(objectType,world.resolve("java.lang.Class").getSuperclass());
ResolvedType d = world.resolve("reflect.tests.D");
assertEquals(world.resolve("reflect.tests.C"),d.getSuperclass());
}
protected int findMethod(String name, ResolvedMember[] methods) {
for (int i=0; i<methods.length; i++) {
if (name.equals(methods[i].getName())) {
return i;
}
}
return -1;
}
protected int findMethod(String name, int numArgs, ResolvedMember[] methods) {
for (int i=0; i<methods.length; i++) {
if (name.equals(methods[i].getName()) && (methods[i].getParameterTypes().length == numArgs)) {
return i;
}
}
return -1;
}
public void testGetDeclaredMethods() {
ResolvedMember[] methods = objectType.getDeclaredMethods();
assertEquals(Object.class.getDeclaredMethods().length + Object.class.getDeclaredConstructors().length, methods.length);
ResolvedType c = world.resolve("reflect.tests.C");
methods = c.getDeclaredMethods();
assertEquals(3,methods.length);
int idx = findMethod("foo", methods);
assertTrue(idx > -1);
assertEquals(world.resolve("java.lang.String"),methods[idx].getReturnType());
assertEquals(1, methods[idx].getParameterTypes().length);
assertEquals(objectType,methods[idx].getParameterTypes()[0]);
assertEquals(1,methods[idx].getExceptions().length);
assertEquals(world.resolve("java.lang.Exception"),methods[idx].getExceptions()[0]);
int baridx = findMethod("bar", methods);
int initidx = findMethod("<init>", methods);
assertTrue(baridx > -1);
assertTrue(initidx > -1);
assertTrue(baridx != initidx && baridx != idx && idx <= 2 && initidx <= 2 && baridx <= 2);
ResolvedType d = world.resolve("reflect.tests.D");
methods = d.getDeclaredMethods();
assertEquals(2,methods.length);
classType = world.resolve("java.lang.Class");
methods = classType.getDeclaredMethods();
assertEquals(Class.class.getDeclaredMethods().length + Class.class.getDeclaredConstructors().length, methods.length);
}
public void testGetDeclaredFields() {
ResolvedMember[] fields = objectType.getDeclaredFields();
assertEquals(0,fields.length);
ResolvedType c = world.resolve("reflect.tests.C");
fields = c.getDeclaredFields();
assertEquals(2,fields.length);
assertEquals("f",fields[0].getName());
assertEquals("s",fields[1].getName());
assertEquals(ResolvedType.INT,fields[0].getReturnType());
assertEquals(world.resolve("java.lang.String"),fields[1].getReturnType());
}
public void testGetDeclaredInterfaces() {
ResolvedType[] interfaces = objectType.getDeclaredInterfaces();
assertEquals(0,interfaces.length);
ResolvedType d = world.resolve("reflect.tests.D");
interfaces = d.getDeclaredInterfaces();
assertEquals(1,interfaces.length);
assertEquals(world.resolve("java.io.Serializable"),interfaces[0]);
}
public void testGetDeclaredPointcuts() {
ResolvedMember[] pointcuts = objectType.getDeclaredPointcuts();
assertEquals(0,pointcuts.length);
}
public void testSerializableSuperclass() {
ResolvedType serializableType = world.resolve("java.io.Serializable");
ResolvedType superType = serializableType.getSuperclass();
assertTrue("Superclass of serializable should be Object but was "+superType,superType.equals(UnresolvedType.OBJECT));
BcelWorld bcelworld = new BcelWorld();
bcelworld.setBehaveInJava5Way(true);
ResolvedType bcelSupertype = bcelworld.resolve(UnresolvedType.SERIALIZABLE).getSuperclass();
assertTrue("Should be null but is "+bcelSupertype,bcelSupertype.equals(UnresolvedType.OBJECT));
}
public void testSubinterfaceSuperclass() {
ResolvedType ifaceType = world.resolve("java.security.Key");
ResolvedType superType = ifaceType.getSuperclass();
assertTrue("Superclass should be Object but was "+superType,superType.equals(UnresolvedType.OBJECT));
BcelWorld bcelworld = new BcelWorld();
bcelworld.setBehaveInJava5Way(true);
ResolvedType bcelSupertype = bcelworld.resolve("java.security.Key").getSuperclass();
assertTrue("Should be null but is "+bcelSupertype,bcelSupertype.equals(UnresolvedType.OBJECT));
}
public void testVoidSuperclass() {
ResolvedType voidType = world.resolve(Void.TYPE);
ResolvedType superType = voidType.getSuperclass();
assertNull(superType);
BcelWorld bcelworld = new BcelWorld();
bcelworld.setBehaveInJava5Way(true);
ResolvedType bcelSupertype = bcelworld.resolve("void").getSuperclass();
assertTrue("Should be null but is "+bcelSupertype,bcelSupertype==null);
}
public void testIntSuperclass() {
ResolvedType voidType = world.resolve(Integer.TYPE);
ResolvedType superType = voidType.getSuperclass();
assertNull(superType);
BcelWorld bcelworld = new BcelWorld();
bcelworld.setBehaveInJava5Way(true);
ResolvedType bcelSupertype = bcelworld.resolve("int").getSuperclass();
assertTrue("Should be null but is "+bcelSupertype,bcelSupertype==null);
}
public void testGenericInterfaceSuperclass_BcelWorldResolution() {
BcelWorld bcelworld = new BcelWorld();
bcelworld.setBehaveInJava5Way(true);
UnresolvedType javaUtilMap = UnresolvedType.forName("java.util.Map");
ReferenceType rawType = (ReferenceType) bcelworld.resolve(javaUtilMap);
assertTrue("Should be the raw type ?!? "+rawType.getTypekind(),rawType.isRawType());
ReferenceType genericType = (ReferenceType)rawType.getGenericType();
assertTrue("Should be the generic type ?!? "+genericType.getTypekind(),genericType.isGenericType());
ResolvedType rt = rawType.getSuperclass();
assertTrue("Superclass for Map raw type should be Object but was "+rt,rt.equals(UnresolvedType.OBJECT));
ResolvedType rt2 = genericType.getSuperclass();
assertTrue("Superclass for Map generic type should be Object but was "+rt2,rt2.equals(UnresolvedType.OBJECT));
}
// FIXME asc maybe. The reflection list of methods returned doesn't include <clinit> (the static initializer) ... is that really a problem.
public void testCompareSubclassDelegates() {
boolean barfIfClinitMissing = false;
world.setBehaveInJava5Way(true);
BcelWorld bcelWorld = new BcelWorld(getClass().getClassLoader(),IMessageHandler.THROW,null);
bcelWorld.setBehaveInJava5Way(true);
UnresolvedType javaUtilHashMap = UnresolvedType.forName("java.util.HashMap");
ReferenceType rawType =(ReferenceType)bcelWorld.resolve(javaUtilHashMap );
ReferenceType rawReflectType =(ReferenceType)world.resolve(javaUtilHashMap );
ResolvedMember[] rms1 = rawType.getDelegate().getDeclaredMethods();
ResolvedMember[] rms2 = rawReflectType.getDelegate().getDeclaredMethods();
StringBuffer errors = new StringBuffer();
Set one = new HashSet();
for (int i = 0; i < rms1.length; i++) {
one.add(rms1[i].toString());
}
Set two = new HashSet();
for (int i = 0; i < rms2.length; i++) {
two.add(rms2[i].toString());
}
for (int i = 0;i<rms2.length;i++) {
if (!one.contains(rms2[i].toString())) {
errors.append("Couldn't find "+rms2[i].toString()+" in the bcel set\n");
}
}
for (int i = 0;i<rms1.length;i++) {
if (!two.contains(rms1[i].toString())) {
if (!barfIfClinitMissing && rms1[i].getName().equals("<clinit>")) continue;
errors.append("Couldn't find "+rms1[i].toString()+" in the reflection set\n");
}
}
assertTrue("Errors:"+errors.toString(),errors.length()==0);
// the good old ibm vm seems to offer clinit through its reflection support (see pr145322)
if (rms1.length==rms2.length) return;
if (barfIfClinitMissing) {
// the numbers must be exact
assertEquals(rms1.length,rms2.length);
} else {
// the numbers can be out by one in favour of bcel
if (rms1.length!=(rms2.length+1)) {
for (int i = 0; i < rms1.length; i++) {
System.err.println("bcel"+i+" is "+rms1[i]);
}
for (int i = 0; i < rms2.length; i++) {
System.err.println("refl"+i+" is "+rms2[i]);
}
}
assertTrue("Should be one extra (clinit) in BCEL case, but bcel="+rms1.length+" reflect="+rms2.length,rms1.length==rms2.length+1);
}
}
// todo: array of int
protected void setUp() throws Exception {
world = new ReflectionWorld(getClass().getClassLoader());
objectType = world.resolve("java.lang.Object");
}
}
|
153,535 |
Bug 153535 Bug in reflection delegate signature for array of object type
|
The following problem is interesting because the advice weaves correctly with Java 1.5 LTW and also using Java 1.4 with build-time weaving. However, the following call pointcut isn't matching the expected call site in Java 1.4 load-time weaving (*). Pointcut: private pointcut inExecQuery() : (within(uk.ltd.getahead.dwr.impl.ExecuteQuery) || within(uk.ltd.getahead.dwr.ExecuteQuery)); public pointcut dwrQuery(Method method, Object receiver, Object[] params) : inExecQuery() && withincode(* execute(..)) && call(* Method.invoke(..)) && args(receiver, params) && target(method); protected pointcut monitorEnd() : dwrQuery(*, *, *); Matching call site: Object reply = method.invoke(object, params); I've tracked it down to failing to find the method in ResolvedType.matches. On line 405: "m1.getSignature()"= "(Ljava/lang/Object;[Ljava.lang.Object;)Ljava/lang/Object;" "m2.getSignature()"= "(Ljava/lang/Object;[Ljava/lang/Object;)Ljava/lang/Object;" Note the difference between . and / ^ ^ It looks to me like the signature for array types in the reflection delegate is erroneously using . instead of /. I have attached a patch to the ReflectionBasedReferenceTypeDelegateTest that isolates this unexpected signature return. Hopefully you agree that this is not correct. If not, some more information follows. Here's the stack trace where the match fails: ResolvedType.matches(Member, Member) line: 405 ReferenceType(ResolvedType).lookupMember(Member, Iterator) line: 347 ReferenceType(ResolvedType).lookupMethod(Member) line: 326 LTWWorld(World).resolve(Member) line: 504 MemberImpl.resolve(World) line: 93 JoinPointSignatureIterator.addSignaturesUpToFirstDefiningMember() line: 109 JoinPointSignatureIterator.<init>(Member, World) line: 51 MemberImpl.getJoinPointSignatures(World) line: 943 SignaturePattern.matches(Member, World, boolean) line: 286 KindedPointcut.matchInternal(Shadow) line: 106 KindedPointcut(Pointcut).match(Shadow) line: 146 AndPointcut.matchInternal(Shadow) line: 53 AndPointcut(Pointcut).match(Shadow) line: 146 AndPointcut.matchInternal(Shadow) line: 51 AndPointcut(Pointcut).match(Shadow) line: 146 AndPointcut.matchInternal(Shadow) line: 51 AndPointcut(Pointcut).match(Shadow) line: 146 AndPointcut.matchInternal(Shadow) line: 51 AndPointcut(Pointcut).match(Shadow) line: 146 OrPointcut.matchInternal(Shadow) line: 50 OrPointcut(Pointcut).match(Shadow) line: 146 BcelAdvice(ShadowMunger).match(Shadow, World) line: 71 BcelAdvice(Advice).match(Shadow, World) line: 112 BcelAdvice.match(Shadow, World) line: 107 BcelClassWeaver.match(BcelShadow, List) line: 2806 BcelClassWeaver.matchInvokeInstruction(LazyMethodGen, InstructionHandle, InvokeInstruction, BcelShadow, List) line: 2768 BcelClassWeaver.match(LazyMethodGen, InstructionHandle, BcelShadow, List) line: 2506 BcelClassWeaver.match(LazyMethodGen) line: 2332 BcelClassWeaver.weave() line: 494 BcelClassWeaver.weave(BcelWorld, LazyClassGen, List, List, List) line: 119 BcelWeaver.weave(UnwovenClassFile, BcelObjectType, boolean) line: 1613 BcelWeaver.weaveWithoutDump(UnwovenClassFile, BcelObjectType) line: 1564 BcelWeaver.weaveAndNotify(UnwovenClassFile, BcelObjectType, IWeaveRequestor) line: 1341 BcelWeaver.weave(IClassFileProvider) line: 1163 ClassLoaderWeavingAdaptor(WeavingAdaptor).getWovenBytes(String, byte[]) line: 319 ClassLoaderWeavingAdaptor(WeavingAdaptor).weaveClass(String, byte[]) line: 225 Aj.preProcess(String, byte[], ClassLoader) line: 77 ClassPreProcessorAdapter.preProcess(String, byte[], ClassLoader) line: 67 ClassPreProcessorHelper.defineClass0Pre(ClassLoader, String, byte[], int, int, ProtectionDomain) line: 107 WebappClassLoader(ClassLoader).defineClass(String, byte[], int, int, ProtectionDomain) line: 539 WebappClassLoader(SecureClassLoader).defineClass(String, byte[], int, int, CodeSource) line: 123 WebappClassLoader.findClassInternal(String) line: 1786 WebappClassLoader.findClass(String) line: 1048 WebappClassLoader.loadClass(String, boolean) line: 1506 WebappClassLoader.loadClass(String) line: 1385 WebappClassLoader(ClassLoader).loadClassInternal(String) line: 302 Class.forName0(String, boolean, ClassLoader) line: not available [native method] Class.forName(String) line: 141 InitializeLog.setWarnLogging(String) line: 121 InitializeLog.initializeLogging() line: 96 ContextLoaderServlet.init() line: 13 ContextLoaderServlet(GenericServlet).init(ServletConfig) line: 212 StandardWrapper.loadServlet() line: 879 StandardWrapper.load() line: 767 StandardContext.loadOnStartup(Container[]) line: 3483 StandardContext.start() line: 3709 StandardHost(ContainerBase).addChildInternal(Container) line: 776 StandardHost(ContainerBase).addChild(Container) line: 759 StandardHost.addChild(Container) line: 537 StandardHostDeployer.install(String, URL) line: 260 StandardHost.install(String, URL) line: 730 HostConfig.deployWARs(File, String[]) line: 558 HostConfig.deployApps() line: 373 HostConfig.start() line: 784 HostConfig.lifecycleEvent(LifecycleEvent) line: 330 LifecycleSupport.fireLifecycleEvent(String, Object) line: 119 StandardHost(ContainerBase).start() line: 1155 StandardHost.start() line: 696 StandardEngine(ContainerBase).start() line: 1147 StandardEngine.start() line: 310 StandardService.start() line: 449 StandardServer.start() line: 2212 Catalina.start() line: 458 Catalina.execute() line: 345 Catalina.process(String[]) line: 129 NativeMethodAccessorImpl.invoke0(Method, Object, Object[]) line: not available [native method] NativeMethodAccessorImpl.invoke(Object, Object[]) line: 39 DelegatingMethodAccessorImpl.invoke(Object, Object[]) line: 25 Method.invoke(Object, Object[]) line: 324 Bootstrap.main(String[]) line: 150 I'm using a modified version of Alex Vasseur's LTW plugin for a Java 1.4 VM although I haven't tested on the JRockIt plugin for a 1.4 VM: my guess is that this would fail there too.
|
resolved fixed
|
82e3e13
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-08-15T11:51:21Z | 2006-08-11T07:06:40Z |
weaver5/java5-testsrc/org/aspectj/weaver/reflect/ReflectionBasedReferenceTypeDelegateTest.java
|
/* *******************************************************************
* Copyright (c) 2005 Contributors.
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Eclipse Public License v1.0
* which accompanies this distribution and is available at
* http://eclipse.org/legal/epl-v10.html
*
* Contributors:
* Adrian Colyer Initial implementation
* ******************************************************************/
package org.aspectj.weaver.reflect;
import java.util.HashSet;
import java.util.Set;
import junit.framework.TestCase;
import org.aspectj.bridge.IMessageHandler;
import org.aspectj.weaver.ReferenceType;
import org.aspectj.weaver.ResolvedMember;
import org.aspectj.weaver.ResolvedType;
import org.aspectj.weaver.UnresolvedType;
import org.aspectj.weaver.bcel.BcelWorld;
public abstract class ReflectionBasedReferenceTypeDelegateTest extends TestCase {
protected ReflectionWorld world;
private ResolvedType objectType;
private ResolvedType classType;
public void testIsAspect() {
assertFalse(objectType.isAspect());
}
public void testIsAnnotationStyleAspect() {
assertFalse(objectType.isAnnotationStyleAspect());
}
public void testIsInterface() {
assertFalse(objectType.isInterface());
assertTrue(world.resolve("java.io.Serializable").isInterface());
}
public void testIsEnum() {
assertFalse(objectType.isEnum());
}
public void testIsAnnotation() {
assertFalse(objectType.isAnnotation());
}
public void testIsAnnotationWithRuntimeRetention() {
assertFalse(objectType.isAnnotationWithRuntimeRetention());
}
public void testIsClass() {
assertTrue(objectType.isClass());
assertFalse(world.resolve("java.io.Serializable").isClass());
}
public void testIsGeneric() {
assertFalse(objectType.isGenericType());
}
public void testIsExposedToWeaver() {
assertFalse(objectType.isExposedToWeaver());
}
public void testHasAnnotation() {
assertFalse(objectType.hasAnnotation(UnresolvedType.forName("Foo")));
}
public void testGetAnnotations() {
assertEquals("no entries",0,objectType.getAnnotations().length);
}
public void testGetAnnotationTypes() {
assertEquals("no entries",0,objectType.getAnnotationTypes().length);
}
public void testGetTypeVariables() {
assertEquals("no entries",0,objectType.getTypeVariables().length);
}
public void testGetPerClause() {
assertNull(objectType.getPerClause());
}
public void testGetModifiers() {
assertEquals(Object.class.getModifiers(),objectType.getModifiers());
}
public void testGetSuperclass() {
assertTrue("Superclass of object should be null, but it is: "+objectType.getSuperclass(),objectType.getSuperclass()==null);
assertEquals(objectType,world.resolve("java.lang.Class").getSuperclass());
ResolvedType d = world.resolve("reflect.tests.D");
assertEquals(world.resolve("reflect.tests.C"),d.getSuperclass());
}
protected int findMethod(String name, ResolvedMember[] methods) {
for (int i=0; i<methods.length; i++) {
if (name.equals(methods[i].getName())) {
return i;
}
}
return -1;
}
protected int findMethod(String name, int numArgs, ResolvedMember[] methods) {
for (int i=0; i<methods.length; i++) {
if (name.equals(methods[i].getName()) && (methods[i].getParameterTypes().length == numArgs)) {
return i;
}
}
return -1;
}
public void testGetDeclaredMethods() {
ResolvedMember[] methods = objectType.getDeclaredMethods();
assertEquals(Object.class.getDeclaredMethods().length + Object.class.getDeclaredConstructors().length, methods.length);
ResolvedType c = world.resolve("reflect.tests.C");
methods = c.getDeclaredMethods();
assertEquals(3,methods.length);
int idx = findMethod("foo", methods);
assertTrue(idx > -1);
assertEquals(world.resolve("java.lang.String"),methods[idx].getReturnType());
assertEquals(1, methods[idx].getParameterTypes().length);
assertEquals(objectType,methods[idx].getParameterTypes()[0]);
assertEquals(1,methods[idx].getExceptions().length);
assertEquals(world.resolve("java.lang.Exception"),methods[idx].getExceptions()[0]);
int baridx = findMethod("bar", methods);
int initidx = findMethod("<init>", methods);
assertTrue(baridx > -1);
assertTrue(initidx > -1);
assertTrue(baridx != initidx && baridx != idx && idx <= 2 && initidx <= 2 && baridx <= 2);
ResolvedType d = world.resolve("reflect.tests.D");
methods = d.getDeclaredMethods();
assertEquals(2,methods.length);
classType = world.resolve("java.lang.Class");
methods = classType.getDeclaredMethods();
assertEquals(Class.class.getDeclaredMethods().length + Class.class.getDeclaredConstructors().length, methods.length);
}
public void testGetDeclaredFields() {
ResolvedMember[] fields = objectType.getDeclaredFields();
assertEquals(0,fields.length);
ResolvedType c = world.resolve("reflect.tests.C");
fields = c.getDeclaredFields();
assertEquals(2,fields.length);
assertEquals("f",fields[0].getName());
assertEquals("s",fields[1].getName());
assertEquals(ResolvedType.INT,fields[0].getReturnType());
assertEquals(world.resolve("java.lang.String"),fields[1].getReturnType());
}
public void testGetDeclaredInterfaces() {
ResolvedType[] interfaces = objectType.getDeclaredInterfaces();
assertEquals(0,interfaces.length);
ResolvedType d = world.resolve("reflect.tests.D");
interfaces = d.getDeclaredInterfaces();
assertEquals(1,interfaces.length);
assertEquals(world.resolve("java.io.Serializable"),interfaces[0]);
}
public void testGetDeclaredPointcuts() {
ResolvedMember[] pointcuts = objectType.getDeclaredPointcuts();
assertEquals(0,pointcuts.length);
}
public void testSerializableSuperclass() {
ResolvedType serializableType = world.resolve("java.io.Serializable");
ResolvedType superType = serializableType.getSuperclass();
assertTrue("Superclass of serializable should be Object but was "+superType,superType.equals(UnresolvedType.OBJECT));
BcelWorld bcelworld = new BcelWorld();
bcelworld.setBehaveInJava5Way(true);
ResolvedType bcelSupertype = bcelworld.resolve(UnresolvedType.SERIALIZABLE).getSuperclass();
assertTrue("Should be null but is "+bcelSupertype,bcelSupertype.equals(UnresolvedType.OBJECT));
}
public void testSubinterfaceSuperclass() {
ResolvedType ifaceType = world.resolve("java.security.Key");
ResolvedType superType = ifaceType.getSuperclass();
assertTrue("Superclass should be Object but was "+superType,superType.equals(UnresolvedType.OBJECT));
BcelWorld bcelworld = new BcelWorld();
bcelworld.setBehaveInJava5Way(true);
ResolvedType bcelSupertype = bcelworld.resolve("java.security.Key").getSuperclass();
assertTrue("Should be null but is "+bcelSupertype,bcelSupertype.equals(UnresolvedType.OBJECT));
}
public void testVoidSuperclass() {
ResolvedType voidType = world.resolve(Void.TYPE);
ResolvedType superType = voidType.getSuperclass();
assertNull(superType);
BcelWorld bcelworld = new BcelWorld();
bcelworld.setBehaveInJava5Way(true);
ResolvedType bcelSupertype = bcelworld.resolve("void").getSuperclass();
assertTrue("Should be null but is "+bcelSupertype,bcelSupertype==null);
}
public void testIntSuperclass() {
ResolvedType voidType = world.resolve(Integer.TYPE);
ResolvedType superType = voidType.getSuperclass();
assertNull(superType);
BcelWorld bcelworld = new BcelWorld();
bcelworld.setBehaveInJava5Way(true);
ResolvedType bcelSupertype = bcelworld.resolve("int").getSuperclass();
assertTrue("Should be null but is "+bcelSupertype,bcelSupertype==null);
}
public void testGenericInterfaceSuperclass_BcelWorldResolution() {
BcelWorld bcelworld = new BcelWorld();
bcelworld.setBehaveInJava5Way(true);
UnresolvedType javaUtilMap = UnresolvedType.forName("java.util.Map");
ReferenceType rawType = (ReferenceType) bcelworld.resolve(javaUtilMap);
assertTrue("Should be the raw type ?!? "+rawType.getTypekind(),rawType.isRawType());
ReferenceType genericType = (ReferenceType)rawType.getGenericType();
assertTrue("Should be the generic type ?!? "+genericType.getTypekind(),genericType.isGenericType());
ResolvedType rt = rawType.getSuperclass();
assertTrue("Superclass for Map raw type should be Object but was "+rt,rt.equals(UnresolvedType.OBJECT));
ResolvedType rt2 = genericType.getSuperclass();
assertTrue("Superclass for Map generic type should be Object but was "+rt2,rt2.equals(UnresolvedType.OBJECT));
}
// FIXME asc maybe. The reflection list of methods returned doesn't include <clinit> (the static initializer) ... is that really a problem.
public void testCompareSubclassDelegates() {
boolean barfIfClinitMissing = false;
world.setBehaveInJava5Way(true);
BcelWorld bcelWorld = new BcelWorld(getClass().getClassLoader(),IMessageHandler.THROW,null);
bcelWorld.setBehaveInJava5Way(true);
UnresolvedType javaUtilHashMap = UnresolvedType.forName("java.util.HashMap");
ReferenceType rawType =(ReferenceType)bcelWorld.resolve(javaUtilHashMap );
ReferenceType rawReflectType =(ReferenceType)world.resolve(javaUtilHashMap );
ResolvedMember[] rms1 = rawType.getDelegate().getDeclaredMethods();
ResolvedMember[] rms2 = rawReflectType.getDelegate().getDeclaredMethods();
StringBuffer errors = new StringBuffer();
Set one = new HashSet();
for (int i = 0; i < rms1.length; i++) {
one.add(rms1[i].toString());
}
Set two = new HashSet();
for (int i = 0; i < rms2.length; i++) {
two.add(rms2[i].toString());
}
for (int i = 0;i<rms2.length;i++) {
if (!one.contains(rms2[i].toString())) {
errors.append("Couldn't find "+rms2[i].toString()+" in the bcel set\n");
}
}
for (int i = 0;i<rms1.length;i++) {
if (!two.contains(rms1[i].toString())) {
if (!barfIfClinitMissing && rms1[i].getName().equals("<clinit>")) continue;
errors.append("Couldn't find "+rms1[i].toString()+" in the reflection set\n");
}
}
assertTrue("Errors:"+errors.toString(),errors.length()==0);
// the good old ibm vm seems to offer clinit through its reflection support (see pr145322)
if (rms1.length==rms2.length) return;
if (barfIfClinitMissing) {
// the numbers must be exact
assertEquals(rms1.length,rms2.length);
} else {
// the numbers can be out by one in favour of bcel
if (rms1.length!=(rms2.length+1)) {
for (int i = 0; i < rms1.length; i++) {
System.err.println("bcel"+i+" is "+rms1[i]);
}
for (int i = 0; i < rms2.length; i++) {
System.err.println("refl"+i+" is "+rms2[i]);
}
}
assertTrue("Should be one extra (clinit) in BCEL case, but bcel="+rms1.length+" reflect="+rms2.length,rms1.length==rms2.length+1);
}
}
// todo: array of int
protected void setUp() throws Exception {
world = new ReflectionWorld(getClass().getClassLoader());
objectType = world.resolve("java.lang.Object");
}
}
|
154,332 |
Bug 154332 [annotations] Incorrect handling of java.lang annotations when matching
|
As raised by Mr Bodkin on the list: Can anyone tell me why this compiling this program produces warnings for marker but not for deprecated (in a recent dev build of AJDT)? Is this just a bug? Both have runtime retention, so I would expect equivalent behavior. @Deprecated @Marker public aspect Annot { pointcut test() : within(@Marker *);// *); declare warning: staticinitialization(@Deprecated *): "deprecated"; declare warning: staticinitialization(@Marker *): "marker"; public static void main(String argz[]) { new Baz().foo(); } } @Deprecated @Marker class Baz { public void foo() {} } @Retention(RetentionPolicy.RUNTIME) public @interface Marker { }
|
resolved fixed
|
59123b0
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-08-18T08:21:58Z | 2006-08-18T08:33:20Z |
tests/bugs153/pr154332/Annot.java
| |
154,332 |
Bug 154332 [annotations] Incorrect handling of java.lang annotations when matching
|
As raised by Mr Bodkin on the list: Can anyone tell me why this compiling this program produces warnings for marker but not for deprecated (in a recent dev build of AJDT)? Is this just a bug? Both have runtime retention, so I would expect equivalent behavior. @Deprecated @Marker public aspect Annot { pointcut test() : within(@Marker *);// *); declare warning: staticinitialization(@Deprecated *): "deprecated"; declare warning: staticinitialization(@Marker *): "marker"; public static void main(String argz[]) { new Baz().foo(); } } @Deprecated @Marker class Baz { public void foo() {} } @Retention(RetentionPolicy.RUNTIME) public @interface Marker { }
|
resolved fixed
|
59123b0
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-08-18T08:21:58Z | 2006-08-18T08:33:20Z |
tests/src/org/aspectj/systemtest/ajc153/Ajc153Tests.java
|
/*******************************************************************************
* Copyright (c) 2006 IBM
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Andy Clement - initial API and implementation
*******************************************************************************/
package org.aspectj.systemtest.ajc153;
import java.io.File;
import junit.framework.Test;
import org.aspectj.testing.Utils;
import org.aspectj.testing.XMLBasedAjcTestCase;
import org.aspectj.weaver.bcel.Utility;
public class Ajc153Tests extends org.aspectj.testing.XMLBasedAjcTestCase {
//public void testGenericsProblem_pr151978() { runTest("generics problem");}
//public void testMissingLineNumbersInStacktraceBefore_pr145442() { runTest("missing line numbers in stacktrace before");}
//public void testMissingLineNumbersInStacktraceAfter_pr145442() { runTest("missing line numbers in stacktrace after");}
//public void testMissingLineNumbersInStacktraceAround_pr145442() { runTest("missing line numbers in stacktrace around");}
// public void testArgnamesAndJavac_pr148381() { runTest("argNames and javac");}
// public void testCFlowXMLAspectLTW_pr149096() { runTest("cflow xml concrete aspect"); }
// public void testAmbiguousBinding_pr121805() { runTest("ambiguous binding");}
public void 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 testVisibilityProblem_pr149071() { runTest("visibility problem");}
// public void testAdviceNotWovenAspectPath_pr147841() { runTest("advice not woven on aspectpath");}
public void testGenericSignatures_pr148409() { runTest("generic signature problem"); }
// public void testBrokenIfArgsCflowAtAj_pr145018() { runTest("ataj crashing with cflow, if and args");}
public void testCantFindType_pr149322_01() {runTest("can't find type on interface call 1");}
public void testCantFindType_pr149322_02() {runTest("can't find type on interface call 2");}
public void testCantFindType_pr149322_03() {runTest("can't find type on interface call 3");}
public void 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 static Test suite() {
return XMLBasedAjcTestCase.loadSuite(Ajc153Tests.class);
}
protected File getSpecFile() {
return new File("../tests/src/org/aspectj/systemtest/ajc153/ajc153.xml");
}
}
|
154,332 |
Bug 154332 [annotations] Incorrect handling of java.lang annotations when matching
|
As raised by Mr Bodkin on the list: Can anyone tell me why this compiling this program produces warnings for marker but not for deprecated (in a recent dev build of AJDT)? Is this just a bug? Both have runtime retention, so I would expect equivalent behavior. @Deprecated @Marker public aspect Annot { pointcut test() : within(@Marker *);// *); declare warning: staticinitialization(@Deprecated *): "deprecated"; declare warning: staticinitialization(@Marker *): "marker"; public static void main(String argz[]) { new Baz().foo(); } } @Deprecated @Marker class Baz { public void foo() {} } @Retention(RetentionPolicy.RUNTIME) public @interface Marker { }
|
resolved fixed
|
59123b0
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-08-18T08:21:58Z | 2006-08-18T08:33:20Z |
weaver/src/org/aspectj/weaver/bcel/BcelObjectType.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
* RonBodkin/AndyClement optimizations for memory consumption/speed
* ******************************************************************/
package org.aspectj.weaver.bcel;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import org.aspectj.apache.bcel.classfile.Attribute;
import org.aspectj.apache.bcel.classfile.Field;
import org.aspectj.apache.bcel.classfile.JavaClass;
import org.aspectj.apache.bcel.classfile.Method;
import org.aspectj.apache.bcel.classfile.Signature;
import org.aspectj.apache.bcel.classfile.Signature.ClassSignature;
import org.aspectj.apache.bcel.classfile.annotation.Annotation;
import org.aspectj.apache.bcel.classfile.annotation.ArrayElementValue;
import org.aspectj.apache.bcel.classfile.annotation.ElementNameValuePair;
import org.aspectj.apache.bcel.classfile.annotation.ElementValue;
import org.aspectj.bridge.IMessageHandler;
import org.aspectj.weaver.AbstractReferenceTypeDelegate;
import org.aspectj.weaver.AjAttribute;
import org.aspectj.weaver.AjcMemberMaker;
import org.aspectj.weaver.AnnotationTargetKind;
import org.aspectj.weaver.AnnotationX;
import org.aspectj.weaver.BCException;
import org.aspectj.weaver.ReferenceType;
import org.aspectj.weaver.ReferenceTypeDelegate;
import org.aspectj.weaver.ResolvedMember;
import org.aspectj.weaver.ResolvedPointcutDefinition;
import org.aspectj.weaver.ResolvedType;
import org.aspectj.weaver.SourceContextImpl;
import org.aspectj.weaver.TypeVariable;
import org.aspectj.weaver.UnresolvedType;
import org.aspectj.weaver.WeaverStateInfo;
import org.aspectj.weaver.World;
import org.aspectj.weaver.bcel.AtAjAttributes.BindingScope;
import org.aspectj.weaver.bcel.BcelGenericSignatureToTypeXConverter.GenericSignatureFormatException;
import org.aspectj.weaver.patterns.Declare;
import org.aspectj.weaver.patterns.DeclareErrorOrWarning;
import org.aspectj.weaver.patterns.DeclarePrecedence;
import org.aspectj.weaver.patterns.FormalBinding;
import org.aspectj.weaver.patterns.IScope;
import org.aspectj.weaver.patterns.PerClause;
public class BcelObjectType extends AbstractReferenceTypeDelegate {
public JavaClass javaClass;
private LazyClassGen lazyClassGen = null; // set lazily if it's an aspect
private int modifiers;
private String className;
private String superclassSignature;
private String superclassName;
private String[] interfaceSignatures;
private ResolvedMember[] fields = null;
private ResolvedMember[] methods = null;
private ResolvedType[] annotationTypes = null;
private AnnotationX[] annotations = null;
private TypeVariable[] typeVars = null;
private String retentionPolicy;
private AnnotationTargetKind[] annotationTargetKinds;
// Aspect related stuff (pointcuts *could* be in a java class)
private AjAttribute.WeaverVersionInfo wvInfo = AjAttribute.WeaverVersionInfo.UNKNOWN;
private ResolvedPointcutDefinition[] pointcuts = null;
private ResolvedMember[] privilegedAccess = null;
private WeaverStateInfo weaverState = null;
private PerClause perClause = null;
private List typeMungers = Collections.EMPTY_LIST;
private List declares = Collections.EMPTY_LIST;
private Signature.FormalTypeParameter[] formalsForResolution = null;
private ClassSignature cachedGenericClassTypeSignature;
private String declaredSignature = null;
private boolean hasBeenWoven = false;
private boolean isGenericType = false;
private boolean isInterface;
private boolean isEnum;
private boolean isAnnotation;
private boolean isAnonymous;
private boolean isNested;
private boolean isObject = false; // set upon construction
private boolean isAnnotationStyleAspect = false;// set upon construction
private boolean isCodeStyleAspect = false; // not redundant with field above!
private int bitflag = 0x0000;
// discovery bits
private static final int DISCOVERED_ANNOTATION_RETENTION_POLICY = 0x0001;
private static final int UNPACKED_GENERIC_SIGNATURE = 0x0002;
private static final int UNPACKED_AJATTRIBUTES = 0x0004; // see note(1) below
private static final int DISCOVERED_ANNOTATION_TARGET_KINDS = 0x0008;
private static final int DISCOVERED_DECLARED_SIGNATURE = 0x0010;
private static final int DISCOVERED_WHETHER_ANNOTATION_STYLE = 0x0020;
private static final int DAMAGED = 0x0040; // see note(2) below
/*
* Notes:
* note(1):
* in some cases (perclause inheritance) we encounter unpacked state when calling getPerClause
*
* note(2):
* A BcelObjectType is 'damaged' if it has been modified from what was original constructed from
* the bytecode. This currently happens if the parents are modified or an annotation is added -
* ideally BcelObjectType should be immutable but that's a bigger piece of work. XXX
*/
// ------------------ construction and initialization
BcelObjectType(ReferenceType resolvedTypeX, JavaClass javaClass, boolean exposedToWeaver) {
super(resolvedTypeX, exposedToWeaver);
this.javaClass = javaClass;
initializeFromJavaclass();
//ATAJ: set the delegate right now for @AJ pointcut, else it is done too late to lookup
// @AJ pc refs annotation in class hierarchy
resolvedTypeX.setDelegate(this);
if (resolvedTypeX.getSourceContext()==SourceContextImpl.UNKNOWN_SOURCE_CONTEXT) {
setSourceContext(new SourceContextImpl(this));
}
// this should only ever be java.lang.Object which is
// the only class in Java-1.4 with no superclasses
isObject = (javaClass.getSuperclassNameIndex() == 0);
ensureAspectJAttributesUnpacked();
setSourcefilename(javaClass.getSourceFileName());
}
// repeat initialization
public void setJavaClass(JavaClass newclass) {
this.javaClass = newclass;
resetState();
initializeFromJavaclass();
}
private void initializeFromJavaclass() {
isInterface = javaClass.isInterface();
isEnum = javaClass.isEnum();
isAnnotation = javaClass.isAnnotation();
isAnonymous = javaClass.isAnonymous();
isNested = javaClass.isNested();
modifiers = javaClass.getAccessFlags();
superclassName = javaClass.getSuperclassName();
className = javaClass.getClassName();
cachedGenericClassTypeSignature = javaClass.getGenericClassTypeSignature();
}
// --- getters
// Java related
public boolean isInterface() {return isInterface;}
public boolean isEnum() {return isEnum;}
public boolean isAnnotation() {return isAnnotation;}
public boolean isAnonymous() {return isAnonymous;}
public boolean isNested() {return isNested;}
public int getModifiers() {return modifiers;}
/**
* Must take into account generic signature
*/
public ResolvedType getSuperclass() {
if (isObject) return null;
ensureGenericSignatureUnpacked();
if (superclassSignature == null) {
if (superclassName==null) superclassName = javaClass.getSuperclassName();
superclassSignature = getResolvedTypeX().getWorld().resolve(UnresolvedType.forName(superclassName)).getSignature();
}
ResolvedType res = getResolvedTypeX().getWorld().resolve(UnresolvedType.forSignature(superclassSignature));
return res;
}
/**
* Retrieves the declared interfaces - this allows for the generic signature on a type. If specified
* then the generic signature is used to work out the types - this gets around the results of
* erasure when the class was originally compiled.
*/
public ResolvedType[] getDeclaredInterfaces() {
ensureGenericSignatureUnpacked();
ResolvedType[] interfaceTypes = null;
if (interfaceSignatures == null) {
String[] names = javaClass.getInterfaceNames();
interfaceSignatures = new String[names.length];
interfaceTypes = new ResolvedType[names.length];
for (int i = 0, len = names.length; i < len; i++) {
interfaceTypes[i] = getResolvedTypeX().getWorld().resolve(UnresolvedType.forName(names[i]));
interfaceSignatures[i] = interfaceTypes[i].getSignature();
}
} else {
interfaceTypes = new ResolvedType[interfaceSignatures.length];
for (int i = 0, len = interfaceSignatures.length; i < len; i++) {
interfaceTypes[i] = getResolvedTypeX().getWorld().resolve(UnresolvedType.forSignature(interfaceSignatures[i]));
}
}
return interfaceTypes;
}
public ResolvedMember[] getDeclaredMethods() {
ensureGenericSignatureUnpacked();
if (methods == null) {
Method[] ms = javaClass.getMethods();
methods = new ResolvedMember[ms.length];
for (int i = ms.length - 1; i >= 0; i--) {
methods[i] = new BcelMethod(this, ms[i]);
}
}
return methods;
}
public ResolvedMember[] getDeclaredFields() {
ensureGenericSignatureUnpacked();
if (fields == null) {
Field[] fs = javaClass.getFields();
fields = new ResolvedMember[fs.length];
for (int i = 0, len = fs.length; i < len; i++) {
fields[i] = new BcelField(this, fs[i]);
}
}
return fields;
}
public TypeVariable[] getTypeVariables() {
if (!isGeneric()) return TypeVariable.NONE;
if (typeVars == null) {
Signature.ClassSignature classSig = cachedGenericClassTypeSignature;//javaClass.getGenericClassTypeSignature();
typeVars = new TypeVariable[classSig.formalTypeParameters.length];
for (int i = 0; i < typeVars.length; i++) {
Signature.FormalTypeParameter ftp = classSig.formalTypeParameters[i];
try {
typeVars[i] = BcelGenericSignatureToTypeXConverter.formalTypeParameter2TypeVariable(
ftp,
classSig.formalTypeParameters,
getResolvedTypeX().getWorld());
} catch (GenericSignatureFormatException e) {
// this is a development bug, so fail fast with good info
throw new IllegalStateException(
"While getting the type variables for type " + this.toString()
+ " with generic signature " + classSig +
" the following error condition was detected: " + e.getMessage());
}
}
}
return typeVars;
}
// Aspect related
public Collection getTypeMungers() {return typeMungers;}
public Collection getDeclares() {return declares;}
public Collection getPrivilegedAccesses() {
if (privilegedAccess == null) return Collections.EMPTY_LIST;
return Arrays.asList(privilegedAccess);
}
public ResolvedMember[] getDeclaredPointcuts() {
return pointcuts;
}
public boolean isAspect() {
return perClause != null;
}
/**
* Check if the type is an @AJ aspect (no matter if used from an LTW point of view).
* Such aspects are annotated with @Aspect
*
* @return true for @AJ aspect
*/
public boolean isAnnotationStyleAspect() {
if ((bitflag&DISCOVERED_WHETHER_ANNOTATION_STYLE)==0) {
bitflag|=DISCOVERED_WHETHER_ANNOTATION_STYLE;
isAnnotationStyleAspect = !isCodeStyleAspect && hasAnnotation(AjcMemberMaker.ASPECT_ANNOTATION);
}
return isAnnotationStyleAspect;
}
/**
* Process any org.aspectj.weaver attributes stored against the class.
*/
private void ensureAspectJAttributesUnpacked() {
if ((bitflag&UNPACKED_AJATTRIBUTES)!=0) return;
bitflag|=UNPACKED_AJATTRIBUTES;
IMessageHandler msgHandler = getResolvedTypeX().getWorld().getMessageHandler();
// Pass in empty list that can store things for readAj5 to process
List l = BcelAttributes.readAjAttributes(className,javaClass.getAttributes(), getResolvedTypeX().getSourceContext(),getResolvedTypeX().getWorld(),AjAttribute.WeaverVersionInfo.UNKNOWN);
List pointcuts = new ArrayList();
typeMungers = new ArrayList();
declares = new ArrayList();
processAttributes(l,pointcuts,false);
l = AtAjAttributes.readAj5ClassAttributes(javaClass, getResolvedTypeX(), getResolvedTypeX().getSourceContext(), msgHandler,isCodeStyleAspect);
AjAttribute.Aspect deferredAspectAttribute = processAttributes(l,pointcuts,true);
this.pointcuts = (ResolvedPointcutDefinition[])
pointcuts.toArray(new ResolvedPointcutDefinition[pointcuts.size()]);
resolveAnnotationDeclares(l);
if (deferredAspectAttribute != null) {
// we can finally process the aspect and its associated perclause...
perClause = deferredAspectAttribute.reifyFromAtAspectJ(this.getResolvedTypeX());
}
}
private AjAttribute.Aspect processAttributes(List attributeList, List pointcuts, boolean fromAnnotations) {
AjAttribute.Aspect deferredAspectAttribute = null;
for (Iterator iter = attributeList.iterator(); iter.hasNext();) {
AjAttribute a = (AjAttribute) iter.next();
//System.err.println("unpacking: " + this + " and " + a);
if (a instanceof AjAttribute.Aspect) {
if (fromAnnotations) {
deferredAspectAttribute = (AjAttribute.Aspect) a;
} else {
perClause = ((AjAttribute.Aspect)a).reify(this.getResolvedTypeX());
isCodeStyleAspect = true;
}
} else if (a instanceof AjAttribute.PointcutDeclarationAttribute) {
pointcuts.add(((AjAttribute.PointcutDeclarationAttribute)a).reify());
} else if (a instanceof AjAttribute.WeaverState) {
weaverState = ((AjAttribute.WeaverState)a).reify();
} else if (a instanceof AjAttribute.TypeMunger) {
typeMungers.add(((AjAttribute.TypeMunger)a).reify(getResolvedTypeX().getWorld(), getResolvedTypeX()));
} else if (a instanceof AjAttribute.DeclareAttribute) {
declares.add(((AjAttribute.DeclareAttribute)a).getDeclare());
} else if (a instanceof AjAttribute.PrivilegedAttribute) {
privilegedAccess = ((AjAttribute.PrivilegedAttribute)a).getAccessedMembers();
} else if (a instanceof AjAttribute.SourceContextAttribute) {
if (getResolvedTypeX().getSourceContext() instanceof SourceContextImpl) {
AjAttribute.SourceContextAttribute sca = (AjAttribute.SourceContextAttribute)a;
((SourceContextImpl)getResolvedTypeX().getSourceContext()).configureFromAttribute(sca.getSourceFileName(),sca.getLineBreaks());
}
} else if (a instanceof AjAttribute.WeaverVersionInfo) {
wvInfo = (AjAttribute.WeaverVersionInfo)a; // Set the weaver version used to build this type
} else {
throw new BCException("bad attribute " + a);
}
}
return deferredAspectAttribute;
}
/**
* Extra processing step needed because declares that come from annotations are not pre-resolved.
* We can't do the resolution until *after* the pointcuts have been resolved.
* @param attributeList
*/
private void resolveAnnotationDeclares(List attributeList) {
FormalBinding[] bindings = new org.aspectj.weaver.patterns.FormalBinding[0];
IScope bindingScope = new BindingScope(
getResolvedTypeX(),
getResolvedTypeX().getSourceContext(),
bindings
);
for (Iterator iter = attributeList.iterator(); iter.hasNext();) {
AjAttribute a = (AjAttribute) iter.next();
if (a instanceof AjAttribute.DeclareAttribute) {
Declare decl = (((AjAttribute.DeclareAttribute)a).getDeclare());
if (decl instanceof DeclareErrorOrWarning ||
decl instanceof DeclarePrecedence) {
decl.resolve(bindingScope);
}
}
}
}
public PerClause getPerClause() {
ensureAspectJAttributesUnpacked();
return perClause;
}
public JavaClass getJavaClass() {
return javaClass;
}
public void ensureDelegateConsistent() {
if ((bitflag&DAMAGED)!=0) {resetState();}
}
public void resetState() {
if (javaClass == null) {
// we might store the classname and allow reloading?
// At this point we are relying on the world to not evict if it might want to reweave multiple times
throw new BCException("can't weave evicted type");
}
bitflag=0x0000;
this.annotationTypes = null;
this.annotations = null;
this.interfaceSignatures=null;
this.superclassSignature = null;
this.superclassName = null;
this.fields = null;
this.methods = null;
this.pointcuts = null;
this.perClause = null;
this.weaverState = null;
this.lazyClassGen = null;
hasBeenWoven=false;
isObject = (javaClass.getSuperclassNameIndex() == 0);
isAnnotationStyleAspect=false;
ensureAspectJAttributesUnpacked();
}
public void finishedWith() {
// memory usage experiments....
// this.interfaces = null;
// this.superClass = null;
// this.fields = null;
// this.methods = null;
// this.pointcuts = null;
// this.perClause = null;
// this.weaverState = null;
// this.lazyClassGen = null;
// this next line frees up memory, but need to understand incremental implications
// before leaving it in.
// getResolvedTypeX().setSourceContext(null);
}
public WeaverStateInfo getWeaverState() {
return weaverState;
}
void setWeaverState(WeaverStateInfo weaverState) {
this.weaverState = weaverState;
}
public void printWackyStuff(PrintStream out) {
if (typeMungers.size() > 0) out.println(" TypeMungers: " + typeMungers);
if (declares.size() > 0) out.println(" declares: " + declares);
}
/**
* Return the lazyClassGen associated with this type. For aspect types, this
* value will be cached, since it is used to inline advice. For non-aspect
* types, this lazyClassGen is always newly constructed.
*/
public LazyClassGen getLazyClassGen() {
LazyClassGen ret = lazyClassGen;
if (ret == null) {
//System.err.println("creating lazy class gen for: " + this);
ret = new LazyClassGen(this);
//ret.print(System.err);
//System.err.println("made LCG from : " + this.getJavaClass().getSuperclassName );
if (isAspect()) {
lazyClassGen = ret;
}
}
return ret;
}
public boolean isSynthetic() {
return getResolvedTypeX().isSynthetic();
}
public AjAttribute.WeaverVersionInfo getWeaverVersionAttribute() {
return wvInfo;
}
public void addParent(ResolvedType newParent) {
bitflag|=DAMAGED;
if (newParent.isClass()) {
superclassSignature = newParent.getSignature();
superclassName = newParent.getName();
// superClass = newParent;
} else {
ResolvedType[] oldInterfaceNames = getDeclaredInterfaces();
int exists = -1;
for (int i = 0; i < oldInterfaceNames.length; i++) {
ResolvedType type = oldInterfaceNames[i];
if (type.equals(newParent)) {exists = i;break; }
}
if (exists==-1) {
int len = interfaceSignatures.length;
String[] newInterfaceSignatures = new String[len+1];
System.arraycopy(interfaceSignatures, 0, newInterfaceSignatures, 0, len);
newInterfaceSignatures[len]=newParent.getSignature();
interfaceSignatures = newInterfaceSignatures;
}
}
//System.err.println("javaClass: " + Arrays.asList(javaClass.getInterfaceNames()) + " super " + superclassName);
//if (lazyClassGen != null) lazyClassGen.print();
}
// -- annotation related
public ResolvedType[] getAnnotationTypes() {
ensureAnnotationsUnpacked();
return annotationTypes;
}
public AnnotationX[] getAnnotations() {
ensureAnnotationsUnpacked();
return annotations;
}
public boolean hasAnnotation(UnresolvedType ofType) {
ensureAnnotationsUnpacked();
for (int i = 0; i < annotationTypes.length; i++) {
ResolvedType ax = annotationTypes[i];
if (ax.equals(ofType)) return true;
}
return false;
}
// evil mutator - adding state not stored in the java class
public void addAnnotation(AnnotationX annotation) {
bitflag|=DAMAGED;
int len = annotations.length;
AnnotationX[] ret = new AnnotationX[len+1];
System.arraycopy(annotations, 0, ret, 0, len);
ret[len] = annotation;
annotations = ret;
len = annotationTypes.length;
ResolvedType[] ret2 = new ResolvedType[len+1];
System.arraycopy(annotationTypes,0,ret2,0,len);
ret2[len] = getResolvedTypeX().getWorld().resolve(UnresolvedType.forName(annotation.getTypeName()));
annotationTypes = ret2;
}
public boolean isAnnotationWithRuntimeRetention() {
return (getRetentionPolicy()==null?false:getRetentionPolicy().equals("RUNTIME"));
}
public String getRetentionPolicy() {
if ((bitflag&DISCOVERED_ANNOTATION_RETENTION_POLICY)==0) {
bitflag|=DISCOVERED_ANNOTATION_RETENTION_POLICY;
retentionPolicy=null; // null means we have no idea
if (isAnnotation()) {
ensureAnnotationsUnpacked();
for (int i = annotations.length-1; i>=0; i--) {
AnnotationX ax = annotations[i];
if (ax.getTypeName().equals(UnresolvedType.AT_RETENTION.getName())) {
List values = ax.getBcelAnnotation().getValues();
for (Iterator it = values.iterator(); it.hasNext();) {
ElementNameValuePair element = (ElementNameValuePair) it.next();
ElementValue v = element.getValue();
retentionPolicy = v.stringifyValue();
return retentionPolicy;
}
}
}
}
}
return retentionPolicy;
}
public boolean canAnnotationTargetType() {
AnnotationTargetKind[] targetKinds = getAnnotationTargetKinds();
if (targetKinds == null) return true;
for (int i = 0; i < targetKinds.length; i++) {
if (targetKinds[i].equals(AnnotationTargetKind.TYPE)) {
return true;
}
}
return false;
}
public AnnotationTargetKind[] getAnnotationTargetKinds() {
if ((bitflag&DISCOVERED_ANNOTATION_TARGET_KINDS)!=0) return annotationTargetKinds;
bitflag|=DISCOVERED_ANNOTATION_TARGET_KINDS;
annotationTargetKinds = null; // null means we have no idea or the @Target annotation hasn't been used
List targetKinds = new ArrayList();
if (isAnnotation()) {
Annotation[] annotationsOnThisType = javaClass.getAnnotations();
for (int i = 0; i < annotationsOnThisType.length; i++) {
Annotation a = annotationsOnThisType[i];
if (a.getTypeName().equals(UnresolvedType.AT_TARGET.getName())) {
ArrayElementValue arrayValue = (ArrayElementValue)((ElementNameValuePair)a.getValues().get(0)).getValue();
ElementValue[] evs = arrayValue.getElementValuesArray();
if (evs!=null) {
for (int j = 0; j < evs.length; j++) {
String targetKind = evs[j].stringifyValue();
if (targetKind.equals("ANNOTATION_TYPE")) { targetKinds.add(AnnotationTargetKind.ANNOTATION_TYPE);
} else if (targetKind.equals("CONSTRUCTOR")) { targetKinds.add(AnnotationTargetKind.CONSTRUCTOR);
} else if (targetKind.equals("FIELD")) { targetKinds.add(AnnotationTargetKind.FIELD);
} else if (targetKind.equals("LOCAL_VARIABLE")) { targetKinds.add(AnnotationTargetKind.LOCAL_VARIABLE);
} else if (targetKind.equals("METHOD")) { targetKinds.add(AnnotationTargetKind.METHOD);
} else if (targetKind.equals("PACKAGE")) { targetKinds.add(AnnotationTargetKind.PACKAGE);
} else if (targetKind.equals("PARAMETER")) { targetKinds.add(AnnotationTargetKind.PARAMETER);
} else if (targetKind.equals("TYPE")) { targetKinds.add(AnnotationTargetKind.TYPE);}
}
}
}
}
if (!targetKinds.isEmpty()) {
annotationTargetKinds = new AnnotationTargetKind[targetKinds.size()];
return (AnnotationTargetKind[]) targetKinds.toArray(annotationTargetKinds);
}
}
return annotationTargetKinds;
}
// --- unpacking methods
private void ensureAnnotationsUnpacked() {
if (annotationTypes == null) {
Annotation annos[] = javaClass.getAnnotations();
if (annos==null || annos.length==0) {
annotationTypes = ResolvedType.NONE;
annotations = AnnotationX.NONE;
} else {
World w = getResolvedTypeX().getWorld();
annotationTypes = new ResolvedType[annos.length];
annotations = new AnnotationX[annos.length];
for (int i = 0; i < annos.length; i++) {
Annotation annotation = annos[i];
annotationTypes[i] = w.resolve(UnresolvedType.forName(annotation.getTypeName()));
annotations[i] = new AnnotationX(annotation,w);
}
}
}
}
// ---
public String getDeclaredGenericSignature() {
ensureGenericInfoProcessed();
return declaredSignature;
}
Signature.ClassSignature getGenericClassTypeSignature() {
return cachedGenericClassTypeSignature;
}
private void ensureGenericSignatureUnpacked() {
if ((bitflag&UNPACKED_GENERIC_SIGNATURE)!=0) return;
bitflag|=UNPACKED_GENERIC_SIGNATURE;
if (!getResolvedTypeX().getWorld().isInJava5Mode()) return;
Signature.ClassSignature cSig = getGenericClassTypeSignature();
if (cSig != null) {
formalsForResolution = cSig.formalTypeParameters;
if (isNestedClass()) {
// we have to find any type variables from the outer type before proceeding with resolution.
Signature.FormalTypeParameter[] extraFormals = getFormalTypeParametersFromOuterClass();
if (extraFormals.length > 0) {
List allFormals = new ArrayList();
for (int i = 0; i < formalsForResolution.length; i++) {
allFormals.add(formalsForResolution[i]);
}
for (int i = 0; i < extraFormals.length; i++) {
allFormals.add(extraFormals[i]);
}
formalsForResolution = new Signature.FormalTypeParameter[allFormals.size()];
allFormals.toArray(formalsForResolution);
}
}
Signature.ClassTypeSignature superSig = cSig.superclassSignature;
try {
// this.superClass =
// BcelGenericSignatureToTypeXConverter.classTypeSignature2TypeX(
// superSig, formalsForResolution, getResolvedTypeX().getWorld());
ResolvedType rt =
BcelGenericSignatureToTypeXConverter.classTypeSignature2TypeX(
superSig, formalsForResolution, getResolvedTypeX().getWorld());
this.superclassSignature = rt.getSignature();
this.superclassName = rt.getName();
} catch (GenericSignatureFormatException e) {
// development bug, fail fast with good info
throw new IllegalStateException(
"While determining the generic superclass of " + this.className
+ " with generic signature " + getDeclaredGenericSignature()+ " the following error was detected: "
+ e.getMessage());
}
// this.interfaces = new ResolvedType[cSig.superInterfaceSignatures.length];
this.interfaceSignatures = new String[cSig.superInterfaceSignatures.length];
for (int i = 0; i < cSig.superInterfaceSignatures.length; i++) {
try {
// this.interfaces[i] =
// BcelGenericSignatureToTypeXConverter.classTypeSignature2TypeX(
// cSig.superInterfaceSignatures[i],
// formalsForResolution,
// getResolvedTypeX().getWorld());
this.interfaceSignatures[i] =
BcelGenericSignatureToTypeXConverter.classTypeSignature2TypeX(
cSig.superInterfaceSignatures[i],
formalsForResolution,
getResolvedTypeX().getWorld()).getSignature();
} catch (GenericSignatureFormatException e) {
// development bug, fail fast with good info
throw new IllegalStateException(
"While determing the generic superinterfaces of " + this.className
+ " with generic signature " + getDeclaredGenericSignature() +" the following error was detected: "
+ e.getMessage());
}
}
}
if (isGeneric()) {
// update resolved typex to point at generic type not raw type.
ReferenceType genericType = (ReferenceType) this.resolvedTypeX.getGenericType();
//genericType.setSourceContext(this.resolvedTypeX.getSourceContext());
genericType.setStartPos(this.resolvedTypeX.getStartPos());
this.resolvedTypeX = genericType;
}
}
public Signature.FormalTypeParameter[] getAllFormals() {
ensureGenericSignatureUnpacked();
if (formalsForResolution == null) {
return new Signature.FormalTypeParameter[0];
} else {
return formalsForResolution;
}
}
private boolean isNestedClass() {
return className.indexOf('$') != -1;
}
private ReferenceType getOuterClass() {
if (!isNestedClass()) throw new IllegalStateException("Can't get the outer class of a non-nested type");
int lastDollar = className.lastIndexOf('$');
String superClassName = className.substring(0,lastDollar);
UnresolvedType outer = UnresolvedType.forName(superClassName);
return (ReferenceType) outer.resolve(getResolvedTypeX().getWorld());
}
private Signature.FormalTypeParameter[] getFormalTypeParametersFromOuterClass() {
List typeParameters = new ArrayList();
ReferenceType outer = getOuterClass();
ReferenceTypeDelegate outerDelegate = outer.getDelegate();
if (!(outerDelegate instanceof BcelObjectType)) {
throw new IllegalStateException("How come we're in BcelObjectType resolving an inner type of something that is NOT a BcelObjectType??");
}
BcelObjectType outerObjectType = (BcelObjectType) outerDelegate;
if (outerObjectType.isNestedClass()) {
Signature.FormalTypeParameter[] parentParams = outerObjectType.getFormalTypeParametersFromOuterClass();
for (int i = 0; i < parentParams.length; i++) {
typeParameters.add(parentParams[i]);
}
}
Signature.ClassSignature outerSig = outerObjectType.getGenericClassTypeSignature();
if (outerSig != null) {
for (int i = 0; i < outerSig.formalTypeParameters .length; i++) {
typeParameters.add(outerSig.formalTypeParameters[i]);
}
}
Signature.FormalTypeParameter[] ret = new Signature.FormalTypeParameter[typeParameters.size()];
typeParameters.toArray(ret);
return ret;
}
private void ensureGenericInfoProcessed() {
if ((bitflag & DISCOVERED_DECLARED_SIGNATURE)!=0) return;
bitflag |= DISCOVERED_DECLARED_SIGNATURE;
Attribute[] as = javaClass.getAttributes();
for (int i = 0; i < as.length && declaredSignature==null; i++) {
Attribute attribute = as[i];
if (attribute instanceof Signature) declaredSignature = ((Signature)attribute).getSignature();
}
if (declaredSignature!=null) isGenericType= (declaredSignature.charAt(0)=='<');
}
public boolean isGeneric() {
ensureGenericInfoProcessed();
return isGenericType;
}
public String toString() {
return (javaClass==null?"BcelObjectType":"BcelObjectTypeFor:"+className);
}
// --- state management
public void evictWeavingState() {
// Can't chuck all this away
if (getResolvedTypeX().getWorld().couldIncrementalCompileFollow()) return;
if (javaClass != null) {
// Force retrieval of any lazy information
ensureAnnotationsUnpacked();
ensureGenericInfoProcessed();
getDeclaredInterfaces();
getDeclaredFields();
getDeclaredMethods();
// The lazyClassGen is preserved for aspects - it exists to enable around advice
// inlining since the method will need 'injecting' into the affected class. If
// XnoInline is on, we can chuck away the lazyClassGen since it won't be required
// later.
if (getResolvedTypeX().getWorld().isXnoInline()) lazyClassGen=null;
// discard expensive bytecode array containing reweavable info
if (weaverState != null) {
weaverState.setReweavable(false);
weaverState.setUnwovenClassFileData(null);
}
for (int i = methods.length - 1; i >= 0; i--) methods[i].evictWeavingState();
for (int i = fields.length - 1; i >= 0; i--) fields[i].evictWeavingState();
javaClass = null;
// setSourceContext(SourceContextImpl.UNKNOWN_SOURCE_CONTEXT); // bit naughty
// interfaces=null; // force reinit - may get us the right instances!
// superClass=null;
}
}
public void weavingCompleted() {
hasBeenWoven = true;
if (getResolvedTypeX().getWorld().isRunMinimalMemory()) evictWeavingState();
if (getSourceContext()!=null && !getResolvedTypeX().isAspect()) getSourceContext().tidy();
}
// --- methods for testing
// for testing - if we have this attribute, return it - will return null if it doesnt know anything
public AjAttribute[] getAttributes(String name) {
List results = new ArrayList();
List l = BcelAttributes.readAjAttributes(javaClass.getClassName(),javaClass.getAttributes(), getResolvedTypeX().getSourceContext(),getResolvedTypeX().getWorld(),AjAttribute.WeaverVersionInfo.UNKNOWN);
for (Iterator iter = l.iterator(); iter.hasNext();) {
AjAttribute element = (AjAttribute) iter.next();
if (element.getNameString().equals(name)) results.add(element);
}
if (results.size()>0) {
return (AjAttribute[])results.toArray(new AjAttribute[]{});
}
return null;
}
// for testing - use with the method above - this returns *all* including those that are not Aj attributes
public String[] getAttributeNames() {
Attribute[] as = javaClass.getAttributes();
String[] strs = new String[as.length];
for (int j = 0; j < as.length; j++) {
strs[j] = as[j].getName();
}
return strs;
}
// for testing
public void addPointcutDefinition(ResolvedPointcutDefinition d) {
bitflag|=DAMAGED;
int len = pointcuts.length;
ResolvedPointcutDefinition[] ret = new ResolvedPointcutDefinition[len+1];
System.arraycopy(pointcuts, 0, ret, 0, len);
ret[len] = d;
pointcuts = ret;
}
public boolean hasBeenWoven() {
return hasBeenWoven;
}
}
|
149,560 |
Bug 149560 [@AspectJ] Incorrect weaving of static initialization join point
|
This error occurs if static initialization of one aspect class is woven with an advice from another aspect. It worked fine in version 1.5.0 - see the decompiled code snippet: static { Object obj = new Factory("ItoMonitoringAspect.java", Class.forName("cz.kb.usermanagement.ito.ItoMonitoringAspect")); ajc$tjp_0 = ((Factory) (obj)).makeSJP("staticinitialization", ((Factory) (obj)).makeInitializerSig("8", "cz.kb.usermanagement.ito.ItoMonitoringAspect"), 0); obj = Factory.makeJP(ajc$tjp_0, null, null); // the static initialization of this aspect class is deliberately woven using // advice from another aspect defined elsewhere. try { UserManagementLogAspect.aspectOf().beforeClassInit(((org.aspectj.lang.JoinPoint) (obj))); } catch(Throwable throwable) { if(throwable instanceof ExceptionInInitializerError) { throw (ExceptionInInitializerError)throwable; } else { UserManagementLogAspect.aspectOf().afterClassInit(); throw throwable; } } UserManagementLogAspect.aspectOf().afterClassInit(); // this line below was there when compiling using AspectJ 1.5.0 // but is missing in when using AJC 1.5.2. (Note: the line is, however, present if the static // initialization of this aspect class is NOT woven by advice from the other aspect). ajc$postClinit(); } As a result of the missing call to ajc$postClinit() the aspect instance is not created and it's method .aspectOf() throws org.aspectj.lang.NoAspectBoundException.
|
resolved fixed
|
945a257
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-08-22T15:22:06Z | 2006-07-04T10:46:40Z |
tests/bugs153/pr149560/AnnStyle.java
| |
149,560 |
Bug 149560 [@AspectJ] Incorrect weaving of static initialization join point
|
This error occurs if static initialization of one aspect class is woven with an advice from another aspect. It worked fine in version 1.5.0 - see the decompiled code snippet: static { Object obj = new Factory("ItoMonitoringAspect.java", Class.forName("cz.kb.usermanagement.ito.ItoMonitoringAspect")); ajc$tjp_0 = ((Factory) (obj)).makeSJP("staticinitialization", ((Factory) (obj)).makeInitializerSig("8", "cz.kb.usermanagement.ito.ItoMonitoringAspect"), 0); obj = Factory.makeJP(ajc$tjp_0, null, null); // the static initialization of this aspect class is deliberately woven using // advice from another aspect defined elsewhere. try { UserManagementLogAspect.aspectOf().beforeClassInit(((org.aspectj.lang.JoinPoint) (obj))); } catch(Throwable throwable) { if(throwable instanceof ExceptionInInitializerError) { throw (ExceptionInInitializerError)throwable; } else { UserManagementLogAspect.aspectOf().afterClassInit(); throw throwable; } } UserManagementLogAspect.aspectOf().afterClassInit(); // this line below was there when compiling using AspectJ 1.5.0 // but is missing in when using AJC 1.5.2. (Note: the line is, however, present if the static // initialization of this aspect class is NOT woven by advice from the other aspect). ajc$postClinit(); } As a result of the missing call to ajc$postClinit() the aspect instance is not created and it's method .aspectOf() throws org.aspectj.lang.NoAspectBoundException.
|
resolved fixed
|
945a257
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-08-22T15:22:06Z | 2006-07-04T10:46:40Z |
tests/bugs153/pr149560/CodeStyle.java
| |
149,560 |
Bug 149560 [@AspectJ] Incorrect weaving of static initialization join point
|
This error occurs if static initialization of one aspect class is woven with an advice from another aspect. It worked fine in version 1.5.0 - see the decompiled code snippet: static { Object obj = new Factory("ItoMonitoringAspect.java", Class.forName("cz.kb.usermanagement.ito.ItoMonitoringAspect")); ajc$tjp_0 = ((Factory) (obj)).makeSJP("staticinitialization", ((Factory) (obj)).makeInitializerSig("8", "cz.kb.usermanagement.ito.ItoMonitoringAspect"), 0); obj = Factory.makeJP(ajc$tjp_0, null, null); // the static initialization of this aspect class is deliberately woven using // advice from another aspect defined elsewhere. try { UserManagementLogAspect.aspectOf().beforeClassInit(((org.aspectj.lang.JoinPoint) (obj))); } catch(Throwable throwable) { if(throwable instanceof ExceptionInInitializerError) { throw (ExceptionInInitializerError)throwable; } else { UserManagementLogAspect.aspectOf().afterClassInit(); throw throwable; } } UserManagementLogAspect.aspectOf().afterClassInit(); // this line below was there when compiling using AspectJ 1.5.0 // but is missing in when using AJC 1.5.2. (Note: the line is, however, present if the static // initialization of this aspect class is NOT woven by advice from the other aspect). ajc$postClinit(); } As a result of the missing call to ajc$postClinit() the aspect instance is not created and it's method .aspectOf() throws org.aspectj.lang.NoAspectBoundException.
|
resolved fixed
|
945a257
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-08-22T15:22:06Z | 2006-07-04T10:46:40Z |
tests/src/org/aspectj/systemtest/ajc153/Ajc153Tests.java
|
/*******************************************************************************
* Copyright (c) 2006 IBM
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Andy Clement - initial API and implementation
*******************************************************************************/
package org.aspectj.systemtest.ajc153;
import java.io.File;
import junit.framework.Test;
import org.aspectj.testing.Utils;
import org.aspectj.testing.XMLBasedAjcTestCase;
import org.aspectj.weaver.bcel.Utility;
public class Ajc153Tests extends org.aspectj.testing.XMLBasedAjcTestCase {
//public void testGenericsProblem_pr151978() { runTest("generics problem");}
//public void testMissingLineNumbersInStacktraceBefore_pr145442() { runTest("missing line numbers in stacktrace before");}
//public void testMissingLineNumbersInStacktraceAfter_pr145442() { runTest("missing line numbers in stacktrace after");}
//public void testMissingLineNumbersInStacktraceAround_pr145442() { runTest("missing line numbers in stacktrace around");}
// public void testArgnamesAndJavac_pr148381() { runTest("argNames and javac");}
// public void testCFlowXMLAspectLTW_pr149096() { runTest("cflow xml concrete aspect"); }
// public void testAmbiguousBinding_pr121805() { runTest("ambiguous binding");}
public void 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 testVisibilityProblem_pr149071() { runTest("visibility problem");}
// public void testAdviceNotWovenAspectPath_pr147841() { runTest("advice not woven on aspectpath");}
public void testGenericSignatures_pr148409() { runTest("generic signature problem"); }
// public void testBrokenIfArgsCflowAtAj_pr145018() { runTest("ataj crashing with cflow, if and args");}
public void testCantFindType_pr149322_01() {runTest("can't find type on interface call 1");}
public void testCantFindType_pr149322_02() {runTest("can't find type on interface call 2");}
public void testCantFindType_pr149322_03() {runTest("can't find type on interface call 3");}
public void 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 static Test suite() {
return XMLBasedAjcTestCase.loadSuite(Ajc153Tests.class);
}
protected File getSpecFile() {
return new File("../tests/src/org/aspectj/systemtest/ajc153/ajc153.xml");
}
}
|
149,560 |
Bug 149560 [@AspectJ] Incorrect weaving of static initialization join point
|
This error occurs if static initialization of one aspect class is woven with an advice from another aspect. It worked fine in version 1.5.0 - see the decompiled code snippet: static { Object obj = new Factory("ItoMonitoringAspect.java", Class.forName("cz.kb.usermanagement.ito.ItoMonitoringAspect")); ajc$tjp_0 = ((Factory) (obj)).makeSJP("staticinitialization", ((Factory) (obj)).makeInitializerSig("8", "cz.kb.usermanagement.ito.ItoMonitoringAspect"), 0); obj = Factory.makeJP(ajc$tjp_0, null, null); // the static initialization of this aspect class is deliberately woven using // advice from another aspect defined elsewhere. try { UserManagementLogAspect.aspectOf().beforeClassInit(((org.aspectj.lang.JoinPoint) (obj))); } catch(Throwable throwable) { if(throwable instanceof ExceptionInInitializerError) { throw (ExceptionInInitializerError)throwable; } else { UserManagementLogAspect.aspectOf().afterClassInit(); throw throwable; } } UserManagementLogAspect.aspectOf().afterClassInit(); // this line below was there when compiling using AspectJ 1.5.0 // but is missing in when using AJC 1.5.2. (Note: the line is, however, present if the static // initialization of this aspect class is NOT woven by advice from the other aspect). ajc$postClinit(); } As a result of the missing call to ajc$postClinit() the aspect instance is not created and it's method .aspectOf() throws org.aspectj.lang.NoAspectBoundException.
|
resolved fixed
|
945a257
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-08-22T15:22:06Z | 2006-07-04T10:46:40Z |
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
}
/**
* 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 only one but reports "+EclipseFactory.debug_mungerCount,EclipseFactory.debug_mungerCount==1);
alter("PR141956","inc1");
build("PR141956");
assertTrue("Should be only one but reports "+EclipseFactory.debug_mungerCount,EclipseFactory.debug_mungerCount==1);
alter("PR141956","inc1");
build("PR141956");
assertTrue("Should be only one but reports "+EclipseFactory.debug_mungerCount,EclipseFactory.debug_mungerCount==1);
alter("PR141956","inc1");
build("PR141956");
assertTrue("Should be only one but reports "+EclipseFactory.debug_mungerCount,EclipseFactory.debug_mungerCount==1);
}
// 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 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();
assertTrue("expected the handler to be an IMessageHolder but wasn't ",
handler instanceof IMessageHolder);
IMessage[] msgs = ((IMessageHolder)AjdeManager.getMessageHandler()).getMessages(null,true);
assertTrue("There should be no messages but I found: "+msgs.length,msgs.length==0);
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");
checkWasFullBuild();
warnings = MyTaskListManager.getWarningMessages();
assertTrue("There should be no warnings after adding a whitespace:\n"
+warnings,warnings.isEmpty());
}
// --- 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.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);
}
}
|
149,560 |
Bug 149560 [@AspectJ] Incorrect weaving of static initialization join point
|
This error occurs if static initialization of one aspect class is woven with an advice from another aspect. It worked fine in version 1.5.0 - see the decompiled code snippet: static { Object obj = new Factory("ItoMonitoringAspect.java", Class.forName("cz.kb.usermanagement.ito.ItoMonitoringAspect")); ajc$tjp_0 = ((Factory) (obj)).makeSJP("staticinitialization", ((Factory) (obj)).makeInitializerSig("8", "cz.kb.usermanagement.ito.ItoMonitoringAspect"), 0); obj = Factory.makeJP(ajc$tjp_0, null, null); // the static initialization of this aspect class is deliberately woven using // advice from another aspect defined elsewhere. try { UserManagementLogAspect.aspectOf().beforeClassInit(((org.aspectj.lang.JoinPoint) (obj))); } catch(Throwable throwable) { if(throwable instanceof ExceptionInInitializerError) { throw (ExceptionInInitializerError)throwable; } else { UserManagementLogAspect.aspectOf().afterClassInit(); throw throwable; } } UserManagementLogAspect.aspectOf().afterClassInit(); // this line below was there when compiling using AspectJ 1.5.0 // but is missing in when using AJC 1.5.2. (Note: the line is, however, present if the static // initialization of this aspect class is NOT woven by advice from the other aspect). ajc$postClinit(); } As a result of the missing call to ajc$postClinit() the aspect instance is not created and it's method .aspectOf() throws org.aspectj.lang.NoAspectBoundException.
|
resolved fixed
|
945a257
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-08-22T15:22:06Z | 2006-07-04T10:46:40Z |
weaver/src/org/aspectj/weaver/bcel/BcelPerClauseAspectAdder.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.weaver.bcel;
import org.aspectj.apache.bcel.Constants;
import org.aspectj.apache.bcel.generic.ATHROW;
import org.aspectj.apache.bcel.generic.BranchInstruction;
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.NOP;
import org.aspectj.apache.bcel.generic.ObjectType;
import org.aspectj.apache.bcel.generic.POP;
import org.aspectj.apache.bcel.generic.PUSH;
import org.aspectj.apache.bcel.generic.ReferenceType;
import org.aspectj.apache.bcel.generic.Type;
import org.aspectj.weaver.AjAttribute;
import org.aspectj.weaver.AjcMemberMaker;
import org.aspectj.weaver.Member;
import org.aspectj.weaver.NameMangler;
import org.aspectj.weaver.ResolvedMember;
import org.aspectj.weaver.ResolvedType;
import org.aspectj.weaver.UnresolvedType;
import org.aspectj.weaver.patterns.PerClause;
/**
* Adds aspectOf, hasAspect etc to the annotation defined aspects
*
* @author <a href="mailto:alex AT gnilux DOT com">Alexandre Vasseur</a>
*/
public class BcelPerClauseAspectAdder extends BcelTypeMunger {
private PerClause.Kind kind;
private boolean hasGeneratedInner = false;
public BcelPerClauseAspectAdder(ResolvedType aspect, PerClause.Kind kind) {
super(null,aspect);
this.kind = kind;
if (kind == PerClause.SINGLETON || kind == PerClause.PERTYPEWITHIN || kind == PerClause.PERCFLOW) {
// no inner needed
hasGeneratedInner = true;
}
}
public boolean munge(BcelClassWeaver weaver) {
LazyClassGen gen = weaver.getLazyClassGen();
doAggressiveInner(gen);
// Only munge the aspect type
if (!gen.getType().equals(aspectType)) {
return false;
}
return doMunge(gen, true);
}
public boolean forceMunge(LazyClassGen gen, boolean checkAlreadyThere) {
doAggressiveInner(gen);
return doMunge(gen, checkAlreadyThere);
}
private void doAggressiveInner(LazyClassGen gen) {
// agressively generate the inner interface if any
// Note: we do so because of the bug #75442 that leads to have this interface implemented by all classes and not
// only those matched by the per clause, which fails under LTW since the very first class
// gets weaved and impl this interface that is still not defined.
if (!hasGeneratedInner) {
if (kind == PerClause.PEROBJECT) {//redundant test - see constructor, but safer
//inner class
UnresolvedType interfaceTypeX = AjcMemberMaker.perObjectInterfaceType(aspectType);
LazyClassGen interfaceGen = new LazyClassGen(
interfaceTypeX.getName(),
"java.lang.Object",
null,
Constants.ACC_INTERFACE + Constants.ACC_PUBLIC + Constants.ACC_ABSTRACT,
new String[0],
getWorld()
);
interfaceGen.addMethodGen(makeMethodGen(interfaceGen, AjcMemberMaker.perObjectInterfaceGet(aspectType)));
interfaceGen.addMethodGen(makeMethodGen(interfaceGen, AjcMemberMaker.perObjectInterfaceSet(aspectType)));
//not really an inner class of it but that does not matter, we pass back to the LTW
gen.addGeneratedInner(interfaceGen);
}
hasGeneratedInner = true;
}
}
private boolean doMunge(LazyClassGen gen, boolean checkAlreadyThere) {
if (checkAlreadyThere && hasPerClauseMembersAlready(gen)) {
return false;
}
generatePerClauseMembers(gen);
if (kind == PerClause.SINGLETON) {
generatePerSingletonAspectOfMethod(gen);
generatePerSingletonHasAspectMethod(gen);
generatePerSingletonAjcClinitMethod(gen);
} else if (kind == PerClause.PEROBJECT) {
generatePerObjectAspectOfMethod(gen);
generatePerObjectHasAspectMethod(gen);
generatePerObjectBindMethod(gen);
// these will be added by the PerObjectInterface munger that affects the type - pr144602
// generatePerObjectGetSetMethods(gen);
} else if (kind == PerClause.PERCFLOW) {
generatePerCflowAspectOfMethod(gen);
generatePerCflowHasAspectMethod(gen);
generatePerCflowPushMethod(gen);
generatePerCflowAjcClinitMethod(gen);
} else if (kind == PerClause.PERTYPEWITHIN) {
generatePerTWAspectOfMethod(gen);
generatePerTWHasAspectMethod(gen);
generatePerTWGetInstanceMethod(gen);
generatePerTWCreateAspectInstanceMethod(gen);
} else {
throw new Error("should not happen - not such kind " + kind.getName());
}
return true;
}
public ResolvedMember getMatchingSyntheticMember(Member member) {
return null;
}
public ResolvedMember getSignature() {
return null;
}
public boolean matches(ResolvedType onType) {
//we cannot return onType.equals(aspectType)
//since we need to eagerly create the nested ajcMighHaveAspect interface on LTW
return true;
//return aspectType.equals(onType);
}
private boolean hasPerClauseMembersAlready(LazyClassGen classGen) {
ResolvedMember[] methods = classGen.getBcelObjectType().getDeclaredMethods();
for (int i = 0; i < methods.length; i++) {
ResolvedMember method = methods[i];
if ("aspectOf".equals(method.getName())) {
if ("()".equals(method.getParameterSignature()) && (kind == PerClause.SINGLETON || kind == PerClause.PERCFLOW)) {
return true;
} else if ("(Ljava/lang/Object;)".equals(method.getParameterSignature()) && kind == PerClause.PEROBJECT) {
return true;
} else if ("(Ljava/lang/Class;)".equals(method.getParameterSignature()) && kind == PerClause.PERTYPEWITHIN) {
return true;
}
}
}
return false;
}
private void generatePerClauseMembers(LazyClassGen classGen) {
//FIXME Alex handle when field already there - or handle it with / similar to isAnnotationDefinedAspect()
// for that use aspectType and iterate on the fields.
//FIXME Alex percflowX is not using this one but AJ code style does generate it so..
ResolvedMember failureFieldInfo = AjcMemberMaker.initFailureCauseField(aspectType);
classGen.addField(makeFieldGen(classGen, failureFieldInfo).getField(), null);
if (kind == PerClause.SINGLETON) {
ResolvedMember perSingletonFieldInfo = AjcMemberMaker.perSingletonField(aspectType);
classGen.addField(makeFieldGen(classGen, perSingletonFieldInfo).getField(), null);
// pr144602 - don't need to do this, PerObjectInterface munger will do it
// } else if (kind == PerClause.PEROBJECT) {
// ResolvedMember perObjectFieldInfo = AjcMemberMaker.perObjectField(aspectType, aspectType);
// classGen.addField(makeFieldGen(classGen, perObjectFieldInfo).getField(), null);
// // if lazy generation of the inner interface MayHaveAspect works on LTW (see previous note)
// // it should be done here.
} else if (kind == PerClause.PERCFLOW) {
ResolvedMember perCflowFieldInfo = AjcMemberMaker.perCflowField(aspectType);
classGen.addField(makeFieldGen(classGen, perCflowFieldInfo).getField(), null);
} else if (kind == PerClause.PERTYPEWITHIN) {
ResolvedMember perTypeWithinForField = AjcMemberMaker.perTypeWithinWithinTypeField(aspectType, aspectType);
classGen.addField(makeFieldGen(classGen, perTypeWithinForField).getField(), null);
// } else {
// throw new Error("Should not happen - no such kind " + kind.toString());
}
}
private void generatePerSingletonAspectOfMethod(LazyClassGen classGen) {
InstructionFactory factory = classGen.getFactory();
LazyMethodGen method = makeMethodGen(classGen, AjcMemberMaker.perSingletonAspectOfMethod(aspectType));
flagAsSynthetic(method, false);
classGen.addMethodGen(method);
InstructionList il = method.getBody();
il.append(Utility.createGet(factory, AjcMemberMaker.perSingletonField(aspectType)));
BranchInstruction ifNotNull = InstructionFactory.createBranchInstruction(Constants.IFNONNULL, null);
il.append(ifNotNull);
il.append(factory.createNew(AjcMemberMaker.NO_ASPECT_BOUND_EXCEPTION.getName()));
il.append(InstructionConstants.DUP);
il.append(new PUSH(classGen.getConstantPoolGen(), aspectType.getName()));
il.append(Utility.createGet(factory, AjcMemberMaker.initFailureCauseField(aspectType)));
il.append(factory.createInvoke(AjcMemberMaker.NO_ASPECT_BOUND_EXCEPTION.getName(), "<init>", Type.VOID, new Type[] { Type.STRING, new ObjectType("java.lang.Throwable") }, Constants.INVOKESPECIAL));
il.append(InstructionConstants.ATHROW);
InstructionHandle ifElse = il.append(Utility.createGet(factory, AjcMemberMaker.perSingletonField(aspectType)));
il.append(InstructionFactory.createReturn(Type.OBJECT));
ifNotNull.setTarget(ifElse);
}
private void generatePerSingletonHasAspectMethod(LazyClassGen classGen) {
InstructionFactory factory = classGen.getFactory();
LazyMethodGen method = makeMethodGen(classGen, AjcMemberMaker.perSingletonHasAspectMethod(aspectType));
flagAsSynthetic(method, false);
classGen.addMethodGen(method);
InstructionList il = method.getBody();
il.append(Utility.createGet(factory, AjcMemberMaker.perSingletonField(aspectType)));
BranchInstruction ifNull = InstructionFactory.createBranchInstruction(Constants.IFNULL, null);
il.append(ifNull);
il.append(new PUSH(classGen.getConstantPoolGen(), true));
il.append(InstructionFactory.createReturn(Type.INT));
InstructionHandle ifElse = il.append(new PUSH(classGen.getConstantPoolGen(), false));
il.append(InstructionFactory.createReturn(Type.INT));
ifNull.setTarget(ifElse);
}
private void generatePerSingletonAjcClinitMethod(LazyClassGen classGen) {
InstructionFactory factory = classGen.getFactory();
LazyMethodGen method = makeMethodGen(classGen, AjcMemberMaker.ajcPostClinitMethod(aspectType));
flagAsSynthetic(method, true);
classGen.addMethodGen(method);
InstructionList il = method.getBody();
il.append(factory.createNew(aspectType.getName()));
il.append(InstructionConstants.DUP);
il.append(factory.createInvoke(aspectType.getName(), "<init>", Type.VOID, Type.NO_ARGS, Constants.INVOKESPECIAL));
il.append(Utility.createSet(factory, AjcMemberMaker.perSingletonField(aspectType)));
il.append(InstructionFactory.createReturn(Type.VOID));
// patch <clinit> to delegate to ajc$postClinit at the end
LazyMethodGen clinit = classGen.getStaticInitializer();
il = new InstructionList();
InstructionHandle tryStart = il.append(factory.createInvoke(aspectType.getName(), NameMangler.AJC_POST_CLINIT_NAME, Type.VOID, Type.NO_ARGS, Constants.INVOKESTATIC));
BranchInstruction tryEnd = InstructionFactory.createBranchInstruction(Constants.GOTO, null);
il.append(tryEnd);
InstructionHandle handler = il.append(InstructionConstants.ASTORE_0);
il.append(InstructionConstants.ALOAD_0);
il.append(Utility.createSet(factory, AjcMemberMaker.initFailureCauseField(aspectType)));
il.append(InstructionFactory.createReturn(Type.VOID));
tryEnd.setTarget(il.getEnd());
// replace the original "return" with a "nop"
//TODO AV - a bit odd, looks like Bcel alters bytecode and has a IMPDEP1 in its representation
if (clinit.getBody().getEnd().getInstruction().getOpcode() == Constants.IMPDEP1) {
clinit.getBody().getEnd().getPrev().setInstruction(new NOP());
}
clinit.getBody().getEnd().setInstruction(new NOP());
clinit.getBody().append(il);
clinit.addExceptionHandler(
tryStart, handler, handler, new ObjectType("java.lang.Throwable"), false
);
}
private void generatePerObjectAspectOfMethod(LazyClassGen classGen) {
InstructionFactory factory = classGen.getFactory();
ReferenceType interfaceType = (ReferenceType) BcelWorld.makeBcelType(AjcMemberMaker.perObjectInterfaceType(aspectType));
LazyMethodGen method = makeMethodGen(classGen, AjcMemberMaker.perObjectAspectOfMethod(aspectType));
flagAsSynthetic(method, false);
classGen.addMethodGen(method);
InstructionList il = method.getBody();
il.append(InstructionConstants.ALOAD_0);
il.append(factory.createInstanceOf(interfaceType));
BranchInstruction ifEq = InstructionFactory.createBranchInstruction(Constants.IFEQ, null);
il.append(ifEq);
il.append(InstructionConstants.ALOAD_0);
il.append(factory.createCheckCast(interfaceType));
il.append(Utility.createInvoke(factory, Constants.INVOKEINTERFACE, AjcMemberMaker.perObjectInterfaceGet(aspectType)));
il.append(InstructionConstants.DUP);
BranchInstruction ifNull = InstructionFactory.createBranchInstruction(Constants.IFNULL, null);
il.append(ifNull);
il.append(InstructionFactory.createReturn(BcelWorld.makeBcelType(aspectType)));
InstructionHandle ifNullElse = il.append(new POP());
ifNull.setTarget(ifNullElse);
InstructionHandle ifEqElse = il.append(factory.createNew(AjcMemberMaker.NO_ASPECT_BOUND_EXCEPTION.getName()));
ifEq.setTarget(ifEqElse);
il.append(InstructionConstants.DUP);
il.append(factory.createInvoke(AjcMemberMaker.NO_ASPECT_BOUND_EXCEPTION.getName(), "<init>", Type.VOID, Type.NO_ARGS, Constants.INVOKESPECIAL));
il.append(new ATHROW());
}
private void generatePerObjectHasAspectMethod(LazyClassGen classGen) {
InstructionFactory factory = classGen.getFactory();
ReferenceType interfaceType = (ReferenceType) BcelWorld.makeBcelType(AjcMemberMaker.perObjectInterfaceType(aspectType));
LazyMethodGen method = makeMethodGen(classGen, AjcMemberMaker.perObjectHasAspectMethod(aspectType));
flagAsSynthetic(method, false);
classGen.addMethodGen(method);
InstructionList il = method.getBody();
il.append(InstructionConstants.ALOAD_0);
il.append(factory.createInstanceOf(interfaceType));
BranchInstruction ifEq = InstructionFactory.createBranchInstruction(Constants.IFEQ, null);
il.append(ifEq);
il.append(InstructionConstants.ALOAD_0);
il.append(factory.createCheckCast(interfaceType));
il.append(Utility.createInvoke(factory, Constants.INVOKEINTERFACE, AjcMemberMaker.perObjectInterfaceGet(aspectType)));
BranchInstruction ifNull = InstructionFactory.createBranchInstruction(Constants.IFNULL, null);
il.append(ifNull);
il.append(InstructionConstants.ICONST_1);
il.append(InstructionFactory.createReturn(Type.INT));
InstructionHandle ifEqElse = il.append(InstructionConstants.ICONST_0);
ifEq.setTarget(ifEqElse);
ifNull.setTarget(ifEqElse);
il.append(InstructionFactory.createReturn(Type.INT));
}
private void generatePerObjectBindMethod(LazyClassGen classGen) {
InstructionFactory factory = classGen.getFactory();
ReferenceType interfaceType = (ReferenceType) BcelWorld.makeBcelType(AjcMemberMaker.perObjectInterfaceType(aspectType));
LazyMethodGen method = makeMethodGen(classGen, AjcMemberMaker.perObjectBind(aspectType));
flagAsSynthetic(method, true);
classGen.addMethodGen(method);
InstructionList il = method.getBody();
il.append(InstructionConstants.ALOAD_0);
il.append(factory.createInstanceOf(interfaceType));
BranchInstruction ifEq = InstructionFactory.createBranchInstruction(Constants.IFEQ, null);
il.append(ifEq);
il.append(InstructionConstants.ALOAD_0);
il.append(factory.createCheckCast(interfaceType));
il.append(Utility.createInvoke(factory, Constants.INVOKEINTERFACE, AjcMemberMaker.perObjectInterfaceGet(aspectType)));
BranchInstruction ifNonNull = InstructionFactory.createBranchInstruction(Constants.IFNONNULL, null);
il.append(ifNonNull);
il.append(InstructionConstants.ALOAD_0);
il.append(factory.createCheckCast(interfaceType));
il.append(factory.createNew(aspectType.getName()));
il.append(InstructionConstants.DUP);
il.append(factory.createInvoke(aspectType.getName(), "<init>", Type.VOID, Type.NO_ARGS, Constants.INVOKESPECIAL));
il.append(Utility.createInvoke(factory, Constants.INVOKEINTERFACE, AjcMemberMaker.perObjectInterfaceSet(aspectType)));
InstructionHandle end = il.append(InstructionFactory.createReturn(Type.VOID));
ifEq.setTarget(end);
ifNonNull.setTarget(end);
}
private void generatePerObjectGetSetMethods(LazyClassGen classGen) {
InstructionFactory factory = classGen.getFactory();
LazyMethodGen methodGet = makeMethodGen(classGen, AjcMemberMaker.perObjectInterfaceGet(aspectType));
flagAsSynthetic(methodGet, true);
classGen.addMethodGen(methodGet);
InstructionList ilGet = methodGet.getBody();
ilGet = new InstructionList();
ilGet.append(InstructionConstants.ALOAD_0);
ilGet.append(Utility.createGet(factory, AjcMemberMaker.perObjectField(aspectType, aspectType)));
ilGet.append(InstructionFactory.createReturn(Type.OBJECT));
LazyMethodGen methodSet = makeMethodGen(classGen, AjcMemberMaker.perObjectInterfaceSet(aspectType));
flagAsSynthetic(methodSet, true);
classGen.addMethodGen(methodSet);
InstructionList ilSet = methodSet.getBody();
ilSet = new InstructionList();
ilSet.append(InstructionConstants.ALOAD_0);
ilSet.append(InstructionConstants.ALOAD_1);
ilSet.append(Utility.createSet(factory, AjcMemberMaker.perObjectField(aspectType, aspectType)));
ilSet.append(InstructionFactory.createReturn(Type.VOID));
}
private void generatePerCflowAspectOfMethod(LazyClassGen classGen) {
InstructionFactory factory = classGen.getFactory();
LazyMethodGen method = makeMethodGen(classGen, AjcMemberMaker.perCflowAspectOfMethod(aspectType));
flagAsSynthetic(method, false);
classGen.addMethodGen(method);
InstructionList il = method.getBody();
il.append(Utility.createGet(factory, AjcMemberMaker.perCflowField(aspectType)));
il.append(Utility.createInvoke(factory, Constants.INVOKEVIRTUAL, AjcMemberMaker.cflowStackPeekInstance()));
il.append(factory.createCheckCast((ReferenceType)BcelWorld.makeBcelType(aspectType)));
il.append(InstructionFactory.createReturn(Type.OBJECT));
}
private void generatePerCflowHasAspectMethod(LazyClassGen classGen) {
InstructionFactory factory = classGen.getFactory();
LazyMethodGen method = makeMethodGen(classGen, AjcMemberMaker.perCflowHasAspectMethod(aspectType));
flagAsSynthetic(method, false);
classGen.addMethodGen(method);
InstructionList il = method.getBody();
il.append(Utility.createGet(factory, AjcMemberMaker.perCflowField(aspectType)));
il.append(Utility.createInvoke(factory, Constants.INVOKEVIRTUAL, AjcMemberMaker.cflowStackIsValid()));
il.append(InstructionFactory.createReturn(Type.INT));
}
private void generatePerCflowPushMethod(LazyClassGen classGen) {
InstructionFactory factory = classGen.getFactory();
LazyMethodGen method = makeMethodGen(classGen, AjcMemberMaker.perCflowPush(aspectType));
flagAsSynthetic(method, true);
classGen.addMethodGen(method);
InstructionList il = method.getBody();
il.append(Utility.createGet(factory, AjcMemberMaker.perCflowField(aspectType)));
il.append(factory.createNew(aspectType.getName()));
il.append(InstructionConstants.DUP);
il.append(factory.createInvoke(aspectType.getName(), "<init>", Type.VOID, Type.NO_ARGS, Constants.INVOKESPECIAL));
il.append(Utility.createInvoke(factory, Constants.INVOKEVIRTUAL, AjcMemberMaker.cflowStackPushInstance()));
il.append(InstructionFactory.createReturn(Type.VOID));
}
private void generatePerCflowAjcClinitMethod(LazyClassGen classGen) {
InstructionFactory factory = classGen.getFactory();
LazyMethodGen method = makeMethodGen(classGen, AjcMemberMaker.ajcPreClinitMethod(aspectType));
flagAsSynthetic(method, true);
classGen.addMethodGen(method);
InstructionList il = method.getBody();
il.append(factory.createNew(AjcMemberMaker.CFLOW_STACK_TYPE.getName()));
il.append(InstructionConstants.DUP);
il.append(factory.createInvoke(AjcMemberMaker.CFLOW_STACK_TYPE.getName(), "<init>", Type.VOID, Type.NO_ARGS, Constants.INVOKESPECIAL));
il.append(Utility.createSet(factory, AjcMemberMaker.perCflowField(aspectType)));
il.append(InstructionFactory.createReturn(Type.VOID));
// patch <clinit> to delegate to ajc$preClinit at the beginning
LazyMethodGen clinit = classGen.getStaticInitializer();
il = new InstructionList();
il.append(factory.createInvoke(aspectType.getName(), NameMangler.AJC_PRE_CLINIT_NAME, Type.VOID, Type.NO_ARGS, Constants.INVOKESTATIC));
clinit.getBody().insert(il);
}
private void generatePerTWAspectOfMethod(LazyClassGen classGen) {
InstructionFactory factory = classGen.getFactory();
LazyMethodGen method = makeMethodGen(classGen, AjcMemberMaker.perTypeWithinAspectOfMethod(aspectType,classGen.getWorld().isInJava5Mode()));
flagAsSynthetic(method, false);
classGen.addMethodGen(method);
InstructionList il = method.getBody();
InstructionHandle tryStart = il.append(InstructionConstants.ALOAD_0);
il.append(Utility.createInvoke(
factory,
Constants.INVOKESTATIC,
AjcMemberMaker.perTypeWithinGetInstance(aspectType)
));
il.append(InstructionConstants.ASTORE_1);
il.append(InstructionConstants.ALOAD_1);
BranchInstruction ifNonNull = InstructionFactory.createBranchInstruction(Constants.IFNONNULL, null);
il.append(ifNonNull);
il.append(factory.createNew(AjcMemberMaker.NO_ASPECT_BOUND_EXCEPTION.getName()));
il.append(InstructionConstants.DUP);
il.append(new PUSH(classGen.getConstantPoolGen(), aspectType.getName()));
il.append(InstructionConstants.ACONST_NULL);
il.append(factory.createInvoke(AjcMemberMaker.NO_ASPECT_BOUND_EXCEPTION.getName(), "<init>", Type.VOID, new Type[] { Type.STRING, new ObjectType("java.lang.Throwable") }, Constants.INVOKESPECIAL));
il.append(InstructionConstants.ATHROW);
InstructionHandle ifElse = il.append(InstructionConstants.ALOAD_1);
ifNonNull.setTarget(ifElse);
il.append(InstructionFactory.createReturn(Type.OBJECT));
InstructionHandle handler = il.append(InstructionConstants.ASTORE_1);
il.append(factory.createNew(AjcMemberMaker.NO_ASPECT_BOUND_EXCEPTION.getName()));
il.append(InstructionConstants.DUP);
il.append(factory.createInvoke(AjcMemberMaker.NO_ASPECT_BOUND_EXCEPTION.getName(), "<init>", Type.VOID, Type.NO_ARGS, Constants.INVOKESPECIAL));
il.append(InstructionConstants.ATHROW);
method.addExceptionHandler(
tryStart, handler.getPrev(), handler, new ObjectType("java.lang.Exception"), false
);
}
private void generatePerTWHasAspectMethod(LazyClassGen classGen) {
InstructionFactory factory = classGen.getFactory();
LazyMethodGen method = makeMethodGen(classGen, AjcMemberMaker.perTypeWithinHasAspectMethod(aspectType,classGen.getWorld().isInJava5Mode()));
flagAsSynthetic(method, false);
classGen.addMethodGen(method);
InstructionList il = method.getBody();
InstructionHandle tryStart = il.append(InstructionConstants.ALOAD_0);
il.append(Utility.createInvoke(
factory,
Constants.INVOKESTATIC,
AjcMemberMaker.perTypeWithinGetInstance(aspectType)
));
BranchInstruction ifNull = InstructionFactory.createBranchInstruction(Constants.IFNULL, null);
il.append(ifNull);
il.append(InstructionConstants.ICONST_1);
il.append(InstructionConstants.IRETURN);
InstructionHandle ifElse = il.append(InstructionConstants.ICONST_0);
ifNull.setTarget(ifElse);
il.append(InstructionConstants.IRETURN);
InstructionHandle handler = il.append(InstructionConstants.ASTORE_1);
il.append(InstructionConstants.ICONST_0);
il.append(InstructionConstants.IRETURN);
method.addExceptionHandler(
tryStart, handler.getPrev(), handler, new ObjectType("java.lang.Exception"), false
);
}
private void generatePerTWGetInstanceMethod(LazyClassGen classGen) {
InstructionFactory factory = classGen.getFactory();
LazyMethodGen method = makeMethodGen(classGen, AjcMemberMaker.perTypeWithinGetInstance(aspectType));
flagAsSynthetic(method, true);
classGen.addMethodGen(method);
InstructionList il = method.getBody();
InstructionHandle tryStart = il.append(InstructionConstants.ALOAD_0);
il.append(new PUSH(factory.getConstantPool(), NameMangler.perTypeWithinLocalAspectOf(aspectType)));
il.append(InstructionConstants.ACONST_NULL);//Class[] for "getDeclaredMethod"
il.append(factory.createInvoke(
"java/lang/Class",
"getDeclaredMethod",
Type.getType("Ljava/lang/reflect/Method;"),
new Type[]{Type.getType("Ljava/lang/String;"), Type.getType("[Ljava/lang/Class;")},
Constants.INVOKEVIRTUAL
));
il.append(InstructionConstants.ACONST_NULL);//Object for "invoke", static method
il.append(InstructionConstants.ACONST_NULL);//Object[] for "invoke", no arg
il.append(factory.createInvoke(
"java/lang/reflect/Method",
"invoke",
Type.OBJECT,
new Type[]{Type.getType("Ljava/lang/Object;"), Type.getType("[Ljava/lang/Object;")},
Constants.INVOKEVIRTUAL
));
il.append(factory.createCheckCast((ReferenceType) BcelWorld.makeBcelType(aspectType)));
il.append(InstructionConstants.ARETURN);
InstructionHandle handler = il.append(InstructionConstants.ASTORE_1);
il.append(InstructionConstants.ACONST_NULL);
il.append(InstructionConstants.ARETURN);
method.addExceptionHandler(
tryStart, handler.getPrev(), handler, new ObjectType("java.lang.Exception"), false
);
}
private void generatePerTWCreateAspectInstanceMethod(LazyClassGen classGen) {
InstructionFactory factory = classGen.getFactory();
LazyMethodGen method = makeMethodGen(classGen, AjcMemberMaker.perTypeWithinCreateAspectInstance(aspectType));
flagAsSynthetic(method, true);
classGen.addMethodGen(method);
InstructionList il = method.getBody();
il.append(factory.createNew(aspectType.getName()));
il.append(InstructionConstants.DUP);
il.append(factory.createInvoke(
aspectType.getName(), "<init>", Type.VOID, Type.NO_ARGS, Constants.INVOKESPECIAL
));
il.append(InstructionConstants.ASTORE_1);
il.append(InstructionConstants.ALOAD_1);
il.append(InstructionConstants.ALOAD_0);
il.append(Utility.createSet(
factory,
AjcMemberMaker.perTypeWithinWithinTypeField(aspectType, aspectType)
));
il.append(InstructionConstants.ALOAD_1);
il.append(InstructionConstants.ARETURN);
}
/**
* Add standard Synthetic (if wished) and AjSynthetic (always) attributes
* @param methodGen
* @param makeJavaSynthetic true if standard Synthetic attribute must be set as well (invisible to user)
*/
private static void flagAsSynthetic(LazyMethodGen methodGen, boolean makeJavaSynthetic) {
if (makeJavaSynthetic) {
methodGen.makeSynthetic();
}
methodGen.addAttribute(
BcelAttributes.bcelAttribute(
new AjAttribute.AjSynthetic(),
methodGen.getEnclosingClass().getConstantPoolGen()
)
);
}
// public boolean isLateTypeMunger() {
// return true;
//}
}
|
149,560 |
Bug 149560 [@AspectJ] Incorrect weaving of static initialization join point
|
This error occurs if static initialization of one aspect class is woven with an advice from another aspect. It worked fine in version 1.5.0 - see the decompiled code snippet: static { Object obj = new Factory("ItoMonitoringAspect.java", Class.forName("cz.kb.usermanagement.ito.ItoMonitoringAspect")); ajc$tjp_0 = ((Factory) (obj)).makeSJP("staticinitialization", ((Factory) (obj)).makeInitializerSig("8", "cz.kb.usermanagement.ito.ItoMonitoringAspect"), 0); obj = Factory.makeJP(ajc$tjp_0, null, null); // the static initialization of this aspect class is deliberately woven using // advice from another aspect defined elsewhere. try { UserManagementLogAspect.aspectOf().beforeClassInit(((org.aspectj.lang.JoinPoint) (obj))); } catch(Throwable throwable) { if(throwable instanceof ExceptionInInitializerError) { throw (ExceptionInInitializerError)throwable; } else { UserManagementLogAspect.aspectOf().afterClassInit(); throw throwable; } } UserManagementLogAspect.aspectOf().afterClassInit(); // this line below was there when compiling using AspectJ 1.5.0 // but is missing in when using AJC 1.5.2. (Note: the line is, however, present if the static // initialization of this aspect class is NOT woven by advice from the other aspect). ajc$postClinit(); } As a result of the missing call to ajc$postClinit() the aspect instance is not created and it's method .aspectOf() throws org.aspectj.lang.NoAspectBoundException.
|
resolved fixed
|
945a257
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-08-22T15:22:06Z | 2006-07-04T10:46: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"
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;
}
}
|
150,271 |
Bug 150271 Allow multiple levels of LTW information
|
It would be nice if basic information about load-time weaving (what version of AspectJ is being used, what loaders are doing weaving and what configuration is being used) was available without all of the -verbose information listing of all classes woven or not woven. It's also unfortunate that the flags for weaving level are 2 quite different ones: -Daj.weaving.verbose -Dorg.aspectj.weaver.showWeaveInfo Why not something like -Dorg.aspectj.weaver.level=[none|summary|info|verbose] summary: just what configuration is used info: list affected join points etc. (like showWeaveInfo) verbose: all (like verbose now)
|
resolved fixed
|
8549d86
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-08-23T11:52:22Z | 2006-07-11T15:00:00Z |
loadtime/src/org/aspectj/weaver/loadtime/ClassLoaderWeavingAdaptor.java
|
/*******************************************************************************
* Copyright (c) 2005 Contributors.
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Eclipse Public License v1.0
* which accompanies this distribution and is available at
* http://eclipse.org/legal/epl-v10.html
*
* Contributors:
* Alexandre Vasseur initial implementation
* David Knibb weaving context enhancments
*******************************************************************************/
package org.aspectj.weaver.loadtime;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.URL;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Properties;
import java.util.StringTokenizer;
import org.aspectj.asm.IRelationship;
import org.aspectj.bridge.AbortException;
import org.aspectj.bridge.ISourceLocation;
import org.aspectj.util.LangUtil;
import org.aspectj.weaver.ICrossReferenceHandler;
import org.aspectj.weaver.Lint;
import org.aspectj.weaver.ResolvedType;
import org.aspectj.weaver.UnresolvedType;
import org.aspectj.weaver.World;
import org.aspectj.weaver.Lint.Kind;
import org.aspectj.weaver.bcel.BcelWeaver;
import org.aspectj.weaver.loadtime.definition.Definition;
import org.aspectj.weaver.loadtime.definition.DocumentParser;
import org.aspectj.weaver.ltw.LTWWorld;
import org.aspectj.weaver.patterns.PatternParser;
import org.aspectj.weaver.patterns.TypePattern;
import org.aspectj.weaver.tools.GeneratedClassHandler;
import org.aspectj.weaver.tools.Trace;
import org.aspectj.weaver.tools.TraceFactory;
import org.aspectj.weaver.tools.WeavingAdaptor;
/**
* @author <a href="mailto:alex AT gnilux DOT com">Alexandre Vasseur</a>
*/
public class ClassLoaderWeavingAdaptor extends WeavingAdaptor {
private final static String AOP_XML = "META-INF/aop.xml";
private boolean initialized;
private List m_dumpTypePattern = new ArrayList();
private boolean m_dumpBefore = false;
private List m_includeTypePattern = new ArrayList();
private List m_excludeTypePattern = new ArrayList();
private List m_includeStartsWith = new ArrayList();
private List m_excludeStartsWith = new ArrayList();
private List m_aspectExcludeTypePattern = new ArrayList();
private List m_aspectExcludeStartsWith = new ArrayList();
private List m_aspectIncludeTypePattern = new ArrayList();
private List m_aspectIncludeStartsWith = new ArrayList();
private StringBuffer namespace;
private IWeavingContext weavingContext;
private static Trace trace = TraceFactory.getTraceFactory().getTrace(ClassLoaderWeavingAdaptor.class);
public ClassLoaderWeavingAdaptor() {
super();
if (trace.isTraceEnabled()) trace.enter("<init>",this);
if (trace.isTraceEnabled()) trace.exit("<init>");
}
/**
* We don't need a reference to the class loader and using it during
* construction can cause problems with recursion. It also makes sense
* to supply the weaving context during initialization to.
* @deprecated
*/
public ClassLoaderWeavingAdaptor(final ClassLoader deprecatedLoader, final IWeavingContext deprecatedContext) {
super();
if (trace.isTraceEnabled()) trace.enter("<init>",this,new Object[] { deprecatedLoader, deprecatedContext });
if (trace.isTraceEnabled()) trace.exit("<init>");
}
protected void initialize (final ClassLoader classLoader, IWeavingContext context) {
//super(null);// at this stage we don't have yet a generatedClassHandler to define to the VM the closures
if (initialized) return;
if (trace.isTraceEnabled()) trace.enter("initialize",this,new Object[] { classLoader, context });
this.weavingContext = context;
if (weavingContext == null) {
weavingContext = new DefaultWeavingContext(classLoader);
}
createMessageHandler();
this.generatedClassHandler = new GeneratedClassHandler() {
/**
* Callback when we need to define a Closure in the JVM
*
* @param name
* @param bytes
*/
public void acceptClass(String name, byte[] bytes) {
try {
if (shouldDump(name.replace('/', '.'), false)) {
dump(name, bytes, false);
}
} catch (Throwable throwable) {
throwable.printStackTrace();
}
defineClass(classLoader, name, bytes);// could be done lazily using the hook
}
};
List definitions = parseDefinitions(classLoader);
if (!isEnabled()) {
if (trace.isTraceEnabled()) trace.exit("initialize",false);
return;
}
bcelWorld = new LTWWorld(
classLoader, weavingContext, // TODO when the world works in terms of the context, we can remove the loader...
getMessageHandler(), new ICrossReferenceHandler() {
public void addCrossReference(ISourceLocation from, ISourceLocation to, IRelationship.Kind kind, boolean runtimeTest) {
;// for tools only
}
}
);
// //TODO this AJ code will call
// //org.aspectj.apache.bcel.Repository.setRepository(this);
// //ie set some static things
// //==> bogus as Bcel is expected to be
// org.aspectj.apache.bcel.Repository.setRepository(new ClassLoaderRepository(loader));
weaver = new BcelWeaver(bcelWorld);
// register the definitions
registerDefinitions(weaver, classLoader, definitions);
if (isEnabled()) {
//bcelWorld.setResolutionLoader(loader.getParent());//(ClassLoader)null);//
// after adding aspects
weaver.prepareForWeave();
}
else {
bcelWorld = null;
weaver = null;
}
initialized = true;
if (trace.isTraceEnabled()) trace.exit("initialize",isEnabled());
}
/**
* Load and cache the aop.xml/properties according to the classloader visibility rules
*
* @param weaver
* @param loader
*/
private List parseDefinitions(final ClassLoader loader) {
List definitions = new ArrayList();
try {
info("register classloader " + getClassLoaderName(loader));
//TODO av underoptimized: we will parse each XML once per CL that see it
//TODO av dev mode needed ? TBD -Daj5.def=...
if (ClassLoader.getSystemClassLoader().equals(loader)) {
String file = System.getProperty("aj5.def", null);
if (file != null) {
info("using (-Daj5.def) " + file);
definitions.add(DocumentParser.parse((new File(file)).toURL()));
}
}
String resourcePath = System.getProperty("org.aspectj.weaver.loadtime.configuration",AOP_XML);
StringTokenizer st = new StringTokenizer(resourcePath,";");
while(st.hasMoreTokens()){
Enumeration xmls = weavingContext.getResources(st.nextToken());
// System.out.println("? registerDefinitions: found-aop.xml=" + xmls.hasMoreElements() + ", loader=" + loader);
while (xmls.hasMoreElements()) {
URL xml = (URL) xmls.nextElement();
info("using configuration " + weavingContext.getFile(xml));
definitions.add(DocumentParser.parse(xml));
}
}
if (definitions.isEmpty()) {
disable();// will allow very fast skip in shouldWeave()
info("no configuration found. Disabling weaver for class loader " + getClassLoaderName(loader));
}
} catch (Exception e) {
disable();// will allow very fast skip in shouldWeave()
warn("parse definitions failed",e);
}
return definitions;
}
private void registerDefinitions(final BcelWeaver weaver, final ClassLoader loader, List definitions) {
try {
registerOptions(weaver, loader, definitions);
registerAspectExclude(weaver, loader, definitions);
registerAspectInclude(weaver, loader, definitions);
registerAspects(weaver, loader, definitions);
registerIncludeExclude(weaver, loader, definitions);
registerDump(weaver, loader, definitions);
} catch (Exception e) {
disable();// will allow very fast skip in shouldWeave()
warn("register definition failed",(e instanceof AbortException)?null:e);
}
}
private String getClassLoaderName (ClassLoader loader) {
return weavingContext.getClassLoaderName();
}
/**
* Configure the weaver according to the option directives
* TODO av - don't know if it is that good to reuse, since we only allow a small subset of options in LTW
*
* @param weaver
* @param loader
* @param definitions
*/
private void registerOptions(final BcelWeaver weaver, final ClassLoader loader, final List definitions) {
StringBuffer allOptions = new StringBuffer();
for (Iterator iterator = definitions.iterator(); iterator.hasNext();) {
Definition definition = (Definition) iterator.next();
allOptions.append(definition.getWeaverOptions()).append(' ');
}
Options.WeaverOption weaverOption = Options.parse(allOptions.toString(), loader, getMessageHandler());
// configure the weaver and world
// AV - code duplicates AspectJBuilder.initWorldAndWeaver()
World world = weaver.getWorld();
setMessageHandler(weaverOption.messageHandler);
world.setXlazyTjp(weaverOption.lazyTjp);
world.setXHasMemberSupportEnabled(weaverOption.hasMember);
world.setOptionalJoinpoints(weaverOption.optionalJoinpoints);
world.setPinpointMode(weaverOption.pinpoint);
weaver.setReweavableMode(weaverOption.notReWeavable);
world.performExtraConfiguration(weaverOption.xSet);
world.setXnoInline(weaverOption.noInline);
// AMC - autodetect as per line below, needed for AtAjLTWTests.testLTWUnweavable
world.setBehaveInJava5Way(LangUtil.is15VMOrGreater());
world.setAddSerialVerUID(weaverOption.addSerialVersionUID);
/* First load defaults */
bcelWorld.getLint().loadDefaultProperties();
/* Second overlay LTW defaults */
bcelWorld.getLint().adviceDidNotMatch.setKind(null);
/* Third load user file using -Xlintfile so that -Xlint wins */
if (weaverOption.lintFile != null) {
InputStream resource = null;
try {
resource = loader.getResourceAsStream(weaverOption.lintFile);
Exception failure = null;
if (resource != null) {
try {
Properties properties = new Properties();
properties.load(resource);
world.getLint().setFromProperties(properties);
} catch (IOException e) {
failure = e;
}
}
if (failure != null || resource == null) {
warn("Cannot access resource for -Xlintfile:"+weaverOption.lintFile,failure);
// world.getMessageHandler().handleMessage(new Message(
// "Cannot access resource for -Xlintfile:"+weaverOption.lintFile,
// IMessage.WARNING,
// failure,
// null));
}
} finally {
try { resource.close(); } catch (Throwable t) {;}
}
}
/* Fourth override with -Xlint */
if (weaverOption.lint != null) {
if (weaverOption.lint.equals("default")) {//FIXME should be AjBuildConfig.AJLINT_DEFAULT but yetanother deps..
bcelWorld.getLint().loadDefaultProperties();
} else {
bcelWorld.getLint().setAll(weaverOption.lint);
}
}
//TODO proceedOnError option
}
private void registerAspectExclude(final BcelWeaver weaver, final ClassLoader loader, final List definitions) {
String fastMatchInfo = null;
for (Iterator iterator = definitions.iterator(); iterator.hasNext();) {
Definition definition = (Definition) iterator.next();
for (Iterator iterator1 = definition.getAspectExcludePatterns().iterator(); iterator1.hasNext();) {
String exclude = (String) iterator1.next();
TypePattern excludePattern = new PatternParser(exclude).parseTypePattern();
m_aspectExcludeTypePattern.add(excludePattern);
fastMatchInfo = looksLikeStartsWith(exclude);
if (fastMatchInfo != null) {
m_aspectExcludeStartsWith.add(fastMatchInfo);
}
}
}
}
private void registerAspectInclude(final BcelWeaver weaver, final ClassLoader loader, final List definitions) {
String fastMatchInfo = null;
for (Iterator iterator = definitions.iterator(); iterator.hasNext();) {
Definition definition = (Definition) iterator.next();
for (Iterator iterator1 = definition.getAspectIncludePatterns().iterator(); iterator1.hasNext();) {
String include = (String) iterator1.next();
TypePattern includePattern = new PatternParser(include).parseTypePattern();
m_aspectIncludeTypePattern.add(includePattern);
fastMatchInfo = looksLikeStartsWith(include);
if (fastMatchInfo != null) {
m_aspectIncludeStartsWith.add(fastMatchInfo);
}
}
}
}
protected void lint (String name, String[] infos) {
Lint lint = bcelWorld.getLint();
Kind kind = lint.getLintKind(name);
kind.signal(infos,null,null);
}
public String getContextId () {
return weavingContext.getId();
}
/**
* Register the aspect, following include / exclude rules
*
* @param weaver
* @param loader
* @param definitions
*/
private void registerAspects(final BcelWeaver weaver, final ClassLoader loader, final List definitions) {
if (trace.isTraceEnabled()) trace.enter("registerAspects",this, new Object[] { weaver, loader, definitions} );
//TODO: the exclude aspect allow to exclude aspect defined upper in the CL hierarchy - is it what we want ??
// if not, review the getResource so that we track which resource is defined by which CL
//iterate aspectClassNames
//exclude if in any of the exclude list
for (Iterator iterator = definitions.iterator(); iterator.hasNext();) {
Definition definition = (Definition) iterator.next();
for (Iterator aspects = definition.getAspectClassNames().iterator(); aspects.hasNext();) {
String aspectClassName = (String) aspects.next();
if (acceptAspect(aspectClassName)) {
info("register aspect " + aspectClassName);
// System.err.println("? ClassLoaderWeavingAdaptor.registerAspects() aspectName=" + aspectClassName + ", loader=" + loader + ", bundle=" + weavingContext.getClassLoaderName());
/*ResolvedType aspect = */weaver.addLibraryAspect(aspectClassName);
//generate key for SC
if(namespace==null){
namespace=new StringBuffer(aspectClassName);
}else{
namespace = namespace.append(";"+aspectClassName);
}
}
else {
// warn("aspect excluded: " + aspectClassName);
lint("aspectExcludedByConfiguration", new String[] { aspectClassName, getClassLoaderName(loader) });
}
}
}
//iterate concreteAspects
//exclude if in any of the exclude list - note that the user defined name matters for that to happen
for (Iterator iterator = definitions.iterator(); iterator.hasNext();) {
Definition definition = (Definition) iterator.next();
for (Iterator aspects = definition.getConcreteAspects().iterator(); aspects.hasNext();) {
Definition.ConcreteAspect concreteAspect = (Definition.ConcreteAspect) aspects.next();
if (acceptAspect(concreteAspect.name)) {
ConcreteAspectCodeGen gen = new ConcreteAspectCodeGen(concreteAspect, weaver.getWorld());
if (!gen.validate()) {
error("Concrete-aspect '"+concreteAspect.name+"' could not be registered");
break;
}
this.generatedClassHandler.acceptClass(
concreteAspect.name,
gen.getBytes()
);
/*ResolvedType aspect = */weaver.addLibraryAspect(concreteAspect.name);
//generate key for SC
if(namespace==null){
namespace=new StringBuffer(concreteAspect.name);
}else{
namespace = namespace.append(";"+concreteAspect.name);
}
}
}
}
// System.out.println("ClassLoaderWeavingAdaptor.registerAspects() classloader=" + weavingContext.getClassLoaderName() + ", namespace=" + namespace);
/* We didn't register any aspects so disable the adaptor */
if (namespace == null) {
disable();
info("no aspects registered. Disabling weaver for class loader " + getClassLoaderName(loader));
}
if (trace.isTraceEnabled()) trace.exit("registerAspects",isEnabled());
}
/**
* Register the include / exclude filters
* We duplicate simple patterns in startWith filters that will allow faster matching without ResolvedType
*
* @param weaver
* @param loader
* @param definitions
*/
private void registerIncludeExclude(final BcelWeaver weaver, final ClassLoader loader, final List definitions) {
String fastMatchInfo = null;
for (Iterator iterator = definitions.iterator(); iterator.hasNext();) {
Definition definition = (Definition) iterator.next();
for (Iterator iterator1 = definition.getIncludePatterns().iterator(); iterator1.hasNext();) {
String include = (String) iterator1.next();
TypePattern includePattern = new PatternParser(include).parseTypePattern();
m_includeTypePattern.add(includePattern);
fastMatchInfo = looksLikeStartsWith(include);
if (fastMatchInfo != null) {
m_includeStartsWith.add(fastMatchInfo);
}
}
for (Iterator iterator1 = definition.getExcludePatterns().iterator(); iterator1.hasNext();) {
String exclude = (String) iterator1.next();
TypePattern excludePattern = new PatternParser(exclude).parseTypePattern();
m_excludeTypePattern.add(excludePattern);
fastMatchInfo = looksLikeStartsWith(exclude);
if (fastMatchInfo != null) {
m_excludeStartsWith.add(fastMatchInfo);
}
}
}
}
/**
* Checks if the type pattern can be handled as a startswith check
*
* TODO AV - enhance to support "char.sss" ie FQN direclty (match iff equals)
* we could also add support for "*..*charss" endsWith style?
*
* @param typePattern
* @return null if not possible, or the startWith sequence to test against
*/
private String looksLikeStartsWith(String typePattern) {
if (typePattern.indexOf('@') >= 0
|| typePattern.indexOf('+') >= 0
|| typePattern.indexOf(' ') >= 0
|| typePattern.charAt(typePattern.length()-1) != '*') {
return null;
}
// now must looks like with "charsss..*" or "cha.rss..*" etc
// note that "*" and "*..*" won't be fast matched
// and that "charsss.*" will not neither
int length = typePattern.length();
if (typePattern.endsWith("..*") && length > 3) {
if (typePattern.indexOf("..") == length-3 // no ".." before last sequence
&& typePattern.indexOf('*') == length-1) { // no "*" before last sequence
return typePattern.substring(0, length-2).replace('$', '.');
// ie "charsss." or "char.rss." etc
}
}
return null;
}
/**
* Register the dump filter
*
* @param weaver
* @param loader
* @param definitions
*/
private void registerDump(final BcelWeaver weaver, final ClassLoader loader, final List definitions) {
for (Iterator iterator = definitions.iterator(); iterator.hasNext();) {
Definition definition = (Definition) iterator.next();
for (Iterator iterator1 = definition.getDumpPatterns().iterator(); iterator1.hasNext();) {
String dump = (String) iterator1.next();
TypePattern pattern = new PatternParser(dump).parseTypePattern();
m_dumpTypePattern.add(pattern);
}
if (definition.shouldDumpBefore()) {
m_dumpBefore = true;
}
}
}
protected boolean accept(String className, byte[] bytes) {
// avoid ResolvedType if not needed
if (m_excludeTypePattern.isEmpty() && m_includeTypePattern.isEmpty()) {
return true;
}
// still try to avoid ResolvedType if we have simple patterns
String fastClassName = className.replace('/', '.').replace('$', '.');
for (int i = 0; i < m_excludeStartsWith.size(); i++) {
if (fastClassName.startsWith((String)m_excludeStartsWith.get(i))) {
return false;
}
}
/*
* Bug 120363
* If we have an exclude pattern that cannot be matched using "starts with"
* then we cannot fast accept
*/
if (m_excludeTypePattern.isEmpty()) {
boolean fastAccept = false;//defaults to false if no fast include
for (int i = 0; i < m_includeStartsWith.size(); i++) {
fastAccept = fastClassName.startsWith((String)m_includeStartsWith.get(i));
if (fastAccept) {
break;
}
}
}
// needs further analysis
// TODO AV - needs refactoring
// during LTW this calling resolve at that stage is BAD as we do have the bytecode from the classloader hook
// but still go thru resolve that will do a getResourcesAsStream on disk
// this is also problematic for jit stub which are not on disk - as often underlying infra
// does returns null or some other info for getResourceAsStream (f.e. WLS 9 CR248491)
// Instead I parse the given bytecode. But this also means it will be parsed again in
// new WeavingClassFileProvider() from WeavingAdaptor.getWovenBytes()...
ensureDelegateInitialized(className,bytes);
ResolvedType classInfo = delegateForCurrentClass.getResolvedTypeX();//BAD: weaver.getWorld().resolve(UnresolvedType.forName(className), true);
//exclude are "AND"ed
for (Iterator iterator = m_excludeTypePattern.iterator(); iterator.hasNext();) {
TypePattern typePattern = (TypePattern) iterator.next();
if (typePattern.matchesStatically(classInfo)) {
// exclude match - skip
return false;
}
}
//include are "OR"ed
boolean accept = true;//defaults to true if no include
for (Iterator iterator = m_includeTypePattern.iterator(); iterator.hasNext();) {
TypePattern typePattern = (TypePattern) iterator.next();
accept = typePattern.matchesStatically(classInfo);
if (accept) {
break;
}
// goes on if this include did not match ("OR"ed)
}
return accept;
}
//FIXME we don't use include/exclude of others aop.xml
//this can be nice but very dangerous as well to change that
private boolean acceptAspect(String aspectClassName) {
// avoid ResolvedType if not needed
if (m_aspectExcludeTypePattern.isEmpty() && m_aspectIncludeTypePattern.isEmpty()) {
return true;
}
// still try to avoid ResolvedType if we have simple patterns
// EXCLUDE: if one match then reject
String fastClassName = aspectClassName.replace('/', '.').replace('.', '$');
for (int i = 0; i < m_aspectExcludeStartsWith.size(); i++) {
if (fastClassName.startsWith((String)m_aspectExcludeStartsWith.get(i))) {
return false;
}
}
//INCLUDE: if one match then accept
for (int i = 0; i < m_aspectIncludeStartsWith.size(); i++) {
if (fastClassName.startsWith((String)m_aspectIncludeStartsWith.get(i))) {
return true;
}
}
// needs further analysis
ResolvedType classInfo = weaver.getWorld().resolve(UnresolvedType.forName(aspectClassName), true);
//exclude are "AND"ed
for (Iterator iterator = m_aspectExcludeTypePattern.iterator(); iterator.hasNext();) {
TypePattern typePattern = (TypePattern) iterator.next();
if (typePattern.matchesStatically(classInfo)) {
// exclude match - skip
return false;
}
}
//include are "OR"ed
boolean accept = true;//defaults to true if no include
for (Iterator iterator = m_aspectIncludeTypePattern.iterator(); iterator.hasNext();) {
TypePattern typePattern = (TypePattern) iterator.next();
accept = typePattern.matchesStatically(classInfo);
if (accept) {
break;
}
// goes on if this include did not match ("OR"ed)
}
return accept;
}
protected boolean shouldDump(String className, boolean before) {
// Don't dump before weaving unless asked to
if (before && !m_dumpBefore) {
return false;
}
// avoid ResolvedType if not needed
if (m_dumpTypePattern.isEmpty()) {
return false;
}
//TODO AV - optimize for className.startWith only
ResolvedType classInfo = weaver.getWorld().resolve(UnresolvedType.forName(className), true);
//dump
for (Iterator iterator = m_dumpTypePattern.iterator(); iterator.hasNext();) {
TypePattern typePattern = (TypePattern) iterator.next();
if (typePattern.matchesStatically(classInfo)) {
// dump match
return true;
}
}
return false;
}
/*
* shared classes methods
*/
/**
* @return Returns the key.
*/
public String getNamespace() {
// System.out.println("ClassLoaderWeavingAdaptor.getNamespace() classloader=" + weavingContext.getClassLoaderName() + ", namespace=" + namespace);
if(namespace==null) return "";
else return new String(namespace);
}
/**
* Check to see if any classes are stored in the generated classes cache.
* Then flush the cache if it is not empty
* @param className TODO
* @return true if a class has been generated and is stored in the cache
*/
public boolean generatedClassesExistFor (String className) {
// System.err.println("? ClassLoaderWeavingAdaptor.generatedClassesExist() classname=" + className + ", size=" + generatedClasses);
if (className == null) return !generatedClasses.isEmpty();
else return generatedClasses.containsKey(className);
}
/**
* Flush the generated classes cache
*/
public void flushGeneratedClasses() {
// System.err.println("? ClassLoaderWeavingAdaptor.flushGeneratedClasses() generatedClasses=" + generatedClasses);
generatedClasses = new HashMap();
}
private void defineClass(ClassLoader loader, String name, byte[] bytes) {
if (trace.isTraceEnabled()) trace.enter("defineClass",this,new Object[] {loader,name,bytes});
Object clazz = null;
info("generating class '" + name + "'");
try {
//TODO av protection domain, and optimize
Method defineClass = ClassLoader.class.getDeclaredMethod(
"defineClass", new Class[] { String.class,
bytes.getClass(), int.class, int.class });
defineClass.setAccessible(true);
clazz = defineClass.invoke(loader, new Object[] { name, bytes,
new Integer(0), new Integer(bytes.length) });
} catch (InvocationTargetException e) {
if (e.getTargetException() instanceof LinkageError) {
warn("define generated class failed",e.getTargetException());
//is already defined (happens for X$ajcMightHaveAspect interfaces since aspects are reweaved)
// TODO maw I don't think this is OK and
} else {
warn("define generated class failed",e.getTargetException());
}
} catch (Exception e) {
warn("define generated class failed",e);
}
if (trace.isTraceEnabled()) trace.exit("defineClass",clazz);
}
}
|
150,271 |
Bug 150271 Allow multiple levels of LTW information
|
It would be nice if basic information about load-time weaving (what version of AspectJ is being used, what loaders are doing weaving and what configuration is being used) was available without all of the -verbose information listing of all classes woven or not woven. It's also unfortunate that the flags for weaving level are 2 quite different ones: -Daj.weaving.verbose -Dorg.aspectj.weaver.showWeaveInfo Why not something like -Dorg.aspectj.weaver.level=[none|summary|info|verbose] summary: just what configuration is used info: list affected join points etc. (like showWeaveInfo) verbose: all (like verbose now)
|
resolved fixed
|
8549d86
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-08-23T11:52:22Z | 2006-07-11T15:00:00Z |
loadtime/src/org/aspectj/weaver/loadtime/DefaultMessageHandler.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.bridge.IMessageHandler;
import org.aspectj.bridge.IMessage;
import org.aspectj.bridge.AbortException;
/**
* @author <a href="mailto:alex AT gnilux DOT com">Alexandre Vasseur</a>
*/
public class DefaultMessageHandler implements IMessageHandler {
boolean isVerbose = false;
boolean showWeaveInfo = false;
boolean showWarn = true;
public boolean handleMessage(IMessage message) throws AbortException {
if (isIgnoring(message.getKind())) {
return false;
} else {
if (message.getKind().isSameOrLessThan(IMessage.INFO)) {
return SYSTEM_OUT.handleMessage(message);
} else {
return SYSTEM_ERR.handleMessage(message);
}
}
}
public boolean isIgnoring(IMessage.Kind kind) {
if (kind.equals(IMessage.WEAVEINFO)) {
return !showWeaveInfo;
}
if (kind.isSameOrLessThan(IMessage.INFO)) {
return !isVerbose;
}
return !showWarn;
}
public void dontIgnore(IMessage.Kind kind) {
if (kind.equals(IMessage.WEAVEINFO)) {
showWeaveInfo = true;
} else if (kind.equals(IMessage.DEBUG)) {
isVerbose = true;
} else if (kind.equals(IMessage.WARNING)) {
showWarn = false;
}
}
}
|
150,271 |
Bug 150271 Allow multiple levels of LTW information
|
It would be nice if basic information about load-time weaving (what version of AspectJ is being used, what loaders are doing weaving and what configuration is being used) was available without all of the -verbose information listing of all classes woven or not woven. It's also unfortunate that the flags for weaving level are 2 quite different ones: -Daj.weaving.verbose -Dorg.aspectj.weaver.showWeaveInfo Why not something like -Dorg.aspectj.weaver.level=[none|summary|info|verbose] summary: just what configuration is used info: list affected join points etc. (like showWeaveInfo) verbose: all (like verbose now)
|
resolved fixed
|
8549d86
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-08-23T11:52:22Z | 2006-07-11T15:00:00Z |
loadtime/src/org/aspectj/weaver/loadtime/Options.java
|
/*******************************************************************************
* Copyright (c) 2005 Contributors.
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Eclipse Public License v1.0
* which accompanies this distribution and is available at
* http://eclipse.org/legal/epl-v10.html
*
* Contributors:
* Alexandre Vasseur initial implementation
*******************************************************************************/
package org.aspectj.weaver.loadtime;
import org.aspectj.bridge.IMessage;
import org.aspectj.bridge.IMessageHandler;
import org.aspectj.bridge.Message;
import org.aspectj.util.LangUtil;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
/**
* A class that hanldes LTW options.
* Note: AV - I choosed to not reuse AjCompilerOptions and alike since those implies too many dependancies on
* jdt and ajdt modules.
*
* @author <a href="mailto:alex AT gnilux DOT com">Alexandre Vasseur</a>
*/
public class Options {
private final static String OPTION_15 = "-1.5";
private final static String OPTION_lazyTjp = "-XlazyTjp";
private final static String OPTION_noWarn = "-nowarn";
private final static String OPTION_noWarnNone = "-warn:none";
private final static String OPTION_proceedOnError = "-proceedOnError";
private final static String OPTION_verbose = "-verbose";
private final static String OPTION_reweavable = "-Xreweavable";//notReweavable is default for LTW
private final static String OPTION_noinline = "-Xnoinline";
private final static String OPTION_addSerialVersionUID = "-XaddSerialVersionUID";
private final static String OPTION_hasMember = "-XhasMember";
private final static String OPTION_pinpoint = "-Xdev:pinpoint";
private final static String OPTION_showWeaveInfo = "-showWeaveInfo";
private final static String OPTIONVALUED_messageHandler = "-XmessageHandlerClass:";
private static final String OPTIONVALUED_Xlintfile = "-Xlintfile:";
private static final String OPTIONVALUED_Xlint = "-Xlint:";
private static final String OPTIONVALUED_joinpoints = "-Xjoinpoints:";
private static final String OPTIONVALUED_Xset = "-Xset:";
public static WeaverOption parse(String options, ClassLoader laoder, IMessageHandler imh) {
WeaverOption weaverOption = new WeaverOption(imh);
if (LangUtil.isEmpty(options)) {
return weaverOption;
}
// the first option wins
List flags = LangUtil.anySplit(options, " ");
Collections.reverse(flags);
// do a first round on the message handler since it will report the options themselves
for (Iterator iterator = flags.iterator(); iterator.hasNext();) {
String arg = (String) iterator.next();
if (arg.startsWith(OPTIONVALUED_messageHandler)) {
if (arg.length() > OPTIONVALUED_messageHandler.length()) {
String handlerClass = arg.substring(OPTIONVALUED_messageHandler.length()).trim();
try {
Class handler = Class.forName(handlerClass, false, laoder);
weaverOption.messageHandler = ((IMessageHandler) handler.newInstance());
} catch (Throwable t) {
weaverOption.messageHandler.handleMessage(
new Message(
"Cannot instantiate message handler " + handlerClass,
IMessage.ERROR,
t,
null
)
);
}
}
}
}
// configure the other options
for (Iterator iterator = flags.iterator(); iterator.hasNext();) {
String arg = (String) iterator.next();
if (arg.equals(OPTION_15)) {
weaverOption.java5 = true;
} else if (arg.equalsIgnoreCase(OPTION_lazyTjp)) {
weaverOption.lazyTjp = true;
} else if (arg.equalsIgnoreCase(OPTION_noinline)) {
weaverOption.noInline = true;
} else if (arg.equalsIgnoreCase(OPTION_addSerialVersionUID)) {
weaverOption.addSerialVersionUID=true;
} else if (arg.equalsIgnoreCase(OPTION_noWarn) || arg.equalsIgnoreCase(OPTION_noWarnNone)) {
weaverOption.noWarn = true;
} else if (arg.equalsIgnoreCase(OPTION_proceedOnError)) {
weaverOption.proceedOnError = true;
} else if (arg.equalsIgnoreCase(OPTION_reweavable)) {
weaverOption.notReWeavable = false;
} else if (arg.equalsIgnoreCase(OPTION_showWeaveInfo)) {
weaverOption.showWeaveInfo = true;
} else if (arg.equalsIgnoreCase(OPTION_hasMember)) {
weaverOption.hasMember = true;
} else if (arg.startsWith(OPTIONVALUED_joinpoints)) {
if (arg.length()>OPTIONVALUED_joinpoints.length())
weaverOption.optionalJoinpoints = arg.substring(OPTIONVALUED_joinpoints.length()).trim();
} else if (arg.equalsIgnoreCase(OPTION_verbose)) {
weaverOption.verbose = true;
} else if (arg.equalsIgnoreCase(OPTION_pinpoint)) {
weaverOption.pinpoint = true;
} else if (arg.startsWith(OPTIONVALUED_messageHandler)) {
;// handled in first round
} else if (arg.startsWith(OPTIONVALUED_Xlintfile)) {
if (arg.length() > OPTIONVALUED_Xlintfile.length()) {
weaverOption.lintFile = arg.substring(OPTIONVALUED_Xlintfile.length()).trim();
}
} else if (arg.startsWith(OPTIONVALUED_Xlint)) {
if (arg.length() > OPTIONVALUED_Xlint.length()) {
weaverOption.lint = arg.substring(OPTIONVALUED_Xlint.length()).trim();
}
} else if (arg.startsWith(OPTIONVALUED_Xset)) {
if (arg.length() > OPTIONVALUED_Xlint.length()) {
weaverOption.xSet = arg.substring(OPTIONVALUED_Xset.length()).trim();
}
} else {
weaverOption.messageHandler.handleMessage(
new Message(
"Cannot configure weaver with option '" + arg + "': unknown option",
IMessage.WARNING,
null,
null
)
);
}
}
// refine message handler configuration
if (weaverOption.noWarn) {
weaverOption.messageHandler.dontIgnore(IMessage.WARNING);
}
if (weaverOption.verbose) {
weaverOption.messageHandler.dontIgnore(IMessage.INFO);
}
if (weaverOption.showWeaveInfo) {
weaverOption.messageHandler.dontIgnore(IMessage.WEAVEINFO);
}
return weaverOption;
}
public static class WeaverOption {
boolean java5;
boolean lazyTjp;
boolean hasMember;
String optionalJoinpoints;
boolean noWarn;
boolean proceedOnError;
boolean verbose;
boolean notReWeavable = true;//default to notReweavable for LTW (faster)
boolean noInline;
boolean addSerialVersionUID;
boolean showWeaveInfo;
boolean pinpoint;
IMessageHandler messageHandler;
String lint;
String lintFile;
String xSet;
public WeaverOption(IMessageHandler imh) {
// messageHandler = new DefaultMessageHandler();//default
this.messageHandler = imh;
}
}
}
|
150,271 |
Bug 150271 Allow multiple levels of LTW information
|
It would be nice if basic information about load-time weaving (what version of AspectJ is being used, what loaders are doing weaving and what configuration is being used) was available without all of the -verbose information listing of all classes woven or not woven. It's also unfortunate that the flags for weaving level are 2 quite different ones: -Daj.weaving.verbose -Dorg.aspectj.weaver.showWeaveInfo Why not something like -Dorg.aspectj.weaver.level=[none|summary|info|verbose] summary: just what configuration is used info: list affected join points etc. (like showWeaveInfo) verbose: all (like verbose now)
|
resolved fixed
|
8549d86
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-08-23T11:52:22Z | 2006-07-11T15:00:00Z |
tests/java5/ataspectj/ataspectj/TestHelper.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 ataspectj;
import junit.textui.TestRunner;
import junit.framework.TestResult;
import junit.framework.Assert;
import junit.framework.TestFailure;
import java.util.Enumeration;
import org.aspectj.bridge.IMessage;
import org.aspectj.bridge.AbortException;
import org.aspectj.weaver.loadtime.DefaultMessageHandler;
/**
* Helper to run a test as a main class, but still throw exception and not just print on stderr
* upon test failure.
* <p/>
* This is required for Ajc test case that are also designed to work with LTW.
*
* @author <a href="mailto:alex AT gnilux DOT com">Alexandre Vasseur</a>
*/
public class TestHelper extends DefaultMessageHandler {
public static void runAndThrowOnFailure(junit.framework.Test test) {
TestRunner r = new TestRunner();
TestResult rr = r.doRun(test);
if (!rr.wasSuccessful()) {
StringBuffer sb = new StringBuffer("\n");
Enumeration e = rr.failures();
while (e.hasMoreElements()) {
sb.append("JUnit Failure: ");
TestFailure failure = (TestFailure)e.nextElement();
sb.append(failure.thrownException().toString());
sb.append("\n");
}
e = rr.errors();
while (e.hasMoreElements()) {
sb.append("JUnit Error: ");
TestFailure failure = (TestFailure)e.nextElement();
sb.append(failure.thrownException().toString());
sb.append("\n");
}
throw new RuntimeException(sb.toString());
}
}
public boolean handleMessage(IMessage message) throws AbortException {
boolean ret = super.handleMessage(message);
if (message.getKind().isSameOrLessThan(IMessage.INFO)) {
;
} else {
// we do exit here since Assert.fail will only trigger a runtime exception that might
// be catched by the weaver anyway
System.err.println("*** Exiting - got a warning/fail/error/abort IMessage");
System.exit(-1);
}
return ret;
}
}
|
150,271 |
Bug 150271 Allow multiple levels of LTW information
|
It would be nice if basic information about load-time weaving (what version of AspectJ is being used, what loaders are doing weaving and what configuration is being used) was available without all of the -verbose information listing of all classes woven or not woven. It's also unfortunate that the flags for weaving level are 2 quite different ones: -Daj.weaving.verbose -Dorg.aspectj.weaver.showWeaveInfo Why not something like -Dorg.aspectj.weaver.level=[none|summary|info|verbose] summary: just what configuration is used info: list affected join points etc. (like showWeaveInfo) verbose: all (like verbose now)
|
resolved fixed
|
8549d86
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-08-23T11:52:22Z | 2006-07-11T15:00:00Z |
weaver/src/org/aspectj/weaver/tools/WeavingAdaptor.java
|
/* *******************************************************************
* Copyright (c) 2004 IBM Corporation
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Eclipse Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Matthew Webster, Adrian Colyer,
* Martin Lippert initial implementation
* ******************************************************************/
package org.aspectj.weaver.tools;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.StringTokenizer;
import org.aspectj.bridge.AbortException;
import org.aspectj.bridge.IMessage;
import org.aspectj.bridge.IMessageContext;
import org.aspectj.bridge.IMessageHandler;
import org.aspectj.bridge.Message;
import org.aspectj.bridge.MessageUtil;
import org.aspectj.bridge.MessageWriter;
import org.aspectj.bridge.Version;
import org.aspectj.bridge.WeaveMessage;
import org.aspectj.bridge.IMessage.Kind;
import org.aspectj.org.objectweb.asm.ClassReader;
import org.aspectj.util.FileUtil;
import org.aspectj.util.LangUtil;
import org.aspectj.weaver.IClassFileProvider;
import org.aspectj.weaver.IWeaveRequestor;
import org.aspectj.weaver.ResolvedType;
import org.aspectj.weaver.bcel.BcelObjectType;
import org.aspectj.weaver.bcel.BcelWeaver;
import org.aspectj.weaver.bcel.BcelWorld;
import org.aspectj.weaver.bcel.UnwovenClassFile;
import org.aspectj.weaver.bcel.Utility;
/**
* This adaptor allows the AspectJ compiler to be embedded in an existing
* system to facilitate load-time weaving. It provides an interface for a
* weaving class loader to provide a classpath to be woven by a set of
* aspects. A callback is supplied to allow a class loader to define classes
* generated by the compiler during the weaving process.
* <p>
* A weaving class loader should create a <code>WeavingAdaptor</code> before
* any classes are defined, typically during construction. The set of aspects
* passed to the adaptor is fixed for the lifetime of the adaptor although the
* classpath can be augmented. A system property can be set to allow verbose
* weaving messages to be written to the console.
*
*/
public class WeavingAdaptor implements IMessageContext {
/**
* System property used to turn on verbose weaving messages
*/
public static final String WEAVING_ADAPTOR_VERBOSE = "aj.weaving.verbose";
public static final String SHOW_WEAVE_INFO_PROPERTY = "org.aspectj.weaver.showWeaveInfo";
public static final String TRACE_MESSAGES_PROPERTY = "org.aspectj.tracing.messages";
private boolean enabled = true;
protected boolean verbose = getVerbose();
protected BcelWorld bcelWorld;
protected BcelWeaver weaver;
private IMessageHandler messageHandler;
private WeavingAdaptorMessageHandler messageHolder;
protected GeneratedClassHandler generatedClassHandler;
protected Map generatedClasses = new HashMap(); /* String -> UnwovenClassFile */
protected BcelObjectType delegateForCurrentClass; // lazily initialized, should be used to prevent parsing bytecode multiple times
private static Trace trace = TraceFactory.getTraceFactory().getTrace(WeavingAdaptor.class);
protected WeavingAdaptor () {
}
/**
* Construct a WeavingAdaptor with a reference to a weaving class loader. The
* adaptor will automatically search the class loader hierarchy to resolve
* classes. The adaptor will also search the hierarchy for WeavingClassLoader
* instances to determine the set of aspects to be used ofr weaving.
* @param loader instance of <code>ClassLoader</code>
*/
public WeavingAdaptor (WeavingClassLoader loader) {
// System.err.println("? WeavingAdaptor.<init>(" + loader +"," + aspectURLs.length + ")");
generatedClassHandler = loader;
init(getFullClassPath((ClassLoader)loader),getFullAspectPath((ClassLoader)loader/*,aspectURLs*/));
}
/**
* Construct a WeavingAdator with a reference to a
* <code>GeneratedClassHandler</code>, a full search path for resolving
* classes and a complete set of aspects. The search path must include
* classes loaded by the class loader constructing the WeavingAdaptor and
* all its parents in the hierarchy.
* @param handler <code>GeneratedClassHandler</code>
* @param classURLs the URLs from which to resolve classes
* @param aspectURLs the aspects used to weave classes defined by this class loader
*/
public WeavingAdaptor (GeneratedClassHandler handler, URL[] classURLs, URL[] aspectURLs) {
// System.err.println("? WeavingAdaptor.<init>()");
generatedClassHandler = handler;
init(FileUtil.makeClasspath(classURLs),FileUtil.makeClasspath(aspectURLs));
}
private List getFullClassPath (ClassLoader loader) {
List list = new LinkedList();
for (; loader != null; loader = loader.getParent()) {
if (loader instanceof URLClassLoader) {
URL[] urls = ((URLClassLoader)loader).getURLs();
list.addAll(0,FileUtil.makeClasspath(urls));
}
else {
warn("cannot determine classpath");
}
}
list.addAll(0,makeClasspath(System.getProperty("sun.boot.class.path")));
return list;
}
private List getFullAspectPath (ClassLoader loader) {
List list = new LinkedList();
for (; loader != null; loader = loader.getParent()) {
if (loader instanceof WeavingClassLoader) {
URL[] urls = ((WeavingClassLoader)loader).getAspectURLs();
list.addAll(0,FileUtil.makeClasspath(urls));
}
}
return list;
}
private static boolean getVerbose () {
return Boolean.getBoolean(WEAVING_ADAPTOR_VERBOSE);
}
private void init(List classPath, List aspectPath) {
createMessageHandler();
info("using classpath: " + classPath);
info("using aspectpath: " + aspectPath);
bcelWorld = new BcelWorld(classPath,messageHandler,null);
bcelWorld.setXnoInline(false);
bcelWorld.getLint().loadDefaultProperties();
if (LangUtil.is15VMOrGreater()) {
bcelWorld.setBehaveInJava5Way(true);
}
weaver = new BcelWeaver(bcelWorld);
registerAspectLibraries(aspectPath);
}
protected void createMessageHandler() {
messageHolder = new WeavingAdaptorMessageHandler(new PrintWriter(System.err));
messageHandler = messageHolder;
if (verbose) messageHandler.dontIgnore(IMessage.INFO);
if (Boolean.getBoolean(SHOW_WEAVE_INFO_PROPERTY)) messageHandler.dontIgnore(IMessage.WEAVEINFO);
info("AspectJ Weaver Version " + Version.text + " built on " + Version.time_text); //$NON-NLS-1$
}
protected IMessageHandler getMessageHandler () {
return messageHandler;
}
protected void setMessageHandler (IMessageHandler mh) {
if (mh instanceof ISupportsMessageContext) {
ISupportsMessageContext smc = (ISupportsMessageContext)mh;
smc.setMessageContext(this);
}
if (mh != messageHolder) messageHolder.setDelegate(mh);
messageHolder.flushMessages();
}
protected void disable () {
enabled = false;
messageHolder.flushMessages();
}
protected boolean isEnabled () {
return enabled;
}
/**
* Appends URL to path used by the WeavingAdptor to resolve classes
* @param url to be appended to search path
*/
public void addURL(URL url) {
File libFile = new File(url.getPath());
try {
weaver.addLibraryJarFile(libFile);
}
catch (IOException ex) {
warn("bad library: '" + libFile + "'");
}
}
/**
* Weave a class using aspects previously supplied to the adaptor.
* @param name the name of the class
* @param bytes the class bytes
* @return the woven bytes
* @exception IOException weave failed
*/
public byte[] weaveClass (String name, byte[] bytes) throws IOException {
if (enabled) {
try {
delegateForCurrentClass=null;
if (trace.isTraceEnabled()) trace.enter("weaveClass",this,new Object[] {name,bytes});
name = name.replace('/','.');
if (couldWeave(name, bytes)) {
if (accept(name, bytes)) {
// TODO @AspectJ problem
// Annotation style aspects need to be included regardless in order to get
// a valid aspectOf()/hasAspect() generated in them. However - if they are excluded
// (via include/exclude in aop.xml) they really should only get aspectOf()/hasAspect()
// and not be included in the full set of aspects being applied by 'this' weaver
info("weaving '" + name + "'");
bytes = getWovenBytes(name, bytes);
} else if (shouldWeaveAnnotationStyleAspect(name, bytes)) {
// an @AspectJ aspect needs to be at least munged by the aspectOf munger
info("weaving '" + name + "'");
bytes = getAtAspectJAspectBytes(name, bytes);
} else {
info("not weaving '" + name + "'");
}
} else {
info("cannot weave '" + name + "'");
}
if (trace.isTraceEnabled()) trace.exit("weaveClass",bytes);
} finally {
delegateForCurrentClass=null;
}
}
return bytes;
}
/**
* @param name
* @return true if even valid to weave: either with an accept check or to munge it for @AspectJ aspectof support
*/
private boolean couldWeave (String name, byte[] bytes) {
return !generatedClasses.containsKey(name) && shouldWeaveName(name);
}
//ATAJ
protected boolean accept(String name, byte[] bytes) {
return true;
}
protected boolean shouldDump(String name, boolean before) {
return false;
}
private boolean shouldWeaveName (String name) {
boolean should =
!((name.startsWith("org.aspectj.")
|| name.startsWith("java.")
|| name.startsWith("javax."))
//|| name.startsWith("$Proxy")//JDK proxies//FIXME AV is that 1.3 proxy ? fe. ataspect.$Proxy0 is a java5 proxy...
|| name.startsWith("sun.reflect."));//JDK reflect
return should;
}
/**
* We allow @AJ aspect weaving so that we can add aspectOf() as part of the weaving
* (and not part of the source compilation)
*
* @param name
* @param bytes bytecode (from classloader), allow to NOT lookup stuff on disk again during resolve
* @return true if @Aspect
*/
private boolean shouldWeaveAnnotationStyleAspect(String name, byte[] bytes) {
if (delegateForCurrentClass==null) {
if (weaver.getWorld().isASMAround()) return asmCheckAnnotationStyleAspect(bytes);
else ensureDelegateInitialized(name, bytes);
}
return (delegateForCurrentClass.isAnnotationStyleAspect());
}
private boolean asmCheckAnnotationStyleAspect(byte[] bytes) {
IsAtAspectAnnotationVisitor detector = new IsAtAspectAnnotationVisitor();
ClassReader cr = new ClassReader(bytes);
try {
cr.accept(detector, true);//, ClassReader.SKIP_DEBUG | ClassReader.SKIP_CODE | ClassReader.SKIP_FRAMES);
} catch (Exception spe) {
// if anything goes wrong, e.g., an NPE, then assume it's NOT an @AspectJ aspect...
System.err.println("Unexpected problem parsing bytes to discover @Aspect annotation");
spe.printStackTrace();
return false;
}
return detector.isAspect();
}
protected void ensureDelegateInitialized(String name,byte[] bytes) {
if (delegateForCurrentClass==null)
delegateForCurrentClass = ((BcelWorld)weaver.getWorld()).addSourceObjectType(Utility.makeJavaClass(name, bytes));
}
/**
* Weave a set of bytes defining a class.
* @param name the name of the class being woven
* @param bytes the bytes that define the class
* @return byte[] the woven bytes for the class
* @throws IOException
*/
private byte[] getWovenBytes(String name, byte[] bytes) throws IOException {
WeavingClassFileProvider wcp = new WeavingClassFileProvider(name,bytes);
weaver.weave(wcp);
return wcp.getBytes();
}
/**
* Weave a set of bytes defining a class for only what is needed to turn @AspectJ aspect
* in a usefull form ie with aspectOf method - see #113587
* @param name the name of the class being woven
* @param bytes the bytes that define the class
* @return byte[] the woven bytes for the class
* @throws IOException
*/
private byte[] getAtAspectJAspectBytes(String name, byte[] bytes) throws IOException {
WeavingClassFileProvider wcp = new WeavingClassFileProvider(name,bytes);
wcp.setApplyAtAspectJMungersOnly();
weaver.weave(wcp);
return wcp.getBytes();
}
private void registerAspectLibraries(List aspectPath) {
// System.err.println("? WeavingAdaptor.registerAspectLibraries(" + aspectPath + ")");
for (Iterator i = aspectPath.iterator(); i.hasNext();) {
String libName = (String)i.next();
addAspectLibrary(libName);
}
weaver.prepareForWeave();
}
/*
* Register an aspect library with this classloader for use during
* weaving. This class loader will also return (unmodified) any of the
* classes in the library in response to a <code>findClass()</code> request.
* The library is not required to be on the weavingClasspath given when this
* classloader was constructed.
* @param aspectLibraryJarFile a jar file representing an aspect library
* @throws IOException
*/
private void addAspectLibrary(String aspectLibraryName) {
File aspectLibrary = new File(aspectLibraryName);
if (aspectLibrary.isDirectory()
|| (FileUtil.isZipFile(aspectLibrary))) {
try {
info("adding aspect library: '" + aspectLibrary + "'");
weaver.addLibraryJarFile(aspectLibrary);
} catch (IOException ex) {
error("exception adding aspect library: '" + ex + "'");
}
} else {
error("bad aspect library: '" + aspectLibrary + "'");
}
}
private static List makeClasspath(String cp) {
List ret = new ArrayList();
if (cp != null) {
StringTokenizer tok = new StringTokenizer(cp,File.pathSeparator);
while (tok.hasMoreTokens()) {
ret.add(tok.nextToken());
}
}
return ret;
}
protected boolean info (String message) {
return MessageUtil.info(messageHandler,message);
}
protected boolean warn (String message) {
return MessageUtil.warn(messageHandler,message);
}
protected boolean warn (String message, Throwable th) {
return messageHandler.handleMessage(new Message(message, IMessage.WARNING, th, null));
}
protected boolean error (String message) {
return MessageUtil.error(messageHandler,message);
}
public String getContextId () {
return "WeavingAdaptor";
}
/**
* Dump the given bytcode in _dump/... (dev mode)
*
* @param name
* @param b
* @param before whether we are dumping before weaving
* @throws Throwable
*/
protected void dump(String name, byte[] b, boolean before) {
String dirName = "_ajdump";
if (before) dirName = dirName + File.separator + "_before";
String className = name.replace('.', '/');
final File dir;
if (className.indexOf('/') > 0) {
dir = new File(dirName + File.separator + className.substring(0, className.lastIndexOf('/')));
} else {
dir = new File(dirName);
}
dir.mkdirs();
String fileName = dirName + File.separator + className + ".class";
try {
// System.out.println("WeavingAdaptor.dump() fileName=" + new File(fileName).getAbsolutePath());
FileOutputStream os = new FileOutputStream(fileName);
os.write(b);
os.close();
}
catch (IOException ex) {
warn("unable to dump class " + name + " in directory " + dirName,ex);
}
}
/**
* Processes messages arising from weaver operations.
* Tell weaver to abort on any message more severe than warning.
*/
protected class WeavingAdaptorMessageHandler implements IMessageHandler {
private IMessageHandler delegate;
private boolean accumulating = true;
private List messages = new ArrayList();
protected boolean traceMessages = Boolean.getBoolean(TRACE_MESSAGES_PROPERTY);
public WeavingAdaptorMessageHandler (PrintWriter writer) {
this.delegate = new WeavingAdaptorMessageWriter(writer);
}
public boolean handleMessage(IMessage message) throws AbortException {
if (traceMessages) traceMessage(message);
if (accumulating) {
boolean result = addMessage(message);
if (0 <= message.getKind().compareTo(IMessage.ERROR)) {
throw new AbortException(message);
}
return result;
}
else return delegate.handleMessage(message);
}
private void traceMessage (IMessage message) {
if (message instanceof WeaveMessage) {
trace.debug(render(message));
}
else if (message.isDebug()) {
trace.debug(render(message));
}
else if (message.isInfo()) {
trace.info(render(message));
}
else if (message.isWarning()) {
trace.warn(render(message),message.getThrown());
}
else if (message.isError()) {
trace.error(render(message),message.getThrown());
}
else if (message.isFailed()) {
trace.fatal(render(message),message.getThrown());
}
else if (message.isAbort()) {
trace.fatal(render(message),message.getThrown());
}
else {
trace.error(render(message),message.getThrown());
}
}
protected String render(IMessage message) {
return "[" + getContextId() + "] " + message.toString();
}
public boolean isIgnoring (Kind kind) {
return delegate.isIgnoring(kind);
}
public void dontIgnore (IMessage.Kind kind) {
if (null != kind) {
delegate.dontIgnore(kind);
}
}
private boolean addMessage (IMessage message) {
messages.add(message);
return true;
}
public void flushMessages () {
for (Iterator iter = messages.iterator(); iter.hasNext();) {
IMessage message = (IMessage)iter.next();
delegate.handleMessage(message);
}
accumulating = false;
messages.clear();
}
public void setDelegate (IMessageHandler messageHandler) {
delegate = messageHandler;
}
}
protected class WeavingAdaptorMessageWriter extends MessageWriter {
private Set ignoring = new HashSet();
private IMessage.Kind failKind;
public WeavingAdaptorMessageWriter (PrintWriter writer) {
super(writer,true);
ignore(IMessage.WEAVEINFO);
ignore(IMessage.INFO);
this.failKind = IMessage.ERROR;
}
public boolean handleMessage(IMessage message) throws AbortException {
boolean result = super.handleMessage(message);
if (0 <= message.getKind().compareTo(failKind)) {
throw new AbortException(message);
}
return true;
}
public boolean isIgnoring (Kind kind) {
return ((null != kind) && (ignoring.contains(kind)));
}
/**
* Set a message kind to be ignored from now on
*/
public void ignore (IMessage.Kind kind) {
if ((null != kind) && (!ignoring.contains(kind))) {
ignoring.add(kind);
}
}
/**
* Remove a message kind from the list of those ignored from now on.
*/
public void dontIgnore (IMessage.Kind kind) {
if (null != kind) {
ignoring.remove(kind);
}
}
protected String render(IMessage message) {
return "[" + getContextId() + "] " + super.render(message);
}
}
private class WeavingClassFileProvider implements IClassFileProvider {
private UnwovenClassFile unwovenClass;
private List unwovenClasses = new ArrayList(); /* List<UnovenClassFile> */
private UnwovenClassFile wovenClass;
private boolean isApplyAtAspectJMungersOnly = false;
public WeavingClassFileProvider (String name, byte[] bytes) {
ensureDelegateInitialized(name, bytes);
this.unwovenClass = new UnwovenClassFile(name,delegateForCurrentClass.getResolvedTypeX().getName(),bytes);
this.unwovenClasses.add(unwovenClass);
if (shouldDump(name.replace('/', '.'),true)) {
dump(name, bytes, true);
}
}
public void setApplyAtAspectJMungersOnly() {
isApplyAtAspectJMungersOnly = true;
}
public boolean isApplyAtAspectJMungersOnly() {
return isApplyAtAspectJMungersOnly;
}
public byte[] getBytes () {
if (wovenClass != null) return wovenClass.getBytes();
else return unwovenClass.getBytes();
}
public Iterator getClassFileIterator() {
return unwovenClasses.iterator();
}
public IWeaveRequestor getRequestor() {
return new IWeaveRequestor() {
public void acceptResult(UnwovenClassFile result) {
if (wovenClass == null) {
wovenClass = result;
String name = result.getClassName();
if (shouldDump(name.replace('/', '.'), false)) {
dump(name, result.getBytes(), false);
}
}
/* Classes generated by weaver e.g. around closure advice */
else {
String className = result.getClassName();
generatedClasses.put(className,result);
generatedClasses.put(wovenClass.getClassName(),result);
generatedClassHandler.acceptClass(className,result.getBytes());
}
}
public void processingReweavableState() { }
public void addingTypeMungers() {}
public void weavingAspects() {}
public void weavingClasses() {}
public void weaveCompleted() {
ResolvedType.resetPrimitives();
if (delegateForCurrentClass!=null) delegateForCurrentClass.weavingCompleted();
ResolvedType.resetPrimitives();
//bcelWorld.discardType(typeBeingProcessed.getResolvedTypeX()); // work in progress
}
};
}
}
}
|
129,525 |
Bug 129525 Don't Dump Bytecodes to Syserr in LTW
|
The load-time weaving system can produce truly massive quantities of output when there's a weaving error, since the system dumps the bytecode to syserr. It would be much better to produce an ajcore file and just point to it, or use some other log.
|
resolved fixed
|
04fa1dc
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-08-24T17:32:00Z | 2006-02-27T08:46:40Z |
loadtime/src/org/aspectj/weaver/loadtime/ClassLoaderWeavingAdaptor.java
|
/*******************************************************************************
* Copyright (c) 2005 Contributors.
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Eclipse Public License v1.0
* which accompanies this distribution and is available at
* http://eclipse.org/legal/epl-v10.html
*
* Contributors:
* Alexandre Vasseur initial implementation
* David Knibb weaving context enhancments
*******************************************************************************/
package org.aspectj.weaver.loadtime;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.URL;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Properties;
import java.util.StringTokenizer;
import org.aspectj.asm.IRelationship;
import org.aspectj.bridge.AbortException;
import org.aspectj.bridge.Constants;
import org.aspectj.bridge.ISourceLocation;
import org.aspectj.util.LangUtil;
import org.aspectj.weaver.ICrossReferenceHandler;
import org.aspectj.weaver.Lint;
import org.aspectj.weaver.ResolvedType;
import org.aspectj.weaver.UnresolvedType;
import org.aspectj.weaver.World;
import org.aspectj.weaver.Lint.Kind;
import org.aspectj.weaver.bcel.BcelWeaver;
import org.aspectj.weaver.loadtime.definition.Definition;
import org.aspectj.weaver.loadtime.definition.DocumentParser;
import org.aspectj.weaver.ltw.LTWWorld;
import org.aspectj.weaver.patterns.PatternParser;
import org.aspectj.weaver.patterns.TypePattern;
import org.aspectj.weaver.tools.GeneratedClassHandler;
import org.aspectj.weaver.tools.Trace;
import org.aspectj.weaver.tools.TraceFactory;
import org.aspectj.weaver.tools.WeavingAdaptor;
/**
* @author <a href="mailto:alex AT gnilux DOT com">Alexandre Vasseur</a>
*/
public class ClassLoaderWeavingAdaptor extends WeavingAdaptor {
private final static String AOP_XML = Constants.AOP_USER_XML + ";" + Constants.AOP_AJC_XML;
private boolean initialized;
private List m_dumpTypePattern = new ArrayList();
private boolean m_dumpBefore = false;
private List m_includeTypePattern = new ArrayList();
private List m_excludeTypePattern = new ArrayList();
private List m_includeStartsWith = new ArrayList();
private List m_excludeStartsWith = new ArrayList();
private List m_aspectExcludeTypePattern = new ArrayList();
private List m_aspectExcludeStartsWith = new ArrayList();
private List m_aspectIncludeTypePattern = new ArrayList();
private List m_aspectIncludeStartsWith = new ArrayList();
private StringBuffer namespace;
private IWeavingContext weavingContext;
private static Trace trace = TraceFactory.getTraceFactory().getTrace(ClassLoaderWeavingAdaptor.class);
public ClassLoaderWeavingAdaptor() {
super();
if (trace.isTraceEnabled()) trace.enter("<init>",this);
if (trace.isTraceEnabled()) trace.exit("<init>");
}
/**
* We don't need a reference to the class loader and using it during
* construction can cause problems with recursion. It also makes sense
* to supply the weaving context during initialization to.
* @deprecated
*/
public ClassLoaderWeavingAdaptor(final ClassLoader deprecatedLoader, final IWeavingContext deprecatedContext) {
super();
if (trace.isTraceEnabled()) trace.enter("<init>",this,new Object[] { deprecatedLoader, deprecatedContext });
if (trace.isTraceEnabled()) trace.exit("<init>");
}
protected void initialize (final ClassLoader classLoader, IWeavingContext context) {
//super(null);// at this stage we don't have yet a generatedClassHandler to define to the VM the closures
if (initialized) return;
if (trace.isTraceEnabled()) trace.enter("initialize",this,new Object[] { classLoader, context });
this.weavingContext = context;
if (weavingContext == null) {
weavingContext = new DefaultWeavingContext(classLoader);
}
createMessageHandler();
this.generatedClassHandler = new GeneratedClassHandler() {
/**
* Callback when we need to define a Closure in the JVM
*
* @param name
* @param bytes
*/
public void acceptClass(String name, byte[] bytes) {
try {
if (shouldDump(name.replace('/', '.'), false)) {
dump(name, bytes, false);
}
} catch (Throwable throwable) {
throwable.printStackTrace();
}
defineClass(classLoader, name, bytes);// could be done lazily using the hook
}
};
List definitions = parseDefinitions(classLoader);
if (!isEnabled()) {
if (trace.isTraceEnabled()) trace.exit("initialize",false);
return;
}
bcelWorld = new LTWWorld(
classLoader, weavingContext, // TODO when the world works in terms of the context, we can remove the loader...
getMessageHandler(), new ICrossReferenceHandler() {
public void addCrossReference(ISourceLocation from, ISourceLocation to, IRelationship.Kind kind, boolean runtimeTest) {
;// for tools only
}
}
);
// //TODO this AJ code will call
// //org.aspectj.apache.bcel.Repository.setRepository(this);
// //ie set some static things
// //==> bogus as Bcel is expected to be
// org.aspectj.apache.bcel.Repository.setRepository(new ClassLoaderRepository(loader));
weaver = new BcelWeaver(bcelWorld);
// register the definitions
registerDefinitions(weaver, classLoader, definitions);
if (isEnabled()) {
//bcelWorld.setResolutionLoader(loader.getParent());//(ClassLoader)null);//
// after adding aspects
weaver.prepareForWeave();
}
else {
bcelWorld = null;
weaver = null;
}
initialized = true;
if (trace.isTraceEnabled()) trace.exit("initialize",isEnabled());
}
/**
* Load and cache the aop.xml/properties according to the classloader visibility rules
*
* @param weaver
* @param loader
*/
private List parseDefinitions(final ClassLoader loader) {
List definitions = new ArrayList();
try {
info("register classloader " + getClassLoaderName(loader));
//TODO av underoptimized: we will parse each XML once per CL that see it
//TODO av dev mode needed ? TBD -Daj5.def=...
if (ClassLoader.getSystemClassLoader().equals(loader)) {
String file = System.getProperty("aj5.def", null);
if (file != null) {
info("using (-Daj5.def) " + file);
definitions.add(DocumentParser.parse((new File(file)).toURL()));
}
}
String resourcePath = System.getProperty("org.aspectj.weaver.loadtime.configuration",AOP_XML);
StringTokenizer st = new StringTokenizer(resourcePath,";");
while(st.hasMoreTokens()){
Enumeration xmls = weavingContext.getResources(st.nextToken());
// System.out.println("? registerDefinitions: found-aop.xml=" + xmls.hasMoreElements() + ", loader=" + loader);
while (xmls.hasMoreElements()) {
URL xml = (URL) xmls.nextElement();
info("using configuration " + weavingContext.getFile(xml));
definitions.add(DocumentParser.parse(xml));
}
}
if (definitions.isEmpty()) {
disable();// will allow very fast skip in shouldWeave()
info("no configuration found. Disabling weaver for class loader " + getClassLoaderName(loader));
}
} catch (Exception e) {
disable();// will allow very fast skip in shouldWeave()
warn("parse definitions failed",e);
}
return definitions;
}
private void registerDefinitions(final BcelWeaver weaver, final ClassLoader loader, List definitions) {
try {
registerOptions(weaver, loader, definitions);
registerAspectExclude(weaver, loader, definitions);
registerAspectInclude(weaver, loader, definitions);
registerAspects(weaver, loader, definitions);
registerIncludeExclude(weaver, loader, definitions);
registerDump(weaver, loader, definitions);
} catch (Exception e) {
disable();// will allow very fast skip in shouldWeave()
warn("register definition failed",(e instanceof AbortException)?null:e);
}
}
private String getClassLoaderName (ClassLoader loader) {
return weavingContext.getClassLoaderName();
}
/**
* Configure the weaver according to the option directives
* TODO av - don't know if it is that good to reuse, since we only allow a small subset of options in LTW
*
* @param weaver
* @param loader
* @param definitions
*/
private void registerOptions(final BcelWeaver weaver, final ClassLoader loader, final List definitions) {
StringBuffer allOptions = new StringBuffer();
for (Iterator iterator = definitions.iterator(); iterator.hasNext();) {
Definition definition = (Definition) iterator.next();
allOptions.append(definition.getWeaverOptions()).append(' ');
}
Options.WeaverOption weaverOption = Options.parse(allOptions.toString(), loader, getMessageHandler());
// configure the weaver and world
// AV - code duplicates AspectJBuilder.initWorldAndWeaver()
World world = weaver.getWorld();
setMessageHandler(weaverOption.messageHandler);
world.setXlazyTjp(weaverOption.lazyTjp);
world.setXHasMemberSupportEnabled(weaverOption.hasMember);
world.setOptionalJoinpoints(weaverOption.optionalJoinpoints);
world.setPinpointMode(weaverOption.pinpoint);
weaver.setReweavableMode(weaverOption.notReWeavable);
world.performExtraConfiguration(weaverOption.xSet);
world.setXnoInline(weaverOption.noInline);
// AMC - autodetect as per line below, needed for AtAjLTWTests.testLTWUnweavable
world.setBehaveInJava5Way(LangUtil.is15VMOrGreater());
world.setAddSerialVerUID(weaverOption.addSerialVersionUID);
/* First load defaults */
bcelWorld.getLint().loadDefaultProperties();
/* Second overlay LTW defaults */
bcelWorld.getLint().adviceDidNotMatch.setKind(null);
/* Third load user file using -Xlintfile so that -Xlint wins */
if (weaverOption.lintFile != null) {
InputStream resource = null;
try {
resource = loader.getResourceAsStream(weaverOption.lintFile);
Exception failure = null;
if (resource != null) {
try {
Properties properties = new Properties();
properties.load(resource);
world.getLint().setFromProperties(properties);
} catch (IOException e) {
failure = e;
}
}
if (failure != null || resource == null) {
warn("Cannot access resource for -Xlintfile:"+weaverOption.lintFile,failure);
// world.getMessageHandler().handleMessage(new Message(
// "Cannot access resource for -Xlintfile:"+weaverOption.lintFile,
// IMessage.WARNING,
// failure,
// null));
}
} finally {
try { resource.close(); } catch (Throwable t) {;}
}
}
/* Fourth override with -Xlint */
if (weaverOption.lint != null) {
if (weaverOption.lint.equals("default")) {//FIXME should be AjBuildConfig.AJLINT_DEFAULT but yetanother deps..
bcelWorld.getLint().loadDefaultProperties();
} else {
bcelWorld.getLint().setAll(weaverOption.lint);
}
}
//TODO proceedOnError option
}
private void registerAspectExclude(final BcelWeaver weaver, final ClassLoader loader, final List definitions) {
String fastMatchInfo = null;
for (Iterator iterator = definitions.iterator(); iterator.hasNext();) {
Definition definition = (Definition) iterator.next();
for (Iterator iterator1 = definition.getAspectExcludePatterns().iterator(); iterator1.hasNext();) {
String exclude = (String) iterator1.next();
TypePattern excludePattern = new PatternParser(exclude).parseTypePattern();
m_aspectExcludeTypePattern.add(excludePattern);
fastMatchInfo = looksLikeStartsWith(exclude);
if (fastMatchInfo != null) {
m_aspectExcludeStartsWith.add(fastMatchInfo);
}
}
}
}
private void registerAspectInclude(final BcelWeaver weaver, final ClassLoader loader, final List definitions) {
String fastMatchInfo = null;
for (Iterator iterator = definitions.iterator(); iterator.hasNext();) {
Definition definition = (Definition) iterator.next();
for (Iterator iterator1 = definition.getAspectIncludePatterns().iterator(); iterator1.hasNext();) {
String include = (String) iterator1.next();
TypePattern includePattern = new PatternParser(include).parseTypePattern();
m_aspectIncludeTypePattern.add(includePattern);
fastMatchInfo = looksLikeStartsWith(include);
if (fastMatchInfo != null) {
m_aspectIncludeStartsWith.add(fastMatchInfo);
}
}
}
}
protected void lint (String name, String[] infos) {
Lint lint = bcelWorld.getLint();
Kind kind = lint.getLintKind(name);
kind.signal(infos,null,null);
}
public String getContextId () {
return weavingContext.getId();
}
/**
* Register the aspect, following include / exclude rules
*
* @param weaver
* @param loader
* @param definitions
*/
private void registerAspects(final BcelWeaver weaver, final ClassLoader loader, final List definitions) {
if (trace.isTraceEnabled()) trace.enter("registerAspects",this, new Object[] { weaver, loader, definitions} );
//TODO: the exclude aspect allow to exclude aspect defined upper in the CL hierarchy - is it what we want ??
// if not, review the getResource so that we track which resource is defined by which CL
//iterate aspectClassNames
//exclude if in any of the exclude list
for (Iterator iterator = definitions.iterator(); iterator.hasNext();) {
Definition definition = (Definition) iterator.next();
for (Iterator aspects = definition.getAspectClassNames().iterator(); aspects.hasNext();) {
String aspectClassName = (String) aspects.next();
if (acceptAspect(aspectClassName)) {
info("register aspect " + aspectClassName);
// System.err.println("? ClassLoaderWeavingAdaptor.registerAspects() aspectName=" + aspectClassName + ", loader=" + loader + ", bundle=" + weavingContext.getClassLoaderName());
/*ResolvedType aspect = */weaver.addLibraryAspect(aspectClassName);
//generate key for SC
if(namespace==null){
namespace=new StringBuffer(aspectClassName);
}else{
namespace = namespace.append(";"+aspectClassName);
}
}
else {
// warn("aspect excluded: " + aspectClassName);
lint("aspectExcludedByConfiguration", new String[] { aspectClassName, getClassLoaderName(loader) });
}
}
}
//iterate concreteAspects
//exclude if in any of the exclude list - note that the user defined name matters for that to happen
for (Iterator iterator = definitions.iterator(); iterator.hasNext();) {
Definition definition = (Definition) iterator.next();
for (Iterator aspects = definition.getConcreteAspects().iterator(); aspects.hasNext();) {
Definition.ConcreteAspect concreteAspect = (Definition.ConcreteAspect) aspects.next();
if (acceptAspect(concreteAspect.name)) {
ConcreteAspectCodeGen gen = new ConcreteAspectCodeGen(concreteAspect, weaver.getWorld());
if (!gen.validate()) {
error("Concrete-aspect '"+concreteAspect.name+"' could not be registered");
break;
}
this.generatedClassHandler.acceptClass(
concreteAspect.name,
gen.getBytes()
);
/*ResolvedType aspect = */weaver.addLibraryAspect(concreteAspect.name);
//generate key for SC
if(namespace==null){
namespace=new StringBuffer(concreteAspect.name);
}else{
namespace = namespace.append(";"+concreteAspect.name);
}
}
}
}
// System.out.println("ClassLoaderWeavingAdaptor.registerAspects() classloader=" + weavingContext.getClassLoaderName() + ", namespace=" + namespace);
/* We didn't register any aspects so disable the adaptor */
if (namespace == null) {
disable();
info("no aspects registered. Disabling weaver for class loader " + getClassLoaderName(loader));
}
if (trace.isTraceEnabled()) trace.exit("registerAspects",isEnabled());
}
/**
* Register the include / exclude filters
* We duplicate simple patterns in startWith filters that will allow faster matching without ResolvedType
*
* @param weaver
* @param loader
* @param definitions
*/
private void registerIncludeExclude(final BcelWeaver weaver, final ClassLoader loader, final List definitions) {
String fastMatchInfo = null;
for (Iterator iterator = definitions.iterator(); iterator.hasNext();) {
Definition definition = (Definition) iterator.next();
for (Iterator iterator1 = definition.getIncludePatterns().iterator(); iterator1.hasNext();) {
String include = (String) iterator1.next();
TypePattern includePattern = new PatternParser(include).parseTypePattern();
m_includeTypePattern.add(includePattern);
fastMatchInfo = looksLikeStartsWith(include);
if (fastMatchInfo != null) {
m_includeStartsWith.add(fastMatchInfo);
}
}
for (Iterator iterator1 = definition.getExcludePatterns().iterator(); iterator1.hasNext();) {
String exclude = (String) iterator1.next();
TypePattern excludePattern = new PatternParser(exclude).parseTypePattern();
m_excludeTypePattern.add(excludePattern);
fastMatchInfo = looksLikeStartsWith(exclude);
if (fastMatchInfo != null) {
m_excludeStartsWith.add(fastMatchInfo);
}
}
}
}
/**
* Checks if the type pattern can be handled as a startswith check
*
* TODO AV - enhance to support "char.sss" ie FQN direclty (match iff equals)
* we could also add support for "*..*charss" endsWith style?
*
* @param typePattern
* @return null if not possible, or the startWith sequence to test against
*/
private String looksLikeStartsWith(String typePattern) {
if (typePattern.indexOf('@') >= 0
|| typePattern.indexOf('+') >= 0
|| typePattern.indexOf(' ') >= 0
|| typePattern.charAt(typePattern.length()-1) != '*') {
return null;
}
// now must looks like with "charsss..*" or "cha.rss..*" etc
// note that "*" and "*..*" won't be fast matched
// and that "charsss.*" will not neither
int length = typePattern.length();
if (typePattern.endsWith("..*") && length > 3) {
if (typePattern.indexOf("..") == length-3 // no ".." before last sequence
&& typePattern.indexOf('*') == length-1) { // no "*" before last sequence
return typePattern.substring(0, length-2).replace('$', '.');
// ie "charsss." or "char.rss." etc
}
}
return null;
}
/**
* Register the dump filter
*
* @param weaver
* @param loader
* @param definitions
*/
private void registerDump(final BcelWeaver weaver, final ClassLoader loader, final List definitions) {
for (Iterator iterator = definitions.iterator(); iterator.hasNext();) {
Definition definition = (Definition) iterator.next();
for (Iterator iterator1 = definition.getDumpPatterns().iterator(); iterator1.hasNext();) {
String dump = (String) iterator1.next();
TypePattern pattern = new PatternParser(dump).parseTypePattern();
m_dumpTypePattern.add(pattern);
}
if (definition.shouldDumpBefore()) {
m_dumpBefore = true;
}
}
}
protected boolean accept(String className, byte[] bytes) {
// avoid ResolvedType if not needed
if (m_excludeTypePattern.isEmpty() && m_includeTypePattern.isEmpty()) {
return true;
}
// still try to avoid ResolvedType if we have simple patterns
String fastClassName = className.replace('/', '.').replace('$', '.');
for (int i = 0; i < m_excludeStartsWith.size(); i++) {
if (fastClassName.startsWith((String)m_excludeStartsWith.get(i))) {
return false;
}
}
/*
* Bug 120363
* If we have an exclude pattern that cannot be matched using "starts with"
* then we cannot fast accept
*/
if (m_excludeTypePattern.isEmpty()) {
boolean fastAccept = false;//defaults to false if no fast include
for (int i = 0; i < m_includeStartsWith.size(); i++) {
fastAccept = fastClassName.startsWith((String)m_includeStartsWith.get(i));
if (fastAccept) {
break;
}
}
}
// needs further analysis
// TODO AV - needs refactoring
// during LTW this calling resolve at that stage is BAD as we do have the bytecode from the classloader hook
// but still go thru resolve that will do a getResourcesAsStream on disk
// this is also problematic for jit stub which are not on disk - as often underlying infra
// does returns null or some other info for getResourceAsStream (f.e. WLS 9 CR248491)
// Instead I parse the given bytecode. But this also means it will be parsed again in
// new WeavingClassFileProvider() from WeavingAdaptor.getWovenBytes()...
ensureDelegateInitialized(className,bytes);
ResolvedType classInfo = delegateForCurrentClass.getResolvedTypeX();//BAD: weaver.getWorld().resolve(UnresolvedType.forName(className), true);
//exclude are "AND"ed
for (Iterator iterator = m_excludeTypePattern.iterator(); iterator.hasNext();) {
TypePattern typePattern = (TypePattern) iterator.next();
if (typePattern.matchesStatically(classInfo)) {
// exclude match - skip
return false;
}
}
//include are "OR"ed
boolean accept = true;//defaults to true if no include
for (Iterator iterator = m_includeTypePattern.iterator(); iterator.hasNext();) {
TypePattern typePattern = (TypePattern) iterator.next();
accept = typePattern.matchesStatically(classInfo);
if (accept) {
break;
}
// goes on if this include did not match ("OR"ed)
}
return accept;
}
//FIXME we don't use include/exclude of others aop.xml
//this can be nice but very dangerous as well to change that
private boolean acceptAspect(String aspectClassName) {
// avoid ResolvedType if not needed
if (m_aspectExcludeTypePattern.isEmpty() && m_aspectIncludeTypePattern.isEmpty()) {
return true;
}
// still try to avoid ResolvedType if we have simple patterns
// EXCLUDE: if one match then reject
String fastClassName = aspectClassName.replace('/', '.').replace('.', '$');
for (int i = 0; i < m_aspectExcludeStartsWith.size(); i++) {
if (fastClassName.startsWith((String)m_aspectExcludeStartsWith.get(i))) {
return false;
}
}
//INCLUDE: if one match then accept
for (int i = 0; i < m_aspectIncludeStartsWith.size(); i++) {
if (fastClassName.startsWith((String)m_aspectIncludeStartsWith.get(i))) {
return true;
}
}
// needs further analysis
ResolvedType classInfo = weaver.getWorld().resolve(UnresolvedType.forName(aspectClassName), true);
//exclude are "AND"ed
for (Iterator iterator = m_aspectExcludeTypePattern.iterator(); iterator.hasNext();) {
TypePattern typePattern = (TypePattern) iterator.next();
if (typePattern.matchesStatically(classInfo)) {
// exclude match - skip
return false;
}
}
//include are "OR"ed
boolean accept = true;//defaults to true if no include
for (Iterator iterator = m_aspectIncludeTypePattern.iterator(); iterator.hasNext();) {
TypePattern typePattern = (TypePattern) iterator.next();
accept = typePattern.matchesStatically(classInfo);
if (accept) {
break;
}
// goes on if this include did not match ("OR"ed)
}
return accept;
}
protected boolean shouldDump(String className, boolean before) {
// Don't dump before weaving unless asked to
if (before && !m_dumpBefore) {
return false;
}
// avoid ResolvedType if not needed
if (m_dumpTypePattern.isEmpty()) {
return false;
}
//TODO AV - optimize for className.startWith only
ResolvedType classInfo = weaver.getWorld().resolve(UnresolvedType.forName(className), true);
//dump
for (Iterator iterator = m_dumpTypePattern.iterator(); iterator.hasNext();) {
TypePattern typePattern = (TypePattern) iterator.next();
if (typePattern.matchesStatically(classInfo)) {
// dump match
return true;
}
}
return false;
}
/*
* shared classes methods
*/
/**
* @return Returns the key.
*/
public String getNamespace() {
// System.out.println("ClassLoaderWeavingAdaptor.getNamespace() classloader=" + weavingContext.getClassLoaderName() + ", namespace=" + namespace);
if(namespace==null) return "";
else return new String(namespace);
}
/**
* Check to see if any classes are stored in the generated classes cache.
* Then flush the cache if it is not empty
* @param className TODO
* @return true if a class has been generated and is stored in the cache
*/
public boolean generatedClassesExistFor (String className) {
// System.err.println("? ClassLoaderWeavingAdaptor.generatedClassesExist() classname=" + className + ", size=" + generatedClasses);
if (className == null) return !generatedClasses.isEmpty();
else return generatedClasses.containsKey(className);
}
/**
* Flush the generated classes cache
*/
public void flushGeneratedClasses() {
// System.err.println("? ClassLoaderWeavingAdaptor.flushGeneratedClasses() generatedClasses=" + generatedClasses);
generatedClasses = new HashMap();
}
private void defineClass(ClassLoader loader, String name, byte[] bytes) {
if (trace.isTraceEnabled()) trace.enter("defineClass",this,new Object[] {loader,name,bytes});
Object clazz = null;
debug("generating class '" + name + "'");
try {
//TODO av protection domain, and optimize
Method defineClass = ClassLoader.class.getDeclaredMethod(
"defineClass", new Class[] { String.class,
bytes.getClass(), int.class, int.class });
defineClass.setAccessible(true);
clazz = defineClass.invoke(loader, new Object[] { name, bytes,
new Integer(0), new Integer(bytes.length) });
} catch (InvocationTargetException e) {
if (e.getTargetException() instanceof LinkageError) {
warn("define generated class failed",e.getTargetException());
//is already defined (happens for X$ajcMightHaveAspect interfaces since aspects are reweaved)
// TODO maw I don't think this is OK and
} else {
warn("define generated class failed",e.getTargetException());
}
} catch (Exception e) {
warn("define generated class failed",e);
}
if (trace.isTraceEnabled()) trace.exit("defineClass",clazz);
}
}
|
129,525 |
Bug 129525 Don't Dump Bytecodes to Syserr in LTW
|
The load-time weaving system can produce truly massive quantities of output when there's a weaving error, since the system dumps the bytecode to syserr. It would be much better to produce an ajcore file and just point to it, or use some other log.
|
resolved fixed
|
04fa1dc
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-08-24T17:32:00Z | 2006-02-27T08:46:40Z |
loadtime/src/org/aspectj/weaver/loadtime/WeavingURLClassLoader.java
|
/* *******************************************************************
* Copyright (c) 2004 IBM Corporation
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Eclipse Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Matthew Webster, Adrian Colyer,
* Martin Lippert initial implementation
* ******************************************************************/
package org.aspectj.weaver.loadtime;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.security.CodeSource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.StringTokenizer;
import org.aspectj.weaver.ExtensibleURLClassLoader;
import org.aspectj.weaver.tools.WeavingAdaptor;
import org.aspectj.weaver.tools.WeavingClassLoader;
public class WeavingURLClassLoader extends ExtensibleURLClassLoader implements WeavingClassLoader {
public static final String WEAVING_CLASS_PATH = "aj.class.path";
public static final String WEAVING_ASPECT_PATH = "aj.aspect.path";
private URL[] aspectURLs;
private WeavingAdaptor adaptor;
private boolean initializingAdaptor;
private Map generatedClasses = new HashMap(); /* String -> byte[] */
/*
* This constructor is needed when using "-Djava.system.class.loader".
*/
public WeavingURLClassLoader (ClassLoader parent) {
this(getURLs(getClassPath()),getURLs(getAspectPath()),parent);
// System.out.println("? WeavingURLClassLoader.WeavingURLClassLoader()");
}
public WeavingURLClassLoader (URL[] urls, ClassLoader parent) {
super(urls,parent);
// System.out.println("WeavingURLClassLoader.WeavingURLClassLoader()");
}
public WeavingURLClassLoader (URL[] classURLs, URL[] aspectURLs, ClassLoader parent) {
super(classURLs,parent);
// System.out.println("> WeavingURLClassLoader.WeavingURLClassLoader() classURLs=" + Arrays.asList(classURLs));
this.aspectURLs = aspectURLs;
/* If either we nor our parent is using an ASPECT_PATH use a new-style
* adaptor
*/
if (this.aspectURLs.length > 0 || getParent() instanceof WeavingClassLoader) {
try {
adaptor = new WeavingAdaptor(this);
}
catch (ExceptionInInitializerError ex) {
ex.printStackTrace(System.out);
throw ex;
}
}
// System.out.println("< WeavingURLClassLoader.WeavingURLClassLoader() adaptor=" + adaptor);
}
private static String getAspectPath () {
return System.getProperty(WEAVING_ASPECT_PATH,"");
}
private static String getClassPath () {
return System.getProperty(WEAVING_CLASS_PATH,"");
}
private static URL[] getURLs (String path) {
List urlList = new ArrayList();
for (StringTokenizer t = new StringTokenizer(path,File.pathSeparator);
t.hasMoreTokens();) {
File f = new File(t.nextToken().trim());
try {
if (f.exists()) {
URL url = f.toURL();
if (url != null) urlList.add(url);
}
} catch (MalformedURLException e) {}
}
URL[] urls = new URL[urlList.size()];
urlList.toArray(urls);
return urls;
}
protected void addURL(URL url) {
adaptor.addURL(url);
super.addURL(url);
}
/**
* Override to weave class using WeavingAdaptor
*/
protected Class defineClass(String name, byte[] b, CodeSource cs) throws IOException {
// System.err.println("? WeavingURLClassLoader.defineClass(" + name + ", [" + b.length + "])");
/* Avoid recursion during adaptor initialization */
if (!initializingAdaptor) {
/* Need to defer creation because of possible recursion during constructor execution */
if (adaptor == null && !initializingAdaptor) {
createAdaptor();
}
b = adaptor.weaveClass(name,b);
}
return super.defineClass(name, b, cs);
}
private void createAdaptor () {
DefaultWeavingContext weavingContext = new DefaultWeavingContext (this) {
/* Ensures consistent LTW messages for testing */
public String getClassLoaderName() {
return loader.getClass().getName();
}
};
ClassLoaderWeavingAdaptor clwAdaptor = new ClassLoaderWeavingAdaptor();
initializingAdaptor = true;
clwAdaptor.initialize(this,weavingContext);
initializingAdaptor = false;
adaptor = clwAdaptor;
}
/**
* Override to find classes generated by WeavingAdaptor
*/
protected byte[] getBytes (String name) throws IOException {
byte[] bytes = super.getBytes(name);
if (bytes == null) {
// return adaptor.findClass(name);
return (byte[])generatedClasses.remove(name);
}
return bytes;
}
/**
* Implement method from WeavingClassLoader
*/
public URL[] getAspectURLs() {
return aspectURLs;
}
public void acceptClass (String name, byte[] bytes) {
generatedClasses.put(name,bytes);
}
// protected synchronized Class loadClass(String name, boolean resolve) throws ClassNotFoundException {
// System.err.println("> WeavingURLClassLoader.loadClass() name=" + name);
// Class clazz= super.loadClass(name, resolve);
// System.err.println("< WeavingURLClassLoader.loadClass() clazz=" + clazz + ", loader=" + clazz.getClassLoader());
// return clazz;
// }
// private interface ClassPreProcessorAdaptor extends ClassPreProcessor {
// public void addURL(URL url);
// }
//
// private class WeavingAdaptorPreProcessor implements ClassPreProcessorAdaptor {
//
// private WeavingAdaptor adaptor;
//
// public WeavingAdaptorPreProcessor (WeavingClassLoader wcl) {
// adaptor = new WeavingAdaptor(wcl);
// }
//
// public void initialize() {
// }
//
// public byte[] preProcess(String className, byte[] bytes, ClassLoader classLoader) {
// return adaptor.weaveClass(className,bytes);
// }
//
// public void addURL(URL url) {
//
// }
// }
}
|
129,525 |
Bug 129525 Don't Dump Bytecodes to Syserr in LTW
|
The load-time weaving system can produce truly massive quantities of output when there's a weaving error, since the system dumps the bytecode to syserr. It would be much better to produce an ajcore file and just point to it, or use some other log.
|
resolved fixed
|
04fa1dc
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-08-24T17:32:00Z | 2006-02-27T08:46:40Z |
tests/src/org/aspectj/systemtest/ajc153/Ajc153Tests.java
|
/*******************************************************************************
* Copyright (c) 2006 IBM
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Andy Clement - initial API and implementation
*******************************************************************************/
package org.aspectj.systemtest.ajc153;
import java.io.File;
import junit.framework.Test;
import org.aspectj.testing.Utils;
import org.aspectj.testing.XMLBasedAjcTestCase;
import org.aspectj.weaver.bcel.Utility;
public class Ajc153Tests extends org.aspectj.testing.XMLBasedAjcTestCase {
//public void testGenericsProblem_pr151978() { runTest("generics problem");}
//public void testMissingLineNumbersInStacktraceBefore_pr145442() { runTest("missing line numbers in stacktrace before");}
//public void testMissingLineNumbersInStacktraceAfter_pr145442() { runTest("missing line numbers in stacktrace after");}
//public void testMissingLineNumbersInStacktraceAround_pr145442() { runTest("missing line numbers in stacktrace around");}
// public void testArgnamesAndJavac_pr148381() { runTest("argNames and javac");}
// public void testCFlowXMLAspectLTW_pr149096() { runTest("cflow xml concrete aspect"); }
// public void testAmbiguousBinding_pr121805() { runTest("ambiguous binding");}
public void 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 testVisibilityProblem_pr149071() { runTest("visibility problem");}
// public void testAdviceNotWovenAspectPath_pr147841() { runTest("advice not woven on aspectpath");}
public void testGenericSignatures_pr148409() { runTest("generic signature problem"); }
// public void testBrokenIfArgsCflowAtAj_pr145018() { runTest("ataj crashing with cflow, if and args");}
public void testCantFindType_pr149322_01() {runTest("can't find type on interface call 1");}
public void testCantFindType_pr149322_02() {runTest("can't find type on interface call 2");}
public void testCantFindType_pr149322_03() {runTest("can't find type on interface call 3");}
public void 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 static Test suite() {
return XMLBasedAjcTestCase.loadSuite(Ajc153Tests.class);
}
protected File getSpecFile() {
return new File("../tests/src/org/aspectj/systemtest/ajc153/ajc153.xml");
}
}
|
129,525 |
Bug 129525 Don't Dump Bytecodes to Syserr in LTW
|
The load-time weaving system can produce truly massive quantities of output when there's a weaving error, since the system dumps the bytecode to syserr. It would be much better to produce an ajcore file and just point to it, or use some other log.
|
resolved fixed
|
04fa1dc
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-08-24T17:32:00Z | 2006-02-27T08:46:40Z |
weaver/src/org/aspectj/weaver/tools/WeavingAdaptor.java
|
/* *******************************************************************
* Copyright (c) 2004 IBM Corporation
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Eclipse Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Matthew Webster, Adrian Colyer,
* Martin Lippert initial implementation
* ******************************************************************/
package org.aspectj.weaver.tools;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.StringTokenizer;
import org.aspectj.bridge.AbortException;
import org.aspectj.bridge.IMessage;
import org.aspectj.bridge.IMessageContext;
import org.aspectj.bridge.IMessageHandler;
import org.aspectj.bridge.Message;
import org.aspectj.bridge.MessageUtil;
import org.aspectj.bridge.MessageWriter;
import org.aspectj.bridge.Version;
import org.aspectj.bridge.WeaveMessage;
import org.aspectj.bridge.IMessage.Kind;
import org.aspectj.org.objectweb.asm.ClassReader;
import org.aspectj.util.FileUtil;
import org.aspectj.util.LangUtil;
import org.aspectj.weaver.IClassFileProvider;
import org.aspectj.weaver.IWeaveRequestor;
import org.aspectj.weaver.ResolvedType;
import org.aspectj.weaver.bcel.BcelObjectType;
import org.aspectj.weaver.bcel.BcelWeaver;
import org.aspectj.weaver.bcel.BcelWorld;
import org.aspectj.weaver.bcel.UnwovenClassFile;
import org.aspectj.weaver.bcel.Utility;
/**
* This adaptor allows the AspectJ compiler to be embedded in an existing
* system to facilitate load-time weaving. It provides an interface for a
* weaving class loader to provide a classpath to be woven by a set of
* aspects. A callback is supplied to allow a class loader to define classes
* generated by the compiler during the weaving process.
* <p>
* A weaving class loader should create a <code>WeavingAdaptor</code> before
* any classes are defined, typically during construction. The set of aspects
* passed to the adaptor is fixed for the lifetime of the adaptor although the
* classpath can be augmented. A system property can be set to allow verbose
* weaving messages to be written to the console.
*
*/
public class WeavingAdaptor implements IMessageContext {
/**
* System property used to turn on verbose weaving messages
*/
public static final String WEAVING_ADAPTOR_VERBOSE = "aj.weaving.verbose";
public static final String SHOW_WEAVE_INFO_PROPERTY = "org.aspectj.weaver.showWeaveInfo";
public static final String TRACE_MESSAGES_PROPERTY = "org.aspectj.tracing.messages";
private boolean enabled = true;
protected boolean verbose = getVerbose();
protected BcelWorld bcelWorld;
protected BcelWeaver weaver;
private IMessageHandler messageHandler;
private WeavingAdaptorMessageHandler messageHolder;
protected GeneratedClassHandler generatedClassHandler;
protected Map generatedClasses = new HashMap(); /* String -> UnwovenClassFile */
protected BcelObjectType delegateForCurrentClass; // lazily initialized, should be used to prevent parsing bytecode multiple times
private static Trace trace = TraceFactory.getTraceFactory().getTrace(WeavingAdaptor.class);
protected WeavingAdaptor () {
}
/**
* Construct a WeavingAdaptor with a reference to a weaving class loader. The
* adaptor will automatically search the class loader hierarchy to resolve
* classes. The adaptor will also search the hierarchy for WeavingClassLoader
* instances to determine the set of aspects to be used ofr weaving.
* @param loader instance of <code>ClassLoader</code>
*/
public WeavingAdaptor (WeavingClassLoader loader) {
// System.err.println("? WeavingAdaptor.<init>(" + loader +"," + aspectURLs.length + ")");
generatedClassHandler = loader;
init(getFullClassPath((ClassLoader)loader),getFullAspectPath((ClassLoader)loader/*,aspectURLs*/));
}
/**
* Construct a WeavingAdator with a reference to a
* <code>GeneratedClassHandler</code>, a full search path for resolving
* classes and a complete set of aspects. The search path must include
* classes loaded by the class loader constructing the WeavingAdaptor and
* all its parents in the hierarchy.
* @param handler <code>GeneratedClassHandler</code>
* @param classURLs the URLs from which to resolve classes
* @param aspectURLs the aspects used to weave classes defined by this class loader
*/
public WeavingAdaptor (GeneratedClassHandler handler, URL[] classURLs, URL[] aspectURLs) {
// System.err.println("? WeavingAdaptor.<init>()");
generatedClassHandler = handler;
init(FileUtil.makeClasspath(classURLs),FileUtil.makeClasspath(aspectURLs));
}
private List getFullClassPath (ClassLoader loader) {
List list = new LinkedList();
for (; loader != null; loader = loader.getParent()) {
if (loader instanceof URLClassLoader) {
URL[] urls = ((URLClassLoader)loader).getURLs();
list.addAll(0,FileUtil.makeClasspath(urls));
}
else {
warn("cannot determine classpath");
}
}
list.addAll(0,makeClasspath(System.getProperty("sun.boot.class.path")));
return list;
}
private List getFullAspectPath (ClassLoader loader) {
List list = new LinkedList();
for (; loader != null; loader = loader.getParent()) {
if (loader instanceof WeavingClassLoader) {
URL[] urls = ((WeavingClassLoader)loader).getAspectURLs();
list.addAll(0,FileUtil.makeClasspath(urls));
}
}
return list;
}
private static boolean getVerbose () {
return Boolean.getBoolean(WEAVING_ADAPTOR_VERBOSE);
}
private void init(List classPath, List aspectPath) {
createMessageHandler();
info("using classpath: " + classPath);
info("using aspectpath: " + aspectPath);
bcelWorld = new BcelWorld(classPath,messageHandler,null);
bcelWorld.setXnoInline(false);
bcelWorld.getLint().loadDefaultProperties();
if (LangUtil.is15VMOrGreater()) {
bcelWorld.setBehaveInJava5Way(true);
}
weaver = new BcelWeaver(bcelWorld);
registerAspectLibraries(aspectPath);
}
protected void createMessageHandler() {
messageHolder = new WeavingAdaptorMessageHandler(new PrintWriter(System.err));
messageHandler = messageHolder;
if (verbose) messageHandler.dontIgnore(IMessage.INFO);
if (Boolean.getBoolean(SHOW_WEAVE_INFO_PROPERTY)) messageHandler.dontIgnore(IMessage.WEAVEINFO);
info("AspectJ Weaver Version " + Version.text + " built on " + Version.time_text); //$NON-NLS-1$
}
protected IMessageHandler getMessageHandler () {
return messageHandler;
}
protected void setMessageHandler (IMessageHandler mh) {
if (mh instanceof ISupportsMessageContext) {
ISupportsMessageContext smc = (ISupportsMessageContext)mh;
smc.setMessageContext(this);
}
if (mh != messageHolder) messageHolder.setDelegate(mh);
messageHolder.flushMessages();
}
protected void disable () {
enabled = false;
messageHolder.flushMessages();
}
protected boolean isEnabled () {
return enabled;
}
/**
* Appends URL to path used by the WeavingAdptor to resolve classes
* @param url to be appended to search path
*/
public void addURL(URL url) {
File libFile = new File(url.getPath());
try {
weaver.addLibraryJarFile(libFile);
}
catch (IOException ex) {
warn("bad library: '" + libFile + "'");
}
}
/**
* Weave a class using aspects previously supplied to the adaptor.
* @param name the name of the class
* @param bytes the class bytes
* @return the woven bytes
* @exception IOException weave failed
*/
public byte[] weaveClass (String name, byte[] bytes) throws IOException {
if (enabled) {
try {
delegateForCurrentClass=null;
if (trace.isTraceEnabled()) trace.enter("weaveClass",this,new Object[] {name,bytes});
name = name.replace('/','.');
if (couldWeave(name, bytes)) {
if (accept(name, bytes)) {
// TODO @AspectJ problem
// Annotation style aspects need to be included regardless in order to get
// a valid aspectOf()/hasAspect() generated in them. However - if they are excluded
// (via include/exclude in aop.xml) they really should only get aspectOf()/hasAspect()
// and not be included in the full set of aspects being applied by 'this' weaver
debug("weaving '" + name + "'");
bytes = getWovenBytes(name, bytes);
} else if (shouldWeaveAnnotationStyleAspect(name, bytes)) {
// an @AspectJ aspect needs to be at least munged by the aspectOf munger
debug("weaving '" + name + "'");
bytes = getAtAspectJAspectBytes(name, bytes);
} else {
debug("not weaving '" + name + "'");
}
} else {
debug("cannot weave '" + name + "'");
}
if (trace.isTraceEnabled()) trace.exit("weaveClass",bytes);
} finally {
delegateForCurrentClass=null;
}
}
return bytes;
}
/**
* @param name
* @return true if even valid to weave: either with an accept check or to munge it for @AspectJ aspectof support
*/
private boolean couldWeave (String name, byte[] bytes) {
return !generatedClasses.containsKey(name) && shouldWeaveName(name);
}
//ATAJ
protected boolean accept(String name, byte[] bytes) {
return true;
}
protected boolean shouldDump(String name, boolean before) {
return false;
}
private boolean shouldWeaveName (String name) {
boolean should =
!((name.startsWith("org.aspectj.")
|| name.startsWith("java.")
|| name.startsWith("javax."))
//|| name.startsWith("$Proxy")//JDK proxies//FIXME AV is that 1.3 proxy ? fe. ataspect.$Proxy0 is a java5 proxy...
|| name.startsWith("sun.reflect."));//JDK reflect
return should;
}
/**
* We allow @AJ aspect weaving so that we can add aspectOf() as part of the weaving
* (and not part of the source compilation)
*
* @param name
* @param bytes bytecode (from classloader), allow to NOT lookup stuff on disk again during resolve
* @return true if @Aspect
*/
private boolean shouldWeaveAnnotationStyleAspect(String name, byte[] bytes) {
if (delegateForCurrentClass==null) {
if (weaver.getWorld().isASMAround()) return asmCheckAnnotationStyleAspect(bytes);
else ensureDelegateInitialized(name, bytes);
}
return (delegateForCurrentClass.isAnnotationStyleAspect());
}
private boolean asmCheckAnnotationStyleAspect(byte[] bytes) {
IsAtAspectAnnotationVisitor detector = new IsAtAspectAnnotationVisitor();
ClassReader cr = new ClassReader(bytes);
try {
cr.accept(detector, true);//, ClassReader.SKIP_DEBUG | ClassReader.SKIP_CODE | ClassReader.SKIP_FRAMES);
} catch (Exception spe) {
// if anything goes wrong, e.g., an NPE, then assume it's NOT an @AspectJ aspect...
System.err.println("Unexpected problem parsing bytes to discover @Aspect annotation");
spe.printStackTrace();
return false;
}
return detector.isAspect();
}
protected void ensureDelegateInitialized(String name,byte[] bytes) {
if (delegateForCurrentClass==null)
delegateForCurrentClass = ((BcelWorld)weaver.getWorld()).addSourceObjectType(Utility.makeJavaClass(name, bytes));
}
/**
* Weave a set of bytes defining a class.
* @param name the name of the class being woven
* @param bytes the bytes that define the class
* @return byte[] the woven bytes for the class
* @throws IOException
*/
private byte[] getWovenBytes(String name, byte[] bytes) throws IOException {
WeavingClassFileProvider wcp = new WeavingClassFileProvider(name,bytes);
weaver.weave(wcp);
return wcp.getBytes();
}
/**
* Weave a set of bytes defining a class for only what is needed to turn @AspectJ aspect
* in a usefull form ie with aspectOf method - see #113587
* @param name the name of the class being woven
* @param bytes the bytes that define the class
* @return byte[] the woven bytes for the class
* @throws IOException
*/
private byte[] getAtAspectJAspectBytes(String name, byte[] bytes) throws IOException {
WeavingClassFileProvider wcp = new WeavingClassFileProvider(name,bytes);
wcp.setApplyAtAspectJMungersOnly();
weaver.weave(wcp);
return wcp.getBytes();
}
private void registerAspectLibraries(List aspectPath) {
// System.err.println("? WeavingAdaptor.registerAspectLibraries(" + aspectPath + ")");
for (Iterator i = aspectPath.iterator(); i.hasNext();) {
String libName = (String)i.next();
addAspectLibrary(libName);
}
weaver.prepareForWeave();
}
/*
* Register an aspect library with this classloader for use during
* weaving. This class loader will also return (unmodified) any of the
* classes in the library in response to a <code>findClass()</code> request.
* The library is not required to be on the weavingClasspath given when this
* classloader was constructed.
* @param aspectLibraryJarFile a jar file representing an aspect library
* @throws IOException
*/
private void addAspectLibrary(String aspectLibraryName) {
File aspectLibrary = new File(aspectLibraryName);
if (aspectLibrary.isDirectory()
|| (FileUtil.isZipFile(aspectLibrary))) {
try {
info("adding aspect library: '" + aspectLibrary + "'");
weaver.addLibraryJarFile(aspectLibrary);
} catch (IOException ex) {
error("exception adding aspect library: '" + ex + "'");
}
} else {
error("bad aspect library: '" + aspectLibrary + "'");
}
}
private static List makeClasspath(String cp) {
List ret = new ArrayList();
if (cp != null) {
StringTokenizer tok = new StringTokenizer(cp,File.pathSeparator);
while (tok.hasMoreTokens()) {
ret.add(tok.nextToken());
}
}
return ret;
}
protected boolean debug (String message) {
return MessageUtil.debug(messageHandler,message);
}
protected boolean info (String message) {
return MessageUtil.info(messageHandler,message);
}
protected boolean warn (String message) {
return MessageUtil.warn(messageHandler,message);
}
protected boolean warn (String message, Throwable th) {
return messageHandler.handleMessage(new Message(message, IMessage.WARNING, th, null));
}
protected boolean error (String message) {
return MessageUtil.error(messageHandler,message);
}
public String getContextId () {
return "WeavingAdaptor";
}
/**
* Dump the given bytcode in _dump/... (dev mode)
*
* @param name
* @param b
* @param before whether we are dumping before weaving
* @throws Throwable
*/
protected void dump(String name, byte[] b, boolean before) {
String dirName = "_ajdump";
if (before) dirName = dirName + File.separator + "_before";
String className = name.replace('.', '/');
final File dir;
if (className.indexOf('/') > 0) {
dir = new File(dirName + File.separator + className.substring(0, className.lastIndexOf('/')));
} else {
dir = new File(dirName);
}
dir.mkdirs();
String fileName = dirName + File.separator + className + ".class";
try {
// System.out.println("WeavingAdaptor.dump() fileName=" + new File(fileName).getAbsolutePath());
FileOutputStream os = new FileOutputStream(fileName);
os.write(b);
os.close();
}
catch (IOException ex) {
warn("unable to dump class " + name + " in directory " + dirName,ex);
}
}
/**
* Processes messages arising from weaver operations.
* Tell weaver to abort on any message more severe than warning.
*/
protected class WeavingAdaptorMessageHandler implements IMessageHandler {
private IMessageHandler delegate;
private boolean accumulating = true;
private List messages = new ArrayList();
protected boolean traceMessages = Boolean.getBoolean(TRACE_MESSAGES_PROPERTY);
public WeavingAdaptorMessageHandler (PrintWriter writer) {
this.delegate = new WeavingAdaptorMessageWriter(writer);
}
public boolean handleMessage(IMessage message) throws AbortException {
if (traceMessages) traceMessage(message);
if (accumulating) {
boolean result = addMessage(message);
if (0 <= message.getKind().compareTo(IMessage.ERROR)) {
throw new AbortException(message);
}
return result;
}
else return delegate.handleMessage(message);
}
private void traceMessage (IMessage message) {
if (message instanceof WeaveMessage) {
trace.debug(render(message));
}
else if (message.isDebug()) {
trace.debug(render(message));
}
else if (message.isInfo()) {
trace.info(render(message));
}
else if (message.isWarning()) {
trace.warn(render(message),message.getThrown());
}
else if (message.isError()) {
trace.error(render(message),message.getThrown());
}
else if (message.isFailed()) {
trace.fatal(render(message),message.getThrown());
}
else if (message.isAbort()) {
trace.fatal(render(message),message.getThrown());
}
else {
trace.error(render(message),message.getThrown());
}
}
protected String render(IMessage message) {
return "[" + getContextId() + "] " + message.toString();
}
public boolean isIgnoring (Kind kind) {
return delegate.isIgnoring(kind);
}
public void dontIgnore (IMessage.Kind kind) {
if (null != kind) {
delegate.dontIgnore(kind);
}
}
private boolean addMessage (IMessage message) {
messages.add(message);
return true;
}
public void flushMessages () {
for (Iterator iter = messages.iterator(); iter.hasNext();) {
IMessage message = (IMessage)iter.next();
delegate.handleMessage(message);
}
accumulating = false;
messages.clear();
}
public void setDelegate (IMessageHandler messageHandler) {
delegate = messageHandler;
}
}
protected class WeavingAdaptorMessageWriter extends MessageWriter {
private Set ignoring = new HashSet();
private IMessage.Kind failKind;
public WeavingAdaptorMessageWriter (PrintWriter writer) {
super(writer,true);
ignore(IMessage.WEAVEINFO);
ignore(IMessage.DEBUG);
ignore(IMessage.INFO);
this.failKind = IMessage.ERROR;
}
public boolean handleMessage(IMessage message) throws AbortException {
boolean result = super.handleMessage(message);
if (0 <= message.getKind().compareTo(failKind)) {
throw new AbortException(message);
}
return true;
}
public boolean isIgnoring (Kind kind) {
return ((null != kind) && (ignoring.contains(kind)));
}
/**
* Set a message kind to be ignored from now on
*/
public void ignore (IMessage.Kind kind) {
if ((null != kind) && (!ignoring.contains(kind))) {
ignoring.add(kind);
}
}
/**
* Remove a message kind from the list of those ignored from now on.
*/
public void dontIgnore (IMessage.Kind kind) {
if (null != kind) {
ignoring.remove(kind);
}
}
protected String render(IMessage message) {
return "[" + getContextId() + "] " + super.render(message);
}
}
private class WeavingClassFileProvider implements IClassFileProvider {
private UnwovenClassFile unwovenClass;
private List unwovenClasses = new ArrayList(); /* List<UnovenClassFile> */
private UnwovenClassFile wovenClass;
private boolean isApplyAtAspectJMungersOnly = false;
public WeavingClassFileProvider (String name, byte[] bytes) {
ensureDelegateInitialized(name, bytes);
this.unwovenClass = new UnwovenClassFile(name,delegateForCurrentClass.getResolvedTypeX().getName(),bytes);
this.unwovenClasses.add(unwovenClass);
if (shouldDump(name.replace('/', '.'),true)) {
dump(name, bytes, true);
}
}
public void setApplyAtAspectJMungersOnly() {
isApplyAtAspectJMungersOnly = true;
}
public boolean isApplyAtAspectJMungersOnly() {
return isApplyAtAspectJMungersOnly;
}
public byte[] getBytes () {
if (wovenClass != null) return wovenClass.getBytes();
else return unwovenClass.getBytes();
}
public Iterator getClassFileIterator() {
return unwovenClasses.iterator();
}
public IWeaveRequestor getRequestor() {
return new IWeaveRequestor() {
public void acceptResult(UnwovenClassFile result) {
if (wovenClass == null) {
wovenClass = result;
String name = result.getClassName();
if (shouldDump(name.replace('/', '.'), false)) {
dump(name, result.getBytes(), false);
}
}
/* Classes generated by weaver e.g. around closure advice */
else {
String className = result.getClassName();
generatedClasses.put(className,result);
generatedClasses.put(wovenClass.getClassName(),result);
generatedClassHandler.acceptClass(className,result.getBytes());
}
}
public void processingReweavableState() { }
public void addingTypeMungers() {}
public void weavingAspects() {}
public void weavingClasses() {}
public void weaveCompleted() {
ResolvedType.resetPrimitives();
if (delegateForCurrentClass!=null) delegateForCurrentClass.weavingCompleted();
ResolvedType.resetPrimitives();
//bcelWorld.discardType(typeBeingProcessed.getResolvedTypeX()); // work in progress
}
};
}
}
}
|
155,213 |
Bug 155213 [ltw] can get into a state with the Version static initializer
|
The static initializer in Version that parses the time_text string and turns it into a long field seems to sometimes get loadtime weaving into a state - touching DateFormatters early on is always a pain, so I'm moving it to be processed on first reference. I could take it a step further ... if WeaverStateInfo didn't write out the time (it doesnt read it back in!!) it would never be used at all in normal processing - potentially saving us from loading a bunch of underpinning junk to do the formatting...
|
resolved fixed
|
40cf610
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-08-25T12:41:38Z | 2006-08-25T12:46:40Z |
ajde/src/org/aspectj/ajde/ui/swing/OptionsFrame.java
|
/* *******************************************************************
* Copyright (c) 1999-2001 Xerox Corporation,
* 2002 Palo Alto Research Center, Incorporated (PARC).
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Eclipse Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Xerox/PARC initial implementation
* ******************************************************************/
package org.aspectj.ajde.ui.swing;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.io.IOException;
import java.util.Date;
import javax.swing.BorderFactory;
//import javax.swing.Box;
//import javax.swing.ButtonGroup;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;
import javax.swing.JTextArea;
import javax.swing.UIManager;
import javax.swing.border.Border;
import javax.swing.border.TitledBorder;
import org.aspectj.ajde.Ajde;
import org.aspectj.bridge.Version;
/**
* UI for setting user-configureable options.
*
* @author Mik Kersten
*/
public class OptionsFrame extends JFrame {
private static final long serialVersionUID = -859222442871124487L;
// XXX using \n b/c JTextArea.setLineWrap(true) lineates inside words.
private static final String ABOUT_TEXT =
"\nThe AspectJ compiler and core tools are produced by the\n" +
"AspectJ project.\n\n" +
"This software is distributed under the Eclipse Public License\n" +
"version 1.0, approved by the Open Source Initiative as\n" +
"conforming to the Open Source Definition.\n\n" +
"For support or for more information about the AspectJ\n" +
"project or the license, visit the project home page at\n" +
" http://eclipse.org/aspectj\n\n" +
"If you find a bug (not solved by the documentation in the\n" +
"Development Environment Guide available with this release,\n" +
"any release notes, or the bug database), please submit steps\n" +
"to reproduce the bug (using the IDE component) at:\n" +
" http://bugs.eclipse.org/bugs/enter_bug.cgi?product=AspectJ";
private JTabbedPane main_tabbedPane = new JTabbedPane();
private JPanel button_panel = new JPanel();
private JButton apply_button = new JButton();
private JButton cancel_button = new JButton();
private JButton ok_button = new JButton();
private TitledBorder titledBorder1;
private TitledBorder titledBorder2;
private TitledBorder titledBorder3;
// private Border border1;
private TitledBorder titledBorder4;
private TitledBorder titledBorder5;
// private Border border2;
private TitledBorder titledBorder6;
// private Box temp_box = Box.createVerticalBox();
// private Border border3;
private TitledBorder titledBorder7;
private Border border4;
private TitledBorder titledBorder8;
private Border border5;
private TitledBorder titledBorder9;
// private Border border6;
private TitledBorder titledBorder10;
// private ButtonGroup views_buttonGroup = new ButtonGroup();
private Border border7;
private TitledBorder titledBorder11;
private Border border8;
private TitledBorder titledBorder12;
private JPanel about_panel = new JPanel();
private BorderLayout borderLayout9 = new BorderLayout();
JTextArea jTextArea1 = new JTextArea();
JPanel jPanel1 = new JPanel();
JLabel version_label = new JLabel();
JLabel jLabel1 = new JLabel();
BorderLayout borderLayout1 = new BorderLayout();
Border border9;
JLabel built_label = new JLabel();
public OptionsFrame(IconRegistry icons) {
try {
jbInit();
this.setTitle("AJDE Settings");
this.setIconImage(((ImageIcon)icons.getBrowserOptionsIcon()).getImage());
this.setSize(500, 500);
this.setLocation(200, 100);
version_label.setText("Version: " + Version.text);
built_label.setText("Built: " + new Date(Version.time).toString());
addOptionsPanel(new BuildOptionsPanel());
loadOptions();
}
catch(Exception e) {
Ajde.getDefault().getErrorHandler().handleError("Could not open OptionsFrame", e);
}
}
/**
* Adds the panel in the second-to-last postion.
*/
public void addOptionsPanel(OptionsPanel panel) {
main_tabbedPane.add(panel, main_tabbedPane.getComponentCount()-1);
loadOptions();
}
public void removeOptionsPanel(OptionsPanel panel) {
main_tabbedPane.remove(panel);
}
public void showPanel(OptionsPanel panel) {
setVisible(true);
main_tabbedPane.setSelectedComponent(panel);
}
private void loadOptions() {
try {
Component[] components = main_tabbedPane.getComponents();
for
(int i = 0; i < components.length; i++) {
if (components[i] instanceof OptionsPanel) {
((OptionsPanel)components[i]).loadOptions();
}
}
} catch (IOException ioe) {
Ajde.getDefault().getErrorHandler().handleError("Could not load options.", ioe);
}
}
private void saveOptions() {
try {
Component[] components = main_tabbedPane.getComponents();
for (int i = 0; i < components.length; i++) {
if (components[i] instanceof OptionsPanel) {
((OptionsPanel)components[i]).saveOptions();
}
}
} catch (IOException ioe) {
Ajde.getDefault().getErrorHandler().handleError("Could not load options.", ioe);
}
}
private void close() {
this.setVisible(false);
}
private void apply_button_actionPerformed(ActionEvent e) {
saveOptions();
}
private void ok_button_actionPerformed(ActionEvent e) {
saveOptions();
close();
}
private void cancel_button_actionPerformed(ActionEvent e) {
close();
}
private void jbInit() throws Exception {
titledBorder1 = new TitledBorder(BorderFactory.createEtchedBorder(Color.white,new Color(156, 156, 158)),"Sorting");
titledBorder2 = new TitledBorder(BorderFactory.createEtchedBorder(Color.white,new Color(148, 145, 140)),"Associations (navigeable relations between sturcture nodes)");
titledBorder3 = new TitledBorder(BorderFactory.createEtchedBorder(Color.white,new Color(156, 156, 158)),"Member Filtering (nodes to exclude from view)");
BorderFactory.createLineBorder(Color.black,2);
titledBorder4 = new TitledBorder(BorderFactory.createEtchedBorder(Color.white,new Color(148, 145, 140)),"Compile Options");
titledBorder5 = new TitledBorder("");
BorderFactory.createLineBorder(Color.black,2);
titledBorder6 = new TitledBorder(BorderFactory.createEtchedBorder(Color.white,new Color(148, 145, 140)),"Run Options");
BorderFactory.createEtchedBorder(Color.white,new Color(156, 156, 158));
titledBorder7 = new TitledBorder(BorderFactory.createEtchedBorder(Color.white,new Color(156, 156, 158)),"Granularity (all nodes below selected level will be hidden)");
border4 = BorderFactory.createEtchedBorder(Color.white,new Color(156, 156, 158));
titledBorder8 = new TitledBorder(border4,"Member Visibility");
border5 = BorderFactory.createEtchedBorder(Color.white,new Color(156, 156, 158));
titledBorder9 = new TitledBorder(border5,"Member Modifiers");
BorderFactory.createEmptyBorder();
titledBorder10 = new TitledBorder(BorderFactory.createEtchedBorder(Color.white,new Color(148, 145, 140)),"Structure View Properties");
border7 = BorderFactory.createEtchedBorder(Color.white,new Color(156, 156, 158));
titledBorder11 = new TitledBorder(border7,"Member Kinds");
border8 = BorderFactory.createEtchedBorder(Color.white,new Color(148, 145, 140));
titledBorder12 = new TitledBorder(border8,"Build Paths");
border9 = BorderFactory.createEmptyBorder(6,6,6,6);
jPanel1.setLayout(borderLayout1);
jLabel1.setFont(new java.awt.Font("Dialog", 1, 14));
jLabel1.setText("AspectJ Development Environment (AJDE)");
version_label.setFont(new java.awt.Font("Dialog", 1, 12));
version_label.setText("Version: ");
apply_button.setFont(new java.awt.Font("Dialog", 0, 11));
apply_button.setMaximumSize(new Dimension(70, 24));
apply_button.setMinimumSize(new Dimension(63, 24));
apply_button.setPreferredSize(new Dimension(70, 24));
apply_button.setText("Apply");
apply_button.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(ActionEvent e) {
apply_button_actionPerformed(e);
}
});
cancel_button.setFont(new java.awt.Font("Dialog", 0, 11));
cancel_button.setMaximumSize(new Dimension(70, 24));
cancel_button.setMinimumSize(new Dimension(67, 24));
cancel_button.setPreferredSize(new Dimension(70, 24));
cancel_button.setText("Cancel");
cancel_button.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(ActionEvent e) {
cancel_button_actionPerformed(e);
}
});
ok_button.setFont(new java.awt.Font("Dialog", 0, 11));
ok_button.setMaximumSize(new Dimension(70, 24));
ok_button.setMinimumSize(new Dimension(49, 24));
ok_button.setPreferredSize(new Dimension(70, 24));
ok_button.setText("OK");
ok_button.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(ActionEvent e) {
ok_button_actionPerformed(e);
}
});
main_tabbedPane.setFont(new java.awt.Font("Dialog", 0, 11));
titledBorder1.setTitle("Ordering (sort order of nodes)");
titledBorder1.setTitleFont(new java.awt.Font("Dialog", 0, 11));
titledBorder2.setTitle("Associations (navigeable relations between structure nodes)");
titledBorder2.setTitleFont(new java.awt.Font("Dialog", 0, 11));
titledBorder3.setTitleFont(new java.awt.Font("Dialog", 0, 11));
titledBorder6.setTitleFont(new java.awt.Font("Dialog", 0, 11));
titledBorder5.setTitleFont(new java.awt.Font("Dialog", 0, 11));
titledBorder4.setTitle("Compiler Flags");
titledBorder4.setTitleFont(new java.awt.Font("Dialog", 0, 11));
titledBorder7.setTitleFont(new java.awt.Font("Dialog", 0, 11));
titledBorder8.setTitle("Access Modifiers");
titledBorder8.setTitleFont(new java.awt.Font("Dialog", 0, 11));
titledBorder9.setTitleFont(new java.awt.Font("Dialog", 0, 11));
titledBorder10.setTitleFont(new java.awt.Font("Dialog", 0, 11));
titledBorder11.setTitleFont(new java.awt.Font("Dialog", 0, 11));
titledBorder12.setTitleFont(new java.awt.Font("Dialog", 0, 11));
about_panel.setLayout(borderLayout9);
jTextArea1.setBackground(UIManager.getColor("ColorChooser.background"));
jTextArea1.setFont(new java.awt.Font("SansSerif", 0, 12));
jTextArea1.setEditable(false);
jTextArea1.setText(ABOUT_TEXT);
about_panel.setBorder(border9);
built_label.setText("Built: ");
built_label.setFont(new java.awt.Font("Dialog", 1, 12));
main_tabbedPane.add(about_panel, "About AJDE");
this.getContentPane().add(button_panel, BorderLayout.SOUTH);
button_panel.add(ok_button, null);
button_panel.add(cancel_button, null);
button_panel.add(apply_button, null);
this.getContentPane().add(main_tabbedPane, BorderLayout.CENTER);
about_panel.add(jTextArea1, BorderLayout.CENTER);
about_panel.add(jPanel1, BorderLayout.NORTH);
jPanel1.add(jLabel1, BorderLayout.NORTH);
jPanel1.add(version_label, BorderLayout.CENTER);
jPanel1.add(built_label, BorderLayout.SOUTH);
}
}
|
155,213 |
Bug 155213 [ltw] can get into a state with the Version static initializer
|
The static initializer in Version that parses the time_text string and turns it into a long field seems to sometimes get loadtime weaving into a state - touching DateFormatters early on is always a pain, so I'm moving it to be processed on first reference. I could take it a step further ... if WeaverStateInfo didn't write out the time (it doesnt read it back in!!) it would never be used at all in normal processing - potentially saving us from loading a bunch of underpinning junk to do the formatting...
|
resolved fixed
|
40cf610
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-08-25T12:41:38Z | 2006-08-25T12:46:40Z |
bridge/src/org/aspectj/bridge/Version.java
|
/* ********************************************************************
* Copyright (c) 1998-2001 Xerox Corporation,
* 2002 Palo Alto Research Center, Incorporated (PARC).
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Eclipse Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Xerox/PARC initial implementation
* *******************************************************************/
package org.aspectj.bridge;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.Date;
/** release-specific version information */
public class Version {
// generated from build/lib/BridgeVersion.java
/** default version value for development version */
public static final String DEVELOPMENT = "DEVELOPMENT";
// VersionUptodate.java depends on this value
/** default time value for development version */
public static final long NOTIME = 0L;
/** set by build script */
public static final String text = "DEVELOPMENT";
// VersionUptodate.java scans for "static final String text = "
/**
* Time text set by build script using SIMPLE_DATE_FORMAT.
* (if DEVELOPMENT version, invalid)
*/
public static final String time_text = "";
/**
* time in seconds-since-... format, used by programmatic clients.
* (if DEVELOPMENT version, NOTIME)
*/
public static final long time;
/** format used by build script to set time_text */
public static final String SIMPLE_DATE_FORMAT = "EEEE MMM d, yyyy 'at' HH:mm:ss z";
// if not DEVELOPMENT version, read time text using format used to set time
static {
long foundTime = NOTIME;
try {
SimpleDateFormat format = new SimpleDateFormat(SIMPLE_DATE_FORMAT);
ParsePosition pos = new ParsePosition(0);
Date date = format.parse(time_text, pos);
foundTime = date.getTime();
} catch (Throwable t) {
}
time = foundTime;
}
/**
* Test whether the version is as specified by any first argument.
* Emit text to System.err on failure
* @param args String[] with first argument equal to Version.text
* @see Version#text
*/
public static void main(String[] args) {
if ((null != args) && (0 < args.length)) {
if (!Version.text.equals(args[0])) {
System.err.println("version expected: \""
+ args[0]
+ "\" actual=\""
+ Version.text
+ "\"");
}
}
}
}
|
155,213 |
Bug 155213 [ltw] can get into a state with the Version static initializer
|
The static initializer in Version that parses the time_text string and turns it into a long field seems to sometimes get loadtime weaving into a state - touching DateFormatters early on is always a pain, so I'm moving it to be processed on first reference. I could take it a step further ... if WeaverStateInfo didn't write out the time (it doesnt read it back in!!) it would never be used at all in normal processing - potentially saving us from loading a bunch of underpinning junk to do the formatting...
|
resolved fixed
|
40cf610
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-08-25T12:41:38Z | 2006-08-25T12:46:40Z |
bridge/testsrc/org/aspectj/bridge/VersionTest.java
|
/* *******************************************************************
* Copyright (c) 1999-2001 Xerox Corporation,
* 2002 Palo Alto Research Center, Incorporated (PARC).
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Eclipse Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Xerox/PARC initial implementation
* ******************************************************************/
package org.aspectj.bridge;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;
import junit.framework.TestCase;
import junit.textui.TestRunner;
/**
*
*/
public class VersionTest extends TestCase {
private static final String ME
= "org.aspectj.bridge.VersionTest";
/** @param args ignored */
public static void main(String[] args) {
TestRunner.main(new String[] {ME});
}
/**
* Constructor for MessageTest.
* @param name
*/
public VersionTest(String name) {
super(name);
}
public void testVersion() {
if (Version.time_text.equals("")) return; // dev build, we can only test this on the build server.
Date date = new Date(Version.time);
SimpleDateFormat format = new SimpleDateFormat(Version.SIMPLE_DATE_FORMAT, Locale.getDefault());
format.setTimeZone(TimeZone.getTimeZone("GMT"));
String timeString = format.format(date);
assertEquals(Version.time_text, timeString);
}
}
|
155,213 |
Bug 155213 [ltw] can get into a state with the Version static initializer
|
The static initializer in Version that parses the time_text string and turns it into a long field seems to sometimes get loadtime weaving into a state - touching DateFormatters early on is always a pain, so I'm moving it to be processed on first reference. I could take it a step further ... if WeaverStateInfo didn't write out the time (it doesnt read it back in!!) it would never be used at all in normal processing - potentially saving us from loading a bunch of underpinning junk to do the formatting...
|
resolved fixed
|
40cf610
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-08-25T12:41:38Z | 2006-08-25T12:46:40Z |
weaver/src/org/aspectj/weaver/AjAttribute.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.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.EOFException;
import java.io.IOException;
import org.aspectj.bridge.MessageUtil;
import org.aspectj.bridge.Version;
import org.aspectj.util.FileUtil;
import org.aspectj.weaver.patterns.Declare;
import org.aspectj.weaver.patterns.IScope;
import org.aspectj.weaver.patterns.PerClause;
import org.aspectj.weaver.patterns.Pointcut;
/**
* These attributes are written to and read from .class files (see the JVM spec).
*
* <p>Each member or type can have a number of AjAttributes. Each
* such attribute is in 1-1 correspondence with an Unknown bcel attribute.
* Creating one of these does NOTHING to the underlying thing, so if you really
* want to add an attribute to a particular thing, well, you'd better actually do that.
*
* @author Erik Hilsdale
* @author Jim Hugunin
*/
public abstract class AjAttribute {
public static final String AttributePrefix = "org.aspectj.weaver";
protected abstract void write(DataOutputStream s) throws IOException;
public abstract String getNameString();
public char[] getNameChars() {
return getNameString().toCharArray();
}
/**
* Just writes the contents
*/
public byte[] getBytes() {
try {
ByteArrayOutputStream b0 = new ByteArrayOutputStream();
DataOutputStream s0 = new DataOutputStream(b0);
write(s0);
return b0.toByteArray();
} catch (IOException e) {
// shouldn't happen with ByteArrayOutputStreams
throw new RuntimeException("sanity check");
}
}
/**
* Writes the full attribute, i.e. name_index, length, and contents
*/
public byte[] getAllBytes(short nameIndex) {
try {
byte[] bytes = getBytes();
ByteArrayOutputStream b0 = new ByteArrayOutputStream();
DataOutputStream s0 = new DataOutputStream(b0);
s0.writeShort(nameIndex);
s0.writeInt(bytes.length);
s0.write(bytes);
return b0.toByteArray();
} catch (IOException e) {
// shouldn't happen with ByteArrayOutputStreams
throw new RuntimeException("sanity check");
}
}
public static AjAttribute read(AjAttribute.WeaverVersionInfo v, String name, byte[] bytes, ISourceContext context,World w) {
try {
if (bytes == null) bytes = new byte[0];
VersionedDataInputStream s = new VersionedDataInputStream(new ByteArrayInputStream(bytes));
s.setVersion(v);
if (name.equals(Aspect.AttributeName)) {
return new Aspect(PerClause.readPerClause(s, context));
} else if (name.equals(MethodDeclarationLineNumberAttribute.AttributeName)) {
return MethodDeclarationLineNumberAttribute.read(s);
} else if (name.equals(WeaverState.AttributeName)) {
return new WeaverState(WeaverStateInfo.read(s, context));
} else if (name.equals(WeaverVersionInfo.AttributeName)) {
return WeaverVersionInfo.read(s);
} else if (name.equals(AdviceAttribute.AttributeName)) {
AdviceAttribute aa = AdviceAttribute.read(s, context);
aa.getPointcut().check(context,w);
return aa;
} else if (name.equals(PointcutDeclarationAttribute.AttributeName)) {
PointcutDeclarationAttribute pda = new PointcutDeclarationAttribute(ResolvedPointcutDefinition.read(s, context));
pda.pointcutDef.getPointcut().check(context,w);
return pda;
} else if (name.equals(TypeMunger.AttributeName)) {
return new TypeMunger(ResolvedTypeMunger.read(s, context));
} else if (name.equals(AjSynthetic.AttributeName)) {
return new AjSynthetic();
} else if (name.equals(DeclareAttribute.AttributeName)) {
return new DeclareAttribute(Declare.read(s, context));
} else if (name.equals(PrivilegedAttribute.AttributeName)) {
return PrivilegedAttribute.read(s, context);
} else if (name.equals(SourceContextAttribute.AttributeName)) {
return SourceContextAttribute.read(s);
} else if (name.equals(EffectiveSignatureAttribute.AttributeName)) {
return EffectiveSignatureAttribute.read(s, context);
} else {
// We have to tell the user about this...
if (w == null || w.getMessageHandler()==null) throw new BCException("unknown attribute" + name);
w.getMessageHandler().handleMessage(MessageUtil.warn("unknown attribute encountered "+name));
return null;
}
} catch (IOException e) {
throw new BCException("malformed " + name + " attribute " + e);
}
}
//----
/** Synthetic members should have NO advice put on them or on their contents.
* This attribute is currently unused as we consider all members starting
* with NameMangler.PREFIX to automatically be synthetic. As we use this we might
* find that we want multiple
* kinds of synthetic. In particular, if we want to treat the call to a synthetic getter
* (say, of an introduced field) as a field reference itself, then a method might want
* a particular kind of AjSynthetic attribute that also includes a signature of what
* it stands for.
*/
public static class AjSynthetic extends AjAttribute {
public static final String AttributeName = "org.aspectj.weaver.AjSynthetic";
public String getNameString() {
return AttributeName;
}
// private ResolvedTypeMunger munger;
public AjSynthetic() {}
public void write(DataOutputStream s) throws IOException {}
}
public static class TypeMunger extends AjAttribute {
public static final String AttributeName = "org.aspectj.weaver.TypeMunger";
public String getNameString() {
return AttributeName;
}
private ResolvedTypeMunger munger;
public TypeMunger(ResolvedTypeMunger munger) {
this.munger = munger;
}
public void write(DataOutputStream s) throws IOException {
munger.write(s);
}
public ConcreteTypeMunger reify(World world, ResolvedType aspectType) {
return world.concreteTypeMunger(munger, aspectType);
}
}
public static class WeaverState extends AjAttribute {
public static final String AttributeName = "org.aspectj.weaver.WeaverState";
public String getNameString() {
return AttributeName;
}
private WeaverStateInfo kind;
public WeaverState(WeaverStateInfo kind) {
this.kind = kind;
}
public void write(DataOutputStream s) throws IOException {
kind.write(s);
}
public WeaverStateInfo reify() {
return kind;
}
}
public static class WeaverVersionInfo extends AjAttribute {
public static final String AttributeName = "org.aspectj.weaver.WeaverVersion";
// If you change the format of an AspectJ class file, you have two options:
// - changing the minor version means you have not added anything that prevents
// previous versions of the weaver from operating (e.g. MethodDeclarationLineNumber attribute)
// - changing the major version means you have added something that prevents previous
// versions of the weaver from operating correctly.
//
// The user will get a warning for any org.aspectj.weaver attributes the weaver does
// not recognize.
// When we don't know ... (i.e. pre 1.2.1)
public static short WEAVER_VERSION_MAJOR_UNKNOWN = 0;
public static short WEAVER_VERSION_MINOR_UNKNOWN = 0;
// These are the weaver major/minor numbers for AspectJ 1.2.1
public static short WEAVER_VERSION_MAJOR_AJ121 = 1;
public static short WEAVER_VERSION_MINOR_AJ121 = 0;
// These are the weaver major/minor numbers for AspectJ 1.5.0
public static short WEAVER_VERSION_MAJOR_AJ150M4 = 3;
public static short WEAVER_VERSION_MAJOR_AJ150 = 2;
public static short WEAVER_VERSION_MINOR_AJ150 = 0;
// These are the weaver major/minor versions for *this* weaver
private static short CURRENT_VERSION_MAJOR = WEAVER_VERSION_MAJOR_AJ150M4;
private static short CURRENT_VERSION_MINOR = WEAVER_VERSION_MINOR_AJ150;
public static final WeaverVersionInfo UNKNOWN =
new WeaverVersionInfo(WEAVER_VERSION_MAJOR_UNKNOWN,WEAVER_VERSION_MINOR_UNKNOWN);
// These are the versions read in from a particular class file.
private short major_version;
private short minor_version;
private long buildstamp = Version.NOTIME;
public String getNameString() {
return AttributeName;
}
// Default ctor uses the current version numbers
public WeaverVersionInfo() {
this.major_version = CURRENT_VERSION_MAJOR;
this.minor_version = CURRENT_VERSION_MINOR;
}
public WeaverVersionInfo(short major,short minor) {
major_version = major;
minor_version = minor;
}
public void write(DataOutputStream s) throws IOException {
s.writeShort(CURRENT_VERSION_MAJOR);
s.writeShort(CURRENT_VERSION_MINOR);
s.writeLong(Version.time); // build used to construct the class...
}
public static WeaverVersionInfo read(VersionedDataInputStream s) throws IOException {
short major = s.readShort();
short minor = s.readShort();
WeaverVersionInfo wvi = new WeaverVersionInfo(major,minor);
if (s.getMajorVersion()>=WEAVER_VERSION_MAJOR_AJ150M4) {
long stamp = 0;
try {
stamp = s.readLong();
wvi.setBuildstamp(stamp);
} catch (EOFException eof) {
// didnt find that build stamp - its not the end of the world
}
}
return wvi;
}
public short getMajorVersion() {
return major_version;
}
public short getMinorVersion() {
return minor_version;
}
public static short getCurrentWeaverMajorVersion() {
return CURRENT_VERSION_MAJOR;
}
public static short getCurrentWeaverMinorVersion() {
return CURRENT_VERSION_MINOR;
}
public void setBuildstamp(long stamp) {
this.buildstamp = stamp;
}
public long getBuildstamp() {
return buildstamp;
}
public String toString() {
return major_version+"."+minor_version;
}
public static String toCurrentVersionString() {
return CURRENT_VERSION_MAJOR+"."+CURRENT_VERSION_MINOR;
}
}
public static class SourceContextAttribute extends AjAttribute {
public static final String AttributeName = "org.aspectj.weaver.SourceContext";
public String getNameString() {
return AttributeName;
}
private String sourceFileName;
private int[] lineBreaks;
public SourceContextAttribute(String sourceFileName, int[] lineBreaks) {
this.sourceFileName = sourceFileName;
this.lineBreaks = lineBreaks;
}
public void write(DataOutputStream s) throws IOException {
s.writeUTF(sourceFileName);
FileUtil.writeIntArray(lineBreaks, s);
}
public static SourceContextAttribute read(VersionedDataInputStream s) throws IOException {
return new SourceContextAttribute(s.readUTF(), FileUtil.readIntArray(s));
}
public int[] getLineBreaks() {
return lineBreaks;
}
public String getSourceFileName() {
return sourceFileName;
}
}
public static class MethodDeclarationLineNumberAttribute extends AjAttribute {
public static final String AttributeName = "org.aspectj.weaver.MethodDeclarationLineNumber";
public String getNameString() {
return AttributeName;
}
private int lineNumber;
// AV: added in 1.5 M3 thus handling cases where we don't have that information
private int offset;
public MethodDeclarationLineNumberAttribute(int line, int offset) {
this.lineNumber = line;
this.offset = offset;
}
public int getLineNumber() { return lineNumber; }
public int getOffset() { return offset; }
public void write(DataOutputStream s) throws IOException {
s.writeInt(lineNumber);
s.writeInt(offset);
}
public static MethodDeclarationLineNumberAttribute read(VersionedDataInputStream s) throws IOException {
int line = s.readInt();
int offset = 0;
if (s.available()>0) {
offset = s.readInt();
}
return new MethodDeclarationLineNumberAttribute(line, offset);
}
public String toString() {
return AttributeName + ": " + lineNumber + ":" + offset;
}
}
public static class PointcutDeclarationAttribute extends AjAttribute {
public static final String AttributeName = "org.aspectj.weaver.PointcutDeclaration";
public String getNameString() {
return AttributeName;
}
private ResolvedPointcutDefinition pointcutDef;
public PointcutDeclarationAttribute(ResolvedPointcutDefinition pointcutDef) {
this.pointcutDef = pointcutDef;
}
public void write(DataOutputStream s) throws IOException {
pointcutDef.write(s);
}
public ResolvedPointcutDefinition reify() {
return pointcutDef;
}
}
public static class DeclareAttribute extends AjAttribute {
public static final String AttributeName = "org.aspectj.weaver.Declare";
public String getNameString() {
return AttributeName;
}
private Declare declare;
public DeclareAttribute(Declare declare) {
this.declare = declare;
}
public void write(DataOutputStream s) throws IOException {
declare.write(s);
}
public Declare getDeclare() {
return declare;
}
}
public static class AdviceAttribute extends AjAttribute {
public static final String AttributeName = "org.aspectj.weaver.Advice";
public String getNameString() {
return AttributeName;
}
private AdviceKind kind;
private Pointcut pointcut;
private int extraParameterFlags;
private int start;
private int end;
private ISourceContext sourceContext;
// these are only used by around advice
private boolean proceedInInners;
private ResolvedMember[] proceedCallSignatures; // size == # of proceed calls in body
private boolean[] formalsUnchangedToProceed; // size == formals.size
private UnresolvedType[] declaredExceptions;
/**
* @param lexicalPosition must be greater than the lexicalPosition
* of any advice declared before this one in an aspect, otherwise,
* it can be any value.
*/
public AdviceAttribute(AdviceKind kind, Pointcut pointcut, int extraArgumentFlags,
int start, int end, ISourceContext sourceContext) {
this.kind = kind;
this.pointcut = pointcut;
this.extraParameterFlags = extraArgumentFlags;
this.start = start;
this.end = end;
this.sourceContext = sourceContext;
//XXX put this back when testing works better (or fails better)
//if (kind == AdviceKind.Around) throw new IllegalArgumentException("not for around");
}
public AdviceAttribute(AdviceKind kind, Pointcut pointcut, int extraArgumentFlags,
int start, int end, ISourceContext sourceContext,
boolean proceedInInners, ResolvedMember[] proceedCallSignatures,
boolean[] formalsUnchangedToProceed, UnresolvedType[] declaredExceptions) {
this.kind = kind;
this.pointcut = pointcut;
this.extraParameterFlags = extraArgumentFlags;
this.start = start;
this.end = end;
this.sourceContext = sourceContext;
if (kind != AdviceKind.Around) throw new IllegalArgumentException("only for around");
this.proceedInInners = proceedInInners;
this.proceedCallSignatures = proceedCallSignatures;
this.formalsUnchangedToProceed = formalsUnchangedToProceed;
this.declaredExceptions = declaredExceptions;
}
public static AdviceAttribute read(VersionedDataInputStream s, ISourceContext context) throws IOException {
AdviceKind kind = AdviceKind.read(s);
if (kind == AdviceKind.Around) {
return new AdviceAttribute(
kind,
Pointcut.read(s, context),
s.readByte(),
s.readInt(), s.readInt(), context,
s.readBoolean(),
ResolvedMemberImpl.readResolvedMemberArray(s, context),
FileUtil.readBooleanArray(s),
UnresolvedType.readArray(s));
} else {
return new AdviceAttribute(
kind,
Pointcut.read(s, context),
s.readByte(),
s.readInt(), s.readInt(), context);
}
}
public void write(DataOutputStream s) throws IOException {
kind.write(s);
pointcut.write(s);
s.writeByte(extraParameterFlags);
s.writeInt(start);
s.writeInt(end);
if (kind == AdviceKind.Around) {
s.writeBoolean(proceedInInners);
ResolvedMemberImpl.writeArray(proceedCallSignatures, s);
FileUtil.writeBooleanArray(formalsUnchangedToProceed, s);
UnresolvedType.writeArray(declaredExceptions, s);
}
}
public Advice reify(Member signature, World world) {
return world.createAdviceMunger(this, pointcut, signature);
}
public String toString() {
return "AdviceAttribute(" + kind + ", " + pointcut + ", " +
extraParameterFlags + ", " + start+")";
}
public int getExtraParameterFlags() {
return extraParameterFlags;
}
public AdviceKind getKind() {
return kind;
}
public Pointcut getPointcut() {
return pointcut;
}
public UnresolvedType[] getDeclaredExceptions() {
return declaredExceptions;
}
public boolean[] getFormalsUnchangedToProceed() {
return formalsUnchangedToProceed;
}
public ResolvedMember[] getProceedCallSignatures() {
return proceedCallSignatures;
}
public boolean isProceedInInners() {
return proceedInInners;
}
public int getEnd() {
return end;
}
public ISourceContext getSourceContext() {
return sourceContext;
}
public int getStart() {
return start;
}
}
public static class Aspect extends AjAttribute {
public static final String AttributeName = "org.aspectj.weaver.Aspect";
public String getNameString() {
return AttributeName;
}
private PerClause perClause;
private IScope resolutionScope;
public Aspect(PerClause perClause) {
this.perClause = perClause;
}
public PerClause reify(ResolvedType inAspect) {
//XXXperClause.concretize(inAspect);
return perClause;
}
public PerClause reifyFromAtAspectJ(ResolvedType inAspect) {
perClause.resolve(resolutionScope);
return perClause;
}
public void write(DataOutputStream s) throws IOException {
perClause.write(s);
}
public void setResolutionScope(IScope binding) {
this.resolutionScope = binding;
}
}
public static class PrivilegedAttribute extends AjAttribute {
public static final String AttributeName = "org.aspectj.weaver.Privileged";
public String getNameString() {
return AttributeName;
}
private ResolvedMember[] accessedMembers;
public PrivilegedAttribute(ResolvedMember[] accessedMembers) {
this.accessedMembers = accessedMembers;
}
public void write(DataOutputStream s) throws IOException {
ResolvedMemberImpl.writeArray(accessedMembers, s);
}
public ResolvedMember[] getAccessedMembers() {
return accessedMembers;
}
public static PrivilegedAttribute read(VersionedDataInputStream s, ISourceContext context) throws IOException {
return new PrivilegedAttribute(ResolvedMemberImpl.readResolvedMemberArray(s, context));
}
}
public static class EffectiveSignatureAttribute extends AjAttribute {
public static final String AttributeName = "org.aspectj.weaver.EffectiveSignature";
public String getNameString() {
return AttributeName;
}
private ResolvedMember effectiveSignature;
private Shadow.Kind shadowKind;
private boolean weaveBody;
public EffectiveSignatureAttribute(ResolvedMember effectiveSignature, Shadow.Kind shadowKind, boolean weaveBody) {
this.effectiveSignature = effectiveSignature;
this.shadowKind = shadowKind;
this.weaveBody = weaveBody;
}
public void write(DataOutputStream s) throws IOException {
effectiveSignature.write(s);
shadowKind.write(s);
s.writeBoolean(weaveBody);
}
public static EffectiveSignatureAttribute read(VersionedDataInputStream s, ISourceContext context) throws IOException {
return new EffectiveSignatureAttribute(
ResolvedMemberImpl.readResolvedMember(s, context),
Shadow.Kind.read(s),
s.readBoolean());
}
public ResolvedMember getEffectiveSignature() {
return effectiveSignature;
}
public String toString() {
return "EffectiveSignatureAttribute(" + effectiveSignature + ", " + shadowKind + ")";
}
public Shadow.Kind getShadowKind() {
return shadowKind;
}
public boolean isWeaveBody() {
return weaveBody;
}
}
}
|
155,148 |
Bug 155148 jdk14 trace deadlock in oc4j
|
I turned on tracing for the Aj class inside of Oracle's OC4J server. In one test (not always) it deadlocked. It looks like the threads are each trying to lock each other's loader. Notice that one of the threads is in the toString method of the Oracle ClassLoader (perhaps another reason to prefer tracing argument class names and system identity hashcodes). Here's a thread dump from Ctrl+BREAK: Found one Java-level deadlock: ============================= "WorkExecutorWorkerThread-1": waiting to lock monitor 0x003384ec (object 0x05239e48, a oracle.classloader.Po licyClassLoader), which is held by "OC4J Launcher" "OC4J Launcher": waiting to lock monitor 0x0033848c (object 0x0554f0e8, a oracle.classloader.Po licyClassLoader), which is held by "WorkExecutorWorkerThread-1" Java stack information for the threads listed above: =================================================== "WorkExecutorWorkerThread-1": at oracle.classloader.SearchPolicy.loadClass(SearchPolicy.java:641) - waiting to lock <0x05239e48> (a oracle.classloader.PolicyClassLoader) at oracle.classloader.PolicyClassLoader.askParentForClass(PolicyClassLoa der.java:1284) at oracle.classloader.SearchPolicy$AskParent.getClass(SearchPolicy.java: 69) at oracle.classloader.SearchSequence.getClass(SearchSequence.java:119) at oracle.classloader.SearchPolicy.loadClass(SearchPolicy.java:642) - locked <0x0554f0e8> (a oracle.classloader.PolicyClassLoader) at oracle.classloader.PolicyClassLoader.askParentForClass(PolicyClassLoa der.java:1284) at oracle.classloader.SearchPolicy$AskParent.getClass(SearchPolicy.java: 69) at oracle.classloader.SearchSequence.getClass(SearchSequence.java:119) at oracle.classloader.PolicyClassLoader.internalLoadClass(PolicyClassLoa der.java:1660) - locked <0x056a9ed0> (a oracle.classloader.PolicyClassLoader) at oracle.classloader.PolicyClassLoader.loadClass(PolicyClassLoader.java :1621) at oracle.classloader.PolicyClassLoader.loadClass(PolicyClassLoader.java :1606) at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:319) - locked <0x056a9ed0> (a oracle.classloader.PolicyClassLoader) at oracle.j2ee.ra.jms.generic.WorkConsumer.doReceive(WorkConsumer.java:9 87) at oracle.j2ee.ra.jms.generic.WorkConsumer.run(WorkConsumer.java:215) - locked <0x05de2718> (a oracle.j2ee.ra.jms.generic.WorkConsumer) at oracle.j2ee.connector.work.WorkWrapper.runTargetWork(WorkWrapper.java :242) at oracle.j2ee.connector.work.WorkWrapper.doWork(WorkWrapper.java:215) at oracle.j2ee.connector.work.WorkWrapper.run(WorkWrapper.java:190) at EDU.oswego.cs.dl.util.concurrent.PooledExecutor$Worker.run(PooledExec utor.java:814) at java.lang.Thread.run(Thread.java:595) "OC4J Launcher": at oracle.classloader.PolicyClassLoader.toString(PolicyClassLoader.java: 1846) - waiting to lock <0x0554f0e8> (a oracle.classloader.PolicyClassLoader) at java.text.MessageFormat.subformat(MessageFormat.java:1237) at java.text.MessageFormat.format(MessageFormat.java:828) at java.text.Format.format(Format.java:133) at java.text.MessageFormat.format(MessageFormat.java:804) at java.util.logging.Formatter.formatMessage(Formatter.java:130) - locked <0x0514e920> (a java.util.logging.SimpleFormatter) at java.util.logging.SimpleFormatter.format(SimpleFormatter.java:63) - locked <0x0514e920> (a java.util.logging.SimpleFormatter) at java.util.logging.StreamHandler.publish(StreamHandler.java:179) - locked <0x0514a0a8> (a java.util.logging.FileHandler) at java.util.logging.FileHandler.publish(FileHandler.java:555) - locked <0x0514a0a8> (a java.util.logging.FileHandler) at java.util.logging.Logger.log(Logger.java:428) at java.util.logging.Logger.doLog(Logger.java:450) at java.util.logging.Logger.logp(Logger.java:619) at java.util.logging.Logger.entering(Logger.java:870) at org.aspectj.weaver.tools.Jdk14Trace.enter(Jdk14Trace.java:32) at org.aspectj.weaver.loadtime.Aj.preProcess(Aj.java:67) at org.aspectj.weaver.loadtime.ClassPreProcessorAgentAdapter.transform(C lassPreProcessorAgentAdapter.java:55) at sun.instrument.TransformerManager.transform(TransformerManager.java:1 22) at sun.instrument.InstrumentationImpl.transform(InstrumentationImpl.java :155) at java.lang.ClassLoader.defineClass1(Native Method) at java.lang.ClassLoader.defineClass(ClassLoader.java:620) at oracle.classloader.PolicyClassLoader.defineClass(PolicyClassLoader.ja va:2224) at oracle.classloader.PolicyClassLoader.findLocalClass(PolicyClassLoader .java:1457) at oracle.classloader.SearchPolicy$FindLocal.getClass(SearchPolicy.java: 167) at oracle.classloader.SearchSequence.getClass(SearchSequence.java:119) at oracle.classloader.PolicyClassLoader.internalLoadClass(PolicyClassLoa der.java:1660) - locked <0x05239e48> (a oracle.classloader.PolicyClassLoader) at oracle.classloader.PolicyClassLoader.loadClass(PolicyClassLoader.java :1621) at oracle.classloader.PolicyClassLoader.loadClass(PolicyClassLoader.java :1606) at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:319) - locked <0x05239e48> (a oracle.classloader.PolicyClassLoader) at com.evermind.server.http.HttpRequestHandler.<init>(HttpRequestHandler .java:97) at com.evermind.server.http.HttpConnectionListener$HttpNIOAcceptHandler. getReadHandler(HttpConnectionListener.java:116) at oracle.oc4j.network.ReadHandlerPool.getContextFromBackend(ReadHandler Pool.java:63) at com.evermind.util.BBPool.startPool(BBPool.java:42) at oracle.oc4j.network.ReadHandlerPool.register(ReadHandlerPool.java:25) - locked <0x05ec9290> (a java.util.ArrayList) at oracle.oc4j.network.ServerSocketAcceptHandler.setPoolOptions(ServerSo cketAcceptHandler.java:140) at com.evermind.server.http.HttpConnectionListener.setRequestHandlerPool (HttpConnectionListener.java:232) at com.evermind.server.http.HttpConnectionListener.initHandlers(HttpConn ectionListener.java:226) at com.evermind.server.http.HttpConnectionListener.<init>(HttpConnection Listener.java:174) at com.evermind.server.http.HttpServer.getListener(HttpServer.java:481) - locked <0x05ec4f88> (a com.evermind.server.http.HttpServer) at com.evermind.server.http.HttpServer.setSites(HttpServer.java:267) - locked <0x05ec4f88> (a com.evermind.server.http.HttpServer) at com.evermind.server.http.HttpServer.setConfig(HttpServer.java:180) at com.evermind.server.ApplicationServer.initializeHttp(ApplicationServe r.java:2296) at com.evermind.server.ApplicationServer.setConfig(ApplicationServer.jav a:944) at com.evermind.server.ApplicationServerLauncher.run(ApplicationServerLa uncher.java:113) - locked <0x0530eb20> (a java.lang.Object) at java.lang.Thread.run(Thread.java:595) Found 1 deadlock.
|
resolved fixed
|
6be7097
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-08-25T14:37:34Z | 2006-08-25T01:40:00Z |
loadtime/src/org/aspectj/weaver/loadtime/DefaultWeavingContext.java
|
/*******************************************************************************
* Copyright (c) 2005 Contributors.
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Eclipse Public License v1.0
* which accompanies this distribution and is available at
* http://eclipse.org/legal/epl-v10.html
*
* Contributors:
* David Knibb initial implementation
*******************************************************************************/
package org.aspectj.weaver.loadtime;
import java.io.IOException;
import java.net.URL;
import java.util.Enumeration;
/**
* Use in non-OSGi environment
*
* @author David Knibb
*/
public class DefaultWeavingContext implements IWeavingContext {
protected ClassLoader loader;
private String shortName;
/**
* Construct a new WeavingContext to use the specifed ClassLoader
* This is the constructor which should be used.
* @param loader
*/
public DefaultWeavingContext(ClassLoader loader) {
this.loader = loader;
}
/**
* Same as ClassLoader.getResources()
*/
public Enumeration getResources(String name) throws IOException {
return loader.getResources(name);
}
/**
* @return null as we are not in an OSGi environment (therefore no bundles)
*/
public String getBundleIdFromURL(URL url) {
return "";
}
/**
* @return classname@hashcode
*/
public String getClassLoaderName() {
return ((loader!=null)?loader.getClass().getName()+"@"+loader.hashCode():"null");
}
/**
* @return filename
*/
public String getFile(URL url) {
return url.getFile();
}
/**
* @return unqualifiedclassname@hashcode
*/
public String getId () {
if (shortName == null) {
shortName = getClassLoaderName().replace('$','.');
int index = shortName.lastIndexOf(".");
shortName = shortName.substring(index + 1);
}
return shortName;
}
public String getSuffix () {
return getClassLoaderName();
}
public boolean isLocallyDefined(String classname) {
String asResource = classname.replace('.', '/').concat(".class");
URL localURL = loader.getResource(asResource);
if (localURL == null) return false;
boolean isLocallyDefined = true;
ClassLoader parent = loader.getParent();
if (parent != null) {
URL parentURL = parent.getResource(asResource);
if (localURL.equals(parentURL)) isLocallyDefined = false;
}
return isLocallyDefined;
}
}
|
155,148 |
Bug 155148 jdk14 trace deadlock in oc4j
|
I turned on tracing for the Aj class inside of Oracle's OC4J server. In one test (not always) it deadlocked. It looks like the threads are each trying to lock each other's loader. Notice that one of the threads is in the toString method of the Oracle ClassLoader (perhaps another reason to prefer tracing argument class names and system identity hashcodes). Here's a thread dump from Ctrl+BREAK: Found one Java-level deadlock: ============================= "WorkExecutorWorkerThread-1": waiting to lock monitor 0x003384ec (object 0x05239e48, a oracle.classloader.Po licyClassLoader), which is held by "OC4J Launcher" "OC4J Launcher": waiting to lock monitor 0x0033848c (object 0x0554f0e8, a oracle.classloader.Po licyClassLoader), which is held by "WorkExecutorWorkerThread-1" Java stack information for the threads listed above: =================================================== "WorkExecutorWorkerThread-1": at oracle.classloader.SearchPolicy.loadClass(SearchPolicy.java:641) - waiting to lock <0x05239e48> (a oracle.classloader.PolicyClassLoader) at oracle.classloader.PolicyClassLoader.askParentForClass(PolicyClassLoa der.java:1284) at oracle.classloader.SearchPolicy$AskParent.getClass(SearchPolicy.java: 69) at oracle.classloader.SearchSequence.getClass(SearchSequence.java:119) at oracle.classloader.SearchPolicy.loadClass(SearchPolicy.java:642) - locked <0x0554f0e8> (a oracle.classloader.PolicyClassLoader) at oracle.classloader.PolicyClassLoader.askParentForClass(PolicyClassLoa der.java:1284) at oracle.classloader.SearchPolicy$AskParent.getClass(SearchPolicy.java: 69) at oracle.classloader.SearchSequence.getClass(SearchSequence.java:119) at oracle.classloader.PolicyClassLoader.internalLoadClass(PolicyClassLoa der.java:1660) - locked <0x056a9ed0> (a oracle.classloader.PolicyClassLoader) at oracle.classloader.PolicyClassLoader.loadClass(PolicyClassLoader.java :1621) at oracle.classloader.PolicyClassLoader.loadClass(PolicyClassLoader.java :1606) at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:319) - locked <0x056a9ed0> (a oracle.classloader.PolicyClassLoader) at oracle.j2ee.ra.jms.generic.WorkConsumer.doReceive(WorkConsumer.java:9 87) at oracle.j2ee.ra.jms.generic.WorkConsumer.run(WorkConsumer.java:215) - locked <0x05de2718> (a oracle.j2ee.ra.jms.generic.WorkConsumer) at oracle.j2ee.connector.work.WorkWrapper.runTargetWork(WorkWrapper.java :242) at oracle.j2ee.connector.work.WorkWrapper.doWork(WorkWrapper.java:215) at oracle.j2ee.connector.work.WorkWrapper.run(WorkWrapper.java:190) at EDU.oswego.cs.dl.util.concurrent.PooledExecutor$Worker.run(PooledExec utor.java:814) at java.lang.Thread.run(Thread.java:595) "OC4J Launcher": at oracle.classloader.PolicyClassLoader.toString(PolicyClassLoader.java: 1846) - waiting to lock <0x0554f0e8> (a oracle.classloader.PolicyClassLoader) at java.text.MessageFormat.subformat(MessageFormat.java:1237) at java.text.MessageFormat.format(MessageFormat.java:828) at java.text.Format.format(Format.java:133) at java.text.MessageFormat.format(MessageFormat.java:804) at java.util.logging.Formatter.formatMessage(Formatter.java:130) - locked <0x0514e920> (a java.util.logging.SimpleFormatter) at java.util.logging.SimpleFormatter.format(SimpleFormatter.java:63) - locked <0x0514e920> (a java.util.logging.SimpleFormatter) at java.util.logging.StreamHandler.publish(StreamHandler.java:179) - locked <0x0514a0a8> (a java.util.logging.FileHandler) at java.util.logging.FileHandler.publish(FileHandler.java:555) - locked <0x0514a0a8> (a java.util.logging.FileHandler) at java.util.logging.Logger.log(Logger.java:428) at java.util.logging.Logger.doLog(Logger.java:450) at java.util.logging.Logger.logp(Logger.java:619) at java.util.logging.Logger.entering(Logger.java:870) at org.aspectj.weaver.tools.Jdk14Trace.enter(Jdk14Trace.java:32) at org.aspectj.weaver.loadtime.Aj.preProcess(Aj.java:67) at org.aspectj.weaver.loadtime.ClassPreProcessorAgentAdapter.transform(C lassPreProcessorAgentAdapter.java:55) at sun.instrument.TransformerManager.transform(TransformerManager.java:1 22) at sun.instrument.InstrumentationImpl.transform(InstrumentationImpl.java :155) at java.lang.ClassLoader.defineClass1(Native Method) at java.lang.ClassLoader.defineClass(ClassLoader.java:620) at oracle.classloader.PolicyClassLoader.defineClass(PolicyClassLoader.ja va:2224) at oracle.classloader.PolicyClassLoader.findLocalClass(PolicyClassLoader .java:1457) at oracle.classloader.SearchPolicy$FindLocal.getClass(SearchPolicy.java: 167) at oracle.classloader.SearchSequence.getClass(SearchSequence.java:119) at oracle.classloader.PolicyClassLoader.internalLoadClass(PolicyClassLoa der.java:1660) - locked <0x05239e48> (a oracle.classloader.PolicyClassLoader) at oracle.classloader.PolicyClassLoader.loadClass(PolicyClassLoader.java :1621) at oracle.classloader.PolicyClassLoader.loadClass(PolicyClassLoader.java :1606) at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:319) - locked <0x05239e48> (a oracle.classloader.PolicyClassLoader) at com.evermind.server.http.HttpRequestHandler.<init>(HttpRequestHandler .java:97) at com.evermind.server.http.HttpConnectionListener$HttpNIOAcceptHandler. getReadHandler(HttpConnectionListener.java:116) at oracle.oc4j.network.ReadHandlerPool.getContextFromBackend(ReadHandler Pool.java:63) at com.evermind.util.BBPool.startPool(BBPool.java:42) at oracle.oc4j.network.ReadHandlerPool.register(ReadHandlerPool.java:25) - locked <0x05ec9290> (a java.util.ArrayList) at oracle.oc4j.network.ServerSocketAcceptHandler.setPoolOptions(ServerSo cketAcceptHandler.java:140) at com.evermind.server.http.HttpConnectionListener.setRequestHandlerPool (HttpConnectionListener.java:232) at com.evermind.server.http.HttpConnectionListener.initHandlers(HttpConn ectionListener.java:226) at com.evermind.server.http.HttpConnectionListener.<init>(HttpConnection Listener.java:174) at com.evermind.server.http.HttpServer.getListener(HttpServer.java:481) - locked <0x05ec4f88> (a com.evermind.server.http.HttpServer) at com.evermind.server.http.HttpServer.setSites(HttpServer.java:267) - locked <0x05ec4f88> (a com.evermind.server.http.HttpServer) at com.evermind.server.http.HttpServer.setConfig(HttpServer.java:180) at com.evermind.server.ApplicationServer.initializeHttp(ApplicationServe r.java:2296) at com.evermind.server.ApplicationServer.setConfig(ApplicationServer.jav a:944) at com.evermind.server.ApplicationServerLauncher.run(ApplicationServerLa uncher.java:113) - locked <0x0530eb20> (a java.lang.Object) at java.lang.Thread.run(Thread.java:595) Found 1 deadlock.
|
resolved fixed
|
6be7097
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-08-25T14:37:34Z | 2006-08-25T01:40:00Z |
weaver/src/org/aspectj/weaver/tools/AbstractTrace.java
|
/*******************************************************************************
* Copyright (c) 2006 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Matthew Webster - initial implementation
*******************************************************************************/
package org.aspectj.weaver.tools;
import java.io.File;
import java.lang.reflect.Array;
import java.text.SimpleDateFormat;
import java.util.Collection;
import java.util.Date;
public abstract class AbstractTrace implements Trace {
protected Class tracedClass;
private static SimpleDateFormat timeFormat;
protected AbstractTrace (Class clazz) {
this.tracedClass = clazz;
}
public abstract void enter (String methodName, Object thiz, Object[] args);
public abstract void enter(String methodName, Object thiz);
public abstract void exit(String methodName, Object ret);
public abstract void exit(String methodName, Throwable th);
/*
* Convenience methods
*/
public void enter (String methodName) {
enter(methodName,null,null);
}
public void enter (String methodName, Object thiz, Object arg) {
enter(methodName,thiz,new Object[] { arg });
}
public void enter (String methodName, Object thiz, boolean z) {
enter(methodName,thiz,new Boolean(z));
}
public void exit (String methodName, boolean b) {
exit(methodName,new Boolean(b));
}
public void event (String methodName, Object thiz, Object arg) {
event(methodName,thiz,new Object[] { arg });
}
public void warn(String message) {
warn(message,null);
}
public void error(String message) {
error(message,null);
}
public void fatal (String message) {
fatal(message,null);
}
/*
* Formatting
*/
protected String formatMessage(String kind, String className, String methodName, Object thiz, Object[] args) {
StringBuffer message = new StringBuffer();
Date now = new Date();
message.append(formatDate(now)).append(" ");
message.append(Thread.currentThread().getName()).append(" ");
message.append(kind).append(" ");
message.append(className);
message.append(".").append(methodName);
if (thiz != null) message.append(" ").append(formatObj(thiz));
if (args != null) message.append(" ").append(formatArgs(args));
return message.toString();
}
protected String formatMessage(String kind, String text, Throwable th) {
StringBuffer message = new StringBuffer();
Date now = new Date();
message.append(formatDate(now)).append(" ");
message.append(Thread.currentThread().getName()).append(" ");
message.append(kind).append(" ");
message.append(text);
if (th != null) message.append(" ").append(formatObj(th));
return message.toString();
}
private static String formatDate (Date date) {
if (timeFormat == null) {
timeFormat = new SimpleDateFormat("HH:mm:ss.SSS");
}
return timeFormat.format(date);
}
/**
* Format objects safely avoiding toString which can cause recursion,
* NullPointerExceptions or highly verbose results.
*
* @param obj parameter to be formatted
* @return the formated parameter
*/
protected Object formatObj(Object obj) {
/* These classes have a safe implementation of toString() */
if (obj == null
|| obj instanceof String
|| obj instanceof Number
|| obj instanceof Boolean
|| obj instanceof Exception
|| obj instanceof Character
|| obj instanceof Class
|| obj instanceof File
|| obj instanceof StringBuffer
) return obj;
else if (obj.getClass().isArray()) {
return formatArray(obj);
}
else if (obj instanceof Collection) {
return formatCollection((Collection)obj);
}
else try {
/* Classes can provide an alternative implementation of toString() */
if (obj instanceof Traceable) {
Traceable t = (Traceable)obj;
return t.toTraceString();
}
/* Use classname@hashcode */
else return obj.getClass().getName() + "@" + Integer.toString(obj.hashCode(),16);
/* Object.hashCode() can be override and may thow an exception */
} catch (Exception ex) {
return obj.getClass().getName();
}
}
protected String formatArray (Object obj) {
return obj.getClass().getComponentType().getName() + "[" + Array.getLength(obj) + "]";
}
protected String formatCollection (Collection c) {
return c.getClass().getName() + "(" + c.size() + ")";
}
/**
* Format arguments into a comma separated list
*
* @param names array of argument names
* @param args array of arguments
* @return the formated list
*/
protected String formatArgs(Object[] args) {
StringBuffer sb = new StringBuffer();
for (int i = 0; i < args.length; i++) {
sb.append(formatObj(args[i]));
if (i < args.length-1) sb.append(", ");
}
return sb.toString();
}
}
|
155,148 |
Bug 155148 jdk14 trace deadlock in oc4j
|
I turned on tracing for the Aj class inside of Oracle's OC4J server. In one test (not always) it deadlocked. It looks like the threads are each trying to lock each other's loader. Notice that one of the threads is in the toString method of the Oracle ClassLoader (perhaps another reason to prefer tracing argument class names and system identity hashcodes). Here's a thread dump from Ctrl+BREAK: Found one Java-level deadlock: ============================= "WorkExecutorWorkerThread-1": waiting to lock monitor 0x003384ec (object 0x05239e48, a oracle.classloader.Po licyClassLoader), which is held by "OC4J Launcher" "OC4J Launcher": waiting to lock monitor 0x0033848c (object 0x0554f0e8, a oracle.classloader.Po licyClassLoader), which is held by "WorkExecutorWorkerThread-1" Java stack information for the threads listed above: =================================================== "WorkExecutorWorkerThread-1": at oracle.classloader.SearchPolicy.loadClass(SearchPolicy.java:641) - waiting to lock <0x05239e48> (a oracle.classloader.PolicyClassLoader) at oracle.classloader.PolicyClassLoader.askParentForClass(PolicyClassLoa der.java:1284) at oracle.classloader.SearchPolicy$AskParent.getClass(SearchPolicy.java: 69) at oracle.classloader.SearchSequence.getClass(SearchSequence.java:119) at oracle.classloader.SearchPolicy.loadClass(SearchPolicy.java:642) - locked <0x0554f0e8> (a oracle.classloader.PolicyClassLoader) at oracle.classloader.PolicyClassLoader.askParentForClass(PolicyClassLoa der.java:1284) at oracle.classloader.SearchPolicy$AskParent.getClass(SearchPolicy.java: 69) at oracle.classloader.SearchSequence.getClass(SearchSequence.java:119) at oracle.classloader.PolicyClassLoader.internalLoadClass(PolicyClassLoa der.java:1660) - locked <0x056a9ed0> (a oracle.classloader.PolicyClassLoader) at oracle.classloader.PolicyClassLoader.loadClass(PolicyClassLoader.java :1621) at oracle.classloader.PolicyClassLoader.loadClass(PolicyClassLoader.java :1606) at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:319) - locked <0x056a9ed0> (a oracle.classloader.PolicyClassLoader) at oracle.j2ee.ra.jms.generic.WorkConsumer.doReceive(WorkConsumer.java:9 87) at oracle.j2ee.ra.jms.generic.WorkConsumer.run(WorkConsumer.java:215) - locked <0x05de2718> (a oracle.j2ee.ra.jms.generic.WorkConsumer) at oracle.j2ee.connector.work.WorkWrapper.runTargetWork(WorkWrapper.java :242) at oracle.j2ee.connector.work.WorkWrapper.doWork(WorkWrapper.java:215) at oracle.j2ee.connector.work.WorkWrapper.run(WorkWrapper.java:190) at EDU.oswego.cs.dl.util.concurrent.PooledExecutor$Worker.run(PooledExec utor.java:814) at java.lang.Thread.run(Thread.java:595) "OC4J Launcher": at oracle.classloader.PolicyClassLoader.toString(PolicyClassLoader.java: 1846) - waiting to lock <0x0554f0e8> (a oracle.classloader.PolicyClassLoader) at java.text.MessageFormat.subformat(MessageFormat.java:1237) at java.text.MessageFormat.format(MessageFormat.java:828) at java.text.Format.format(Format.java:133) at java.text.MessageFormat.format(MessageFormat.java:804) at java.util.logging.Formatter.formatMessage(Formatter.java:130) - locked <0x0514e920> (a java.util.logging.SimpleFormatter) at java.util.logging.SimpleFormatter.format(SimpleFormatter.java:63) - locked <0x0514e920> (a java.util.logging.SimpleFormatter) at java.util.logging.StreamHandler.publish(StreamHandler.java:179) - locked <0x0514a0a8> (a java.util.logging.FileHandler) at java.util.logging.FileHandler.publish(FileHandler.java:555) - locked <0x0514a0a8> (a java.util.logging.FileHandler) at java.util.logging.Logger.log(Logger.java:428) at java.util.logging.Logger.doLog(Logger.java:450) at java.util.logging.Logger.logp(Logger.java:619) at java.util.logging.Logger.entering(Logger.java:870) at org.aspectj.weaver.tools.Jdk14Trace.enter(Jdk14Trace.java:32) at org.aspectj.weaver.loadtime.Aj.preProcess(Aj.java:67) at org.aspectj.weaver.loadtime.ClassPreProcessorAgentAdapter.transform(C lassPreProcessorAgentAdapter.java:55) at sun.instrument.TransformerManager.transform(TransformerManager.java:1 22) at sun.instrument.InstrumentationImpl.transform(InstrumentationImpl.java :155) at java.lang.ClassLoader.defineClass1(Native Method) at java.lang.ClassLoader.defineClass(ClassLoader.java:620) at oracle.classloader.PolicyClassLoader.defineClass(PolicyClassLoader.ja va:2224) at oracle.classloader.PolicyClassLoader.findLocalClass(PolicyClassLoader .java:1457) at oracle.classloader.SearchPolicy$FindLocal.getClass(SearchPolicy.java: 167) at oracle.classloader.SearchSequence.getClass(SearchSequence.java:119) at oracle.classloader.PolicyClassLoader.internalLoadClass(PolicyClassLoa der.java:1660) - locked <0x05239e48> (a oracle.classloader.PolicyClassLoader) at oracle.classloader.PolicyClassLoader.loadClass(PolicyClassLoader.java :1621) at oracle.classloader.PolicyClassLoader.loadClass(PolicyClassLoader.java :1606) at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:319) - locked <0x05239e48> (a oracle.classloader.PolicyClassLoader) at com.evermind.server.http.HttpRequestHandler.<init>(HttpRequestHandler .java:97) at com.evermind.server.http.HttpConnectionListener$HttpNIOAcceptHandler. getReadHandler(HttpConnectionListener.java:116) at oracle.oc4j.network.ReadHandlerPool.getContextFromBackend(ReadHandler Pool.java:63) at com.evermind.util.BBPool.startPool(BBPool.java:42) at oracle.oc4j.network.ReadHandlerPool.register(ReadHandlerPool.java:25) - locked <0x05ec9290> (a java.util.ArrayList) at oracle.oc4j.network.ServerSocketAcceptHandler.setPoolOptions(ServerSo cketAcceptHandler.java:140) at com.evermind.server.http.HttpConnectionListener.setRequestHandlerPool (HttpConnectionListener.java:232) at com.evermind.server.http.HttpConnectionListener.initHandlers(HttpConn ectionListener.java:226) at com.evermind.server.http.HttpConnectionListener.<init>(HttpConnection Listener.java:174) at com.evermind.server.http.HttpServer.getListener(HttpServer.java:481) - locked <0x05ec4f88> (a com.evermind.server.http.HttpServer) at com.evermind.server.http.HttpServer.setSites(HttpServer.java:267) - locked <0x05ec4f88> (a com.evermind.server.http.HttpServer) at com.evermind.server.http.HttpServer.setConfig(HttpServer.java:180) at com.evermind.server.ApplicationServer.initializeHttp(ApplicationServe r.java:2296) at com.evermind.server.ApplicationServer.setConfig(ApplicationServer.jav a:944) at com.evermind.server.ApplicationServerLauncher.run(ApplicationServerLa uncher.java:113) - locked <0x0530eb20> (a java.lang.Object) at java.lang.Thread.run(Thread.java:595) Found 1 deadlock.
|
resolved fixed
|
6be7097
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-08-25T14:37:34Z | 2006-08-25T01:40:00Z |
weaver/testsrc/org/aspectj/weaver/AbstractTraceTest.java
|
/*******************************************************************************
* Copyright (c) 2006 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Matthew Webster - initial implementation
*******************************************************************************/
package org.aspectj.weaver;
import java.util.ArrayList;
import junit.framework.TestCase;
import org.aspectj.weaver.tools.AbstractTrace;
import org.aspectj.weaver.tools.DefaultTrace;
import org.aspectj.weaver.tools.Traceable;
public abstract class AbstractTraceTest extends TestCase {
protected AbstractTrace trace;
public void testIsTraceEnabled() {
DefaultTrace trace = new DefaultTrace(getClass());
assertFalse(trace.isTraceEnabled());
}
public void testEnterWithThisAndArgs() {
trace.enter("testEnterWithThisAndArgs",this,new Object[] { "arg1", "arg2" });
}
public void testEnterWithThisAndArray() {
Object arg1 = new String[] { "s1", "s2" };
Object arg2 = new char[] { 'a', 'b', 'c' };
trace.enter("testEnterWithThisAndArgs",this,new Object[] { arg1, arg2 });
}
public void testEnterWithThisAndCollection() {
Object arg1 = new ArrayList();
trace.enter("testEnterWithThisAndArgs",this,new Object[] { arg1 });
}
public void testEnterWithThisAndTraceable () {
Object arg1 = new Traceable() {
public String toTraceString() {
return "Traceable";
}
};
trace.enter("testEnterWithThisAndArgs",this,new Object[] { arg1 });
}
public void testEnterWithThis() {
trace.enter("testEnterWithThis",this);
}
public void testEnter() {
trace.enter("testEnter");
}
public void testExitWithReturn() {
trace.exit("testExitWithReturn","ret");
}
public void testExitWithThrowable() {
trace.exit("testExitWithThrowable",new RuntimeException());
}
public void testExit() {
trace.exit("testExit");
}
public void testEvent() {
trace.event("testEvent");
}
public void testEventWithThisAndArgs() {
trace.event("testEventWithThisAndArgs",this,new Object[] { "arg1", "arg2" });
}
public void testEventWithThisAndArg() {
trace.event("testEventWithThisAndArg",this,"arg1");
}
public void testDebug() {
trace.debug("debug");
}
public void testInfo() {
trace.info("information");
}
public void testWarn() {
trace.warn("warning");
}
public void testWarnWithException() {
trace.warn("warning",new RuntimeException("warning"));
}
public void testError() {
trace.error("error");
}
public void testErrorWithException() {
trace.error("error",new RuntimeException("error"));
}
public void testFatal() {
trace.fatal("fatal");
}
public void testFatalWithException() {
trace.fatal("fatal",new RuntimeException("fatal"));
}
}
|
155,148 |
Bug 155148 jdk14 trace deadlock in oc4j
|
I turned on tracing for the Aj class inside of Oracle's OC4J server. In one test (not always) it deadlocked. It looks like the threads are each trying to lock each other's loader. Notice that one of the threads is in the toString method of the Oracle ClassLoader (perhaps another reason to prefer tracing argument class names and system identity hashcodes). Here's a thread dump from Ctrl+BREAK: Found one Java-level deadlock: ============================= "WorkExecutorWorkerThread-1": waiting to lock monitor 0x003384ec (object 0x05239e48, a oracle.classloader.Po licyClassLoader), which is held by "OC4J Launcher" "OC4J Launcher": waiting to lock monitor 0x0033848c (object 0x0554f0e8, a oracle.classloader.Po licyClassLoader), which is held by "WorkExecutorWorkerThread-1" Java stack information for the threads listed above: =================================================== "WorkExecutorWorkerThread-1": at oracle.classloader.SearchPolicy.loadClass(SearchPolicy.java:641) - waiting to lock <0x05239e48> (a oracle.classloader.PolicyClassLoader) at oracle.classloader.PolicyClassLoader.askParentForClass(PolicyClassLoa der.java:1284) at oracle.classloader.SearchPolicy$AskParent.getClass(SearchPolicy.java: 69) at oracle.classloader.SearchSequence.getClass(SearchSequence.java:119) at oracle.classloader.SearchPolicy.loadClass(SearchPolicy.java:642) - locked <0x0554f0e8> (a oracle.classloader.PolicyClassLoader) at oracle.classloader.PolicyClassLoader.askParentForClass(PolicyClassLoa der.java:1284) at oracle.classloader.SearchPolicy$AskParent.getClass(SearchPolicy.java: 69) at oracle.classloader.SearchSequence.getClass(SearchSequence.java:119) at oracle.classloader.PolicyClassLoader.internalLoadClass(PolicyClassLoa der.java:1660) - locked <0x056a9ed0> (a oracle.classloader.PolicyClassLoader) at oracle.classloader.PolicyClassLoader.loadClass(PolicyClassLoader.java :1621) at oracle.classloader.PolicyClassLoader.loadClass(PolicyClassLoader.java :1606) at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:319) - locked <0x056a9ed0> (a oracle.classloader.PolicyClassLoader) at oracle.j2ee.ra.jms.generic.WorkConsumer.doReceive(WorkConsumer.java:9 87) at oracle.j2ee.ra.jms.generic.WorkConsumer.run(WorkConsumer.java:215) - locked <0x05de2718> (a oracle.j2ee.ra.jms.generic.WorkConsumer) at oracle.j2ee.connector.work.WorkWrapper.runTargetWork(WorkWrapper.java :242) at oracle.j2ee.connector.work.WorkWrapper.doWork(WorkWrapper.java:215) at oracle.j2ee.connector.work.WorkWrapper.run(WorkWrapper.java:190) at EDU.oswego.cs.dl.util.concurrent.PooledExecutor$Worker.run(PooledExec utor.java:814) at java.lang.Thread.run(Thread.java:595) "OC4J Launcher": at oracle.classloader.PolicyClassLoader.toString(PolicyClassLoader.java: 1846) - waiting to lock <0x0554f0e8> (a oracle.classloader.PolicyClassLoader) at java.text.MessageFormat.subformat(MessageFormat.java:1237) at java.text.MessageFormat.format(MessageFormat.java:828) at java.text.Format.format(Format.java:133) at java.text.MessageFormat.format(MessageFormat.java:804) at java.util.logging.Formatter.formatMessage(Formatter.java:130) - locked <0x0514e920> (a java.util.logging.SimpleFormatter) at java.util.logging.SimpleFormatter.format(SimpleFormatter.java:63) - locked <0x0514e920> (a java.util.logging.SimpleFormatter) at java.util.logging.StreamHandler.publish(StreamHandler.java:179) - locked <0x0514a0a8> (a java.util.logging.FileHandler) at java.util.logging.FileHandler.publish(FileHandler.java:555) - locked <0x0514a0a8> (a java.util.logging.FileHandler) at java.util.logging.Logger.log(Logger.java:428) at java.util.logging.Logger.doLog(Logger.java:450) at java.util.logging.Logger.logp(Logger.java:619) at java.util.logging.Logger.entering(Logger.java:870) at org.aspectj.weaver.tools.Jdk14Trace.enter(Jdk14Trace.java:32) at org.aspectj.weaver.loadtime.Aj.preProcess(Aj.java:67) at org.aspectj.weaver.loadtime.ClassPreProcessorAgentAdapter.transform(C lassPreProcessorAgentAdapter.java:55) at sun.instrument.TransformerManager.transform(TransformerManager.java:1 22) at sun.instrument.InstrumentationImpl.transform(InstrumentationImpl.java :155) at java.lang.ClassLoader.defineClass1(Native Method) at java.lang.ClassLoader.defineClass(ClassLoader.java:620) at oracle.classloader.PolicyClassLoader.defineClass(PolicyClassLoader.ja va:2224) at oracle.classloader.PolicyClassLoader.findLocalClass(PolicyClassLoader .java:1457) at oracle.classloader.SearchPolicy$FindLocal.getClass(SearchPolicy.java: 167) at oracle.classloader.SearchSequence.getClass(SearchSequence.java:119) at oracle.classloader.PolicyClassLoader.internalLoadClass(PolicyClassLoa der.java:1660) - locked <0x05239e48> (a oracle.classloader.PolicyClassLoader) at oracle.classloader.PolicyClassLoader.loadClass(PolicyClassLoader.java :1621) at oracle.classloader.PolicyClassLoader.loadClass(PolicyClassLoader.java :1606) at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:319) - locked <0x05239e48> (a oracle.classloader.PolicyClassLoader) at com.evermind.server.http.HttpRequestHandler.<init>(HttpRequestHandler .java:97) at com.evermind.server.http.HttpConnectionListener$HttpNIOAcceptHandler. getReadHandler(HttpConnectionListener.java:116) at oracle.oc4j.network.ReadHandlerPool.getContextFromBackend(ReadHandler Pool.java:63) at com.evermind.util.BBPool.startPool(BBPool.java:42) at oracle.oc4j.network.ReadHandlerPool.register(ReadHandlerPool.java:25) - locked <0x05ec9290> (a java.util.ArrayList) at oracle.oc4j.network.ServerSocketAcceptHandler.setPoolOptions(ServerSo cketAcceptHandler.java:140) at com.evermind.server.http.HttpConnectionListener.setRequestHandlerPool (HttpConnectionListener.java:232) at com.evermind.server.http.HttpConnectionListener.initHandlers(HttpConn ectionListener.java:226) at com.evermind.server.http.HttpConnectionListener.<init>(HttpConnection Listener.java:174) at com.evermind.server.http.HttpServer.getListener(HttpServer.java:481) - locked <0x05ec4f88> (a com.evermind.server.http.HttpServer) at com.evermind.server.http.HttpServer.setSites(HttpServer.java:267) - locked <0x05ec4f88> (a com.evermind.server.http.HttpServer) at com.evermind.server.http.HttpServer.setConfig(HttpServer.java:180) at com.evermind.server.ApplicationServer.initializeHttp(ApplicationServe r.java:2296) at com.evermind.server.ApplicationServer.setConfig(ApplicationServer.jav a:944) at com.evermind.server.ApplicationServerLauncher.run(ApplicationServerLa uncher.java:113) - locked <0x0530eb20> (a java.lang.Object) at java.lang.Thread.run(Thread.java:595) Found 1 deadlock.
|
resolved fixed
|
6be7097
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-08-25T14:37:34Z | 2006-08-25T01:40:00Z |
weaver5/java5-src/org/aspectj/weaver/tools/Jdk14Trace.java
|
/*******************************************************************************
* Copyright (c) 2006 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Matthew Webster - initial implementation
*******************************************************************************/
package org.aspectj.weaver.tools;
import java.util.logging.Handler;
import java.util.logging.Level;
import java.util.logging.Logger;
public class Jdk14Trace extends AbstractTrace {
private Logger logger;
private String name;
public Jdk14Trace (Class clazz) {
super(clazz);
this.name = clazz.getName();
this.logger = Logger.getLogger(name);
}
public void enter(String methodName, Object thiz, Object[] args) {
if (logger.isLoggable(Level.FINE)) {
logger.entering(name,methodName,formatObj(thiz));
if (args != null && logger.isLoggable(Level.FINER)) {
logger.entering(name,methodName,args);
}
}
}
public void enter(String methodName, Object thiz) {
enter(methodName,thiz,null);
}
public void exit(String methodName, Object ret) {
if (logger.isLoggable(Level.FINE)) {
logger.exiting(name,methodName,ret);
}
}
public void exit(String methodName, Throwable th) {
if (logger.isLoggable(Level.FINE)) {
logger.exiting(name,methodName,th);
}
}
public void exit(String methodName) {
if (logger.isLoggable(Level.FINE)) {
logger.exiting(name,methodName);
}
}
public void event(String methodName, Object thiz, Object[] args) {
if (logger.isLoggable(Level.FINE)) {
logger.logp(Level.FINER,name,methodName,"EVENT",formatObj(thiz));
if (args != null && logger.isLoggable(Level.FINER)) {
logger.logp(Level.FINER,name,methodName,"EVENT",args);
}
}
}
public void event(String methodName) {
if (logger.isLoggable(Level.FINE)) {
logger.logp(Level.FINER,name,methodName,"EVENT");
}
}
public boolean isTraceEnabled() {
return logger.isLoggable(Level.FINER);
}
public void setTraceEnabled (boolean b) {
if (b) {
logger.setLevel(Level.FINER);
Handler[] handlers = logger.getHandlers();
if (handlers.length == 0) {
Logger parent = logger.getParent();
if (parent != null) handlers = parent.getHandlers();
}
for (int i = 0; i < handlers.length; i++) {
Handler handler = handlers[i];
handler.setLevel(Level.FINER);
}
}
else {
logger.setLevel(Level.INFO);
}
}
public void debug (String message) {
if (logger.isLoggable(Level.FINE)) {
logger.fine(message);
}
}
public void info(String message) {
if (logger.isLoggable(Level.INFO)) {
logger.info(message);
}
}
public void warn (String message, Throwable th) {
if (logger.isLoggable(Level.WARNING)) {
logger.log(Level.WARNING,message,th);
}
}
public void error (String message, Throwable th) {
if (logger.isLoggable(Level.SEVERE)) {
logger.log(Level.SEVERE,message,th);
}
}
public void fatal (String message, Throwable th) {
if (logger.isLoggable(Level.SEVERE)) {
logger.log(Level.SEVERE,message,th);
}
}
}
|
155,238 |
Bug 155238 Trace should use System.identityHashCode, not hashCode
|
The tracing module uses obj.hashCode() to identify untrusted objects when formatting. I think it would be a little safer and more accurate to use System.identityHashCode(obj). This way the tracing code wouldn't call any application-defined code, and would give a value that can't change if the loader state changes.
|
resolved fixed
|
14e8b7d
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-08-30T09:46:37Z | 2006-08-25T15:33:20Z |
loadtime/src/org/aspectj/weaver/loadtime/DefaultWeavingContext.java
|
/*******************************************************************************
* Copyright (c) 2005 Contributors.
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Eclipse Public License v1.0
* which accompanies this distribution and is available at
* http://eclipse.org/legal/epl-v10.html
*
* Contributors:
* David Knibb initial implementation
*******************************************************************************/
package org.aspectj.weaver.loadtime;
import java.io.IOException;
import java.net.URL;
import java.util.Enumeration;
/**
* Use in non-OSGi environment
*
* @author David Knibb
*/
public class DefaultWeavingContext implements IWeavingContext {
protected ClassLoader loader;
private String shortName;
/**
* Construct a new WeavingContext to use the specifed ClassLoader
* This is the constructor which should be used.
* @param loader
*/
public DefaultWeavingContext(ClassLoader loader) {
this.loader = loader;
}
/**
* Same as ClassLoader.getResources()
*/
public Enumeration getResources(String name) throws IOException {
return loader.getResources(name);
}
/**
* @return null as we are not in an OSGi environment (therefore no bundles)
*/
public String getBundleIdFromURL(URL url) {
return "";
}
/**
* @return classname@hashcode
*/
public String getClassLoaderName() {
return ((loader!=null)?loader.getClass().getName()+"@"+Integer.toHexString(loader.hashCode()):"null");
}
/**
* @return filename
*/
public String getFile(URL url) {
return url.getFile();
}
/**
* @return unqualifiedclassname@hashcode
*/
public String getId () {
if (shortName == null) {
shortName = getClassLoaderName().replace('$','.');
int index = shortName.lastIndexOf(".");
shortName = shortName.substring(index + 1);
}
return shortName;
}
public String getSuffix () {
return getClassLoaderName();
}
public boolean isLocallyDefined(String classname) {
String asResource = classname.replace('.', '/').concat(".class");
URL localURL = loader.getResource(asResource);
if (localURL == null) return false;
boolean isLocallyDefined = true;
ClassLoader parent = loader.getParent();
if (parent != null) {
URL parentURL = parent.getResource(asResource);
if (localURL.equals(parentURL)) isLocallyDefined = false;
}
return isLocallyDefined;
}
}
|
155,238 |
Bug 155238 Trace should use System.identityHashCode, not hashCode
|
The tracing module uses obj.hashCode() to identify untrusted objects when formatting. I think it would be a little safer and more accurate to use System.identityHashCode(obj). This way the tracing code wouldn't call any application-defined code, and would give a value that can't change if the loader state changes.
|
resolved fixed
|
14e8b7d
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-08-30T09:46:37Z | 2006-08-25T15:33:20Z |
weaver/src/org/aspectj/weaver/tools/AbstractTrace.java
|
/*******************************************************************************
* Copyright (c) 2006 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Matthew Webster - initial implementation
*******************************************************************************/
package org.aspectj.weaver.tools;
import java.io.File;
import java.lang.reflect.Array;
import java.text.SimpleDateFormat;
import java.util.Collection;
import java.util.Date;
public abstract class AbstractTrace implements Trace {
protected Class tracedClass;
private static SimpleDateFormat timeFormat;
protected AbstractTrace (Class clazz) {
this.tracedClass = clazz;
}
public abstract void enter (String methodName, Object thiz, Object[] args);
public abstract void enter(String methodName, Object thiz);
public abstract void exit(String methodName, Object ret);
public abstract void exit(String methodName, Throwable th);
/*
* Convenience methods
*/
public void enter (String methodName) {
enter(methodName,null,null);
}
public void enter (String methodName, Object thiz, Object arg) {
enter(methodName,thiz,new Object[] { arg });
}
public void enter (String methodName, Object thiz, boolean z) {
enter(methodName,thiz,new Boolean(z));
}
public void exit (String methodName, boolean b) {
exit(methodName,new Boolean(b));
}
public void event (String methodName, Object thiz, Object arg) {
event(methodName,thiz,new Object[] { arg });
}
public void warn(String message) {
warn(message,null);
}
public void error(String message) {
error(message,null);
}
public void fatal (String message) {
fatal(message,null);
}
/*
* Formatting
*/
protected String formatMessage(String kind, String className, String methodName, Object thiz, Object[] args) {
StringBuffer message = new StringBuffer();
Date now = new Date();
message.append(formatDate(now)).append(" ");
message.append(Thread.currentThread().getName()).append(" ");
message.append(kind).append(" ");
message.append(className);
message.append(".").append(methodName);
if (thiz != null) message.append(" ").append(formatObj(thiz));
if (args != null) message.append(" ").append(formatArgs(args));
return message.toString();
}
protected String formatMessage(String kind, String text, Throwable th) {
StringBuffer message = new StringBuffer();
Date now = new Date();
message.append(formatDate(now)).append(" ");
message.append(Thread.currentThread().getName()).append(" ");
message.append(kind).append(" ");
message.append(text);
if (th != null) message.append(" ").append(formatObj(th));
return message.toString();
}
private static String formatDate (Date date) {
if (timeFormat == null) {
timeFormat = new SimpleDateFormat("HH:mm:ss.SSS");
}
return timeFormat.format(date);
}
/**
* Format objects safely avoiding toString which can cause recursion,
* NullPointerExceptions or highly verbose results.
*
* @param obj parameter to be formatted
* @return the formated parameter
*/
protected Object formatObj(Object obj) {
/* These classes have a safe implementation of toString() */
if (obj == null
|| obj instanceof String
|| obj instanceof Number
|| obj instanceof Boolean
|| obj instanceof Exception
|| obj instanceof Character
|| obj instanceof Class
|| obj instanceof File
|| obj instanceof StringBuffer
) return obj;
else if (obj.getClass().isArray()) {
return formatArray(obj);
}
else if (obj instanceof Collection) {
return formatCollection((Collection)obj);
}
else try {
/* Classes can provide an alternative implementation of toString() */
if (obj instanceof Traceable) {
Traceable t = (Traceable)obj;
return t.toTraceString();
}
/* Use classname@hashcode */
else return obj.getClass().getName() + "@" + Integer.toHexString(obj.hashCode());
/* Object.hashCode() can be override and may thow an exception */
} catch (Exception ex) {
return obj.getClass().getName() + "@FFFFFFFF";
}
}
protected String formatArray (Object obj) {
return obj.getClass().getComponentType().getName() + "[" + Array.getLength(obj) + "]";
}
protected String formatCollection (Collection c) {
return c.getClass().getName() + "(" + c.size() + ")";
}
/**
* Format arguments into a comma separated list
*
* @param names array of argument names
* @param args array of arguments
* @return the formated list
*/
protected String formatArgs(Object[] args) {
StringBuffer sb = new StringBuffer();
for (int i = 0; i < args.length; i++) {
sb.append(formatObj(args[i]));
if (i < args.length-1) sb.append(", ");
}
return sb.toString();
}
protected Object[] formatObjects(Object[] args) {
for (int i = 0; i < args.length; i++) {
args[i] = formatObj(args[i]);
}
return args;
}
}
|
155,972 |
Bug 155972 NullPointerException in ConstructorSignature.getConstructor()
|
AspectJ version: 1.5.3.200608290814 When advising a constructor, we can do the following to obtain the constructor as a java.lang.reflect.Member: Member cons = ((ConstructorSignature) thisJoinPointStaticPart .getSignature()).getConstructor(); however that sometimes fails, and returns null.
|
resolved fixed
|
090de7e
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-09-04T14:24:51Z | 2006-09-01T11:26:40Z |
runtime/src/org/aspectj/runtime/reflect/ConstructorSignatureImpl.java
|
/* *******************************************************************
* Copyright (c) 1999-2001 Xerox Corporation,
* 2002 Palo Alto Research Center, Incorporated (PARC).
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Eclipse Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Xerox/PARC initial implementation
* ******************************************************************/
package org.aspectj.runtime.reflect;
import java.lang.reflect.Constructor;
import org.aspectj.lang.reflect.ConstructorSignature;
class ConstructorSignatureImpl extends CodeSignatureImpl implements ConstructorSignature {
private Constructor constructor;
ConstructorSignatureImpl(int modifiers, Class declaringType,
Class[] parameterTypes, String[] parameterNames, Class[] exceptionTypes)
{
super(modifiers, "<init>", declaringType, parameterTypes, parameterNames, exceptionTypes);
}
ConstructorSignatureImpl(String stringRep) {
super(stringRep);
}
public String getName() { return "<init>"; }
protected String createToString(StringMaker sm) {
StringBuffer buf = new StringBuffer();
buf.append(sm.makeModifiersString(getModifiers()));
buf.append(sm.makePrimaryTypeName(getDeclaringType(),getDeclaringTypeName()));
sm.addSignature(buf, getParameterTypes());
sm.addThrows(buf, getExceptionTypes());
return buf.toString();
}
/* (non-Javadoc)
* @see org.aspectj.runtime.reflect.MemberSignatureImpl#createAccessibleObject()
*/
public Constructor getConstructor() {
if (constructor == null) {
try {
constructor = declaringType.getDeclaredConstructor(getParameterTypes());
} catch (Exception ex) {
; // nothing we can do, caller will see null
}
}
return constructor;
}
}
|
155,972 |
Bug 155972 NullPointerException in ConstructorSignature.getConstructor()
|
AspectJ version: 1.5.3.200608290814 When advising a constructor, we can do the following to obtain the constructor as a java.lang.reflect.Member: Member cons = ((ConstructorSignature) thisJoinPointStaticPart .getSignature()).getConstructor(); however that sometimes fails, and returns null.
|
resolved fixed
|
090de7e
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-09-04T14:24:51Z | 2006-09-01T11:26:40Z |
runtime/src/org/aspectj/runtime/reflect/FieldSignatureImpl.java
|
/* *******************************************************************
* Copyright (c) 1999-2001 Xerox Corporation,
* 2002 Palo Alto Research Center, Incorporated (PARC).
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Eclipse Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Xerox/PARC initial implementation
* ******************************************************************/
package org.aspectj.runtime.reflect;
import java.lang.reflect.Field;
import org.aspectj.lang.reflect.FieldSignature;
public class FieldSignatureImpl extends MemberSignatureImpl implements FieldSignature {
Class fieldType;
private Field field;
FieldSignatureImpl(int modifiers, String name, Class declaringType,
Class fieldType)
{
super(modifiers, name, declaringType);
this.fieldType = fieldType;
}
FieldSignatureImpl(String stringRep) {
super(stringRep);
}
public Class getFieldType() {
if (fieldType == null) fieldType = extractType(3);
return fieldType;
}
protected String createToString(StringMaker sm) {
StringBuffer buf = new StringBuffer();
buf.append(sm.makeModifiersString(getModifiers()));
if (sm.includeArgs) buf.append(sm.makeTypeName(getFieldType()));
if (sm.includeArgs) buf.append(" ");
buf.append(sm.makePrimaryTypeName(getDeclaringType(),getDeclaringTypeName()));
buf.append(".");
buf.append(getName());
return buf.toString();
}
/* (non-Javadoc)
* @see org.aspectj.runtime.reflect.MemberSignatureImpl#createAccessibleObject()
*/
public Field getField() {
if (field == null) {
try {
field = declaringType.getDeclaredField(getName());
} catch (Exception ex) {
; // nothing we can do, caller will see null
}
}
return field;
}
}
|
155,972 |
Bug 155972 NullPointerException in ConstructorSignature.getConstructor()
|
AspectJ version: 1.5.3.200608290814 When advising a constructor, we can do the following to obtain the constructor as a java.lang.reflect.Member: Member cons = ((ConstructorSignature) thisJoinPointStaticPart .getSignature()).getConstructor(); however that sometimes fails, and returns null.
|
resolved fixed
|
090de7e
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-09-04T14:24:51Z | 2006-09-01T11:26:40Z |
runtime/src/org/aspectj/runtime/reflect/InitializerSignatureImpl.java
|
/* *******************************************************************
* Copyright (c) 1999-2001 Xerox Corporation,
* 2002 Palo Alto Research Center, Incorporated (PARC).
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Eclipse Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Xerox/PARC initial implementation
* ******************************************************************/
package org.aspectj.runtime.reflect;
import org.aspectj.lang.reflect.InitializerSignature;
import java.lang.reflect.Constructor;
import java.lang.reflect.Modifier;
class InitializerSignatureImpl extends CodeSignatureImpl implements InitializerSignature {
private Constructor constructor;
InitializerSignatureImpl(int modifiers, Class declaringType) {
super(modifiers, Modifier.isStatic(modifiers) ? "<clinit>" : "<init>", declaringType, EMPTY_CLASS_ARRAY,
EMPTY_STRING_ARRAY, EMPTY_CLASS_ARRAY);
}
InitializerSignatureImpl(String stringRep) {
super(stringRep);
}
public String getName() {
return Modifier.isStatic(getModifiers()) ? "<clinit>": "<init>";
}
protected String createToString(StringMaker sm) {
StringBuffer buf = new StringBuffer();
buf.append(sm.makeModifiersString(getModifiers()));
buf.append(sm.makePrimaryTypeName(getDeclaringType(),getDeclaringTypeName()));
buf.append(".");
buf.append(getName());
return buf.toString();
}
/* (non-Javadoc)
* @see org.aspectj.runtime.reflect.MemberSignatureImpl#createAccessibleObject()
*/
public Constructor getInitializer() {
if (constructor == null) {
try {
constructor = declaringType.getDeclaredConstructor(getParameterTypes());
} catch (Exception ex) {
; // nothing we can do, caller will see null
}
}
return constructor;
}
}
|
155,972 |
Bug 155972 NullPointerException in ConstructorSignature.getConstructor()
|
AspectJ version: 1.5.3.200608290814 When advising a constructor, we can do the following to obtain the constructor as a java.lang.reflect.Member: Member cons = ((ConstructorSignature) thisJoinPointStaticPart .getSignature()).getConstructor(); however that sometimes fails, and returns null.
|
resolved fixed
|
090de7e
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-09-04T14:24:51Z | 2006-09-01T11:26:40Z |
tests/bugs153/pr155972/ConstructorTest.java
| |
155,972 |
Bug 155972 NullPointerException in ConstructorSignature.getConstructor()
|
AspectJ version: 1.5.3.200608290814 When advising a constructor, we can do the following to obtain the constructor as a java.lang.reflect.Member: Member cons = ((ConstructorSignature) thisJoinPointStaticPart .getSignature()).getConstructor(); however that sometimes fails, and returns null.
|
resolved fixed
|
090de7e
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-09-04T14:24:51Z | 2006-09-01T11:26:40Z |
tests/bugs153/pr155972/FieldTest.java
| |
155,972 |
Bug 155972 NullPointerException in ConstructorSignature.getConstructor()
|
AspectJ version: 1.5.3.200608290814 When advising a constructor, we can do the following to obtain the constructor as a java.lang.reflect.Member: Member cons = ((ConstructorSignature) thisJoinPointStaticPart .getSignature()).getConstructor(); however that sometimes fails, and returns null.
|
resolved fixed
|
090de7e
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-09-04T14:24:51Z | 2006-09-01T11:26:40Z |
tests/bugs153/pr155972/InitializerTest.java
| |
155,972 |
Bug 155972 NullPointerException in ConstructorSignature.getConstructor()
|
AspectJ version: 1.5.3.200608290814 When advising a constructor, we can do the following to obtain the constructor as a java.lang.reflect.Member: Member cons = ((ConstructorSignature) thisJoinPointStaticPart .getSignature()).getConstructor(); however that sometimes fails, and returns null.
|
resolved fixed
|
090de7e
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-09-04T14:24:51Z | 2006-09-01T11:26:40Z |
tests/src/org/aspectj/systemtest/ajc153/Ajc153Tests.java
|
/*******************************************************************************
* Copyright (c) 2006 IBM
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Andy Clement - initial API and implementation
*******************************************************************************/
package org.aspectj.systemtest.ajc153;
import java.io.File;
import junit.framework.Test;
import org.aspectj.testing.Utils;
import org.aspectj.testing.XMLBasedAjcTestCase;
import org.aspectj.weaver.bcel.Utility;
public class Ajc153Tests extends org.aspectj.testing.XMLBasedAjcTestCase {
//public void testGenericsProblem_pr151978() { runTest("generics problem");}
//public void testMissingLineNumbersInStacktraceBefore_pr145442() { runTest("missing line numbers in stacktrace before");}
//public void testMissingLineNumbersInStacktraceAfter_pr145442() { runTest("missing line numbers in stacktrace after");}
//public void testMissingLineNumbersInStacktraceAround_pr145442() { runTest("missing line numbers in stacktrace around");}
// public void testArgnamesAndJavac_pr148381() { runTest("argNames and javac");}
// public void testCFlowXMLAspectLTW_pr149096() { runTest("cflow xml concrete aspect"); }
// public void testAmbiguousBinding_pr121805() { runTest("ambiguous binding");}
public void 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 testVisibilityProblem_pr149071() { runTest("visibility problem");}
// public void testAdviceNotWovenAspectPath_pr147841() { runTest("advice not woven on aspectpath");}
public void testGenericSignatures_pr148409() { runTest("generic signature problem"); }
// public void testBrokenIfArgsCflowAtAj_pr145018() { runTest("ataj crashing with cflow, if and args");}
public void testCantFindType_pr149322_01() {runTest("can't find type on interface call 1");}
public void testCantFindType_pr149322_02() {runTest("can't find type on interface call 2");}
public void testCantFindType_pr149322_03() {runTest("can't find type on interface call 3");}
public void 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 static Test suite() {
return XMLBasedAjcTestCase.loadSuite(Ajc153Tests.class);
}
protected File getSpecFile() {
return new File("../tests/src/org/aspectj/systemtest/ajc153/ajc153.xml");
}
}
|
153,845 |
Bug 153845 [generics] Problem with signature for generic type
|
public aspect OuterAspect { private pointcut isSetter() : execution(void set*(..)); public static aspect InnerAspect pertarget(isSetter()) { } } java.lang.IllegalStateException at org.aspectj.apache.bcel.classfile.GenericSignatureParser.parseFieldTypeSignature(GenericSignatureParser.java:163) at org.aspectj.apache.bcel.classfile.GenericSignatureParser.parseTypeArgument(GenericSignatureParser.java:253) at org.aspectj.apache.bcel.classfile.GenericSignatureParser.maybeParseTypeArguments(GenericSignatureParser.java:261) at org.aspectj.apache.bcel.classfile.GenericSignatureParser.parseClassTypeSignature(GenericSignatureParser.java:208) at org.aspectj.apache.bcel.classfile.GenericSignatureParser.parseAsClassSignature(GenericSignatureParser.java:56) at org.aspectj.apache.bcel.classfile.Signature.asClassSignature(Signature.java:315) at org.aspectj.apache.bcel.classfile.JavaClass.getGenericClassTypeSignature(JavaClass.java:973) at org.aspectj.weaver.bcel.BcelObjectType.initializeFromJavaclass(BcelObjectType.java:164) at org.aspectj.weaver.bcel.BcelObjectType.<init>(BcelObjectType.java:131) at org.aspectj.weaver.bcel.BcelWorld.buildBcelDelegate(BcelWorld.java:337) at org.aspectj.weaver.bcel.BcelWorld.addSourceObjectType(BcelWorld.java:395) at org.aspectj.weaver.bcel.BcelWeaver.addIfAspect(BcelWeaver.java:263) at org.aspectj.weaver.bcel.BcelWeaver.addAspectsFromDirectory(BcelWeaver.java:255) at org.aspectj.weaver.bcel.BcelWeaver.addLibraryJarFile(BcelWeaver.java:205) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.initBcelWorld(AjBuildManager.java:698) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.doBuild(AjBuildManager.java:223) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.doBuild(AjBuildManager.java:199) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.incrementalBuild(AjBuildManager.java:170) at org.aspectj.ajde.internal.CompilerAdapter.compile(CompilerAdapter.java:117) at org.aspectj.ajde.internal.AspectJBuildManager$CompilerThread.run(AspectJBuildManager.java:191) IllegalStateException thrown: Expecting [,L, or T, but found Pjava while unpacking Ljava/util/AbstractSet<Pjava/util/Map$Entry<TK;TV;>;>;
|
resolved fixed
|
70ae0f8
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-09-14T10:38:50Z | 2006-08-15T02:46:40Z |
tests/bugs153/pr153845/Aspect.java
| |
153,845 |
Bug 153845 [generics] Problem with signature for generic type
|
public aspect OuterAspect { private pointcut isSetter() : execution(void set*(..)); public static aspect InnerAspect pertarget(isSetter()) { } } java.lang.IllegalStateException at org.aspectj.apache.bcel.classfile.GenericSignatureParser.parseFieldTypeSignature(GenericSignatureParser.java:163) at org.aspectj.apache.bcel.classfile.GenericSignatureParser.parseTypeArgument(GenericSignatureParser.java:253) at org.aspectj.apache.bcel.classfile.GenericSignatureParser.maybeParseTypeArguments(GenericSignatureParser.java:261) at org.aspectj.apache.bcel.classfile.GenericSignatureParser.parseClassTypeSignature(GenericSignatureParser.java:208) at org.aspectj.apache.bcel.classfile.GenericSignatureParser.parseAsClassSignature(GenericSignatureParser.java:56) at org.aspectj.apache.bcel.classfile.Signature.asClassSignature(Signature.java:315) at org.aspectj.apache.bcel.classfile.JavaClass.getGenericClassTypeSignature(JavaClass.java:973) at org.aspectj.weaver.bcel.BcelObjectType.initializeFromJavaclass(BcelObjectType.java:164) at org.aspectj.weaver.bcel.BcelObjectType.<init>(BcelObjectType.java:131) at org.aspectj.weaver.bcel.BcelWorld.buildBcelDelegate(BcelWorld.java:337) at org.aspectj.weaver.bcel.BcelWorld.addSourceObjectType(BcelWorld.java:395) at org.aspectj.weaver.bcel.BcelWeaver.addIfAspect(BcelWeaver.java:263) at org.aspectj.weaver.bcel.BcelWeaver.addAspectsFromDirectory(BcelWeaver.java:255) at org.aspectj.weaver.bcel.BcelWeaver.addLibraryJarFile(BcelWeaver.java:205) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.initBcelWorld(AjBuildManager.java:698) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.doBuild(AjBuildManager.java:223) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.doBuild(AjBuildManager.java:199) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.incrementalBuild(AjBuildManager.java:170) at org.aspectj.ajde.internal.CompilerAdapter.compile(CompilerAdapter.java:117) at org.aspectj.ajde.internal.AspectJBuildManager$CompilerThread.run(AspectJBuildManager.java:191) IllegalStateException thrown: Expecting [,L, or T, but found Pjava while unpacking Ljava/util/AbstractSet<Pjava/util/Map$Entry<TK;TV;>;>;
|
resolved fixed
|
70ae0f8
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-09-14T10:38:50Z | 2006-08-15T02:46:40Z |
tests/bugs153/pr153845/Aspect2.java
| |
153,845 |
Bug 153845 [generics] Problem with signature for generic type
|
public aspect OuterAspect { private pointcut isSetter() : execution(void set*(..)); public static aspect InnerAspect pertarget(isSetter()) { } } java.lang.IllegalStateException at org.aspectj.apache.bcel.classfile.GenericSignatureParser.parseFieldTypeSignature(GenericSignatureParser.java:163) at org.aspectj.apache.bcel.classfile.GenericSignatureParser.parseTypeArgument(GenericSignatureParser.java:253) at org.aspectj.apache.bcel.classfile.GenericSignatureParser.maybeParseTypeArguments(GenericSignatureParser.java:261) at org.aspectj.apache.bcel.classfile.GenericSignatureParser.parseClassTypeSignature(GenericSignatureParser.java:208) at org.aspectj.apache.bcel.classfile.GenericSignatureParser.parseAsClassSignature(GenericSignatureParser.java:56) at org.aspectj.apache.bcel.classfile.Signature.asClassSignature(Signature.java:315) at org.aspectj.apache.bcel.classfile.JavaClass.getGenericClassTypeSignature(JavaClass.java:973) at org.aspectj.weaver.bcel.BcelObjectType.initializeFromJavaclass(BcelObjectType.java:164) at org.aspectj.weaver.bcel.BcelObjectType.<init>(BcelObjectType.java:131) at org.aspectj.weaver.bcel.BcelWorld.buildBcelDelegate(BcelWorld.java:337) at org.aspectj.weaver.bcel.BcelWorld.addSourceObjectType(BcelWorld.java:395) at org.aspectj.weaver.bcel.BcelWeaver.addIfAspect(BcelWeaver.java:263) at org.aspectj.weaver.bcel.BcelWeaver.addAspectsFromDirectory(BcelWeaver.java:255) at org.aspectj.weaver.bcel.BcelWeaver.addLibraryJarFile(BcelWeaver.java:205) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.initBcelWorld(AjBuildManager.java:698) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.doBuild(AjBuildManager.java:223) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.doBuild(AjBuildManager.java:199) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.incrementalBuild(AjBuildManager.java:170) at org.aspectj.ajde.internal.CompilerAdapter.compile(CompilerAdapter.java:117) at org.aspectj.ajde.internal.AspectJBuildManager$CompilerThread.run(AspectJBuildManager.java:191) IllegalStateException thrown: Expecting [,L, or T, but found Pjava while unpacking Ljava/util/AbstractSet<Pjava/util/Map$Entry<TK;TV;>;>;
|
resolved fixed
|
70ae0f8
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-09-14T10:38:50Z | 2006-08-15T02:46:40Z |
tests/bugs153/pr153845/GenericType.java
| |
153,845 |
Bug 153845 [generics] Problem with signature for generic type
|
public aspect OuterAspect { private pointcut isSetter() : execution(void set*(..)); public static aspect InnerAspect pertarget(isSetter()) { } } java.lang.IllegalStateException at org.aspectj.apache.bcel.classfile.GenericSignatureParser.parseFieldTypeSignature(GenericSignatureParser.java:163) at org.aspectj.apache.bcel.classfile.GenericSignatureParser.parseTypeArgument(GenericSignatureParser.java:253) at org.aspectj.apache.bcel.classfile.GenericSignatureParser.maybeParseTypeArguments(GenericSignatureParser.java:261) at org.aspectj.apache.bcel.classfile.GenericSignatureParser.parseClassTypeSignature(GenericSignatureParser.java:208) at org.aspectj.apache.bcel.classfile.GenericSignatureParser.parseAsClassSignature(GenericSignatureParser.java:56) at org.aspectj.apache.bcel.classfile.Signature.asClassSignature(Signature.java:315) at org.aspectj.apache.bcel.classfile.JavaClass.getGenericClassTypeSignature(JavaClass.java:973) at org.aspectj.weaver.bcel.BcelObjectType.initializeFromJavaclass(BcelObjectType.java:164) at org.aspectj.weaver.bcel.BcelObjectType.<init>(BcelObjectType.java:131) at org.aspectj.weaver.bcel.BcelWorld.buildBcelDelegate(BcelWorld.java:337) at org.aspectj.weaver.bcel.BcelWorld.addSourceObjectType(BcelWorld.java:395) at org.aspectj.weaver.bcel.BcelWeaver.addIfAspect(BcelWeaver.java:263) at org.aspectj.weaver.bcel.BcelWeaver.addAspectsFromDirectory(BcelWeaver.java:255) at org.aspectj.weaver.bcel.BcelWeaver.addLibraryJarFile(BcelWeaver.java:205) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.initBcelWorld(AjBuildManager.java:698) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.doBuild(AjBuildManager.java:223) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.doBuild(AjBuildManager.java:199) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.incrementalBuild(AjBuildManager.java:170) at org.aspectj.ajde.internal.CompilerAdapter.compile(CompilerAdapter.java:117) at org.aspectj.ajde.internal.AspectJBuildManager$CompilerThread.run(AspectJBuildManager.java:191) IllegalStateException thrown: Expecting [,L, or T, but found Pjava while unpacking Ljava/util/AbstractSet<Pjava/util/Map$Entry<TK;TV;>;>;
|
resolved fixed
|
70ae0f8
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-09-14T10:38:50Z | 2006-08-15T02:46:40Z |
tests/bugs153/pr153845/Interface.java
| |
153,845 |
Bug 153845 [generics] Problem with signature for generic type
|
public aspect OuterAspect { private pointcut isSetter() : execution(void set*(..)); public static aspect InnerAspect pertarget(isSetter()) { } } java.lang.IllegalStateException at org.aspectj.apache.bcel.classfile.GenericSignatureParser.parseFieldTypeSignature(GenericSignatureParser.java:163) at org.aspectj.apache.bcel.classfile.GenericSignatureParser.parseTypeArgument(GenericSignatureParser.java:253) at org.aspectj.apache.bcel.classfile.GenericSignatureParser.maybeParseTypeArguments(GenericSignatureParser.java:261) at org.aspectj.apache.bcel.classfile.GenericSignatureParser.parseClassTypeSignature(GenericSignatureParser.java:208) at org.aspectj.apache.bcel.classfile.GenericSignatureParser.parseAsClassSignature(GenericSignatureParser.java:56) at org.aspectj.apache.bcel.classfile.Signature.asClassSignature(Signature.java:315) at org.aspectj.apache.bcel.classfile.JavaClass.getGenericClassTypeSignature(JavaClass.java:973) at org.aspectj.weaver.bcel.BcelObjectType.initializeFromJavaclass(BcelObjectType.java:164) at org.aspectj.weaver.bcel.BcelObjectType.<init>(BcelObjectType.java:131) at org.aspectj.weaver.bcel.BcelWorld.buildBcelDelegate(BcelWorld.java:337) at org.aspectj.weaver.bcel.BcelWorld.addSourceObjectType(BcelWorld.java:395) at org.aspectj.weaver.bcel.BcelWeaver.addIfAspect(BcelWeaver.java:263) at org.aspectj.weaver.bcel.BcelWeaver.addAspectsFromDirectory(BcelWeaver.java:255) at org.aspectj.weaver.bcel.BcelWeaver.addLibraryJarFile(BcelWeaver.java:205) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.initBcelWorld(AjBuildManager.java:698) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.doBuild(AjBuildManager.java:223) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.doBuild(AjBuildManager.java:199) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.incrementalBuild(AjBuildManager.java:170) at org.aspectj.ajde.internal.CompilerAdapter.compile(CompilerAdapter.java:117) at org.aspectj.ajde.internal.AspectJBuildManager$CompilerThread.run(AspectJBuildManager.java:191) IllegalStateException thrown: Expecting [,L, or T, but found Pjava while unpacking Ljava/util/AbstractSet<Pjava/util/Map$Entry<TK;TV;>;>;
|
resolved fixed
|
70ae0f8
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-09-14T10:38:50Z | 2006-08-15T02:46:40Z |
tests/bugs153/pr153845/Nothing.java
| |
153,845 |
Bug 153845 [generics] Problem with signature for generic type
|
public aspect OuterAspect { private pointcut isSetter() : execution(void set*(..)); public static aspect InnerAspect pertarget(isSetter()) { } } java.lang.IllegalStateException at org.aspectj.apache.bcel.classfile.GenericSignatureParser.parseFieldTypeSignature(GenericSignatureParser.java:163) at org.aspectj.apache.bcel.classfile.GenericSignatureParser.parseTypeArgument(GenericSignatureParser.java:253) at org.aspectj.apache.bcel.classfile.GenericSignatureParser.maybeParseTypeArguments(GenericSignatureParser.java:261) at org.aspectj.apache.bcel.classfile.GenericSignatureParser.parseClassTypeSignature(GenericSignatureParser.java:208) at org.aspectj.apache.bcel.classfile.GenericSignatureParser.parseAsClassSignature(GenericSignatureParser.java:56) at org.aspectj.apache.bcel.classfile.Signature.asClassSignature(Signature.java:315) at org.aspectj.apache.bcel.classfile.JavaClass.getGenericClassTypeSignature(JavaClass.java:973) at org.aspectj.weaver.bcel.BcelObjectType.initializeFromJavaclass(BcelObjectType.java:164) at org.aspectj.weaver.bcel.BcelObjectType.<init>(BcelObjectType.java:131) at org.aspectj.weaver.bcel.BcelWorld.buildBcelDelegate(BcelWorld.java:337) at org.aspectj.weaver.bcel.BcelWorld.addSourceObjectType(BcelWorld.java:395) at org.aspectj.weaver.bcel.BcelWeaver.addIfAspect(BcelWeaver.java:263) at org.aspectj.weaver.bcel.BcelWeaver.addAspectsFromDirectory(BcelWeaver.java:255) at org.aspectj.weaver.bcel.BcelWeaver.addLibraryJarFile(BcelWeaver.java:205) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.initBcelWorld(AjBuildManager.java:698) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.doBuild(AjBuildManager.java:223) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.doBuild(AjBuildManager.java:199) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.incrementalBuild(AjBuildManager.java:170) at org.aspectj.ajde.internal.CompilerAdapter.compile(CompilerAdapter.java:117) at org.aspectj.ajde.internal.AspectJBuildManager$CompilerThread.run(AspectJBuildManager.java:191) IllegalStateException thrown: Expecting [,L, or T, but found Pjava while unpacking Ljava/util/AbstractSet<Pjava/util/Map$Entry<TK;TV;>;>;
|
resolved fixed
|
70ae0f8
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-09-14T10:38:50Z | 2006-08-15T02:46:40Z |
tests/src/org/aspectj/systemtest/ajc153/Ajc153Tests.java
|
/*******************************************************************************
* Copyright (c) 2006 IBM
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Andy Clement - initial API and implementation
*******************************************************************************/
package org.aspectj.systemtest.ajc153;
import java.io.File;
import junit.framework.Test;
import org.aspectj.testing.Utils;
import org.aspectj.testing.XMLBasedAjcTestCase;
import org.aspectj.weaver.bcel.Utility;
public class Ajc153Tests extends org.aspectj.testing.XMLBasedAjcTestCase {
//public void testGenericsProblem_pr151978() { runTest("generics problem");}
//public void testMissingLineNumbersInStacktraceBefore_pr145442() { runTest("missing line numbers in stacktrace before");}
//public void testMissingLineNumbersInStacktraceAfter_pr145442() { runTest("missing line numbers in stacktrace after");}
//public void testMissingLineNumbersInStacktraceAround_pr145442() { runTest("missing line numbers in stacktrace around");}
// public void testArgnamesAndJavac_pr148381() { runTest("argNames and javac");}
// public void testCFlowXMLAspectLTW_pr149096() { runTest("cflow xml concrete aspect"); }
// public void testAmbiguousBinding_pr121805() { runTest("ambiguous binding");}
// public void testNoIllegalStateExceptionWithGenericInnerAspect_pr156058() { runTest("no IllegalStateException with generic inner aspect"); }
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 testVisibilityProblem_pr149071() { runTest("visibility problem");}
// public void testAdviceNotWovenAspectPath_pr147841() { runTest("advice not woven on aspectpath");}
public void testGenericSignatures_pr148409() { runTest("generic signature problem"); }
// public void testBrokenIfArgsCflowAtAj_pr145018() { runTest("ataj crashing with cflow, if and args");}
public void testCantFindType_pr149322_01() {runTest("can't find type on interface call 1");}
public void testCantFindType_pr149322_02() {runTest("can't find type on interface call 2");}
public void testCantFindType_pr149322_03() {runTest("can't find type on interface call 3");}
public void 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 static Test suite() {
return XMLBasedAjcTestCase.loadSuite(Ajc153Tests.class);
}
protected File getSpecFile() {
return new File("../tests/src/org/aspectj/systemtest/ajc153/ajc153.xml");
}
}
|
153,845 |
Bug 153845 [generics] Problem with signature for generic type
|
public aspect OuterAspect { private pointcut isSetter() : execution(void set*(..)); public static aspect InnerAspect pertarget(isSetter()) { } } java.lang.IllegalStateException at org.aspectj.apache.bcel.classfile.GenericSignatureParser.parseFieldTypeSignature(GenericSignatureParser.java:163) at org.aspectj.apache.bcel.classfile.GenericSignatureParser.parseTypeArgument(GenericSignatureParser.java:253) at org.aspectj.apache.bcel.classfile.GenericSignatureParser.maybeParseTypeArguments(GenericSignatureParser.java:261) at org.aspectj.apache.bcel.classfile.GenericSignatureParser.parseClassTypeSignature(GenericSignatureParser.java:208) at org.aspectj.apache.bcel.classfile.GenericSignatureParser.parseAsClassSignature(GenericSignatureParser.java:56) at org.aspectj.apache.bcel.classfile.Signature.asClassSignature(Signature.java:315) at org.aspectj.apache.bcel.classfile.JavaClass.getGenericClassTypeSignature(JavaClass.java:973) at org.aspectj.weaver.bcel.BcelObjectType.initializeFromJavaclass(BcelObjectType.java:164) at org.aspectj.weaver.bcel.BcelObjectType.<init>(BcelObjectType.java:131) at org.aspectj.weaver.bcel.BcelWorld.buildBcelDelegate(BcelWorld.java:337) at org.aspectj.weaver.bcel.BcelWorld.addSourceObjectType(BcelWorld.java:395) at org.aspectj.weaver.bcel.BcelWeaver.addIfAspect(BcelWeaver.java:263) at org.aspectj.weaver.bcel.BcelWeaver.addAspectsFromDirectory(BcelWeaver.java:255) at org.aspectj.weaver.bcel.BcelWeaver.addLibraryJarFile(BcelWeaver.java:205) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.initBcelWorld(AjBuildManager.java:698) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.doBuild(AjBuildManager.java:223) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.doBuild(AjBuildManager.java:199) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.incrementalBuild(AjBuildManager.java:170) at org.aspectj.ajde.internal.CompilerAdapter.compile(CompilerAdapter.java:117) at org.aspectj.ajde.internal.AspectJBuildManager$CompilerThread.run(AspectJBuildManager.java:191) IllegalStateException thrown: Expecting [,L, or T, but found Pjava while unpacking Ljava/util/AbstractSet<Pjava/util/Map$Entry<TK;TV;>;>;
|
resolved fixed
|
70ae0f8
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-09-14T10:38:50Z | 2006-08-15T02:46: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(someParameters[i].getSignature());
}
ret.append(">;");
return ret.toString();
}
}
|
158,412 |
Bug 158412 @Pointcut in declare error results in NPE
|
I am trying to use an @AspectJ @Pointcut in a "normal" AspectJ declare error expression. That results in the following exception. java.lang.NullPointerException at org.aspectj.weaver.patterns.ReferencePointcut.concretize1(ReferencePointcut.java:361) at org.aspectj.weaver.patterns.Pointcut.concretize(Pointcut.java:233) at org.aspectj.weaver.patterns.NotPointcut.concretize1(NotPointcut.java:100) at org.aspectj.weaver.patterns.Pointcut.concretize(Pointcut.java:233) at org.aspectj.weaver.patterns.AndPointcut.concretize1(AndPointcut.java:97) at org.aspectj.weaver.patterns.Pointcut.concretize(Pointcut.java:233) at org.aspectj.weaver.patterns.Pointcut.concretize(Pointcut.java:220) at org.aspectj.weaver.Checker.concretize(Checker.java:45) at org.aspectj.weaver.CrosscuttingMembers.addShadowMunger(CrosscuttingMembers.java:91) at org.aspectj.weaver.CrosscuttingMembers.addDeclare(CrosscuttingMembers.java:122) at org.aspectj.weaver.CrosscuttingMembers.addDeclares(CrosscuttingMembers.java:113) at org.aspectj.weaver.CrosscuttingMembersSet.addAdviceLikeDeclares(CrosscuttingMembersSet.java:117) at org.aspectj.ajdt.internal.compiler.lookup.AjLookupEnvironment.addAdviceLikeDeclares(AjLookupEnvironment.java:382) at org.aspectj.ajdt.internal.compiler.lookup.AjLookupEnvironment.completeTypeBindings(AjLookupEnvironment.java:245) 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.doBuild(AjBuildManager.java:199) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.incrementalBuild(AjBuildManager.java:170) at org.aspectj.ajde.internal.CompilerAdapter.compile(CompilerAdapter.java:117) at org.aspectj.ajde.internal.AspectJBuildManager$CompilerThread.run(AspectJBuildManager.java:191) NullPointerException thrown: null
|
resolved fixed
|
e56a69a
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-09-25T13:51:40Z | 2006-09-23T08:26:40Z |
org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/compiler/lookup/EclipseSourceType.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 perClause
* ******************************************************************/
package org.aspectj.ajdt.internal.compiler.lookup;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import org.aspectj.ajdt.internal.compiler.ast.AdviceDeclaration;
import org.aspectj.ajdt.internal.compiler.ast.AspectDeclaration;
import org.aspectj.ajdt.internal.compiler.ast.DeclareAnnotationDeclaration;
import org.aspectj.ajdt.internal.compiler.ast.DeclareDeclaration;
import org.aspectj.ajdt.internal.compiler.ast.InterTypeDeclaration;
import org.aspectj.ajdt.internal.compiler.ast.PointcutDeclaration;
import org.aspectj.ajdt.internal.core.builder.EclipseSourceContext;
import org.aspectj.bridge.IMessage;
import org.aspectj.org.eclipse.jdt.core.compiler.CharOperation;
import org.aspectj.org.eclipse.jdt.internal.compiler.ast.ASTNode;
import org.aspectj.org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration;
import org.aspectj.org.eclipse.jdt.internal.compiler.ast.Annotation;
import org.aspectj.org.eclipse.jdt.internal.compiler.ast.ArrayInitializer;
import org.aspectj.org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration;
import org.aspectj.org.eclipse.jdt.internal.compiler.ast.Expression;
import org.aspectj.org.eclipse.jdt.internal.compiler.ast.MemberValuePair;
import org.aspectj.org.eclipse.jdt.internal.compiler.ast.NormalAnnotation;
import org.aspectj.org.eclipse.jdt.internal.compiler.ast.QualifiedNameReference;
import org.aspectj.org.eclipse.jdt.internal.compiler.ast.SingleMemberAnnotation;
import org.aspectj.org.eclipse.jdt.internal.compiler.ast.SingleNameReference;
import org.aspectj.org.eclipse.jdt.internal.compiler.ast.StringLiteral;
import org.aspectj.org.eclipse.jdt.internal.compiler.ast.TypeDeclaration;
import org.aspectj.org.eclipse.jdt.internal.compiler.ast.TypeParameter;
import org.aspectj.org.eclipse.jdt.internal.compiler.impl.Constant;
import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.BinaryTypeBinding;
import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.CompilerModifiers;
import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.FieldBinding;
import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.MethodBinding;
import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.ReferenceBinding;
import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.SourceTypeBinding;
import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.TagBits;
import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.TypeBinding;
import org.aspectj.weaver.AbstractReferenceTypeDelegate;
import org.aspectj.weaver.AnnotationAJ;
import org.aspectj.weaver.AnnotationNameValuePair;
import org.aspectj.weaver.AnnotationTargetKind;
import org.aspectj.weaver.AnnotationValue;
import org.aspectj.weaver.AnnotationX;
import org.aspectj.weaver.ArrayAnnotationValue;
import org.aspectj.weaver.EnumAnnotationValue;
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.UnresolvedType;
import org.aspectj.weaver.WeaverStateInfo;
import org.aspectj.weaver.World;
import org.aspectj.weaver.patterns.PerClause;
import org.aspectj.weaver.patterns.PerFromSuper;
import org.aspectj.weaver.patterns.PerSingleton;
/**
* Supports viewing eclipse TypeDeclarations/SourceTypeBindings as a ResolvedType
*
* @author Jim Hugunin
*/
public class EclipseSourceType extends AbstractReferenceTypeDelegate {
private static final char[] pointcutSig = "Lorg/aspectj/lang/annotation/Pointcut;".toCharArray();
private static final char[] aspectSig = "Lorg/aspectj/lang/annotation/Aspect;".toCharArray();
protected ResolvedPointcutDefinition[] declaredPointcuts = null;
protected ResolvedMember[] declaredMethods = null;
protected ResolvedMember[] declaredFields = null;
public List declares = new ArrayList();
public List typeMungers = new ArrayList();
private EclipseFactory factory;
private SourceTypeBinding binding;
private TypeDeclaration declaration;
private CompilationUnitDeclaration unit;
private boolean annotationsResolved = false;
private ResolvedType[] resolvedAnnotations = null;
private boolean discoveredAnnotationTargetKinds = false;
private AnnotationTargetKind[] annotationTargetKinds;
private AnnotationX[] annotations = null;
private final static ResolvedType[] NO_ANNOTATION_TYPES = new ResolvedType[0];
private final static AnnotationX[] NO_ANNOTATIONS = new AnnotationX[0];
protected EclipseFactory eclipseWorld() {
return factory;
}
public EclipseSourceType(ReferenceType resolvedTypeX, EclipseFactory factory,
SourceTypeBinding binding, TypeDeclaration declaration,
CompilationUnitDeclaration unit)
{
super(resolvedTypeX, true);
this.factory = factory;
this.binding = binding;
this.declaration = declaration;
this.unit = unit;
setSourceContext(new EclipseSourceContext(declaration.compilationResult));
resolvedTypeX.setStartPos(declaration.sourceStart);
resolvedTypeX.setEndPos(declaration.sourceEnd);
}
public boolean isAspect() {
final boolean isCodeStyle = declaration instanceof AspectDeclaration;
return isCodeStyle?isCodeStyle:isAnnotationStyleAspect();
}
public boolean isAnonymous() {
return ((declaration.modifiers & ASTNode.AnonymousAndLocalMask) != 0);
}
public boolean isNested() {
return ((declaration.modifiers & ASTNode.IsMemberTypeMASK) != 0);
}
public ResolvedType getOuterClass() {
if (declaration.enclosingType==null) return null;
return eclipseWorld().fromEclipse(declaration.enclosingType.binding);
}
public boolean isAnnotationStyleAspect() {
if (declaration.annotations == null) {
return false;
}
ResolvedType[] annotations = getAnnotationTypes();
for (int i = 0; i < annotations.length; i++) {
if ("org.aspectj.lang.annotation.Aspect".equals(annotations[i].getName())) {
return true;
}
}
return false;
}
private boolean isAnnotationStylePointcut(Annotation[] annotations) {
if (annotations == null) return false;
for (int i = 0; i < annotations.length; i++) {
if (annotations[i].resolvedType == null) continue; // XXX happens if we do this very early from buildInterTypeandPerClause
// may prevent us from resolving references made in @Pointcuts to
// an @Pointcut in a code-style aspect
char[] sig = annotations[i].resolvedType.signature();
if (CharOperation.equals(pointcutSig,sig)) {
return true;
}
}
return false;
}
public WeaverStateInfo getWeaverState() {
return null;
}
public ResolvedType getSuperclass() {
if (binding.isInterface()) return getResolvedTypeX().getWorld().getCoreType(UnresolvedType.OBJECT);
//XXX what about java.lang.Object
return eclipseWorld().fromEclipse(binding.superclass());
}
public ResolvedType[] getDeclaredInterfaces() {
return eclipseWorld().fromEclipse(binding.superInterfaces());
}
protected void fillDeclaredMembers() {
List declaredPointcuts = new ArrayList();
List declaredMethods = new ArrayList();
List declaredFields = new ArrayList();
binding.methods(); // the important side-effect of this call is to make sure bindings are completed
AbstractMethodDeclaration[] methods = declaration.methods;
if (methods != null) {
for (int i=0, len=methods.length; i < len; i++) {
AbstractMethodDeclaration amd = methods[i];
if (amd == null || amd.ignoreFurtherInvestigation) continue;
if (amd instanceof PointcutDeclaration) {
PointcutDeclaration d = (PointcutDeclaration)amd;
ResolvedPointcutDefinition df = d.makeResolvedPointcutDefinition(factory);
declaredPointcuts.add(df);
} else if (amd instanceof InterTypeDeclaration) {
// these are handled in a separate pass
continue;
} else if (amd instanceof DeclareDeclaration &&
!(amd instanceof DeclareAnnotationDeclaration)) { // surfaces the annotated ajc$ method
// these are handled in a separate pass
continue;
} else if (amd instanceof AdviceDeclaration) {
// these are ignored during compilation and only used during weaving
continue;
} else if ((amd.annotations != null) && isAnnotationStylePointcut(amd.annotations)) {
// consider pointcuts defined via annotations
ResolvedPointcutDefinition df = makeResolvedPointcutDefinition(amd);
if (df!=null) declaredPointcuts.add(df);
} else {
if (amd.binding == null || !amd.binding.isValidBinding()) continue;
ResolvedMember member = factory.makeResolvedMember(amd.binding);
if (unit != null) {
member.setSourceContext(new EclipseSourceContext(unit.compilationResult,amd.binding.sourceStart()));
member.setPosition(amd.binding.sourceStart(),amd.binding.sourceEnd());
}
declaredMethods.add(member);
}
}
}
FieldBinding[] fields = binding.fields();
for (int i=0, len=fields.length; i < len; i++) {
FieldBinding f = fields[i];
declaredFields.add(factory.makeResolvedMember(f));
}
this.declaredPointcuts = (ResolvedPointcutDefinition[])
declaredPointcuts.toArray(new ResolvedPointcutDefinition[declaredPointcuts.size()]);
this.declaredMethods = (ResolvedMember[])
declaredMethods.toArray(new ResolvedMember[declaredMethods.size()]);
this.declaredFields = (ResolvedMember[])
declaredFields.toArray(new ResolvedMember[declaredFields.size()]);
}
private ResolvedPointcutDefinition makeResolvedPointcutDefinition(AbstractMethodDeclaration md) {
if (md.binding==null) return null; // there is another error that has caused this... pr138143
ResolvedPointcutDefinition resolvedPointcutDeclaration = new ResolvedPointcutDefinition(
factory.fromBinding(md.binding.declaringClass),
md.modifiers,
new String(md.selector),
factory.fromBindings(md.binding.parameters),
null); //??? might want to use null
resolvedPointcutDeclaration.setPosition(md.sourceStart, md.sourceEnd);
resolvedPointcutDeclaration.setSourceContext(new EclipseSourceContext(md.compilationResult));
return resolvedPointcutDeclaration;
}
/**
* This method may not return all fields, for example it may
* not include the ajc$initFailureCause or ajc$perSingletonInstance
* fields - see bug 129613
*/
public ResolvedMember[] getDeclaredFields() {
if (declaredFields == null) fillDeclaredMembers();
return declaredFields;
}
/**
* This method may not return all methods, for example it may
* not include clinit, aspectOf, hasAspect or ajc$postClinit
* methods - see bug 129613
*/
public ResolvedMember[] getDeclaredMethods() {
if (declaredMethods == null) fillDeclaredMembers();
return declaredMethods;
}
public ResolvedMember[] getDeclaredPointcuts() {
if (declaredPointcuts == null) fillDeclaredMembers();
return declaredPointcuts;
}
public int getModifiers() {
// only return the real Java modifiers, not the extra eclipse ones
return binding.modifiers & CompilerModifiers.AccJustFlag;
}
public String toString() {
return "EclipseSourceType(" + new String(binding.sourceName()) + ")";
}
//XXX make sure this is applied to classes and interfaces
public void checkPointcutDeclarations() {
ResolvedMember[] pointcuts = getDeclaredPointcuts();
boolean sawError = false;
for (int i=0, len=pointcuts.length; i < len; i++) {
if (pointcuts[i].isAbstract()) {
if (!this.isAspect()) {
eclipseWorld().showMessage(IMessage.ERROR,
"abstract pointcut only allowed in aspect" + pointcuts[i].getName(),
pointcuts[i].getSourceLocation(), null);
sawError = true;
} else if (!binding.isAbstract()) {
eclipseWorld().showMessage(IMessage.ERROR,
"abstract pointcut in concrete aspect" + pointcuts[i],
pointcuts[i].getSourceLocation(), null);
sawError = true;
}
}
for (int j=i+1; j < len; j++) {
if (pointcuts[i].getName().equals(pointcuts[j].getName())) {
eclipseWorld().showMessage(IMessage.ERROR,
"duplicate pointcut name: " + pointcuts[j].getName(),
pointcuts[i].getSourceLocation(), pointcuts[j].getSourceLocation());
sawError = true;
}
}
}
//now check all inherited pointcuts to be sure that they're handled reasonably
if (sawError || !isAspect()) return;
// find all pointcuts that override ones from super and check override is legal
// i.e. same signatures and greater or equal visibility
// find all inherited abstract pointcuts and make sure they're concretized if I'm concrete
// find all inherited pointcuts and make sure they don't conflict
getResolvedTypeX().getExposedPointcuts(); //??? this is an odd construction
}
//???
// public CrosscuttingMembers collectCrosscuttingMembers() {
// return crosscuttingMembers;
// }
// public ISourceLocation getSourceLocation() {
// TypeDeclaration dec = binding.scope.referenceContext;
// return new EclipseSourceLocation(dec.compilationResult, dec.sourceStart, dec.sourceEnd);
// }
public boolean isInterface() {
return binding.isInterface();
}
// XXXAJ5: Should be constants in the eclipse compiler somewhere, once it supports 1.5
public final static short ACC_ANNOTATION = 0x2000;
public final static short ACC_ENUM = 0x4000;
public boolean isEnum() {
return (binding.getAccessFlags() & ACC_ENUM)!=0;
}
public boolean isAnnotation() {
return (binding.getAccessFlags() & ACC_ANNOTATION)!=0;
}
public void addAnnotation(AnnotationX annotationX) {
// XXX Big hole here - annotationX holds a BCEL annotation but
// we need an Eclipse one here, we haven't written the conversion utils
// yet. Not sure if this method will be called in practice...
throw new RuntimeException("EclipseSourceType.addAnnotation() not implemented");
}
public boolean isAnnotationWithRuntimeRetention() {
if (!isAnnotation()) {
return false;
} else {
return (binding.getAnnotationTagBits() & TagBits.AnnotationRetentionMASK) == TagBits.AnnotationRuntimeRetention;
}
}
public String getRetentionPolicy() {
if (isAnnotation()) {
if ((binding.getAnnotationTagBits() & TagBits.AnnotationRetentionMASK) == TagBits.AnnotationRuntimeRetention) return "RUNTIME";
if ((binding.getAnnotationTagBits() & TagBits.AnnotationRetentionMASK) == TagBits.AnnotationSourceRetention) return "SOURCE";
if ((binding.getAnnotationTagBits() & TagBits.AnnotationRetentionMASK) == TagBits.AnnotationClassRetention) return "CLASS";
}
return null;
}
public boolean canAnnotationTargetType() {
if (isAnnotation()) {
return ((binding.getAnnotationTagBits() & TagBits.AnnotationForType) != 0 );
}
return false;
}
public AnnotationTargetKind[] getAnnotationTargetKinds() {
if (discoveredAnnotationTargetKinds) return annotationTargetKinds;
discoveredAnnotationTargetKinds = true;
annotationTargetKinds = null; // null means we have no idea or the @Target annotation hasn't been used
// if (isAnnotation()) {
// Annotation[] annotationsOnThisType = declaration.annotations;
// if (annotationsOnThisType != null) {
// for (int i = 0; i < annotationsOnThisType.length; i++) {
// Annotation a = annotationsOnThisType[i];
// if (a.resolvedType != null) {
// String packageName = new String(a.resolvedType.qualifiedPackageName()).concat(".");
// String sourceName = new String(a.resolvedType.qualifiedSourceName());
// if ((packageName + sourceName).equals(UnresolvedType.AT_TARGET.getName())) {
// MemberValuePair[] pairs = a.memberValuePairs();
// for (int j = 0; j < pairs.length; j++) {
// MemberValuePair pair = pairs[j];
// targetKind = pair.value.toString();
// return targetKind;
// }
// }
// }
// }
// }
// }
// return targetKind;
if (isAnnotation()) {
List targetKinds = new ArrayList();
if ((binding.getAnnotationTagBits() & TagBits.AnnotationForAnnotationType) != 0) targetKinds.add(AnnotationTargetKind.ANNOTATION_TYPE);
if ((binding.getAnnotationTagBits() & TagBits.AnnotationForConstructor) != 0) targetKinds.add(AnnotationTargetKind.CONSTRUCTOR);
if ((binding.getAnnotationTagBits() & TagBits.AnnotationForField) != 0) targetKinds.add(AnnotationTargetKind.FIELD);
if ((binding.getAnnotationTagBits() & TagBits.AnnotationForLocalVariable) != 0) targetKinds.add(AnnotationTargetKind.LOCAL_VARIABLE);
if ((binding.getAnnotationTagBits() & TagBits.AnnotationForMethod) != 0) targetKinds.add(AnnotationTargetKind.METHOD);
if ((binding.getAnnotationTagBits() & TagBits.AnnotationForPackage) != 0) targetKinds.add(AnnotationTargetKind.PACKAGE);
if ((binding.getAnnotationTagBits() & TagBits.AnnotationForParameter) != 0) targetKinds.add(AnnotationTargetKind.PARAMETER);
if ((binding.getAnnotationTagBits() & TagBits.AnnotationForType) != 0) targetKinds.add(AnnotationTargetKind.TYPE);
if (!targetKinds.isEmpty()) {
annotationTargetKinds = new AnnotationTargetKind[targetKinds.size()];
return (AnnotationTargetKind[]) targetKinds.toArray(annotationTargetKinds);
}
}
return annotationTargetKinds;
}
public boolean hasAnnotation(UnresolvedType ofType) {
// Make sure they are resolved
if (!annotationsResolved) {
TypeDeclaration.resolveAnnotations(declaration.staticInitializerScope, declaration.annotations, binding);
annotationsResolved = true;
}
Annotation[] as = declaration.annotations;
if (as == null) return false;
for (int i = 0; i < as.length; i++) {
Annotation annotation = as[i];
if (annotation.resolvedType == null) {
// Something has gone wrong - probably we have a 1.4 rt.jar around
// which will result in a separate error message.
return false;
}
String tname = CharOperation.charToString(annotation.resolvedType.constantPoolName());
if (UnresolvedType.forName(tname).equals(ofType)) {
return true;
}
}
return false;
}
/**
* WARNING: This method does not have a complete implementation.
*
* The aim is that it converts Eclipse annotation objects to the AspectJ form of
* annotations (the type AnnotationAJ). The AnnotationX objects returned are wrappers
* over either a Bcel annotation type or the AspectJ AnnotationAJ type.
* The minimal implementation provided here is for processing the RetentionPolicy and
* Target annotation types - these are the only ones which the weaver will attempt to
* process from an EclipseSourceType.
*
* More notes:
* The pipeline has required us to implement this. With the pipeline we can be weaving
* a type and asking questions of annotations before they have been turned into Bcel
* objects - ie. when they are still in EclipseSourceType form. Without the pipeline we
* would have converted everything to Bcel objects before proceeding with weaving.
* Because the pipeline won't start weaving until all aspects have been compiled and
* the fact that no AspectJ constructs match on the values within annotations, this code
* only needs to deal with converting system annotations that the weaver needs to process
* (RetentionPolicy, Target).
*/
public AnnotationX[] getAnnotations() {
if (annotations!=null) return annotations; // only do this once
getAnnotationTypes(); // forces resolution and sets resolvedAnnotations
Annotation[] as = declaration.annotations;
if (as==null || as.length==0) {
annotations = NO_ANNOTATIONS;
} else {
annotations = new AnnotationX[as.length];
for (int i = 0; i < as.length; i++) {
annotations[i]=convertEclipseAnnotation(as[i],factory.getWorld());
}
}
return annotations;
}
/**
* Convert one eclipse annotation into an AnnotationX object containing an AnnotationAJ object.
*
* This code and the helper methods used by it will go *BANG* if they encounter anything
* not currently supported - this is safer than limping along with a malformed annotation. When
* the *BANG* is encountered the bug reporter should indicate the kind of annotation they
* were working with and this code can be enhanced to support it.
*/
public AnnotationX convertEclipseAnnotation(Annotation eclipseAnnotation,World w) {
// TODO if it is sourcevisible, we shouldn't let it through!!!!!!!!! testcase!
ResolvedType annotationType = factory.fromTypeBindingToRTX(eclipseAnnotation.type.resolvedType);
long bs = (eclipseAnnotation.bits & TagBits.AnnotationRetentionMASK);
boolean isRuntimeVisible = (eclipseAnnotation.bits & TagBits.AnnotationRetentionMASK) == TagBits.AnnotationRuntimeRetention;
AnnotationAJ annotationAJ = new AnnotationAJ(annotationType.getSignature(),isRuntimeVisible);
generateAnnotation(eclipseAnnotation,annotationAJ);
return new AnnotationX(annotationAJ,w);
}
static class MissingImplementationException extends RuntimeException {
MissingImplementationException(String reason) {
super(reason);
}
}
private void generateAnnotation(Annotation annotation,AnnotationAJ annotationAJ) {
if (annotation instanceof NormalAnnotation) {
NormalAnnotation normalAnnotation = (NormalAnnotation) annotation;
MemberValuePair[] memberValuePairs = normalAnnotation.memberValuePairs;
if (memberValuePairs != null) {
int memberValuePairsLength = memberValuePairs.length;
for (int i = 0; i < memberValuePairsLength; i++) {
MemberValuePair memberValuePair = memberValuePairs[i];
MethodBinding methodBinding = memberValuePair.binding;
if (methodBinding == null) {
// is this just a marker annotation?
throw new MissingImplementationException(
"Please raise an AspectJ bug. AspectJ does not know how to convert this annotation ["+annotation+"]");
} else {
AnnotationValue av = generateElementValue(memberValuePair.value, methodBinding.returnType);
AnnotationNameValuePair anvp = new AnnotationNameValuePair(new String(memberValuePair.name),av);
annotationAJ.addNameValuePair(anvp);
}
}
} else {
throw new MissingImplementationException(
"Please raise an AspectJ bug. AspectJ does not know how to convert this annotation ["+annotation+"]");
}
} else if (annotation instanceof SingleMemberAnnotation) {
// this is a single member annotation (one member value)
SingleMemberAnnotation singleMemberAnnotation = (SingleMemberAnnotation) annotation;
MethodBinding methodBinding = singleMemberAnnotation.memberValuePairs()[0].binding;
if (methodBinding == null) {
throw new MissingImplementationException(
"Please raise an AspectJ bug. AspectJ does not know how to convert this annotation ["+annotation+"]");
} else {
AnnotationValue av = generateElementValue(singleMemberAnnotation.memberValue, methodBinding.returnType);
annotationAJ.addNameValuePair(
new AnnotationNameValuePair(new String(singleMemberAnnotation.memberValuePairs()[0].name),av));
}
} else {
// this is a marker annotation (no member value pairs)
throw new MissingImplementationException(
"Please raise an AspectJ bug. AspectJ does not know how to convert this annotation ["+annotation+"]");
}
}
private AnnotationValue generateElementValue(Expression defaultValue,TypeBinding memberValuePairReturnType) {
Constant constant = defaultValue.constant;
TypeBinding defaultValueBinding = defaultValue.resolvedType;
if (defaultValueBinding == null) {
throw new MissingImplementationException(
"Please raise an AspectJ bug. AspectJ does not know how to convert this annotation value ["+defaultValue+"]");
} else {
if (memberValuePairReturnType.isArrayType() && !defaultValueBinding.isArrayType()) {
if (constant != null && constant != Constant.NotAConstant) {
throw new MissingImplementationException(
"Please raise an AspectJ bug. AspectJ does not know how to convert this annotation value ["+defaultValue+"]");
// generateElementValue(attributeOffset, defaultValue, constant, memberValuePairReturnType.leafComponentType());
} else {
AnnotationValue av = generateElementValueForNonConstantExpression(defaultValue, defaultValueBinding);
return new ArrayAnnotationValue(new AnnotationValue[]{av});
}
} else {
if (constant != null && constant != Constant.NotAConstant) {
throw new MissingImplementationException(
"Please raise an AspectJ bug. AspectJ does not know how to convert this annotation value ["+defaultValue+"]");
// generateElementValue(attributeOffset, defaultValue, constant, memberValuePairReturnType.leafComponentType());
} else {
AnnotationValue av = generateElementValueForNonConstantExpression(defaultValue, defaultValueBinding);
return av;
}
}
}
}
private AnnotationValue generateElementValueForNonConstantExpression(Expression defaultValue, TypeBinding defaultValueBinding) {
if (defaultValueBinding != null) {
if (defaultValueBinding.isEnum()) {
FieldBinding fieldBinding = null;
if (defaultValue instanceof QualifiedNameReference) {
QualifiedNameReference nameReference = (QualifiedNameReference) defaultValue;
fieldBinding = (FieldBinding) nameReference.binding;
} else if (defaultValue instanceof SingleNameReference) {
SingleNameReference nameReference = (SingleNameReference) defaultValue;
fieldBinding = (FieldBinding) nameReference.binding;
} else {
throw new MissingImplementationException(
"Please raise an AspectJ bug. AspectJ does not know how to convert this annotation value ["+defaultValue+"]");
}
if (fieldBinding != null) {
String sig = new String(fieldBinding.type.signature());
AnnotationValue enumValue = new EnumAnnotationValue(sig,new String(fieldBinding.name));
return enumValue;
}
throw new MissingImplementationException(
"Please raise an AspectJ bug. AspectJ does not know how to convert this annotation value ["+defaultValue+"]");
} else if (defaultValueBinding.isAnnotationType()) {
throw new MissingImplementationException(
"Please raise an AspectJ bug. AspectJ does not know how to convert this annotation value ["+defaultValue+"]");
// contents[contentsOffset++] = (byte) '@';
// generateAnnotation((Annotation) defaultValue, attributeOffset);
} else if (defaultValueBinding.isArrayType()) {
// array type
if (defaultValue instanceof ArrayInitializer) {
ArrayInitializer arrayInitializer = (ArrayInitializer) defaultValue;
int arrayLength = arrayInitializer.expressions != null ? arrayInitializer.expressions.length : 0;
AnnotationValue[] values = new AnnotationValue[arrayLength];
for (int i = 0; i < arrayLength; i++) {
values[i] = generateElementValue(arrayInitializer.expressions[i], defaultValueBinding.leafComponentType());//, attributeOffset);
}
ArrayAnnotationValue aav = new ArrayAnnotationValue(values);
return aav;
} else {
throw new MissingImplementationException(
"Please raise an AspectJ bug. AspectJ does not know how to convert this annotation value ["+defaultValue+"]");
}
} else {
// class type
throw new MissingImplementationException(
"Please raise an AspectJ bug. AspectJ does not know how to convert this annotation value ["+defaultValue+"]");
// if (contentsOffset + 3 >= this.contents.length) {
// resizeContents(3);
// }
// contents[contentsOffset++] = (byte) 'c';
// if (defaultValue instanceof ClassLiteralAccess) {
// ClassLiteralAccess classLiteralAccess = (ClassLiteralAccess) defaultValue;
// final int classInfoIndex = constantPool.literalIndex(classLiteralAccess.targetType.signature());
// contents[contentsOffset++] = (byte) (classInfoIndex >> 8);
// contents[contentsOffset++] = (byte) classInfoIndex;
// } else {
// contentsOffset = attributeOffset;
// }
}
} else {
throw new MissingImplementationException(
"Please raise an AspectJ bug. AspectJ does not know how to convert this annotation value ["+defaultValue+"]");
// contentsOffset = attributeOffset;
}
}
// ---------------------------------
public ResolvedType[] getAnnotationTypes() {
if (resolvedAnnotations!=null) return resolvedAnnotations;
// Make sure they are resolved
if (!annotationsResolved) {
TypeDeclaration.resolveAnnotations(declaration.staticInitializerScope, declaration.annotations, binding);
annotationsResolved = true;
}
if (declaration.annotations == null) {
resolvedAnnotations = NO_ANNOTATION_TYPES;//new ResolvedType[0];
} else {
resolvedAnnotations = new ResolvedType[declaration.annotations.length];
Annotation[] as = declaration.annotations;
for (int i = 0; i < as.length; i++) {
Annotation annotation = as[i];
resolvedAnnotations[i] =factory.fromTypeBindingToRTX(annotation.type.resolvedType);
}
}
return resolvedAnnotations;
}
public PerClause getPerClause() {
//should probably be: ((AspectDeclaration)declaration).perClause;
// but we don't need this level of detail, and working with real per clauses
// at this stage of compilation is not worth the trouble
if (!isAnnotationStyleAspect()) {
if(declaration instanceof AspectDeclaration) {
PerClause pc = ((AspectDeclaration)declaration).perClause;
if (pc != null) return pc;
}
return new PerSingleton();
} else {
// for @Aspect, we do need the real kind though we don't need the real perClause
// at least try to get the right perclause
PerClause pc = null;
if (declaration instanceof AspectDeclaration)
pc = ((AspectDeclaration)declaration).perClause;
if (pc==null) {
PerClause.Kind kind = getPerClauseForTypeDeclaration(declaration);
//returning a perFromSuper is enough to get the correct kind.. (that's really a hack - AV)
return new PerFromSuper(kind);
}
return pc;
}
}
PerClause.Kind getPerClauseForTypeDeclaration(TypeDeclaration typeDeclaration) {
Annotation[] annotations = typeDeclaration.annotations;
for (int i = 0; i < annotations.length; i++) {
Annotation annotation = annotations[i];
if (CharOperation.equals(aspectSig, annotation.resolvedType.signature())) {
// found @Aspect(...)
if (annotation.memberValuePairs() == null || annotation.memberValuePairs().length == 0) {
// it is an @Aspect or @Aspect()
// needs to use PerFromSuper if declaration extends a super aspect
PerClause.Kind kind = lookupPerClauseKind(typeDeclaration.binding.superclass);
// if no super aspect, we have a @Aspect() means singleton
if (kind == null) {
return PerClause.SINGLETON;
} else {
return kind;
}
} else if (annotation instanceof SingleMemberAnnotation) {
// it is an @Aspect(...something...)
SingleMemberAnnotation theAnnotation = (SingleMemberAnnotation)annotation;
String clause = new String(((StringLiteral)theAnnotation.memberValue).source());//TODO cast safe ?
return determinePerClause(typeDeclaration, clause);
} else if (annotation instanceof NormalAnnotation) { // this kind if it was added by the visitor !
// it is an @Aspect(...something...)
NormalAnnotation theAnnotation = (NormalAnnotation)annotation;
if (theAnnotation.memberValuePairs==null || theAnnotation.memberValuePairs.length<1) return PerClause.SINGLETON;
String clause = new String(((StringLiteral)theAnnotation.memberValuePairs[0].value).source());//TODO cast safe ?
return determinePerClause(typeDeclaration, clause);
} else {
eclipseWorld().showMessage(IMessage.ABORT,
"@Aspect annotation is expected to be SingleMemberAnnotation with 'String value()' as unique element",
new EclipseSourceLocation(typeDeclaration.compilationResult, typeDeclaration.sourceStart, typeDeclaration.sourceEnd), null);
return PerClause.SINGLETON;//fallback strategy just to avoid NPE
}
}
}
return null;//no @Aspect annotation at all (not as aspect)
}
private PerClause.Kind determinePerClause(TypeDeclaration typeDeclaration, String clause) {
if (clause.startsWith("perthis(")) {
return PerClause.PEROBJECT;
} else if (clause.startsWith("pertarget(")) {
return PerClause.PEROBJECT;
} else if (clause.startsWith("percflow(")) {
return PerClause.PERCFLOW;
} else if (clause.startsWith("percflowbelow(")) {
return PerClause.PERCFLOW;
} else if (clause.startsWith("pertypewithin(")) {
return PerClause.PERTYPEWITHIN;
} else if (clause.startsWith("issingleton(")) {
return PerClause.SINGLETON;
} else {
eclipseWorld().showMessage(IMessage.ABORT,
"cannot determine perClause '" + clause + "'",
new EclipseSourceLocation(typeDeclaration.compilationResult, typeDeclaration.sourceStart, typeDeclaration.sourceEnd), null);
return PerClause.SINGLETON;//fallback strategy just to avoid NPE
}
}
// adapted from AspectDeclaration
private PerClause.Kind lookupPerClauseKind(ReferenceBinding binding) {
final PerClause.Kind kind;
if (binding instanceof BinaryTypeBinding) {
ResolvedType superTypeX = factory.fromEclipse(binding);
PerClause perClause = superTypeX.getPerClause();
// clause is null for non aspect classes since coming from BCEL attributes
if (perClause != null) {
kind = superTypeX.getPerClause().getKind();
} else {
kind = null;
}
} else if (binding instanceof SourceTypeBinding ) {
SourceTypeBinding sourceSc = (SourceTypeBinding)binding;
if (sourceSc.scope.referenceContext instanceof AspectDeclaration) {
//code style
kind = ((AspectDeclaration)sourceSc.scope.referenceContext).perClause.getKind();
} else if (sourceSc.scope.referenceContext instanceof TypeDeclaration) {
// if @Aspect: perFromSuper, else if @Aspect(..) get from anno value, else null
kind = getPerClauseForTypeDeclaration((TypeDeclaration)(sourceSc.scope.referenceContext));
} else {
//XXX should not happen
kind = null;
}
} else {
//XXX need to handle this too
kind = null;
}
return kind;
}
public Collection getDeclares() {
return declares;
}
public Collection getPrivilegedAccesses() {
return Collections.EMPTY_LIST;
}
public Collection getTypeMungers() {
return typeMungers;
}
public boolean doesNotExposeShadowMungers() {
return true;
}
public String getDeclaredGenericSignature() {
return CharOperation.charToString(binding.genericSignature());
}
public boolean isGeneric() {
return binding.isGenericType();
}
public TypeVariable[] getTypeVariables() {
if (declaration.typeParameters == null) return new TypeVariable[0];
TypeVariable[] typeVariables = new TypeVariable[declaration.typeParameters.length];
for (int i = 0; i < typeVariables.length; i++) {
typeVariables[i] = typeParameter2TypeVariable(declaration.typeParameters[i]);
}
return typeVariables;
}
private TypeVariable typeParameter2TypeVariable(TypeParameter aTypeParameter) {
String name = new String(aTypeParameter.name);
ReferenceBinding superclassBinding = aTypeParameter.binding.superclass;
UnresolvedType superclass = UnresolvedType.forSignature(new String(superclassBinding.signature()));
UnresolvedType[] superinterfaces = null;
ReferenceBinding[] superInterfaceBindings = aTypeParameter.binding.superInterfaces;
if (superInterfaceBindings != null) {
superinterfaces = new UnresolvedType[superInterfaceBindings.length];
for (int i = 0; i < superInterfaceBindings.length; i++) {
superinterfaces[i] = UnresolvedType.forSignature(new String(superInterfaceBindings[i].signature()));
}
}
// XXX what about lower binding?
TypeVariable tv = new TypeVariable(name,superclass,superinterfaces);
tv.setDeclaringElement(factory.fromBinding(aTypeParameter.binding.declaringElement));
tv.setRank(aTypeParameter.binding.rank);
return tv;
}
public void ensureDelegateConsistent() {
// do nothing, currently these can't become inconsistent (phew)
}
}
|
158,412 |
Bug 158412 @Pointcut in declare error results in NPE
|
I am trying to use an @AspectJ @Pointcut in a "normal" AspectJ declare error expression. That results in the following exception. java.lang.NullPointerException at org.aspectj.weaver.patterns.ReferencePointcut.concretize1(ReferencePointcut.java:361) at org.aspectj.weaver.patterns.Pointcut.concretize(Pointcut.java:233) at org.aspectj.weaver.patterns.NotPointcut.concretize1(NotPointcut.java:100) at org.aspectj.weaver.patterns.Pointcut.concretize(Pointcut.java:233) at org.aspectj.weaver.patterns.AndPointcut.concretize1(AndPointcut.java:97) at org.aspectj.weaver.patterns.Pointcut.concretize(Pointcut.java:233) at org.aspectj.weaver.patterns.Pointcut.concretize(Pointcut.java:220) at org.aspectj.weaver.Checker.concretize(Checker.java:45) at org.aspectj.weaver.CrosscuttingMembers.addShadowMunger(CrosscuttingMembers.java:91) at org.aspectj.weaver.CrosscuttingMembers.addDeclare(CrosscuttingMembers.java:122) at org.aspectj.weaver.CrosscuttingMembers.addDeclares(CrosscuttingMembers.java:113) at org.aspectj.weaver.CrosscuttingMembersSet.addAdviceLikeDeclares(CrosscuttingMembersSet.java:117) at org.aspectj.ajdt.internal.compiler.lookup.AjLookupEnvironment.addAdviceLikeDeclares(AjLookupEnvironment.java:382) at org.aspectj.ajdt.internal.compiler.lookup.AjLookupEnvironment.completeTypeBindings(AjLookupEnvironment.java:245) 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.doBuild(AjBuildManager.java:199) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.incrementalBuild(AjBuildManager.java:170) at org.aspectj.ajde.internal.CompilerAdapter.compile(CompilerAdapter.java:117) at org.aspectj.ajde.internal.AspectJBuildManager$CompilerThread.run(AspectJBuildManager.java:191) NullPointerException thrown: null
|
resolved fixed
|
e56a69a
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-09-25T13:51:40Z | 2006-09-23T08:26:40Z |
tests/bugs153/pr158412/dao/Foo.java
| |
158,412 |
Bug 158412 @Pointcut in declare error results in NPE
|
I am trying to use an @AspectJ @Pointcut in a "normal" AspectJ declare error expression. That results in the following exception. java.lang.NullPointerException at org.aspectj.weaver.patterns.ReferencePointcut.concretize1(ReferencePointcut.java:361) at org.aspectj.weaver.patterns.Pointcut.concretize(Pointcut.java:233) at org.aspectj.weaver.patterns.NotPointcut.concretize1(NotPointcut.java:100) at org.aspectj.weaver.patterns.Pointcut.concretize(Pointcut.java:233) at org.aspectj.weaver.patterns.AndPointcut.concretize1(AndPointcut.java:97) at org.aspectj.weaver.patterns.Pointcut.concretize(Pointcut.java:233) at org.aspectj.weaver.patterns.Pointcut.concretize(Pointcut.java:220) at org.aspectj.weaver.Checker.concretize(Checker.java:45) at org.aspectj.weaver.CrosscuttingMembers.addShadowMunger(CrosscuttingMembers.java:91) at org.aspectj.weaver.CrosscuttingMembers.addDeclare(CrosscuttingMembers.java:122) at org.aspectj.weaver.CrosscuttingMembers.addDeclares(CrosscuttingMembers.java:113) at org.aspectj.weaver.CrosscuttingMembersSet.addAdviceLikeDeclares(CrosscuttingMembersSet.java:117) at org.aspectj.ajdt.internal.compiler.lookup.AjLookupEnvironment.addAdviceLikeDeclares(AjLookupEnvironment.java:382) at org.aspectj.ajdt.internal.compiler.lookup.AjLookupEnvironment.completeTypeBindings(AjLookupEnvironment.java:245) 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.doBuild(AjBuildManager.java:199) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.incrementalBuild(AjBuildManager.java:170) at org.aspectj.ajde.internal.CompilerAdapter.compile(CompilerAdapter.java:117) at org.aspectj.ajde.internal.AspectJBuildManager$CompilerThread.run(AspectJBuildManager.java:191) NullPointerException thrown: null
|
resolved fixed
|
e56a69a
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-09-25T13:51:40Z | 2006-09-23T08:26:40Z |
tests/bugs153/pr158412/layering/SystemArchitektur.java
| |
158,412 |
Bug 158412 @Pointcut in declare error results in NPE
|
I am trying to use an @AspectJ @Pointcut in a "normal" AspectJ declare error expression. That results in the following exception. java.lang.NullPointerException at org.aspectj.weaver.patterns.ReferencePointcut.concretize1(ReferencePointcut.java:361) at org.aspectj.weaver.patterns.Pointcut.concretize(Pointcut.java:233) at org.aspectj.weaver.patterns.NotPointcut.concretize1(NotPointcut.java:100) at org.aspectj.weaver.patterns.Pointcut.concretize(Pointcut.java:233) at org.aspectj.weaver.patterns.AndPointcut.concretize1(AndPointcut.java:97) at org.aspectj.weaver.patterns.Pointcut.concretize(Pointcut.java:233) at org.aspectj.weaver.patterns.Pointcut.concretize(Pointcut.java:220) at org.aspectj.weaver.Checker.concretize(Checker.java:45) at org.aspectj.weaver.CrosscuttingMembers.addShadowMunger(CrosscuttingMembers.java:91) at org.aspectj.weaver.CrosscuttingMembers.addDeclare(CrosscuttingMembers.java:122) at org.aspectj.weaver.CrosscuttingMembers.addDeclares(CrosscuttingMembers.java:113) at org.aspectj.weaver.CrosscuttingMembersSet.addAdviceLikeDeclares(CrosscuttingMembersSet.java:117) at org.aspectj.ajdt.internal.compiler.lookup.AjLookupEnvironment.addAdviceLikeDeclares(AjLookupEnvironment.java:382) at org.aspectj.ajdt.internal.compiler.lookup.AjLookupEnvironment.completeTypeBindings(AjLookupEnvironment.java:245) 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.doBuild(AjBuildManager.java:199) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.incrementalBuild(AjBuildManager.java:170) at org.aspectj.ajde.internal.CompilerAdapter.compile(CompilerAdapter.java:117) at org.aspectj.ajde.internal.AspectJBuildManager$CompilerThread.run(AspectJBuildManager.java:191) NullPointerException thrown: null
|
resolved fixed
|
e56a69a
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-09-25T13:51:40Z | 2006-09-23T08:26:40Z |
tests/src/org/aspectj/systemtest/ajc153/Ajc153Tests.java
|
/*******************************************************************************
* Copyright (c) 2006 IBM
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Andy Clement - initial API and implementation
*******************************************************************************/
package org.aspectj.systemtest.ajc153;
import java.io.File;
import junit.framework.Test;
import org.aspectj.testing.Utils;
import org.aspectj.testing.XMLBasedAjcTestCase;
import org.aspectj.weaver.bcel.Utility;
public class Ajc153Tests extends org.aspectj.testing.XMLBasedAjcTestCase {
//public void testGenericsProblem_pr151978() { runTest("generics problem");}
//public void testMissingLineNumbersInStacktraceBefore_pr145442() { runTest("missing line numbers in stacktrace before");}
//public void testMissingLineNumbersInStacktraceAfter_pr145442() { runTest("missing line numbers in stacktrace after");}
//public void testMissingLineNumbersInStacktraceAround_pr145442() { runTest("missing line numbers in stacktrace around");}
// public void testArgnamesAndJavac_pr148381() { runTest("argNames and javac");}
// public void testCFlowXMLAspectLTW_pr149096() { runTest("cflow xml concrete aspect"); }
// public void testAmbiguousBinding_pr121805() { runTest("ambiguous binding");}
// public void testNoIllegalStateExceptionWithGenericInnerAspect_pr156058() { runTest("no IllegalStateException with generic inner aspect"); }
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 testVisibilityProblem_pr149071() { runTest("visibility problem");}
// public void testAdviceNotWovenAspectPath_pr147841() { runTest("advice not woven on aspectpath");}
public void testGenericSignatures_pr148409() { runTest("generic signature problem"); }
// public void testBrokenIfArgsCflowAtAj_pr145018() { runTest("ataj crashing with cflow, if and args");}
public void testCantFindType_pr149322_01() {runTest("can't find type on interface call 1");}
public void testCantFindType_pr149322_02() {runTest("can't find type on interface call 2");}
public void testCantFindType_pr149322_03() {runTest("can't find type on interface call 3");}
public void 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 static Test suite() {
return XMLBasedAjcTestCase.loadSuite(Ajc153Tests.class);
}
protected File getSpecFile() {
return new File("../tests/src/org/aspectj/systemtest/ajc153/ajc153.xml");
}
}
|
148,908 |
Bug 148908 incorrect source signature for field ipe with qualified allocation expression
| null |
resolved fixed
|
fc39df1
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-09-26T09:26:33Z | 2006-06-27T23:13:20Z |
org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/core/builder/AsmHierarchyBuilder.java
|
/* *******************************************************************
* Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC).
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Eclipse Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* PARC initial implementation
* Mik Kersten revisions, added additional relationships
* Alexandre Vasseur support for @AJ style
* ******************************************************************/
package org.aspectj.ajdt.internal.core.builder;
import java.io.File;
import java.io.IOException;
import java.util.*;
import org.aspectj.ajdt.internal.compiler.ast.*;
import org.aspectj.ajdt.internal.compiler.lookup.AjLookupEnvironment;
import org.aspectj.ajdt.internal.compiler.lookup.EclipseFactory;
import org.aspectj.asm.*;
import org.aspectj.asm.internal.ProgramElement;
import org.aspectj.bridge.ISourceLocation;
import org.aspectj.bridge.SourceLocation;
import org.aspectj.org.eclipse.jdt.internal.compiler.ASTVisitor;
import org.aspectj.org.eclipse.jdt.internal.compiler.CompilationResult;
import org.aspectj.org.eclipse.jdt.internal.compiler.ast.*;
import org.aspectj.org.eclipse.jdt.internal.compiler.env.IGenericType;
import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.*;
import org.aspectj.org.eclipse.jdt.internal.compiler.problem.ProblemHandler;
import org.aspectj.util.LangUtil;
import org.aspectj.weaver.*;
import org.aspectj.weaver.patterns.*;
/**
* At each iteration of <CODE>processCompilationUnit</CODE> the declarations for a
* particular compilation unit are added to the hierarchy passed as a a parameter.
* <p>
* Clients who extend this class need to ensure that they do not override any of the existing
* behavior. If they do, the structure model will not be built properly and tools such as IDE
* structure views and ajdoc will fail.
* <p>
* <b>Note:</b> this class is not considered public API and the overridable
* methods are subject to change.
*
* @author Mik Kersten
*/
public class AsmHierarchyBuilder extends ASTVisitor {
protected AsmElementFormatter formatter = new AsmElementFormatter();
// pr148027 - stop generating uses pointcut/pointcut used by relationship
// until we do it in the same way as other relationships.
public static boolean shouldAddUsesPointcut = false;
/**
* Reset for every compilation unit.
*/
protected AjBuildConfig buildConfig;
/**
* Reset for every compilation unit.
*/
protected Stack stack;
/**
* Reset for every compilation unit.
*/
private CompilationResult currCompilationResult;
private String filename;
int[] lineseps;
/**
*
* @param cuDeclaration
* @param buildConfig
* @param structureModel hiearchy to add this unit's declarations to
*/
public void buildStructureForCompilationUnit(CompilationUnitDeclaration cuDeclaration, IHierarchy structureModel, AjBuildConfig buildConfig) {
currCompilationResult = cuDeclaration.compilationResult();
filename = new String(currCompilationResult.fileName);
lineseps = currCompilationResult.lineSeparatorPositions;
LangUtil.throwIaxIfNull(currCompilationResult, "result");
stack = new Stack();
this.buildConfig = buildConfig;
internalBuild(cuDeclaration, structureModel);
this.buildConfig = null; // clear reference since this structure is anchored in static
currCompilationResult=null;
stack.clear();
// throw new RuntimeException("not implemented");
}
private void internalBuild(CompilationUnitDeclaration unit, IHierarchy structureModel) {
LangUtil.throwIaxIfNull(structureModel, "structureModel");
// if (!currCompilationResult.equals(unit.compilationResult())) {
// throw new IllegalArgumentException("invalid unit: " + unit);
// }
// ---- summary
// add unit to package (or root if no package),
// first removing any duplicate (XXX? removes children if 3 classes in same file?)
// push the node on the stack
// and traverse
// -- create node to add
final File file = new File(new String(unit.getFileName()));
final IProgramElement cuNode;
{
// AMC - use the source start and end from the compilation unit decl
int startLine = getStartLine(unit);
int endLine = getEndLine(unit);
SourceLocation sourceLocation
= new SourceLocation(file, startLine, endLine);
sourceLocation.setOffset(unit.sourceStart);
cuNode = new ProgramElement(
new String(file.getName()),
IProgramElement.Kind.FILE_JAVA,
sourceLocation,
0,null,null);
}
cuNode.addChild(new ProgramElement(
"import declarations",
IProgramElement.Kind.IMPORT_REFERENCE,
null,0,null,null));
final IProgramElement addToNode = genAddToNode(unit, structureModel);
// -- remove duplicates before adding (XXX use them instead?)
if (addToNode!=null && addToNode.getChildren()!=null) {
for (ListIterator itt = addToNode.getChildren().listIterator(); itt.hasNext(); ) {
IProgramElement child = (IProgramElement)itt.next();
ISourceLocation childLoc = child.getSourceLocation();
if (null == childLoc) {
// XXX ok, packages have null source locations
// signal others?
} else if (childLoc.getSourceFile().equals(file)) {
itt.remove();
}
}
}
// -- add and traverse
addToNode.addChild(cuNode);
stack.push(cuNode);
unit.traverse(this, unit.scope);
// -- update file map (XXX do this before traversal?)
try {
structureModel.addToFileMap(file.getCanonicalPath(), cuNode);
} catch (IOException e) {
System.err.println("IOException " + e.getMessage()
+ " creating path for " + file );
// XXX signal IOException when canonicalizing file path
}
}
/**
* Get/create the node (package or root) to add to.
*/
private IProgramElement genAddToNode(
CompilationUnitDeclaration unit,
IHierarchy structureModel) {
final IProgramElement addToNode;
{
ImportReference currentPackage = unit.currentPackage;
if (null == currentPackage) {
addToNode = structureModel.getRoot();
} else {
String pkgName;
{
StringBuffer nameBuffer = new StringBuffer();
final char[][] importName = currentPackage.getImportName();
final int last = importName.length-1;
for (int i = 0; i < importName.length; i++) {
nameBuffer.append(new String(importName[i]));
if (i < last) {
nameBuffer.append('.');
}
}
pkgName = nameBuffer.toString();
}
IProgramElement pkgNode = null;
if (structureModel!=null && structureModel.getRoot()!=null && structureModel.getRoot().getChildren()!=null) {
for (Iterator it = structureModel.getRoot().getChildren().iterator();
it.hasNext(); ) {
IProgramElement currNode = (IProgramElement)it.next();
if (pkgName.equals(currNode.getName())) {
pkgNode = currNode;
break;
}
}
}
if (pkgNode == null) {
// note packages themselves have no source location
pkgNode = new ProgramElement(
pkgName,
IProgramElement.Kind.PACKAGE,
new ArrayList()
);
structureModel.getRoot().addChild(pkgNode);
}
addToNode = pkgNode;
}
}
return addToNode;
}
public boolean visit(TypeDeclaration typeDeclaration, CompilationUnitScope scope) {
String name = new String(typeDeclaration.name);
IProgramElement.Kind kind = IProgramElement.Kind.CLASS;
if (typeDeclaration instanceof AspectDeclaration) kind = IProgramElement.Kind.ASPECT;
else if (typeDeclaration.kind() == IGenericType.INTERFACE_DECL) kind = IProgramElement.Kind.INTERFACE;
else if (typeDeclaration.kind() == IGenericType.ENUM_DECL) kind = IProgramElement.Kind.ENUM;
else if (typeDeclaration.kind() == IGenericType.ANNOTATION_TYPE_DECL) kind = IProgramElement.Kind.ANNOTATION;
//@AJ support
if (typeDeclaration.annotations != null) {
for (int i = 0; i < typeDeclaration.annotations.length; i++) {
Annotation annotation = typeDeclaration.annotations[i];
if (Arrays.equals(annotation.type.getTypeBindingPublic(scope).signature(),
"Lorg/aspectj/lang/annotation/Aspect;".toCharArray())) {
kind = IProgramElement.Kind.ASPECT;
}
}
}
int typeModifiers = typeDeclaration.modifiers;
if (typeDeclaration instanceof AspectDeclaration) {
typeModifiers = ((AspectDeclaration)typeDeclaration).getDeclaredModifiers();
}
IProgramElement peNode = new ProgramElement(
name,
kind,
makeLocation(typeDeclaration),
typeModifiers, null,null);
peNode.setSourceSignature(genSourceSignature(typeDeclaration));
peNode.setFormalComment(generateJavadocComment(typeDeclaration));
((IProgramElement)stack.peek()).addChild(peNode);
stack.push(peNode);
return true;
}
public void endVisit(TypeDeclaration typeDeclaration, CompilationUnitScope scope) {
stack.pop();
}
// ??? share impl with visit(TypeDeclaration, ..) ?
public boolean visit(TypeDeclaration memberTypeDeclaration, ClassScope scope) {
String name = new String(memberTypeDeclaration.name);
IProgramElement.Kind kind = IProgramElement.Kind.CLASS;
if (memberTypeDeclaration instanceof AspectDeclaration) kind = IProgramElement.Kind.ASPECT;
else if (memberTypeDeclaration.kind() == IGenericType.INTERFACE_DECL) kind = IProgramElement.Kind.INTERFACE;
else if (memberTypeDeclaration.kind() == IGenericType.ENUM_DECL) kind = IProgramElement.Kind.ENUM;
else if (memberTypeDeclaration.kind() == IGenericType.ANNOTATION_TYPE_DECL) kind = IProgramElement.Kind.ANNOTATION;
//@AJ support
if (memberTypeDeclaration.annotations != null) {
for (int i = 0; i < memberTypeDeclaration.annotations.length; i++) {
Annotation annotation = memberTypeDeclaration.annotations[i];
if (Arrays.equals(annotation.type.getTypeBindingPublic(scope).signature(),
"Lorg/aspectj/lang/annotation/Aspect;".toCharArray())) {
kind = IProgramElement.Kind.ASPECT;
}
}
}
int typeModifiers = memberTypeDeclaration.modifiers;
if (memberTypeDeclaration instanceof AspectDeclaration) {
typeModifiers = ((AspectDeclaration)memberTypeDeclaration).getDeclaredModifiers();
}
IProgramElement peNode = new ProgramElement(
name,
kind,
makeLocation(memberTypeDeclaration),
typeModifiers,null,null);
peNode.setSourceSignature(genSourceSignature(memberTypeDeclaration));
peNode.setFormalComment(generateJavadocComment(memberTypeDeclaration));
((IProgramElement)stack.peek()).addChild(peNode);
stack.push(peNode);
return true;
}
public void endVisit(TypeDeclaration memberTypeDeclaration, ClassScope scope) {
stack.pop();
}
public boolean visit(TypeDeclaration memberTypeDeclaration, BlockScope scope) {
String fullName = "<undefined>";
if (memberTypeDeclaration.allocation != null
&& memberTypeDeclaration.allocation.type != null) {
// Create a name something like 'new Runnable() {..}'
fullName = "new "+memberTypeDeclaration.allocation.type.toString()+"() {..}";
} else if (memberTypeDeclaration.binding != null
&& memberTypeDeclaration.binding.constantPoolName() != null) {
// If we couldn't find a nice name like 'new Runnable() {..}' then use the number after the $
fullName = new String(memberTypeDeclaration.binding.constantPoolName());
int dollar = fullName.indexOf('$');
fullName = fullName.substring(dollar+1);
}
IProgramElement.Kind kind = IProgramElement.Kind.CLASS;
if (memberTypeDeclaration.kind() == IGenericType.INTERFACE_DECL) kind = IProgramElement.Kind.INTERFACE;
else if (memberTypeDeclaration.kind() == IGenericType.ENUM_DECL) kind = IProgramElement.Kind.ENUM;
else if (memberTypeDeclaration.kind() == IGenericType.ANNOTATION_TYPE_DECL) kind = IProgramElement.Kind.ANNOTATION;
//@AJ support
if (memberTypeDeclaration.annotations != null) {
for (int i = 0; i < memberTypeDeclaration.annotations.length; i++) {
Annotation annotation = memberTypeDeclaration.annotations[i];
if (Arrays.equals(annotation.type.getTypeBindingPublic(scope).signature(),
"Lorg/aspectj/lang/annotation/Aspect;".toCharArray())) {
kind = IProgramElement.Kind.ASPECT;
break;
}
}
}
IProgramElement peNode = new ProgramElement(
fullName,
kind,
makeLocation(memberTypeDeclaration),
memberTypeDeclaration.modifiers,null,null);
peNode.setSourceSignature(genSourceSignature(memberTypeDeclaration));
peNode.setFormalComment(generateJavadocComment(memberTypeDeclaration));
// if we're something like 'new Runnable(){..}' then set the
// bytecodeSignature to be the typename so we can match it later
// when creating the structure model
if (peNode.getBytecodeSignature() == null
&& memberTypeDeclaration.binding != null
&& memberTypeDeclaration.binding.constantPoolName() != null) {
StringTokenizer st = new StringTokenizer(
new String(memberTypeDeclaration.binding.constantPoolName()),"/");
while(st.hasMoreTokens()) {
String s = st.nextToken();
if (!st.hasMoreTokens()) {
peNode.setBytecodeSignature(s);
}
}
}
((IProgramElement)stack.peek()).addChild(peNode);
stack.push(peNode);
return true;
}
public void endVisit(TypeDeclaration memberTypeDeclaration, BlockScope scope) {
stack.pop();
}
private String genSourceSignature(TypeDeclaration typeDeclaration) {
StringBuffer output = new StringBuffer();
typeDeclaration.printHeader(0, output);
return output.toString();
}
private IProgramElement findEnclosingClass(Stack stack) {
for (int i = stack.size()-1; i >= 0; i--) {
IProgramElement pe = (IProgramElement)stack.get(i);
if (pe.getKind() == IProgramElement.Kind.CLASS) {
return pe;
}
}
return (IProgramElement)stack.peek();
}
public boolean visit(MethodDeclaration methodDeclaration, ClassScope scope) {
IProgramElement peNode = null;
// For intertype decls, use the modifiers from the original signature, not the generated method
if (methodDeclaration instanceof InterTypeDeclaration) {
InterTypeDeclaration itd = (InterTypeDeclaration) methodDeclaration;
ResolvedMember sig = itd.getSignature();
peNode = new ProgramElement(
null,
IProgramElement.Kind.ERROR,
makeLocation(methodDeclaration),
(sig!=null?sig.getModifiers():0),null,null);
} else {
peNode = new ProgramElement(
null,
IProgramElement.Kind.ERROR,
makeLocation(methodDeclaration),
methodDeclaration.modifiers,null,null);
}
formatter.genLabelAndKind(methodDeclaration, peNode); // will set the name
genBytecodeInfo(methodDeclaration, peNode);
List namedPointcuts = genNamedPointcuts(methodDeclaration);
if (shouldAddUsesPointcut) addUsesPointcutRelationsForNode(peNode, namedPointcuts, methodDeclaration);
if (methodDeclaration.returnType!=null) {
// if we don't make the distinction between ITD fields and other
// methods, then we loose the type, for example int, for the field
// and instead get "void".
if (peNode.getKind().equals(IProgramElement.Kind.INTER_TYPE_FIELD)) {
peNode.setCorrespondingType(methodDeclaration.returnType.toString());
} else {
if (methodDeclaration.returnType.resolvedType!=null)
peNode.setCorrespondingType(methodDeclaration.returnType.resolvedType.debugName());
else
peNode.setCorrespondingType(null);
}
} else {
peNode.setCorrespondingType(null);
}
peNode.setSourceSignature(genSourceSignature(methodDeclaration));
peNode.setFormalComment(generateJavadocComment(methodDeclaration));
// TODO: add return type test
if (peNode.getKind().equals(IProgramElement.Kind.METHOD)) {
if ((peNode.getName().charAt(0)=='m') &&
(peNode.toLabelString().equals("main(String[])")
|| peNode.toLabelString().equals("main(java.lang.String[])"))
&& peNode.getModifiers().contains(IProgramElement.Modifiers.STATIC)
&& peNode.getAccessibility().equals(IProgramElement.Accessibility.PUBLIC)) {
((IProgramElement)stack.peek()).setRunnable(true);
}
}
stack.push(peNode);
return true;
}
private void addUsesPointcutRelationsForNode(IProgramElement peNode, List namedPointcuts, MethodDeclaration declaration) {
for (Iterator it = namedPointcuts.iterator(); it.hasNext();) {
ReferencePointcut rp = (ReferencePointcut) it.next();
ResolvedMember member = getPointcutDeclaration(rp, declaration);
if (member != null) {
IRelationship foreward = AsmManager.getDefault().getRelationshipMap()
.get(peNode.getHandleIdentifier(),
IRelationship.Kind.USES_POINTCUT, "uses pointcut", false, true);
IProgramElement forwardIPE = AsmManager.getDefault().getHierarchy()
.findElementForSourceLine(member.getSourceLocation());
foreward.addTarget(AsmManager.getDefault().getHandleProvider()
.createHandleIdentifier(forwardIPE));
IRelationship back = AsmManager.getDefault().getRelationshipMap()
.get(AsmManager.getDefault().getHandleProvider()
.createHandleIdentifier(forwardIPE),
IRelationship.Kind.USES_POINTCUT, "pointcut used by", false, true);
back.addTarget(peNode.getHandleIdentifier());
}
}
}
private ResolvedMember getPointcutDeclaration(ReferencePointcut rp, MethodDeclaration declaration) {
EclipseFactory factory = ((AjLookupEnvironment)declaration.scope.environment()).factory;
World world = factory.getWorld();
UnresolvedType onType = rp.onType;
if (onType == null) {
if (declaration.binding != null) {
Member member = factory.makeResolvedMember(declaration.binding);
onType = member.getDeclaringType();
} else {
return null;
}
}
ResolvedMember[] members = onType.resolve(world).getDeclaredPointcuts();
if (members != null) {
for (int i = 0; i < members.length; i++) {
if (members[i].getName().equals(rp.name)) {
return members[i];
}
}
}
return null;
}
/**
* @param methodDeclaration
* @return all of the named pointcuts referenced by the PCD of this declaration
*/
private List genNamedPointcuts(MethodDeclaration methodDeclaration) {
List pointcuts = new ArrayList();
if (methodDeclaration instanceof AdviceDeclaration) {
if (((AdviceDeclaration)methodDeclaration).pointcutDesignator != null)
addAllNamed(((AdviceDeclaration)methodDeclaration).pointcutDesignator.getPointcut(), pointcuts);
} else if (methodDeclaration instanceof PointcutDeclaration) {
if (((PointcutDeclaration)methodDeclaration).pointcutDesignator != null)
addAllNamed(((PointcutDeclaration)methodDeclaration).pointcutDesignator.getPointcut(), pointcuts);
}
return pointcuts;
}
/**
* @param left
* @param pointcuts accumulator for named pointcuts
*/
private void addAllNamed(Pointcut pointcut, List pointcuts) {
if (pointcut == null) return;
if (pointcut instanceof ReferencePointcut) {
ReferencePointcut rp = (ReferencePointcut)pointcut;
pointcuts.add(rp);
} else if (pointcut instanceof AndPointcut) {
AndPointcut ap = (AndPointcut)pointcut;
addAllNamed(ap.getLeft(), pointcuts);
addAllNamed(ap.getRight(), pointcuts);
} else if (pointcut instanceof OrPointcut) {
OrPointcut op = (OrPointcut)pointcut;
addAllNamed(op.getLeft(), pointcuts);
addAllNamed(op.getRight(), pointcuts);
}
}
private String genSourceSignature(MethodDeclaration methodDeclaration) {
StringBuffer output = new StringBuffer();
ASTNode.printModifiers(methodDeclaration.modifiers, output);
methodDeclaration.printReturnType(0, output).append(methodDeclaration.selector).append('(');
if (methodDeclaration.arguments != null) {
for (int i = 0; i < methodDeclaration.arguments.length; i++) {
if (i > 0) output.append(", "); //$NON-NLS-1$
methodDeclaration.arguments[i].print(0, output);
}
}
output.append(')');
if (methodDeclaration.thrownExceptions != null) {
output.append(" throws "); //$NON-NLS-1$
for (int i = 0; i < methodDeclaration.thrownExceptions.length; i++) {
if (i > 0) output.append(", "); //$NON-NLS-1$
methodDeclaration.thrownExceptions[i].print(0, output);
}
}
return output.toString();
}
// protected void genBytecodeInfo(MethodDeclaration methodDeclaration, IProgramElement peNode) {
// if (methodDeclaration.binding != null) {
// String memberName = "";
// String memberBytecodeSignature = "";
// try {
// EclipseFactory factory = ((AjLookupEnvironment)methodDeclaration.scope.environment()).factory;
// Member member = factory.makeResolvedMember(methodDeclaration.binding);
// memberName = member.getName();
// memberBytecodeSignature = member.getSignature();
// } catch (BCException bce) { // bad type name
// memberName = "<undefined>";
// } catch (NullPointerException npe) {
// memberName = "<undefined>";
// }
//
// peNode.setBytecodeName(memberName);
// peNode.setBytecodeSignature(memberBytecodeSignature);
// }
// ((IProgramElement)stack.peek()).addChild(peNode);
// }
protected void genBytecodeInfo(MethodDeclaration methodDeclaration, IProgramElement peNode) {
if (methodDeclaration.binding != null) {
try {
EclipseFactory factory = ((AjLookupEnvironment)methodDeclaration.scope.environment()).factory;
Member member = factory.makeResolvedMember(methodDeclaration.binding);
peNode.setBytecodeName(member.getName());
peNode.setBytecodeSignature(member.getSignature());
} catch (BCException bce) { // bad type name
bce.printStackTrace();
} catch (NullPointerException npe) {
npe.printStackTrace();
}
}
((IProgramElement)stack.peek()).addChild(peNode);
}
public void endVisit(MethodDeclaration methodDeclaration, ClassScope scope) {
stack.pop();
}
public boolean visit(ImportReference importRef, CompilationUnitScope scope) {
int dotIndex = importRef.toString().lastIndexOf('.');
String currPackageImport = "";
if (dotIndex != -1) {
currPackageImport = importRef.toString().substring(0, dotIndex);
}
if (!((ProgramElement)stack.peek()).getPackageName().equals(currPackageImport)) {
IProgramElement peNode = new ProgramElement(
new String(importRef.toString()),
IProgramElement.Kind.IMPORT_REFERENCE,
makeLocation(importRef),
0,
null,null);
ProgramElement imports = (ProgramElement)((ProgramElement)stack.peek()).getChildren().get(0);
imports.addChild(0, peNode);
stack.push(peNode);
}
return true;
}
public void endVisit(ImportReference importRef, CompilationUnitScope scope) {
int dotIndex = importRef.toString().lastIndexOf('.');
String currPackageImport = "";
if (dotIndex != -1) {
currPackageImport = importRef.toString().substring(0, dotIndex);
}
if (!((ProgramElement)stack.peek()).getPackageName().equals(currPackageImport)) {
stack.pop();
}
}
public boolean visit(FieldDeclaration fieldDeclaration, MethodScope scope) {
IProgramElement peNode = null;
if (fieldDeclaration.type == null) { // The field represents an enum value
peNode = new ProgramElement(
new String(fieldDeclaration.name),IProgramElement.Kind.ENUM_VALUE,
makeLocation(fieldDeclaration), fieldDeclaration.modifiers,
null,null);
peNode.setCorrespondingType(fieldDeclaration.binding.type.debugName());
} else {
peNode = new ProgramElement(
new String(fieldDeclaration.name),IProgramElement.Kind.FIELD,
makeLocation(fieldDeclaration), fieldDeclaration.modifiers,
null,null);
peNode.setCorrespondingType(fieldDeclaration.type.toString());
}
peNode.setSourceSignature(genSourceSignature(fieldDeclaration));
peNode.setFormalComment(generateJavadocComment(fieldDeclaration));
((IProgramElement)stack.peek()).addChild(peNode);
stack.push(peNode);
return true;
}
public void endVisit(FieldDeclaration fieldDeclaration, MethodScope scope) {
stack.pop();
}
/**
* Checks if comments should be added to the model before generating.
*/
protected String generateJavadocComment(ASTNode astNode) {
if (buildConfig != null && !buildConfig.isGenerateJavadocsInModelMode()) return null;
StringBuffer sb = new StringBuffer(); // !!! specify length?
boolean completed = false;
int startIndex = -1;
if (astNode instanceof MethodDeclaration) {
startIndex = ((MethodDeclaration)astNode).declarationSourceStart;
} else if (astNode instanceof FieldDeclaration) {
startIndex = ((FieldDeclaration)astNode).declarationSourceStart;
} else if (astNode instanceof TypeDeclaration) {
startIndex = ((TypeDeclaration)astNode).declarationSourceStart;
}
if (startIndex == -1) {
return null;
} else if (currCompilationResult.compilationUnit.getContents()[startIndex] == '/' // look for /**
&& currCompilationResult.compilationUnit.getContents()[startIndex+1] == '*'
&& currCompilationResult.compilationUnit.getContents()[startIndex+2] == '*') {
for (int i = startIndex; i < astNode.sourceStart && !completed; i++) {
char curr = currCompilationResult.compilationUnit.getContents()[i];
if (curr == '/' && sb.length() > 2 && sb.charAt(sb.length()-1) == '*') completed = true; // found */
sb.append(currCompilationResult.compilationUnit.getContents()[i]);
}
return sb.toString();
} else {
return null;
}
}
/**
* Doesn't print qualified allocation expressions.
*/
protected String genSourceSignature(FieldDeclaration fieldDeclaration) {
StringBuffer output = new StringBuffer();
if (fieldDeclaration.type == null) { // This is an enum value
output.append(fieldDeclaration.name); // the "," or ";" has to be put on by whatever uses the sourceSignature
return output.toString();
} else {
FieldDeclaration.printModifiers(fieldDeclaration.modifiers, output);
fieldDeclaration.type.print(0, output).append(' ').append(fieldDeclaration.name);
}
if (fieldDeclaration.initialization != null
&& !(fieldDeclaration.initialization instanceof QualifiedAllocationExpression)) {
output.append(" = "); //$NON-NLS-1$
if (fieldDeclaration.initialization instanceof ExtendedStringLiteral) {
output.append("\"<extended string literal>\"");
} else {
fieldDeclaration.initialization.printExpression(0, output);
}
}
output.append(';');
return output.toString();
}
// public boolean visit(ImportReference importRef, CompilationUnitScope scope) {
// ProgramElementNode peNode = new ProgramElementNode(
// new String(importRef.toString()),
// ProgramElementNode.Kind.,
// makeLocation(importRef),
// 0,
// "",
// new ArrayList());
// ((IProgramElement)stack.peek()).addChild(0, peNode);
// stack.push(peNode);
// return true;
// }
// public void endVisit(ImportReference importRef,CompilationUnitScope scope) {
// stack.pop();
// }
public boolean visit(ConstructorDeclaration constructorDeclaration, ClassScope scope) {
if (constructorDeclaration.isDefaultConstructor) {
stack.push(null); // a little wierd but does the job
return true;
}
StringBuffer argumentsSignature = new StringBuffer();
argumentsSignature.append("(");
if (constructorDeclaration.arguments!=null) {
for (int i = 0;i<constructorDeclaration.arguments.length;i++) {
argumentsSignature.append(constructorDeclaration.arguments[i].type);
if (i+1<constructorDeclaration.arguments.length) argumentsSignature.append(",");
}
}
argumentsSignature.append(")");
IProgramElement peNode = new ProgramElement(
new String(constructorDeclaration.selector),
IProgramElement.Kind.CONSTRUCTOR,
makeLocation(constructorDeclaration),
constructorDeclaration.modifiers,
null,null);
formatter.setParameters(constructorDeclaration, peNode);
peNode.setModifiers(constructorDeclaration.modifiers);
peNode.setSourceSignature(genSourceSignature(constructorDeclaration));
// Fix to enable us to anchor things from ctor nodes
if (constructorDeclaration.binding != null) {
String memberName = "";
String memberBytecodeSignature = "";
try {
EclipseFactory factory = ((AjLookupEnvironment)constructorDeclaration.scope.environment()).factory;
Member member = factory.makeResolvedMember(constructorDeclaration.binding);
memberName = member.getName();
memberBytecodeSignature = member.getSignature();
} catch (BCException bce) { // bad type name
memberName = "<undefined>";
} catch (NullPointerException npe) {
memberName = "<undefined>";
}
peNode.setBytecodeName(memberName);
peNode.setBytecodeSignature(memberBytecodeSignature);
}
((IProgramElement)stack.peek()).addChild(peNode);
stack.push(peNode);
return true;
}
public void endVisit(ConstructorDeclaration constructorDeclaration, ClassScope scope) {
stack.pop();
}
private String genSourceSignature(ConstructorDeclaration constructorDeclaration) {
StringBuffer output = new StringBuffer();
ASTNode.printModifiers(constructorDeclaration.modifiers, output);
output.append(constructorDeclaration.selector).append('(');
if (constructorDeclaration.arguments != null) {
for (int i = 0; i < constructorDeclaration.arguments.length; i++) {
if (i > 0) output.append(", "); //$NON-NLS-1$
constructorDeclaration.arguments[i].print(0, output);
}
}
output.append(')');
if (constructorDeclaration.thrownExceptions != null) {
output.append(" throws "); //$NON-NLS-1$
for (int i = 0; i < constructorDeclaration.thrownExceptions.length; i++) {
if (i > 0) output.append(", "); //$NON-NLS-1$
constructorDeclaration.thrownExceptions[i].print(0, output);
}
}
return output.toString();
}
// public boolean visit(Clinit clinit, ClassScope scope) {
// ProgramElementNode peNode = new ProgramElementNode(
// "<clinit>",
// ProgramElementNode.Kind.INITIALIZER,
// makeLocation(clinit),
// clinit.modifiers,
// "",
// new ArrayList());
// ((IProgramElement)stack.peek()).addChild(peNode);
// stack.push(peNode);
// return false;
// }
// public void endVisit(Clinit clinit, ClassScope scope) {
// stack.pop();
// }
/** This method works-around an odd traverse implementation on Initializer
*/
private Initializer inInitializer = null;
public boolean visit(Initializer initializer, MethodScope scope) {
if (initializer == inInitializer) return false;
inInitializer = initializer;
IProgramElement peNode = new ProgramElement(
"...",
IProgramElement.Kind.INITIALIZER,
makeLocation(initializer),
initializer.modifiers,null,null);
// "",
// new ArrayList());
((IProgramElement)stack.peek()).addChild(peNode);
stack.push(peNode);
initializer.block.traverse(this, scope);
stack.pop();
inInitializer=null;
return false;
}
// ??? handle non-existant files
protected ISourceLocation makeLocation(ASTNode node) {
String fileName = "";
if (filename != null) {
fileName = this.filename;
}
// AMC - different strategies based on node kind
int startLine = getStartLine(node);
int endLine = getEndLine(node);
SourceLocation loc = null;
if ( startLine <= endLine ) {
// found a valid end line for this node...
loc = new SourceLocation(new File(fileName), startLine, endLine);
loc.setOffset(node.sourceStart);
} else {
loc = new SourceLocation(new File(fileName), startLine);
loc.setOffset(node.sourceStart);
}
return loc;
}
// AMC - overloaded set of methods to get start and end lines for
// various ASTNode types. They have no common ancestor in the
// hierarchy!!
protected int getStartLine( ASTNode n){
// if ( n instanceof AbstractVariableDeclaration ) return getStartLine( (AbstractVariableDeclaration)n);
// if ( n instanceof AbstractMethodDeclaration ) return getStartLine( (AbstractMethodDeclaration)n);
// if ( n instanceof TypeDeclaration ) return getStartLine( (TypeDeclaration)n);
return ProblemHandler.searchLineNumber(lineseps,
// currCompilationResult.lineSeparatorPositions,
n.sourceStart);
}
// AMC - overloaded set of methods to get start and end lines for
// various ASTNode types. They have no common ancestor in the
// hierarchy!!
protected int getEndLine( ASTNode n){
if ( n instanceof AbstractVariableDeclaration ) return getEndLine( (AbstractVariableDeclaration)n);
if ( n instanceof AbstractMethodDeclaration ) return getEndLine( (AbstractMethodDeclaration)n);
if ( n instanceof TypeDeclaration ) return getEndLine( (TypeDeclaration)n);
return ProblemHandler.searchLineNumber(lineseps,
// currCompilationResult.lineSeparatorPositions,
n.sourceEnd);
}
// AMC - overloaded set of methods to get start and end lines for
// various ASTNode types. They have no common ancestor in the
// hierarchy!!
// private int getStartLine( AbstractVariableDeclaration avd ) {
// return ProblemHandler.searchLineNumber(
// currCompilationResult.lineSeparatorPositions,
// avd.declarationSourceStart);
// }
// AMC - overloaded set of methods to get start and end lines for
// various ASTNode types. They have no common ancestor in the
// hierarchy!!
private int getEndLine( AbstractVariableDeclaration avd ){
return ProblemHandler.searchLineNumber(lineseps,
// currCompilationResult.lineSeparatorPositions,
avd.declarationSourceEnd);
}
// AMC - overloaded set of methods to get start and end lines for
// various ASTNode types. They have no common ancestor in the
// hierarchy!!
// private int getStartLine( AbstractMethodDeclaration amd ){
// return ProblemHandler.searchLineNumber(
// currCompilationResult.lineSeparatorPositions,
// amd.declarationSourceStart);
// }
// AMC - overloaded set of methods to get start and end lines for
// various ASTNode types. They have no common ancestor in the
// hierarchy!!
private int getEndLine( AbstractMethodDeclaration amd) {
return ProblemHandler.searchLineNumber(lineseps,
// currCompilationResult.lineSeparatorPositions,
amd.declarationSourceEnd);
}
// AMC - overloaded set of methods to get start and end lines for
// various ASTNode types. They have no common ancestor in the
// hierarchy!!
// private int getStartLine( TypeDeclaration td ){
// return ProblemHandler.searchLineNumber(
// currCompilationResult.lineSeparatorPositions,
// td.declarationSourceStart);
// }
// AMC - overloaded set of methods to get start and end lines for
// various ASTNode types. They have no common ancestor in the
// hierarchy!!
private int getEndLine( TypeDeclaration td){
return ProblemHandler.searchLineNumber(lineseps,
// currCompilationResult.lineSeparatorPositions,
td.declarationSourceEnd);
}
}
|
148,908 |
Bug 148908 incorrect source signature for field ipe with qualified allocation expression
| null |
resolved fixed
|
fc39df1
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-09-26T09:26:33Z | 2006-06-27T23:13:20Z |
tests/bugs153/pr148908/BadInterface.java
| |
148,908 |
Bug 148908 incorrect source signature for field ipe with qualified allocation expression
| null |
resolved fixed
|
fc39df1
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-09-26T09:26:33Z | 2006-06-27T23:13:20Z |
tests/src/org/aspectj/systemtest/ajc153/Ajc153Tests.java
|
/*******************************************************************************
* Copyright (c) 2006 IBM
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Andy Clement - initial API and implementation
*******************************************************************************/
package org.aspectj.systemtest.ajc153;
import java.io.File;
import junit.framework.Test;
import org.aspectj.testing.Utils;
import org.aspectj.testing.XMLBasedAjcTestCase;
import org.aspectj.weaver.bcel.Utility;
public class Ajc153Tests extends org.aspectj.testing.XMLBasedAjcTestCase {
//public void testGenericsProblem_pr151978() { runTest("generics problem");}
//public void testMissingLineNumbersInStacktraceBefore_pr145442() { runTest("missing line numbers in stacktrace before");}
//public void testMissingLineNumbersInStacktraceAfter_pr145442() { runTest("missing line numbers in stacktrace after");}
//public void testMissingLineNumbersInStacktraceAround_pr145442() { runTest("missing line numbers in stacktrace around");}
// public void testArgnamesAndJavac_pr148381() { runTest("argNames and javac");}
// public void testCFlowXMLAspectLTW_pr149096() { runTest("cflow xml concrete aspect"); }
// public void testAmbiguousBinding_pr121805() { runTest("ambiguous binding");}
// public void testNoIllegalStateExceptionWithGenericInnerAspect_pr156058() { runTest("no IllegalStateException with generic inner aspect"); }
// public void testNegatedAnnotationMatchingProblem_pr153464() { runTest("negated annotation matching problem");}
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 testVisibilityProblem_pr149071() { runTest("visibility problem");}
// public void testAdviceNotWovenAspectPath_pr147841() { runTest("advice not woven on aspectpath");}
public void testGenericSignatures_pr148409() { runTest("generic signature problem"); }
// public void testBrokenIfArgsCflowAtAj_pr145018() { runTest("ataj crashing with cflow, if and args");}
public void testCantFindType_pr149322_01() {runTest("can't find type on interface call 1");}
public void testCantFindType_pr149322_02() {runTest("can't find type on interface call 2");}
public void testCantFindType_pr149322_03() {runTest("can't find type on interface call 3");}
public void 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 static Test suite() {
return XMLBasedAjcTestCase.loadSuite(Ajc153Tests.class);
}
protected File getSpecFile() {
return new File("../tests/src/org/aspectj/systemtest/ajc153/ajc153.xml");
}
}
|
158,624 |
Bug 158624 Compiler Error: generics and arrays
|
OK, not sure what to report here or what info you need, but here's the set up, message, and erroreous class. I don't understand the errors from the compiler enough to parse down the erroneous file to something that contains only the bug, but I could if direction were given. Here's my set up: Eclipse SDK Version: 3.2.0 Build id: M20060629-1905 With AJDT: Eclipse AspectJ Development Tools Version: 1.4.1.200608141223 AspectJ version: 1.5.3.200608210848 Here's the bug dump from the compiler inside Eclipse: java.lang.UnsupportedOperationException at org.aspectj.weaver.UnresolvedType.parameterize(UnresolvedType.java:221) at org.aspectj.weaver.ResolvedMemberImpl.parameterize(ResolvedMemberImpl.java:680) at org.aspectj.weaver.ResolvedMemberImpl.parameterize(ResolvedMemberImpl.java:690) at org.aspectj.weaver.ResolvedMemberImpl.parameterizedWith(ResolvedMemberImpl.java:643) at org.aspectj.weaver.ResolvedMemberImpl.parameterizedWith(ResolvedMemberImpl.java:597) at org.aspectj.weaver.ReferenceType.getDeclaredMethods(ReferenceType.java:508) at org.aspectj.weaver.ResolvedType$4.get(ResolvedType.java:226) at org.aspectj.weaver.Iterators$3$1.hasNext(Iterators.java:118) at org.aspectj.weaver.Iterators$5.hasNext(Iterators.java:171) at org.aspectj.weaver.Iterators$3.hasNext(Iterators.java:128) at org.aspectj.weaver.ResolvedType.lookupMember(ResolvedType.java:346) at org.aspectj.weaver.ResolvedType.lookupMethod(ResolvedType.java:327) at org.aspectj.weaver.World.resolve(World.java:523) at org.aspectj.weaver.MemberImpl.resolve(MemberImpl.java:93) at org.aspectj.weaver.JoinPointSignatureIterator.addSignaturesUpToFirstDefiningMember(JoinPointSignatureIterator.java:109) at org.aspectj.weaver.JoinPointSignatureIterator.<init>(JoinPointSignatureIterator.java:51) at org.aspectj.weaver.MemberImpl.getJoinPointSignatures(MemberImpl.java:943) at org.aspectj.weaver.patterns.SignaturePattern.matches(SignaturePattern.java:286) at org.aspectj.weaver.patterns.KindedPointcut.matchInternal(KindedPointcut.java:106) at org.aspectj.weaver.patterns.Pointcut.match(Pointcut.java:146) at org.aspectj.weaver.patterns.AndPointcut.matchInternal(AndPointcut.java:51) 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:117) at org.aspectj.weaver.bcel.BcelClassWeaver.match(BcelClassWeaver.java:2806) at org.aspectj.weaver.bcel.BcelClassWeaver.matchInvokeInstruction(BcelClassWeaver.java:2768) 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:1606) at org.aspectj.weaver.bcel.BcelWeaver.weaveWithoutDump(BcelWeaver.java:1557) at org.aspectj.weaver.bcel.BcelWeaver.weaveAndNotify(BcelWeaver.java:1335) at org.aspectj.weaver.bcel.BcelWeaver.weave(BcelWeaver.java:1155) at org.aspectj.ajdt.internal.compiler.AjPipeliningCompilerAdapter.weaveQueuedEntries(AjPipeliningCompilerAdapter.java:455) at org.aspectj.ajdt.internal.compiler.AjPipeliningCompilerAdapter.queueForWeaving(AjPipeliningCompilerAdapter.java:392) at org.aspectj.ajdt.internal.compiler.AjPipeliningCompilerAdapter.afterProcessing(AjPipeliningCompilerAdapter.java:380) at org.aspectj.ajdt.internal.compiler.CompilerAdapter.ajc$after$org_aspectj_ajdt_internal_compiler_CompilerAdapter$5$6b855184(CompilerAdapter.aj:98) at org.aspectj.org.eclipse.jdt.internal.compiler.Compiler.process(Compiler.java:533) at org.aspectj.org.eclipse.jdt.internal.compiler.Compiler.compile(Compiler.java:329) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.performCompilation(AjBuildManager.java:892) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.doBuild(AjBuildManager.java:246) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.batchBuild(AjBuildManager.java:165) at org.aspectj.ajde.internal.CompilerAdapter.compile(CompilerAdapter.java:122) at org.aspectj.ajde.internal.AspectJBuildManager$CompilerThread.run(AspectJBuildManager.java:191) trouble in: public class com.wec.lib.util.test.SyncValueTest extends junit.framework.TestCase: private com.wec.lib.util.test.SyncValueTest$SyncInteger a private com.wec.lib.util.test.SyncValueTest$SyncInteger b private com.wec.lib.util.test.SyncValueTest$SyncInteger c private com.wec.lib.util.test.SyncValueTest$SyncInteger d private com.wec.lib.util.test.SyncValueTest$SyncInteger e public void <init>(): ALOAD_0 // Lcom/wec/lib/util/test/SyncValueTest; this (line 17) INVOKESPECIAL junit.framework.TestCase.<init> ()V constructor-execution(void com.wec.lib.util.test.SyncValueTest.<init>()) | ALOAD_0 // Lcom/wec/lib/util/test/SyncValueTest; this (line 27) | NEW com.wec.lib.util.test.SyncValueTest$SyncInteger | DUP | ALOAD_0 // Lcom/wec/lib/util/test/SyncValueTest; this | ICONST_1 | INVOKESPECIAL com.wec.lib.util.test.SyncValueTest$SyncInteger.<init> (Lcom/wec/lib/util/test/SyncValueTest;I)V | PUTFIELD com.wec.lib.util.test.SyncValueTest.a Lcom/wec/lib/util/test/SyncValueTest$SyncInteger; | ALOAD_0 // Lcom/wec/lib/util/test/SyncValueTest; this (line 28) | NEW com.wec.lib.util.test.SyncValueTest$SyncInteger | DUP | ALOAD_0 // Lcom/wec/lib/util/test/SyncValueTest; this | ICONST_2 | INVOKESPECIAL com.wec.lib.util.test.SyncValueTest$SyncInteger.<init> (Lcom/wec/lib/util/test/SyncValueTest;I)V | PUTFIELD com.wec.lib.util.test.SyncValueTest.b Lcom/wec/lib/util/test/SyncValueTest$SyncInteger; | ALOAD_0 // Lcom/wec/lib/util/test/SyncValueTest; this (line 29) | NEW com.wec.lib.util.test.SyncValueTest$SyncInteger | DUP | ALOAD_0 // Lcom/wec/lib/util/test/SyncValueTest; this | ICONST_3 | INVOKESPECIAL com.wec.lib.util.test.SyncValueTest$SyncInteger.<init> (Lcom/wec/lib/util/test/SyncValueTest;I)V | PUTFIELD com.wec.lib.util.test.SyncValueTest.c Lcom/wec/lib/util/test/SyncValueTest$SyncInteger; | ALOAD_0 // Lcom/wec/lib/util/test/SyncValueTest; this (line 30) | NEW com.wec.lib.util.test.SyncValueTest$SyncInteger | DUP | ALOAD_0 // Lcom/wec/lib/util/test/SyncValueTest; this | ICONST_4 | INVOKESPECIAL com.wec.lib.util.test.SyncValueTest$SyncInteger.<init> (Lcom/wec/lib/util/test/SyncValueTest;I)V | PUTFIELD com.wec.lib.util.test.SyncValueTest.d Lcom/wec/lib/util/test/SyncValueTest$SyncInteger; | ALOAD_0 // Lcom/wec/lib/util/test/SyncValueTest; this (line 31) | NEW com.wec.lib.util.test.SyncValueTest$SyncInteger | DUP | ALOAD_0 // Lcom/wec/lib/util/test/SyncValueTest; this | ICONST_5 | INVOKESPECIAL com.wec.lib.util.test.SyncValueTest$SyncInteger.<init> (Lcom/wec/lib/util/test/SyncValueTest;I)V | PUTFIELD com.wec.lib.util.test.SyncValueTest.e Lcom/wec/lib/util/test/SyncValueTest$SyncInteger; | RETURN (line 17) constructor-execution(void com.wec.lib.util.test.SyncValueTest.<init>()) end public void <init>() public void testSyncValueGroup() org.aspectj.weaver.MethodDeclarationLineNumber: 39:1035 : method-execution(void com.wec.lib.util.test.SyncValueTest.testSyncValueGroup()) | ALOAD_0 // Lcom/wec/lib/util/test/SyncValueTest; this (line 42) | GETFIELD com.wec.lib.util.test.SyncValueTest.a Lcom/wec/lib/util/test/SyncValueTest$SyncInteger; | ICONST_1 | ANEWARRAY com.wec.lib.util.SyncValueGroup | DUP | ICONST_0 | ALOAD_0 // Lcom/wec/lib/util/test/SyncValueTest; this | GETFIELD com.wec.lib.util.test.SyncValueTest.b Lcom/wec/lib/util/test/SyncValueTest$SyncInteger; | AASTORE | method-call(void com.wec.lib.util.test.SyncValueTest$SyncInteger.link(com.wec.lib.util.SyncValueGroup[])) | | INVOKEVIRTUAL com.wec.lib.util.test.SyncValueTest$SyncInteger.link ([Lcom/wec/lib/util/SyncValueGroup;)V | method-call(void com.wec.lib.util.test.SyncValueTest$SyncInteger.link(com.wec.lib.util.SyncValueGroup[])) | ALOAD_0 // Lcom/wec/lib/util/test/SyncValueTest; this (line 43) | GETFIELD com.wec.lib.util.test.SyncValueTest.a Lcom/wec/lib/util/test/SyncValueTest$SyncInteger; | INVOKEVIRTUAL com.wec.lib.util.test.SyncValueTest$SyncInteger.getValue ()Ljava/lang/Object; | ALOAD_0 // Lcom/wec/lib/util/test/SyncValueTest; this | GETFIELD com.wec.lib.util.test.SyncValueTest.b Lcom/wec/lib/util/test/SyncValueTest$SyncInteger; | INVOKEVIRTUAL com.wec.lib.util.test.SyncValueTest$SyncInteger.getValue ()Ljava/lang/Object; | IF_ACMPNE L0 | ICONST_1 | GOTO L1 | L0: ICONST_0 | L1: INVOKESTATIC com.wec.lib.util.test.SyncValueTest.assertTrue (Z)V | ICONST_1 (line 44) | ALOAD_0 // Lcom/wec/lib/util/test/SyncValueTest; this | GETFIELD com.wec.lib.util.test.SyncValueTest.b Lcom/wec/lib/util/test/SyncValueTest$SyncInteger; | INVOKEVIRTUAL com.wec.lib.util.test.SyncValueTest$SyncInteger.getValue ()Ljava/lang/Object; | CHECKCAST java.lang.Integer | INVOKEVIRTUAL java.lang.Integer.intValue ()I | IF_ICMPNE L2 | ICONST_1 | GOTO L3 | L2: ICONST_0 | L3: INVOKESTATIC com.wec.lib.util.test.SyncValueTest.assertTrue (Z)V | ALOAD_0 // Lcom/wec/lib/util/test/SyncValueTest; this (line 45) | GETFIELD com.wec.lib.util.test.SyncValueTest.b Lcom/wec/lib/util/test/SyncValueTest$SyncInteger; | ICONST_2 | INVOKESTATIC java.lang.Integer.valueOf (I)Ljava/lang/Integer; | INVOKEVIRTUAL com.wec.lib.util.test.SyncValueTest$SyncInteger.setValue (Ljava/lang/Object;)V | ICONST_2 (line 46) | ALOAD_0 // Lcom/wec/lib/util/test/SyncValueTest; this | GETFIELD com.wec.lib.util.test.SyncValueTest.a Lcom/wec/lib/util/test/SyncValueTest$SyncInteger; | INVOKEVIRTUAL com.wec.lib.util.test.SyncValueTest$SyncInteger.getValue ()Ljava/lang/Object; | CHECKCAST java.lang.Integer | INVOKEVIRTUAL java.lang.Integer.intValue ()I | IF_ICMPNE L4 | ICONST_1 | GOTO L5 | L4: ICONST_0 | L5: INVOKESTATIC com.wec.lib.util.test.SyncValueTest.assertTrue (Z)V | ALOAD_0 // Lcom/wec/lib/util/test/SyncValueTest; this (line 47) | GETFIELD com.wec.lib.util.test.SyncValueTest.b Lcom/wec/lib/util/test/SyncValueTest$SyncInteger; | ICONST_1 | ANEWARRAY com.wec.lib.util.SyncValueGroup | DUP | ICONST_0 | ALOAD_0 // Lcom/wec/lib/util/test/SyncValueTest; this | GETFIELD com.wec.lib.util.test.SyncValueTest.c Lcom/wec/lib/util/test/SyncValueTest$SyncInteger; | AASTORE | INVOKEVIRTUAL com.wec.lib.util.test.SyncValueTest$SyncInteger.link ([Lcom/wec/lib/util/SyncValueGroup;)V | ICONST_2 (line 48) | ALOAD_0 // Lcom/wec/lib/util/test/SyncValueTest; this | GETFIELD com.wec.lib.util.test.SyncValueTest.c Lcom/wec/lib/util/test/SyncValueTest$SyncInteger; | INVOKEVIRTUAL com.wec.lib.util.test.SyncValueTest$SyncInteger.getValue ()Ljava/lang/Object; | CHECKCAST java.lang.Integer | INVOKEVIRTUAL java.lang.Integer.intValue ()I | IF_ICMPNE L6 | ICONST_1 | GOTO L7 | L6: ICONST_0 | L7: INVOKESTATIC com.wec.lib.util.test.SyncValueTest.assertTrue (Z)V | ALOAD_0 // Lcom/wec/lib/util/test/SyncValueTest; this (line 49) | GETFIELD com.wec.lib.util.test.SyncValueTest.c Lcom/wec/lib/util/test/SyncValueTest$SyncInteger; | ICONST_3 | INVOKESTATIC java.lang.Integer.valueOf (I)Ljava/lang/Integer; | INVOKEVIRTUAL com.wec.lib.util.test.SyncValueTest$SyncInteger.setValue (Ljava/lang/Object;)V | ICONST_3 (line 50) | ALOAD_0 // Lcom/wec/lib/util/test/SyncValueTest; this | GETFIELD com.wec.lib.util.test.SyncValueTest.a Lcom/wec/lib/util/test/SyncValueTest$SyncInteger; | INVOKEVIRTUAL com.wec.lib.util.test.SyncValueTest$SyncInteger.getValue ()Ljava/lang/Object; | CHECKCAST java.lang.Integer | INVOKEVIRTUAL java.lang.Integer.intValue ()I | IF_ICMPNE L8 | ICONST_1 | GOTO L9 | L8: ICONST_0 | L9: INVOKESTATIC com.wec.lib.util.test.SyncValueTest.assertTrue (Z)V | ICONST_3 (line 51) | ALOAD_0 // Lcom/wec/lib/util/test/SyncValueTest; this | GETFIELD com.wec.lib.util.test.SyncValueTest.b Lcom/wec/lib/util/test/SyncValueTest$SyncInteger; | INVOKEVIRTUAL com.wec.lib.util.test.SyncValueTest$SyncInteger.getValue ()Ljava/lang/Object; | CHECKCAST java.lang.Integer | INVOKEVIRTUAL java.lang.Integer.intValue ()I | IF_ICMPNE L10 | ICONST_1 | GOTO L11 | L10: ICONST_0 | L11: INVOKESTATIC com.wec.lib.util.test.SyncValueTest.assertTrue (Z)V | ALOAD_0 // Lcom/wec/lib/util/test/SyncValueTest; this (line 52) | GETFIELD com.wec.lib.util.test.SyncValueTest.a Lcom/wec/lib/util/test/SyncValueTest$SyncInteger; | ICONST_4 | INVOKESTATIC java.lang.Integer.valueOf (I)Ljava/lang/Integer; | INVOKEVIRTUAL com.wec.lib.util.test.SyncValueTest$SyncInteger.setValue (Ljava/lang/Object;)V | ICONST_4 (line 53) | ALOAD_0 // Lcom/wec/lib/util/test/SyncValueTest; this | GETFIELD com.wec.lib.util.test.SyncValueTest.c Lcom/wec/lib/util/test/SyncValueTest$SyncInteger; | INVOKEVIRTUAL com.wec.lib.util.test.SyncValueTest$SyncInteger.getValue ()Ljava/lang/Object; | CHECKCAST java.lang.Integer | INVOKEVIRTUAL java.lang.Integer.intValue ()I | IF_ICMPNE L12 | ICONST_1 | GOTO L13 | L12: ICONST_0 | L13: INVOKESTATIC com.wec.lib.util.test.SyncValueTest.assertTrue (Z)V | ICONST_4 (line 54) | ALOAD_0 // Lcom/wec/lib/util/test/SyncValueTest; this | GETFIELD com.wec.lib.util.test.SyncValueTest.b Lcom/wec/lib/util/test/SyncValueTest$SyncInteger; | INVOKEVIRTUAL com.wec.lib.util.test.SyncValueTest$SyncInteger.getValue ()Ljava/lang/Object; | CHECKCAST java.lang.Integer | INVOKEVIRTUAL java.lang.Integer.intValue ()I | IF_ICMPNE L14 | ICONST_1 | GOTO L15 | L14: ICONST_0 | L15: INVOKESTATIC com.wec.lib.util.test.SyncValueTest.assertTrue (Z)V | ALOAD_0 // Lcom/wec/lib/util/test/SyncValueTest; this (line 55) | GETFIELD com.wec.lib.util.test.SyncValueTest.b Lcom/wec/lib/util/test/SyncValueTest$SyncInteger; | ICONST_1 | INVOKESTATIC java.lang.Integer.valueOf (I)Ljava/lang/Integer; | INVOKEVIRTUAL com.wec.lib.util.test.SyncValueTest$SyncInteger.setValue (Ljava/lang/Object;)V | ICONST_1 (line 56) | ALOAD_0 // Lcom/wec/lib/util/test/SyncValueTest; this | GETFIELD com.wec.lib.util.test.SyncValueTest.c Lcom/wec/lib/util/test/SyncValueTest$SyncInteger; | INVOKEVIRTUAL com.wec.lib.util.test.SyncValueTest$SyncInteger.getValue ()Ljava/lang/Object; | CHECKCAST java.lang.Integer | INVOKEVIRTUAL java.lang.Integer.intValue ()I | IF_ICMPNE L16 | ICONST_1 | GOTO L17 | L16: ICONST_0 | L17: INVOKESTATIC com.wec.lib.util.test.SyncValueTest.assertTrue (Z)V | ICONST_1 (line 57) | ALOAD_0 // Lcom/wec/lib/util/test/SyncValueTest; this | GETFIELD com.wec.lib.util.test.SyncValueTest.a Lcom/wec/lib/util/test/SyncValueTest$SyncInteger; | INVOKEVIRTUAL com.wec.lib.util.test.SyncValueTest$SyncInteger.getValue ()Ljava/lang/Object; | CHECKCAST java.lang.Integer | INVOKEVIRTUAL java.lang.Integer.intValue ()I | IF_ICMPNE L18 | ICONST_1 | GOTO L19 | L18: ICONST_0 | L19: INVOKESTATIC com.wec.lib.util.test.SyncValueTest.assertTrue (Z)V | ALOAD_0 // Lcom/wec/lib/util/test/SyncValueTest; this (line 59) | GETFIELD com.wec.lib.util.test.SyncValueTest.d Lcom/wec/lib/util/test/SyncValueTest$SyncInteger; | ICONST_1 | ANEWARRAY com.wec.lib.util.SyncValueGroup | DUP | ICONST_0 | ALOAD_0 // Lcom/wec/lib/util/test/SyncValueTest; this | GETFIELD com.wec.lib.util.test.SyncValueTest.e Lcom/wec/lib/util/test/SyncValueTest$SyncInteger; | AASTORE | INVOKEVIRTUAL com.wec.lib.util.test.SyncValueTest$SyncInteger.link ([Lcom/wec/lib/util/SyncValueGroup;)V | ALOAD_0 // Lcom/wec/lib/util/test/SyncValueTest; this (line 60) | GETFIELD com.wec.lib.util.test.SyncValueTest.d Lcom/wec/lib/util/test/SyncValueTest$SyncInteger; | INVOKEVIRTUAL com.wec.lib.util.test.SyncValueTest$SyncInteger.getValue ()Ljava/lang/Object; | ALOAD_0 // Lcom/wec/lib/util/test/SyncValueTest; this | GETFIELD com.wec.lib.util.test.SyncValueTest.e Lcom/wec/lib/util/test/SyncValueTest$SyncInteger; | INVOKEVIRTUAL com.wec.lib.util.test.SyncValueTest$SyncInteger.getValue ()Ljava/lang/Object; | IF_ACMPNE L20 | ICONST_1 | GOTO L21 | L20: ICONST_0 | L21: INVOKESTATIC com.wec.lib.util.test.SyncValueTest.assertTrue (Z)V | ALOAD_0 // Lcom/wec/lib/util/test/SyncValueTest; this (line 63) | GETFIELD com.wec.lib.util.test.SyncValueTest.b Lcom/wec/lib/util/test/SyncValueTest$SyncInteger; | ICONST_1 | ANEWARRAY com.wec.lib.util.SyncValueGroup | DUP | ICONST_0 | ALOAD_0 // Lcom/wec/lib/util/test/SyncValueTest; this | GETFIELD com.wec.lib.util.test.SyncValueTest.d Lcom/wec/lib/util/test/SyncValueTest$SyncInteger; | AASTORE | INVOKEVIRTUAL com.wec.lib.util.test.SyncValueTest$SyncInteger.link ([Lcom/wec/lib/util/SyncValueGroup;)V | ICONST_1 (line 64) | ALOAD_0 // Lcom/wec/lib/util/test/SyncValueTest; this | GETFIELD com.wec.lib.util.test.SyncValueTest.d Lcom/wec/lib/util/test/SyncValueTest$SyncInteger; | INVOKEVIRTUAL com.wec.lib.util.test.SyncValueTest$SyncInteger.getValue ()Ljava/lang/Object; | CHECKCAST java.lang.Integer | INVOKEVIRTUAL java.lang.Integer.intValue ()I | IF_ICMPNE L22 | ICONST_1 | GOTO L23 | L22: ICONST_0 | L23: INVOKESTATIC com.wec.lib.util.test.SyncValueTest.assertTrue (Z)V | ICONST_1 (line 65) | ALOAD_0 // Lcom/wec/lib/util/test/SyncValueTest; this | GETFIELD com.wec.lib.util.test.SyncValueTest.e Lcom/wec/lib/util/test/SyncValueTest$SyncInteger; | INVOKEVIRTUAL com.wec.lib.util.test.SyncValueTest$SyncInteger.getValue ()Ljava/lang/Object; | CHECKCAST java.lang.Integer | INVOKEVIRTUAL java.lang.Integer.intValue ()I | IF_ICMPNE L24 | ICONST_1 | GOTO L25 | L24: ICONST_0 | L25: INVOKESTATIC com.wec.lib.util.test.SyncValueTest.assertTrue (Z)V | ALOAD_0 // Lcom/wec/lib/util/test/SyncValueTest; this (line 66) | GETFIELD com.wec.lib.util.test.SyncValueTest.d Lcom/wec/lib/util/test/SyncValueTest$SyncInteger; | BIPUSH 8 | INVOKESTATIC java.lang.Integer.valueOf (I)Ljava/lang/Integer; | INVOKEVIRTUAL com.wec.lib.util.test.SyncValueTest$SyncInteger.setValue (Ljava/lang/Object;)V | BIPUSH 8 (line 67) | ALOAD_0 // Lcom/wec/lib/util/test/SyncValueTest; this | GETFIELD com.wec.lib.util.test.SyncValueTest.a Lcom/wec/lib/util/test/SyncValueTest$SyncInteger; | INVOKEVIRTUAL com.wec.lib.util.test.SyncValueTest$SyncInteger.getValue ()Ljava/lang/Object; | CHECKCAST java.lang.Integer | INVOKEVIRTUAL java.lang.Integer.intValue ()I | IF_ICMPNE L26 | ICONST_1 | GOTO L27 | L26: ICONST_0 | L27: INVOKESTATIC com.wec.lib.util.test.SyncValueTest.assertTrue (Z)V | BIPUSH 8 (line 68) | ALOAD_0 // Lcom/wec/lib/util/test/SyncValueTest; this | GETFIELD com.wec.lib.util.test.SyncValueTest.b Lcom/wec/lib/util/test/SyncValueTest$SyncInteger; | INVOKEVIRTUAL com.wec.lib.util.test.SyncValueTest$SyncInteger.getValue ()Ljava/lang/Object; | CHECKCAST java.lang.Integer | INVOKEVIRTUAL java.lang.Integer.intValue ()I | IF_ICMPNE L28 | ICONST_1 | GOTO L29 | L28: ICONST_0 | L29: INVOKESTATIC com.wec.lib.util.test.SyncValueTest.assertTrue (Z)V | BIPUSH 8 (line 69) | ALOAD_0 // Lcom/wec/lib/util/test/SyncValueTest; this | GETFIELD com.wec.lib.util.test.SyncValueTest.c Lcom/wec/lib/util/test/SyncValueTest$SyncInteger; | INVOKEVIRTUAL com.wec.lib.util.test.SyncValueTest$SyncInteger.getValue ()Ljava/lang/Object; | CHECKCAST java.lang.Integer | INVOKEVIRTUAL java.lang.Integer.intValue ()I | IF_ICMPNE L30 | ICONST_1 | GOTO L31 | L30: ICONST_0 | L31: INVOKESTATIC com.wec.lib.util.test.SyncValueTest.assertTrue (Z)V | BIPUSH 8 (line 70) | ALOAD_0 // Lcom/wec/lib/util/test/SyncValueTest; this | GETFIELD com.wec.lib.util.test.SyncValueTest.d Lcom/wec/lib/util/test/SyncValueTest$SyncInteger; | INVOKEVIRTUAL com.wec.lib.util.test.SyncValueTest$SyncInteger.getValue ()Ljava/lang/Object; | CHECKCAST java.lang.Integer | INVOKEVIRTUAL java.lang.Integer.intValue ()I | IF_ICMPNE L32 | ICONST_1 | GOTO L33 | L32: ICONST_0 | L33: INVOKESTATIC com.wec.lib.util.test.SyncValueTest.assertTrue (Z)V | BIPUSH 8 (line 71) | ALOAD_0 // Lcom/wec/lib/util/test/SyncValueTest; this | GETFIELD com.wec.lib.util.test.SyncValueTest.e Lcom/wec/lib/util/test/SyncValueTest$SyncInteger; | INVOKEVIRTUAL com.wec.lib.util.test.SyncValueTest$SyncInteger.getValue ()Ljava/lang/Object; | CHECKCAST java.lang.Integer | INVOKEVIRTUAL java.lang.Integer.intValue ()I | IF_ICMPNE L34 | ICONST_1 | GOTO L35 | L34: ICONST_0 | L35: INVOKESTATIC com.wec.lib.util.test.SyncValueTest.assertTrue (Z)V | ALOAD_0 // Lcom/wec/lib/util/test/SyncValueTest; this (line 74) | GETFIELD com.wec.lib.util.test.SyncValueTest.c Lcom/wec/lib/util/test/SyncValueTest$SyncInteger; | INVOKEVIRTUAL com.wec.lib.util.test.SyncValueTest$SyncInteger.unlink ()V | ALOAD_0 // Lcom/wec/lib/util/test/SyncValueTest; this (line 75) | GETFIELD com.wec.lib.util.test.SyncValueTest.c Lcom/wec/lib/util/test/SyncValueTest$SyncInteger; | ICONST_3 | INVOKESTATIC java.lang.Integer.valueOf (I)Ljava/lang/Integer; | INVOKEVIRTUAL com.wec.lib.util.test.SyncValueTest$SyncInteger.setValue (Ljava/lang/Object;)V | ALOAD_0 // Lcom/wec/lib/util/test/SyncValueTest; this (line 76) | GETFIELD com.wec.lib.util.test.SyncValueTest.b Lcom/wec/lib/util/test/SyncValueTest$SyncInteger; | ICONST_2 | INVOKESTATIC java.lang.Integer.valueOf (I)Ljava/lang/Integer; | INVOKEVIRTUAL com.wec.lib.util.test.SyncValueTest$SyncInteger.setValue (Ljava/lang/Object;)V | ICONST_2 (line 77) | ALOAD_0 // Lcom/wec/lib/util/test/SyncValueTest; this | GETFIELD com.wec.lib.util.test.SyncValueTest.a Lcom/wec/lib/util/test/SyncValueTest$SyncInteger; | INVOKEVIRTUAL com.wec.lib.util.test.SyncValueTest$SyncInteger.getValue ()Ljava/lang/Object; | CHECKCAST java.lang.Integer | INVOKEVIRTUAL java.lang.Integer.intValue ()I | IF_ICMPNE L36 | ICONST_1 | GOTO L37 | L36: ICONST_0 | L37: INVOKESTATIC com.wec.lib.util.test.SyncValueTest.assertTrue (Z)V | ICONST_2 (line 78) | ALOAD_0 // Lcom/wec/lib/util/test/SyncValueTest; this | GETFIELD com.wec.lib.util.test.SyncValueTest.b Lcom/wec/lib/util/test/SyncValueTest$SyncInteger; | INVOKEVIRTUAL com.wec.lib.util.test.SyncValueTest$SyncInteger.getValue ()Ljava/lang/Object; | CHECKCAST java.lang.Integer | INVOKEVIRTUAL java.lang.Integer.intValue ()I | IF_ICMPNE L38 | ICONST_1 | GOTO L39 | L38: ICONST_0 | L39: INVOKESTATIC com.wec.lib.util.test.SyncValueTest.assertTrue (Z)V | ICONST_3 (line 79) | ALOAD_0 // Lcom/wec/lib/util/test/SyncValueTest; this | GETFIELD com.wec.lib.util.test.SyncValueTest.c Lcom/wec/lib/util/test/SyncValueTest$SyncInteger; | INVOKEVIRTUAL com.wec.lib.util.test.SyncValueTest$SyncInteger.getValue ()Ljava/lang/Object; | CHECKCAST java.lang.Integer | INVOKEVIRTUAL java.lang.Integer.intValue ()I | IF_ICMPNE L40 | ICONST_1 | GOTO L41 | L40: ICONST_0 | L41: INVOKESTATIC com.wec.lib.util.test.SyncValueTest.assertTrue (Z)V | ICONST_2 (line 80) | ALOAD_0 // Lcom/wec/lib/util/test/SyncValueTest; this | GETFIELD com.wec.lib.util.test.SyncValueTest.d Lcom/wec/lib/util/test/SyncValueTest$SyncInteger; | INVOKEVIRTUAL com.wec.lib.util.test.SyncValueTest$SyncInteger.getValue ()Ljava/lang/Object; | CHECKCAST java.lang.Integer | INVOKEVIRTUAL java.lang.Integer.intValue ()I | IF_ICMPNE L42 | ICONST_1 | GOTO L43 | L42: ICONST_0 | L43: INVOKESTATIC com.wec.lib.util.test.SyncValueTest.assertTrue (Z)V | ICONST_2 (line 81) | ALOAD_0 // Lcom/wec/lib/util/test/SyncValueTest; this | GETFIELD com.wec.lib.util.test.SyncValueTest.e Lcom/wec/lib/util/test/SyncValueTest$SyncInteger; | INVOKEVIRTUAL com.wec.lib.util.test.SyncValueTest$SyncInteger.getValue ()Ljava/lang/Object; | CHECKCAST java.lang.Integer | INVOKEVIRTUAL java.lang.Integer.intValue ()I | IF_ICMPNE L44 | ICONST_1 | GOTO L45 | L44: ICONST_0 | L45: INVOKESTATIC com.wec.lib.util.test.SyncValueTest.assertTrue (Z)V | ALOAD_0 // Lcom/wec/lib/util/test/SyncValueTest; this (line 82) | GETFIELD com.wec.lib.util.test.SyncValueTest.d Lcom/wec/lib/util/test/SyncValueTest$SyncInteger; | INVOKEVIRTUAL com.wec.lib.util.test.SyncValueTest$SyncInteger.unlink ()V | ALOAD_0 // Lcom/wec/lib/util/test/SyncValueTest; this (line 83) | GETFIELD com.wec.lib.util.test.SyncValueTest.c Lcom/wec/lib/util/test/SyncValueTest$SyncInteger; | ICONST_1 | ANEWARRAY com.wec.lib.util.SyncValueGroup | DUP | ICONST_0 | ALOAD_0 // Lcom/wec/lib/util/test/SyncValueTest; this | GETFIELD com.wec.lib.util.test.SyncValueTest.d Lcom/wec/lib/util/test/SyncValueTest$SyncInteger; | AASTORE | INVOKEVIRTUAL com.wec.lib.util.test.SyncValueTest$SyncInteger.link ([Lcom/wec/lib/util/SyncValueGroup;)V | ALOAD_0 // Lcom/wec/lib/util/test/SyncValueTest; this (line 84) | GETFIELD com.wec.lib.util.test.SyncValueTest.a Lcom/wec/lib/util/test/SyncValueTest$SyncInteger; | ICONST_1 | INVOKESTATIC java.lang.Integer.valueOf (I)Ljava/lang/Integer; | INVOKEVIRTUAL com.wec.lib.util.test.SyncValueTest$SyncInteger.setValue (Ljava/lang/Object;)V | ICONST_1 (line 85) | ALOAD_0 // Lcom/wec/lib/util/test/SyncValueTest; this | GETFIELD com.wec.lib.util.test.SyncValueTest.a Lcom/wec/lib/util/test/SyncValueTest$SyncInteger; | INVOKEVIRTUAL com.wec.lib.util.test.SyncValueTest$SyncInteger.getValue ()Ljava/lang/Object; | CHECKCAST java.lang.Integer | INVOKEVIRTUAL java.lang.Integer.intValue ()I | IF_ICMPNE L46 | ICONST_1 | GOTO L47 | L46: ICONST_0 | L47: INVOKESTATIC com.wec.lib.util.test.SyncValueTest.assertTrue (Z)V | ICONST_1 (line 86) | ALOAD_0 // Lcom/wec/lib/util/test/SyncValueTest; this | GETFIELD com.wec.lib.util.test.SyncValueTest.b Lcom/wec/lib/util/test/SyncValueTest$SyncInteger; | INVOKEVIRTUAL com.wec.lib.util.test.SyncValueTest$SyncInteger.getValue ()Ljava/lang/Object; | CHECKCAST java.lang.Integer | INVOKEVIRTUAL java.lang.Integer.intValue ()I | IF_ICMPNE L48 | ICONST_1 | GOTO L49 | L48: ICONST_0 | L49: INVOKESTATIC com.wec.lib.util.test.SyncValueTest.assertTrue (Z)V | ICONST_3 (line 87) | ALOAD_0 // Lcom/wec/lib/util/test/SyncValueTest; this | GETFIELD com.wec.lib.util.test.SyncValueTest.c Lcom/wec/lib/util/test/SyncValueTest$SyncInteger; | INVOKEVIRTUAL com.wec.lib.util.test.SyncValueTest$SyncInteger.getValue ()Ljava/lang/Object; | CHECKCAST java.lang.Integer | INVOKEVIRTUAL java.lang.Integer.intValue ()I | IF_ICMPNE L50 | ICONST_1 | GOTO L51 | L50: ICONST_0 | L51: INVOKESTATIC com.wec.lib.util.test.SyncValueTest.assertTrue (Z)V | ICONST_3 (line 88) | ALOAD_0 // Lcom/wec/lib/util/test/SyncValueTest; this | GETFIELD com.wec.lib.util.test.SyncValueTest.d Lcom/wec/lib/util/test/SyncValueTest$SyncInteger; | INVOKEVIRTUAL com.wec.lib.util.test.SyncValueTest$SyncInteger.getValue ()Ljava/lang/Object; | CHECKCAST java.lang.Integer | INVOKEVIRTUAL java.lang.Integer.intValue ()I | IF_ICMPNE L52 | ICONST_1 | GOTO L53 | L52: ICONST_0 | L53: INVOKESTATIC com.wec.lib.util.test.SyncValueTest.assertTrue (Z)V | ICONST_1 (line 89) | ALOAD_0 // Lcom/wec/lib/util/test/SyncValueTest; this | GETFIELD com.wec.lib.util.test.SyncValueTest.e Lcom/wec/lib/util/test/SyncValueTest$SyncInteger; | INVOKEVIRTUAL com.wec.lib.util.test.SyncValueTest$SyncInteger.getValue ()Ljava/lang/Object; | CHECKCAST java.lang.Integer | INVOKEVIRTUAL java.lang.Integer.intValue ()I | IF_ICMPNE L54 | ICONST_1 | GOTO L55 | L54: ICONST_0 | L55: INVOKESTATIC com.wec.lib.util.test.SyncValueTest.assertTrue (Z)V | RETURN (line 90) method-execution(void com.wec.lib.util.test.SyncValueTest.testSyncValueGroup()) end public void testSyncValueGroup() end public class com.wec.lib.util.test.SyncValueTest when weaving classes when weaving when batch building BuildConfig[D:\workspace\.metadata\.plugins\org.eclipse.ajdt.core\ANSER2.generated.lst] #Files=365 Here's the class: package com.wec.lib.util.test; import static com.wec.ide.Constants.UNCHECKED; import junit.framework.TestCase; import org.junit.Test; import com.wec.lib.util.SyncValueGroup; import com.wec.scrum.Tests; /** * This class tests the SyncValueGroup utility class. */ @Tests(classes = { SyncValueGroup.class }) @SuppressWarnings("nls") public class SyncValueTest extends TestCase { class SyncInteger extends SyncValueGroup<Integer> { public SyncInteger(int val) { super(new Integer(val)); } public void valueChanged() { } } private SyncInteger a = new SyncInteger(1); private SyncInteger b = new SyncInteger(2); private SyncInteger c = new SyncInteger(3); private SyncInteger d = new SyncInteger(4); private SyncInteger e = new SyncInteger(5); /** * Ensures that SyncValueGroup replicates values and * calls valueChange. */ @SuppressWarnings(UNCHECKED) @Test public void testSyncValueGroup() { // Link tests a.link(b); assertTrue(a.getValue() == b.getValue()); assertTrue(1 == b.getValue()); b.setValue(2); assertTrue(2 == a.getValue()); b.link(c); assertTrue(2 == c.getValue()); c.setValue(3); assertTrue(3 == a.getValue()); assertTrue(3 == b.getValue()); a.setValue(4); assertTrue(4 == c.getValue()); assertTrue(4 == b.getValue()); b.setValue(1); assertTrue(1 == c.getValue()); assertTrue(1 == a.getValue()); d.link(e); assertTrue(d.getValue() == e.getValue()); // Join loops b.link(d); assertTrue(1 == d.getValue()); assertTrue(1 == e.getValue()); d.setValue(8); assertTrue(8 == a.getValue()); assertTrue(8 == b.getValue()); assertTrue(8 == c.getValue()); assertTrue(8 == d.getValue()); assertTrue(8 == e.getValue()); // Unlink tests c.unlink(); c.setValue(3); b.setValue(2); assertTrue(2 == a.getValue()); assertTrue(2 == b.getValue()); assertTrue(3 == c.getValue()); assertTrue(2 == d.getValue()); assertTrue(2 == e.getValue()); d.unlink(); c.link(d); a.setValue(1); assertTrue(1 == a.getValue()); assertTrue(1 == b.getValue()); assertTrue(3 == c.getValue()); assertTrue(3 == d.getValue()); assertTrue(1 == e.getValue()); } }
|
resolved fixed
|
ea4ff8a
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-09-29T12:20:31Z | 2006-09-25T18:46:40Z |
tests/bugs153/pr158624/ValueChange.java
| |
158,624 |
Bug 158624 Compiler Error: generics and arrays
|
OK, not sure what to report here or what info you need, but here's the set up, message, and erroreous class. I don't understand the errors from the compiler enough to parse down the erroneous file to something that contains only the bug, but I could if direction were given. Here's my set up: Eclipse SDK Version: 3.2.0 Build id: M20060629-1905 With AJDT: Eclipse AspectJ Development Tools Version: 1.4.1.200608141223 AspectJ version: 1.5.3.200608210848 Here's the bug dump from the compiler inside Eclipse: java.lang.UnsupportedOperationException at org.aspectj.weaver.UnresolvedType.parameterize(UnresolvedType.java:221) at org.aspectj.weaver.ResolvedMemberImpl.parameterize(ResolvedMemberImpl.java:680) at org.aspectj.weaver.ResolvedMemberImpl.parameterize(ResolvedMemberImpl.java:690) at org.aspectj.weaver.ResolvedMemberImpl.parameterizedWith(ResolvedMemberImpl.java:643) at org.aspectj.weaver.ResolvedMemberImpl.parameterizedWith(ResolvedMemberImpl.java:597) at org.aspectj.weaver.ReferenceType.getDeclaredMethods(ReferenceType.java:508) at org.aspectj.weaver.ResolvedType$4.get(ResolvedType.java:226) at org.aspectj.weaver.Iterators$3$1.hasNext(Iterators.java:118) at org.aspectj.weaver.Iterators$5.hasNext(Iterators.java:171) at org.aspectj.weaver.Iterators$3.hasNext(Iterators.java:128) at org.aspectj.weaver.ResolvedType.lookupMember(ResolvedType.java:346) at org.aspectj.weaver.ResolvedType.lookupMethod(ResolvedType.java:327) at org.aspectj.weaver.World.resolve(World.java:523) at org.aspectj.weaver.MemberImpl.resolve(MemberImpl.java:93) at org.aspectj.weaver.JoinPointSignatureIterator.addSignaturesUpToFirstDefiningMember(JoinPointSignatureIterator.java:109) at org.aspectj.weaver.JoinPointSignatureIterator.<init>(JoinPointSignatureIterator.java:51) at org.aspectj.weaver.MemberImpl.getJoinPointSignatures(MemberImpl.java:943) at org.aspectj.weaver.patterns.SignaturePattern.matches(SignaturePattern.java:286) at org.aspectj.weaver.patterns.KindedPointcut.matchInternal(KindedPointcut.java:106) at org.aspectj.weaver.patterns.Pointcut.match(Pointcut.java:146) at org.aspectj.weaver.patterns.AndPointcut.matchInternal(AndPointcut.java:51) 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:117) at org.aspectj.weaver.bcel.BcelClassWeaver.match(BcelClassWeaver.java:2806) at org.aspectj.weaver.bcel.BcelClassWeaver.matchInvokeInstruction(BcelClassWeaver.java:2768) 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:1606) at org.aspectj.weaver.bcel.BcelWeaver.weaveWithoutDump(BcelWeaver.java:1557) at org.aspectj.weaver.bcel.BcelWeaver.weaveAndNotify(BcelWeaver.java:1335) at org.aspectj.weaver.bcel.BcelWeaver.weave(BcelWeaver.java:1155) at org.aspectj.ajdt.internal.compiler.AjPipeliningCompilerAdapter.weaveQueuedEntries(AjPipeliningCompilerAdapter.java:455) at org.aspectj.ajdt.internal.compiler.AjPipeliningCompilerAdapter.queueForWeaving(AjPipeliningCompilerAdapter.java:392) at org.aspectj.ajdt.internal.compiler.AjPipeliningCompilerAdapter.afterProcessing(AjPipeliningCompilerAdapter.java:380) at org.aspectj.ajdt.internal.compiler.CompilerAdapter.ajc$after$org_aspectj_ajdt_internal_compiler_CompilerAdapter$5$6b855184(CompilerAdapter.aj:98) at org.aspectj.org.eclipse.jdt.internal.compiler.Compiler.process(Compiler.java:533) at org.aspectj.org.eclipse.jdt.internal.compiler.Compiler.compile(Compiler.java:329) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.performCompilation(AjBuildManager.java:892) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.doBuild(AjBuildManager.java:246) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.batchBuild(AjBuildManager.java:165) at org.aspectj.ajde.internal.CompilerAdapter.compile(CompilerAdapter.java:122) at org.aspectj.ajde.internal.AspectJBuildManager$CompilerThread.run(AspectJBuildManager.java:191) trouble in: public class com.wec.lib.util.test.SyncValueTest extends junit.framework.TestCase: private com.wec.lib.util.test.SyncValueTest$SyncInteger a private com.wec.lib.util.test.SyncValueTest$SyncInteger b private com.wec.lib.util.test.SyncValueTest$SyncInteger c private com.wec.lib.util.test.SyncValueTest$SyncInteger d private com.wec.lib.util.test.SyncValueTest$SyncInteger e public void <init>(): ALOAD_0 // Lcom/wec/lib/util/test/SyncValueTest; this (line 17) INVOKESPECIAL junit.framework.TestCase.<init> ()V constructor-execution(void com.wec.lib.util.test.SyncValueTest.<init>()) | ALOAD_0 // Lcom/wec/lib/util/test/SyncValueTest; this (line 27) | NEW com.wec.lib.util.test.SyncValueTest$SyncInteger | DUP | ALOAD_0 // Lcom/wec/lib/util/test/SyncValueTest; this | ICONST_1 | INVOKESPECIAL com.wec.lib.util.test.SyncValueTest$SyncInteger.<init> (Lcom/wec/lib/util/test/SyncValueTest;I)V | PUTFIELD com.wec.lib.util.test.SyncValueTest.a Lcom/wec/lib/util/test/SyncValueTest$SyncInteger; | ALOAD_0 // Lcom/wec/lib/util/test/SyncValueTest; this (line 28) | NEW com.wec.lib.util.test.SyncValueTest$SyncInteger | DUP | ALOAD_0 // Lcom/wec/lib/util/test/SyncValueTest; this | ICONST_2 | INVOKESPECIAL com.wec.lib.util.test.SyncValueTest$SyncInteger.<init> (Lcom/wec/lib/util/test/SyncValueTest;I)V | PUTFIELD com.wec.lib.util.test.SyncValueTest.b Lcom/wec/lib/util/test/SyncValueTest$SyncInteger; | ALOAD_0 // Lcom/wec/lib/util/test/SyncValueTest; this (line 29) | NEW com.wec.lib.util.test.SyncValueTest$SyncInteger | DUP | ALOAD_0 // Lcom/wec/lib/util/test/SyncValueTest; this | ICONST_3 | INVOKESPECIAL com.wec.lib.util.test.SyncValueTest$SyncInteger.<init> (Lcom/wec/lib/util/test/SyncValueTest;I)V | PUTFIELD com.wec.lib.util.test.SyncValueTest.c Lcom/wec/lib/util/test/SyncValueTest$SyncInteger; | ALOAD_0 // Lcom/wec/lib/util/test/SyncValueTest; this (line 30) | NEW com.wec.lib.util.test.SyncValueTest$SyncInteger | DUP | ALOAD_0 // Lcom/wec/lib/util/test/SyncValueTest; this | ICONST_4 | INVOKESPECIAL com.wec.lib.util.test.SyncValueTest$SyncInteger.<init> (Lcom/wec/lib/util/test/SyncValueTest;I)V | PUTFIELD com.wec.lib.util.test.SyncValueTest.d Lcom/wec/lib/util/test/SyncValueTest$SyncInteger; | ALOAD_0 // Lcom/wec/lib/util/test/SyncValueTest; this (line 31) | NEW com.wec.lib.util.test.SyncValueTest$SyncInteger | DUP | ALOAD_0 // Lcom/wec/lib/util/test/SyncValueTest; this | ICONST_5 | INVOKESPECIAL com.wec.lib.util.test.SyncValueTest$SyncInteger.<init> (Lcom/wec/lib/util/test/SyncValueTest;I)V | PUTFIELD com.wec.lib.util.test.SyncValueTest.e Lcom/wec/lib/util/test/SyncValueTest$SyncInteger; | RETURN (line 17) constructor-execution(void com.wec.lib.util.test.SyncValueTest.<init>()) end public void <init>() public void testSyncValueGroup() org.aspectj.weaver.MethodDeclarationLineNumber: 39:1035 : method-execution(void com.wec.lib.util.test.SyncValueTest.testSyncValueGroup()) | ALOAD_0 // Lcom/wec/lib/util/test/SyncValueTest; this (line 42) | GETFIELD com.wec.lib.util.test.SyncValueTest.a Lcom/wec/lib/util/test/SyncValueTest$SyncInteger; | ICONST_1 | ANEWARRAY com.wec.lib.util.SyncValueGroup | DUP | ICONST_0 | ALOAD_0 // Lcom/wec/lib/util/test/SyncValueTest; this | GETFIELD com.wec.lib.util.test.SyncValueTest.b Lcom/wec/lib/util/test/SyncValueTest$SyncInteger; | AASTORE | method-call(void com.wec.lib.util.test.SyncValueTest$SyncInteger.link(com.wec.lib.util.SyncValueGroup[])) | | INVOKEVIRTUAL com.wec.lib.util.test.SyncValueTest$SyncInteger.link ([Lcom/wec/lib/util/SyncValueGroup;)V | method-call(void com.wec.lib.util.test.SyncValueTest$SyncInteger.link(com.wec.lib.util.SyncValueGroup[])) | ALOAD_0 // Lcom/wec/lib/util/test/SyncValueTest; this (line 43) | GETFIELD com.wec.lib.util.test.SyncValueTest.a Lcom/wec/lib/util/test/SyncValueTest$SyncInteger; | INVOKEVIRTUAL com.wec.lib.util.test.SyncValueTest$SyncInteger.getValue ()Ljava/lang/Object; | ALOAD_0 // Lcom/wec/lib/util/test/SyncValueTest; this | GETFIELD com.wec.lib.util.test.SyncValueTest.b Lcom/wec/lib/util/test/SyncValueTest$SyncInteger; | INVOKEVIRTUAL com.wec.lib.util.test.SyncValueTest$SyncInteger.getValue ()Ljava/lang/Object; | IF_ACMPNE L0 | ICONST_1 | GOTO L1 | L0: ICONST_0 | L1: INVOKESTATIC com.wec.lib.util.test.SyncValueTest.assertTrue (Z)V | ICONST_1 (line 44) | ALOAD_0 // Lcom/wec/lib/util/test/SyncValueTest; this | GETFIELD com.wec.lib.util.test.SyncValueTest.b Lcom/wec/lib/util/test/SyncValueTest$SyncInteger; | INVOKEVIRTUAL com.wec.lib.util.test.SyncValueTest$SyncInteger.getValue ()Ljava/lang/Object; | CHECKCAST java.lang.Integer | INVOKEVIRTUAL java.lang.Integer.intValue ()I | IF_ICMPNE L2 | ICONST_1 | GOTO L3 | L2: ICONST_0 | L3: INVOKESTATIC com.wec.lib.util.test.SyncValueTest.assertTrue (Z)V | ALOAD_0 // Lcom/wec/lib/util/test/SyncValueTest; this (line 45) | GETFIELD com.wec.lib.util.test.SyncValueTest.b Lcom/wec/lib/util/test/SyncValueTest$SyncInteger; | ICONST_2 | INVOKESTATIC java.lang.Integer.valueOf (I)Ljava/lang/Integer; | INVOKEVIRTUAL com.wec.lib.util.test.SyncValueTest$SyncInteger.setValue (Ljava/lang/Object;)V | ICONST_2 (line 46) | ALOAD_0 // Lcom/wec/lib/util/test/SyncValueTest; this | GETFIELD com.wec.lib.util.test.SyncValueTest.a Lcom/wec/lib/util/test/SyncValueTest$SyncInteger; | INVOKEVIRTUAL com.wec.lib.util.test.SyncValueTest$SyncInteger.getValue ()Ljava/lang/Object; | CHECKCAST java.lang.Integer | INVOKEVIRTUAL java.lang.Integer.intValue ()I | IF_ICMPNE L4 | ICONST_1 | GOTO L5 | L4: ICONST_0 | L5: INVOKESTATIC com.wec.lib.util.test.SyncValueTest.assertTrue (Z)V | ALOAD_0 // Lcom/wec/lib/util/test/SyncValueTest; this (line 47) | GETFIELD com.wec.lib.util.test.SyncValueTest.b Lcom/wec/lib/util/test/SyncValueTest$SyncInteger; | ICONST_1 | ANEWARRAY com.wec.lib.util.SyncValueGroup | DUP | ICONST_0 | ALOAD_0 // Lcom/wec/lib/util/test/SyncValueTest; this | GETFIELD com.wec.lib.util.test.SyncValueTest.c Lcom/wec/lib/util/test/SyncValueTest$SyncInteger; | AASTORE | INVOKEVIRTUAL com.wec.lib.util.test.SyncValueTest$SyncInteger.link ([Lcom/wec/lib/util/SyncValueGroup;)V | ICONST_2 (line 48) | ALOAD_0 // Lcom/wec/lib/util/test/SyncValueTest; this | GETFIELD com.wec.lib.util.test.SyncValueTest.c Lcom/wec/lib/util/test/SyncValueTest$SyncInteger; | INVOKEVIRTUAL com.wec.lib.util.test.SyncValueTest$SyncInteger.getValue ()Ljava/lang/Object; | CHECKCAST java.lang.Integer | INVOKEVIRTUAL java.lang.Integer.intValue ()I | IF_ICMPNE L6 | ICONST_1 | GOTO L7 | L6: ICONST_0 | L7: INVOKESTATIC com.wec.lib.util.test.SyncValueTest.assertTrue (Z)V | ALOAD_0 // Lcom/wec/lib/util/test/SyncValueTest; this (line 49) | GETFIELD com.wec.lib.util.test.SyncValueTest.c Lcom/wec/lib/util/test/SyncValueTest$SyncInteger; | ICONST_3 | INVOKESTATIC java.lang.Integer.valueOf (I)Ljava/lang/Integer; | INVOKEVIRTUAL com.wec.lib.util.test.SyncValueTest$SyncInteger.setValue (Ljava/lang/Object;)V | ICONST_3 (line 50) | ALOAD_0 // Lcom/wec/lib/util/test/SyncValueTest; this | GETFIELD com.wec.lib.util.test.SyncValueTest.a Lcom/wec/lib/util/test/SyncValueTest$SyncInteger; | INVOKEVIRTUAL com.wec.lib.util.test.SyncValueTest$SyncInteger.getValue ()Ljava/lang/Object; | CHECKCAST java.lang.Integer | INVOKEVIRTUAL java.lang.Integer.intValue ()I | IF_ICMPNE L8 | ICONST_1 | GOTO L9 | L8: ICONST_0 | L9: INVOKESTATIC com.wec.lib.util.test.SyncValueTest.assertTrue (Z)V | ICONST_3 (line 51) | ALOAD_0 // Lcom/wec/lib/util/test/SyncValueTest; this | GETFIELD com.wec.lib.util.test.SyncValueTest.b Lcom/wec/lib/util/test/SyncValueTest$SyncInteger; | INVOKEVIRTUAL com.wec.lib.util.test.SyncValueTest$SyncInteger.getValue ()Ljava/lang/Object; | CHECKCAST java.lang.Integer | INVOKEVIRTUAL java.lang.Integer.intValue ()I | IF_ICMPNE L10 | ICONST_1 | GOTO L11 | L10: ICONST_0 | L11: INVOKESTATIC com.wec.lib.util.test.SyncValueTest.assertTrue (Z)V | ALOAD_0 // Lcom/wec/lib/util/test/SyncValueTest; this (line 52) | GETFIELD com.wec.lib.util.test.SyncValueTest.a Lcom/wec/lib/util/test/SyncValueTest$SyncInteger; | ICONST_4 | INVOKESTATIC java.lang.Integer.valueOf (I)Ljava/lang/Integer; | INVOKEVIRTUAL com.wec.lib.util.test.SyncValueTest$SyncInteger.setValue (Ljava/lang/Object;)V | ICONST_4 (line 53) | ALOAD_0 // Lcom/wec/lib/util/test/SyncValueTest; this | GETFIELD com.wec.lib.util.test.SyncValueTest.c Lcom/wec/lib/util/test/SyncValueTest$SyncInteger; | INVOKEVIRTUAL com.wec.lib.util.test.SyncValueTest$SyncInteger.getValue ()Ljava/lang/Object; | CHECKCAST java.lang.Integer | INVOKEVIRTUAL java.lang.Integer.intValue ()I | IF_ICMPNE L12 | ICONST_1 | GOTO L13 | L12: ICONST_0 | L13: INVOKESTATIC com.wec.lib.util.test.SyncValueTest.assertTrue (Z)V | ICONST_4 (line 54) | ALOAD_0 // Lcom/wec/lib/util/test/SyncValueTest; this | GETFIELD com.wec.lib.util.test.SyncValueTest.b Lcom/wec/lib/util/test/SyncValueTest$SyncInteger; | INVOKEVIRTUAL com.wec.lib.util.test.SyncValueTest$SyncInteger.getValue ()Ljava/lang/Object; | CHECKCAST java.lang.Integer | INVOKEVIRTUAL java.lang.Integer.intValue ()I | IF_ICMPNE L14 | ICONST_1 | GOTO L15 | L14: ICONST_0 | L15: INVOKESTATIC com.wec.lib.util.test.SyncValueTest.assertTrue (Z)V | ALOAD_0 // Lcom/wec/lib/util/test/SyncValueTest; this (line 55) | GETFIELD com.wec.lib.util.test.SyncValueTest.b Lcom/wec/lib/util/test/SyncValueTest$SyncInteger; | ICONST_1 | INVOKESTATIC java.lang.Integer.valueOf (I)Ljava/lang/Integer; | INVOKEVIRTUAL com.wec.lib.util.test.SyncValueTest$SyncInteger.setValue (Ljava/lang/Object;)V | ICONST_1 (line 56) | ALOAD_0 // Lcom/wec/lib/util/test/SyncValueTest; this | GETFIELD com.wec.lib.util.test.SyncValueTest.c Lcom/wec/lib/util/test/SyncValueTest$SyncInteger; | INVOKEVIRTUAL com.wec.lib.util.test.SyncValueTest$SyncInteger.getValue ()Ljava/lang/Object; | CHECKCAST java.lang.Integer | INVOKEVIRTUAL java.lang.Integer.intValue ()I | IF_ICMPNE L16 | ICONST_1 | GOTO L17 | L16: ICONST_0 | L17: INVOKESTATIC com.wec.lib.util.test.SyncValueTest.assertTrue (Z)V | ICONST_1 (line 57) | ALOAD_0 // Lcom/wec/lib/util/test/SyncValueTest; this | GETFIELD com.wec.lib.util.test.SyncValueTest.a Lcom/wec/lib/util/test/SyncValueTest$SyncInteger; | INVOKEVIRTUAL com.wec.lib.util.test.SyncValueTest$SyncInteger.getValue ()Ljava/lang/Object; | CHECKCAST java.lang.Integer | INVOKEVIRTUAL java.lang.Integer.intValue ()I | IF_ICMPNE L18 | ICONST_1 | GOTO L19 | L18: ICONST_0 | L19: INVOKESTATIC com.wec.lib.util.test.SyncValueTest.assertTrue (Z)V | ALOAD_0 // Lcom/wec/lib/util/test/SyncValueTest; this (line 59) | GETFIELD com.wec.lib.util.test.SyncValueTest.d Lcom/wec/lib/util/test/SyncValueTest$SyncInteger; | ICONST_1 | ANEWARRAY com.wec.lib.util.SyncValueGroup | DUP | ICONST_0 | ALOAD_0 // Lcom/wec/lib/util/test/SyncValueTest; this | GETFIELD com.wec.lib.util.test.SyncValueTest.e Lcom/wec/lib/util/test/SyncValueTest$SyncInteger; | AASTORE | INVOKEVIRTUAL com.wec.lib.util.test.SyncValueTest$SyncInteger.link ([Lcom/wec/lib/util/SyncValueGroup;)V | ALOAD_0 // Lcom/wec/lib/util/test/SyncValueTest; this (line 60) | GETFIELD com.wec.lib.util.test.SyncValueTest.d Lcom/wec/lib/util/test/SyncValueTest$SyncInteger; | INVOKEVIRTUAL com.wec.lib.util.test.SyncValueTest$SyncInteger.getValue ()Ljava/lang/Object; | ALOAD_0 // Lcom/wec/lib/util/test/SyncValueTest; this | GETFIELD com.wec.lib.util.test.SyncValueTest.e Lcom/wec/lib/util/test/SyncValueTest$SyncInteger; | INVOKEVIRTUAL com.wec.lib.util.test.SyncValueTest$SyncInteger.getValue ()Ljava/lang/Object; | IF_ACMPNE L20 | ICONST_1 | GOTO L21 | L20: ICONST_0 | L21: INVOKESTATIC com.wec.lib.util.test.SyncValueTest.assertTrue (Z)V | ALOAD_0 // Lcom/wec/lib/util/test/SyncValueTest; this (line 63) | GETFIELD com.wec.lib.util.test.SyncValueTest.b Lcom/wec/lib/util/test/SyncValueTest$SyncInteger; | ICONST_1 | ANEWARRAY com.wec.lib.util.SyncValueGroup | DUP | ICONST_0 | ALOAD_0 // Lcom/wec/lib/util/test/SyncValueTest; this | GETFIELD com.wec.lib.util.test.SyncValueTest.d Lcom/wec/lib/util/test/SyncValueTest$SyncInteger; | AASTORE | INVOKEVIRTUAL com.wec.lib.util.test.SyncValueTest$SyncInteger.link ([Lcom/wec/lib/util/SyncValueGroup;)V | ICONST_1 (line 64) | ALOAD_0 // Lcom/wec/lib/util/test/SyncValueTest; this | GETFIELD com.wec.lib.util.test.SyncValueTest.d Lcom/wec/lib/util/test/SyncValueTest$SyncInteger; | INVOKEVIRTUAL com.wec.lib.util.test.SyncValueTest$SyncInteger.getValue ()Ljava/lang/Object; | CHECKCAST java.lang.Integer | INVOKEVIRTUAL java.lang.Integer.intValue ()I | IF_ICMPNE L22 | ICONST_1 | GOTO L23 | L22: ICONST_0 | L23: INVOKESTATIC com.wec.lib.util.test.SyncValueTest.assertTrue (Z)V | ICONST_1 (line 65) | ALOAD_0 // Lcom/wec/lib/util/test/SyncValueTest; this | GETFIELD com.wec.lib.util.test.SyncValueTest.e Lcom/wec/lib/util/test/SyncValueTest$SyncInteger; | INVOKEVIRTUAL com.wec.lib.util.test.SyncValueTest$SyncInteger.getValue ()Ljava/lang/Object; | CHECKCAST java.lang.Integer | INVOKEVIRTUAL java.lang.Integer.intValue ()I | IF_ICMPNE L24 | ICONST_1 | GOTO L25 | L24: ICONST_0 | L25: INVOKESTATIC com.wec.lib.util.test.SyncValueTest.assertTrue (Z)V | ALOAD_0 // Lcom/wec/lib/util/test/SyncValueTest; this (line 66) | GETFIELD com.wec.lib.util.test.SyncValueTest.d Lcom/wec/lib/util/test/SyncValueTest$SyncInteger; | BIPUSH 8 | INVOKESTATIC java.lang.Integer.valueOf (I)Ljava/lang/Integer; | INVOKEVIRTUAL com.wec.lib.util.test.SyncValueTest$SyncInteger.setValue (Ljava/lang/Object;)V | BIPUSH 8 (line 67) | ALOAD_0 // Lcom/wec/lib/util/test/SyncValueTest; this | GETFIELD com.wec.lib.util.test.SyncValueTest.a Lcom/wec/lib/util/test/SyncValueTest$SyncInteger; | INVOKEVIRTUAL com.wec.lib.util.test.SyncValueTest$SyncInteger.getValue ()Ljava/lang/Object; | CHECKCAST java.lang.Integer | INVOKEVIRTUAL java.lang.Integer.intValue ()I | IF_ICMPNE L26 | ICONST_1 | GOTO L27 | L26: ICONST_0 | L27: INVOKESTATIC com.wec.lib.util.test.SyncValueTest.assertTrue (Z)V | BIPUSH 8 (line 68) | ALOAD_0 // Lcom/wec/lib/util/test/SyncValueTest; this | GETFIELD com.wec.lib.util.test.SyncValueTest.b Lcom/wec/lib/util/test/SyncValueTest$SyncInteger; | INVOKEVIRTUAL com.wec.lib.util.test.SyncValueTest$SyncInteger.getValue ()Ljava/lang/Object; | CHECKCAST java.lang.Integer | INVOKEVIRTUAL java.lang.Integer.intValue ()I | IF_ICMPNE L28 | ICONST_1 | GOTO L29 | L28: ICONST_0 | L29: INVOKESTATIC com.wec.lib.util.test.SyncValueTest.assertTrue (Z)V | BIPUSH 8 (line 69) | ALOAD_0 // Lcom/wec/lib/util/test/SyncValueTest; this | GETFIELD com.wec.lib.util.test.SyncValueTest.c Lcom/wec/lib/util/test/SyncValueTest$SyncInteger; | INVOKEVIRTUAL com.wec.lib.util.test.SyncValueTest$SyncInteger.getValue ()Ljava/lang/Object; | CHECKCAST java.lang.Integer | INVOKEVIRTUAL java.lang.Integer.intValue ()I | IF_ICMPNE L30 | ICONST_1 | GOTO L31 | L30: ICONST_0 | L31: INVOKESTATIC com.wec.lib.util.test.SyncValueTest.assertTrue (Z)V | BIPUSH 8 (line 70) | ALOAD_0 // Lcom/wec/lib/util/test/SyncValueTest; this | GETFIELD com.wec.lib.util.test.SyncValueTest.d Lcom/wec/lib/util/test/SyncValueTest$SyncInteger; | INVOKEVIRTUAL com.wec.lib.util.test.SyncValueTest$SyncInteger.getValue ()Ljava/lang/Object; | CHECKCAST java.lang.Integer | INVOKEVIRTUAL java.lang.Integer.intValue ()I | IF_ICMPNE L32 | ICONST_1 | GOTO L33 | L32: ICONST_0 | L33: INVOKESTATIC com.wec.lib.util.test.SyncValueTest.assertTrue (Z)V | BIPUSH 8 (line 71) | ALOAD_0 // Lcom/wec/lib/util/test/SyncValueTest; this | GETFIELD com.wec.lib.util.test.SyncValueTest.e Lcom/wec/lib/util/test/SyncValueTest$SyncInteger; | INVOKEVIRTUAL com.wec.lib.util.test.SyncValueTest$SyncInteger.getValue ()Ljava/lang/Object; | CHECKCAST java.lang.Integer | INVOKEVIRTUAL java.lang.Integer.intValue ()I | IF_ICMPNE L34 | ICONST_1 | GOTO L35 | L34: ICONST_0 | L35: INVOKESTATIC com.wec.lib.util.test.SyncValueTest.assertTrue (Z)V | ALOAD_0 // Lcom/wec/lib/util/test/SyncValueTest; this (line 74) | GETFIELD com.wec.lib.util.test.SyncValueTest.c Lcom/wec/lib/util/test/SyncValueTest$SyncInteger; | INVOKEVIRTUAL com.wec.lib.util.test.SyncValueTest$SyncInteger.unlink ()V | ALOAD_0 // Lcom/wec/lib/util/test/SyncValueTest; this (line 75) | GETFIELD com.wec.lib.util.test.SyncValueTest.c Lcom/wec/lib/util/test/SyncValueTest$SyncInteger; | ICONST_3 | INVOKESTATIC java.lang.Integer.valueOf (I)Ljava/lang/Integer; | INVOKEVIRTUAL com.wec.lib.util.test.SyncValueTest$SyncInteger.setValue (Ljava/lang/Object;)V | ALOAD_0 // Lcom/wec/lib/util/test/SyncValueTest; this (line 76) | GETFIELD com.wec.lib.util.test.SyncValueTest.b Lcom/wec/lib/util/test/SyncValueTest$SyncInteger; | ICONST_2 | INVOKESTATIC java.lang.Integer.valueOf (I)Ljava/lang/Integer; | INVOKEVIRTUAL com.wec.lib.util.test.SyncValueTest$SyncInteger.setValue (Ljava/lang/Object;)V | ICONST_2 (line 77) | ALOAD_0 // Lcom/wec/lib/util/test/SyncValueTest; this | GETFIELD com.wec.lib.util.test.SyncValueTest.a Lcom/wec/lib/util/test/SyncValueTest$SyncInteger; | INVOKEVIRTUAL com.wec.lib.util.test.SyncValueTest$SyncInteger.getValue ()Ljava/lang/Object; | CHECKCAST java.lang.Integer | INVOKEVIRTUAL java.lang.Integer.intValue ()I | IF_ICMPNE L36 | ICONST_1 | GOTO L37 | L36: ICONST_0 | L37: INVOKESTATIC com.wec.lib.util.test.SyncValueTest.assertTrue (Z)V | ICONST_2 (line 78) | ALOAD_0 // Lcom/wec/lib/util/test/SyncValueTest; this | GETFIELD com.wec.lib.util.test.SyncValueTest.b Lcom/wec/lib/util/test/SyncValueTest$SyncInteger; | INVOKEVIRTUAL com.wec.lib.util.test.SyncValueTest$SyncInteger.getValue ()Ljava/lang/Object; | CHECKCAST java.lang.Integer | INVOKEVIRTUAL java.lang.Integer.intValue ()I | IF_ICMPNE L38 | ICONST_1 | GOTO L39 | L38: ICONST_0 | L39: INVOKESTATIC com.wec.lib.util.test.SyncValueTest.assertTrue (Z)V | ICONST_3 (line 79) | ALOAD_0 // Lcom/wec/lib/util/test/SyncValueTest; this | GETFIELD com.wec.lib.util.test.SyncValueTest.c Lcom/wec/lib/util/test/SyncValueTest$SyncInteger; | INVOKEVIRTUAL com.wec.lib.util.test.SyncValueTest$SyncInteger.getValue ()Ljava/lang/Object; | CHECKCAST java.lang.Integer | INVOKEVIRTUAL java.lang.Integer.intValue ()I | IF_ICMPNE L40 | ICONST_1 | GOTO L41 | L40: ICONST_0 | L41: INVOKESTATIC com.wec.lib.util.test.SyncValueTest.assertTrue (Z)V | ICONST_2 (line 80) | ALOAD_0 // Lcom/wec/lib/util/test/SyncValueTest; this | GETFIELD com.wec.lib.util.test.SyncValueTest.d Lcom/wec/lib/util/test/SyncValueTest$SyncInteger; | INVOKEVIRTUAL com.wec.lib.util.test.SyncValueTest$SyncInteger.getValue ()Ljava/lang/Object; | CHECKCAST java.lang.Integer | INVOKEVIRTUAL java.lang.Integer.intValue ()I | IF_ICMPNE L42 | ICONST_1 | GOTO L43 | L42: ICONST_0 | L43: INVOKESTATIC com.wec.lib.util.test.SyncValueTest.assertTrue (Z)V | ICONST_2 (line 81) | ALOAD_0 // Lcom/wec/lib/util/test/SyncValueTest; this | GETFIELD com.wec.lib.util.test.SyncValueTest.e Lcom/wec/lib/util/test/SyncValueTest$SyncInteger; | INVOKEVIRTUAL com.wec.lib.util.test.SyncValueTest$SyncInteger.getValue ()Ljava/lang/Object; | CHECKCAST java.lang.Integer | INVOKEVIRTUAL java.lang.Integer.intValue ()I | IF_ICMPNE L44 | ICONST_1 | GOTO L45 | L44: ICONST_0 | L45: INVOKESTATIC com.wec.lib.util.test.SyncValueTest.assertTrue (Z)V | ALOAD_0 // Lcom/wec/lib/util/test/SyncValueTest; this (line 82) | GETFIELD com.wec.lib.util.test.SyncValueTest.d Lcom/wec/lib/util/test/SyncValueTest$SyncInteger; | INVOKEVIRTUAL com.wec.lib.util.test.SyncValueTest$SyncInteger.unlink ()V | ALOAD_0 // Lcom/wec/lib/util/test/SyncValueTest; this (line 83) | GETFIELD com.wec.lib.util.test.SyncValueTest.c Lcom/wec/lib/util/test/SyncValueTest$SyncInteger; | ICONST_1 | ANEWARRAY com.wec.lib.util.SyncValueGroup | DUP | ICONST_0 | ALOAD_0 // Lcom/wec/lib/util/test/SyncValueTest; this | GETFIELD com.wec.lib.util.test.SyncValueTest.d Lcom/wec/lib/util/test/SyncValueTest$SyncInteger; | AASTORE | INVOKEVIRTUAL com.wec.lib.util.test.SyncValueTest$SyncInteger.link ([Lcom/wec/lib/util/SyncValueGroup;)V | ALOAD_0 // Lcom/wec/lib/util/test/SyncValueTest; this (line 84) | GETFIELD com.wec.lib.util.test.SyncValueTest.a Lcom/wec/lib/util/test/SyncValueTest$SyncInteger; | ICONST_1 | INVOKESTATIC java.lang.Integer.valueOf (I)Ljava/lang/Integer; | INVOKEVIRTUAL com.wec.lib.util.test.SyncValueTest$SyncInteger.setValue (Ljava/lang/Object;)V | ICONST_1 (line 85) | ALOAD_0 // Lcom/wec/lib/util/test/SyncValueTest; this | GETFIELD com.wec.lib.util.test.SyncValueTest.a Lcom/wec/lib/util/test/SyncValueTest$SyncInteger; | INVOKEVIRTUAL com.wec.lib.util.test.SyncValueTest$SyncInteger.getValue ()Ljava/lang/Object; | CHECKCAST java.lang.Integer | INVOKEVIRTUAL java.lang.Integer.intValue ()I | IF_ICMPNE L46 | ICONST_1 | GOTO L47 | L46: ICONST_0 | L47: INVOKESTATIC com.wec.lib.util.test.SyncValueTest.assertTrue (Z)V | ICONST_1 (line 86) | ALOAD_0 // Lcom/wec/lib/util/test/SyncValueTest; this | GETFIELD com.wec.lib.util.test.SyncValueTest.b Lcom/wec/lib/util/test/SyncValueTest$SyncInteger; | INVOKEVIRTUAL com.wec.lib.util.test.SyncValueTest$SyncInteger.getValue ()Ljava/lang/Object; | CHECKCAST java.lang.Integer | INVOKEVIRTUAL java.lang.Integer.intValue ()I | IF_ICMPNE L48 | ICONST_1 | GOTO L49 | L48: ICONST_0 | L49: INVOKESTATIC com.wec.lib.util.test.SyncValueTest.assertTrue (Z)V | ICONST_3 (line 87) | ALOAD_0 // Lcom/wec/lib/util/test/SyncValueTest; this | GETFIELD com.wec.lib.util.test.SyncValueTest.c Lcom/wec/lib/util/test/SyncValueTest$SyncInteger; | INVOKEVIRTUAL com.wec.lib.util.test.SyncValueTest$SyncInteger.getValue ()Ljava/lang/Object; | CHECKCAST java.lang.Integer | INVOKEVIRTUAL java.lang.Integer.intValue ()I | IF_ICMPNE L50 | ICONST_1 | GOTO L51 | L50: ICONST_0 | L51: INVOKESTATIC com.wec.lib.util.test.SyncValueTest.assertTrue (Z)V | ICONST_3 (line 88) | ALOAD_0 // Lcom/wec/lib/util/test/SyncValueTest; this | GETFIELD com.wec.lib.util.test.SyncValueTest.d Lcom/wec/lib/util/test/SyncValueTest$SyncInteger; | INVOKEVIRTUAL com.wec.lib.util.test.SyncValueTest$SyncInteger.getValue ()Ljava/lang/Object; | CHECKCAST java.lang.Integer | INVOKEVIRTUAL java.lang.Integer.intValue ()I | IF_ICMPNE L52 | ICONST_1 | GOTO L53 | L52: ICONST_0 | L53: INVOKESTATIC com.wec.lib.util.test.SyncValueTest.assertTrue (Z)V | ICONST_1 (line 89) | ALOAD_0 // Lcom/wec/lib/util/test/SyncValueTest; this | GETFIELD com.wec.lib.util.test.SyncValueTest.e Lcom/wec/lib/util/test/SyncValueTest$SyncInteger; | INVOKEVIRTUAL com.wec.lib.util.test.SyncValueTest$SyncInteger.getValue ()Ljava/lang/Object; | CHECKCAST java.lang.Integer | INVOKEVIRTUAL java.lang.Integer.intValue ()I | IF_ICMPNE L54 | ICONST_1 | GOTO L55 | L54: ICONST_0 | L55: INVOKESTATIC com.wec.lib.util.test.SyncValueTest.assertTrue (Z)V | RETURN (line 90) method-execution(void com.wec.lib.util.test.SyncValueTest.testSyncValueGroup()) end public void testSyncValueGroup() end public class com.wec.lib.util.test.SyncValueTest when weaving classes when weaving when batch building BuildConfig[D:\workspace\.metadata\.plugins\org.eclipse.ajdt.core\ANSER2.generated.lst] #Files=365 Here's the class: package com.wec.lib.util.test; import static com.wec.ide.Constants.UNCHECKED; import junit.framework.TestCase; import org.junit.Test; import com.wec.lib.util.SyncValueGroup; import com.wec.scrum.Tests; /** * This class tests the SyncValueGroup utility class. */ @Tests(classes = { SyncValueGroup.class }) @SuppressWarnings("nls") public class SyncValueTest extends TestCase { class SyncInteger extends SyncValueGroup<Integer> { public SyncInteger(int val) { super(new Integer(val)); } public void valueChanged() { } } private SyncInteger a = new SyncInteger(1); private SyncInteger b = new SyncInteger(2); private SyncInteger c = new SyncInteger(3); private SyncInteger d = new SyncInteger(4); private SyncInteger e = new SyncInteger(5); /** * Ensures that SyncValueGroup replicates values and * calls valueChange. */ @SuppressWarnings(UNCHECKED) @Test public void testSyncValueGroup() { // Link tests a.link(b); assertTrue(a.getValue() == b.getValue()); assertTrue(1 == b.getValue()); b.setValue(2); assertTrue(2 == a.getValue()); b.link(c); assertTrue(2 == c.getValue()); c.setValue(3); assertTrue(3 == a.getValue()); assertTrue(3 == b.getValue()); a.setValue(4); assertTrue(4 == c.getValue()); assertTrue(4 == b.getValue()); b.setValue(1); assertTrue(1 == c.getValue()); assertTrue(1 == a.getValue()); d.link(e); assertTrue(d.getValue() == e.getValue()); // Join loops b.link(d); assertTrue(1 == d.getValue()); assertTrue(1 == e.getValue()); d.setValue(8); assertTrue(8 == a.getValue()); assertTrue(8 == b.getValue()); assertTrue(8 == c.getValue()); assertTrue(8 == d.getValue()); assertTrue(8 == e.getValue()); // Unlink tests c.unlink(); c.setValue(3); b.setValue(2); assertTrue(2 == a.getValue()); assertTrue(2 == b.getValue()); assertTrue(3 == c.getValue()); assertTrue(2 == d.getValue()); assertTrue(2 == e.getValue()); d.unlink(); c.link(d); a.setValue(1); assertTrue(1 == a.getValue()); assertTrue(1 == b.getValue()); assertTrue(3 == c.getValue()); assertTrue(3 == d.getValue()); assertTrue(1 == e.getValue()); } }
|
resolved fixed
|
ea4ff8a
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-09-29T12:20:31Z | 2006-09-25T18:46: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 testMissingLineNumbersInStacktraceAfter_pr145442() { runTest("missing line numbers in stacktrace after");}
// public void testMissingLineNumbersInStacktraceAround_pr145442() { runTest("missing line numbers in stacktrace around");}
// public void testArgnamesAndJavac_pr148381() { runTest("argNames and javac");}
// public void testCFlowXMLAspectLTW_pr149096() { runTest("cflow xml concrete aspect"); }
// public void testAmbiguousBinding_pr121805() { runTest("ambiguous binding");}
// public void testNoIllegalStateExceptionWithGenericInnerAspect_pr156058() { runTest("no IllegalStateException with generic inner aspect"); }
// public void testNegatedAnnotationMatchingProblem_pr153464() { runTest("negated annotation matching problem");}
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 testVisibilityProblem_pr149071() { runTest("visibility problem");}
// public void testAdviceNotWovenAspectPath_pr147841() { runTest("advice not woven on aspectpath");}
public void testGenericSignatures_pr148409() { runTest("generic signature problem"); }
// public void testBrokenIfArgsCflowAtAj_pr145018() { runTest("ataj crashing with cflow, if and args");}
public void testCantFindType_pr149322_01() {runTest("can't find type on interface call 1");}
public void testCantFindType_pr149322_02() {runTest("can't find type on interface call 2");}
public void testCantFindType_pr149322_03() {runTest("can't find type on interface call 3");}
public void 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 static Test suite() {
return XMLBasedAjcTestCase.loadSuite(Ajc153Tests.class);
}
protected File getSpecFile() {
return new File("../tests/src/org/aspectj/systemtest/ajc153/ajc153.xml");
}
}
|
158,624 |
Bug 158624 Compiler Error: generics and arrays
|
OK, not sure what to report here or what info you need, but here's the set up, message, and erroreous class. I don't understand the errors from the compiler enough to parse down the erroneous file to something that contains only the bug, but I could if direction were given. Here's my set up: Eclipse SDK Version: 3.2.0 Build id: M20060629-1905 With AJDT: Eclipse AspectJ Development Tools Version: 1.4.1.200608141223 AspectJ version: 1.5.3.200608210848 Here's the bug dump from the compiler inside Eclipse: java.lang.UnsupportedOperationException at org.aspectj.weaver.UnresolvedType.parameterize(UnresolvedType.java:221) at org.aspectj.weaver.ResolvedMemberImpl.parameterize(ResolvedMemberImpl.java:680) at org.aspectj.weaver.ResolvedMemberImpl.parameterize(ResolvedMemberImpl.java:690) at org.aspectj.weaver.ResolvedMemberImpl.parameterizedWith(ResolvedMemberImpl.java:643) at org.aspectj.weaver.ResolvedMemberImpl.parameterizedWith(ResolvedMemberImpl.java:597) at org.aspectj.weaver.ReferenceType.getDeclaredMethods(ReferenceType.java:508) at org.aspectj.weaver.ResolvedType$4.get(ResolvedType.java:226) at org.aspectj.weaver.Iterators$3$1.hasNext(Iterators.java:118) at org.aspectj.weaver.Iterators$5.hasNext(Iterators.java:171) at org.aspectj.weaver.Iterators$3.hasNext(Iterators.java:128) at org.aspectj.weaver.ResolvedType.lookupMember(ResolvedType.java:346) at org.aspectj.weaver.ResolvedType.lookupMethod(ResolvedType.java:327) at org.aspectj.weaver.World.resolve(World.java:523) at org.aspectj.weaver.MemberImpl.resolve(MemberImpl.java:93) at org.aspectj.weaver.JoinPointSignatureIterator.addSignaturesUpToFirstDefiningMember(JoinPointSignatureIterator.java:109) at org.aspectj.weaver.JoinPointSignatureIterator.<init>(JoinPointSignatureIterator.java:51) at org.aspectj.weaver.MemberImpl.getJoinPointSignatures(MemberImpl.java:943) at org.aspectj.weaver.patterns.SignaturePattern.matches(SignaturePattern.java:286) at org.aspectj.weaver.patterns.KindedPointcut.matchInternal(KindedPointcut.java:106) at org.aspectj.weaver.patterns.Pointcut.match(Pointcut.java:146) at org.aspectj.weaver.patterns.AndPointcut.matchInternal(AndPointcut.java:51) 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:117) at org.aspectj.weaver.bcel.BcelClassWeaver.match(BcelClassWeaver.java:2806) at org.aspectj.weaver.bcel.BcelClassWeaver.matchInvokeInstruction(BcelClassWeaver.java:2768) 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:1606) at org.aspectj.weaver.bcel.BcelWeaver.weaveWithoutDump(BcelWeaver.java:1557) at org.aspectj.weaver.bcel.BcelWeaver.weaveAndNotify(BcelWeaver.java:1335) at org.aspectj.weaver.bcel.BcelWeaver.weave(BcelWeaver.java:1155) at org.aspectj.ajdt.internal.compiler.AjPipeliningCompilerAdapter.weaveQueuedEntries(AjPipeliningCompilerAdapter.java:455) at org.aspectj.ajdt.internal.compiler.AjPipeliningCompilerAdapter.queueForWeaving(AjPipeliningCompilerAdapter.java:392) at org.aspectj.ajdt.internal.compiler.AjPipeliningCompilerAdapter.afterProcessing(AjPipeliningCompilerAdapter.java:380) at org.aspectj.ajdt.internal.compiler.CompilerAdapter.ajc$after$org_aspectj_ajdt_internal_compiler_CompilerAdapter$5$6b855184(CompilerAdapter.aj:98) at org.aspectj.org.eclipse.jdt.internal.compiler.Compiler.process(Compiler.java:533) at org.aspectj.org.eclipse.jdt.internal.compiler.Compiler.compile(Compiler.java:329) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.performCompilation(AjBuildManager.java:892) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.doBuild(AjBuildManager.java:246) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.batchBuild(AjBuildManager.java:165) at org.aspectj.ajde.internal.CompilerAdapter.compile(CompilerAdapter.java:122) at org.aspectj.ajde.internal.AspectJBuildManager$CompilerThread.run(AspectJBuildManager.java:191) trouble in: public class com.wec.lib.util.test.SyncValueTest extends junit.framework.TestCase: private com.wec.lib.util.test.SyncValueTest$SyncInteger a private com.wec.lib.util.test.SyncValueTest$SyncInteger b private com.wec.lib.util.test.SyncValueTest$SyncInteger c private com.wec.lib.util.test.SyncValueTest$SyncInteger d private com.wec.lib.util.test.SyncValueTest$SyncInteger e public void <init>(): ALOAD_0 // Lcom/wec/lib/util/test/SyncValueTest; this (line 17) INVOKESPECIAL junit.framework.TestCase.<init> ()V constructor-execution(void com.wec.lib.util.test.SyncValueTest.<init>()) | ALOAD_0 // Lcom/wec/lib/util/test/SyncValueTest; this (line 27) | NEW com.wec.lib.util.test.SyncValueTest$SyncInteger | DUP | ALOAD_0 // Lcom/wec/lib/util/test/SyncValueTest; this | ICONST_1 | INVOKESPECIAL com.wec.lib.util.test.SyncValueTest$SyncInteger.<init> (Lcom/wec/lib/util/test/SyncValueTest;I)V | PUTFIELD com.wec.lib.util.test.SyncValueTest.a Lcom/wec/lib/util/test/SyncValueTest$SyncInteger; | ALOAD_0 // Lcom/wec/lib/util/test/SyncValueTest; this (line 28) | NEW com.wec.lib.util.test.SyncValueTest$SyncInteger | DUP | ALOAD_0 // Lcom/wec/lib/util/test/SyncValueTest; this | ICONST_2 | INVOKESPECIAL com.wec.lib.util.test.SyncValueTest$SyncInteger.<init> (Lcom/wec/lib/util/test/SyncValueTest;I)V | PUTFIELD com.wec.lib.util.test.SyncValueTest.b Lcom/wec/lib/util/test/SyncValueTest$SyncInteger; | ALOAD_0 // Lcom/wec/lib/util/test/SyncValueTest; this (line 29) | NEW com.wec.lib.util.test.SyncValueTest$SyncInteger | DUP | ALOAD_0 // Lcom/wec/lib/util/test/SyncValueTest; this | ICONST_3 | INVOKESPECIAL com.wec.lib.util.test.SyncValueTest$SyncInteger.<init> (Lcom/wec/lib/util/test/SyncValueTest;I)V | PUTFIELD com.wec.lib.util.test.SyncValueTest.c Lcom/wec/lib/util/test/SyncValueTest$SyncInteger; | ALOAD_0 // Lcom/wec/lib/util/test/SyncValueTest; this (line 30) | NEW com.wec.lib.util.test.SyncValueTest$SyncInteger | DUP | ALOAD_0 // Lcom/wec/lib/util/test/SyncValueTest; this | ICONST_4 | INVOKESPECIAL com.wec.lib.util.test.SyncValueTest$SyncInteger.<init> (Lcom/wec/lib/util/test/SyncValueTest;I)V | PUTFIELD com.wec.lib.util.test.SyncValueTest.d Lcom/wec/lib/util/test/SyncValueTest$SyncInteger; | ALOAD_0 // Lcom/wec/lib/util/test/SyncValueTest; this (line 31) | NEW com.wec.lib.util.test.SyncValueTest$SyncInteger | DUP | ALOAD_0 // Lcom/wec/lib/util/test/SyncValueTest; this | ICONST_5 | INVOKESPECIAL com.wec.lib.util.test.SyncValueTest$SyncInteger.<init> (Lcom/wec/lib/util/test/SyncValueTest;I)V | PUTFIELD com.wec.lib.util.test.SyncValueTest.e Lcom/wec/lib/util/test/SyncValueTest$SyncInteger; | RETURN (line 17) constructor-execution(void com.wec.lib.util.test.SyncValueTest.<init>()) end public void <init>() public void testSyncValueGroup() org.aspectj.weaver.MethodDeclarationLineNumber: 39:1035 : method-execution(void com.wec.lib.util.test.SyncValueTest.testSyncValueGroup()) | ALOAD_0 // Lcom/wec/lib/util/test/SyncValueTest; this (line 42) | GETFIELD com.wec.lib.util.test.SyncValueTest.a Lcom/wec/lib/util/test/SyncValueTest$SyncInteger; | ICONST_1 | ANEWARRAY com.wec.lib.util.SyncValueGroup | DUP | ICONST_0 | ALOAD_0 // Lcom/wec/lib/util/test/SyncValueTest; this | GETFIELD com.wec.lib.util.test.SyncValueTest.b Lcom/wec/lib/util/test/SyncValueTest$SyncInteger; | AASTORE | method-call(void com.wec.lib.util.test.SyncValueTest$SyncInteger.link(com.wec.lib.util.SyncValueGroup[])) | | INVOKEVIRTUAL com.wec.lib.util.test.SyncValueTest$SyncInteger.link ([Lcom/wec/lib/util/SyncValueGroup;)V | method-call(void com.wec.lib.util.test.SyncValueTest$SyncInteger.link(com.wec.lib.util.SyncValueGroup[])) | ALOAD_0 // Lcom/wec/lib/util/test/SyncValueTest; this (line 43) | GETFIELD com.wec.lib.util.test.SyncValueTest.a Lcom/wec/lib/util/test/SyncValueTest$SyncInteger; | INVOKEVIRTUAL com.wec.lib.util.test.SyncValueTest$SyncInteger.getValue ()Ljava/lang/Object; | ALOAD_0 // Lcom/wec/lib/util/test/SyncValueTest; this | GETFIELD com.wec.lib.util.test.SyncValueTest.b Lcom/wec/lib/util/test/SyncValueTest$SyncInteger; | INVOKEVIRTUAL com.wec.lib.util.test.SyncValueTest$SyncInteger.getValue ()Ljava/lang/Object; | IF_ACMPNE L0 | ICONST_1 | GOTO L1 | L0: ICONST_0 | L1: INVOKESTATIC com.wec.lib.util.test.SyncValueTest.assertTrue (Z)V | ICONST_1 (line 44) | ALOAD_0 // Lcom/wec/lib/util/test/SyncValueTest; this | GETFIELD com.wec.lib.util.test.SyncValueTest.b Lcom/wec/lib/util/test/SyncValueTest$SyncInteger; | INVOKEVIRTUAL com.wec.lib.util.test.SyncValueTest$SyncInteger.getValue ()Ljava/lang/Object; | CHECKCAST java.lang.Integer | INVOKEVIRTUAL java.lang.Integer.intValue ()I | IF_ICMPNE L2 | ICONST_1 | GOTO L3 | L2: ICONST_0 | L3: INVOKESTATIC com.wec.lib.util.test.SyncValueTest.assertTrue (Z)V | ALOAD_0 // Lcom/wec/lib/util/test/SyncValueTest; this (line 45) | GETFIELD com.wec.lib.util.test.SyncValueTest.b Lcom/wec/lib/util/test/SyncValueTest$SyncInteger; | ICONST_2 | INVOKESTATIC java.lang.Integer.valueOf (I)Ljava/lang/Integer; | INVOKEVIRTUAL com.wec.lib.util.test.SyncValueTest$SyncInteger.setValue (Ljava/lang/Object;)V | ICONST_2 (line 46) | ALOAD_0 // Lcom/wec/lib/util/test/SyncValueTest; this | GETFIELD com.wec.lib.util.test.SyncValueTest.a Lcom/wec/lib/util/test/SyncValueTest$SyncInteger; | INVOKEVIRTUAL com.wec.lib.util.test.SyncValueTest$SyncInteger.getValue ()Ljava/lang/Object; | CHECKCAST java.lang.Integer | INVOKEVIRTUAL java.lang.Integer.intValue ()I | IF_ICMPNE L4 | ICONST_1 | GOTO L5 | L4: ICONST_0 | L5: INVOKESTATIC com.wec.lib.util.test.SyncValueTest.assertTrue (Z)V | ALOAD_0 // Lcom/wec/lib/util/test/SyncValueTest; this (line 47) | GETFIELD com.wec.lib.util.test.SyncValueTest.b Lcom/wec/lib/util/test/SyncValueTest$SyncInteger; | ICONST_1 | ANEWARRAY com.wec.lib.util.SyncValueGroup | DUP | ICONST_0 | ALOAD_0 // Lcom/wec/lib/util/test/SyncValueTest; this | GETFIELD com.wec.lib.util.test.SyncValueTest.c Lcom/wec/lib/util/test/SyncValueTest$SyncInteger; | AASTORE | INVOKEVIRTUAL com.wec.lib.util.test.SyncValueTest$SyncInteger.link ([Lcom/wec/lib/util/SyncValueGroup;)V | ICONST_2 (line 48) | ALOAD_0 // Lcom/wec/lib/util/test/SyncValueTest; this | GETFIELD com.wec.lib.util.test.SyncValueTest.c Lcom/wec/lib/util/test/SyncValueTest$SyncInteger; | INVOKEVIRTUAL com.wec.lib.util.test.SyncValueTest$SyncInteger.getValue ()Ljava/lang/Object; | CHECKCAST java.lang.Integer | INVOKEVIRTUAL java.lang.Integer.intValue ()I | IF_ICMPNE L6 | ICONST_1 | GOTO L7 | L6: ICONST_0 | L7: INVOKESTATIC com.wec.lib.util.test.SyncValueTest.assertTrue (Z)V | ALOAD_0 // Lcom/wec/lib/util/test/SyncValueTest; this (line 49) | GETFIELD com.wec.lib.util.test.SyncValueTest.c Lcom/wec/lib/util/test/SyncValueTest$SyncInteger; | ICONST_3 | INVOKESTATIC java.lang.Integer.valueOf (I)Ljava/lang/Integer; | INVOKEVIRTUAL com.wec.lib.util.test.SyncValueTest$SyncInteger.setValue (Ljava/lang/Object;)V | ICONST_3 (line 50) | ALOAD_0 // Lcom/wec/lib/util/test/SyncValueTest; this | GETFIELD com.wec.lib.util.test.SyncValueTest.a Lcom/wec/lib/util/test/SyncValueTest$SyncInteger; | INVOKEVIRTUAL com.wec.lib.util.test.SyncValueTest$SyncInteger.getValue ()Ljava/lang/Object; | CHECKCAST java.lang.Integer | INVOKEVIRTUAL java.lang.Integer.intValue ()I | IF_ICMPNE L8 | ICONST_1 | GOTO L9 | L8: ICONST_0 | L9: INVOKESTATIC com.wec.lib.util.test.SyncValueTest.assertTrue (Z)V | ICONST_3 (line 51) | ALOAD_0 // Lcom/wec/lib/util/test/SyncValueTest; this | GETFIELD com.wec.lib.util.test.SyncValueTest.b Lcom/wec/lib/util/test/SyncValueTest$SyncInteger; | INVOKEVIRTUAL com.wec.lib.util.test.SyncValueTest$SyncInteger.getValue ()Ljava/lang/Object; | CHECKCAST java.lang.Integer | INVOKEVIRTUAL java.lang.Integer.intValue ()I | IF_ICMPNE L10 | ICONST_1 | GOTO L11 | L10: ICONST_0 | L11: INVOKESTATIC com.wec.lib.util.test.SyncValueTest.assertTrue (Z)V | ALOAD_0 // Lcom/wec/lib/util/test/SyncValueTest; this (line 52) | GETFIELD com.wec.lib.util.test.SyncValueTest.a Lcom/wec/lib/util/test/SyncValueTest$SyncInteger; | ICONST_4 | INVOKESTATIC java.lang.Integer.valueOf (I)Ljava/lang/Integer; | INVOKEVIRTUAL com.wec.lib.util.test.SyncValueTest$SyncInteger.setValue (Ljava/lang/Object;)V | ICONST_4 (line 53) | ALOAD_0 // Lcom/wec/lib/util/test/SyncValueTest; this | GETFIELD com.wec.lib.util.test.SyncValueTest.c Lcom/wec/lib/util/test/SyncValueTest$SyncInteger; | INVOKEVIRTUAL com.wec.lib.util.test.SyncValueTest$SyncInteger.getValue ()Ljava/lang/Object; | CHECKCAST java.lang.Integer | INVOKEVIRTUAL java.lang.Integer.intValue ()I | IF_ICMPNE L12 | ICONST_1 | GOTO L13 | L12: ICONST_0 | L13: INVOKESTATIC com.wec.lib.util.test.SyncValueTest.assertTrue (Z)V | ICONST_4 (line 54) | ALOAD_0 // Lcom/wec/lib/util/test/SyncValueTest; this | GETFIELD com.wec.lib.util.test.SyncValueTest.b Lcom/wec/lib/util/test/SyncValueTest$SyncInteger; | INVOKEVIRTUAL com.wec.lib.util.test.SyncValueTest$SyncInteger.getValue ()Ljava/lang/Object; | CHECKCAST java.lang.Integer | INVOKEVIRTUAL java.lang.Integer.intValue ()I | IF_ICMPNE L14 | ICONST_1 | GOTO L15 | L14: ICONST_0 | L15: INVOKESTATIC com.wec.lib.util.test.SyncValueTest.assertTrue (Z)V | ALOAD_0 // Lcom/wec/lib/util/test/SyncValueTest; this (line 55) | GETFIELD com.wec.lib.util.test.SyncValueTest.b Lcom/wec/lib/util/test/SyncValueTest$SyncInteger; | ICONST_1 | INVOKESTATIC java.lang.Integer.valueOf (I)Ljava/lang/Integer; | INVOKEVIRTUAL com.wec.lib.util.test.SyncValueTest$SyncInteger.setValue (Ljava/lang/Object;)V | ICONST_1 (line 56) | ALOAD_0 // Lcom/wec/lib/util/test/SyncValueTest; this | GETFIELD com.wec.lib.util.test.SyncValueTest.c Lcom/wec/lib/util/test/SyncValueTest$SyncInteger; | INVOKEVIRTUAL com.wec.lib.util.test.SyncValueTest$SyncInteger.getValue ()Ljava/lang/Object; | CHECKCAST java.lang.Integer | INVOKEVIRTUAL java.lang.Integer.intValue ()I | IF_ICMPNE L16 | ICONST_1 | GOTO L17 | L16: ICONST_0 | L17: INVOKESTATIC com.wec.lib.util.test.SyncValueTest.assertTrue (Z)V | ICONST_1 (line 57) | ALOAD_0 // Lcom/wec/lib/util/test/SyncValueTest; this | GETFIELD com.wec.lib.util.test.SyncValueTest.a Lcom/wec/lib/util/test/SyncValueTest$SyncInteger; | INVOKEVIRTUAL com.wec.lib.util.test.SyncValueTest$SyncInteger.getValue ()Ljava/lang/Object; | CHECKCAST java.lang.Integer | INVOKEVIRTUAL java.lang.Integer.intValue ()I | IF_ICMPNE L18 | ICONST_1 | GOTO L19 | L18: ICONST_0 | L19: INVOKESTATIC com.wec.lib.util.test.SyncValueTest.assertTrue (Z)V | ALOAD_0 // Lcom/wec/lib/util/test/SyncValueTest; this (line 59) | GETFIELD com.wec.lib.util.test.SyncValueTest.d Lcom/wec/lib/util/test/SyncValueTest$SyncInteger; | ICONST_1 | ANEWARRAY com.wec.lib.util.SyncValueGroup | DUP | ICONST_0 | ALOAD_0 // Lcom/wec/lib/util/test/SyncValueTest; this | GETFIELD com.wec.lib.util.test.SyncValueTest.e Lcom/wec/lib/util/test/SyncValueTest$SyncInteger; | AASTORE | INVOKEVIRTUAL com.wec.lib.util.test.SyncValueTest$SyncInteger.link ([Lcom/wec/lib/util/SyncValueGroup;)V | ALOAD_0 // Lcom/wec/lib/util/test/SyncValueTest; this (line 60) | GETFIELD com.wec.lib.util.test.SyncValueTest.d Lcom/wec/lib/util/test/SyncValueTest$SyncInteger; | INVOKEVIRTUAL com.wec.lib.util.test.SyncValueTest$SyncInteger.getValue ()Ljava/lang/Object; | ALOAD_0 // Lcom/wec/lib/util/test/SyncValueTest; this | GETFIELD com.wec.lib.util.test.SyncValueTest.e Lcom/wec/lib/util/test/SyncValueTest$SyncInteger; | INVOKEVIRTUAL com.wec.lib.util.test.SyncValueTest$SyncInteger.getValue ()Ljava/lang/Object; | IF_ACMPNE L20 | ICONST_1 | GOTO L21 | L20: ICONST_0 | L21: INVOKESTATIC com.wec.lib.util.test.SyncValueTest.assertTrue (Z)V | ALOAD_0 // Lcom/wec/lib/util/test/SyncValueTest; this (line 63) | GETFIELD com.wec.lib.util.test.SyncValueTest.b Lcom/wec/lib/util/test/SyncValueTest$SyncInteger; | ICONST_1 | ANEWARRAY com.wec.lib.util.SyncValueGroup | DUP | ICONST_0 | ALOAD_0 // Lcom/wec/lib/util/test/SyncValueTest; this | GETFIELD com.wec.lib.util.test.SyncValueTest.d Lcom/wec/lib/util/test/SyncValueTest$SyncInteger; | AASTORE | INVOKEVIRTUAL com.wec.lib.util.test.SyncValueTest$SyncInteger.link ([Lcom/wec/lib/util/SyncValueGroup;)V | ICONST_1 (line 64) | ALOAD_0 // Lcom/wec/lib/util/test/SyncValueTest; this | GETFIELD com.wec.lib.util.test.SyncValueTest.d Lcom/wec/lib/util/test/SyncValueTest$SyncInteger; | INVOKEVIRTUAL com.wec.lib.util.test.SyncValueTest$SyncInteger.getValue ()Ljava/lang/Object; | CHECKCAST java.lang.Integer | INVOKEVIRTUAL java.lang.Integer.intValue ()I | IF_ICMPNE L22 | ICONST_1 | GOTO L23 | L22: ICONST_0 | L23: INVOKESTATIC com.wec.lib.util.test.SyncValueTest.assertTrue (Z)V | ICONST_1 (line 65) | ALOAD_0 // Lcom/wec/lib/util/test/SyncValueTest; this | GETFIELD com.wec.lib.util.test.SyncValueTest.e Lcom/wec/lib/util/test/SyncValueTest$SyncInteger; | INVOKEVIRTUAL com.wec.lib.util.test.SyncValueTest$SyncInteger.getValue ()Ljava/lang/Object; | CHECKCAST java.lang.Integer | INVOKEVIRTUAL java.lang.Integer.intValue ()I | IF_ICMPNE L24 | ICONST_1 | GOTO L25 | L24: ICONST_0 | L25: INVOKESTATIC com.wec.lib.util.test.SyncValueTest.assertTrue (Z)V | ALOAD_0 // Lcom/wec/lib/util/test/SyncValueTest; this (line 66) | GETFIELD com.wec.lib.util.test.SyncValueTest.d Lcom/wec/lib/util/test/SyncValueTest$SyncInteger; | BIPUSH 8 | INVOKESTATIC java.lang.Integer.valueOf (I)Ljava/lang/Integer; | INVOKEVIRTUAL com.wec.lib.util.test.SyncValueTest$SyncInteger.setValue (Ljava/lang/Object;)V | BIPUSH 8 (line 67) | ALOAD_0 // Lcom/wec/lib/util/test/SyncValueTest; this | GETFIELD com.wec.lib.util.test.SyncValueTest.a Lcom/wec/lib/util/test/SyncValueTest$SyncInteger; | INVOKEVIRTUAL com.wec.lib.util.test.SyncValueTest$SyncInteger.getValue ()Ljava/lang/Object; | CHECKCAST java.lang.Integer | INVOKEVIRTUAL java.lang.Integer.intValue ()I | IF_ICMPNE L26 | ICONST_1 | GOTO L27 | L26: ICONST_0 | L27: INVOKESTATIC com.wec.lib.util.test.SyncValueTest.assertTrue (Z)V | BIPUSH 8 (line 68) | ALOAD_0 // Lcom/wec/lib/util/test/SyncValueTest; this | GETFIELD com.wec.lib.util.test.SyncValueTest.b Lcom/wec/lib/util/test/SyncValueTest$SyncInteger; | INVOKEVIRTUAL com.wec.lib.util.test.SyncValueTest$SyncInteger.getValue ()Ljava/lang/Object; | CHECKCAST java.lang.Integer | INVOKEVIRTUAL java.lang.Integer.intValue ()I | IF_ICMPNE L28 | ICONST_1 | GOTO L29 | L28: ICONST_0 | L29: INVOKESTATIC com.wec.lib.util.test.SyncValueTest.assertTrue (Z)V | BIPUSH 8 (line 69) | ALOAD_0 // Lcom/wec/lib/util/test/SyncValueTest; this | GETFIELD com.wec.lib.util.test.SyncValueTest.c Lcom/wec/lib/util/test/SyncValueTest$SyncInteger; | INVOKEVIRTUAL com.wec.lib.util.test.SyncValueTest$SyncInteger.getValue ()Ljava/lang/Object; | CHECKCAST java.lang.Integer | INVOKEVIRTUAL java.lang.Integer.intValue ()I | IF_ICMPNE L30 | ICONST_1 | GOTO L31 | L30: ICONST_0 | L31: INVOKESTATIC com.wec.lib.util.test.SyncValueTest.assertTrue (Z)V | BIPUSH 8 (line 70) | ALOAD_0 // Lcom/wec/lib/util/test/SyncValueTest; this | GETFIELD com.wec.lib.util.test.SyncValueTest.d Lcom/wec/lib/util/test/SyncValueTest$SyncInteger; | INVOKEVIRTUAL com.wec.lib.util.test.SyncValueTest$SyncInteger.getValue ()Ljava/lang/Object; | CHECKCAST java.lang.Integer | INVOKEVIRTUAL java.lang.Integer.intValue ()I | IF_ICMPNE L32 | ICONST_1 | GOTO L33 | L32: ICONST_0 | L33: INVOKESTATIC com.wec.lib.util.test.SyncValueTest.assertTrue (Z)V | BIPUSH 8 (line 71) | ALOAD_0 // Lcom/wec/lib/util/test/SyncValueTest; this | GETFIELD com.wec.lib.util.test.SyncValueTest.e Lcom/wec/lib/util/test/SyncValueTest$SyncInteger; | INVOKEVIRTUAL com.wec.lib.util.test.SyncValueTest$SyncInteger.getValue ()Ljava/lang/Object; | CHECKCAST java.lang.Integer | INVOKEVIRTUAL java.lang.Integer.intValue ()I | IF_ICMPNE L34 | ICONST_1 | GOTO L35 | L34: ICONST_0 | L35: INVOKESTATIC com.wec.lib.util.test.SyncValueTest.assertTrue (Z)V | ALOAD_0 // Lcom/wec/lib/util/test/SyncValueTest; this (line 74) | GETFIELD com.wec.lib.util.test.SyncValueTest.c Lcom/wec/lib/util/test/SyncValueTest$SyncInteger; | INVOKEVIRTUAL com.wec.lib.util.test.SyncValueTest$SyncInteger.unlink ()V | ALOAD_0 // Lcom/wec/lib/util/test/SyncValueTest; this (line 75) | GETFIELD com.wec.lib.util.test.SyncValueTest.c Lcom/wec/lib/util/test/SyncValueTest$SyncInteger; | ICONST_3 | INVOKESTATIC java.lang.Integer.valueOf (I)Ljava/lang/Integer; | INVOKEVIRTUAL com.wec.lib.util.test.SyncValueTest$SyncInteger.setValue (Ljava/lang/Object;)V | ALOAD_0 // Lcom/wec/lib/util/test/SyncValueTest; this (line 76) | GETFIELD com.wec.lib.util.test.SyncValueTest.b Lcom/wec/lib/util/test/SyncValueTest$SyncInteger; | ICONST_2 | INVOKESTATIC java.lang.Integer.valueOf (I)Ljava/lang/Integer; | INVOKEVIRTUAL com.wec.lib.util.test.SyncValueTest$SyncInteger.setValue (Ljava/lang/Object;)V | ICONST_2 (line 77) | ALOAD_0 // Lcom/wec/lib/util/test/SyncValueTest; this | GETFIELD com.wec.lib.util.test.SyncValueTest.a Lcom/wec/lib/util/test/SyncValueTest$SyncInteger; | INVOKEVIRTUAL com.wec.lib.util.test.SyncValueTest$SyncInteger.getValue ()Ljava/lang/Object; | CHECKCAST java.lang.Integer | INVOKEVIRTUAL java.lang.Integer.intValue ()I | IF_ICMPNE L36 | ICONST_1 | GOTO L37 | L36: ICONST_0 | L37: INVOKESTATIC com.wec.lib.util.test.SyncValueTest.assertTrue (Z)V | ICONST_2 (line 78) | ALOAD_0 // Lcom/wec/lib/util/test/SyncValueTest; this | GETFIELD com.wec.lib.util.test.SyncValueTest.b Lcom/wec/lib/util/test/SyncValueTest$SyncInteger; | INVOKEVIRTUAL com.wec.lib.util.test.SyncValueTest$SyncInteger.getValue ()Ljava/lang/Object; | CHECKCAST java.lang.Integer | INVOKEVIRTUAL java.lang.Integer.intValue ()I | IF_ICMPNE L38 | ICONST_1 | GOTO L39 | L38: ICONST_0 | L39: INVOKESTATIC com.wec.lib.util.test.SyncValueTest.assertTrue (Z)V | ICONST_3 (line 79) | ALOAD_0 // Lcom/wec/lib/util/test/SyncValueTest; this | GETFIELD com.wec.lib.util.test.SyncValueTest.c Lcom/wec/lib/util/test/SyncValueTest$SyncInteger; | INVOKEVIRTUAL com.wec.lib.util.test.SyncValueTest$SyncInteger.getValue ()Ljava/lang/Object; | CHECKCAST java.lang.Integer | INVOKEVIRTUAL java.lang.Integer.intValue ()I | IF_ICMPNE L40 | ICONST_1 | GOTO L41 | L40: ICONST_0 | L41: INVOKESTATIC com.wec.lib.util.test.SyncValueTest.assertTrue (Z)V | ICONST_2 (line 80) | ALOAD_0 // Lcom/wec/lib/util/test/SyncValueTest; this | GETFIELD com.wec.lib.util.test.SyncValueTest.d Lcom/wec/lib/util/test/SyncValueTest$SyncInteger; | INVOKEVIRTUAL com.wec.lib.util.test.SyncValueTest$SyncInteger.getValue ()Ljava/lang/Object; | CHECKCAST java.lang.Integer | INVOKEVIRTUAL java.lang.Integer.intValue ()I | IF_ICMPNE L42 | ICONST_1 | GOTO L43 | L42: ICONST_0 | L43: INVOKESTATIC com.wec.lib.util.test.SyncValueTest.assertTrue (Z)V | ICONST_2 (line 81) | ALOAD_0 // Lcom/wec/lib/util/test/SyncValueTest; this | GETFIELD com.wec.lib.util.test.SyncValueTest.e Lcom/wec/lib/util/test/SyncValueTest$SyncInteger; | INVOKEVIRTUAL com.wec.lib.util.test.SyncValueTest$SyncInteger.getValue ()Ljava/lang/Object; | CHECKCAST java.lang.Integer | INVOKEVIRTUAL java.lang.Integer.intValue ()I | IF_ICMPNE L44 | ICONST_1 | GOTO L45 | L44: ICONST_0 | L45: INVOKESTATIC com.wec.lib.util.test.SyncValueTest.assertTrue (Z)V | ALOAD_0 // Lcom/wec/lib/util/test/SyncValueTest; this (line 82) | GETFIELD com.wec.lib.util.test.SyncValueTest.d Lcom/wec/lib/util/test/SyncValueTest$SyncInteger; | INVOKEVIRTUAL com.wec.lib.util.test.SyncValueTest$SyncInteger.unlink ()V | ALOAD_0 // Lcom/wec/lib/util/test/SyncValueTest; this (line 83) | GETFIELD com.wec.lib.util.test.SyncValueTest.c Lcom/wec/lib/util/test/SyncValueTest$SyncInteger; | ICONST_1 | ANEWARRAY com.wec.lib.util.SyncValueGroup | DUP | ICONST_0 | ALOAD_0 // Lcom/wec/lib/util/test/SyncValueTest; this | GETFIELD com.wec.lib.util.test.SyncValueTest.d Lcom/wec/lib/util/test/SyncValueTest$SyncInteger; | AASTORE | INVOKEVIRTUAL com.wec.lib.util.test.SyncValueTest$SyncInteger.link ([Lcom/wec/lib/util/SyncValueGroup;)V | ALOAD_0 // Lcom/wec/lib/util/test/SyncValueTest; this (line 84) | GETFIELD com.wec.lib.util.test.SyncValueTest.a Lcom/wec/lib/util/test/SyncValueTest$SyncInteger; | ICONST_1 | INVOKESTATIC java.lang.Integer.valueOf (I)Ljava/lang/Integer; | INVOKEVIRTUAL com.wec.lib.util.test.SyncValueTest$SyncInteger.setValue (Ljava/lang/Object;)V | ICONST_1 (line 85) | ALOAD_0 // Lcom/wec/lib/util/test/SyncValueTest; this | GETFIELD com.wec.lib.util.test.SyncValueTest.a Lcom/wec/lib/util/test/SyncValueTest$SyncInteger; | INVOKEVIRTUAL com.wec.lib.util.test.SyncValueTest$SyncInteger.getValue ()Ljava/lang/Object; | CHECKCAST java.lang.Integer | INVOKEVIRTUAL java.lang.Integer.intValue ()I | IF_ICMPNE L46 | ICONST_1 | GOTO L47 | L46: ICONST_0 | L47: INVOKESTATIC com.wec.lib.util.test.SyncValueTest.assertTrue (Z)V | ICONST_1 (line 86) | ALOAD_0 // Lcom/wec/lib/util/test/SyncValueTest; this | GETFIELD com.wec.lib.util.test.SyncValueTest.b Lcom/wec/lib/util/test/SyncValueTest$SyncInteger; | INVOKEVIRTUAL com.wec.lib.util.test.SyncValueTest$SyncInteger.getValue ()Ljava/lang/Object; | CHECKCAST java.lang.Integer | INVOKEVIRTUAL java.lang.Integer.intValue ()I | IF_ICMPNE L48 | ICONST_1 | GOTO L49 | L48: ICONST_0 | L49: INVOKESTATIC com.wec.lib.util.test.SyncValueTest.assertTrue (Z)V | ICONST_3 (line 87) | ALOAD_0 // Lcom/wec/lib/util/test/SyncValueTest; this | GETFIELD com.wec.lib.util.test.SyncValueTest.c Lcom/wec/lib/util/test/SyncValueTest$SyncInteger; | INVOKEVIRTUAL com.wec.lib.util.test.SyncValueTest$SyncInteger.getValue ()Ljava/lang/Object; | CHECKCAST java.lang.Integer | INVOKEVIRTUAL java.lang.Integer.intValue ()I | IF_ICMPNE L50 | ICONST_1 | GOTO L51 | L50: ICONST_0 | L51: INVOKESTATIC com.wec.lib.util.test.SyncValueTest.assertTrue (Z)V | ICONST_3 (line 88) | ALOAD_0 // Lcom/wec/lib/util/test/SyncValueTest; this | GETFIELD com.wec.lib.util.test.SyncValueTest.d Lcom/wec/lib/util/test/SyncValueTest$SyncInteger; | INVOKEVIRTUAL com.wec.lib.util.test.SyncValueTest$SyncInteger.getValue ()Ljava/lang/Object; | CHECKCAST java.lang.Integer | INVOKEVIRTUAL java.lang.Integer.intValue ()I | IF_ICMPNE L52 | ICONST_1 | GOTO L53 | L52: ICONST_0 | L53: INVOKESTATIC com.wec.lib.util.test.SyncValueTest.assertTrue (Z)V | ICONST_1 (line 89) | ALOAD_0 // Lcom/wec/lib/util/test/SyncValueTest; this | GETFIELD com.wec.lib.util.test.SyncValueTest.e Lcom/wec/lib/util/test/SyncValueTest$SyncInteger; | INVOKEVIRTUAL com.wec.lib.util.test.SyncValueTest$SyncInteger.getValue ()Ljava/lang/Object; | CHECKCAST java.lang.Integer | INVOKEVIRTUAL java.lang.Integer.intValue ()I | IF_ICMPNE L54 | ICONST_1 | GOTO L55 | L54: ICONST_0 | L55: INVOKESTATIC com.wec.lib.util.test.SyncValueTest.assertTrue (Z)V | RETURN (line 90) method-execution(void com.wec.lib.util.test.SyncValueTest.testSyncValueGroup()) end public void testSyncValueGroup() end public class com.wec.lib.util.test.SyncValueTest when weaving classes when weaving when batch building BuildConfig[D:\workspace\.metadata\.plugins\org.eclipse.ajdt.core\ANSER2.generated.lst] #Files=365 Here's the class: package com.wec.lib.util.test; import static com.wec.ide.Constants.UNCHECKED; import junit.framework.TestCase; import org.junit.Test; import com.wec.lib.util.SyncValueGroup; import com.wec.scrum.Tests; /** * This class tests the SyncValueGroup utility class. */ @Tests(classes = { SyncValueGroup.class }) @SuppressWarnings("nls") public class SyncValueTest extends TestCase { class SyncInteger extends SyncValueGroup<Integer> { public SyncInteger(int val) { super(new Integer(val)); } public void valueChanged() { } } private SyncInteger a = new SyncInteger(1); private SyncInteger b = new SyncInteger(2); private SyncInteger c = new SyncInteger(3); private SyncInteger d = new SyncInteger(4); private SyncInteger e = new SyncInteger(5); /** * Ensures that SyncValueGroup replicates values and * calls valueChange. */ @SuppressWarnings(UNCHECKED) @Test public void testSyncValueGroup() { // Link tests a.link(b); assertTrue(a.getValue() == b.getValue()); assertTrue(1 == b.getValue()); b.setValue(2); assertTrue(2 == a.getValue()); b.link(c); assertTrue(2 == c.getValue()); c.setValue(3); assertTrue(3 == a.getValue()); assertTrue(3 == b.getValue()); a.setValue(4); assertTrue(4 == c.getValue()); assertTrue(4 == b.getValue()); b.setValue(1); assertTrue(1 == c.getValue()); assertTrue(1 == a.getValue()); d.link(e); assertTrue(d.getValue() == e.getValue()); // Join loops b.link(d); assertTrue(1 == d.getValue()); assertTrue(1 == e.getValue()); d.setValue(8); assertTrue(8 == a.getValue()); assertTrue(8 == b.getValue()); assertTrue(8 == c.getValue()); assertTrue(8 == d.getValue()); assertTrue(8 == e.getValue()); // Unlink tests c.unlink(); c.setValue(3); b.setValue(2); assertTrue(2 == a.getValue()); assertTrue(2 == b.getValue()); assertTrue(3 == c.getValue()); assertTrue(2 == d.getValue()); assertTrue(2 == e.getValue()); d.unlink(); c.link(d); a.setValue(1); assertTrue(1 == a.getValue()); assertTrue(1 == b.getValue()); assertTrue(3 == c.getValue()); assertTrue(3 == d.getValue()); assertTrue(1 == e.getValue()); } }
|
resolved fixed
|
ea4ff8a
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-09-29T12:20:31Z | 2006-09-25T18:46:40Z |
weaver/src/org/aspectj/weaver/ResolvedMemberImpl.java
|
/* *******************************************************************
* Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC).
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Eclipse Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* PARC initial implementation
* ******************************************************************/
package org.aspectj.weaver;
import java.io.DataOutputStream;
import java.io.IOException;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.aspectj.bridge.ISourceLocation;
/**
* This is the declared member, i.e. it will always correspond to an
* actual method/... declaration
*/
public class ResolvedMemberImpl extends MemberImpl implements IHasPosition, AnnotatedElement, TypeVariableDeclaringElement, ResolvedMember {
private String[] parameterNames = null;
protected UnresolvedType[] checkedExceptions = UnresolvedType.NONE;
/**
* if this member is a parameterized version of a member in a generic type,
* then this field holds a reference to the member we parameterize.
*/
protected ResolvedMember backingGenericMember = null;
protected Set annotationTypes = null;
// Some members are 'created' to represent other things (for example ITDs). These
// members have their annotations stored elsewhere, and this flag indicates that is
// the case. It is up to the caller to work out where that is!
// Once determined the caller may choose to stash the annotations in this member...
private boolean isAnnotatedElsewhere = false; // this field is not serialized.
private boolean isAjSynthetic = false;
// generic methods have type variables
protected TypeVariable[] typeVariables;
// these three fields hold the source location of this member
protected int start, end;
protected ISourceContext sourceContext = null;
//XXX deprecate this in favor of the constructor below
public ResolvedMemberImpl(
Kind kind,
UnresolvedType declaringType,
int modifiers,
UnresolvedType returnType,
String name,
UnresolvedType[] parameterTypes)
{
super(kind, declaringType, modifiers, returnType, name, parameterTypes);
}
public ResolvedMemberImpl(
Kind kind,
UnresolvedType declaringType,
int modifiers,
UnresolvedType returnType,
String name,
UnresolvedType[] parameterTypes,
UnresolvedType[] checkedExceptions)
{
super(kind, declaringType, modifiers, returnType, name, parameterTypes);
this.checkedExceptions = checkedExceptions;
}
public ResolvedMemberImpl(
Kind kind,
UnresolvedType declaringType,
int modifiers,
UnresolvedType returnType,
String name,
UnresolvedType[] parameterTypes,
UnresolvedType[] checkedExceptions,
ResolvedMember backingGenericMember)
{
this(kind, declaringType, modifiers, returnType, name, parameterTypes,checkedExceptions);
this.backingGenericMember = backingGenericMember;
this.isAjSynthetic = backingGenericMember.isAjSynthetic();
}
public ResolvedMemberImpl(
Kind kind,
UnresolvedType declaringType,
int modifiers,
String name,
String signature)
{
super(kind, declaringType, modifiers, name, signature);
}
/**
* Compute the full set of signatures for a member. This walks up the hierarchy
* giving the ResolvedMember in each defining type in the hierarchy. A shadowMember
* can be created with a target type (declaring type) that does not actually define
* the member. This is ok as long as the member is inherited in the declaring type.
* Each declaring type in the line to the actual declaring type is added as an additional
* signature. For example:
*
* class A { void foo(); }
* class B extends A {}
*
* shadowMember : void B.foo()
*
* gives { void B.foo(), void A.foo() }
* @param joinPointSignature
* @param inAWorld
*/
public static JoinPointSignature[] getJoinPointSignatures(Member joinPointSignature, World inAWorld) {
// Walk up hierarchy creating one member for each type up to and including the
// first defining type
ResolvedType originalDeclaringType = joinPointSignature.getDeclaringType().resolve(inAWorld);
ResolvedMemberImpl firstDefiningMember = (ResolvedMemberImpl) joinPointSignature.resolve(inAWorld);
if (firstDefiningMember == null) {
return new JoinPointSignature[0];
}
// declaringType can be unresolved if we matched a synthetic member generated by Aj...
// should be fixed elsewhere but add this resolve call on the end for now so that we can
// focus on one problem at a time...
ResolvedType firstDefiningType = firstDefiningMember.getDeclaringType().resolve(inAWorld);
if (firstDefiningType != originalDeclaringType) {
if (joinPointSignature.getKind() == Member.CONSTRUCTOR) {
return new JoinPointSignature[0];
}
// else if (shadowMember.isStatic()) {
// return new ResolvedMember[] {firstDefiningMember};
// }
}
List declaringTypes = new ArrayList();
accumulateTypesInBetween(originalDeclaringType,
firstDefiningType,
declaringTypes);
Set memberSignatures = new HashSet();
for (Iterator iter = declaringTypes.iterator(); iter.hasNext();) {
ResolvedType declaringType = (ResolvedType) iter.next();
ResolvedMember member = firstDefiningMember.withSubstituteDeclaringType(declaringType);
memberSignatures.add(member);
}
if (shouldWalkUpHierarchyFor(firstDefiningMember)) {
// now walk up the hierarchy from the firstDefiningMember and include the signature for
// every type between the firstDefiningMember and the root defining member.
Iterator superTypeIterator = firstDefiningType.getDirectSupertypes();
List typesAlreadyVisited = new ArrayList();
accumulateMembersMatching(firstDefiningMember,superTypeIterator,typesAlreadyVisited,memberSignatures);
}
JoinPointSignature[] ret = new JoinPointSignature[memberSignatures.size()];
memberSignatures.toArray(ret);
return ret;
}
private static boolean shouldWalkUpHierarchyFor(Member aMember) {
if (aMember.getKind() == Member.CONSTRUCTOR) return false;
if (aMember.getKind() == Member.FIELD) return false;
if (aMember.isStatic()) return false;
return true;
}
/**
* Build a list containing every type between subtype and supertype, inclusively.
*/
private static void accumulateTypesInBetween(ResolvedType subType, ResolvedType superType, List types) {
types.add(subType);
if (subType == superType) {
return;
} else {
for (Iterator iter = subType.getDirectSupertypes(); iter.hasNext();) {
ResolvedType parent = (ResolvedType) iter.next();
if (superType.isAssignableFrom(parent)) {
accumulateTypesInBetween(parent, superType,types);
}
}
}
}
/**
* We have a resolved member, possibly with type parameter references as parameters or return
* type. We need to find all its ancestor members. When doing this, a type parameter matches
* regardless of bounds (bounds can be narrowed down the hierarchy).
*/
private static void accumulateMembersMatching(
ResolvedMemberImpl memberToMatch,
Iterator typesToLookIn,
List typesAlreadyVisited,
Set foundMembers) {
while(typesToLookIn.hasNext()) {
ResolvedType toLookIn = (ResolvedType) typesToLookIn.next();
if (!typesAlreadyVisited.contains(toLookIn)) {
typesAlreadyVisited.add(toLookIn);
ResolvedMemberImpl foundMember = (ResolvedMemberImpl) toLookIn.lookupResolvedMember(memberToMatch,true);
if (foundMember != null && isVisibleTo(memberToMatch,foundMember)) {
List declaringTypes = new ArrayList();
// declaring type can be unresolved if the member can from an ITD...
ResolvedType resolvedDeclaringType = foundMember.getDeclaringType().resolve(toLookIn.getWorld());
accumulateTypesInBetween(toLookIn, resolvedDeclaringType, declaringTypes);
for (Iterator iter = declaringTypes.iterator(); iter.hasNext();) {
ResolvedType declaringType = (ResolvedType) iter.next();
// typesAlreadyVisited.add(declaringType);
ResolvedMember member = foundMember.withSubstituteDeclaringType(declaringType);
foundMembers.add(member);
}
if (toLookIn.isParameterizedType() && (foundMember.backingGenericMember != null)) {
foundMembers.add(new JoinPointSignature(foundMember.backingGenericMember,foundMember.declaringType.resolve(toLookIn.getWorld())));
}
accumulateMembersMatching(foundMember,toLookIn.getDirectSupertypes(),typesAlreadyVisited,foundMembers);
// if this was a parameterized type, look in the generic type that backs it too
}
}
}
}
/**
* Returns true if the parent member is visible to the child member
* In the same declaring type this is always true, otherwise if parent is private
* it is false.
* @param childMember
* @param parentMember
* @return
*/
private static boolean isVisibleTo(ResolvedMember childMember, ResolvedMember parentMember) {
if (childMember.getDeclaringType().equals(parentMember.getDeclaringType())) return true;
if (Modifier.isPrivate(parentMember.getModifiers())) {
return false;
} else {
return true;
}
}
// ----
public final int getModifiers(World world) {
return modifiers;
}
public final int getModifiers() {
return modifiers;
}
// ----
public final UnresolvedType[] getExceptions(World world) {
return getExceptions();
}
public UnresolvedType[] getExceptions() {
return checkedExceptions;
}
public ShadowMunger getAssociatedShadowMunger() {
return null;
}
// ??? true or false?
public boolean isAjSynthetic() {
return isAjSynthetic;
}
protected void setAjSynthetic(boolean b) {isAjSynthetic= b;}
public boolean hasAnnotations() {
return (annotationTypes!=null);
}
public boolean hasAnnotation(UnresolvedType ofType) {
// The ctors don't allow annotations to be specified ... yet - but
// that doesn't mean it is an error to call this method.
// Normally the weaver will be working with subtypes of
// this type - BcelField/BcelMethod
if (annotationTypes==null) return false;
return annotationTypes.contains(ofType);
}
public ResolvedType[] getAnnotationTypes() {
// The ctors don't allow annotations to be specified ... yet - but
// that doesn't mean it is an error to call this method.
// Normally the weaver will be working with subtypes of
// this type - BcelField/BcelMethod
if (annotationTypes == null) return null;
return (ResolvedType[])annotationTypes.toArray(new ResolvedType[]{});
}
public AnnotationX[] getAnnotations() {
if (backingGenericMember != null) return backingGenericMember.getAnnotations();
return super.getAnnotations();
}
public void setAnnotationTypes(UnresolvedType[] annotationtypes) {
if (annotationTypes == null) annotationTypes = new HashSet();
for (int i = 0; i < annotationtypes.length; i++) {
UnresolvedType typeX = annotationtypes[i];
annotationTypes.add(typeX);
}
}
public void addAnnotation(AnnotationX annotation) {
// FIXME asc only allows for annotation types, not instances - should it?
if (annotationTypes == null) annotationTypes = new HashSet();
annotationTypes.add(annotation.getSignature());
}
public boolean isBridgeMethod() {
return (modifiers & Constants.ACC_BRIDGE)!=0 && getKind().equals(METHOD);
}
public boolean isVarargsMethod() {
return (modifiers & Constants.ACC_VARARGS)!=0;
}
public void setVarargsMethod() {
modifiers = modifiers | Constants.ACC_VARARGS;
}
public boolean isSynthetic() {
// See Bcelmethod.isSynthetic() which takes account of preJava5 Synthetic modifier
return (modifiers & 4096)!=0; // do we know better?
}
public void write(DataOutputStream s) throws IOException {
getKind().write(s);
getDeclaringType().write(s);
s.writeInt(modifiers);
s.writeUTF(getName());
s.writeUTF(getSignature());
UnresolvedType.writeArray(getExceptions(), s);
s.writeInt(getStart());
s.writeInt(getEnd());
s.writeBoolean(isVarargsMethod());
// Write out any type variables...
if (typeVariables==null) {
s.writeInt(0);
} else {
s.writeInt(typeVariables.length);
for (int i = 0; i < typeVariables.length; i++) {
typeVariables[i].write(s);
}
}
String gsig = getGenericSignature();
if (getSignature().equals(gsig)) {
s.writeBoolean(false);
} else {
s.writeBoolean(true);
s.writeInt(parameterTypes.length);
for (int i = 0; i < parameterTypes.length; i++) {
UnresolvedType array_element = parameterTypes[i];
array_element.write(s);
}
returnType.write(s);
}
}
public String getGenericSignature() {
StringBuffer sb = new StringBuffer();
if (typeVariables!=null) {
sb.append("<");
for (int i = 0; i < typeVariables.length; i++) {
sb.append(typeVariables[i].getSignature());
}
sb.append(">");
}
sb.append("(");
for (int i = 0; i < parameterTypes.length; i++) {
UnresolvedType array_element = parameterTypes[i];
sb.append(array_element.getSignature());
}
sb.append(")");
sb.append(returnType.getSignature());
return sb.toString();
}
public static void writeArray(ResolvedMember[] members, DataOutputStream s) throws IOException {
s.writeInt(members.length);
for (int i = 0, len = members.length; i < len; i++) {
members[i].write(s);
}
}
public static ResolvedMemberImpl readResolvedMember(VersionedDataInputStream s, ISourceContext sourceContext) throws IOException {
ResolvedMemberImpl m = new ResolvedMemberImpl(Kind.read(s), UnresolvedType.read(s), s.readInt(),
s.readUTF(), s.readUTF());
m.checkedExceptions = UnresolvedType.readArray(s);
m.start = s.readInt();
m.end = s.readInt();
m.sourceContext = sourceContext;
if (s.getMajorVersion()>=AjAttribute.WeaverVersionInfo.WEAVER_VERSION_MAJOR_AJ150) {
if (s.getMajorVersion()>=AjAttribute.WeaverVersionInfo.WEAVER_VERSION_MAJOR_AJ150M4) {
boolean isvarargs = s.readBoolean();
if (isvarargs) m.setVarargsMethod();
}
int tvcount = s.readInt();
if (tvcount!=0) {
m.typeVariables = new TypeVariable[tvcount];
for (int i=0;i<tvcount;i++) {
m.typeVariables[i]=TypeVariable.read(s);
m.typeVariables[i].setDeclaringElement(m);
}
}
if (s.getMajorVersion()>=AjAttribute.WeaverVersionInfo.WEAVER_VERSION_MAJOR_AJ150M4) {
boolean hasAGenericSignature = s.readBoolean();
if (hasAGenericSignature) {
int ps = s.readInt();
UnresolvedType[] params = new UnresolvedType[ps];
for (int i = 0; i < params.length; i++) {
UnresolvedType type = params[i];
params[i]=TypeFactory.createTypeFromSignature(s.readUTF());
}
UnresolvedType rt = TypeFactory.createTypeFromSignature(s.readUTF());
m.parameterTypes = params;
m.returnType = rt;
}
}
}
return m;
}
public static ResolvedMember[] readResolvedMemberArray(VersionedDataInputStream s, ISourceContext context) throws IOException {
int len = s.readInt();
ResolvedMember[] members = new ResolvedMember[len];
for (int i=0; i < len; i++) {
members[i] = ResolvedMemberImpl.readResolvedMember(s, context);
}
return members;
}
public ResolvedMember resolve(World world) {
// make sure all the pieces of a resolvedmember really are resolved
try {
if (typeVariables!=null && typeVariables.length>0) {
for (int i = 0; i < typeVariables.length; i++) {
typeVariables[i] = typeVariables[i].resolve(world);
}
}
world.setTypeVariableLookupScope(this);
if (annotationTypes!=null) {
Set r = new HashSet();
for (Iterator iter = annotationTypes.iterator(); iter.hasNext();) {
UnresolvedType element = (UnresolvedType) iter.next();
r.add(world.resolve(element));
}
annotationTypes = r;
}
declaringType = declaringType.resolve(world);
if (declaringType.isRawType()) declaringType = ((ReferenceType)declaringType).getGenericType();
if (parameterTypes!=null && parameterTypes.length>0) {
for (int i = 0; i < parameterTypes.length; i++) {
parameterTypes[i] = parameterTypes[i].resolve(world);
}
}
returnType = returnType.resolve(world);
} finally {
world.setTypeVariableLookupScope(null);
}
return this;
}
public ISourceContext getSourceContext(World world) {
return getDeclaringType().resolve(world).getSourceContext();
}
public String[] getParameterNames() {
return parameterNames;
}
public final void setParameterNames(String[] pnames) {
parameterNames = pnames;
}
public final String[] getParameterNames(World world) {
return getParameterNames();
}
public AjAttribute.EffectiveSignatureAttribute getEffectiveSignature() {
return null;
}
public ISourceLocation getSourceLocation() {
//System.out.println("get context: " + this + " is " + sourceContext);
if (getSourceContext() == null) {
//System.err.println("no context: " + this);
return null;
}
return getSourceContext().makeSourceLocation(this);
}
public int getEnd() {
return end;
}
public ISourceContext getSourceContext() {
return sourceContext;
}
public int getStart() {
return start;
}
public void setPosition(int sourceStart, int sourceEnd) {
this.start = sourceStart;
this.end = sourceEnd;
}
public void setDeclaringType(ReferenceType rt) {
declaringType = rt;
}
public void setSourceContext(ISourceContext sourceContext) {
this.sourceContext = sourceContext;
}
public boolean isAbstract() {
return Modifier.isAbstract(modifiers);
}
public boolean isPublic() {
return Modifier.isPublic(modifiers);
}
public boolean isProtected() {
return Modifier.isProtected(modifiers);
}
public boolean isNative() {
return Modifier.isNative(modifiers);
}
public boolean isDefault() {
return !(isPublic() || isProtected() || isPrivate());
}
public boolean isVisible(ResolvedType fromType) {
World world = fromType.getWorld();
return ResolvedType.isVisible(getModifiers(), getDeclaringType().resolve(world),
fromType);
}
public void setCheckedExceptions(UnresolvedType[] checkedExceptions) {
this.checkedExceptions = checkedExceptions;
}
public void setAnnotatedElsewhere(boolean b) {
isAnnotatedElsewhere = b;
}
public boolean isAnnotatedElsewhere() {
return isAnnotatedElsewhere;
}
/**
* Get the UnresolvedType for the return type, taking generic signature into account
*/
public UnresolvedType getGenericReturnType() {
return getReturnType();
}
/**
* Get the TypeXs of the parameter types, taking generic signature into account
*/
public UnresolvedType[] getGenericParameterTypes() {
return getParameterTypes();
}
public ResolvedMemberImpl parameterizedWith(UnresolvedType[] typeParameters,ResolvedType newDeclaringType, boolean isParameterized) {
return parameterizedWith(typeParameters,newDeclaringType,isParameterized,null);
}
/**
* Return a resolvedmember in which all the type variables in the signature
* have been replaced with the given bindings.
* The 'isParameterized' flag tells us whether we are creating a raw type
* version or not. if (isParameterized) then List<T> will turn into
* List<String> (for example) - if (!isParameterized) then List<T> will turn
* into List.
*/
public ResolvedMemberImpl parameterizedWith(UnresolvedType[] typeParameters,ResolvedType newDeclaringType, boolean isParameterized,List aliases) {
if (//isParameterized && <-- might need this bit...
!getDeclaringType().isGenericType()) {
throw new IllegalStateException("Can't ask to parameterize a member of non-generic type: "+getDeclaringType()+" kind("+getDeclaringType().typeKind+")");
}
TypeVariable[] typeVariables = getDeclaringType().getTypeVariables();
if (isParameterized && (typeVariables.length != typeParameters.length)) {
throw new IllegalStateException("Wrong number of type parameters supplied");
}
Map typeMap = new HashMap();
boolean typeParametersSupplied = typeParameters!=null && typeParameters.length>0;
if (typeVariables!=null) {
// If no 'replacements' were supplied in the typeParameters array then collapse
// type variables to their first bound.
for (int i = 0; i < typeVariables.length; i++) {
UnresolvedType ut = (!typeParametersSupplied?typeVariables[i].getFirstBound():typeParameters[i]);
typeMap.put(typeVariables[i].getName(),ut);
}
}
// For ITDs on generic types that use type variables from the target type, the aliases
// record the alternative names used throughout the ITD expression that must map to
// the same value as the type variables real name.
if (aliases!=null) {
int posn = 0;
for (Iterator iter = aliases.iterator(); iter.hasNext();) {
String typeVariableAlias = (String) iter.next();
typeMap.put(typeVariableAlias,(!typeParametersSupplied?typeVariables[posn].getFirstBound():typeParameters[posn]));
posn++;
}
}
UnresolvedType parameterizedReturnType = parameterize(getGenericReturnType(),typeMap,isParameterized);
UnresolvedType[] parameterizedParameterTypes = new UnresolvedType[getGenericParameterTypes().length];
for (int i = 0; i < parameterizedParameterTypes.length; i++) {
parameterizedParameterTypes[i] =
parameterize(getGenericParameterTypes()[i], typeMap,isParameterized);
}
ResolvedMemberImpl ret = new ResolvedMemberImpl(
getKind(),
newDeclaringType,
getModifiers(),
parameterizedReturnType,
getName(),
parameterizedParameterTypes,
getExceptions(),
this
);
ret.setTypeVariables(getTypeVariables());
ret.setSourceContext(getSourceContext());
ret.setPosition(getStart(),getEnd());
ret.setParameterNames(getParameterNames());
return ret;
}
public void setTypeVariables(TypeVariable[] tvars) {
typeVariables = tvars;
}
public TypeVariable[] getTypeVariables() {
return typeVariables;
}
protected UnresolvedType parameterize(UnresolvedType aType, Map typeVariableMap, boolean inParameterizedType) {
if (aType instanceof TypeVariableReference) {
String variableName = ((TypeVariableReference)aType).getTypeVariable().getName();
if (!typeVariableMap.containsKey(variableName)) {
return aType; // if the type variable comes from the method (and not the type) thats OK
}
return (UnresolvedType) typeVariableMap.get(variableName);
} else if (aType.isParameterizedType()) {
if (inParameterizedType) {
return aType.parameterize(typeVariableMap);
} else {
return aType.getRawType();
}
} else if (aType.isArray()) {
// The component type might be a type variable (pr150095)
int dims = 1;
String sig = aType.getSignature();
while (sig.charAt(dims)=='[') dims++;
UnresolvedType componentSig = UnresolvedType.forSignature(sig.substring(dims));
UnresolvedType arrayType = ResolvedType.makeArray(parameterize(componentSig,typeVariableMap,inParameterizedType),dims);
return arrayType;
}
return aType;
}
/**
* If this member is defined by a parameterized super-type, return the erasure
* of that member.
* For example:
* interface I<T> { T foo(T aTea); }
* class C implements I<String> {
* String foo(String aString) { return "something"; }
* }
* The resolved member for C.foo has signature String foo(String). The
* erasure of that member is Object foo(Object) -- use upper bound of type
* variable.
* A type is a supertype of itself.
*/
public ResolvedMember getErasure() {
if (calculatedMyErasure) return myErasure;
calculatedMyErasure = true;
ResolvedType resolvedDeclaringType = (ResolvedType) getDeclaringType();
// this next test is fast, and the result is cached.
if (!resolvedDeclaringType.hasParameterizedSuperType()) {
return null;
} else {
// we have one or more parameterized super types.
// this member may be defined by one of them... we need to find out.
Collection declaringTypes = this.getDeclaringTypes(resolvedDeclaringType.getWorld());
for (Iterator iter = declaringTypes.iterator(); iter.hasNext();) {
ResolvedType aDeclaringType = (ResolvedType) iter.next();
if (aDeclaringType.isParameterizedType()) {
// we've found the (a?) parameterized type that defines this member.
// now get the erasure of it
ResolvedMemberImpl matchingMember = (ResolvedMemberImpl) aDeclaringType.lookupMemberNoSupers(this);
if (matchingMember != null && matchingMember.backingGenericMember != null) {
myErasure = matchingMember.backingGenericMember;
return myErasure;
}
}
}
}
return null;
}
private ResolvedMember myErasure = null;
private boolean calculatedMyErasure = false;
public boolean hasBackingGenericMember() {
return backingGenericMember!=null;
}
public ResolvedMember getBackingGenericMember() {
return backingGenericMember;
}
/**
* For ITDs, we use the default factory methods to build a resolved member, then alter a couple of characteristics
* using this method - this is safe.
*/
public void resetName(String newName) {this.name = newName;}
public void resetKind(Kind newKind) {this.kind=newKind; }
public void resetModifiers(int newModifiers) {this.modifiers=newModifiers;}
public void resetReturnTypeToObjectArray() {
returnType = UnresolvedType.OBJECTARRAY;
}
/**
* Returns a copy of this member but with the declaring type swapped.
* Copy only needs to be shallow.
* @param newDeclaringType
*/
public JoinPointSignature withSubstituteDeclaringType(ResolvedType newDeclaringType) {
JoinPointSignature ret = new JoinPointSignature(this,newDeclaringType);
return ret;
}
/**
* Returns true if this member matches the other. The matching takes into account
* name and parameter types only. When comparing parameter types, we allow any type
* variable to match any other type variable regardless of bounds.
*/
public boolean matches(ResolvedMember aCandidateMatch) {
ResolvedMemberImpl candidateMatchImpl = (ResolvedMemberImpl)aCandidateMatch;
if (!getName().equals(aCandidateMatch.getName())) return false;
UnresolvedType[] myParameterTypes = getGenericParameterTypes();
UnresolvedType[] candidateParameterTypes = aCandidateMatch.getGenericParameterTypes();
if (myParameterTypes.length != candidateParameterTypes.length) return false;
String myParameterSignature = getParameterSigWithBoundsRemoved();
String candidateParameterSignature = candidateMatchImpl.getParameterSigWithBoundsRemoved();
if (myParameterSignature.equals(candidateParameterSignature)) {
return true;
} else {
// try erasure
myParameterSignature = getParameterSigErasure();
candidateParameterSignature = candidateMatchImpl.getParameterSigErasure();
return myParameterSignature.equals(candidateParameterSignature);
}
}
/** converts e.g. <T extends Number>.... List<T> to just Ljava/util/List<T;>;
* whereas the full signature would be Ljava/util/List<T:Ljava/lang/Number;>;
*/
private String myParameterSignatureWithBoundsRemoved = null;
/**
* converts e.g. <T extends Number>.... List<T> to just Ljava/util/List;
*/
private String myParameterSignatureErasure = null;
// does NOT produce a meaningful java signature, but does give a unique string suitable for
// comparison.
private String getParameterSigWithBoundsRemoved() {
if (myParameterSignatureWithBoundsRemoved != null) return myParameterSignatureWithBoundsRemoved;
StringBuffer sig = new StringBuffer();
UnresolvedType[] myParameterTypes = getGenericParameterTypes();
for (int i = 0; i < myParameterTypes.length; i++) {
appendSigWithTypeVarBoundsRemoved(myParameterTypes[i], sig);
}
myParameterSignatureWithBoundsRemoved = sig.toString();
return myParameterSignatureWithBoundsRemoved;
}
private String getParameterSigErasure() {
if (myParameterSignatureErasure != null) return myParameterSignatureErasure;
StringBuffer sig = new StringBuffer();
UnresolvedType[] myParameterTypes = getParameterTypes();
for (int i = 0; i < myParameterTypes.length; i++) {
UnresolvedType thisParameter = myParameterTypes[i];
if (thisParameter.isTypeVariableReference()) {
sig.append(thisParameter.getUpperBound().getSignature());
} else {
sig.append(thisParameter.getSignature());
}
}
myParameterSignatureErasure = sig.toString();
return myParameterSignatureErasure;
}
// does NOT produce a meaningful java signature, but does give a unique string suitable for
// comparison.
private void appendSigWithTypeVarBoundsRemoved(UnresolvedType aType, StringBuffer toBuffer) {
if (aType.isTypeVariableReference()) {
toBuffer.append("T;");
} else if (aType.isParameterizedType()) {
toBuffer.append(aType.getRawType().getSignature());
toBuffer.append("<");
for (int i = 0; i < aType.getTypeParameters().length; i++) {
appendSigWithTypeVarBoundsRemoved(aType.getTypeParameters()[i], toBuffer);
}
toBuffer.append(">;");
} else {
toBuffer.append(aType.getSignature());
}
}
/**
* Useful for writing tests, returns *everything* we know about this member.
*/
public String toDebugString() {
StringBuffer r = new StringBuffer();
// modifiers
int mods = modifiers;
if ((mods & 4096)>0) mods = mods -4096; // remove synthetic (added in the ASM case but not in the BCEL case...)
if ((mods & 512)>0) mods = mods -512; // remove interface (added in the BCEL case but not in the ASM case...)
if ((mods & 131072)>0) mods = mods -131072; // remove deprecated (added in the ASM case but not in the BCEL case...)
String modsStr = Modifier.toString(mods);
if (modsStr.length()!=0) r.append(modsStr).append("("+mods+")").append(" ");
// type variables
if (typeVariables!=null && typeVariables.length>0) {
r.append("<");
for (int i = 0; i < typeVariables.length; i++) {
if (i>0) r.append(",");
TypeVariable t = typeVariables[i];
r.append(t.toDebugString());
}
r.append("> ");
}
// 'declaring' type
r.append(getGenericReturnType().toDebugString());
r.append(' ');
// name
r.append(declaringType.getName());
r.append('.');
r.append(name);
// parameter signature if a method
if (kind != FIELD) {
r.append("(");
UnresolvedType[] params = getGenericParameterTypes();
boolean parameterNamesExist = showParameterNames && parameterNames!=null && parameterNames.length==params.length;
if (params.length != 0) {
for (int i=0, len = params.length; i < len; i++) {
if (i>0) r.append(", ");
r.append(params[i].toDebugString());
if (parameterNamesExist) r.append(" ").append(parameterNames[i]);
}
}
r.append(")");
}
return r.toString();
}
// SECRETAPI - controlling whether parameter names come out in the debug string (for testing purposes)
public static boolean showParameterNames = true;
public String toGenericString() {
StringBuffer buf = new StringBuffer();
buf.append(getGenericReturnType().getSimpleName());
buf.append(' ');
buf.append(declaringType.getName());
buf.append('.');
buf.append(name);
if (kind != FIELD) {
buf.append("(");
UnresolvedType[] params = getGenericParameterTypes();
if (params.length != 0) {
buf.append(params[0].getSimpleName());
for (int i=1, len = params.length; i < len; i++) {
buf.append(", ");
buf.append(params[i].getSimpleName());
}
}
buf.append(")");
}
return buf.toString();
}
public TypeVariable getTypeVariableNamed(String name) {
// Check locally...
if (typeVariables!=null) {
for (int i = 0; i < typeVariables.length; i++) {
if (typeVariables[i].getName().equals(name)) return typeVariables[i];
}
}
// check the declaring type!
return declaringType.getTypeVariableNamed(name);
// Do generic aspects with ITDs that share type variables with the aspect and the target type and have their own tvars cause this to be messier?
}
public void evictWeavingState() { }
}
|
158,573 |
Bug 158573 changing value of variable in aspect results in adviceDidNotMatch warning
| null |
resolved fixed
|
cd9fd11
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-09-29T14:21:57Z | 2006-09-25T16:00:00Z |
tests/multiIncremental/PR158573/base/C.java
| |
158,573 |
Bug 158573 changing value of variable in aspect results in adviceDidNotMatch warning
| null |
resolved fixed
|
cd9fd11
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-09-29T14:21:57Z | 2006-09-25T16:00:00Z |
tests/src/org/aspectj/systemtest/incremental/tools/MultiProjectIncrementalTests.java
|
/* *******************************************************************
* Copyright (c) 2005 Contributors.
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Eclipse Public License v1.0
* which accompanies this distribution and is available at
* http://eclipse.org/legal/epl-v10.html
*
* Contributors:
* Andy Clement initial implementation
* ******************************************************************/
package org.aspectj.systemtest.incremental.tools;
import java.io.BufferedReader;
import java.io.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 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();
}
// --- 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);
}
}
|
158,573 |
Bug 158573 changing value of variable in aspect results in adviceDidNotMatch warning
| null |
resolved fixed
|
cd9fd11
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-09-29T14:21:57Z | 2006-09-25T16:00:00Z |
weaver/src/org/aspectj/weaver/CrosscuttingMembers.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.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import org.aspectj.weaver.bcel.BcelMethod;
import org.aspectj.weaver.bcel.BcelTypeMunger;
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.PerClause;
import org.aspectj.weaver.patterns.Pointcut;
import org.aspectj.weaver.patterns.PointcutRewriter;
/**
* This holds on to all members that have an invasive effect outside of
* there own compilation unit. These members need to be all gathered up and in
* a world before any weaving can take place.
*
* They are also important in the compilation process and need to be gathered
* up before the inter-type declaration weaving stage (unsurprisingly).
*
* All members are concrete.
*
* @author Jim Hugunin
*/
public class CrosscuttingMembers {
private ResolvedType inAspect;
private World world;
private PerClause perClause;
private List shadowMungers = new ArrayList(4);
private List typeMungers = new ArrayList(4);
private List lateTypeMungers = new ArrayList(0);
private List declareParents = new ArrayList(4);
private List declareSofts = new ArrayList(0);
private List declareDominates = new ArrayList(4);
// These are like declare parents type mungers
private List declareAnnotationsOnType = new ArrayList();
private List declareAnnotationsOnField = new ArrayList();
private List declareAnnotationsOnMethods = new ArrayList(); // includes ctors
private boolean shouldConcretizeIfNeeded = true;
public CrosscuttingMembers(ResolvedType inAspect, boolean shouldConcretizeIfNeeded) {
this.inAspect = inAspect;
this.world = inAspect.getWorld();
this.shouldConcretizeIfNeeded = shouldConcretizeIfNeeded;
}
// public void addConcreteShadowMungers(Collection c) {
// shadowMungers.addAll(c);
// }
public void addConcreteShadowMunger(ShadowMunger m) {
// assert m is concrete
shadowMungers.add(m);
}
public void addShadowMungers(Collection c) {
for (Iterator i = c.iterator(); i.hasNext(); ) {
addShadowMunger( (ShadowMunger)i.next() );
}
}
private void addShadowMunger(ShadowMunger m) {
if (inAspect.isAbstract()) return; // we don't do mungers for abstract aspects
addConcreteShadowMunger(m.concretize(inAspect, world, perClause));
}
public void addTypeMungers(Collection c) {
typeMungers.addAll(c);
}
public void addTypeMunger(ConcreteTypeMunger m) {
if (m == null) throw new Error("FIXME AV - should not happen or what ?");//return; //???
typeMungers.add(m);
}
public void addLateTypeMungers(Collection c) {
lateTypeMungers.addAll(c);
}
public void addLateTypeMunger(ConcreteTypeMunger m) {
lateTypeMungers.add(m);
}
public void addDeclares(Collection c) {
for (Iterator i = c.iterator(); i.hasNext(); ) {
addDeclare( (Declare)i.next() );
}
}
public void addDeclare(Declare declare) {
// this is not extensible, oh well
if (declare instanceof DeclareErrorOrWarning) {
ShadowMunger m = new Checker((DeclareErrorOrWarning)declare);
m.setDeclaringType(declare.getDeclaringType());
addShadowMunger(m);
} else if (declare instanceof DeclarePrecedence) {
declareDominates.add(declare);
} else if (declare instanceof DeclareParents) {
DeclareParents dp = (DeclareParents)declare;
exposeTypes(dp.getParents().getExactTypes());
declareParents.add(dp);
} else if (declare instanceof DeclareSoft) {
DeclareSoft d = (DeclareSoft)declare;
// Ordered so that during concretization we can check the related munger
ShadowMunger m = Advice.makeSoftener(world, d.getPointcut(), d.getException(),inAspect,d);
m.setDeclaringType(d.getDeclaringType());
Pointcut concretePointcut = d.getPointcut().concretize(inAspect, d.getDeclaringType(), 0,m);
m.pointcut = concretePointcut;
declareSofts.add(new DeclareSoft(d.getException(), concretePointcut));
addConcreteShadowMunger(m);
} else if (declare instanceof DeclareAnnotation) {
// FIXME asc perf Possible Improvement. Investigate why this is called twice in a weave ?
DeclareAnnotation da = (DeclareAnnotation)declare;
if (da.getAspect() == null) da.setAspect(this.inAspect);
if (da.isDeclareAtType()) {
declareAnnotationsOnType.add(da);
} else if (da.isDeclareAtField()) {
declareAnnotationsOnField.add(da);
} else if (da.isDeclareAtMethod() || da.isDeclareAtConstuctor()) {
declareAnnotationsOnMethods.add(da);
}
} else {
throw new RuntimeException("unimplemented");
}
}
public void exposeTypes(Collection typesToExpose) {
for (Iterator i = typesToExpose.iterator(); i.hasNext(); ) {
exposeType((UnresolvedType)i.next());
}
}
public void exposeType(UnresolvedType typeToExpose) {
if (ResolvedType.isMissing(typeToExpose)) return;
if (typeToExpose.isParameterizedType() || typeToExpose.isRawType()) {
if (typeToExpose instanceof ResolvedType) {
typeToExpose = ((ResolvedType)typeToExpose).getGenericType();
} else {
typeToExpose = UnresolvedType.forSignature(typeToExpose.getErasureSignature());
}
}
ResolvedMember member = new ResolvedMemberImpl(
Member.STATIC_INITIALIZATION, typeToExpose, 0, ResolvedType.VOID, "", UnresolvedType.NONE);
addTypeMunger(world.concreteTypeMunger(
new PrivilegedAccessMunger(member), inAspect));
}
public void addPrivilegedAccesses(Collection accessedMembers) {
for (Iterator i = accessedMembers.iterator(); i.hasNext(); ) {
addPrivilegedAccess( (ResolvedMember)i.next() );
}
}
private void addPrivilegedAccess(ResolvedMember member) {
//System.err.println("add priv access: " + member);
addTypeMunger(world.concreteTypeMunger(new PrivilegedAccessMunger(member), inAspect));
}
public Collection getCflowEntries() {
ArrayList ret = new ArrayList();
for (Iterator i = shadowMungers.iterator(); i.hasNext(); ) {
ShadowMunger m = (ShadowMunger)i.next();
if (m instanceof Advice) {
Advice a = (Advice)m;
if (a.getKind().isCflow()) {
ret.add(a);
}
}
}
return ret;
}
/**
* Updates the records if something has changed. This is called at most twice, firstly
* whilst collecting ITDs and declares. At this point the CrosscuttingMembers we're
* comparing ourselves with doesn't know about shadowmungers. Therefore a straight comparison
* with the existing list of shadowmungers would return that something has changed
* even though it might not have, so in this first round we ignore the shadowMungers.
* The second time this is called is whilst we're preparing to weave. At this point
* we know everything in the system and so we're able to compare the shadowMunger list.
* (see bug 129163)
*
* @param other
* @param careAboutShadowMungers
* @return true if something has changed since the last time this method was
* called, false otherwise
*/
public boolean replaceWith(CrosscuttingMembers other,boolean careAboutShadowMungers) {
boolean changed = false;
if (careAboutShadowMungers) {
if (perClause == null || !perClause.equals(other.perClause)) {
changed = true;
perClause = other.perClause;
}
}
//XXX all of the below should be set equality rather than list equality
//System.err.println("old: " + shadowMungers + " new: " + other.shadowMungers);
if (careAboutShadowMungers) {
// bug 129163: use set equality rather than list equality
Set theseShadowMungers = new HashSet();
Set theseInlinedAroundMungers = new HashSet();
for (Iterator iter = shadowMungers.iterator(); iter
.hasNext();) {
ShadowMunger munger = (ShadowMunger) iter.next();
if (munger instanceof Advice) {
Advice adviceMunger = (Advice)munger;
// bug 154054: if we're around advice that has been inlined
// then we need to do more checking than existing equals
// methods allow
if (!world.isXnoInline() && adviceMunger.getKind().equals(AdviceKind.Around)) {
theseInlinedAroundMungers.add(adviceMunger);
} else {
theseShadowMungers.add(adviceMunger);
}
} else {
theseShadowMungers.add(munger);
}
}
Set tempSet = new HashSet();
tempSet.addAll(other.shadowMungers);
Set otherShadowMungers = new HashSet();
Set otherInlinedAroundMungers = new HashSet();
for (Iterator iter = tempSet.iterator(); iter.hasNext();) {
ShadowMunger munger = (ShadowMunger) iter.next();
if (munger instanceof Advice) {
Advice adviceMunger = (Advice)munger;
// bug 154054: if we're around advice that has been inlined
// then we need to do more checking than existing equals
// methods allow
if (!world.isXnoInline() && adviceMunger.getKind().equals(AdviceKind.Around)) {
otherInlinedAroundMungers.add(rewritePointcutInMunger(adviceMunger));
} else {
otherShadowMungers.add(rewritePointcutInMunger(adviceMunger));
}
} else {
otherShadowMungers.add(rewritePointcutInMunger(munger));
}
}
if (!theseShadowMungers.equals(otherShadowMungers)) {
changed = true;
}
if (!equivalent(theseInlinedAroundMungers,otherInlinedAroundMungers)) {
changed = true;
}
// replace the existing list of shadowmungers with the
// new ones in case anything like the sourcelocation has
// changed, however, don't want this flagged as a change
// which will force a full build - bug 134541
shadowMungers = other.shadowMungers;
}
// bug 129163: use set equality rather than list equality and
// if we dont care about shadow mungers then ignore those
// typeMungers which are created to help with the implementation
// of shadowMungers
Set theseTypeMungers = new HashSet();
Set otherTypeMungers = new HashSet();
if (!careAboutShadowMungers) {
for (Iterator iter = typeMungers.iterator(); iter.hasNext();) {
Object o = iter.next();
if (o instanceof BcelTypeMunger) {
BcelTypeMunger typeMunger = (BcelTypeMunger) o;
if (!typeMunger.existsToSupportShadowMunging()) {
theseTypeMungers.add(typeMunger);
}
} else {
theseTypeMungers.add(o);
}
}
for (Iterator iter = other.typeMungers.iterator(); iter.hasNext();) {
Object o = iter.next();
if (o instanceof BcelTypeMunger) {
BcelTypeMunger typeMunger = (BcelTypeMunger) o;
if (!typeMunger.existsToSupportShadowMunging()) {
otherTypeMungers.add(typeMunger);
}
} else {
otherTypeMungers.add(o);
}
}
} else {
theseTypeMungers.addAll(typeMungers);
otherTypeMungers.addAll(other.typeMungers);
}
// initial go at equivalence logic rather than set compare (see pr133532)
// if (theseTypeMungers.size()!=otherTypeMungers.size()) {
// changed = true;
// typeMungers = other.typeMungers;
// } else {
// boolean foundInequality=false;
// for (Iterator iter = theseTypeMungers.iterator(); iter.hasNext() && !foundInequality;) {
// Object thisOne = (Object) iter.next();
// boolean foundInOtherSet = false;
// for (Iterator iterator = otherTypeMungers.iterator(); iterator.hasNext();) {
// Object otherOne = (Object) iterator.next();
// if (thisOne instanceof ConcreteTypeMunger && otherOne instanceof ConcreteTypeMunger) {
// if (((ConcreteTypeMunger)thisOne).equivalentTo(otherOne)) {
// foundInOtherSet=true;
// } else if (thisOne.equals(otherOne)) {
// foundInOtherSet=true;
// }
// } else {
// if (thisOne.equals(otherOne)) {
// foundInOtherSet=true;
// }
// }
// }
// if (!foundInOtherSet) foundInequality=true;
// }
// if (foundInequality) {
// changed = true;
// typeMungers = other.typeMungers;
//// } else {
//// typeMungers = other.typeMungers;
// }
// }
if (!theseTypeMungers.equals(otherTypeMungers)) {
changed = true;
typeMungers = other.typeMungers;
}
if (!lateTypeMungers.equals(other.lateTypeMungers)) {
changed = true;
lateTypeMungers = other.lateTypeMungers;
}
if (!declareDominates.equals(other.declareDominates)) {
changed = true;
declareDominates = other.declareDominates;
}
if (!declareParents.equals(other.declareParents)) {
changed = true;
declareParents = other.declareParents;
}
if (!declareSofts.equals(other.declareSofts)) {
changed = true;
declareSofts = other.declareSofts;
}
// DECAT for when attempting to replace an aspect
if (!declareAnnotationsOnType.equals(other.declareAnnotationsOnType)) {
changed = true;
declareAnnotationsOnType = other.declareAnnotationsOnType;
}
if (!declareAnnotationsOnField.equals(other.declareAnnotationsOnField)) {
changed = true;
declareAnnotationsOnField = other.declareAnnotationsOnField;
}
if (!declareAnnotationsOnMethods.equals(other.declareAnnotationsOnMethods)) {
changed = true;
declareAnnotationsOnMethods = other.declareAnnotationsOnMethods;
}
return changed;
}
private boolean equivalent(Set theseInlinedAroundMungers, Set otherInlinedAroundMungers) {
if (theseInlinedAroundMungers.size() != otherInlinedAroundMungers.size()) {
return false;
}
for (Iterator iter = theseInlinedAroundMungers.iterator(); iter.hasNext();) {
Advice thisAdvice = (Advice) iter.next();
boolean foundIt = false;
for (Iterator iterator = otherInlinedAroundMungers.iterator(); iterator.hasNext();) {
Advice otherAdvice = (Advice) iterator.next();
if (thisAdvice.equals(otherAdvice)) {
if(thisAdvice.getSignature() instanceof BcelMethod) {
if (((BcelMethod)thisAdvice.getSignature())
.isEquivalentTo(otherAdvice.getSignature()) ) {
foundIt = true;
continue;
}
}
return false;
}
}
if (!foundIt) {
return false;
}
}
return true;
}
private ShadowMunger rewritePointcutInMunger(ShadowMunger munger) {
PointcutRewriter pr = new PointcutRewriter();
Pointcut p = munger.getPointcut();
Pointcut newP = pr.rewrite(p);
if (p.m_ignoreUnboundBindingForNames.length!=0) {// *sigh* dirty fix for dirty hacky implementation pr149305
newP.m_ignoreUnboundBindingForNames = p.m_ignoreUnboundBindingForNames;
}
munger.setPointcut(newP);
return munger;
}
public void setPerClause(PerClause perClause) {
if (this.shouldConcretizeIfNeeded) {
this.perClause = perClause.concretize(inAspect);
} else {
this.perClause = perClause;
}
}
public List getDeclareDominates() {
return declareDominates;
}
public List getDeclareParents() {
return declareParents;
}
public List getDeclareSofts() {
return declareSofts;
}
public List getShadowMungers() {
return shadowMungers;
}
public List getTypeMungers() {
return typeMungers;
}
public List getLateTypeMungers() {
return lateTypeMungers;
}
public List getDeclareAnnotationOnTypes() {
return declareAnnotationsOnType;
}
public List getDeclareAnnotationOnFields() {
return declareAnnotationsOnField;
}
/**
* includes declare @method and @constructor
*/
public List getDeclareAnnotationOnMethods() {
return declareAnnotationsOnMethods;
}
}
|
158,573 |
Bug 158573 changing value of variable in aspect results in adviceDidNotMatch warning
| null |
resolved fixed
|
cd9fd11
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-09-29T14:21:57Z | 2006-09-25T16: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;
}
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);
}
}
|
152,366 |
Bug 152366 LTW Within Patterns Should Accept AND For Consistency
|
The load-time weaving definition system accepts AND in addition to && for pointcuts, but it silently accepts and then fails to work with type patterns that use AND. Such type patterns are important when creating exceptions (e.g., excluding weblogic..* && !weblogic.jdbc..*) and using AND is also helpful here. I've attached a patch to support this and tests to show it's working.
|
resolved fixed
|
7b831ff
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-10-03T14:30:21Z | 2006-07-31T18:20:00Z |
loadtime/src/org/aspectj/weaver/loadtime/definition/DocumentParser.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.definition;
import java.io.InputStream;
import java.net.URL;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParserFactory;
import org.aspectj.util.LangUtil;
import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.DefaultHandler;
import org.xml.sax.helpers.XMLReaderFactory;
/**
* FIXME AV - doc, concrete aspect
*
* @author <a href="mailto:alex AT gnilux DOT com">Alexandre Vasseur</a>
*/
public class DocumentParser extends DefaultHandler {
/**
* The current DTD public id. The matching dtd will be searched as a resource.
*/
private final static String DTD_PUBLIC_ID = "-//AspectJ//DTD 1.5.0//EN";
/**
* The DTD alias, for better user experience.
*/
private final static String DTD_PUBLIC_ID_ALIAS = "-//AspectJ//DTD//EN";
/**
* A handler to the DTD stream so that we are only using one file descriptor
*/
private final static InputStream DTD_STREAM = DocumentParser.class.getResourceAsStream("/aspectj_1_5_0.dtd");
private final static String ASPECTJ_ELEMENT = "aspectj";
private final static String WEAVER_ELEMENT = "weaver";
private final static String DUMP_ELEMENT = "dump";
private final static String DUMP_BEFOREANDAFTER_ATTRIBUTE = "beforeandafter";
private final static String INCLUDE_ELEMENT = "include";
private final static String EXCLUDE_ELEMENT = "exclude";
private final static String OPTIONS_ATTRIBUTE = "options";
private final static String ASPECTS_ELEMENT = "aspects";
private final static String ASPECT_ELEMENT = "aspect";
private final static String CONCRETE_ASPECT_ELEMENT = "concrete-aspect";
private final static String NAME_ATTRIBUTE = "name";
private final static String EXTEND_ATTRIBUTE = "extends";
private final static String PRECEDENCE_ATTRIBUTE = "precedence";
private final static String POINTCUT_ELEMENT = "pointcut";
private final static String WITHIN_ATTRIBUTE = "within";
private final static String EXPRESSION_ATTRIBUTE = "expression";
private final Definition m_definition;
private boolean m_inAspectJ;
private boolean m_inWeaver;
private boolean m_inAspects;
private Definition.ConcreteAspect m_lastConcreteAspect;
private DocumentParser() {
m_definition = new Definition();
}
public static Definition parse(final URL url) throws Exception {
InputStream in = null;
try {
DocumentParser parser = new DocumentParser();
XMLReader xmlReader = getXMLReader();
xmlReader.setContentHandler(parser);
xmlReader.setErrorHandler(parser);
try {
xmlReader.setFeature("http://xml.org/sax/features/validation", false);
} catch (SAXException e) {
;//fine, the parser don't do validation
}
try {
xmlReader.setFeature("http://xml.org/sax/features/external-general-entities", false);
} catch (SAXException e) {
;//fine, the parser don't do validation
}
try {
xmlReader.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
} catch (SAXException e) {
;//fine, the parser don't do validation
}
xmlReader.setEntityResolver(parser);
in = url.openStream();
xmlReader.parse(new InputSource(in));
return parser.m_definition;
} finally {
try {
in.close();
} catch (Throwable t) {
;
}
}
}
private static XMLReader getXMLReader() throws SAXException, ParserConfigurationException {
XMLReader xmlReader = null;
/* Try this first for Java 5 */
try {
xmlReader = XMLReaderFactory.createXMLReader();
}
/* .. and ignore "System property ... not set" and then try this instead */
catch (SAXException ex) {
xmlReader = SAXParserFactory.newInstance().newSAXParser().getXMLReader();
}
return xmlReader;
}
public InputSource resolveEntity(String publicId, String systemId) throws SAXException {
if (publicId.equals(DTD_PUBLIC_ID) || publicId.equals(DTD_PUBLIC_ID_ALIAS)) {
InputStream in = DTD_STREAM;
if (in == null) {
System.err.println(
"AspectJ - WARN - could not read DTD "
+ publicId
);
return null;
} else {
return new InputSource(in);
}
} else {
System.err.println(
"AspectJ - WARN - unknown DTD "
+ publicId
+ " - consider using "
+ DTD_PUBLIC_ID
);
return null;
}
}
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
if (ASPECT_ELEMENT.equals(qName)) {
String name = attributes.getValue(NAME_ATTRIBUTE);
if (!isNull(name)) {
m_definition.getAspectClassNames().add(name);
}
} else if (WEAVER_ELEMENT.equals(qName)) {
String options = attributes.getValue(OPTIONS_ATTRIBUTE);
if (!isNull(options)) {
m_definition.appendWeaverOptions(options);
}
m_inWeaver = true;
} else if (CONCRETE_ASPECT_ELEMENT.equals(qName)) {
String name = attributes.getValue(NAME_ATTRIBUTE);
String extend = attributes.getValue(EXTEND_ATTRIBUTE);
String precedence = attributes.getValue(PRECEDENCE_ATTRIBUTE);
if (!isNull(name)) {
if (isNull(precedence) && !isNull(extend)) {//if no precedence, then extends must be there
m_lastConcreteAspect = new Definition.ConcreteAspect(name, extend);
} else if (!isNull(precedence)) {
// wether a pure precedence def, or an extendsANDprecedence def.
m_lastConcreteAspect = new Definition.ConcreteAspect(name, extend, precedence);
}
m_definition.getConcreteAspects().add(m_lastConcreteAspect);
}
} else if (POINTCUT_ELEMENT.equals(qName) && m_lastConcreteAspect != null) {
String name = attributes.getValue(NAME_ATTRIBUTE);
String expression = attributes.getValue(EXPRESSION_ATTRIBUTE);
if (!isNull(name) && !isNull(expression)) {
m_lastConcreteAspect.pointcuts.add(new Definition.Pointcut(name, replaceXmlAnd(expression)));
}
} else if (ASPECTJ_ELEMENT.equals(qName)) {
if (m_inAspectJ) {
throw new SAXException("Found nested <aspectj> element");
}
m_inAspectJ = true;
} else if (ASPECTS_ELEMENT.equals(qName)) {
m_inAspects = true;
} else if (INCLUDE_ELEMENT.equals(qName) && m_inWeaver) {
String typePattern = attributes.getValue(WITHIN_ATTRIBUTE);
if (!isNull(typePattern)) {
m_definition.getIncludePatterns().add(typePattern);
}
} else if (EXCLUDE_ELEMENT.equals(qName) && m_inWeaver) {
String typePattern = attributes.getValue(WITHIN_ATTRIBUTE);
if (!isNull(typePattern)) {
m_definition.getExcludePatterns().add(typePattern);
}
} else if (DUMP_ELEMENT.equals(qName) && m_inWeaver) {
String typePattern = attributes.getValue(WITHIN_ATTRIBUTE);
if (!isNull(typePattern)) {
m_definition.getDumpPatterns().add(typePattern);
}
String beforeAndAfter = attributes.getValue(DUMP_BEFOREANDAFTER_ATTRIBUTE);
if (isTrue(beforeAndAfter)) {
m_definition.setDumpBefore(true);
}
} else if (EXCLUDE_ELEMENT.equals(qName) && m_inAspects) {
String typePattern = attributes.getValue(WITHIN_ATTRIBUTE);
if (!isNull(typePattern)) {
m_definition.getAspectExcludePatterns().add(typePattern);
}
} else if (INCLUDE_ELEMENT.equals(qName) && m_inAspects) {
String typePattern = attributes.getValue(WITHIN_ATTRIBUTE);
if (!isNull(typePattern)) {
m_definition.getAspectIncludePatterns().add(typePattern);
}
} else {
throw new SAXException("Unknown element while parsing <aspectj> element: " + qName);
}
super.startElement(uri, localName, qName, attributes);
}
public void endElement(String uri, String localName, String qName) throws SAXException {
if (CONCRETE_ASPECT_ELEMENT.equals(qName)) {
m_lastConcreteAspect = null;
} else if (ASPECTJ_ELEMENT.equals(qName)) {
m_inAspectJ = false;
} else if (WEAVER_ELEMENT.equals(qName)) {
m_inWeaver = false;
} else if (ASPECTS_ELEMENT.equals(qName)) {
m_inAspects = false;
}
super.endElement(uri, localName, qName);
}
//TODO AV - define what we want for XML parser error - for now stderr
public void warning(SAXParseException e) throws SAXException {
super.warning(e);
}
public void error(SAXParseException e) throws SAXException {
super.error(e);
}
public void fatalError(SAXParseException e) throws SAXException {
super.fatalError(e);
}
private static String replaceXmlAnd(String expression) {
//TODO AV do we need to handle "..)AND" or "AND(.." ?
return LangUtil.replace(expression, " AND ", " && ");
}
private boolean isNull(String s) {
return (s == null || s.length() <= 0);
}
private boolean isTrue(String s) {
return (s != null && s.equals("true"));
}
}
|
152,366 |
Bug 152366 LTW Within Patterns Should Accept AND For Consistency
|
The load-time weaving definition system accepts AND in addition to && for pointcuts, but it silently accepts and then fails to work with type patterns that use AND. Such type patterns are important when creating exceptions (e.g., excluding weblogic..* && !weblogic.jdbc..*) and using AND is also helpful here. I've attached a patch to support this and tests to show it's working.
|
resolved fixed
|
7b831ff
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-10-03T14:30:21Z | 2006-07-31T18:20:00Z |
tests/src/org/aspectj/systemtest/ajc150/ltw/LTWTests.java
|
/*******************************************************************************
* Copyright (c) 2005 Contributors.
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Eclipse Public License v1.0
* which accompanies this distribution and is available at
* http://eclipse.org/legal/epl-v10.html
*
* Contributors:
* Matthew Webster initial implementation
*******************************************************************************/
package org.aspectj.systemtest.ajc150.ltw;
import java.io.File;
import java.util.Enumeration;
import java.util.Properties;
import junit.framework.Test;
import org.aspectj.testing.XMLBasedAjcTestCase;
import org.aspectj.weaver.tools.WeavingAdaptor;
public class LTWTests extends org.aspectj.testing.XMLBasedAjcTestCase {
public static Test suite() {
return XMLBasedAjcTestCase.loadSuite(LTWTests.class);
}
protected File getSpecFile() {
return new File("../tests/src/org/aspectj/systemtest/ajc150/ltw/ltw.xml");
}
public void test001(){
runTest("Ensure 1st aspect is rewoven when weaving 2nd aspect");
}
public void testOutxmlFile (){
runTest("Ensure valid aop.xml file is generated");
}
public void testOutxmlJar (){
runTest("Ensure valid aop.xml is generated for -outjar");
}
public void testNoAopxml(){
setSystemProperty(WeavingAdaptor.WEAVING_ADAPTOR_VERBOSE,"true");
runTest("Ensure no weaving without visible aop.xml");
}
public void testDefineConcreteAspect(){
runTest("Define concrete sub-aspect using aop.xml");
}
public void testDeclareAbstractAspect(){
// setSystemProperty(WeavingAdaptor.WEAVING_ADAPTOR_VERBOSE,"true");
// setSystemProperty(WeavingAdaptor.SHOW_WEAVE_INFO_PROPERTY,"true");
runTest("Use abstract aspect for ITD using aop.xml");
}
public void testAspectsInclude () {
runTest("Ensure a subset of inherited aspects is used for weaving");
}
public void testAspectsIncludeWithLintWarning () {
runTest("Ensure weaver lint warning issued when an aspect is not used for weaving");
}
public void testXsetEnabled () {
runTest("Set Xset properties enabled");
}
public void testXsetDisabled () {
runTest("Set Xset properties disabled");
}
public void testXlintfileEmpty () {
runTest("Empty Xlint.properties file");
}
public void testXlintfileMissing () {
runTest("Warning with missing Xlint.properties file");
}
public void testXlintWarningAdviceDidNotMatchSuppressed () {
runTest("Warning when advice doesn't match suppressed for LTW");
}
public void testXlintfile () {
runTest("Override suppressing of warning when advice doesn't match using -Xlintfile");
}
public void testXlintDefault () {
runTest("Warning when advice doesn't match using -Xlint:default");
}
public void testXlintWarning () {
runTest("Override suppressing of warning when advice doesn't match using -Xlint:warning");
}
public void testNonstandardJarFiles() {
runTest("Nonstandard jar file extensions");
}
public void testOddzipOnClasspath() {
runTest("Odd zip on classpath");
}
public void testJ14LTWWithXML() {
runTest("JDK14 LTW with XML");
}
public void testJ14LTWWithASPECTPATH() {
runTest("JDK14 LTW with ASPECTPATH");
}
//public void testDiscardingWovenTypes() {
// runTest("discarding woven types - 1");
//}
public void testWeavingTargetOfCallAggressivelyInLTW_DeclareParents_pr133770() {
runTest("aggressive ltw - decp");
}
public void testWeavingTargetOfCallAggressivelyInLTW_DeclareParents_pr133770_Deactivate() {
runTest("aggressive ltw - decp - deactivate");
}
public void testWeavingTargetOfCallAggressivelyInLTW_DeclareParents_Nested_pr133770() {
runTest("aggressive ltw - decp - 2");
}
public void testWeavingTargetOfCallAggressivelyInLTW_DeclareParents_Hierarchy_pr133770() {
runTest("aggressive ltw - hierarchy");
}
public void testSeparateCompilationDeclareParentsCall_pr133770() {
runTest("separate compilation with ltw: declare parents and call");
}
public void testConfigutationSystemProperty_pr149289 () {
runTest("override default path using -Dorg.aspectj.weaver.loadtime.configuration");
}
/*
* Allow system properties to be set and restored
* TODO maw move to XMLBasedAjcTestCase or RunSpec
*/
private final static String NULL = "null";
private Properties savedProperties;
protected void setSystemProperty (String key, String value) {
Properties systemProperties = System.getProperties();
copyProperty(key,systemProperties,savedProperties);
systemProperties.setProperty(key,value);
}
private static void copyProperty (String key, Properties from, Properties to) {
String value = from.getProperty(key,NULL);
to.setProperty(key,value);
}
protected void setUp() throws Exception {
super.setUp();
savedProperties = new Properties();
}
protected void tearDown() throws Exception {
super.tearDown();
/* Restore system properties */
Properties systemProperties = System.getProperties();
for (Enumeration enu = savedProperties.keys(); enu.hasMoreElements(); ) {
String key = (String)enu.nextElement();
String value = savedProperties.getProperty(key);
if (value == NULL) systemProperties.remove(key);
else systemProperties.setProperty(key,value);
}
}
}
|
156,904 |
Bug 156904 Incorrect warning when advising a private method of a private inner class
|
The Eclipse AJDT give an incorrect warning when you want to advise a private method of a private inner class. When I want to advise a private method in a private inner class, like this public class Outer { private class Inner { private void myMethod() } } Using the following poincut: poincut innerpointcut():execution( * Outer.Inner.myMethod() ); and advice: before():innerpointcut() { System.out.println( "executing!" ); } I get a warning "invalidAbsoluteTypeName" next to my pointcut, but next to the advice, there is a marker that points to the private method.
|
resolved fixed
|
782ade2
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-10-03T15:00:34Z | 2006-09-11T18:40:00Z |
tests/bugs153/pr156904/inDiffPkgAndImport/Outer.java
| |
156,904 |
Bug 156904 Incorrect warning when advising a private method of a private inner class
|
The Eclipse AJDT give an incorrect warning when you want to advise a private method of a private inner class. When I want to advise a private method in a private inner class, like this public class Outer { private class Inner { private void myMethod() } } Using the following poincut: poincut innerpointcut():execution( * Outer.Inner.myMethod() ); and advice: before():innerpointcut() { System.out.println( "executing!" ); } I get a warning "invalidAbsoluteTypeName" next to my pointcut, but next to the advice, there is a marker that points to the private method.
|
resolved fixed
|
782ade2
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-10-03T15:00:34Z | 2006-09-11T18:40:00Z |
tests/bugs153/pr156904/inDiffPkgWithoutImport/Outer.java
| |
156,904 |
Bug 156904 Incorrect warning when advising a private method of a private inner class
|
The Eclipse AJDT give an incorrect warning when you want to advise a private method of a private inner class. When I want to advise a private method in a private inner class, like this public class Outer { private class Inner { private void myMethod() } } Using the following poincut: poincut innerpointcut():execution( * Outer.Inner.myMethod() ); and advice: before():innerpointcut() { System.out.println( "executing!" ); } I get a warning "invalidAbsoluteTypeName" next to my pointcut, but next to the advice, there is a marker that points to the private method.
|
resolved fixed
|
782ade2
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-10-03T15:00:34Z | 2006-09-11T18:40:00Z |
tests/bugs153/pr156904/inSamePkg/Outer.java
| |
156,904 |
Bug 156904 Incorrect warning when advising a private method of a private inner class
|
The Eclipse AJDT give an incorrect warning when you want to advise a private method of a private inner class. When I want to advise a private method in a private inner class, like this public class Outer { private class Inner { private void myMethod() } } Using the following poincut: poincut innerpointcut():execution( * Outer.Inner.myMethod() ); and advice: before():innerpointcut() { System.out.println( "executing!" ); } I get a warning "invalidAbsoluteTypeName" next to my pointcut, but next to the advice, there is a marker that points to the private method.
|
resolved fixed
|
782ade2
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-10-03T15:00:34Z | 2006-09-11T18:40:00Z |
tests/src/org/aspectj/systemtest/ajc153/Ajc153Tests.java
|
/*******************************************************************************
* Copyright (c) 2006 IBM
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Andy Clement - initial API and implementation
*******************************************************************************/
package org.aspectj.systemtest.ajc153;
import java.io.File;
import junit.framework.Test;
import org.aspectj.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 testNoIllegalStateExceptionWithGenericInnerAspect_pr156058() { runTest("no IllegalStateException with generic inner aspect"); }
// public void testNegatedAnnotationMatchingProblem_pr153464() { runTest("negated annotation matching problem");}
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 static Test suite() {
return XMLBasedAjcTestCase.loadSuite(Ajc153Tests.class);
}
protected File getSpecFile() {
return new File("../tests/src/org/aspectj/systemtest/ajc153/ajc153.xml");
}
}
|
156,904 |
Bug 156904 Incorrect warning when advising a private method of a private inner class
|
The Eclipse AJDT give an incorrect warning when you want to advise a private method of a private inner class. When I want to advise a private method in a private inner class, like this public class Outer { private class Inner { private void myMethod() } } Using the following poincut: poincut innerpointcut():execution( * Outer.Inner.myMethod() ); and advice: before():innerpointcut() { System.out.println( "executing!" ); } I get a warning "invalidAbsoluteTypeName" next to my pointcut, but next to the advice, there is a marker that points to the private method.
|
resolved fixed
|
782ade2
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-10-03T15:00:34Z | 2006-09-11T18:40:00Z |
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 = lookupTypeInWorld(scope.getWorld(), fullyQualifiedName);
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;
}
private ResolvedType lookupTypeInWorld(World world, String typeName) {
ResolvedType ret = world.resolve(UnresolvedType.forName(typeName),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) {
if (!verifyTypeParameters(aType.resolve(scope.getWorld()),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();
}
ResolvedType type = TypeFactory.createParameterizedType(aType.resolve(scope.getWorld()), 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);
}
}
|
159,143 |
Bug 159143 subtype pattern not working for declare annotation on method
|
Using AspectJ 1.5.3.200609271036, when declaring an annotation on a method, get unexpected error when using subtype wildcard for the declaring type. E.g., declare @method : void Foo+.foo() : @MethodAnnotation; Error text: "The method 'void Foo+.foo()' does not exist"
|
resolved fixed
|
513564a
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-10-04T07:27:44Z | 2006-09-28T16:13:20Z |
tests/bugs153/pr159143/DeclareMethodAnnotation.java
| |
159,143 |
Bug 159143 subtype pattern not working for declare annotation on method
|
Using AspectJ 1.5.3.200609271036, when declaring an annotation on a method, get unexpected error when using subtype wildcard for the declaring type. E.g., declare @method : void Foo+.foo() : @MethodAnnotation; Error text: "The method 'void Foo+.foo()' does not exist"
|
resolved fixed
|
513564a
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-10-04T07:27:44Z | 2006-09-28T16:13:20Z |
tests/src/org/aspectj/systemtest/ajc153/Ajc153Tests.java
|
/*******************************************************************************
* Copyright (c) 2006 IBM
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Andy Clement - initial API and implementation
*******************************************************************************/
package org.aspectj.systemtest.ajc153;
import java.io.File;
import junit.framework.Test;
import org.aspectj.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 testNoIllegalStateExceptionWithGenericInnerAspect_pr156058() { runTest("no IllegalStateException with generic inner aspect"); }
// public void testNegatedAnnotationMatchingProblem_pr153464() { runTest("negated annotation matching problem");}
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 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");
}
}
|
159,896 |
Bug 159896 advice from injars do not have unique handles with the JDTLikeHandleProvider
|
Advice of the same kind contained in the same aspect currently do not have unique handles if the aspect is on the aspectpath.
|
resolved fixed
|
d532892
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-10-06T16:29:03Z | 2006-10-05T14:53:20Z |
tests/features153/jdtlikehandleprovider/ClassForAspectpath.java
| |
159,896 |
Bug 159896 advice from injars do not have unique handles with the JDTLikeHandleProvider
|
Advice of the same kind contained in the same aspect currently do not have unique handles if the aspect is on the aspectpath.
|
resolved fixed
|
d532892
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-10-06T16:29:03Z | 2006-10-05T14:53:20Z |
tests/src/org/aspectj/systemtest/ajc153/JDTLikeHandleProviderTests.java
|
/********************************************************************
* Copyright (c) 2006 Contributors. All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Eclipse Public License v1.0
* which accompanies this distribution and is available at
* http://eclipse.org/legal/epl-v10.html
*
* Contributors: IBM Corporation - initial API and implementation
* Helen Hawkins - initial version
*******************************************************************/
package org.aspectj.systemtest.ajc153;
import java.io.File;
import java.util.Iterator;
import java.util.List;
import junit.framework.Test;
import org.aspectj.asm.AsmManager;
import org.aspectj.asm.IElementHandleProvider;
import org.aspectj.asm.IHierarchy;
import org.aspectj.asm.IProgramElement;
import org.aspectj.asm.internal.JDTLikeHandleProvider;
import org.aspectj.testing.XMLBasedAjcTestCase;
public class JDTLikeHandleProviderTests extends XMLBasedAjcTestCase {
IElementHandleProvider handleProvider;
protected void setUp() throws Exception {
super.setUp();
handleProvider = AsmManager.getDefault().getHandleProvider();
AsmManager.getDefault().setHandleProvider(new JDTLikeHandleProvider());
}
protected void tearDown() throws Exception {
super.tearDown();
AsmManager.getDefault().setHandleProvider(handleProvider);
}
public void testMoreThanOneNamedPointcut() {
runTest("More than one named pointcut");
}
public void testAspectHandle() {
runTest("aspect handle");
IHierarchy top = AsmManager.getDefault().getHierarchy();
IProgramElement pe = top.findElementForType("pkg", "A1");
String expected = "<pkg*A1.aj}A1";
String found = pe.getHandleIdentifier();
assertEquals("handleIdentifier - expected " + expected + ", but found "
+ found, expected, found);
}
public void testAdviceHandle() {
runTest("advice handle");
compareHandles(IProgramElement.Kind.ADVICE,
"before(): <anonymous pointcut>",
"<pkg*A2.aj}A2&before");
}
public void testPointcutHandle() {
runTest("pointcut handle");
compareHandles(IProgramElement.Kind.POINTCUT,
"p()",
"<pkg*A4.aj}A4+p");
}
public void testGetIPEWithAspectHandle() {
runTest("get IProgramElement with aspect handle");
IHierarchy top = AsmManager.getDefault().getHierarchy();
String handle = "<pkg*A1.aj}A1";
IProgramElement ipe = top.getElement(handle);
assertNotNull("should have found ipe with handle " + handle, ipe);
IProgramElement ipe2 = top.getElement(handle);
assertEquals("should be the same IPE",ipe,ipe2);
}
public void testAdviceHandleWithCrossCutting() {
runTest("advice handle with crosscutting");
compareHandles(IProgramElement.Kind.ADVICE,
"before(): <anonymous pointcut>",
"<pkg*A3.aj}A3&before");
}
public void testPointcutHandleWithArgs() {
runTest("pointcut handle with args");
compareHandles(IProgramElement.Kind.POINTCUT,
"p(java.lang.Integer)",
"*A6.aj}A6+p+QInteger;");
}
public void testAdviceHandleWithArgs() {
runTest("advice handle with args");
compareHandles(IProgramElement.Kind.ADVICE,
"afterReturning(java.lang.Integer): p..",
"<pkg*A8.aj}A8&afterReturning&QInteger;");
}
public void testFieldITD() {
runTest("field itd handle");
compareHandles(IProgramElement.Kind.INTER_TYPE_FIELD,
"C.x",
"<pkg*A9.aj}A9)C.x");
}
public void testMethodITD() {
runTest("method itd handle");
compareHandles(IProgramElement.Kind.INTER_TYPE_METHOD,
"C.method()",
"<pkg*A9.aj}A9)C.method");
}
public void testMethodITDWithArgs() {
runTest("method itd with args handle");
compareHandles(IProgramElement.Kind.INTER_TYPE_METHOD,
"C.methodWithArgs(int)",
"<pkg*A9.aj}A9)C.methodWithArgs)I");
}
public void testConstructorITDWithArgs() {
runTest("constructor itd with args");
compareHandles(IProgramElement.Kind.INTER_TYPE_CONSTRUCTOR,
"C.C(int,java.lang.String)",
"<pkg*A13.aj}A13)C.C)I)QString;");
}
public void testDeclareParentsHandle() {
runTest("declare parents handle");
compareHandles(IProgramElement.Kind.DECLARE_PARENTS,
"declare parents: implements C2",
"<pkg*A7.aj}A7`declare parents");
}
public void testTwoDeclareParents() {
runTest("two declare parents in same file");
compareHandles(IProgramElement.Kind.DECLARE_PARENTS,
"declare parents: extends C5",
"<pkg*A7.aj}A7`declare parents!2");
}
public void testMethodCallHandle() {
runTest("method call handle");
compareHandles(IProgramElement.Kind.CODE,
"method-call(void pkg.C.m2())",
"<pkg*A10.aj[C~m1?method-call(void pkg.C.m2())");
}
public void testDeclareAtType() {
// AJDT: =AJHandleProject/src<pkg*A.aj}A`declare \@type
runTest("declare @type");
compareHandles(IProgramElement.Kind.DECLARE_ANNOTATION_AT_TYPE,
"declare @type: pkg.C : @MyAnnotation",
"<pkg*A12.aj}A`declare @type");
}
public void testDeclareAtField() {
// AJDT: =AJHandleProject/src<pkg*A.aj}A`declare \@field
runTest("declare @field");
compareHandles(IProgramElement.Kind.DECLARE_ANNOTATION_AT_FIELD,
"declare @field: int pkg.C.someField : @MyAnnotation",
"<pkg*A12.aj}A`declare @field!2");
}
public void testDeclareAtMethod() {
// AJDT: =AJHandleProject/src<pkg*A.aj}A`declare \@method
runTest("declare @method");
compareHandles(IProgramElement.Kind.DECLARE_ANNOTATION_AT_METHOD,
"declare @method: public void pkg.C.method1() : @MyAnnotation",
"<pkg*A12.aj}A`declare @method!3");
}
public void testDeclareAtConstructor() {
// AJDT: =AJHandleProject/src<pkg*A.aj}A`declare \@constructor
runTest("declare @constructor");
compareHandles(IProgramElement.Kind.DECLARE_ANNOTATION_AT_CONSTRUCTOR,
"declare @constructor: pkg.C.new() : @MyAnnotation",
"<pkg*A12.aj}A`declare @constructor!4");
}
// what about 2 pieces of before advice with the same
// signature and the same pointcut
public void testTwoPiecesOfAdviceWithSameSignatureAndPointcut() {
runTest("two pieces of advice with the same signature and pointcut");
IHierarchy top = AsmManager.getDefault().getHierarchy();
IProgramElement parent = top.findElementForLabel(top.getRoot(),
IProgramElement.Kind.ASPECT, "A5");
List children = parent.getChildren();
String handle1 = null;
String handle2 = null;
for (Iterator iter = children.iterator(); iter.hasNext();) {
IProgramElement element = (IProgramElement) iter.next();
if (element.getKind().equals(IProgramElement.Kind.ADVICE)) {
if (handle1 == null) {
handle1 = element.getHandleIdentifier();
} else {
handle2 = element.getHandleIdentifier();
}
}
}
String expected1 = "<pkg*A5.aj}A5&before";
String expected2 = "<pkg*A5.aj}A5&before!2";
boolean b = expected1.equals(handle1);
if (b) {
assertEquals("handleIdentifier - expected " + expected2 + ", but found "
+ handle2, expected2, handle2);
} else {
assertEquals("handleIdentifier - expected " + expected1 + ", but found "
+ handle2, expected1, handle2);
assertEquals("handleIdentifier - expected " + expected2 + ", but found "
+ handle1, expected2, handle1);
}
}
public void testDeclareWarningHandle() {
runTest("declare warning handle");
compareHandles(IProgramElement.Kind.DECLARE_WARNING,
"declare warning: \"Illegal call.\"",
"<pkg*A11.aj}A11`declare warning");
}
public void testTwoDeclareWarningHandles() {
runTest("two declare warning handles");
compareHandles(IProgramElement.Kind.DECLARE_WARNING,
"declare warning: \"blah\"",
"<pkg*A11.aj}A11`declare warning!2");
}
// this is to ensure the logic for not including '1' in the count
// works correctly. We don't want a decw ipe with count 1 but we do
// want one with count 10.
public void testTenDeclareWarningHandles() {
runTest("ten declare warning handles");
compareHandles(IProgramElement.Kind.DECLARE_WARNING,
"declare warning: \"warning 1\"",
"*DeclareWarnings.aj}DeclareWarnings`declare warning");
compareHandles(IProgramElement.Kind.DECLARE_WARNING,
"declare warning: \"warning 10\"",
"*DeclareWarnings.aj}DeclareWarnings`declare warning!10");
}
// these two handles are the same unless we have added a counter
// on the end
public void testIPEsWithSameNameHaveUniqueHandles_methodCall() {
runTest("ipes with same name have unique handles - method-call");
IHierarchy top = AsmManager.getDefault().getHierarchy();
String handle1 = "*TwoMethodCalls.aj[Main~main~\\[QString;?method-call(" +
"void java.io.PrintStream.println(java.lang.String))";
assertNotNull("expected to find node with handle " + handle1
+ ", but did not",top.getElement(handle1));
String handle2 = "*TwoMethodCalls.aj[Main~main~\\[QString;?method-call(" +
"void java.io.PrintStream.println(java.lang.String))!2";
assertNotNull("expected to find node with handle " + handle2
+ ", but did not",top.getElement(handle2));
String handle3 = "*TwoMethodCalls.aj[Main~main~\\[QString;?method-call(" +
"void java.io.PrintStream.println(java.lang.String))!3";
assertNull("expected not to find node with handle " + handle3
+ ", but found one",top.getElement(handle3));
}
// these two handles should be different anyway so second one
// shouldn't have the "2"
public void testIPEsWithDiffNamesDontHaveCounter_methodCall() {
runTest("ipes with different names do not have counter - method-call");
IHierarchy top = AsmManager.getDefault().getHierarchy();
String handle1 = "*TwoDiffMethodCalls.aj[Main~main~\\[QString;?method-call(" +
"void java.io.PrintStream.println(java.lang.String))";
assertNotNull("expected to find node with handle " + handle1
+ ", but did not",top.getElement(handle1));
String handle2 = "*TwoDiffMethodCalls.aj[Main~method~\\[QString;?method-call(" +
"void java.io.PrintStream.println(java.lang.String))";
assertNotNull("expected to find node with handle " + handle2
+ ", but did not",top.getElement(handle2));
}
public void testIPEsWithSameNameHaveUniqueHandles_handler() {
runTest("ipes with same name have unique handles - handler");
IHierarchy top = AsmManager.getDefault().getHierarchy();
String handle1 = "*Handler.aj[C~method?exception-handler(void C." +
"<catch>(java.io.FileNotFoundException))";
assertNotNull("expected to find node with handle " + handle1
+ ", but did not",top.getElement(handle1));
String handle2 = "*Handler.aj[C~method?exception-handler(void C." +
"<catch>(java.io.FileNotFoundException))!2";
assertNotNull("expected to find node with handle " + handle2
+ ", but did not",top.getElement(handle2));
}
public void testIPEsWithSameNameHaveUniqueHandles_get() {
runTest("ipes with same name have unique handles - get");
IHierarchy top = AsmManager.getDefault().getHierarchy();
String handle1 = "*Get.aj[C1~method1?field-get(int C1.x)";
assertNotNull("expected to find node with handle " + handle1
+ ", but did not",top.getElement(handle1));
String handle2 = "*Get.aj[C1~method1?field-get(int C1.x)!2";
assertNotNull("expected to find node with handle " + handle2
+ ", but did not",top.getElement(handle2));
}
public void testIPEsWithSameNameHaveUniqueHandles_set() {
runTest("ipes with same name have unique handles - set");
IHierarchy top = AsmManager.getDefault().getHierarchy();
String handle1 = "*Set.aj[C1~method?field-set(int C1.x)";
assertNotNull("expected to find node with handle " + handle1
+ ", but did not",top.getElement(handle1));
String handle2 = "*Set.aj[C1~method?field-set(int C1.x)!2";
assertNotNull("expected to find node with handle " + handle2
+ ", but did not",top.getElement(handle2));
}
//---------- following tests ensure we produce the same handles as jdt -----//
//---------- (apart from the prefix)
// NOTES: there is no ipe equivalent to a package fragment root or
//
public void testCompilationUnitSameAsJDT() {
// JDT: =TJP Example/src<tjp{Demo.java
runTest("compilation unit same as jdt");
compareHandles(IProgramElement.Kind.FILE_JAVA,
"Demo.java",
"<tjp{Demo.java");
}
public void testClassSameAsJDT() {
// JDT: =Java5 Handles/src<pkg{C.java[C
runTest("class same as jdt");
compareHandles(IProgramElement.Kind.CLASS,
"C","<pkg{C.java[C");
}
public void testInterfaceSameAsJDT() {
// JDT: =Java5 Handles/src<pkg{C.java[MyInterface
runTest("interface same as jdt");
compareHandles(IProgramElement.Kind.INTERFACE,
"MyInterface","<pkg{C.java[MyInterface");
}
public void testConstructorSameAsJDT() {
// JDT: =Java5 Handles/src<pkg{C.java[C~C
runTest("constructor same as jdt");
compareHandles(IProgramElement.Kind.CONSTRUCTOR,
"C()","<pkg{C.java[C~C");
}
public void testConstructorWithArgsSameAsJDT() {
// JDT: =Java5 Handles/src<pkg{C.java[C~C~QString;
runTest("constructor with args same as jdt");
compareHandles(IProgramElement.Kind.CONSTRUCTOR,
"C(java.lang.String)","<pkg{C.java[C~C~QString;");
}
// public void testPackageDeclarationSameAsJDT() {
// // JDT: =TJP Example/src<tjp{Demo.java%tjp
// fail("package declaration isn't the same");
// runTest("package declaration same as jdt");
// compareHandles(IProgramElement.Kind.PACKAGE,
// "tjp",
// "<tjp{Demo.java%tjp");
// }
public void testImportDeclarationSameAsJDT() {
// JDT: =TJP Example/src<tjp{Demo.java#java.io.*
runTest("import declaration same as jdt");
compareHandles(IProgramElement.Kind.IMPORT_REFERENCE,
"java.io.*",
"<tjp{Demo.java#java.io.*");
}
public void testTypeSameAsJDT() {
// JDT: =TJP Example/src<tjp{Demo.java[Demo
runTest("type same as jdt");
IHierarchy top = AsmManager.getDefault().getHierarchy();
IProgramElement pe = top.findElementForType("tjp", "Demo");
String expected = "<tjp{Demo.java[Demo";
String found = pe.getHandleIdentifier();
assertEquals("handleIdentifier - expected " + expected + ", but found "
+ found, expected, found);
}
public void testFieldSameAsJDT() {
// JDT: =TJP Example/src<tjp{Demo.java[Demo^d
runTest("field same as jdt");
compareHandles(IProgramElement.Kind.FIELD,
"d",
"<tjp{Demo.java[Demo^d");
}
public void testInitializationSameAsJDT() {
// JDT: =TJP Example/src<tjp{Demo.java[Demo|1
// and =TJP Example/src<tjp{Demo.java[Demo|2
runTest("initialization same as jdt");
IHierarchy top = AsmManager.getDefault().getHierarchy();
IProgramElement parent = top.findElementForLabel(top.getRoot(),
IProgramElement.Kind.CLASS, "Demo");
List children = parent.getChildren();
String handle1 = null;
String handle2 = null;
for (Iterator iter = children.iterator(); iter.hasNext();) {
IProgramElement element = (IProgramElement) iter.next();
if (element.getKind().equals(IProgramElement.Kind.INITIALIZER)) {
if (handle1 == null) {
handle1 = element.getHandleIdentifier();
} else {
handle2 = element.getHandleIdentifier();
}
}
}
String expected1 = "<tjp{Demo.java[Demo|1";
String expected2 = "<tjp{Demo.java[Demo|2";
boolean b = expected1.equals(handle1);
System.err.println("actual: " + handle1);
System.err.println("actual: " + handle2);
if (b) {
assertEquals("handleIdentifier - expected " + expected2 + ", but found "
+ handle2, expected2, handle2);
} else {
assertEquals("handleIdentifier - expected " + expected1 + ", but found "
+ handle2, expected1, handle2);
assertEquals("handleIdentifier - expected " + expected2 + ", but found "
+ handle1, expected2, handle1);
}
}
public void testMethodWithStringArrayArgsSameAsJDT() {
// JDT: =TJP Example/src<tjp{Demo.java[Demo~main~\[QString;
runTest("method with string array as argument same as jdt");
compareHandles(IProgramElement.Kind.METHOD,
"main(java.lang.String[])",
"<tjp{Demo.java[Demo~main~\\[QString;");
}
public void testMethodWithIntArrayArgsSameAsJDT() {
// JDT: =TJP Example/src<tjp{Demo.java[Demo~m~\[I
runTest("method with int array as argument same as jdt");
compareHandles(IProgramElement.Kind.METHOD,
"m(int[])",
"<tjp{Demo.java[Demo~m~\\[I");
}
public void testMethodWithNoArgsSameAsJDT() {
// JDT: =TJP Example/src<tjp{Demo.java[Demo~go
runTest("method with no args same as jdt");
compareHandles(IProgramElement.Kind.METHOD,
"go()",
"<tjp{Demo.java[Demo~go");
}
public void testMethodWithTwoArgsSameAsJDT() {
// JDT: =TJP Example/src<tjp{Demo.java[Demo~foo~I~QObject;
runTest("method with two args same as jdt");
compareHandles(IProgramElement.Kind.METHOD,
"foo(int,java.lang.Object)",
"<tjp{Demo.java[Demo~foo~I~QObject;");
}
public void testMethodWithTwoStringArgsSameAsJDT() {
// JDT: =TJP Example/src<tjp{Demo.java[Demo~m2~QString;~QString;
runTest("method with two string args same as jdt");
compareHandles(IProgramElement.Kind.METHOD,
"m2(java.lang.String,java.lang.String)",
"<tjp{Demo.java[Demo~m2~QString;~QString;");
}
public void testEnumSameAsJDT() {
// JDT: =Java5 Handles/src<pkg{E.java[E
runTest("enum same as jdt");
IHierarchy top = AsmManager.getDefault().getHierarchy();
IProgramElement pe = top.findElementForType("pkg", "E");
String expected = "<pkg{E.java[E";
String found = pe.getHandleIdentifier();
assertEquals("handleIdentifier - expected " + expected + ", but found "
+ found, expected, found);
}
public void testEnumValueSameAsJDT() {
// JDT: =Java5 Handles/src<pkg{E.java[E^A
runTest("enum value same as jdt");
compareHandles(IProgramElement.Kind.ENUM_VALUE,
"A","<pkg{E.java[E^A");
}
public void testAnnotationSameAsJDT() {
// JDT: =Java5 Handles/src<pkg{MyAnnotation.java[MyAnnotation
runTest("annotation same as jdt");
IHierarchy top = AsmManager.getDefault().getHierarchy();
IProgramElement pe = top.findElementForType("pkg", "MyAnnotation");
String expected = "<pkg{MyAnnotation.java[MyAnnotation";
String found = pe.getHandleIdentifier();
assertEquals("handleIdentifier - expected " + expected + ", but found "
+ found, expected, found);
}
public void testMethodWithListArgSameAsJDT() {
// JDT: =Java5 Handles/src<pkg{Java5Class.java[Java5Class~method2~QList;
runTest("method with list arg same as jdt");
compareHandles(IProgramElement.Kind.METHOD,
"method2(java.util.List)",
"<pkg{Java5Class.java[Java5Class~method2~QList;");
}
public void testMethodWithGenericArgSameAsJDT() {
// JDT: =Java5 Handles/src<pkg{Java5Class.java[Java5Class
// ~genericMethod1~QList\<QString;>;
runTest("method with generic arg same as jdt");
compareHandles(IProgramElement.Kind.METHOD,
"genericMethod1(java.util.List<java.lang.String>)",
"<pkg{Java5Class.java[Java5Class~genericMethod1~QList\\<QString;>;");
}
public void testMethodWithTwoGenericArgsSameAsJDT() {
// JDT: =Java5 Handles/src<pkg{Java5Class.java[Java5Class
// ~genericMethod2~QList\<QString;>;~QMyGenericClass\<QInteger;>;
runTest("method with two generic args same as jdt");
compareHandles(IProgramElement.Kind.METHOD,
"genericMethod2(java.util.List<java.lang.String>,"
+"pkg.MyGenericClass<java.lang.Integer>)",
"<pkg{Java5Class.java[Java5Class~genericMethod2~QList"
+"\\<QString;>;~QMyGenericClass\\<QInteger;>;");
}
public void testMethodWithTwoTypeParametersSameAsJDT() {
// JDT: =Java5 Handles/src<pkg{Java5Class.java[Java5Class~genericMethod4
// ~QMyGenericClass2\<QString;QInteger;>;
runTest("method with two type parameters same as jdt");
compareHandles(IProgramElement.Kind.METHOD,
"genericMethod4(pkg.MyGenericClass2<java.lang.String,java.lang.Integer>)",
"<pkg{Java5Class.java[Java5Class~genericMethod4" +
"~QMyGenericClass2\\<QString;QInteger;>;");
}
public void testMethodWithTwoArgsSameAsJDT_2() {
// JDT: =Java5 Handles/src<pkg{Java5Class.java[Java5Class
// ~genericMethod3~I~QList\<QString;>;
runTest("method with two args one of which is generic same as jdt");
compareHandles(IProgramElement.Kind.METHOD,
"genericMethod3(int,java.util.List<java.lang.String>)",
"<pkg{Java5Class.java[Java5Class~genericMethod3~I~QList\\<QString;>;");
}
/*
* Still to do;
* PROJECT,
PACKAGE,
FILE,
FILE_ASPECTJ,
FILE_LST,
DECLARE_ERROR,
DECLARE_SOFT,
DECLARE_PRECEDENCE,
*/
// ----------- helper methods ---------------
private void compareHandles(IProgramElement.Kind kind, String ipeName, String expectedHandle) {
IHierarchy top = AsmManager.getDefault().getHierarchy();
IProgramElement pe = top.findElementForLabel(top.getRoot(),kind,ipeName);
String found = pe.getHandleIdentifier();
System.err.println("expected: " + expectedHandle);
System.err.println("actual: " + found);
assertEquals("handleIdentifier - expected " + expectedHandle + ", but found "
+ found, expectedHandle, found);
}
// ///////////////////////////////////////
public static Test suite() {
return XMLBasedAjcTestCase.loadSuite(JDTLikeHandleProviderTests.class);
}
protected File getSpecFile() {
return new File(
"../tests/src/org/aspectj/systemtest/ajc153/jdtlikehandleprovider.xml");
}
}
|
159,896 |
Bug 159896 advice from injars do not have unique handles with the JDTLikeHandleProvider
|
Advice of the same kind contained in the same aspect currently do not have unique handles if the aspect is on the aspectpath.
|
resolved fixed
|
d532892
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-10-06T16:29:03Z | 2006-10-05T14:53:20Z |
weaver/src/org/aspectj/weaver/ShadowMunger.java
|
/* *******************************************************************
* Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC).
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Eclipse Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* PARC initial implementation
* ******************************************************************/
package org.aspectj.weaver;
import java.io.File;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.Map;
import org.aspectj.asm.AsmManager;
import org.aspectj.asm.IProgramElement;
import org.aspectj.asm.internal.ProgramElement;
import org.aspectj.bridge.ISourceLocation;
import org.aspectj.bridge.SourceLocation;
import org.aspectj.util.PartialOrder;
import org.aspectj.weaver.bcel.BcelAdvice;
import org.aspectj.weaver.patterns.DeclareErrorOrWarning;
import org.aspectj.weaver.patterns.PerClause;
import org.aspectj.weaver.patterns.Pointcut;
/**
* For every shadow munger, nothing can be done with it until it is concretized. Then...
*
* (Then we call fast match.)
*
* For every shadow munger, for every shadow,
* first match is called,
* then (if match returned true) the shadow munger is specialized for the shadow,
* which may modify state.
* Then implement is called.
*/
public abstract class ShadowMunger implements PartialOrder.PartialComparable, IHasPosition {
protected Pointcut pointcut;
// these three fields hold the source location of this munger
protected int start, end;
protected ISourceContext sourceContext;
private ISourceLocation sourceLocation;
private ISourceLocation binarySourceLocation;
private File binaryFile;
private String handle = null;
private ResolvedType declaringType; // the type that declared this munger.
public ShadowMunger(Pointcut pointcut, int start, int end, ISourceContext sourceContext) {
this.pointcut = pointcut;
this.start = start;
this.end = end;
this.sourceContext = sourceContext;
}
public abstract ShadowMunger concretize(ResolvedType fromType, World world, PerClause clause);
public abstract void specializeOn(Shadow shadow);
public abstract void implementOn(Shadow shadow);
/**
* All overriding methods should call super
*/
public boolean match(Shadow shadow, World world) {
return pointcut.match(shadow).maybeTrue();
}
public abstract ShadowMunger parameterizeWith(ResolvedType declaringType,Map typeVariableMap);
public int fallbackCompareTo(Object other) {
return toString().compareTo(toString());
}
public int getEnd() {
return end;
}
public int getStart() {
return start;
}
public ISourceLocation getSourceLocation() {
if (sourceLocation == null) {
if (sourceContext != null) {
sourceLocation = sourceContext.makeSourceLocation(this);
}
}
if (isBinary()) {
if (binarySourceLocation == null) {
binarySourceLocation = getBinarySourceLocation(sourceLocation);
}
return binarySourceLocation;
}
return sourceLocation;
}
public String getHandle() {
if (null == handle) {
ISourceLocation sl = getSourceLocation();
if (sl != null) {
IProgramElement ipe = AsmManager.getDefault().getHierarchy().findElementForSourceLine(sl);
handle = AsmManager.getDefault().getHandleProvider().createHandleIdentifier(ipe);
}
}
return handle;
}
// ---- fields
public static final ShadowMunger[] NONE = new ShadowMunger[0];
public Pointcut getPointcut() {
return pointcut;
}
// pointcut may be updated during rewriting...
public void setPointcut(Pointcut pointcut) {
this.pointcut = pointcut;
}
/**
* Invoked when the shadow munger of a resolved type are processed.
* @param aType
*/
public void setDeclaringType(ResolvedType aType) {
this.declaringType = aType;
}
public ResolvedType getDeclaringType() {
return this.declaringType;
}
/**
* @return a Collection of ResolvedType for all checked exceptions that
* might be thrown by this munger
*/
public abstract Collection getThrownExceptions();
/**
* Does the munger has to check that its exception are accepted by the shadow ?
* ATAJ: It s not the case for @AJ around advice f.e. that can throw Throwable, even if the advised
* method does not throw any exceptions.
* @return true if munger has to check that its exceptions can be throwned based on the shadow
*/
public abstract boolean mustCheckExceptions();
/**
* Returns the ResolvedType corresponding to the aspect in which this
* shadowMunger is declared. This is different for deow's and advice.
*/
public abstract ResolvedType getResolvedDeclaringAspect();
/**
* Creates the hierarchy for binary aspects
*/
public void createHierarchy() {
if (!isBinary()) return;
IProgramElement sourceFileNode = AsmManager.getDefault().getHierarchy().findElementForSourceLine(getSourceLocation());
// the call to findElementForSourceLine(ISourceLocation) returns a file node
// if it can't find a node in the hierarchy for the given sourcelocation.
// Therefore, if this is returned, we know we can't find one and have to
// continue to fault in the model.
if (!sourceFileNode.getKind().equals(IProgramElement.Kind.FILE_JAVA)) {
return;
}
ResolvedType aspect = getResolvedDeclaringAspect();
// create the class file node
IProgramElement classFileNode = new ProgramElement(
sourceFileNode.getName() + " (binary)",
IProgramElement.Kind.CLASS,
getBinarySourceLocation(aspect.getSourceLocation()),
0,null,null);
// create package ipe if one exists....
IProgramElement root = AsmManager.getDefault().getHierarchy().getRoot();
if (aspect.getPackageName() != null) {
// check that there doesn't already exist a node with this name
IProgramElement pkgNode = AsmManager.getDefault().getHierarchy().findElementForLabel(
root,IProgramElement.Kind.PACKAGE,aspect.getPackageName());
// note packages themselves have no source location
if (pkgNode == null) {
pkgNode = new ProgramElement(
aspect.getPackageName(),
IProgramElement.Kind.PACKAGE,
new ArrayList());
root.addChild(pkgNode);
pkgNode.addChild(classFileNode);
} else {
// need to add it first otherwise the handle for classFileNode
// may not be generated correctly if it uses information from
// it's parent node
pkgNode.addChild(classFileNode);
for (Iterator iter = pkgNode.getChildren().iterator(); iter.hasNext();) {
IProgramElement element = (IProgramElement) iter.next();
if (!element.equals(classFileNode) &&
element.getHandleIdentifier().equals(
classFileNode.getHandleIdentifier())) {
// already added the classfile so have already
// added the structure for this aspect
pkgNode.removeChild(classFileNode);
return;
}
}
}
} else {
// need to add it first otherwise the handle for classFileNode
// may not be generated correctly if it uses information from
// it's parent node
root.addChild(classFileNode);
for (Iterator iter = root.getChildren().iterator(); iter.hasNext();) {
IProgramElement element = (IProgramElement) iter.next();
if (!element.equals(classFileNode) &&
element.getHandleIdentifier().equals(
classFileNode.getHandleIdentifier())) {
// already added the sourcefile so have already
// added the structure for this aspect
root.removeChild(classFileNode);
return;
}
}
}
// add and create empty import declaration ipe
classFileNode.addChild(new ProgramElement(
"import declarations",
IProgramElement.Kind.IMPORT_REFERENCE,
null,0,null,null));
// add and create aspect ipe
IProgramElement aspectNode = new ProgramElement(
aspect.getSimpleName(),
IProgramElement.Kind.ASPECT,
getBinarySourceLocation(aspect.getSourceLocation()),
aspect.getModifiers(),
null,null);
classFileNode.addChild(aspectNode);
addChildNodes(aspectNode,aspect.getDeclaredPointcuts());
addChildNodes(aspectNode,aspect.getDeclaredAdvice());
addChildNodes(aspectNode,aspect.getDeclares());
}
private void addChildNodes(IProgramElement parent,ResolvedMember[] children) {
for (int i = 0; i < children.length; i++) {
ResolvedMember pcd = children[i];
if (pcd instanceof ResolvedPointcutDefinition) {
ResolvedPointcutDefinition rpcd = (ResolvedPointcutDefinition)pcd;
parent.addChild(new ProgramElement(
pcd.getName(),
IProgramElement.Kind.POINTCUT,
getBinarySourceLocation(rpcd.getPointcut().getSourceLocation()),
pcd.getModifiers(),
null,
Collections.EMPTY_LIST));
}
}
}
private void addChildNodes(IProgramElement parent, Collection children) {
for (Iterator iter = children.iterator(); iter.hasNext();) {
Object element = (Object) iter.next();
if (element instanceof DeclareErrorOrWarning) {
DeclareErrorOrWarning decl = (DeclareErrorOrWarning)element;
IProgramElement deowNode = new ProgramElement(
decl.isError() ? "declare error" : "declare warning",
decl.isError() ? IProgramElement.Kind.DECLARE_ERROR : IProgramElement.Kind.DECLARE_WARNING,
getBinarySourceLocation(decl.getSourceLocation()),
decl.getDeclaringType().getModifiers(),
null,null);
deowNode.setDetails("\"" + AsmRelationshipUtils.genDeclareMessage(decl.getMessage()) + "\"");
parent.addChild(deowNode);
} else if (element instanceof BcelAdvice) {
BcelAdvice advice = (BcelAdvice)element;
IProgramElement adviceNode = new ProgramElement(
advice.kind.getName(),
IProgramElement.Kind.ADVICE,
getBinarySourceLocation(advice.getSourceLocation()),
advice.signature.getModifiers(),null,Collections.EMPTY_LIST);
adviceNode.setDetails(AsmRelationshipUtils.genPointcutDetails(advice.getPointcut()));
parent.addChild(adviceNode);
}
}
}
/**
* Returns the binarySourceLocation for the given sourcelocation. This
* isn't cached because it's used when faulting in the binary nodes
* and is called with ISourceLocations for all advice, pointcuts and deows
* contained within the resolvedDeclaringAspect.
*/
private ISourceLocation getBinarySourceLocation(ISourceLocation sl) {
if (sl == null) return null;
String sourceFileName = null;
if (getResolvedDeclaringAspect() instanceof ReferenceType) {
String s = ((ReferenceType)getResolvedDeclaringAspect()).getDelegate().getSourcefilename();
int i = s.lastIndexOf('/');
if (i != -1) {
sourceFileName = s.substring(i+1);
} else {
sourceFileName = s;
}
}
ISourceLocation sLoc = new SourceLocation(
getBinaryFile(),
sl.getLine(),
sl.getEndLine(),
((sl.getColumn() == 0) ? ISourceLocation.NO_COLUMN : sl.getColumn()),
sl.getContext(),
sourceFileName);
return sLoc;
}
/**
* Returns the File with pathname to the class file, for example either
* C:\temp\ajcSandbox\workspace\ajcTest16957.tmp\simple.jar!pkg\BinaryAspect.class
* if the class file is in a jar file, or
* C:\temp\ajcSandbox\workspace\ajcTest16957.tmp!pkg\BinaryAspect.class
* if the class file is in a directory
*/
private File getBinaryFile() {
if (binaryFile == null) {
String s = getResolvedDeclaringAspect().getBinaryPath();
File f = getResolvedDeclaringAspect().getSourceLocation().getSourceFile();
int i = f.getPath().lastIndexOf('.');
String path = f.getPath().substring(0,i) + ".class";
binaryFile = new File(s + "!" + path);
}
return binaryFile;
}
/**
* Returns whether or not this shadow munger came from
* a binary aspect - keep a record of whether or not we've
* checked if we're binary otherwise we keep caluclating the
* same thing many times
*/
protected boolean isBinary() {
if (!checkedIsBinary) {
ResolvedType rt = getResolvedDeclaringAspect();
if (rt != null) {
isBinary = ((rt.getBinaryPath() == null) ? false : true);
}
checkedIsBinary = true;
}
return isBinary;
}
private boolean isBinary;
private boolean checkedIsBinary;
}
|
159,896 |
Bug 159896 advice from injars do not have unique handles with the JDTLikeHandleProvider
|
Advice of the same kind contained in the same aspect currently do not have unique handles if the aspect is on the aspectpath.
|
resolved fixed
|
d532892
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-10-06T16:29:03Z | 2006-10-05T14:53:20Z |
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;
}
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";
}
}
|
160,167 |
Bug 160167 NPE when using crossrefs option for iajc ant task
|
The ant task is shown below. I ommited the full paths to the values of inpath, outJar, and argfiles, because they are somewhat long (hence the "..." before the file names): <iajc crossrefs="true" argfiles="...\weave-jars.txt" inpath="...\org.eclipse.core.runtime_3.2.0.v20060603.jar" outJar="...\org.eclipse.core.runtime_3.2.0.v20060603_woven.jar"> <classpath> <pathelement location="C:\aspectj1.5\lib\aspectjrt.jar"/> <fileset dir="${plugins.dir}"> <include name="**/*.jar"/> </fileset> </classpath> </iajc> My argfile only contains the absolute path of a single .aj file, which contains one aspect. The aspect is shown below. It is very basic - advice bodies simply toggle a boolean variable. public aspect FFDC { public static boolean bit = false; protected pointcut ffdcScope(): within(org.eclipse..*); protected pointcut excluded(): within(org.eclipse.ffdc.FFDC+) || within(org.eclipse.core.internal.runtime.PlatformActivator); before(CoreException c): ffdcScope() && !excluded() && handler(CoreException+) && args(c) { bit = !bit; } after() throwing(CoreException c): ffdcScope() && !excluded() && !handler(*) { bit = !bit; } after(Plugin activator): execution(void PlatformActivator.start(..)) && this(activator) { bit = !bit; } } This task worked properly before I added "crossrefs=true". After adding this option, I get the following error: weave-C:\eclipse\sdk-aspect-package\eclipse\plugins\org.eclipse.core.runtime_3.2.0.v20060603.jar: [iajc] abort ABORT -- (NullPointerException) null [iajc] null [iajc] java.lang.NullPointerException [iajc] at org.aspectj.ajdt.internal.core.builder.AjBuildManager.doBuild(AjBuildManager.java:313) [iajc] at org.aspectj.ajdt.internal.core.builder.AjBuildManager.batchBuild(AjBuildManager.java:163) [iajc] at org.aspectj.ajdt.ajc.AjdtCommand.doCommand(AjdtCommand.java:112) [iajc] at org.aspectj.ajdt.ajc.AjdtCommand.runCommand(AjdtCommand.java:60) [iajc] at org.aspectj.tools.ajc.Main.run(Main.java:367) [iajc] at org.aspectj.tools.ajc.Main.runMain(Main.java:246) [iajc] at org.aspectj.tools.ant.taskdefs.AjcTask.executeInSameVM(AjcTask.java:1282) [iajc] at org.aspectj.tools.ant.taskdefs.AjcTask.execute(AjcTask.java:1080) [iajc] at org.apache.tools.ant.UnknownElement.execute(UnknownElement.java:275) [iajc] at org.apache.tools.ant.Task.perform(Task.java:364) [iajc] at org.apache.tools.ant.Target.execute(Target.java:341) [iajc] at org.apache.tools.ant.Target.performTasks(Target.java:369) [iajc] at org.apache.tools.ant.Project.executeSortedTargets(Project.java:1216) [iajc] at org.apache.tools.ant.helper.SingleCheckExecutor.executeTargets(SingleCheckExecutor.java:37) [iajc] at org.apache.tools.ant.Project.executeTargets(Project.java:1068) [iajc] at org.apache.tools.ant.taskdefs.Ant.execute(Ant.java:382) [iajc] at org.apache.tools.ant.taskdefs.CallTarget.execute(CallTarget.java:107) [iajc] at org.apache.tools.ant.UnknownElement.execute(UnknownElement.java:275) [iajc] at org.apache.tools.ant.Task.perform(Task.java:364) [iajc] at org.apache.tools.ant.Target.execute(Target.java:341) [iajc] at org.apache.tools.ant.Target.performTasks(Target.java:369) [iajc] at org.apache.tools.ant.Project.executeSortedTargets(Project.java:1216) [iajc] at org.apache.tools.ant.Project.executeTarget(Project.java:1185) [iajc] at org.apache.tools.ant.helper.DefaultExecutor.executeTargets(DefaultExecutor.java:40) [iajc] at org.apache.tools.ant.Project.executeTargets(Project.java:1068) [iajc] at org.apache.tools.ant.Main.runBuild(Main.java:668) [iajc] at org.apache.tools.ant.Main.startAnt(Main.java:187) [iajc] at org.apache.tools.ant.launch.Launcher.run(Launcher.java:246) [iajc] at org.apache.tools.ant.launch.Launcher.main(Launcher.java:67)
|
resolved fixed
|
f7508cf
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-10-09T12:28:29Z | 2006-10-08T23:26:40Z |
org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/core/builder/AjBuildManager.java
|
/* *******************************************************************
* Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC).
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Eclipse Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* PARC initial implementation
* ******************************************************************/
package org.aspectj.ajdt.internal.core.builder;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileFilter;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.jar.Attributes;
import java.util.jar.JarFile;
import java.util.jar.JarInputStream;
import java.util.jar.JarOutputStream;
import java.util.jar.Manifest;
import java.util.zip.ZipEntry;
import org.aspectj.ajdt.internal.compiler.AjCompilerAdapter;
import org.aspectj.ajdt.internal.compiler.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.ClasspathDirectory;
import org.aspectj.org.eclipse.jdt.internal.compiler.batch.CompilationUnit;
import org.aspectj.org.eclipse.jdt.internal.compiler.batch.FileSystem;
import org.aspectj.org.eclipse.jdt.internal.compiler.env.ICompilationUnit;
import org.aspectj.org.eclipse.jdt.internal.compiler.env.INameEnvironment;
import org.aspectj.org.eclipse.jdt.internal.compiler.impl.CompilerOptions;
import org.aspectj.org.eclipse.jdt.internal.compiler.parser.Parser;
import org.aspectj.org.eclipse.jdt.internal.compiler.problem.AbortCompilation;
import org.aspectj.org.eclipse.jdt.internal.compiler.problem.DefaultProblemFactory;
import org.aspectj.tools.ajc.Main;
import org.aspectj.util.FileUtil;
import org.aspectj.weaver.Dump;
import org.aspectj.weaver.ResolvedType;
import org.aspectj.weaver.World;
import org.aspectj.weaver.bcel.BcelWeaver;
import org.aspectj.weaver.bcel.BcelWorld;
import org.aspectj.weaver.bcel.UnwovenClassFile;
import org.eclipse.core.runtime.OperationCanceledException;
public class AjBuildManager implements IOutputClassFileNameProvider,IBinarySourceProvider,ICompilerAdapterFactory {
private static final String CROSSREFS_FILE_NAME = "build.lst";
private static final String CANT_WRITE_RESULT = "unable to write compilation result";
private static final String MANIFEST_NAME = "META-INF/MANIFEST.MF";
static final boolean COPY_INPATH_DIR_RESOURCES = false;
// 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.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;
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()) {
String configFileProxy = buildConfig.getOutputDir().getAbsolutePath()
+ File.separator
+ CROSSREFS_FILE_NAME;
AsmManager.getDefault().writeStructureModel(configFileProxy);
}
// have to tell state we succeeded or next is not incremental
state.successfulCompile(buildConfig,batch);
copyResourcesToDestination();
if (buildConfig.getOutxmlName() != null) {
writeOutxmlFile();
}
/*boolean weaved = *///weaveAndGenerateClassFiles();
// if not weaved, then no-op build, no model changes
// but always returns true
// XXX weaved not in Mik's incremental
if (buildConfig.isGenerateModelMode()) {
AsmManager.getDefault().fireModelUpdated();
}
CompilationAndWeavingContext.leavingPhase(ct);
} finally {
if (baseHandler instanceof ILifecycleAware) {
((ILifecycleAware)baseHandler).buildFinished(!batch);
}
if (zos != null) {
closeOutputStream(buildConfig.getOutputJar());
}
ret = !handler.hasErrors();
if (getBcelWorld()!=null) getBcelWorld().tidyUp();
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) {
OutputStream fos =
FileUtil.makeOutputStream(new File(buildConfig.getOutputDir(),MANIFEST_NAME));
manifest.write(fos);
fos.close();
}
}
private boolean acceptResource(String resourceName) {
if (
(resourceName.startsWith("CVS/")) ||
(resourceName.indexOf("/CVS/") != -1) ||
(resourceName.endsWith("/CVS")) ||
(resourceName.endsWith(".class")) ||
(resourceName.startsWith(".svn/")) ||
(resourceName.indexOf("/.svn/")!=-1) ||
(resourceName.endsWith("/.svn")) ||
(resourceName.toUpperCase().equals(MANIFEST_NAME))
)
{
return false;
} else {
return true;
}
}
private void writeOutxmlFile () throws IOException {
if (ignoreOutxml) return;
String filename = buildConfig.getOutxmlName();
// System.err.println("? AjBuildManager.writeOutxmlFile() outxml=" + filename);
// System.err.println("? AjBuildManager.writeOutxmlFile() outputDir=" + buildConfig.getOutputDir());
ByteArrayOutputStream baos = new ByteArrayOutputStream();
PrintStream ps = new PrintStream(baos);
ps.println("<aspectj>");
ps.println("<aspects>");
if (state.getAspectNames() != null) {
for (Iterator i = state.getAspectNames().iterator(); i.hasNext();) {
String name = (String)i.next();
ps.println("<aspect name=\"" + name + "\"/>");
}
}
ps.println("</aspects>");
ps.println("</aspectj>");
ps.println();
ps.close();
if (zos != null) {
ZipEntry newEntry = new ZipEntry(filename);
zos.putNextEntry(newEntry);
zos.write(baos.toByteArray());
zos.closeEntry();
} else {
OutputStream fos =
FileUtil.makeOutputStream(new File(buildConfig.getOutputDir(),filename));
fos.write(baos.toByteArray());
fos.close();
}
}
// public static void dumprels() {
// IRelationshipMap irm = AsmManager.getDefault().getRelationshipMap();
// int ctr = 1;
// Set entries = irm.getEntries();
// for (Iterator iter = entries.iterator(); iter.hasNext();) {
// String hid = (String) iter.next();
// List rels = irm.get(hid);
// for (Iterator iterator = rels.iterator(); iterator.hasNext();) {
// IRelationship ir = (IRelationship) iterator.next();
// List targets = ir.getTargets();
// for (Iterator iterator2 = targets.iterator();
// iterator2.hasNext();
// ) {
// String thid = (String) iterator2.next();
// System.err.println("Hid:"+(ctr++)+":(targets="+targets.size()+") "+hid+" ("+ir.getName()+") "+thid);
// }
// }
// }
// }
/**
* Responsible for managing the ASM model between builds. Contains the policy for
* maintaining the persistance of elements in the model.
*
* This code is driven before each 'fresh' (batch) build to create
* a new model.
*/
private void setupModel(AjBuildConfig config) {
AsmManager.setCreatingModel(config.isEmacsSymMode() || config.isGenerateModelMode());
if (!AsmManager.isCreatingModel()) return;
AsmManager.getDefault().createNewASM();
// AsmManager.getDefault().getRelationshipMap().clear();
IHierarchy model = AsmManager.getDefault().getHierarchy();
String rootLabel = "<root>";
IProgramElement.Kind kind = IProgramElement.Kind.FILE_JAVA;
if (buildConfig.getConfigFile() != null) {
rootLabel = buildConfig.getConfigFile().getName();
model.setConfigFile(buildConfig.getConfigFile().getAbsolutePath());
kind = IProgramElement.Kind.FILE_LST;
}
model.setRoot(new ProgramElement(rootLabel, kind, new ArrayList()));
model.setFileMap(new HashMap());
setStructureModel(model);
state.setStructureModel(model);
state.setRelationshipMap(AsmManager.getDefault().getRelationshipMap());
}
//
// private void dumplist(List l) {
// System.err.println("---- "+l.size());
// for (int i =0 ;i<l.size();i++) System.err.println(i+"\t "+l.get(i));
// }
// private void accumulateFileNodes(IProgramElement ipe,List store) {
// if (ipe.getKind()==IProgramElement.Kind.FILE_JAVA ||
// ipe.getKind()==IProgramElement.Kind.FILE_ASPECTJ) {
// if (!ipe.getName().equals("<root>")) {
// store.add(ipe);
// return;
// }
// }
// for (Iterator i = ipe.getChildren().iterator();i.hasNext();) {
// accumulateFileNodes((IProgramElement)i.next(),store);
// }
// }
/** init only on initial batch compile? no file-specific options */
private void initBcelWorld(IMessageHandler handler) throws IOException {
List cp =
buildConfig.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);
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();
//??? incremental issues
for (Iterator i = buildConfig.getInJars().iterator(); i.hasNext(); ) {
File inJar = (File)i.next();
List unwovenClasses = bcelWeaver.addJarFile(inJar, buildConfig.getOutputDir(),false);
state.recordBinarySource(inJar.getPath(), unwovenClasses);
}
for (Iterator i = buildConfig.getInpath().iterator(); i.hasNext(); ) {
File inPathElement = (File)i.next();
if (!inPathElement.isDirectory()) {
// its a jar file on the inpath
// the weaver method can actually handle dirs, but we don't call it, see next block
List unwovenClasses = bcelWeaver.addJarFile(inPathElement,buildConfig.getOutputDir(),true);
state.recordBinarySource(inPathElement.getPath(),unwovenClasses);
} else {
// add each class file in an in-dir individually, this gives us the best error reporting
// (they are like 'source' files then), and enables a cleaner incremental treatment of
// class file changes in indirs.
File[] binSrcs = FileUtil.listFiles(inPathElement, binarySourceFilter);
for (int j = 0; j < binSrcs.length; j++) {
UnwovenClassFile ucf =
bcelWeaver.addClassFile(binSrcs[j], inPathElement, buildConfig.getOutputDir());
List ucfl = new ArrayList();
ucfl.add(ucf);
state.recordBinarySource(binSrcs[j].getPath(),ucfl);
}
}
}
bcelWeaver.setReweavableMode(buildConfig.isXNotReweavable());
//check for org.aspectj.runtime.JoinPoint
ResolvedType joinPoint = bcelWorld.resolve("org.aspectj.lang.JoinPoint");
if (joinPoint.isMissing()) {
IMessage message =
new Message("classpath error: unable to find org.aspectj.lang.JoinPoint (check that aspectjrt.jar is in your classpath)",
null,
true);
handler.handleMessage(message);
}
}
public World getWorld() {
return getBcelWorld();
}
void addAspectClassFilesToWeaver(List addedClassFiles) throws IOException {
for (Iterator i = addedClassFiles.iterator(); i.hasNext(); ) {
UnwovenClassFile classFile = (UnwovenClassFile) i.next();
getWeaver().addClassFile(classFile);
}
}
// public boolean weaveAndGenerateClassFiles() throws IOException {
// handler.handleMessage(MessageUtil.info("weaving"));
// if (progressListener != null) progressListener.setText("weaving aspects");
// bcelWeaver.setProgressListener(progressListener, 0.5, 0.5/state.addedClassFiles.size());
// //!!! doesn't provide intermediate progress during weaving
// // XXX add all aspects even during incremental builds?
// addAspectClassFilesToWeaver(state.addedClassFiles);
// if (buildConfig.isNoWeave()) {
// if (buildConfig.getOutputJar() != null) {
// bcelWeaver.dumpUnwoven(buildConfig.getOutputJar());
// } else {
// bcelWeaver.dumpUnwoven();
// bcelWeaver.dumpResourcesToOutPath();
// }
// } else {
// if (buildConfig.getOutputJar() != null) {
// bcelWeaver.weave(buildConfig.getOutputJar());
// } else {
// bcelWeaver.weave();
// bcelWeaver.dumpResourcesToOutPath();
// }
// }
// if (progressListener != null) progressListener.setProgress(1.0);
// return true;
// //return messageAdapter.getErrorCount() == 0; //!javaBuilder.notifier.anyErrors();
// }
public FileSystem getLibraryAccess(String[] classpaths, String[] filenames) {
String defaultEncoding = buildConfig.getOptions().defaultEncoding;
if ("".equals(defaultEncoding)) //$NON-NLS-1$
defaultEncoding = null; //$NON-NLS-1$
// Bug 46671: We need an array as long as the number of elements in the classpath - *even though* not every
// element of the classpath is likely to be a directory. If we ensure every element of the array is set to
// only look for BINARY, then we make sure that for any classpath element that is a directory, we won't build
// a classpathDirectory object that will attempt to look for source when it can't find binary.
int[] classpathModes = new int[classpaths.length];
for (int i =0 ;i<classpaths.length;i++) classpathModes[i]=ClasspathDirectory.BINARY;
return new FileSystem(classpaths, filenames, defaultEncoding,classpathModes);
}
public IProblemFactory getProblemFactory() {
return new DefaultProblemFactory(Locale.getDefault());
}
/*
* Build the set of compilation source units
*/
public CompilationUnit[] getCompilationUnits(String[] filenames, String[] encodings) {
int fileCount = filenames.length;
CompilationUnit[] units = new CompilationUnit[fileCount];
// HashtableOfObject knownFileNames = new HashtableOfObject(fileCount);
String defaultEncoding = buildConfig.getOptions().defaultEncoding;
if ("".equals(defaultEncoding)) //$NON-NLS-1$
defaultEncoding = null; //$NON-NLS-1$
for (int i = 0; i < fileCount; i++) {
String encoding = encodings[i];
if (encoding == null)
encoding = defaultEncoding;
units[i] = new CompilationUnit(null, filenames[i], encoding);
}
return units;
}
public String extractDestinationPathFromSourceFile(CompilationResult result) {
ICompilationUnit compilationUnit = result.compilationUnit;
if (compilationUnit != null) {
char[] fileName = compilationUnit.getFileName();
int lastIndex = CharOperation.lastIndexOf(java.io.File.separatorChar, fileName);
if (lastIndex == -1) {
return System.getProperty("user.dir"); //$NON-NLS-1$
}
return new String(CharOperation.subarray(fileName, 0, lastIndex));
}
return System.getProperty("user.dir"); //$NON-NLS-1$
}
public void performCompilation(List files) {
if (progressListener != null) {
compiledCount=0;
sourceFileCount = files.size();
progressListener.setText("compiling source files");
}
//System.err.println("got files: " + files);
String[] filenames = new String[files.size()];
String[] encodings = new String[files.size()];
//System.err.println("filename: " + this.filenames);
for (int i=0; i < files.size(); i++) {
filenames[i] = ((File)files.get(i)).getPath();
}
List cps = buildConfig.getFullClasspath();
Dump.saveFullClasspath(cps);
String[] classpaths = new String[cps.size()];
for (int i=0; i < cps.size(); i++) {
classpaths[i] = (String)cps.get(i);
}
//System.out.println("compiling");
environment = getLibraryAccess(classpaths, filenames);
if (!state.getClassNameToFileMap().isEmpty()) {
environment = new StatefulNameEnvironment(environment, state.getClassNameToFileMap());
}
org.aspectj.ajdt.internal.compiler.CompilerAdapter.setCompilerAdapterFactory(this);
org.aspectj.org.eclipse.jdt.internal.compiler.Compiler compiler =
new org.aspectj.org.eclipse.jdt.internal.compiler.Compiler(environment,
DefaultErrorHandlingPolicies.proceedWithAllProblems(),
buildConfig.getOptions().getMap(),
getBatchRequestor(),
getProblemFactory());
CompilerOptions options = compiler.options;
options.produceReferenceInfo = true; //TODO turn off when not needed
try {
compiler.compile(getCompilationUnits(filenames, encodings));
} catch (OperationCanceledException oce) {
handler.handleMessage(new Message("build cancelled:"+oce.getMessage(),IMessage.WARNING,null,null));
}
// cleanup
org.aspectj.ajdt.internal.compiler.CompilerAdapter.setCompilerAdapterFactory(null);
AnonymousClassPublisher.aspectOf().setAnonymousClassCreationListener(null);
environment.cleanup();
environment = null;
}
/*
* Answer the component to which will be handed back compilation results from the compiler
*/
public IIntermediateResultsRequestor getInterimResultRequestor() {
return new IIntermediateResultsRequestor() {
public void acceptResult(InterimCompilationResult result) {
if (progressListener != null) {
compiledCount++;
progressListener.setProgress((compiledCount/2.0)/sourceFileCount);
progressListener.setText("compiled: " + result.fileName());
}
state.noteResult(result);
if (progressListener!=null && progressListener.isCancelledRequested()) {
throw new AbortCompilation(true,
new OperationCanceledException("Compilation cancelled as requested"));
}
}
};
}
public ICompilerRequestor getBatchRequestor() {
return new ICompilerRequestor() {
public void acceptResult(CompilationResult unitResult) {
// end of compile, must now write the results to the output destination
// this is either a jar file or a file in a directory
if (!(unitResult.hasErrors() && !proceedOnError())) {
Collection classFiles = unitResult.compiledTypes.values();
boolean shouldAddAspectName = (buildConfig.getOutxmlName() != null);
for (Iterator iter = classFiles.iterator(); iter.hasNext();) {
ClassFile classFile = (ClassFile) iter.next();
String filename = new String(classFile.fileName());
String classname = filename.replace('/', '.');
filename = filename.replace('/', File.separatorChar) + ".class";
try {
if (buildConfig.getOutputJar() == null) {
writeDirectoryEntry(unitResult, classFile,filename);
} else {
writeZipEntry(classFile,filename);
}
if (shouldAddAspectName) addAspectName(classname);
} catch (IOException ex) {
IMessage message = EclipseAdapterUtils.makeErrorMessage(
new String(unitResult.fileName),
CANT_WRITE_RESULT,
ex);
handler.handleMessage(message);
}
}
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) {
BcelWorld world = getBcelWorld();
ResolvedType type = world.resolve(name);
// System.err.println("? writeAspectName() type=" + type);
if (type.isAspect()) {
if (state.getAspectNames() == null) {
state.initializeAspectNamesList();
}
if (!state.getAspectNames().contains(name)) {
state.getAspectNames().add(name);
}
}
}
};
}
protected boolean proceedOnError() {
return buildConfig.getProceedOnError();
}
// public void noteClassFiles(AjCompiler.InterimResult result) {
// if (result == null) return;
// CompilationResult unitResult = result.result;
// String sourceFileName = result.fileName();
// if (!(unitResult.hasErrors() && !proceedOnError())) {
// List unwovenClassFiles = new ArrayList();
// Enumeration classFiles = unitResult.compiledTypes.elements();
// while (classFiles.hasMoreElements()) {
// ClassFile classFile = (ClassFile) classFiles.nextElement();
// String filename = new String(classFile.fileName());
// filename = filename.replace('/', File.separatorChar) + ".class";
//
// File destinationPath = buildConfig.getOutputDir();
// if (destinationPath == null) {
// filename = new File(filename).getName();
// filename = new File(extractDestinationPathFromSourceFile(unitResult), filename).getPath();
// } else {
// filename = new File(destinationPath, filename).getPath();
// }
//
// //System.out.println("classfile: " + filename);
// unwovenClassFiles.add(new UnwovenClassFile(filename, classFile.getBytes()));
// }
// state.noteClassesFromFile(unitResult, sourceFileName, unwovenClassFiles);
//// System.out.println("file: " + sourceFileName);
//// for (int i=0; i < unitResult.simpleNameReferences.length; i++) {
//// System.out.println("simple: " + new String(unitResult.simpleNameReferences[i]));
//// }
//// for (int i=0; i < unitResult.qualifiedReferences.length; i++) {
//// System.out.println("qualified: " +
//// new String(CharOperation.concatWith(unitResult.qualifiedReferences[i], '/')));
//// }
// } else {
// state.noteClassesFromFile(null, sourceFileName, Collections.EMPTY_LIST);
// }
// }
//
private void setBuildConfig(AjBuildConfig buildConfig) {
this.buildConfig = buildConfig;
if (!this.environmentSupportsIncrementalCompilation) {
this.environmentSupportsIncrementalCompilation =
(buildConfig.isIncrementalMode() || buildConfig.isIncrementalFileMode());
}
handler.reset();
}
String makeClasspathString(AjBuildConfig buildConfig) {
if (buildConfig == null || buildConfig.getFullClasspath() == null) return "";
StringBuffer buf = new StringBuffer();
boolean first = true;
for (Iterator it = buildConfig.getFullClasspath().iterator(); it.hasNext(); ) {
if (first) { first = false; }
else { buf.append(File.pathSeparator); }
buf.append(it.next().toString());
}
return buf.toString();
}
/**
* This will return null if aspectjrt.jar is present and has the correct version.
* Otherwise it will return a string message indicating the problem.
*/
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();
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;
}
}
|
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/multiIncremental/PR149293_1/base/src/mypackage/MyAbstractClass.java
| |
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/multiIncremental/PR149293_1/base/src/mypackage/MyAspect.java
| |
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/multiIncremental/PR149293_1/base/src/mypackage/MyBaseClass.java
| |
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/multiIncremental/PR149293_1/base/src/mypackage/MyInterface.java
| |
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/multiIncremental/PR149293_1/inc1/src/mypackage/MySubclass.java
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.