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
55,341
Bug 55341 error Type mismatch: cannot convert from java.lang.String to java.lang.String
When compiling a binary concrete aspect library (for later LTW) consisting of more than one aspect that performs an ITD on a target class not exposed to the weaver I get the following error: error Type mismatch: cannot convert from java.lang.String to java.lang.String The error does not oocur if a complete build & weave is performed. Testcase attached.
resolved fixed
0521e79
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2004-04-02T12:45:13Z
2004-03-19T09:53:20Z
tests/bugs/StringToString/X.java
55,341
Bug 55341 error Type mismatch: cannot convert from java.lang.String to java.lang.String
When compiling a binary concrete aspect library (for later LTW) consisting of more than one aspect that performs an ITD on a target class not exposed to the weaver I get the following error: error Type mismatch: cannot convert from java.lang.String to java.lang.String The error does not oocur if a complete build & weave is performed. Testcase attached.
resolved fixed
0521e79
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2004-04-02T12:45:13Z
2004-03-19T09:53:20Z
weaver/testsrc/org/aspectj/weaver/WeavingURLClassLoaderTest.java
/* ******************************************************************* * Copyright (c) 2004 IBM Corporation * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Common Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * Matthew Webster initial implementation * ******************************************************************/ package org.aspectj.weaver; import java.io.File; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.net.URL; import junit.framework.TestCase; import org.aspectj.bridge.AbortException; import org.aspectj.util.FileUtil; import org.aspectj.weaver.tools.WeavingAdaptor; /** * @author websterm * * To change the template for this generated type comment go to * Window>Preferences>Java>Code Generation>Code and Comments */ public class WeavingURLClassLoaderTest extends TestCase { private final static String CLASSES_JAR = BcweaverTests.TESTDATA_PATH + "/ltw-classes.jar"; private final static String WOVEN_JAR = BcweaverTests.TESTDATA_PATH + "/ltw-woven.jar"; private final static String JUNK_JAR = BcweaverTests.TESTDATA_PATH + "/ltw-junk.jar"; private final static String ADVICE_ASPECTS = BcweaverTests.TESTDATA_PATH + "/ltw-aspects.jar"; private final static String AROUNDCLOSURE_ASPECTS = BcweaverTests.TESTDATA_PATH + "/ltw-acaspects.jar"; private final static String ITD_ASPECTS = BcweaverTests.TESTDATA_PATH + "/ltw-itdaspects.jar"; private final static String PER_ASPECTS = BcweaverTests.TESTDATA_PATH + "/ltw-peraspects.jar"; public WeavingURLClassLoaderTest(String name) { super(name); System.setProperty(WeavingAdaptor.WEAVING_ADAPTOR_VERBOSE,"true"); } public void testLoadClass () { System.setProperty(WeavingURLClassLoader.WEAVING_ASPECT_PATH,""); System.setProperty(WeavingURLClassLoader.WEAVING_CLASS_PATH,CLASSES_JAR); WeavingURLClassLoader loader = new WeavingURLClassLoader(getClass().getClassLoader()); try { Class clazz = loader.loadClass("LTWHelloWorld"); invokeMain(clazz,new String[] {}); } catch (Exception ex) { fail(ex.toString()); } } public void testLoadWovenClass () { System.setProperty(WeavingURLClassLoader.WEAVING_ASPECT_PATH,""); System.setProperty(WeavingURLClassLoader.WEAVING_CLASS_PATH,WOVEN_JAR); WeavingURLClassLoader loader = new WeavingURLClassLoader(getClass().getClassLoader()); try { Class clazz = loader.loadClass("LTWHelloWorld"); invokeMain(clazz,new String[] { "LTWAspect" }); } catch (Exception ex) { fail(ex.toString()); } } public void testWeaveWovenClass () { System.setProperty(WeavingURLClassLoader.WEAVING_ASPECT_PATH,ADVICE_ASPECTS); System.setProperty(WeavingURLClassLoader.WEAVING_CLASS_PATH,ADVICE_ASPECTS + File.pathSeparator + WOVEN_JAR); WeavingURLClassLoader loader = new WeavingURLClassLoader(getClass().getClassLoader()); try { Class clazz = loader.loadClass("LTWHelloWorld"); fail("Expecting org.aspectj.bridge.AbortException"); } catch (Exception ex) { assertTrue("Expecting org.aspectj.bridge.AbortException caught " + ex,(ex instanceof AbortException)); } } public void testWeavingURLClassLoader () { URL classes = FileUtil.getFileURL(new File(CLASSES_JAR)); URL aspects = FileUtil.getFileURL(new File(ADVICE_ASPECTS)); URL[] classURLs = new URL[] { aspects, classes }; URL[] aspectURLs = new URL[] { aspects }; WeavingURLClassLoader loader = new WeavingURLClassLoader(classURLs,aspectURLs,getClass().getClassLoader()); try { Class clazz = loader.loadClass("LTWHelloWorld"); invokeMain(clazz,new String[] { "LTWAspect" }); } catch (Exception ex) { fail(ex.toString()); } } public void testWeaveAdvice () { System.setProperty(WeavingURLClassLoader.WEAVING_ASPECT_PATH,ADVICE_ASPECTS); System.setProperty(WeavingURLClassLoader.WEAVING_CLASS_PATH,ADVICE_ASPECTS + File.pathSeparator + CLASSES_JAR); WeavingURLClassLoader loader = new WeavingURLClassLoader(getClass().getClassLoader()); try { Class clazz = loader.loadClass("LTWHelloWorld"); invokeMain(clazz,new String[] { "LTWAspect" }); } catch (Exception ex) { fail(ex.toString()); } } public void testWeaveAroundClosure () { System.setProperty(WeavingURLClassLoader.WEAVING_ASPECT_PATH,AROUNDCLOSURE_ASPECTS); System.setProperty(WeavingURLClassLoader.WEAVING_CLASS_PATH,AROUNDCLOSURE_ASPECTS + File.pathSeparator + CLASSES_JAR); WeavingURLClassLoader loader = new WeavingURLClassLoader(getClass().getClassLoader()); try { Class clazz = loader.loadClass("LTWHelloWorld"); invokeMain(clazz,new String[] { "LTWAroundClosure" }); } catch (Exception ex) { fail(ex.toString()); } } public void testWeavingITD () { URL classes = FileUtil.getFileURL(new File(CLASSES_JAR)); URL aspects = FileUtil.getFileURL(new File(ITD_ASPECTS)); URL[] classURLs = new URL[] { aspects, classes }; URL[] aspectURLs = new URL[] { aspects }; WeavingURLClassLoader loader = new WeavingURLClassLoader(classURLs,aspectURLs,getClass().getClassLoader()); try { Class clazz = loader.loadClass("LTWHelloWorld"); /* Uncomment when bug #55341 fixed */ // invokeMain(clazz,new String[] { "LTWInterfaceITD", "LTWFieldITD", "LTWMethodITD" }); invokeMain(clazz,new String[] { "LTWInterfaceITD", "LTWFieldITD" }); } catch (Exception ex) { fail(ex.toString()); } } public void testWeavingPer () { URL classes = FileUtil.getFileURL(new File(CLASSES_JAR)); URL aspects = FileUtil.getFileURL(new File(PER_ASPECTS)); URL[] classURLs = new URL[] { aspects, classes }; URL[] aspectURLs = new URL[] { aspects }; WeavingURLClassLoader loader = new WeavingURLClassLoader(classURLs,aspectURLs,getClass().getClassLoader()); try { Class clazz = loader.loadClass("LTWHelloWorld"); invokeMain(clazz,new String[] { "LTWPerthis" }); } catch (Exception ex) { fail(ex.toString()); } } public void testWeavingAspects () { URL classes = FileUtil.getFileURL(new File(CLASSES_JAR)); URL aspects1 = FileUtil.getFileURL(new File(ADVICE_ASPECTS)); URL aspects2 = FileUtil.getFileURL(new File(AROUNDCLOSURE_ASPECTS)); URL aspects3 = FileUtil.getFileURL(new File(ITD_ASPECTS)); URL aspects4 = FileUtil.getFileURL(new File(PER_ASPECTS)); URL[] classURLs = new URL[] { aspects1, aspects2, aspects3, aspects4, classes }; URL[] aspectURLs = new URL[] { aspects1, aspects2, aspects3, aspects4 }; WeavingURLClassLoader loader = new WeavingURLClassLoader(classURLs,aspectURLs,getClass().getClassLoader()); try { Class clazz = loader.loadClass("LTWHelloWorld"); /* Uncomment when bug #55341 fixed */ // invokeMain(clazz,new String[] { "LTWAspect", "LTWAroundClosure", "LTWPerthis", "LTWInterfaceITD", "LTWFieldITD", "LTWMethodITD", "LTWPerthis"}); invokeMain(clazz,new String[] { "LTWAspect", "LTWAroundClosure", "LTWPerthis", "LTWInterfaceITD", "LTWFieldITD", "LTWPerthis"}); } catch (Exception ex) { fail(ex.toString()); } } public void testJunkJar () { File junkJar = new File(JUNK_JAR); assertFalse(junkJar + " should not exist",junkJar.exists()); URL classes = FileUtil.getFileURL(junkJar); URL[] classURLs = new URL[] { classes }; URL[] aspectURLs = new URL[] { }; WeavingURLClassLoader loader = new WeavingURLClassLoader(classURLs,aspectURLs,getClass().getClassLoader()); try { Class clazz = loader.loadClass("LTWHelloWorld"); fail("Expecting java.lang.ClassNotFoundException"); } catch (Exception ex) { assertTrue("Expecting java.lang.ClassNotFoundException caught " + ex,(ex instanceof ClassNotFoundException)); } } public void testAddURL () { URL classes = FileUtil.getFileURL(new File(CLASSES_JAR)); URL aspects = FileUtil.getFileURL(new File(ADVICE_ASPECTS)); URL[] classURLs = new URL[] { aspects }; URL[] aspectURLs = new URL[] { aspects }; WeavingURLClassLoader loader = new WeavingURLClassLoader(classURLs,aspectURLs,getClass().getClassLoader()); loader.addURL(classes); try { Class clazz = loader.loadClass("LTWHelloWorld"); invokeMain(clazz,new String[] { "LTWAspect" }); } catch (Exception ex) { fail(ex.toString()); } } public void testParentChild() { URL classes = FileUtil.getFileURL(new File(CLASSES_JAR)); URL aspects = FileUtil.getFileURL(new File(ADVICE_ASPECTS)); URL[] classURLs = new URL[] { aspects }; URL[] aspectURLs = new URL[] { aspects }; WeavingURLClassLoader parent = new WeavingURLClassLoader(classURLs,aspectURLs,getClass().getClassLoader()); classURLs = new URL[] { classes }; aspectURLs = new URL[] { }; WeavingURLClassLoader child = new WeavingURLClassLoader(classURLs,aspectURLs,parent); try { Class clazz = child.loadClass("LTWHelloWorld"); invokeMain(clazz,new String[] { "LTWAspect" }); } catch (Exception ex) { fail(ex.toString()); } } /* * Aspects on ASPECTPATH but missing from CLASSPATH */ public void testIncompletePath () { System.setProperty(WeavingURLClassLoader.WEAVING_ASPECT_PATH,ADVICE_ASPECTS); System.setProperty(WeavingURLClassLoader.WEAVING_CLASS_PATH,CLASSES_JAR); WeavingURLClassLoader loader = new WeavingURLClassLoader(getClass().getClassLoader()); try { Class clazz = loader.loadClass("LTWHelloWorld"); invokeMain(clazz,new String[] { "LTWAspect" }); fail("Expecting java.lang.NoClassDefFoundError"); } catch (Exception ex) { } } /* * Ensure package object is correct */ public void testPackage () { System.setProperty(WeavingURLClassLoader.WEAVING_ASPECT_PATH,""); System.setProperty(WeavingURLClassLoader.WEAVING_CLASS_PATH,CLASSES_JAR); WeavingURLClassLoader loader = new WeavingURLClassLoader(getClass().getClassLoader()); try { Class clazz = loader.loadClass("ltw.LTWPackageTest"); invokeMain(clazz,new String[] { }); Package pakkage = clazz.getPackage(); assertTrue("Expected 'ltw' got " + pakkage,(pakkage != null)); } catch (Exception ex) { fail(ex.toString()); } } public static void invokeMain (Class clazz, String[] args) { Class[] paramTypes = new Class[1]; paramTypes[0] = args.getClass(); try { Method method = clazz.getDeclaredMethod("main",paramTypes); Object[] params = new Object[1]; params[0] = args; method.invoke(null,params); } catch (InvocationTargetException ex) { throw new RuntimeException(ex.getTargetException().toString()); } catch (Exception ex) { throw new RuntimeException(ex.toString()); } } }
57,430
Bug 57430 exception printing
Exceptions thrown from the compiler used to be printed once, with the submit-bug header. Now they are printed twice, without and with the header. True of CVS version.
resolved fixed
e7ac54f
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2004-04-07T09:07:43Z
2004-04-05T10:13:20Z
org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/compiler/AjCompilerAdapter.java
/******************************************************************************* * Copyright (c) 2004 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Common Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.aspectj.ajdt.internal.compiler; import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import org.aspectj.ajdt.internal.compiler.lookup.EclipseFactory; import org.aspectj.bridge.IMessage; import org.aspectj.bridge.IMessageHandler; import org.aspectj.bridge.IProgressListener; import org.aspectj.weaver.bcel.BcelWeaver; import org.aspectj.weaver.bcel.BcelWorld; import org.eclipse.jdt.internal.compiler.CompilationResult; import org.eclipse.jdt.internal.compiler.Compiler; import org.eclipse.jdt.internal.compiler.ICompilerAdapter; import org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration; import org.eclipse.jdt.internal.compiler.env.ICompilationUnit; import org.eclipse.jdt.internal.compiler.problem.AbortCompilation; /** * @author colyer * * Adapts standard JDT Compiler to add in AspectJ specific behaviours. */ public class AjCompilerAdapter implements ICompilerAdapter { private Compiler compiler; private BcelWeaver weaver; private EclipseFactory eWorld; private boolean isBatchCompile; private boolean reportedErrors; private boolean isXNoWeave; private IIntermediateResultsRequestor intermediateResultsRequestor; private IProgressListener progressListener; private IOutputClassFileNameProvider outputFileNameProvider; private IBinarySourceProvider binarySourceProvider; private WeaverMessageHandler weaverMessageHandler; private Map /* fileName |-> List<UnwovenClassFile> */ binarySourceSetForFullWeave = new HashMap(); private Collection /*InterimCompilationResult*/ resultSetForFullWeave = Collections.EMPTY_LIST; List /*InterimResult*/ resultsPendingWeave = new ArrayList(); /** * Create an adapter, and tell it everything it needs to now to drive the AspectJ * parts of a compile cycle. * @param compiler the JDT compiler that produces class files from source * @param isBatchCompile true if this is a full build (non-incremental) * @param world the bcelWorld used for type resolution during weaving * @param weaver the weaver * @param intRequestor recipient of interim compilation results from compiler (pre-weave) * @param outputFileNameProvider implementor of a strategy providing output file names for results * @param binarySourceEntries binary source that we didn't compile, but that we need to weave * @param resultSetForFullWeave if we are doing an incremental build, and the weaver determines * that we need to weave the world, this is the set of intermediate * results that will be passed to the weaver. * @param isXNoWeave */ public AjCompilerAdapter(Compiler compiler, boolean isBatchCompile, BcelWorld world, BcelWeaver weaver, EclipseFactory eFactory, IIntermediateResultsRequestor intRequestor, IProgressListener progressListener, IOutputClassFileNameProvider outputFileNameProvider, IBinarySourceProvider binarySourceProvider, Map fullBinarySourceEntries, /* fileName |-> List<UnwovenClassFile> */ Collection /* InterimCompilationResult */ resultSetForFullWeave, boolean isXNoWeave) { this.compiler = compiler; this.isBatchCompile = isBatchCompile; this.weaver = weaver; this.intermediateResultsRequestor = intRequestor; this.progressListener = progressListener; this.outputFileNameProvider = outputFileNameProvider; this.binarySourceProvider = binarySourceProvider; this.isXNoWeave = isXNoWeave; this.binarySourceSetForFullWeave = fullBinarySourceEntries; this.resultSetForFullWeave = resultSetForFullWeave; this.eWorld = eFactory; IMessageHandler msgHandler = world.getMessageHandler(); weaverMessageHandler = new WeaverMessageHandler(msgHandler, compiler); world.setMessageHandler(weaverMessageHandler); } public void beforeCompiling(ICompilationUnit[] sourceUnits) { resultsPendingWeave = new ArrayList(); reportedErrors = false; } public void afterCompiling() { try { if (isXNoWeave || reportedErrors) { // no point weaving... just tell the requestor we're done notifyRequestor(); } else { weave(); // notification happens as weave progresses... } } catch (IOException ex) { AbortCompilation ac = new AbortCompilation(null,ex); throw ac; } } public void beforeProcessing(CompilationUnitDeclaration unit) { eWorld.showMessage(IMessage.INFO, "compiling " + new String(unit.getFileName()), null, null); } public void afterProcessing(CompilationUnitDeclaration unit, int unitIndex) { eWorld.finishedCompilationUnit(unit); InterimCompilationResult intRes = new InterimCompilationResult(unit.compilationResult,outputFileNameProvider); if (unit.compilationResult.hasErrors()) reportedErrors = true; if (intermediateResultsRequestor != null) { intermediateResultsRequestor.acceptResult(intRes); } if (isXNoWeave) { acceptResult(unit.compilationResult); } else { resultsPendingWeave.add(intRes); } } public void beforeResolving(CompilationUnitDeclaration unit, ICompilationUnit sourceUnit, boolean verifyMethods, boolean analyzeCode, boolean generateCode) { resultsPendingWeave = new ArrayList(); reportedErrors = false; } public void afterResolving(CompilationUnitDeclaration unit, ICompilationUnit sourceUnit, boolean verifyMethods, boolean analyzeCode, boolean generateCode) { InterimCompilationResult intRes = new InterimCompilationResult(unit.compilationResult,outputFileNameProvider); if (unit.compilationResult.hasErrors()) reportedErrors = true; if (isXNoWeave || !generateCode) { acceptResult(unit.compilationResult); } else if (generateCode){ resultsPendingWeave.add(intRes); try { weave(); } catch (IOException ex) { AbortCompilation ac = new AbortCompilation(null,ex); throw ac; } } } // helper methods... // ================================================================================== /* * Called from the weaverAdapter once it has finished weaving the class files * associated with a given compilation result. */ public void acceptResult(CompilationResult result) { compiler.requestor.acceptResult(result.tagAsAccepted()); if (compiler.unitsToProcess != null) { for (int i = 0; i < compiler.unitsToProcess.length; i++) { if (compiler.unitsToProcess[i] != null) { if (compiler.unitsToProcess[i].compilationResult == result) { compiler.unitsToProcess[i] = null; } } } } } private List getBinarySourcesFrom(Map binarySourceEntries) { // Map is fileName |-> List<UnwovenClassFile> List ret = new ArrayList(); for (Iterator binIter = binarySourceEntries.keySet().iterator(); binIter.hasNext();) { String sourceFileName = (String) binIter.next(); List unwovenClassFiles = (List) binarySourceEntries.get(sourceFileName); CompilationResult result = new CompilationResult(sourceFileName.toCharArray(),0,0,20); result.noSourceAvailable(); InterimCompilationResult binarySource = new InterimCompilationResult(result,unwovenClassFiles); ret.add(binarySource); } return ret; } private void notifyRequestor() { for (Iterator iter = resultsPendingWeave.iterator(); iter.hasNext();) { InterimCompilationResult iresult = (InterimCompilationResult) iter.next(); compiler.requestor.acceptResult(iresult.result().tagAsAccepted()); } } private void weave() throws IOException { // ensure weaver state is set up correctly for (Iterator iter = resultsPendingWeave.iterator(); iter.hasNext();) { InterimCompilationResult iresult = (InterimCompilationResult) iter.next(); for (int i = 0; i < iresult.unwovenClassFiles().length; i++) { weaver.addClassFile(iresult.unwovenClassFiles()[i]); } } weaver.prepareForWeave(); if (weaver.needToReweaveWorld()) { if (!isBatchCompile) addAllKnownClassesToWeaveList(); // if it's batch, they're already on the list... resultsPendingWeave.addAll(getBinarySourcesFrom(binarySourceSetForFullWeave)); } else { Map binarySourcesToAdd = binarySourceProvider.getBinarySourcesForThisWeave(); resultsPendingWeave.addAll(getBinarySourcesFrom(binarySourcesToAdd)); } // if (isBatchCompile) { // resultsPendingWeave.addAll(getBinarySourcesFrom(binarySourceSetForFullWeave)); // // passed into the compiler, the set of classes in injars and inpath... // } else if (weaver.needToReweaveWorld()) { // addAllKnownClassesToWeaveList(); // resultsPendingWeave.addAll(getBinarySourcesFrom(binarySourceSetForFullWeave)); // } weaver.weave(new WeaverAdapter(this,weaverMessageHandler,progressListener)); } private void addAllKnownClassesToWeaveList() { // results pending weave already has some results from this (incremental) compile // add in results from any other source for (Iterator iter = resultSetForFullWeave.iterator(); iter.hasNext();) { InterimCompilationResult ir = (InterimCompilationResult) iter.next(); if (!resultsPendingWeave.contains(ir)) { // equality based on source file name... ir.result().hasBeenAccepted = false; // it may have been accepted before, start again resultsPendingWeave.add(ir); } } } }
57,436
Bug 57436 Java 1.5 fails to run classes produced by ajc
Java 1.5 beta reports a ClassFormatError when running programs (e.g., spacewar) compiled by ajc 1.1.1 and the latest CVS head. Sun's Java 1.5 beta binary-compatibility docs say that some obfuscators violated the .class format specification, so those .class files will fail when run under 1.5. (The docs also say they are still incomplete.) Although 1.5 is still beta, we would want to submit a bug to Sun if our implementation techniques are valid, so we don't have to change those techniques. For 1.2, we should at document if we don't fix, since many people are using 1.5.
resolved fixed
b0d32ca
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2004-04-08T10:46:58Z
2004-04-05T10:13:20Z
org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/compiler/ast/AspectDeclaration.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Common Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * PARC initial implementation * ******************************************************************/ package org.aspectj.ajdt.internal.compiler.ast; import java.lang.reflect.Modifier; import java.util.*; import org.aspectj.ajdt.internal.compiler.lookup.*; import org.aspectj.weaver.*; import org.aspectj.weaver.patterns.*; import org.eclipse.jdt.internal.compiler.ClassFile; import org.eclipse.jdt.internal.compiler.CompilationResult; //import org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration; import org.eclipse.jdt.internal.compiler.ast.Clinit; //import org.eclipse.jdt.internal.compiler.ast.ConstructorDeclaration; import org.eclipse.jdt.internal.compiler.ast.TypeDeclaration; import org.eclipse.jdt.internal.compiler.codegen.CodeStream; import org.eclipse.jdt.internal.compiler.codegen.Label; import org.eclipse.jdt.internal.compiler.lookup.*; //import org.eclipse.jdt.internal.compiler.parser.Parser; // (we used to...) making all aspects member types avoids a nasty hierarchy pain // switched from MemberTypeDeclaration to TypeDeclaration public class AspectDeclaration extends TypeDeclaration { //public IAjDeclaration[] ajDeclarations; private AjAttribute.Aspect aspectAttribute; public PerClause perClause; public ResolvedMember aspectOfMethod; public ResolvedMember hasAspectMethod; public Map accessForInline = new HashMap(); public Map superAccessForInline = new HashMap(); public boolean isPrivileged; public EclipseSourceType concreteName; public ResolvedTypeX.Name typeX; public EclipseFactory factory; //??? should use this consistently public int adviceCounter = 1; // Used as a part of the generated name for advice methods // for better error messages in 1.0 to 1.1 transition public TypePattern dominatesPattern; public AspectDeclaration(CompilationResult compilationResult) { super(compilationResult); //perClause = new PerSingleton(); } public boolean isAbstract() { return (modifiers & AccAbstract) != 0; } public void resolve() { if (binding == null) { ignoreFurtherInvestigation = true; return; } super.resolve(); } public void checkSpec(ClassScope scope) { if (ignoreFurtherInvestigation) return; if (dominatesPattern != null) { scope.problemReporter().signalError( dominatesPattern.getStart(), dominatesPattern.getEnd(), "dominates has changed for 1.1, use 'declare precedence: " + new String(this.name) + ", " + dominatesPattern.toString() + ";' " + "in the body of the aspect instead"); } if (!isAbstract()) { MethodBinding[] methods = binding.methods(); for (int i=0, len = methods.length; i < len; i++) { MethodBinding m = methods[i]; if (m.isConstructor()) { // this make all constructors in aspects invisible and thus uncallable //XXX this only works for aspects that come from source methods[i] = new MethodBinding(m, binding) { public boolean canBeSeenBy( InvocationSite invocationSite, Scope scope) { return false; } }; if (m.parameters != null && m.parameters.length != 0) { scope.problemReporter().signalError(m.sourceStart(), m.sourceEnd(), "only zero-argument constructors allowed in concrete aspect"); } } } } if (this.enclosingType != null) { if (!Modifier.isStatic(modifiers)) { scope.problemReporter().signalError(sourceStart, sourceEnd, "inner aspects must be static"); ignoreFurtherInvestigation = true; return; } } EclipseFactory world = EclipseFactory.fromScopeLookupEnvironment(scope); ResolvedTypeX myType = typeX; //if (myType == null) System.err.println("bad myType for: " + this); ResolvedTypeX superType = myType.getSuperclass(); // can't be Serializable/Cloneable unless -XserializableAspects if (!world.buildManager.buildConfig.isXserializableAspects()) { if (world.getWorld().resolve(TypeX.SERIALIZABLE).isAssignableFrom(myType)) { scope.problemReporter().signalError(sourceStart, sourceEnd, "aspects may not implement Serializable"); ignoreFurtherInvestigation = true; return; } if (world.getWorld().resolve(TypeX.CLONEABLE).isAssignableFrom(myType)) { scope.problemReporter().signalError(sourceStart, sourceEnd, "aspects may not implement Cloneable"); ignoreFurtherInvestigation = true; return; } } if (superType.isAspect()) { if (!superType.isAbstract()) { scope.problemReporter().signalError(sourceStart, sourceEnd, "can not extend a concrete aspect"); ignoreFurtherInvestigation = true; return; } } } private FieldBinding initFailureField= null; public void generateCode(ClassFile enclosingClassFile) { if (ignoreFurtherInvestigation) { if (binding == null) return; ClassFile.createProblemType( this, scope.referenceCompilationUnit().compilationResult); return; } // make me and my binding public this.modifiers = AstUtil.makePublic(this.modifiers); this.binding.modifiers = AstUtil.makePublic(this.binding.modifiers); if (!isAbstract()) { initFailureField = factory.makeFieldBinding(AjcMemberMaker.initFailureCauseField(typeX)); binding.addField(initFailureField); if (perClause == null) { // we've already produced an error for this } else if (perClause.getKind() == PerClause.SINGLETON) { binding.addField(factory.makeFieldBinding(AjcMemberMaker.perSingletonField( typeX))); methods[0] = new AspectClinit((Clinit)methods[0], compilationResult, false, true, initFailureField); } else if (perClause.getKind() == PerClause.PERCFLOW) { binding.addField( factory.makeFieldBinding( AjcMemberMaker.perCflowField( typeX))); methods[0] = new AspectClinit((Clinit)methods[0], compilationResult, true, false, null); } else if (perClause.getKind() == PerClause.PEROBJECT) { // binding.addField( // world.makeFieldBinding( // AjcMemberMaker.perCflowField( // typeX))); } else { throw new RuntimeException("unimplemented"); } } if (EclipseFactory.DEBUG) System.out.println(toString()); super.generateCode(enclosingClassFile); } public boolean needClassInitMethod() { return true; } protected void generateAttributes(ClassFile classFile) { if (!isAbstract()) generatePerSupportMembers(classFile); generateInlineAccessMembers(classFile); classFile.extraAttributes.add( new EclipseAttributeAdapter(new AjAttribute.Aspect(perClause))); if (binding.privilegedHandler != null) { ResolvedMember[] members = ((PrivilegedHandler)binding.privilegedHandler).getMembers(); classFile.extraAttributes.add( new EclipseAttributeAdapter(new AjAttribute.PrivilegedAttribute(members))); } //XXX need to get this attribute on anyone with a pointcut for good errors classFile.extraAttributes.add( new EclipseAttributeAdapter(new AjAttribute.SourceContextAttribute( new String(compilationResult().getFileName()), compilationResult().lineSeparatorPositions))); super.generateAttributes(classFile); } private void generateInlineAccessMembers(ClassFile classFile) { for (Iterator i = superAccessForInline.values().iterator(); i.hasNext(); ) { AccessForInlineVisitor.SuperAccessMethodPair pair = (AccessForInlineVisitor.SuperAccessMethodPair)i.next(); generateSuperAccessMethod(classFile, pair.accessMethod, pair.originalMethod); } for (Iterator i = accessForInline.entrySet().iterator(); i.hasNext(); ) { Map.Entry e = (Map.Entry)i.next(); generateInlineAccessMethod(classFile, (Binding)e.getValue(), (ResolvedMember)e.getKey()); } } private void generatePerSupportMembers(ClassFile classFile) { if (isAbstract()) return; //XXX otherwise we need to have this (error handling?) if (aspectOfMethod == null) return; if (perClause == null) { System.err.println("has null perClause: " + this); return; } EclipseFactory world = EclipseFactory.fromScopeLookupEnvironment(this.scope); if (perClause.getKind() == PerClause.SINGLETON) { generatePerSingletonAspectOfMethod(classFile); generatePerSingletonHasAspectMethod(classFile); generatePerSingletonAjcClinitMethod(classFile); } else if (perClause.getKind() == PerClause.PERCFLOW) { generatePerCflowAspectOfMethod(classFile); generatePerCflowHasAspectMethod(classFile); generatePerCflowPushMethod(classFile); generatePerCflowAjcClinitMethod(classFile); } else if (perClause.getKind() == PerClause.PEROBJECT) { TypeBinding interfaceType = generatePerObjectInterface(classFile); world.addTypeBinding(interfaceType); generatePerObjectAspectOfMethod(classFile, interfaceType); generatePerObjectHasAspectMethod(classFile, interfaceType); generatePerObjectBindMethod(classFile, interfaceType); } else { throw new RuntimeException("unimplemented"); } } private static interface BodyGenerator { public void generate(CodeStream codeStream); } private void generateMethod(ClassFile classFile, ResolvedMember member, BodyGenerator gen) { final EclipseFactory world = EclipseFactory.fromScopeLookupEnvironment(this.scope); generateMethod(classFile, world.makeMethodBinding(member), gen); } private void generateMethod(ClassFile classFile, MethodBinding methodBinding, BodyGenerator gen) { // EclipseFactory world = EclipseFactory.fromScopeLookupEnvironment(this.scope); classFile.generateMethodInfoHeader(methodBinding); int methodAttributeOffset = classFile.contentsOffset; int attributeNumber = classFile.generateMethodInfoAttribute(methodBinding, AstUtil.getAjSyntheticAttribute()); int codeAttributeOffset = classFile.contentsOffset; classFile.generateCodeAttributeHeader(); CodeStream codeStream = classFile.codeStream; codeStream.init(classFile); codeStream.initializeMaxLocals(methodBinding); // body starts here gen.generate(codeStream); // body ends here classFile.completeCodeAttribute(codeAttributeOffset); attributeNumber++; classFile.completeMethodInfo(methodAttributeOffset, attributeNumber); } private void generatePerCflowAspectOfMethod( ClassFile classFile) { final EclipseFactory world = EclipseFactory.fromScopeLookupEnvironment(this.scope); generateMethod(classFile, aspectOfMethod, new BodyGenerator() { public void generate(CodeStream codeStream) { // body starts here codeStream.getstatic( world.makeFieldBinding( AjcMemberMaker.perCflowField( typeX))); codeStream.invokevirtual(world.makeMethodBindingForCall( AjcMemberMaker.cflowStackPeekInstance())); codeStream.checkcast(binding); codeStream.areturn(); // body ends here }}); } private void generatePerCflowHasAspectMethod(ClassFile classFile) { final EclipseFactory world = EclipseFactory.fromScopeLookupEnvironment(this.scope); generateMethod(classFile, hasAspectMethod, new BodyGenerator() { public void generate(CodeStream codeStream) { // body starts here codeStream.getstatic( world.makeFieldBinding( AjcMemberMaker.perCflowField( typeX))); codeStream.invokevirtual(world.makeMethodBindingForCall( AjcMemberMaker.cflowStackIsValid())); codeStream.ireturn(); // body ends here }}); } private void generatePerCflowPushMethod( ClassFile classFile) { final EclipseFactory world = EclipseFactory.fromScopeLookupEnvironment(this.scope); generateMethod(classFile, world.makeMethodBinding(AjcMemberMaker.perCflowPush( EclipseFactory.fromBinding(binding))), new BodyGenerator() { public void generate(CodeStream codeStream) { // body starts here codeStream.getstatic( world.makeFieldBinding( AjcMemberMaker.perCflowField( typeX))); codeStream.new_(binding); codeStream.dup(); codeStream.invokespecial( new MethodBinding(0, "<init>".toCharArray(), BaseTypes.VoidBinding, new TypeBinding[0], new ReferenceBinding[0], binding)); codeStream.invokevirtual(world.makeMethodBindingForCall( AjcMemberMaker.cflowStackPushInstance())); codeStream.return_(); // body ends here }}); } private void generatePerCflowAjcClinitMethod( ClassFile classFile) { final EclipseFactory world = EclipseFactory.fromScopeLookupEnvironment(this.scope); generateMethod(classFile, world.makeMethodBinding(AjcMemberMaker.ajcPreClinitMethod( EclipseFactory.fromBinding(binding))), new BodyGenerator() { public void generate(CodeStream codeStream) { // body starts here codeStream.new_(world.makeTypeBinding(AjcMemberMaker.CFLOW_STACK_TYPE)); codeStream.dup(); codeStream.invokespecial(world.makeMethodBindingForCall(AjcMemberMaker.cflowStackInit())); codeStream.putstatic( world.makeFieldBinding( AjcMemberMaker.perCflowField( typeX))); codeStream.return_(); // body ends here }}); } private TypeBinding generatePerObjectInterface( ClassFile classFile) { final EclipseFactory world = EclipseFactory.fromScopeLookupEnvironment(this.scope); TypeX interfaceTypeX = AjcMemberMaker.perObjectInterfaceType(typeX); HelperInterfaceBinding interfaceType = new HelperInterfaceBinding(this.binding, interfaceTypeX); world.addTypeBinding(interfaceType); interfaceType.addMethod(world, AjcMemberMaker.perObjectInterfaceGet(typeX)); interfaceType.addMethod(world, AjcMemberMaker.perObjectInterfaceSet(typeX)); interfaceType.generateClass(compilationResult, classFile); return interfaceType; } private void generatePerObjectAspectOfMethod( ClassFile classFile, final TypeBinding interfaceType) { final EclipseFactory world = EclipseFactory.fromScopeLookupEnvironment(this.scope); generateMethod(classFile, aspectOfMethod, new BodyGenerator() { public void generate(CodeStream codeStream) { // body starts here Label wrongType = new Label(codeStream); Label popWrongType = new Label(codeStream); codeStream.aload_0(); codeStream.instance_of(interfaceType); codeStream.ifeq(wrongType); codeStream.aload_0(); codeStream.checkcast(interfaceType); codeStream.invokeinterface(world.makeMethodBindingForCall( AjcMemberMaker.perObjectInterfaceGet(typeX))); codeStream.dup(); codeStream.ifnull(popWrongType); codeStream.areturn(); popWrongType.place(); codeStream.pop(); wrongType.place(); codeStream.new_(world.makeTypeBinding(AjcMemberMaker.NO_ASPECT_BOUND_EXCEPTION)); codeStream.dup(); codeStream.invokespecial(world.makeMethodBindingForCall( AjcMemberMaker.noAspectBoundExceptionInit() )); codeStream.athrow(); // body ends here }}); } private void generatePerObjectHasAspectMethod(ClassFile classFile, final TypeBinding interfaceType) { final EclipseFactory world = EclipseFactory.fromScopeLookupEnvironment(this.scope); generateMethod(classFile, hasAspectMethod, new BodyGenerator() { public void generate(CodeStream codeStream) { // body starts here Label wrongType = new Label(codeStream); codeStream.aload_0(); codeStream.instance_of(interfaceType); codeStream.ifeq(wrongType); codeStream.aload_0(); codeStream.checkcast(interfaceType); codeStream.invokeinterface(world.makeMethodBindingForCall( AjcMemberMaker.perObjectInterfaceGet(typeX))); codeStream.ifnull(wrongType); codeStream.iconst_1(); codeStream.ireturn(); wrongType.place(); codeStream.iconst_0(); codeStream.ireturn(); // body ends here }}); } private void generatePerObjectBindMethod( ClassFile classFile, final TypeBinding interfaceType) { final EclipseFactory world = EclipseFactory.fromScopeLookupEnvironment(this.scope); generateMethod(classFile, AjcMemberMaker.perObjectBind(EclipseFactory.fromBinding(binding)), new BodyGenerator() { public void generate(CodeStream codeStream) { // body starts here Label wrongType = new Label(codeStream); codeStream.aload_0(); codeStream.instance_of(interfaceType); codeStream.ifeq(wrongType); //XXX this case might call for screaming codeStream.aload_0(); codeStream.checkcast(interfaceType); codeStream.invokeinterface(world.makeMethodBindingForCall( AjcMemberMaker.perObjectInterfaceGet(typeX))); //XXX should do a check for null here and throw a NoAspectBound codeStream.ifnonnull(wrongType); codeStream.aload_0(); codeStream.checkcast(interfaceType); codeStream.new_(binding); codeStream.dup(); codeStream.invokespecial( new MethodBinding(0, "<init>".toCharArray(), BaseTypes.VoidBinding, new TypeBinding[0], new ReferenceBinding[0], binding)); codeStream.invokeinterface(world.makeMethodBindingForCall( AjcMemberMaker.perObjectInterfaceSet(typeX))); wrongType.place(); codeStream.return_(); // body ends here }}); } private void generatePerSingletonAspectOfMethod(ClassFile classFile) { final EclipseFactory world = EclipseFactory.fromScopeLookupEnvironment(this.scope); generateMethod(classFile, aspectOfMethod, new BodyGenerator() { public void generate(CodeStream codeStream) { // body starts here codeStream.getstatic(world.makeFieldBinding(AjcMemberMaker.perSingletonField( typeX))); Label isNull = new Label(codeStream); codeStream.dup(); codeStream.ifnull(isNull); codeStream.areturn(); isNull.place(); codeStream.incrStackSize(+1); // the dup trick above confuses the stack counter codeStream.new_(world.makeTypeBinding(AjcMemberMaker.NO_ASPECT_BOUND_EXCEPTION)); codeStream.dup(); codeStream.ldc(typeX.getNameAsIdentifier()); codeStream.getstatic(initFailureField); codeStream.invokespecial(world.makeMethodBindingForCall( AjcMemberMaker.noAspectBoundExceptionInitWithCause() )); codeStream.athrow(); // body ends here }}); } private void generatePerSingletonHasAspectMethod(ClassFile classFile) { final EclipseFactory world = EclipseFactory.fromScopeLookupEnvironment(this.scope); generateMethod(classFile, hasAspectMethod, new BodyGenerator() { public void generate(CodeStream codeStream) { // body starts here codeStream.getstatic(world.makeFieldBinding(AjcMemberMaker.perSingletonField( typeX))); Label isNull = new Label(codeStream); codeStream.ifnull(isNull); codeStream.iconst_1(); codeStream.ireturn(); isNull.place(); codeStream.iconst_0(); codeStream.ireturn(); // body ends here }}); } private void generatePerSingletonAjcClinitMethod( ClassFile classFile) { final EclipseFactory world = EclipseFactory.fromScopeLookupEnvironment(this.scope); generateMethod(classFile, world.makeMethodBinding(AjcMemberMaker.ajcPostClinitMethod( EclipseFactory.fromBinding(binding))), new BodyGenerator() { public void generate(CodeStream codeStream) { // body starts here codeStream.new_(binding); codeStream.dup(); codeStream.invokespecial( new MethodBinding(0, "<init>".toCharArray(), BaseTypes.VoidBinding, new TypeBinding[0], new ReferenceBinding[0], binding)); codeStream.putstatic( world.makeFieldBinding( AjcMemberMaker.perSingletonField( typeX))); codeStream.return_(); // body ends here }}); } private void generateSuperAccessMethod(ClassFile classFile, final MethodBinding accessMethod, final ResolvedMember method) { generateMethod(classFile, accessMethod, new BodyGenerator() { public void generate(CodeStream codeStream) { // body starts here codeStream.aload_0(); AstUtil.generateParameterLoads(accessMethod.parameters, codeStream); codeStream.invokespecial( factory.makeMethodBinding(method)); AstUtil.generateReturn(accessMethod.returnType, codeStream); // body ends here }}); } private void generateInlineAccessMethod(ClassFile classFile, final Binding binding, final ResolvedMember member) { if (binding instanceof InlineAccessFieldBinding) { generateInlineAccessors(classFile, (InlineAccessFieldBinding)binding, member); } else { generateInlineAccessMethod(classFile, (MethodBinding)binding, member); } } private void generateInlineAccessors(ClassFile classFile, final InlineAccessFieldBinding accessField, final ResolvedMember field) { final FieldBinding fieldBinding = factory.makeFieldBinding(field); generateMethod(classFile, accessField.reader, new BodyGenerator() { public void generate(CodeStream codeStream) { // body starts here if (field.isStatic()) { codeStream.getstatic(fieldBinding); } else { codeStream.aload_0(); codeStream.getfield(fieldBinding); } AstUtil.generateReturn(accessField.reader.returnType, codeStream); // body ends here }}); generateMethod(classFile, accessField.writer, new BodyGenerator() { public void generate(CodeStream codeStream) { // body starts here if (field.isStatic()) { codeStream.load(fieldBinding.type, 0); codeStream.putstatic(fieldBinding); } else { codeStream.aload_0(); codeStream.load(fieldBinding.type, 1); codeStream.putfield(fieldBinding); } codeStream.return_(); // body ends here }}); } private void generateInlineAccessMethod(ClassFile classFile, final MethodBinding accessMethod, final ResolvedMember method) { generateMethod(classFile, accessMethod, new BodyGenerator() { public void generate(CodeStream codeStream) { // body starts here AstUtil.generateParameterLoads(accessMethod.parameters, codeStream); if (method.isStatic()) { codeStream.invokestatic(factory.makeMethodBinding(method)); } else { codeStream.invokevirtual(factory.makeMethodBinding(method)); } AstUtil.generateReturn(accessMethod.returnType, codeStream); // body ends here }}); } private PerClause.Kind lookupPerClauseKind(ReferenceBinding binding) { PerClause perClause; if (binding instanceof BinaryTypeBinding) { ResolvedTypeX superTypeX = factory.fromEclipse(binding); perClause = superTypeX.getPerClause(); } else if (binding instanceof SourceTypeBinding ) { SourceTypeBinding sourceSc = (SourceTypeBinding)binding; if (sourceSc.scope.referenceContext instanceof AspectDeclaration) { perClause = ((AspectDeclaration)sourceSc.scope.referenceContext).perClause; } else { return null; } } else { //XXX need to handle this too return null; } if (perClause == null) { return lookupPerClauseKind(binding.superclass()); } else { return perClause.getKind(); } } private void buildPerClause(ClassScope scope) { EclipseFactory world = EclipseFactory.fromScopeLookupEnvironment(scope); if (perClause == null) { PerClause.Kind kind = lookupPerClauseKind(binding.superclass); if (kind == null) { perClause = new PerSingleton(); } else { perClause = new PerFromSuper(kind); } } aspectAttribute = new AjAttribute.Aspect(perClause); if (ignoreFurtherInvestigation) return; //??? if (!isAbstract()) { if (perClause.getKind() == PerClause.SINGLETON) { aspectOfMethod = AjcMemberMaker.perSingletonAspectOfMethod(typeX); hasAspectMethod = AjcMemberMaker.perSingletonHasAspectMethod(typeX); } else if (perClause.getKind() == PerClause.PERCFLOW) { aspectOfMethod = AjcMemberMaker.perCflowAspectOfMethod(typeX); hasAspectMethod = AjcMemberMaker.perCflowHasAspectMethod(typeX); } else if (perClause.getKind() == PerClause.PEROBJECT) { aspectOfMethod = AjcMemberMaker.perObjectAspectOfMethod(typeX); hasAspectMethod = AjcMemberMaker.perObjectHasAspectMethod(typeX); } else { throw new RuntimeException("bad per clause: " + perClause); } binding.addMethod(world.makeMethodBinding(aspectOfMethod)); binding.addMethod(world.makeMethodBinding(hasAspectMethod)); } resolvePerClause(); //XXX might be too soon for some error checking } private PerClause resolvePerClause() { EclipseScope iscope = new EclipseScope(new FormalBinding[0], scope); perClause.resolve(iscope); return perClause; } public void buildInterTypeAndPerClause(ClassScope classScope) { factory = EclipseFactory.fromScopeLookupEnvironment(scope); if (isPrivileged) { binding.privilegedHandler = new PrivilegedHandler(this); } checkSpec(classScope); if (ignoreFurtherInvestigation) return; buildPerClause(scope); if (methods != null) { for (int i = 0; i < methods.length; i++) { if (methods[i] instanceof InterTypeDeclaration) { EclipseTypeMunger m = ((InterTypeDeclaration)methods[i]).build(classScope); if (m != null) concreteName.typeMungers.add(m); } else if (methods[i] instanceof DeclareDeclaration) { Declare d = ((DeclareDeclaration)methods[i]).build(classScope); if (d != null) concreteName.declares.add(d); } } } concreteName.getDeclaredPointcuts(); } // public String toString(int tab) { // return tabString(tab) + toStringHeader() + toStringBody(tab); // } // // public String toStringBody(int tab) { // // String s = " {"; //$NON-NLS-1$ // // // if (memberTypes != null) { // for (int i = 0; i < memberTypes.length; i++) { // if (memberTypes[i] != null) { // s += "\n" + memberTypes[i].toString(tab + 1); //$NON-NLS-1$ // } // } // } // if (fields != null) { // for (int fieldI = 0; fieldI < fields.length; fieldI++) { // if (fields[fieldI] != null) { // s += "\n" + fields[fieldI].toString(tab + 1); //$NON-NLS-1$ // if (fields[fieldI].isField()) // s += ";"; //$NON-NLS-1$ // } // } // } // if (methods != null) { // for (int i = 0; i < methods.length; i++) { // if (methods[i] != null) { // s += "\n" + methods[i].toString(tab + 1); //$NON-NLS-1$ // } // } // } // s += "\n" + tabString(tab) + "}"; //$NON-NLS-2$ //$NON-NLS-1$ // return s; // } public StringBuffer printHeader(int indent, StringBuffer output) { printModifiers(this.modifiers, output); output.append("aspect " ); output.append(name); if (superclass != null) { output.append(" extends "); //$NON-NLS-1$ superclass.print(0, output); } if (superInterfaces != null && superInterfaces.length > 0) { output.append(isInterface() ? " extends " : " implements ");//$NON-NLS-2$ //$NON-NLS-1$ for (int i = 0; i < superInterfaces.length; i++) { if (i > 0) output.append( ", "); //$NON-NLS-1$ superInterfaces[i].print(0, output); } } return output; //XXX we should append the per-clause } }
59,596
Bug 59596 Null pointer exception while weaving java.awt.Label
I tried to add an Aspect to java.awt.Label. I compile the aspect via: ajc -inpath /usr/local/j2sdk_nb/j2sdk1.4.2/jre/lib/rt.jar Timestamp.java Here is the aspect Timestamp.java: aspect Timestamp { private int java.awt.Label._ts_read = 0; private int java.awt.Label._ts_write = 0; pointcut writeOp(): call (void java.awt.Label.setText (String)); pointcut readOp(): call (String java.awt.Label.getText()); after (java.awt.Label b) returning: readOp() && target (b) { b._ts_read++; } after (java.awt.Label b) returning: writeOp() && target (b) { b._ts_write++; System.out.println (b._ts_write); } public static void main (String[] args) { java.awt.Label b1 = new java.awt.Label(); b1.setText ("abc"); } } Here is the error message I get from ajc: null java.lang.NullPointerException at org.aspectj.ajdt.internal.core.builder.EclipseAdapterUtils.makeLocationContext(EclipseAdapterUtils.java:50) at org.aspectj.ajdt.internal.core.builder.EclipseAdapterUtils.makeSourceLocation(EclipseAdapterUtils.java:120) at org.aspectj.ajdt.internal.core.builder.EclipseAdapterUtils.makeMessage(EclipseAdapterUtils.java:129) at org.aspectj.ajdt.internal.core.builder.AjBuildManager$4.acceptResult(AjBuildManager.java:663) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.acceptResult(AjCompilerAdapter.java:178) at org.aspectj.ajdt.internal.compiler.WeaverAdapter.finishedWith(WeaverAdapter.java:203) at org.aspectj.ajdt.internal.compiler.WeaverAdapter.weaveCompleted(WeaverAdapter.java:167) at org.aspectj.weaver.bcel.BcelWeaver.weave(BcelWeaver.java:570) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.weave(AjCompilerAdapter.java:239) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.afterCompiling(AjCompilerAdapter.java:114) at org.eclipse.jdt.internal.compiler.Compiler.compile(Compiler.java:376) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.performCompilation(AjBuildManager.java:600) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.doBuild(AjBuildManager.java:160) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.batchBuild(AjBuildManager.java:94) at org.aspectj.ajdt.ajc.AjdtCommand.doCommand(AjdtCommand.java:102) at org.aspectj.ajdt.ajc.AjdtCommand.runCommand(AjdtCommand.java:53) at org.aspectj.tools.ajc.Main.run(Main.java:280) at org.aspectj.tools.ajc.Main.runMain(Main.java:217) at org.aspectj.tools.ajc.Main.main(Main.java:79) 1 fail|abort
resolved fixed
a97f3b6
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2004-04-23T16:24:27Z
2004-04-22T10:33: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 Common Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * PARC initial implementation * ******************************************************************/ package org.aspectj.ajdt.internal.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.eclipse.jdt.core.compiler.IProblem; import 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))) //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)) { }; 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()); } IMessage msg = new Message(problem.getMessage(), problem.getSupplementaryMessageInfo(), problem.isError() ? IMessage.ERROR : IMessage.WARNING, sourceLocation, null, seeAlsoLocations); 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() { } }
54,238
Bug 54238 Restore build cancelling to Swing-based IDEs
Core compiler implementation changes have resulted in an incompatability with AJDE's build cancelling mechanism. Once the core canceling behavior stabilizes this needs to be restored.
resolved fixed
a17b51b
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2004-04-27T18:55:41Z
2004-03-10T03:40:00Z
ajbrowser/src/org/aspectj/tools/ajbrowser/BasicEditor.java
/* ******************************************************************* * Copyright (c) 1999-2001 Xerox Corporation, * 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Common Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * Xerox/PARC initial implementation * ******************************************************************/ package org.aspectj.tools.ajbrowser; import java.awt.BorderLayout; import java.awt.Font; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; //import java.net.URL; import javax.swing.JEditorPane; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.text.BadLocationException; import javax.swing.text.DefaultHighlighter; import org.aspectj.ajde.Ajde; import org.aspectj.ajde.EditorAdapter; import org.aspectj.bridge.ISourceLocation; /** * Bare-bones editor implementation used when the framework is being used * standalone. * * @author Mik Kersten */ public class BasicEditor implements EditorAdapter { private String NO_FILE = "<no file selected>"; private String filePath = NO_FILE; private JPanel editor_panel = new JPanel(); // @todo get rid of these private int currHighlightStart = 0; private int currHighlightEnd = 0; private BorderLayout borderLayout1 = new BorderLayout(); private JScrollPane jScrollPane1 = new JScrollPane(); private JEditorPane editorPane = new JEditorPane(); public BasicEditor() { try { editorPane.setEditable(true); editorPane.setContentType("text/plain"); editorPane.setFont(new Font("Monospaced", 0, 11)); editor_panel.add(editorPane); jbInit(); } catch(Exception e) { Ajde.getDefault().getErrorHandler().handleError("Could not initialize GUI.", e); } } public String getCurrFile() { return filePath; } public void showSourceLine(ISourceLocation sourceLocation, boolean highlight) { showSourceLine(sourceLocation.getSourceFile().getAbsolutePath(), sourceLocation.getLine(), highlight); } public void showSourceLine(int lineNumber, boolean highlight) { showSourceLine(filePath, lineNumber, highlight); } public void pasteToCaretPos(String text) { if (currHighlightEnd < 1) return; String contents = editorPane.getText(); String pasted = contents.substring(0, currHighlightEnd) + text + contents.substring(currHighlightEnd, contents.length()); editorPane.setText(pasted); } public void showSourceLine(String filePath, int lineNumber, boolean highlight) { //AjdeUIManager.getDefault().getIdeUIAdapter().resetEditor(); this.filePath = filePath; // if (oldPath != filePath && !Ajde.INSTANCE.BROWSER_MANAGER.isGlobalMode()) { // Ajde.INSTANCE.BROWSER_MANAGER.updateView(); // } // Ajde.IDE_MANAGER.setEditorStatusText(filePath); currHighlightStart = 0; currHighlightEnd = 0; editorPane.setText(readFile(filePath, lineNumber)); try { editorPane.getHighlighter().addHighlight(currHighlightStart, currHighlightEnd, DefaultHighlighter.DefaultPainter); editorPane.setCaretPosition(currHighlightStart); } catch (BadLocationException ble) { Ajde.getDefault().getErrorHandler().handleError("Could not highlight location.", ble); } BrowserManager.getDefault().getEditorManager().notifyCurrentFileChanged(filePath); } /** * Not implemented. */ public void showSourcelineAnnotation(String filePath, int lineNumber, java.util.List items) { } public void addEditorViewForSourceLine(String filePath, int lineNumber) { } public void saveContents() throws IOException { if (filePath != NO_FILE && filePath != "" && editorPane.getText() != "") { BufferedWriter writer = new BufferedWriter(new FileWriter(filePath)); writer.write(editorPane.getText()); writer.flush(); } } public JPanel getPanel() { return editor_panel; } public void showSourceForFile(String filePath) { } public void showSourceForLine(int lineNumber, boolean highlight) { } public void showSourceForSourceLine(String filePath, int lineNumber, boolean highlight) { } public String getCurrSourceFilePath() { return null; } public void setBreakpointRequest(String filePath, int lineNumber, boolean isDeferred) { } public void clearBreakpointRequest(String filePath, int lineNumber) { } private String readFile(String filePath, int lineNumber) { try { // URL url = ClassLoader.getSystemResource(filePath); File file = new File(filePath); if (!file.exists()) { return "ERROR: file \"" + filePath + "\" does not exist."; } BufferedReader reader = new BufferedReader(new FileReader(file)); StringBuffer contents = new StringBuffer(); String line = reader.readLine(); int numLines = 0; while (line != null) { numLines++; if (numLines < lineNumber) { currHighlightStart += line.length()+1; } if (numLines == lineNumber) { currHighlightEnd = currHighlightStart + line.length(); } contents.append(line); contents.append('\n'); line = reader.readLine(); } return contents.toString(); } catch (IOException ioe) { return "ERROR: could not read file \"" + filePath + "\", make sure that you have mounted /project/aop on X:\\"; } } private void jbInit() throws Exception { editor_panel.setFont(new java.awt.Font("DialogInput", 1, 12)); editor_panel.setLayout(borderLayout1); editor_panel.add(jScrollPane1, BorderLayout.CENTER); jScrollPane1.getViewport().add(editorPane, null); } }
59,909
Bug 59909 CFlowStack removesThreads to late
Problem: The current implementation of CFlowStack (Version 1.1-till 1.2 rc1) stores all threads in a hashtable. These Threads are removes after several calls to the methods getThreadStack(). (In our cases >70 calls.) In our project, this cycle is much to long. We have soveral long running threads, which grap quite a lot of lot of memory. This memory can only be freed after the threads have been removed from the CFlowStack. In our production code we sum up to more than 300 Threads stored in different CFlowStack Varaibles. Often this results in out of memory Errors. Added patch provides an improved freeing scheme. It checks if the size of the table has grown, if it has, it checks if it can remove some threads.
resolved fixed
5f6b18b
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2004-05-05T10:18:01Z
2004-04-26T09:00:00Z
runtime/src/org/aspectj/runtime/internal/CFlowStack.java
/* ******************************************************************* * Copyright (c) 1999-2001 Xerox Corporation, * 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Common Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * Xerox/PARC initial implementation * ******************************************************************/ package org.aspectj.runtime.internal; import org.aspectj.lang.NoAspectBoundException; import org.aspectj.runtime.CFlow; import java.util.Stack; import java.util.Hashtable; import java.util.Enumeration; public class CFlowStack { private Hashtable stacks = new Hashtable(); private Thread cached_thread; private Stack cached_stack; private int change_count = 0; private static final int COLLECT_AT = 20000; private static final int MIN_COLLECT_AT = 100; private synchronized Stack getThreadStack() { if (Thread.currentThread() != cached_thread) { cached_thread = Thread.currentThread(); cached_stack = (Stack)stacks.get(cached_thread); if (cached_stack == null) { cached_stack = new Stack(); stacks.put(cached_thread, cached_stack); } change_count++; // Collect more often if there are many threads, but not *too* often int size = Math.max(1, stacks.size()); // should be >1 b/c always live threads, but... if (change_count > Math.max(MIN_COLLECT_AT, COLLECT_AT/size)) { Stack dead_stacks = new Stack(); for (Enumeration e = stacks.keys(); e.hasMoreElements(); ) { Thread t = (Thread)e.nextElement(); if (!t.isAlive()) dead_stacks.push(t); } for (Enumeration e = dead_stacks.elements(); e.hasMoreElements(); ) { Thread t = (Thread)e.nextElement(); stacks.remove(t); } change_count = 0; } } return cached_stack; } //XXX dangerous, try to remove public void push(Object obj) { getThreadStack().push(obj); } public void pushInstance(Object obj) { getThreadStack().push(new CFlow(obj)); } public void push(Object[] obj) { getThreadStack().push(new CFlowPlusState(obj)); } public void pop() { getThreadStack().pop(); } public Object peek() { Stack stack = getThreadStack(); if (stack.isEmpty()) throw new org.aspectj.lang.NoAspectBoundException(); return (Object)stack.peek(); } public Object get(int index) { CFlow cf = peekCFlow(); return (null == cf ? null : cf.get(index)); } public Object peekInstance() { CFlow cf = peekCFlow(); if (cf != null ) return cf.getAspect(); else throw new NoAspectBoundException(); } public CFlow peekCFlow() { Stack stack = getThreadStack(); if (stack.isEmpty()) return null; return (CFlow)stack.peek(); } public CFlow peekTopCFlow() { Stack stack = getThreadStack(); if (stack.isEmpty()) return null; return (CFlow)stack.elementAt(0); } public boolean isValid() { return !getThreadStack().isEmpty(); } }
59,909
Bug 59909 CFlowStack removesThreads to late
Problem: The current implementation of CFlowStack (Version 1.1-till 1.2 rc1) stores all threads in a hashtable. These Threads are removes after several calls to the methods getThreadStack(). (In our cases >70 calls.) In our project, this cycle is much to long. We have soveral long running threads, which grap quite a lot of lot of memory. This memory can only be freed after the threads have been removed from the CFlowStack. In our production code we sum up to more than 300 Threads stored in different CFlowStack Varaibles. Often this results in out of memory Errors. Added patch provides an improved freeing scheme. It checks if the size of the table has grown, if it has, it checks if it can remove some threads.
resolved fixed
5f6b18b
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2004-05-05T10:18:01Z
2004-04-26T09:00:00Z
runtime/src/org/aspectj/runtime/internal/cflowstack/ThreadStack.java
59,909
Bug 59909 CFlowStack removesThreads to late
Problem: The current implementation of CFlowStack (Version 1.1-till 1.2 rc1) stores all threads in a hashtable. These Threads are removes after several calls to the methods getThreadStack(). (In our cases >70 calls.) In our project, this cycle is much to long. We have soveral long running threads, which grap quite a lot of lot of memory. This memory can only be freed after the threads have been removed from the CFlowStack. In our production code we sum up to more than 300 Threads stored in different CFlowStack Varaibles. Often this results in out of memory Errors. Added patch provides an improved freeing scheme. It checks if the size of the table has grown, if it has, it checks if it can remove some threads.
resolved fixed
5f6b18b
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2004-05-05T10:18:01Z
2004-04-26T09:00:00Z
runtime/src/org/aspectj/runtime/internal/cflowstack/ThreadStackFactory.java
59,909
Bug 59909 CFlowStack removesThreads to late
Problem: The current implementation of CFlowStack (Version 1.1-till 1.2 rc1) stores all threads in a hashtable. These Threads are removes after several calls to the methods getThreadStack(). (In our cases >70 calls.) In our project, this cycle is much to long. We have soveral long running threads, which grap quite a lot of lot of memory. This memory can only be freed after the threads have been removed from the CFlowStack. In our production code we sum up to more than 300 Threads stored in different CFlowStack Varaibles. Often this results in out of memory Errors. Added patch provides an improved freeing scheme. It checks if the size of the table has grown, if it has, it checks if it can remove some threads.
resolved fixed
5f6b18b
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2004-05-05T10:18:01Z
2004-04-26T09:00:00Z
runtime/src/org/aspectj/runtime/internal/cflowstack/ThreadStackFactoryImpl.java
59,909
Bug 59909 CFlowStack removesThreads to late
Problem: The current implementation of CFlowStack (Version 1.1-till 1.2 rc1) stores all threads in a hashtable. These Threads are removes after several calls to the methods getThreadStack(). (In our cases >70 calls.) In our project, this cycle is much to long. We have soveral long running threads, which grap quite a lot of lot of memory. This memory can only be freed after the threads have been removed from the CFlowStack. In our production code we sum up to more than 300 Threads stored in different CFlowStack Varaibles. Often this results in out of memory Errors. Added patch provides an improved freeing scheme. It checks if the size of the table has grown, if it has, it checks if it can remove some threads.
resolved fixed
5f6b18b
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2004-05-05T10:18:01Z
2004-04-26T09:00:00Z
runtime/src/org/aspectj/runtime/internal/cflowstack/ThreadStackFactoryImpl11.java
59,909
Bug 59909 CFlowStack removesThreads to late
Problem: The current implementation of CFlowStack (Version 1.1-till 1.2 rc1) stores all threads in a hashtable. These Threads are removes after several calls to the methods getThreadStack(). (In our cases >70 calls.) In our project, this cycle is much to long. We have soveral long running threads, which grap quite a lot of lot of memory. This memory can only be freed after the threads have been removed from the CFlowStack. In our production code we sum up to more than 300 Threads stored in different CFlowStack Varaibles. Often this results in out of memory Errors. Added patch provides an improved freeing scheme. It checks if the size of the table has grown, if it has, it checks if it can remove some threads.
resolved fixed
5f6b18b
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2004-05-05T10:18:01Z
2004-04-26T09:00:00Z
runtime/src/org/aspectj/runtime/internal/cflowstack/ThreadStackImpl11.java
59,599
Bug 59599 Race condition in test suite for incremental
On faster machines (my linux desktop, andy's home pc) several of the tests in ajcTests.xml are failing (suite attached). This appears to be due to a race condition between checking directory contents and waiting for the compilation to complete. I have an environment in which I can test candidate fixes if you can give me a pointer for what to tweak...
resolved fixed
bd16033
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2004-05-05T10:18:34Z
2004-04-22T10:33:20Z
testing/src/org/aspectj/testing/harness/bridge/DirChanges.java
/* ******************************************************************* * Copyright (c) 1999-2001 Xerox Corporation, * 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Common Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * Xerox/PARC initial implementation * ******************************************************************/ package org.aspectj.testing.harness.bridge; import java.io.File; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.aspectj.bridge.IMessageHandler; import org.aspectj.bridge.MessageUtil; import org.aspectj.testing.util.TestUtil; import org.aspectj.testing.xml.IXmlWritable; import org.aspectj.testing.xml.XMLWriter; import org.aspectj.util.FileUtil; import org.aspectj.util.LangUtil; /** * Calculate changes in a directory tree. * This implements two different specification styles: * <ul> * <li>Specify files added, removed, updated, and/or a component * to check any existing files</li> * <li>Specify expected directory. When complete this checks that * any files in expected directory are matched in the actual. * (.class files are dissassembled before comparison.) * </li> * </ul> * Usage: * <ul> * <li>Set up with any expected changes and/or an expected directory</li> * <li>Set up with any file checker</li> * <li>start(..) before changes. * This issues messages for any removed files not found, * which represent an error in the expected changes.</li> * <li>Do whatever operations will change the directory</li> * <li>end(..). * This issues messages for any files not removed, added, or updated, * and, if any checker was set, any checker messages for matching * added or updated files</li> * </ul> * When comparing directories, this ignores any paths containing "CVS". */ public class DirChanges { private static final boolean EXISTS = true; final Spec spec; /** start time, in milliseconds - valid only from start(..)..end(..) */ long startTime; /** base directory of actual files - valid only from start(..)..end(..) */ File baseDir; /** if set, this is run against any resulting existing files * specified in added/updated lists. * This does not affect expected-directory comparison. */ IFileChecker fileChecker; /** handler valid from start..end of start(..) and end(..) methods */ IMessageHandler handler; /** * Constructor for DirChanges. */ public DirChanges(Spec spec) { LangUtil.throwIaxIfNull(spec, "spec"); this.spec = spec; } /** * Inspect the base dir, and issue any messages for * removed files not present. * @param baseDir File for a readable directory * @return true if this started without sending messages * for removed files not present. */ public boolean start(IMessageHandler handler, File baseDir) { FileUtil.throwIaxUnlessCanReadDir(baseDir, "baseDir"); final IMessageHandler oldHandler = this.handler; this.handler = handler; this.baseDir = baseDir; startTime = 0l; final boolean doCompare = false; boolean result = exists("at start, did not expect added file to exist", !EXISTS, spec.added, doCompare); result &= exists("at start, expected unchanged file to exist", EXISTS, spec.unchanged, doCompare); result &= exists("at start, expected updated file to exist", EXISTS, spec.updated, doCompare); result &= exists("at start, expected removed file to exist", EXISTS, spec.removed, doCompare); startTime = System.currentTimeMillis(); this.handler = oldHandler; return result; } /** * Inspect the base dir, issue any messages for * files not added, files not updated, and files not removed, * and compare expected/actual files added or updated. * @throws IllegalStateException if called before start(..) */ public boolean end(IMessageHandler handler, File srcBaseDir) { FileUtil.throwIaxUnlessCanReadDir(baseDir, "baseDir"); if (0l == startTime) { throw new IllegalStateException("called before start"); } final IMessageHandler oldHandler = this.handler; this.handler = handler; try { // variant 1: check specified files // deferring comparison to end... final boolean doCompare = (null != fileChecker); final boolean fastFail = spec.fastFail; boolean result = exists("at end, expected file was not added", EXISTS, spec.added, doCompare); if (result || !fastFail) { result &= exists("at end, expected file was not unchanged", EXISTS, spec.unchanged, doCompare, false); } if (result || !fastFail) { result &= exists("at end, expected file was not updated", EXISTS, spec.updated, doCompare); } if (result || !fastFail) { result &= exists("at end, file exists, was not removed", !EXISTS, spec.removed, doCompare); } // if (result || !fastFail) { // // XXX validate that unchanged mod-time did not change // } // variant 1: compare expected directory if (result || !fastFail) { result &= compareDir(srcBaseDir); } return result; } finally { this.handler = oldHandler; baseDir = null; startTime = 0l; } } /** * Verify that all files in any specified expected directory * have matching files in the base directory, putting any messages * in the handler (only one if the spec indicates fast-fail). * @param srcBaseDir the File for the base directory of the test sources * (any expected dir is specified relative to this directory) * @return true if the same, false otherwise */ private boolean compareDir(File srcBaseDir) { if (null == spec.expDir) { return true; } File expDir = new File(srcBaseDir, spec.expDir); File actDir = baseDir; //System.err.println("XXX comparing actDir=" + actDir + " expDir=" + expDir); return TestUtil.sameDirectoryContents(handler, expDir, actDir, spec.fastFail); } /** @param comp FileMessageComparer (if any) given matching messages to compare */ protected void setFileComparer(IFileChecker comp) { this.fileChecker = comp; } /** * Signal fail if any files do {not} exist or do {not} have last-mod-time after startTime * @param handler the IMessageHandler sink for messages * @param label the String infix for the fail message * @param exists if true, then file must exist and be modified after start time; * if false, then the file must not exist or must be modified before start time. * @param pathList the List of path (without any Spec.defaultSuffix) of File * in Spec.baseDir to find (or not, if !exists) */ protected boolean exists( String label, boolean exists, List pathList, boolean doCompare) { // boolean expectStartEarlier = true; return exists(label, exists, pathList,doCompare, true); } protected boolean exists( String label, boolean exists, List pathList, boolean doCompare, boolean expectStartEarlier) { boolean result = true; if (!LangUtil.isEmpty(pathList)) { // final File expDir = ((!doCompare || (null == spec.expDir)) // ? null // : new File(baseDir, spec.expDir)); for (Iterator iter = pathList.iterator(); iter.hasNext();) { final String entry = (String) iter.next() ; String path = entry ; if (null != spec.defaultSuffix) { if (".class".equals(spec.defaultSuffix)) { path = path.replace('.', '/'); } path = path + spec.defaultSuffix; } File actualFile = new File(baseDir, path); if (exists != (actualFile.canRead() && actualFile.isFile() && (expectStartEarlier ? startTime <= actualFile.lastModified() : startTime > actualFile.lastModified() ))) { failMessage(handler, exists, label, path, actualFile); if (result) { result = false; } } else if (exists && doCompare && (null != fileChecker)) { if (!fileChecker.checkFile(handler, path, actualFile) && result) { result = false; } } } } return result; } /** * Generate fail message "{un}expected {label} file {path} in {baseDir}". * @param handler the IMessageHandler sink * @param label String message infix * @param path the path to the file */ protected void failMessage( IMessageHandler handler, boolean exists, String label, String path, File file) { MessageUtil.fail(handler, label + " \"" + path + "\" in " + baseDir); } /** Check actual File found at a path, usually to diff expected/actual contents */ public static interface IFileChecker { /** * Check file found at path. * Implementations should return false when adding fail (or worse) * message to the handler, and true otherwise. * @param handler IMessageHandler sink for messages, esp. fail. * @param path String for normalized path portion of actualFile.getPath() * @param actualFile File to file found * @return false if check failed and messages added to handler */ boolean checkFile(IMessageHandler handler, String path, File actualFile); } // File-comparison code with a bit more generality -- too unweildy // /** // * Default FileChecker compares files literally, transforming any // * with registered normalizers. // */ // public static class FileChecker implements IFileChecker { // final File baseExpectedDir; // NormalizedCompareFiles fileComparer; // // public FileChecker(File baseExpectedDir) { // this.baseExpectedDir = baseExpectedDir; // fileComparer = new NormalizedCompareFiles(); // } // public boolean checkFile(IMessageHandler handler, String path, File actualFile) { // if (null == baseExpectedDir) { // MessageUtil.error(handler, "null baseExpectedDir set on construction"); // } else if (!baseExpectedDir.canRead() || !baseExpectedDir.isDirectory()) { // MessageUtil.error(handler, "bad baseExpectedDir: " + baseExpectedDir); // } else { // File expectedFile = new File(baseExpectedDir, path); // if (!expectedFile.canRead()) { // MessageUtil.fail(handler, "cannot read expected file: " + expectedFile); // } else { // return doCheckFile(handler, expectedFile, actualFile, path); // } // } // return false; // } // // protected boolean doCheckFile( // IMessageHandler handler, // File expectedFile, // File actualFile, // String path) { // fileComparer.setHandler(handler); // FileLine[] expected = fileComparer.diff(); // return false; // } // } // /** // * CompareFiles implementation that pre-processes input // * to normalize it. Currently it reads all files except // * .class files, which it disassembles first. // */ // public static class NormalizedCompareFiles extends CompareFiles { // private final static String[] NO_PATHS = new String[0]; // private static String normalPath(File file) { // XXX util // if (null == file) { // return ""; // } // return file.getAbsolutePath().replace('\\', '/'); // } // // private String[] baseDirs; // private IMessageHandler handler; // // public NormalizedCompareFiles() { // } // // void init(IMessageHandler handler, File[] baseDirs) { // this.handler = handler; // if (null == baseDirs) { // this.baseDirs = NO_PATHS; // } else { // this.baseDirs = new String[baseDirs.length]; // for (int i = 0; i < baseDirs.length; i++) { // this.baseDirs[i] = normalPath(baseDirs[i]) + "/"; // } // } // } // // private String getClassName(File file) { // String result = null; // String path = normalPath(file); // if (!path.endsWith(".class")) { // MessageUtil.error(handler, // "NormalizedCompareFiles expected " // + file // + " to end with .class"); // } else { // path = path.substring(0, path.length()-6); // for (int i = 0; i < baseDirs.length; i++) { // if (path.startsWith(baseDirs[i])) { // return path.substring(baseDirs[i].length()).replace('/', '.'); // } // } // MessageUtil.error(handler, // "NormalizedCompareFiles expected " // + file // + " to start with one of " // + LangUtil.arrayAsList(baseDirs)); // } // // return result; // } // // /** // * Read file as normalized lines, sending handler any messages // * ERROR for input failures and FAIL for processing failures. // * @return NOLINES on error or normalized lines from file otherwise // */ // public FileLine[] getFileLines(File file) { // FileLineator capture = new FileLineator(); // InputStream in = null; // try { // if (!file.getPath().endsWith(".class")) { // in = new FileInputStream(file); // FileUtil.copyStream( // new BufferedReader(new InputStreamReader(in)), // new PrintWriter(capture)); // } else { // String name = getClassName(file); // if (null == name) { // return new FileLine[0]; // } // String path = normalPath(file); // path = path.substring(0, path.length()-name.length()); // // XXX sole dependency on bcweaver/bcel // LazyClassGen.disassemble(path, name, capture); // } // } catch (IOException e) { // MessageUtil.fail(handler, // "NormalizedCompareFiles IOException reading " + file, e); // return null; // } finally { // if (null != in) { // try { in.close(); } // catch (IOException e) {} // ignore // } // capture.flush(); // capture.close(); // } // String missed = capture.getMissed(); // if (!LangUtil.isEmpty(missed)) { // MessageUtil.fail(handler, // "NormalizedCompareFiles missed input: " // + missed); // return null; // } else { // return capture.getFileLines(); // } // } // // // } /** * Specification for a set of File added, removed, or updated * in a given directory, or for a directory base for a tree of expected files. * If defaultSuffix is specified, entries may be added without it. * Currently the directory tree * only is used to verify files that are expected * and found after the process completes. */ public static class Spec implements IXmlWritable { /** XML element name */ public static final String XMLNAME = "dir-changes"; /** a symbolic name for the base directory */ String dirToken; // XXX default to class? /** if set, then append to specified paths when seeking files */ String defaultSuffix; /** relative path of dir with expected files for comparison */ String expDir; /** if true, fail on first mis-match */ boolean fastFail; /** relative paths (String) of expected files added */ final ArrayList added; /** relative paths (String) of expected files removed/deleted */ final ArrayList removed; /** relative paths (String) of expected files updated/changed */ final ArrayList updated; /** relative paths (String) of expected files NOT * added, removed, or changed * XXX unchanged unimplemented */ final ArrayList unchanged; public Spec() { added = new ArrayList(); removed = new ArrayList(); updated = new ArrayList(); unchanged = new ArrayList(); } /** * @param dirToken the symbol name of the base directory (classes, run) */ public void setDirToken(String dirToken) { this.dirToken = dirToken; } /** * Set the directory containing the expected files. * @param expectedDirRelativePath path relative to the test base * of the directory containing expected results for the output dir. */ public void setExpDir(String expectedDirRelativePath) { expDir = expectedDirRelativePath; } /** * @param clipSuffix the String suffix, if any, to clip automatically */ public void setDefaultSuffix(String defaultSuffix) { this.defaultSuffix = defaultSuffix; } public void setAdded(String items) { XMLWriter.addFlattenedItems(added, items); } public void setRemoved(String items) { XMLWriter.addFlattenedItems(removed, items); } public void setUpdated(String items) { XMLWriter.addFlattenedItems(updated, items); } public void setUnchanged(String items) { XMLWriter.addFlattenedItems(unchanged, items); } public void setFastfail(boolean fastFail) { this.fastFail = fastFail; } /** @return true if some list was specified */ private boolean hasFileList() { return (!LangUtil.isEmpty(added) || !LangUtil.isEmpty(removed) || !LangUtil.isEmpty(updated) || !LangUtil.isEmpty(unchanged) ); } /** * Emit specification in XML form if not empty. * This writes nothing if there is no expected dir * and there are no added, removed, or changed. * fastFail is written only if true, since the default is false. */ public void writeXml(XMLWriter out) { if (!hasFileList() && LangUtil.isEmpty(expDir)) { return; } // XXX need to permit defaults here... out.startElement(XMLNAME, false); if (!LangUtil.isEmpty(dirToken)) { out.printAttribute("dirToken", dirToken.trim()); } if (!LangUtil.isEmpty(defaultSuffix)) { out.printAttribute("defaultSuffix", defaultSuffix.trim()); } if (!LangUtil.isEmpty(expDir)) { out.printAttribute("expDir", expDir.trim()); } if (!LangUtil.isEmpty(added)) { out.printAttribute("added", XMLWriter.flattenList(added)); } if (!LangUtil.isEmpty(removed)) { out.printAttribute("removed", XMLWriter.flattenList(removed)); } if (!LangUtil.isEmpty(updated)) { out.printAttribute("updated", XMLWriter.flattenList(updated)); } if (!LangUtil.isEmpty(unchanged)) { out.printAttribute("unchanged", XMLWriter.flattenList(unchanged)); } if (fastFail) { out.printAttribute("fastFail", "true"); } out.endElement(XMLNAME); } /** * Write list as elements to XMLWriter. * @param out XMLWriter output sink * @param dirChanges List of DirChanges.Spec to write */ public static void writeXml(XMLWriter out, List dirChanges) { if (LangUtil.isEmpty(dirChanges)) { return; } LangUtil.throwIaxIfNull(out, "out"); for (Iterator iter = dirChanges.iterator(); iter.hasNext();) { DirChanges.Spec spec = (DirChanges.Spec) iter.next(); if (null == spec) { continue; } spec.writeXml(out); } } } // class Spec }
62,227
Bug 62227 Load Time Weaving aborts on any kind of warning (declare/xlint)
The message handler in the weaving adapter for load time weaving says: public boolean handleMessage(IMessage message) throws AbortException { if (!isIgnoring(message.getKind())) { if (verbose) System.err.println(message.getMessage()); throw new AbortException(message); } return true; } This means for warnings it goes bang. So, even a declare warning that is meant to tell the user something informational during a LTW will cause the code to blow up. The fix is straightforward and simply to log warning messages and only fail for error messages. I am waiting for a testcase from Matthew before checking in the fix.
resolved fixed
9ebfc84
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2004-05-14T12:51:52Z
2004-05-14T10:20:00Z
org.aspectj.ajdt.core/testsrc/org/aspectj/ajdt/internal/compiler/batch/BcweaverJarMaker.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Common Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * PARC initial implementation * ******************************************************************/ package org.aspectj.ajdt.internal.compiler.batch; import java.io.File; import java.io.IOException; import java.util.*; import java.util.ArrayList; import org.aspectj.ajdt.ajc.AjdtAjcTests; public class BcweaverJarMaker { public BcweaverJarMaker() { super(); } public static void main(String[] args) throws IOException { makeJar0(); makeJar1(); makeJar1a(); makeJar2(); makeJarObviousNothing(); makeJarHardNothing(); makeTestJars(); makeURLWeavingClassLoaderJars(); } public static void makeJar0() throws IOException { List args = new ArrayList(); args.add("-outjar"); args.add("../weaver/testdata/tracing.jar"); args.add("-classpath"); args.add("../runtime/bin" + File.pathSeparator + System.getProperty("aspectjrt.path")); args.add(AjdtAjcTests.TESTDATA_PATH + "/src1/Trace.java"); args.add(AjdtAjcTests.TESTDATA_PATH + "/src1/MyTrace.java"); CommandTestCase.runCompiler(args, CommandTestCase.NO_ERRORS); } public static void makeJar1() throws IOException { List args = new ArrayList(); args.add("-outjar"); args.add("../weaver/testdata/megatrace.jar"); args.add("-classpath"); args.add("../runtime/bin" + File.pathSeparator + System.getProperty("aspectjrt.path")); args.add(AjdtAjcTests.TESTDATA_PATH + "/src1/trace/MegaTrace.java"); args.add(AjdtAjcTests.TESTDATA_PATH + "/src1/trace/ExecTrace.java"); CommandTestCase.runCompiler(args, CommandTestCase.NO_ERRORS); } public static void makeJarObviousNothing() throws IOException { List args = new ArrayList(); args.add("-outjar"); args.add("../weaver/testdata/megatrace0easy.jar"); args.add("-classpath"); args.add("../runtime/bin" + File.pathSeparator + System.getProperty("aspectjrt.path")); args.add(AjdtAjcTests.TESTDATA_PATH + "/src1/trace/MegaTrace.java"); args.add(AjdtAjcTests.TESTDATA_PATH + "/src1/trace/ObviousTraceNothing.java"); CommandTestCase.runCompiler(args, CommandTestCase.NO_ERRORS); } public static void makeJarHardNothing() throws IOException { List args = new ArrayList(); args.add("-outjar"); args.add("../weaver/testdata/megatrace0hard.jar"); args.add("-classpath"); args.add("../runtime/bin" + File.pathSeparator + System.getProperty("aspectjrt.path")); args.add(AjdtAjcTests.TESTDATA_PATH + "/src1/trace/MegaTrace.java"); args.add(AjdtAjcTests.TESTDATA_PATH + "/src1/trace/HardTraceNothing.java"); CommandTestCase.runCompiler(args, CommandTestCase.NO_ERRORS); } public static void makeJar1a() throws IOException { List args = new ArrayList(); args.add("-outjar"); args.add("../weaver/testdata/megatraceNoweave.jar"); args.add("-noweave"); args.add("-classpath"); args.add("../runtime/bin" + File.pathSeparator + System.getProperty("aspectjrt.path")); args.add(AjdtAjcTests.TESTDATA_PATH + "/src1/trace/MegaTrace.java"); args.add(AjdtAjcTests.TESTDATA_PATH + "/src1/trace/ExecTrace.java"); CommandTestCase.runCompiler(args, CommandTestCase.NO_ERRORS); } public static void makeJar2() throws IOException { List args = new ArrayList(); args.add("-outjar"); args.add("../weaver/testdata/dummyAspect.jar"); args.add("-classpath"); args.add("../runtime/bin" + File.pathSeparator + System.getProperty("aspectjrt.path")); args.add(AjdtAjcTests.TESTDATA_PATH + "/src1/DummyAspect.java"); CommandTestCase.runCompiler(args, CommandTestCase.NO_ERRORS); } public static void makeTestJars() throws IOException { List args = new ArrayList(); args.add("-classpath"); args.add("../lib/test/aspectjrt.jar;../lib/test/testing-client.jar" + File.pathSeparator + System.getProperty("aspectjrt.path")); args.add("-outjar"); args.add("../tests/new/options11/aspectlib1.jar"); args.add("../tests/new/options11/library1/*.java"); CommandTestCase.runCompiler(args, CommandTestCase.NO_ERRORS); args = new ArrayList(); args.add("-classpath"); args.add("../lib/test/aspectjrt.jar;../lib/test/testing-client.jar" + File.pathSeparator + System.getProperty("aspectjrt.path")); args.add("-outjar"); args.add("../tests/new/options11/aspectlib2.jar"); args.add("../tests/new/options11/library2/*.java"); CommandTestCase.runCompiler(args, CommandTestCase.NO_ERRORS); args = new ArrayList(); args.add("-classpath"); args.add("../lib/test/aspectjrt.jar;../lib/test/testing-client.jar" + File.pathSeparator + System.getProperty("aspectjrt.path")); args.add("-outjar"); args.add("../tests/new/options11/injar.jar"); args.add("../tests/new/options11/injar/*.java"); CommandTestCase.runCompiler(args, CommandTestCase.NO_ERRORS); args = new ArrayList(); args.add("-classpath"); args.add("../lib/test/aspectjrt.jar;../lib/test/testing-client.jar" + File.pathSeparator + System.getProperty("aspectjrt.path")); args.add("-outjar"); args.add("../tests/bugs/serialVersionUID/injar.jar"); args.add("../tests/bugs/serialVersionUID/Test.java"); args.add("../tests/bugs/serialVersionUID/Util.java"); CommandTestCase.runCompiler(args, CommandTestCase.NO_ERRORS); // For PR55341 args = new ArrayList(); args.add("-classpath"); args.add("../lib/test/aspectjrt.jar;../lib/test/testing-client.jar" + File.pathSeparator + System.getProperty("aspectjrt.path")); args.add("-outjar"); args.add("../tests/bugs/StringToString/helloworld.jar"); args.add("../tests/bugs/StringToString/HW.java"); CommandTestCase.runCompiler(args, CommandTestCase.NO_ERRORS); } public static void makeURLWeavingClassLoaderJars() throws IOException { List args = new ArrayList(); /* * Vanilla classes */ args.add("-classpath"); args.add("../lib/test/aspectjrt.jar;../lib/test/testing-client.jar" + File.pathSeparator + System.getProperty("aspectjrt.path")); args.add("-outjar"); args.add("../weaver/testdata/ltw-classes.jar"); args.add(AjdtAjcTests.TESTDATA_PATH + "/src1/LTWHelloWorld.java"); args.add(AjdtAjcTests.TESTDATA_PATH + "/src1/ltw/LTWPackageTest.java"); CommandTestCase.runCompiler(args, CommandTestCase.NO_ERRORS); /* * Woven classes */ args = new ArrayList(); args.add("-classpath"); args.add("../lib/test/aspectjrt.jar;../lib/test/testing-client.jar;../weaver/testdata/ltw-classes.jar" + File.pathSeparator + System.getProperty("aspectjrt.path")); args.add("-outjar"); args.add("../weaver/testdata/ltw-woven.jar"); args.add(AjdtAjcTests.TESTDATA_PATH + "/src1/LTWHelloWorld.java"); args.add(AjdtAjcTests.TESTDATA_PATH + "/src1/LTWAspect.aj"); CommandTestCase.runCompiler(args, CommandTestCase.NO_ERRORS); /* * Advice */ args = new ArrayList(); args.add("-classpath"); args.add("../lib/test/aspectjrt.jar;../lib/test/testing-client.jar;../weaver/testdata/ltw-classes.jar" + File.pathSeparator + System.getProperty("aspectjrt.path")); args.add("-outjar"); args.add("../weaver/testdata/ltw-aspects.jar"); args.add(AjdtAjcTests.TESTDATA_PATH + "/src1/LTWAspect.aj"); CommandTestCase.runCompiler(args, CommandTestCase.NO_ERRORS); /* * Around closure advice */ args = new ArrayList(); args.add("-classpath"); args.add("../lib/test/aspectjrt.jar;../lib/test/testing-client.jar;../weaver/testdata/ltw-classes.jar" + File.pathSeparator + System.getProperty("aspectjrt.path")); args.add("-outjar"); args.add("../weaver/testdata/ltw-acaspects.jar"); args.add(AjdtAjcTests.TESTDATA_PATH + "/src1/LTWAroundClosure.aj"); CommandTestCase.runCompiler(args, CommandTestCase.NO_ERRORS); /* * ITD */ args = new ArrayList(); args.add("-Xlint:ignore"); args.add("-classpath"); args.add("../lib/test/aspectjrt.jar;../lib/test/testing-client.jar;../weaver/testdata/ltw-classes.jar" + File.pathSeparator + System.getProperty("aspectjrt.path")); args.add("-outjar"); args.add("../weaver/testdata/ltw-itdaspects.jar"); args.add(AjdtAjcTests.TESTDATA_PATH + "/src1/LTWInterfaceITD.aj"); args.add(AjdtAjcTests.TESTDATA_PATH + "/src1/LTWFieldITD.aj"); args.add(AjdtAjcTests.TESTDATA_PATH + "/src1/LTWMethodITD.aj"); CommandTestCase.runCompiler(args, CommandTestCase.NO_ERRORS); /* * perXXX() */ args = new ArrayList(); args.add("-classpath"); args.add("../lib/test/aspectjrt.jar;../lib/test/testing-client.jar;../weaver/testdata/ltw-classes.jar" + File.pathSeparator + System.getProperty("aspectjrt.path")); args.add("-outjar"); args.add("../weaver/testdata/ltw-peraspects.jar"); args.add(AjdtAjcTests.TESTDATA_PATH + "/src1/LTWPerthis.aj"); CommandTestCase.runCompiler(args, CommandTestCase.NO_ERRORS); } }
62,227
Bug 62227 Load Time Weaving aborts on any kind of warning (declare/xlint)
The message handler in the weaving adapter for load time weaving says: public boolean handleMessage(IMessage message) throws AbortException { if (!isIgnoring(message.getKind())) { if (verbose) System.err.println(message.getMessage()); throw new AbortException(message); } return true; } This means for warnings it goes bang. So, even a declare warning that is meant to tell the user something informational during a LTW will cause the code to blow up. The fix is straightforward and simply to log warning messages and only fail for error messages. I am waiting for a testcase from Matthew before checking in the fix.
resolved fixed
9ebfc84
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2004-05-14T12:51:52Z
2004-05-14T10:20:00Z
weaver/src/org/aspectj/weaver/WeavingURLClassLoader.java
/* ******************************************************************* * Copyright (c) 2004 IBM Corporation * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Common Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * Matthew Webster, Adrian Colyer, * Martin Lippert initial implementation * ******************************************************************/ package org.aspectj.weaver; import java.io.File; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import java.net.URLClassLoader; import java.net.URLConnection; import java.net.URLStreamHandler; import java.net.URLStreamHandlerFactory; 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.util.UtilClassLoader; import org.aspectj.weaver.tools.*; 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 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.err.println("? WeavingURLClassLoader.<init>(" + parent + ")"); } public WeavingURLClassLoader (URL[] classURLs, URL[] aspectURLs, ClassLoader parent) { super(classURLs,parent); // System.err.println("? WeavingURLClassLoader.<init>()"); this.aspectURLs = aspectURLs; adaptor = new WeavingAdaptor(this); } 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 + "])"); b = adaptor.weaveClass(name,b); return super.defineClass(name, b, cs); } /** * 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); } }
62,227
Bug 62227 Load Time Weaving aborts on any kind of warning (declare/xlint)
The message handler in the weaving adapter for load time weaving says: public boolean handleMessage(IMessage message) throws AbortException { if (!isIgnoring(message.getKind())) { if (verbose) System.err.println(message.getMessage()); throw new AbortException(message); } return true; } This means for warnings it goes bang. So, even a declare warning that is meant to tell the user something informational during a LTW will cause the code to blow up. The fix is straightforward and simply to log warning messages and only fail for error messages. I am waiting for a testcase from Matthew before checking in the fix.
resolved fixed
9ebfc84
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2004-05-14T12:51:52Z
2004-05-14T10:20: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 Common Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * Matthew Webster, Adrian Colyer, * Martin Lippert initial implementation * ******************************************************************/ package org.aspectj.weaver.tools; import java.io.File; import java.io.IOException; import java.net.URL; import java.net.URLClassLoader; import java.util.ArrayList; import java.util.Arrays; import java.util.Enumeration; 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 java.util.jar.JarEntry; import java.util.jar.JarFile; import org.aspectj.bridge.AbortException; import org.aspectj.bridge.IMessage; import org.aspectj.bridge.IMessageHandler; import org.aspectj.bridge.MessageHandler; import org.aspectj.bridge.IMessage.Kind; import org.aspectj.util.FileUtil; import org.aspectj.weaver.IClassFileProvider; import org.aspectj.weaver.IWeaveRequestor; import org.aspectj.weaver.ResolvedTypeX; import org.aspectj.weaver.bcel.BcelObjectType; import org.aspectj.weaver.bcel.BcelWeaver; import org.aspectj.weaver.bcel.BcelWorld; import org.aspectj.weaver.bcel.LazyClassGen; import org.aspectj.weaver.bcel.UnwovenClassFile; /** * This adaptor allows the AspectJ compiler to be embedded in an existing * system to facilitate load-time weaving. It provides an interface for a * weaving class loader to provide a classpath to be woven by a set of * aspects. A callback is supplied to allow a class loader to define classes * generated by the compiler during the weaving process. * <p> * A weaving class loader should create a <code>WeavingAdaptor</code> before * any classes are defined, typically during construction. The set of aspects * passed to the adaptor is fixed for the lifetime of the adaptor although the * classpath can be augmented. A system property can be set to allow verbose * weaving messages to be written to the console. * */ public class WeavingAdaptor { /** * System property used to turn on verbose weaving messages */ public static final String WEAVING_ADAPTOR_VERBOSE = "aj.weaving.verbose"; private boolean enabled = true; private boolean verbose = getVerbose(); private BcelWorld bcelWorld = null; private BcelWeaver weaver = null; private IMessageHandler messageHandler = null; private GeneratedClassHandler generatedClassHandler; private Map generatedClasses = new HashMap(); /* String -> UnwovenClassFile */ /** * 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 { if (verbose) System.err.println("WeavingAdaptor: Warning - could not determine classpath for " + loader); } } 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) { if (verbose) System.out.println("WeavingAdaptor: classPath='" + classPath + "'"); // make sure the weaver can find all types... messageHandler = new MessageHandler(); bcelWorld = new BcelWorld(classPath,messageHandler,null); bcelWorld.setXnoInline(false); bcelWorld.getLint().loadDefaultProperties(); weaver = new BcelWeaver(bcelWorld); registerAspectLibraries(aspectPath); } /** * Appends URL to path used by the WeavingAdptor to resolve classes * @param url to be appended to search path */ public void addURL(URL url) { try { weaver.addLibraryJarFile(new File(url.getPath())); } catch (IOException ex) { } } /** * 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 (shouldWeave(name)) { bytes = getWovenBytes(name, bytes); } return bytes; } private boolean shouldWeave (String name) { name = name.replace('/','.'); boolean b = (enabled && !generatedClasses.containsKey(name) && shouldWeaveName(name) && shouldWeaveAspect(name)); if (verbose) System.out.println("WeavingAdaptor: shouldWeave('" + name + "') " + b); return b; } private boolean shouldWeaveName (String name) { return !((name.startsWith("org.apache.bcel.") || name.startsWith("org.aspectj.") || name.startsWith("java.") || name.startsWith("javax."))); } private boolean shouldWeaveAspect (String name) { ResolvedTypeX type = bcelWorld.resolve(name); return (type == null || !type.isAspect()); } /** * 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 * @throws FileNotFoundException */ private byte[] getWovenBytes(String name, byte[] bytes) throws IOException { WeavingClassFileProvider wcp = new WeavingClassFileProvider(name,bytes); weaver.weave(wcp); return wcp.getBytes(); // UnwovenClassFile unwoven = new UnwovenClassFile(name,bytes); // // // weave // BcelObjectType bcelType = bcelWorld.addSourceObjectType(unwoven.getJavaClass()); // LazyClassGen woven = weaver.weaveWithoutDump(unwoven,bcelType); // // byte[] wovenBytes = woven != null ? woven.getJavaClass(bcelWorld).getBytes() : bytes; // return wovenBytes; } private void registerAspectLibraries(List aspectPath) { // System.err.println("? WeavingAdaptor.registerAspectLibraries(" + aspectPath + ")"); for (Iterator i = aspectPath.iterator(); i.hasNext();) { String lib = (String)i.next(); File libFile = new File(lib); if (libFile.isFile() && lib.endsWith(".jar")) { try { if (verbose) System.out.println("WeavingAdaptor: adding aspect '" + lib + "' to weaver"); addAspectLibrary(new File(lib)); } catch (IOException ioEx) { if (verbose) System.err.println( "WeavingAdaptor: Warning - could not load aspect path entry " + lib + " : " + ioEx); } } else { if (verbose) System.err.println( "WeavingAdaptor: Warning - ignoring aspect path entry: " + lib); } } 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(File aspectLibraryJarFile) throws IOException { weaver.addLibraryJarFile(aspectLibraryJarFile); // weaver.prepareForWeave(); } 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; } /** * Processes messages arising from weaver operations. * Tell weaver to abort on any non-informational error. */ private class MessageHandler implements IMessageHandler { public boolean handleMessage(IMessage message) throws AbortException { if (!isIgnoring(message.getKind())) { if (verbose) System.err.println(message.getMessage()); throw new AbortException(message); } return true; } public boolean isIgnoring(Kind kind) { return ((kind == IMessage.INFO) || (kind == IMessage.DEBUG)); } } private class WeavingClassFileProvider implements IClassFileProvider { private List unwovenClasses = new ArrayList(); /* List<UnovenClassFile> */ private UnwovenClassFile wovenClass; public WeavingClassFileProvider (String name, byte[] bytes) { UnwovenClassFile unwoven = new UnwovenClassFile(name,bytes); unwovenClasses.add(unwoven); bcelWorld.addSourceObjectType(unwoven.getJavaClass()); } public byte[] getBytes () { return wovenClass.getBytes(); } public Iterator getClassFileIterator() { return unwovenClasses.iterator(); } public IWeaveRequestor getRequestor() { return new IWeaveRequestor() { public void acceptResult(UnwovenClassFile result) { if (wovenClass == null) { wovenClass = result; } /* Classes generated by weaver e.g. around closure advice */ else { String className = result.getClassName(); generatedClasses.put(className,result); generatedClassHandler.acceptClass(className,result.getBytes()); } } public void processingReweavableState() { } public void addingTypeMungers() {} public void weavingAspects() {} public void weavingClasses() {} public void weaveCompleted() {} }; } } }
62,227
Bug 62227 Load Time Weaving aborts on any kind of warning (declare/xlint)
The message handler in the weaving adapter for load time weaving says: public boolean handleMessage(IMessage message) throws AbortException { if (!isIgnoring(message.getKind())) { if (verbose) System.err.println(message.getMessage()); throw new AbortException(message); } return true; } This means for warnings it goes bang. So, even a declare warning that is meant to tell the user something informational during a LTW will cause the code to blow up. The fix is straightforward and simply to log warning messages and only fail for error messages. I am waiting for a testcase from Matthew before checking in the fix.
resolved fixed
9ebfc84
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2004-05-14T12:51:52Z
2004-05-14T10:20:00Z
weaver/testsrc/org/aspectj/weaver/WeavingURLClassLoaderTest.java
/* ******************************************************************* * Copyright (c) 2004 IBM Corporation * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Common Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * Matthew Webster initial implementation * ******************************************************************/ package org.aspectj.weaver; import java.io.File; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.net.URL; import junit.framework.TestCase; import org.aspectj.bridge.AbortException; import org.aspectj.util.FileUtil; import org.aspectj.weaver.tools.WeavingAdaptor; /** * @author websterm * * To change the template for this generated type comment go to * Window>Preferences>Java>Code Generation>Code and Comments */ public class WeavingURLClassLoaderTest extends TestCase { private final static String CLASSES_JAR = BcweaverTests.TESTDATA_PATH + "/ltw-classes.jar"; private final static String WOVEN_JAR = BcweaverTests.TESTDATA_PATH + "/ltw-woven.jar"; private final static String JUNK_JAR = BcweaverTests.TESTDATA_PATH + "/ltw-junk.jar"; private final static String ADVICE_ASPECTS = BcweaverTests.TESTDATA_PATH + "/ltw-aspects.jar"; private final static String AROUNDCLOSURE_ASPECTS = BcweaverTests.TESTDATA_PATH + "/ltw-acaspects.jar"; private final static String ITD_ASPECTS = BcweaverTests.TESTDATA_PATH + "/ltw-itdaspects.jar"; private final static String PER_ASPECTS = BcweaverTests.TESTDATA_PATH + "/ltw-peraspects.jar"; public WeavingURLClassLoaderTest(String name) { super(name); System.setProperty(WeavingAdaptor.WEAVING_ADAPTOR_VERBOSE,"true"); } public void testLoadClass () { System.setProperty(WeavingURLClassLoader.WEAVING_ASPECT_PATH,""); System.setProperty(WeavingURLClassLoader.WEAVING_CLASS_PATH,CLASSES_JAR); WeavingURLClassLoader loader = new WeavingURLClassLoader(getClass().getClassLoader()); try { Class clazz = loader.loadClass("LTWHelloWorld"); invokeMain(clazz,new String[] {}); } catch (Exception ex) { fail(ex.toString()); } } public void testLoadWovenClass () { System.setProperty(WeavingURLClassLoader.WEAVING_ASPECT_PATH,""); System.setProperty(WeavingURLClassLoader.WEAVING_CLASS_PATH,WOVEN_JAR); WeavingURLClassLoader loader = new WeavingURLClassLoader(getClass().getClassLoader()); try { Class clazz = loader.loadClass("LTWHelloWorld"); invokeMain(clazz,new String[] { "LTWAspect" }); } catch (Exception ex) { fail(ex.toString()); } } public void testWeaveWovenClass () { System.setProperty(WeavingURLClassLoader.WEAVING_ASPECT_PATH,ADVICE_ASPECTS); System.setProperty(WeavingURLClassLoader.WEAVING_CLASS_PATH,ADVICE_ASPECTS + File.pathSeparator + WOVEN_JAR); WeavingURLClassLoader loader = new WeavingURLClassLoader(getClass().getClassLoader()); try { Class clazz = loader.loadClass("LTWHelloWorld"); fail("Expecting org.aspectj.bridge.AbortException"); } catch (Exception ex) { assertTrue("Expecting org.aspectj.bridge.AbortException caught " + ex,(ex instanceof AbortException)); } } public void testWeavingURLClassLoader () { URL classes = FileUtil.getFileURL(new File(CLASSES_JAR)); URL aspects = FileUtil.getFileURL(new File(ADVICE_ASPECTS)); URL[] classURLs = new URL[] { aspects, classes }; URL[] aspectURLs = new URL[] { aspects }; WeavingURLClassLoader loader = new WeavingURLClassLoader(classURLs,aspectURLs,getClass().getClassLoader()); try { Class clazz = loader.loadClass("LTWHelloWorld"); invokeMain(clazz,new String[] { "LTWAspect" }); } catch (Exception ex) { fail(ex.toString()); } } public void testWeaveAdvice () { System.setProperty(WeavingURLClassLoader.WEAVING_ASPECT_PATH,ADVICE_ASPECTS); System.setProperty(WeavingURLClassLoader.WEAVING_CLASS_PATH,ADVICE_ASPECTS + File.pathSeparator + CLASSES_JAR); WeavingURLClassLoader loader = new WeavingURLClassLoader(getClass().getClassLoader()); try { Class clazz = loader.loadClass("LTWHelloWorld"); invokeMain(clazz,new String[] { "LTWAspect" }); } catch (Exception ex) { fail(ex.toString()); } } public void testWeaveAroundClosure () { System.setProperty(WeavingURLClassLoader.WEAVING_ASPECT_PATH,AROUNDCLOSURE_ASPECTS); System.setProperty(WeavingURLClassLoader.WEAVING_CLASS_PATH,AROUNDCLOSURE_ASPECTS + File.pathSeparator + CLASSES_JAR); WeavingURLClassLoader loader = new WeavingURLClassLoader(getClass().getClassLoader()); try { Class clazz = loader.loadClass("LTWHelloWorld"); invokeMain(clazz,new String[] { "LTWAroundClosure" }); } catch (Exception ex) { fail(ex.toString()); } } public void testWeavingITD () { URL classes = FileUtil.getFileURL(new File(CLASSES_JAR)); URL aspects = FileUtil.getFileURL(new File(ITD_ASPECTS)); URL[] classURLs = new URL[] { aspects, classes }; URL[] aspectURLs = new URL[] { aspects }; WeavingURLClassLoader loader = new WeavingURLClassLoader(classURLs,aspectURLs,getClass().getClassLoader()); try { Class clazz = loader.loadClass("LTWHelloWorld"); invokeMain(clazz,new String[] { "LTWInterfaceITD", "LTWFieldITD", "LTWMethodITD" }); } catch (Exception ex) { fail(ex.toString()); } } public void testWeavingPer () { URL classes = FileUtil.getFileURL(new File(CLASSES_JAR)); URL aspects = FileUtil.getFileURL(new File(PER_ASPECTS)); URL[] classURLs = new URL[] { aspects, classes }; URL[] aspectURLs = new URL[] { aspects }; WeavingURLClassLoader loader = new WeavingURLClassLoader(classURLs,aspectURLs,getClass().getClassLoader()); try { Class clazz = loader.loadClass("LTWHelloWorld"); invokeMain(clazz,new String[] { "LTWPerthis" }); } catch (Exception ex) { fail(ex.toString()); } } public void testWeavingAspects () { URL classes = FileUtil.getFileURL(new File(CLASSES_JAR)); URL aspects1 = FileUtil.getFileURL(new File(ADVICE_ASPECTS)); URL aspects2 = FileUtil.getFileURL(new File(AROUNDCLOSURE_ASPECTS)); URL aspects3 = FileUtil.getFileURL(new File(ITD_ASPECTS)); URL aspects4 = FileUtil.getFileURL(new File(PER_ASPECTS)); URL[] classURLs = new URL[] { aspects1, aspects2, aspects3, aspects4, classes }; URL[] aspectURLs = new URL[] { aspects1, aspects2, aspects3, aspects4 }; WeavingURLClassLoader loader = new WeavingURLClassLoader(classURLs,aspectURLs,getClass().getClassLoader()); try { Class clazz = loader.loadClass("LTWHelloWorld"); invokeMain(clazz,new String[] { "LTWAspect", "LTWAroundClosure", "LTWPerthis", "LTWInterfaceITD", "LTWFieldITD", "LTWMethodITD", "LTWPerthis"}); } catch (Exception ex) { fail(ex.toString()); } } public void testJunkJar () { File junkJar = new File(JUNK_JAR); assertFalse(junkJar + " should not exist",junkJar.exists()); URL classes = FileUtil.getFileURL(junkJar); URL[] classURLs = new URL[] { classes }; URL[] aspectURLs = new URL[] { }; WeavingURLClassLoader loader = new WeavingURLClassLoader(classURLs,aspectURLs,getClass().getClassLoader()); try { Class clazz = loader.loadClass("LTWHelloWorld"); fail("Expecting java.lang.ClassNotFoundException"); } catch (Exception ex) { assertTrue("Expecting java.lang.ClassNotFoundException caught " + ex,(ex instanceof ClassNotFoundException)); } } public void testAddURL () { URL classes = FileUtil.getFileURL(new File(CLASSES_JAR)); URL aspects = FileUtil.getFileURL(new File(ADVICE_ASPECTS)); URL[] classURLs = new URL[] { aspects }; URL[] aspectURLs = new URL[] { aspects }; WeavingURLClassLoader loader = new WeavingURLClassLoader(classURLs,aspectURLs,getClass().getClassLoader()); loader.addURL(classes); try { Class clazz = loader.loadClass("LTWHelloWorld"); invokeMain(clazz,new String[] { "LTWAspect" }); } catch (Exception ex) { fail(ex.toString()); } } public void testParentChild() { URL classes = FileUtil.getFileURL(new File(CLASSES_JAR)); URL aspects = FileUtil.getFileURL(new File(ADVICE_ASPECTS)); URL[] classURLs = new URL[] { aspects }; URL[] aspectURLs = new URL[] { aspects }; WeavingURLClassLoader parent = new WeavingURLClassLoader(classURLs,aspectURLs,getClass().getClassLoader()); classURLs = new URL[] { classes }; aspectURLs = new URL[] { }; WeavingURLClassLoader child = new WeavingURLClassLoader(classURLs,aspectURLs,parent); try { Class clazz = child.loadClass("LTWHelloWorld"); invokeMain(clazz,new String[] { "LTWAspect" }); } catch (Exception ex) { fail(ex.toString()); } } /* * Aspects on ASPECTPATH but missing from CLASSPATH */ public void testIncompletePath () { System.setProperty(WeavingURLClassLoader.WEAVING_ASPECT_PATH,ADVICE_ASPECTS); System.setProperty(WeavingURLClassLoader.WEAVING_CLASS_PATH,CLASSES_JAR); WeavingURLClassLoader loader = new WeavingURLClassLoader(getClass().getClassLoader()); try { Class clazz = loader.loadClass("LTWHelloWorld"); invokeMain(clazz,new String[] { "LTWAspect" }); fail("Expecting java.lang.NoClassDefFoundError"); } catch (Exception ex) { } } /* * Ensure package object is correct */ public void testPackage () { System.setProperty(WeavingURLClassLoader.WEAVING_ASPECT_PATH,""); System.setProperty(WeavingURLClassLoader.WEAVING_CLASS_PATH,CLASSES_JAR); WeavingURLClassLoader loader = new WeavingURLClassLoader(getClass().getClassLoader()); try { Class clazz = loader.loadClass("ltw.LTWPackageTest"); invokeMain(clazz,new String[] { }); Package pakkage = clazz.getPackage(); assertTrue("Expected 'ltw' got " + pakkage,(pakkage != null)); } catch (Exception ex) { fail(ex.toString()); } } public static void invokeMain (Class clazz, String[] args) { Class[] paramTypes = new Class[1]; paramTypes[0] = args.getClass(); try { Method method = clazz.getDeclaredMethod("main",paramTypes); Object[] params = new Object[1]; params[0] = args; method.invoke(null,params); } catch (InvocationTargetException ex) { throw new RuntimeException(ex.getTargetException().toString()); } catch (Exception ex) { throw new RuntimeException(ex.toString()); } } }
61,411
Bug 61411 AJDoc launch script on Windows can lose arguments
Using AspectJ 1.2rc1 on Windows XP This report highlights a problem that I've seen using ajdoc.bat on Windows but the issue applies equally to the ajc.bat and ajbrowser.bat files as well. The %ASPECTJ_HOME%\bin\ajdoc.bat file that users run to launch the ajdoc tool imposes a limit of only 9 command line arguments that may be passed to the class org.aspectj.tools.ajdoc.Main. In scenarios where there the -sourcepath, -classpath, -d etc options are used it is easy for these to "eat up" the list of arguments that are passed into the JVM. A long list of packages entered at the end of the ajdoc.bat command can be truncated or possibly even ignored (in which case an error message will be output telling the user that no classes or packages have been specified). In order to prevent a limit being put on the number of arguments passed to the launched JVM, the invocation line needs to end with %* rather than the %1 %2 %3 %4 %5 %6 %7 %8 %9 list it currently uses. The proposed fix also *seems* (could somebody else confirm this ?) to sort out another problem regarding the ajdoc.bat file which is this : long semi- colon delimited paths supplied as the arguments for the -sourcepath and -classpath options seem to get split apart and passed into the JVM as separate arguments unless the entire path list is supplied inside quotes. This should not be necessary. It seems that the batch file processor interprets the semi-colons in a path list as delimiters between arguments. Consequently each element in the path list is treated as a separate argument instead of being part of one big string representing the sourcepath or classpath.
resolved fixed
39c3a3b
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2004-05-28T15:19:14Z
2004-05-07T17:13:20Z
build/src/$installer$/org/aspectj/Main.java
/* ******************************************************************* * Copyright (c) 2000-2001 Xerox Corporation, * 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Common Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * Xerox/PARC initial implementation * ******************************************************************/ package $installer$.org.aspectj; import java.awt.BorderLayout; import java.awt.Component; import java.awt.Dimension; import java.awt.FlowLayout; import java.awt.Font; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Toolkit; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.awt.event.WindowListener; import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.FileWriter; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.PrintStream; import java.lang.reflect.InvocationTargetException; import java.net.URL; import java.util.Map; import java.util.Properties; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; import javax.swing.BorderFactory; import javax.swing.BoxLayout; import javax.swing.Icon; import javax.swing.JButton; import javax.swing.JEditorPane; import javax.swing.JFileChooser; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JProgressBar; import javax.swing.JTextArea; import javax.swing.JTextField; import javax.swing.SwingUtilities; import javax.swing.border.Border; import javax.swing.border.CompoundBorder; import javax.swing.border.EmptyBorder; /** * Invoke the Installer gui. * There are two ways to run without GUI by passing parameters to main: * <ol> * <li>pass <code>-text {pathToPropertiesFile}</code>: * <ul> * <li> "-text".equals(arg[0])</li> * <li> arg[1] is the path to a properties file which defines * name="output.dir" value="{path to output dir}" * name="context.javaPath" value="{path to JDKDIR}", i.e,. * <pre>output.dir=c:/latest * "context.javaPath=c:/apps/jdk1.3.1</pre></li> * <li>outputDir must be created and empty (i.e., no overwriting</li> * <li>the VM being invoked should be the target vm</li> * </ul> * </li> * <li>pass <code>-to {pathToTargetDir}</code>: * <ul> * <li> "-to".equals(arg[0])</li> * <li> arg[1] is the path to a writable install directory. * </li> * </ul> * </li> */ public class Main { public static void main(String[] args) { Options.loadArgs(args); boolean hasGui = true; Properties properties = new Properties(); InputStream istream = null; try { istream = Main.class.getResourceAsStream(Installer.RESOURCE_DIR + "/properties.txt"); if (istream == null) { System.err.println("unable to load properties.txt using Main.class - exiting"); Main.exit(-1); } properties.load(istream); // when running outside GUI, load values into properties // so that property-value resolution works // (otherwise, could just set values below). // XXX not sure if this indirection is actually needed. if (null != Options.textProperties) { istream.close(); istream = new FileInputStream(Options.textProperties); properties.load(istream); hasGui = false; } else if (null != Options.targetDir) { String path = null; try { path = Options.targetDir.getCanonicalPath(); } catch (IOException e) { path = Options.targetDir.getAbsolutePath(); } String javaPath = ConfigureLauncherPane.getDefaultJavaHomeLocation(); if (null == javaPath) { System.err.println("using GUI - unable to find java"); } else { properties.setProperty("output.dir", path); properties.setProperty("context.javaPath", javaPath); hasGui = false; } } } catch (IOException ioe) { handleException(ioe); } finally { if (null != istream) { try {istream.close();} catch (IOException e){} // ignore } } try { String className = (String)properties.get("installer.main.class"); //UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); Installer installer = (Installer)Class.forName(className).newInstance(); InstallContext installerContext = new InstallContext(properties); installerContext.setHasGui(hasGui); installer.setContext(installerContext); if (installerContext.hasGui()) { // let context force whether or not to run gui installer.runGUI(); } else { // set output dir and java path in context after minimal validation String propName = "output.dir"; String propValue = properties.getProperty(propName); if (null == propValue) { throw new Exception("expecting property " + propName); } String outputDirName = propValue; propName = "context.javaPath"; propValue = properties.getProperty(propName); if (null == propValue) { throw new Exception("expecting property " + propName); } String javaPath = propValue; File outputDir = new File(outputDirName); if (! outputDir.isDirectory()) { throw new Exception("not a dir outputDirName: " + outputDirName + " dir: " + outputDir); } if (! outputDir.canWrite()) { throw new Exception("cannot write outputDirName: " + outputDirName + " dir: " + outputDir); } InstallContext context = installer.getContext(); // todo: why not use installerContext? context.setOutputDir(outputDir); context.javaPath = new File(javaPath); // todo: check javaPath for ... bin/java? lib/rt.jar? if (! outputDir.isDirectory() || ! outputDir.canRead()) { throw new Exception("invalid javaPath: " + javaPath); } // directly set context and run WizardPane.setContext(installerContext); installer.run(); } } catch (Exception e) { handleException(e); } } public static void handleException(Throwable e) { System.out.println("internal error: " + e.toString()); e.printStackTrace(); Main.exit(-1); } /** indirection for System.exit - todo apply cleanup here as necessary */ public static void exit(int value) { System.exit(value); } } // class Main class Options { public static boolean verbose = false; public static String textProperties = null; public static File targetDir = null; public static boolean forceError1 = false; public static boolean forceError2 = false; public static boolean forceHandConfigure = false; public static void loadArgs(String[] args) { if (args == null) return; for (int i=0; i<args.length; i++) { String arg = args[i]; if (arg == null) continue; if (arg.equals("-verbose")) verbose = true; else if (arg.equals("-forceError1")) forceError1 = true; else if (arg.equals("-forceError2")) forceError2 = true; else if (arg.equals("-forceHandConfigure")) forceHandConfigure = true; else if (arg.equals("-text")) { if (i+1 < args.length) { textProperties = args[++i]; } } else if (arg.equals("-to")) { String next = "no argument"; if (i+1 < args.length) { next = args[++i]; File targDir = new File(next); if (targDir.isDirectory() && targDir.canWrite()) { targetDir = targDir; } } if (null == targetDir) { System.err.println("invalid -to dir: " + next); } } } } } /** tools installer installs the entire 1.1+ distribution */ class ToolsInstaller extends Installer { public String getTitle() { return "Installer for AspectJ(TM)"; } public String getPrefix() { return "tools"; } public String getReadmeFilename() { return "README-AspectJ.html"; } public ToolsInstaller() { InstallPane installPane = new InstallPane(true); setInstallPane(installPane); panes = new WizardPane[] { new IntroPane(), new ConfigureLauncherPane(), new LocationPane(), installPane, new FinishPane() }; } } class DocsInstaller extends Installer { public String getTitle() { return "AspectJ(TM) Documentation and Examples Installer"; } public String getPrefix() { return "docs"; } public DocsInstaller() { InstallPane installPane = new InstallPane(false); setInstallPane(installPane); panes = new WizardPane[] { new IntroPane(), new LocationPane(), installPane, new FinishPane() }; } } class AJDEForJBuilderInstaller extends Installer { public String getTitle() { return "AspectJ(TM) Support for JBuilder"; } public String getPrefix() { return "ajdeForJBuilder"; } public AJDEForJBuilderInstaller() { InstallPane installPane = new InstallPane(false); setInstallPane(installPane); panes = new WizardPane[] { new IntroPane(), new LocationPane() { public String getDefaultLocation() { if (context.onWindows()) { // check some default locations String[] paths = { "c:\\JBuilder6\\lib\\ext", "c:\\apps\\JBuilder6\\lib\\ext", "c:\\Program Files\\JBuilder6\\lib\\ext" }; int pathIndex = 0; for (; pathIndex < paths.length; pathIndex++) { if (new File(paths[pathIndex]).exists()) return paths[pathIndex]; } return "c:\\JBuilder6\\lib\\ext"; } else { return "/usr/JBuilder6/lib/ext"; } } /** * Make sure that the old jar file gets removed. */ public void verify() { File jbuilder = new File(location.getText() + "/../../lib/jbuilder.jar"); if (!jbuilder.exists() && hasGui()) { int ret = JOptionPane.showConfirmDialog (frame, "The location you specified does not seem to be a " + "valid JBuilder install directory." + " Continue?", "Confirm Install", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE); if (ret != JOptionPane.YES_OPTION) { Main.exit(-1); } else { // do nothing } } File oldFile = new File(location.getText() + "/ajbuilder.jar"); if (oldFile.exists() && hasGui()) { int ret = JOptionPane.showConfirmDialog(frame, "This old version of AJDE for JBuilder (\"ajbuilder.jar\") exists" + " and must be removed from the install directory." + " OK to delete?", "Confirm Delete", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE); if (ret != JOptionPane.YES_OPTION) { Main.exit(-1); } else { oldFile.delete(); } } } }, installPane, new FinishPane() }; } } class AJDEForForteInstaller extends Installer { public String getTitle() { return "AspectJ(TM) Support for Forte 4J"; } public String getPrefix() { return "ajdeForForte"; } private String installLoc = ""; public AJDEForForteInstaller() { InstallPane installPane = new InstallPane(false); setInstallPane(installPane); panes = new WizardPane[] { new IntroPane(), new LocationPane() { public String getDefaultLocation() { if (context.onWindows()) { // check some default locations String[] paths = { "c:\\forte4j\\modules", "c:\\apps\\forte4j\\modules", "c:\\Program Files\\forte4j\\modules" }; int pathIndex = 0; for (; pathIndex < paths.length; pathIndex++) { if (new File(paths[pathIndex]).exists()) return paths[pathIndex]; } return "c:\\forte4j\\modules"; } else { return "/usr/forte4j/modules"; } } public void verify() { File forte = new File(location.getText() + "/../lib/openide.jar"); installLoc = location.getText(); if (!forte.exists() && hasGui()) { int ret = JOptionPane.showConfirmDialog (frame, "The location you specified does not seem to be a " + "valid Forte install directory." + " Continue?", "Confirm Install", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE); if (ret != JOptionPane.YES_OPTION) { Main.exit(-1); } else { // do nothing } } } }, installPane, new FinishPane() { public void finalActions() { // todo verify dir ../lib/ext exists? // !!! this should be done with two install locations, not by moving a file new File(installLoc + "/../lib/ext/aspectjrt.jar").delete(); new File(installLoc + "/aspectjrt.jar").renameTo(new File((installLoc + "/../lib/ext/aspectjrt.jar"))); new File(installLoc + "/aspectjrt.jar").delete(); } } }; } } class SrcInstaller extends Installer { public String getTitle() { return "AspectJ(TM) Compiler and Core Tools Sources Installer"; } public String getPrefix() { return "sources"; } public SrcInstaller() { InstallPane installPane = new InstallPane(false); setInstallPane(installPane); panes = new WizardPane[] { new IntroPane(), new LocationPane(), installPane, new FinishPane() }; } } abstract class Installer { static final String EXIT_MESSAGE = "Are you sure you want to cancel the installation?"; static final String EXIT_TITLE = "Exiting installer"; /** relative directory in jar from package $installer$.org.aspectj for loading resources - todo must be tracked during build */ public static final String RESOURCE_DIR = "resources"; JFrame frame; InstallContext context; /** special pane that actually does the installation */ InstallPane installPane; public Installer() { } protected void setInstallPane(InstallPane installPane) { this.installPane = installPane; } public InstallPane getInstallPane() { return installPane; } /** directly run the install pane, if any */ public void run() { if (null != installPane) { installPane.run(); } } public abstract String getPrefix(); public String getReadmeFilename() { return "README-" + getPrefix().toUpperCase()+".html"; } public void setContext(InstallContext context) { this.context = context; context.installer = this; } public InstallContext getContext() { return context; } public String getTitle() { return "AspectJ(TM) Installer"; } public int getWidth() { return 640; } public int getHeight() { return 460; } protected WizardPane[] panes = new WizardPane[0]; public WizardPane[] getPanes() { return panes; } public int findPaneIndex(WizardPane pane) { for (int i = 0; i < panes.length; i++) { if (panes[i] == pane) return i; } return -1; } Component header, footer, body; public void runGUI() { frame = new JFrame(getTitle()); WindowListener wl = new WindowAdapter() { public void windowClosing(WindowEvent arg0) { Main.exit(-1); // -1 unless exiting through done button } }; frame.addWindowListener(wl); if (Options.forceError1) { throw new RuntimeException("forced error1 for testing purposes"); } Dimension size = Toolkit.getDefaultToolkit().getScreenSize(); int x = (int)(size.getWidth() - getWidth()) / 2; int y = (int)(size.getHeight() - getHeight()) / 2; //include a few sanity checks on starting position if (x < 0) x = 0; if (x > 600) x = 600; if (y < 0) y = 0; if (y > 400) y = 400; frame.setLocation(x, y); frame.setSize(getWidth(), getHeight()); moveToPane(getPanes()[0]); frame.setVisible(true); } public void moveToPane(WizardPane pane) { WizardPane.setContext(this.context); Dimension size = frame.getContentPane().getSize(); JPanel contents = new JPanel(); contents.setLayout(new BorderLayout()); header = makeHeader(); contents.add(header, BorderLayout.NORTH); body = pane.getPanel(); contents.add(body, BorderLayout.CENTER); footer = pane.getButtons(); contents.add(footer, BorderLayout.SOUTH); contents.revalidate(); contents.setSize(size); frame.setContentPane(contents); //XXX deal with threading here? pane.run(); } public Icon loadImage(String name) { return new javax.swing.ImageIcon(this.getClass().getResource(name)); } public Component makeHeader() { return new JLabel(loadImage(Installer.RESOURCE_DIR + "/aspectjBanner.gif")); } public ActionListener makeNextAction(final WizardPane pane) { int nextPaneIndex = findPaneIndex(pane) + 1; if (nextPaneIndex >= getPanes().length) { return null; } final WizardPane nextPane = getPanes()[nextPaneIndex]; return new ActionListener() { public void actionPerformed(ActionEvent e) { pane.finish(); moveToPane(nextPane); } }; } public ActionListener makeBackAction(final WizardPane pane) { int nextPaneIndex = findPaneIndex(pane) - 1; if (nextPaneIndex < 0) { return null; } final WizardPane nextPane = getPanes()[nextPaneIndex]; return new ActionListener() { public void actionPerformed(ActionEvent e) { moveToPane(nextPane); } }; } public ActionListener makeCancelAction(WizardPane pane) { return new ActionListener() { public void actionPerformed(ActionEvent e) { int ret = JOptionPane.showConfirmDialog(frame, EXIT_MESSAGE, EXIT_TITLE, JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE); if (ret == JOptionPane.YES_OPTION) { Main.exit(-1); } } }; } public ActionListener makeFinishAction(WizardPane pane) { return new ActionListener() { public void actionPerformed(ActionEvent e) { Main.exit(0); } }; } } // willing to go up to 3 levels deep to find either jre or jdk // jre\[*\]lib\ext // jdk*\lib\tools.jar /***** final static int MAX_DEPTH = 4; public static void findPaths(String prefix, File currentDir, int currentDepth) { if (currentDepth > MAX_DEPTH) return; if (!currentDir.exists() || !currentDir.isDirectory()) return; File [] files = currentDir.listFiles(); if (files == null) return; for (int i=0; i<files.length; i++) { if (files[i] == null) continue; if (!files[i].isDirectory()) continue; if (files[i].getName().startsWith(prefix)) { System.out.println("found: " + files[i]); } else { findPaths(prefix, files[i], currentDepth + 1); } } } public static void findPaths(String prefix) { File [] files = File.listRoots(); for (int i=1; i<files.length; i++) { if (!files[i].isDirectory()) continue; if (files[i].getName().toLowerCase().startsWith(prefix)) { System.out.println("found: " + files[i]); } else { findPaths(prefix, files[i], 1); } } } *****/ class InstallContext { public InstallContext(Map properties) { this.properties = properties; properties.put("user.home", System.getProperty("user.home")); //System.out.println("new install context"); } private File outputDir; public void setOutputDir(File outputDir) { this.outputDir = outputDir; properties.put("installer.output.dir", outputDir.getAbsolutePath()); properties.put("installer.output.dir.bin", new File(outputDir, "bin").getAbsolutePath()); properties.put("installer.output.dir.doc", new File(outputDir, "doc").getAbsolutePath()); properties.put("installer.output.aspectjrt", new File(new File(outputDir, "lib"), "aspectjrt.jar").getAbsolutePath()); properties.put("installer.output.readme", new File(outputDir, installer.getReadmeFilename()).getAbsolutePath()); } public File getOutputDir() { return outputDir; } private boolean hasGui; public File javaPath; public File toolsJarPath; public Installer installer; private Map properties; public boolean hasGui() { return hasGui; } public void setHasGui(boolean hasGui) { if (this.hasGui != hasGui) { this.hasGui = hasGui; } } public Font getFont() { return new Font("Serif", Font.PLAIN, 14); } public String getOS() { return System.getProperty("os.name"); } public boolean onOS2() { return getOS().equals("OS2") || getOS().equals("OS/2"); } public boolean onWindows() { return getOS().startsWith("Windows") || onOS2(); } public boolean onWindowsPro() { return getOS().equals("Windows NT") || getOS().equals("Windows 2000"); } public boolean onMacintosh() { return getOS().startsWith("Mac"); } public boolean onUnix() { return !onMacintosh() && !onWindows(); } static final String[] TEXT_EXTENSIONS = { ".txt", ".text", ".htm", ".html", ".java", ".ajava", "README", ".lst" }; public boolean isTextFile(File file) { String name = file.getName(); for (int i=0; i < TEXT_EXTENSIONS.length; i++) { if (name.endsWith(TEXT_EXTENSIONS[i])) return true; } return false; } public void handleException(Throwable e) { System.out.println("internal error: " + e.toString()); e.printStackTrace(); if (hasGui()) { JOptionPane.showMessageDialog(installer.frame, e.toString(), "Unexpected Exception", JOptionPane.ERROR_MESSAGE); } } final static String OVERWRITE_MESSAGE = "Overwrite file "; final static String OVERWRITE_TITLE = "Overwrite?"; final static String[] OVERWRITE_OPTIONS = { "Yes", "No", "Yes to all" //, "No to all" }; final static int OVERWRITE_YES = 0; final static int OVERWRITE_NO = 1; final static int OVERWRITE_ALL = 2; //final static int OVERWRITE_NONE = 3; int overwriteState = OVERWRITE_NO; boolean shouldOverwrite(final File file) { //System.out.println("overwrite: " + file + " state " + overwriteState); if (overwriteState == OVERWRITE_ALL) return true; //if (overwriteState == OVERWRITE_NONE) return false; try { SwingUtilities.invokeAndWait(new Runnable() { public void run() { int ret = JOptionPane.showOptionDialog(installer.frame, OVERWRITE_MESSAGE+file.getPath(), OVERWRITE_TITLE, JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, null, OVERWRITE_OPTIONS, OVERWRITE_OPTIONS[OVERWRITE_YES]); overwriteState = ret; } }); } catch (InvocationTargetException ite) { handleException(ite.getTargetException()); } catch (InterruptedException ie) { } return overwriteState == OVERWRITE_YES || overwriteState == OVERWRITE_ALL; } public Map getProperties() { return properties; } } abstract class WizardPane { static InstallContext context; protected JButton backButton = null; protected JButton nextButton = null; protected JButton cancelButton = null; public static void setContext(InstallContext con) { context = con; } public abstract JPanel makePanel(); protected JTextArea makeTextArea(String data) { JTextArea text = new JTextArea(data); text.setOpaque(false); text.setFont(context.getFont()); text.setEditable(false); return text; } /** @return false only if there is an InstallContext saying there is no GUI */ protected boolean hasGui() { final InstallContext icontext = context; return ((null == icontext) || icontext.hasGui()); } public static String stringFromStream(InputStream stream) throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(stream, "US-ASCII")); StringBuffer ret = new StringBuffer(); int data; while ( (data = reader.read()) != -1) { ret.append( (char)data ); } return ret.toString(); } public static String removeHead(String text) { int startIndex = text.indexOf("<head>"); int stopIndex = text.indexOf("</head>"); if (startIndex == -1 || stopIndex == -1) return text; stopIndex += 7; return text.substring(0, startIndex) + text.substring(stopIndex); } static String styleHeader = "<head></head>";/*<STYLE TYPE=\"text/css\"><!--\n" + " h2 {\n" + " font-size: x-large;\n" + " font-family: Serif;\n" + " font-weight: normal;\n" + " }\n" + " p {\n" + " font-family: Serif;\n" + " font-weight: normal;\n" + //" color:black;\n" + "}</head>\n";*/ public static String applyProperties(String text, Map map) { // ${name} -> map.get(name).toString() int lastIndex = 0; StringBuffer buf = new StringBuffer(); int startIndex; while ( (startIndex = text.indexOf("${", lastIndex)) != -1) { int endIndex = text.indexOf('}', startIndex); //XXX internal error here if (endIndex == -1) break; buf.append(text.substring(lastIndex, startIndex)); String key = text.substring(startIndex+2, endIndex); lastIndex = endIndex+1; Object replaceText = map.get(key); //System.out.println("key: " + key + " -> " + replaceText); if (replaceText == null) replaceText = "NOT_FOUND"; buf.append(replaceText.toString()); } buf.append(text.substring(lastIndex)); return buf.toString(); } public static String applyProperties(String text) { return applyProperties(text, context.getProperties()); } protected String loadText(String filename) { String fullname = Installer.RESOURCE_DIR + "/" + filename; //context.installer.getPrefix() + "-" + filename; try { String text = stringFromStream(getClass().getResourceAsStream(fullname)); text = styleHeader + removeHead(text); text = applyProperties(text); //System.out.println(text); return text; } catch (IOException e) { context.handleException(e); return ""; } } protected JEditorPane makeHTMLArea(String filename) { JEditorPane editorPane = new JEditorPane("text/html", loadText(filename)); /* { public void paint(Graphics g) { Graphics2D g2 = (Graphics2D)g; g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); super.paint(g2); } };*/ editorPane.setEditable(false); editorPane.setOpaque(false); return editorPane; } protected void setHTMLArea(JEditorPane pane, String filename) { pane.setText(loadText(filename)); } protected JPanel makeLocationBox(String label, JTextField textField, JButton browseButton) { JPanel box = new JPanel(); box.setLayout(new BoxLayout(box, BoxLayout.X_AXIS)); textField.setFont(context.getFont()); textField.selectAll(); box.add(textField); box.add(browseButton); Border border = BorderFactory.createTitledBorder(label); final int INSET = 8; border = new CompoundBorder(border, new EmptyBorder(1, INSET, INSET, INSET)); box.setBorder(border); return box; } private JPanel panel = null; public JPanel getPanel() { if (panel == null) { panel = makePanel(); panel.setBorder(BorderFactory.createEmptyBorder(0, 10, 0, 10)); } return panel; } protected void setListener(JButton button, ActionListener listener) { if (listener == null) { button.setEnabled(false); } else { button.addActionListener(listener); } } protected Component makeButtons(Installer installer) { JPanel panel = new JPanel(new FlowLayout(FlowLayout.RIGHT)); backButton = new JButton("Back"); setListener(backButton, installer.makeBackAction(this)); panel.add(backButton); nextButton = new JButton("Next"); setListener(nextButton, installer.makeNextAction(this)); panel.add(nextButton); //.setDefaultCapable(true); JLabel space = new JLabel(); space.setPreferredSize(new Dimension(20, 0)); panel.add(space); cancelButton = new JButton("Cancel"); setListener(cancelButton, installer.makeCancelAction(this)); panel.add(cancelButton); return panel; } private Component buttons = null; public Component getButtons() { if (buttons == null) { buttons = makeButtons(context.installer); //buttons.setBorder(BorderFactory.createEmptyBorder(0, 10, 0, 10)); } context.installer.frame.getRootPane().setDefaultButton(nextButton); return buttons; } public void finish() { if (Options.forceError2) { throw new RuntimeException("forced error2 for testing purposes"); } } public void run() {} } class IntroPane extends WizardPane { public JPanel makePanel() { Component text = makeHTMLArea("intro.html"); JPanel panel = new JPanel(new BorderLayout()); panel.add(text); return panel; } } class FinishPane extends WizardPane { public JPanel makePanel() { Component text = makeHTMLArea("finish.html"); JPanel panel = new JPanel(new BorderLayout()); panel.add(text); finalActions(); return panel; } public Component makeButtons(Installer installer) { Component ret = super.makeButtons(installer); nextButton.setText("Finish"); nextButton.setEnabled(true); nextButton.addActionListener(installer.makeFinishAction(this)); backButton.setEnabled(false); cancelButton.setEnabled(false); return ret; } public void finalActions() { } } class LocationPane extends WizardPane implements ActionListener { //XXX need more sophisticated default location finding //XXX would like to find the place they last chose... public String getDefaultLocation() { if (context.onWindows()) { //XXX hard-coded majorminor version needs to be fixed by 1.1 release return "c:\\aspectj1.2"; } else { return new File(System.getProperty("user.home"), "aspectj1.2").getAbsolutePath(); } } protected JTextField location; public JPanel makePanel() { Component text = makeHTMLArea("location.html"); location = new JTextField(getDefaultLocation()); JButton browse = new JButton("Browse..."); browse.addActionListener(this); JPanel locationBox = makeLocationBox("installation directory", location, browse); GridBagLayout bag = new GridBagLayout(); GridBagConstraints c = new GridBagConstraints(); JPanel panel = new JPanel(bag); c.fill = GridBagConstraints.BOTH; c.weightx = 1.0; c.gridwidth = GridBagConstraints.REMAINDER; bag.setConstraints(text, c); panel.add(text); c.weighty = 1.0; c.fill = GridBagConstraints.HORIZONTAL; c.gridwidth = GridBagConstraints.REMAINDER; bag.setConstraints(locationBox, c); panel.add(locationBox); //XXX set next button to read install //context.nextButton.setText("Install"); return panel; } public Component makeButtons(Installer installer) { Component ret = super.makeButtons(installer); nextButton.setText("Install"); return ret; } public void actionPerformed(ActionEvent e) { JFileChooser chooser = new JFileChooser(); // { // public void approveSelection() { // System.out.println("approved selection"); // } //}; //field.getText()); chooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES); int returnVal = chooser.showDialog(location, "Select"); if(returnVal == JFileChooser.APPROVE_OPTION) { File file = chooser.getSelectedFile(); if (!file.isDirectory()) file = file.getParentFile(); String name = file.getPath(); location.setText(name); location.selectAll(); } } /** * Override to do any additional checks. */ protected void verify() {} public void finish() { verify(); context.setOutputDir(new File(location.getText())); } } class ConfigureLauncherPane extends WizardPane { /* //XXX check that the returned file is valid public String getDefaultJavaLocation() { String name = "java"; if (context.onWindows()) name += ".exe"; if (Options.verbose) { System.out.println("java.home: " + System.getProperty("java.home")); System.out.println(" java: " + new File(new File(System.getProperty("java.home"), "bin"), name)); System.out.println(" java: " + new File(new File(System.getProperty("java.home"), "bin"), name).getPath()); } return new File(new File(System.getProperty("java.home"), "bin"), name).getPath(); } */ public static String getDefaultJavaHomeLocation() { if (!Options.forceHandConfigure) { File javaHome = findJavaHome(); if (javaHome != null) return javaHome.getPath(); } return null; } public void chooseFile(JTextField field) { JFileChooser chooser = new JFileChooser(); //field.getText()); chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); int returnVal = chooser.showDialog(field, "Select"); if(returnVal == JFileChooser.APPROVE_OPTION) { String name = chooser.getSelectedFile().getPath(); field.setText(name); field.selectAll(); } } public ActionListener makeJavaLocationBrowseListener() { return new ActionListener() { public void actionPerformed(ActionEvent e) { chooseFile(javaLocation); } }; } // public ActionListener makeToolsJarLocationBrowseListener() { // return new ActionListener() { // public void actionPerformed(ActionEvent e) { // chooseFile(toolsJarLocation); // } // }; // } private JTextField javaLocation; //private JTextField toolsJarLocation; public JPanel makePanel() { String javaPath = getDefaultJavaHomeLocation(); //String toolsJarPath = getDefaultToolsJarLocation(); Component text; if (javaPath == null) { javaPath = "<java home not found>"; text = makeHTMLArea("configure-hand.html"); } else { text = makeHTMLArea("configure-auto.html"); } javaLocation = new JTextField(javaPath); JButton javaLocationBrowse = new JButton("Browse..."); javaLocationBrowse.addActionListener(makeJavaLocationBrowseListener()); JPanel javaLocationBox = makeLocationBox("java home directory", javaLocation, javaLocationBrowse); // toolsJarLocation = new JTextField(toolsJarPath); // JButton toolsJarLocationBrowse = new JButton("Browse..."); // toolsJarLocationBrowse.addActionListener(makeToolsJarLocationBrowseListener()); // JPanel toolsJarLocationBox = makeLocationBox("full path to tools.jar", toolsJarLocation, toolsJarLocationBrowse); GridBagLayout bag = new GridBagLayout(); GridBagConstraints c = new GridBagConstraints(); JPanel panel = new JPanel(bag); c.fill = GridBagConstraints.BOTH; c.weightx = 1.0; c.weighty = 1.0; //c.ipady = 10; c.gridwidth = GridBagConstraints.REMAINDER; bag.setConstraints(text, c); panel.add(text); c.weighty = 0.0; //c.fill = GridBagConstraints.VERTICAL; bag.setConstraints(javaLocationBox, c); panel.add(javaLocationBox); // c.weighty = 0.25; // JLabel space = new JLabel(); // bag.setConstraints(space, c); // panel.add(space); // c.weighty = 0.0; // bag.setConstraints(toolsJarLocationBox, c); // panel.add(toolsJarLocationBox); c.weighty = 0.5; JLabel space = new JLabel(); bag.setConstraints(space, c); panel.add(space); return panel; } public void finish() { context.javaPath = new File(javaLocation.getText()); // context.toolsJarPath = new File(toolsJarLocation.getText()); //XXX need much more work on helping the user get these paths right // if (context.javaPath.isDirectory()) { // context.javaPath = new File(context.javaPath, "java"); // } // if (context.toolsJarPath.isDirectory()) { // context.toolsJarPath = new File(context.toolsJarPath, "tools.jar"); // } } //XXX add user.home to prefixes in a rational way public static final String[] windowsPaths = { "c:\\jdk", "c:\\apps\\jdk", "${user.home}\\jdk" }; public static final String[] unixPaths = { "/usr/local/bin/jdk", "/usr/bin/jdk", "/usr/bin/jdk", "${user.home}/jdk" }; public static final String[] suffixes = { "1.3.1", "1.3", "1.2", "13", "12", "2", "", "1.4" }; public static boolean windows = true; public static boolean isLegalJavaHome(File home) { File bin = new File(home, "bin"); return new File(bin, "java").isFile() || new File(bin, "java.exe").isFile(); } public static boolean isLegalJDKHome(File home) { File lib = new File(home, "lib"); return new File(lib, "tools.jar").isFile(); } public static File findJavaHome() { String s = System.getProperty("java.home"); File javaHome = null; if (s != null) { javaHome = new File(s); if (isLegalJDKHome(javaHome)) return javaHome; if (isLegalJavaHome(javaHome)) { File parent = javaHome.getParentFile(); if (parent != null && isLegalJDKHome(parent)) return parent; } } String[] paths; if (windows) { paths = windowsPaths; } else { paths = unixPaths; } for (int suffixIndex = 0; suffixIndex < suffixes.length; suffixIndex++) { String suffix = suffixes[suffixIndex]; for (int prefixIndex = 0; prefixIndex < paths.length; prefixIndex++) { String prefix = paths[prefixIndex]; prefix = applyProperties(prefix); File test = new File(prefix+suffix); if (isLegalJavaHome(test)) { if (isLegalJDKHome(test)) return test; else if (javaHome == null) javaHome = test; } } } return javaHome; } } class InstallPane extends WizardPane { private JProgressBar progressBar; private JTextField progressItem; private JEditorPane message; private boolean makeLaunchScripts = false; public InstallPane(boolean makeLaunchScripts) { this.makeLaunchScripts = makeLaunchScripts; } public JPanel makePanel() { message = makeHTMLArea("install-start.html"); progressBar = new JProgressBar(); progressItem = new JTextField(); progressItem.setOpaque(false); progressItem.setFont(context.getFont()); progressItem.setEditable(false); GridBagLayout bag = new GridBagLayout(); GridBagConstraints c = new GridBagConstraints(); JPanel panel = new JPanel(bag); c.fill = GridBagConstraints.BOTH; c.weightx = 1.0; c.weighty = 1.0; //c.ipady = 10; c.gridwidth = GridBagConstraints.REMAINDER; bag.setConstraints(message, c); panel.add(message); c.weighty = 0.0; //c.fill = GridBagConstraints.VERTICAL; bag.setConstraints(progressBar, c); panel.add(progressBar); c.weighty = 0.1; JLabel space = new JLabel(); bag.setConstraints(space, c); panel.add(space); c.weighty = 0.0; bag.setConstraints(progressItem, c); panel.add(progressItem); c.weighty = 0.5; space = new JLabel(); bag.setConstraints(space, c); panel.add(space); return panel; } class InstallRunner implements Runnable { public InstallRunner() {} public void run() { try { new CurrentJarUnpacker(context, InstallPane.this).unpack(Installer.RESOURCE_DIR + "/contents.txt", context.getOutputDir()); if (makeLaunchScripts) { LaunchScriptMaker lsm = new LaunchScriptMaker(context); lsm.writeScript("ajc"); lsm.writeScript("ajdoc"); //lsm.writeScript("ajdb"); lsm.writeScript("ajbrowser"); // While the experimental aj(.bat) launch script is // shipped in the docs path lsm.writeAJLaunchScript(); } if (hasGui()) { progressBar.setValue(100); setHTMLArea(message, "install-finish.html"); } } catch (IOException ioe) { context.handleException(ioe); } if (hasGui()) { cancelButton.setEnabled(false); nextButton.setEnabled(true); } } } public Component makeButtons(Installer installer) { Component ret = super.makeButtons(installer); //nextButton.setText("Finish"); nextButton.setEnabled(false); //nextButton.addActionListener(installer.makeFinishAction(this)); backButton.setEnabled(false); return ret; } public void run() { Thread thread = new Thread(new InstallRunner()); thread.start(); } public void progressMessage(final String message) { if (!hasGui()) { return; } try { //XXX performance tradeoff between invokeAndWait and invokeLater... SwingUtilities.invokeAndWait(new Runnable() { public void run() { progressItem.setText(message); } }); } catch (InvocationTargetException ite) { context.handleException(ite.getTargetException()); } catch (InterruptedException ie) { } } int nBytes = 0; int bytesWritten = 0; public void progressBytesWritten(int bytes) { if (!hasGui()) { return; } bytesWritten += bytes; final int PCT = (int)(100.0 * bytesWritten / nBytes); //System.out.println("bytesWritten: " + bytesWritten); try { //XXX performance tradeoff between invokeAndWait and invokeLater... SwingUtilities.invokeAndWait(new Runnable() { public void run() { progressBar.setValue(PCT); } }); } catch (InvocationTargetException ite) { context.handleException(ite.getTargetException()); } catch (InterruptedException ie) { } } } class CurrentJarUnpacker { InstallContext context; InstallPane installPane; public CurrentJarUnpacker(InstallContext context, InstallPane installPane) { this.context = context; this.installPane = installPane; } public File makeOutputFile(String name, File outputFile) { int index; int lastIndex = 0; while ( (index = name.indexOf('/', lastIndex)) != -1) { outputFile = new File(outputFile, name.substring(lastIndex, index)); lastIndex = index + 1; } return new File(outputFile, name.substring(lastIndex)); } final static int BUF_SIZE = 4096; public void writeStream(InputStream zis, File outputFile) throws IOException { if (outputFile.exists()) { if (!context.shouldOverwrite(outputFile)) return; } installPane.progressMessage("writing " + outputFile.getAbsolutePath()); outputFile.getParentFile().mkdirs(); if (context.isTextFile(outputFile)) { writeTextStream(zis, outputFile); } else { writeBinaryStream(zis, outputFile); } } public void writeBinaryStream(InputStream zis, File outputFile) throws IOException { byte[] buffer = new byte[BUF_SIZE]; int nRead = 0; OutputStream os = new BufferedOutputStream(new FileOutputStream(outputFile)); while ( (nRead = zis.read(buffer)) != -1) { os.write(buffer, 0, nRead); installPane.progressBytesWritten(nRead); } os.close(); } public void writeTextStream(InputStream zis, File outputFile) throws IOException { BufferedWriter os = new BufferedWriter(new FileWriter(outputFile)); BufferedReader r = new BufferedReader(new InputStreamReader(zis, "US-ASCII")); String l; while ( (l = r.readLine()) != null) { os.write(l); os.newLine(); installPane.progressBytesWritten(l.length() + 1); } os.close(); } public void writeResource(String name, File outputDir) throws IOException { File outputFile = makeOutputFile(name, outputDir); //System.out.println("finding name: " + name); writeStream(getClass().getResourceAsStream("/" + name), outputFile); } public void unpack(String contentsName, File outputDir) throws IOException { URL url = getClass().getResource(contentsName); InputStream stream = url.openStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(stream, "US-ASCII")); String line = reader.readLine(); installPane.nBytes = Integer.parseInt(line); while ( (line = reader.readLine()) != null) { writeResource(line, outputDir); } installPane.progressMessage("done writing"); } } class LaunchScriptMaker { static final String toolsPackage = "org.aspectj.tools"; InstallContext context; public LaunchScriptMaker(InstallContext context) { this.context = context; } /** * */ public void writeAJLaunchScript() throws IOException { String name = "aj"; if (!context.onUnix()) { if (context.onOS2()) { name += ".cmd"; } else if (context.onWindows()) { name += ".bat"; } } File destDir = new File(context.getOutputDir(), "doc/examples/ltw"); destDir.mkdirs(); File file = new File(destDir, name); PrintStream ps = getPrintStream(file); writeAJLaunchScriptContent(ps); ps.close(); if (context.onUnix()) { makeExecutable(file); } } /** * @param ps */ private void writeAJLaunchScriptContent(PrintStream ps) { if (context.onUnix()) { writeUnixHeader(ps); writeAJUnixLaunchLine(ps); } else { writeWindowsHeader(ps); writeAJWindowsLaunchLine(ps); } } /** * @param ps */ private void writeAJWindowsLaunchLine(PrintStream ps) { ps.println( "\"%JAVA_HOME%\\bin\\java\" -classpath " + "\"%ASPECTJ_HOME%\\lib\\aspectjtools.jar\"" + " \"-Djava.system.class.loader=org.aspectj.weaver.WeavingURLClassLoader\"" + " \"-Daj.class.path=%ASPECTPATH%;%CLASSPATH%\"" + " \"-Daj.aspect.path=%ASPECTPATH%\"" + " " + makeScriptArgs(false)); } /** * @param ps */ private void writeAJUnixLaunchLine(PrintStream ps) { String sep = File.pathSeparator; ps.println( "\"$JAVA_HOME/bin/java\" -classpath" + " \"$ASPECTJ_HOME/lib/aspectjtools.jar\"" + " \"-Djava.system.class.loader=org.aspectj.weaver.WeavingURLClassLoader\"" + " \"-Daj.class.path=$ASPECTPATH:$CLASSPATH\"" + " \"-Daj.aspect.path=$ASPECTPATH\"" + " " + makeScriptArgs(true)); } private void writeWindowsHeader(PrintStream ps) { ps.println("@echo off"); ps.println("REM This file generated by AspectJ installer"); ps.println("REM Created on "+new java.util.Date()+" by "+ System.getProperty("user.name")); ps.println(""); ps.println("if \"%JAVA_HOME%\" == \"\" set JAVA_HOME=" + context.javaPath.getAbsolutePath()); ps.println("if \"%ASPECTJ_HOME%\" == \"\" set ASPECTJ_HOME=" + context.getOutputDir().getAbsolutePath()); ps.println(""); ps.println("if exist \"%JAVA_HOME%\\bin\\java.exe\" goto haveJava"); ps.println("if exist \"%JAVA_HOME%\\bin\\java.bat\" goto haveJava"); ps.println("if exist \"%JAVA_HOME%\\bin\\java\" goto haveJava"); ps.println("echo java does not exist as %JAVA_HOME%\\bin\\java"); ps.println("echo please fix the JAVA_HOME environment variable"); ps.println(":haveJava"); } private void writeWindowsLaunchLine(String className, PrintStream ps) { ps.println("\"%JAVA_HOME%\\bin\\java\" -classpath " + // "\"%ASPECTJ_HOME%\\lib\\aspectjtools.jar;%CLASSPATH%\""+ "\"%ASPECTJ_HOME%\\lib\\aspectjtools.jar;%JAVA_HOME%\\lib\\tools.jar;%CLASSPATH%\"" + " -Xmx64M " + className + //" -defaultClasspath " + "\"%CLASSPATH%\"" + " " + makeScriptArgs(false)); } private void writeUnixHeader(PrintStream ps) { File binsh = new File(File.separator+"bin", "sh"); if (binsh.canRead()) { ps.println("#!"+binsh.getPath()); } ps.println("# This file generated by AspectJ installer"); ps.println("# Created on "+new java.util.Date()+" by "+ System.getProperty("user.name")); ps.println(""); ps.println("if [ \"$JAVA_HOME\" = \"\" ] ; then JAVA_HOME=" + quote(true, false, context.javaPath.getAbsolutePath())); ps.println("fi"); ps.println("if [ \"$ASPECTJ_HOME\" = \"\" ] ; then ASPECTJ_HOME=" + quote(true, false, context.getOutputDir())); ps.println("fi"); ps.println(""); } private void writeUnixLaunchLine( String className, PrintStream ps) { String sep = File.pathSeparator; ps.println( "\"$JAVA_HOME/bin/java\" -classpath " + "\"$ASPECTJ_HOME/lib/aspectjtools.jar" + sep + "$JAVA_HOME/lib/tools.jar" + sep + "$CLASSPATH\"" + " -Xmx64M " + className + " " + makeScriptArgs(true)); } private void makeExecutable(File file) { try { Runtime curRuntime = Runtime.getRuntime(); curRuntime.exec("chmod 777 " + quote(true, false, file)); } catch (Throwable t) { // ignore any errors that occur while trying to chmod } } private String makeScriptArgs(boolean unixStyle) { if (unixStyle) { return "\"$@\""; } else if (context.onWindowsPro()) { return "%*"; } else { return "%1 %2 %3 %4 %5 %6 %7 %8 %9"; } } private String quote(boolean unixStyle, boolean forceQuotes, File file) { return quote(unixStyle, forceQuotes, file.getAbsolutePath()); } private String quote(boolean unixStyle, boolean forceQuotes, String s) { if (context.onWindows() && unixStyle) { s = s.replace('\\', '/'); } if (!forceQuotes && s.indexOf(' ') == -1) return s; return "\""+s+"\""; } private File makeScriptFile(String name, boolean unixStyle) throws IOException { if (!unixStyle) { if (context.onOS2()) { name += ".cmd"; } else if (context.onWindows()) { name += ".bat"; } } //XXX probably want a context.getOutputBinDir() File bindir = new File(context.getOutputDir(), "bin"); bindir.mkdirs(); File file = new File(bindir, name); return file; } private PrintStream getPrintStream(File file) throws IOException { return new PrintStream(new BufferedOutputStream(new FileOutputStream(file))); } String makeClassPathVar(boolean unixStyle) { if (unixStyle) { return "$CLASSPATH"; } else { return "%CLASSPATH%"; } } public String makeClassPath(boolean unixStyle) throws IOException { return context.toolsJarPath.getAbsolutePath() + File.pathSeparator + //XXX want context.getOutputLibDir() new File(new File(context.getOutputDir(), "lib"), "aspectjtools.jar").getAbsolutePath() + File.pathSeparator + makeClassPathVar(unixStyle); } public void writeScript(String className, PrintStream ps, boolean unixStyle) throws IOException { if (unixStyle) { writeUnixHeader(ps); writeUnixLaunchLine(className, ps); } else { writeWindowsHeader(ps); writeWindowsLaunchLine(className, ps); } /* ps.print(quote(unixStyle, false, context.javaPath.getAbsolutePath())); ps.print(" "); ps.print("-classpath "); ps.print(quote(unixStyle, true, makeClassPath(unixStyle))); ps.print(" "); ps.print("-Xmx64M "); ps.print(className); ps.print(" "); ps.print(makeScriptArgs(unixStyle)); */ } public void writeScript(String className, boolean unixStyle) throws IOException { File file = makeScriptFile(className, unixStyle); if (!checkExistingFile(file)) return; PrintStream ps = getPrintStream(file); writeScript(toolsPackage + '.' + className + ".Main", ps, unixStyle); ps.close(); //??? unixStyle vs. onUnix() if (context.onUnix()) makeExecutable(file); } public boolean checkExistingFile(File file) { if (!file.exists()) return true; return context.shouldOverwrite(file); } /* final static String OVERWRITE_MESSAGE = "Overwrite launch script "; final static String OVERWRITE_TITLE = "Overwrite?"; final static String[] OVERWRITE_OPTIONS = { "Yes", "No", "Yes to all", "No to all" }; final static int OVERWRITE_YES = 0; final static int OVERWRITE_NO = 1; final static int OVERWRITE_ALL = 2; final static int OVERWRITE_NONE = 3; int overwriteState = OVERWRITE_NO; boolean shouldOverwrite(final File file) { if (overwriteState == OVERWRITE_ALL) return true; if (overwriteState == OVERWRITE_NONE) return false; try { SwingUtilities.invokeAndWait(new Runnable() { public void run() { int ret = JOptionPane.showOptionDialog(context.installer.frame, OVERWRITE_MESSAGE+file.getPath(), OVERWRITE_TITLE, JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, null, OVERWRITE_OPTIONS, OVERWRITE_OPTIONS[OVERWRITE_YES]); overwriteState = ret; } }); } catch (InvocationTargetException ite) { context.handleException(ite.getTargetException()); } catch (InterruptedException ie) { } return overwriteState == OVERWRITE_YES || overwriteState == OVERWRITE_ALL; } */ public void writeScript(String className) throws IOException { writeScript(className, true); if (context.onWindows()) { writeScript(className, false); } } } class JarUnpacker { InstallContext context; InstallPane installPane; public JarUnpacker(InstallContext context, InstallPane installPane) { this.context = context; this.installPane = installPane; } public File makeOutputFile(String name, File outputFile) { int index; int lastIndex = 0; while ( (index = name.indexOf('/', lastIndex)) != -1) { outputFile = new File(outputFile, name.substring(lastIndex, index)); lastIndex = index + 1; } return new File(outputFile, name.substring(lastIndex)); } final static int BUF_SIZE = 4096; public void writeStream(ZipInputStream zis, File outputFile) throws IOException { if (outputFile.exists()) { if (!context.shouldOverwrite(outputFile)) return; } installPane.progressMessage("writing " + outputFile.getAbsolutePath()); outputFile.getParentFile().mkdirs(); if (context.isTextFile(outputFile)) { writeTextStream(zis, outputFile); } else { writeBinaryStream(zis, outputFile); } } public void writeBinaryStream(ZipInputStream zis, File outputFile) throws IOException { byte[] buffer = new byte[BUF_SIZE]; int nRead = 0; OutputStream os = new BufferedOutputStream(new FileOutputStream(outputFile)); while ( (nRead = zis.read(buffer)) != -1) { os.write(buffer, 0, nRead); installPane.progressBytesWritten(nRead); } os.close(); } public void writeTextStream(ZipInputStream zis, File outputFile) throws IOException { BufferedWriter os = new BufferedWriter(new FileWriter(outputFile)); BufferedReader r = new BufferedReader(new InputStreamReader(zis, "US-ASCII")); String l; while ( (l = r.readLine()) != null) { os.write(l); os.newLine(); installPane.progressBytesWritten(l.length() + 1); } os.close(); } public void writeEntry(ZipInputStream zis, ZipEntry entry, File outputDir) throws IOException { if (entry.isDirectory()) return; String name = entry.getName(); File outputFile = makeOutputFile(name, outputDir); writeStream(zis, outputFile); } public void unpack(String jarName, File outputDir) throws IOException { URL url = getClass().getResource(jarName); InputStream stream = url.openStream(); ZipInputStream zis = new ZipInputStream(stream); // int i = 0; ZipEntry entry; while ((entry = zis.getNextEntry()) != null) { // final String name = entry.getName(); writeEntry(zis, entry, outputDir); // } installPane.progressMessage("done writing"); } }
68,494
Bug 68494 ajdoc does not support .aj files
In addition to accepting .java source files ajdoc needs to accept .aj files.
resolved fixed
3707411
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2004-06-24T22:11:53Z
2004-06-24T15:13:20Z
ajdoc/src/org/aspectj/tools/ajdoc/Main.java
/* ******************************************************************* * Copyright (c) 1999-2001 Xerox Corporation, * 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Common Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * Xerox/PARC initial implementation * Mik Kersten port to AspectJ 1.1+ code base * ******************************************************************/ package org.aspectj.tools.ajdoc; import java.io.*; import java.util.*; import java.io.FileFilter; import org.aspectj.bridge.Version; import org.aspectj.util.FileUtil; /** * This is an old implementation of ajdoc that does not use an OO style. However, it * does the job, and should serve to evolve a lightweight ajdoc implementation until * we can make a properly extended javadoc implementation. * * @author Mik Kersten */ public class Main implements Config { private static final String FAIL_MESSAGE = "> compile failed, exiting ajdoc"; static SymbolManager symbolManager = null; /** Command line options. */ static Vector options; /** Options to pass to ajc. */ static Vector ajcOptions; /** All of the files to be processed by ajdoc. */ static Vector filenames; /** List of files to pass to javadoc. */ static Vector fileList; /** List of packages to pass to javadoc. */ static Vector packageList; /** Default to package visiblity. */ static String docModifier = "package"; static Vector sourcepath; static boolean verboseMode = false; static boolean packageMode = false; static boolean authorStandardDocletSwitch = false; static boolean versionStandardDocletSwitch = false; static File rootDir = null; static Hashtable declIDTable = new Hashtable(); static String docDir = "."; private static boolean deleteTempFilesOnExit = true; private static boolean aborted = false; public static void clearState() { symbolManager = null; options = new Vector(); ajcOptions = new Vector(); filenames = new Vector(); fileList= new Vector(); packageList = new Vector(); docModifier = "package"; sourcepath = new Vector(); verboseMode = false; packageMode = false; rootDir = null; declIDTable = new Hashtable(); docDir = "."; aborted = false; deleteTempFilesOnExit = true; } public static void main(String[] args) { clearState(); // if (!JavadocRunner.has14ToolsAvailable()) { // System.err.println("ajdoc requires a JDK 1.4 or later tools jar - exiting"); // aborted = true; // return; // } // STEP 1: parse the command line and do other global setup sourcepath.addElement("."); // add the current directory to the classapth parseCommandLine(args); rootDir = getRootDir(); symbolManager = SymbolManager.getDefault(); File[] inputFiles = new File[filenames.size()]; File[] signatureFiles = new File[filenames.size()]; try { // create the workingdir if it doesn't exist if ( !(new File( Config.WORKING_DIR ).isDirectory()) ) { File dir = new File( Config.WORKING_DIR ); dir.mkdir(); if (deleteTempFilesOnExit) dir.deleteOnExit(); } for (int i = 0; i < filenames.size(); i++) { inputFiles[i] = findFile((String)filenames.elementAt(i)); //signatureFiles[i] = createSignatureFile(inputFiles[i]); } // PHASE 0: call ajc ajcOptions.addElement("-noExit"); ajcOptions.addElement("-XjavadocsInModel"); // TODO: wrong option to force model gen ajcOptions.addElement("-d"); ajcOptions.addElement(rootDir.getAbsolutePath()); String[] argsToCompiler = new String[ajcOptions.size() + inputFiles.length]; int i = 0; for ( ; i < ajcOptions.size(); i++ ) { argsToCompiler[i] = (String)ajcOptions.elementAt(i); } for ( int j = 0; j < inputFiles.length; j++) { argsToCompiler[i] = inputFiles[j].getAbsolutePath(); //System.out.println(">> file to ajc: " + inputFiles[j].getAbsolutePath()); i++; } // System.out.println(Arrays.asList(argsToCompiler)); System.out.println( "> Calling ajc..." ); CompilerWrapper.main(argsToCompiler); if (CompilerWrapper.hasErrors()) { System.out.println(FAIL_MESSAGE); aborted = true; return; } /* for (int ii = 0; ii < inputFiles.length; ii++) { String tempFP = inputFiles[ii].getAbsolutePath(); tempFP = tempFP.substring(0, tempFP.length()-4); tempFP += "ajsym"; System.out.println( ">> checking: " + tempFP); File tempF = new File(tempFP); if ( !tempF.exists() ) System.out.println( ">>> doesn't exist!" ); } */ for (int ii = 0; ii < filenames.size(); ii++) { signatureFiles[ii] = createSignatureFile(inputFiles[ii]); } // PHASE 1: generate Signature files (Java with DeclIDs and no bodies). System.out.println( "> Building signature files..." ); StubFileGenerator.doFiles(declIDTable, symbolManager, inputFiles, signatureFiles); // PHASE 2: let Javadoc generate HTML (with DeclIDs) System.out.println( "> Calling javadoc..." ); String[] javadocargs = null; if ( packageMode ) { int numExtraArgs = 2; if (authorStandardDocletSwitch) numExtraArgs++; if (versionStandardDocletSwitch) numExtraArgs++; javadocargs = new String[numExtraArgs + options.size() + packageList.size() + fileList.size() ]; javadocargs[0] = "-sourcepath"; javadocargs[1] = Config.WORKING_DIR; int argIndex = 2; if (authorStandardDocletSwitch) { javadocargs[argIndex] = "-author"; argIndex++; } if (versionStandardDocletSwitch) { javadocargs[argIndex] = "-version"; } //javadocargs[1] = getSourcepathAsString(); for (int k = 0; k < options.size(); k++) { javadocargs[numExtraArgs+k] = (String)options.elementAt(k); } for (int k = 0; k < packageList.size(); k++) { javadocargs[numExtraArgs+options.size() + k] = (String)packageList.elementAt(k); } for (int k = 0; k < fileList.size(); k++) { javadocargs[numExtraArgs+options.size() + packageList.size() + k] = (String)fileList.elementAt(k); } } else { javadocargs = new String[options.size() + signatureFiles.length]; for (int k = 0; k < options.size(); k++) { javadocargs[k] = (String)options.elementAt(k); } for (int k = 0; k < signatureFiles.length; k++) { javadocargs[options.size() + k] = signatureFiles[k].getCanonicalPath(); } } JavadocRunner.callJavadoc(javadocargs); //for ( int o = 0; o < inputFiles.length; o++ ) { // System.out.println( "file: " + inputFiles[o] ); //} // PHASE 3: add AspectDoc specific stuff to the HTML (and remove the DeclIDS). /** We start with the known HTML files (the ones that correspond directly to the * input files.) As we go along, we may learn that Javadoc split one .java file * into multiple .html files to handle inner classes or local classes. The html * file decorator picks that up. */ System.out.println( "> Decorating html files..." ); HtmlDecorator.decorateHTMLFromInputFiles(declIDTable, rootDir, symbolManager, inputFiles, docModifier); System.out.println( "> Removing generated tags (this may take a while)..." ); removeDeclIDsFromFile("index-all.html", true); removeDeclIDsFromFile("serialized-form.html", true); if (packageList.size() > 0) { for (int p = 0; p < packageList.size(); p++) { removeDeclIDsFromFile(((String)packageList.elementAt(p)).replace('.','/') + Config.DIR_SEP_CHAR + "package-summary.html", true); } } else { File[] files = FileUtil.listFiles(rootDir, new FileFilter() { public boolean accept(File f) { return f.getName().equals("package-summary.html"); } }); for (int j = 0; j < files.length; j++) { removeDeclIDsFromFile(files[j].getAbsolutePath(), false); } } System.out.println( "> Finished." ); } catch (Throwable e) { handleInternalError(e); exit(-2); } } private static void removeDeclIDsFromFile(String filename, boolean relativePath) { // Remove the decl ids from "index-all.html" File indexFile; if (relativePath) { indexFile = new File(docDir + Config.DIR_SEP_CHAR + filename); } else { indexFile = new File(filename); } try { if ( indexFile.exists() ) { BufferedReader indexFileReader = new BufferedReader( new FileReader( indexFile ) ); String indexFileBuffer = ""; String line = indexFileReader.readLine(); while ( line != null ) { int indexStart = line.indexOf( Config.DECL_ID_STRING ); int indexEnd = line.indexOf( Config.DECL_ID_TERMINATOR ); if ( indexStart != -1 && indexEnd != -1 ) { line = line.substring( 0, indexStart ) + line.substring( indexEnd+Config.DECL_ID_TERMINATOR.length() ); } indexFileBuffer += line; line = indexFileReader.readLine(); } FileOutputStream fos = new FileOutputStream( indexFile ); fos.write( indexFileBuffer.getBytes() ); } } catch (IOException ioe) { // be siltent } } /** * If the file doesn't exist on the specified path look for it in all the other * paths specified by the "sourcepath" option. */ static File findFile( String filename ) throws IOException { return new File( filename ); /* File file = new File(filename); if (file.exists()) { return file; } else { for ( int i = 0; i < sourcePath.size(); i++ ) { File currPath = new File((String)sourcePath.elementAt(i)); File currFile = new File(currPath + "/" + filename); // !!! if ( file.exists()) { return file; } } } throw new IOException("couldn't find source file: " + filename); */ } static Vector getSourcePath() { Vector sourcePath = new Vector(); boolean found = false; for ( int i = 0; i < options.size(); i++ ) { String currOption = (String)options.elementAt(i); if (found && !currOption.startsWith("-")) { sourcePath.add(currOption); } if (currOption.equals("-sourcepath")) { found = true; } } return sourcePath; } static File getRootDir() { File rootDir = new File( "." ); for ( int i = 0; i < options.size(); i++ ) { if ( ((String)options.elementAt(i)).equals( "-d" ) ) { rootDir = new File((String)options.elementAt(i+1)); if ( !rootDir.exists() ) { rootDir.mkdir(); // System.out.println( "Destination directory not found: " + // (String)options.elementAt(i+1) ); // System.exit( -1 ); } } } return rootDir; } static File createSignatureFile(File inputFile) throws IOException { String packageName = StructureUtil.getPackageDeclarationFromFile(inputFile); String filename = ""; if ( packageName != null ) { String pathName = Config.WORKING_DIR + '/' + packageName.replace('.', '/'); File packageDir = new File(pathName); if ( !packageDir.exists() ) { packageDir.mkdirs(); if (deleteTempFilesOnExit) packageDir.deleteOnExit(); } //verifyPackageDirExists(packageName, null); packageName = packageName.replace( '.','/' ); // !!! filename = Config.WORKING_DIR + Config.DIR_SEP_CHAR + packageName + Config.DIR_SEP_CHAR + inputFile.getName(); } else { filename = Config.WORKING_DIR + Config.DIR_SEP_CHAR + inputFile.getName(); } File signatureFile = new File( filename ); if (deleteTempFilesOnExit) signatureFile.deleteOnExit(); return signatureFile; } // static void verifyPackageDirExists( String packageName, String offset ) { // System.err.println(">>> name: " + packageName + ", offset: " + offset); // if ( packageName.indexOf( "." ) != -1 ) { // File tempFile = new File("c:/aspectj-test/d1/d2/d3"); // tempFile.mkdirs(); // String currPkgDir = packageName.substring( 0, packageName.indexOf( "." ) ); // String remainingPkg = packageName.substring( packageName.indexOf( "." )+1 ); // String filePath = null; // if ( offset != null ) { // filePath = Config.WORKING_DIR + Config.DIR_SEP_CHAR + // offset + Config.DIR_SEP_CHAR + currPkgDir ; // } // else { // filePath = Config.WORKING_DIR + Config.DIR_SEP_CHAR + currPkgDir; // } // File packageDir = new File( filePath ); // if ( !packageDir.exists() ) { // packageDir.mkdir(); // if (deleteTempFilesOnExit) packageDir.deleteOnExit(); // } // if ( remainingPkg != "" ) { // verifyPackageDirExists( remainingPkg, currPkgDir ); // } // } // else { // String filePath = null; // if ( offset != null ) { // filePath = Config.WORKING_DIR + Config.DIR_SEP_CHAR + offset + Config.DIR_SEP_CHAR + packageName; // } // else { // filePath = Config.WORKING_DIR + Config.DIR_SEP_CHAR + packageName; // } // File packageDir = new File( filePath ); // if ( !packageDir.exists() ) { // packageDir.mkdir(); // if (deleteTempFilesOnExit) packageDir.deleteOnExit(); // } // } // } /** * Can read Eclipse-generated single-line arg */ static void parseCommandLine(String[] args) { if (args.length == 0) { displayHelpAndExit( null ); } else if (args.length == 1 && args[0].startsWith("@")) { String argFile = args[0].substring(1); System.out.println("> Using arg file: " + argFile); BufferedReader br; try { br = new BufferedReader(new FileReader(argFile)); String line = ""; line = br.readLine(); StringTokenizer st = new StringTokenizer(line, " "); List argList = new ArrayList(); while(st.hasMoreElements()) { argList.add((String)st.nextElement()); } //System.err.println(argList); args = new String[argList.size()]; int counter = 0; for (Iterator it = argList.iterator(); it.hasNext(); ) { args[counter] = (String)it.next(); counter++; } } catch (FileNotFoundException e) { System.err.println("> could not read arg file: " + argFile); e.printStackTrace(); } catch (IOException ioe) { System.err.println("> could not read arg file: " + argFile); ioe.printStackTrace(); } } List vargs = new LinkedList(Arrays.asList(args)); parseArgs(vargs, new File( "." )); // !!! if (filenames.size() == 0) { displayHelpAndExit( "ajdoc: No packages or classes specified" ); } } static void setSourcepath(String arg) { sourcepath.clear(); arg = arg + File.pathSeparator; // makes things easier for ourselves StringTokenizer tokenizer = new StringTokenizer(arg, File.pathSeparator); while (tokenizer.hasMoreElements()) { sourcepath.addElement(tokenizer.nextElement()); } } static String getSourcepathAsString() { String cPath = ""; for (int i = 0; i < sourcepath.size(); i++) { cPath += (String)sourcepath.elementAt(i) + Config.DIR_SEP_CHAR + Config.WORKING_DIR; if (i != sourcepath.size()-1) { cPath += File.pathSeparator; } } return cPath; } static void parseArgs(List vargs, File currentWorkingDir) { boolean addNextAsOption = false; boolean addNextAsArgFile = false; boolean addNextToAJCOptions = false; boolean addNextAsDocDir = false; boolean addNextAsClasspath = false; boolean ignoreArg = false; // used for discrepancy betwen class/sourcepath in ajc/javadoc boolean addNextAsSourcePath = false; if ( vargs.size() == 0 ) { displayHelpAndExit( null ); } for (int i = 0; i < vargs.size() ; i++) { String arg = (String)vargs.get(i); ignoreArg = false; if ( addNextToAJCOptions ) { ajcOptions.addElement( arg ); addNextToAJCOptions = false; } if ( addNextAsDocDir ) { docDir = arg; addNextAsDocDir = false; } if ( addNextAsClasspath ) { addNextAsClasspath = false; } if ( addNextAsSourcePath ) { setSourcepath( arg ); addNextAsSourcePath = false; ignoreArg = true; } if ( arg.startsWith("@") ) { expandAtSignFile(arg.substring(1), currentWorkingDir); } else if ( arg.equals( "-argfile" ) ) { addNextAsArgFile = true; } else if ( addNextAsArgFile ) { expandAtSignFile(arg, currentWorkingDir); addNextAsArgFile = false; } else if (arg.equals("-d") ) { addNextAsOption = true; options.addElement(arg); addNextAsDocDir = true; } else if ( arg.equals( "-bootclasspath" ) ) { addNextAsOption = true; addNextToAJCOptions = true; options.addElement( arg ); ajcOptions.addElement( arg ); } else if ( arg.equals( "-source" ) ) { addNextAsOption = true; addNextToAJCOptions = true; addNextAsClasspath = true; options.addElement(arg); ajcOptions.addElement(arg); } else if ( arg.equals( "-classpath" ) ) { addNextAsOption = true; addNextToAJCOptions = true; addNextAsClasspath = true; options.addElement( arg ); ajcOptions.addElement( arg ); } else if ( arg.equals( "-sourcepath" ) ) { addNextAsSourcePath = true; //options.addElement( arg ); //ajcOptions.addElement( arg ); } else if (arg.equals("-XajdocDebug")) { deleteTempFilesOnExit = false; } else if (arg.equals("-use")) { System.out.println("> Ignoring unsupported option: -use"); } else if (arg.equals("-splitindex")) { // passed to javadoc } else if (arg.startsWith("-") || addNextAsOption) { if ( arg.equals( "-private" ) ) { docModifier = "private"; }else if ( arg.equals( "-package" ) ) { docModifier = "package"; } else if ( arg.equals( "-protected" ) ) { docModifier = "protected"; } else if ( arg.equals( "-public" ) ) { docModifier = "public"; } else if ( arg.equals( "-verbose" ) ) { verboseMode = true; } else if ( arg.equals( "-author" ) ) { authorStandardDocletSwitch = true; } else if ( arg.equals( "-version" ) ) { versionStandardDocletSwitch = true; } else if ( arg.equals( "-v" ) ) { System.out.println(getVersion()); exit(0); } else if ( arg.equals( "-help" ) ) { displayHelpAndExit( null ); } else if ( arg.equals( "-doclet" ) || arg.equals( "-docletpath" ) ) { System.out.println( "The doclet and docletpath options are not currently supported \n" + "since ajdoc makes assumptions about the behavior of the standard \n" + "doclet. If you would find this option useful please email us at: \n" + " \n" + " aspectj-dev@eclipse.org \n" + " \n" ); exit(0); } else if (arg.equals("-nonavbar") || arg.equals("-noindex")) { // pass through //System.err.println("> ignoring unsupported option: " + arg); } else if ( addNextAsOption ) { // pass through } else { System.err.println("> unrecognized argument: " + arg); displayHelpAndExit( null ); } options.addElement(arg); addNextAsOption = false; } else { // check if this is a file or a package // System.err.println(">>>>>>>> " + ); String entryName = arg.substring(arg.lastIndexOf(File.separator)+1); if ((arg.endsWith(".java") && entryName.indexOf('.') == entryName.length()-5) || arg.endsWith(".lst") && arg != null ) { File f = new File(arg); if (f.isAbsolute()) { filenames.addElement(arg); } else { filenames.addElement( currentWorkingDir + Config.DIR_SEP_CHAR + arg ); } fileList.addElement( arg ); } // PACKAGE MODE STUFF else if (!ignoreArg) { packageMode = true; packageList.addElement( arg ); arg = arg.replace( '.', '/' ); // !!! // do this for every item in the classpath for ( int c = 0; c < sourcepath.size(); c++ ) { String path = (String)sourcepath.elementAt(c) + Config.DIR_SEP_CHAR + arg; File pkg = new File(path); if ( pkg.isDirectory() ) { String[] files = pkg.list( new FilenameFilter() { public boolean accept( File dir, String name ) { int index1 = name.lastIndexOf( "." ); int index2 = name.length(); if ( (index1 >= 0 && index2 >= 0 ) && (name.substring(index1, index2).equals( ".java" ) ) ) { return true; } else { return false; } } } ); for ( int j = 0; j < files.length; j++ ) { filenames.addElement( (String)sourcepath.elementAt(c) + Config.DIR_SEP_CHAR + arg + Config.DIR_SEP_CHAR + files[j] ); } } else if (c == sourcepath.size() ) { // last element on classpath System.out.println( "ajdoc: No package, class, or source file " + "found named " + arg + "." ); } else { // didn't find it on that element of the classpath but that's ok } } } } } // set the default visibility as an option to javadoc option if ( !options.contains( "-private" ) && !options.contains( "-package" ) && !options.contains( "-protected" ) && !options.contains( "-public" ) ) { options.addElement( "-package" ); } } static void expandAtSignFile(String filename, File currentWorkingDir) { List result = new LinkedList(); File atFile = qualifiedFile(filename, currentWorkingDir); String atFileParent = atFile.getParent(); File myWorkingDir = null; if (atFileParent != null) myWorkingDir = new File(atFileParent); try { BufferedReader stream = new BufferedReader(new FileReader(atFile)); String line = null; while ( (line = stream.readLine()) != null) { // strip out any comments of the form # to end of line int commentStart = line.indexOf("//"); if (commentStart != -1) { line = line.substring(0, commentStart); } // remove extra whitespace that might have crept in line = line.trim(); // ignore blank lines if (line.length() == 0) continue; result.add(line); } } catch (IOException e) { System.err.println("Error while reading the @ file " + atFile.getPath() + ".\n" + e); System.exit( -1 ); } parseArgs(result, myWorkingDir); } static File qualifiedFile(String name, File currentWorkingDir) { name = name.replace('/', File.separatorChar); File file = new File(name); if (!file.isAbsolute() && currentWorkingDir != null) { file = new File(currentWorkingDir, name); } return file; } static void displayHelpAndExit(String message) { if (message != null) System.err.println(message); System.err.println(); System.err.println(Config.USAGE); exit(0); } static protected void exit(int value) { System.out.flush(); System.err.flush(); System.exit(value); } /* This section of code handles errors that occur during compilation */ static final String internalErrorMessage = "Please copy the following text into an email message and send it,\n" + "along with any additional information you can add to: \n" + " \n" + " aspectj-dev@eclipse.org \n" + " \n"; static public void handleInternalError(Throwable uncaughtThrowable) { System.err.println("An internal error occured in ajdoc"); System.err.println(internalErrorMessage); System.err.println(uncaughtThrowable.toString()); uncaughtThrowable.printStackTrace(); System.err.println(); } static String getVersion() { return "ajdoc version " + Version.text; } public static boolean hasAborted() { return aborted; } }
68,494
Bug 68494 ajdoc does not support .aj files
In addition to accepting .java source files ajdoc needs to accept .aj files.
resolved fixed
3707411
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2004-06-24T22:11:53Z
2004-06-24T15:13:20Z
ajdoc/src/org/aspectj/tools/ajdoc/StructureUtil.java
/* ******************************************************************* * Copyright (c) 2003 Contributors. * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Common Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * Mik Kersten initial implementation * ******************************************************************/ package org.aspectj.tools.ajdoc; import java.io.File; import java.util.Iterator; import java.util.List; import org.aspectj.asm.AsmManager; import org.aspectj.asm.IProgramElement; import org.aspectj.asm.IRelationship; /** * @author Mik Kersten */ public class StructureUtil { /** * @return null if a relationship of that kind is not found */ public static List/*IProgramElement*/ getTargets(IProgramElement node, IRelationship.Kind kind) { List relations = AsmManager.getDefault().getRelationshipMap().get(node); List targets = null; if (relations == null) return null; for (Iterator it = relations.iterator(); it.hasNext(); ) { IRelationship rtn = (IRelationship)it.next(); if (rtn.getKind().equals(kind)) { targets = rtn.getTargets(); } } return targets; } public static String getPackageDeclarationFromFile(File file) { IProgramElement fileNode = (IProgramElement)AsmManager.getDefault().getHierarchy().findElementForSourceFile(file.getAbsolutePath()); String packageName = ((IProgramElement)fileNode.getChildren().get(0)).getPackageName(); return packageName; } public static String genSignature(IProgramElement node) { StringBuffer sb = new StringBuffer(); String accessibility = node.getAccessibility().toString(); if (!accessibility.equals("package")) { sb.append(accessibility); sb.append(' '); } String modifiers = ""; for (Iterator modIt = node.getModifiers().iterator(); modIt.hasNext(); ) { modifiers += modIt.next() + " "; } if (node.getKind().equals(IProgramElement.Kind.METHOD) || node.getKind().equals(IProgramElement.Kind.FIELD)) { sb.append(node.getCorrespondingType()); sb.append(' '); } if (node.getKind().equals(IProgramElement.Kind.CLASS)) { sb.append("class "); } else if (node.getKind().equals(IProgramElement.Kind.INTERFACE)) { sb.append("interface "); } sb.append(node.getName()); if (node.getParameterTypes() != null ) { sb.append('('); for (int i = 0; i < node.getParameterTypes().size(); i++) { sb.append((String)node.getParameterTypes().get(i)); sb.append(' '); sb.append((String)node.getParameterNames().get(i)); if (i < node.getParameterTypes().size()-1) { sb.append(", "); } } sb.append(')'); } return sb.toString(); } public static boolean isAnonymous(IProgramElement node) { boolean isIntName = true; try { Integer.valueOf(node.getName()); } catch (NumberFormatException nfe) { // !!! using exceptions for logic, fix isIntName = false; } // System.err.println(">>>>>>>> " + node.getName()); return isIntName || node.getName().startsWith("new "); // return isIntName; // if (!isIntName) { // // return node.getName().startsWith("new "); // } else { // return false; // } } }
68,494
Bug 68494 ajdoc does not support .aj files
In addition to accepting .java source files ajdoc needs to accept .aj files.
resolved fixed
3707411
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2004-06-24T22:11:53Z
2004-06-24T15:13:20Z
ajdoc/src/org/aspectj/tools/ajdoc/StubFileGenerator.java
/* ******************************************************************* * Copyright (c) 1999-2001 Xerox Corporation, * 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Common Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * Xerox/PARC initial implementation * Mik Kersten port to AspectJ 1.1+ code base * ******************************************************************/ package org.aspectj.tools.ajdoc; import java.io.*; import java.util.Hashtable; import java.util.Iterator; import java.util.List; import org.aspectj.asm.AsmManager; import org.aspectj.asm.IProgramElement; /** * @author Mik Kersten */ class StubFileGenerator { static Hashtable declIDTable = null; static void doFiles(Hashtable table, SymbolManager symbolManager, File[] inputFiles, File[] signatureFiles) { declIDTable = table; for (int i = 0; i < inputFiles.length; i++) { processFile(symbolManager, inputFiles[i], signatureFiles[i]); } } static void processFile(SymbolManager symbolManager, File inputFile, File signatureFile) { try { PrintWriter writer = new PrintWriter(new BufferedWriter(new FileWriter(signatureFile.getCanonicalPath()))); String packageName = StructureUtil.getPackageDeclarationFromFile(inputFile); if (packageName != null ) { writer.println( "package " + packageName + ";" ); } IProgramElement fileNode = (IProgramElement)AsmManager.getDefault().getHierarchy().findElementForSourceFile(inputFile.getAbsolutePath()); for (Iterator it = fileNode.getChildren().iterator(); it.hasNext(); ) { IProgramElement node = (IProgramElement)it.next(); if (node.getKind().equals(IProgramElement.Kind.IMPORT_REFERENCE)) { processImportDeclaration(node, writer); } else { processTypeDeclaration(node, writer); } } // if we got an error we don't want the contents of the file writer.close(); } catch (IOException e) { System.err.println(e.getMessage()); e.printStackTrace(); } } private static void processImportDeclaration(IProgramElement node, PrintWriter writer) throws IOException { List imports = node.getChildren(); for (Iterator i = imports.iterator(); i.hasNext();) { IProgramElement importNode = (IProgramElement) i.next(); writer.print("import "); writer.print(importNode.getName()); writer.println(';'); } } private static void processTypeDeclaration(IProgramElement classNode, PrintWriter writer) throws IOException { String formalComment = addDeclID(classNode, classNode.getFormalComment()); writer.println(formalComment); String signature = genSourceSignature(classNode);// StructureUtil.genSignature(classNode); // System.err.println("######" + signature + ", " + classNode.getName()); if (!StructureUtil.isAnonymous(classNode) && !classNode.getName().equals("<undefined>")) { writer.println(signature + " {" ); processMembers(classNode.getChildren(), writer, classNode.getKind().equals(IProgramElement.Kind.INTERFACE)); writer.println(); writer.println("}"); } } private static void processMembers(List/*IProgramElement*/ members, PrintWriter writer, boolean declaringTypeIsInterface) throws IOException { for (Iterator it = members.iterator(); it.hasNext();) { IProgramElement member = (IProgramElement) it.next(); if (member.getKind().isType()) { if (!member.getParent().getKind().equals(IProgramElement.Kind.METHOD) && !StructureUtil.isAnonymous(member)) {// don't print anonymous types // System.err.println(">>>>>>>>>>>>>" + member.getName() + "<<<<" + member.getParent()); processTypeDeclaration(member, writer); } } else { String formalComment = addDeclID(member, member.getFormalComment());; writer.println(formalComment); String signature = ""; if (!member.getKind().equals(IProgramElement.Kind.POINTCUT) && !member.getKind().equals(IProgramElement.Kind.ADVICE)) { signature = member.getSourceSignature();//StructureUtil.genSignature(member); } if (member.getKind().isDeclare()) { System.err.println("> Skipping declare (ajdoc limitation): " + member.toLabelString()); } else if (signature != null && signature != "" && !member.getKind().isInterTypeMember() && !member.getKind().equals(IProgramElement.Kind.INITIALIZER) && !StructureUtil.isAnonymous(member)) { writer.print(signature); } else { // System.err.println(">> skipping: " + member.getKind()); } if (member.getKind().equals(IProgramElement.Kind.METHOD) || member.getKind().equals(IProgramElement.Kind.CONSTRUCTOR)) { if (member.getParent().getKind().equals(IProgramElement.Kind.INTERFACE) || signature.indexOf("abstract ") != -1) { writer.println(";"); } else { writer.println(" { }"); } } else if (member.getKind().equals(IProgramElement.Kind.FIELD)) { // writer.println(";"); } } } } /** * Translates "aspect" to "class", as long as its not ".aspect" */ private static String genSourceSignature(IProgramElement classNode) { String signature = classNode.getSourceSignature(); int index = signature.indexOf("aspect"); if (index != -1 && signature.charAt(index-1) != '.') { signature = signature.substring(0, index) + "class " + signature.substring(index + 6, signature.length()); } return signature; } static int nextDeclID = 0; static String addDeclID(IProgramElement decl, String formalComment) { String declID = "" + ++nextDeclID; declIDTable.put(declID, decl); return addToFormal(formalComment, Config.DECL_ID_STRING + declID + Config.DECL_ID_TERMINATOR); } /** * We want to go: * just before the first period * just before the first @ * just before the end of the comment * * Adds a place holder for the period ('#') if one will need to be * replaced. */ static String addToFormal(String formalComment, String string) { boolean appendPeriod = true; if ( (formalComment == null) || formalComment.equals("")) { //formalComment = "/**\n * . \n */\n"; formalComment = "/**\n * \n */\n"; appendPeriod = false; } formalComment = formalComment.trim(); int atsignPos = formalComment.indexOf('@'); int endPos = formalComment.indexOf("*/"); int periodPos = formalComment.indexOf("/**")+2; int position = 0; String periodPlaceHolder = ""; if ( periodPos != -1 ) { position = periodPos+1; } else if ( atsignPos != -1 ) { string = string + "\n * "; position = atsignPos; } else if ( endPos != -1 ) { string = "* " + string + "\n"; position = endPos; } else { // !!! perhaps this error should not be silent throw new Error("Failed to append to formal comment for comment: " + formalComment ); } return formalComment.substring(0, position) + periodPlaceHolder + string + formalComment.substring(position); } }
68,494
Bug 68494 ajdoc does not support .aj files
In addition to accepting .java source files ajdoc needs to accept .aj files.
resolved fixed
3707411
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2004-06-24T22:11:53Z
2004-06-24T15:13:20Z
ajdoc/testdata/coverage/foo/UseThisAspectForLinkCheck.java
package foo; import fluffy.*; import fluffy.bunny.*; import fluffy.bunny.rocks.*; public aspect UseThisAspectForLinkCheck { int foo; pointcut allExecutions(): execution(* *..*(..)); before(): allExecutions() { System.err.println("yo"); } after(): allExecutions() { System.err.println("go"); } }
68,494
Bug 68494 ajdoc does not support .aj files
In addition to accepting .java source files ajdoc needs to accept .aj files.
resolved fixed
3707411
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2004-06-24T22:11:53Z
2004-06-24T15:13:20Z
ajdoc/testsrc/org/aspectj/tools/ajdoc/CoverageTestCase.java
/* ******************************************************************* * Copyright (c) 2003 Contributors. * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Common Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * Mik Kersten initial implementation * ******************************************************************/ package org.aspectj.tools.ajdoc; import java.io.File; import junit.framework.TestCase; /** * A long way to go until full coverage, but this is the place to add more. * * @author Mik Kersten */ public class CoverageTestCase extends TestCase { public void testCoverage() { // System.err.println(new File("testdata/figures-demo").exists()); File file1 = new File("testdata/coverage/foo/ClassA.java"); File aspect1 = new File("testdata/coverage/foo/UseThisAspectForLinkCheck.java"); File file2 = new File("testdata/coverage/foo/InterfaceI.java"); File file3 = new File("testdata/coverage/foo/PlainJava.java"); File file4 = new File("testdata/coverage/foo/ModelCoverage.java"); File file5 = new File("testdata/coverage/fluffy/Fluffy.java"); File file6 = new File("testdata/coverage/fluffy/bunny/Bunny.java"); File file7 = new File("testdata/coverage/fluffy/bunny/rocks/Rocks.java"); File file8 = new File("testdata/coverage/fluffy/bunny/rocks/UseThisAspectForLinkCheckToo.java"); File outdir = new File("testdata/coverage/doc"); String[] args = { // "-XajdocDebug", "-source", "1.4", "-private", "-d", outdir.getAbsolutePath(), aspect1.getAbsolutePath(), file1.getAbsolutePath(), file2.getAbsolutePath(), file3.getAbsolutePath(), file4.getAbsolutePath(), file5.getAbsolutePath(), file6.getAbsolutePath(), file7.getAbsolutePath(), file8.getAbsolutePath() }; org.aspectj.tools.ajdoc.Main.main(args); } // public void testPlainJava() { // File file1 = new File("testdata/coverage/foo/PlainJava.java"); // File outdir = new File("testdata/coverage/doc"); // // String[] args = { "-d", // outdir.getAbsolutePath(), // file1.getAbsolutePath() }; // // org.aspectj.tools.ajdoc.Main.main(args); // } protected void setUp() throws Exception { super.setUp(); } protected void tearDown() throws Exception { super.tearDown(); } }
69,011
Bug 69011 ajdoc fails when using default package
null
resolved fixed
2cc4826
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2004-07-05T18:19:15Z
2004-06-30T15:40:00Z
ajdoc/src/org/aspectj/tools/ajdoc/StubFileGenerator.java
/* ******************************************************************* * Copyright (c) 1999-2001 Xerox Corporation, * 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Common Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * Xerox/PARC initial implementation * Mik Kersten port to AspectJ 1.1+ code base * ******************************************************************/ package org.aspectj.tools.ajdoc; import java.io.*; import java.util.Hashtable; import java.util.Iterator; import java.util.List; import org.aspectj.asm.AsmManager; import org.aspectj.asm.IProgramElement; /** * @author Mik Kersten */ class StubFileGenerator { static Hashtable declIDTable = null; static void doFiles(Hashtable table, SymbolManager symbolManager, File[] inputFiles, File[] signatureFiles) { declIDTable = table; for (int i = 0; i < inputFiles.length; i++) { processFile(symbolManager, inputFiles[i], signatureFiles[i]); } } static void processFile(SymbolManager symbolManager, File inputFile, File signatureFile) { try { String path = StructureUtil.translateAjPathName(signatureFile.getCanonicalPath()); PrintWriter writer = new PrintWriter(new BufferedWriter(new FileWriter(path))); String packageName = StructureUtil.getPackageDeclarationFromFile(inputFile); if (packageName != null ) { writer.println( "package " + packageName + ";" ); } IProgramElement fileNode = (IProgramElement)AsmManager.getDefault().getHierarchy().findElementForSourceFile(inputFile.getAbsolutePath()); for (Iterator it = fileNode.getChildren().iterator(); it.hasNext(); ) { IProgramElement node = (IProgramElement)it.next(); if (node.getKind().equals(IProgramElement.Kind.IMPORT_REFERENCE)) { processImportDeclaration(node, writer); } else { processTypeDeclaration(node, writer); } } // if we got an error we don't want the contents of the file writer.close(); } catch (IOException e) { System.err.println(e.getMessage()); e.printStackTrace(); } } private static void processImportDeclaration(IProgramElement node, PrintWriter writer) throws IOException { List imports = node.getChildren(); for (Iterator i = imports.iterator(); i.hasNext();) { IProgramElement importNode = (IProgramElement) i.next(); writer.print("import "); writer.print(importNode.getName()); writer.println(';'); } } private static void processTypeDeclaration(IProgramElement classNode, PrintWriter writer) throws IOException { String formalComment = addDeclID(classNode, classNode.getFormalComment()); writer.println(formalComment); String signature = genSourceSignature(classNode);// StructureUtil.genSignature(classNode); // System.err.println("######" + signature + ", " + classNode.getName()); if (!StructureUtil.isAnonymous(classNode) && !classNode.getName().equals("<undefined>")) { writer.println(signature + " {" ); processMembers(classNode.getChildren(), writer, classNode.getKind().equals(IProgramElement.Kind.INTERFACE)); writer.println(); writer.println("}"); } } private static void processMembers(List/*IProgramElement*/ members, PrintWriter writer, boolean declaringTypeIsInterface) throws IOException { for (Iterator it = members.iterator(); it.hasNext();) { IProgramElement member = (IProgramElement) it.next(); if (member.getKind().isType()) { if (!member.getParent().getKind().equals(IProgramElement.Kind.METHOD) && !StructureUtil.isAnonymous(member)) {// don't print anonymous types // System.err.println(">>>>>>>>>>>>>" + member.getName() + "<<<<" + member.getParent()); processTypeDeclaration(member, writer); } } else { String formalComment = addDeclID(member, member.getFormalComment());; writer.println(formalComment); String signature = ""; if (!member.getKind().equals(IProgramElement.Kind.POINTCUT) && !member.getKind().equals(IProgramElement.Kind.ADVICE)) { signature = member.getSourceSignature();//StructureUtil.genSignature(member); } if (member.getKind().isDeclare()) { System.err.println("> Skipping declare (ajdoc limitation): " + member.toLabelString()); } else if (signature != null && signature != "" && !member.getKind().isInterTypeMember() && !member.getKind().equals(IProgramElement.Kind.INITIALIZER) && !StructureUtil.isAnonymous(member)) { writer.print(signature); } else { // System.err.println(">> skipping: " + member.getKind()); } if (member.getKind().equals(IProgramElement.Kind.METHOD) || member.getKind().equals(IProgramElement.Kind.CONSTRUCTOR)) { if (member.getParent().getKind().equals(IProgramElement.Kind.INTERFACE) || signature.indexOf("abstract ") != -1) { writer.println(";"); } else { writer.println(" { }"); } } else if (member.getKind().equals(IProgramElement.Kind.FIELD)) { // writer.println(";"); } } } } /** * Translates "aspect" to "class", as long as its not ".aspect" */ private static String genSourceSignature(IProgramElement classNode) { String signature = classNode.getSourceSignature(); int index = signature.indexOf("aspect"); if (index != -1 && signature.charAt(index-1) != '.') { signature = signature.substring(0, index) + "class " + signature.substring(index + 6, signature.length()); } return signature; } static int nextDeclID = 0; static String addDeclID(IProgramElement decl, String formalComment) { String declID = "" + ++nextDeclID; declIDTable.put(declID, decl); return addToFormal(formalComment, Config.DECL_ID_STRING + declID + Config.DECL_ID_TERMINATOR); } /** * We want to go: * just before the first period * just before the first @ * just before the end of the comment * * Adds a place holder for the period ('#') if one will need to be * replaced. */ static String addToFormal(String formalComment, String string) { boolean appendPeriod = true; if ( (formalComment == null) || formalComment.equals("")) { //formalComment = "/**\n * . \n */\n"; formalComment = "/**\n * \n */\n"; appendPeriod = false; } formalComment = formalComment.trim(); int atsignPos = formalComment.indexOf('@'); int endPos = formalComment.indexOf("*/"); int periodPos = formalComment.indexOf("/**")+2; int position = 0; String periodPlaceHolder = ""; if ( periodPos != -1 ) { position = periodPos+1; } else if ( atsignPos != -1 ) { string = string + "\n * "; position = atsignPos; } else if ( endPos != -1 ) { string = "* " + string + "\n"; position = endPos; } else { // !!! perhaps this error should not be silent throw new Error("Failed to append to formal comment for comment: " + formalComment ); } return formalComment.substring(0, position) + periodPlaceHolder + string + formalComment.substring(position); } }
69,011
Bug 69011 ajdoc fails when using default package
null
resolved fixed
2cc4826
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2004-07-05T18:19:15Z
2004-06-30T15:40:00Z
ajdoc/testdata/coverage/InDefaultPackage.java
69,011
Bug 69011 ajdoc fails when using default package
null
resolved fixed
2cc4826
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2004-07-05T18:19:15Z
2004-06-30T15:40:00Z
ajdoc/testsrc/org/aspectj/tools/ajdoc/CoverageTestCase.java
/* ******************************************************************* * Copyright (c) 2003 Contributors. * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Common Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * Mik Kersten initial implementation * ******************************************************************/ package org.aspectj.tools.ajdoc; import java.io.File; import junit.framework.TestCase; /** * A long way to go until full coverage, but this is the place to add more. * * @author Mik Kersten */ public class CoverageTestCase extends TestCase { public void testCoverage() { // System.err.println(new File("testdata/figures-demo").exists()); File file1 = new File("testdata/coverage/foo/ClassA.java"); File aspect1 = new File("testdata/coverage/foo/UseThisAspectForLinkCheck.aj"); File file2 = new File("testdata/coverage/foo/InterfaceI.java"); File file3 = new File("testdata/coverage/foo/PlainJava.java"); File file4 = new File("testdata/coverage/foo/ModelCoverage.java"); File file5 = new File("testdata/coverage/fluffy/Fluffy.java"); File file6 = new File("testdata/coverage/fluffy/bunny/Bunny.java"); File file7 = new File("testdata/coverage/fluffy/bunny/rocks/Rocks.java"); File file8 = new File("testdata/coverage/fluffy/bunny/rocks/UseThisAspectForLinkCheckToo.java"); File outdir = new File("testdata/coverage/doc"); String[] args = { // "-XajdocDebug", "-source", "1.4", "-private", "-d", outdir.getAbsolutePath(), aspect1.getAbsolutePath(), file1.getAbsolutePath(), file2.getAbsolutePath(), file3.getAbsolutePath(), file4.getAbsolutePath(), file5.getAbsolutePath(), file6.getAbsolutePath(), file7.getAbsolutePath(), file8.getAbsolutePath() }; org.aspectj.tools.ajdoc.Main.main(args); } // public void testPlainJava() { // File file1 = new File("testdata/coverage/foo/PlainJava.java"); // File outdir = new File("testdata/coverage/doc"); // // String[] args = { "-d", // outdir.getAbsolutePath(), // file1.getAbsolutePath() }; // // org.aspectj.tools.ajdoc.Main.main(args); // } protected void setUp() throws Exception { super.setUp(); } protected void tearDown() throws Exception { super.tearDown(); } }
70,008
Bug 70008 problem with ajdoc -public
null
resolved fixed
8dc0845
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2004-07-14T20:36:00Z
2004-07-14T10:13:20Z
ajdoc/src/org/aspectj/tools/ajdoc/HtmlDecorator.java
/* ******************************************************************* * Copyright (c) 1999-2001 Xerox Corporation, * 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Common Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * Xerox/PARC initial implementation * Mik Kersten port to AspectJ 1.1+ code base * ******************************************************************/ package org.aspectj.tools.ajdoc; import java.io.*; import java.util.*; import org.aspectj.asm.AsmManager; import org.aspectj.asm.IProgramElement; import org.aspectj.asm.IRelationship; /** * @author Mik Kersten */ class HtmlDecorator { static List visibleFileList = new ArrayList(); static Hashtable declIDTable = null; static SymbolManager symbolManager = null; static File rootDir = null; static void decorateHTMLFromInputFiles(Hashtable table, File newRootDir, SymbolManager sm, File[] inputFiles, String docModifier ) throws IOException { rootDir = newRootDir; declIDTable = table; symbolManager = sm; for (int i = 0; i < inputFiles.length; i++) { decorateHTMLFromDecls(symbolManager.getDeclarations(inputFiles[i].getCanonicalPath()), rootDir.getCanonicalPath() + Config.DIR_SEP_CHAR, docModifier, false); } } static void decorateHTMLFromDecls(Declaration[] decls, String base, String docModifier, boolean exceededNestingLevel) throws IOException { if ( decls != null ) { for (int i = 0; i < decls.length; i++) { Declaration decl = decls[i]; decorateHTMLFromDecl(decl, base, docModifier, exceededNestingLevel); } } } /** * Before attempting to decorate the HTML file we have to verify that it exists, * which depends on the documentation visibility specified to c. * * Depending on docModifier, can document * - public: only public * - protected: protected and public (default) * - package: package protected and public * - private: everything */ static void decorateHTMLFromDecl(Declaration decl, String base, String docModifier, boolean exceededNestingLevel ) throws IOException { boolean nestedClass = false; if ( decl.isType() ) { boolean decorateFile = true; if ( (docModifier.equals("private")) || // everything (docModifier.equals("package") && decl.getModifiers().indexOf( "private" ) == -1) || // package (docModifier.equals("protected") && (decl.getModifiers().indexOf( "protected" ) != -1 || decl.getModifiers().indexOf( "public" ) != -1 )) || (docModifier.equals("public") && decl.getModifiers().indexOf( "public" ) != -1) ) { visibleFileList.add(decl.getSignature()); String packageName = decl.getPackageName(); String filename = ""; if ( packageName != null ) { int index1 = base.lastIndexOf(Config.DIR_SEP_CHAR); int index2 = base.lastIndexOf("."); String currFileClass = ""; if (index1 > -1 && index2 > 0 && index1 < index2) { currFileClass = base.substring(index1+1, index2); } // XXX only one level of nexting if (currFileClass.equals(decl.getDeclaringType())) { nestedClass = true; packageName = packageName.replace( '.','/' ); String newBase = ""; if ( base.lastIndexOf(Config.DIR_SEP_CHAR) > 0 ) { newBase = base.substring(0, base.lastIndexOf(Config.DIR_SEP_CHAR)); } String signature = constructNestedTypeName(decl.getNode()); filename = newBase + Config.DIR_SEP_CHAR + packageName + Config.DIR_SEP_CHAR + currFileClass + //"." + signature + ".html"; } else { packageName = packageName.replace( '.','/' ); filename = base + packageName + Config.DIR_SEP_CHAR + decl.getSignature() + ".html"; } } else { filename = base + decl.getSignature() + ".html"; } if (!exceededNestingLevel) { decorateHTMLFile(new File(filename)); decorateHTMLFromDecls(decl.getDeclarations(), base + decl.getSignature() + ".", docModifier, nestedClass); } else { System.out.println("Warning: can not generate documentation for nested " + "inner class: " + decl.getSignature() ); } } } } private static String constructNestedTypeName(IProgramElement node) { if (node.getParent().getKind().isSourceFile()) { return node.getName(); } else { String nodeName = ""; if (node.getKind().isType()) nodeName += '.' + node.getName(); return constructNestedTypeName(node.getParent()) + nodeName; } } static void decorateHTMLFile(File file) throws IOException { System.out.println( "> Decorating " + file.getCanonicalPath() + "..." ); BufferedReader reader = new BufferedReader(new FileReader(file)); StringBuffer fileContents = new StringBuffer(); String line = reader.readLine(); while( line != null ) { fileContents.append(line + "\n"); line = reader.readLine(); } boolean isSecond = false; int index = 0; IProgramElement decl; while ( true ) { //---this next part is an inlined procedure that returns two values--- //---the next declaration and the index at which that declaration's--- //---DeclID sits in the .html file --- String contents = fileContents.toString(); int start = contents.indexOf( Config.DECL_ID_STRING, index); int end = contents.indexOf( Config.DECL_ID_TERMINATOR, index ); if ( start == -1 ) decl = null; else if ( end == -1 ) throw new Error("Malformed DeclID."); else { String tid = contents.substring(start + Config.DECL_ID_STRING.length(), end); decl = (IProgramElement)declIDTable.get(tid); index = start; } //--- --- //--- --- if ( decl == null ) break; fileContents.delete(start, end + Config.DECL_ID_TERMINATOR.length()); if ( decl.getKind().isType() ) { isSecond = true; // addIntroductionDocumentation(decl, fileContents, index); // addAdviceDocumentation(decl, fileContents, index); // addPointcutDocumentation(decl, fileContents, index); addAspectDocumentation(decl, fileContents, index); } else { decorateMemberDocumentation(decl, fileContents, index); } } // Change "Class" to "Aspect", HACK: depends on "affects:" int classStartIndex = fileContents.toString().indexOf("<BR>\nClass"); if (classStartIndex != -1 && fileContents.toString().indexOf("Advises:") != -1) { int classEndIndex = fileContents.toString().indexOf("</H2>", classStartIndex); if (classStartIndex != -1 && classEndIndex != -1) { String classLine = fileContents.toString().substring(classStartIndex, classEndIndex); String aspectLine = "<BR>\n" + "Aspect " + classLine.substring(11, classLine.length()); fileContents.delete(classStartIndex, classEndIndex); fileContents.insert(classStartIndex, aspectLine); } } file.delete(); FileOutputStream fos = new FileOutputStream( file ); fos.write( fileContents.toString().getBytes() ); } static void addAspectDocumentation(IProgramElement node, StringBuffer fileBuffer, int index ) { // List relations = AsmManager.getDefault().getRelationshipMap().get(node); // System.err.println("> node: " + node + ", " + "relations: " + relations); List pointcuts = new ArrayList(); List advice = new ArrayList(); for (Iterator it = node.getChildren().iterator(); it.hasNext(); ) { IProgramElement member = (IProgramElement)it.next(); if (member.getKind().equals(IProgramElement.Kind.POINTCUT)) { pointcuts.add(member); } else if (member.getKind().equals(IProgramElement.Kind.ADVICE)) { advice.add(member); } } if (pointcuts.size() > 0) { insertDeclarationsSummary(fileBuffer, pointcuts, "Pointcut Summary", index); insertDeclarationsDetails(fileBuffer, pointcuts, "Pointcut Detail", index); } if (advice.size() > 0) { insertDeclarationsSummary(fileBuffer, advice, "Advice Summary", index); insertDeclarationsDetails(fileBuffer, advice, "Advice Detail", index); } } // static void addIntroductionDocumentation(IProgramElement decl, // StringBuffer fileBuffer, // int index ) { // Declaration[] introductions = decl.getIntroductionDeclarations(); // if ( introductions.length > 0 ) { // insertDeclarationsSummary(fileBuffer, // introductions, // "Introduction Summary", // index); // insertDeclarationsDetails(fileBuffer, // introductions, // "Introduction Detail", // index); // } // } static void insertDeclarationsSummary(StringBuffer fileBuffer, List decls, String kind, int index) { int insertIndex = findSummaryIndex(fileBuffer, index); // insert the head of the table String tableHead = "<!-- ======== " + kind.toUpperCase() + " ======= -->\n\n" + "<TABLE BORDER=\"1\" WIDTH=\"100%\" CELLPADDING=\"1\"" + "CELLSPACING=\"0\"><TR><TD COLSPAN=2 BGCOLOR=\"#CCCCFF\">" + "<FONT SIZE=\"+2\"><B>" + kind + "</B></FONT></TD></TR>\n"; fileBuffer.insert(insertIndex, tableHead); insertIndex += tableHead.length(); // insert the body of the table for ( int i = 0; i < decls.size(); i++ ) { IProgramElement decl = (IProgramElement)decls.get(i); // insert the table row accordingly String comment = generateSummaryComment(decl); String entry = ""; if ( kind.equals( "Advice Summary" ) ) { entry += "<TR><TD>" + "<A HREF=\"#" + generateHREFName(decl) + "\">" + "<TT>" + generateAdviceSignatures(decl) + "</TT></A><BR>&nbsp;"; if (!comment.equals("")) { entry += comment + "<P>"; } entry += generateAffects(decl, false) + "</TD>" + "</TR><TD>\n"; } else if ( kind.equals( "Pointcut Summary" ) ) { entry += "<TR><TD WIDTH=\"1%\">" + "<FONT SIZE=-1><TT>" + genAccessibility(decl) + "</TT></FONT>" + "</TD>\n" + "<TD>" + "<TT><A HREF=\"#" + generateHREFName(decl) + "\">" + decl.toLabelString() + "</A></TT><BR>&nbsp;"; if (!comment.equals("")) { entry += comment + "<P>"; } entry += "</TR></TD>\n"; } else if ( kind.equals( "Introduction Summary" ) ) { entry += "<TR><TD WIDTH=\"1%\">" + "<FONT SIZE=-1><TT>" + decl.getModifiers() + "</TT></FONT>" + "</TD>" + "<TD>" + "<A HREF=\"#" + generateHREFName(decl) + "\">" + "<TT>introduction " + decl.toLabelString() + "</TT></A><P>" + generateIntroductionSignatures(decl, false) + generateAffects(decl, true); } // insert the entry fileBuffer.insert(insertIndex, entry); insertIndex += entry.length(); } // insert the end of the table String tableTail = "</TABLE><P>&nbsp;\n"; fileBuffer.insert(insertIndex, tableTail); insertIndex += tableTail.length(); } private static String genAccessibility(IProgramElement decl) { if (decl.getAccessibility().equals(IProgramElement.Accessibility.PACKAGE)) { return "(package private)"; } else { return decl.getAccessibility().toString(); } } static void insertDeclarationsDetails(StringBuffer fileBuffer, List decls, String kind, int index) { int insertIndex = findDetailsIndex(fileBuffer, index); // insert the table heading String detailsHeading = "<P>&nbsp;\n" + "<!-- ======== " + kind.toUpperCase() + " SUMMARY ======= -->\n\n" + "<TABLE BORDER=\"1\" CELLPADDING=\"3\" CELLSPACING=\"0\" WIDTH=\"100%\">\n" + "<TR BGCOLOR=\"#CCCCFF\" CLASS=\"TableHeadingColor\">\n" + "<TD COLSPAN=1><FONT SIZE=\"+2\">\n" + "<B>" + kind + "</B></FONT></TD>\n" + "</TR>\n" + "</TABLE>"; fileBuffer.insert(insertIndex, detailsHeading); insertIndex += detailsHeading.length(); // insert the details for ( int i = 0; i < decls.size(); i++ ) { IProgramElement decl = (IProgramElement)decls.get(i); String entry = ""; // insert the table row accordingly entry += "<A NAME=\"" + generateHREFName(decl) + "\"><!-- --></A>\n"; if ( kind.equals( "Advice Detail" ) ) { entry += "<H3>" + decl.getName() + "</H3><P>"; entry += "<TT>" + generateAdviceSignatures(decl) + "</TT>\n" + "<P>" + generateDetailsComment(decl) + "<P>" + generateAffects(decl, false); } else if (kind.equals("Pointcut Detail")) { entry += "<H3>" + decl.toLabelString() + "</H3><P>" + generateDetailsComment(decl); } else if (kind.equals("Introduction Detail")) { entry += "<H3>introduction " + decl.toLabelString() + "</H3><P>"; entry += generateIntroductionSignatures(decl, true) + generateAffects(decl, true) + generateDetailsComment(decl); } // insert the entry if (i != decls.size()-1) { entry += "<P><HR>\n"; } else { entry += "<P>"; } fileBuffer.insert(insertIndex, entry); insertIndex += entry.length(); } } /** * TODO: don't place the summary first. */ static int findSummaryIndex(StringBuffer fileBuffer, int index) { String fbs = fileBuffer.toString(); String MARKER_1 = "<!-- =========== FIELD SUMMARY =========== -->"; String MARKER_2 = "<!-- ======== CONSTRUCTOR SUMMARY ======== -->"; int index1 = fbs.indexOf(MARKER_1, index); int index2 = fbs.indexOf(MARKER_2, index); if (index1 < index2) { return index1; } else { return index2; } } static int findDetailsIndex(StringBuffer fileBuffer, int index) { String fbs = fileBuffer.toString(); String MARKER_1 = "<!-- ========= CONSTRUCTOR DETAIL ======== -->"; String MARKER_2 = "<!-- ============ FIELD DETAIL =========== -->"; String MARKER_3 = "<!-- ============ METHOD DETAIL ========== -->"; int index1 = fbs.indexOf(MARKER_1, index); int index2 = fbs.indexOf(MARKER_2, index); int index3 = fbs.indexOf(MARKER_3, index); if (index1 < index2 && index1 < index3) { return index1; } else if (index2 < index1 && index2 < index3) { return index2; } else { return index3; } } static void decorateMemberDocumentation(IProgramElement node, StringBuffer fileContentsBuffer, int index ) { List targets = StructureUtil.getTargets(node, IRelationship.Kind.ADVICE); if (targets != null && !targets.isEmpty()) { String prevName = ""; String adviceDoc = "<TABLE WIDTH=\"100%\" BGCOLOR=#FFFFFF><TR>" + "<TD width=\"15%\" bgcolor=\"#FFD8B0\"><B><FONT COLOR=000000>&nbsp;Advised&nbsp;by:</font></b></td><td>"; String relativePackagePath = getRelativePathFromHere( node.getPackageName().replace('.', '/') + Config.DIR_SEP_CHAR); List addedNames = new ArrayList(); for (Iterator it = targets.iterator(); it.hasNext(); ) { String currHandle = (String)it.next(); IProgramElement currDecl = AsmManager.getDefault().getHierarchy().findElementForHandle(currHandle); String packagePath = ""; if (currDecl.getPackageName() != null && !currDecl.getPackageName().equals("")) { packagePath = currDecl.getPackageName().replace('.', '/') + Config.DIR_SEP_CHAR; } String hrefName = ""; String hrefLink = ""; // Start the hRefLink with the relative path based on where // *this* type (i.e. the advised) is in the package structure. hrefLink = relativePackagePath + packagePath; if (currDecl.getPackageName() != null ) { hrefName = currDecl.getPackageName().replace('.', '/'); // hrefLink = "";//+ currDecl.getPackageName() + Config.DIR_SEP_CHAR; } hrefName += Config.DIR_SEP_CHAR + currDecl.getParent().toLinkLabelString() + "." + currDecl.getName(); hrefLink += currDecl.getParent().toLinkLabelString() + ".html" + "#" + currDecl.toLabelString(); if (!addedNames.contains(hrefName)) { adviceDoc = adviceDoc + "<A HREF=\"" + hrefLink + "\"><tt>" + hrefName.replace('/', '.') + "</tt></A>"; if (it.hasNext()) adviceDoc += ", "; addedNames.add(hrefName); } } adviceDoc += "</TR></TD></TABLE>\n"; fileContentsBuffer.insert( index, adviceDoc ); } } /** * TODO: probably want to make this the same for intros and advice. */ static String generateAffects(IProgramElement decl, boolean isIntroduction) { List targets = StructureUtil.getTargets(decl, IRelationship.Kind.ADVICE); if (targets == null) return null; List packageList = new ArrayList(); String entry = "<TABLE WIDTH=\"100%\" BGCOLOR=#FFFFFF><TR>" + "<TD width=\"10%\" bgcolor=\"#FFD8B0\"><B><FONT COLOR=000000>&nbsp;Advises:</b></font></td><td>"; String relativePackagePath = getRelativePathFromHere( decl.getPackageName().replace('.', '/') + Config.DIR_SEP_CHAR); List addedNames = new ArrayList(); // for ensuring that we don't add duplciates for (Iterator it = targets.iterator(); it.hasNext(); ) { String currHandle = (String)it.next(); IProgramElement currDecl = AsmManager.getDefault().getHierarchy().findElementForHandle(currHandle); if (currDecl.getKind().equals(IProgramElement.Kind.CODE)) { currDecl = currDecl.getParent(); // promote to enclosing } if (currDecl != null && !StructureUtil.isAnonymous(currDecl.getParent())) { String packagePath = ""; if (currDecl.getPackageName() != null && !currDecl.getPackageName().equals("")) { packagePath = currDecl.getPackageName().replace('.', '/') + Config.DIR_SEP_CHAR; } String typeSignature = constructNestedTypeName(currDecl); String hrefName = packagePath + typeSignature; // Start the hRefLink with the relative path based on where // *this* type (i.e. the advisor) is in the package structure. String hrefLink = relativePackagePath + packagePath + typeSignature + ".html"; if (!currDecl.getKind().isType()) { hrefName += '.' + currDecl.getName(); hrefLink += "#" + currDecl.toLabelString(); } if (!addedNames.contains(hrefName)) { entry += "<A HREF=\"" + hrefLink + "\"><tt>" + hrefName.replace('/', '.') + "</tt></A>"; // !!! don't replace if (it.hasNext()) entry += ", "; addedNames.add(hrefName); } } } entry += "</B></FONT></TD></TR></TABLE>\n</TR></TD>\n"; return entry; } /** * Generates a relative directory path fragment that can be * used to navigate "upwards" from the directory location * implied by the argument. * @param packagePath * @return String consisting of multiple "../" parts, one for * each component part of the input <code>packagePath</code>. */ private static String getRelativePathFromHere(String packagePath) { StringBuffer result = new StringBuffer(""); if (packagePath != null && (packagePath.indexOf("/") != -1)) { StringTokenizer sTok = new StringTokenizer(packagePath, "/", false); while (sTok.hasMoreTokens()) { sTok.nextToken(); // don't care about the token value result.append(".." + Config.DIR_SEP_CHAR); }// end while }// end if return result.toString(); } static String generateIntroductionSignatures(IProgramElement decl, boolean isDetails) { return "<not implemented>"; // Declaration[] decls = decl.getDeclarations(); // String entry = ""; // for ( int j = 0; j < decls.length; j++ ) { // Declaration currDecl = decls[j]; // if ( currDecl != null ) { // entry += // "<TT><B>" + // currDecl.getSignature() + // "</B></TT><BR>"; // } // if (isDetails) { // entry += generateDetailsComment(currDecl) + "<P>"; // } // else { // entry += generateSummaryComment(currDecl) + "<P>"; // } // } // return entry; } static String generateAdviceSignatures(IProgramElement decl ) { return "<B>" + decl.toLabelString() + "</B>"; } static String generateSummaryComment(IProgramElement decl) { String COMMENT_INDENT = "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"; // !!! String formattedComment = getFormattedComment(decl); int periodIndex = formattedComment.indexOf( '.' ); if (formattedComment.equals("")) { return ""; } else if ( periodIndex != -1 ) { return COMMENT_INDENT + formattedComment.substring( 0, periodIndex+1 ) ; } else { return COMMENT_INDENT + formattedComment; } } static String generateDetailsComment(IProgramElement decl) { return getFormattedComment(decl); } static String generateHREFName(IProgramElement decl) { String hrefLink = decl.toLabelString(); // !!! return hrefLink; } /** * Figure out the link relative to the package. */ static String generateAffectsHREFLink(String declaringType) { String link = rootDir.getAbsolutePath() + "/" + declaringType + ".html"; return link; } /** * This formats a comment according to the rules in the Java Langauge Spec: * <I>The text of a docuemntation comment consists of the characters between * the /** that begins the comment and the 'star-slash' that ends it. The text is * devided into one or more lines. On each of these lines, the leading * * characters are ignored; for lines other than the first, blanks and * tabs preceding the initial * characters are also discarded.</I> * * TODO: implement formatting or linking for tags. */ static String getFormattedComment(IProgramElement decl) { String comment = decl.getFormalComment(); if (comment == null) return ""; String formattedComment = ""; // strip the comment markers int startIndex = comment.indexOf("/**"); int endIndex = comment.indexOf("*/"); if ( startIndex == -1 ) { startIndex = 0; } else { startIndex += 3; } if ( endIndex == -1 ) { endIndex = comment.length(); } comment = comment.substring( startIndex, endIndex ); // string the leading whitespace and '*' characters at the beginning of each line BufferedReader reader = new BufferedReader( new StringReader( comment ) ); try { for (String line = reader.readLine(); line != null; line = reader.readLine()) { line = line.trim(); for (int i = 0; i < line.length(); i++ ) { if ( line.charAt(0) == '*' ) { line = line.substring(1, line.length()); } else { break; } } // !!! remove any @see and @link tags from the line //int seeIndex = line.indexOf("@see"); //int linkIndex = line.indexOf("@link"); //if ( seeIndex != -1 ) { // line = line.substring(0, seeIndex) + line.substring(seeIndex); //} //if ( linkIndex != -1 ) { // line = line.substring(0, linkIndex) + line.substring(linkIndex); //} formattedComment += line; } } catch ( IOException ioe ) { throw new Error( "Couldn't format comment for declaration: " + decl.getName() ); } return formattedComment; } }
70,008
Bug 70008 problem with ajdoc -public
null
resolved fixed
8dc0845
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2004-07-14T20:36:00Z
2004-07-14T10:13:20Z
ajdoc/testdata/coverage/foo/PkgVisibleClass.java
70,008
Bug 70008 problem with ajdoc -public
null
resolved fixed
8dc0845
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2004-07-14T20:36:00Z
2004-07-14T10:13:20Z
ajdoc/testsrc/org/aspectj/tools/ajdoc/CoverageTestCase.java
/* ******************************************************************* * Copyright (c) 2003 Contributors. * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Common Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * Mik Kersten initial implementation * ******************************************************************/ package org.aspectj.tools.ajdoc; import java.io.File; import junit.framework.TestCase; /** * A long way to go until full coverage, but this is the place to add more. * * @author Mik Kersten */ public class CoverageTestCase extends TestCase { public void testCoverage() { // System.err.println(new File("testdata/figures-demo").exists()); File file0 = new File("testdata/coverage/InDefaultPackage.java"); File file1 = new File("testdata/coverage/foo/ClassA.java"); File aspect1 = new File("testdata/coverage/foo/UseThisAspectForLinkCheck.aj"); File file2 = new File("testdata/coverage/foo/InterfaceI.java"); File file3 = new File("testdata/coverage/foo/PlainJava.java"); File file4 = new File("testdata/coverage/foo/ModelCoverage.java"); File file5 = new File("testdata/coverage/fluffy/Fluffy.java"); File file6 = new File("testdata/coverage/fluffy/bunny/Bunny.java"); File file7 = new File("testdata/coverage/fluffy/bunny/rocks/Rocks.java"); File file8 = new File("testdata/coverage/fluffy/bunny/rocks/UseThisAspectForLinkCheckToo.java"); File outdir = new File("testdata/coverage/doc"); String[] args = { // "-XajdocDebug", "-source", "1.4", "-private", "-d", outdir.getAbsolutePath(), aspect1.getAbsolutePath(), file0.getAbsolutePath(), file1.getAbsolutePath(), file2.getAbsolutePath(), file3.getAbsolutePath(), file4.getAbsolutePath(), file5.getAbsolutePath(), file6.getAbsolutePath(), file7.getAbsolutePath(), file8.getAbsolutePath() }; org.aspectj.tools.ajdoc.Main.main(args); } // public void testPlainJava() { // File file1 = new File("testdata/coverage/foo/PlainJava.java"); // File outdir = new File("testdata/coverage/doc"); // // String[] args = { "-d", // outdir.getAbsolutePath(), // file1.getAbsolutePath() }; // // org.aspectj.tools.ajdoc.Main.main(args); // } protected void setUp() throws Exception { super.setUp(); } protected void tearDown() throws Exception { super.tearDown(); } }
70,008
Bug 70008 problem with ajdoc -public
null
resolved fixed
8dc0845
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2004-07-14T20:36:00Z
2004-07-14T10:13:20Z
ajdoc/testsrc/org/aspectj/tools/ajdoc/SpacewarTestCase.java
/* ******************************************************************* * Copyright (c) 2003 Contributors. * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Common Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * Mik Kersten initial implementation * ******************************************************************/ package org.aspectj.tools.ajdoc; import java.io.File; import junit.framework.TestCase; /** * @author Mik Kersten */ public class SpacewarTestCase extends TestCase { public void testSimpleExample() { // System.err.println(new File("testdata/figures-demo").exists()); File outdir = new File("testdata/spacewar/docdir"); File sourcepath = new File("testdata/spacewar"); String[] args = { "-d", outdir.getAbsolutePath(), "-sourcepath", sourcepath.getAbsolutePath(), "spacewar", "coordination" }; org.aspectj.tools.ajdoc.Main.main(args); assertTrue(true); } protected void setUp() throws Exception { super.setUp(); } protected void tearDown() throws Exception { super.tearDown(); } }
70,619
Bug 70619 compiler aborts with "conflicting dominates orders" with circular declare precedences
The following program causes ajc 1.2 to abort: public class Conflict { public static void main(String[] args) { } } aspect Conflict1 { declare precedence: Conflict1, Conflict2; before(): execution(* *(..)) { } } aspect Conflict2 { declare precedence: Conflict2, Conflict1; after(): execution(* *(..)) { } }
resolved fixed
75852d7
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2004-07-26T13:28:20Z
2004-07-22T15:26:40Z
tests/bugs/bug70619/Conflict.java
70,619
Bug 70619 compiler aborts with "conflicting dominates orders" with circular declare precedences
The following program causes ajc 1.2 to abort: public class Conflict { public static void main(String[] args) { } } aspect Conflict1 { declare precedence: Conflict1, Conflict2; before(): execution(* *(..)) { } } aspect Conflict2 { declare precedence: Conflict2, Conflict1; after(): execution(* *(..)) { } }
resolved fixed
75852d7
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2004-07-26T13:28:20Z
2004-07-22T15:26:40Z
tests/bugs/bug70619/Precedence.java
70,619
Bug 70619 compiler aborts with "conflicting dominates orders" with circular declare precedences
The following program causes ajc 1.2 to abort: public class Conflict { public static void main(String[] args) { } } aspect Conflict1 { declare precedence: Conflict1, Conflict2; before(): execution(* *(..)) { } } aspect Conflict2 { declare precedence: Conflict2, Conflict1; after(): execution(* *(..)) { } }
resolved fixed
75852d7
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2004-07-26T13:28:20Z
2004-07-22T15:26:40Z
weaver/src/org/aspectj/weaver/World.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Common Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * PARC initial implementation * ******************************************************************/ package org.aspectj.weaver; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; 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.weaver.patterns.DeclarePrecedence; import org.aspectj.weaver.patterns.Pointcut; public abstract class World { protected IMessageHandler messageHandler = IMessageHandler.SYSTEM_ERR; protected ICrossReferenceHandler xrefHandler = null; protected TypeMap typeMap = new TypeMap(); // Signature to ResolvedType protected CrosscuttingMembersSet crosscuttingMembersSet = new CrosscuttingMembersSet(this); protected IHierarchy model = null; protected Lint lint = new Lint(this); protected boolean XnoInline; protected boolean XlazyTjp; protected World() { super(); typeMap.put("B", ResolvedTypeX.BYTE); typeMap.put("S", ResolvedTypeX.SHORT); typeMap.put("I", ResolvedTypeX.INT); typeMap.put("J", ResolvedTypeX.LONG); typeMap.put("F", ResolvedTypeX.FLOAT); typeMap.put("D", ResolvedTypeX.DOUBLE); typeMap.put("C", ResolvedTypeX.CHAR); typeMap.put("Z", ResolvedTypeX.BOOLEAN); typeMap.put("V", ResolvedTypeX.VOID); } public ResolvedTypeX[] resolve(TypeX[] types) { int len = types.length; ResolvedTypeX[] ret = new ResolvedTypeX[len]; for (int i=0; i<len; i++) { ret[i] = resolve(types[i]); } return ret; } public ResolvedTypeX resolve(TypeX ty) { return resolve(ty, false); } public ResolvedTypeX resolve(TypeX ty, boolean allowMissing) { //System.out.println("resolve: " + ty + " world " + typeMap.keySet()); String signature = ty.getSignature(); ResolvedTypeX ret = typeMap.get(signature); if (ret != null) return ret; if (ty.isArray()) { ret = new ResolvedTypeX.Array(signature, this, resolve(ty.getComponentType(), allowMissing)); } else { ret = resolveObjectType(ty); if (!allowMissing && ret == ResolvedTypeX.MISSING) { //Thread.currentThread().dumpStack(); MessageUtil.error(messageHandler, "can't find type " + ty.getName()); // + " on classpath " + classPath); } } //System.out.println("ret: " + ret); typeMap.put(signature, ret); return ret; } //XXX helper method might be bad public ResolvedTypeX resolve(String name) { return resolve(TypeX.forName(name)); } protected final ResolvedTypeX resolveObjectType(TypeX ty) { ResolvedTypeX.Name name = new ResolvedTypeX.Name(ty.getSignature(), this); ResolvedTypeX.ConcreteName concreteName = resolveObjectType(name); if (concreteName == null) return ResolvedTypeX.MISSING; name.setDelegate(concreteName); return name; } protected abstract ResolvedTypeX.ConcreteName resolveObjectType(ResolvedTypeX.Name ty); protected final boolean isCoerceableFrom(TypeX type, TypeX other) { return resolve(type).isCoerceableFrom(other); } protected final boolean isAssignableFrom(TypeX type, TypeX other) { return resolve(type).isAssignableFrom(other); } public boolean needsNoConversionFrom(TypeX type, TypeX other) { return resolve(type).needsNoConversionFrom(other); } protected final boolean isInterface(TypeX type) { return resolve(type).isInterface(); } protected final ResolvedTypeX getSuperclass(TypeX type) { return resolve(type).getSuperclass(); } protected final TypeX[] getDeclaredInterfaces(TypeX type) { return resolve(type).getDeclaredInterfaces(); } protected final int getModifiers(TypeX type) { return resolve(type).getModifiers(); } protected final ResolvedMember[] getDeclaredFields(TypeX type) { return resolve(type).getDeclaredFields(); } protected final ResolvedMember[] getDeclaredMethods(TypeX type) { return resolve(type).getDeclaredMethods(); } protected final ResolvedMember[] getDeclaredPointcuts(TypeX type) { return resolve(type).getDeclaredPointcuts(); } // ---- members // XXX should we worry about dealing with context and looking up access? public ResolvedMember resolve(Member member) { ResolvedTypeX declaring = member.getDeclaringType().resolve(this); 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); } protected int getModifiers(Member member) { ResolvedMember r = resolve(member); if (r == null) throw new BCException("bad resolve of " + member); return r.getModifiers(); } protected String[] getParameterNames(Member member) { return resolve(member).getParameterNames(); } protected TypeX[] getExceptions(Member member) { return resolve(member).getExceptions(); } // ---- pointcuts public ResolvedPointcutDefinition findPointcut(TypeX typeX, String name) { throw new RuntimeException("not implemented yet"); } /** * Get the shadow mungers of this world. * * @return a list of {@link IShadowMunger}s appropriate for this world. */ //public abstract List getShadowMungers(); // ---- empty world public static final World EMPTY = new World() { public List getShadowMungers() { return Collections.EMPTY_LIST; } public ResolvedTypeX.ConcreteName resolveObjectType(ResolvedTypeX.Name ty) { return null; } public Advice concreteAdvice(AjAttribute.AdviceAttribute attribute, Pointcut p, Member m) { throw new RuntimeException("unimplemented"); } public ConcreteTypeMunger concreteTypeMunger(ResolvedTypeMunger munger, ResolvedTypeX aspectType) { throw new RuntimeException("unimplemented"); } }; public abstract Advice concreteAdvice( AjAttribute.AdviceAttribute attribute, Pointcut pointcut, Member signature); public final Advice concreteAdvice( 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 concreteAdvice(attribute, p, signature); } public ConcreteTypeMunger makeCflowStackFieldAdder(ResolvedMember cflowField) { throw new RuntimeException("unimplemented"); } public abstract ConcreteTypeMunger concreteTypeMunger(ResolvedTypeMunger munger, ResolvedTypeX aspectType); /** * 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) { this.messageHandler = messageHandler; } public void setXRefHandler(ICrossReferenceHandler xrefHandler) { this.xrefHandler = xrefHandler; } public void showMessage( Kind kind, String message, ISourceLocation loc1, ISourceLocation loc2) { if (loc1 != null) { messageHandler.handleMessage(new Message(message, kind, null, loc1)); if (loc2 != null) { messageHandler.handleMessage(new Message(message, kind, null, loc2)); } } else { messageHandler.handleMessage(new Message(message, kind, null, loc2)); } } // public void addDeclare(ResolvedTypeX onType, Declare declare, boolean forWeaving) { // // this is not extensible, oh well // if (declare instanceof DeclareErrorOrWarning) { // ShadowMunger m = new Checker((DeclareErrorOrWarning)declare); // onType.addShadowMunger(m); // } else if (declare instanceof DeclareDominates) { // declareDominates.add(declare); // } else if (declare instanceof DeclareParents) { // declareParents.add(declare); // } else if (declare instanceof DeclareSoft) { // DeclareSoft d = (DeclareSoft)declare; // declareSoft.add(d); // if (forWeaving) { // ShadowMunger m = Advice.makeSoftener(this, d.getPointcut().concretize(onType, 0), d.getException()); // onType.addShadowMunger(m); // } // } else { // throw new RuntimeException("unimplemented"); // } // } /** * Same signature as org.aspectj.util.PartialOrder.PartialComparable.compareTo */ public int compareByDominates(ResolvedTypeX aspect1, ResolvedTypeX aspect2) { //System.out.println("dom compare: " + aspect1 + " with " + aspect2); //System.out.println(crosscuttingMembersSet.getDeclareDominates()); //??? We probably want to cache this result. This is order N where N is the //??? number of dominates declares in the whole system. //??? This method can be called a large number of times. int order = 0; for (Iterator i = crosscuttingMembersSet.getDeclareDominates().iterator(); i.hasNext(); ) { DeclarePrecedence d = (DeclarePrecedence)i.next(); int thisOrder = d.compare(aspect1, aspect2); //System.out.println("comparing: " + thisOrder + ": " + d); if (thisOrder != 0) { if (order != 0 && order != thisOrder) { throw new BCException("conflicting dominates orders"); } else { order = thisOrder; } } } return order; } public int comparePrecedence(ResolvedTypeX aspect1, ResolvedTypeX aspect2) { //System.err.println("compare precedence " + aspect1 + ", " + aspect2); if (aspect1.equals(aspect2)) return 0; int ret = compareByDominates(aspect1, aspect2); if (ret != 0) return ret; if (aspect1.isAssignableFrom(aspect2)) return -1; else if (aspect2.isAssignableFrom(aspect1)) return +1; return 0; } public List getDeclareParents() { return crosscuttingMembersSet.getDeclareParents(); } 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 ResolvedTypeX.Name lookupOrCreateName(TypeX ty) { String signature = ty.getSignature(); ResolvedTypeX.Name ret = (ResolvedTypeX.Name)typeMap.get(signature); if (ret == null) { ret = new ResolvedTypeX.Name(signature, this); typeMap.put(signature, ret); } return ret; } // public void clearUnexposed() { // List toRemove = new ArrayList(); // for (Iterator iter = typeMap.keySet().iterator(); iter.hasNext();) { // String sig = (String) iter.next(); // ResolvedTypeX x = (ResolvedTypeX) typeMap.get(sig); // if (!x.isExposedToWeaver() && (!x.isPrimitive())) toRemove.add(sig); // } // for (Iterator iter = toRemove.iterator(); iter.hasNext();) { // typeMap.remove(iter.next()); // } // } // // // for testing... // public void dumpTypeMap() { // int exposed = 0; // for (Iterator iter = typeMap.keySet().iterator(); iter.hasNext();) { // String sig = (String) iter.next(); // ResolvedTypeX x = (ResolvedTypeX) typeMap.get(sig); // if (x.isExposedToWeaver()) exposed++; // } // System.out.println("type map contains " + typeMap.size() + " entries, " + exposed + " exposed to weaver"); // } // // public void deepDumpTypeMap() { // for (Iterator iter = typeMap.keySet().iterator(); iter.hasNext();) { // String sig = (String) iter.next(); // ResolvedTypeX x = (ResolvedTypeX) typeMap.get(sig); // if (! (x instanceof ResolvedTypeX.Name)) { // System.out.println(sig + " -> " + x.getClass().getName() + ", " + x.getClassName()); // } else { // ResolvedTypeX.ConcreteName cname = ((ResolvedTypeX.Name)x).getDelegate(); // System.out.println(sig + " -> " + cname.getClass().getName() + ", " + cname.toString()); // } // } // // } // Map of types in the world, with soft links to expendable ones protected static class TypeMap { private Map tMap = new HashMap(); private Map expendableMap = new WeakHashMap(); public ResolvedTypeX put(String key, ResolvedTypeX type) { if (isExpendable(type)) { return (ResolvedTypeX) expendableMap.put(key,type); } else { return (ResolvedTypeX) tMap.put(key,type); } } public ResolvedTypeX get(String key) { ResolvedTypeX ret = (ResolvedTypeX) tMap.get(key); if (ret == null) ret = (ResolvedTypeX) expendableMap.get(key); return ret; } public ResolvedTypeX remove(String key) { ResolvedTypeX ret = (ResolvedTypeX) tMap.remove(key); if (ret == null) ret = (ResolvedTypeX) expendableMap.remove(key); return ret; } private boolean isExpendable(ResolvedTypeX type) { return ( (type != null) && (!type.isExposedToWeaver()) && (!type.isPrimitive()) ); } } }
53,999
Bug 53999 "can't bind type" message has $ for . in type name for declare soft
cosmetic mistake in error message... expected: can't bind type name 'unknown.Error' actual: can't bind type name 'unknown$Error' (not sure why it would ever be munged with $) public class Test { public static void main(String[] args) { test(); } static void test() { throw new Error("hello"); } static aspect A { declare soft : unknown.Error : call(void test()); // CE } }
resolved fixed
936459c
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2004-07-27T10:34:41Z
2004-03-08T04:26:40Z
tests/bugs/Cosmetic.java
53,999
Bug 53999 "can't bind type" message has $ for . in type name for declare soft
cosmetic mistake in error message... expected: can't bind type name 'unknown.Error' actual: can't bind type name 'unknown$Error' (not sure why it would ever be munged with $) public class Test { public static void main(String[] args) { test(); } static void test() { throw new Error("hello"); } static aspect A { declare soft : unknown.Error : call(void test()); // CE } }
resolved fixed
936459c
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2004-07-27T10:34:41Z
2004-03-08T04:26:40Z
weaver/src/org/aspectj/weaver/patterns/WildTypePattern.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Common Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * PARC initial implementation * ******************************************************************/ package org.aspectj.weaver.patterns; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.util.ArrayList; import java.util.List; import org.aspectj.bridge.IMessage; import org.aspectj.bridge.Message; import org.aspectj.bridge.MessageUtil; import org.aspectj.util.FileUtil; import org.aspectj.util.FuzzyBoolean; import org.aspectj.weaver.ISourceContext; import org.aspectj.weaver.ResolvedTypeX; import org.aspectj.weaver.TypeX; //XXX need to use dim in matching public class WildTypePattern extends TypePattern { NamePattern[] namePatterns; int ellipsisCount; String[] importedPrefixes; String[] knownMatches; int dim; WildTypePattern(NamePattern[] namePatterns, boolean includeSubtypes, int dim) { super(includeSubtypes); 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); } public WildTypePattern(List names, boolean includeSubtypes, int dim, int endPos) { this(names, includeSubtypes, dim); this.end = endPos; } //XXX inefficient implementation public static char[][] splitNames(String s) { List ret = new ArrayList(); int startIndex = 0; while (true) { int breakIndex = s.indexOf('.', startIndex); // what about / if (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(ResolvedTypeX type) { String targetTypeName = type.getName(); //System.err.println("match: " + targetTypeName + ", " + knownMatches); //Arrays.asList(importedPrefixes)); return matchesExactlyByName(targetTypeName); } /** * @param targetTypeName * @return */ private boolean matchesExactlyByName(String targetTypeName) { //XXX hack if (knownMatches == null && importedPrefixes == null) { return innerMatchesExactly(targetTypeName); } // 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) { 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))) { 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()))) { return true; } } } return innerMatchesExactly(targetTypeName); } private int lastIndexOfDotOrDollar(String string) { int dot = string.lastIndexOf('.'); int dollar = string.lastIndexOf('$'); return Math.max(dot, dollar); } private boolean innerMatchesExactly(String targetTypeName) { //??? doing this everytime is not very efficient char[][] names = splitNames(targetTypeName); return innerMatchesExactly(names); } private boolean innerMatchesExactly(char[][] names) { int namesLength = names.length; int patternsLength = namePatterns.length; int namesIndex = 0; int patternsIndex = 0; 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(ResolvedTypeX 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() { //System.err.println("extract from : " + Arrays.asList(namePatterns)); int len = namePatterns.length; 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(); } /** * 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 (isStar()) { return TypePattern.ANY; //??? loses source location } 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); binding.copyLocationFrom(this); bindings.register(binding, scope); return binding; } } String cleanName = maybeGetCleanName(); if (cleanName != null) { TypeX type; //System.out.println("resolve: " + cleanName); //??? this loop has too many inefficiencies to count while ((type = scope.lookupType(cleanName, this)) == ResolvedTypeX.MISSING) { int lastDot = cleanName.lastIndexOf('.'); if (lastDot == -1) break; cleanName = cleanName.substring(0, lastDot) + '$' + cleanName.substring(lastDot+1); } if (type == ResolvedTypeX.MISSING) { if (requireExactType) { if (!allowBinding) { scope.getWorld().getMessageHandler().handleMessage( MessageUtil.error("can't bind type name '" + cleanName + "'", getSourceLocation())); } else if (scope.getWorld().getLint().invalidAbsoluteTypeName.isEnabled()) { scope.getWorld().getLint().invalidAbsoluteTypeName.signal(cleanName, getSourceLocation()); } return NO; } else if (scope.getWorld().getLint().invalidAbsoluteTypeName.isEnabled()) { scope.getWorld().getLint().invalidAbsoluteTypeName.signal(cleanName, getSourceLocation()); } } else { if (dim != 0) type = TypeX.makeArray(type, dim); TypePattern ret = new ExactTypePattern(type, includeSubtypes); ret.copyLocationFrom(this); return ret; } } else { if (requireExactType) { scope.getWorld().getMessageHandler().handleMessage( MessageUtil.error("wildcard type pattern not allowed, must use type name", getSourceLocation())); return NO; } //XXX need to implement behavior for Lint.invalidWildcardTypeName } importedPrefixes = scope.getImportedPrefixes(); knownMatches = preMatch(scope.getImportedNames()); return this; } public TypePattern resolveBindingsFromRTTI(boolean allowBinding, boolean requireExactType) { if (isStar()) { return TypePattern.ANY; //??? loses source location } String cleanName = maybeGetCleanName(); if (cleanName != null) { Class clazz = null; clazz = maybeGetPrimitiveClass(cleanName); while (clazz == null) { try { clazz = Class.forName(cleanName); } catch (ClassNotFoundException cnf) { int lastDotIndex = cleanName.lastIndexOf('.'); if (lastDotIndex == -1) break; cleanName = cleanName.substring(0, lastDotIndex) + '$' + cleanName.substring(lastDotIndex+1); } } if (clazz == null) { try { clazz = Class.forName("java.lang." + cleanName); } catch (ClassNotFoundException cnf) { } } if (clazz == null) { if (requireExactType) { return NO; } } else { TypeX type = TypeX.forName(clazz.getName()); if (dim != 0) type = TypeX.makeArray(type,dim); TypePattern ret = new ExactTypePattern(type, includeSubtypes); ret.copyLocationFrom(this); return ret; } } else if (requireExactType) { return NO; } importedPrefixes = SimpleScope.javaLangPrefixArray; knownMatches = new String[0]; return this; } private Class maybeGetPrimitiveClass(String typeName) { return (Class) ExactTypePattern.primitiveTypesMap.get(typeName); } public boolean isStar() { 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]); //??? 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(ResolvedTypeX enclosingType) { // this.importedPrefixes = enclosingType.getImportedPrefixes(); // this.knownNames = prematch(enclosingType.getImportedNames()); // } public String toString() { StringBuffer buf = new StringBuffer(); 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()); } } 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; for (int i=0; i < len; i++) { if (!o.namePatterns[i].equals(this.namePatterns[i])) return false; } return true; } public int hashCode() { int result = 17; for (int i = 0, len = namePatterns.length; i < len; i++) { result = 37*result + namePatterns[i].hashCode(); } return result; } public FuzzyBoolean matchesInstanceof(Class type) { return FuzzyBoolean.NO; } public boolean matchesExactly(Class type) { return matchesExactlyByName(type.getName()); } /** * @see org.aspectj.weaver.patterns.PatternNode#write(DataOutputStream) */ public void write(DataOutputStream s) throws IOException { s.writeByte(TypePattern.WILD); s.writeShort(namePatterns.length); for (int i = 0; i < namePatterns.length; i++) { namePatterns[i].write(s); } s.writeBoolean(includeSubtypes); s.writeInt(dim); //??? 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); } public static TypePattern read(DataInputStream 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); ret.knownMatches = FileUtil.readStringArray(s); ret.importedPrefixes = FileUtil.readStringArray(s); ret.readLocation(context, s); return ret; } }
69,459
Bug 69459 Hiding of Instance Methods by static methods
Using Introduction it is possible to hide instance methods by static methods. Example: class Super { public void m(){}; } class Sub {} aspect A { public static void Sub.m(){} } Acccording to the Java Language Specification this is not allowed. Is this behaviour desired ?? It is also possible to override static methods by instance methods, wich causes a compile time error in java.
resolved fixed
b184363
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2004-07-27T14:17:32Z
2004-07-07T14:20:00Z
tests/bugs/intertypeOverrides/Aspect1.java
69,459
Bug 69459 Hiding of Instance Methods by static methods
Using Introduction it is possible to hide instance methods by static methods. Example: class Super { public void m(){}; } class Sub {} aspect A { public static void Sub.m(){} } Acccording to the Java Language Specification this is not allowed. Is this behaviour desired ?? It is also possible to override static methods by instance methods, wich causes a compile time error in java.
resolved fixed
b184363
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2004-07-27T14:17:32Z
2004-07-07T14:20:00Z
tests/bugs/intertypeOverrides/Aspect2.java
69,459
Bug 69459 Hiding of Instance Methods by static methods
Using Introduction it is possible to hide instance methods by static methods. Example: class Super { public void m(){}; } class Sub {} aspect A { public static void Sub.m(){} } Acccording to the Java Language Specification this is not allowed. Is this behaviour desired ?? It is also possible to override static methods by instance methods, wich causes a compile time error in java.
resolved fixed
b184363
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2004-07-27T14:17:32Z
2004-07-07T14:20:00Z
tests/bugs/intertypeOverrides/IntertypeOverrides.java
69,459
Bug 69459 Hiding of Instance Methods by static methods
Using Introduction it is possible to hide instance methods by static methods. Example: class Super { public void m(){}; } class Sub {} aspect A { public static void Sub.m(){} } Acccording to the Java Language Specification this is not allowed. Is this behaviour desired ?? It is also possible to override static methods by instance methods, wich causes a compile time error in java.
resolved fixed
b184363
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2004-07-27T14:17:32Z
2004-07-07T14:20:00Z
tests/bugs/intertypeOverrides/IntertypeOverrides2.java
69,459
Bug 69459 Hiding of Instance Methods by static methods
Using Introduction it is possible to hide instance methods by static methods. Example: class Super { public void m(){}; } class Sub {} aspect A { public static void Sub.m(){} } Acccording to the Java Language Specification this is not allowed. Is this behaviour desired ?? It is also possible to override static methods by instance methods, wich causes a compile time error in java.
resolved fixed
b184363
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2004-07-27T14:17:32Z
2004-07-07T14:20:00Z
tests/bugs/intertypeOverrides/Subclass.java
69,459
Bug 69459 Hiding of Instance Methods by static methods
Using Introduction it is possible to hide instance methods by static methods. Example: class Super { public void m(){}; } class Sub {} aspect A { public static void Sub.m(){} } Acccording to the Java Language Specification this is not allowed. Is this behaviour desired ?? It is also possible to override static methods by instance methods, wich causes a compile time error in java.
resolved fixed
b184363
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2004-07-27T14:17:32Z
2004-07-07T14:20:00Z
tests/bugs/intertypeOverrides/Superclass.java
69,459
Bug 69459 Hiding of Instance Methods by static methods
Using Introduction it is possible to hide instance methods by static methods. Example: class Super { public void m(){}; } class Sub {} aspect A { public static void Sub.m(){} } Acccording to the Java Language Specification this is not allowed. Is this behaviour desired ?? It is also possible to override static methods by instance methods, wich causes a compile time error in java.
resolved fixed
b184363
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2004-07-27T14:17:32Z
2004-07-07T14:20:00Z
weaver/src/org/aspectj/weaver/ResolvedTypeX.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Common Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * PARC initial implementation * ******************************************************************/ package org.aspectj.weaver; import java.lang.reflect.Modifier; 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.bridge.IMessage; import org.aspectj.bridge.ISourceLocation; import org.aspectj.bridge.Message; import org.aspectj.bridge.MessageUtil; import org.aspectj.weaver.patterns.Declare; import org.aspectj.weaver.patterns.PerClause; public abstract class ResolvedTypeX extends TypeX { protected World world; ResolvedTypeX(String signature, World world) { super(signature); this.world = world; } // ---- things that don't require a world /** returns Iterator&lt;ResolvedTypeX&gt; */ public final Iterator getDirectSupertypes() { Iterator ifacesIterator = Iterators.array(getDeclaredInterfaces()); ResolvedTypeX superclass = getSuperclass(); if (superclass == null) { return ifacesIterator; } else { return Iterators.snoc(ifacesIterator, superclass); } } public abstract ResolvedMember[] getDeclaredFields(); public abstract ResolvedMember[] getDeclaredMethods(); public abstract ResolvedTypeX[] getDeclaredInterfaces(); public abstract ResolvedMember[] getDeclaredPointcuts(); public abstract ResolvedTypeX getSuperclass(); public abstract int getModifiers(); public abstract boolean needsNoConversionFrom(TypeX other); public abstract boolean isCoerceableFrom(TypeX other); public abstract boolean isAssignableFrom(TypeX other); // ---- things that would require a world if I weren't resolved public final Iterator getDirectSupertypes(World world) { return getDirectSupertypes(); } public final ResolvedMember[] getDeclaredFields(World world) { return getDeclaredFields(); } public final ResolvedMember[] getDeclaredMethods(World world) { return getDeclaredMethods(); } public final TypeX[] getDeclaredInterfaces(World world) { return getDeclaredInterfaces(); } public final ResolvedMember[] getDeclaredPointcuts(World world) { return getDeclaredPointcuts(); } public final int getModifiers(World world) { return getModifiers(); } public final TypeX getSuperclass(World world) { return getSuperclass(); } // conversions public final boolean isAssignableFrom(TypeX other, World world) { return isAssignableFrom(other); } public final boolean isCoerceableFrom(TypeX other, World world) { return isCoerceableFrom(other); } public boolean needsNoConversionFrom(TypeX other, World world) { return needsNoConversionFrom(other); } public final boolean isConvertableFrom(TypeX other) { if (this.equals(OBJECT) || other.equals(OBJECT)) return true; return this.isCoerceableFrom(other); } // utilities public ResolvedTypeX getResolvedComponentType() { return null; } public ResolvedTypeX resolve(World world) { return this; } public World getWorld() { return world; } // ---- things from object public final boolean equals(Object other) { if (other instanceof ResolvedTypeX) { return this == other; } else { return super.equals(other); } } // ---- difficult things /** * returns an iterator through all of the fields of this type, in order * for checking from JVM spec 2ed 5.4.3.2. This means that the order is * * <ul><li> fields from current class </li> * <li> recur into direct superinterfaces </li> * <li> recur into superclass </li> * </ul> * * We keep a hashSet of interfaces that we've visited so we don't spiral * out into 2^n land. */ public Iterator getFields() { final Iterators.Filter dupFilter = Iterators.dupFilter(); Iterators.Getter typeGetter = new Iterators.Getter() { public Iterator get(Object o) { return dupFilter.filter( ((ResolvedTypeX)o).getDirectSupertypes()); } }; Iterators.Getter fieldGetter = new Iterators.Getter() { public Iterator get(Object o) { return Iterators.array(((ResolvedTypeX)o).getDeclaredFields()); } }; return Iterators.mapOver( Iterators.recur(this, typeGetter), fieldGetter); } /** * returns an iterator through all of the methods of this type, in order * for checking from JVM spec 2ed 5.4.3.3. This means that the order is * * <ul><li> methods from current class </li> * <li> recur into superclass, all the way up, not touching interfaces </li> * <li> recur into all superinterfaces, in some unspecified order </li> * </ul> * * We keep a hashSet of interfaces that we've visited so we don't spiral * out into 2^n land. */ public Iterator getMethods() { final Iterators.Filter dupFilter = Iterators.dupFilter(); Iterators.Getter ifaceGetter = new Iterators.Getter() { public Iterator get(Object o) { return dupFilter.filter( Iterators.array(((ResolvedTypeX)o).getDeclaredInterfaces()) ); } }; Iterators.Getter methodGetter = new Iterators.Getter() { public Iterator get(Object o) { return Iterators.array(((ResolvedTypeX)o).getDeclaredMethods()); } }; return Iterators.mapOver( Iterators.append( new Iterator() { ResolvedTypeX curr = ResolvedTypeX.this; public boolean hasNext() { return curr != null; } public Object next() { ResolvedTypeX ret = curr; curr = curr.getSuperclass(); return ret; } public void remove() { throw new UnsupportedOperationException(); } }, Iterators.recur(this, ifaceGetter)), methodGetter); } /** * described in JVM spec 2ed 5.4.3.2 */ public ResolvedMember lookupField(Member m) { return lookupMember(m, getFields()); } /** * described in JVM spec 2ed 5.4.3.3 */ public ResolvedMember lookupMethod(Member m) { return lookupMember(m, getMethods()); } /** return null if not found */ private ResolvedMember lookupMember(Member m, Iterator i) { while (i.hasNext()) { ResolvedMember f = (ResolvedMember) i.next(); if (matches(f, m)) return f; } return null; //ResolvedMember.Missing; //throw new BCException("can't find " + m); } /** return null if not found */ private ResolvedMember lookupMember(Member m, ResolvedMember[] a) { for (int i = 0; i < a.length; i++) { ResolvedMember f = a[i]; if (matches(f, m)) return f; } return null; } public static boolean matches(Member m1, Member m2) { if (m1 == null) return m2 == null; if (m2 == null) return false; return m1.getName().equals(m2.getName()) && m1.getSignature().equals(m2.getSignature()); } public static boolean conflictingSignature(Member m1, Member m2) { if (m1 == null || m2 == null) return false; if (!m1.getName().equals(m2.getName())) { return false; } if (m1.getKind() != m2.getKind()) { return false; } if (m1.getKind() == Member.FIELD) { return m1.getDeclaringType().equals(m2.getDeclaringType()); } else if (m1.getKind() == Member.POINTCUT) { return true; } TypeX[] p1 = m1.getParameterTypes(); TypeX[] p2 = m2.getParameterTypes(); int n = p1.length; if (n != p2.length) return false; for (int i=0; i < n; i++) { if (!p1[i].equals(p2[i])) return false; } return true; } /** * returns an iterator through all of the pointcuts of this type, in order * for checking from JVM spec 2ed 5.4.3.2 (as for fields). This means that the order is * * <ul><li> pointcuts from current class </li> * <li> recur into direct superinterfaces </li> * <li> recur into superclass </li> * </ul> * * We keep a hashSet of interfaces that we've visited so we don't spiral * out into 2^n land. */ public Iterator getPointcuts() { final Iterators.Filter dupFilter = Iterators.dupFilter(); // same order as fields Iterators.Getter typeGetter = new Iterators.Getter() { public Iterator get(Object o) { return dupFilter.filter( ((ResolvedTypeX)o).getDirectSupertypes()); } }; Iterators.Getter pointcutGetter = new Iterators.Getter() { public Iterator get(Object o) { //System.err.println("getting for " + o); return Iterators.array(((ResolvedTypeX)o).getDeclaredPointcuts()); } }; return Iterators.mapOver( Iterators.recur(this, typeGetter), pointcutGetter); } public ResolvedPointcutDefinition findPointcut(String name) { //System.err.println("looking for pointcuts " + this); for (Iterator i = getPointcuts(); i.hasNext(); ) { ResolvedPointcutDefinition f = (ResolvedPointcutDefinition) i.next(); //System.err.println(f); if (name.equals(f.getName())) { return f; } } return null; // should we throw an exception here? } // all about collecting CrosscuttingMembers //??? collecting data-structure, shouldn't really be a field public CrosscuttingMembers crosscuttingMembers; public CrosscuttingMembers collectCrosscuttingMembers() { crosscuttingMembers = new CrosscuttingMembers(this); crosscuttingMembers.setPerClause(getPerClause()); crosscuttingMembers.addShadowMungers(collectShadowMungers()); crosscuttingMembers.addTypeMungers(getTypeMungers()); crosscuttingMembers.addDeclares(collectDeclares(!this.doesNotExposeShadowMungers())); crosscuttingMembers.addPrivilegedAccesses(getPrivilegedAccesses()); //System.err.println("collected cc members: " + this + ", " + collectDeclares()); return crosscuttingMembers; } public final Collection collectDeclares(boolean includeAdviceLike) { if (! this.isAspect() ) return Collections.EMPTY_LIST; ArrayList ret = new ArrayList(); //if (this.isAbstract()) { for (Iterator i = getDeclares().iterator(); i.hasNext();) { Declare dec = (Declare) i.next(); if (!dec.isAdviceLike()) ret.add(dec); } if (!includeAdviceLike) return ret; if (!this.isAbstract()) { //ret.addAll(getDeclares()); final Iterators.Filter dupFilter = Iterators.dupFilter(); Iterators.Getter typeGetter = new Iterators.Getter() { public Iterator get(Object o) { return dupFilter.filter( ((ResolvedTypeX)o).getDirectSupertypes()); } }; Iterator typeIterator = Iterators.recur(this, typeGetter); while (typeIterator.hasNext()) { ResolvedTypeX ty = (ResolvedTypeX) typeIterator.next(); //System.out.println("super: " + ty + ", " + ); for (Iterator i = ty.getDeclares().iterator(); i.hasNext();) { Declare dec = (Declare) i.next(); if (dec.isAdviceLike()) ret.add(dec); } } } return ret; } private final Collection collectShadowMungers() { if (! this.isAspect() || this.isAbstract() || this.doesNotExposeShadowMungers()) return Collections.EMPTY_LIST; ArrayList acc = new ArrayList(); final Iterators.Filter dupFilter = Iterators.dupFilter(); Iterators.Getter typeGetter = new Iterators.Getter() { public Iterator get(Object o) { return dupFilter.filter( ((ResolvedTypeX)o).getDirectSupertypes()); } }; Iterator typeIterator = Iterators.recur(this, typeGetter); while (typeIterator.hasNext()) { ResolvedTypeX ty = (ResolvedTypeX) typeIterator.next(); acc.addAll(ty.getDeclaredShadowMungers()); } return acc; } protected boolean doesNotExposeShadowMungers() { return false; } public PerClause getPerClause() { return null; } protected Collection getDeclares() { return Collections.EMPTY_LIST; } protected Collection getTypeMungers() { return Collections.EMPTY_LIST; } protected Collection getPrivilegedAccesses() { return Collections.EMPTY_LIST; } // ---- useful things public final boolean isInterface() { return Modifier.isInterface(getModifiers()); } public final boolean isAbstract() { return Modifier.isAbstract(getModifiers()); } public boolean isClass() { return false; } public boolean isAspect() { return false; } public boolean isSynthetic() { return signature.indexOf("$ajc") != -1; } public final boolean isFinal() { return Modifier.isFinal(getModifiers()); } public Collection getDeclaredAdvice() { List l = new ArrayList(); ResolvedMember[] methods = getDeclaredMethods(); for (int i=0, len = methods.length; i < len; i++) { ShadowMunger munger = methods[i].getAssociatedShadowMunger(); if (munger != null) l.add(munger); } return l; } private List shadowMungers = new ArrayList(0); public Collection getDeclaredShadowMungers() { Collection c = getDeclaredAdvice(); c.addAll(shadowMungers); return c; } public void addShadowMunger(ShadowMunger munger) { shadowMungers.add(munger); } // ---- only for testing! public ResolvedMember[] getDeclaredJavaFields() { return filterInJavaVisible(getDeclaredFields()); } public ResolvedMember[] getDeclaredJavaMethods() { return filterInJavaVisible(getDeclaredMethods()); } public ShadowMunger[] getDeclaredShadowMungersArray() { List l = (List) getDeclaredShadowMungers(); return (ShadowMunger[]) l.toArray(new ShadowMunger[l.size()]); } private ResolvedMember[] filterInJavaVisible(ResolvedMember[] ms) { List l = new ArrayList(); for (int i=0, len = ms.length; i < len; i++) { if (! ms[i].isAjSynthetic() && ms[i].getAssociatedShadowMunger() == null) { l.add(ms[i]); } } return (ResolvedMember[]) l.toArray(new ResolvedMember[l.size()]); } public abstract ISourceContext getSourceContext(); // ---- fields public static final ResolvedTypeX[] NONE = new ResolvedTypeX[0]; public static final Primitive BYTE = new Primitive("B", 1, 0); public static final Primitive CHAR = new Primitive("C", 1, 1); public static final Primitive DOUBLE = new Primitive("D", 2, 2); public static final Primitive FLOAT = new Primitive("F", 1, 3); public static final Primitive INT = new Primitive("I", 1, 4); public static final Primitive LONG = new Primitive("J", 2, 5); public static final Primitive SHORT = new Primitive("S", 1, 6); public static final Primitive VOID = new Primitive("V", 0, 8); public static final Primitive BOOLEAN = new Primitive("Z", 1, 7); public static final Missing MISSING = new Missing(); // ---- types public static class Name extends ResolvedTypeX { private ConcreteName delegate = null; private ISourceContext sourceContext = null; private int startPos = 0; private int endPos = 0; //??? should set delegate before any use public Name(String signature, World world) { super(signature, world); } public final boolean isClass() { return delegate.isClass(); } public boolean isAspect() { return delegate.isAspect(); } public final boolean needsNoConversionFrom(TypeX o) { return isAssignableFrom(o); } public final boolean isAssignableFrom(TypeX o) { if (o.isPrimitive()) return false; ResolvedTypeX other = o.resolve(world); return isAssignableFrom(other); } public final boolean isCoerceableFrom(TypeX o) { ResolvedTypeX other = o.resolve(world); if (this.isAssignableFrom(other) || other.isAssignableFrom(this)) { return true; } 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 = ((Name)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 boolean isAssignableFrom(ResolvedTypeX other) { if (this == other) return true; for(Iterator i = other.getDirectSupertypes(); i.hasNext(); ) { if (this.isAssignableFrom((ResolvedTypeX) i.next())) return true; } return false; } public ISourceContext getSourceContext() { return sourceContext; } public ISourceLocation getSourceLocation() { if (sourceContext == null) return null; return sourceContext.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() { return delegate.getDeclaredFields(); } public ResolvedTypeX[] getDeclaredInterfaces() { return delegate.getDeclaredInterfaces(); } public ResolvedMember[] getDeclaredMethods() { return delegate.getDeclaredMethods(); } public ResolvedMember[] getDeclaredPointcuts() { return delegate.getDeclaredPointcuts(); } public PerClause getPerClause() { return delegate.getPerClause(); } protected Collection getDeclares() { return delegate.getDeclares(); } protected Collection getTypeMungers() { return delegate.getTypeMungers(); } protected Collection getPrivilegedAccesses() { return delegate.getPrivilegedAccesses(); } public int getModifiers() { return delegate.getModifiers(); } public ResolvedTypeX getSuperclass() { return delegate.getSuperclass(); } public ConcreteName getDelegate() { return delegate; } public void setDelegate(ConcreteName delegate) { this.delegate = delegate; } public int getEndPos() { return endPos; } public int getStartPos() { return startPos; } public void setEndPos(int endPos) { this.endPos = endPos; } public void setSourceContext(ISourceContext sourceContext) { this.sourceContext = sourceContext; } public void setStartPos(int startPos) { this.startPos = startPos; } public boolean doesNotExposeShadowMungers() { return delegate.doesNotExposeShadowMungers(); } } public static abstract class ConcreteName { //protected ISourceContext sourceContext; protected boolean exposedToWeaver; protected ResolvedTypeX.Name resolvedTypeX; public ConcreteName(ResolvedTypeX.Name resolvedTypeX, boolean exposedToWeaver) { //???super(signature, world); this.resolvedTypeX = resolvedTypeX; this.exposedToWeaver = exposedToWeaver; } public final boolean isClass() { return !isAspect() && !isInterface(); } public abstract boolean isAspect(); public abstract boolean isInterface(); public abstract ResolvedMember[] getDeclaredFields(); public abstract ResolvedTypeX[] getDeclaredInterfaces(); public abstract ResolvedMember[] getDeclaredMethods(); public abstract ResolvedMember[] getDeclaredPointcuts(); public abstract PerClause getPerClause(); protected abstract Collection getDeclares() ; protected abstract Collection getTypeMungers(); protected abstract Collection getPrivilegedAccesses(); public abstract int getModifiers(); public abstract ResolvedTypeX getSuperclass(); // public abstract ISourceLocation getSourceLocation(); public abstract WeaverStateInfo getWeaverState(); // public ISourceContext getSourceContext() { // return sourceContext; // } /** * Designed to be overriden by EclipseType to disable collection of shadow mungers * during pre-weave compilation phase */ public boolean doesNotExposeShadowMungers() { return false; } public boolean isExposedToWeaver() { return exposedToWeaver; } public ResolvedTypeX.Name getResolvedTypeX() { return resolvedTypeX; } } static class Array extends ResolvedTypeX { ResolvedTypeX componentType; Array(String s, World world, ResolvedTypeX componentType) { super(s, world); this.componentType = componentType; } public final ResolvedMember[] getDeclaredFields() { return ResolvedMember.NONE; } public final ResolvedMember[] getDeclaredMethods() { // ??? should this return clone? Probably not... return ResolvedMember.NONE; } public final ResolvedTypeX[] getDeclaredInterfaces() { return new ResolvedTypeX[] { world.resolve(CLONEABLE), world.resolve(SERIALIZABLE) }; } public final ResolvedMember[] getDeclaredPointcuts() { return ResolvedMember.NONE; } public final ResolvedTypeX getSuperclass() { return world.resolve(OBJECT); } public final boolean isAssignableFrom(TypeX o) { if (! o.isArray()) return false; if (o.getComponentType().isPrimitive()) { return o.equals(this); } else { return getComponentType().isAssignableFrom(o.getComponentType(), world); } } public final boolean isCoerceableFrom(TypeX o) { if (o.equals(TypeX.OBJECT) || o.equals(TypeX.SERIALIZABLE) || o.equals(TypeX.CLONEABLE)) { return true; } if (! o.isArray()) return false; if (o.getComponentType().isPrimitive()) { return o.equals(this); } else { return getComponentType().isCoerceableFrom(o.getComponentType(), world); } } public final boolean needsNoConversionFrom(TypeX o) { return isAssignableFrom(o); } public final int getModifiers() { int mask = Modifier.PUBLIC | Modifier.PRIVATE | Modifier.PROTECTED; return (componentType.getModifiers() & mask) | Modifier.FINAL; } public TypeX getComponentType() { return componentType; } public ResolvedTypeX getResolvedComponentType() { return componentType; } public ISourceContext getSourceContext() { return getResolvedComponentType().getSourceContext(); } } static class Primitive extends ResolvedTypeX { private int size; private int index; Primitive(String signature, int size, int index) { super(signature, null); this.size = size; this.index = index; } public final int getSize() { return size; } public final int getModifiers() { return Modifier.PUBLIC | Modifier.FINAL; } public final boolean isPrimitive() { return true; } public final boolean isAssignableFrom(TypeX other) { if (! other.isPrimitive()) return false; return assignTable[((Primitive)other).index][index]; } public final boolean isCoerceableFrom(TypeX other) { if (this == other) return true; if (! other.isPrimitive()) return false; if (index > 6 || ((Primitive)other).index > 6) return false; return true; } public final boolean needsNoConversionFrom(TypeX other) { if (! other.isPrimitive()) return false; return noConvertTable[((Primitive)other).index][index]; } private static final boolean[][] assignTable = {// to: B C D F I J S V Z from { true , true , true , true , true , true , true , false, false }, // B { false, true , true , true , true , true , false, false, false }, // C { false, false, true , false, false, false, false, false, false }, // D { false, false, true , true , false, false, false, false, false }, // F { false, false, true , true , true , true , false, false, false }, // I { false, false, true , true , false, true , false, false, false }, // J { false, false, true , true , true , true , true , false, false }, // S { false, false, false, false, false, false, false, true , false }, // V { false, false, false, false, false, false, false, false, true }, // Z }; private static final boolean[][] noConvertTable = {// to: B C D F I J S V Z from { true , true , false, false, true , false, true , false, false }, // B { false, true , false, false, true , false, false, false, false }, // C { false, false, true , false, false, false, false, false, false }, // D { false, false, false, true , false, false, false, false, false }, // F { false, false, false, false, true , false, false, false, false }, // I { false, false, false, false, false, true , false, false, false }, // J { false, false, false, false, true , false, true , false, false }, // S { false, false, false, false, false, false, false, true , false }, // V { false, false, false, false, false, false, false, false, true }, // Z }; // ---- public final ResolvedMember[] getDeclaredFields() { return ResolvedMember.NONE; } public final ResolvedMember[] getDeclaredMethods() { return ResolvedMember.NONE; } public final ResolvedTypeX[] getDeclaredInterfaces() { return ResolvedTypeX.NONE; } public final ResolvedMember[] getDeclaredPointcuts() { return ResolvedMember.NONE; } public final ResolvedTypeX getSuperclass() { return null; } public ISourceContext getSourceContext() { return null; } } static class Missing extends ResolvedTypeX { Missing() { super(MISSING_NAME, null); } // public final String toString() { // return "<missing>"; // } public final String getName() { return MISSING_NAME; } public final ResolvedMember[] getDeclaredFields() { return ResolvedMember.NONE; } public final ResolvedMember[] getDeclaredMethods() { return ResolvedMember.NONE; } public final ResolvedTypeX[] getDeclaredInterfaces() { return ResolvedTypeX.NONE; } public final ResolvedMember[] getDeclaredPointcuts() { return ResolvedMember.NONE; } public final ResolvedTypeX getSuperclass() { return null; } public final int getModifiers() { return 0; } public final boolean isAssignableFrom(TypeX other) { return false; } public final boolean isCoerceableFrom(TypeX other) { return false; } public boolean needsNoConversionFrom(TypeX other) { return false; } public ISourceContext getSourceContext() { return null; } } /** return null if not found */ public ResolvedMember lookupMemberNoSupers(Member member) { ResolvedMember ret; if (member.getKind() == Member.FIELD) { ret = lookupMember(member, getDeclaredFields()); } else { // assert member.getKind() == Member.METHOD || member.getKind() == Member.CONSTRUCTOR ret = lookupMember(member, getDeclaredMethods()); } if (ret == null && interTypeMungers != null) { for (Iterator i = interTypeMungers.iterator(); i.hasNext();) { ConcreteTypeMunger tm = (ConcreteTypeMunger) i.next(); if (matches(tm.getSignature(), member)) { return tm.getSignature(); } } } return ret; } protected List interTypeMungers = new ArrayList(0); public List getInterTypeMungers() { return interTypeMungers; } /** * ??? This method is O(N*M) where N = number of methods and M is number of * inter-type declarations in my super */ public List getInterTypeMungersIncludingSupers() { ArrayList ret = new ArrayList(); collectInterTypeMungers(ret); return ret; } private void collectInterTypeMungers(List collector) { for (Iterator iter = getDirectSupertypes(); iter.hasNext();) { ResolvedTypeX superType = (ResolvedTypeX) iter.next(); superType.collectInterTypeMungers(collector); } outer: for (Iterator iter1 = collector.iterator(); iter1.hasNext(); ) { ConcreteTypeMunger superMunger = (ConcreteTypeMunger) iter1.next(); if ( superMunger.getSignature() == null) continue; if ( !superMunger.getSignature().isAbstract()) continue; for (Iterator iter = getInterTypeMungers().iterator(); iter.hasNext();) { ConcreteTypeMunger myMunger = (ConcreteTypeMunger) iter.next(); if (conflictingSignature(myMunger.getSignature(), superMunger.getSignature())) { iter1.remove(); continue outer; } } if (!superMunger.getSignature().isPublic()) continue; for (Iterator iter = getMethods(); iter.hasNext(); ) { ResolvedMember method = (ResolvedMember)iter.next(); if (conflictingSignature(method, superMunger.getSignature())) { iter1.remove(); continue outer; } } } collector.addAll(getInterTypeMungers()); } /** * Check that we don't have any abstract type mungers unless this * type is abstract. */ public void checkInterTypeMungers() { if (isAbstract()) return; for (Iterator iter = getInterTypeMungersIncludingSupers().iterator(); iter.hasNext();) { ConcreteTypeMunger element = (ConcreteTypeMunger) iter.next(); if (element.getSignature() != null && element.getSignature().isAbstract()) { world.getMessageHandler().handleMessage( new Message("must implement abstract inter-type declaration: " + element.getSignature(), "", IMessage.ERROR, getSourceLocation(), null, new ISourceLocation[] { element.getSourceLocation() })); } } } /** * Returns a ResolvedTypeX object representing the declaring type of this type, or * null if this type does not represent a non-package-level-type. * * <strong>Warning</strong>: This is guaranteed to work for all member types. * For anonymous/local types, the only guarantee is given in JLS 13.1, where * it guarantees that if you call getDeclaringType() repeatedly, you will eventually * get the top-level class, but it does not say anything about classes in between. * * @return the declaring TypeX object, or null. */ public ResolvedTypeX getDeclaringType() { if (isArray()) return null; String name = getName(); int lastDollar = name.lastIndexOf('$'); while (lastDollar != -1) { ResolvedTypeX ret = world.resolve(TypeX.forName(name.substring(0, lastDollar)), true); if (ret != ResolvedTypeX.MISSING) return ret; lastDollar = name.lastIndexOf('$', lastDollar-1); } return null; } public static boolean isVisible(int modifiers, ResolvedTypeX targetType, ResolvedTypeX fromType) { //System.err.println("mod: " + modifiers + ", " + targetType + " and " + fromType); if (Modifier.isPublic(modifiers)) { return true; } else if (Modifier.isPrivate(modifiers)) { return targetType.getOutermostType().equals(fromType.getOutermostType()); } else if (Modifier.isProtected(modifiers)) { return samePackage(targetType, fromType) || targetType.isAssignableFrom(fromType); } else { // package-visible return samePackage(targetType, fromType); } } private static boolean samePackage( ResolvedTypeX targetType, ResolvedTypeX fromType) { String p1 = targetType.getPackageName(); String p2 = fromType.getPackageName(); if (p1 == null) return p2 == null; if (p2 == null) return false; return p1.equals(p2); } public void addInterTypeMunger(ConcreteTypeMunger munger) { ResolvedMember sig = munger.getSignature(); if (sig == null || munger.getMunger() == null || munger.getMunger().getKind() == ResolvedTypeMunger.PrivilegedAccess) { interTypeMungers.add(munger); return; } //System.err.println("add: " + munger + " to " + this.getClassName() + " with " + interTypeMungers); if (sig.getKind() == Member.METHOD) { if (!compareToExistingMembers(munger, getMethods())) return; if (this.isInterface()) { if (!compareToExistingMembers(munger, Arrays.asList(world.resolve(OBJECT).getDeclaredMethods()).iterator())) return; } } else if (sig.getKind() == Member.FIELD) { if (!compareToExistingMembers(munger, Arrays.asList(getDeclaredFields()).iterator())) return; } else { if (!compareToExistingMembers(munger, Arrays.asList(getDeclaredMethods()).iterator())) return; } // now compare to existingMungers for (Iterator i = interTypeMungers.iterator(); i.hasNext(); ) { ConcreteTypeMunger existingMunger = (ConcreteTypeMunger)i.next(); if (conflictingSignature(existingMunger.getSignature(), munger.getSignature())) { //System.err.println("match " + munger + " with " + existingMunger); if (isVisible(munger.getSignature().getModifiers(), munger.getAspectType(), existingMunger.getAspectType())) { //System.err.println(" is visible"); int c = compareMemberPrecedence(sig, existingMunger.getSignature()); if (c == 0) { c = getWorld().comparePrecedence(munger.getAspectType(), existingMunger.getAspectType()); } //System.err.println(" compare: " + c); if (c < 0) { // the existing munger dominates the new munger checkLegalOverride(munger.getSignature(), existingMunger.getSignature()); return; } else if (c > 0) { // the new munger dominates the existing one checkLegalOverride(existingMunger.getSignature(), munger.getSignature()); i.remove(); break; } else { interTypeConflictError(munger, existingMunger); interTypeConflictError(existingMunger, munger); return; } } } } //System.err.println("adding: " + munger + " to " + this); interTypeMungers.add(munger); } //??? returning too soon private boolean compareToExistingMembers(ConcreteTypeMunger munger, Iterator existingMembers) { ResolvedMember sig = munger.getSignature(); while (existingMembers.hasNext()) { ResolvedMember existingMember = (ResolvedMember)existingMembers.next(); if (conflictingSignature(existingMember, munger.getSignature())) { //System.err.println("conflict: " + existingMember + " with " + munger); //System.err.println(munger.getSourceLocation() + ", " + munger.getSignature() + ", " + munger.getSignature().getSourceLocation()); if (isVisible(existingMember.getModifiers(), this, munger.getAspectType())) { int c = compareMemberPrecedence(sig, existingMember); //System.err.println(" c: " + c); if (c < 0) { // existingMember dominates munger checkLegalOverride(munger.getSignature(), existingMember); return false; } else if (c > 0) { // munger dominates existingMember checkLegalOverride(existingMember, munger.getSignature()); //interTypeMungers.add(munger); //??? might need list of these overridden abstracts continue; } else { //XXX dual errors possible if (this instanceof BcelObjectType) return false; //XXX ignores separate comp getWorld().getMessageHandler().handleMessage( MessageUtil.error("inter-type declaration from " + munger.getAspectType().getName() + " conflicts with existing member: " + existingMember, munger.getSourceLocation()) ); } } else { //interTypeMungers.add(munger); } //return; } } return true; } public boolean checkLegalOverride(ResolvedMember parent, ResolvedMember child) { //System.err.println("check: " + child.getDeclaringType() + " overrides " + parent.getDeclaringType()); if (!parent.getReturnType().equals(child.getReturnType())) { world.showMessage(IMessage.ERROR, "can't override " + parent + " with " + child + " return types don't match", child.getSourceLocation(), parent.getSourceLocation()); return false; } if (parent.getKind() == Member.POINTCUT) { TypeX[] pTypes = parent.getParameterTypes(); TypeX[] cTypes = child.getParameterTypes(); if (!Arrays.equals(pTypes, cTypes)) { world.showMessage(IMessage.ERROR, "can't override " + parent + " with " + child + " parameter types don't match", child.getSourceLocation(), parent.getSourceLocation()); return false; } } //System.err.println("check: " + child.getModifiers() + " more visible " + parent.getModifiers()); if (isMoreVisible(parent.getModifiers(), child.getModifiers())) { world.showMessage(IMessage.ERROR, "can't override " + parent + " with " + child + " visibility is reduced", child.getSourceLocation(), parent.getSourceLocation()); return false; } // check declared exceptions ResolvedTypeX[] childExceptions = world.resolve(child.getExceptions()); ResolvedTypeX[] parentExceptions = world.resolve(parent.getExceptions()); ResolvedTypeX runtimeException = world.resolve("java.lang.RuntimeException"); ResolvedTypeX error = world.resolve("java.lang.Error"); outer: for (int i=0, leni = childExceptions.length; i < leni; i++) { //System.err.println("checking: " + childExceptions[i]); if (runtimeException.isAssignableFrom(childExceptions[i])) continue; if (error.isAssignableFrom(childExceptions[i])) continue; for (int j = 0, lenj = parentExceptions.length; j < lenj; j++) { if (parentExceptions[j].isAssignableFrom(childExceptions[i])) continue outer; } world.showMessage(IMessage.ERROR, "overriden method doesn't throw " + childExceptions[i].getName(), child.getSourceLocation(), null); return false; } return true; } private int compareMemberPrecedence(ResolvedMember m1, ResolvedMember m2) { //if (!m1.getReturnType().equals(m2.getReturnType())) return 0; if (Modifier.isAbstract(m1.getModifiers())) return -1; if (Modifier.isAbstract(m2.getModifiers())) return +1; if (m1.getDeclaringType().equals(m2.getDeclaringType())) return 0; ResolvedTypeX t1 = m1.getDeclaringType().resolve(world); ResolvedTypeX t2 = m2.getDeclaringType().resolve(world); if (t1.isAssignableFrom(t2)) { return -1; } if (t2.isAssignableFrom(t1)) { return +1; } return 0; } public static boolean isMoreVisible(int m1, int m2) { if (Modifier.isPrivate(m1)) return false; if (isPackage(m1)) return Modifier.isPrivate(m2); if (Modifier.isProtected(m1)) return /* private package */ (Modifier.isPrivate(m2) || isPackage(m2)); if (Modifier.isPublic(m1)) return /* private package protected */ ! Modifier.isPublic(m2); throw new RuntimeException("bad modifier: " + m1); } private static boolean isPackage(int i) { return (0 == (i & (Modifier.PUBLIC | Modifier.PRIVATE | Modifier.PROTECTED))); } private void interTypeConflictError( ConcreteTypeMunger m1, ConcreteTypeMunger m2) { //XXX this works only if we ignore separate compilation issues //XXX dual errors possible if (this instanceof BcelObjectType) return; //System.err.println("conflict at " + m2.getSourceLocation()); getWorld().showMessage(IMessage.ERROR, "intertype declaration from " + m1.getAspectType().getName() + " conflicts with intertype declaration: " + m2.getSignature() + " from " + m2.getAspectType().getName(), m2.getSourceLocation(), getSourceLocation()); } public ResolvedMember lookupSyntheticMember(Member member) { //??? horribly inefficient //for (Iterator i = //System.err.println("lookup " + member + " in " + interTypeMungers); for (Iterator i = interTypeMungers.iterator(); i.hasNext(); ) { ConcreteTypeMunger m = (ConcreteTypeMunger)i.next(); ResolvedMember ret = m.getMatchingSyntheticMember(member); if (ret != null) { //System.err.println(" found: " + ret); return ret; } } return null; } public void clearInterTypeMungers() { interTypeMungers = new ArrayList(); } public boolean isTopmostImplementor(ResolvedTypeX interfaceType) { if (isInterface()) return false; if (!interfaceType.isAssignableFrom(this)) return false; // check that I'm truly the topmost implementor if (interfaceType.isAssignableFrom(this.getSuperclass())) { return false; } return true; } public List getExposedPointcuts() { List ret = new ArrayList(); if (getSuperclass() != null) ret.addAll(getSuperclass().getExposedPointcuts()); for (Iterator i = Arrays.asList(getDeclaredInterfaces()).iterator(); i.hasNext(); ) { ResolvedTypeX t = (ResolvedTypeX)i.next(); addPointcutsResolvingConflicts(ret, Arrays.asList(t.getDeclaredPointcuts()), false); } addPointcutsResolvingConflicts(ret, Arrays.asList(getDeclaredPointcuts()), true); for (Iterator i = ret.iterator(); i.hasNext(); ) { ResolvedPointcutDefinition inherited = (ResolvedPointcutDefinition)i.next(); // System.err.println("looking at: " + inherited + " in " + this); // System.err.println(" " + inherited.isAbstract() + " in " + this.isAbstract()); if (inherited.isAbstract()) { if (!this.isAbstract()) { getWorld().showMessage(IMessage.ERROR, "inherited abstract " + inherited + " is not made concrete in " + this.getName(), inherited.getSourceLocation(), this.getSourceLocation()); } } } return ret; } private void addPointcutsResolvingConflicts(List acc, List added, boolean isOverriding) { for (Iterator i = added.iterator(); i.hasNext();) { ResolvedPointcutDefinition toAdd = (ResolvedPointcutDefinition) i.next(); //System.err.println("adding: " + toAdd); for (Iterator j = acc.iterator(); j.hasNext();) { ResolvedPointcutDefinition existing = (ResolvedPointcutDefinition) j.next(); if (existing == toAdd) continue; if (!isVisible(existing.getModifiers(), existing.getDeclaringType().resolve(getWorld()), this)) { continue; } if (conflictingSignature(existing, toAdd)) { if (isOverriding) { checkLegalOverride(existing, toAdd); j.remove(); } else { getWorld().showMessage( IMessage.ERROR, "conflicting inherited pointcuts in " + this.getName() + toAdd.getSignature(), existing.getSourceLocation(), toAdd.getSourceLocation()); j.remove(); } } } acc.add(toAdd); } } public ISourceLocation getSourceLocation() { return null; } public boolean isExposedToWeaver() { return false; } public WeaverStateInfo getWeaverState() { return null; } }
58,681
Bug 58681 -X should output available -X options
ajc should emit the available -X options on -help or -X request (the latter like java) to get more traffic and feedback on the experimental options.
resolved fixed
6ea8300
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2004-07-27T15:44:24Z
2004-04-15T17:26:40Z
org.aspectj.ajdt.core/src/org/aspectj/ajdt/ajc/AjdtCommand.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Common Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * PARC initial implementation * ******************************************************************/ package org.aspectj.ajdt.ajc; import org.aspectj.ajdt.internal.core.builder.*; import org.aspectj.bridge.*; import org.eclipse.jdt.internal.core.builder.MissingSourceFileException; /** * ICommand adapter for the AspectJ compiler. * Not thread-safe. */ public class AjdtCommand implements ICommand { /** Message String for any AbortException thrown from ICommand API's */ public static final String ABORT_MESSAGE = "ABORT"; // private boolean canRepeatCommand = true; AjBuildManager buildManager = null; String[] savedArgs = null; /** * Run AspectJ compiler, wrapping any exceptions thrown as * ABORT messages (containing ABORT_MESSAGE String). * @param args the String[] for the compiler * @param handler the IMessageHandler for any messages * @see org.aspectj.bridge.ICommand#runCommand(String[], IMessageHandler) * @return false if handler has errors or the command failed */ public boolean runCommand(String[] args, IMessageHandler handler) { buildManager = new AjBuildManager(handler); savedArgs = new String[args.length]; System.arraycopy(args, 0, savedArgs, 0, savedArgs.length); for (int i = 0; i < args.length; i++) { if ("-help".equals(args[i])) { // should be info, but handler usually suppresses MessageUtil.abort(handler, BuildArgParser.getUsage()); return true; } } return doCommand(handler, false); } /** * Run AspectJ compiler, wrapping any exceptions thrown as * ABORT messages (containing ABORT_MESSAGE String). * @param handler the IMessageHandler for any messages * @see org.aspectj.bridge.ICommand#repeatCommand(IMessageHandler) * @return false if handler has errors or the command failed */ public boolean repeatCommand(IMessageHandler handler) { if (null == buildManager) { MessageUtil.abort(handler, "repeatCommand called before runCommand"); return false; } return doCommand(handler, true); } /** * Delegate of both runCommand and repeatCommand. * This invokes the argument parser each time * (even when repeating). * If the parser detects errors, this signals an * abort with the usage message and returns false. * @param handler the IMessageHandler sink for any messages * @param repeat if true, do incremental build, else do batch build * @return false if handler has any errors or command failed */ protected boolean doCommand(IMessageHandler handler, boolean repeat) { try { //buildManager.setMessageHandler(handler); CountingMessageHandler counter = new CountingMessageHandler(handler); if (counter.hasErrors()) { return false; } // regenerate configuration b/c world might have changed (?) AjBuildConfig config = genBuildConfig(savedArgs, counter); if (!config.shouldProceed()) { return true; } if (!config.hasSources()) { MessageUtil.error(counter, "no sources specified"); } if (counter.hasErrors()) { // print usage for config errors String usage = BuildArgParser.getUsage(); MessageUtil.abort(handler, usage); return false; } //System.err.println("errs: " + counter.hasErrors()); return ((repeat ? buildManager.incrementalBuild(config, handler) : buildManager.batchBuild(config, handler)) && !counter.hasErrors()); } catch (AbortException ae) { if (ae.isSilent()) { throw ae; } else { MessageUtil.abort(handler, ABORT_MESSAGE, ae); } } catch (MissingSourceFileException t) { MessageUtil.error(handler, t.getMessage()); } catch (Throwable t) { MessageUtil.abort(handler, ABORT_MESSAGE, t); } return false; } /** * This creates a build configuration for the arguments. * Errors reported to the handler: * <ol> * <li>The parser detects some directly</li> * <li>The parser grabs some from the error stream * emitted by its superclass</li> * <li>The configuration has a self-test</li> * </ol> * In the latter two cases, the errors do not have * a source location context for locating the error. */ public static AjBuildConfig genBuildConfig(String[] args, CountingMessageHandler handler) { BuildArgParser parser = new BuildArgParser(handler); AjBuildConfig config = parser.genBuildConfig(args); ISourceLocation location = null; if (config.getConfigFile() != null) { location = new SourceLocation(config.getConfigFile(), 0); } String message = parser.getOtherMessages(true); if (null != message) { IMessage.Kind kind = inferKind(message); IMessage m = new Message(message, kind, null, location); handler.handleMessage(m); } // message = config.configErrors(); // if (null != message) { // IMessage.Kind kind = inferKind(message); // IMessage m = new Message(message, kind, null, location); // handler.handleMessage(m); // } return config; } /** @return IMessage.WARNING unless message contains error or info */ protected static IMessage.Kind inferKind(String message) { // XXX dubious if (-1 != message.indexOf("error")) { return IMessage.ERROR; } else if (-1 != message.indexOf("info")) { return IMessage.INFO; } else { return IMessage.WARNING; } } }
58,681
Bug 58681 -X should output available -X options
ajc should emit the available -X options on -help or -X request (the latter like java) to get more traffic and feedback on the experimental options.
resolved fixed
6ea8300
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2004-07-27T15:44:24Z
2004-04-15T17:26:40Z
org.aspectj.ajdt.core/src/org/aspectj/ajdt/ajc/BuildArgParser.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Common Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * PARC initial implementation * ******************************************************************/ package org.aspectj.ajdt.ajc; import java.io.*; import java.util.*; import org.aspectj.ajdt.internal.core.builder.*; import org.aspectj.bridge.*; import org.aspectj.util.*; import org.eclipse.jdt.core.compiler.InvalidInputException; import org.eclipse.jdt.internal.compiler.batch.Main; import org.eclipse.jdt.internal.compiler.impl.CompilerOptions; public class BuildArgParser extends Main { private static final String BUNDLE_NAME = "org.aspectj.ajdt.ajc.messages"; private static boolean LOADED_BUNDLE = false; static { bundle = ResourceBundle.getBundle(BUNDLE_NAME); if (!LOADED_BUNDLE) { LOADED_BUNDLE = true; } } /** to initialize super's PrintWriter but refer to underlying StringWriter */ private static class StringPrintWriter extends PrintWriter { public final StringWriter stringWriter; StringPrintWriter(StringWriter sw) { super(sw); this.stringWriter = sw; } } /** @return multi-line String usage for the compiler */ public static String getUsage() { return Main.bind("misc.usage"); } /** * StringWriter sink for some errors. * This only captures errors not handled by any IMessageHandler parameter * and only when no PrintWriter is set in the constructor. * XXX This relies on (Sun's) implementation of StringWriter, * which returns the actual (not copy) internal StringBuffer. */ private final StringBuffer errorSink; private IMessageHandler handler; /** * Overrides super's bundle. */ public BuildArgParser(PrintWriter writer, IMessageHandler handler) { super(writer, writer, false); if (writer instanceof StringPrintWriter) { errorSink = ((StringPrintWriter) writer).stringWriter.getBuffer(); } else { errorSink = null; } this.handler = handler; } /** Set up to capture messages using getOtherMessages(boolean) */ public BuildArgParser(IMessageHandler handler) { this(new StringPrintWriter(new StringWriter()),handler); } /** * Generate build configuration for the input args, * passing to handler any error messages. * @param args the String[] arguments for the build configuration * @return AjBuildConfig per args, * which will be invalid unless there are no handler errors. */ public AjBuildConfig genBuildConfig(String[] args) { AjBuildConfig config = new AjBuildConfig(); populateBuildConfig(config, args, true, null); return config; } /** * Generate build configuration for the input args, * passing to handler any error messages. * @param args the String[] arguments for the build configuration * @param setClasspath determines if the classpath should be parsed and set on the build configuration * @param configFile can be null * @return AjBuildConfig per args, * which will be invalid unless there are no handler errors. */ public AjBuildConfig populateBuildConfig(AjBuildConfig buildConfig, String[] args, boolean setClasspath, File configFile) { buildConfig.setConfigFile(configFile); try { // sets filenames to be non-null in order to make sure that file paramters are ignored super.filenames = new String[] { "" }; AjcConfigParser parser = new AjcConfigParser(buildConfig, handler); parser.parseCommandLine(args); boolean incrementalMode = buildConfig.isIncrementalMode() || buildConfig.isIncrementalFileMode(); List fileList = new ArrayList(); List files = parser.getFiles(); if (!LangUtil.isEmpty(files)) { if (incrementalMode) { MessageUtil.error(handler, "incremental mode only handles source files using -sourceroots"); } else { fileList.addAll(files); } } List javaArgList = new ArrayList(); // disable all special eclipse warnings by default - why??? //??? might want to instead override getDefaultOptions() javaArgList.add("-warn:none"); // these next four lines are some nonsense to fool the eclipse batch compiler // without these it will go searching for reasonable values from properties //TODO fix org.eclipse.jdt.internal.compiler.batch.Main so this hack isn't needed javaArgList.add("-classpath"); javaArgList.add(System.getProperty("user.dir")); javaArgList.add("-bootclasspath"); javaArgList.add(System.getProperty("user.dir")); javaArgList.addAll(parser.getUnparsedArgs()); super.configure((String[])javaArgList.toArray(new String[javaArgList.size()])); if (!proceed) { buildConfig.doNotProceed(); return buildConfig; } if (buildConfig.getSourceRoots() != null) { for (Iterator i = buildConfig.getSourceRoots().iterator(); i.hasNext(); ) { fileList.addAll(collectSourceRootFiles((File)i.next())); } } buildConfig.setFiles(fileList); if (destinationPath != null) { // XXX ?? unparsed but set? buildConfig.setOutputDir(new File(destinationPath)); } if (setClasspath) { buildConfig.setClasspath(getClasspath(parser)); } if (incrementalMode && (0 == buildConfig.getSourceRoots().size())) { MessageUtil.error(handler, "specify a source root when in incremental mode"); } setDebugOptions(); buildConfig.getOptions().set(options); } catch (InvalidInputException iie) { ISourceLocation location = null; if (buildConfig.getConfigFile() != null) { location = new SourceLocation(buildConfig.getConfigFile(), 0); } IMessage m = new Message(iie.getMessage(), IMessage.ERROR, null, location); handler.handleMessage(m); } return buildConfig; } // from super... public void printVersion() { System.err.println("AspectJ Compiler " + Version.text + " built on " + Version.time_text); //$NON-NLS-1$ System.err.flush(); } public void printUsage() { System.out.println(bind("misc.usage")); //$NON-NLS-1$ System.out.flush(); } /** * Get messages not dumped to handler or any PrintWriter. * @param flush if true, empty errors * @return null if none, String otherwise * @see BuildArgParser() */ public String getOtherMessages(boolean flush) { if (null == errorSink) { return null; } String result = errorSink.toString().trim(); if (0 == result.length()) { result = null; } if (flush) { errorSink.setLength(0); } return result; } private void setDebugOptions() { options.put( CompilerOptions.OPTION_LocalVariableAttribute, CompilerOptions.GENERATE); options.put( CompilerOptions.OPTION_LineNumberAttribute, CompilerOptions.GENERATE); options.put( CompilerOptions.OPTION_SourceFileAttribute, CompilerOptions.GENERATE); } private Collection collectSourceRootFiles(File dir) { return Arrays.asList(FileUtil.listFiles(dir, FileUtil.aspectjSourceFileFilter)); } /** * If the classpath is not set, we use the environment's java.class.path, but remove * the aspectjtools.jar entry from that list in order to prevent wierd bootstrap issues * (refer to bug#39959). */ public List getClasspath(AjcConfigParser parser) { List ret = new ArrayList(); if (parser.bootclasspath == null) { addClasspath(System.getProperty("sun.boot.class.path", ""), ret); } else { addClasspath(parser.bootclasspath, ret); } String extdirs = parser.extdirs; if (extdirs == null) { extdirs = System.getProperty("java.ext.dirs", ""); } addExtDirs(extdirs, ret); if (parser.classpath == null) { addClasspath(System.getProperty("java.class.path", ""), ret); List fixedList = new ArrayList(); for (Iterator it = ret.iterator(); it.hasNext(); ) { String entry = (String)it.next(); if (!entry.endsWith("aspectjtools.jar")) { fixedList.add(entry); } } ret = fixedList; } else { addClasspath(parser.classpath, ret); } //??? eclipse seems to put outdir on the classpath //??? we're brave and believe we don't need it return ret; } private void addExtDirs(String extdirs, List classpathCollector) { StringTokenizer tokenizer = new StringTokenizer(extdirs, File.pathSeparator); while (tokenizer.hasMoreTokens()) { // classpathCollector.add(tokenizer.nextToken()); File dirFile = new File((String)tokenizer.nextToken()); if (dirFile.canRead() && dirFile.isDirectory()) { File[] files = dirFile.listFiles(FileUtil.ZIP_FILTER); for (int i = 0; i < files.length; i++) { classpathCollector.add(files[i].getAbsolutePath()); } } else { // XXX alert on invalid -extdirs entries } } } private void addClasspath(String classpath, List classpathCollector) { StringTokenizer tokenizer = new StringTokenizer(classpath, File.pathSeparator); while (tokenizer.hasMoreTokens()) { classpathCollector.add(tokenizer.nextToken()); } } private class AjcConfigParser extends ConfigParser { private String bootclasspath = null; private String classpath = null; private String extdirs = null; private List unparsedArgs = new ArrayList(); private AjBuildConfig buildConfig; private IMessageHandler handler; public AjcConfigParser(AjBuildConfig buildConfig, IMessageHandler handler) { this.buildConfig = buildConfig; this.handler = handler; } public List getUnparsedArgs() { return unparsedArgs; } /** * Extract AspectJ-specific options (except for argfiles). * Caller should warn when sourceroots is empty but in * incremental mode. * Signals warnings or errors through handler set in constructor. */ public void parseOption(String arg, LinkedList args) { // XXX use ListIterator.remove() int nextArgIndex = args.indexOf(arg)+1; // XXX assumes unique // trim arg? if (LangUtil.isEmpty(arg)) { showWarning("empty arg found"); } else if (arg.equals("-inpath")) {; if (args.size() > nextArgIndex) { // buildConfig.getAjOptions().put(AjCompilerOptions.OPTION_Inpath, CompilerOptions.PRESERVE); List inPath = buildConfig.getInpath(); StringTokenizer st = new StringTokenizer( ((ConfigParser.Arg)args.get(nextArgIndex)).getValue(), File.pathSeparator); while (st.hasMoreTokens()) { String filename = st.nextToken(); File file = makeFile(filename); if (file.exists() && FileUtil.hasZipSuffix(filename)) { inPath.add(file); } else { if (file.isDirectory()) { inPath.add(file); } else showError("bad inpath component: " + filename); } } buildConfig.setInPath(inPath); args.remove(args.get(nextArgIndex)); } } else if (arg.equals("-injars")) {; if (args.size() > nextArgIndex) { // buildConfig.getAjOptions().put(AjCompilerOptions.OPTION_InJARs, CompilerOptions.PRESERVE); StringTokenizer st = new StringTokenizer( ((ConfigParser.Arg)args.get(nextArgIndex)).getValue(), File.pathSeparator); while (st.hasMoreTokens()) { String filename = st.nextToken(); File jarFile = makeFile(filename); if (jarFile.exists() && FileUtil.hasZipSuffix(filename)) { buildConfig.getInJars().add(jarFile); } else { File dirFile = makeFile(filename); if (dirFile.isDirectory()) { buildConfig.getInJars().add(dirFile); } else showError("bad injar: " + filename); } } args.remove(args.get(nextArgIndex)); } } else if (arg.equals("-aspectpath")) {; if (args.size() > nextArgIndex) { StringTokenizer st = new StringTokenizer( ((ConfigParser.Arg)args.get(nextArgIndex)).getValue(), File.pathSeparator); while (st.hasMoreTokens()) { String filename = st.nextToken(); File jarFile = makeFile(filename); if (jarFile.exists() && FileUtil.hasZipSuffix(filename)) { buildConfig.getAspectpath().add(jarFile); } else { showError("bad aspectpath: " + filename); } } args.remove(args.get(nextArgIndex)); } } else if (arg.equals("-sourceroots")) { if (args.size() > nextArgIndex) { List sourceRoots = new ArrayList(); StringTokenizer st = new StringTokenizer( ((ConfigParser.Arg)args.get(nextArgIndex)).getValue(), File.pathSeparator); while (st.hasMoreTokens()) { File f = makeFile(st.nextToken()); if (f.isDirectory() && f.canRead()) { sourceRoots.add(f); } else { showError("bad sourceroot: " + f); } } if (0 < sourceRoots.size()) { buildConfig.setSourceRoots(sourceRoots); } args.remove(args.get(nextArgIndex)); } else { showError("-sourceroots requires list of directories"); } } else if (arg.equals("-outjar")) { if (args.size() > nextArgIndex) { // buildConfig.getAjOptions().put(AjCompilerOptions.OPTION_OutJAR, CompilerOptions.GENERATE); File jarFile = makeFile(((ConfigParser.Arg)args.get(nextArgIndex)).getValue()); if (FileUtil.hasZipSuffix(jarFile)) { try { if (!jarFile.exists()) { jarFile.createNewFile(); } buildConfig.setOutputJar(jarFile); } catch (IOException ioe) { showError("unable to create outjar file: " + jarFile); } } else { showError("invalid -outjar file: " + jarFile); } args.remove(args.get(nextArgIndex)); } else { showError("-outjar requires jar path argument"); } } else if (arg.equals("-incremental")) { buildConfig.setIncrementalMode(true); } else if (arg.equals("-XincrementalFile")) { if (args.size() > nextArgIndex) { File file = makeFile(((ConfigParser.Arg)args.get(nextArgIndex)).getValue()); buildConfig.setIncrementalFile(file); if (!file.canRead()) { showError("bad -XincrementalFile : " + file); // if not created before recompile test, stop after first compile } args.remove(args.get(nextArgIndex)); } else { showError("-XincrementalFile requires file argument"); } } else if (arg.equals("-emacssym")) { buildConfig.setEmacsSymMode(true); buildConfig.setGenerateModelMode(true); } else if (arg.equals("-XjavadocsInModel")) { buildConfig.setGenerateModelMode(true); buildConfig.setGenerateJavadocsInModelMode(true); } else if (arg.equals("-noweave") || arg.equals( "-XnoWeave")) { buildConfig.setNoWeave(true); } else if (arg.equals("-XserializableAspects")) { buildConfig.setXserializableAspects(true); } else if (arg.equals("-XlazyTjp")) { buildConfig.setXlazyTjp(true); } else if (arg.startsWith("-Xreweavable")) { buildConfig.setXreweavable(true); if (arg.endsWith(":compress")) { buildConfig.setXreweavableCompressClasses(true); } } else if (arg.equals("-XnoInline")) { buildConfig.setXnoInline(true); } else if (arg.equals("-Xlintfile")) { if (args.size() > nextArgIndex) { File lintSpecFile = makeFile(((ConfigParser.Arg)args.get(nextArgIndex)).getValue()); // XXX relax restriction on props file suffix? if (lintSpecFile.canRead() && lintSpecFile.getName().endsWith(".properties")) { buildConfig.setLintSpecFile(lintSpecFile); } else { showError("bad -Xlintfile file: " + lintSpecFile); buildConfig.setLintSpecFile(null); } args.remove(args.get(nextArgIndex)); } else { showError("-Xlintfile requires .properties file argument"); } } else if (arg.equals("-Xlint")) { // buildConfig.getAjOptions().put( // AjCompilerOptions.OPTION_Xlint, // CompilerOptions.GENERATE); buildConfig.setLintMode(AjBuildConfig.AJLINT_DEFAULT); } else if (arg.startsWith("-Xlint:")) { if (7 < arg.length()) { buildConfig.setLintMode(arg.substring(7)); } else { showError("invalid lint option " + arg); } } else if (arg.equals("-bootclasspath")) { if (args.size() > nextArgIndex) { bootclasspath = ((ConfigParser.Arg)args.get(nextArgIndex)).getValue(); args.remove(args.get(nextArgIndex)); } else { showError("-bootclasspath requires classpath entries"); } } else if (arg.equals("-classpath")) { if (args.size() > nextArgIndex) { classpath = ((ConfigParser.Arg)args.get(nextArgIndex)).getValue(); args.remove(args.get(nextArgIndex)); } else { showError("-classpath requires classpath entries"); } } else if (arg.equals("-extdirs")) { if (args.size() > nextArgIndex) { extdirs = ((ConfigParser.Arg)args.get(nextArgIndex)).getValue(); args.remove(args.get(nextArgIndex)); } else { showError("-extdirs requires list of external directories"); } // error on directory unless -d, -{boot}classpath, or -extdirs } else if (arg.equals("-d")) { dirLookahead(arg, args, nextArgIndex); // } else if (arg.equals("-classpath")) { // dirLookahead(arg, args, nextArgIndex); // } else if (arg.equals("-bootclasspath")) { // dirLookahead(arg, args, nextArgIndex); // } else if (arg.equals("-extdirs")) { // dirLookahead(arg, args, nextArgIndex); } else if (new File(arg).isDirectory()) { showError("dir arg not permitted: " + arg); } else { // argfile, @file parsed by superclass // no eclipse options parsed: // -d args, -help (handled), // -classpath, -target, -1.3, -1.4, -source [1.3|1.4] // -nowarn, -warn:[...], -deprecation, -noImportError, // -proceedOnError, -g:[...], -preserveAllLocals, // -referenceInfo, -encoding, -verbose, -log, -time // -noExit, -repeat unparsedArgs.add(arg); } } protected void dirLookahead(String arg, LinkedList argList, int nextArgIndex) { unparsedArgs.add(arg); ConfigParser.Arg next = (ConfigParser.Arg) argList.get(nextArgIndex); String value = next.getValue(); if (!LangUtil.isEmpty(value)) { if (new File(value).isDirectory()) { unparsedArgs.add(value); argList.remove(next); return; } } } public void showError(String message) { ISourceLocation location = null; if (buildConfig.getConfigFile() != null) { location = new SourceLocation(buildConfig.getConfigFile(), 0); } IMessage errorMessage = new Message(CONFIG_MSG + message, IMessage.ERROR, null, location); handler.handleMessage(errorMessage); // MessageUtil.error(handler, CONFIG_MSG + message); } protected void showWarning(String message) { ISourceLocation location = null; if (buildConfig.getConfigFile() != null) { location = new SourceLocation(buildConfig.getConfigFile(), 0); } IMessage errorMessage = new Message(CONFIG_MSG + message, IMessage.WARNING, null, location); handler.handleMessage(errorMessage); // MessageUtil.warn(handler, message); } protected File makeFile(File dir, String name) { name = name.replace('/', File.separatorChar); File ret = new File(name); if (dir == null || ret.isAbsolute()) return ret; try { dir = dir.getCanonicalFile(); } catch (IOException ioe) { } return new File(dir, name); } } }
58,681
Bug 58681 -X should output available -X options
ajc should emit the available -X options on -help or -X request (the latter like java) to get more traffic and feedback on the experimental options.
resolved fixed
6ea8300
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2004-07-27T15:44:24Z
2004-04-15T17:26:40Z
org.aspectj.ajdt.core/src/org/aspectj/tools/ajc/Main.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Common Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * PARC initial implementation * ******************************************************************/ package org.aspectj.tools.ajc; import java.io.File; import java.io.IOException; import java.io.PrintStream; import java.util.List; import org.aspectj.bridge.AbortException; import org.aspectj.bridge.ICommand; import org.aspectj.bridge.IMessage; import org.aspectj.bridge.IMessageHandler; import org.aspectj.bridge.IMessageHolder; import org.aspectj.bridge.ISourceLocation; import org.aspectj.bridge.Message; import org.aspectj.bridge.MessageHandler; import org.aspectj.bridge.MessageUtil; import org.aspectj.bridge.ReflectionFactory; import org.aspectj.bridge.Version; import org.aspectj.util.FileUtil; import org.aspectj.util.LangUtil; /** * Programmatic and command-line interface to AspectJ compiler. * The compiler is an ICommand obtained by reflection. * Not thread-safe. * By default, messages are printed as they are emitted; * info messages go to the output stream, and * warnings and errors go to the error stream. * <p> * Clients can handle all messages by registering a holder: * <pre>Main main = new Main(); * IMessageHolder holder = new MessageHandler(); * main.setHolder(holder);</pre> * Clients can get control after each command completes * by installing a Runnable: * <pre>main.setCompletionRunner(new Runnable() {..});</pre> * */ public class Main { /** Header used when rendering exceptions for users */ public static final String THROWN_PREFIX = "Exception thrown from AspectJ "+ Version.text + LangUtil.EOL + ""+ LangUtil.EOL + "This might be logged as a bug already -- find current bugs at" + LangUtil.EOL + " http://bugs.eclipse.org/bugs/buglist.cgi?product=AspectJ&component=Compiler" + LangUtil.EOL + "" + LangUtil.EOL + "Bugs for exceptions thrown have titles File:line from the top stack, " + LangUtil.EOL + "e.g., \"SomeFile.java:243\"" + LangUtil.EOL + "" + LangUtil.EOL + "If you don't find the exception below in a bug, please add a new bug" + LangUtil.EOL + "at http://bugs.eclipse.org/bugs/enter_bug.cgi?product=AspectJ" + LangUtil.EOL + "To make the bug a priority, please include a test program" + LangUtil.EOL + "that can reproduce this exception." + LangUtil.EOL; private static final String OUT_OF_MEMORY_MSG = "AspectJ " + Version.text + " ran out of memory during compilation:" + LangUtil.EOL + LangUtil.EOL + "Please increase the memory available to ajc by editing the ajc script " + LangUtil.EOL + "found in your AspectJ installation directory. The -Xmx parameter value" + LangUtil.EOL + "should be increased from 64M (default) to 128M or even 256M." + LangUtil.EOL + LangUtil.EOL + "See the AspectJ FAQ available from the documentation link" + LangUtil.EOL + "on the AspectJ home page at http://www.eclipse.org/aspectj"; /** @param args the String[] of command-line arguments */ public static void main(String[] args) throws IOException { new Main().runMain(args, true); } /** * Convenience method to run ajc and collect String lists of messages. * This can be reflectively invoked with the * List collecting parameters supplied by a parent class loader. * The String messages take the same form as command-line messages. * @param args the String[] args to pass to the compiler * @param useSystemExit if true and errors, return System.exit(errs) * @param fails the List sink, if any, for String failure (or worse) messages * @param errors the List sink, if any, for String error messages * @param warnings the List sink, if any, for String warning messages * @param info the List sink, if any, for String info messages * @return number of messages reported with level ERROR or above * @throws any unchecked exceptions the compiler does */ public static int bareMain( String[] args, boolean useSystemExit, List fails, List errors, List warnings, List infos) { Main main = new Main(); MessageHandler holder = new MessageHandler(); main.setHolder(holder); try { main.runMain(args, useSystemExit); } finally { readMessages(holder, IMessage.FAIL, true, fails); readMessages(holder, IMessage.ERROR, false, errors); readMessages(holder, IMessage.WARNING, false, warnings); readMessages(holder, IMessage.INFO, false, infos); } return holder.numMessages(IMessage.ERROR, true); } /** Read messages of a given kind into a List as String */ private static void readMessages( IMessageHolder holder, IMessage.Kind kind, boolean orGreater, List sink) { if ((null == sink) || (null == holder)) { return; } IMessage[] messages = holder.getMessages(kind, orGreater); if (!LangUtil.isEmpty(messages)) { StringBuffer buf = new StringBuffer(); for (int i = 0; i < messages.length; i++) { sink.add(MessagePrinter.render(messages[i])); } } } /** * @return String rendering throwable as compiler error for user/console, * including information on how to report as a bug. * @throws NullPointerException if thrown is null */ public static String renderExceptionForUser(Throwable thrown) { String m = thrown.getMessage(); return THROWN_PREFIX + (null != m ? m + "\n": "") + LangUtil.renderException(thrown, true); } /** append nothing if numItems is 0, * numItems + label + (numItems > 1? "s" : "") otherwise, * prefixing with " " if sink has content */ private static void appendNLabel(StringBuffer sink, String label, int numItems) { if (0 == numItems) { return; } if (0 < sink.length()) { sink.append(", "); } sink.append(numItems + " "); if (!LangUtil.isEmpty(label)) { sink.append(label); } if (1 < numItems) { sink.append("s"); } } /** control iteration/continuation for command (compiler) */ protected CommandController controller; /** ReflectionFactory identifier for command (compiler) */ protected String commandName; /** client-set message sink */ private IMessageHolder clientHolder; /** internally-set message sink */ protected final MessageHandler ourHandler; private int lastFails; private int lastErrors; /** if not null, run this synchronously after each compile completes */ private Runnable completionRunner; public Main() { controller = new CommandController(); commandName = ReflectionFactory.ECLIPSE; ourHandler = new MessageHandler(true); } /** * Run without throwing exceptions but optionally using System.exit(..). * This sets up a message handler which emits messages immediately, * so report(boolean, IMessageHandler) only reports total number * of errors or warnings. * @param args the String[] command line for the compiler * @param useSystemExit if true, use System.exit(int) to complete * unless one of the args is -noExit. * and signal result (0 no exceptions/error, <0 exceptions, >0 compiler errors). */ public void runMain(String[] args, boolean useSystemExit) { boolean verbose = (-1 != ("" + LangUtil.arrayAsList(args)).indexOf("-verbose")); IMessageHolder holder = clientHolder; if (null == holder) { holder = ourHandler; if (verbose) { ourHandler.setInterceptor(MessagePrinter.VERBOSE); } else { ourHandler.ignore(IMessage.INFO); ourHandler.setInterceptor(MessagePrinter.TERSE); } } // make sure we handle out of memory gracefully... try { // byte[] b = new byte[100000000]; for testing OoME only! run(args, holder); } catch (OutOfMemoryError outOfMemory) { IMessage outOfMemoryMessage = new Message(OUT_OF_MEMORY_MSG,null,true); holder.handleMessage(outOfMemoryMessage); systemExit(holder); // we can't reasonably continue from this point. } boolean skipExit = false; if (useSystemExit && !LangUtil.isEmpty(args)) { // sigh - pluck -noExit for (int i = 0; i < args.length; i++) { if ("-noExit".equals(args[i])) { skipExit = true; break; } } } if (useSystemExit && !skipExit) { systemExit(holder); } } /** * Run without using System.exit(..), putting all messages in holder: * <ul> * <li>ERROR: compiler error</li> * <li>WARNING: compiler warning</li> * <li>FAIL: command error (bad arguments, exception thrown)</li> * </ul> * This handles incremental behavior: * <ul> * <li>If args include "-incremental", repeat for every input char * until 'q' is entered.<li> * <li>If args include "-incrementalTagFile {file}", repeat every time * we detect that {file} modification time has changed. </li> * <li>Either way, list files recompiled each time if args includes "-verbose".</li> * <li>Exit when the commmand/compiler throws any Throwable.</li> * </ul> * When complete, this contains all the messages of the final * run of the command and/or any FAIL messages produced in running * the command, including any Throwable thrown by the command itself. * * @param args the String[] command line for the compiler * @param holder the MessageHandler sink for messages. */ public void run(String[] args, IMessageHolder holder) { if (LangUtil.isEmpty(args)) { args = new String[] { "-help" }; } else if (controller.running()) { fail(holder, "already running with controller: " + controller, null); return; } args = controller.init(args, holder); if (0 < holder.numMessages(IMessage.ERROR, true)) { return; } ICommand command = ReflectionFactory.makeCommand(commandName, holder); if (0 < holder.numMessages(IMessage.ERROR, true)) { return; } try { // boolean verbose = (-1 != ("" + Arrays.asList(args)).indexOf("-verbose")); outer: while (true) { boolean passed = command.runCommand(args, holder); if (report(passed, holder) && controller.incremental()) { // final boolean onCommandLine = controller.commandLineIncremental(); while (controller.doRepeatCommand()) { holder.clearMessages(); if (controller.buildFresh()) { continue outer; } else { passed = command.repeatCommand(holder); } if (!report(passed, holder)) { break; } } } break; } } catch (AbortException ae) { if (ae.isSilent()) { quit(); } else { IMessage message = ae.getIMessage(); Throwable thrown = ae.getThrown(); if (null == thrown) { // toss AbortException wrapper if (null != message) { holder.handleMessage(message); } else { fail(holder, "abort without message", ae); } } else if (null == message) { fail(holder, "aborted", thrown); } else { String mssg = MessageUtil.MESSAGE_MOST.renderToString(message); fail(holder, mssg, thrown); } } } catch (Throwable t) { fail(holder, "unexpected exception", t); } } /** call this to stop after the next iteration of incremental compile */ public void quit() { controller.quit(); } /** * Set holder to be passed all messages. * When holder is set, messages will not be printed by default. * @param holder the IMessageHolder sink for all messages * (use null to restore default behavior) */ public void setHolder(IMessageHolder holder) { clientHolder = holder; } /** * Install a Runnable to be invoked synchronously * after each compile completes. * @param runner the Runnable to invoke - null to disable */ public void setCompletionRunner(Runnable runner) { this.completionRunner = runner; } /** * Call System.exit(int) with values derived from the number * of failures/aborts or errors in messages. * @param messages the IMessageHolder to interrogate. * @param messages */ protected void systemExit(IMessageHolder messages) { int num = lastFails; // messages.numMessages(IMessage.FAIL, true); if (0 < num) { System.exit(-num); } num = lastErrors; // messages.numMessages(IMessage.ERROR, false); if (0 < num) { System.exit(num); } System.exit(0); } /** Messages to the user */ protected void outMessage(String message) { // XXX coordinate with MessagePrinter System.out.print(message); System.out.flush(); } /** * Report results from a (possibly-incremental) compile run. * This delegates to any reportHandler or otherwise * prints summary counts of errors/warnings to System.err (if any errors) * or System.out (if only warnings). * WARNING: this silently ignores other messages like FAIL, * but clears the handler of all messages when returning true. XXX false * * This implementation ignores the pass parameter but * clears the holder after reporting * on the assumption messages were handled/printed already. * (ignoring UnsupportedOperationException from holder.clearMessages()). * @param pass true result of the command * @param holder IMessageHolder with messages from the command * @see reportCommandResults(IMessageHolder) * @return false if the process should abort */ protected boolean report(boolean pass, IMessageHolder holder) { lastFails = holder.numMessages(IMessage.FAIL, true); boolean result = (0 == lastFails); final Runnable runner = completionRunner; if (null != runner) { runner.run(); } if (holder == ourHandler) { lastErrors = holder.numMessages(IMessage.ERROR, false); int warnings = holder.numMessages(IMessage.WARNING, false); StringBuffer sb = new StringBuffer(); appendNLabel(sb, "fail|abort", lastFails); appendNLabel(sb, "error", lastErrors); appendNLabel(sb, "warning", warnings); if (0 < sb.length()) { PrintStream out = (0 < (lastErrors + lastFails) ? System.err : System.out); out.println(""); // XXX "wrote class file" messages no eol? out.println(sb.toString()); } } return result; } /** convenience API to make fail messages (without MessageUtils's fail prefix) */ protected static void fail(IMessageHandler handler, String message, Throwable thrown) { handler.handleMessage(new Message(message, IMessage.FAIL, thrown, null)); } /** * interceptor IMessageHandler to print as we go. * This formats all messages to the user. */ public static class MessagePrinter implements IMessageHandler { public static final IMessageHandler VERBOSE = new MessagePrinter(true); public static final IMessageHandler TERSE = new MessagePrinter(false); final boolean verbose; protected MessagePrinter(boolean verbose) { this.verbose = verbose; } /** * Print errors and warnings to System.err, * and optionally info to System.out, * rendering message String only. * @return false always */ public boolean handleMessage(IMessage message) { if (null != message) { PrintStream out = getStreamFor(message.getKind()); if (null != out) { out.println(render(message)); } } return false; } /** * Render message differently. * If abort, then prefix stack trace with feedback request. * If the actual message is empty, then use toString on the whole. * Prefix message part with file:line; * If it has context, suffix message with context. * @param message the IMessage to render * @return String rendering IMessage (never null) */ public static String render(IMessage message) { // IMessage.Kind kind = message.getKind(); StringBuffer sb = new StringBuffer(); String text = message.getMessage(); if (text.equals(AbortException.NO_MESSAGE_TEXT)) { text = null; } boolean toString = (LangUtil.isEmpty(text)); if (toString) { text = message.toString(); } ISourceLocation loc = message.getSourceLocation(); String context = null; if (null != loc) { File file = loc.getSourceFile(); if (null != file) { String name = file.getName(); if (!toString || (-1 == text.indexOf(name))) { sb.append(FileUtil.getBestPath(file)); if (loc.getLine() > 0) { sb.append(":" + loc.getLine()); } int col = loc.getColumn(); if (0 < col) { sb.append(":" + col); } sb.append(" "); } } context = loc.getContext(); } // per Wes' suggestion on dev... if (message.getKind() == IMessage.ERROR) { sb.append("error "); } else if (message.getKind() == IMessage.WARNING) { sb.append("warning "); } sb.append(text); if (null != context) { sb.append(LangUtil.EOL); sb.append(context); } String details = message.getDetails(); if (details != null) { sb.append(LangUtil.EOL); sb.append('\t'); sb.append(details); } Throwable thrown = message.getThrown(); if (null != thrown) { sb.append(LangUtil.EOL); sb.append(Main.renderExceptionForUser(thrown)); } if (message.getExtraSourceLocations().isEmpty()) { return sb.toString(); } else { return MessageUtil.addExtraSourceLocations(message, sb.toString()); } } public boolean isIgnoring(IMessage.Kind kind) { return (null != getStreamFor(kind)); } /** @return System.err for FAIL, ABORT, ERROR, and WARNING, * System.out for INFO if verbose. */ protected PrintStream getStreamFor(IMessage.Kind kind) { if (IMessage.WARNING.isSameOrLessThan(kind)) { return System.err; } else if (verbose && IMessage.INFO.equals(kind)) { return System.out; } else { return null; } } } /** controller for repeatable command delays until input or file changed or removed */ public static class CommandController { public static String TAG_FILE_OPTION = "-XincrementalFile"; public static String INCREMENTAL_OPTION = "-incremental"; /** maximum 10-minute delay between filesystem checks */ public static long MAX_DELAY = 1000 * 600; /** default 5-second delay between filesystem checks */ public static long DEFAULT_DELAY = 1000 * 5; /** @see init(String[]) */ private static String[][] OPTIONS = new String[][] { new String[] { INCREMENTAL_OPTION }, new String[] { TAG_FILE_OPTION, null } }; /** true between init(String[]) and doRepeatCommand() that returns false */ private boolean running; /** true after quit() called */ private boolean quit; /** true if incremental mode, waiting for input other than 'q' */ private boolean incremental; /** true if incremental mode, waiting for file to change (repeat) or disappear (quit) */ private File tagFile; /** last modification time for tagFile as of last command - 0 to start */ private long fileModTime; /** delay between filesystem checks for tagFile modification time */ private long delay; /** true just after user types 'r' for rebuild */ private boolean buildFresh; public CommandController() { delay = DEFAULT_DELAY; } /** * @param argList read and strip incremental args from this * @param sink IMessageHandler for error messages * @return String[] remainder of args */ public String[] init(String[] args, IMessageHandler sink) { running = true; // String[] unused; if (!LangUtil.isEmpty(args)) { String[][] options = LangUtil.copyStrings(OPTIONS); /*unused = */LangUtil.extractOptions(args, options); incremental = (null != options[0][0]); if (null != options[1][0]) { File file = new File(options[1][1]); if (!file.exists()) { MessageUtil.abort(sink, "tag file does not exist: " + file); } else { tagFile = file; fileModTime = tagFile.lastModified(); } } } return args; } /** @return true if init(String[]) called but doRepeatCommand has not * returned false */ public boolean running() { return running; } /** @param delay milliseconds between filesystem checks */ public void setDelay(long delay) { if ((delay > -1) && (delay < MAX_DELAY)) { this.delay = delay; } } /** @return true if INCREMENTAL_OPTION or TAG_FILE_OPTION was in args */ public boolean incremental() { return (incremental || (null != tagFile)); } /** @return true if INCREMENTAL_OPTION was in args */ public boolean commandLineIncremental() { return incremental; } public void quit() { if (!quit) { quit = true; } } /** @return true just after user typed 'r' */ boolean buildFresh() { return buildFresh; } /** @return false if we should quit, true to do another command */ boolean doRepeatCommand() { if (!running) { return false; } boolean result = false; if (quit) { result = false; } else if (incremental) { try { if (buildFresh) { // reset before input request buildFresh = false; } System.out.println(" press enter to recompile, r to rebuild, q to quit: "); System.out.flush(); // boolean doMore = false; // seek for one q or a series of [\n\r]... do { int input = System.in.read(); if ('q' == input) { break; // result = false; } else if ('r' == input) { buildFresh = true; result = true; } else if (('\n' == input) || ('\r' == input)) { result = true; } // else eat anything else } while (!result); System.in.skip(Integer.MAX_VALUE); } catch (IOException e) { // XXX silence for error? result = false; } } else if (null != tagFile) { long curModTime; while (true) { if (!tagFile.exists()) { result = false; break; } else if (fileModTime == (curModTime = tagFile.lastModified())) { fileCheckDelay(); } else { fileModTime = curModTime; result = true; break; } } } // else, not incremental - false if (!result && running) { running = false; } return result; } /** delay between filesystem checks, returning if quit is set */ protected void fileCheckDelay() { // final Thread thread = Thread.currentThread(); long targetTime = System.currentTimeMillis() + delay; // long curTime; while (targetTime > System.currentTimeMillis()) { if (quit) { return; } try { Thread.sleep(300); } // 1/3-second delta for quit check catch (InterruptedException e) {} } } } }
58,681
Bug 58681 -X should output available -X options
ajc should emit the available -X options on -help or -X request (the latter like java) to get more traffic and feedback on the experimental options.
resolved fixed
6ea8300
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2004-07-27T15:44:24Z
2004-04-15T17:26:40Z
org.aspectj.ajdt.core/testsrc/EajcModuleTests.java
/* ******************************************************************* * Copyright (c) 1999-2001 Xerox Corporation, * 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Common Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * PARC initial implementation * ******************************************************************/ // default package import junit.framework.*; import junit.framework.Test; public class EajcModuleTests extends TestCase { public static Test suite() { TestSuite suite = new TestSuite(EajcModuleTests.class.getName()); suite.addTest(org.aspectj.ajdt.ajc.AjdtAjcTests.suite()); suite.addTest(org.aspectj.ajdt.internal.compiler.batch.AjdtBatchTests.suite()); suite.addTest(org.aspectj.ajdt.internal.core.builder.AjdtBuilderTests.suite()); return suite; } public EajcModuleTests(String name) { super(name); } }
58,681
Bug 58681 -X should output available -X options
ajc should emit the available -X options on -help or -X request (the latter like java) to get more traffic and feedback on the experimental options.
resolved fixed
6ea8300
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2004-07-27T15:44:24Z
2004-04-15T17:26:40Z
org.aspectj.ajdt.core/testsrc/org/aspectj/tools/ajc/MainTest.java
/* ******************************************************************* * Copyright (c) 2004 Contributors. * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Common Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * Wes Isberg initial implementation * ******************************************************************/ package org.aspectj.tools.ajc; import java.util.ArrayList; import junit.framework.TestCase; /** * */ public class MainTest extends TestCase { public void testMainbare() { ArrayList list = new ArrayList(); Main.bareMain(new String[] {"-help"}, false, list, null, null, null); assertTrue(1 == list.size()); Object o = list.get(0); assertTrue(o instanceof String); assertTrue(-1 != ((String)o).indexOf("-aspectpath")); assertTrue(-1 != ((String)o).indexOf("-incremental")); } }
64,331
Bug 64331 java.lang.NullPointerException in WeaverMessageHandler class
null
resolved fixed
573741c
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2004-07-28T14:43:40Z
2004-05-27T15:00:00Z
org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/compiler/WeaverMessageHandler.java
/******************************************************************************* * Copyright (c) 2004 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Common Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.aspectj.ajdt.internal.compiler; import java.util.List; import org.aspectj.ajdt.internal.compiler.lookup.EclipseSourceLocation; import org.aspectj.bridge.AbortException; import org.aspectj.bridge.IMessage; import org.aspectj.bridge.IMessageHandler; import org.aspectj.bridge.ISourceLocation; import org.aspectj.bridge.IMessage.Kind; import org.eclipse.jdt.core.compiler.IProblem; import org.eclipse.jdt.internal.compiler.CompilationResult; import org.eclipse.jdt.internal.compiler.Compiler; import org.eclipse.jdt.internal.compiler.impl.ReferenceContext; import org.eclipse.jdt.internal.compiler.problem.DefaultProblem; import org.eclipse.jdt.internal.compiler.problem.ProblemSeverities; /** * @author colyer * * To change the template for this generated type comment go to * Window&gt;Preferences&gt;Java&gt;Code Generation&gt;Code and Comments */ public class WeaverMessageHandler implements IMessageHandler { private IMessageHandler sink; private CompilationResult currentlyWeaving; private Compiler compiler; public WeaverMessageHandler(IMessageHandler handler, Compiler compiler) { this.sink = handler; this.compiler = compiler; } public void setCurrentResult(CompilationResult result) { currentlyWeaving = result; } public boolean handleMessage(IMessage message) throws AbortException { if (! (message.isError() || message.isWarning()) ) return sink.handleMessage(message); // we only care about warnings and errors here... ISourceLocation sLoc = message.getSourceLocation(); // See bug 62073. We should assert that the caller pass the correct primary source location. // But for AJ1.2 final we will simply do less processing of the locations if that is not the // case (By calling sink.handleMessage()) - this ensures we don't put out bogus source context info. if (sLoc instanceof EclipseSourceLocation) { EclipseSourceLocation esLoc = (EclipseSourceLocation)sLoc; if (currentlyWeaving!=null && esLoc.getCompilationResult()!=null) { if (!currentlyWeaving.equals(((EclipseSourceLocation)sLoc).getCompilationResult())) return sink.handleMessage(message); // throw new RuntimeException("Primary source location must match the file we are currently processing!"); } } CompilationResult problemSource = currentlyWeaving; if (problemSource == null) { // must be a problem found during completeTypeBindings phase of begin to compile if (sLoc instanceof EclipseSourceLocation) { problemSource = ((EclipseSourceLocation)sLoc).getCompilationResult(); } if (problemSource == null) { // XXX this is ok for ajc, will have to do better for AJDT in time... return sink.handleMessage(message); } } int startPos = getStartPos(sLoc,problemSource); int endPos = getEndPos(sLoc,problemSource); int severity = message.isError() ? ProblemSeverities.Error : ProblemSeverities.Warning; char[] filename = problemSource.fileName; boolean usedBinarySourceFileName = false; if (problemSource.isFromBinarySource()) { if (sLoc != null) { filename = sLoc.getSourceFile().getPath().toCharArray(); usedBinarySourceFileName = true; } } ReferenceContext referenceContext = findReferenceContextFor(problemSource); IProblem problem = compiler.problemReporter.createProblem( filename, IProblem.Unclassified, new String[0], new String[] {message.getMessage()}, severity, startPos, endPos, sLoc != null ? sLoc.getLine() : 0, referenceContext, problemSource ); IProblem[] seeAlso = buildSeeAlsoProblems(message.getExtraSourceLocations(), problemSource, usedBinarySourceFileName); problem.setSeeAlsoProblems(seeAlso); if (message.getDetails() != null) { problem.setSupplementaryMessageInfo(message.getDetails()); } compiler.problemReporter.record(problem, problemSource, referenceContext); return true; } public boolean isIgnoring(Kind kind) { return sink.isIgnoring(kind); } private int getStartPos(ISourceLocation sLoc,CompilationResult result) { int pos = 0; if (sLoc == null) return 0; int line = sLoc.getLine(); if (sLoc instanceof EclipseSourceLocation) { pos = ((EclipseSourceLocation)sLoc).getStartPos(); } else { if (line <= 1) return 0; if (result != null) { if ((result.lineSeparatorPositions != null) && (result.lineSeparatorPositions.length >= (line-1))) { pos = result.lineSeparatorPositions[line-2] + 1; } } } return pos; } private int getEndPos(ISourceLocation sLoc,CompilationResult result) { int pos = 0; if (sLoc == null) return 0; int line = sLoc.getLine(); if (line <= 0) line = 1; if (sLoc instanceof EclipseSourceLocation) { pos = ((EclipseSourceLocation)sLoc).getEndPos(); } else { if (result != null) { if ((result.lineSeparatorPositions != null) && (result.lineSeparatorPositions.length >= line)) { pos = result.lineSeparatorPositions[line -1] -1; } } } return pos; } private ReferenceContext findReferenceContextFor(CompilationResult result) { ReferenceContext context = null; if (compiler.unitsToProcess == null) return null; for (int i = 0; i < compiler.unitsToProcess.length; i++) { if ((compiler.unitsToProcess[i] != null) && (compiler.unitsToProcess[i].compilationResult == result)) { context = compiler.unitsToProcess[i]; break; } } return context; } private IProblem[] buildSeeAlsoProblems(List sourceLocations, CompilationResult problemSource, boolean usedBinarySourceFileName) { int probLength = sourceLocations.size(); if (usedBinarySourceFileName) probLength++; IProblem[] ret = new IProblem[probLength]; for (int i = 0; i < sourceLocations.size(); i++) { ISourceLocation loc = (ISourceLocation) sourceLocations.get(i); ret[i] = new DefaultProblem(loc.getSourceFile().getPath().toCharArray(), "see also", 0, new String[] {}, ProblemSeverities.Ignore, getStartPos(loc,null), getEndPos(loc,null), loc.getLine()); } if (usedBinarySourceFileName) { ret[ret.length -1] = new DefaultProblem(problemSource.fileName,"see also",0,new String[] {}, ProblemSeverities.Ignore,0, 0,0); } return ret; } }
64,331
Bug 64331 java.lang.NullPointerException in WeaverMessageHandler class
null
resolved fixed
573741c
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2004-07-28T14:43:40Z
2004-05-27T15:00:00Z
tests/bugs/abstractITDs/A.java
64,331
Bug 64331 java.lang.NullPointerException in WeaverMessageHandler class
null
resolved fixed
573741c
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2004-07-28T14:43:40Z
2004-05-27T15:00:00Z
tests/bugs/abstractITDs/C.java
64,331
Bug 64331 java.lang.NullPointerException in WeaverMessageHandler class
null
resolved fixed
573741c
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2004-07-28T14:43:40Z
2004-05-27T15:00:00Z
weaver/src/org/aspectj/weaver/ResolvedTypeX.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Common Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * PARC initial implementation * ******************************************************************/ package org.aspectj.weaver; import java.lang.reflect.Modifier; 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.bridge.IMessage; import org.aspectj.bridge.ISourceLocation; import org.aspectj.bridge.Message; import org.aspectj.bridge.MessageUtil; import org.aspectj.weaver.patterns.Declare; import org.aspectj.weaver.patterns.PerClause; public abstract class ResolvedTypeX extends TypeX { protected World world; ResolvedTypeX(String signature, World world) { super(signature); this.world = world; } // ---- things that don't require a world /** returns Iterator&lt;ResolvedTypeX&gt; */ public final Iterator getDirectSupertypes() { Iterator ifacesIterator = Iterators.array(getDeclaredInterfaces()); ResolvedTypeX superclass = getSuperclass(); if (superclass == null) { return ifacesIterator; } else { return Iterators.snoc(ifacesIterator, superclass); } } public abstract ResolvedMember[] getDeclaredFields(); public abstract ResolvedMember[] getDeclaredMethods(); public abstract ResolvedTypeX[] getDeclaredInterfaces(); public abstract ResolvedMember[] getDeclaredPointcuts(); public abstract ResolvedTypeX getSuperclass(); public abstract int getModifiers(); public abstract boolean needsNoConversionFrom(TypeX other); public abstract boolean isCoerceableFrom(TypeX other); public abstract boolean isAssignableFrom(TypeX other); // ---- things that would require a world if I weren't resolved public final Iterator getDirectSupertypes(World world) { return getDirectSupertypes(); } public final ResolvedMember[] getDeclaredFields(World world) { return getDeclaredFields(); } public final ResolvedMember[] getDeclaredMethods(World world) { return getDeclaredMethods(); } public final TypeX[] getDeclaredInterfaces(World world) { return getDeclaredInterfaces(); } public final ResolvedMember[] getDeclaredPointcuts(World world) { return getDeclaredPointcuts(); } public final int getModifiers(World world) { return getModifiers(); } public final TypeX getSuperclass(World world) { return getSuperclass(); } // conversions public final boolean isAssignableFrom(TypeX other, World world) { return isAssignableFrom(other); } public final boolean isCoerceableFrom(TypeX other, World world) { return isCoerceableFrom(other); } public boolean needsNoConversionFrom(TypeX other, World world) { return needsNoConversionFrom(other); } public final boolean isConvertableFrom(TypeX other) { if (this.equals(OBJECT) || other.equals(OBJECT)) return true; return this.isCoerceableFrom(other); } // utilities public ResolvedTypeX getResolvedComponentType() { return null; } public ResolvedTypeX resolve(World world) { return this; } public World getWorld() { return world; } // ---- things from object public final boolean equals(Object other) { if (other instanceof ResolvedTypeX) { return this == other; } else { return super.equals(other); } } // ---- difficult things /** * returns an iterator through all of the fields of this type, in order * for checking from JVM spec 2ed 5.4.3.2. This means that the order is * * <ul><li> fields from current class </li> * <li> recur into direct superinterfaces </li> * <li> recur into superclass </li> * </ul> * * We keep a hashSet of interfaces that we've visited so we don't spiral * out into 2^n land. */ public Iterator getFields() { final Iterators.Filter dupFilter = Iterators.dupFilter(); Iterators.Getter typeGetter = new Iterators.Getter() { public Iterator get(Object o) { return dupFilter.filter( ((ResolvedTypeX)o).getDirectSupertypes()); } }; Iterators.Getter fieldGetter = new Iterators.Getter() { public Iterator get(Object o) { return Iterators.array(((ResolvedTypeX)o).getDeclaredFields()); } }; return Iterators.mapOver( Iterators.recur(this, typeGetter), fieldGetter); } /** * returns an iterator through all of the methods of this type, in order * for checking from JVM spec 2ed 5.4.3.3. This means that the order is * * <ul><li> methods from current class </li> * <li> recur into superclass, all the way up, not touching interfaces </li> * <li> recur into all superinterfaces, in some unspecified order </li> * </ul> * * We keep a hashSet of interfaces that we've visited so we don't spiral * out into 2^n land. */ public Iterator getMethods() { final Iterators.Filter dupFilter = Iterators.dupFilter(); Iterators.Getter ifaceGetter = new Iterators.Getter() { public Iterator get(Object o) { return dupFilter.filter( Iterators.array(((ResolvedTypeX)o).getDeclaredInterfaces()) ); } }; Iterators.Getter methodGetter = new Iterators.Getter() { public Iterator get(Object o) { return Iterators.array(((ResolvedTypeX)o).getDeclaredMethods()); } }; return Iterators.mapOver( Iterators.append( new Iterator() { ResolvedTypeX curr = ResolvedTypeX.this; public boolean hasNext() { return curr != null; } public Object next() { ResolvedTypeX ret = curr; curr = curr.getSuperclass(); return ret; } public void remove() { throw new UnsupportedOperationException(); } }, Iterators.recur(this, ifaceGetter)), methodGetter); } /** * described in JVM spec 2ed 5.4.3.2 */ public ResolvedMember lookupField(Member m) { return lookupMember(m, getFields()); } /** * described in JVM spec 2ed 5.4.3.3 */ public ResolvedMember lookupMethod(Member m) { return lookupMember(m, getMethods()); } /** return null if not found */ private ResolvedMember lookupMember(Member m, Iterator i) { while (i.hasNext()) { ResolvedMember f = (ResolvedMember) i.next(); if (matches(f, m)) return f; } return null; //ResolvedMember.Missing; //throw new BCException("can't find " + m); } /** return null if not found */ private ResolvedMember lookupMember(Member m, ResolvedMember[] a) { for (int i = 0; i < a.length; i++) { ResolvedMember f = a[i]; if (matches(f, m)) return f; } return null; } public static boolean matches(Member m1, Member m2) { if (m1 == null) return m2 == null; if (m2 == null) return false; return m1.getName().equals(m2.getName()) && m1.getSignature().equals(m2.getSignature()); } public static boolean conflictingSignature(Member m1, Member m2) { if (m1 == null || m2 == null) return false; if (!m1.getName().equals(m2.getName())) { return false; } if (m1.getKind() != m2.getKind()) { return false; } if (m1.getKind() == Member.FIELD) { return m1.getDeclaringType().equals(m2.getDeclaringType()); } else if (m1.getKind() == Member.POINTCUT) { return true; } TypeX[] p1 = m1.getParameterTypes(); TypeX[] p2 = m2.getParameterTypes(); int n = p1.length; if (n != p2.length) return false; for (int i=0; i < n; i++) { if (!p1[i].equals(p2[i])) return false; } return true; } /** * returns an iterator through all of the pointcuts of this type, in order * for checking from JVM spec 2ed 5.4.3.2 (as for fields). This means that the order is * * <ul><li> pointcuts from current class </li> * <li> recur into direct superinterfaces </li> * <li> recur into superclass </li> * </ul> * * We keep a hashSet of interfaces that we've visited so we don't spiral * out into 2^n land. */ public Iterator getPointcuts() { final Iterators.Filter dupFilter = Iterators.dupFilter(); // same order as fields Iterators.Getter typeGetter = new Iterators.Getter() { public Iterator get(Object o) { return dupFilter.filter( ((ResolvedTypeX)o).getDirectSupertypes()); } }; Iterators.Getter pointcutGetter = new Iterators.Getter() { public Iterator get(Object o) { //System.err.println("getting for " + o); return Iterators.array(((ResolvedTypeX)o).getDeclaredPointcuts()); } }; return Iterators.mapOver( Iterators.recur(this, typeGetter), pointcutGetter); } public ResolvedPointcutDefinition findPointcut(String name) { //System.err.println("looking for pointcuts " + this); for (Iterator i = getPointcuts(); i.hasNext(); ) { ResolvedPointcutDefinition f = (ResolvedPointcutDefinition) i.next(); //System.err.println(f); if (name.equals(f.getName())) { return f; } } return null; // should we throw an exception here? } // all about collecting CrosscuttingMembers //??? collecting data-structure, shouldn't really be a field public CrosscuttingMembers crosscuttingMembers; public CrosscuttingMembers collectCrosscuttingMembers() { crosscuttingMembers = new CrosscuttingMembers(this); crosscuttingMembers.setPerClause(getPerClause()); crosscuttingMembers.addShadowMungers(collectShadowMungers()); crosscuttingMembers.addTypeMungers(getTypeMungers()); crosscuttingMembers.addDeclares(collectDeclares(!this.doesNotExposeShadowMungers())); crosscuttingMembers.addPrivilegedAccesses(getPrivilegedAccesses()); //System.err.println("collected cc members: " + this + ", " + collectDeclares()); return crosscuttingMembers; } public final Collection collectDeclares(boolean includeAdviceLike) { if (! this.isAspect() ) return Collections.EMPTY_LIST; ArrayList ret = new ArrayList(); //if (this.isAbstract()) { for (Iterator i = getDeclares().iterator(); i.hasNext();) { Declare dec = (Declare) i.next(); if (!dec.isAdviceLike()) ret.add(dec); } if (!includeAdviceLike) return ret; if (!this.isAbstract()) { //ret.addAll(getDeclares()); final Iterators.Filter dupFilter = Iterators.dupFilter(); Iterators.Getter typeGetter = new Iterators.Getter() { public Iterator get(Object o) { return dupFilter.filter( ((ResolvedTypeX)o).getDirectSupertypes()); } }; Iterator typeIterator = Iterators.recur(this, typeGetter); while (typeIterator.hasNext()) { ResolvedTypeX ty = (ResolvedTypeX) typeIterator.next(); //System.out.println("super: " + ty + ", " + ); for (Iterator i = ty.getDeclares().iterator(); i.hasNext();) { Declare dec = (Declare) i.next(); if (dec.isAdviceLike()) ret.add(dec); } } } return ret; } private final Collection collectShadowMungers() { if (! this.isAspect() || this.isAbstract() || this.doesNotExposeShadowMungers()) return Collections.EMPTY_LIST; ArrayList acc = new ArrayList(); final Iterators.Filter dupFilter = Iterators.dupFilter(); Iterators.Getter typeGetter = new Iterators.Getter() { public Iterator get(Object o) { return dupFilter.filter( ((ResolvedTypeX)o).getDirectSupertypes()); } }; Iterator typeIterator = Iterators.recur(this, typeGetter); while (typeIterator.hasNext()) { ResolvedTypeX ty = (ResolvedTypeX) typeIterator.next(); acc.addAll(ty.getDeclaredShadowMungers()); } return acc; } protected boolean doesNotExposeShadowMungers() { return false; } public PerClause getPerClause() { return null; } protected Collection getDeclares() { return Collections.EMPTY_LIST; } protected Collection getTypeMungers() { return Collections.EMPTY_LIST; } protected Collection getPrivilegedAccesses() { return Collections.EMPTY_LIST; } // ---- useful things public final boolean isInterface() { return Modifier.isInterface(getModifiers()); } public final boolean isAbstract() { return Modifier.isAbstract(getModifiers()); } public boolean isClass() { return false; } public boolean isAspect() { return false; } public boolean isSynthetic() { return signature.indexOf("$ajc") != -1; } public final boolean isFinal() { return Modifier.isFinal(getModifiers()); } public Collection getDeclaredAdvice() { List l = new ArrayList(); ResolvedMember[] methods = getDeclaredMethods(); for (int i=0, len = methods.length; i < len; i++) { ShadowMunger munger = methods[i].getAssociatedShadowMunger(); if (munger != null) l.add(munger); } return l; } private List shadowMungers = new ArrayList(0); public Collection getDeclaredShadowMungers() { Collection c = getDeclaredAdvice(); c.addAll(shadowMungers); return c; } public void addShadowMunger(ShadowMunger munger) { shadowMungers.add(munger); } // ---- only for testing! public ResolvedMember[] getDeclaredJavaFields() { return filterInJavaVisible(getDeclaredFields()); } public ResolvedMember[] getDeclaredJavaMethods() { return filterInJavaVisible(getDeclaredMethods()); } public ShadowMunger[] getDeclaredShadowMungersArray() { List l = (List) getDeclaredShadowMungers(); return (ShadowMunger[]) l.toArray(new ShadowMunger[l.size()]); } private ResolvedMember[] filterInJavaVisible(ResolvedMember[] ms) { List l = new ArrayList(); for (int i=0, len = ms.length; i < len; i++) { if (! ms[i].isAjSynthetic() && ms[i].getAssociatedShadowMunger() == null) { l.add(ms[i]); } } return (ResolvedMember[]) l.toArray(new ResolvedMember[l.size()]); } public abstract ISourceContext getSourceContext(); // ---- fields public static final ResolvedTypeX[] NONE = new ResolvedTypeX[0]; public static final Primitive BYTE = new Primitive("B", 1, 0); public static final Primitive CHAR = new Primitive("C", 1, 1); public static final Primitive DOUBLE = new Primitive("D", 2, 2); public static final Primitive FLOAT = new Primitive("F", 1, 3); public static final Primitive INT = new Primitive("I", 1, 4); public static final Primitive LONG = new Primitive("J", 2, 5); public static final Primitive SHORT = new Primitive("S", 1, 6); public static final Primitive VOID = new Primitive("V", 0, 8); public static final Primitive BOOLEAN = new Primitive("Z", 1, 7); public static final Missing MISSING = new Missing(); // ---- types public static class Name extends ResolvedTypeX { private ConcreteName delegate = null; private ISourceContext sourceContext = null; private int startPos = 0; private int endPos = 0; //??? should set delegate before any use public Name(String signature, World world) { super(signature, world); } public final boolean isClass() { return delegate.isClass(); } public boolean isAspect() { return delegate.isAspect(); } public final boolean needsNoConversionFrom(TypeX o) { return isAssignableFrom(o); } public final boolean isAssignableFrom(TypeX o) { if (o.isPrimitive()) return false; ResolvedTypeX other = o.resolve(world); return isAssignableFrom(other); } public final boolean isCoerceableFrom(TypeX o) { ResolvedTypeX other = o.resolve(world); if (this.isAssignableFrom(other) || other.isAssignableFrom(this)) { return true; } 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 = ((Name)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 boolean isAssignableFrom(ResolvedTypeX other) { if (this == other) return true; for(Iterator i = other.getDirectSupertypes(); i.hasNext(); ) { if (this.isAssignableFrom((ResolvedTypeX) i.next())) return true; } return false; } public ISourceContext getSourceContext() { return sourceContext; } public ISourceLocation getSourceLocation() { if (sourceContext == null) return null; return sourceContext.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() { return delegate.getDeclaredFields(); } public ResolvedTypeX[] getDeclaredInterfaces() { return delegate.getDeclaredInterfaces(); } public ResolvedMember[] getDeclaredMethods() { return delegate.getDeclaredMethods(); } public ResolvedMember[] getDeclaredPointcuts() { return delegate.getDeclaredPointcuts(); } public PerClause getPerClause() { return delegate.getPerClause(); } protected Collection getDeclares() { return delegate.getDeclares(); } protected Collection getTypeMungers() { return delegate.getTypeMungers(); } protected Collection getPrivilegedAccesses() { return delegate.getPrivilegedAccesses(); } public int getModifiers() { return delegate.getModifiers(); } public ResolvedTypeX getSuperclass() { return delegate.getSuperclass(); } public ConcreteName getDelegate() { return delegate; } public void setDelegate(ConcreteName delegate) { this.delegate = delegate; } public int getEndPos() { return endPos; } public int getStartPos() { return startPos; } public void setEndPos(int endPos) { this.endPos = endPos; } public void setSourceContext(ISourceContext sourceContext) { this.sourceContext = sourceContext; } public void setStartPos(int startPos) { this.startPos = startPos; } public boolean doesNotExposeShadowMungers() { return delegate.doesNotExposeShadowMungers(); } } public static abstract class ConcreteName { //protected ISourceContext sourceContext; protected boolean exposedToWeaver; protected ResolvedTypeX.Name resolvedTypeX; public ConcreteName(ResolvedTypeX.Name resolvedTypeX, boolean exposedToWeaver) { //???super(signature, world); this.resolvedTypeX = resolvedTypeX; this.exposedToWeaver = exposedToWeaver; } public final boolean isClass() { return !isAspect() && !isInterface(); } public abstract boolean isAspect(); public abstract boolean isInterface(); public abstract ResolvedMember[] getDeclaredFields(); public abstract ResolvedTypeX[] getDeclaredInterfaces(); public abstract ResolvedMember[] getDeclaredMethods(); public abstract ResolvedMember[] getDeclaredPointcuts(); public abstract PerClause getPerClause(); protected abstract Collection getDeclares() ; protected abstract Collection getTypeMungers(); protected abstract Collection getPrivilegedAccesses(); public abstract int getModifiers(); public abstract ResolvedTypeX getSuperclass(); // public abstract ISourceLocation getSourceLocation(); public abstract WeaverStateInfo getWeaverState(); // public ISourceContext getSourceContext() { // return sourceContext; // } /** * Designed to be overriden by EclipseType to disable collection of shadow mungers * during pre-weave compilation phase */ public boolean doesNotExposeShadowMungers() { return false; } public boolean isExposedToWeaver() { return exposedToWeaver; } public ResolvedTypeX.Name getResolvedTypeX() { return resolvedTypeX; } } static class Array extends ResolvedTypeX { ResolvedTypeX componentType; Array(String s, World world, ResolvedTypeX componentType) { super(s, world); this.componentType = componentType; } public final ResolvedMember[] getDeclaredFields() { return ResolvedMember.NONE; } public final ResolvedMember[] getDeclaredMethods() { // ??? should this return clone? Probably not... return ResolvedMember.NONE; } public final ResolvedTypeX[] getDeclaredInterfaces() { return new ResolvedTypeX[] { world.resolve(CLONEABLE), world.resolve(SERIALIZABLE) }; } public final ResolvedMember[] getDeclaredPointcuts() { return ResolvedMember.NONE; } public final ResolvedTypeX getSuperclass() { return world.resolve(OBJECT); } public final boolean isAssignableFrom(TypeX o) { if (! o.isArray()) return false; if (o.getComponentType().isPrimitive()) { return o.equals(this); } else { return getComponentType().isAssignableFrom(o.getComponentType(), world); } } public final boolean isCoerceableFrom(TypeX o) { if (o.equals(TypeX.OBJECT) || o.equals(TypeX.SERIALIZABLE) || o.equals(TypeX.CLONEABLE)) { return true; } if (! o.isArray()) return false; if (o.getComponentType().isPrimitive()) { return o.equals(this); } else { return getComponentType().isCoerceableFrom(o.getComponentType(), world); } } public final boolean needsNoConversionFrom(TypeX o) { return isAssignableFrom(o); } public final int getModifiers() { int mask = Modifier.PUBLIC | Modifier.PRIVATE | Modifier.PROTECTED; return (componentType.getModifiers() & mask) | Modifier.FINAL; } public TypeX getComponentType() { return componentType; } public ResolvedTypeX getResolvedComponentType() { return componentType; } public ISourceContext getSourceContext() { return getResolvedComponentType().getSourceContext(); } } static class Primitive extends ResolvedTypeX { private int size; private int index; Primitive(String signature, int size, int index) { super(signature, null); this.size = size; this.index = index; } public final int getSize() { return size; } public final int getModifiers() { return Modifier.PUBLIC | Modifier.FINAL; } public final boolean isPrimitive() { return true; } public final boolean isAssignableFrom(TypeX other) { if (! other.isPrimitive()) return false; return assignTable[((Primitive)other).index][index]; } public final boolean isCoerceableFrom(TypeX other) { if (this == other) return true; if (! other.isPrimitive()) return false; if (index > 6 || ((Primitive)other).index > 6) return false; return true; } public final boolean needsNoConversionFrom(TypeX other) { if (! other.isPrimitive()) return false; return noConvertTable[((Primitive)other).index][index]; } private static final boolean[][] assignTable = {// to: B C D F I J S V Z from { true , true , true , true , true , true , true , false, false }, // B { false, true , true , true , true , true , false, false, false }, // C { false, false, true , false, false, false, false, false, false }, // D { false, false, true , true , false, false, false, false, false }, // F { false, false, true , true , true , true , false, false, false }, // I { false, false, true , true , false, true , false, false, false }, // J { false, false, true , true , true , true , true , false, false }, // S { false, false, false, false, false, false, false, true , false }, // V { false, false, false, false, false, false, false, false, true }, // Z }; private static final boolean[][] noConvertTable = {// to: B C D F I J S V Z from { true , true , false, false, true , false, true , false, false }, // B { false, true , false, false, true , false, false, false, false }, // C { false, false, true , false, false, false, false, false, false }, // D { false, false, false, true , false, false, false, false, false }, // F { false, false, false, false, true , false, false, false, false }, // I { false, false, false, false, false, true , false, false, false }, // J { false, false, false, false, true , false, true , false, false }, // S { false, false, false, false, false, false, false, true , false }, // V { false, false, false, false, false, false, false, false, true }, // Z }; // ---- public final ResolvedMember[] getDeclaredFields() { return ResolvedMember.NONE; } public final ResolvedMember[] getDeclaredMethods() { return ResolvedMember.NONE; } public final ResolvedTypeX[] getDeclaredInterfaces() { return ResolvedTypeX.NONE; } public final ResolvedMember[] getDeclaredPointcuts() { return ResolvedMember.NONE; } public final ResolvedTypeX getSuperclass() { return null; } public ISourceContext getSourceContext() { return null; } } static class Missing extends ResolvedTypeX { Missing() { super(MISSING_NAME, null); } // public final String toString() { // return "<missing>"; // } public final String getName() { return MISSING_NAME; } public final ResolvedMember[] getDeclaredFields() { return ResolvedMember.NONE; } public final ResolvedMember[] getDeclaredMethods() { return ResolvedMember.NONE; } public final ResolvedTypeX[] getDeclaredInterfaces() { return ResolvedTypeX.NONE; } public final ResolvedMember[] getDeclaredPointcuts() { return ResolvedMember.NONE; } public final ResolvedTypeX getSuperclass() { return null; } public final int getModifiers() { return 0; } public final boolean isAssignableFrom(TypeX other) { return false; } public final boolean isCoerceableFrom(TypeX other) { return false; } public boolean needsNoConversionFrom(TypeX other) { return false; } public ISourceContext getSourceContext() { return null; } } /** return null if not found */ public ResolvedMember lookupMemberNoSupers(Member member) { ResolvedMember ret; if (member.getKind() == Member.FIELD) { ret = lookupMember(member, getDeclaredFields()); } else { // assert member.getKind() == Member.METHOD || member.getKind() == Member.CONSTRUCTOR ret = lookupMember(member, getDeclaredMethods()); } if (ret == null && interTypeMungers != null) { for (Iterator i = interTypeMungers.iterator(); i.hasNext();) { ConcreteTypeMunger tm = (ConcreteTypeMunger) i.next(); if (matches(tm.getSignature(), member)) { return tm.getSignature(); } } } return ret; } protected List interTypeMungers = new ArrayList(0); public List getInterTypeMungers() { return interTypeMungers; } /** * ??? This method is O(N*M) where N = number of methods and M is number of * inter-type declarations in my super */ public List getInterTypeMungersIncludingSupers() { ArrayList ret = new ArrayList(); collectInterTypeMungers(ret); return ret; } private void collectInterTypeMungers(List collector) { for (Iterator iter = getDirectSupertypes(); iter.hasNext();) { ResolvedTypeX superType = (ResolvedTypeX) iter.next(); superType.collectInterTypeMungers(collector); } outer: for (Iterator iter1 = collector.iterator(); iter1.hasNext(); ) { ConcreteTypeMunger superMunger = (ConcreteTypeMunger) iter1.next(); if ( superMunger.getSignature() == null) continue; if ( !superMunger.getSignature().isAbstract()) continue; for (Iterator iter = getInterTypeMungers().iterator(); iter.hasNext();) { ConcreteTypeMunger myMunger = (ConcreteTypeMunger) iter.next(); if (conflictingSignature(myMunger.getSignature(), superMunger.getSignature())) { iter1.remove(); continue outer; } } if (!superMunger.getSignature().isPublic()) continue; for (Iterator iter = getMethods(); iter.hasNext(); ) { ResolvedMember method = (ResolvedMember)iter.next(); if (conflictingSignature(method, superMunger.getSignature())) { iter1.remove(); continue outer; } } } collector.addAll(getInterTypeMungers()); } /** * Check that we don't have any abstract type mungers unless this * type is abstract. */ public void checkInterTypeMungers() { if (isAbstract()) return; for (Iterator iter = getInterTypeMungersIncludingSupers().iterator(); iter.hasNext();) { ConcreteTypeMunger element = (ConcreteTypeMunger) iter.next(); if (element.getSignature() != null && element.getSignature().isAbstract()) { world.getMessageHandler().handleMessage( new Message("must implement abstract inter-type declaration: " + element.getSignature(), "", IMessage.ERROR, getSourceLocation(), null, new ISourceLocation[] { element.getSourceLocation() })); } } } /** * Returns a ResolvedTypeX object representing the declaring type of this type, or * null if this type does not represent a non-package-level-type. * * <strong>Warning</strong>: This is guaranteed to work for all member types. * For anonymous/local types, the only guarantee is given in JLS 13.1, where * it guarantees that if you call getDeclaringType() repeatedly, you will eventually * get the top-level class, but it does not say anything about classes in between. * * @return the declaring TypeX object, or null. */ public ResolvedTypeX getDeclaringType() { if (isArray()) return null; String name = getName(); int lastDollar = name.lastIndexOf('$'); while (lastDollar != -1) { ResolvedTypeX ret = world.resolve(TypeX.forName(name.substring(0, lastDollar)), true); if (ret != ResolvedTypeX.MISSING) return ret; lastDollar = name.lastIndexOf('$', lastDollar-1); } return null; } public static boolean isVisible(int modifiers, ResolvedTypeX targetType, ResolvedTypeX fromType) { //System.err.println("mod: " + modifiers + ", " + targetType + " and " + fromType); if (Modifier.isPublic(modifiers)) { return true; } else if (Modifier.isPrivate(modifiers)) { return targetType.getOutermostType().equals(fromType.getOutermostType()); } else if (Modifier.isProtected(modifiers)) { return samePackage(targetType, fromType) || targetType.isAssignableFrom(fromType); } else { // package-visible return samePackage(targetType, fromType); } } private static boolean samePackage( ResolvedTypeX targetType, ResolvedTypeX fromType) { String p1 = targetType.getPackageName(); String p2 = fromType.getPackageName(); if (p1 == null) return p2 == null; if (p2 == null) return false; return p1.equals(p2); } public void addInterTypeMunger(ConcreteTypeMunger munger) { ResolvedMember sig = munger.getSignature(); if (sig == null || munger.getMunger() == null || munger.getMunger().getKind() == ResolvedTypeMunger.PrivilegedAccess) { interTypeMungers.add(munger); return; } //System.err.println("add: " + munger + " to " + this.getClassName() + " with " + interTypeMungers); if (sig.getKind() == Member.METHOD) { if (!compareToExistingMembers(munger, getMethods())) return; if (this.isInterface()) { if (!compareToExistingMembers(munger, Arrays.asList(world.resolve(OBJECT).getDeclaredMethods()).iterator())) return; } } else if (sig.getKind() == Member.FIELD) { if (!compareToExistingMembers(munger, Arrays.asList(getDeclaredFields()).iterator())) return; } else { if (!compareToExistingMembers(munger, Arrays.asList(getDeclaredMethods()).iterator())) return; } // now compare to existingMungers for (Iterator i = interTypeMungers.iterator(); i.hasNext(); ) { ConcreteTypeMunger existingMunger = (ConcreteTypeMunger)i.next(); if (conflictingSignature(existingMunger.getSignature(), munger.getSignature())) { //System.err.println("match " + munger + " with " + existingMunger); if (isVisible(munger.getSignature().getModifiers(), munger.getAspectType(), existingMunger.getAspectType())) { //System.err.println(" is visible"); int c = compareMemberPrecedence(sig, existingMunger.getSignature()); if (c == 0) { c = getWorld().comparePrecedence(munger.getAspectType(), existingMunger.getAspectType()); } //System.err.println(" compare: " + c); if (c < 0) { // the existing munger dominates the new munger checkLegalOverride(munger.getSignature(), existingMunger.getSignature()); return; } else if (c > 0) { // the new munger dominates the existing one checkLegalOverride(existingMunger.getSignature(), munger.getSignature()); i.remove(); break; } else { interTypeConflictError(munger, existingMunger); interTypeConflictError(existingMunger, munger); return; } } } } //System.err.println("adding: " + munger + " to " + this); interTypeMungers.add(munger); } //??? returning too soon private boolean compareToExistingMembers(ConcreteTypeMunger munger, Iterator existingMembers) { ResolvedMember sig = munger.getSignature(); while (existingMembers.hasNext()) { ResolvedMember existingMember = (ResolvedMember)existingMembers.next(); //System.err.println("Comparing munger: "+sig+" with member "+existingMember); if (conflictingSignature(existingMember, munger.getSignature())) { //System.err.println("conflict: existingMember=" + existingMember + " typeMunger=" + munger); //System.err.println(munger.getSourceLocation() + ", " + munger.getSignature() + ", " + munger.getSignature().getSourceLocation()); if (isVisible(existingMember.getModifiers(), this, munger.getAspectType())) { int c = compareMemberPrecedence(sig, existingMember); //System.err.println(" c: " + c); if (c < 0) { // existingMember dominates munger checkLegalOverride(munger.getSignature(), existingMember); return false; } else if (c > 0) { // munger dominates existingMember checkLegalOverride(existingMember, munger.getSignature()); //interTypeMungers.add(munger); //??? might need list of these overridden abstracts continue; } else { //XXX dual errors possible if (this instanceof BcelObjectType) return false; //XXX ignores separate comp getWorld().getMessageHandler().handleMessage( MessageUtil.error("inter-type declaration from " + munger.getAspectType().getName() + " conflicts with existing member: " + existingMember, munger.getSourceLocation()) ); } } else { //interTypeMungers.add(munger); } //return; } } return true; } public boolean checkLegalOverride(ResolvedMember parent, ResolvedMember child) { //System.err.println("check: " + child.getDeclaringType() + " overrides " + parent.getDeclaringType()); if (!parent.getReturnType().equals(child.getReturnType())) { world.showMessage(IMessage.ERROR, "can't override " + parent + " with " + child + " return types don't match", child.getSourceLocation(), parent.getSourceLocation()); return false; } if (parent.getKind() == Member.POINTCUT) { TypeX[] pTypes = parent.getParameterTypes(); TypeX[] cTypes = child.getParameterTypes(); if (!Arrays.equals(pTypes, cTypes)) { world.showMessage(IMessage.ERROR, "can't override " + parent + " with " + child + " parameter types don't match", child.getSourceLocation(), parent.getSourceLocation()); return false; } } //System.err.println("check: " + child.getModifiers() + " more visible " + parent.getModifiers()); if (isMoreVisible(parent.getModifiers(), child.getModifiers())) { world.showMessage(IMessage.ERROR, "can't override " + parent + " with " + child + " visibility is reduced", child.getSourceLocation(), parent.getSourceLocation()); return false; } // check declared exceptions ResolvedTypeX[] childExceptions = world.resolve(child.getExceptions()); ResolvedTypeX[] parentExceptions = world.resolve(parent.getExceptions()); ResolvedTypeX runtimeException = world.resolve("java.lang.RuntimeException"); ResolvedTypeX error = world.resolve("java.lang.Error"); outer: for (int i=0, leni = childExceptions.length; i < leni; i++) { //System.err.println("checking: " + childExceptions[i]); if (runtimeException.isAssignableFrom(childExceptions[i])) continue; if (error.isAssignableFrom(childExceptions[i])) continue; for (int j = 0, lenj = parentExceptions.length; j < lenj; j++) { if (parentExceptions[j].isAssignableFrom(childExceptions[i])) continue outer; } world.showMessage(IMessage.ERROR, "overriden method doesn't throw " + childExceptions[i].getName(), child.getSourceLocation(), null); return false; } if (parent.isStatic() && !child.isStatic()) { world.showMessage(IMessage.ERROR, child.toString()+" cannot override "+parent.toString()+"; overridden method is static", child.getSourceLocation(),null); } else if (child.isStatic() && !parent.isStatic()) { world.showMessage(IMessage.ERROR, child.toString()+" cannot override "+parent.toString()+"; overriding method is static", child.getSourceLocation(),null); } return true; } private int compareMemberPrecedence(ResolvedMember m1, ResolvedMember m2) { //if (!m1.getReturnType().equals(m2.getReturnType())) return 0; if (Modifier.isAbstract(m1.getModifiers())) return -1; if (Modifier.isAbstract(m2.getModifiers())) return +1; if (m1.getDeclaringType().equals(m2.getDeclaringType())) return 0; ResolvedTypeX t1 = m1.getDeclaringType().resolve(world); ResolvedTypeX t2 = m2.getDeclaringType().resolve(world); if (t1.isAssignableFrom(t2)) { return -1; } if (t2.isAssignableFrom(t1)) { return +1; } return 0; } public static boolean isMoreVisible(int m1, int m2) { if (Modifier.isPrivate(m1)) return false; if (isPackage(m1)) return Modifier.isPrivate(m2); if (Modifier.isProtected(m1)) return /* private package */ (Modifier.isPrivate(m2) || isPackage(m2)); if (Modifier.isPublic(m1)) return /* private package protected */ ! Modifier.isPublic(m2); throw new RuntimeException("bad modifier: " + m1); } private static boolean isPackage(int i) { return (0 == (i & (Modifier.PUBLIC | Modifier.PRIVATE | Modifier.PROTECTED))); } private void interTypeConflictError( ConcreteTypeMunger m1, ConcreteTypeMunger m2) { //XXX this works only if we ignore separate compilation issues //XXX dual errors possible if (this instanceof BcelObjectType) return; //System.err.println("conflict at " + m2.getSourceLocation()); getWorld().showMessage(IMessage.ERROR, "intertype declaration from " + m1.getAspectType().getName() + " conflicts with intertype declaration: " + m2.getSignature() + " from " + m2.getAspectType().getName(), m2.getSourceLocation(), getSourceLocation()); } public ResolvedMember lookupSyntheticMember(Member member) { //??? horribly inefficient //for (Iterator i = //System.err.println("lookup " + member + " in " + interTypeMungers); for (Iterator i = interTypeMungers.iterator(); i.hasNext(); ) { ConcreteTypeMunger m = (ConcreteTypeMunger)i.next(); ResolvedMember ret = m.getMatchingSyntheticMember(member); if (ret != null) { //System.err.println(" found: " + ret); return ret; } } return null; } public void clearInterTypeMungers() { interTypeMungers = new ArrayList(); } public boolean isTopmostImplementor(ResolvedTypeX interfaceType) { if (isInterface()) return false; if (!interfaceType.isAssignableFrom(this)) return false; // check that I'm truly the topmost implementor if (interfaceType.isAssignableFrom(this.getSuperclass())) { return false; } return true; } public List getExposedPointcuts() { List ret = new ArrayList(); if (getSuperclass() != null) ret.addAll(getSuperclass().getExposedPointcuts()); for (Iterator i = Arrays.asList(getDeclaredInterfaces()).iterator(); i.hasNext(); ) { ResolvedTypeX t = (ResolvedTypeX)i.next(); addPointcutsResolvingConflicts(ret, Arrays.asList(t.getDeclaredPointcuts()), false); } addPointcutsResolvingConflicts(ret, Arrays.asList(getDeclaredPointcuts()), true); for (Iterator i = ret.iterator(); i.hasNext(); ) { ResolvedPointcutDefinition inherited = (ResolvedPointcutDefinition)i.next(); // System.err.println("looking at: " + inherited + " in " + this); // System.err.println(" " + inherited.isAbstract() + " in " + this.isAbstract()); if (inherited.isAbstract()) { if (!this.isAbstract()) { getWorld().showMessage(IMessage.ERROR, "inherited abstract " + inherited + " is not made concrete in " + this.getName(), inherited.getSourceLocation(), this.getSourceLocation()); } } } return ret; } private void addPointcutsResolvingConflicts(List acc, List added, boolean isOverriding) { for (Iterator i = added.iterator(); i.hasNext();) { ResolvedPointcutDefinition toAdd = (ResolvedPointcutDefinition) i.next(); //System.err.println("adding: " + toAdd); for (Iterator j = acc.iterator(); j.hasNext();) { ResolvedPointcutDefinition existing = (ResolvedPointcutDefinition) j.next(); if (existing == toAdd) continue; if (!isVisible(existing.getModifiers(), existing.getDeclaringType().resolve(getWorld()), this)) { continue; } if (conflictingSignature(existing, toAdd)) { if (isOverriding) { checkLegalOverride(existing, toAdd); j.remove(); } else { getWorld().showMessage( IMessage.ERROR, "conflicting inherited pointcuts in " + this.getName() + toAdd.getSignature(), existing.getSourceLocation(), toAdd.getSourceLocation()); j.remove(); } } } acc.add(toAdd); } } public ISourceLocation getSourceLocation() { return null; } public boolean isExposedToWeaver() { return false; } public WeaverStateInfo getWeaverState() { return null; } }
48,990
Bug 48990 Special case if(false) to not require a dynamic test
FastMatch, the efficient pattern matching for pointcuts on the constant pool, is currrently only implemented for the within pointcut. I am planning to provide further oimplementations for other pointcuts by release 1.2.
resolved fixed
10c6de6
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2004-07-28T15:13:09Z
2003-12-17T11:20:00Z
org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/compiler/ast/IfPseudoToken.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Common Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * PARC initial implementation * ******************************************************************/ package org.aspectj.ajdt.internal.compiler.ast; import java.lang.reflect.Modifier; import org.aspectj.weaver.Member; import org.aspectj.weaver.ResolvedMember; import org.aspectj.weaver.TypeX; import org.aspectj.weaver.patterns.IfPointcut; import org.aspectj.weaver.patterns.Pointcut; import org.eclipse.jdt.internal.compiler.CompilationResult; import org.eclipse.jdt.internal.compiler.ast.Argument; import org.eclipse.jdt.internal.compiler.ast.Expression; import org.eclipse.jdt.internal.compiler.ast.MethodDeclaration; import org.eclipse.jdt.internal.compiler.ast.ReturnStatement; import org.eclipse.jdt.internal.compiler.ast.Statement; import org.eclipse.jdt.internal.compiler.ast.TypeDeclaration; import org.eclipse.jdt.internal.compiler.lookup.TypeBinding; import org.eclipse.jdt.internal.compiler.parser.Parser; /** * (formals*): ... if(expr) ... * * generates the following: * public static final boolean ajc$if_N(formals*, [thisJoinPoints as needed]) { * return expr; * } * * Here's the complicated bit, it deals with cflow: * (a): ... this(a) && cflow(if (a == foo)) is an error. * The way we capture this is: * We generate the ajc$if method with an (a) parameter, we let eclipse do the proper * name binding. We then, as a post pass (that we need to do anyway) look for the * used parameters. If a is used, we signal an error because a was not one of the * cflow variables. * XXX we'll do this part after we do cflow * * The IfPointcut pcd then generates itself always as a dynamic test, it has to * get the right parameters through any named pointcut references... */ public class IfPseudoToken extends PseudoToken { public Expression expr; public MethodDeclaration testMethod; private IfPointcut pointcut; public IfPseudoToken( Parser parser, Expression expr) { super(parser, "if", false); this.expr = expr; } public Pointcut maybeGetParsedPointcut() { pointcut = new IfPointcut(new ResolvedMember(Member.METHOD, TypeX.OBJECT, 0, "if_", "()V"), 0); return pointcut; } /** * enclosingDec is either AdviceDeclaration or PointcutDeclaration */ public void postParse(TypeDeclaration typeDec, MethodDeclaration enclosingDec) { // typeDec.scope.problemReporter().signalError(sourceStart, sourceEnd, // "if pcd is not implemented in 1.1alpha1"); //XXX need to implement correctly if (pointcut == null) return; testMethod = makeMethod(enclosingDec.compilationResult, enclosingDec); AstUtil.addMethodDeclaration(typeDec, testMethod); } //XXX static state bad private static int counter = 0; //XXX todo: make sure that errors in Arguments only get displayed once private MethodDeclaration makeMethod(CompilationResult result, MethodDeclaration enclosingDec) { MethodDeclaration ret = new IfMethodDeclaration(result, pointcut); ret.modifiers = AccStatic | AccFinal | AccPublic; ret.returnType = AstUtil.makeTypeReference(TypeBinding.BooleanBinding); ret.selector = ("ajc$if_" + counter++).toCharArray(); ret.arguments = makeArguments(enclosingDec); ret.statements = new Statement[] { new ReturnStatement(expr, expr.sourceStart, expr.sourceEnd) }; return ret; } private Argument[] makeArguments(MethodDeclaration enclosingDec) { Argument[] baseArguments = enclosingDec.arguments; int len = baseArguments.length; if (enclosingDec instanceof AdviceDeclaration) { len = ((AdviceDeclaration)enclosingDec).baseArgumentCount; } Argument[] ret = new Argument[len]; for (int i=0; i < len; i ++) { Argument a = baseArguments[i]; ret[i] = new Argument(a.name, AstUtil.makeLongPos(a.sourceStart, a.sourceEnd), a.type, Modifier.FINAL); } ret = AdviceDeclaration.addTjpArguments(ret); return ret; } }
48,990
Bug 48990 Special case if(false) to not require a dynamic test
FastMatch, the efficient pattern matching for pointcuts on the constant pool, is currrently only implemented for the within pointcut. I am planning to provide further oimplementations for other pointcuts by release 1.2.
resolved fixed
10c6de6
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2004-07-28T15:13:09Z
2003-12-17T11:20:00Z
weaver/src/org/aspectj/weaver/patterns/IfPointcut.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Common Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * PARC initial implementation * ******************************************************************/ package org.aspectj.weaver.patterns; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.util.ArrayList; import java.util.List; import org.aspectj.bridge.IMessage; import org.aspectj.util.FuzzyBoolean; import org.aspectj.weaver.Advice; import org.aspectj.weaver.ISourceContext; import org.aspectj.weaver.IntMap; import org.aspectj.weaver.ResolvedMember; import org.aspectj.weaver.ResolvedPointcutDefinition; import org.aspectj.weaver.ResolvedTypeX; import org.aspectj.weaver.Shadow; import org.aspectj.weaver.ShadowMunger; import org.aspectj.weaver.ast.Expr; import org.aspectj.weaver.ast.Literal; import org.aspectj.weaver.ast.Test; import org.aspectj.weaver.ast.Var; public class IfPointcut extends Pointcut { public ResolvedMember testMethod; public int extraParameterFlags; public Pointcut residueSource; int baseArgsCount; //XXX some way to compute args public IfPointcut(ResolvedMember testMethod, int extraParameterFlags) { this.testMethod = testMethod; this.extraParameterFlags = extraParameterFlags; } public FuzzyBoolean fastMatch(FastMatchInfo type) { return FuzzyBoolean.MAYBE; } public FuzzyBoolean match(Shadow shadow) { //??? this is not maximally efficient return FuzzyBoolean.MAYBE; } public void write(DataOutputStream s) throws IOException { s.writeByte(Pointcut.IF); testMethod.write(s); s.writeByte(extraParameterFlags); writeLocation(s); } public static Pointcut read(DataInputStream s, ISourceContext context) throws IOException { IfPointcut ret = new IfPointcut(ResolvedMember.readResolvedMember(s, context), s.readByte()); ret.readLocation(context, s); return ret; } public void resolveBindings(IScope scope, Bindings bindings) { //??? all we need is good error messages in here in cflow contexts } public void resolveBindingsFromRTTI() {} public boolean equals(Object other) { if (!(other instanceof IfPointcut)) return false; IfPointcut o = (IfPointcut)other; return o.testMethod.equals(this.testMethod); } public int hashCode() { int result = 17; result = 37*result + testMethod.hashCode(); return result; } public String toString() { return "if(" + testMethod + ")"; } //??? The implementation of name binding and type checking in if PCDs is very convoluted // There has to be a better way... private boolean findingResidue = false; public Test findResidue(Shadow shadow, ExposedState state) { if (findingResidue) return Literal.TRUE; findingResidue = true; try { ExposedState myState = new ExposedState(baseArgsCount); //System.out.println(residueSource); //??? we throw out the test that comes from this walk. All we want here // is bindings for the arguments residueSource.findResidue(shadow, myState); //System.out.println(myState); Test ret = Literal.TRUE; List args = new ArrayList(); for (int i=0; i < baseArgsCount; i++) { Var v = myState.get(i); args.add(v); ret = Test.makeAnd(ret, Test.makeInstanceof(v, testMethod.getParameterTypes()[i].resolve(shadow.getIWorld()))); } // handle thisJoinPoint parameters if ((extraParameterFlags & Advice.ThisJoinPoint) != 0) { args.add(shadow.getThisJoinPointVar()); } if ((extraParameterFlags & Advice.ThisJoinPointStaticPart) != 0) { args.add(shadow.getThisJoinPointStaticPartVar()); } if ((extraParameterFlags & Advice.ThisEnclosingJoinPointStaticPart) != 0) { args.add(shadow.getThisEnclosingJoinPointStaticPartVar()); } ret = Test.makeAnd(ret, Test.makeCall(testMethod, (Expr[])args.toArray(new Expr[args.size()]))); return ret; } finally { findingResidue = false; } } public Pointcut concretize(ResolvedTypeX inAspect, IntMap bindings) { return this.concretize1(inAspect, bindings); } private IfPointcut partiallyConcretized = null; public Pointcut concretize1(ResolvedTypeX inAspect, IntMap bindings) { //System.err.println("concretize: " + this + " already: " + partiallyConcretized); if (isDeclare(bindings.getEnclosingAdvice())) { // Enforce rule about which designators are supported in declare inAspect.getWorld().showMessage(IMessage.ERROR, "if() pointcut designator cannot be used in declare statement", bindings.getEnclosingAdvice().getSourceLocation(), null); return Pointcut.makeMatchesNothing(Pointcut.CONCRETE); } if (partiallyConcretized != null) { return partiallyConcretized; } IfPointcut ret = new IfPointcut(testMethod, extraParameterFlags); partiallyConcretized = ret; // It is possible to directly code your pointcut expression in a per clause // rather than defining a pointcut declaration and referencing it in your // per clause. If you do this, we have problems (bug #62458). For now, // let's police that you are trying to code a pointcut in a per clause and // put out a compiler error. if (bindings.directlyInAdvice() && bindings.getEnclosingAdvice()==null) { // Assumption: if() is in a per clause if we say we are directly in advice // but we have no enclosing advice. inAspect.getWorld().showMessage(IMessage.ERROR, "if() pointcut designator cannot be used directly in a per clause (compiler limitation). Create a named pointcut containing the if() and refer to it", this.getSourceLocation(),null); return Pointcut.makeMatchesNothing(Pointcut.CONCRETE); } if (bindings.directlyInAdvice()) { ShadowMunger advice = bindings.getEnclosingAdvice(); if (advice instanceof Advice) { ret.baseArgsCount = ((Advice)advice).getBaseParameterCount(); } else { ret.baseArgsCount = 0; } ret.residueSource = advice.getPointcut().concretize(inAspect, ret.baseArgsCount, advice); } else { ResolvedPointcutDefinition def = bindings.peekEnclosingDefinitition(); if (def == CflowPointcut.CFLOW_MARKER) { inAspect.getWorld().showMessage(IMessage.ERROR, "if not supported lexically within cflow (compiler limitation)", getSourceLocation(), null); return Pointcut.makeMatchesNothing(Pointcut.CONCRETE); } ret.baseArgsCount = def.getParameterTypes().length; IntMap newBindings = IntMap.idMap(ret.baseArgsCount); newBindings.copyContext(bindings); ret.residueSource = def.getPointcut().concretize(inAspect, newBindings); } return ret; } }
48,990
Bug 48990 Special case if(false) to not require a dynamic test
FastMatch, the efficient pattern matching for pointcuts on the constant pool, is currrently only implemented for the within pointcut. I am planning to provide further oimplementations for other pointcuts by release 1.2.
resolved fixed
10c6de6
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2004-07-28T15:13:09Z
2003-12-17T11:20:00Z
weaver/src/org/aspectj/weaver/patterns/Pointcut.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Common Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * PARC initial implementation * ******************************************************************/ package org.aspectj.weaver.patterns; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.aspectj.lang.JoinPoint; import org.aspectj.util.FuzzyBoolean; import org.aspectj.util.TypeSafeEnum; import org.aspectj.weaver.Advice; import org.aspectj.weaver.AdviceKind; import org.aspectj.weaver.BCException; import org.aspectj.weaver.Checker; import org.aspectj.weaver.ISourceContext; import org.aspectj.weaver.IntMap; import org.aspectj.weaver.ResolvedTypeX; import org.aspectj.weaver.Shadow; import org.aspectj.weaver.ShadowMunger; import org.aspectj.weaver.ast.Literal; import org.aspectj.weaver.ast.Test; /** * The lifecycle of Pointcuts is modeled by Pointcut.State. It has three things: * * <p>Creation -- SYMBOLIC -- then resolve(IScope) -- RESOLVED -- concretize(...) -- CONCRETE * * @author Erik Hilsdale * @author Jim Hugunin */ public abstract class Pointcut extends PatternNode { public static final class State extends TypeSafeEnum { public State(String name, int key) { super(name, key); } } public static final State SYMBOLIC = new State("symbolic", 0); public static final State RESOLVED = new State("resolved", 1); public static final State CONCRETE = new State("concrete", 2); public State state; /** * Constructor for Pattern. */ public Pointcut() { super(); this.state = SYMBOLIC; } /** * Could I match any shadows in the code defined within this type? */ public abstract FuzzyBoolean fastMatch(FastMatchInfo info); /** * Do I really match this shadow? * XXX implementors need to handle state */ public abstract FuzzyBoolean match(Shadow shadow); /* * for runtime / dynamic pointcuts. * Default implementation delegates to StaticPart matcher */ public FuzzyBoolean match(JoinPoint jp, JoinPoint.StaticPart enclosingJoinPoint) { return match(jp.getStaticPart()); } /* * for runtime / dynamic pointcuts. * Not all pointcuts can be matched at runtime, those that can should overide either * match(JoinPoint), or this method, or both. */ public FuzzyBoolean match(JoinPoint.StaticPart jpsp) { throw new UnsupportedOperationException("Pointcut expression " + this.toString() + "cannot be matched at runtime"); } public static final byte KINDED = 1; public static final byte WITHIN = 2; public static final byte THIS_OR_TARGET = 3; public static final byte ARGS = 4; public static final byte AND = 5; public static final byte OR = 6; public static final byte NOT = 7; public static final byte REFERENCE = 8; public static final byte IF = 9; public static final byte CFLOW = 10; public static final byte WITHINCODE = 12; public static final byte HANDLER = 13; public static final byte NONE = 20; // internal, only called from resolve protected abstract void resolveBindings(IScope scope, Bindings bindings); // internal, only called from resolve protected abstract void resolveBindingsFromRTTI(); /** * Returns this pointcut mutated */ public Pointcut resolve(IScope scope) { assertState(SYMBOLIC); Bindings bindingTable = new Bindings(scope.getFormalCount()); this.resolveBindings(scope, bindingTable); bindingTable.checkAllBound(scope); this.state = RESOLVED; return this; } /** * Returns this pointcut with type patterns etc resolved based on available RTTI */ public Pointcut resolve() { assertState(SYMBOLIC); this.resolveBindingsFromRTTI(); this.state = RESOLVED; return this; } /** * Returns a new pointcut */ public Pointcut concretize(ResolvedTypeX inAspect, int arity) { return concretize(inAspect, IntMap.idMap(arity)); } //XXX this is the signature we're moving to public Pointcut concretize(ResolvedTypeX inAspect, int arity, ShadowMunger advice) { //if (state == CONCRETE) return this; //??? IntMap map = IntMap.idMap(arity); map.setEnclosingAdvice(advice); map.setConcreteAspect(inAspect); return concretize(inAspect, map); } public boolean isDeclare(ShadowMunger munger) { if (munger == null) return false; // ??? Is it actually an error if we get a null munger into this method. if (munger instanceof Checker) return true; if (((Advice)munger).getKind().equals(AdviceKind.Softener)) return true; return false; } public Pointcut concretize(ResolvedTypeX inAspect, IntMap bindings) { //!!! add this test -- assertState(RESOLVED); Pointcut ret = this.concretize1(inAspect, bindings); if (shouldCopyLocationForConcretize()) ret.copyLocationFrom(this); ret.state = CONCRETE; return ret; } protected boolean shouldCopyLocationForConcretize() { return true; } /** * Resolves and removes ReferencePointcuts, replacing with basic ones * * @param inAspect the aspect to resolve relative to * @param bindings a Map from formal index in the current lexical context * -> formal index in the concrete advice that will run * * This must always return a new Pointcut object (even if the concretized * Pointcut is identical to the resolved one). That behavior is * assumed in many places. * XXX fix implementors to handle state */ protected abstract Pointcut concretize1(ResolvedTypeX inAspect, IntMap bindings); //XXX implementors need to handle state /** * This can be called from NotPointcut even for Pointcuts that * don't match the shadow */ public abstract Test findResidue(Shadow shadow, ExposedState state); //XXX we're not sure whether or not this is needed //XXX currently it's unused we're keeping it around as a stub public void postRead(ResolvedTypeX enclosingType) {} public static Pointcut read(DataInputStream s, ISourceContext context) throws IOException { byte kind = s.readByte(); Pointcut ret; switch(kind) { case KINDED: ret = KindedPointcut.read(s, context); break; case WITHIN: ret = WithinPointcut.read(s, context); break; case THIS_OR_TARGET: ret = ThisOrTargetPointcut.read(s, context); break; case ARGS: ret = ArgsPointcut.read(s, context); break; case AND: ret = AndPointcut.read(s, context); break; case OR: ret = OrPointcut.read(s, context); break; case NOT: ret = NotPointcut.read(s, context); break; case REFERENCE: ret = ReferencePointcut.read(s, context); break; case IF: ret = IfPointcut.read(s, context); break; case CFLOW: ret = CflowPointcut.read(s, context); break; case WITHINCODE: ret = WithincodePointcut.read(s, context); break; case HANDLER: ret = HandlerPointcut.read(s, context); break; case NONE: ret = makeMatchesNothing(RESOLVED); break; default: throw new BCException("unknown kind: " + kind); } ret.state = RESOLVED; return ret; } //public void prepare(Shadow shadow) {} // ---- test method public static Pointcut fromString(String str) { PatternParser parser = new PatternParser(str); return parser.parsePointcut(); } private static class MatchesNothingPointcut extends Pointcut { public Test findResidue(Shadow shadow, ExposedState state) { return Literal.FALSE; // can only get here if an earlier error occurred } public FuzzyBoolean fastMatch(FastMatchInfo type) { return FuzzyBoolean.NO; } public FuzzyBoolean match(Shadow shadow) { return FuzzyBoolean.NO; } public FuzzyBoolean match(JoinPoint.StaticPart jpsp) { return FuzzyBoolean.NO; } public void resolveBindings(IScope scope, Bindings bindings) { } public void resolveBindingsFromRTTI() { } public void postRead(ResolvedTypeX enclosingType) { } public Pointcut concretize1( ResolvedTypeX inAspect, IntMap bindings) { return makeMatchesNothing(state); } public void write(DataOutputStream s) throws IOException { s.writeByte(NONE); } public String toString() { return ""; } } //public static Pointcut MatchesNothing = new MatchesNothingPointcut(); //??? there could possibly be some good optimizations to be done at this point public static Pointcut makeMatchesNothing(State state) { Pointcut ret = new MatchesNothingPointcut(); ret.state = state; return ret; } public void assertState(State state) { if (this.state != state) { throw new BCException("expected state: " + state + " got: " + this.state); } } }
61,536
Bug 61536 Front-end bug, shouldn't allow patterns of the form foo.., should be foo..*
See following code: public class Test2 { public static void main(String args[]) { System.out.println("Hi"); } } aspect Aspect2 { // shouldn't one have to say, java..* instead of java.. in the following?? // Note that the first advice (incorrect one) passes the front-end, but does // not match, whereas the second one does match. I believe the front-end // should reject the first one. before () : call( * java..(..)) && within(Test2) { System.out.println( "Incorrect One: Before a call of method in a java package "); } before () : call( * java..*(..)) && within(Test2) { System.out.println( "Correct One: Before a call of method in a java package "); } }
resolved fixed
45bce91
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2004-07-29T12:39:42Z
2004-05-09T16:26:40Z
tests/bugs/EllipsesStar.java
61,536
Bug 61536 Front-end bug, shouldn't allow patterns of the form foo.., should be foo..*
See following code: public class Test2 { public static void main(String args[]) { System.out.println("Hi"); } } aspect Aspect2 { // shouldn't one have to say, java..* instead of java.. in the following?? // Note that the first advice (incorrect one) passes the front-end, but does // not match, whereas the second one does match. I believe the front-end // should reject the first one. before () : call( * java..(..)) && within(Test2) { System.out.println( "Incorrect One: Before a call of method in a java package "); } before () : call( * java..*(..)) && within(Test2) { System.out.println( "Correct One: Before a call of method in a java package "); } }
resolved fixed
45bce91
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2004-07-29T12:39:42Z
2004-05-09T16:26:40Z
weaver/src/org/aspectj/weaver/patterns/PatternParser.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Common Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * PARC initial implementation * ******************************************************************/ package org.aspectj.weaver.patterns; import java.util.ArrayList; import java.util.List; import org.aspectj.weaver.ISourceContext; import org.aspectj.weaver.Member; import org.aspectj.weaver.Shadow; //XXX doesn't handle errors for extra tokens very well (sometimes ignores) public class PatternParser { private ITokenSource tokenSource; private ISourceContext sourceContext; /** * Constructor for PatternParser. */ public PatternParser(ITokenSource tokenSource) { super(); this.tokenSource = tokenSource; this.sourceContext = tokenSource.getSourceContext(); } public PerClause maybeParsePerClause() { IToken tok = tokenSource.peek(); if (tok == IToken.EOF) return null; if (tok.isIdentifier()) { String name = tok.getString(); if (name.equals("issingleton")) { return parsePerSingleton(); } else if (name.equals("perthis")) { return parsePerObject(true); } else if (name.equals("pertarget")) { return parsePerObject(false); } else if (name.equals("percflow")) { return parsePerCflow(false); } else if (name.equals("percflowbelow")) { return parsePerCflow(true); } else { return null; } } return null; } private PerClause parsePerCflow(boolean isBelow) { parseIdentifier(); eat("("); Pointcut entry = parsePointcut(); eat(")"); return new PerCflow(entry, isBelow); } private PerClause parsePerObject(boolean isThis) { parseIdentifier(); eat("("); Pointcut entry = parsePointcut(); eat(")"); return new PerObject(entry, isThis); } private PerClause parsePerSingleton() { parseIdentifier(); eat("("); eat(")"); return new PerSingleton(); } public Declare parseDeclare() { int startPos = tokenSource.peek().getStart(); eatIdentifier("declare"); String kind = parseIdentifier(); eat(":"); Declare ret; //XXX beta add soft, dominates if (kind.equals("error")) { ret = parseErrorOrWarning(true); } else if (kind.equals("warning")) { ret = parseErrorOrWarning(false); } else if (kind.equals("precedence")) { ret = parseDominates(); } else if (kind.equals("dominates")) { throw new ParserException("name changed to declare precedence", tokenSource.peek(-2)); } else if (kind.equals("parents")) { ret = parseParents(); } else if (kind.equals("soft")) { ret = parseSoft(); } else { throw new ParserException("expected one of error, warning, parents, soft, dominates", tokenSource.peek(-1)); } int endPos = tokenSource.peek(-1).getEnd(); ret.setLocation(sourceContext, startPos, endPos); return ret; } public DeclarePrecedence parseDominates() { List l = new ArrayList(); do { l.add(parseTypePattern()); } while (maybeEat(",")); return new DeclarePrecedence(l); } private Declare parseParents() { TypePattern p = parseTypePattern(); IToken t = tokenSource.next(); if (!(t.getString().equals("extends") || t.getString().equals("implements"))) { throw new ParserException("extends or implements", t); } List l = new ArrayList(); do { l.add(parseTypePattern()); } while (maybeEat(",")); //XXX somewhere in the chain we need to enforce that we have only ExactTypePatterns return new DeclareParents(p, l); } private Declare parseSoft() { TypePattern p = parseTypePattern(); eat(":"); Pointcut pointcut = parsePointcut(); return new DeclareSoft(p, pointcut); } private Declare parseErrorOrWarning(boolean isError) { Pointcut pointcut = parsePointcut(); eat(":"); String message = parseStringLiteral(); return new DeclareErrorOrWarning(isError, pointcut, message); } public Pointcut parsePointcut() { Pointcut p = parseAtomicPointcut(); if (maybeEat("&&")) { p = new AndPointcut(p, parseNotOrPointcut()); } if (maybeEat("||")) { p = new OrPointcut(p, parsePointcut()); } return p; } private Pointcut parseNotOrPointcut() { Pointcut p = parseAtomicPointcut(); if (maybeEat("&&")) { p = new AndPointcut(p, parsePointcut()); } return p; } private Pointcut parseAtomicPointcut() { if (maybeEat("!")) { int startPos = tokenSource.peek(-1).getStart(); Pointcut p = new NotPointcut(parseAtomicPointcut(), startPos); return p; } if (maybeEat("(")) { Pointcut p = parsePointcut(); eat(")"); return p; } int startPos = tokenSource.peek().getStart(); Pointcut p = parseSinglePointcut(); int endPos = tokenSource.peek(-1).getEnd(); p.setLocation(sourceContext, startPos, endPos); return p; } public Pointcut parseSinglePointcut() { int start = tokenSource.getIndex(); IToken t = tokenSource.peek(); Pointcut p = t.maybeGetParsedPointcut(); if (p != null) { tokenSource.next(); return p; } String kind = parseIdentifier(); tokenSource.setIndex(start); if (kind.equals("execution") || kind.equals("call") || kind.equals("get") || kind.equals("set")) { return parseKindedPointcut(); } else if (kind.equals("args")) { return parseArgsPointcut(); } else if (kind.equals("this") || kind.equals("target")) { return parseThisOrTargetPointcut(); } else if (kind.equals("within")) { return parseWithinPointcut(); } else if (kind.equals("withincode")) { return parseWithinCodePointcut(); } else if (kind.equals("cflow")) { return parseCflowPointcut(false); } else if (kind.equals("cflowbelow")) { return parseCflowPointcut(true); } else if (kind.equals("adviceexecution")) { parseIdentifier(); eat("("); eat(")"); return new KindedPointcut(Shadow.AdviceExecution, new SignaturePattern(Member.ADVICE, ModifiersPattern.ANY, TypePattern.ANY, TypePattern.ANY, NamePattern.ANY, TypePatternList.ANY, ThrowsPattern.ANY)); } else if (kind.equals("handler")) { parseIdentifier(); eat("("); TypePattern typePat = parseTypePattern(); eat(")"); return new HandlerPointcut(typePat); } else if (kind.equals("initialization")) { parseIdentifier(); eat("("); SignaturePattern sig = parseConstructorSignaturePattern(); eat(")"); return new KindedPointcut(Shadow.Initialization, sig); } else if (kind.equals("staticinitialization")) { parseIdentifier(); eat("("); TypePattern typePat = parseTypePattern(); eat(")"); return new KindedPointcut(Shadow.StaticInitialization, new SignaturePattern(Member.STATIC_INITIALIZATION, ModifiersPattern.ANY, TypePattern.ANY, typePat, NamePattern.ANY, TypePatternList.EMPTY, ThrowsPattern.ANY)); } else if (kind.equals("preinitialization")) { parseIdentifier(); eat("("); SignaturePattern sig = parseConstructorSignaturePattern(); eat(")"); return new KindedPointcut(Shadow.PreInitialization, sig); } else { return parseReferencePointcut(); } } private SignaturePattern parseConstructorSignaturePattern() { SignaturePattern ret = parseMethodOrConstructorSignaturePattern(); if (ret.getKind() == Member.CONSTRUCTOR) return ret; throw new ParserException("constructor pattern required, found method pattern", ret); } private Pointcut parseWithinCodePointcut() { parseIdentifier(); eat("("); SignaturePattern sig = parseMethodOrConstructorSignaturePattern(); eat(")"); return new WithincodePointcut(sig); } private Pointcut parseCflowPointcut(boolean isBelow) { parseIdentifier(); eat("("); Pointcut entry = parsePointcut(); eat(")"); return new CflowPointcut(entry, isBelow, null); } /** * Method parseWithinPointcut. * @return Pointcut */ private Pointcut parseWithinPointcut() { parseIdentifier(); eat("("); TypePattern type = parseTypePattern(); eat(")"); return new WithinPointcut(type); } /** * Method parseThisOrTargetPointcut. * @return Pointcut */ private Pointcut parseThisOrTargetPointcut() { String kind = parseIdentifier(); eat("("); TypePattern type = parseTypePattern(); eat(")"); return new ThisOrTargetPointcut(kind.equals("this"), type); } /** * Method parseArgsPointcut. * @return Pointcut */ private Pointcut parseArgsPointcut() { parseIdentifier(); TypePatternList arguments = parseArgumentsPattern(); return new ArgsPointcut(arguments); } private Pointcut parseReferencePointcut() { TypePattern onType = parseTypePattern(); NamePattern name = tryToExtractName(onType); if (name == null) { throw new ParserException("name pattern", tokenSource.peek()); } if (onType.toString().equals("")) { onType = null; } TypePatternList arguments = parseArgumentsPattern(); return new ReferencePointcut(onType, name.maybeGetSimpleName(), arguments); } public List parseDottedIdentifier() { List ret = new ArrayList(); ret.add(parseIdentifier()); while (maybeEat(".")) { ret.add(parseIdentifier()); } return ret; } private KindedPointcut parseKindedPointcut() { String kind = parseIdentifier(); eat("("); SignaturePattern sig; Shadow.Kind shadowKind = null; if (kind.equals("execution")) { sig = parseMethodOrConstructorSignaturePattern(); if (sig.getKind() == Member.METHOD) { shadowKind = Shadow.MethodExecution; } else if (sig.getKind() == Member.CONSTRUCTOR) { shadowKind = Shadow.ConstructorExecution; } } else if (kind.equals("call")) { sig = parseMethodOrConstructorSignaturePattern(); if (sig.getKind() == Member.METHOD) { shadowKind = Shadow.MethodCall; } else if (sig.getKind() == Member.CONSTRUCTOR) { shadowKind = Shadow.ConstructorCall; } } else if (kind.equals("get")) { sig = parseFieldSignaturePattern(); shadowKind = Shadow.FieldGet; } else if (kind.equals("set")) { sig = parseFieldSignaturePattern(); shadowKind = Shadow.FieldSet; } else { throw new ParserException("bad kind: " + kind, tokenSource.peek()); } eat(")"); return new KindedPointcut(shadowKind, sig); } public TypePattern parseTypePattern() { TypePattern p = parseAtomicTypePattern(); if (maybeEat("&&")) { p = new AndTypePattern(p, parseNotOrTypePattern()); } if (maybeEat("||")) { p = new OrTypePattern(p, parseTypePattern()); } return p; } private TypePattern parseNotOrTypePattern() { TypePattern p = parseAtomicTypePattern(); if (maybeEat("&&")) { p = new AndTypePattern(p, parseTypePattern()); } return p; } private TypePattern parseAtomicTypePattern() { if (maybeEat("!")) { //int startPos = tokenSource.peek(-1).getStart(); //??? we lose source location for true start of !type TypePattern p = new NotTypePattern(parseAtomicTypePattern()); return p; } if (maybeEat("(")) { TypePattern p = parseTypePattern(); eat(")"); return p; } int startPos = tokenSource.peek().getStart(); TypePattern p = parseSingleTypePattern(); int endPos = tokenSource.peek(-1).getEnd(); p.setLocation(sourceContext, startPos, endPos); return p; } public TypePattern parseSingleTypePattern() { List names = parseDottedNamePattern(); // new ArrayList(); // NamePattern p1 = parseNamePattern(); // names.add(p1); // while (maybeEat(".")) { // if (maybeEat(".")) { // names.add(NamePattern.ELLIPSIS); // } // NamePattern p2 = parseNamePattern(); // names.add(p2); // } int dim = 0; while (maybeEat("[")) { eat("]"); dim++; } boolean includeSubtypes = maybeEat("+"); int endPos = tokenSource.peek(-1).getEnd(); //??? what about the source location of any's???? if (names.size() == 1 && ((NamePattern)names.get(0)).isAny() && dim == 0) return TypePattern.ANY; return new WildTypePattern(names, includeSubtypes, dim, endPos); } public List parseDottedNamePattern() { List names = new ArrayList(); StringBuffer buf = new StringBuffer(); IToken previous = null; while (true) { IToken tok; int startPos = tokenSource.peek().getStart(); String afterDot = null; while (true) { tok = tokenSource.peek(); if (previous != null) { if (!isAdjacent(previous, tok)) break; } if (tok.getString() == "*" || tok.isIdentifier()) { buf.append(tok.getString()); } else if (tok.getLiteralKind() != null) { //System.err.println("literal kind: " + tok.getString()); String s = tok.getString(); int dot = s.indexOf('.'); if (dot != -1) { buf.append(s.substring(0, dot)); afterDot = s.substring(dot+1); previous = tokenSource.next(); break; } buf.append(s); // ??? so-so } else { break; } previous = tokenSource.next(); //XXX need to handle floats and other fun stuff } int endPos = tokenSource.peek(-1).getEnd(); if (buf.length() == 0 && names.isEmpty()) { throw new ParserException("expected name pattern", tok); } if (buf.length() == 0) { names.add(NamePattern.ELLIPSIS); } else { checkLegalName(buf.toString(), previous); NamePattern ret = new NamePattern(buf.toString()); ret.setLocation(sourceContext, startPos, endPos); names.add(ret); } if (afterDot == null) { buf.setLength(0); if (!maybeEat(".")) break; else previous = tokenSource.peek(-1); } else { buf.setLength(0); buf.append(afterDot); afterDot = null; } } //System.err.println("parsed: " + names); return names; } public NamePattern parseNamePattern() { StringBuffer buf = new StringBuffer(); IToken previous = null; IToken tok; int startPos = tokenSource.peek().getStart(); while (true) { tok = tokenSource.peek(); if (previous != null) { if (!isAdjacent(previous, tok)) break; } if (tok.getString() == "*" || tok.isIdentifier()) { buf.append(tok.getString()); } else if (tok.getLiteralKind() != null) { //System.err.println("literal kind: " + tok.getString()); String s = tok.getString(); if (s.indexOf('.') != -1) break; buf.append(s); // ??? so-so } else { break; } previous = tokenSource.next(); //XXX need to handle floats and other fun stuff } int endPos = tokenSource.peek(-1).getEnd(); if (buf.length() == 0) { throw new ParserException("expected name pattern", tok); } checkLegalName(buf.toString(), previous); NamePattern ret = new NamePattern(buf.toString()); ret.setLocation(sourceContext, startPos, endPos); return ret; } private void checkLegalName(String s, IToken tok) { char ch = s.charAt(0); if (!(ch == '*' || Character.isJavaIdentifierStart(ch))) { throw new ParserException("illegal identifier start (" + ch + ")", tok); } for (int i=1, len=s.length(); i < len; i++) { ch = s.charAt(i); if (!(ch == '*' || Character.isJavaIdentifierPart(ch))) { throw new ParserException("illegal identifier character (" + ch + ")", tok); } } } private boolean isAdjacent(IToken first, IToken second) { return first.getEnd() == second.getStart()-1; } public ModifiersPattern parseModifiersPattern() { int requiredFlags = 0; int forbiddenFlags = 0; int start; while (true) { start = tokenSource.getIndex(); boolean isForbidden = false; isForbidden = maybeEat("!"); IToken t = tokenSource.next(); int flag = ModifiersPattern.getModifierFlag(t.getString()); if (flag == -1) break; if (isForbidden) forbiddenFlags |= flag; else requiredFlags |= flag; } tokenSource.setIndex(start); if (requiredFlags == 0 && forbiddenFlags == 0) { return ModifiersPattern.ANY; } else { return new ModifiersPattern(requiredFlags, forbiddenFlags); } } public TypePatternList parseArgumentsPattern() { List patterns = new ArrayList(); eat("("); if (maybeEat(")")) { return new TypePatternList(); } do { if (maybeEat(".")) { eat("."); patterns.add(TypePattern.ELLIPSIS); } else { patterns.add(parseTypePattern()); } } while (maybeEat(",")); eat(")"); return new TypePatternList(patterns); } public ThrowsPattern parseOptionalThrowsPattern() { IToken t = tokenSource.peek(); if (t.isIdentifier() && t.getString().equals("throws")) { tokenSource.next(); List required = new ArrayList(); List forbidden = new ArrayList(); do { boolean isForbidden = maybeEat("!"); //???might want an error for a second ! without a paren TypePattern p = parseTypePattern(); if (isForbidden) forbidden.add(p); else required.add(p); } while (maybeEat(",")); return new ThrowsPattern(new TypePatternList(required), new TypePatternList(forbidden)); } return ThrowsPattern.ANY; } public SignaturePattern parseMethodOrConstructorSignaturePattern() { int startPos = tokenSource.peek().getStart(); ModifiersPattern modifiers = parseModifiersPattern(); TypePattern returnType = parseTypePattern(); TypePattern declaringType; NamePattern name = null; Member.Kind kind; // here we can check for 'new' if (maybeEatNew(returnType)) { kind = Member.CONSTRUCTOR; if (returnType.toString().length() == 0) { declaringType = TypePattern.ANY; } else { declaringType = returnType; } returnType = TypePattern.ANY; name = NamePattern.ANY; } else { kind = Member.METHOD; declaringType = parseTypePattern(); if (maybeEat(".")) { name = parseNamePattern(); } else { name = tryToExtractName(declaringType); if (name == null) { throw new ParserException("name pattern", tokenSource.peek()); } String simpleName = name.maybeGetSimpleName(); //XXX should add check for any Java keywords if (simpleName != null && simpleName.equals("new")) { throw new ParserException("constructor patterns have no return type", tokenSource.peek()); } if (declaringType.toString().equals("")) { declaringType = TypePattern.ANY; } } } TypePatternList parameterTypes = parseArgumentsPattern(); ThrowsPattern throwsPattern = parseOptionalThrowsPattern(); SignaturePattern ret = new SignaturePattern(kind, modifiers, returnType, declaringType, name, parameterTypes, throwsPattern); int endPos = tokenSource.peek(-1).getEnd(); ret.setLocation(sourceContext, startPos, endPos); return ret; } private boolean maybeEatNew(TypePattern returnType) { if (returnType instanceof WildTypePattern) { WildTypePattern p = (WildTypePattern)returnType; if (p.maybeExtractName("new")) return true; } int start = tokenSource.getIndex(); if (maybeEat(".")) { String id = maybeEatIdentifier(); if (id != null && id.equals("new")) return true; tokenSource.setIndex(start); } return false; } public SignaturePattern parseFieldSignaturePattern() { int startPos = tokenSource.peek().getStart(); ModifiersPattern modifiers = parseModifiersPattern(); TypePattern returnType = parseTypePattern(); TypePattern declaringType = parseTypePattern(); NamePattern name; //System.err.println("parsed field: " + declaringType.toString()); if (maybeEat(".")) { name = parseNamePattern(); } else { name = tryToExtractName(declaringType); if (declaringType.toString().equals("")) { declaringType = TypePattern.ANY; } } SignaturePattern ret = new SignaturePattern(Member.FIELD, modifiers, returnType, declaringType, name, TypePatternList.ANY, ThrowsPattern.ANY); int endPos = tokenSource.peek(-1).getEnd(); ret.setLocation(sourceContext, startPos, endPos); return ret; } private NamePattern tryToExtractName(TypePattern nextType) { if (nextType == TypePattern.ANY) { return NamePattern.ANY; } else if (nextType instanceof WildTypePattern) { WildTypePattern p = (WildTypePattern)nextType; return p.extractName(); } else { return null; } } public String parseStringLiteral() { IToken token = tokenSource.next(); String literalKind = token.getLiteralKind(); if (literalKind == "string") { return token.getString(); } throw new ParserException("string", token); } public String parseIdentifier() { IToken token = tokenSource.next(); if (token.isIdentifier()) return token.getString(); throw new ParserException("identifier", token); } public void eatIdentifier(String expectedValue) { IToken next = tokenSource.next(); if (!next.getString().equals(expectedValue)) { throw new ParserException(expectedValue, next); } } public boolean maybeEatIdentifier(String expectedValue) { IToken next = tokenSource.peek(); if (next.getString().equals(expectedValue)) { tokenSource.next(); return true; } else { return false; } } public void eat(String expectedValue) { IToken next = tokenSource.next(); if (next.getString() != expectedValue) { throw new ParserException(expectedValue, next); } } public boolean maybeEat(String token) { IToken next = tokenSource.peek(); if (next.getString() == token) { tokenSource.next(); return true; } else { return false; } } public String maybeEatIdentifier() { IToken next = tokenSource.peek(); if (next.isIdentifier()) { tokenSource.next(); return next.getString(); } else { return null; } } public boolean peek(String token) { IToken next = tokenSource.peek(); return next.getString() == token; } public PatternParser(String data) { this(BasicTokenSource.makeTokenSource(data)); } }
30,439
Bug 30439 spurious "circular dependency" error
AspectJ Compiler 1.1beta4 This program: aspect Foo { pointcut p1(): execution(void f()) && cflow(execution(void f1())); pointcut p2(): execution(void f()) && cflow(execution(void f2())); before(): p1() { } after(): p1() { } before(): p2() { } after(): p2() { } } class A { void f1() { f(); } void f2() { f(); } void f() { } } results in these errors: circular dependency at method-execution(void A.f()) circular dependency at method-execution(void A.f()) circular dependency at method-execution(void A.f()) circular dependency at method-execution(void A.f()) 4 errors If I comment out any one of the four pieces of advice, all the errors go away. Also, assuming that there is a valid reason for printing this error sometimes, how come there's no line number? --Doug
resolved fixed
4feb835
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2004-07-29T15:04:00Z
2003-01-28T21:40:00Z
weaver/src/org/aspectj/weaver/Advice.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Common Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * PARC initial implementation * ******************************************************************/ package org.aspectj.weaver; import java.util.Collections; import java.util.List; import org.aspectj.bridge.IMessage; import org.aspectj.weaver.patterns.AndPointcut; import org.aspectj.weaver.patterns.PerClause; import org.aspectj.weaver.patterns.Pointcut; import org.aspectj.weaver.patterns.TypePattern; public abstract class Advice extends ShadowMunger { protected AjAttribute.AdviceAttribute attribute; // the pointcut field is ignored protected AdviceKind kind; // alias of attribute.getKind() protected Member signature; // not necessarily declaring aspect, this is a semantics change from 1.0 protected ResolvedTypeX concreteAspect; // null until after concretize protected List innerCflowEntries = Collections.EMPTY_LIST; // just for cflow*Entry kinds protected int nFreeVars; // just for cflow*Entry kinds protected TypePattern exceptionType; // just for Softener kind public static Advice makeCflowEntry(World world, Pointcut entry, boolean isBelow, Member stackField, int nFreeVars, List innerCflowEntries, ResolvedTypeX inAspect){ Advice ret = world.concreteAdvice(isBelow ? AdviceKind.CflowBelowEntry : AdviceKind.CflowEntry, entry, stackField, 0, entry); //0); ret.innerCflowEntries = innerCflowEntries; ret.nFreeVars = nFreeVars; ret.concreteAspect = inAspect; return ret; } public static Advice makePerCflowEntry(World world, Pointcut entry, boolean isBelow, Member stackField, ResolvedTypeX inAspect, List innerCflowEntries) { Advice ret = world.concreteAdvice(isBelow ? AdviceKind.PerCflowBelowEntry : AdviceKind.PerCflowEntry, entry, stackField, 0, entry); ret.innerCflowEntries = innerCflowEntries; ret.concreteAspect = inAspect; return ret; } public static Advice makePerObjectEntry(World world, Pointcut entry, boolean isThis, ResolvedTypeX inAspect) { Advice ret = world.concreteAdvice(isThis ? AdviceKind.PerThisEntry : AdviceKind.PerTargetEntry, entry, null, 0, entry); ret.concreteAspect = inAspect; return ret; } public static Advice makeSoftener(World world, Pointcut entry, TypePattern exceptionType,ResolvedTypeX inAspect) { Advice ret = world.concreteAdvice(AdviceKind.Softener, entry, null, 0, entry); ret.exceptionType = exceptionType; ret.concreteAspect = inAspect; // System.out.println("made ret: " + ret + " with " + exceptionType); return ret; } public Advice(AjAttribute.AdviceAttribute attribute, Pointcut pointcut, Member signature) { super(pointcut, attribute.getStart(), attribute.getEnd(), attribute.getSourceContext()); this.attribute = attribute; this.kind = attribute.getKind(); // alias this.signature = signature; } public boolean match(Shadow shadow, World world) { if (super.match(shadow, world)) { if (shadow.getKind() == Shadow.ExceptionHandler) { if (kind.isAfter() || kind == AdviceKind.Around) { world.showMessage(IMessage.WARNING, "Only before advice is supported on handler join points (compiler limitation)", getSourceLocation(), shadow.getSourceLocation()); return false; } } if (hasExtraParameter() && kind == AdviceKind.AfterReturning) { return getExtraParameterType().isConvertableFrom(shadow.getReturnType(), world); } else if (kind == AdviceKind.PerTargetEntry) { return shadow.hasTarget(); } else if (kind == AdviceKind.PerThisEntry) { return shadow.hasThis(); } else if (kind == AdviceKind.Around) { if (shadow.getKind() == Shadow.PreInitialization) { world.showMessage(IMessage.ERROR, "around on pre-initialization not supported (compiler limitation)", getSourceLocation(), shadow.getSourceLocation()); return false; } else if (shadow.getKind() == Shadow.Initialization) { world.showMessage(IMessage.ERROR, "around on initialization not supported (compiler limitation)", getSourceLocation(), shadow.getSourceLocation()); return false; } else if (shadow.getKind() == Shadow.StaticInitialization && shadow.getEnclosingType().isInterface(world)) { world.showMessage(IMessage.ERROR, "around on staticinitialization of interface \'" + shadow.getEnclosingType().getName() + "\' not supported (compiler limitation)", getSourceLocation(), shadow.getSourceLocation()); return false; } else { //System.err.println(getSignature().getReturnType() + " from " + shadow.getReturnType()); if (getSignature().getReturnType() == ResolvedTypeX.VOID) { if (shadow.getReturnType() != ResolvedTypeX.VOID) { world.showMessage(IMessage.ERROR, "applying to join point that doesn't return void: " + shadow, getSourceLocation(), shadow.getSourceLocation()); return false; } } else if (getSignature().getReturnType().equals(TypeX.OBJECT)) { return true; } else if(!shadow.getReturnType().isAssignableFrom(getSignature().getReturnType(), world)) { //System.err.println(this + ", " + sourceContext + ", " + start); world.showMessage(IMessage.ERROR, "incompatible return type applying to " + shadow, getSourceLocation(), shadow.getSourceLocation()); return false; } } } return true; } else { return false; } } // ---- public AdviceKind getKind() { return kind; } public Member getSignature() { return signature; } public boolean hasExtraParameter() { return (getExtraParameterFlags() & ExtraArgument) != 0; } protected int getExtraParameterFlags() { return attribute.getExtraParameterFlags(); } protected int getExtraParameterCount() { return countOnes(getExtraParameterFlags() & ParameterMask); } public static int countOnes(int bits) { int ret = 0; while (bits != 0) { if ((bits & 1) != 0) ret += 1; bits = bits >> 1; } return ret; } public int getBaseParameterCount() { return getSignature().getParameterTypes().length - getExtraParameterCount(); } public TypeX getExtraParameterType() { if (!hasExtraParameter()) return ResolvedTypeX.MISSING; return signature.getParameterTypes()[getBaseParameterCount()]; } public TypeX getDeclaringAspect() { return signature.getDeclaringType(); } protected String extraParametersToString() { if (getExtraParameterFlags() == 0) { return ""; } else { return "(extraFlags: " + getExtraParameterFlags() + ")"; } } public Pointcut getPointcut() { return pointcut; } // ---- /** @param fromType is guaranteed to be a non-abstract aspect * @param perClause has been concretized at a higher level */ public ShadowMunger concretize(ResolvedTypeX fromType, World world, PerClause clause) { // assert !fromType.isAbstract(); Pointcut p = pointcut.concretize(fromType, signature.getArity(), this); if (clause != null) { p = new AndPointcut(clause, p); p.state = Pointcut.CONCRETE; } Advice munger = world.concreteAdvice(attribute, p, signature); munger.concreteAspect = fromType; //System.err.println("concretizing here " + p + " with clause " + clause); return munger; } // ---- from object public String toString() { return "(" + getKind() + extraParametersToString() + ": " + pointcut + "->" + signature + ")"; } public boolean equals(Object other) { if (! (other instanceof Advice)) return false; Advice o = (Advice) other; return o.attribute.equals(attribute) && o.pointcut.equals(pointcut) && o.signature.equals(signature); } private volatile int hashCode = 0; public int hashCode() { if (hashCode == 0) { int result = 17; result = 37*result + kind.hashCode(); result = 37*result + pointcut.hashCode(); if (signature != null) result = 37*result + signature.hashCode(); hashCode = result; } return hashCode; } // ---- fields public static final int ExtraArgument = 1; public static final int ThisJoinPoint = 2; public static final int ThisJoinPointStaticPart = 4; public static final int ThisEnclosingJoinPointStaticPart = 8; public static final int ParameterMask = 0xf; public static final int CanInline = 0x40; // for testing only public void setLexicalPosition(int lexicalPosition) { start = lexicalPosition; } public ResolvedTypeX getConcreteAspect() { return concreteAspect; } }
30,439
Bug 30439 spurious "circular dependency" error
AspectJ Compiler 1.1beta4 This program: aspect Foo { pointcut p1(): execution(void f()) && cflow(execution(void f1())); pointcut p2(): execution(void f()) && cflow(execution(void f2())); before(): p1() { } after(): p1() { } before(): p2() { } after(): p2() { } } class A { void f1() { f(); } void f2() { f(); } void f() { } } results in these errors: circular dependency at method-execution(void A.f()) circular dependency at method-execution(void A.f()) circular dependency at method-execution(void A.f()) circular dependency at method-execution(void A.f()) 4 errors If I comment out any one of the four pieces of advice, all the errors go away. Also, assuming that there is a valid reason for printing this error sometimes, how come there's no line number? --Doug
resolved fixed
4feb835
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2004-07-29T15:04:00Z
2003-01-28T21:40:00Z
weaver/src/org/aspectj/weaver/Lint.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Common Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * PARC initial implementation * ******************************************************************/ package org.aspectj.weaver; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.text.MessageFormat; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Properties; import org.aspectj.bridge.IMessage; import org.aspectj.bridge.ISourceLocation; import org.aspectj.bridge.Message; import org.aspectj.bridge.MessageUtil; public class Lint { /* private */ Map kinds = new HashMap(); /* private */ World world; public final Kind invalidAbsoluteTypeName = new Kind("invalidAbsoluteTypeName", "no match for this type name: {0}"); public final Kind invalidWildcardTypeName = new Kind("invalidWildcardTypeName", "no match for this type pattern: {0}"); public final Kind unresolvableMember = new Kind("unresolvableMember", "can not resolve this member: {0}"); public final Kind typeNotExposedToWeaver = new Kind("typeNotExposedToWeaver", "this affected type is not exposed to the weaver: {0}"); public final Kind shadowNotInStructure = new Kind("shadowNotInStructure", "the shadow for this join point is not exposed in the structure model: {0}"); public final Kind unmatchedSuperTypeInCall = new Kind("unmatchedSuperTypeInCall", "does not match because declaring type is {0}, if match desired use target({1})"); public final Kind canNotImplementLazyTjp = new Kind("canNotImplementLazyTjp", "can not implement lazyTjp on this joinpoint {0} because around advice is used"); public final Kind needsSerialVersionUIDField = new Kind("needsSerialVersionUIDField", "serialVersionUID of type {0} needs to be set because of {1}"); public final Kind serialVersionUIDBroken = new Kind("brokeSerialVersionCompatibility", "serialVersionUID of type {0} is broken because of added field {1}"); public final Kind noInterfaceCtorJoinpoint = new Kind("noInterfaceCtorJoinpoint","no interface constructor-execution join point - use {0}+ for implementing classes"); public Lint(World world) { this.world = world; } public void setAll(String messageKind) { setAll(getMessageKind(messageKind)); } private void setAll(IMessage.Kind messageKind) { for (Iterator i = kinds.values().iterator(); i.hasNext(); ) { Kind kind = (Kind)i.next(); kind.setKind(messageKind); } } public void setFromProperties(File file) { try { InputStream s = new FileInputStream(file); setFromProperties(s); } catch (IOException ioe) { MessageUtil.error(world.getMessageHandler(), "problem loading Xlint properties file: " + file.getPath() + ", " + ioe.getMessage()); } } public void loadDefaultProperties() { InputStream s = getClass().getResourceAsStream("XlintDefault.properties"); if (s == null) { MessageUtil.warn(world.getMessageHandler(), "couldn't load XlintDefault.properties"); return; } try { setFromProperties(s); } catch (IOException ioe) { MessageUtil.error(world.getMessageHandler(), "problem loading XlintDefault.properties, " + ioe.getMessage()); } } private void setFromProperties(InputStream s) throws IOException { Properties p = new Properties(); p.load(s); setFromProperties(p); } public void setFromProperties(Properties properties) { for (Iterator i = properties.entrySet().iterator(); i.hasNext(); ) { Map.Entry entry = (Map.Entry)i.next(); Kind kind = (Kind)kinds.get(entry.getKey()); if (kind == null) { MessageUtil.error(world.getMessageHandler(), "invalid Xlint key: " + entry.getKey()); } else { kind.setKind(getMessageKind((String)entry.getValue())); } } } private IMessage.Kind getMessageKind(String v) { if (v.equals("ignore")) return null; else if (v.equals("warning")) return IMessage.WARNING; else if (v.equals("error")) return IMessage.ERROR; MessageUtil.error(world.getMessageHandler(), "invalid Xlint message kind (must be one of ignore, warning, error): " + v); return null; } public class Kind { private String name; private String message; private IMessage.Kind kind = IMessage.WARNING; public Kind(String name, String message) { this.name = name; this.message = message; kinds.put(this.name, this); } public boolean isEnabled() { return kind != null; } public String getName() { return name; } public IMessage.Kind getKind() { return kind; } public void setKind(IMessage.Kind kind) { this.kind = kind; } public void signal(String info, ISourceLocation location) { if (kind == null) return; String text = MessageFormat.format(message, new Object[] {info} ); text += " [Xlint:" + name + "]"; world.getMessageHandler().handleMessage(new Message(text, kind, null, location)); } public void signal(String[] infos, ISourceLocation location, ISourceLocation[] extraLocations) { if (kind == null) return; String text = MessageFormat.format(message, infos ); text += " [Xlint:" + name + "]"; world.getMessageHandler().handleMessage( new Message(text, "", kind, location, null, extraLocations)); } } }
30,439
Bug 30439 spurious "circular dependency" error
AspectJ Compiler 1.1beta4 This program: aspect Foo { pointcut p1(): execution(void f()) && cflow(execution(void f1())); pointcut p2(): execution(void f()) && cflow(execution(void f2())); before(): p1() { } after(): p1() { } before(): p2() { } after(): p2() { } } class A { void f1() { f(); } void f2() { f(); } void f() { } } results in these errors: circular dependency at method-execution(void A.f()) circular dependency at method-execution(void A.f()) circular dependency at method-execution(void A.f()) circular dependency at method-execution(void A.f()) 4 errors If I comment out any one of the four pieces of advice, all the errors go away. Also, assuming that there is a valid reason for printing this error sometimes, how come there's no line number? --Doug
resolved fixed
4feb835
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2004-07-29T15:04:00Z
2003-01-28T21:40:00Z
weaver/src/org/aspectj/weaver/NewConstructorTypeMunger.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Common Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * PARC initial implementation * ******************************************************************/ package org.aspectj.weaver; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.util.Set; import org.aspectj.bridge.IMessage; public class NewConstructorTypeMunger extends ResolvedTypeMunger { private ResolvedMember syntheticConstructor; private ResolvedMember explicitConstructor; public NewConstructorTypeMunger( ResolvedMember signature, ResolvedMember syntheticConstructor, ResolvedMember explicitConstructor, Set superMethodsCalled) { super(Constructor, signature); this.syntheticConstructor = syntheticConstructor; this.explicitConstructor = explicitConstructor; this.setSuperMethodsCalled(superMethodsCalled); } //XXX horrible name clash here public ResolvedMember getDispatchMethod(TypeX aspectType) { return AjcMemberMaker.interMethodBody(signature, aspectType); } public void write(DataOutputStream s) throws IOException { kind.write(s); signature.write(s); syntheticConstructor.write(s); explicitConstructor.write(s); writeSuperMethodsCalled(s); } public static ResolvedTypeMunger readConstructor(DataInputStream s, ISourceContext context) throws IOException { return new NewConstructorTypeMunger( ResolvedMember.readResolvedMember(s, context), ResolvedMember.readResolvedMember(s, context), ResolvedMember.readResolvedMember(s, context), readSuperMethodsCalled(s)); } public ResolvedMember getExplicitConstructor() { return explicitConstructor; } public ResolvedMember getSyntheticConstructor() { return syntheticConstructor; } public void setExplicitConstructor(ResolvedMember explicitConstructor) { this.explicitConstructor = explicitConstructor; } public ResolvedMember getMatchingSyntheticMember(Member member, ResolvedTypeX aspectType) { ResolvedMember ret = getSyntheticConstructor(); if (ResolvedTypeX.matches(ret, member)) return getSignature(); return super.getMatchingSyntheticMember(member, aspectType); } public void check(World world) { if (getSignature().getDeclaringType().isAspect(world)) { world.showMessage(IMessage.ERROR, "can't declare constructor on an aspect", getSignature().getSourceLocation(), null); } } }
30,439
Bug 30439 spurious "circular dependency" error
AspectJ Compiler 1.1beta4 This program: aspect Foo { pointcut p1(): execution(void f()) && cflow(execution(void f1())); pointcut p2(): execution(void f()) && cflow(execution(void f2())); before(): p1() { } after(): p1() { } before(): p2() { } after(): p2() { } } class A { void f1() { f(); } void f2() { f(); } void f() { } } results in these errors: circular dependency at method-execution(void A.f()) circular dependency at method-execution(void A.f()) circular dependency at method-execution(void A.f()) circular dependency at method-execution(void A.f()) 4 errors If I comment out any one of the four pieces of advice, all the errors go away. Also, assuming that there is a valid reason for printing this error sometimes, how come there's no line number? --Doug
resolved fixed
4feb835
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2004-07-29T15:04:00Z
2003-01-28T21:40:00Z
weaver/src/org/aspectj/weaver/ResolvedTypeX.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Common Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * PARC initial implementation * ******************************************************************/ package org.aspectj.weaver; import java.lang.reflect.Modifier; 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.bridge.IMessage; import org.aspectj.bridge.ISourceLocation; import org.aspectj.bridge.Message; import org.aspectj.bridge.MessageUtil; import org.aspectj.weaver.patterns.Declare; import org.aspectj.weaver.patterns.PerClause; public abstract class ResolvedTypeX extends TypeX { protected World world; ResolvedTypeX(String signature, World world) { super(signature); this.world = world; } // ---- things that don't require a world /** returns Iterator&lt;ResolvedTypeX&gt; */ public final Iterator getDirectSupertypes() { Iterator ifacesIterator = Iterators.array(getDeclaredInterfaces()); ResolvedTypeX superclass = getSuperclass(); if (superclass == null) { return ifacesIterator; } else { return Iterators.snoc(ifacesIterator, superclass); } } public abstract ResolvedMember[] getDeclaredFields(); public abstract ResolvedMember[] getDeclaredMethods(); public abstract ResolvedTypeX[] getDeclaredInterfaces(); public abstract ResolvedMember[] getDeclaredPointcuts(); public abstract ResolvedTypeX getSuperclass(); public abstract int getModifiers(); public abstract boolean needsNoConversionFrom(TypeX other); public abstract boolean isCoerceableFrom(TypeX other); public abstract boolean isAssignableFrom(TypeX other); // ---- things that would require a world if I weren't resolved public final Iterator getDirectSupertypes(World world) { return getDirectSupertypes(); } public final ResolvedMember[] getDeclaredFields(World world) { return getDeclaredFields(); } public final ResolvedMember[] getDeclaredMethods(World world) { return getDeclaredMethods(); } public final TypeX[] getDeclaredInterfaces(World world) { return getDeclaredInterfaces(); } public final ResolvedMember[] getDeclaredPointcuts(World world) { return getDeclaredPointcuts(); } public final int getModifiers(World world) { return getModifiers(); } public final TypeX getSuperclass(World world) { return getSuperclass(); } // conversions public final boolean isAssignableFrom(TypeX other, World world) { return isAssignableFrom(other); } public final boolean isCoerceableFrom(TypeX other, World world) { return isCoerceableFrom(other); } public boolean needsNoConversionFrom(TypeX other, World world) { return needsNoConversionFrom(other); } public final boolean isConvertableFrom(TypeX other) { if (this.equals(OBJECT) || other.equals(OBJECT)) return true; return this.isCoerceableFrom(other); } // utilities public ResolvedTypeX getResolvedComponentType() { return null; } public ResolvedTypeX resolve(World world) { return this; } public World getWorld() { return world; } // ---- things from object public final boolean equals(Object other) { if (other instanceof ResolvedTypeX) { return this == other; } else { return super.equals(other); } } // ---- difficult things /** * returns an iterator through all of the fields of this type, in order * for checking from JVM spec 2ed 5.4.3.2. This means that the order is * * <ul><li> fields from current class </li> * <li> recur into direct superinterfaces </li> * <li> recur into superclass </li> * </ul> * * We keep a hashSet of interfaces that we've visited so we don't spiral * out into 2^n land. */ public Iterator getFields() { final Iterators.Filter dupFilter = Iterators.dupFilter(); Iterators.Getter typeGetter = new Iterators.Getter() { public Iterator get(Object o) { return dupFilter.filter( ((ResolvedTypeX)o).getDirectSupertypes()); } }; Iterators.Getter fieldGetter = new Iterators.Getter() { public Iterator get(Object o) { return Iterators.array(((ResolvedTypeX)o).getDeclaredFields()); } }; return Iterators.mapOver( Iterators.recur(this, typeGetter), fieldGetter); } /** * returns an iterator through all of the methods of this type, in order * for checking from JVM spec 2ed 5.4.3.3. This means that the order is * * <ul><li> methods from current class </li> * <li> recur into superclass, all the way up, not touching interfaces </li> * <li> recur into all superinterfaces, in some unspecified order </li> * </ul> * * We keep a hashSet of interfaces that we've visited so we don't spiral * out into 2^n land. */ public Iterator getMethods() { final Iterators.Filter dupFilter = Iterators.dupFilter(); Iterators.Getter ifaceGetter = new Iterators.Getter() { public Iterator get(Object o) { return dupFilter.filter( Iterators.array(((ResolvedTypeX)o).getDeclaredInterfaces()) ); } }; Iterators.Getter methodGetter = new Iterators.Getter() { public Iterator get(Object o) { return Iterators.array(((ResolvedTypeX)o).getDeclaredMethods()); } }; return Iterators.mapOver( Iterators.append( new Iterator() { ResolvedTypeX curr = ResolvedTypeX.this; public boolean hasNext() { return curr != null; } public Object next() { ResolvedTypeX ret = curr; curr = curr.getSuperclass(); return ret; } public void remove() { throw new UnsupportedOperationException(); } }, Iterators.recur(this, ifaceGetter)), methodGetter); } /** * described in JVM spec 2ed 5.4.3.2 */ public ResolvedMember lookupField(Member m) { return lookupMember(m, getFields()); } /** * described in JVM spec 2ed 5.4.3.3 */ public ResolvedMember lookupMethod(Member m) { return lookupMember(m, getMethods()); } /** return null if not found */ private ResolvedMember lookupMember(Member m, Iterator i) { while (i.hasNext()) { ResolvedMember f = (ResolvedMember) i.next(); if (matches(f, m)) return f; } return null; //ResolvedMember.Missing; //throw new BCException("can't find " + m); } /** return null if not found */ private ResolvedMember lookupMember(Member m, ResolvedMember[] a) { for (int i = 0; i < a.length; i++) { ResolvedMember f = a[i]; if (matches(f, m)) return f; } return null; } public static boolean matches(Member m1, Member m2) { if (m1 == null) return m2 == null; if (m2 == null) return false; return m1.getName().equals(m2.getName()) && m1.getSignature().equals(m2.getSignature()); } public static boolean conflictingSignature(Member m1, Member m2) { if (m1 == null || m2 == null) return false; if (!m1.getName().equals(m2.getName())) { return false; } if (m1.getKind() != m2.getKind()) { return false; } if (m1.getKind() == Member.FIELD) { return m1.getDeclaringType().equals(m2.getDeclaringType()); } else if (m1.getKind() == Member.POINTCUT) { return true; } TypeX[] p1 = m1.getParameterTypes(); TypeX[] p2 = m2.getParameterTypes(); int n = p1.length; if (n != p2.length) return false; for (int i=0; i < n; i++) { if (!p1[i].equals(p2[i])) return false; } return true; } /** * returns an iterator through all of the pointcuts of this type, in order * for checking from JVM spec 2ed 5.4.3.2 (as for fields). This means that the order is * * <ul><li> pointcuts from current class </li> * <li> recur into direct superinterfaces </li> * <li> recur into superclass </li> * </ul> * * We keep a hashSet of interfaces that we've visited so we don't spiral * out into 2^n land. */ public Iterator getPointcuts() { final Iterators.Filter dupFilter = Iterators.dupFilter(); // same order as fields Iterators.Getter typeGetter = new Iterators.Getter() { public Iterator get(Object o) { return dupFilter.filter( ((ResolvedTypeX)o).getDirectSupertypes()); } }; Iterators.Getter pointcutGetter = new Iterators.Getter() { public Iterator get(Object o) { //System.err.println("getting for " + o); return Iterators.array(((ResolvedTypeX)o).getDeclaredPointcuts()); } }; return Iterators.mapOver( Iterators.recur(this, typeGetter), pointcutGetter); } public ResolvedPointcutDefinition findPointcut(String name) { //System.err.println("looking for pointcuts " + this); for (Iterator i = getPointcuts(); i.hasNext(); ) { ResolvedPointcutDefinition f = (ResolvedPointcutDefinition) i.next(); //System.err.println(f); if (name.equals(f.getName())) { return f; } } return null; // should we throw an exception here? } // all about collecting CrosscuttingMembers //??? collecting data-structure, shouldn't really be a field public CrosscuttingMembers crosscuttingMembers; public CrosscuttingMembers collectCrosscuttingMembers() { crosscuttingMembers = new CrosscuttingMembers(this); crosscuttingMembers.setPerClause(getPerClause()); crosscuttingMembers.addShadowMungers(collectShadowMungers()); crosscuttingMembers.addTypeMungers(getTypeMungers()); crosscuttingMembers.addDeclares(collectDeclares(!this.doesNotExposeShadowMungers())); crosscuttingMembers.addPrivilegedAccesses(getPrivilegedAccesses()); //System.err.println("collected cc members: " + this + ", " + collectDeclares()); return crosscuttingMembers; } public final Collection collectDeclares(boolean includeAdviceLike) { if (! this.isAspect() ) return Collections.EMPTY_LIST; ArrayList ret = new ArrayList(); //if (this.isAbstract()) { for (Iterator i = getDeclares().iterator(); i.hasNext();) { Declare dec = (Declare) i.next(); if (!dec.isAdviceLike()) ret.add(dec); } if (!includeAdviceLike) return ret; if (!this.isAbstract()) { //ret.addAll(getDeclares()); final Iterators.Filter dupFilter = Iterators.dupFilter(); Iterators.Getter typeGetter = new Iterators.Getter() { public Iterator get(Object o) { return dupFilter.filter( ((ResolvedTypeX)o).getDirectSupertypes()); } }; Iterator typeIterator = Iterators.recur(this, typeGetter); while (typeIterator.hasNext()) { ResolvedTypeX ty = (ResolvedTypeX) typeIterator.next(); //System.out.println("super: " + ty + ", " + ); for (Iterator i = ty.getDeclares().iterator(); i.hasNext();) { Declare dec = (Declare) i.next(); if (dec.isAdviceLike()) ret.add(dec); } } } return ret; } private final Collection collectShadowMungers() { if (! this.isAspect() || this.isAbstract() || this.doesNotExposeShadowMungers()) return Collections.EMPTY_LIST; ArrayList acc = new ArrayList(); final Iterators.Filter dupFilter = Iterators.dupFilter(); Iterators.Getter typeGetter = new Iterators.Getter() { public Iterator get(Object o) { return dupFilter.filter( ((ResolvedTypeX)o).getDirectSupertypes()); } }; Iterator typeIterator = Iterators.recur(this, typeGetter); while (typeIterator.hasNext()) { ResolvedTypeX ty = (ResolvedTypeX) typeIterator.next(); acc.addAll(ty.getDeclaredShadowMungers()); } return acc; } protected boolean doesNotExposeShadowMungers() { return false; } public PerClause getPerClause() { return null; } protected Collection getDeclares() { return Collections.EMPTY_LIST; } protected Collection getTypeMungers() { return Collections.EMPTY_LIST; } protected Collection getPrivilegedAccesses() { return Collections.EMPTY_LIST; } // ---- useful things public final boolean isInterface() { return Modifier.isInterface(getModifiers()); } public final boolean isAbstract() { return Modifier.isAbstract(getModifiers()); } public boolean isClass() { return false; } public boolean isAspect() { return false; } public boolean isSynthetic() { return signature.indexOf("$ajc") != -1; } public final boolean isFinal() { return Modifier.isFinal(getModifiers()); } public Collection getDeclaredAdvice() { List l = new ArrayList(); ResolvedMember[] methods = getDeclaredMethods(); for (int i=0, len = methods.length; i < len; i++) { ShadowMunger munger = methods[i].getAssociatedShadowMunger(); if (munger != null) l.add(munger); } return l; } private List shadowMungers = new ArrayList(0); public Collection getDeclaredShadowMungers() { Collection c = getDeclaredAdvice(); c.addAll(shadowMungers); return c; } public void addShadowMunger(ShadowMunger munger) { shadowMungers.add(munger); } // ---- only for testing! public ResolvedMember[] getDeclaredJavaFields() { return filterInJavaVisible(getDeclaredFields()); } public ResolvedMember[] getDeclaredJavaMethods() { return filterInJavaVisible(getDeclaredMethods()); } public ShadowMunger[] getDeclaredShadowMungersArray() { List l = (List) getDeclaredShadowMungers(); return (ShadowMunger[]) l.toArray(new ShadowMunger[l.size()]); } private ResolvedMember[] filterInJavaVisible(ResolvedMember[] ms) { List l = new ArrayList(); for (int i=0, len = ms.length; i < len; i++) { if (! ms[i].isAjSynthetic() && ms[i].getAssociatedShadowMunger() == null) { l.add(ms[i]); } } return (ResolvedMember[]) l.toArray(new ResolvedMember[l.size()]); } public abstract ISourceContext getSourceContext(); // ---- fields public static final ResolvedTypeX[] NONE = new ResolvedTypeX[0]; public static final Primitive BYTE = new Primitive("B", 1, 0); public static final Primitive CHAR = new Primitive("C", 1, 1); public static final Primitive DOUBLE = new Primitive("D", 2, 2); public static final Primitive FLOAT = new Primitive("F", 1, 3); public static final Primitive INT = new Primitive("I", 1, 4); public static final Primitive LONG = new Primitive("J", 2, 5); public static final Primitive SHORT = new Primitive("S", 1, 6); public static final Primitive VOID = new Primitive("V", 0, 8); public static final Primitive BOOLEAN = new Primitive("Z", 1, 7); public static final Missing MISSING = new Missing(); // ---- types public static class Name extends ResolvedTypeX { private ConcreteName delegate = null; private ISourceContext sourceContext = null; private int startPos = 0; private int endPos = 0; //??? should set delegate before any use public Name(String signature, World world) { super(signature, world); } public final boolean isClass() { return delegate.isClass(); } public boolean isAspect() { return delegate.isAspect(); } public final boolean needsNoConversionFrom(TypeX o) { return isAssignableFrom(o); } public final boolean isAssignableFrom(TypeX o) { if (o.isPrimitive()) return false; ResolvedTypeX other = o.resolve(world); return isAssignableFrom(other); } public final boolean isCoerceableFrom(TypeX o) { ResolvedTypeX other = o.resolve(world); if (this.isAssignableFrom(other) || other.isAssignableFrom(this)) { return true; } 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 = ((Name)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 boolean isAssignableFrom(ResolvedTypeX other) { if (this == other) return true; for(Iterator i = other.getDirectSupertypes(); i.hasNext(); ) { if (this.isAssignableFrom((ResolvedTypeX) i.next())) return true; } return false; } public ISourceContext getSourceContext() { return sourceContext; } public ISourceLocation getSourceLocation() { if (sourceContext == null) return null; return sourceContext.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() { return delegate.getDeclaredFields(); } public ResolvedTypeX[] getDeclaredInterfaces() { return delegate.getDeclaredInterfaces(); } public ResolvedMember[] getDeclaredMethods() { return delegate.getDeclaredMethods(); } public ResolvedMember[] getDeclaredPointcuts() { return delegate.getDeclaredPointcuts(); } public PerClause getPerClause() { return delegate.getPerClause(); } protected Collection getDeclares() { return delegate.getDeclares(); } protected Collection getTypeMungers() { return delegate.getTypeMungers(); } protected Collection getPrivilegedAccesses() { return delegate.getPrivilegedAccesses(); } public int getModifiers() { return delegate.getModifiers(); } public ResolvedTypeX getSuperclass() { return delegate.getSuperclass(); } public ConcreteName getDelegate() { return delegate; } public void setDelegate(ConcreteName delegate) { this.delegate = delegate; } public int getEndPos() { return endPos; } public int getStartPos() { return startPos; } public void setEndPos(int endPos) { this.endPos = endPos; } public void setSourceContext(ISourceContext sourceContext) { this.sourceContext = sourceContext; } public void setStartPos(int startPos) { this.startPos = startPos; } public boolean doesNotExposeShadowMungers() { return delegate.doesNotExposeShadowMungers(); } } public static abstract class ConcreteName { //protected ISourceContext sourceContext; protected boolean exposedToWeaver; protected ResolvedTypeX.Name resolvedTypeX; public ConcreteName(ResolvedTypeX.Name resolvedTypeX, boolean exposedToWeaver) { //???super(signature, world); this.resolvedTypeX = resolvedTypeX; this.exposedToWeaver = exposedToWeaver; } public final boolean isClass() { return !isAspect() && !isInterface(); } public abstract boolean isAspect(); public abstract boolean isInterface(); public abstract ResolvedMember[] getDeclaredFields(); public abstract ResolvedTypeX[] getDeclaredInterfaces(); public abstract ResolvedMember[] getDeclaredMethods(); public abstract ResolvedMember[] getDeclaredPointcuts(); public abstract PerClause getPerClause(); protected abstract Collection getDeclares() ; protected abstract Collection getTypeMungers(); protected abstract Collection getPrivilegedAccesses(); public abstract int getModifiers(); public abstract ResolvedTypeX getSuperclass(); // public abstract ISourceLocation getSourceLocation(); public abstract WeaverStateInfo getWeaverState(); // public ISourceContext getSourceContext() { // return sourceContext; // } /** * Designed to be overriden by EclipseType to disable collection of shadow mungers * during pre-weave compilation phase */ public boolean doesNotExposeShadowMungers() { return false; } public boolean isExposedToWeaver() { return exposedToWeaver; } public ResolvedTypeX.Name getResolvedTypeX() { return resolvedTypeX; } } static class Array extends ResolvedTypeX { ResolvedTypeX componentType; Array(String s, World world, ResolvedTypeX componentType) { super(s, world); this.componentType = componentType; } public final ResolvedMember[] getDeclaredFields() { return ResolvedMember.NONE; } public final ResolvedMember[] getDeclaredMethods() { // ??? should this return clone? Probably not... return ResolvedMember.NONE; } public final ResolvedTypeX[] getDeclaredInterfaces() { return new ResolvedTypeX[] { world.resolve(CLONEABLE), world.resolve(SERIALIZABLE) }; } public final ResolvedMember[] getDeclaredPointcuts() { return ResolvedMember.NONE; } public final ResolvedTypeX getSuperclass() { return world.resolve(OBJECT); } public final boolean isAssignableFrom(TypeX o) { if (! o.isArray()) return false; if (o.getComponentType().isPrimitive()) { return o.equals(this); } else { return getComponentType().isAssignableFrom(o.getComponentType(), world); } } public final boolean isCoerceableFrom(TypeX o) { if (o.equals(TypeX.OBJECT) || o.equals(TypeX.SERIALIZABLE) || o.equals(TypeX.CLONEABLE)) { return true; } if (! o.isArray()) return false; if (o.getComponentType().isPrimitive()) { return o.equals(this); } else { return getComponentType().isCoerceableFrom(o.getComponentType(), world); } } public final boolean needsNoConversionFrom(TypeX o) { return isAssignableFrom(o); } public final int getModifiers() { int mask = Modifier.PUBLIC | Modifier.PRIVATE | Modifier.PROTECTED; return (componentType.getModifiers() & mask) | Modifier.FINAL; } public TypeX getComponentType() { return componentType; } public ResolvedTypeX getResolvedComponentType() { return componentType; } public ISourceContext getSourceContext() { return getResolvedComponentType().getSourceContext(); } } static class Primitive extends ResolvedTypeX { private int size; private int index; Primitive(String signature, int size, int index) { super(signature, null); this.size = size; this.index = index; } public final int getSize() { return size; } public final int getModifiers() { return Modifier.PUBLIC | Modifier.FINAL; } public final boolean isPrimitive() { return true; } public final boolean isAssignableFrom(TypeX other) { if (! other.isPrimitive()) return false; return assignTable[((Primitive)other).index][index]; } public final boolean isCoerceableFrom(TypeX other) { if (this == other) return true; if (! other.isPrimitive()) return false; if (index > 6 || ((Primitive)other).index > 6) return false; return true; } public final boolean needsNoConversionFrom(TypeX other) { if (! other.isPrimitive()) return false; return noConvertTable[((Primitive)other).index][index]; } private static final boolean[][] assignTable = {// to: B C D F I J S V Z from { true , true , true , true , true , true , true , false, false }, // B { false, true , true , true , true , true , false, false, false }, // C { false, false, true , false, false, false, false, false, false }, // D { false, false, true , true , false, false, false, false, false }, // F { false, false, true , true , true , true , false, false, false }, // I { false, false, true , true , false, true , false, false, false }, // J { false, false, true , true , true , true , true , false, false }, // S { false, false, false, false, false, false, false, true , false }, // V { false, false, false, false, false, false, false, false, true }, // Z }; private static final boolean[][] noConvertTable = {// to: B C D F I J S V Z from { true , true , false, false, true , false, true , false, false }, // B { false, true , false, false, true , false, false, false, false }, // C { false, false, true , false, false, false, false, false, false }, // D { false, false, false, true , false, false, false, false, false }, // F { false, false, false, false, true , false, false, false, false }, // I { false, false, false, false, false, true , false, false, false }, // J { false, false, false, false, true , false, true , false, false }, // S { false, false, false, false, false, false, false, true , false }, // V { false, false, false, false, false, false, false, false, true }, // Z }; // ---- public final ResolvedMember[] getDeclaredFields() { return ResolvedMember.NONE; } public final ResolvedMember[] getDeclaredMethods() { return ResolvedMember.NONE; } public final ResolvedTypeX[] getDeclaredInterfaces() { return ResolvedTypeX.NONE; } public final ResolvedMember[] getDeclaredPointcuts() { return ResolvedMember.NONE; } public final ResolvedTypeX getSuperclass() { return null; } public ISourceContext getSourceContext() { return null; } } static class Missing extends ResolvedTypeX { Missing() { super(MISSING_NAME, null); } // public final String toString() { // return "<missing>"; // } public final String getName() { return MISSING_NAME; } public final ResolvedMember[] getDeclaredFields() { return ResolvedMember.NONE; } public final ResolvedMember[] getDeclaredMethods() { return ResolvedMember.NONE; } public final ResolvedTypeX[] getDeclaredInterfaces() { return ResolvedTypeX.NONE; } public final ResolvedMember[] getDeclaredPointcuts() { return ResolvedMember.NONE; } public final ResolvedTypeX getSuperclass() { return null; } public final int getModifiers() { return 0; } public final boolean isAssignableFrom(TypeX other) { return false; } public final boolean isCoerceableFrom(TypeX other) { return false; } public boolean needsNoConversionFrom(TypeX other) { return false; } public ISourceContext getSourceContext() { return null; } } /** return null if not found */ public ResolvedMember lookupMemberNoSupers(Member member) { ResolvedMember ret; if (member.getKind() == Member.FIELD) { ret = lookupMember(member, getDeclaredFields()); } else { // assert member.getKind() == Member.METHOD || member.getKind() == Member.CONSTRUCTOR ret = lookupMember(member, getDeclaredMethods()); } if (ret == null && interTypeMungers != null) { for (Iterator i = interTypeMungers.iterator(); i.hasNext();) { ConcreteTypeMunger tm = (ConcreteTypeMunger) i.next(); if (matches(tm.getSignature(), member)) { return tm.getSignature(); } } } return ret; } protected List interTypeMungers = new ArrayList(0); public List getInterTypeMungers() { return interTypeMungers; } /** * ??? This method is O(N*M) where N = number of methods and M is number of * inter-type declarations in my super */ public List getInterTypeMungersIncludingSupers() { ArrayList ret = new ArrayList(); collectInterTypeMungers(ret); return ret; } private void collectInterTypeMungers(List collector) { for (Iterator iter = getDirectSupertypes(); iter.hasNext();) { ResolvedTypeX superType = (ResolvedTypeX) iter.next(); superType.collectInterTypeMungers(collector); } outer: for (Iterator iter1 = collector.iterator(); iter1.hasNext(); ) { ConcreteTypeMunger superMunger = (ConcreteTypeMunger) iter1.next(); if ( superMunger.getSignature() == null) continue; if ( !superMunger.getSignature().isAbstract()) continue; for (Iterator iter = getInterTypeMungers().iterator(); iter.hasNext();) { ConcreteTypeMunger myMunger = (ConcreteTypeMunger) iter.next(); if (conflictingSignature(myMunger.getSignature(), superMunger.getSignature())) { iter1.remove(); continue outer; } } if (!superMunger.getSignature().isPublic()) continue; for (Iterator iter = getMethods(); iter.hasNext(); ) { ResolvedMember method = (ResolvedMember)iter.next(); if (conflictingSignature(method, superMunger.getSignature())) { iter1.remove(); continue outer; } } } collector.addAll(getInterTypeMungers()); } /** * Check that we don't have any abstract type mungers unless this * type is abstract. */ public void checkInterTypeMungers() { if (isAbstract()) return; for (Iterator iter = getInterTypeMungersIncludingSupers().iterator(); iter.hasNext();) { ConcreteTypeMunger element = (ConcreteTypeMunger) iter.next(); if (element.getSignature() != null && element.getSignature().isAbstract()) { ISourceLocation xtraLocation = element.getSourceLocation(); if (xtraLocation == null) { // Until intertype mungers remember where they came from, the source location // for the element is null when binary weaving. In these cases uses the // source location for the aspect containing the ITD xtraLocation = element.getAspectType().getSourceLocation(); } world.getMessageHandler().handleMessage( new Message("must implement abstract inter-type declaration: " + element.getSignature(), "", IMessage.ERROR, getSourceLocation(), null, new ISourceLocation[] { xtraLocation })); } } } /** * Returns a ResolvedTypeX object representing the declaring type of this type, or * null if this type does not represent a non-package-level-type. * * <strong>Warning</strong>: This is guaranteed to work for all member types. * For anonymous/local types, the only guarantee is given in JLS 13.1, where * it guarantees that if you call getDeclaringType() repeatedly, you will eventually * get the top-level class, but it does not say anything about classes in between. * * @return the declaring TypeX object, or null. */ public ResolvedTypeX getDeclaringType() { if (isArray()) return null; String name = getName(); int lastDollar = name.lastIndexOf('$'); while (lastDollar != -1) { ResolvedTypeX ret = world.resolve(TypeX.forName(name.substring(0, lastDollar)), true); if (ret != ResolvedTypeX.MISSING) return ret; lastDollar = name.lastIndexOf('$', lastDollar-1); } return null; } public static boolean isVisible(int modifiers, ResolvedTypeX targetType, ResolvedTypeX fromType) { //System.err.println("mod: " + modifiers + ", " + targetType + " and " + fromType); if (Modifier.isPublic(modifiers)) { return true; } else if (Modifier.isPrivate(modifiers)) { return targetType.getOutermostType().equals(fromType.getOutermostType()); } else if (Modifier.isProtected(modifiers)) { return samePackage(targetType, fromType) || targetType.isAssignableFrom(fromType); } else { // package-visible return samePackage(targetType, fromType); } } private static boolean samePackage( ResolvedTypeX targetType, ResolvedTypeX fromType) { String p1 = targetType.getPackageName(); String p2 = fromType.getPackageName(); if (p1 == null) return p2 == null; if (p2 == null) return false; return p1.equals(p2); } public void addInterTypeMunger(ConcreteTypeMunger munger) { ResolvedMember sig = munger.getSignature(); if (sig == null || munger.getMunger() == null || munger.getMunger().getKind() == ResolvedTypeMunger.PrivilegedAccess) { interTypeMungers.add(munger); return; } //System.err.println("add: " + munger + " to " + this.getClassName() + " with " + interTypeMungers); if (sig.getKind() == Member.METHOD) { if (!compareToExistingMembers(munger, getMethods())) return; if (this.isInterface()) { if (!compareToExistingMembers(munger, Arrays.asList(world.resolve(OBJECT).getDeclaredMethods()).iterator())) return; } } else if (sig.getKind() == Member.FIELD) { if (!compareToExistingMembers(munger, Arrays.asList(getDeclaredFields()).iterator())) return; } else { if (!compareToExistingMembers(munger, Arrays.asList(getDeclaredMethods()).iterator())) return; } // now compare to existingMungers for (Iterator i = interTypeMungers.iterator(); i.hasNext(); ) { ConcreteTypeMunger existingMunger = (ConcreteTypeMunger)i.next(); if (conflictingSignature(existingMunger.getSignature(), munger.getSignature())) { //System.err.println("match " + munger + " with " + existingMunger); if (isVisible(munger.getSignature().getModifiers(), munger.getAspectType(), existingMunger.getAspectType())) { //System.err.println(" is visible"); int c = compareMemberPrecedence(sig, existingMunger.getSignature()); if (c == 0) { c = getWorld().comparePrecedence(munger.getAspectType(), existingMunger.getAspectType()); } //System.err.println(" compare: " + c); if (c < 0) { // the existing munger dominates the new munger checkLegalOverride(munger.getSignature(), existingMunger.getSignature()); return; } else if (c > 0) { // the new munger dominates the existing one checkLegalOverride(existingMunger.getSignature(), munger.getSignature()); i.remove(); break; } else { interTypeConflictError(munger, existingMunger); interTypeConflictError(existingMunger, munger); return; } } } } //System.err.println("adding: " + munger + " to " + this); interTypeMungers.add(munger); } //??? returning too soon private boolean compareToExistingMembers(ConcreteTypeMunger munger, Iterator existingMembers) { ResolvedMember sig = munger.getSignature(); while (existingMembers.hasNext()) { ResolvedMember existingMember = (ResolvedMember)existingMembers.next(); //System.err.println("Comparing munger: "+sig+" with member "+existingMember); if (conflictingSignature(existingMember, munger.getSignature())) { //System.err.println("conflict: existingMember=" + existingMember + " typeMunger=" + munger); //System.err.println(munger.getSourceLocation() + ", " + munger.getSignature() + ", " + munger.getSignature().getSourceLocation()); if (isVisible(existingMember.getModifiers(), this, munger.getAspectType())) { int c = compareMemberPrecedence(sig, existingMember); //System.err.println(" c: " + c); if (c < 0) { // existingMember dominates munger checkLegalOverride(munger.getSignature(), existingMember); return false; } else if (c > 0) { // munger dominates existingMember checkLegalOverride(existingMember, munger.getSignature()); //interTypeMungers.add(munger); //??? might need list of these overridden abstracts continue; } else { //XXX dual errors possible if (this instanceof BcelObjectType) return false; //XXX ignores separate comp getWorld().getMessageHandler().handleMessage( MessageUtil.error("inter-type declaration from " + munger.getAspectType().getName() + " conflicts with existing member: " + existingMember, munger.getSourceLocation()) ); } } else { //interTypeMungers.add(munger); } //return; } } return true; } public boolean checkLegalOverride(ResolvedMember parent, ResolvedMember child) { //System.err.println("check: " + child.getDeclaringType() + " overrides " + parent.getDeclaringType()); if (!parent.getReturnType().equals(child.getReturnType())) { world.showMessage(IMessage.ERROR, "can't override " + parent + " with " + child + " return types don't match", child.getSourceLocation(), parent.getSourceLocation()); return false; } if (parent.getKind() == Member.POINTCUT) { TypeX[] pTypes = parent.getParameterTypes(); TypeX[] cTypes = child.getParameterTypes(); if (!Arrays.equals(pTypes, cTypes)) { world.showMessage(IMessage.ERROR, "can't override " + parent + " with " + child + " parameter types don't match", child.getSourceLocation(), parent.getSourceLocation()); return false; } } //System.err.println("check: " + child.getModifiers() + " more visible " + parent.getModifiers()); if (isMoreVisible(parent.getModifiers(), child.getModifiers())) { world.showMessage(IMessage.ERROR, "can't override " + parent + " with " + child + " visibility is reduced", child.getSourceLocation(), parent.getSourceLocation()); return false; } // check declared exceptions ResolvedTypeX[] childExceptions = world.resolve(child.getExceptions()); ResolvedTypeX[] parentExceptions = world.resolve(parent.getExceptions()); ResolvedTypeX runtimeException = world.resolve("java.lang.RuntimeException"); ResolvedTypeX error = world.resolve("java.lang.Error"); outer: for (int i=0, leni = childExceptions.length; i < leni; i++) { //System.err.println("checking: " + childExceptions[i]); if (runtimeException.isAssignableFrom(childExceptions[i])) continue; if (error.isAssignableFrom(childExceptions[i])) continue; for (int j = 0, lenj = parentExceptions.length; j < lenj; j++) { if (parentExceptions[j].isAssignableFrom(childExceptions[i])) continue outer; } world.showMessage(IMessage.ERROR, "overriden method doesn't throw " + childExceptions[i].getName(), child.getSourceLocation(), null); return false; } if (parent.isStatic() && !child.isStatic()) { world.showMessage(IMessage.ERROR, child.toString()+" cannot override "+parent.toString()+"; overridden method is static", child.getSourceLocation(),null); } else if (child.isStatic() && !parent.isStatic()) { world.showMessage(IMessage.ERROR, child.toString()+" cannot override "+parent.toString()+"; overriding method is static", child.getSourceLocation(),null); } return true; } private int compareMemberPrecedence(ResolvedMember m1, ResolvedMember m2) { //if (!m1.getReturnType().equals(m2.getReturnType())) return 0; if (Modifier.isAbstract(m1.getModifiers())) return -1; if (Modifier.isAbstract(m2.getModifiers())) return +1; if (m1.getDeclaringType().equals(m2.getDeclaringType())) return 0; ResolvedTypeX t1 = m1.getDeclaringType().resolve(world); ResolvedTypeX t2 = m2.getDeclaringType().resolve(world); if (t1.isAssignableFrom(t2)) { return -1; } if (t2.isAssignableFrom(t1)) { return +1; } return 0; } public static boolean isMoreVisible(int m1, int m2) { if (Modifier.isPrivate(m1)) return false; if (isPackage(m1)) return Modifier.isPrivate(m2); if (Modifier.isProtected(m1)) return /* private package */ (Modifier.isPrivate(m2) || isPackage(m2)); if (Modifier.isPublic(m1)) return /* private package protected */ ! Modifier.isPublic(m2); throw new RuntimeException("bad modifier: " + m1); } private static boolean isPackage(int i) { return (0 == (i & (Modifier.PUBLIC | Modifier.PRIVATE | Modifier.PROTECTED))); } private void interTypeConflictError( ConcreteTypeMunger m1, ConcreteTypeMunger m2) { //XXX this works only if we ignore separate compilation issues //XXX dual errors possible if (this instanceof BcelObjectType) return; //System.err.println("conflict at " + m2.getSourceLocation()); getWorld().showMessage(IMessage.ERROR, "intertype declaration from " + m1.getAspectType().getName() + " conflicts with intertype declaration: " + m2.getSignature() + " from " + m2.getAspectType().getName(), m2.getSourceLocation(), getSourceLocation()); } public ResolvedMember lookupSyntheticMember(Member member) { //??? horribly inefficient //for (Iterator i = //System.err.println("lookup " + member + " in " + interTypeMungers); for (Iterator i = interTypeMungers.iterator(); i.hasNext(); ) { ConcreteTypeMunger m = (ConcreteTypeMunger)i.next(); ResolvedMember ret = m.getMatchingSyntheticMember(member); if (ret != null) { //System.err.println(" found: " + ret); return ret; } } return null; } public void clearInterTypeMungers() { interTypeMungers = new ArrayList(); } public boolean isTopmostImplementor(ResolvedTypeX interfaceType) { if (isInterface()) return false; if (!interfaceType.isAssignableFrom(this)) return false; // check that I'm truly the topmost implementor if (interfaceType.isAssignableFrom(this.getSuperclass())) { return false; } return true; } public List getExposedPointcuts() { List ret = new ArrayList(); if (getSuperclass() != null) ret.addAll(getSuperclass().getExposedPointcuts()); for (Iterator i = Arrays.asList(getDeclaredInterfaces()).iterator(); i.hasNext(); ) { ResolvedTypeX t = (ResolvedTypeX)i.next(); addPointcutsResolvingConflicts(ret, Arrays.asList(t.getDeclaredPointcuts()), false); } addPointcutsResolvingConflicts(ret, Arrays.asList(getDeclaredPointcuts()), true); for (Iterator i = ret.iterator(); i.hasNext(); ) { ResolvedPointcutDefinition inherited = (ResolvedPointcutDefinition)i.next(); // System.err.println("looking at: " + inherited + " in " + this); // System.err.println(" " + inherited.isAbstract() + " in " + this.isAbstract()); if (inherited.isAbstract()) { if (!this.isAbstract()) { getWorld().showMessage(IMessage.ERROR, "inherited abstract " + inherited + " is not made concrete in " + this.getName(), inherited.getSourceLocation(), this.getSourceLocation()); } } } return ret; } private void addPointcutsResolvingConflicts(List acc, List added, boolean isOverriding) { for (Iterator i = added.iterator(); i.hasNext();) { ResolvedPointcutDefinition toAdd = (ResolvedPointcutDefinition) i.next(); //System.err.println("adding: " + toAdd); for (Iterator j = acc.iterator(); j.hasNext();) { ResolvedPointcutDefinition existing = (ResolvedPointcutDefinition) j.next(); if (existing == toAdd) continue; if (!isVisible(existing.getModifiers(), existing.getDeclaringType().resolve(getWorld()), this)) { continue; } if (conflictingSignature(existing, toAdd)) { if (isOverriding) { checkLegalOverride(existing, toAdd); j.remove(); } else { getWorld().showMessage( IMessage.ERROR, "conflicting inherited pointcuts in " + this.getName() + toAdd.getSignature(), existing.getSourceLocation(), toAdd.getSourceLocation()); j.remove(); } } } acc.add(toAdd); } } public ISourceLocation getSourceLocation() { return null; } public boolean isExposedToWeaver() { return false; } public WeaverStateInfo getWeaverState() { return null; } }
30,439
Bug 30439 spurious "circular dependency" error
AspectJ Compiler 1.1beta4 This program: aspect Foo { pointcut p1(): execution(void f()) && cflow(execution(void f1())); pointcut p2(): execution(void f()) && cflow(execution(void f2())); before(): p1() { } after(): p1() { } before(): p2() { } after(): p2() { } } class A { void f1() { f(); } void f2() { f(); } void f() { } } results in these errors: circular dependency at method-execution(void A.f()) circular dependency at method-execution(void A.f()) circular dependency at method-execution(void A.f()) circular dependency at method-execution(void A.f()) 4 errors If I comment out any one of the four pieces of advice, all the errors go away. Also, assuming that there is a valid reason for printing this error sometimes, how come there's no line number? --Doug
resolved fixed
4feb835
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2004-07-29T15:04:00Z
2003-01-28T21:40:00Z
weaver/src/org/aspectj/weaver/Shadow.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Common Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * PARC initial implementation * ******************************************************************/ package org.aspectj.weaver; import java.io.DataInputStream; import java.io.IOException; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.aspectj.asm.IRelationship; import org.aspectj.bridge.*; import org.aspectj.bridge.MessageUtil; import org.aspectj.lang.JoinPoint; import org.aspectj.util.PartialOrder; import org.aspectj.util.TypeSafeEnum; import org.aspectj.weaver.ast.Var; /* * The superclass of anything representing a the shadow of a join point. A shadow represents * some bit of code, and encompasses both entry and exit from that code. All shadows have a kind * and a signature. */ public abstract class Shadow { private final Kind kind; private final Member signature; protected final Shadow enclosingShadow; protected List mungers = new ArrayList(1); // ---- protected Shadow(Kind kind, Member signature, Shadow enclosingShadow) { this.kind = kind; this.signature = signature; this.enclosingShadow = enclosingShadow; } // ---- public abstract World getIWorld(); public List /*ShadowMunger*/ getMungers() { return mungers; } /** * could this(*) pcd ever match */ public final boolean hasThis() { if (getKind().neverHasThis()) { return false; } else if (getKind().isEnclosingKind()) { return !getSignature().isStatic(); } else if (enclosingShadow == null) { return false; } else { return enclosingShadow.hasThis(); } } /** * the type of the this object here * * @throws IllegalStateException if there is no this here */ public final TypeX getThisType() { if (!hasThis()) throw new IllegalStateException("no this"); if (getKind().isEnclosingKind()) { return getSignature().getDeclaringType(); } else { return enclosingShadow.getThisType(); } } /** * a var referencing this * * @throws IllegalStateException if there is no target here */ public abstract Var getThisVar(); /** * could target(*) pcd ever match */ public final boolean hasTarget() { if (getKind().neverHasTarget()) { return false; } else if (getKind().isTargetSameAsThis()) { return hasThis(); } else { return !getSignature().isStatic(); } } /** * the type of the target object here * * @throws IllegalStateException if there is no target here */ public final TypeX getTargetType() { if (!hasTarget()) throw new IllegalStateException("no target"); return getSignature().getDeclaringType(); } /** * a var referencing the target * * @throws IllegalStateException if there is no target here */ public abstract Var getTargetVar(); public TypeX[] getArgTypes() { if (getKind() == FieldSet) return new TypeX[] { getSignature().getReturnType() }; return getSignature().getParameterTypes(); } public TypeX getArgType(int arg) { if (getKind() == FieldSet) return getSignature().getReturnType(); return getSignature().getParameterTypes()[arg]; } public int getArgCount() { if (getKind() == FieldSet) return 1; return getSignature() .getParameterTypes().length; } public abstract TypeX getEnclosingType(); public abstract Var getArgVar(int i); public abstract Var getThisJoinPointVar(); public abstract Var getThisJoinPointStaticPartVar(); public abstract Var getThisEnclosingJoinPointStaticPartVar(); public abstract Member getEnclosingCodeSignature(); /** returns the kind of shadow this is, representing what happens under this shadow */ public Kind getKind() { return kind; } /** returns the signature of the thing under this shadow */ public Member getSignature() { return signature; } public TypeX getReturnType() { if (kind == ConstructorCall) return getSignature().getDeclaringType(); else if (kind == FieldSet) return ResolvedTypeX.VOID; return getSignature().getReturnType(); } /** * These names are the ones that will be returned by thisJoinPoint.getKind() * Those need to be documented somewhere */ public static final Kind MethodCall = new Kind(JoinPoint.METHOD_CALL, 1, true); public static final Kind ConstructorCall = new Kind(JoinPoint.CONSTRUCTOR_CALL, 2, true); public static final Kind MethodExecution = new Kind(JoinPoint.METHOD_EXECUTION, 3, false); public static final Kind ConstructorExecution = new Kind(JoinPoint.CONSTRUCTOR_EXECUTION, 4, false); public static final Kind FieldGet = new Kind(JoinPoint.FIELD_GET, 5, true); public static final Kind FieldSet = new Kind(JoinPoint.FIELD_SET, 6, true); public static final Kind StaticInitialization = new Kind(JoinPoint.STATICINITIALIZATION, 7, false); public static final Kind PreInitialization = new Kind(JoinPoint.PREINTIALIZATION, 8, false); public static final Kind AdviceExecution = new Kind(JoinPoint.ADVICE_EXECUTION, 9, false); public static final Kind Initialization = new Kind(JoinPoint.INITIALIZATION, 10, false); public static final Kind ExceptionHandler = new Kind(JoinPoint.EXCEPTION_HANDLER, 11, true); public static final int MAX_SHADOW_KIND = 11; public static final Kind[] SHADOW_KINDS = new Kind[] { MethodCall, ConstructorCall, MethodExecution, ConstructorExecution, FieldGet, FieldSet, StaticInitialization, PreInitialization, AdviceExecution, Initialization, ExceptionHandler, }; /** A type-safe enum representing the kind of shadows */ public static final class Kind extends TypeSafeEnum { private boolean argsOnStack; //XXX unused public Kind(String name, int key, boolean argsOnStack) { super(name, key); this.argsOnStack = argsOnStack; } public String toLegalJavaIdentifier() { return getName().replace('-', '_'); } public boolean argsOnStack() { return !isTargetSameAsThis(); } // !!! this is false for handlers! public boolean allowsExtraction() { return true; } // XXX revisit along with removal of priorities public boolean hasHighPriorityExceptions() { return !isTargetSameAsThis(); } /** * These are all the shadows that contains other shadows within them and * are often directly associated with methods. */ public boolean isEnclosingKind() { return this == MethodExecution || this == ConstructorExecution || this == AdviceExecution || this == StaticInitialization || this == Initialization; } public boolean isTargetSameAsThis() { return this == MethodExecution || this == ConstructorExecution || this == StaticInitialization || this == PreInitialization || this == AdviceExecution || this == Initialization; } public boolean neverHasTarget() { return this == ConstructorCall || this == ExceptionHandler || this == PreInitialization || this == StaticInitialization; } public boolean neverHasThis() { return this == PreInitialization || this == StaticInitialization; } public String getSimpleName() { int dash = getName().lastIndexOf('-'); if (dash == -1) return getName(); else return getName().substring(dash+1); } public static Kind read(DataInputStream s) throws IOException { int key = s.readByte(); switch(key) { case 1: return MethodCall; case 2: return ConstructorCall; case 3: return MethodExecution; case 4: return ConstructorExecution; case 5: return FieldGet; case 6: return FieldSet; case 7: return StaticInitialization; case 8: return PreInitialization; case 9: return AdviceExecution; case 10: return Initialization; case 11: return ExceptionHandler; } throw new BCException("unknown kind: " + key); } } protected boolean checkMunger(ShadowMunger munger) { for (Iterator i = munger.getThrownExceptions().iterator(); i.hasNext(); ) { if (!checkCanThrow(munger, (ResolvedTypeX)i.next() )) return false; } return true; } protected boolean checkCanThrow(ShadowMunger munger, ResolvedTypeX resolvedTypeX) { if (getKind() == ExceptionHandler) { //XXX much too lenient rules here, need to walk up exception handlers return true; } if (!isDeclaredException(resolvedTypeX, getSignature())) { getIWorld().showMessage(IMessage.ERROR, "can't throw checked exception \'" + resolvedTypeX + "\' at this join point \'" + this +"\'", // from advice in \'" + munger. + "\'", getSourceLocation(), munger.getSourceLocation()); } return true; } private boolean isDeclaredException( ResolvedTypeX resolvedTypeX, Member member) { ResolvedTypeX[] excs = getIWorld().resolve(member.getExceptions(getIWorld())); for (int i=0, len=excs.length; i < len; i++) { if (excs[i].isAssignableFrom(resolvedTypeX)) return true; } return false; } public void addMunger(ShadowMunger munger) { if (checkMunger(munger)) this.mungers.add(munger); } public final void implement() { sortMungers(); if (mungers == null) return; prepareForMungers(); implementMungers(); } private void sortMungers() { List sorted = PartialOrder.sort(mungers); if (sorted == null) { // this means that we have circular dependencies for (Iterator i = mungers.iterator(); i.hasNext(); ) { ShadowMunger m = (ShadowMunger)i.next(); getIWorld().getMessageHandler().handleMessage( MessageUtil.error("circular advice dependency at " + this, m.getSourceLocation())); } } mungers = sorted; } /** Prepare the shadow for implementation. After this is done, the shadow * should be in such a position that each munger simply needs to be implemented. */ protected void prepareForMungers() { throw new RuntimeException("Generic shadows cannot be prepared"); } /** Actually implement the (non-empty) mungers associated with this shadow */ private void implementMungers() { World world = getIWorld(); for (Iterator iter = mungers.iterator(); iter.hasNext();) { ShadowMunger munger = (ShadowMunger) iter.next(); munger.implementOn(this); if (world.xrefHandler != null) { world.xrefHandler.addCrossReference(munger.getSourceLocation(),this.getSourceLocation(),IRelationship.Kind.ADVICE); } if (world.getModel() != null) { //System.err.println("munger: " + munger + " on " + this); AsmRelationshipProvider.adviceMunger(world.getModel(), this, munger); } } } public String makeReflectiveFactoryString() { return null; //XXX } public abstract ISourceLocation getSourceLocation(); // ---- utility public String toString() { return getKind() + "(" + getSignature() + ")"; // + getSourceLines(); } }
30,439
Bug 30439 spurious "circular dependency" error
AspectJ Compiler 1.1beta4 This program: aspect Foo { pointcut p1(): execution(void f()) && cflow(execution(void f1())); pointcut p2(): execution(void f()) && cflow(execution(void f2())); before(): p1() { } after(): p1() { } before(): p2() { } after(): p2() { } } class A { void f1() { f(); } void f2() { f(); } void f() { } } results in these errors: circular dependency at method-execution(void A.f()) circular dependency at method-execution(void A.f()) circular dependency at method-execution(void A.f()) circular dependency at method-execution(void A.f()) 4 errors If I comment out any one of the four pieces of advice, all the errors go away. Also, assuming that there is a valid reason for printing this error sometimes, how come there's no line number? --Doug
resolved fixed
4feb835
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2004-07-29T15:04:00Z
2003-01-28T21:40:00Z
weaver/src/org/aspectj/weaver/WeaverMessages.java
30,439
Bug 30439 spurious "circular dependency" error
AspectJ Compiler 1.1beta4 This program: aspect Foo { pointcut p1(): execution(void f()) && cflow(execution(void f1())); pointcut p2(): execution(void f()) && cflow(execution(void f2())); before(): p1() { } after(): p1() { } before(): p2() { } after(): p2() { } } class A { void f1() { f(); } void f2() { f(); } void f() { } } results in these errors: circular dependency at method-execution(void A.f()) circular dependency at method-execution(void A.f()) circular dependency at method-execution(void A.f()) circular dependency at method-execution(void A.f()) 4 errors If I comment out any one of the four pieces of advice, all the errors go away. Also, assuming that there is a valid reason for printing this error sometimes, how come there's no line number? --Doug
resolved fixed
4feb835
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2004-07-29T15:04:00Z
2003-01-28T21:40:00Z
weaver/src/org/aspectj/weaver/WeaverStateInfo.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Common Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * PARC initial implementation * ******************************************************************/ package org.aspectj.weaver; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Set; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; import java.util.zip.ZipOutputStream; import org.aspectj.bridge.IMessage; import org.aspectj.weaver.bcel.BcelTypeMunger; /** * WeaverStateInfo represents how a type was processed. It is used by the weaver to determine how a type * was previously treated and whether reweaving is allowed. * The format in the data stream is: * * Byte: Kind. UNTOUCHED|WOVEN|EXTENDED - If extended it can have two extra bits set 'REWEAVABLE' and 'REWEAVABLE_COMPRESSION_BIT' * Short: typeMungerCount - how many type mungers have affected this type * <TypeX & ResolvedTypeMunger>: The type mungers themselves * If we are reweavable then we also have: * Short: Number of aspects that touched this type in some way when it was previously woven * <String> The fully qualified name of each type * Int: Length of class file data (i.e. the unwovenclassfile) * Byte[]: The class file data, compressed if REWEAVABLE_COMPRESSION_BIT set. */ public class WeaverStateInfo { private List/*Entry*/ typeMungers; private boolean oldStyle; private boolean reweavable; private boolean reweavableCompressedMode; // If true, unwovenClassFile is compressed on write and uncompressed on read private Set /*String*/ aspectsAffectingType; // These must exist in the world for reweaving to be valid private byte[] unwovenClassFile; // Original 'untouched' class file private static boolean reweavableDefault = false; private static boolean reweavableCompressedModeDefault = false; public WeaverStateInfo() { this(new ArrayList(), false,reweavableDefault,reweavableCompressedModeDefault); } private WeaverStateInfo(List typeMungers, boolean oldStyle,boolean reweavableMode,boolean reweavableCompressedMode) { this.typeMungers = typeMungers; this.oldStyle = oldStyle; this.reweavable = reweavableMode; this.reweavableCompressedMode = reweavableCompressedMode; this.aspectsAffectingType= new HashSet(); this.unwovenClassFile = null; } public static void setReweavableModeDefaults(boolean mode, boolean compress) { reweavableDefault = mode; reweavableCompressedModeDefault = compress; } private static final int UNTOUCHED=0, WOVEN=2, EXTENDED=3; // Use 'bits' for these capabilities - only valid in EXTENDED mode private static final byte REWEAVABLE_BIT = 1<<4; private static final byte REWEAVABLE_COMPRESSION_BIT = 1<<5; public static final WeaverStateInfo read(DataInputStream s, ISourceContext context) throws IOException { byte b = s.readByte(); boolean isReweavable = ((b&REWEAVABLE_BIT)!=0); if (isReweavable) b=(byte) (b-REWEAVABLE_BIT); boolean isReweavableCompressed = ((b&REWEAVABLE_COMPRESSION_BIT)!=0); if (isReweavableCompressed) b=(byte) (b-REWEAVABLE_COMPRESSION_BIT); switch(b) { case UNTOUCHED: throw new RuntimeException("unexpected UNWOVEN"); case WOVEN: return new WeaverStateInfo(Collections.EMPTY_LIST, true,isReweavable,isReweavableCompressed); case EXTENDED: int n = s.readShort(); List l = new ArrayList(); for (int i=0; i < n; i++) { TypeX aspectType = TypeX.read(s); ResolvedTypeMunger typeMunger = ResolvedTypeMunger.read(s, context); l.add(new Entry(aspectType, typeMunger)); } WeaverStateInfo wsi = new WeaverStateInfo(l,false,isReweavable,isReweavableCompressed); readAnyReweavableData(wsi,s); return wsi; } throw new RuntimeException("bad WeaverState.Kind: " + b); } private static class Entry { public TypeX aspectType; public ResolvedTypeMunger typeMunger; public Entry(TypeX aspectType, ResolvedTypeMunger typeMunger) { this.aspectType = aspectType; this.typeMunger = typeMunger; } public String toString() { return "<" + aspectType + ", " + typeMunger + ">"; } } public void write(DataOutputStream s) throws IOException { if (oldStyle) throw new RuntimeException("shouldn't be writing this"); byte weaverStateInfoKind = EXTENDED; if (reweavable) weaverStateInfoKind |= REWEAVABLE_BIT; if (reweavableCompressedMode) weaverStateInfoKind |= REWEAVABLE_COMPRESSION_BIT; s.writeByte(weaverStateInfoKind); int n = typeMungers.size(); s.writeShort(n); for (int i=0; i < n; i++) { Entry e = (Entry)typeMungers.get(i); e.aspectType.write(s); e.typeMunger.write(s); } writeAnyReweavableData(this,s); } public void addConcreteMunger(ConcreteTypeMunger munger) { typeMungers.add(new Entry(munger.getAspectType(), munger.getMunger())); } public String toString() { return "WeaverStateInfo(" + typeMungers + ", " + oldStyle + ")"; } public List getTypeMungers(ResolvedTypeX onType) { World world = onType.getWorld(); List ret = new ArrayList(); for (Iterator i = typeMungers.iterator(); i.hasNext();) { Entry entry = (Entry) i.next(); ResolvedTypeX aspectType = world.resolve(entry.aspectType, true); if (aspectType == ResolvedTypeX.MISSING) { world.showMessage(IMessage.ERROR, "aspect " + entry.aspectType + " is needed when using type " + onType, onType.getSourceLocation(), null); continue; } ret.add(new BcelTypeMunger(entry.typeMunger, aspectType)); } return ret; } public boolean isOldStyle() { return oldStyle; } public byte[] getUnwovenClassFileData() { return unwovenClassFile; } public void setUnwovenClassFileData(byte[] data) { unwovenClassFile = data; } public boolean isReweavable() { return reweavable; } public void setReweavable(boolean rw,boolean compressData) { reweavable = rw; reweavableCompressedMode = compressData; } public void addAspectsAffectingType(Collection /*String*/ aspects) { aspectsAffectingType.addAll(aspects); } public void addAspectAffectingType(String aspectType) { aspectsAffectingType.add(aspectType); } public Set /*String*/ getAspectsAffectingType() { return this.aspectsAffectingType; } //// private static void readAnyReweavableData(WeaverStateInfo wsi,DataInputStream s) throws IOException { if (wsi.isReweavable()) { // Load list of aspects that need to exist in the world for reweaving to be 'legal' int numberAspectsAffectingType = s.readShort(); for (int i=0; i < numberAspectsAffectingType; i++) {wsi.addAspectAffectingType(s.readUTF());} int unwovenClassFileSize = s.readInt(); byte[] classData = null; // The data might or might not be compressed: if (!wsi.reweavableCompressedMode) { // Read it straight in classData = new byte[unwovenClassFileSize]; int bytesread = s.read(classData); if (bytesread!=unwovenClassFileSize) throw new IOException("ERROR whilst reading reweavable data, expected "+ unwovenClassFileSize+" bytes, only found "+bytesread); } else { // Decompress it classData = new byte[unwovenClassFileSize]; ZipInputStream zis = new ZipInputStream(s); ZipEntry zen = zis.getNextEntry(); int current = 0; int bytesToGo=unwovenClassFileSize; while (bytesToGo>0) { int amount = zis.read(classData,current,bytesToGo); current+=amount; bytesToGo-=amount; } zis.closeEntry(); if (bytesToGo!=0) throw new IOException("ERROR whilst reading compressed reweavable data, expected "+ unwovenClassFileSize+" bytes, only found "+current); } wsi.setUnwovenClassFileData(classData); } } private static void writeAnyReweavableData(WeaverStateInfo wsi,DataOutputStream s) throws IOException { if (wsi.isReweavable()) { // Write out list of aspects that must exist next time we try and weave this class s.writeShort(wsi.aspectsAffectingType.size()); if (wsi.aspectsAffectingType.size()>0) { for (Iterator iter = wsi.aspectsAffectingType.iterator(); iter.hasNext();) { String type = (String) iter.next(); s.writeUTF(type); } } byte[] data = wsi.unwovenClassFile; s.writeInt(data.length); // Do we need to compress the data? if (!wsi.reweavableCompressedMode) { s.write(wsi.unwovenClassFile); } else { ZipOutputStream zos = new ZipOutputStream(s); ZipEntry ze = new ZipEntry("data"); zos.putNextEntry(ze); zos.write(wsi.unwovenClassFile,0,wsi.unwovenClassFile.length); zos.closeEntry(); } } } }
30,439
Bug 30439 spurious "circular dependency" error
AspectJ Compiler 1.1beta4 This program: aspect Foo { pointcut p1(): execution(void f()) && cflow(execution(void f1())); pointcut p2(): execution(void f()) && cflow(execution(void f2())); before(): p1() { } after(): p1() { } before(): p2() { } after(): p2() { } } class A { void f1() { f(); } void f2() { f(); } void f() { } } results in these errors: circular dependency at method-execution(void A.f()) circular dependency at method-execution(void A.f()) circular dependency at method-execution(void A.f()) circular dependency at method-execution(void A.f()) 4 errors If I comment out any one of the four pieces of advice, all the errors go away. Also, assuming that there is a valid reason for printing this error sometimes, how come there's no line number? --Doug
resolved fixed
4feb835
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2004-07-29T15:04:00Z
2003-01-28T21:40:00Z
weaver/src/org/aspectj/weaver/World.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Common Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * PARC initial implementation * ******************************************************************/ package org.aspectj.weaver; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; 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.weaver.patterns.DeclarePrecedence; import org.aspectj.weaver.patterns.Pointcut; public abstract class World { protected IMessageHandler messageHandler = IMessageHandler.SYSTEM_ERR; protected ICrossReferenceHandler xrefHandler = null; protected TypeMap typeMap = new TypeMap(); // Signature to ResolvedType protected CrosscuttingMembersSet crosscuttingMembersSet = new CrosscuttingMembersSet(this); protected IHierarchy model = null; protected Lint lint = new Lint(this); protected boolean XnoInline; protected boolean XlazyTjp; protected World() { super(); typeMap.put("B", ResolvedTypeX.BYTE); typeMap.put("S", ResolvedTypeX.SHORT); typeMap.put("I", ResolvedTypeX.INT); typeMap.put("J", ResolvedTypeX.LONG); typeMap.put("F", ResolvedTypeX.FLOAT); typeMap.put("D", ResolvedTypeX.DOUBLE); typeMap.put("C", ResolvedTypeX.CHAR); typeMap.put("Z", ResolvedTypeX.BOOLEAN); typeMap.put("V", ResolvedTypeX.VOID); } public ResolvedTypeX[] resolve(TypeX[] types) { int len = types.length; ResolvedTypeX[] ret = new ResolvedTypeX[len]; for (int i=0; i<len; i++) { ret[i] = resolve(types[i]); } return ret; } public ResolvedTypeX resolve(TypeX ty) { return resolve(ty, false); } public ResolvedTypeX resolve(TypeX ty, boolean allowMissing) { //System.out.println("resolve: " + ty + " world " + typeMap.keySet()); String signature = ty.getSignature(); ResolvedTypeX ret = typeMap.get(signature); if (ret != null) return ret; if (ty.isArray()) { ret = new ResolvedTypeX.Array(signature, this, resolve(ty.getComponentType(), allowMissing)); } else { ret = resolveObjectType(ty); if (!allowMissing && ret == ResolvedTypeX.MISSING) { //Thread.currentThread().dumpStack(); MessageUtil.error(messageHandler, "can't find type " + ty.getName()); // + " on classpath " + classPath); } } //System.out.println("ret: " + ret); typeMap.put(signature, ret); return ret; } //XXX helper method might be bad public ResolvedTypeX resolve(String name) { return resolve(TypeX.forName(name)); } protected final ResolvedTypeX resolveObjectType(TypeX ty) { ResolvedTypeX.Name name = new ResolvedTypeX.Name(ty.getSignature(), this); ResolvedTypeX.ConcreteName concreteName = resolveObjectType(name); if (concreteName == null) return ResolvedTypeX.MISSING; name.setDelegate(concreteName); return name; } protected abstract ResolvedTypeX.ConcreteName resolveObjectType(ResolvedTypeX.Name ty); protected final boolean isCoerceableFrom(TypeX type, TypeX other) { return resolve(type).isCoerceableFrom(other); } protected final boolean isAssignableFrom(TypeX type, TypeX other) { return resolve(type).isAssignableFrom(other); } public boolean needsNoConversionFrom(TypeX type, TypeX other) { return resolve(type).needsNoConversionFrom(other); } protected final boolean isInterface(TypeX type) { return resolve(type).isInterface(); } protected final ResolvedTypeX getSuperclass(TypeX type) { return resolve(type).getSuperclass(); } protected final TypeX[] getDeclaredInterfaces(TypeX type) { return resolve(type).getDeclaredInterfaces(); } protected final int getModifiers(TypeX type) { return resolve(type).getModifiers(); } protected final ResolvedMember[] getDeclaredFields(TypeX type) { return resolve(type).getDeclaredFields(); } protected final ResolvedMember[] getDeclaredMethods(TypeX type) { return resolve(type).getDeclaredMethods(); } protected final ResolvedMember[] getDeclaredPointcuts(TypeX type) { return resolve(type).getDeclaredPointcuts(); } // ---- members // XXX should we worry about dealing with context and looking up access? public ResolvedMember resolve(Member member) { ResolvedTypeX declaring = member.getDeclaringType().resolve(this); 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); } protected int getModifiers(Member member) { ResolvedMember r = resolve(member); if (r == null) throw new BCException("bad resolve of " + member); return r.getModifiers(); } protected String[] getParameterNames(Member member) { return resolve(member).getParameterNames(); } protected TypeX[] getExceptions(Member member) { return resolve(member).getExceptions(); } // ---- pointcuts public ResolvedPointcutDefinition findPointcut(TypeX typeX, String name) { throw new RuntimeException("not implemented yet"); } /** * Get the shadow mungers of this world. * * @return a list of {@link IShadowMunger}s appropriate for this world. */ //public abstract List getShadowMungers(); // ---- empty world public static final World EMPTY = new World() { public List getShadowMungers() { return Collections.EMPTY_LIST; } public ResolvedTypeX.ConcreteName resolveObjectType(ResolvedTypeX.Name ty) { return null; } public Advice concreteAdvice(AjAttribute.AdviceAttribute attribute, Pointcut p, Member m) { throw new RuntimeException("unimplemented"); } public ConcreteTypeMunger concreteTypeMunger(ResolvedTypeMunger munger, ResolvedTypeX aspectType) { throw new RuntimeException("unimplemented"); } }; public abstract Advice concreteAdvice( AjAttribute.AdviceAttribute attribute, Pointcut pointcut, Member signature); public final Advice concreteAdvice( 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 concreteAdvice(attribute, p, signature); } public ConcreteTypeMunger makeCflowStackFieldAdder(ResolvedMember cflowField) { throw new RuntimeException("unimplemented"); } public abstract ConcreteTypeMunger concreteTypeMunger(ResolvedTypeMunger munger, ResolvedTypeX aspectType); /** * 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) { this.messageHandler = messageHandler; } public void setXRefHandler(ICrossReferenceHandler xrefHandler) { this.xrefHandler = xrefHandler; } public void showMessage( Kind kind, String message, ISourceLocation loc1, ISourceLocation loc2) { if (loc1 != null) { messageHandler.handleMessage(new Message(message, kind, null, loc1)); if (loc2 != null) { messageHandler.handleMessage(new Message(message, kind, null, loc2)); } } else { messageHandler.handleMessage(new Message(message, kind, null, loc2)); } } // public void addDeclare(ResolvedTypeX onType, Declare declare, boolean forWeaving) { // // this is not extensible, oh well // if (declare instanceof DeclareErrorOrWarning) { // ShadowMunger m = new Checker((DeclareErrorOrWarning)declare); // onType.addShadowMunger(m); // } else if (declare instanceof DeclareDominates) { // declareDominates.add(declare); // } else if (declare instanceof DeclareParents) { // declareParents.add(declare); // } else if (declare instanceof DeclareSoft) { // DeclareSoft d = (DeclareSoft)declare; // declareSoft.add(d); // if (forWeaving) { // ShadowMunger m = Advice.makeSoftener(this, d.getPointcut().concretize(onType, 0), d.getException()); // onType.addShadowMunger(m); // } // } else { // throw new RuntimeException("unimplemented"); // } // } /** * Same signature as org.aspectj.util.PartialOrder.PartialComparable.compareTo */ public int compareByDominates(ResolvedTypeX aspect1, ResolvedTypeX aspect2) { //System.out.println("dom compare: " + aspect1 + " with " + aspect2); //System.out.println(crosscuttingMembersSet.getDeclareDominates()); //??? We probably want to cache this result. This is order N where N is the //??? number of dominates declares in the whole system. //??? This method can be called a large number of times. int order = 0; DeclarePrecedence orderer = null; // Records the declare precedence statement that gives the first ordering for (Iterator i = crosscuttingMembersSet.getDeclareDominates().iterator(); i.hasNext(); ) { DeclarePrecedence d = (DeclarePrecedence)i.next(); int thisOrder = d.compare(aspect1, aspect2); //System.out.println("comparing: " + thisOrder + ": " + d); 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: "+ aspect1.getName()+" and "+aspect2.getName(),null,true,isls); messageHandler.handleMessage(m); // throw new BCException("conflicting dominates orders"+d.getSourceLocation()); } else { order = thisOrder; } } } return order; } public int comparePrecedence(ResolvedTypeX aspect1, ResolvedTypeX aspect2) { //System.err.println("compare precedence " + aspect1 + ", " + aspect2); if (aspect1.equals(aspect2)) return 0; int ret = compareByDominates(aspect1, aspect2); if (ret != 0) return ret; if (aspect1.isAssignableFrom(aspect2)) return -1; else if (aspect2.isAssignableFrom(aspect1)) return +1; return 0; } public List getDeclareParents() { return crosscuttingMembersSet.getDeclareParents(); } 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 ResolvedTypeX.Name lookupOrCreateName(TypeX ty) { String signature = ty.getSignature(); ResolvedTypeX.Name ret = (ResolvedTypeX.Name)typeMap.get(signature); if (ret == null) { ret = new ResolvedTypeX.Name(signature, this); typeMap.put(signature, ret); } return ret; } // public void clearUnexposed() { // List toRemove = new ArrayList(); // for (Iterator iter = typeMap.keySet().iterator(); iter.hasNext();) { // String sig = (String) iter.next(); // ResolvedTypeX x = (ResolvedTypeX) typeMap.get(sig); // if (!x.isExposedToWeaver() && (!x.isPrimitive())) toRemove.add(sig); // } // for (Iterator iter = toRemove.iterator(); iter.hasNext();) { // typeMap.remove(iter.next()); // } // } // // // for testing... // public void dumpTypeMap() { // int exposed = 0; // for (Iterator iter = typeMap.keySet().iterator(); iter.hasNext();) { // String sig = (String) iter.next(); // ResolvedTypeX x = (ResolvedTypeX) typeMap.get(sig); // if (x.isExposedToWeaver()) exposed++; // } // System.out.println("type map contains " + typeMap.size() + " entries, " + exposed + " exposed to weaver"); // } // // public void deepDumpTypeMap() { // for (Iterator iter = typeMap.keySet().iterator(); iter.hasNext();) { // String sig = (String) iter.next(); // ResolvedTypeX x = (ResolvedTypeX) typeMap.get(sig); // if (! (x instanceof ResolvedTypeX.Name)) { // System.out.println(sig + " -> " + x.getClass().getName() + ", " + x.getClassName()); // } else { // ResolvedTypeX.ConcreteName cname = ((ResolvedTypeX.Name)x).getDelegate(); // System.out.println(sig + " -> " + cname.getClass().getName() + ", " + cname.toString()); // } // } // // } // Map of types in the world, with soft links to expendable ones protected static class TypeMap { private Map tMap = new HashMap(); private Map expendableMap = new WeakHashMap(); public ResolvedTypeX put(String key, ResolvedTypeX type) { if (isExpendable(type)) { return (ResolvedTypeX) expendableMap.put(key,type); } else { return (ResolvedTypeX) tMap.put(key,type); } } public ResolvedTypeX get(String key) { ResolvedTypeX ret = (ResolvedTypeX) tMap.get(key); if (ret == null) ret = (ResolvedTypeX) expendableMap.get(key); return ret; } public ResolvedTypeX remove(String key) { ResolvedTypeX ret = (ResolvedTypeX) tMap.remove(key); if (ret == null) ret = (ResolvedTypeX) expendableMap.remove(key); return ret; } private boolean isExpendable(ResolvedTypeX type) { return ( (type != null) && (!type.isExposedToWeaver()) && (!type.isPrimitive()) ); } } }
30,439
Bug 30439 spurious "circular dependency" error
AspectJ Compiler 1.1beta4 This program: aspect Foo { pointcut p1(): execution(void f()) && cflow(execution(void f1())); pointcut p2(): execution(void f()) && cflow(execution(void f2())); before(): p1() { } after(): p1() { } before(): p2() { } after(): p2() { } } class A { void f1() { f(); } void f2() { f(); } void f() { } } results in these errors: circular dependency at method-execution(void A.f()) circular dependency at method-execution(void A.f()) circular dependency at method-execution(void A.f()) circular dependency at method-execution(void A.f()) 4 errors If I comment out any one of the four pieces of advice, all the errors go away. Also, assuming that there is a valid reason for printing this error sometimes, how come there's no line number? --Doug
resolved fixed
4feb835
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2004-07-29T15:04:00Z
2003-01-28T21:40:00Z
weaver/src/org/aspectj/weaver/bcel/BcelClassWeaver.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Common Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * PARC initial implementation * ******************************************************************/ package org.aspectj.weaver.bcel; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import org.apache.bcel.Constants; import org.apache.bcel.generic.BranchInstruction; import org.apache.bcel.generic.CPInstruction; import org.apache.bcel.generic.ConstantPoolGen; import org.apache.bcel.generic.FieldInstruction; import org.apache.bcel.generic.INVOKESPECIAL; import org.apache.bcel.generic.IndexedInstruction; import org.apache.bcel.generic.Instruction; import org.apache.bcel.generic.InstructionConstants; import org.apache.bcel.generic.InstructionFactory; import org.apache.bcel.generic.InstructionHandle; import org.apache.bcel.generic.InstructionList; import org.apache.bcel.generic.InstructionTargeter; import org.apache.bcel.generic.InvokeInstruction; import org.apache.bcel.generic.LocalVariableInstruction; import org.apache.bcel.generic.NEW; import org.apache.bcel.generic.ObjectType; import org.apache.bcel.generic.PUTFIELD; import org.apache.bcel.generic.PUTSTATIC; import org.apache.bcel.generic.RET; import org.apache.bcel.generic.ReturnInstruction; import org.apache.bcel.generic.Select; import org.apache.bcel.generic.Type; import org.aspectj.bridge.IMessage; import org.aspectj.util.PartialOrder; import org.aspectj.weaver.AjAttribute; import org.aspectj.weaver.AjcMemberMaker; import org.aspectj.weaver.BCException; import org.aspectj.weaver.ConcreteTypeMunger; import org.aspectj.weaver.IClassWeaver; import org.aspectj.weaver.IntMap; import org.aspectj.weaver.Member; import org.aspectj.weaver.NameMangler; import org.aspectj.weaver.NewFieldTypeMunger; import org.aspectj.weaver.ResolvedMember; import org.aspectj.weaver.ResolvedTypeX; import org.aspectj.weaver.Shadow; import org.aspectj.weaver.ShadowMunger; import org.aspectj.weaver.WeaverStateInfo; import org.aspectj.weaver.Shadow.Kind; import org.aspectj.weaver.patterns.FastMatchInfo; class BcelClassWeaver implements IClassWeaver { /** * This is called from {@link BcelWeaver} to perform the per-class weaving process. */ public static boolean weave( BcelWorld world, LazyClassGen clazz, List shadowMungers, List typeMungers) { boolean b = new BcelClassWeaver(world, clazz, shadowMungers, typeMungers).weave(); //System.out.println(clazz.getClassName() + ", " + clazz.getType().getWeaverState()); //clazz.print(); return b; } // -------------------------------------------- private final LazyClassGen clazz; private final List shadowMungers; private final List typeMungers; private final BcelObjectType ty; // alias of clazz.getType() private final BcelWorld world; // alias of ty.getWorld() private final ConstantPoolGen cpg; // alias of clazz.getConstantPoolGen() private final InstructionFactory fact; // alias of clazz.getFactory(); private final List addedLazyMethodGens = new ArrayList(); private final Set addedDispatchTargets = new HashSet(); // Static setting across BcelClassWeavers private static boolean inReweavableMode = false; private static boolean compressReweavableAttributes = false; private List addedSuperInitializersAsList = null; // List<IfaceInitList> private final Map addedSuperInitializers = new HashMap(); // Interface -> IfaceInitList private List addedThisInitializers = new ArrayList(); // List<NewFieldMunger> private List addedClassInitializers = new ArrayList(); // List<NewFieldMunger> private BcelShadow clinitShadow = null; /** * This holds the initialization and pre-initialization shadows for this class * that were actually matched by mungers (if no match, then we don't even create the * shadows really). */ private final List initializationShadows = new ArrayList(1); private BcelClassWeaver( BcelWorld world, LazyClassGen clazz, List shadowMungers, List typeMungers) { super(); // assert world == clazz.getType().getWorld() this.world = world; this.clazz = clazz; this.shadowMungers = shadowMungers; this.typeMungers = typeMungers; this.ty = clazz.getBcelObjectType(); this.cpg = clazz.getConstantPoolGen(); this.fact = clazz.getFactory(); fastMatchShadowMungers(shadowMungers); initializeSuperInitializerMap(ty.getResolvedTypeX()); } private List[] perKindShadowMungers; private boolean canMatchBodyShadows = false; private boolean canMatchInitialization = false; private void fastMatchShadowMungers(List shadowMungers) { perKindShadowMungers = new List[Shadow.MAX_SHADOW_KIND+1]; for (int i = 0; i < Shadow.SHADOW_KINDS.length; i++) { Shadow.Kind kind = Shadow.SHADOW_KINDS[i]; ArrayList mungers = new ArrayList(0); perKindShadowMungers[kind.getKey()] = mungers; fastMatchShadowMungers(shadowMungers, mungers, kind); if (mungers.isEmpty()) { perKindShadowMungers[kind.getKey()] = null; } else { if (kind == Shadow.Initialization) { canMatchInitialization = true; } else if (!kind.isEnclosingKind()) { canMatchBodyShadows = true; } } } } private boolean canMatch(Shadow.Kind kind) { return perKindShadowMungers[kind.getKey()] != null; } private void fastMatchShadowMungers(List shadowMungers, ArrayList mungers, Kind kind) { FastMatchInfo info = new FastMatchInfo(clazz.getType(), kind); for (Iterator i = shadowMungers.iterator(); i.hasNext();) { ShadowMunger munger = (ShadowMunger) i.next(); if (munger.getPointcut().fastMatch(info).maybeTrue()) mungers.add(munger); } } private void initializeSuperInitializerMap(ResolvedTypeX child) { ResolvedTypeX[] superInterfaces = child.getDeclaredInterfaces(); for (int i=0, len=superInterfaces.length; i < len; i++) { if (ty.getResolvedTypeX().isTopmostImplementor(superInterfaces[i])) { if (addSuperInitializer(superInterfaces[i])) { initializeSuperInitializerMap(superInterfaces[i]); } } } } private boolean addSuperInitializer(ResolvedTypeX onType) { IfaceInitList l = (IfaceInitList) addedSuperInitializers.get(onType); if (l != null) return false; l = new IfaceInitList(onType); addedSuperInitializers.put(onType, l); return true; } public void addInitializer(ConcreteTypeMunger cm) { NewFieldTypeMunger m = (NewFieldTypeMunger) cm.getMunger(); ResolvedTypeX onType = m.getSignature().getDeclaringType().resolve(world); if (m.getSignature().isStatic()) { addedClassInitializers.add(cm); } else { if (onType == ty.getResolvedTypeX()) { addedThisInitializers.add(cm); } else { IfaceInitList l = (IfaceInitList) addedSuperInitializers.get(onType); l.list.add(cm); } } } private static class IfaceInitList implements PartialOrder.PartialComparable { final ResolvedTypeX onType; List list = new ArrayList(); IfaceInitList(ResolvedTypeX onType) { this.onType = onType; } public int compareTo(Object other) { IfaceInitList o = (IfaceInitList)other; if (onType.isAssignableFrom(o.onType)) return +1; else if (o.onType.isAssignableFrom(onType)) return -1; else return 0; } public int fallbackCompareTo(Object other) { return 0; } } // XXX this is being called, but the result doesn't seem to be being used public boolean addDispatchTarget(ResolvedMember m) { return addedDispatchTargets.add(m); } public void addLazyMethodGen(LazyMethodGen gen) { addedLazyMethodGens.add(gen); } public void addOrReplaceLazyMethodGen(LazyMethodGen mg) { if (alreadyDefined(clazz, mg)) return; for (Iterator i = addedLazyMethodGens.iterator(); i.hasNext(); ) { LazyMethodGen existing = (LazyMethodGen)i.next(); if (signaturesMatch(mg, existing)) { if (existing.definingType == null) { // this means existing was introduced on the class itself return; } else if (mg.definingType.isAssignableFrom(existing.definingType)) { // existing is mg's subtype and dominates mg return; } else if (existing.definingType.isAssignableFrom(mg.definingType)) { // mg is existing's subtype and dominates existing i.remove(); addedLazyMethodGens.add(mg); return; } else { throw new BCException("conflict between: " + mg + " and " + existing); } } } addedLazyMethodGens.add(mg); } private boolean alreadyDefined(LazyClassGen clazz, LazyMethodGen mg) { for (Iterator i = clazz.getMethodGens().iterator(); i.hasNext(); ) { LazyMethodGen existing = (LazyMethodGen)i.next(); if (signaturesMatch(mg, existing)) { if (!mg.isAbstract() && existing.isAbstract()) { i.remove(); return false; } return true; } } return false; } private boolean signaturesMatch(LazyMethodGen mg, LazyMethodGen existing) { return mg.getName().equals(existing.getName()) && mg.getSignature().equals(existing.getSignature()); } // ---- public boolean weave() { if (clazz.isWoven() && !clazz.isReweavable()) { world.showMessage(IMessage.ERROR, "class \'" + clazz.getType().getName() + "\' is already woven and has not been built with -Xreweavable", ty.getSourceLocation(), null); return false; } Set aspectsAffectingType = null; if (inReweavableMode) aspectsAffectingType = new HashSet(); boolean isChanged = false; // we want to "touch" all aspects if (clazz.getType().isAspect()) isChanged = true; // start by munging all typeMungers for (Iterator i = typeMungers.iterator(); i.hasNext(); ) { Object o = i.next(); if ( !(o instanceof BcelTypeMunger) ) { //???System.err.println("surprising: " + o); continue; } BcelTypeMunger munger = (BcelTypeMunger)o; boolean typeMungerAffectedType = munger.munge(this); if (typeMungerAffectedType) { isChanged = true; if (inReweavableMode) aspectsAffectingType.add(munger.getAspectType().getName()); } } // XXX do major sort of stuff // sort according to: Major: type hierarchy // within each list: dominates // don't forget to sort addedThisInitialiers according to dominates addedSuperInitializersAsList = new ArrayList(addedSuperInitializers.values()); addedSuperInitializersAsList = PartialOrder.sort(addedSuperInitializersAsList); if (addedSuperInitializersAsList == null) { throw new BCException("circularity in inter-types"); } // this will create a static initializer if there isn't one // this is in just as bad taste as NOPs LazyMethodGen staticInit = clazz.getStaticInitializer(); staticInit.getBody().insert(genInitInstructions(addedClassInitializers, true)); // now go through each method, and match against each method. This // sets up each method's {@link LazyMethodGen#matchedShadows} field, // and it also possibly adds to {@link #initializationShadows}. List methodGens = new ArrayList(clazz.getMethodGens()); for (Iterator i = methodGens.iterator(); i.hasNext();) { LazyMethodGen mg = (LazyMethodGen)i.next(); //mg.getBody(); if (! mg.hasBody()) continue; boolean shadowMungerMatched = match(mg); if (shadowMungerMatched) { // For matching mungers, add their declaring aspects to the list that affected this type if (inReweavableMode) aspectsAffectingType.addAll(findAspectsForMungers(mg)); isChanged = true; } } if (! isChanged) return false; // now we weave all but the initialization shadows for (Iterator i = methodGens.iterator(); i.hasNext();) { LazyMethodGen mg = (LazyMethodGen)i.next(); if (! mg.hasBody()) continue; implement(mg); } // if we matched any initialization shadows, we inline and weave if (! initializationShadows.isEmpty()) { // Repeat next step until nothing left to inline...cant go on // infinetly as compiler will have detected and reported // "Recursive constructor invocation" while (inlineSelfConstructors(methodGens)); positionAndImplement(initializationShadows); } // finally, if we changed, we add in the introduced methods. if (isChanged) { clazz.getOrCreateWeaverStateInfo(); weaveInAddedMethods(); } if (inReweavableMode) { WeaverStateInfo wsi = clazz.getOrCreateWeaverStateInfo(); wsi.addAspectsAffectingType(aspectsAffectingType); wsi.setUnwovenClassFileData(ty.getJavaClass().getBytes()); wsi.setReweavable(true,compressReweavableAttributes); } else { clazz.getOrCreateWeaverStateInfo().setReweavable(false,false); } return isChanged; } private Set findAspectsForMungers(LazyMethodGen mg) { Set aspectsAffectingType = new HashSet(); for (Iterator iter = mg.matchedShadows.iterator(); iter.hasNext();) { BcelShadow aShadow = (BcelShadow) iter.next(); // Mungers in effect on that shadow for (Iterator iter2 = aShadow.getMungers().iterator();iter2.hasNext();) { ShadowMunger aMunger = (ShadowMunger) iter2.next(); if (aMunger instanceof BcelAdvice) { BcelAdvice bAdvice = (BcelAdvice)aMunger; aspectsAffectingType.add(bAdvice.getConcreteAspect().getName()); } else { // It is a 'Checker' - we don't need to remember aspects that only contributed Checkers... } } } return aspectsAffectingType; } private boolean inlineSelfConstructors(List methodGens) { boolean inlinedSomething = false; for (Iterator i = methodGens.iterator(); i.hasNext();) { LazyMethodGen mg = (LazyMethodGen) i.next(); if (! mg.getName().equals("<init>")) continue; InstructionHandle ih = findSuperOrThisCall(mg); if (ih != null && isThisCall(ih)) { LazyMethodGen donor = getCalledMethod(ih); inlineMethod(donor, mg, ih); inlinedSomething = true; } } return inlinedSomething; } private void positionAndImplement(List initializationShadows) { for (Iterator i = initializationShadows.iterator(); i.hasNext(); ) { BcelShadow s = (BcelShadow) i.next(); positionInitializationShadow(s); //s.getEnclosingMethod().print(); s.implement(); } } private void positionInitializationShadow(BcelShadow s) { LazyMethodGen mg = s.getEnclosingMethod(); InstructionHandle call = findSuperOrThisCall(mg); InstructionList body = mg.getBody(); ShadowRange r = new ShadowRange(body); r.associateWithShadow((BcelShadow) s); if (s.getKind() == Shadow.PreInitialization) { // XXX assert first instruction is an ALOAD_0. // a pre shadow goes from AFTER the first instruction (which we believe to // be an ALOAD_0) to just before the call to super r.associateWithTargets( Range.genStart(body, body.getStart().getNext()), Range.genEnd(body, call.getPrev())); } else { // assert s.getKind() == Shadow.Initialization r.associateWithTargets( Range.genStart(body, call.getNext()), Range.genEnd(body)); } } private boolean isThisCall(InstructionHandle ih) { INVOKESPECIAL inst = (INVOKESPECIAL) ih.getInstruction(); return inst.getClassName(cpg).equals(clazz.getName()); } /** inline a particular call in bytecode. * * @param donor the method we want to inline * @param recipient the method containing the call we want to inline * @param call the instructionHandle in recipient's body holding the call we want to * inline. */ public static void inlineMethod( LazyMethodGen donor, LazyMethodGen recipient, InstructionHandle call) { // assert recipient.contains(call) /* Implementation notes: * * We allocate two slots for every tempvar so we don't screw up * longs and doubles which may share space. This could be conservatively avoided * (no reference to a long/double instruction, don't do it) or packed later. * Right now we don't bother to pack. * * Allocate a new var for each formal param of the inlined. Fill with stack * contents. Then copy the inlined instructions in with the appropriate remap * table. Any framelocs used by locals in inlined are reallocated to top of * frame, */ final InstructionFactory fact = recipient.getEnclosingClass().getFactory(); IntMap frameEnv = new IntMap(); // this also sets up the initial environment InstructionList argumentStores = genArgumentStores(donor, recipient, frameEnv, fact); InstructionList inlineInstructions = genInlineInstructions(donor, recipient, frameEnv, fact, false); inlineInstructions.insert(argumentStores); recipient.getBody().append(call, inlineInstructions); Utility.deleteInstruction(call, recipient); } /** generate the instructions to be inlined. * * @param donor the method from which we will copy (and adjust frame and jumps) * instructions. * @param recipient the method the instructions will go into. Used to get the frame * size so we can allocate new frame locations for locals in donor. * @param frameEnv an environment to map from donor frame to recipient frame, * initially populated with argument locations. * @param fact an instruction factory for recipient */ static InstructionList genInlineInstructions( LazyMethodGen donor, LazyMethodGen recipient, IntMap frameEnv, InstructionFactory fact, boolean keepReturns) { InstructionList footer = new InstructionList(); InstructionHandle end = footer.append(InstructionConstants.NOP); InstructionList ret = new InstructionList(); InstructionList sourceList = donor.getBody(); Map srcToDest = new HashMap(); ConstantPoolGen donorCpg = donor.getEnclosingClass().getConstantPoolGen(); ConstantPoolGen recipientCpg = recipient.getEnclosingClass().getConstantPoolGen(); boolean isAcrossClass = donorCpg != recipientCpg; // first pass: copy the instructions directly, populate the srcToDest map, // fix frame instructions for (InstructionHandle src = sourceList.getStart(); src != null; src = src.getNext()) { Instruction fresh = Utility.copyInstruction(src.getInstruction()); InstructionHandle dest; if (fresh instanceof CPInstruction) { // need to reset index to go to new constant pool. This is totally // a computation leak... we're testing this LOTS of times. Sigh. if (isAcrossClass) { CPInstruction cpi = (CPInstruction) fresh; cpi.setIndex( recipientCpg.addConstant( donorCpg.getConstant(cpi.getIndex()), donorCpg)); } } if (src.getInstruction() == Range.RANGEINSTRUCTION) { dest = ret.append(Range.RANGEINSTRUCTION); } else if (fresh instanceof ReturnInstruction) { if (keepReturns) { dest = ret.append(fresh); } else { dest = ret.append(InstructionFactory.createBranchInstruction(Constants.GOTO, end)); } } else if (fresh instanceof BranchInstruction) { dest = ret.append((BranchInstruction) fresh); } else if ( fresh instanceof LocalVariableInstruction || fresh instanceof RET) { IndexedInstruction indexed = (IndexedInstruction) fresh; int oldIndex = indexed.getIndex(); int freshIndex; if (!frameEnv.hasKey(oldIndex)) { freshIndex = recipient.allocateLocal(2); frameEnv.put(oldIndex, freshIndex); } else { freshIndex = frameEnv.get(oldIndex); } indexed.setIndex(freshIndex); dest = ret.append(fresh); } else { dest = ret.append(fresh); } srcToDest.put(src, dest); } // second pass: retarget branch instructions, copy ranges and tags Map tagMap = new HashMap(); Map shadowMap = new HashMap(); for (InstructionHandle dest = ret.getStart(), src = sourceList.getStart(); dest != null; dest = dest.getNext(), src = src.getNext()) { Instruction inst = dest.getInstruction(); // retarget branches if (inst instanceof BranchInstruction) { BranchInstruction branch = (BranchInstruction) inst; InstructionHandle oldTarget = branch.getTarget(); InstructionHandle newTarget = (InstructionHandle) srcToDest.get(oldTarget); if (newTarget == null) { // assert this is a GOTO // this was a return instruction we previously replaced } else { branch.setTarget(newTarget); if (branch instanceof Select) { Select select = (Select) branch; InstructionHandle[] oldTargets = select.getTargets(); for (int k = oldTargets.length - 1; k >= 0; k--) { select.setTarget( k, (InstructionHandle) srcToDest.get(oldTargets[k])); } } } } //copy over tags and range attributes InstructionTargeter[] srcTargeters = src.getTargeters(); if (srcTargeters != null) { for (int j = srcTargeters.length - 1; j >= 0; j--) { InstructionTargeter old = srcTargeters[j]; if (old instanceof Tag) { Tag oldTag = (Tag) old; Tag fresh = (Tag) tagMap.get(oldTag); if (fresh == null) { fresh = oldTag.copy(); tagMap.put(oldTag, fresh); } dest.addTargeter(fresh); } else if (old instanceof ExceptionRange) { ExceptionRange er = (ExceptionRange) old; if (er.getStart() == src) { ExceptionRange freshEr = new ExceptionRange( recipient.getBody(), er.getCatchType(), er.getPriority()); freshEr.associateWithTargets( dest, (InstructionHandle)srcToDest.get(er.getEnd()), (InstructionHandle)srcToDest.get(er.getHandler())); } } else if (old instanceof ShadowRange) { ShadowRange oldRange = (ShadowRange) old; if (oldRange.getStart() == src) { BcelShadow oldShadow = oldRange.getShadow(); BcelShadow freshEnclosing = oldShadow.getEnclosingShadow() == null ? null : (BcelShadow) shadowMap.get(oldShadow.getEnclosingShadow()); BcelShadow freshShadow = oldShadow.copyInto(recipient, freshEnclosing); ShadowRange freshRange = new ShadowRange(recipient.getBody()); freshRange.associateWithShadow(freshShadow); freshRange.associateWithTargets( dest, (InstructionHandle) srcToDest.get(oldRange.getEnd())); shadowMap.put(oldRange, freshRange); //recipient.matchedShadows.add(freshShadow); // XXX should go through the NEW copied shadow and update // the thisVar, targetVar, and argsVar // ??? Might want to also go through at this time and add // "extra" vars to the shadow. } } } } } if (!keepReturns) ret.append(footer); return ret; } /** generate the argument stores in preparation for inlining. * * @param donor the method we will inline from. Used to get the signature. * @param recipient the method we will inline into. Used to get the frame size * so we can allocate fresh locations. * @param frameEnv an empty environment we populate with a map from donor frame to * recipient frame. * @param fact an instruction factory for recipient */ private static InstructionList genArgumentStores( LazyMethodGen donor, LazyMethodGen recipient, IntMap frameEnv, InstructionFactory fact) { InstructionList ret = new InstructionList(); int donorFramePos = 0; // writing ret back to front because we're popping. if (! donor.isStatic()) { int targetSlot = recipient.allocateLocal(Type.OBJECT); ret.insert(InstructionFactory.createStore(Type.OBJECT, targetSlot)); frameEnv.put(donorFramePos, targetSlot); donorFramePos += 1; } Type[] argTypes = donor.getArgumentTypes(); for (int i = 0, len = argTypes.length; i < len; i++) { Type argType = argTypes[i]; int argSlot = recipient.allocateLocal(argType); ret.insert(InstructionFactory.createStore(argType, argSlot)); frameEnv.put(donorFramePos, argSlot); donorFramePos += argType.getSize(); } return ret; } /** get a called method: Assumes the called method is in this class, * and the reference to it is exact (a la INVOKESPECIAL). * * @param ih The InvokeInstruction instructionHandle pointing to the called method. */ private LazyMethodGen getCalledMethod( InstructionHandle ih) { InvokeInstruction inst = (InvokeInstruction) ih.getInstruction(); String methodName = inst.getName(cpg); String signature = inst.getSignature(cpg); return clazz.getLazyMethodGen(methodName, signature); } private void weaveInAddedMethods() { Collections.sort(addedLazyMethodGens, new Comparator() { public int compare(Object a, Object b) { LazyMethodGen aa = (LazyMethodGen) a; LazyMethodGen bb = (LazyMethodGen) b; int i = aa.getName().compareTo(bb.getName()); if (i != 0) return i; return aa.getSignature().compareTo(bb.getSignature()); } } ); for (Iterator i = addedLazyMethodGens.iterator(); i.hasNext(); ) { clazz.addMethodGen((LazyMethodGen)i.next()); } } void addPerSingletonField(Member field) { ObjectType aspectType = (ObjectType) BcelWorld.makeBcelType(field.getReturnType()); String aspectName = field.getReturnType().getName(); LazyMethodGen clinit = clazz.getStaticInitializer(); InstructionList setup = new InstructionList(); InstructionFactory fact = clazz.getFactory(); setup.append(fact.createNew(aspectType)); setup.append(InstructionFactory.createDup(1)); setup.append(fact.createInvoke( aspectName, "<init>", Type.VOID, new Type[0], Constants.INVOKESPECIAL)); setup.append( fact.createFieldAccess( aspectName, field.getName(), aspectType, Constants.PUTSTATIC)); clinit.getBody().insert(setup); } /** * Returns null if this is not a Java constructor, and then we won't * weave into it at all */ private InstructionHandle findSuperOrThisCall(LazyMethodGen mg) { int depth = 1; InstructionHandle start = mg.getBody().getStart(); while (true) { if (start == null) return null; Instruction inst = start.getInstruction(); if (inst instanceof INVOKESPECIAL && ((INVOKESPECIAL) inst).getName(cpg).equals("<init>")) { depth--; if (depth == 0) return start; } else if (inst instanceof NEW) { depth++; } start = start.getNext(); } } // ---- private boolean match(LazyMethodGen mg) { BcelShadow enclosingShadow; List shadowAccumulator = new ArrayList(); // we want to match ajsynthetic constructors... if (mg.getName().equals("<init>")) { return matchInit(mg, shadowAccumulator); } else if (!shouldWeaveBody(mg)) { //.isAjSynthetic()) { return false; } else { if (mg.getName().equals("<clinit>")) { clinitShadow = enclosingShadow = BcelShadow.makeStaticInitialization(world, mg); //System.err.println(enclosingShadow); } else if (mg.isAdviceMethod()) { enclosingShadow = BcelShadow.makeAdviceExecution(world, mg); } else { AjAttribute.EffectiveSignatureAttribute effective = mg.getEffectiveSignature(); if (effective == null) { enclosingShadow = BcelShadow.makeMethodExecution(world, mg, !canMatchBodyShadows); } else if (effective.isWeaveBody()) { enclosingShadow = BcelShadow.makeShadowForMethod( world, mg, effective.getShadowKind(), effective.getEffectiveSignature()); } else { return false; } } if (canMatchBodyShadows) { for (InstructionHandle h = mg.getBody().getStart(); h != null; h = h.getNext()) { match(mg, h, enclosingShadow, shadowAccumulator); } } if (match(enclosingShadow, shadowAccumulator)) { enclosingShadow.init(); } mg.matchedShadows = shadowAccumulator; return !shadowAccumulator.isEmpty(); } } private boolean matchInit(LazyMethodGen mg, List shadowAccumulator) { BcelShadow enclosingShadow; // XXX the enclosing join point is wrong for things before ignoreMe. InstructionHandle superOrThisCall = findSuperOrThisCall(mg); // we don't walk bodies of things where it's a wrong constructor thingie if (superOrThisCall == null) return false; enclosingShadow = BcelShadow.makeConstructorExecution(world, mg, superOrThisCall); // walk the body boolean beforeSuperOrThisCall = true; if (shouldWeaveBody(mg)) { if (canMatchBodyShadows) { for (InstructionHandle h = mg.getBody().getStart(); h != null; h = h.getNext()) { if (h == superOrThisCall) { beforeSuperOrThisCall = false; continue; } match(mg, h, beforeSuperOrThisCall ? null : enclosingShadow, shadowAccumulator); } } match(enclosingShadow, shadowAccumulator); } // XXX we don't do pre-inits of interfaces // now add interface inits if (superOrThisCall != null && ! isThisCall(superOrThisCall)) { InstructionHandle curr = enclosingShadow.getRange().getStart(); for (Iterator i = addedSuperInitializersAsList.iterator(); i.hasNext(); ) { IfaceInitList l = (IfaceInitList) i.next(); Member ifaceInitSig = AjcMemberMaker.interfaceConstructor(l.onType); BcelShadow initShadow = BcelShadow.makeIfaceInitialization(world, mg, ifaceInitSig); // insert code in place InstructionList inits = genInitInstructions(l.list, false); if (match(initShadow, shadowAccumulator) || !inits.isEmpty()) { initShadow.initIfaceInitializer(curr); initShadow.getRange().insert(inits, Range.OutsideBefore); } } // now we add our initialization code InstructionList inits = genInitInstructions(addedThisInitializers, false); enclosingShadow.getRange().insert(inits, Range.OutsideBefore); } // actually, you only need to inline the self constructors that are // in a particular group (partition the constructors into groups where members // call or are called only by those in the group). Then only inline // constructors // in groups where at least one initialization jp matched. Future work. boolean addedInitialization = match( BcelShadow.makeUnfinishedInitialization(world, mg), initializationShadows); addedInitialization |= match( BcelShadow.makeUnfinishedPreinitialization(world, mg), initializationShadows); mg.matchedShadows = shadowAccumulator; return addedInitialization || !shadowAccumulator.isEmpty(); } private boolean shouldWeaveBody(LazyMethodGen mg) { if (mg.isAjSynthetic()) return mg.getName().equals("<clinit>"); AjAttribute.EffectiveSignatureAttribute a = mg.getEffectiveSignature(); if (a != null) return a.isWeaveBody(); return true; } /** * first sorts the mungers, then gens the initializers in the right order */ private InstructionList genInitInstructions(List list, boolean isStatic) { list = PartialOrder.sort(list); if (list == null) { throw new BCException("circularity in inter-types"); } InstructionList ret = new InstructionList(); for (Iterator i = list.iterator(); i.hasNext();) { ConcreteTypeMunger cmunger = (ConcreteTypeMunger) i.next(); NewFieldTypeMunger munger = (NewFieldTypeMunger) cmunger.getMunger(); ResolvedMember initMethod = munger.getInitMethod(cmunger.getAspectType()); if (!isStatic) ret.append(InstructionConstants.ALOAD_0); ret.append(Utility.createInvoke(fact, world, initMethod)); } return ret; } private void match( LazyMethodGen mg, InstructionHandle ih, BcelShadow enclosingShadow, List shadowAccumulator) { Instruction i = ih.getInstruction(); if (i instanceof FieldInstruction) { FieldInstruction fi = (FieldInstruction) i; if (fi instanceof PUTFIELD || fi instanceof PUTSTATIC) { // check for sets of constant fields. We first check the previous // instruction. If the previous instruction is a LD_WHATEVER (push // constant on the stack) then we must resolve the field to determine // if it's final. If it is final, then we don't generate a shadow. InstructionHandle prevHandle = ih.getPrev(); Instruction prevI = prevHandle.getInstruction(); if (Utility.isConstantPushInstruction(prevI)) { Member field = BcelWorld.makeFieldSignature(clazz, (FieldInstruction) i); ResolvedMember resolvedField = field.resolve(world); if (resolvedField == null) { // we can't find the field, so it's not a join point. } else if (Modifier.isFinal(resolvedField.getModifiers())) { // it's final, so it's the set of a final constant, so it's // not a join point according to 1.0.6 and 1.1. } else { matchSetInstruction(mg, ih, enclosingShadow, shadowAccumulator); } } else { matchSetInstruction(mg, ih, enclosingShadow, shadowAccumulator); } } else { matchGetInstruction(mg, ih, enclosingShadow, shadowAccumulator); } } else if (i instanceof InvokeInstruction) { InvokeInstruction ii = (InvokeInstruction) i; if (ii.getMethodName(clazz.getConstantPoolGen()).equals("<init>")) { match( BcelShadow.makeConstructorCall(world, mg, ih, enclosingShadow), shadowAccumulator); } else if (ii instanceof INVOKESPECIAL) { String onTypeName = ii.getClassName(cpg); if (onTypeName.equals(mg.getEnclosingClass().getName())) { // we are private matchInvokeInstruction(mg, ih, ii, enclosingShadow, shadowAccumulator); } else { // we are a super call, and this is not a join point in AspectJ-1.{0,1} } } else { matchInvokeInstruction(mg, ih, ii, enclosingShadow, shadowAccumulator); } } // performance optimization... we only actually care about ASTORE instructions, // since that's what every javac type thing ever uses to start a handler, but for // now we'll do this for everybody. if (Range.isRangeHandle(ih)) return; InstructionTargeter[] targeters = ih.getTargeters(); if (targeters != null) { for (int j = 0; j < targeters.length; j++) { InstructionTargeter t = targeters[j]; if (t instanceof ExceptionRange) { // assert t.getHandler() == ih ExceptionRange er = (ExceptionRange) t; if (er.getCatchType() == null) continue; if (isInitFailureHandler(ih)) return; match( BcelShadow.makeExceptionHandler( world, er, mg, ih, enclosingShadow), shadowAccumulator); } } } } private boolean isInitFailureHandler(InstructionHandle ih) { // Skip the astore_0 and aload_0 at the start of the handler and // then check if the instruction following these is // 'putstatic ajc$initFailureCause'. If it is then we are // in the handler we created in AspectClinit.generatePostSyntheticCode() InstructionHandle twoInstructionsAway = ih.getNext().getNext(); if (twoInstructionsAway.getInstruction() instanceof PUTSTATIC) { String name = ((PUTSTATIC)twoInstructionsAway.getInstruction()).getFieldName(cpg); if (name.equals(NameMangler.INITFAILURECAUSE_FIELD_NAME)) return true; } return false; } private void matchSetInstruction( LazyMethodGen mg, InstructionHandle ih, BcelShadow enclosingShadow, List shadowAccumulator) { FieldInstruction fi = (FieldInstruction) ih.getInstruction(); Member field = BcelWorld.makeFieldSignature(clazz, fi); // synthetic fields are never join points if (field.getName().startsWith(NameMangler.PREFIX)) return; ResolvedMember resolvedField = field.resolve(world); if (resolvedField == null) { // we can't find the field, so it's not a join point. return; } else if ( Modifier.isFinal(resolvedField.getModifiers()) && Utility.isConstantPushInstruction(ih.getPrev().getInstruction())) { // it's the set of a final constant, so it's // not a join point according to 1.0.6 and 1.1. return; } else if (resolvedField.isSynthetic()) { // sets of synthetics aren't join points in 1.1 return; } else { match( BcelShadow.makeFieldSet(world, mg, ih, enclosingShadow), shadowAccumulator); } } private void matchGetInstruction(LazyMethodGen mg, InstructionHandle ih, BcelShadow enclosingShadow, List shadowAccumulator) { FieldInstruction fi = (FieldInstruction) ih.getInstruction(); Member field = BcelWorld.makeFieldSignature(clazz, fi); // synthetic fields are never join points if (field.getName().startsWith(NameMangler.PREFIX)) return; ResolvedMember resolvedField = field.resolve(world); if (resolvedField == null) { // we can't find the field, so it's not a join point. return; } else if (resolvedField.isSynthetic()) { // sets of synthetics aren't join points in 1.1 return; } else { match(BcelShadow.makeFieldGet(world, mg, ih, enclosingShadow), shadowAccumulator); } } private void matchInvokeInstruction(LazyMethodGen mg, InstructionHandle ih, InvokeInstruction invoke, BcelShadow enclosingShadow, List shadowAccumulator) { String methodName = invoke.getName(cpg); if (methodName.startsWith(NameMangler.PREFIX)) { Member method = BcelWorld.makeMethodSignature(clazz, invoke); ResolvedMember declaredSig = method.resolve(world); //System.err.println(method + ", declaredSig: " +declaredSig); if (declaredSig == null) return; if (declaredSig.getKind() == Member.FIELD) { Shadow.Kind kind; if (method.getReturnType().equals(ResolvedTypeX.VOID)) { kind = Shadow.FieldSet; } else { kind = Shadow.FieldGet; } match(BcelShadow.makeShadowForMethodCall(world, mg, ih, enclosingShadow, kind, declaredSig), shadowAccumulator); } else { AjAttribute.EffectiveSignatureAttribute effectiveSig = declaredSig.getEffectiveSignature(); if (effectiveSig == null) return; //System.err.println("call to inter-type member: " + effectiveSig); if (effectiveSig.isWeaveBody()) return; match(BcelShadow.makeShadowForMethodCall(world, mg, ih, enclosingShadow, effectiveSig.getShadowKind(), effectiveSig.getEffectiveSignature()), shadowAccumulator); } } else { match( BcelShadow.makeMethodCall(world, mg, ih, enclosingShadow), shadowAccumulator); } } private boolean match(BcelShadow shadow, List shadowAccumulator) { //System.err.println("match: " + shadow); boolean isMatched = false; for (Iterator i = shadowMungers.iterator(); i.hasNext(); ) { ShadowMunger munger = (ShadowMunger)i.next(); if (munger.match(shadow, world)) { shadow.addMunger(munger); isMatched = true; if (shadow.getKind() == Shadow.StaticInitialization) { clazz.warnOnAddedStaticInitializer(shadow,munger.getSourceLocation()); } } } if (isMatched) shadowAccumulator.add(shadow); return isMatched; } // ---- private void implement(LazyMethodGen mg) { List shadows = mg.matchedShadows; if (shadows == null) return; // We depend on a partial order such that inner shadows are earlier on the list // than outer shadows. That's fine. This order is preserved if: // A preceeds B iff B.getStart() is LATER THAN A.getStart(). for (Iterator i = shadows.iterator(); i.hasNext(); ) { BcelShadow shadow = (BcelShadow)i.next(); shadow.implement(); } mg.matchedShadows = null; } // ---- public LazyClassGen getLazyClassGen() { return clazz; } public List getShadowMungers() { return shadowMungers; } public BcelWorld getWorld() { return world; } // Called by the BcelWeaver to let us know all BcelClassWeavers need to collect reweavable info public static void setReweavableMode(boolean mode,boolean compress) { inReweavableMode = mode; compressReweavableAttributes = compress; } }
30,439
Bug 30439 spurious "circular dependency" error
AspectJ Compiler 1.1beta4 This program: aspect Foo { pointcut p1(): execution(void f()) && cflow(execution(void f1())); pointcut p2(): execution(void f()) && cflow(execution(void f2())); before(): p1() { } after(): p1() { } before(): p2() { } after(): p2() { } } class A { void f1() { f(); } void f2() { f(); } void f() { } } results in these errors: circular dependency at method-execution(void A.f()) circular dependency at method-execution(void A.f()) circular dependency at method-execution(void A.f()) circular dependency at method-execution(void A.f()) 4 errors If I comment out any one of the four pieces of advice, all the errors go away. Also, assuming that there is a valid reason for printing this error sometimes, how come there's no line number? --Doug
resolved fixed
4feb835
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2004-07-29T15:04:00Z
2003-01-28T21:40:00Z
weaver/src/org/aspectj/weaver/bcel/BcelWeaver.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Common Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * PARC initial implementation * ******************************************************************/ package org.aspectj.weaver.bcel; import java.io.ByteArrayInputStream; 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.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Set; import java.util.jar.Attributes; import java.util.jar.Attributes.Name; import java.util.jar.JarInputStream; import java.util.jar.Manifest; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; import java.util.zip.ZipOutputStream; import org.apache.bcel.classfile.ClassParser; import org.apache.bcel.classfile.JavaClass; import org.aspectj.bridge.IMessage; import org.aspectj.bridge.IProgressListener; import org.aspectj.bridge.Message; import org.aspectj.bridge.SourceLocation; import org.aspectj.util.FileUtil; import org.aspectj.weaver.ConcreteTypeMunger; import org.aspectj.weaver.CrosscuttingMembersSet; import org.aspectj.weaver.IClassFileProvider; import org.aspectj.weaver.IWeaveRequestor; import org.aspectj.weaver.IWeaver; import org.aspectj.weaver.NewParentTypeMunger; import org.aspectj.weaver.ResolvedTypeMunger; import org.aspectj.weaver.ResolvedTypeX; import org.aspectj.weaver.ShadowMunger; import org.aspectj.weaver.TypeX; import org.aspectj.weaver.WeaverStateInfo; import org.aspectj.weaver.patterns.DeclareParents; import org.aspectj.weaver.patterns.FastMatchInfo; public class BcelWeaver implements IWeaver { private BcelWorld world; private CrosscuttingMembersSet xcutSet; private IProgressListener progressListener = null; private double progressMade; private double progressPerClassFile; private boolean inReweavableMode = false; public BcelWeaver(BcelWorld world) { super(); this.world = world; this.xcutSet = world.getCrosscuttingMembersSet(); } public BcelWeaver() { this(new BcelWorld()); } // ---- fields // private Map sourceJavaClasses = new HashMap(); /* String -> UnwovenClassFile */ private List addedClasses = new ArrayList(); /* List<UnovenClassFile> */ private List deletedTypenames = new ArrayList(); /* List<String> */ // private Map resources = new HashMap(); /* String -> UnwovenClassFile */ private Manifest manifest = null; private boolean needToReweaveWorld = false; private List shadowMungerList = null; // setup by prepareForWeave private List typeMungerList = null; // setup by prepareForWeave private List declareParentsList = null; // setup by prepareForWeave private ZipOutputStream zipOutputStream; // ---- // only called for testing public void setShadowMungers(List l) { shadowMungerList = l; } public void addLibraryAspect(String aspectName) { ResolvedTypeX type = world.resolve(aspectName); //System.out.println("type: " + type + " for " + aspectName); if (type.isAspect()) { xcutSet.addOrReplaceAspect(type); } else { throw new RuntimeException("unimplemented"); } } public void addLibraryJarFile(File inFile) throws IOException { ZipInputStream inStream = new ZipInputStream(new FileInputStream(inFile)); //??? buffered List addedAspects = new ArrayList(); while (true) { ZipEntry entry = inStream.getNextEntry(); if (entry == null) break; if (entry.isDirectory() || !entry.getName().endsWith(".class")) { continue; } ClassParser parser = new ClassParser(new ByteArrayInputStream(FileUtil.readAsByteArray(inStream)), entry.getName()); JavaClass jc = parser.parse(); inStream.closeEntry(); ResolvedTypeX type = world.addSourceObjectType(jc).getResolvedTypeX(); if (type.isAspect()) { addedAspects.add(type); } } inStream.close(); for (Iterator i = addedAspects.iterator(); i.hasNext();) { ResolvedTypeX aspectX = (ResolvedTypeX) i.next(); xcutSet.addOrReplaceAspect(aspectX); } } // // The ANT copy task should be used to copy resources across. // private final static boolean CopyResourcesFromInpathDirectoriesToOutput=false; private Set alreadyConfirmedReweavableState; /** * Add any .class files in the directory to the outdir. Anything other than .class files in * the directory (or its subdirectories) are considered resources and are also copied. * */ public List addDirectoryContents(File inFile,File outDir) throws IOException { List addedClassFiles = new ArrayList(); // Get a list of all files (i.e. everything that isnt a directory) File[] files = FileUtil.listFiles(inFile,new FileFilter() { public boolean accept(File f) { boolean accept = !f.isDirectory(); return accept; } }); // For each file, add it either as a real .class file or as a resource for (int i = 0; i < files.length; i++) { addedClassFiles.add(addClassFile(files[i],inFile,outDir)); } return addedClassFiles; } /** Adds all class files in the jar */ public List addJarFile(File inFile, File outDir, boolean canBeDirectory){ // System.err.println("? addJarFile(" + inFile + ", " + outDir + ")"); List addedClassFiles = new ArrayList(); needToReweaveWorld = true; JarInputStream inStream = null; try { // Is this a directory we are looking at? if (inFile.isDirectory() && canBeDirectory) { addedClassFiles.addAll(addDirectoryContents(inFile,outDir)); } else { inStream = new JarInputStream(new FileInputStream(inFile)); //??? buffered addManifest(inStream.getManifest()); while (true) { ZipEntry entry = inStream.getNextEntry(); if (entry == null) break; byte[] bytes = FileUtil.readAsByteArray(inStream); String filename = entry.getName(); UnwovenClassFile classFile = new UnwovenClassFile(new File(outDir, filename).getAbsolutePath(), bytes); if (filename.endsWith(".class")) { this.addClassFile(classFile); addedClassFiles.add(classFile); } // else if (!entry.isDirectory()) { // // /* bug-44190 Copy meta-data */ // addResource(filename,classFile); // } inStream.closeEntry(); } inStream.close(); } } catch (FileNotFoundException ex) { IMessage message = new Message( "Could not find input jar file " + inFile.getPath() + ", ignoring", new SourceLocation(inFile,0), false); world.getMessageHandler().handleMessage(message); } catch (IOException ex) { IMessage message = new Message( "Could not read input jar file " + inFile.getPath() + "(" + ex.getMessage() + ")", new SourceLocation(inFile,0), true); world.getMessageHandler().handleMessage(message); } finally { if (inStream != null) { try {inStream.close();} catch (IOException ex) { IMessage message = new Message( "Could not close input jar file " + inFile.getPath() + "(" + ex.getMessage() + ")", new SourceLocation(inFile,0), true); world.getMessageHandler().handleMessage(message); } } } return addedClassFiles; } // public void addResource(String name, File inPath, File outDir) throws IOException { // // /* Eliminate CVS files. Relative paths use "/" */ // if (!name.startsWith("CVS/") && (-1 == name.indexOf("/CVS/")) && !name.endsWith("/CVS")) { //// System.err.println("? addResource('" + name + "')"); //// BufferedInputStream inStream = new BufferedInputStream(new FileInputStream(inPath)); //// byte[] bytes = new byte[(int)inPath.length()]; //// inStream.read(bytes); //// inStream.close(); // byte[] bytes = FileUtil.readAsByteArray(inPath); // UnwovenClassFile resourceFile = new UnwovenClassFile(new File(outDir, name).getAbsolutePath(), bytes); // addResource(name,resourceFile); // } // } public boolean needToReweaveWorld() { return needToReweaveWorld; } /** Should be addOrReplace */ public void addClassFile(UnwovenClassFile classFile) { addedClasses.add(classFile); // if (null != sourceJavaClasses.put(classFile.getClassName(), classFile)) { //// throw new RuntimeException(classFile.getClassName()); // } world.addSourceObjectType(classFile.getJavaClass()); } public UnwovenClassFile addClassFile(File classFile, File inPathDir, File outDir) throws IOException { FileInputStream fis = new FileInputStream(classFile); byte[] bytes = FileUtil.readAsByteArray(fis); // String relativePath = files[i].getPath(); // ASSERT: files[i].getAbsolutePath().startsWith(inFile.getAbsolutePath() // or we are in trouble... String filename = classFile.getAbsolutePath().substring( inPathDir.getAbsolutePath().length()+1); UnwovenClassFile ucf = new UnwovenClassFile(new File(outDir,filename).getAbsolutePath(),bytes); if (filename.endsWith(".class")) { // System.err.println("BCELWeaver: processing class from input directory "+classFile); this.addClassFile(ucf); } fis.close(); return ucf; } public void deleteClassFile(String typename) { deletedTypenames.add(typename); // sourceJavaClasses.remove(typename); world.deleteSourceObjectType(TypeX.forName(typename)); } // public void addResource (String name, UnwovenClassFile resourceFile) { // /* bug-44190 Change error to warning and copy first resource */ // if (!resources.containsKey(name)) { // resources.put(name, resourceFile); // } // else { // world.showMessage(IMessage.WARNING, "duplicate resource: '" + name + "'", // null, null); // } // } // ---- weave preparation public void prepareForWeave() { needToReweaveWorld = false; // update mungers for (Iterator i = addedClasses.iterator(); i.hasNext(); ) { UnwovenClassFile jc = (UnwovenClassFile)i.next(); String name = jc.getClassName(); ResolvedTypeX type = world.resolve(name); //System.err.println("added: " + type + " aspect? " + type.isAspect()); if (type.isAspect()) { needToReweaveWorld |= xcutSet.addOrReplaceAspect(type); } } for (Iterator i = deletedTypenames.iterator(); i.hasNext(); ) { String name = (String)i.next(); if (xcutSet.deleteAspect(TypeX.forName(name))) needToReweaveWorld = true; } shadowMungerList = xcutSet.getShadowMungers(); typeMungerList = xcutSet.getTypeMungers(); declareParentsList = xcutSet.getDeclareParents(); //XXX this gets us a stable (but completely meaningless) order Collections.sort( shadowMungerList, new Comparator() { public int compare(Object o1, Object o2) { return o1.toString().compareTo(o2.toString()); } }); } // public void dumpUnwoven(File file) throws IOException { // BufferedOutputStream os = FileUtil.makeOutputStream(file); // this.zipOutputStream = new ZipOutputStream(os); // dumpUnwoven(); // /* BUG 40943*/ // dumpResourcesToOutJar(); // zipOutputStream.close(); //this flushes and closes the acutal file // } // // // public void dumpUnwoven() throws IOException { // Collection filesToDump = new HashSet(sourceJavaClasses.values()); // for (Iterator i = filesToDump.iterator(); i.hasNext(); ) { // UnwovenClassFile classFile = (UnwovenClassFile)i.next(); // dumpUnchanged(classFile); // } // } // public void dumpResourcesToOutPath() throws IOException { //// System.err.println("? dumpResourcesToOutPath() resources=" + resources.keySet()); // Iterator i = resources.keySet().iterator(); // while (i.hasNext()) { // UnwovenClassFile res = (UnwovenClassFile)resources.get(i.next()); // dumpUnchanged(res); // } // //resources = new HashMap(); // } // /* BUG #40943 */ // public void dumpResourcesToOutJar() throws IOException { //// System.err.println("? dumpResourcesToOutJar() resources=" + resources.keySet()); // Iterator i = resources.keySet().iterator(); // while (i.hasNext()) { // String name = (String)i.next(); // UnwovenClassFile res = (UnwovenClassFile)resources.get(name); // writeZipEntry(name,res.getBytes()); // } // resources = new HashMap(); // } // // // halfway house for when the jar is managed outside of the weaver, but the resources // // to be copied are known in the weaver. // public void dumpResourcesToOutJar(ZipOutputStream zos) throws IOException { // this.zipOutputStream = zos; // dumpResourcesToOutJar(); // } public void addManifest (Manifest newManifest) { if (manifest == null) { manifest = newManifest; } } private static final String WEAVER_MANIFEST_VERSION = "1.0"; private static final Attributes.Name CREATED_BY = new Name("Created-By"); private static final String WEAVER_CREATED_BY = "AspectJ Compiler"; public Manifest getManifest (boolean shouldCreate) { if (manifest == null && shouldCreate) { manifest = new Manifest(); Attributes attributes = manifest.getMainAttributes(); attributes.put(Name.MANIFEST_VERSION,WEAVER_MANIFEST_VERSION); attributes.put(CREATED_BY,WEAVER_CREATED_BY); } return manifest; } // ---- weaving // Used by some test cases only... public Collection weave(File file) throws IOException { OutputStream os = FileUtil.makeOutputStream(file); this.zipOutputStream = new ZipOutputStream(os); prepareForWeave(); Collection c = weave( new IClassFileProvider() { public Iterator getClassFileIterator() { return addedClasses.iterator(); } public IWeaveRequestor getRequestor() { return new IWeaveRequestor() { public void acceptResult(UnwovenClassFile result) { try { writeZipEntry(result.filename, result.bytes); } catch(IOException ex) {} } public void processingReweavableState() {} public void addingTypeMungers() {} public void weavingAspects() {} public void weavingClasses() {} public void weaveCompleted() {} }; } }); // /* BUG 40943*/ // dumpResourcesToOutJar(); zipOutputStream.close(); //this flushes and closes the acutal file return c; } // public Collection weave() throws IOException { // prepareForWeave(); // Collection filesToWeave; // // if (needToReweaveWorld) { // filesToWeave = sourceJavaClasses.values(); // } else { // filesToWeave = addedClasses; // } // // Collection wovenClassNames = new ArrayList(); // world.showMessage(IMessage.INFO, "might need to weave " + filesToWeave + // "(world=" + needToReweaveWorld + ")", null, null); // // // //System.err.println("typeMungers: " + typeMungerList); // // prepareToProcessReweavableState(); // // clear all state from files we'll be reweaving // for (Iterator i = filesToWeave.iterator(); i.hasNext(); ) { // UnwovenClassFile classFile = (UnwovenClassFile)i.next(); // String className = classFile.getClassName(); // BcelObjectType classType = getClassType(className); // processReweavableStateIfPresent(className, classType); // } // // // // //XXX this isn't quite the right place for this... // for (Iterator i = filesToWeave.iterator(); i.hasNext(); ) { // UnwovenClassFile classFile = (UnwovenClassFile)i.next(); // String className = classFile.getClassName(); // addTypeMungers(className); // } // // // first weave into aspects // for (Iterator i = filesToWeave.iterator(); i.hasNext(); ) { // UnwovenClassFile classFile = (UnwovenClassFile)i.next(); // String className = classFile.getClassName(); // BcelObjectType classType = BcelWorld.getBcelObjectType(world.resolve(className)); // if (classType.isAspect()) { // weave(classFile, classType); // wovenClassNames.add(className); // } // } // // // then weave into non-aspects // for (Iterator i = filesToWeave.iterator(); i.hasNext(); ) { // UnwovenClassFile classFile = (UnwovenClassFile)i.next(); // String className = classFile.getClassName(); // BcelObjectType classType = BcelWorld.getBcelObjectType(world.resolve(className)); // if (! classType.isAspect()) { // weave(classFile, classType); // wovenClassNames.add(className); // } // } // // if (zipOutputStream != null && !needToReweaveWorld) { // Collection filesToDump = new HashSet(sourceJavaClasses.values()); // filesToDump.removeAll(filesToWeave); // for (Iterator i = filesToDump.iterator(); i.hasNext(); ) { // UnwovenClassFile classFile = (UnwovenClassFile)i.next(); // dumpUnchanged(classFile); // } // } // // addedClasses = new ArrayList(); // deletedTypenames = new ArrayList(); // // return wovenClassNames; // } // variation of "weave" that sources class files from an external source. public Collection weave(IClassFileProvider input) throws IOException { Collection wovenClassNames = new ArrayList(); IWeaveRequestor requestor = input.getRequestor(); requestor.processingReweavableState(); prepareToProcessReweavableState(); // clear all state from files we'll be reweaving for (Iterator i = input.getClassFileIterator(); i.hasNext(); ) { UnwovenClassFile classFile = (UnwovenClassFile)i.next(); String className = classFile.getClassName(); BcelObjectType classType = getClassType(className); processReweavableStateIfPresent(className, classType); } requestor.addingTypeMungers(); //XXX this isn't quite the right place for this... for (Iterator i = input.getClassFileIterator(); i.hasNext(); ) { UnwovenClassFile classFile = (UnwovenClassFile)i.next(); String className = classFile.getClassName(); addTypeMungers(className); } requestor.weavingAspects(); // first weave into aspects for (Iterator i = input.getClassFileIterator(); i.hasNext(); ) { UnwovenClassFile classFile = (UnwovenClassFile)i.next(); String className = classFile.getClassName(); BcelObjectType classType = BcelWorld.getBcelObjectType(world.resolve(className)); if (classType.isAspect()) { weaveAndNotify(classFile, classType,requestor); wovenClassNames.add(className); } } requestor.weavingClasses(); // then weave into non-aspects for (Iterator i = input.getClassFileIterator(); i.hasNext(); ) { UnwovenClassFile classFile = (UnwovenClassFile)i.next(); String className = classFile.getClassName(); BcelObjectType classType = BcelWorld.getBcelObjectType(world.resolve(className)); if (! classType.isAspect()) { weaveAndNotify(classFile, classType, requestor); wovenClassNames.add(className); } } addedClasses = new ArrayList(); deletedTypenames = new ArrayList(); requestor.weaveCompleted(); return wovenClassNames; } public void prepareToProcessReweavableState() { if (inReweavableMode) world.showMessage(IMessage.INFO, "weaver operating in reweavable mode. Need to verify any required types exist.", null, null); alreadyConfirmedReweavableState = new HashSet(); } public void processReweavableStateIfPresent(String className, BcelObjectType classType) { // If the class is marked reweavable, check any aspects around when it was built are in this world WeaverStateInfo wsi = classType.getWeaverState(); if (wsi!=null && wsi.isReweavable()) { // Check all necessary types are around! world.showMessage(IMessage.INFO,"processing reweavable type "+className+": "+classType.getSourceLocation().getSourceFile(),null,null); Set aspectsPreviouslyInWorld = wsi.getAspectsAffectingType(); if (aspectsPreviouslyInWorld!=null) { for (Iterator iter = aspectsPreviouslyInWorld.iterator(); iter.hasNext();) { String requiredTypeName = (String) iter.next(); if (!alreadyConfirmedReweavableState.contains(requiredTypeName)) { ResolvedTypeX rtx = world.resolve(TypeX.forName(requiredTypeName),true); boolean exists = rtx!=ResolvedTypeX.MISSING; if (!exists) { world.showMessage(IMessage.ERROR, "type " + requiredTypeName + " is needed by reweavable type " + className, classType.getSourceLocation(), null); } else { if (!world.getMessageHandler().isIgnoring(IMessage.INFO)) world.showMessage(IMessage.INFO,"successfully verified type "+requiredTypeName+ " exists. Originates from "+rtx.getSourceLocation().getSourceFile(),null,null); alreadyConfirmedReweavableState.add(requiredTypeName); } } } } classType.setJavaClass(Utility.makeJavaClass(classType.getJavaClass().getFileName(), wsi.getUnwovenClassFileData())); } else { classType.resetState(); } } private void weaveAndNotify(UnwovenClassFile classFile, BcelObjectType classType, IWeaveRequestor requestor) throws IOException { LazyClassGen clazz = weaveWithoutDump(classFile,classType); classType.finishedWith(); //clazz is null if the classfile was unchanged by weaving... if (clazz != null) { UnwovenClassFile[] newClasses = getClassFilesFor(clazz); for (int i = 0; i < newClasses.length; i++) { requestor.acceptResult(newClasses[i]); } } else { requestor.acceptResult(classFile); } } // helper method public BcelObjectType getClassType(String forClass) { return BcelWorld.getBcelObjectType(world.resolve(forClass)); } public void addTypeMungers(String typeName) { weave(world.resolve(typeName)); } public UnwovenClassFile[] getClassFilesFor(LazyClassGen clazz) { List childClasses = clazz.getChildClasses(world); UnwovenClassFile[] ret = new UnwovenClassFile[1 + childClasses.size()]; ret[0] = new UnwovenClassFile(clazz.getFileName(),clazz.getJavaClass(world).getBytes()); int index = 1; for (Iterator iter = childClasses.iterator(); iter.hasNext();) { UnwovenClassFile.ChildClass element = (UnwovenClassFile.ChildClass) iter.next(); UnwovenClassFile childClass = new UnwovenClassFile(clazz.getFileName() + "$" + element.name, element.bytes); ret[index++] = childClass; } return ret; } public void weave(ResolvedTypeX onType) { onType.clearInterTypeMungers(); // need to do any declare parents before the matching below for (Iterator i = declareParentsList.iterator(); i.hasNext(); ) { DeclareParents p = (DeclareParents)i.next(); List newParents = p.findMatchingNewParents(onType); if (!newParents.isEmpty()) { BcelObjectType classType = BcelWorld.getBcelObjectType(onType); //System.err.println("need to do declare parents for: " + onType); for (Iterator j = newParents.iterator(); j.hasNext(); ) { ResolvedTypeX newParent = (ResolvedTypeX)j.next(); if (newParent.isClass()) { world.showMessage(IMessage.ERROR, "can't use declare parents to change superclass of binary form \'" + onType.getName() + "\' (implementation limitation)", p.getSourceLocation(), null); continue; } classType.addParent(newParent); ResolvedTypeMunger newParentMunger = new NewParentTypeMunger(newParent); onType.addInterTypeMunger(new BcelTypeMunger(newParentMunger, xcutSet.findAspectDeclaringParents(p))); } } } for (Iterator i = typeMungerList.iterator(); i.hasNext(); ) { ConcreteTypeMunger m = (ConcreteTypeMunger)i.next(); if (m.matches(onType)) { onType.addInterTypeMunger(m); } } } // exposed for ClassLoader dynamic weaving public LazyClassGen weaveWithoutDump(UnwovenClassFile classFile, BcelObjectType classType) throws IOException { return weave(classFile, classType, false); } // non-private for testing LazyClassGen weave(UnwovenClassFile classFile, BcelObjectType classType) throws IOException { LazyClassGen ret = weave(classFile, classType, true); if (progressListener != null) { progressMade += progressPerClassFile; progressListener.setProgress(progressMade); progressListener.setText("woven: " + classFile.getFilename()); } return ret; } private LazyClassGen weave(UnwovenClassFile classFile, BcelObjectType classType, boolean dump) throws IOException { if (classType.isSynthetic()) { if (dump) dumpUnchanged(classFile); return null; } // JavaClass javaClass = classType.getJavaClass(); List shadowMungers = fastMatch(shadowMungerList, classType.getResolvedTypeX()); List typeMungers = classType.getResolvedTypeX().getInterTypeMungers(); classType.getResolvedTypeX().checkInterTypeMungers(); LazyClassGen clazz = null; if (shadowMungers.size() > 0 || typeMungers.size() > 0 || classType.isAspect()) { clazz = classType.getLazyClassGen(); //System.err.println("got lazy gen: " + clazz + ", " + clazz.getWeaverState()); try { boolean isChanged = BcelClassWeaver.weave(world, clazz, shadowMungers, typeMungers); if (isChanged) { if (dump) dump(classFile, clazz); return clazz; } } catch (RuntimeException re) { System.err.println("trouble in: "); //XXXclazz.print(System.err); throw re; } catch (Error re) { System.err.println("trouble in: "); clazz.print(System.err); throw re; } } // this is very odd return behavior trying to keep everyone happy if (dump) { dumpUnchanged(classFile); return clazz; } else { return null; } } // ---- writing private void dumpUnchanged(UnwovenClassFile classFile) throws IOException { if (zipOutputStream != null) { writeZipEntry(getEntryName(classFile.getJavaClass().getClassName()), classFile.getBytes()); } else { classFile.writeUnchangedBytes(); } } private String getEntryName(String className) { //XXX what does bcel's getClassName do for inner names return className.replace('.', '/') + ".class"; } private void dump(UnwovenClassFile classFile, LazyClassGen clazz) throws IOException { if (zipOutputStream != null) { String mainClassName = classFile.getJavaClass().getClassName(); writeZipEntry(getEntryName(mainClassName), clazz.getJavaClass(world).getBytes()); if (!clazz.getChildClasses(world).isEmpty()) { for (Iterator i = clazz.getChildClasses(world).iterator(); i.hasNext();) { UnwovenClassFile.ChildClass c = (UnwovenClassFile.ChildClass) i.next(); writeZipEntry(getEntryName(mainClassName + "$" + c.name), c.bytes); } } } else { classFile.writeWovenBytes( clazz.getJavaClass(world).getBytes(), clazz.getChildClasses(world) ); } } private void writeZipEntry(String name, byte[] bytes) throws IOException { ZipEntry newEntry = new ZipEntry(name); //??? get compression scheme right zipOutputStream.putNextEntry(newEntry); zipOutputStream.write(bytes); zipOutputStream.closeEntry(); } private List fastMatch(List list, ResolvedTypeX type) { if (list == null) return Collections.EMPTY_LIST; // here we do the coarsest grained fast match with no kind constraints // this will remove all obvious non-matches and see if we need to do any weaving FastMatchInfo info = new FastMatchInfo(type, null); List result = new ArrayList(); Iterator iter = list.iterator(); while (iter.hasNext()) { ShadowMunger munger = (ShadowMunger)iter.next(); if (munger.getPointcut().fastMatch(info).maybeTrue()) { result.add(munger); } } return result; } public void setProgressListener(IProgressListener listener, double previousProgress, double progressPerClassFile) { progressListener = listener; this.progressMade = previousProgress; this.progressPerClassFile = progressPerClassFile; } public void setReweavableMode(boolean mode,boolean compress) { inReweavableMode = mode; WeaverStateInfo.setReweavableModeDefaults(mode,compress); BcelClassWeaver.setReweavableMode(mode,compress); } public boolean isReweavable() { return inReweavableMode; } }
30,439
Bug 30439 spurious "circular dependency" error
AspectJ Compiler 1.1beta4 This program: aspect Foo { pointcut p1(): execution(void f()) && cflow(execution(void f1())); pointcut p2(): execution(void f()) && cflow(execution(void f2())); before(): p1() { } after(): p1() { } before(): p2() { } after(): p2() { } } class A { void f1() { f(); } void f2() { f(); } void f() { } } results in these errors: circular dependency at method-execution(void A.f()) circular dependency at method-execution(void A.f()) circular dependency at method-execution(void A.f()) circular dependency at method-execution(void A.f()) 4 errors If I comment out any one of the four pieces of advice, all the errors go away. Also, assuming that there is a valid reason for printing this error sometimes, how come there's no line number? --Doug
resolved fixed
4feb835
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2004-07-29T15:04:00Z
2003-01-28T21:40:00Z
weaver/src/org/aspectj/weaver/bcel/ClassPathManager.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Common Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * PARC initial implementation * ******************************************************************/ package org.aspectj.weaver.bcel; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.Enumeration; import java.util.Iterator; import java.util.List; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; import org.aspectj.bridge.IMessageHandler; import org.aspectj.bridge.MessageUtil; import org.aspectj.weaver.TypeX; public class ClassPathManager { private List entries; public ClassPathManager(List classpath, IMessageHandler handler) { entries = new ArrayList(); for (Iterator i = classpath.iterator(); i.hasNext();) { String name = (String) i.next(); addPath(name, handler); } } protected ClassPathManager() {}; public void addPath (String name, IMessageHandler handler) { File f = new File(name); String lc = name.toLowerCase(); if (lc.endsWith(".jar") || lc.endsWith(".zip")) { if (!f.isFile()) { MessageUtil.info(handler, "zipfile classpath entry does not exist: " + name); return; } try { entries.add(new ZipFileEntry(f)); } catch (IOException ioe) { MessageUtil.warn(handler, "zipfile classpath entry is invalid: " + name + "<" + ioe.getMessage() + ">"); return; } } else { if (!f.isDirectory()) { MessageUtil.info(handler, "directory classpath entry does not exist: " + name); return; } entries.add(new DirEntry(f)); } } public ClassFile find(TypeX type) { String name = type.getName(); for (Iterator i = entries.iterator(); i.hasNext(); ) { Entry entry = (Entry)i.next(); ClassFile ret = entry.find(name); if (ret != null) return ret; } return null; } public String toString() { StringBuffer buf = new StringBuffer(); boolean start = true; for (Iterator i = entries.iterator(); i.hasNext(); ) { if (start) { start = false; } else {buf.append(File.pathSeparator); } buf.append(i.next()); } return buf.toString(); } /** * This method is extremely expensive and should only be called rarely */ public List getAllClassFiles() { List ret = new ArrayList(); for (Iterator i = entries.iterator(); i.hasNext(); ) { Entry entry = (Entry)i.next(); ret.addAll(entry.getAllClassFiles()); } return ret; } public abstract static class ClassFile { public abstract InputStream getInputStream() throws IOException; public abstract String getPath(); } public abstract static class Entry { public abstract ClassFile find(String name); public abstract List getAllClassFiles(); } private static class FileClassFile extends ClassFile { private File file; public FileClassFile(File file) { this.file = file; } public InputStream getInputStream() throws IOException { return new FileInputStream(file); } public String getPath() { return file.getPath(); } } public class DirEntry extends Entry { private String dirPath; public DirEntry(File dir) { this.dirPath = dir.getPath(); } public DirEntry(String dirPath) { this.dirPath = dirPath; } public ClassFile find(String name) { File f = new File(dirPath + File.separator + name.replace('.', File.separatorChar) + ".class"); if (f.isFile()) return new FileClassFile(f); else return null; } public List getAllClassFiles() { throw new RuntimeException("unimplemented"); } public String toString() { return dirPath; } } private static class ZipEntryClassFile extends ClassFile { private ZipEntry entry; private ZipFile zipFile; public ZipEntryClassFile(ZipFile zipFile, ZipEntry entry) { this.zipFile = zipFile; this.entry = entry; } public InputStream getInputStream() throws IOException { return zipFile.getInputStream(entry); } public String getPath() { return entry.getName(); } } public class ZipFileEntry extends Entry { private ZipFile zipFile; public ZipFileEntry(File file) throws IOException { this(new ZipFile(file)); } public ZipFileEntry(ZipFile zipFile) { this.zipFile = zipFile; } public ClassFile find(String name) { String key = name.replace('.', '/') + ".class"; ZipEntry entry = zipFile.getEntry(key); if (entry != null) return new ZipEntryClassFile(zipFile, entry); else return null; } public List getAllClassFiles() { List ret = new ArrayList(); for (Enumeration e = zipFile.entries(); e.hasMoreElements(); ) { ZipEntry entry = (ZipEntry)e.nextElement(); String name = entry.getName(); if (hasClassExtension(name)) ret.add(new ZipEntryClassFile(zipFile, entry)); } return ret; } public String toString() { return zipFile.getName(); } } /* private */ static boolean hasClassExtension(String name) { return name.toLowerCase().endsWith((".class")); } }
30,439
Bug 30439 spurious "circular dependency" error
AspectJ Compiler 1.1beta4 This program: aspect Foo { pointcut p1(): execution(void f()) && cflow(execution(void f1())); pointcut p2(): execution(void f()) && cflow(execution(void f2())); before(): p1() { } after(): p1() { } before(): p2() { } after(): p2() { } } class A { void f1() { f(); } void f2() { f(); } void f() { } } results in these errors: circular dependency at method-execution(void A.f()) circular dependency at method-execution(void A.f()) circular dependency at method-execution(void A.f()) circular dependency at method-execution(void A.f()) 4 errors If I comment out any one of the four pieces of advice, all the errors go away. Also, assuming that there is a valid reason for printing this error sometimes, how come there's no line number? --Doug
resolved fixed
4feb835
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2004-07-29T15:04:00Z
2003-01-28T21:40:00Z
weaver/src/org/aspectj/weaver/bcel/LazyClassGen.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Common Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * PARC initial implementation * ******************************************************************/ package org.aspectj.weaver.bcel; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.io.PrintStream; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.SortedMap; import java.util.TreeMap; import org.apache.bcel.Constants; import org.apache.bcel.classfile.Attribute; import org.apache.bcel.classfile.ConstantUtf8; import org.apache.bcel.classfile.Field; import org.apache.bcel.classfile.JavaClass; import org.apache.bcel.classfile.Method; import org.apache.bcel.classfile.Unknown; import org.apache.bcel.generic.ClassGen; import org.apache.bcel.generic.ConstantPoolGen; import org.apache.bcel.generic.FieldGen; import org.apache.bcel.generic.InstructionConstants; import org.apache.bcel.generic.InstructionFactory; import org.apache.bcel.generic.InstructionHandle; import org.apache.bcel.generic.InstructionList; import org.apache.bcel.generic.ObjectType; import org.apache.bcel.generic.PUSH; import org.apache.bcel.generic.RETURN; import org.apache.bcel.generic.Type; import org.aspectj.bridge.IMessage; import org.aspectj.bridge.ISourceLocation; import org.aspectj.util.CollectionUtil; import org.aspectj.weaver.AjAttribute; import org.aspectj.weaver.BCException; import org.aspectj.weaver.Member; import org.aspectj.weaver.NameMangler; import org.aspectj.weaver.ResolvedMember; import org.aspectj.weaver.ResolvedTypeX; import org.aspectj.weaver.Shadow; import org.aspectj.weaver.TypeX; import org.aspectj.weaver.WeaverStateInfo; import org.aspectj.weaver.World; public final class LazyClassGen { // ---- JSR 45 info int highestLineNumber = 0; private SortedMap /* <String, InlinedSourceFileInfo> */ inlinedFiles = new TreeMap(); static class InlinedSourceFileInfo { int highestLineNumber; int offset; // calculated InlinedSourceFileInfo(int highestLineNumber) { this.highestLineNumber = highestLineNumber; } } void addInlinedSourceFileInfo(String fullpath, int highestLineNumber) { Object o = inlinedFiles.get(fullpath); if (o != null) { InlinedSourceFileInfo info = (InlinedSourceFileInfo) o; if (info.highestLineNumber < highestLineNumber) { info.highestLineNumber = highestLineNumber; } } else { inlinedFiles.put(fullpath, new InlinedSourceFileInfo(highestLineNumber)); } } void calculateSourceDebugExtensionOffsets() { int i = roundUpToHundreds(highestLineNumber); for (Iterator iter = inlinedFiles.values().iterator(); iter.hasNext();) { InlinedSourceFileInfo element = (InlinedSourceFileInfo) iter.next(); element.offset = i; i = roundUpToHundreds(i + element.highestLineNumber); } } private static int roundUpToHundreds(int i) { return ((i / 100) + 1) * 100; } int getSourceDebugExtensionOffset(String fullpath) { return ((InlinedSourceFileInfo) inlinedFiles.get(fullpath)).offset; } private Unknown getSourceDebugExtensionAttribute() { int nameIndex = constantPoolGen.addUtf8("SourceDebugExtension"); String data = getSourceDebugExtensionString(); //System.err.println(data); byte[] bytes = Utility.stringToUTF(data); int length = bytes.length; return new Unknown(nameIndex, length, bytes, constantPoolGen.getConstantPool()); } // private LazyClassGen() {} // public static void main(String[] args) { // LazyClassGen m = new LazyClassGen(); // m.highestLineNumber = 37; // m.inlinedFiles.put("boo/baz/foo.java", new InlinedSourceFileInfo( 83)); // m.inlinedFiles.put("boo/barz/foo.java", new InlinedSourceFileInfo(292)); // m.inlinedFiles.put("boo/baz/moo.java", new InlinedSourceFileInfo(128)); // m.calculateSourceDebugExtensionOffsets(); // System.err.println(m.getSourceDebugExtensionString()); // } // For the entire pathname, we're using package names. This is probably wrong. private String getSourceDebugExtensionString() { StringBuffer out = new StringBuffer(); String myFileName = getFileName(); // header section out.append("SMAP\n"); out.append(myFileName); out.append("\nAspectJ\n"); // stratum section out.append("*S AspectJ\n"); // file section out.append("*F\n"); out.append("1 "); out.append(myFileName); out.append("\n"); int i = 2; for (Iterator iter = inlinedFiles.keySet().iterator(); iter.hasNext();) { String element = (String) iter.next(); int ii = element.lastIndexOf('/'); if (ii == -1) { out.append(i++); out.append(' '); out.append(element); out.append('\n'); } else { out.append("+ "); out.append(i++); out.append(' '); out.append(element.substring(ii+1)); out.append('\n'); out.append(element); out.append('\n'); } } // emit line section out.append("*L\n"); out.append("1#1,"); out.append(highestLineNumber); out.append(":1,1\n"); i = 2; for (Iterator iter = inlinedFiles.values().iterator(); iter.hasNext();) { InlinedSourceFileInfo element = (InlinedSourceFileInfo) iter.next(); out.append("1#"); out.append(i++); out.append(','); out.append(element.highestLineNumber); out.append(":"); out.append(element.offset + 1); out.append(",1\n"); } // end section out.append("*E\n"); // and finish up... return out.toString(); } // ---- end JSR45-related stuff /** Emit disassembled class and newline to out */ public static void disassemble(String path, String name, PrintStream out) throws IOException { if (null == out) { return; } //out.println("classPath: " + classPath); BcelWorld world = new BcelWorld(path); LazyClassGen clazz = new LazyClassGen(BcelWorld.getBcelObjectType(world.resolve(name))); clazz.print(out); out.println(); } private BcelObjectType myType; // XXX is not set for types we create private ClassGen myGen; private ConstantPoolGen constantPoolGen; private List /*LazyMethodGen*/ methodGens = new ArrayList(); private List /*LazyClassGen*/ classGens = new ArrayList(); private int childCounter = 0; public int getNewGeneratedNameTag() { return childCounter++; } private InstructionFactory fact; private boolean isSerializable = false; private boolean hasSerialVersionUIDField = false; private boolean hasClinit = false; // ---- public LazyClassGen( String class_name, String super_class_name, String file_name, int access_flags, String[] interfaces) { myGen = new ClassGen(class_name, super_class_name, file_name, access_flags, interfaces); constantPoolGen = myGen.getConstantPool(); fact = new InstructionFactory(myGen, constantPoolGen); } //Non child type, so it comes from a real type in the world. public LazyClassGen(BcelObjectType myType) { myGen = new ClassGen(myType.getJavaClass()); constantPoolGen = myGen.getConstantPool(); fact = new InstructionFactory(myGen, constantPoolGen); this.myType = myType; /* Does this class support serialization */ if (TypeX.SERIALIZABLE.isAssignableFrom(getType(),getType().getWorld())) { isSerializable = true; // ResolvedMember[] fields = getType().getDeclaredFields(); // for (int i = 0; i < fields.length; i++) { // ResolvedMember field = fields[i]; // if (field.getName().equals("serialVersionUID") // && field.isStatic() && field.getType().equals(ResolvedTypeX.LONG)) { // hasSerialVersionUIDField = true; // } // } hasSerialVersionUIDField = hasSerialVersionUIDField(getType()); ResolvedMember[] methods = getType().getDeclaredMethods(); for (int i = 0; i < methods.length; i++) { ResolvedMember method = methods[i]; if (method.getName().equals("<clinit>")) { hasClinit = true; } } } Method[] methods = myGen.getMethods(); for (int i = 0; i < methods.length; i++) { addMethodGen(new LazyMethodGen(methods[i], this)); } } public static boolean hasSerialVersionUIDField (ResolvedTypeX type) { ResolvedMember[] fields = type.getDeclaredFields(); for (int i = 0; i < fields.length; i++) { ResolvedMember field = fields[i]; if (field.getName().equals("serialVersionUID") && field.isStatic() && field.getType().equals(ResolvedTypeX.LONG)) { return true; } } return false; } // public void addAttribute(Attribute i) { // myGen.addAttribute(i); // } // ---- public String getInternalClassName() { return getConstantPoolGen().getConstantPool().getConstantString( myGen.getClassNameIndex(), Constants.CONSTANT_Class); } public String getInternalFileName() { String str = getInternalClassName(); int index = str.lastIndexOf('/'); if (index == -1) { return getFileName(); } else { return str.substring(0, index + 1) + getFileName(); } } public File getPackagePath(File root) { String str = getInternalClassName(); int index = str.lastIndexOf('/'); if (index == -1) return root; return new File(root, str.substring(0, index)); } public String getClassId() { String str = getInternalClassName(); int index = str.lastIndexOf('/'); if (index == -1) return str; return str.substring(index + 1); } public void addMethodGen(LazyMethodGen gen) { //assert gen.getClassName() == super.getClassName(); methodGens.add(gen); if (highestLineNumber < gen.highestLineNumber) highestLineNumber = gen.highestLineNumber; } public void addMethodGen(LazyMethodGen gen, ISourceLocation sourceLocation) { addMethodGen(gen); if (!gen.getMethod().isPrivate()) { warnOnAddedMethod(gen.getMethod(),sourceLocation); } } public void errorOnAddedField (Field field, ISourceLocation sourceLocation) { if (isSerializable && !hasSerialVersionUIDField) { getWorld().getLint().serialVersionUIDBroken.signal( new String[] { myType.getResolvedTypeX().getName().toString(), field.getName() }, sourceLocation, null); } } public void warnOnAddedInterface (String name, ISourceLocation sourceLocation) { warnOnModifiedSerialVersionUID(sourceLocation,"added interface " + name); } public void warnOnAddedMethod (Method method, ISourceLocation sourceLocation) { warnOnModifiedSerialVersionUID(sourceLocation,"added non-private method " + method.getName()); } public void warnOnAddedStaticInitializer (Shadow shadow, ISourceLocation sourceLocation) { if (!hasClinit) { warnOnModifiedSerialVersionUID(sourceLocation,"added static initializer"); } } public void warnOnModifiedSerialVersionUID (ISourceLocation sourceLocation, String reason) { if (isSerializable && !hasSerialVersionUIDField) getWorld().getLint().needsSerialVersionUIDField.signal( new String[] { myType.getResolvedTypeX().getName().toString(), reason }, sourceLocation, null); } public World getWorld () { return myType.getResolvedTypeX().getWorld(); } public List getMethodGens() { return methodGens; //???Collections.unmodifiableList(methodGens); } private void writeBack(BcelWorld world) { if (myType != null && myType.getWeaverState() != null) { myGen.addAttribute(BcelAttributes.bcelAttribute( new AjAttribute.WeaverState(myType.getWeaverState()), getConstantPoolGen())); } addAjcInitializers(); int len = methodGens.size(); myGen.setMethods(new Method[0]); calculateSourceDebugExtensionOffsets(); for (int i = 0; i < len; i++) { LazyMethodGen gen = (LazyMethodGen) methodGens.get(i); // we skip empty clinits if (isEmptyClinit(gen)) continue; myGen.addMethod(gen.getMethod()); } if (inlinedFiles.size() != 0) { if (hasSourceDebugExtensionAttribute(myGen)) { world.showMessage( IMessage.WARNING, "overwriting JSR45 information for " + getFileName() + " (compiler limitation)", null, null); } myGen.addAttribute(getSourceDebugExtensionAttribute()); } } private static boolean hasSourceDebugExtensionAttribute(ClassGen gen) { ConstantPoolGen pool = gen.getConstantPool(); Attribute[] attrs = gen.getAttributes(); for (int i = 0; i < attrs.length; i++) { if ("SourceDebugExtension" .equals(((ConstantUtf8) pool.getConstant(attrs[i].getNameIndex())).getBytes())) { return true; } } return false; } public JavaClass getJavaClass(BcelWorld world) { writeBack(world); return myGen.getJavaClass(); } public void addGeneratedInner(LazyClassGen newClass) { classGens.add(newClass); } public void addInterface(TypeX typeX, ISourceLocation sourceLocation) { myGen.addInterface(typeX.getName()); warnOnAddedInterface(typeX.getName(),sourceLocation); } public void setSuperClass(TypeX typeX) { myGen.setSuperclassName(typeX.getName()); } // non-recursive, may be a bug, ha ha. private List getClassGens() { List ret = new ArrayList(); ret.add(this); ret.addAll(classGens); return ret; } public List getChildClasses(BcelWorld world) { if (classGens.isEmpty()) return Collections.EMPTY_LIST; List ret = new ArrayList(); for (Iterator i = classGens.iterator(); i.hasNext();) { LazyClassGen clazz = (LazyClassGen) i.next(); byte[] bytes = clazz.getJavaClass(world).getBytes(); String name = clazz.getName(); int index = name.lastIndexOf('$'); // XXX this could be bad, check use of dollar signs. name = name.substring(index+1); ret.add(new UnwovenClassFile.ChildClass(name, bytes)); } return ret; } public String toString() { return toShortString(); } public String toShortString() { String s = org.apache.bcel.classfile.Utility.accessToString(myGen.getAccessFlags(), true); if (s != "") s += " "; s += org.apache.bcel.classfile.Utility.classOrInterface(myGen.getAccessFlags()); s += " "; s += myGen.getClassName(); return s; } public String toLongString() { ByteArrayOutputStream s = new ByteArrayOutputStream(); print(new PrintStream(s)); return new String(s.toByteArray()); } public void print() { print(System.out); } public void print(PrintStream out) { List classGens = getClassGens(); for (Iterator iter = classGens.iterator(); iter.hasNext();) { LazyClassGen element = (LazyClassGen) iter.next(); element.printOne(out); if (iter.hasNext()) out.println(); } } private void printOne(PrintStream out) { out.print(toShortString()); out.print(" extends "); out.print( org.apache.bcel.classfile.Utility.compactClassName( myGen.getSuperclassName(), false)); int size = myGen.getInterfaces().length; if (size > 0) { out.print(" implements "); for (int i = 0; i < size; i++) { out.print(myGen.getInterfaceNames()[i]); if (i < size - 1) out.print(", "); } } out.print(":"); out.println(); // XXX make sure to pass types correctly around, so this doesn't happen. if (myType != null) { myType.printWackyStuff(out); } Field[] fields = myGen.getFields(); for (int i = 0, len = fields.length; i < len; i++) { out.print(" "); out.println(fields[i]); } List methodGens = getMethodGens(); for (Iterator iter = methodGens.iterator(); iter.hasNext();) { LazyMethodGen gen = (LazyMethodGen) iter.next(); // we skip empty clinits if (isEmptyClinit(gen)) continue; gen.print(out); if (iter.hasNext()) out.println(); } // out.println(" ATTRIBS: " + Arrays.asList(myGen.getAttributes())); out.println("end " + toShortString()); } private boolean isEmptyClinit(LazyMethodGen gen) { if (!gen.getName().equals("<clinit>")) return false; //System.err.println("checking clinig: " + gen); InstructionHandle start = gen.getBody().getStart(); while (start != null) { if (Range.isRangeHandle(start) || (start.getInstruction() instanceof RETURN)) { start = start.getNext(); } else { return false; } } return true; } public ConstantPoolGen getConstantPoolGen() { return constantPoolGen; } public String getName() { return myGen.getClassName(); } public boolean isWoven() { return myType.getWeaverState() != null; } public boolean isReweavable() { if (myType.getWeaverState()==null) return false; return myType.getWeaverState().isReweavable(); } public Set getAspectsAffectingType() { if (myType.getWeaverState()==null) return null; return myType.getWeaverState().getAspectsAffectingType(); } public WeaverStateInfo getOrCreateWeaverStateInfo() { WeaverStateInfo ret = myType.getWeaverState(); if (ret != null) return ret; ret = new WeaverStateInfo(); myType.setWeaverState(ret); return ret; } public InstructionFactory getFactory() { return fact; } public LazyMethodGen getStaticInitializer() { for (Iterator i = methodGens.iterator(); i.hasNext();) { LazyMethodGen gen = (LazyMethodGen) i.next(); if (gen.getName().equals("<clinit>")) return gen; } LazyMethodGen clinit = new LazyMethodGen( Modifier.STATIC, Type.VOID, "<clinit>", new Type[0], CollectionUtil.NO_STRINGS, this); clinit.getBody().insert(InstructionConstants.RETURN); methodGens.add(clinit); return clinit; } public LazyMethodGen getAjcPreClinit() { for (Iterator i = methodGens.iterator(); i.hasNext();) { LazyMethodGen gen = (LazyMethodGen) i.next(); if (gen.getName().equals(NameMangler.AJC_PRE_CLINIT_NAME)) return gen; } LazyMethodGen ajcClinit = new LazyMethodGen( Modifier.STATIC, Type.VOID, NameMangler.AJC_PRE_CLINIT_NAME, new Type[0], CollectionUtil.NO_STRINGS, this); ajcClinit.getBody().insert(InstructionConstants.RETURN); methodGens.add(ajcClinit); getStaticInitializer().getBody().insert(Utility.createInvoke(getFactory(), ajcClinit)); return ajcClinit; } // reflective thisJoinPoint support Map/*BcelShadow, Field*/ tjpFields = new HashMap(); public static final ObjectType tjpType = new ObjectType("org.aspectj.lang.JoinPoint"); public static final ObjectType staticTjpType = new ObjectType("org.aspectj.lang.JoinPoint$StaticPart"); private static final ObjectType sigType = new ObjectType("org.aspectj.lang.Signature"); // private static final ObjectType slType = // new ObjectType("org.aspectj.lang.reflect.SourceLocation"); private static final ObjectType factoryType = new ObjectType("org.aspectj.runtime.reflect.Factory"); private static final ObjectType classType = new ObjectType("java.lang.Class"); public Field getTjpField(BcelShadow shadow) { Field ret = (Field)tjpFields.get(shadow); if (ret != null) return ret; int modifiers = Modifier.STATIC | Modifier.FINAL; if (getType().isInterface()) { modifiers |= Modifier.PUBLIC; } else { modifiers |= Modifier.PRIVATE; } ret = new FieldGen(modifiers, staticTjpType, "ajc$tjp_" + tjpFields.size(), getConstantPoolGen()).getField(); addField(ret); tjpFields.put(shadow, ret); return ret; } private void addAjcInitializers() { if (tjpFields.size() == 0) return; InstructionList il = initializeAllTjps(); getStaticInitializer().getBody().insert(il); } private InstructionList initializeAllTjps() { InstructionList list = new InstructionList(); InstructionFactory fact = getFactory(); // make a new factory list.append(fact.createNew(factoryType)); list.append(InstructionFactory.createDup(1)); list.append(new PUSH(getConstantPoolGen(), getFileName())); // load the current Class object //XXX check that this works correctly for inners/anonymous list.append(new PUSH(getConstantPoolGen(), getClassName())); //XXX do we need to worry about the fact the theorectically this could throw //a ClassNotFoundException list.append(fact.createInvoke("java.lang.Class", "forName", classType, new Type[] {Type.STRING}, Constants.INVOKESTATIC)); list.append(fact.createInvoke(factoryType.getClassName(), "<init>", Type.VOID, new Type[] {Type.STRING, classType}, Constants.INVOKESPECIAL)); list.append(InstructionFactory.createStore(factoryType, 0)); List entries = new ArrayList(tjpFields.entrySet()); Collections.sort(entries, new Comparator() { public int compare(Object a, Object b) { Map.Entry ae = (Map.Entry) a; Map.Entry be = (Map.Entry) b; return ((Field) ae.getValue()) .getName() .compareTo(((Field)be.getValue()).getName()); } }); for (Iterator i = entries.iterator(); i.hasNext(); ) { Map.Entry entry = (Map.Entry)i.next(); initializeTjp(fact, list, (Field)entry.getValue(), (BcelShadow)entry.getKey()); } return list; } private void initializeTjp(InstructionFactory fact, InstructionList list, Field field, BcelShadow shadow) { Member sig = shadow.getSignature(); //ResolvedMember mem = shadow.getSignature().resolve(shadow.getWorld()); // load the factory list.append(InstructionFactory.createLoad(factoryType, 0)); // load the kind list.append(new PUSH(getConstantPoolGen(), shadow.getKind().getName())); // create the signature list.append(InstructionFactory.createLoad(factoryType, 0)); list.append(new PUSH(getConstantPoolGen(), sig.getSignatureString(shadow.getWorld()))); list.append(fact.createInvoke(factoryType.getClassName(), sig.getSignatureMakerName(), new ObjectType(sig.getSignatureType()), new Type[] { Type.STRING }, Constants.INVOKEVIRTUAL)); //XXX should load source location from shadow list.append(Utility.createConstant(fact, shadow.getSourceLine())); list.append(fact.createInvoke(factoryType.getClassName(), "makeSJP", staticTjpType, new Type[] { Type.STRING, sigType, Type.INT}, Constants.INVOKEVIRTUAL)); // put it in the field list.append(fact.createFieldAccess(getClassName(), field.getName(), staticTjpType, Constants.PUTSTATIC)); } public ResolvedTypeX getType() { if (myType == null) return null; return myType.getResolvedTypeX(); } public BcelObjectType getBcelObjectType() { return myType; } public String getFileName() { return myGen.getFileName(); } private void addField(Field field) { myGen.addField(field); } public void addField(Field field, ISourceLocation sourceLocation) { addField(field); if (!(field.isPrivate() && (field.isStatic() || field.isTransient()))) { errorOnAddedField(field,sourceLocation); } } public String getClassName() { return myGen.getClassName(); } public boolean isInterface() { return myGen.isInterface(); } public LazyMethodGen getLazyMethodGen(Member m) { return getLazyMethodGen(m.getName(), m.getSignature()); } public LazyMethodGen getLazyMethodGen(String name, String signature) { for (Iterator i = methodGens.iterator(); i.hasNext();) { LazyMethodGen gen = (LazyMethodGen) i.next(); if (gen.getName().equals(name) && gen.getSignature().equals(signature)) return gen; } throw new BCException("Class " + this.getName() + " does not have a method " + name + " with signature " + signature); } public void forcePublic() { myGen.setAccessFlags(Utility.makePublic(myGen.getAccessFlags())); } }
30,439
Bug 30439 spurious "circular dependency" error
AspectJ Compiler 1.1beta4 This program: aspect Foo { pointcut p1(): execution(void f()) && cflow(execution(void f1())); pointcut p2(): execution(void f()) && cflow(execution(void f2())); before(): p1() { } after(): p1() { } before(): p2() { } after(): p2() { } } class A { void f1() { f(); } void f2() { f(); } void f() { } } results in these errors: circular dependency at method-execution(void A.f()) circular dependency at method-execution(void A.f()) circular dependency at method-execution(void A.f()) circular dependency at method-execution(void A.f()) 4 errors If I comment out any one of the four pieces of advice, all the errors go away. Also, assuming that there is a valid reason for printing this error sometimes, how come there's no line number? --Doug
resolved fixed
4feb835
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2004-07-29T15:04:00Z
2003-01-28T21:40:00Z
weaver/src/org/aspectj/weaver/bcel/LazyMethodGen.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Common Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * PARC initial implementation * ******************************************************************/ package org.aspectj.weaver.bcel; import java.io.ByteArrayOutputStream; import java.io.PrintStream; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; import java.util.Stack; import org.apache.bcel.Constants; import org.apache.bcel.classfile.Attribute; import org.apache.bcel.classfile.ConstantPool; import org.apache.bcel.classfile.Method; import org.apache.bcel.classfile.Synthetic; import org.apache.bcel.generic.BranchHandle; import org.apache.bcel.generic.BranchInstruction; import org.apache.bcel.generic.CPInstruction; import org.apache.bcel.generic.ClassGenException; import org.apache.bcel.generic.CodeExceptionGen; import org.apache.bcel.generic.ConstantPoolGen; import org.apache.bcel.generic.Instruction; import org.apache.bcel.generic.InstructionHandle; import org.apache.bcel.generic.InstructionList; import org.apache.bcel.generic.InstructionTargeter; import org.apache.bcel.generic.LineNumberGen; import org.apache.bcel.generic.LocalVariableGen; import org.apache.bcel.generic.LocalVariableInstruction; import org.apache.bcel.generic.MethodGen; import org.apache.bcel.generic.ObjectType; import org.apache.bcel.generic.Select; import org.apache.bcel.generic.Type; import org.aspectj.bridge.IMessage; import org.aspectj.weaver.AjAttribute; import org.aspectj.weaver.BCException; import org.aspectj.weaver.ISourceContext; import org.aspectj.weaver.Member; import org.aspectj.weaver.ResolvedTypeX; /** * A LazyMethodGen should be treated as a MethodGen. It's our way of abstracting over the * low-level Method objects. It converts through {@link MethodGen} to create * and to serialize, but that's it. * * <p> At any rate, there are two ways to create LazyMethodGens. * One is from a method, which * does work through MethodGen to do the correct thing. * The other is the creation of a completely empty * LazyMethodGen, and it is used when we're constructing code from scratch. * * <p> We stay away from targeters for rangey things like Shadows and Exceptions. */ public final class LazyMethodGen { private int accessFlags; private Type returnType; private final String name; private Type[] argumentTypes; //private final String[] argumentNames; private String[] declaredExceptions; private InstructionList body; // leaving null for abstracts private Attribute[] attributes; /* private */ final LazyClassGen enclosingClass; private final BcelMethod memberView; int highestLineNumber = 0; /** This is nonnull if this method is the result of an "inlining". We currently * copy methods into other classes for around advice. We add this field so * we can get JSR45 information correct. If/when we do _actual_ inlining, * we'll need to subtype LineNumberTag to have external line numbers. */ String fromFilename = null; private int maxLocals; private boolean canInline = true; private boolean hasExceptionHandlers; private boolean isSynthetic = false; /** * only used by {@link BcelClassWeaver} */ List /*ShadowMungers*/ matchedShadows; // Used for interface introduction // this is the type of the interface the method is technically on public ResolvedTypeX definingType = null; public LazyMethodGen( int accessFlags, Type returnType, String name, Type[] paramTypes, String[] declaredExceptions, LazyClassGen enclosingClass) { //System.err.println("raw create of: " + name + ", " + enclosingClass.getName() + ", " + returnType); this.memberView = null; // ??? should be okay, since constructed ones aren't woven into this.accessFlags = accessFlags; this.returnType = returnType; this.name = name; this.argumentTypes = paramTypes; //this.argumentNames = Utility.makeArgNames(paramTypes.length); this.declaredExceptions = declaredExceptions; if (!Modifier.isAbstract(accessFlags)) { body = new InstructionList(); setMaxLocals(calculateMaxLocals()); } else { body = null; } this.attributes = new Attribute[0]; this.enclosingClass = enclosingClass; assertGoodBody(); } private int calculateMaxLocals() { int ret = 0; if (!Modifier.isStatic(accessFlags)) ret++; for (int i = 0, len = argumentTypes.length; i < len; i++) { ret += argumentTypes[i].getSize(); } return ret; } private Method savedMethod = null; // build from an existing method, lazy build saves most work for initialization public LazyMethodGen(Method m, LazyClassGen enclosingClass) { savedMethod = m; this.enclosingClass = enclosingClass; if (!(m.isAbstract() || m.isNative()) && m.getCode() == null) { throw new RuntimeException("bad non-abstract method with no code: " + m + " on " + enclosingClass); } if ((m.isAbstract() || m.isNative()) && m.getCode() != null) { throw new RuntimeException("bad abstract method with code: " + m + " on " + enclosingClass); } this.memberView = new BcelMethod(enclosingClass.getBcelObjectType(), m); this.accessFlags = m.getAccessFlags(); this.name = m.getName(); } private void initialize() { if (returnType != null) return; //System.err.println("initializing: " + getName() + ", " + enclosingClass.getName() + ", " + returnType + ", " + savedMethod); MethodGen gen = new MethodGen(savedMethod, enclosingClass.getName(), enclosingClass.getConstantPoolGen()); this.returnType = gen.getReturnType(); this.argumentTypes = gen.getArgumentTypes(); this.declaredExceptions = gen.getExceptions(); this.attributes = gen.getAttributes(); this.maxLocals = gen.getMaxLocals(); // this.returnType = BcelWorld.makeBcelType(memberView.getReturnType()); // this.argumentTypes = BcelWorld.makeBcelTypes(memberView.getParameterTypes()); // // this.declaredExceptions = TypeX.getNames(memberView.getExceptions()); //gen.getExceptions(); // this.attributes = new Attribute[0]; //gen.getAttributes(); // this.maxLocals = savedMethod.getCode().getMaxLocals(); if (gen.isAbstract() || gen.isNative()) { body = null; } else { //body = new InstructionList(savedMethod.getCode().getCode()); body = gen.getInstructionList(); unpackHandlers(gen); unpackLineNumbers(gen); unpackLocals(gen); } assertGoodBody(); //System.err.println("initialized: " + this.getClassName() + "." + this.getName()); } // XXX we're relying on the javac promise I've just made up that we won't have an early exception // in the list mask a later exception: That is, for two exceptions E and F, // if E preceeds F, then either E \cup F = {}, or E \nonstrictsubset F. So when we add F, // we add it on the _OUTSIDE_ of any handlers that share starts or ends with it. // with that in mind, we merrily go adding ranges for exceptions. private void unpackHandlers(MethodGen gen) { CodeExceptionGen[] exns = gen.getExceptionHandlers(); if (exns != null) { int len = exns.length; if (len > 0) hasExceptionHandlers = true; int priority = len - 1; for (int i = 0; i < len; i++, priority--) { CodeExceptionGen exn = exns[i]; InstructionHandle start = Range.genStart( body, getOutermostExceptionStart(exn.getStartPC())); InstructionHandle end = Range.genEnd(body, getOutermostExceptionEnd(exn.getEndPC())); // this doesn't necessarily handle overlapping correctly!!! ExceptionRange er = new ExceptionRange( body, exn.getCatchType() == null ? null : BcelWorld.fromBcel(exn.getCatchType()), priority); er.associateWithTargets(start, end, exn.getHandlerPC()); exn.setStartPC(null); // also removes from target exn.setEndPC(null); // also removes from target exn.setHandlerPC(null); // also removes from target } gen.removeExceptionHandlers(); } } private InstructionHandle getOutermostExceptionStart(InstructionHandle ih) { while (true) { if (ExceptionRange.isExceptionStart(ih.getPrev())) { ih = ih.getPrev(); } else { return ih; } } } private InstructionHandle getOutermostExceptionEnd(InstructionHandle ih) { while (true) { if (ExceptionRange.isExceptionEnd(ih.getNext())) { ih = ih.getNext(); } else { return ih; } } } private void unpackLineNumbers(MethodGen gen) { LineNumberTag lr = null; for (InstructionHandle ih = body.getStart(); ih != null; ih = ih.getNext()) { InstructionTargeter[] targeters = ih.getTargeters(); if (targeters != null) { for (int i = targeters.length - 1; i >= 0; i--) { InstructionTargeter targeter = targeters[i]; if (targeter instanceof LineNumberGen) { LineNumberGen lng = (LineNumberGen) targeter; lng.updateTarget(ih, null); int lineNumber = lng.getSourceLine(); if (highestLineNumber < lineNumber) highestLineNumber = lineNumber; lr = new LineNumberTag(lineNumber); } } } if (lr != null) { ih.addTargeter(lr); } } gen.removeLineNumbers(); } private void unpackLocals(MethodGen gen) { Set locals = new HashSet(); for (InstructionHandle ih = body.getStart(); ih != null; ih = ih.getNext()) { InstructionTargeter[] targeters = ih.getTargeters(); List ends = new ArrayList(0); if (targeters != null) { for (int i = targeters.length - 1; i >= 0; i--) { InstructionTargeter targeter = targeters[i]; if (targeter instanceof LocalVariableGen) { LocalVariableGen lng = (LocalVariableGen) targeter; LocalVariableTag lr = new LocalVariableTag(BcelWorld.fromBcel(lng.getType()), lng.getName(), lng.getIndex()); if (lng.getStart() == ih) { locals.add(lr); } else { ends.add(lr); } } } } for (Iterator i = locals.iterator(); i.hasNext(); ) { ih.addTargeter((LocalVariableTag) i.next()); } locals.removeAll(ends); } gen.removeLocalVariables(); } // =============== public int allocateLocal(Type type) { return allocateLocal(type.getSize()); } public int allocateLocal(int slots) { int max = getMaxLocals(); setMaxLocals(max + slots); return max; } public Method getMethod() { if (savedMethod != null) return savedMethod; //??? this relies on gentle treatment of constant pool try { MethodGen gen = pack(); return gen.getMethod(); } catch (ClassGenException e) { enclosingClass.getBcelObjectType().getResolvedTypeX().getWorld().showMessage( IMessage.ERROR, "problem generating method " + this.getClassName() + "." + this.getName() + ": " + e.getMessage(), this.getMemberView() == null ? null : this.getMemberView().getSourceLocation(), null); throw e; } } public void markAsChanged() { initialize(); savedMethod = null; } // ============================= public String toString() { return toLongString(); } public String toShortString() { String access = org.apache.bcel.classfile.Utility.accessToString(getAccessFlags()); StringBuffer buf = new StringBuffer(); if (!access.equals("")) { buf.append(access); buf.append(" "); } buf.append( org.apache.bcel.classfile.Utility.signatureToString( getReturnType().getSignature(), true)); buf.append(" "); buf.append(getName()); buf.append("("); { int len = argumentTypes.length; if (len > 0) { buf.append( org.apache.bcel.classfile.Utility.signatureToString( argumentTypes[0].getSignature(), true)); for (int i = 1; i < argumentTypes.length; i++) { buf.append(", "); buf.append( org.apache.bcel.classfile.Utility.signatureToString( argumentTypes[i].getSignature(), true)); } } } buf.append(")"); { int len = declaredExceptions != null ? declaredExceptions.length : 0; if (len > 0) { buf.append(" throws "); buf.append(declaredExceptions[0]); for (int i = 1; i < declaredExceptions.length; i++) { buf.append(", "); buf.append(declaredExceptions[i]); } } } return buf.toString(); } public String toLongString() { ByteArrayOutputStream s = new ByteArrayOutputStream(); print(new PrintStream(s)); return new String(s.toByteArray()); } public void print() { print(System.out); } public void print(PrintStream out) { out.print(" " + toShortString()); printAspectAttributes(out); InstructionList body = getBody(); if (body == null) { out.println(";"); return; } out.println(":"); new BodyPrinter(out).run(); out.println(" end " + toShortString()); } private void printAspectAttributes(PrintStream out) { ISourceContext context = null; if (enclosingClass != null && enclosingClass.getType() != null) { context = enclosingClass.getType().getSourceContext(); } List as = BcelAttributes.readAjAttributes(attributes, context); if (! as.isEmpty()) { out.println(" " + as.get(0)); // XXX assuming exactly one attribute, munger... } } private class BodyPrinter { Map prefixMap = new HashMap(); Map suffixMap = new HashMap(); Map labelMap = new HashMap(); InstructionList body; PrintStream out; ConstantPool pool; List ranges; BodyPrinter(PrintStream out) { this.pool = enclosingClass.getConstantPoolGen().getConstantPool(); this.body = getBody(); this.out = out; } void run() { //killNops(); assignLabels(); print(); } // label assignment void assignLabels() { LinkedList exnTable = new LinkedList(); String pendingLabel = null; // boolean hasPendingTargeters = false; int lcounter = 0; for (InstructionHandle ih = body.getStart(); ih != null; ih = ih.getNext()) { InstructionTargeter[] targeters = ih.getTargeters(); if (targeters != null) { for (int i = targeters.length - 1; i >= 0; i--) { InstructionTargeter t = targeters[i]; if (t instanceof ExceptionRange) { // assert isRangeHandle(h); ExceptionRange r = (ExceptionRange) t; if (r.getStart() == ih) { insertHandler(r, exnTable); } } else if (t instanceof BranchInstruction) { if (pendingLabel == null) { pendingLabel = "L" + lcounter++; } } else { // assert isRangeHandle(h) } } } if (pendingLabel != null) { labelMap.put(ih, pendingLabel); if (! Range.isRangeHandle(ih)) { pendingLabel = null; } } } int ecounter = 0; for (Iterator i = exnTable.iterator(); i.hasNext();) { ExceptionRange er = (ExceptionRange) i.next(); String exceptionLabel = "E" + ecounter++; labelMap.put(Range.getRealStart(er.getHandler()), exceptionLabel); labelMap.put(er.getHandler(), exceptionLabel); } } // printing void print() { int depth = 0; int currLine = -1; bodyPrint: for (InstructionHandle ih = body.getStart(); ih != null; ih = ih.getNext()) { if (Range.isRangeHandle(ih)) { Range r = Range.getRange(ih); // don't print empty ranges, that is, ranges who contain no actual instructions for (InstructionHandle xx = r.getStart(); Range.isRangeHandle(xx); xx = xx.getNext()) { if (xx == r.getEnd()) continue bodyPrint; } // doesn't handle nested: if (r.getStart().getNext() == r.getEnd()) continue; if (r.getStart() == ih) { printRangeString(r, depth++); } else { if (r.getEnd() != ih) throw new RuntimeException("bad"); printRangeString(r, --depth); } } else { printInstruction(ih, depth); int line = getLineNumber(ih, currLine); if (line != currLine) { currLine = line; out.println(" (line " + line + ")"); } else { out.println(); } } } } void printRangeString(Range r, int depth) { printDepth(depth); out.println(getRangeString(r, labelMap)); } String getRangeString(Range r, Map labelMap) { if (r instanceof ExceptionRange) { ExceptionRange er = (ExceptionRange) r; return er.toString() + " -> " + labelMap.get(er.getHandler()); // // + " PRI " + er.getPriority(); } else { return r.toString(); } } void printDepth(int depth) { pad(BODY_INDENT); while (depth > 0) { out.print("| "); depth--; } } void printLabel(String s, int depth) { int space = Math.max(CODE_INDENT - depth * 2, 0); if (s == null) { pad(space); } else { space = Math.max(space - (s.length() + 2), 0); pad(space); out.print(s); out.print(": "); } } void printInstruction(InstructionHandle h, int depth) { printDepth(depth); printLabel((String) labelMap.get(h), depth); Instruction inst = h.getInstruction(); if (inst instanceof CPInstruction) { CPInstruction cpinst = (CPInstruction) inst; out.print(Constants.OPCODE_NAMES[cpinst.getOpcode()].toUpperCase()); out.print(" "); out.print(pool.constantToString(pool.getConstant(cpinst.getIndex()))); } else if (inst instanceof Select) { Select sinst = (Select) inst; out.println(Constants.OPCODE_NAMES[sinst.getOpcode()].toUpperCase()); int[] matches = sinst.getMatchs(); InstructionHandle[] targets = sinst.getTargets(); InstructionHandle defaultTarget = sinst.getTarget(); for (int i = 0, len = matches.length; i < len; i++) { printDepth(depth); printLabel(null, depth); out.print(" "); out.print(matches[i]); out.print(": \t"); out.println(labelMap.get(targets[i])); } printDepth(depth); printLabel(null, depth); out.print(" "); out.print("default: \t"); out.print(labelMap.get(defaultTarget)); } else if (inst instanceof BranchInstruction) { BranchInstruction brinst = (BranchInstruction) inst; out.print(Constants.OPCODE_NAMES[brinst.getOpcode()].toUpperCase()); out.print(" "); out.print(labelMap.get(brinst.getTarget())); } else if (inst instanceof LocalVariableInstruction) { LocalVariableInstruction lvinst = (LocalVariableInstruction) inst; out.print(inst.toString(false).toUpperCase()); int index = lvinst.getIndex(); LocalVariableTag tag = getLocalVariableTag(h, index); if (tag != null) { out.print(" // "); out.print(tag.getType()); out.print(" "); out.print(tag.getName()); } } else { out.print(inst.toString(false).toUpperCase()); } } static final int BODY_INDENT = 4; static final int CODE_INDENT = 16; void pad(int size) { for (int i = 0; i < size; i++) { out.print(" "); } } } static LocalVariableTag getLocalVariableTag( InstructionHandle ih, int index) { InstructionTargeter[] targeters = ih.getTargeters(); if (targeters == null) return null; for (int i = targeters.length - 1; i >= 0; i--) { InstructionTargeter t = targeters[i]; if (t instanceof LocalVariableTag) { LocalVariableTag lvt = (LocalVariableTag) t; if (lvt.getSlot() == index) return lvt; } } return null; } static int getLineNumber( InstructionHandle ih, int prevLine) { InstructionTargeter[] targeters = ih.getTargeters(); if (targeters == null) return prevLine; for (int i = targeters.length - 1; i >= 0; i--) { InstructionTargeter t = targeters[i]; if (t instanceof LineNumberTag) { return ((LineNumberTag)t).getLineNumber(); } } return prevLine; } public boolean isStatic() { return Modifier.isStatic(getAccessFlags()); } public boolean isAbstract() { return Modifier.isAbstract(getAccessFlags()); } public void addExceptionHandler( InstructionHandle start, InstructionHandle end, InstructionHandle handlerStart, ObjectType catchType, boolean highPriority) { InstructionHandle start1 = Range.genStart(body, start); InstructionHandle end1 = Range.genEnd(body, end); ExceptionRange er = new ExceptionRange(body, BcelWorld.fromBcel(catchType), highPriority); er.associateWithTargets(start1, end1, handlerStart); } public int getAccessFlags() { return accessFlags; } public Type[] getArgumentTypes() { initialize(); return argumentTypes; } public LazyClassGen getEnclosingClass() { return enclosingClass; } public int getMaxLocals() { return maxLocals; } public String getName() { return name; } public Type getReturnType() { initialize(); return returnType; } public void setMaxLocals(int maxLocals) { this.maxLocals = maxLocals; } public InstructionList getBody() { markAsChanged(); return body; } public boolean hasBody() { if (savedMethod != null) return savedMethod.getCode() != null; return body != null; } public Attribute[] getAttributes() { return attributes; } public String[] getDeclaredExceptions() { return declaredExceptions; } public String getClassName() { return enclosingClass.getName(); } // ---- packing! public MethodGen pack() { //killNops(); MethodGen gen = new MethodGen( getAccessFlags(), getReturnType(), getArgumentTypes(), null, //getArgumentNames(), getName(), getEnclosingClass().getName(), new InstructionList(), getEnclosingClass().getConstantPoolGen()); for (int i = 0, len = declaredExceptions.length; i < len; i++) { gen.addException(declaredExceptions[i]); } for (int i = 0, len = attributes.length; i < len; i++) { gen.addAttribute(attributes[i]); } if (isSynthetic) { ConstantPoolGen cpg = gen.getConstantPool(); int index = cpg.addUtf8("Synthetic"); gen.addAttribute(new Synthetic(index, 0, new byte[0], cpg.getConstantPool())); } if (hasBody()) { packBody(gen); gen.setMaxLocals(); gen.setMaxStack(); } else { gen.setInstructionList(null); } return gen; } public void makeSynthetic() { isSynthetic = true; } /** fill the newly created method gen with our body, * inspired by InstructionList.copy() */ public void packBody(MethodGen gen) { HashMap map = new HashMap(); InstructionList fresh = gen.getInstructionList(); /* Make copies of all instructions, append them to the new list * and associate old instruction references with the new ones, i.e., * a 1:1 mapping. */ for (InstructionHandle ih = getBody().getStart(); ih != null; ih = ih.getNext()) { if (Range.isRangeHandle(ih)) { continue; } Instruction i = ih.getInstruction(); Instruction c = Utility.copyInstruction(i); if (c instanceof BranchInstruction) map.put(ih, fresh.append((BranchInstruction) c)); else map.put(ih, fresh.append(c)); } // at this point, no rangeHandles are in fresh. Let's use that... /* Update branch targets and insert various attributes. * Insert our exceptionHandlers * into a sorted list, so they can be added in order later. */ InstructionHandle ih = getBody().getStart(); InstructionHandle jh = fresh.getStart(); LinkedList exnList = new LinkedList(); // map from localvariabletag to instruction handle Map localVariableStarts = new HashMap(); Map localVariableEnds = new HashMap(); int currLine = -1; while (ih != null) { if (map.get(ih) == null) { // we're a range instruction Range r = Range.getRange(ih); if (r instanceof ExceptionRange) { ExceptionRange er = (ExceptionRange) r; if (er.getStart() == ih) { //System.err.println("er " + er); if (!er.isEmpty()){ // order is important, insert handlers in order of start insertHandler(er, exnList); } } } else { // we must be a shadow range or something equally useless, // so forget about doing anything } // just increment ih. ih = ih.getNext(); } else { // assert map.get(ih) == jh Instruction i = ih.getInstruction(); Instruction j = jh.getInstruction(); if (i instanceof BranchInstruction) { BranchInstruction bi = (BranchInstruction) i; BranchInstruction bj = (BranchInstruction) j; InstructionHandle itarget = bi.getTarget(); // old target // try { // New target is in hash map bj.setTarget(remap(itarget, map)); // } catch (NullPointerException e) { // print(); // System.out.println("Was trying to remap " + bi); // System.out.println("who's target was supposedly " + itarget); // throw e; // } if (bi instanceof Select) { // Either LOOKUPSWITCH or TABLESWITCH InstructionHandle[] itargets = ((Select) bi).getTargets(); InstructionHandle[] jtargets = ((Select) bj).getTargets(); for (int k = itargets.length - 1; k >= 0; k--) { // Update all targets jtargets[k] = remap(itargets[k], map); jtargets[k].addTargeter(bj); } } } // now deal with line numbers // and store up info for local variables InstructionTargeter[] targeters = ih.getTargeters(); int lineNumberOffset = (fromFilename == null) ? 0 : getEnclosingClass().getSourceDebugExtensionOffset(fromFilename); if (targeters != null) { for (int k = targeters.length - 1; k >= 0; k--) { InstructionTargeter targeter = targeters[k]; if (targeter instanceof LineNumberTag) { int line = ((LineNumberTag)targeter).getLineNumber(); if (line != currLine) { gen.addLineNumber(jh, line + lineNumberOffset); currLine = line; } } else if (targeter instanceof LocalVariableTag) { LocalVariableTag lvt = (LocalVariableTag) targeter; if (localVariableStarts.get(lvt) == null) { localVariableStarts.put(lvt, jh); } localVariableEnds.put(lvt, jh); } } } // now continue ih = ih.getNext(); jh = jh.getNext(); } } // now add exception handlers for (Iterator iter = exnList.iterator(); iter.hasNext();) { ExceptionRange r = (ExceptionRange) iter.next(); if (r.isEmpty()) continue; gen.addExceptionHandler( remap(r.getRealStart(), map), remap(r.getRealEnd(), map), remap(r.getHandler(), map), (r.getCatchType() == null) ? null : (ObjectType) BcelWorld.makeBcelType(r.getCatchType())); } // now add local variables gen.removeLocalVariables(); // this next iteration _might_ be overkill, but we had problems with // bcel before with duplicate local variables. Now that we're patching // bcel we should be able to do without it if we're paranoid enough // through the rest of the compiler. Map duplicatedLocalMap = new HashMap(); List keys = new ArrayList(); keys.addAll(localVariableStarts.keySet()); for (Iterator iter = keys.iterator(); iter.hasNext(); ) { LocalVariableTag tag = (LocalVariableTag) iter.next(); // have we already added one with the same slot number and start location? // if so, just continue. InstructionHandle start = (InstructionHandle) localVariableStarts.get(tag); Set slots = (Set) duplicatedLocalMap.get(start); if (slots == null) { slots = new HashSet(); duplicatedLocalMap.put(start, slots); } if (slots.contains(new Integer(tag.getSlot()))) { // we already have a var starting at this tag with this slot continue; } slots.add(new Integer(tag.getSlot())); gen.addLocalVariable( tag.getName(), BcelWorld.makeBcelType(tag.getType()), tag.getSlot(), (InstructionHandle) localVariableStarts.get(tag), (InstructionHandle) localVariableEnds.get(tag)); } } /** This proedure should not currently be used. */ // public void killNops() { // InstructionHandle curr = body.getStart(); // while (true) { // if (curr == null) break; // InstructionHandle next = curr.getNext(); // if (curr.getInstruction() instanceof NOP) { // InstructionTargeter[] targeters = curr.getTargeters(); // if (targeters != null) { // for (int i = 0, len = targeters.length; i < len; i++) { // InstructionTargeter targeter = targeters[i]; // targeter.updateTarget(curr, next); // } // } // try { // body.delete(curr); // } catch (TargetLostException e) { // } // } // curr = next; // } // } private static InstructionHandle remap(InstructionHandle ih, Map map) { while (true) { Object ret = map.get(ih); if (ret == null) { ih = ih.getNext(); } else { return (InstructionHandle) ret; } } } // exception ordering. // What we should be doing is dealing with priority inversions way earlier than we are // and counting on the tree structure. In which case, the below code is in fact right. // XXX THIS COMMENT BELOW IS CURRENTLY WRONG. // An exception A preceeds an exception B in the exception table iff: // * A and B were in the original method, and A preceeded B in the original exception table // * If A has a higher priority than B, than it preceeds B. // * If A and B have the same priority, then the one whose START happens EARLIEST has LEAST priority. // in short, the outermost exception has least priority. // we implement this with a LinkedList. We could possibly implement this with a java.util.SortedSet, // but I don't trust the only implementation, TreeSet, to do the right thing. /* private */ static void insertHandler(ExceptionRange fresh, LinkedList l) { // for (ListIterator iter = l.listIterator(); iter.hasNext();) { // ExceptionRange r = (ExceptionRange) iter.next(); // if (fresh.getPriority() >= r.getPriority()) { // iter.previous(); // iter.add(fresh); // return; // } // } l.add(0, fresh); } public boolean isPrivate() { return Modifier.isPrivate(getAccessFlags()); } // ---- /** A good body is a body with the following properties: * * <ul> * <li> For each branch instruction S in body, target T of S is in body. * <li> For each branch instruction S in body, target T of S has S as a targeter. * <li> For each instruction T in body, for each branch instruction S that is a * targeter of T, S is in body. * <li> For each non-range-handle instruction T in body, for each instruction S * that is a targeter of T, S is * either a branch instruction, an exception range or a tag * <li> For each range-handle instruction T in body, there is exactly one targeter S * that is a range. * <li> For each range-handle instruction T in body, the range R targeting T is in body. * <li> For each instruction T in body, for each exception range R targeting T, R is * in body. * <li> For each exception range R in body, let T := R.handler. T is in body, and R is one * of T's targeters * <li> All ranges are properly nested: For all ranges Q and R, if Q.start preceeds * R.start, then R.end preceeds Q.end. * </ul> * * Where the shorthand "R is in body" means "R.start is in body, R.end is in body, and * any InstructionHandle stored in a field of R (such as an exception handle) is in body". */ public void assertGoodBody() { if (true) return; // only enable for debugging, consider using cheaper toString() assertGoodBody(getBody(), toString()); //definingType.getNameAsIdentifier() + "." + getName()); //toString()); } public static void assertGoodBody(InstructionList il, String from) { if (true) return; // only to be enabled for debugging if (il == null) return; Set body = new HashSet(); Stack ranges = new Stack(); for (InstructionHandle ih = il.getStart(); ih != null; ih = ih.getNext()) { body.add(ih); if (ih.getInstruction() instanceof BranchInstruction) { body.add(ih.getInstruction()); } } for (InstructionHandle ih = il.getStart(); ih != null; ih = ih.getNext()) { assertGoodHandle(ih, body, ranges, from); InstructionTargeter[] ts = ih.getTargeters(); if (ts != null) { for (int i = ts.length - 1; i >= 0; i--) { assertGoodTargeter(ts[i], ih, body, from); } } } } private static void assertGoodHandle(InstructionHandle ih, Set body, Stack ranges, String from) { Instruction inst = ih.getInstruction(); if ((inst instanceof BranchInstruction) ^ (ih instanceof BranchHandle)) { throw new BCException("bad instruction/handle pair in " + from); } if (Range.isRangeHandle(ih)) { assertGoodRangeHandle(ih, body, ranges, from); } else if (inst instanceof BranchInstruction) { assertGoodBranchInstruction((BranchHandle) ih, (BranchInstruction) inst, body, ranges, from); } } private static void assertGoodBranchInstruction( BranchHandle ih, BranchInstruction inst, Set body, Stack ranges, String from) { if (ih.getTarget() != inst.getTarget()) { throw new BCException("bad branch instruction/handle pair in " + from); } InstructionHandle target = ih.getTarget(); assertInBody(target, body, from); assertTargetedBy(target, inst, from); if (inst instanceof Select) { Select sel = (Select) inst; InstructionHandle[] itargets = sel.getTargets(); for (int k = itargets.length - 1; k >= 0; k--) { assertInBody(itargets[k], body, from); assertTargetedBy(itargets[k], inst, from); } } } /** ih is an InstructionHandle or a BranchInstruction */ private static void assertInBody(Object ih, Set body, String from) { if (! body.contains(ih)) throw new BCException("thing not in body in " + from); } private static void assertGoodRangeHandle(InstructionHandle ih, Set body, Stack ranges, String from) { Range r = getRangeAndAssertExactlyOne(ih, from); assertGoodRange(r, body, from); if (r.getStart() == ih) { ranges.push(r); } else if (r.getEnd() == ih) { if (ranges.peek() != r) throw new BCException("bad range inclusion in " + from); ranges.pop(); } } private static void assertGoodRange(Range r, Set body, String from) { assertInBody(r.getStart(), body, from); assertRangeHandle(r.getStart(), from); assertTargetedBy(r.getStart(), r, from); assertInBody(r.getEnd(), body, from); assertRangeHandle(r.getEnd(), from); assertTargetedBy(r.getEnd(), r, from); if (r instanceof ExceptionRange) { ExceptionRange er = (ExceptionRange) r; assertInBody(er.getHandler(), body, from); assertTargetedBy(er.getHandler(), r, from); } } private static void assertRangeHandle(InstructionHandle ih, String from) { if (! Range.isRangeHandle(ih)) throw new BCException("bad range handle " + ih + " in " + from); } private static void assertTargetedBy( InstructionHandle target, InstructionTargeter targeter, String from) { InstructionTargeter[] ts = target.getTargeters(); if (ts == null) throw new BCException("bad targeting relationship in " + from); for (int i = ts.length - 1; i >= 0; i--) { if (ts[i] == targeter) return; } throw new RuntimeException("bad targeting relationship in " + from); } private static void assertTargets(InstructionTargeter targeter, InstructionHandle target, String from) { if (targeter instanceof Range) { Range r = (Range) targeter; if (r.getStart() == target || r.getEnd() == target) return; if (r instanceof ExceptionRange) { if (((ExceptionRange)r).getHandler() == target) return; } } else if (targeter instanceof BranchInstruction) { BranchInstruction bi = (BranchInstruction) targeter; if (bi.getTarget() == target) return; if (targeter instanceof Select) { Select sel = (Select) targeter; InstructionHandle[] itargets = sel.getTargets(); for (int k = itargets.length - 1; k >= 0; k--) { if (itargets[k] == target) return; } } } else if (targeter instanceof Tag) { return; } throw new BCException(targeter + " doesn't target " + target + " in " + from ); } private static Range getRangeAndAssertExactlyOne(InstructionHandle ih, String from) { Range ret = null; InstructionTargeter[] ts = ih.getTargeters(); if (ts == null) throw new BCException("range handle with no range in " + from); for (int i = ts.length - 1; i >= 0; i--) { if (ts[i] instanceof Range) { if (ret != null) throw new BCException("range handle with multiple ranges in " + from); ret = (Range) ts[i]; } } if (ret == null) throw new BCException("range handle with no range in " + from); return ret; } private static void assertGoodTargeter( InstructionTargeter t, InstructionHandle ih, Set body, String from) { assertTargets(t, ih, from); if (t instanceof Range) { assertGoodRange((Range) t, body, from); } else if (t instanceof BranchInstruction) { assertInBody(t, body, from); } } // ---- boolean isAdviceMethod() { return memberView.getAssociatedShadowMunger() != null; } boolean isAjSynthetic() { if (memberView == null) return true; return memberView.isAjSynthetic(); } public AjAttribute.EffectiveSignatureAttribute getEffectiveSignature() { //if (memberView == null) return null; return memberView.getEffectiveSignature(); } public String getSignature() { if (memberView!=null) return memberView.getSignature(); return Member.typesToSignature(BcelWorld.fromBcel(getReturnType()), BcelWorld.fromBcel(getArgumentTypes())); } public BcelMethod getMemberView() { return memberView; } public void forcePublic() { markAsChanged(); accessFlags = Utility.makePublic(accessFlags); } public boolean getCanInline() { return canInline; } public void setCanInline(boolean canInline) { this.canInline = canInline; } }
30,439
Bug 30439 spurious "circular dependency" error
AspectJ Compiler 1.1beta4 This program: aspect Foo { pointcut p1(): execution(void f()) && cflow(execution(void f1())); pointcut p2(): execution(void f()) && cflow(execution(void f2())); before(): p1() { } after(): p1() { } before(): p2() { } after(): p2() { } } class A { void f1() { f(); } void f2() { f(); } void f() { } } results in these errors: circular dependency at method-execution(void A.f()) circular dependency at method-execution(void A.f()) circular dependency at method-execution(void A.f()) circular dependency at method-execution(void A.f()) 4 errors If I comment out any one of the four pieces of advice, all the errors go away. Also, assuming that there is a valid reason for printing this error sometimes, how come there's no line number? --Doug
resolved fixed
4feb835
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2004-07-29T15:04:00Z
2003-01-28T21:40:00Z
weaver/src/org/aspectj/weaver/patterns/ArgsPointcut.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Common Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * PARC initial implementation * ******************************************************************/ package org.aspectj.weaver.patterns; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.util.Collection; import java.util.Iterator; import org.aspectj.bridge.IMessage; import org.aspectj.bridge.ISourceLocation; import org.aspectj.bridge.Message; import org.aspectj.lang.JoinPoint; import org.aspectj.lang.reflect.CodeSignature; import org.aspectj.util.FuzzyBoolean; import org.aspectj.weaver.BetaException; import org.aspectj.weaver.ISourceContext; import org.aspectj.weaver.IntMap; import org.aspectj.weaver.ResolvedTypeX; import org.aspectj.weaver.Shadow; import org.aspectj.weaver.TypeX; import org.aspectj.weaver.ast.Literal; import org.aspectj.weaver.ast.Test; /** * args(arguments) * * @author Erik Hilsdale * @author Jim Hugunin */ public class ArgsPointcut extends NameBindingPointcut { TypePatternList arguments; public ArgsPointcut(TypePatternList arguments) { this.arguments = arguments; } public FuzzyBoolean fastMatch(FastMatchInfo type) { return FuzzyBoolean.MAYBE; } public FuzzyBoolean match(Shadow shadow) { FuzzyBoolean ret = arguments.matches(shadow.getIWorld().resolve(shadow.getArgTypes()), TypePattern.DYNAMIC); return ret; } public FuzzyBoolean match(JoinPoint jp, JoinPoint.StaticPart jpsp) { FuzzyBoolean ret = arguments.matches(jp.getArgs(),TypePattern.DYNAMIC); // this may have given a false match (e.g. args(int) may have matched a call to doIt(Integer x)) due to boxing // check for this... if (ret == FuzzyBoolean.YES) { // are the sigs compatible too... CodeSignature sig = (CodeSignature)jp.getSignature(); Class[] pTypes = sig.getParameterTypes(); Collection tps = arguments.getExactTypes(); int sigIndex = 0; for (Iterator iter = tps.iterator(); iter.hasNext();) { TypeX tp = (TypeX) iter.next(); Class lookForClass = getPossiblyBoxed(tp); if (lookForClass != null) { boolean foundMatchInSig = false; while (sigIndex < pTypes.length && !foundMatchInSig) { if (pTypes[sigIndex++] == lookForClass) foundMatchInSig = true; } if (!foundMatchInSig) { ret = FuzzyBoolean.NO; break; } } } } return ret; } private Class getPossiblyBoxed(TypeX tp) { Class ret = (Class) ExactTypePattern.primitiveTypesMap.get(tp.getName()); if (ret == null) ret = (Class) ExactTypePattern.boxedPrimitivesMap.get(tp.getName()); return ret; } public void write(DataOutputStream s) throws IOException { s.writeByte(Pointcut.ARGS); arguments.write(s); writeLocation(s); } public static Pointcut read(DataInputStream s, ISourceContext context) throws IOException { ArgsPointcut ret = new ArgsPointcut(TypePatternList.read(s, context)); ret.readLocation(context, s); return ret; } public boolean equals(Object other) { if (!(other instanceof ArgsPointcut)) return false; ArgsPointcut o = (ArgsPointcut)other; return o.arguments.equals(this.arguments); } public int hashCode() { return arguments.hashCode(); } public void resolveBindings(IScope scope, Bindings bindings) { arguments.resolveBindings(scope, bindings, true, true); if (arguments.ellipsisCount > 1) { scope.message(IMessage.ERROR, this, "uses more than one .. in args (compiler limitation)"); } } public void resolveBindingsFromRTTI() { arguments.resolveBindingsFromRTTI(true, true); if (arguments.ellipsisCount > 1) { throw new UnsupportedOperationException("uses more than one .. in args (compiler limitation)"); } } public void postRead(ResolvedTypeX enclosingType) { arguments.postRead(enclosingType); } public Pointcut concretize1(ResolvedTypeX inAspect, IntMap bindings) { if (isDeclare(bindings.getEnclosingAdvice())) { // Enforce rule about which designators are supported in declare inAspect.getWorld().showMessage(IMessage.ERROR, "args() pointcut designator cannot be used in declare statement", bindings.getEnclosingAdvice().getSourceLocation(), null); return Pointcut.makeMatchesNothing(Pointcut.CONCRETE); } TypePatternList args = arguments.resolveReferences(bindings); if (inAspect.crosscuttingMembers != null) { inAspect.crosscuttingMembers.exposeTypes(args.getExactTypes()); } return new ArgsPointcut(args); } private Test findResidueNoEllipsis(Shadow shadow, ExposedState state, TypePattern[] patterns) { int len = shadow.getArgCount(); //System.err.println("boudn to : " + len + ", " + patterns.length); if (patterns.length != len) { return Literal.FALSE; } Test ret = Literal.TRUE; for (int i=0; i < len; i++) { TypeX argType = shadow.getArgType(i); TypePattern type = patterns[i]; if (!(type instanceof BindingTypePattern)) { if (type.matchesInstanceof(shadow.getIWorld().resolve(argType)).alwaysTrue()) { continue; } } else { BindingTypePattern btp = (BindingTypePattern)type; // Check if we have already bound something to this formal if (state.get(btp.getFormalIndex())!=null) { ISourceLocation isl = getSourceLocation(); Message errorMessage = new Message( "Ambiguous binding of type "+type.getExactType().toString()+ " using args(..) at this line. Use one args(..) per matched join point,"+"" + " see secondary source location for location of extraneous args(..)", shadow.getSourceLocation(),true,new ISourceLocation[]{getSourceLocation()}); shadow.getIWorld().getMessageHandler().handleMessage(errorMessage); } } ret = Test.makeAnd(ret, exposeStateForVar(shadow.getArgVar(i), type, state,shadow.getIWorld())); } return ret; } public Test findResidue(Shadow shadow, ExposedState state) { if (arguments.matches(shadow.getIWorld().resolve(shadow.getArgTypes()), TypePattern.DYNAMIC).alwaysFalse()) { return Literal.FALSE; } int ellipsisCount = arguments.ellipsisCount; if (ellipsisCount == 0) { return findResidueNoEllipsis(shadow, state, arguments.getTypePatterns()); } else if (ellipsisCount == 1) { TypePattern[] patternsWithEllipsis = arguments.getTypePatterns(); TypePattern[] patternsWithoutEllipsis = new TypePattern[shadow.getArgCount()]; int lenWithEllipsis = patternsWithEllipsis.length; int lenWithoutEllipsis = patternsWithoutEllipsis.length; // l1+1 >= l0 int indexWithEllipsis = 0; int indexWithoutEllipsis = 0; while (indexWithoutEllipsis < lenWithoutEllipsis) { TypePattern p = patternsWithEllipsis[indexWithEllipsis++]; if (p == TypePattern.ELLIPSIS) { int newLenWithoutEllipsis = lenWithoutEllipsis - (lenWithEllipsis-indexWithEllipsis); while (indexWithoutEllipsis < newLenWithoutEllipsis) { patternsWithoutEllipsis[indexWithoutEllipsis++] = TypePattern.ANY; } } else { patternsWithoutEllipsis[indexWithoutEllipsis++] = p; } } return findResidueNoEllipsis(shadow, state, patternsWithoutEllipsis); } else { throw new BetaException("unimplemented"); } } public String toString() { return "args" + arguments.toString() + ""; } }
30,439
Bug 30439 spurious "circular dependency" error
AspectJ Compiler 1.1beta4 This program: aspect Foo { pointcut p1(): execution(void f()) && cflow(execution(void f1())); pointcut p2(): execution(void f()) && cflow(execution(void f2())); before(): p1() { } after(): p1() { } before(): p2() { } after(): p2() { } } class A { void f1() { f(); } void f2() { f(); } void f() { } } results in these errors: circular dependency at method-execution(void A.f()) circular dependency at method-execution(void A.f()) circular dependency at method-execution(void A.f()) circular dependency at method-execution(void A.f()) 4 errors If I comment out any one of the four pieces of advice, all the errors go away. Also, assuming that there is a valid reason for printing this error sometimes, how come there's no line number? --Doug
resolved fixed
4feb835
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2004-07-29T15:04:00Z
2003-01-28T21:40:00Z
weaver/src/org/aspectj/weaver/patterns/CflowPointcut.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Common Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * PARC initial implementation * ******************************************************************/ package org.aspectj.weaver.patterns; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.Collection; import java.util.List; import org.aspectj.bridge.IMessage; import org.aspectj.util.FileUtil; import org.aspectj.util.FuzzyBoolean; import org.aspectj.weaver.Advice; import org.aspectj.weaver.CrosscuttingMembers; import org.aspectj.weaver.ISourceContext; import org.aspectj.weaver.IntMap; import org.aspectj.weaver.Member; import org.aspectj.weaver.NameMangler; import org.aspectj.weaver.ResolvedMember; import org.aspectj.weaver.ResolvedPointcutDefinition; import org.aspectj.weaver.ResolvedTypeX; import org.aspectj.weaver.Shadow; import org.aspectj.weaver.TypeX; import org.aspectj.weaver.World; import org.aspectj.weaver.ast.Test; public class CflowPointcut extends Pointcut { private Pointcut entry; private boolean isBelow; private int[] freeVars; /** * Used to indicate that we're in the context of a cflow when concretizing if's * * Will be removed or replaced with something better when we handle this * as a non-error */ public static final ResolvedPointcutDefinition CFLOW_MARKER = new ResolvedPointcutDefinition(null, 0, null, TypeX.NONE, Pointcut.makeMatchesNothing(Pointcut.RESOLVED)); public CflowPointcut(Pointcut entry, boolean isBelow, int[] freeVars) { this.entry = entry; this.isBelow = isBelow; this.freeVars = freeVars; } public FuzzyBoolean fastMatch(FastMatchInfo type) { return FuzzyBoolean.MAYBE; } public FuzzyBoolean match(Shadow shadow) { //??? this is not maximally efficient return FuzzyBoolean.MAYBE; } public void write(DataOutputStream s) throws IOException { s.writeByte(Pointcut.CFLOW); entry.write(s); s.writeBoolean(isBelow); FileUtil.writeIntArray(freeVars, s); writeLocation(s); } public static Pointcut read(DataInputStream s, ISourceContext context) throws IOException { CflowPointcut ret = new CflowPointcut(Pointcut.read(s, context), s.readBoolean(), FileUtil.readIntArray(s)); ret.readLocation(context, s); return ret; } public void resolveBindings(IScope scope, Bindings bindings) { if (bindings == null) { entry.resolveBindings(scope, null); entry.state = RESOLVED; freeVars = new int[0]; } else { //??? for if's sake we might need to be more careful here Bindings entryBindings = new Bindings(bindings.size()); entry.resolveBindings(scope, entryBindings); entry.state = RESOLVED; freeVars = entryBindings.getUsedFormals(); bindings.mergeIn(entryBindings, scope); } } public void resolveBindingsFromRTTI() { if (entry.state != RESOLVED) { entry.resolveBindingsFromRTTI(); } } public boolean equals(Object other) { if (!(other instanceof CflowPointcut)) return false; CflowPointcut o = (CflowPointcut)other; return o.entry.equals(this.entry) && o.isBelow == this.isBelow; } public int hashCode() { int result = 17; result = 37*result + entry.hashCode(); result = 37*result + (isBelow ? 0 : 1); return result; } public String toString() { return "cflow" + (isBelow ? "below" : "") + "(" + entry + ")"; } public Test findResidue(Shadow shadow, ExposedState state) { throw new RuntimeException("unimplemented"); } public Pointcut concretize1(ResolvedTypeX inAspect, IntMap bindings) { if (isDeclare(bindings.getEnclosingAdvice())) { // Enforce rule about which designators are supported in declare inAspect.getWorld().showMessage(IMessage.ERROR, "cflow"+(isBelow?"below":"")+"() pointcut designator cannot be used in declare statement", bindings.getEnclosingAdvice().getSourceLocation(), null); return Pointcut.makeMatchesNothing(Pointcut.CONCRETE); } //make this remap from formal positions to arrayIndices IntMap entryBindings = new IntMap(); for (int i=0, len=freeVars.length; i < len; i++) { int freeVar = freeVars[i]; //int formalIndex = bindings.get(freeVar); entryBindings.put(freeVar, i); } entryBindings.copyContext(bindings); //System.out.println(this + " bindings: " + entryBindings); World world = inAspect.getWorld(); Pointcut concreteEntry; ResolvedTypeX concreteAspect = bindings.getConcreteAspect(); CrosscuttingMembers xcut = concreteAspect.crosscuttingMembers; Collection previousCflowEntries = xcut.getCflowEntries(); entryBindings.pushEnclosingDefinition(CFLOW_MARKER); try { concreteEntry = entry.concretize(inAspect, entryBindings); } finally { entryBindings.popEnclosingDefinitition(); } List innerCflowEntries = new ArrayList(xcut.getCflowEntries()); innerCflowEntries.removeAll(previousCflowEntries); ResolvedMember cflowField = new ResolvedMember( Member.FIELD, concreteAspect, Modifier.STATIC | Modifier.PUBLIC | Modifier.FINAL, NameMangler.cflowStack(xcut), TypeX.forName(NameMangler.CFLOW_STACK_TYPE).getSignature()); //System.out.println("adding field to: " + inAspect + " field " + cflowField); // add field and initializer to inAspect //XXX and then that info above needs to be mapped down here to help with //XXX getting the exposed state right concreteAspect.crosscuttingMembers.addConcreteShadowMunger( Advice.makeCflowEntry(world, concreteEntry, isBelow, cflowField, freeVars.length, innerCflowEntries,inAspect)); concreteAspect.crosscuttingMembers.addTypeMunger( world.makeCflowStackFieldAdder(cflowField)); List slots = new ArrayList(); for (int i=0, len=freeVars.length; i < len; i++) { int freeVar = freeVars[i]; // we don't need to keep state that isn't actually exposed to advice //??? this means that we will store some state that we won't actually use, optimize this later if (!bindings.hasKey(freeVar)) continue; int formalIndex = bindings.get(freeVar); ResolvedTypeX formalType = bindings.getAdviceSignature().getParameterTypes()[formalIndex].resolve(world); ConcreteCflowPointcut.Slot slot = new ConcreteCflowPointcut.Slot(formalIndex, formalType, i); slots.add(slot); } return new ConcreteCflowPointcut(cflowField, slots); } }
30,439
Bug 30439 spurious "circular dependency" error
AspectJ Compiler 1.1beta4 This program: aspect Foo { pointcut p1(): execution(void f()) && cflow(execution(void f1())); pointcut p2(): execution(void f()) && cflow(execution(void f2())); before(): p1() { } after(): p1() { } before(): p2() { } after(): p2() { } } class A { void f1() { f(); } void f2() { f(); } void f() { } } results in these errors: circular dependency at method-execution(void A.f()) circular dependency at method-execution(void A.f()) circular dependency at method-execution(void A.f()) circular dependency at method-execution(void A.f()) 4 errors If I comment out any one of the four pieces of advice, all the errors go away. Also, assuming that there is a valid reason for printing this error sometimes, how come there's no line number? --Doug
resolved fixed
4feb835
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2004-07-29T15:04:00Z
2003-01-28T21:40:00Z
weaver/src/org/aspectj/weaver/patterns/DeclareParents.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Common Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * PARC initial implementation * ******************************************************************/ package org.aspectj.weaver.patterns; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.List; import org.aspectj.bridge.IMessage; import org.aspectj.weaver.ISourceContext; import org.aspectj.weaver.ResolvedTypeX; import org.aspectj.weaver.TypeX; import org.aspectj.weaver.World; public class DeclareParents extends Declare { private TypePattern child; private TypePatternList parents; public DeclareParents(TypePattern child, List parents) { this(child, new TypePatternList(parents)); } private DeclareParents(TypePattern child, TypePatternList parents) { this.child = child; this.parents = parents; } public boolean match(ResolvedTypeX typeX) { if (!child.matchesStatically(typeX)) return false; if (typeX.getWorld().getLint().typeNotExposedToWeaver.isEnabled() && !typeX.isExposedToWeaver()) { typeX.getWorld().getLint().typeNotExposedToWeaver.signal(typeX.getName(), getSourceLocation()); } return true; } public String toString() { StringBuffer buf = new StringBuffer(); buf.append("declare parents: "); buf.append(child); buf.append(" extends "); //extends and implements are treated equivalently buf.append(parents); buf.append(";"); return buf.toString(); } public boolean equals(Object other) { if (!(other instanceof DeclareParents)) return false; DeclareParents o = (DeclareParents)other; return o.child.equals(child) && o.parents.equals(parents); } //??? cache this public int hashCode() { int result = 23; result = 37*result + child.hashCode(); result = 37*result + parents.hashCode(); return result; } public void write(DataOutputStream s) throws IOException { s.writeByte(Declare.PARENTS); child.write(s); parents.write(s); writeLocation(s); } public static Declare read(DataInputStream s, ISourceContext context) throws IOException { Declare ret = new DeclareParents(TypePattern.read(s, context), TypePatternList.read(s, context)); ret.readLocation(context, s); return ret; } public void resolve(IScope scope) { child = child.resolveBindings(scope, Bindings.NONE, false, false); parents = parents.resolveBindings(scope, Bindings.NONE, false, true); // for (int i=0; i < parents.size(); i++) { // parents.get(i).assertExactType(scope.getMessageHandler()); // } } public TypePatternList getParents() { return parents; } public TypePattern getChild() { return child; } public boolean isAdviceLike() { return false; } private ResolvedTypeX maybeGetNewParent(ResolvedTypeX targetType, TypePattern typePattern, World world) { if (typePattern == TypePattern.NO) return null; // already had an error here TypeX iType = typePattern.getExactType(); ResolvedTypeX parentType = iType.resolve(world); if (targetType.equals(world.resolve(TypeX.OBJECT))) { world.showMessage(IMessage.ERROR, "can't change the parents of java.lang.Object", this.getSourceLocation(), null); return null; } if (parentType.isAssignableFrom(targetType)) return null; // already a parent if (targetType.isAssignableFrom(parentType)) { world.showMessage(IMessage.ERROR, "type \'" + targetType.getName() + "\'can not extend itself", this.getSourceLocation(), null ); return null; } if (parentType.isClass()) { if (targetType.isInterface()) { world.showMessage(IMessage.ERROR, "interface can not extend a class", this.getSourceLocation(), null ); return null; // how to handle xcutting errors??? } if (!targetType.getSuperclass().isAssignableFrom(parentType)) { world.showMessage(IMessage.ERROR, "can only insert a class into hierarchy, but " + iType.getName() + " is not a subtype of " + targetType.getSuperclass().getName(), this.getSourceLocation(), null ); return null; } else { return parentType; } } else { return parentType; } } public List/*<ResolvedTypeX>*/ findMatchingNewParents(ResolvedTypeX onType) { if (!match(onType)) return Collections.EMPTY_LIST; List ret = new ArrayList(); for (int i=0; i < parents.size(); i++) { ResolvedTypeX t = maybeGetNewParent(onType, parents.get(i), onType.getWorld()); if (t != null) ret.add(t); } return ret; } }
30,439
Bug 30439 spurious "circular dependency" error
AspectJ Compiler 1.1beta4 This program: aspect Foo { pointcut p1(): execution(void f()) && cflow(execution(void f1())); pointcut p2(): execution(void f()) && cflow(execution(void f2())); before(): p1() { } after(): p1() { } before(): p2() { } after(): p2() { } } class A { void f1() { f(); } void f2() { f(); } void f() { } } results in these errors: circular dependency at method-execution(void A.f()) circular dependency at method-execution(void A.f()) circular dependency at method-execution(void A.f()) circular dependency at method-execution(void A.f()) 4 errors If I comment out any one of the four pieces of advice, all the errors go away. Also, assuming that there is a valid reason for printing this error sometimes, how come there's no line number? --Doug
resolved fixed
4feb835
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2004-07-29T15:04:00Z
2003-01-28T21:40:00Z
weaver/src/org/aspectj/weaver/patterns/DeclarePrecedence.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Common Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * PARC initial implementation * ******************************************************************/ package org.aspectj.weaver.patterns; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.util.List; import org.aspectj.bridge.IMessage; import org.aspectj.weaver.ISourceContext; import org.aspectj.weaver.ResolvedTypeX; public class DeclarePrecedence extends Declare { private TypePatternList patterns; public DeclarePrecedence(List patterns) { this(new TypePatternList(patterns)); } private DeclarePrecedence(TypePatternList patterns) { this.patterns = patterns; } public String toString() { StringBuffer buf = new StringBuffer(); buf.append("declare precedence: "); buf.append(patterns); buf.append(";"); return buf.toString(); } public boolean equals(Object other) { if (!(other instanceof DeclarePrecedence)) return false; DeclarePrecedence o = (DeclarePrecedence)other; return o.patterns.equals(patterns); } public int hashCode() { return patterns.hashCode(); } public void write(DataOutputStream s) throws IOException { s.writeByte(Declare.DOMINATES); patterns.write(s); writeLocation(s); } public static Declare read(DataInputStream s, ISourceContext context) throws IOException { Declare ret = new DeclarePrecedence(TypePatternList.read(s, context)); ret.readLocation(context, s); return ret; } public void resolve(IScope scope) { patterns = patterns.resolveBindings(scope, Bindings.NONE, false, false); boolean seenStar = false; for (int i=0; i < patterns.size(); i++) { TypePattern pi = patterns.get(i); if (pi.isStar()) { if (seenStar) { scope.getWorld().showMessage(IMessage.ERROR, "circularity in declare precedence, '*' occurs more than once", pi.getSourceLocation(), null); } seenStar = true; continue; } ResolvedTypeX exactType = pi.getExactType().resolve(scope.getWorld()); if (exactType == ResolvedTypeX.MISSING) continue; // Cannot do a dec prec specifying a non-aspect types unless suffixed with a '+' if (!exactType.isAspect() && !pi.isIncludeSubtypes()) { scope.getWorld().showMessage(IMessage.ERROR, "Non-aspect types can only be specified in a declare precedence statement when subtypes are included. Non-aspect type is : "+exactType.getName(), pi.getSourceLocation(),null); } for (int j=0; j < patterns.size(); j++) { if (j == i) continue; TypePattern pj = patterns.get(j); if (pj.isStar()) continue; if (pj.matchesStatically(exactType)) { scope.getWorld().showMessage(IMessage.ERROR, "circularity in declare precedence, '" + exactType.getName() + "' matches two patterns", pi.getSourceLocation(), pj.getSourceLocation()); } } } } public TypePatternList getPatterns() { return patterns; } private int matchingIndex(ResolvedTypeX a) { int knownMatch = -1; int starMatch = -1; for (int i=0, len=patterns.size(); i < len; i++) { TypePattern p = patterns.get(i); if (p.isStar()) { starMatch = i; } else if (p.matchesStatically(a)) { if (knownMatch != -1) { a.getWorld().showMessage(IMessage.ERROR, "multiple matches for " + a + ", matches both " + patterns.get(knownMatch) + " and " + p, patterns.get(knownMatch).getSourceLocation(), p.getSourceLocation()); return -1; } else { knownMatch = i; } } } if (knownMatch == -1) return starMatch; else return knownMatch; } public int compare(ResolvedTypeX aspect1, ResolvedTypeX aspect2) { int index1 = matchingIndex(aspect1); int index2 = matchingIndex(aspect2); //System.out.println("a1: " + aspect1 + ", " + aspect2 + " = " + index1 + ", " + index2); if (index1 == -1 || index2 == -1) return 0; if (index1 == index2) return 0; else if (index1 > index2) return -1; else return +1; } public boolean isAdviceLike() { return false; } }
30,439
Bug 30439 spurious "circular dependency" error
AspectJ Compiler 1.1beta4 This program: aspect Foo { pointcut p1(): execution(void f()) && cflow(execution(void f1())); pointcut p2(): execution(void f()) && cflow(execution(void f2())); before(): p1() { } after(): p1() { } before(): p2() { } after(): p2() { } } class A { void f1() { f(); } void f2() { f(); } void f() { } } results in these errors: circular dependency at method-execution(void A.f()) circular dependency at method-execution(void A.f()) circular dependency at method-execution(void A.f()) circular dependency at method-execution(void A.f()) 4 errors If I comment out any one of the four pieces of advice, all the errors go away. Also, assuming that there is a valid reason for printing this error sometimes, how come there's no line number? --Doug
resolved fixed
4feb835
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2004-07-29T15:04:00Z
2003-01-28T21:40:00Z
weaver/src/org/aspectj/weaver/patterns/DeclareSoft.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Common Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * PARC initial implementation * ******************************************************************/ package org.aspectj.weaver.patterns; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.aspectj.bridge.IMessage; import org.aspectj.weaver.ISourceContext; import org.aspectj.weaver.ResolvedTypeX; import org.aspectj.weaver.TypeX; public class DeclareSoft extends Declare { private TypePattern exception; private Pointcut pointcut; public DeclareSoft(TypePattern exception, Pointcut pointcut) { this.exception = exception; this.pointcut = pointcut; } public String toString() { StringBuffer buf = new StringBuffer(); buf.append("declare soft: "); buf.append(exception); buf.append(": "); buf.append(pointcut); buf.append(";"); return buf.toString(); } public boolean equals(Object other) { if (!(other instanceof DeclareSoft)) return false; DeclareSoft o = (DeclareSoft)other; return o.pointcut.equals(pointcut) && o.exception.equals(exception); } public int hashCode() { int result = 19; result = 37*result + pointcut.hashCode(); result = 37*result + exception.hashCode(); return result; } public void write(DataOutputStream s) throws IOException { s.writeByte(Declare.SOFT); exception.write(s); pointcut.write(s); writeLocation(s); } public static Declare read(DataInputStream s, ISourceContext context) throws IOException { Declare ret = new DeclareSoft( TypePattern.read(s, context), Pointcut.read(s, context) ); ret.readLocation(context, s); return ret; } public Pointcut getPointcut() { return pointcut; } public TypePattern getException() { return exception; } public void resolve(IScope scope) { exception = exception.resolveBindings(scope, null, false, true); TypeX excType = exception.getExactType(); if (excType != ResolvedTypeX.MISSING) { if (!scope.getWorld().resolve(TypeX.THROWABLE).isAssignableFrom(excType)) { scope.getWorld().showMessage(IMessage.ERROR, excType.getName() + " is not a subtype of Throwable", exception.getSourceLocation(), null); pointcut = Pointcut.makeMatchesNothing(Pointcut.RESOLVED); return; } } pointcut = pointcut.resolve(scope); } public boolean isAdviceLike() { return true; } }
30,439
Bug 30439 spurious "circular dependency" error
AspectJ Compiler 1.1beta4 This program: aspect Foo { pointcut p1(): execution(void f()) && cflow(execution(void f1())); pointcut p2(): execution(void f()) && cflow(execution(void f2())); before(): p1() { } after(): p1() { } before(): p2() { } after(): p2() { } } class A { void f1() { f(); } void f2() { f(); } void f() { } } results in these errors: circular dependency at method-execution(void A.f()) circular dependency at method-execution(void A.f()) circular dependency at method-execution(void A.f()) circular dependency at method-execution(void A.f()) 4 errors If I comment out any one of the four pieces of advice, all the errors go away. Also, assuming that there is a valid reason for printing this error sometimes, how come there's no line number? --Doug
resolved fixed
4feb835
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2004-07-29T15:04:00Z
2003-01-28T21:40:00Z
weaver/src/org/aspectj/weaver/patterns/IfPointcut.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Common Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * PARC initial implementation * ******************************************************************/ package org.aspectj.weaver.patterns; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.util.ArrayList; import java.util.List; import org.aspectj.bridge.IMessage; import org.aspectj.lang.JoinPoint; import org.aspectj.util.FuzzyBoolean; import org.aspectj.weaver.Advice; import org.aspectj.weaver.ISourceContext; import org.aspectj.weaver.IntMap; import org.aspectj.weaver.ResolvedMember; import org.aspectj.weaver.ResolvedPointcutDefinition; import org.aspectj.weaver.ResolvedTypeX; import org.aspectj.weaver.Shadow; import org.aspectj.weaver.ShadowMunger; import org.aspectj.weaver.ast.Expr; import org.aspectj.weaver.ast.Literal; import org.aspectj.weaver.ast.Test; import org.aspectj.weaver.ast.Var; public class IfPointcut extends Pointcut { public ResolvedMember testMethod; public int extraParameterFlags; public Pointcut residueSource; int baseArgsCount; //XXX some way to compute args public IfPointcut(ResolvedMember testMethod, int extraParameterFlags) { this.testMethod = testMethod; this.extraParameterFlags = extraParameterFlags; } public FuzzyBoolean fastMatch(FastMatchInfo type) { return FuzzyBoolean.MAYBE; } public FuzzyBoolean match(Shadow shadow) { //??? this is not maximally efficient return FuzzyBoolean.MAYBE; } public void write(DataOutputStream s) throws IOException { s.writeByte(Pointcut.IF); testMethod.write(s); s.writeByte(extraParameterFlags); writeLocation(s); } public static Pointcut read(DataInputStream s, ISourceContext context) throws IOException { IfPointcut ret = new IfPointcut(ResolvedMember.readResolvedMember(s, context), s.readByte()); ret.readLocation(context, s); return ret; } public void resolveBindings(IScope scope, Bindings bindings) { //??? all we need is good error messages in here in cflow contexts } public void resolveBindingsFromRTTI() {} public boolean equals(Object other) { if (!(other instanceof IfPointcut)) return false; IfPointcut o = (IfPointcut)other; return o.testMethod.equals(this.testMethod); } public int hashCode() { int result = 17; result = 37*result + testMethod.hashCode(); return result; } public String toString() { return "if(" + testMethod + ")"; } //??? The implementation of name binding and type checking in if PCDs is very convoluted // There has to be a better way... private boolean findingResidue = false; public Test findResidue(Shadow shadow, ExposedState state) { if (findingResidue) return Literal.TRUE; findingResidue = true; try { ExposedState myState = new ExposedState(baseArgsCount); //System.out.println(residueSource); //??? we throw out the test that comes from this walk. All we want here // is bindings for the arguments residueSource.findResidue(shadow, myState); //System.out.println(myState); Test ret = Literal.TRUE; List args = new ArrayList(); for (int i=0; i < baseArgsCount; i++) { Var v = myState.get(i); args.add(v); ret = Test.makeAnd(ret, Test.makeInstanceof(v, testMethod.getParameterTypes()[i].resolve(shadow.getIWorld()))); } // handle thisJoinPoint parameters if ((extraParameterFlags & Advice.ThisJoinPoint) != 0) { args.add(shadow.getThisJoinPointVar()); } if ((extraParameterFlags & Advice.ThisJoinPointStaticPart) != 0) { args.add(shadow.getThisJoinPointStaticPartVar()); } if ((extraParameterFlags & Advice.ThisEnclosingJoinPointStaticPart) != 0) { args.add(shadow.getThisEnclosingJoinPointStaticPartVar()); } ret = Test.makeAnd(ret, Test.makeCall(testMethod, (Expr[])args.toArray(new Expr[args.size()]))); return ret; } finally { findingResidue = false; } } public Pointcut concretize(ResolvedTypeX inAspect, IntMap bindings) { return this.concretize1(inAspect, bindings); } private IfPointcut partiallyConcretized = null; public Pointcut concretize1(ResolvedTypeX inAspect, IntMap bindings) { //System.err.println("concretize: " + this + " already: " + partiallyConcretized); if (isDeclare(bindings.getEnclosingAdvice())) { // Enforce rule about which designators are supported in declare inAspect.getWorld().showMessage(IMessage.ERROR, "if() pointcut designator cannot be used in declare statement", bindings.getEnclosingAdvice().getSourceLocation(), null); return Pointcut.makeMatchesNothing(Pointcut.CONCRETE); } if (partiallyConcretized != null) { return partiallyConcretized; } IfPointcut ret = new IfPointcut(testMethod, extraParameterFlags); partiallyConcretized = ret; // It is possible to directly code your pointcut expression in a per clause // rather than defining a pointcut declaration and referencing it in your // per clause. If you do this, we have problems (bug #62458). For now, // let's police that you are trying to code a pointcut in a per clause and // put out a compiler error. if (bindings.directlyInAdvice() && bindings.getEnclosingAdvice()==null) { // Assumption: if() is in a per clause if we say we are directly in advice // but we have no enclosing advice. inAspect.getWorld().showMessage(IMessage.ERROR, "if() pointcut designator cannot be used directly in a per clause (compiler limitation). Create a named pointcut containing the if() and refer to it", this.getSourceLocation(),null); return Pointcut.makeMatchesNothing(Pointcut.CONCRETE); } if (bindings.directlyInAdvice()) { ShadowMunger advice = bindings.getEnclosingAdvice(); if (advice instanceof Advice) { ret.baseArgsCount = ((Advice)advice).getBaseParameterCount(); } else { ret.baseArgsCount = 0; } ret.residueSource = advice.getPointcut().concretize(inAspect, ret.baseArgsCount, advice); } else { ResolvedPointcutDefinition def = bindings.peekEnclosingDefinitition(); if (def == CflowPointcut.CFLOW_MARKER) { inAspect.getWorld().showMessage(IMessage.ERROR, "if not supported lexically within cflow (compiler limitation)", getSourceLocation(), null); return Pointcut.makeMatchesNothing(Pointcut.CONCRETE); } ret.baseArgsCount = def.getParameterTypes().length; IntMap newBindings = IntMap.idMap(ret.baseArgsCount); newBindings.copyContext(bindings); ret.residueSource = def.getPointcut().concretize(inAspect, newBindings); } return ret; } // public static Pointcut MatchesNothing = new MatchesNothingPointcut(); // ??? there could possibly be some good optimizations to be done at this point public static IfPointcut makeIfFalsePointcut(State state) { IfPointcut ret = new IfFalsePointcut(); ret.state = state; return ret; } private static class IfFalsePointcut extends IfPointcut { public IfFalsePointcut() { super(null,0); } public Test findResidue(Shadow shadow, ExposedState state) { return Literal.FALSE; // can only get here if an earlier error occurred } public FuzzyBoolean fastMatch(FastMatchInfo type) { return FuzzyBoolean.NO; } public FuzzyBoolean match(Shadow shadow) { return FuzzyBoolean.NO; } public FuzzyBoolean match(JoinPoint.StaticPart jpsp) { return FuzzyBoolean.NO; } public void resolveBindings(IScope scope, Bindings bindings) { } public void resolveBindingsFromRTTI() { } public void postRead(ResolvedTypeX enclosingType) { } public Pointcut concretize1( ResolvedTypeX inAspect, IntMap bindings) { if (isDeclare(bindings.getEnclosingAdvice())) { // Enforce rule about which designators are supported in declare inAspect.getWorld().showMessage(IMessage.ERROR, "if() pointcut designator cannot be used in declare statement", bindings.getEnclosingAdvice().getSourceLocation(), null); return Pointcut.makeMatchesNothing(Pointcut.CONCRETE); } return makeIfFalsePointcut(state); } public void write(DataOutputStream s) throws IOException { s.writeByte(Pointcut.IF_FALSE); } public int hashCode() { int result = 17; return result; } public String toString() { return "if(false)"; } } public static IfPointcut makeIfTruePointcut(State state) { IfPointcut ret = new IfTruePointcut(); ret.state = state; return ret; } private static class IfTruePointcut extends IfPointcut { public IfTruePointcut() { super(null,0); } public Test findResidue(Shadow shadow, ExposedState state) { return Literal.TRUE; // can only get here if an earlier error occurred } public FuzzyBoolean fastMatch(FastMatchInfo type) { return FuzzyBoolean.YES; } public FuzzyBoolean match(Shadow shadow) { return FuzzyBoolean.YES; } public FuzzyBoolean match(JoinPoint.StaticPart jpsp) { return FuzzyBoolean.YES; } public void resolveBindings(IScope scope, Bindings bindings) { } public void resolveBindingsFromRTTI() { } public void postRead(ResolvedTypeX enclosingType) { } public Pointcut concretize1( ResolvedTypeX inAspect, IntMap bindings) { if (isDeclare(bindings.getEnclosingAdvice())) { // Enforce rule about which designators are supported in declare inAspect.getWorld().showMessage(IMessage.ERROR, "if() pointcut designator cannot be used in declare statement", bindings.getEnclosingAdvice().getSourceLocation(), null); return Pointcut.makeMatchesNothing(Pointcut.CONCRETE); } return makeIfTruePointcut(state); } public void write(DataOutputStream s) throws IOException { s.writeByte(IF_TRUE); } public int hashCode() { int result = 37; return result; } public String toString() { return "if(true)"; } } }
30,439
Bug 30439 spurious "circular dependency" error
AspectJ Compiler 1.1beta4 This program: aspect Foo { pointcut p1(): execution(void f()) && cflow(execution(void f1())); pointcut p2(): execution(void f()) && cflow(execution(void f2())); before(): p1() { } after(): p1() { } before(): p2() { } after(): p2() { } } class A { void f1() { f(); } void f2() { f(); } void f() { } } results in these errors: circular dependency at method-execution(void A.f()) circular dependency at method-execution(void A.f()) circular dependency at method-execution(void A.f()) circular dependency at method-execution(void A.f()) 4 errors If I comment out any one of the four pieces of advice, all the errors go away. Also, assuming that there is a valid reason for printing this error sometimes, how come there's no line number? --Doug
resolved fixed
4feb835
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2004-07-29T15:04:00Z
2003-01-28T21:40:00Z
weaver/src/org/aspectj/weaver/patterns/PerFromSuper.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Common Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * PARC initial implementation * ******************************************************************/ package org.aspectj.weaver.patterns; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.aspectj.bridge.MessageUtil; import org.aspectj.util.FuzzyBoolean; import org.aspectj.weaver.ISourceContext; import org.aspectj.weaver.ResolvedTypeX; import org.aspectj.weaver.Shadow; import org.aspectj.weaver.ast.Test; public class PerFromSuper extends PerClause { private PerClause.Kind kind; public PerFromSuper(PerClause.Kind kind) { this.kind = kind; } public FuzzyBoolean fastMatch(FastMatchInfo type) { throw new RuntimeException("unimplemented"); } public FuzzyBoolean match(Shadow shadow) { throw new RuntimeException("unimplemented"); } public void resolveBindings(IScope scope, Bindings bindings) { // this method intentionally left blank } public Test findResidue(Shadow shadow, ExposedState state) { throw new RuntimeException("unimplemented"); } public PerClause concretize(ResolvedTypeX inAspect) { PerClause p = lookupConcretePerClause(inAspect.getSuperclass()); if (p == null) { inAspect.getWorld().getMessageHandler().handleMessage( MessageUtil.error("expected per clause on super aspect not found on " + inAspect.getSuperclass(), getSourceLocation()) ); } if (p.getKind() != kind) { inAspect.getWorld().getMessageHandler().handleMessage( MessageUtil.error("wrong kind of per clause on super, expected " + kind + " but found " + p.getKind(), getSourceLocation()) ); } return p.concretize(inAspect); } private PerClause lookupConcretePerClause(ResolvedTypeX lookupType) { PerClause ret = lookupType.getPerClause(); if (ret == null) return null; if (ret instanceof PerFromSuper) { return lookupConcretePerClause(lookupType.getSuperclass()); } return ret; } public void write(DataOutputStream s) throws IOException { FROMSUPER.write(s); kind.write(s); writeLocation(s); } public static PerClause readPerClause(DataInputStream s, ISourceContext context) throws IOException { PerFromSuper ret = new PerFromSuper(Kind.read(s)); ret.readLocation(context, s); return ret; } public String toString() { return "perFromSuper(" + kind + ", " + inAspect + ")"; } public PerClause.Kind getKind() { return kind; } }
30,439
Bug 30439 spurious "circular dependency" error
AspectJ Compiler 1.1beta4 This program: aspect Foo { pointcut p1(): execution(void f()) && cflow(execution(void f1())); pointcut p2(): execution(void f()) && cflow(execution(void f2())); before(): p1() { } after(): p1() { } before(): p2() { } after(): p2() { } } class A { void f1() { f(); } void f2() { f(); } void f() { } } results in these errors: circular dependency at method-execution(void A.f()) circular dependency at method-execution(void A.f()) circular dependency at method-execution(void A.f()) circular dependency at method-execution(void A.f()) 4 errors If I comment out any one of the four pieces of advice, all the errors go away. Also, assuming that there is a valid reason for printing this error sometimes, how come there's no line number? --Doug
resolved fixed
4feb835
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2004-07-29T15:04:00Z
2003-01-28T21:40:00Z
weaver/src/org/aspectj/weaver/patterns/ReferencePointcut.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Common Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * PARC initial implementation * ******************************************************************/ package org.aspectj.weaver.patterns; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.lang.reflect.Modifier; import org.aspectj.bridge.IMessage; import org.aspectj.bridge.MessageUtil; import org.aspectj.util.FuzzyBoolean; import org.aspectj.weaver.ShadowMunger; import org.aspectj.weaver.BCException; import org.aspectj.weaver.ISourceContext; import org.aspectj.weaver.IntMap; import org.aspectj.weaver.ResolvedPointcutDefinition; import org.aspectj.weaver.ResolvedTypeX; import org.aspectj.weaver.Shadow; import org.aspectj.weaver.TypeX; import org.aspectj.weaver.ast.Test; /** */ //XXX needs check that arguments contains no WildTypePatterns public class ReferencePointcut extends Pointcut { public TypeX onType; public TypePattern onTypeSymbolic; public String name; public TypePatternList arguments; //public ResolvedPointcut binding; public ReferencePointcut(TypePattern onTypeSymbolic, String name, TypePatternList arguments) { this.onTypeSymbolic = onTypeSymbolic; this.name = name; this.arguments = arguments; } public ReferencePointcut(TypeX onType, String name, TypePatternList arguments) { this.onType = onType; this.name = name; this.arguments = arguments; } //??? do either of these match methods make any sense??? public FuzzyBoolean fastMatch(FastMatchInfo type) { return FuzzyBoolean.MAYBE; } /** * Do I really match this shadow? */ public FuzzyBoolean match(Shadow shadow) { return FuzzyBoolean.NO; } public String toString() { StringBuffer buf = new StringBuffer(); if (onType != null) { buf.append(onType); buf.append("."); // for (int i=0, len=fromType.length; i < len; i++) { // buf.append(fromType[i]); // buf.append("."); // } } buf.append(name); buf.append(arguments.toString()); return buf.toString(); } public void write(DataOutputStream s) throws IOException { //XXX ignores onType s.writeByte(Pointcut.REFERENCE); if (onType != null) { s.writeBoolean(true); onType.write(s); } else { s.writeBoolean(false); } s.writeUTF(name); arguments.write(s); writeLocation(s); } public static Pointcut read(DataInputStream s, ISourceContext context) throws IOException { TypeX onType = null; if (s.readBoolean()) { onType = TypeX.read(s); } ReferencePointcut ret = new ReferencePointcut(onType, s.readUTF(), TypePatternList.read(s, context)); ret.readLocation(context, s); return ret; } public void resolveBindings(IScope scope, Bindings bindings) { if (onTypeSymbolic != null) { onType = onTypeSymbolic.resolveExactType(scope, bindings); // in this case we've already signalled an error if (onType == ResolvedTypeX.MISSING) return; } ResolvedTypeX searchType; if (onType != null) { searchType = scope.getWorld().resolve(onType); } else { searchType = scope.getEnclosingType(); } arguments.resolveBindings(scope, bindings, true, true); //XXX ensure that arguments has no ..'s in it // check that I refer to a real pointcut declaration and that I match ResolvedPointcutDefinition pointcutDef = searchType.findPointcut(name); // if we're not a static reference, then do a lookup of outers if (pointcutDef == null && onType == null) { while (true) { TypeX declaringType = searchType.getDeclaringType(); if (declaringType == null) break; searchType = declaringType.resolve(scope.getWorld()); pointcutDef = searchType.findPointcut(name); if (pointcutDef != null) { // make this a static reference onType = searchType; break; } } } if (pointcutDef == null) { scope.message(IMessage.ERROR, this, "can't find referenced pointcut"); return; } // check visibility if (!pointcutDef.isVisible(scope.getEnclosingType())) { scope.message(IMessage.ERROR, this, "pointcut declaration " + pointcutDef + " is not accessible"); return; } if (Modifier.isAbstract(pointcutDef.getModifiers())) { if (onType != null) { scope.message(IMessage.ERROR, this, "can't make static reference to abstract pointcut"); return; } else if (!searchType.isAbstract()) { scope.message(IMessage.ERROR, this, "can't use abstract pointcut in concrete context"); return; } } ResolvedTypeX[] parameterTypes = scope.getWorld().resolve(pointcutDef.getParameterTypes()); if (parameterTypes.length != arguments.size()) { scope.message(IMessage.ERROR, this, "incompatible number of arguments to pointcut, expected " + parameterTypes.length + " found " + arguments.size()); return; } for (int i=0,len=arguments.size(); i < len; i++) { TypePattern p = arguments.get(i); //we are allowed to bind to pointcuts which use subtypes as this is type safe if (p == TypePattern.NO) { scope.message(IMessage.ERROR, this, "bad parameter to pointcut reference"); return; } if (!p.matchesSubtypes(parameterTypes[i]) && !p.getExactType().equals(TypeX.OBJECT)) { scope.message(IMessage.ERROR, p, "incompatible type, expected " + parameterTypes[i].getName() + " found " + p); return; } } } public void resolveBindingsFromRTTI() { throw new UnsupportedOperationException("Referenced pointcuts are not supported in runtime evaluation"); } public void postRead(ResolvedTypeX enclosingType) { arguments.postRead(enclosingType); } public Test findResidue(Shadow shadow, ExposedState state) { throw new RuntimeException("shouldn't happen"); } //??? This is not thread safe, but this class is not designed for multi-threading private boolean concretizing = false; public Pointcut concretize1(ResolvedTypeX searchStart, IntMap bindings) { if (concretizing) { //Thread.currentThread().dumpStack(); searchStart.getWorld().getMessageHandler().handleMessage( MessageUtil.error("circular pointcut declaration involving: " + this, getSourceLocation())); return Pointcut.makeMatchesNothing(Pointcut.CONCRETE); } try { concretizing = true; ResolvedPointcutDefinition pointcutDec; if (onType != null) { searchStart = onType.resolve(searchStart.getWorld()); if (searchStart == ResolvedTypeX.MISSING) { return Pointcut.makeMatchesNothing(Pointcut.CONCRETE); } } pointcutDec = searchStart.findPointcut(name); if (pointcutDec == null) { searchStart.getWorld().getMessageHandler().handleMessage( MessageUtil.error("can't find pointcut \'" + name + "\' on " + searchStart.getName(), getSourceLocation()) ); return Pointcut.makeMatchesNothing(Pointcut.CONCRETE); } if (pointcutDec.isAbstract()) { //Thread.currentThread().dumpStack(); ShadowMunger enclosingAdvice = bindings.getEnclosingAdvice(); searchStart.getWorld().showMessage(IMessage.ERROR, pointcutDec + " is abstract", getSourceLocation(), (null == enclosingAdvice) ? null : enclosingAdvice.getSourceLocation()); return Pointcut.makeMatchesNothing(Pointcut.CONCRETE); } //System.err.println("start: " + searchStart); ResolvedTypeX[] parameterTypes = searchStart.getWorld().resolve(pointcutDec.getParameterTypes()); TypePatternList arguments = this.arguments.resolveReferences(bindings); IntMap newBindings = new IntMap(); for (int i=0,len=arguments.size(); i < len; i++) { TypePattern p = arguments.get(i); //we are allowed to bind to pointcuts which use subtypes as this is type safe if (!p.matchesSubtypes(parameterTypes[i]) && !p.getExactType().equals(TypeX.OBJECT)) { throw new BCException("illegal change to pointcut declaration: " + this); } if (p instanceof BindingTypePattern) { newBindings.put(i, ((BindingTypePattern)p).getFormalIndex()); } } newBindings.copyContext(bindings); newBindings.pushEnclosingDefinition(pointcutDec); try { return pointcutDec.getPointcut().concretize(searchStart, newBindings); } finally { newBindings.popEnclosingDefinitition(); } } finally { concretizing = false; } } // We want to keep the original source location, not the reference location protected boolean shouldCopyLocationForConcretize() { return false; } public boolean equals(Object other) { if (!(other instanceof ReferencePointcut)) return false; ReferencePointcut o = (ReferencePointcut)other; return o.name.equals(name) && o.arguments.equals(arguments) && ((o.onType == null) ? (onType == null) : o.onType.equals(onType)); } public int hashCode() { int result = 17; result = 37*result + ((onType == null) ? 0 : onType.hashCode()); result = 37*result + arguments.hashCode(); result = 37*result + name.hashCode(); return result; } }
30,439
Bug 30439 spurious "circular dependency" error
AspectJ Compiler 1.1beta4 This program: aspect Foo { pointcut p1(): execution(void f()) && cflow(execution(void f1())); pointcut p2(): execution(void f()) && cflow(execution(void f2())); before(): p1() { } after(): p1() { } before(): p2() { } after(): p2() { } } class A { void f1() { f(); } void f2() { f(); } void f() { } } results in these errors: circular dependency at method-execution(void A.f()) circular dependency at method-execution(void A.f()) circular dependency at method-execution(void A.f()) circular dependency at method-execution(void A.f()) 4 errors If I comment out any one of the four pieces of advice, all the errors go away. Also, assuming that there is a valid reason for printing this error sometimes, how come there's no line number? --Doug
resolved fixed
4feb835
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2004-07-29T15:04:00Z
2003-01-28T21:40:00Z
weaver/src/org/aspectj/weaver/patterns/ThisOrTargetPointcut.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Common Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * PARC initial implementation * ******************************************************************/ package org.aspectj.weaver.patterns; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.aspectj.bridge.IMessage; import org.aspectj.lang.JoinPoint; import org.aspectj.util.FuzzyBoolean; import org.aspectj.weaver.ISourceContext; import org.aspectj.weaver.IntMap; import org.aspectj.weaver.ResolvedTypeX; import org.aspectj.weaver.Shadow; import org.aspectj.weaver.TypeX; import org.aspectj.weaver.ast.Literal; import org.aspectj.weaver.ast.Test; import org.aspectj.weaver.ast.Var; // /** * Corresponds to target or this pcd. * * <p>type is initially a WildTypePattern. If it stays that way, it's a this(Foo) * type deal. * however, the resolveBindings method may convert it to a BindingTypePattern, * in which * case, it's a this(foo) type deal. * * @author Erik Hilsdale * @author Jim Hugunin */ public class ThisOrTargetPointcut extends NameBindingPointcut { private boolean isThis; private TypePattern type; public ThisOrTargetPointcut(boolean isThis, TypePattern type) { this.isThis = isThis; this.type = type; } public FuzzyBoolean fastMatch(FastMatchInfo type) { return FuzzyBoolean.MAYBE; } private boolean couldMatch(Shadow shadow) { return isThis ? shadow.hasThis() : shadow.hasTarget(); } public FuzzyBoolean match(Shadow shadow) { if (!couldMatch(shadow)) return FuzzyBoolean.NO; TypeX typeToMatch = isThis ? shadow.getThisType() : shadow.getTargetType(); //if (typeToMatch == ResolvedTypeX.MISSING) return FuzzyBoolean.NO; return type.matches(typeToMatch.resolve(shadow.getIWorld()), TypePattern.DYNAMIC); } public FuzzyBoolean match(JoinPoint jp, JoinPoint.StaticPart encJP) { Object toMatch = isThis ? jp.getThis() : jp.getTarget(); if (toMatch == null) return FuzzyBoolean.NO; return type.matches(toMatch.getClass(), TypePattern.DYNAMIC); } public void write(DataOutputStream s) throws IOException { s.writeByte(Pointcut.THIS_OR_TARGET); s.writeBoolean(isThis); type.write(s); writeLocation(s); } public static Pointcut read(DataInputStream s, ISourceContext context) throws IOException { boolean isThis = s.readBoolean(); TypePattern type = TypePattern.read(s, context); ThisOrTargetPointcut ret = new ThisOrTargetPointcut(isThis, type); ret.readLocation(context, s); return ret; } public void resolveBindings(IScope scope, Bindings bindings) { type = type.resolveBindings(scope, bindings, true, true); // ??? handle non-formal } public void resolveBindingsFromRTTI() { type = type.resolveBindingsFromRTTI(true,true); } public void postRead(ResolvedTypeX enclosingType) { type.postRead(enclosingType); } public boolean equals(Object other) { if (!(other instanceof ThisOrTargetPointcut)) return false; ThisOrTargetPointcut o = (ThisOrTargetPointcut)other; return o.isThis == this.isThis && o.type.equals(this.type); } public int hashCode() { int result = 17; result = 37*result + (isThis ? 0 : 1); result = 37*result + type.hashCode(); return result; } public String toString() { return (isThis ? "this(" : "target(") + type + ")"; } public Test findResidue(Shadow shadow, ExposedState state) { if (!couldMatch(shadow)) return Literal.FALSE; if (type == TypePattern.ANY) return Literal.TRUE; Var var = isThis ? shadow.getThisVar() : shadow.getTargetVar(); return exposeStateForVar(var, type, state, shadow.getIWorld()); } public Pointcut concretize1(ResolvedTypeX inAspect, IntMap bindings) { if (isDeclare(bindings.getEnclosingAdvice())) { // Enforce rule about which designators are supported in declare inAspect.getWorld().showMessage(IMessage.ERROR, (isThis?"this":"target")+"() pointcut designator cannot be used in declare statement", bindings.getEnclosingAdvice().getSourceLocation(), null); return Pointcut.makeMatchesNothing(Pointcut.CONCRETE); } TypePattern newType = type.remapAdviceFormals(bindings); if (inAspect.crosscuttingMembers != null) { inAspect.crosscuttingMembers.exposeType(newType.getExactType()); } return new ThisOrTargetPointcut(isThis, newType); } }
30,439
Bug 30439 spurious "circular dependency" error
AspectJ Compiler 1.1beta4 This program: aspect Foo { pointcut p1(): execution(void f()) && cflow(execution(void f1())); pointcut p2(): execution(void f()) && cflow(execution(void f2())); before(): p1() { } after(): p1() { } before(): p2() { } after(): p2() { } } class A { void f1() { f(); } void f2() { f(); } void f() { } } results in these errors: circular dependency at method-execution(void A.f()) circular dependency at method-execution(void A.f()) circular dependency at method-execution(void A.f()) circular dependency at method-execution(void A.f()) 4 errors If I comment out any one of the four pieces of advice, all the errors go away. Also, assuming that there is a valid reason for printing this error sometimes, how come there's no line number? --Doug
resolved fixed
4feb835
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2004-07-29T15:04:00Z
2003-01-28T21:40:00Z
weaver/src/org/aspectj/weaver/patterns/TypePattern.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Common Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * PARC initial implementation * ******************************************************************/ package org.aspectj.weaver.patterns; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.util.Iterator; import org.aspectj.bridge.MessageUtil; import org.aspectj.util.FuzzyBoolean; import org.aspectj.weaver.BCException; import org.aspectj.weaver.ISourceContext; import org.aspectj.weaver.IntMap; import org.aspectj.weaver.ResolvedTypeX; import org.aspectj.weaver.TypeX; /** * On creation, type pattern only contains WildTypePattern nodes, not BindingType or ExactType. * * <p>Then we call resolveBindings() during compilation * During concretization of enclosing pointcuts, we call remapAdviceFormals * * @author Erik Hilsdale * @author Jim Hugunin */ public abstract class TypePattern extends PatternNode { public static class MatchKind { private String name; public MatchKind(String name) { this.name = name; } public String toString() { return name; } } public static final MatchKind STATIC = new MatchKind("STATIC"); public static final MatchKind DYNAMIC = new MatchKind("DYNAMIC"); public static final TypePattern ELLIPSIS = new EllipsisTypePattern(); public static final TypePattern ANY = new AnyTypePattern(); public static final TypePattern NO = new NoTypePattern(); protected boolean includeSubtypes; protected TypePattern(boolean includeSubtypes) { this.includeSubtypes = includeSubtypes; } //XXX non-final for Not, && and || public boolean matchesStatically(ResolvedTypeX type) { if (includeSubtypes) { return matchesSubtypes(type); } else { return matchesExactly(type); } } public abstract FuzzyBoolean matchesInstanceof(ResolvedTypeX type); public final FuzzyBoolean matches(ResolvedTypeX type, MatchKind kind) { //??? This is part of gracefully handling missing references if (type == ResolvedTypeX.MISSING) return FuzzyBoolean.NO; if (kind == STATIC) { return FuzzyBoolean.fromBoolean(matchesStatically(type)); } else if (kind == DYNAMIC) { //System.err.println("matching: " + this + " with " + type); FuzzyBoolean ret = matchesInstanceof(type); //System.err.println(" got: " + ret); return ret; } else { throw new IllegalArgumentException("kind must be DYNAMIC or STATIC"); } } // methods for dynamic pc matching... public final FuzzyBoolean matches(Class toMatch, MatchKind kind) { if (kind == STATIC) { return FuzzyBoolean.fromBoolean(matchesStatically(toMatch)); } else if (kind == DYNAMIC) { //System.err.println("matching: " + this + " with " + type); FuzzyBoolean ret = matchesInstanceof(toMatch); //System.err.println(" got: " + ret); return ret; } else { throw new IllegalArgumentException("kind must be DYNAMIC or STATIC"); } } /** * This variant is only called by the args and handler pcds when doing runtime * matching. We need to handle primitive types correctly in this case (an Integer * should match an int,...). */ public final FuzzyBoolean matches(Object o, MatchKind kind) { if (kind == STATIC) { // handler pcd return FuzzyBoolean.fromBoolean(matchesStatically(o.getClass())); } else if (kind == DYNAMIC) { // args pcd // Class clazz = o.getClass(); // FuzzyBoolean ret = FuzzyBoolean.fromBoolean(matchesSubtypes(clazz)); // if (ret == FuzzyBoolean.NO) { // // try primitive type instead // if (clazz == Integer.class) ret = FuzzyBoolean.fromBoolean(matchesExactly(int.class)); // } // return ret; return matchesInstanceof(o.getClass()); } else { throw new IllegalArgumentException("kind must be DYNAMIC or STATIC"); } } public boolean matchesStatically(Class toMatch) { if (includeSubtypes) { return matchesSubtypes(toMatch); } else { return matchesExactly(toMatch); } } public abstract FuzzyBoolean matchesInstanceof(Class toMatch); protected abstract boolean matchesExactly(Class toMatch); protected boolean matchesSubtypes(Class toMatch) { if (matchesExactly(toMatch)) { return true; } Class superClass = toMatch.getSuperclass(); if (superClass != null) { return matchesSubtypes(superClass); } return false; } protected abstract boolean matchesExactly(ResolvedTypeX type); protected boolean matchesSubtypes(ResolvedTypeX type) { //System.out.println("matching: " + this + " to " + type); if (matchesExactly(type)) { //System.out.println(" true"); return true; } // FuzzyBoolean ret = FuzzyBoolean.NO; // ??? -eh for (Iterator i = type.getDirectSupertypes(); i.hasNext(); ) { ResolvedTypeX superType = (ResolvedTypeX)i.next(); if (matchesSubtypes(superType)) return true; } return false; } public TypeX resolveExactType(IScope scope, Bindings bindings) { TypePattern p = resolveBindings(scope, bindings, false, true); if (p == NO) return ResolvedTypeX.MISSING; return ((ExactTypePattern)p).getType(); } public TypeX getExactType() { if (this instanceof ExactTypePattern) return ((ExactTypePattern)this).getType(); else return ResolvedTypeX.MISSING; } protected TypePattern notExactType(IScope s) { s.getMessageHandler().handleMessage(MessageUtil.error("exact type pattern required", getSourceLocation())); return NO; } // public boolean assertExactType(IMessageHandler m) { // if (this instanceof ExactTypePattern) return true; // // //XXX should try harder to avoid multiple errors for one problem // m.handleMessage(MessageUtil.error("exact type pattern required", getSourceLocation())); // return false; // } /** * This can modify in place, or return a new TypePattern if the type changes. */ public TypePattern resolveBindings(IScope scope, Bindings bindings, boolean allowBinding, boolean requireExactType) { return this; } public TypePattern resolveBindingsFromRTTI(boolean allowBindng, boolean requireExactType) { return this; } public void postRead(ResolvedTypeX enclosingType) { } public boolean isStar() { return false; } /** * This is called during concretization of pointcuts, it is used by BindingTypePattern * to return a new BindingTypePattern with a formal index appropiate for the advice, * rather than for the lexical declaration, i.e. this handles transforamtions through * named pointcuts. * <pre> * pointcut foo(String name): args(name); * --&gt; This makes a BindingTypePattern(0) pointing to the 0th formal * * before(Foo f, String n): this(f) && foo(n) { ... } * --&gt; when resolveReferences is called on the args from the above, it * will return a BindingTypePattern(1) * * before(Foo f): this(f) && foo(*) { ... } * --&gt; when resolveReferences is called on the args from the above, it * will return an ExactTypePattern(String) * </pre> */ public TypePattern remapAdviceFormals(IntMap bindings) { return this; } public static final byte WILD = 1; public static final byte EXACT = 2; public static final byte BINDING = 3; public static final byte ELLIPSIS_KEY = 4; public static final byte ANY_KEY = 5; public static final byte NOT = 6; public static final byte OR = 7; public static final byte AND = 8; public static final byte NO_KEY = 9; public static TypePattern read(DataInputStream s, ISourceContext context) throws IOException { byte key = s.readByte(); switch(key) { case WILD: return WildTypePattern.read(s, context); case EXACT: return ExactTypePattern.read(s, context); case BINDING: return BindingTypePattern.read(s, context); case ELLIPSIS_KEY: return ELLIPSIS; case ANY_KEY: return ANY; case NO_KEY: return NO; case NOT: return NotTypePattern.read(s, context); case OR: return OrTypePattern.read(s, context); case AND: return AndTypePattern.read(s, context); } throw new BCException("unknown TypePattern kind: " + key); } public boolean isIncludeSubtypes() { return includeSubtypes; } } class EllipsisTypePattern extends TypePattern { /** * Constructor for EllipsisTypePattern. * @param includeSubtypes */ public EllipsisTypePattern() { super(false); } /** * @see org.aspectj.weaver.patterns.TypePattern#matchesExactly(IType) */ protected boolean matchesExactly(ResolvedTypeX type) { return false; } /** * @see org.aspectj.weaver.patterns.TypePattern#matchesInstanceof(IType) */ public FuzzyBoolean matchesInstanceof(ResolvedTypeX type) { return FuzzyBoolean.NO; } /** * @see org.aspectj.weaver.patterns.TypePattern#matchesExactly(IType) */ protected boolean matchesExactly(Class type) { return false; } /** * @see org.aspectj.weaver.patterns.TypePattern#matchesInstanceof(IType) */ public FuzzyBoolean matchesInstanceof(Class type) { return FuzzyBoolean.NO; } /** * @see org.aspectj.weaver.patterns.PatternNode#write(DataOutputStream) */ public void write(DataOutputStream s) throws IOException { s.writeByte(ELLIPSIS_KEY); } public String toString() { return ".."; } } class AnyTypePattern extends TypePattern { /** * Constructor for EllipsisTypePattern. * @param includeSubtypes */ public AnyTypePattern() { super(false); } /** * @see org.aspectj.weaver.patterns.TypePattern#matchesExactly(IType) */ protected boolean matchesExactly(ResolvedTypeX type) { return true; } /** * @see org.aspectj.weaver.patterns.TypePattern#matchesInstanceof(IType) */ public FuzzyBoolean matchesInstanceof(ResolvedTypeX type) { return FuzzyBoolean.YES; } /** * @see org.aspectj.weaver.patterns.TypePattern#matchesExactly(IType) */ protected boolean matchesExactly(Class type) { return true; } /** * @see org.aspectj.weaver.patterns.TypePattern#matchesInstanceof(IType) */ public FuzzyBoolean matchesInstanceof(Class type) { return FuzzyBoolean.YES; } /** * @see org.aspectj.weaver.patterns.PatternNode#write(DataOutputStream) */ public void write(DataOutputStream s) throws IOException { s.writeByte(ANY_KEY); } /** * @see org.aspectj.weaver.patterns.TypePattern#matches(IType, MatchKind) */ // public FuzzyBoolean matches(IType type, MatchKind kind) { // return FuzzyBoolean.YES; // } /** * @see org.aspectj.weaver.patterns.TypePattern#matchesSubtypes(IType) */ protected boolean matchesSubtypes(ResolvedTypeX type) { return true; } public boolean isStar() { return true; } public String toString() { return "*"; } } class NoTypePattern extends TypePattern { public NoTypePattern() { super(false); } /** * @see org.aspectj.weaver.patterns.TypePattern#matchesExactly(IType) */ protected boolean matchesExactly(ResolvedTypeX type) { return false; } /** * @see org.aspectj.weaver.patterns.TypePattern#matchesInstanceof(IType) */ public FuzzyBoolean matchesInstanceof(ResolvedTypeX type) { return FuzzyBoolean.NO; } /** * @see org.aspectj.weaver.patterns.TypePattern#matchesExactly(IType) */ protected boolean matchesExactly(Class type) { return false; } /** * @see org.aspectj.weaver.patterns.TypePattern#matchesInstanceof(IType) */ public FuzzyBoolean matchesInstanceof(Class type) { return FuzzyBoolean.NO; } /** * @see org.aspectj.weaver.patterns.PatternNode#write(DataOutputStream) */ public void write(DataOutputStream s) throws IOException { s.writeByte(NO_KEY); } /** * @see org.aspectj.weaver.patterns.TypePattern#matches(IType, MatchKind) */ // public FuzzyBoolean matches(IType type, MatchKind kind) { // return FuzzyBoolean.YES; // } /** * @see org.aspectj.weaver.patterns.TypePattern#matchesSubtypes(IType) */ protected boolean matchesSubtypes(ResolvedTypeX type) { return false; } public boolean isStar() { return false; } public String toString() { return "<nothing>"; } }
30,439
Bug 30439 spurious "circular dependency" error
AspectJ Compiler 1.1beta4 This program: aspect Foo { pointcut p1(): execution(void f()) && cflow(execution(void f1())); pointcut p2(): execution(void f()) && cflow(execution(void f2())); before(): p1() { } after(): p1() { } before(): p2() { } after(): p2() { } } class A { void f1() { f(); } void f2() { f(); } void f() { } } results in these errors: circular dependency at method-execution(void A.f()) circular dependency at method-execution(void A.f()) circular dependency at method-execution(void A.f()) circular dependency at method-execution(void A.f()) 4 errors If I comment out any one of the four pieces of advice, all the errors go away. Also, assuming that there is a valid reason for printing this error sometimes, how come there's no line number? --Doug
resolved fixed
4feb835
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2004-07-29T15:04:00Z
2003-01-28T21: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 Common Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * PARC initial implementation * ******************************************************************/ package org.aspectj.weaver.patterns; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.util.ArrayList; import java.util.List; import org.aspectj.bridge.IMessage; import org.aspectj.bridge.Message; import org.aspectj.bridge.MessageUtil; import org.aspectj.util.FileUtil; import org.aspectj.util.FuzzyBoolean; import org.aspectj.weaver.ISourceContext; import org.aspectj.weaver.ResolvedTypeX; import org.aspectj.weaver.TypeX; //XXX need to use dim in matching public class WildTypePattern extends TypePattern { NamePattern[] namePatterns; int ellipsisCount; String[] importedPrefixes; String[] knownMatches; int dim; WildTypePattern(NamePattern[] namePatterns, boolean includeSubtypes, int dim) { super(includeSubtypes); 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); } public WildTypePattern(List names, boolean includeSubtypes, int dim, int endPos) { this(names, includeSubtypes, dim); this.end = endPos; } //XXX inefficient implementation public static char[][] splitNames(String s) { List ret = new ArrayList(); int startIndex = 0; while (true) { int breakIndex = s.indexOf('.', startIndex); // what about / if (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(ResolvedTypeX type) { String targetTypeName = type.getName(); //System.err.println("match: " + targetTypeName + ", " + knownMatches); //Arrays.asList(importedPrefixes)); return matchesExactlyByName(targetTypeName); } /** * @param targetTypeName * @return */ private boolean matchesExactlyByName(String targetTypeName) { //XXX hack if (knownMatches == null && importedPrefixes == null) { return innerMatchesExactly(targetTypeName); } // 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) { 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))) { 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()))) { return true; } } } return innerMatchesExactly(targetTypeName); } private int lastIndexOfDotOrDollar(String string) { int dot = string.lastIndexOf('.'); int dollar = string.lastIndexOf('$'); return Math.max(dot, dollar); } private boolean innerMatchesExactly(String targetTypeName) { //??? doing this everytime is not very efficient char[][] names = splitNames(targetTypeName); return innerMatchesExactly(names); } private boolean innerMatchesExactly(char[][] names) { int namesLength = names.length; int patternsLength = namePatterns.length; int namesIndex = 0; int patternsIndex = 0; 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(ResolvedTypeX 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() { //System.err.println("extract from : " + Arrays.asList(namePatterns)); int len = namePatterns.length; 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(); } /** * 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 (isStar()) { return TypePattern.ANY; //??? loses source location } 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); binding.copyLocationFrom(this); bindings.register(binding, scope); return binding; } } String cleanName = maybeGetCleanName(); String originalName = cleanName; if (cleanName != null) { TypeX type; //System.out.println("resolve: " + cleanName); //??? this loop has too many inefficiencies to count while ((type = scope.lookupType(cleanName, this)) == ResolvedTypeX.MISSING) { int lastDot = cleanName.lastIndexOf('.'); if (lastDot == -1) break; cleanName = cleanName.substring(0, lastDot) + '$' + cleanName.substring(lastDot+1); } if (type == ResolvedTypeX.MISSING) { if (requireExactType) { if (!allowBinding) { scope.getWorld().getMessageHandler().handleMessage( MessageUtil.error("can't bind type name '" + originalName + "'", getSourceLocation())); } else if (scope.getWorld().getLint().invalidAbsoluteTypeName.isEnabled()) { scope.getWorld().getLint().invalidAbsoluteTypeName.signal(originalName, getSourceLocation()); } return NO; } else if (scope.getWorld().getLint().invalidAbsoluteTypeName.isEnabled()) { scope.getWorld().getLint().invalidAbsoluteTypeName.signal(originalName, getSourceLocation()); } } else { if (dim != 0) type = TypeX.makeArray(type, dim); TypePattern ret = new ExactTypePattern(type, includeSubtypes); ret.copyLocationFrom(this); return ret; } } else { if (requireExactType) { scope.getWorld().getMessageHandler().handleMessage( MessageUtil.error("wildcard type pattern not allowed, must use type name", getSourceLocation())); return NO; } //XXX need to implement behavior for Lint.invalidWildcardTypeName } importedPrefixes = scope.getImportedPrefixes(); knownMatches = preMatch(scope.getImportedNames()); return this; } public TypePattern resolveBindingsFromRTTI(boolean allowBinding, boolean requireExactType) { if (isStar()) { return TypePattern.ANY; //??? loses source location } String cleanName = maybeGetCleanName(); if (cleanName != null) { Class clazz = null; clazz = maybeGetPrimitiveClass(cleanName); while (clazz == null) { try { clazz = Class.forName(cleanName); } catch (ClassNotFoundException cnf) { int lastDotIndex = cleanName.lastIndexOf('.'); if (lastDotIndex == -1) break; cleanName = cleanName.substring(0, lastDotIndex) + '$' + cleanName.substring(lastDotIndex+1); } } if (clazz == null) { try { clazz = Class.forName("java.lang." + cleanName); } catch (ClassNotFoundException cnf) { } } if (clazz == null) { if (requireExactType) { return NO; } } else { TypeX type = TypeX.forName(clazz.getName()); if (dim != 0) type = TypeX.makeArray(type,dim); TypePattern ret = new ExactTypePattern(type, includeSubtypes); ret.copyLocationFrom(this); return ret; } } else if (requireExactType) { return NO; } importedPrefixes = SimpleScope.javaLangPrefixArray; knownMatches = new String[0]; return this; } private Class maybeGetPrimitiveClass(String typeName) { return (Class) ExactTypePattern.primitiveTypesMap.get(typeName); } public boolean isStar() { 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]); //??? 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(ResolvedTypeX enclosingType) { // this.importedPrefixes = enclosingType.getImportedPrefixes(); // this.knownNames = prematch(enclosingType.getImportedNames()); // } public String toString() { StringBuffer buf = new StringBuffer(); 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()); } } 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; for (int i=0; i < len; i++) { if (!o.namePatterns[i].equals(this.namePatterns[i])) return false; } return true; } public int hashCode() { int result = 17; for (int i = 0, len = namePatterns.length; i < len; i++) { result = 37*result + namePatterns[i].hashCode(); } return result; } public FuzzyBoolean matchesInstanceof(Class type) { return FuzzyBoolean.NO; } public boolean matchesExactly(Class type) { return matchesExactlyByName(type.getName()); } /** * @see org.aspectj.weaver.patterns.PatternNode#write(DataOutputStream) */ public void write(DataOutputStream s) throws IOException { s.writeByte(TypePattern.WILD); s.writeShort(namePatterns.length); for (int i = 0; i < namePatterns.length; i++) { namePatterns[i].write(s); } s.writeBoolean(includeSubtypes); s.writeInt(dim); //??? 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); } public static TypePattern read(DataInputStream 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); ret.knownMatches = FileUtil.readStringArray(s); ret.importedPrefixes = FileUtil.readStringArray(s); ret.readLocation(context, s); return ret; } }
30,439
Bug 30439 spurious "circular dependency" error
AspectJ Compiler 1.1beta4 This program: aspect Foo { pointcut p1(): execution(void f()) && cflow(execution(void f1())); pointcut p2(): execution(void f()) && cflow(execution(void f2())); before(): p1() { } after(): p1() { } before(): p2() { } after(): p2() { } } class A { void f1() { f(); } void f2() { f(); } void f() { } } results in these errors: circular dependency at method-execution(void A.f()) circular dependency at method-execution(void A.f()) circular dependency at method-execution(void A.f()) circular dependency at method-execution(void A.f()) 4 errors If I comment out any one of the four pieces of advice, all the errors go away. Also, assuming that there is a valid reason for printing this error sometimes, how come there's no line number? --Doug
resolved fixed
4feb835
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2004-07-29T15:04:00Z
2003-01-28T21:40:00Z
weaver/testsrc/org/aspectj/weaver/BcweaverTests.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Common Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * PARC initial implementation * ******************************************************************/ package org.aspectj.weaver; import java.io.File; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import org.aspectj.util.FileUtil; public class BcweaverTests extends TestCase { public static final String TESTDATA_PATH = "../weaver/testdata"; public static final String OUTDIR_PATH = "../weaver/out"; /** @return File outDir (writable) or null if unable to write */ public static File getOutdir() { File result = new File(OUTDIR_PATH); if (result.mkdirs() || (result.canWrite() && result.isDirectory())) { return result; } return null; } /** best efforts to delete the output directory and any contents */ public static void removeOutDir() { File outDir = getOutdir(); if (null != outDir) { FileUtil.deleteContents(outDir); outDir.delete(); } } public static Test suite() { TestSuite suite = new TestSuite(BcweaverTests.class.getName()); // abstract //suite.addTestSuite(AbstractWorldTestCase.class); //$JUnit-BEGIN$ suite.addTestSuite(MemberTestCase.class); suite.addTestSuite(TypeXTestCase.class); suite.addTestSuite(WeavingURLClassLoaderTest.class); //$JUnit-END$ return suite; } public BcweaverTests(String name) { super(name); } }
30,439
Bug 30439 spurious "circular dependency" error
AspectJ Compiler 1.1beta4 This program: aspect Foo { pointcut p1(): execution(void f()) && cflow(execution(void f1())); pointcut p2(): execution(void f()) && cflow(execution(void f2())); before(): p1() { } after(): p1() { } before(): p2() { } after(): p2() { } } class A { void f1() { f(); } void f2() { f(); } void f() { } } results in these errors: circular dependency at method-execution(void A.f()) circular dependency at method-execution(void A.f()) circular dependency at method-execution(void A.f()) circular dependency at method-execution(void A.f()) 4 errors If I comment out any one of the four pieces of advice, all the errors go away. Also, assuming that there is a valid reason for printing this error sometimes, how come there's no line number? --Doug
resolved fixed
4feb835
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2004-07-29T15:04:00Z
2003-01-28T21:40:00Z
weaver/testsrc/org/aspectj/weaver/WeaverMessagesTestCase.java
70,773
Bug 70773 AspectJ Error: ConncurrentModificationException thrown: null
In AspectJ 1.1.11 for Eclipse, build ID 1.2.0 (and also in the previous 1.1.10) on Eclipse version 3.0.0, build ID 200406351208: If I enable incremental compilation and make a change to a file (typing a space and deleting it, or editing a comment), I get a "ConncurrentModificationException thrown: null" error.
resolved fixed
9aed31d
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2004-08-02T10:14:39Z
2004-07-24T00:46:40Z
org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/compiler/lookup/AjLookupEnvironment.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Common Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * PARC initial implementation * ******************************************************************/ package org.aspectj.ajdt.internal.compiler.lookup; import java.util.*; import org.aspectj.ajdt.internal.compiler.ast.AspectDeclaration; //import org.aspectj.ajdt.internal.compiler.ast.DeclareDeclaration; import org.aspectj.ajdt.internal.compiler.ast.PointcutDeclaration; //import org.aspectj.asm.*; //import org.aspectj.asm.IProgramElement; //import org.aspectj.asm.internal.Relationship; import org.aspectj.bridge.IMessage; import org.aspectj.weaver.*; import org.aspectj.weaver.bcel.LazyClassGen; import org.aspectj.weaver.patterns.*; import org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration; import org.eclipse.jdt.internal.compiler.ast.TypeDeclaration; import org.eclipse.jdt.internal.compiler.env.IBinaryType; import org.eclipse.jdt.internal.compiler.env.INameEnvironment; import org.eclipse.jdt.internal.compiler.impl.CompilerOptions; import org.eclipse.jdt.internal.compiler.impl.ITypeRequestor; import org.eclipse.jdt.internal.compiler.lookup.*; import org.eclipse.jdt.internal.compiler.problem.ProblemReporter; /** * Overrides the default eclipse LookupEnvironment for two purposes. * * 1. To provide some additional phases to <code>completeTypeBindings</code> * that weave declare parents and inter-type declarations at the correct time. * * 2. To intercept the loading of new binary types to ensure the they will have * declare parents and inter-type declarations woven when appropriate. * * @author Jim Hugunin */ public class AjLookupEnvironment extends LookupEnvironment { public EclipseFactory factory = null; // private boolean builtInterTypesAndPerClauses = false; private List pendingTypesToWeave = new ArrayList(); private Map dangerousInterfaces = new HashMap(); public AjLookupEnvironment( ITypeRequestor typeRequestor, CompilerOptions options, ProblemReporter problemReporter, INameEnvironment nameEnvironment) { super(typeRequestor, options, problemReporter, nameEnvironment); } //??? duplicates some of super's code public void completeTypeBindings() { // builtInterTypesAndPerClauses = false; //pendingTypesToWeave = new ArrayList(); stepCompleted = BUILD_TYPE_HIERARCHY; for (int i = lastCompletedUnitIndex + 1; i <= lastUnitIndex; i++) { units[i].scope.checkAndSetImports(); } stepCompleted = CHECK_AND_SET_IMPORTS; for (int i = lastCompletedUnitIndex + 1; i <= lastUnitIndex; i++) { units[i].scope.connectTypeHierarchy(); } stepCompleted = CONNECT_TYPE_HIERARCHY; for (int i = lastCompletedUnitIndex + 1; i <= lastUnitIndex; i++) { units[i].scope.buildFieldsAndMethods(); } // would like to gather up all TypeDeclarations at this point and put them in the factory for (int i = lastCompletedUnitIndex + 1; i <= lastUnitIndex; i++) { SourceTypeBinding[] b = units[i].scope.topLevelTypes; for (int j = 0; j < b.length; j++) { factory.addSourceTypeBinding(b[j]); } } // need to build inter-type declarations for all AspectDeclarations at this point for (int i = lastCompletedUnitIndex + 1; i <= lastUnitIndex; i++) { SourceTypeBinding[] b = units[i].scope.topLevelTypes; for (int j = 0; j < b.length; j++) { buildInterTypeAndPerClause(b[j].scope); addCrosscuttingStructures(b[j].scope); } } factory.finishTypeMungers(); // now do weaving Collection typeMungers = factory.getTypeMungers(); Collection declareParents = factory.getDeclareParents(); doPendingWeaves(); for (int i = lastCompletedUnitIndex + 1; i <= lastUnitIndex; i++) { weaveInterTypeDeclarations(units[i].scope, typeMungers, declareParents); } for (int i = lastCompletedUnitIndex + 1; i <= lastUnitIndex; i++) { SourceTypeBinding[] b = units[i].scope.topLevelTypes; for (int j = 0; j < b.length; j++) { resolvePointcutDeclarations(b[j].scope); } } for (int i = lastCompletedUnitIndex + 1; i <= lastUnitIndex; i++) { SourceTypeBinding[] b = units[i].scope.topLevelTypes; for (int j = 0; j < b.length; j++) { addAdviceLikeDeclares(b[j].scope); } } for (int i = lastCompletedUnitIndex + 1; i <= lastUnitIndex; i++) { units[i] = null; // release unnecessary reference to the parsed unit } stepCompleted = BUILD_FIELDS_AND_METHODS; lastCompletedUnitIndex = lastUnitIndex; } private void doPendingWeaves() { for (Iterator i = pendingTypesToWeave.iterator(); i.hasNext(); ) { SourceTypeBinding t = (SourceTypeBinding)i.next(); weaveInterTypeDeclarations(t); } pendingTypesToWeave.clear(); } private void addAdviceLikeDeclares(ClassScope s) { TypeDeclaration dec = s.referenceContext; if (dec instanceof AspectDeclaration) { ResolvedTypeX typeX = factory.fromEclipse(dec.binding); factory.getWorld().getCrosscuttingMembersSet().addAdviceLikeDeclares(typeX); } SourceTypeBinding sourceType = s.referenceContext.binding; ReferenceBinding[] memberTypes = sourceType.memberTypes; for (int i = 0, length = memberTypes.length; i < length; i++) { addAdviceLikeDeclares(((SourceTypeBinding) memberTypes[i]).scope); } } private void addCrosscuttingStructures(ClassScope s) { TypeDeclaration dec = s.referenceContext; if (dec instanceof AspectDeclaration) { ResolvedTypeX typeX = factory.fromEclipse(dec.binding); factory.getWorld().getCrosscuttingMembersSet().addOrReplaceAspect(typeX); if (typeX.getSuperclass().isAspect() && !typeX.getSuperclass().isExposedToWeaver()) { factory.getWorld().getCrosscuttingMembersSet().addOrReplaceAspect(typeX.getSuperclass()); } } SourceTypeBinding sourceType = s.referenceContext.binding; ReferenceBinding[] memberTypes = sourceType.memberTypes; for (int i = 0, length = memberTypes.length; i < length; i++) { addCrosscuttingStructures(((SourceTypeBinding) memberTypes[i]).scope); } } private void resolvePointcutDeclarations(ClassScope s) { TypeDeclaration dec = s.referenceContext; SourceTypeBinding sourceType = s.referenceContext.binding; boolean hasPointcuts = false; AbstractMethodDeclaration[] methods = dec.methods; boolean initializedMethods = false; if (methods != null) { for (int i=0; i < methods.length; i++) { if (methods[i] instanceof PointcutDeclaration) { hasPointcuts = true; if (!initializedMethods) { sourceType.methods(); //force initialization initializedMethods = true; } ((PointcutDeclaration)methods[i]).resolvePointcut(s); } } } if (hasPointcuts || dec instanceof AspectDeclaration) { ResolvedTypeX.Name name = (ResolvedTypeX.Name)factory.fromEclipse(sourceType); EclipseSourceType eclipseSourceType = (EclipseSourceType)name.getDelegate(); eclipseSourceType.checkPointcutDeclarations(); } ReferenceBinding[] memberTypes = sourceType.memberTypes; for (int i = 0, length = memberTypes.length; i < length; i++) { resolvePointcutDeclarations(((SourceTypeBinding) memberTypes[i]).scope); } } private void buildInterTypeAndPerClause(ClassScope s) { TypeDeclaration dec = s.referenceContext; if (dec instanceof AspectDeclaration) { ((AspectDeclaration)dec).buildInterTypeAndPerClause(s); } SourceTypeBinding sourceType = s.referenceContext.binding; // test classes don't extend aspects if (sourceType.superclass != null) { ResolvedTypeX parent = factory.fromEclipse(sourceType.superclass); if (parent.isAspect() && !(dec instanceof AspectDeclaration)) { factory.showMessage(IMessage.ERROR, "class \'" + new String(sourceType.sourceName) + "\' can not extend aspect \'" + parent.getName() + "\'", factory.fromEclipse(sourceType).getSourceLocation(), null); } } ReferenceBinding[] memberTypes = sourceType.memberTypes; for (int i = 0, length = memberTypes.length; i < length; i++) { buildInterTypeAndPerClause(((SourceTypeBinding) memberTypes[i]).scope); } } private void weaveInterTypeDeclarations(CompilationUnitScope unit, Collection typeMungers, Collection declareParents) { for (int i = 0, length = unit.topLevelTypes.length; i < length; i++) { weaveInterTypeDeclarations(unit.topLevelTypes[i], typeMungers, declareParents, false); } } private void weaveInterTypeDeclarations(SourceTypeBinding sourceType) { if (!factory.areTypeMungersFinished()) { if (!pendingTypesToWeave.contains(sourceType)) pendingTypesToWeave.add(sourceType); } else { weaveInterTypeDeclarations(sourceType, factory.getTypeMungers(), factory.getDeclareParents(), true); } } private void weaveInterTypeDeclarations(SourceTypeBinding sourceType, Collection typeMungers, Collection declareParents, boolean skipInners) { ResolvedTypeX onType = factory.fromEclipse(sourceType); WeaverStateInfo info = onType.getWeaverState(); if (info != null && !info.isOldStyle()) { Collection mungers = onType.getWeaverState().getTypeMungers(onType); //System.out.println(onType + " mungers: " + mungers); for (Iterator i = mungers.iterator(); i.hasNext(); ) { ConcreteTypeMunger m = (ConcreteTypeMunger)i.next(); EclipseTypeMunger munger = factory.makeEclipseTypeMunger(m); if (munger.munge(sourceType)) { if (onType.isInterface() && munger.getMunger().needsAccessToTopmostImplementor()) { if (!onType.getWorld().getCrosscuttingMembersSet().containsAspect(munger.getAspectType())) { dangerousInterfaces.put(onType, "implementors of " + onType + " must be woven by " + munger.getAspectType()); } } } } return; } //System.out.println("dangerousInterfaces: " + dangerousInterfaces); for (Iterator i = dangerousInterfaces.entrySet().iterator(); i.hasNext();) { Map.Entry entry = (Map.Entry) i.next(); ResolvedTypeX interfaceType = (ResolvedTypeX)entry.getKey(); if (onType.isTopmostImplementor(interfaceType)) { factory.showMessage(IMessage.ERROR, onType + ": " + entry.getValue(), onType.getSourceLocation(), null); } } boolean needOldStyleWarning = (info != null && info.isOldStyle()); onType.clearInterTypeMungers(); for (Iterator i = declareParents.iterator(); i.hasNext();) { doDeclareParents((DeclareParents)i.next(), sourceType); } for (Iterator i = typeMungers.iterator(); i.hasNext();) { EclipseTypeMunger munger = (EclipseTypeMunger) i.next(); if (munger.matches(onType)) { if (needOldStyleWarning) { factory.showMessage(IMessage.WARNING, "The class for " + onType + " should be recompiled with ajc-1.1.1 for best results", onType.getSourceLocation(), null); needOldStyleWarning = false; } onType.addInterTypeMunger(munger); AsmInterTypeRelationshipProvider.addRelationship(onType, munger); } } //???onType.checkInterTypeMungers(); onType.checkInterTypeMungers(); for (Iterator i = onType.getInterTypeMungers().iterator(); i.hasNext();) { EclipseTypeMunger munger = (EclipseTypeMunger) i.next(); //System.out.println("applying: " + munger + " to " + new String(sourceType.sourceName)); munger.munge(sourceType); } if (skipInners) return; ReferenceBinding[] memberTypes = sourceType.memberTypes; for (int i = 0, length = memberTypes.length; i < length; i++) { if (memberTypes[i] instanceof SourceTypeBinding) { weaveInterTypeDeclarations((SourceTypeBinding) memberTypes[i], typeMungers, declareParents, false); } } } private void doDeclareParents(DeclareParents declareParents, SourceTypeBinding sourceType) { List newParents = declareParents.findMatchingNewParents(factory.fromEclipse(sourceType)); if (!newParents.isEmpty()) { for (Iterator i = newParents.iterator(); i.hasNext(); ) { ResolvedTypeX parent = (ResolvedTypeX)i.next(); if (dangerousInterfaces.containsKey(parent)) { ResolvedTypeX onType = factory.fromEclipse(sourceType); factory.showMessage(IMessage.ERROR, onType + ": " + dangerousInterfaces.get(parent), onType.getSourceLocation(), null); } addParent(sourceType, parent); } } } private void addParent(SourceTypeBinding sourceType, ResolvedTypeX parent) { ReferenceBinding parentBinding = (ReferenceBinding)factory.makeTypeBinding(parent); if (parentBinding.isClass()) { sourceType.superclass = parentBinding; } else { ReferenceBinding[] oldI = sourceType.superInterfaces; ReferenceBinding[] newI; if (oldI == null) { newI = new ReferenceBinding[1]; newI[0] = parentBinding; } else { int n = oldI.length; newI = new ReferenceBinding[n+1]; System.arraycopy(oldI, 0, newI, 0, n); newI[n] = parentBinding; } sourceType.superInterfaces = newI; warnOnAddedInterface(factory.fromEclipse(sourceType),parent); } } public void warnOnAddedInterface (ResolvedTypeX type, ResolvedTypeX parent) { World world = factory.getWorld(); ResolvedTypeX serializable = world.resolve(TypeX.SERIALIZABLE); if (serializable.isAssignableFrom(type) && !serializable.isAssignableFrom(parent) && !LazyClassGen.hasSerialVersionUIDField(type)) { world.getLint().needsSerialVersionUIDField.signal( new String[] { type.getName().toString(), "added interface " + parent.getName().toString() }, null, null); } } private List pendingTypesToFinish = new ArrayList(); boolean inBinaryTypeCreation = false; public BinaryTypeBinding createBinaryTypeFrom( IBinaryType binaryType, PackageBinding packageBinding, boolean needFieldsAndMethods) { if (inBinaryTypeCreation) { BinaryTypeBinding ret = super.createBinaryTypeFrom( binaryType, packageBinding, needFieldsAndMethods); pendingTypesToFinish.add(ret); return ret; } inBinaryTypeCreation = true; try { BinaryTypeBinding ret = super.createBinaryTypeFrom( binaryType, packageBinding, needFieldsAndMethods); weaveInterTypeDeclarations(ret); return ret; } finally { inBinaryTypeCreation = false; if (!pendingTypesToFinish.isEmpty()) { for (Iterator i = pendingTypesToFinish.iterator(); i.hasNext(); ) { weaveInterTypeDeclarations((BinaryTypeBinding)i.next()); } pendingTypesToFinish.clear(); } } } }
67,774
Bug 67774 Nullpointer-exception in pointcuts using withincode() clause
Hi, I am getting null-pointer-exceptions whenever I try to specify a pointcut with a "withincode(Signature)" clause. E.g.: public aspect DetectSystemOutErrorUsage { pointcut allSystemOutAndSystemErrAccesses(): (get(* System.out) || get(* System.err)) ; declare warning: allSystemOutAndSystemErrAccesses() && !adviceexecution() && !within(com.tivoli.act..Test*) && !within(com.tivoli.act.log..*) && !execution(* com.tivoli.act..*.main(..)) && !execution(* com.tivoli.act..*.usage()) // && !withincode(* com.tivoli.act..*.main(..)) // && !withincode(* com.tivoli.act..*.usage()) : "Warning: use of System.out or System.err - consider logging instead!"; } In the above example excluding main() and usage() methods from the pointcut using an execution(...)-clause (shows) works but using a withincode()-clause (as commented) always yields an NPE: trouble in: null java.lang.NullPointerException at org.aspectj.weaver.patterns.SignaturePattern.matches (SignaturePattern.java:87) at org.aspectj.weaver.patterns.WithincodePointcut.match (WithincodePointcut.java:42) at org.aspectj.weaver.patterns.NotPointcut.match(NotPointcut.java:45) at org.aspectj.weaver.patterns.AndPointcut.match(AndPointcut.java:42) at org.aspectj.weaver.patterns.AndPointcut.match(AndPointcut.java:42) at org.aspectj.weaver.patterns.AndPointcut.match(AndPointcut.java:42) at org.aspectj.weaver.patterns.AndPointcut.match(AndPointcut.java:42) at org.aspectj.weaver.patterns.AndPointcut.match(AndPointcut.java:42) at org.aspectj.weaver.patterns.AndPointcut.match(AndPointcut.java:42) at org.aspectj.weaver.patterns.AndPointcut.match(AndPointcut.java:42) at org.aspectj.weaver.ShadowMunger.match(ShadowMunger.java:62) at org.aspectj.weaver.Checker.match(Checker.java:48) at org.aspectj.weaver.bcel.BcelClassWeaver.match (BcelClassWeaver.java:1121) at org.aspectj.weaver.bcel.BcelClassWeaver.matchInit (BcelClassWeaver.java:895) at org.aspectj.weaver.bcel.BcelClassWeaver.match (BcelClassWeaver.java:793) at org.aspectj.weaver.bcel.BcelClassWeaver.weave (BcelClassWeaver.java:343) at org.aspectj.weaver.bcel.BcelClassWeaver.weave (BcelClassWeaver.java:80) at org.aspectj.weaver.bcel.BcelWeaver.weave(BcelWeaver.java:724) at org.aspectj.weaver.bcel.BcelWeaver.weaveWithoutDump (BcelWeaver.java:689) at org.aspectj.weaver.bcel.BcelWeaver.weaveAndNotify (BcelWeaver.java:615) at org.aspectj.weaver.bcel.BcelWeaver.weave(BcelWeaver.java:563) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.weave (AjCompilerAdapter.java:239) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.afterCompiling (AjCompilerAdapter.java:114) at org.eclipse.jdt.internal.compiler.Compiler.compile(Compiler.java:376) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.performCompilation (AjBuildManager.java:601) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.doBuild (AjBuildManager.java:160) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.batchBuild (AjBuildManager.java:94) at org.aspectj.ajde.internal.CompilerAdapter.compile (CompilerAdapter.java:108) at org.aspectj.ajde.internal.AspectJBuildManager$CompilerThread.run (AspectJBuildManager.java:165) !SESSION Jun 18, 2004 10:49:48.666 --------------------------------------------- eclipse.buildId=I200406110010 java.version=1.4.2_03 java.vendor=Sun Microsystems Inc. BootLoader constants: OS=win32, ARCH=x86, WS=win32, NL=de_CH !ENTRY org.eclipse.ajdt.ui 4 0 Jun 18, 2004 10:49:48.666 !MESSAGE NullPointerException thrown: null !STACK 0 java.lang.NullPointerException at org.aspectj.weaver.patterns.SignaturePattern.matches (SignaturePattern.java:87) at org.aspectj.weaver.patterns.WithincodePointcut.match (WithincodePointcut.java:42) at org.aspectj.weaver.patterns.NotPointcut.match(NotPointcut.java:45) at org.aspectj.weaver.patterns.AndPointcut.match(AndPointcut.java:42) at org.aspectj.weaver.patterns.AndPointcut.match(AndPointcut.java:42) at org.aspectj.weaver.patterns.AndPointcut.match(AndPointcut.java:42) at org.aspectj.weaver.patterns.AndPointcut.match(AndPointcut.java:42) at org.aspectj.weaver.patterns.AndPointcut.match(AndPointcut.java:42) at org.aspectj.weaver.patterns.AndPointcut.match(AndPointcut.java:42) at org.aspectj.weaver.patterns.AndPointcut.match(AndPointcut.java:42) at org.aspectj.weaver.ShadowMunger.match(ShadowMunger.java:62) at org.aspectj.weaver.Checker.match(Checker.java:48) at org.aspectj.weaver.bcel.BcelClassWeaver.match (BcelClassWeaver.java:1121) at org.aspectj.weaver.bcel.BcelClassWeaver.matchInit (BcelClassWeaver.java:895) at org.aspectj.weaver.bcel.BcelClassWeaver.match (BcelClassWeaver.java:793) at org.aspectj.weaver.bcel.BcelClassWeaver.weave (BcelClassWeaver.java:343) at org.aspectj.weaver.bcel.BcelClassWeaver.weave (BcelClassWeaver.java:80) at org.aspectj.weaver.bcel.BcelWeaver.weave(BcelWeaver.java:724) at org.aspectj.weaver.bcel.BcelWeaver.weaveWithoutDump (BcelWeaver.java:689) at org.aspectj.weaver.bcel.BcelWeaver.weaveAndNotify (BcelWeaver.java:615) at org.aspectj.weaver.bcel.BcelWeaver.weave(BcelWeaver.java:563) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.weave (AjCompilerAdapter.java:239) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.afterCompiling (AjCompilerAdapter.java:114) at org.eclipse.jdt.internal.compiler.Compiler.compile(Compiler.java:376) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.performCompilation (AjBuildManager.java:601) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.doBuild (AjBuildManager.java:160) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.batchBuild (AjBuildManager.java:94) at org.aspectj.ajde.internal.CompilerAdapter.compile (CompilerAdapter.java:108) at org.aspectj.ajde.internal.AspectJBuildManager$CompilerThread.run (AspectJBuildManager.java:165) Michael
resolved fixed
7f19ab4
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2004-08-02T13:43:43Z
2004-06-18T09:13:20Z
tests/bugs/WithincodeNPE01.java
67,774
Bug 67774 Nullpointer-exception in pointcuts using withincode() clause
Hi, I am getting null-pointer-exceptions whenever I try to specify a pointcut with a "withincode(Signature)" clause. E.g.: public aspect DetectSystemOutErrorUsage { pointcut allSystemOutAndSystemErrAccesses(): (get(* System.out) || get(* System.err)) ; declare warning: allSystemOutAndSystemErrAccesses() && !adviceexecution() && !within(com.tivoli.act..Test*) && !within(com.tivoli.act.log..*) && !execution(* com.tivoli.act..*.main(..)) && !execution(* com.tivoli.act..*.usage()) // && !withincode(* com.tivoli.act..*.main(..)) // && !withincode(* com.tivoli.act..*.usage()) : "Warning: use of System.out or System.err - consider logging instead!"; } In the above example excluding main() and usage() methods from the pointcut using an execution(...)-clause (shows) works but using a withincode()-clause (as commented) always yields an NPE: trouble in: null java.lang.NullPointerException at org.aspectj.weaver.patterns.SignaturePattern.matches (SignaturePattern.java:87) at org.aspectj.weaver.patterns.WithincodePointcut.match (WithincodePointcut.java:42) at org.aspectj.weaver.patterns.NotPointcut.match(NotPointcut.java:45) at org.aspectj.weaver.patterns.AndPointcut.match(AndPointcut.java:42) at org.aspectj.weaver.patterns.AndPointcut.match(AndPointcut.java:42) at org.aspectj.weaver.patterns.AndPointcut.match(AndPointcut.java:42) at org.aspectj.weaver.patterns.AndPointcut.match(AndPointcut.java:42) at org.aspectj.weaver.patterns.AndPointcut.match(AndPointcut.java:42) at org.aspectj.weaver.patterns.AndPointcut.match(AndPointcut.java:42) at org.aspectj.weaver.patterns.AndPointcut.match(AndPointcut.java:42) at org.aspectj.weaver.ShadowMunger.match(ShadowMunger.java:62) at org.aspectj.weaver.Checker.match(Checker.java:48) at org.aspectj.weaver.bcel.BcelClassWeaver.match (BcelClassWeaver.java:1121) at org.aspectj.weaver.bcel.BcelClassWeaver.matchInit (BcelClassWeaver.java:895) at org.aspectj.weaver.bcel.BcelClassWeaver.match (BcelClassWeaver.java:793) at org.aspectj.weaver.bcel.BcelClassWeaver.weave (BcelClassWeaver.java:343) at org.aspectj.weaver.bcel.BcelClassWeaver.weave (BcelClassWeaver.java:80) at org.aspectj.weaver.bcel.BcelWeaver.weave(BcelWeaver.java:724) at org.aspectj.weaver.bcel.BcelWeaver.weaveWithoutDump (BcelWeaver.java:689) at org.aspectj.weaver.bcel.BcelWeaver.weaveAndNotify (BcelWeaver.java:615) at org.aspectj.weaver.bcel.BcelWeaver.weave(BcelWeaver.java:563) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.weave (AjCompilerAdapter.java:239) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.afterCompiling (AjCompilerAdapter.java:114) at org.eclipse.jdt.internal.compiler.Compiler.compile(Compiler.java:376) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.performCompilation (AjBuildManager.java:601) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.doBuild (AjBuildManager.java:160) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.batchBuild (AjBuildManager.java:94) at org.aspectj.ajde.internal.CompilerAdapter.compile (CompilerAdapter.java:108) at org.aspectj.ajde.internal.AspectJBuildManager$CompilerThread.run (AspectJBuildManager.java:165) !SESSION Jun 18, 2004 10:49:48.666 --------------------------------------------- eclipse.buildId=I200406110010 java.version=1.4.2_03 java.vendor=Sun Microsystems Inc. BootLoader constants: OS=win32, ARCH=x86, WS=win32, NL=de_CH !ENTRY org.eclipse.ajdt.ui 4 0 Jun 18, 2004 10:49:48.666 !MESSAGE NullPointerException thrown: null !STACK 0 java.lang.NullPointerException at org.aspectj.weaver.patterns.SignaturePattern.matches (SignaturePattern.java:87) at org.aspectj.weaver.patterns.WithincodePointcut.match (WithincodePointcut.java:42) at org.aspectj.weaver.patterns.NotPointcut.match(NotPointcut.java:45) at org.aspectj.weaver.patterns.AndPointcut.match(AndPointcut.java:42) at org.aspectj.weaver.patterns.AndPointcut.match(AndPointcut.java:42) at org.aspectj.weaver.patterns.AndPointcut.match(AndPointcut.java:42) at org.aspectj.weaver.patterns.AndPointcut.match(AndPointcut.java:42) at org.aspectj.weaver.patterns.AndPointcut.match(AndPointcut.java:42) at org.aspectj.weaver.patterns.AndPointcut.match(AndPointcut.java:42) at org.aspectj.weaver.patterns.AndPointcut.match(AndPointcut.java:42) at org.aspectj.weaver.ShadowMunger.match(ShadowMunger.java:62) at org.aspectj.weaver.Checker.match(Checker.java:48) at org.aspectj.weaver.bcel.BcelClassWeaver.match (BcelClassWeaver.java:1121) at org.aspectj.weaver.bcel.BcelClassWeaver.matchInit (BcelClassWeaver.java:895) at org.aspectj.weaver.bcel.BcelClassWeaver.match (BcelClassWeaver.java:793) at org.aspectj.weaver.bcel.BcelClassWeaver.weave (BcelClassWeaver.java:343) at org.aspectj.weaver.bcel.BcelClassWeaver.weave (BcelClassWeaver.java:80) at org.aspectj.weaver.bcel.BcelWeaver.weave(BcelWeaver.java:724) at org.aspectj.weaver.bcel.BcelWeaver.weaveWithoutDump (BcelWeaver.java:689) at org.aspectj.weaver.bcel.BcelWeaver.weaveAndNotify (BcelWeaver.java:615) at org.aspectj.weaver.bcel.BcelWeaver.weave(BcelWeaver.java:563) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.weave (AjCompilerAdapter.java:239) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.afterCompiling (AjCompilerAdapter.java:114) at org.eclipse.jdt.internal.compiler.Compiler.compile(Compiler.java:376) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.performCompilation (AjBuildManager.java:601) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.doBuild (AjBuildManager.java:160) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.batchBuild (AjBuildManager.java:94) at org.aspectj.ajde.internal.CompilerAdapter.compile (CompilerAdapter.java:108) at org.aspectj.ajde.internal.AspectJBuildManager$CompilerThread.run (AspectJBuildManager.java:165) Michael
resolved fixed
7f19ab4
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2004-08-02T13:43:43Z
2004-06-18T09:13:20Z
weaver/src/org/aspectj/weaver/bcel/BcelShadow.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Common Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * PARC initial implementation * ******************************************************************/ package org.aspectj.weaver.bcel; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.apache.bcel.Constants; import org.apache.bcel.classfile.Field; import org.apache.bcel.generic.ACONST_NULL; import org.apache.bcel.generic.ArrayType; import org.apache.bcel.generic.BranchInstruction; import org.apache.bcel.generic.ConstantPoolGen; import org.apache.bcel.generic.DUP; import org.apache.bcel.generic.DUP_X1; import org.apache.bcel.generic.FieldInstruction; import org.apache.bcel.generic.INVOKESPECIAL; import org.apache.bcel.generic.INVOKESTATIC; import org.apache.bcel.generic.Instruction; import org.apache.bcel.generic.InstructionConstants; import org.apache.bcel.generic.InstructionFactory; import org.apache.bcel.generic.InstructionHandle; import org.apache.bcel.generic.InstructionList; import org.apache.bcel.generic.InstructionTargeter; import org.apache.bcel.generic.InvokeInstruction; import org.apache.bcel.generic.NEW; import org.apache.bcel.generic.ObjectType; import org.apache.bcel.generic.ReturnInstruction; import org.apache.bcel.generic.SWAP; import org.apache.bcel.generic.StoreInstruction; import org.apache.bcel.generic.TargetLostException; import org.apache.bcel.generic.Type; import org.aspectj.bridge.ISourceLocation; import org.aspectj.weaver.Advice; import org.aspectj.weaver.AdviceKind; import org.aspectj.weaver.AjcMemberMaker; import org.aspectj.weaver.BCException; import org.aspectj.weaver.IntMap; import org.aspectj.weaver.Member; import org.aspectj.weaver.NameMangler; import org.aspectj.weaver.ResolvedMember; import org.aspectj.weaver.ResolvedTypeX; import org.aspectj.weaver.Shadow; import org.aspectj.weaver.ShadowMunger; import org.aspectj.weaver.TypeX; import org.aspectj.weaver.World; import org.aspectj.weaver.ast.Var; /* * Some fun implementation stuff: * * * expressionKind advice is non-execution advice * * may have a target. * * if the body is extracted, it will be extracted into * a static method. The first argument to the static * method is the target * * advice may expose a this object, but that's the advice's * consideration, not ours. This object will NOT be cached in another * local, but will always come from frame zero. * * * non-expressionKind advice is execution advice * * may have a this. * * target is same as this, and is exposed that way to advice * (i.e., target will not be cached, will always come from frame zero) * * if the body is extracted, it will be extracted into a method * with same static/dynamic modifier as enclosing method. If non-static, * target of callback call will be this. * * * because of these two facts, the setup of the actual arguments (including * possible target) callback method is the same for both kinds of advice: * push the targetVar, if it exists (it will not exist for advice on static * things), then push all the argVars. * * Protected things: * * * the above is sufficient for non-expressionKind advice for protected things, * since the target will always be this. * * * For expressionKind things, we have to modify the signature of the callback * method slightly. For non-static expressionKind things, we modify * the first argument of the callback method NOT to be the type specified * by the method/field signature (the owner), but rather we type it to * the currentlyEnclosing type. We are guaranteed this will be fine, * since the verifier verifies that the target is a subtype of the currently * enclosingType. * * Worries: * * * ConstructorCalls will be weirder than all of these, since they * supposedly don't have a target (according to AspectJ), but they clearly * do have a target of sorts, just one that needs to be pushed on the stack, * dupped, and not touched otherwise until the constructor runs. * * @author Jim Hugunin * @author Erik Hilsdale * */ public class BcelShadow extends Shadow { private ShadowRange range; private final BcelWorld world; private final LazyMethodGen enclosingMethod; private boolean fallsThrough; //XXX not used anymore // ---- initialization /** * This generates an unassociated shadow, rooted in a particular method but not rooted * to any particular point in the code. It should be given to a rooted ShadowRange * in the {@link ShadowRange#associateWithShadow(BcelShadow)} method. */ public BcelShadow( BcelWorld world, Kind kind, Member signature, LazyMethodGen enclosingMethod, BcelShadow enclosingShadow) { super(kind, signature, enclosingShadow); this.world = world; this.enclosingMethod = enclosingMethod; fallsThrough = kind.argsOnStack(); } // ---- copies all state, including Shadow's mungers... public BcelShadow copyInto(LazyMethodGen recipient, BcelShadow enclosing) { BcelShadow s = new BcelShadow(world, getKind(), getSignature(), recipient, enclosing); List src = mungers; List dest = s.mungers; for (Iterator i = src.iterator(); i.hasNext(); ) { dest.add(i.next()); } return s; } // ---- overridden behaviour public World getIWorld() { return world; } private void deleteNewAndDup() { final ConstantPoolGen cpg = getEnclosingClass().getConstantPoolGen(); int depth = 1; InstructionHandle ih = range.getStart(); while (true) { Instruction inst = ih.getInstruction(); if (inst instanceof INVOKESPECIAL && ((INVOKESPECIAL) inst).getName(cpg).equals("<init>")) { depth++; } else if (inst instanceof NEW) { depth--; if (depth == 0) break; } ih = ih.getPrev(); } // now IH points to the NEW. We're followed by the DUP, and that is followed // by the actual instruciton we care about. InstructionHandle newHandle = ih; InstructionHandle endHandle = newHandle.getNext(); InstructionHandle nextHandle; if (endHandle.getInstruction() instanceof DUP) { nextHandle = endHandle.getNext(); retargetFrom(newHandle, nextHandle); retargetFrom(endHandle, nextHandle); } else if (endHandle.getInstruction() instanceof DUP_X1) { InstructionHandle dupHandle = endHandle; endHandle = endHandle.getNext(); nextHandle = endHandle.getNext(); if (endHandle.getInstruction() instanceof SWAP) {} else { // XXX see next XXX comment throw new RuntimeException("Unhandled kind of new " + endHandle); } retargetFrom(newHandle, nextHandle); retargetFrom(dupHandle, nextHandle); retargetFrom(endHandle, nextHandle); } else { endHandle = newHandle; nextHandle = endHandle.getNext(); retargetFrom(newHandle, nextHandle); // add a POP here... we found a NEW w/o a dup or anything else, so // we must be in statement context. getRange().insert(InstructionConstants.POP, Range.OutsideAfter); } // assert (dupHandle.getInstruction() instanceof DUP); try { range.getBody().delete(newHandle, endHandle); } catch (TargetLostException e) { throw new BCException("shouldn't happen"); } } private void retargetFrom(InstructionHandle old, InstructionHandle fresh) { InstructionTargeter[] sources = old.getTargeters(); if (sources != null) { for (int i = sources.length - 1; i >= 0; i--) { sources[i].updateTarget(old, fresh); } } } protected void prepareForMungers() { // if we're a constructor call, we need to remove the new:dup or the new:dup_x1:swap, // and store all our // arguments on the frame. // ??? This is a bit of a hack (for the Java langauge). We do this because // we sometime add code "outsideBefore" when dealing with weaving join points. We only // do this for exposing state that is on the stack. It turns out to just work for // everything except for constructor calls and exception handlers. If we were to clean // this up, every ShadowRange would have three instructionHandle points, the start of // the arg-setup code, the start of the running code, and the end of the running code. if (getKind() == ConstructorCall) { deleteNewAndDup(); initializeArgVars(); } else if (getKind() == ExceptionHandler) { ShadowRange range = getRange(); InstructionList body = range.getBody(); InstructionHandle start = range.getStart(); InstructionHandle freshIh = body.insert(start, InstructionConstants.NOP); InstructionTargeter[] targeters = start.getTargeters(); for (int i = 0; i < targeters.length; i++) { InstructionTargeter t = targeters[i]; if (t instanceof ExceptionRange) { ExceptionRange er = (ExceptionRange) t; er.updateTarget(start, freshIh, body); } } } // now we ask each munger to request our state isThisJoinPointLazy = world.isXlazyTjp(); for (Iterator iter = mungers.iterator(); iter.hasNext();) { ShadowMunger munger = (ShadowMunger) iter.next(); munger.specializeOn(this); } initializeThisJoinPoint(); // If we are an expression kind, we require our target/arguments on the stack // before we do our actual thing. However, they may have been removed // from the stack as the shadowMungers have requested state. // if any of our shadowMungers requested either the arguments or target, // the munger will have added code // to pop the target/arguments into temporary variables, represented by // targetVar and argVars. In such a case, we must make sure to re-push the // values. // If we are nonExpressionKind, we don't expect arguments on the stack // so this is moot. If our argVars happen to be null, then we know that // no ShadowMunger has squirrelled away our arguments, so they're still // on the stack. InstructionFactory fact = getFactory(); if (getKind().argsOnStack() && argVars != null) { range.insert( BcelRenderer.renderExprs(fact, world, argVars), Range.InsideBefore); if (targetVar != null) { range.insert( BcelRenderer.renderExpr(fact, world, targetVar), Range.InsideBefore); } if (getKind() == ConstructorCall) { range.insert((Instruction) InstructionFactory.createDup(1), Range.InsideBefore); range.insert( fact.createNew( (ObjectType) BcelWorld.makeBcelType( getSignature().getDeclaringType())), Range.InsideBefore); } } } // ---- getters public ShadowRange getRange() { return range; } public void setRange(ShadowRange range) { this.range = range; } public int getSourceLine() { if (range == null) { if (getEnclosingMethod().hasBody()) { return Utility.getSourceLine(getEnclosingMethod().getBody().getStart()); } else { return 0; } } int ret = Utility.getSourceLine(range.getStart()); if (ret < 0) return 0; return ret; } // overrides public TypeX getEnclosingType() { return getEnclosingClass().getType(); } public LazyClassGen getEnclosingClass() { return enclosingMethod.getEnclosingClass(); } public BcelWorld getWorld() { return world; } // ---- factory methods public static BcelShadow makeConstructorExecution( BcelWorld world, LazyMethodGen enclosingMethod, InstructionHandle justBeforeStart) { final InstructionList body = enclosingMethod.getBody(); BcelShadow s = new BcelShadow( world, ConstructorExecution, world.makeMethodSignature(enclosingMethod), enclosingMethod, null); ShadowRange r = new ShadowRange(body); r.associateWithShadow(s); r.associateWithTargets( Range.genStart(body, justBeforeStart.getNext()), Range.genEnd(body)); return s; } public static BcelShadow makeStaticInitialization( BcelWorld world, LazyMethodGen enclosingMethod) { InstructionList body = enclosingMethod.getBody(); // move the start past ajc$preClinit InstructionHandle clinitStart = body.getStart(); if (clinitStart.getInstruction() instanceof InvokeInstruction) { InvokeInstruction ii = (InvokeInstruction)clinitStart.getInstruction(); if (ii .getName(enclosingMethod.getEnclosingClass().getConstantPoolGen()) .equals(NameMangler.AJC_PRE_CLINIT_NAME)) { clinitStart = clinitStart.getNext(); } } InstructionHandle clinitEnd = body.getEnd(); //XXX should move the end before the postClinit, but the return is then tricky... // if (clinitEnd.getInstruction() instanceof InvokeInstruction) { // InvokeInstruction ii = (InvokeInstruction)clinitEnd.getInstruction(); // if (ii.getName(enclosingMethod.getEnclosingClass().getConstantPoolGen()).equals(NameMangler.AJC_POST_CLINIT_NAME)) { // clinitEnd = clinitEnd.getPrev(); // } // } BcelShadow s = new BcelShadow( world, StaticInitialization, world.makeMethodSignature(enclosingMethod), enclosingMethod, null); ShadowRange r = new ShadowRange(body); r.associateWithShadow(s); r.associateWithTargets( Range.genStart(body, clinitStart), Range.genEnd(body, clinitEnd)); return s; } /** Make the shadow for an exception handler. Currently makes an empty shadow that * only allows before advice to be woven into it. */ public static BcelShadow makeExceptionHandler( BcelWorld world, ExceptionRange exceptionRange, LazyMethodGen enclosingMethod, InstructionHandle startOfHandler, BcelShadow enclosingShadow) { InstructionList body = enclosingMethod.getBody(); TypeX catchType = exceptionRange.getCatchType(); TypeX inType = enclosingMethod.getEnclosingClass().getType(); ResolvedMember sig = Member.makeExceptionHandlerSignature(inType, catchType); sig.parameterNames = new String[] {findHandlerParamName(startOfHandler)}; BcelShadow s = new BcelShadow( world, ExceptionHandler, sig, enclosingMethod, enclosingShadow); ShadowRange r = new ShadowRange(body); r.associateWithShadow(s); InstructionHandle start = Range.genStart(body, startOfHandler); InstructionHandle end = Range.genEnd(body, start); r.associateWithTargets(start, end); exceptionRange.updateTarget(startOfHandler, start, body); return s; } private static String findHandlerParamName(InstructionHandle startOfHandler) { if (startOfHandler.getInstruction() instanceof StoreInstruction && startOfHandler.getNext() != null) { int slot = ((StoreInstruction)startOfHandler.getInstruction()).getIndex(); //System.out.println("got store: " + startOfHandler.getInstruction() + ", " + index); InstructionTargeter[] targeters = startOfHandler.getNext().getTargeters(); if (targeters!=null) { for (int i=targeters.length-1; i >= 0; i--) { if (targeters[i] instanceof LocalVariableTag) { LocalVariableTag t = (LocalVariableTag)targeters[i]; if (t.getSlot() == slot) { return t.getName(); } //System.out.println("tag: " + targeters[i]); } } } } return "<missing>"; } /** create an init join point associated w/ an interface in the body of a constructor */ public static BcelShadow makeIfaceInitialization( BcelWorld world, LazyMethodGen constructor, Member interfaceConstructorSignature) { InstructionList body = constructor.getBody(); // TypeX inType = constructor.getEnclosingClass().getType(); BcelShadow s = new BcelShadow( world, Initialization, interfaceConstructorSignature, constructor, null); s.fallsThrough = true; // ShadowRange r = new ShadowRange(body); // r.associateWithShadow(s); // InstructionHandle start = Range.genStart(body, handle); // InstructionHandle end = Range.genEnd(body, handle); // // r.associateWithTargets(start, end); return s; } public void initIfaceInitializer(InstructionHandle end) { final InstructionList body = enclosingMethod.getBody(); ShadowRange r = new ShadowRange(body); r.associateWithShadow(this); InstructionHandle nop = body.insert(end, InstructionConstants.NOP); r.associateWithTargets( Range.genStart(body, nop), Range.genEnd(body, nop)); } // public static BcelShadow makeIfaceConstructorExecution( // BcelWorld world, // LazyMethodGen constructor, // InstructionHandle next, // Member interfaceConstructorSignature) // { // // final InstructionFactory fact = constructor.getEnclosingClass().getFactory(); // InstructionList body = constructor.getBody(); // // TypeX inType = constructor.getEnclosingClass().getType(); // BcelShadow s = // new BcelShadow( // world, // ConstructorExecution, // interfaceConstructorSignature, // constructor, // null); // s.fallsThrough = true; // ShadowRange r = new ShadowRange(body); // r.associateWithShadow(s); // // ??? this may or may not work // InstructionHandle start = Range.genStart(body, next); // //InstructionHandle end = Range.genEnd(body, body.append(start, fact.NOP)); // InstructionHandle end = Range.genStart(body, next); // //body.append(start, fact.NOP); // // r.associateWithTargets(start, end); // return s; // } /** Create an initialization join point associated with a constructor, but not * with any body of code yet. If this is actually matched, it's range will be set * when we inline self constructors. * * @param constructor The constructor starting this initialization. */ public static BcelShadow makeUnfinishedInitialization( BcelWorld world, LazyMethodGen constructor) { return new BcelShadow( world, Initialization, world.makeMethodSignature(constructor), constructor, null); } public static BcelShadow makeUnfinishedPreinitialization( BcelWorld world, LazyMethodGen constructor) { BcelShadow ret = new BcelShadow( world, PreInitialization, world.makeMethodSignature(constructor), constructor, null); ret.fallsThrough = true; return ret; } public static BcelShadow makeMethodExecution( BcelWorld world, LazyMethodGen enclosingMethod, boolean lazyInit) { if (!lazyInit) return makeMethodExecution(world, enclosingMethod); BcelShadow s = new BcelShadow( world, MethodExecution, enclosingMethod.getMemberView(), enclosingMethod, null); return s; } public void init() { if (range != null) return; final InstructionList body = enclosingMethod.getBody(); ShadowRange r = new ShadowRange(body); r.associateWithShadow(this); r.associateWithTargets( Range.genStart(body), Range.genEnd(body)); } public static BcelShadow makeMethodExecution( BcelWorld world, LazyMethodGen enclosingMethod) { return makeShadowForMethod(world, enclosingMethod, MethodExecution, enclosingMethod.getMemberView()); //world.makeMethodSignature(enclosingMethod)); } public static BcelShadow makeShadowForMethod(BcelWorld world, LazyMethodGen enclosingMethod, Shadow.Kind kind, Member sig) { final InstructionList body = enclosingMethod.getBody(); BcelShadow s = new BcelShadow( world, kind, sig, enclosingMethod, null); ShadowRange r = new ShadowRange(body); r.associateWithShadow(s); r.associateWithTargets( Range.genStart(body), Range.genEnd(body)); return s; } public static BcelShadow makeAdviceExecution( BcelWorld world, LazyMethodGen enclosingMethod) { final InstructionList body = enclosingMethod.getBody(); BcelShadow s = new BcelShadow( world, AdviceExecution, world.makeMethodSignature(enclosingMethod, Member.ADVICE), enclosingMethod, null); ShadowRange r = new ShadowRange(body); r.associateWithShadow(s); r.associateWithTargets(Range.genStart(body), Range.genEnd(body)); return s; } // constructor call shadows are <em>initially</em> just around the // call to the constructor. If ANY advice gets put on it, we move // the NEW instruction inside the join point, which involves putting // all the arguments in temps. public static BcelShadow makeConstructorCall( BcelWorld world, LazyMethodGen enclosingMethod, InstructionHandle callHandle, BcelShadow enclosingShadow) { final InstructionList body = enclosingMethod.getBody(); Member sig = BcelWorld.makeMethodSignature( enclosingMethod.getEnclosingClass(), (InvokeInstruction) callHandle.getInstruction()); BcelShadow s = new BcelShadow( world, ConstructorCall, sig, enclosingMethod, enclosingShadow); ShadowRange r = new ShadowRange(body); r.associateWithShadow(s); r.associateWithTargets( Range.genStart(body, callHandle), Range.genEnd(body, callHandle)); retargetAllBranches(callHandle, r.getStart()); return s; } public static BcelShadow makeMethodCall( BcelWorld world, LazyMethodGen enclosingMethod, InstructionHandle callHandle, BcelShadow enclosingShadow) { final InstructionList body = enclosingMethod.getBody(); BcelShadow s = new BcelShadow( world, MethodCall, BcelWorld.makeMethodSignature( enclosingMethod.getEnclosingClass(), (InvokeInstruction) callHandle.getInstruction()), enclosingMethod, enclosingShadow); ShadowRange r = new ShadowRange(body); r.associateWithShadow(s); r.associateWithTargets( Range.genStart(body, callHandle), Range.genEnd(body, callHandle)); retargetAllBranches(callHandle, r.getStart()); return s; } public static BcelShadow makeShadowForMethodCall( BcelWorld world, LazyMethodGen enclosingMethod, InstructionHandle callHandle, BcelShadow enclosingShadow, Kind kind, ResolvedMember sig) { final InstructionList body = enclosingMethod.getBody(); BcelShadow s = new BcelShadow( world, kind, sig, enclosingMethod, enclosingShadow); ShadowRange r = new ShadowRange(body); r.associateWithShadow(s); r.associateWithTargets( Range.genStart(body, callHandle), Range.genEnd(body, callHandle)); retargetAllBranches(callHandle, r.getStart()); return s; } public static BcelShadow makeFieldGet( BcelWorld world, LazyMethodGen enclosingMethod, InstructionHandle getHandle, BcelShadow enclosingShadow) { final InstructionList body = enclosingMethod.getBody(); BcelShadow s = new BcelShadow( world, FieldGet, BcelWorld.makeFieldSignature( enclosingMethod.getEnclosingClass(), (FieldInstruction) getHandle.getInstruction()), enclosingMethod, enclosingShadow); ShadowRange r = new ShadowRange(body); r.associateWithShadow(s); r.associateWithTargets( Range.genStart(body, getHandle), Range.genEnd(body, getHandle)); retargetAllBranches(getHandle, r.getStart()); return s; } public static BcelShadow makeFieldSet( BcelWorld world, LazyMethodGen enclosingMethod, InstructionHandle setHandle, BcelShadow enclosingShadow) { final InstructionList body = enclosingMethod.getBody(); BcelShadow s = new BcelShadow( world, FieldSet, BcelWorld.makeFieldSignature( enclosingMethod.getEnclosingClass(), (FieldInstruction) setHandle.getInstruction()), enclosingMethod, enclosingShadow); ShadowRange r = new ShadowRange(body); r.associateWithShadow(s); r.associateWithTargets( Range.genStart(body, setHandle), Range.genEnd(body, setHandle)); retargetAllBranches(setHandle, r.getStart()); return s; } public static void retargetAllBranches(InstructionHandle from, InstructionHandle to) { InstructionTargeter[] sources = from.getTargeters(); if (sources != null) { for (int i = sources.length - 1; i >= 0; i--) { InstructionTargeter source = sources[i]; if (source instanceof BranchInstruction) { source.updateTarget(from, to); } } } } // // ---- type access methods // private ObjectType getTargetBcelType() { // return (ObjectType) BcelWorld.makeBcelType(getTargetType()); // } // private Type getArgBcelType(int arg) { // return BcelWorld.makeBcelType(getArgType(arg)); // } // ---- kinding /** * If the end of my range has no real instructions following then * my context needs a return at the end. */ public boolean terminatesWithReturn() { return getRange().getRealNext() == null; } /** * Is arg0 occupied with the value of this */ public boolean arg0HoldsThis() { if (getKind().isEnclosingKind()) { return !getSignature().isStatic(); } else if (enclosingShadow == null) { //XXX this is mostly right // this doesn't do the right thing for calls in the pre part of introduced constructors. return !enclosingMethod.isStatic(); } else { return ((BcelShadow)enclosingShadow).arg0HoldsThis(); } } // ---- argument getting methods private BcelVar thisVar = null; private BcelVar targetVar = null; private BcelVar[] argVars = null; public Var getThisVar() { if (!hasThis()) { throw new IllegalStateException("no this"); } initializeThisVar(); return thisVar; } public Var getTargetVar() { if (!hasTarget()) { throw new IllegalStateException("no target"); } initializeTargetVar(); return targetVar; } public Var getArgVar(int i) { initializeArgVars(); return argVars[i]; } // reflective thisJoinPoint support private BcelVar thisJoinPointVar = null; private boolean isThisJoinPointLazy; private int lazyTjpConsumers = 0; private BcelVar thisJoinPointStaticPartVar = null; // private BcelVar thisEnclosingJoinPointStaticPartVar = null; public final Var getThisJoinPointStaticPartVar() { return getThisJoinPointStaticPartBcelVar(); } public final Var getThisEnclosingJoinPointStaticPartVar() { return getThisEnclosingJoinPointStaticPartBcelVar(); } public void requireThisJoinPoint(boolean hasGuardTest) { if (!hasGuardTest) { isThisJoinPointLazy = false; } else { lazyTjpConsumers++; } if (thisJoinPointVar == null) { thisJoinPointVar = genTempVar(TypeX.forName("org.aspectj.lang.JoinPoint")); } } public Var getThisJoinPointVar() { requireThisJoinPoint(false); return thisJoinPointVar; } void initializeThisJoinPoint() { if (thisJoinPointVar == null) return; if (isThisJoinPointLazy) { isThisJoinPointLazy = checkLazyTjp(); } if (isThisJoinPointLazy) { createThisJoinPoint(); // make sure any state needed is initialized, but throw the instructions out if (lazyTjpConsumers == 1) return; // special case only one lazyTjpUser InstructionFactory fact = getFactory(); InstructionList il = new InstructionList(); il.append(InstructionConstants.ACONST_NULL); il.append(thisJoinPointVar.createStore(fact)); range.insert(il, Range.OutsideBefore); } else { InstructionFactory fact = getFactory(); InstructionList il = createThisJoinPoint(); il.append(thisJoinPointVar.createStore(fact)); range.insert(il, Range.OutsideBefore); } } private boolean checkLazyTjp() { // check for around advice for (Iterator i = mungers.iterator(); i.hasNext();) { ShadowMunger munger = (ShadowMunger) i.next(); if (munger instanceof Advice) { if ( ((Advice)munger).getKind() == AdviceKind.Around) { world.getLint().canNotImplementLazyTjp.signal( new String[] {toString()}, getSourceLocation(), new ISourceLocation[] { munger.getSourceLocation() } ); return false; } } } return true; } InstructionList loadThisJoinPoint() { InstructionFactory fact = getFactory(); InstructionList il = new InstructionList(); if (isThisJoinPointLazy) { il.append(createThisJoinPoint()); if (lazyTjpConsumers > 1) { il.append(thisJoinPointVar.createStore(fact)); InstructionHandle end = il.append(thisJoinPointVar.createLoad(fact)); il.insert(InstructionFactory.createBranchInstruction(Constants.IFNONNULL, end)); il.insert(thisJoinPointVar.createLoad(fact)); } } else { thisJoinPointVar.appendLoad(il, fact); } return il; } InstructionList createThisJoinPoint() { InstructionFactory fact = getFactory(); InstructionList il = new InstructionList(); BcelVar staticPart = getThisJoinPointStaticPartBcelVar(); staticPart.appendLoad(il, fact); if (hasThis()) { ((BcelVar)getThisVar()).appendLoad(il, fact); } else { il.append(new ACONST_NULL()); } if (hasTarget()) { ((BcelVar)getTargetVar()).appendLoad(il, fact); } else { il.append(new ACONST_NULL()); } switch(getArgCount()) { case 0: il.append(fact.createInvoke("org.aspectj.runtime.reflect.Factory", "makeJP", LazyClassGen.tjpType, new Type[] { LazyClassGen.staticTjpType, Type.OBJECT, Type.OBJECT}, Constants.INVOKESTATIC)); break; case 1: ((BcelVar)getArgVar(0)).appendLoadAndConvert(il, fact, world.resolve(ResolvedTypeX.OBJECT)); il.append(fact.createInvoke("org.aspectj.runtime.reflect.Factory", "makeJP", LazyClassGen.tjpType, new Type[] { LazyClassGen.staticTjpType, Type.OBJECT, Type.OBJECT, Type.OBJECT}, Constants.INVOKESTATIC)); break; case 2: ((BcelVar)getArgVar(0)).appendLoadAndConvert(il, fact, world.resolve(ResolvedTypeX.OBJECT)); ((BcelVar)getArgVar(1)).appendLoadAndConvert(il, fact, world.resolve(ResolvedTypeX.OBJECT)); il.append(fact.createInvoke("org.aspectj.runtime.reflect.Factory", "makeJP", LazyClassGen.tjpType, new Type[] { LazyClassGen.staticTjpType, Type.OBJECT, Type.OBJECT, Type.OBJECT, Type.OBJECT}, Constants.INVOKESTATIC)); break; default: il.append(makeArgsObjectArray()); il.append(fact.createInvoke("org.aspectj.runtime.reflect.Factory", "makeJP", LazyClassGen.tjpType, new Type[] { LazyClassGen.staticTjpType, Type.OBJECT, Type.OBJECT, new ArrayType(Type.OBJECT, 1)}, Constants.INVOKESTATIC)); break; } return il; } public BcelVar getThisJoinPointStaticPartBcelVar() { if (thisJoinPointStaticPartVar == null) { Field field = getEnclosingClass().getTjpField(this); thisJoinPointStaticPartVar = new BcelFieldRef( world.resolve(TypeX.forName("org.aspectj.lang.JoinPoint$StaticPart")), getEnclosingClass().getClassName(), field.getName()); // getEnclosingClass().warnOnAddedStaticInitializer(this,munger.getSourceLocation()); } return thisJoinPointStaticPartVar; } public BcelVar getThisEnclosingJoinPointStaticPartBcelVar() { if (enclosingShadow == null) { // the enclosing of an execution is itself return getThisJoinPointStaticPartBcelVar(); } else { return ((BcelShadow)enclosingShadow).getThisJoinPointStaticPartBcelVar(); } } //??? need to better understand all the enclosing variants public Member getEnclosingCodeSignature() { if (getKind().isEnclosingKind()) { return getSignature(); } else if (enclosingShadow == null) { return getEnclosingMethod().getMemberView(); } else { return enclosingShadow.getSignature(); } } private InstructionList makeArgsObjectArray() { InstructionFactory fact = getFactory(); BcelVar arrayVar = genTempVar(TypeX.OBJECTARRAY); final InstructionList il = new InstructionList(); int alen = getArgCount() ; il.append(Utility.createConstant(fact, alen)); il.append((Instruction)fact.createNewArray(Type.OBJECT, (short)1)); arrayVar.appendStore(il, fact); int stateIndex = 0; for (int i = 0, len = getArgCount(); i<len; i++) { arrayVar.appendConvertableArrayStore(il, fact, stateIndex, (BcelVar)getArgVar(i)); stateIndex++; } arrayVar.appendLoad(il, fact); return il; } // ---- initializing var tables /* initializing this is doesn't do anything, because this * is protected from side-effects, so we don't need to copy its location */ private void initializeThisVar() { if (thisVar != null) return; thisVar = new BcelVar(getThisType().resolve(world), 0); thisVar.setPositionInAroundState(0); } public void initializeTargetVar() { InstructionFactory fact = getFactory(); if (targetVar != null) return; if (getKind().isTargetSameAsThis()) { if (hasThis()) initializeThisVar(); targetVar = thisVar; } else { initializeArgVars(); // gotta pop off the args before we find the target TypeX type = getTargetType(); targetVar = genTempVar(type, "ajc$target"); range.insert(targetVar.createStore(fact), Range.OutsideBefore); targetVar.setPositionInAroundState(hasThis() ? 1 : 0); } } public void initializeArgVars() { if (argVars != null) return; InstructionFactory fact = getFactory(); int len = getArgCount(); argVars = new BcelVar[len]; int positionOffset = (hasTarget() ? 1 : 0) + ((hasThis() && !getKind().isTargetSameAsThis()) ? 1 : 0); if (getKind().argsOnStack()) { // we move backwards because we're popping off the stack for (int i = len - 1; i >= 0; i--) { TypeX type = getArgType(i); BcelVar tmp = genTempVar(type, "ajc$arg" + i); range.insert(tmp.createStore(getFactory()), Range.OutsideBefore); int position = i; position += positionOffset; tmp.setPositionInAroundState(position); argVars[i] = tmp; } } else { int index = 0; if (arg0HoldsThis()) index++; for (int i = 0; i < len; i++) { TypeX type = getArgType(i); BcelVar tmp = genTempVar(type, "ajc$arg" + i); range.insert(tmp.createCopyFrom(fact, index), Range.OutsideBefore); argVars[i] = tmp; int position = i; position += positionOffset; // System.out.println("set position: " + tmp + ", " + position + " in " + this); // System.out.println(" hasThis: " + hasThis() + ", hasTarget: " + hasTarget()); tmp.setPositionInAroundState(position); index += type.getSize(); } } } public void initializeForAroundClosure() { initializeArgVars(); if (hasTarget()) initializeTargetVar(); if (hasThis()) initializeThisVar(); // System.out.println("initialized: " + this + " thisVar = " + thisVar); } // ---- weave methods void weaveBefore(BcelAdvice munger) { range.insert( munger.getAdviceInstructions(this, null, range.getRealStart()), Range.InsideBefore); } public void weaveAfter(BcelAdvice munger) { weaveAfterThrowing(munger, TypeX.THROWABLE); weaveAfterReturning(munger); } /** * We guarantee that the return value is on the top of the stack when * munger.getAdviceInstructions() will be run * (Unless we have a void return type in which case there's nothing) */ public void weaveAfterReturning(BcelAdvice munger) { // InstructionFactory fact = getFactory(); List returns = new ArrayList(); Instruction ret = null; for (InstructionHandle ih = range.getStart(); ih != range.getEnd(); ih = ih.getNext()) { if (ih.getInstruction() instanceof ReturnInstruction) { returns.add(ih); ret = Utility.copyInstruction(ih.getInstruction()); } } InstructionList retList; InstructionHandle afterAdvice; if (ret != null) { retList = new InstructionList(ret); afterAdvice = retList.getStart(); } else /* if (munger.hasDynamicTests()) */ { retList = new InstructionList(InstructionConstants.NOP); afterAdvice = retList.getStart(); // } else { // retList = new InstructionList(); // afterAdvice = null; } InstructionList advice = new InstructionList(); BcelVar tempVar = null; if (munger.hasExtraParameter()) { TypeX tempVarType = getReturnType(); if (tempVarType.equals(ResolvedTypeX.VOID)) { tempVar = genTempVar(TypeX.OBJECT); advice.append(InstructionConstants.ACONST_NULL); tempVar.appendStore(advice, getFactory()); } else { tempVar = genTempVar(tempVarType); advice.append(InstructionFactory.createDup(tempVarType.getSize())); tempVar.appendStore(advice, getFactory()); } } advice.append(munger.getAdviceInstructions(this, tempVar, afterAdvice)); if (ret != null) { InstructionHandle gotoTarget = advice.getStart(); for (Iterator i = returns.iterator(); i.hasNext();) { InstructionHandle ih = (InstructionHandle) i.next(); Utility.replaceInstruction( ih, InstructionFactory.createBranchInstruction( Constants.GOTO, gotoTarget), enclosingMethod); } range.append(advice); range.append(retList); } else { range.append(advice); range.append(retList); } } public void weaveAfterThrowing(BcelAdvice munger, TypeX catchType) { // a good optimization would be not to generate anything here // if the shadow is GUARANTEED empty (i.e., there's NOTHING, not even // a shadow, inside me). if (getRange().getStart().getNext() == getRange().getEnd()) return; InstructionFactory fact = getFactory(); InstructionList handler = new InstructionList(); BcelVar exceptionVar = genTempVar(catchType); exceptionVar.appendStore(handler, fact); InstructionList endHandler = new InstructionList( exceptionVar.createLoad(fact)); handler.append(munger.getAdviceInstructions(this, exceptionVar, endHandler.getStart())); handler.append(endHandler); handler.append(InstructionConstants.ATHROW); InstructionHandle handlerStart = handler.getStart(); if (isFallsThrough()) { InstructionHandle jumpTarget = handler.append(InstructionConstants.NOP); handler.insert(InstructionFactory.createBranchInstruction(Constants.GOTO, jumpTarget)); } InstructionHandle protectedEnd = handler.getStart(); range.insert(handler, Range.InsideAfter); enclosingMethod.addExceptionHandler(range.getStart().getNext(), protectedEnd.getPrev(), handlerStart, (ObjectType)BcelWorld.makeBcelType(catchType), //???Type.THROWABLE, // high priority if our args are on the stack getKind().hasHighPriorityExceptions()); } //??? this shares a lot of code with the above weaveAfterThrowing //??? would be nice to abstract that to say things only once public void weaveSoftener(BcelAdvice munger, TypeX catchType) { // a good optimization would be not to generate anything here // if the shadow is GUARANTEED empty (i.e., there's NOTHING, not even // a shadow, inside me). if (getRange().getStart().getNext() == getRange().getEnd()) return; InstructionFactory fact = getFactory(); InstructionList handler = new InstructionList(); BcelVar exceptionVar = genTempVar(catchType); exceptionVar.appendStore(handler, fact); handler.append(fact.createNew(NameMangler.SOFT_EXCEPTION_TYPE)); handler.append(InstructionFactory.createDup(1)); handler.append(exceptionVar.createLoad(fact)); handler.append(fact.createInvoke(NameMangler.SOFT_EXCEPTION_TYPE, "<init>", Type.VOID, new Type[] { Type.THROWABLE }, Constants.INVOKESPECIAL)); //??? special handler.append(InstructionConstants.ATHROW); InstructionHandle handlerStart = handler.getStart(); if (isFallsThrough()) { InstructionHandle jumpTarget = range.getEnd();//handler.append(fact.NOP); handler.insert(InstructionFactory.createBranchInstruction(Constants.GOTO, jumpTarget)); } InstructionHandle protectedEnd = handler.getStart(); range.insert(handler, Range.InsideAfter); enclosingMethod.addExceptionHandler(range.getStart().getNext(), protectedEnd.getPrev(), handlerStart, (ObjectType)BcelWorld.makeBcelType(catchType), // high priority if our args are on the stack getKind().hasHighPriorityExceptions()); } public void weavePerObjectEntry(final BcelAdvice munger, final BcelVar onVar) { final InstructionFactory fact = getFactory(); InstructionList entryInstructions = new InstructionList(); InstructionList entrySuccessInstructions = new InstructionList(); onVar.appendLoad(entrySuccessInstructions, fact); entrySuccessInstructions.append( Utility.createInvoke(fact, world, AjcMemberMaker.perObjectBind(munger.getConcreteAspect()))); InstructionList testInstructions = munger.getTestInstructions(this, entrySuccessInstructions.getStart(), range.getRealStart(), entrySuccessInstructions.getStart()); entryInstructions.append(testInstructions); entryInstructions.append(entrySuccessInstructions); range.insert(entryInstructions, Range.InsideBefore); } public void weaveCflowEntry(final BcelAdvice munger, final Member cflowStackField) { final boolean isPer = munger.getKind() == AdviceKind.PerCflowBelowEntry || munger.getKind() == AdviceKind.PerCflowEntry; final Type objectArrayType = new ArrayType(Type.OBJECT, 1); final InstructionFactory fact = getFactory(); final BcelVar testResult = genTempVar(ResolvedTypeX.BOOLEAN); InstructionList entryInstructions = new InstructionList(); { InstructionList entrySuccessInstructions = new InstructionList(); if (munger.hasDynamicTests()) { entryInstructions.append(Utility.createConstant(fact, 0)); testResult.appendStore(entryInstructions, fact); entrySuccessInstructions.append(Utility.createConstant(fact, 1)); testResult.appendStore(entrySuccessInstructions, fact); } if (isPer) { entrySuccessInstructions.append( fact.createInvoke(munger.getConcreteAspect().getName(), NameMangler.PERCFLOW_PUSH_METHOD, Type.VOID, new Type[] { }, Constants.INVOKESTATIC)); } else { BcelVar[] cflowStateVars = munger.getExposedStateAsBcelVars(); BcelVar arrayVar = genTempVar(TypeX.OBJECTARRAY); int alen = cflowStateVars.length; entrySuccessInstructions.append(Utility.createConstant(fact, alen)); entrySuccessInstructions.append( (Instruction) fact.createNewArray(Type.OBJECT, (short) 1)); arrayVar.appendStore(entrySuccessInstructions, fact); for (int i = 0; i < alen; i++) { arrayVar.appendConvertableArrayStore( entrySuccessInstructions, fact, i, cflowStateVars[i]); } entrySuccessInstructions.append( Utility.createGet(fact, cflowStackField)); arrayVar.appendLoad(entrySuccessInstructions, fact); entrySuccessInstructions.append( fact.createInvoke(NameMangler.CFLOW_STACK_TYPE, "push", Type.VOID, new Type[] { objectArrayType }, Constants.INVOKEVIRTUAL)); } InstructionList testInstructions = munger.getTestInstructions(this, entrySuccessInstructions.getStart(), range.getRealStart(), entrySuccessInstructions.getStart()); entryInstructions.append(testInstructions); entryInstructions.append(entrySuccessInstructions); } // this is the same for both per and non-per weaveAfter(new BcelAdvice(null, null, null, 0, 0, 0, null, null) { public InstructionList getAdviceInstructions( BcelShadow s, BcelVar extraArgVar, InstructionHandle ifNoAdvice) { InstructionList exitInstructions = new InstructionList(); if (munger.hasDynamicTests()) { testResult.appendLoad(exitInstructions, fact); exitInstructions.append( InstructionFactory.createBranchInstruction( Constants.IFEQ, ifNoAdvice)); } exitInstructions.append(Utility.createGet(fact, cflowStackField)); exitInstructions .append( fact .createInvoke( NameMangler.CFLOW_STACK_TYPE, "pop", Type.VOID, new Type[] { }, Constants.INVOKEVIRTUAL)); return exitInstructions; } }); range.insert(entryInstructions, Range.InsideBefore); } public void weaveAroundInline( BcelAdvice munger, boolean hasDynamicTest) { /* Implementation notes: * * AroundInline still extracts the instructions of the original shadow into * an extracted method. This allows inlining of even that advice that doesn't * call proceed or calls proceed more than once. * * It extracts the instructions of the original shadow into a method. * * Then it extracts the instructions of the advice into a new method defined on * this enclosing class. This new method can then be specialized as below. * * Then it searches in the instructions of the advice for any call to the * proceed method. * * At such a call, there is stuff on the stack representing the arguments to * proceed. Pop these into the frame. * * Now build the stack for the call to the extracted method, taking values * either from the join point state or from the new frame locs from proceed. * Now call the extracted method. The right return value should be on the * stack, so no cast is necessary. * * If only one call to proceed is made, we can re-inline the original shadow. * We are not doing that presently. * * If the body of the advice can be determined to not alter the stack, or if * this shadow doesn't care about the stack, i.e. method-execution, then the * new method for the advice can also be re-lined. We are not doing that * presently. */ // !!! THIS BLOCK OF CODE SHOULD BE IN A METHOD CALLED weaveAround(...); Member mungerSig = munger.getSignature(); ResolvedTypeX declaringType = world.resolve(mungerSig.getDeclaringType()); //??? might want some checks here to give better errors BcelObjectType ot = BcelWorld.getBcelObjectType(declaringType); LazyMethodGen adviceMethod = ot.getLazyClassGen().getLazyMethodGen(mungerSig); if (!adviceMethod.getCanInline()) { weaveAroundClosure(munger, hasDynamicTest); return; } // We can't inline around methods if they have around advice on them, this // is because the weaving will extract the body and hence the proceed call. //??? should consider optimizations to recognize simple cases that don't require body extraction enclosingMethod.setCanInline(false); // start by exposing various useful things into the frame final InstructionFactory fact = getFactory(); // now generate the aroundBody method LazyMethodGen extractedMethod = extractMethod( NameMangler.aroundCallbackMethodName( getSignature(), getEnclosingClass()), Modifier.PRIVATE, munger); // now extract the advice into its own method String adviceMethodName = NameMangler.aroundCallbackMethodName( getSignature(), getEnclosingClass()) + "$advice"; List argVarList = new ArrayList(); List proceedVarList = new ArrayList(); int extraParamOffset = 0; // Create the extra parameters that are needed for passing to proceed // This code is very similar to that found in makeCallToCallback and should // be rationalized in the future if (thisVar != null) { argVarList.add(thisVar); proceedVarList.add(new BcelVar(thisVar.getType(), extraParamOffset)); extraParamOffset += thisVar.getType().getSize(); } if (targetVar != null && targetVar != thisVar) { argVarList.add(targetVar); proceedVarList.add(new BcelVar(targetVar.getType(), extraParamOffset)); extraParamOffset += targetVar.getType().getSize(); } for (int i = 0, len = getArgCount(); i < len; i++) { argVarList.add(argVars[i]); proceedVarList.add(new BcelVar(argVars[i].getType(), extraParamOffset)); extraParamOffset += argVars[i].getType().getSize(); } if (thisJoinPointVar != null) { argVarList.add(thisJoinPointVar); proceedVarList.add(new BcelVar(thisJoinPointVar.getType(), extraParamOffset)); extraParamOffset += thisJoinPointVar.getType().getSize(); } Type[] adviceParameterTypes = adviceMethod.getArgumentTypes(); Type[] extractedMethodParameterTypes = extractedMethod.getArgumentTypes(); Type[] parameterTypes = new Type[extractedMethodParameterTypes.length + adviceParameterTypes.length + 1]; int parameterIndex = 0; System.arraycopy( extractedMethodParameterTypes, 0, parameterTypes, parameterIndex, extractedMethodParameterTypes.length); parameterIndex += extractedMethodParameterTypes.length; parameterTypes[parameterIndex++] = BcelWorld.makeBcelType(adviceMethod.getEnclosingClass().getType()); System.arraycopy( adviceParameterTypes, 0, parameterTypes, parameterIndex, adviceParameterTypes.length); LazyMethodGen localAdviceMethod = new LazyMethodGen( Modifier.PRIVATE | Modifier.FINAL | Modifier.STATIC, adviceMethod.getReturnType(), adviceMethodName, parameterTypes, new String[0], getEnclosingClass()); String donorFileName = adviceMethod.getEnclosingClass().getInternalFileName(); String recipientFileName = getEnclosingClass().getInternalFileName(); // System.err.println("donor " + donorFileName); // System.err.println("recip " + recipientFileName); if (! donorFileName.equals(recipientFileName)) { localAdviceMethod.fromFilename = donorFileName; getEnclosingClass().addInlinedSourceFileInfo( donorFileName, adviceMethod.highestLineNumber); } getEnclosingClass().addMethodGen(localAdviceMethod); // create a map that will move all slots in advice method forward by extraParamOffset // in order to make room for the new proceed-required arguments that are added at // the beginning of the parameter list int nVars = adviceMethod.getMaxLocals() + extraParamOffset; IntMap varMap = IntMap.idMap(nVars); for (int i=extraParamOffset; i < nVars; i++) { varMap.put(i-extraParamOffset, i); } localAdviceMethod.getBody().insert( BcelClassWeaver.genInlineInstructions(adviceMethod, localAdviceMethod, varMap, fact, true)); localAdviceMethod.setMaxLocals(nVars); //System.err.println(localAdviceMethod); // the shadow is now empty. First, create a correct call // to the around advice. This includes both the call (which may involve // value conversion of the advice arguments) and the return // (which may involve value conversion of the return value). Right now // we push a null for the unused closure. It's sad, but there it is. InstructionList advice = new InstructionList(); // InstructionHandle adviceMethodInvocation; { for (Iterator i = argVarList.iterator(); i.hasNext(); ) { BcelVar var = (BcelVar)i.next(); var.appendLoad(advice, fact); } // ??? we don't actually need to push NULL for the closure if we take care advice.append( munger.getAdviceArgSetup( this, null, new InstructionList(InstructionConstants.ACONST_NULL))); // adviceMethodInvocation = advice.append( Utility.createInvoke(fact, localAdviceMethod)); //(fact, getWorld(), munger.getSignature())); advice.append( Utility.createConversion( getFactory(), BcelWorld.makeBcelType(munger.getSignature().getReturnType()), extractedMethod.getReturnType())); if (! isFallsThrough()) { advice.append(InstructionFactory.createReturn(extractedMethod.getReturnType())); } } // now, situate the call inside the possible dynamic tests, // and actually add the whole mess to the shadow if (! hasDynamicTest) { range.append(advice); } else { InstructionList afterThingie = new InstructionList(InstructionConstants.NOP); InstructionList callback = makeCallToCallback(extractedMethod); if (terminatesWithReturn()) { callback.append( InstructionFactory.createReturn(extractedMethod.getReturnType())); } else { //InstructionHandle endNop = range.insert(fact.NOP, Range.InsideAfter); advice.append( InstructionFactory.createBranchInstruction( Constants.GOTO, afterThingie.getStart())); } range.append( munger.getTestInstructions( this, advice.getStart(), callback.getStart(), advice.getStart())); range.append(advice); range.append(callback); range.append(afterThingie); } // now search through the advice, looking for a call to PROCEED. // Then we replace the call to proceed with some argument setup, and a // call to the extracted method. String proceedName = NameMangler.proceedMethodName(munger.getSignature().getName()); InstructionHandle curr = localAdviceMethod.getBody().getStart(); InstructionHandle end = localAdviceMethod.getBody().getEnd(); ConstantPoolGen cpg = localAdviceMethod.getEnclosingClass().getConstantPoolGen(); while (curr != end) { InstructionHandle next = curr.getNext(); Instruction inst = curr.getInstruction(); if ((inst instanceof INVOKESTATIC) && proceedName.equals(((INVOKESTATIC) inst).getMethodName(cpg))) { localAdviceMethod.getBody().append( curr, getRedoneProceedCall( fact, extractedMethod, munger, localAdviceMethod, proceedVarList)); Utility.deleteInstruction(curr, localAdviceMethod); } curr = next; } // and that's it. } private InstructionList getRedoneProceedCall( InstructionFactory fact, LazyMethodGen callbackMethod, BcelAdvice munger, LazyMethodGen localAdviceMethod, List argVarList) { InstructionList ret = new InstructionList(); // we have on stack all the arguments for the ADVICE call. // we have in frame somewhere all the arguments for the non-advice call. BcelVar[] adviceVars = munger.getExposedStateAsBcelVars(); IntMap proceedMap = makeProceedArgumentMap(adviceVars); // System.out.println(proceedMap + " for " + this); // System.out.println(argVarList); ResolvedTypeX[] proceedParamTypes = world.resolve(munger.getSignature().getParameterTypes()); // remove this*JoinPoint* as arguments to proceed if (munger.getBaseParameterCount()+1 < proceedParamTypes.length) { int len = munger.getBaseParameterCount()+1; ResolvedTypeX[] newTypes = new ResolvedTypeX[len]; System.arraycopy(proceedParamTypes, 0, newTypes, 0, len); proceedParamTypes = newTypes; } //System.out.println("stateTypes: " + Arrays.asList(stateTypes)); BcelVar[] proceedVars = Utility.pushAndReturnArrayOfVars(proceedParamTypes, ret, fact, localAdviceMethod); Type[] stateTypes = callbackMethod.getArgumentTypes(); // System.out.println("stateTypes: " + Arrays.asList(stateTypes)); for (int i=0, len=stateTypes.length; i < len; i++) { Type stateType = stateTypes[i]; ResolvedTypeX stateTypeX = BcelWorld.fromBcel(stateType).resolve(world); if (proceedMap.hasKey(i)) { //throw new RuntimeException("unimplemented"); proceedVars[proceedMap.get(i)].appendLoadAndConvert(ret, fact, stateTypeX); } else { ((BcelVar) argVarList.get(i)).appendLoad(ret, fact); } } ret.append(Utility.createInvoke(fact, callbackMethod)); ret.append(Utility.createConversion(fact, callbackMethod.getReturnType(), BcelWorld.makeBcelType(munger.getSignature().getReturnType()))); return ret; } public void weaveAroundClosure( BcelAdvice munger, boolean hasDynamicTest) { InstructionFactory fact = getFactory(); enclosingMethod.setCanInline(false); // MOVE OUT ALL THE INSTRUCTIONS IN MY SHADOW INTO ANOTHER METHOD! LazyMethodGen callbackMethod = extractMethod( NameMangler.aroundCallbackMethodName( getSignature(), getEnclosingClass()), 0, munger); BcelVar[] adviceVars = munger.getExposedStateAsBcelVars(); String closureClassName = NameMangler.makeClosureClassName( getEnclosingClass().getType(), getEnclosingClass().getNewGeneratedNameTag()); Member constructorSig = new Member(Member.CONSTRUCTOR, TypeX.forName(closureClassName), 0, "<init>", "([Ljava/lang/Object;)V"); BcelVar closureHolder = null; // This is not being used currently since getKind() == preinitializaiton // cannot happen in around advice if (getKind() == PreInitialization) { closureHolder = genTempVar(AjcMemberMaker.AROUND_CLOSURE_TYPE); } InstructionList closureInstantiation = makeClosureInstantiation(constructorSig, closureHolder); /*LazyMethodGen constructor = */ makeClosureClassAndReturnConstructor( closureClassName, callbackMethod, makeProceedArgumentMap(adviceVars) ); InstructionList returnConversionCode; if (getKind() == PreInitialization) { returnConversionCode = new InstructionList(); BcelVar stateTempVar = genTempVar(TypeX.OBJECTARRAY); closureHolder.appendLoad(returnConversionCode, fact); returnConversionCode.append( Utility.createInvoke( fact, world, AjcMemberMaker.aroundClosurePreInitializationGetter())); stateTempVar.appendStore(returnConversionCode, fact); Type[] stateTypes = getSuperConstructorParameterTypes(); returnConversionCode.append(InstructionConstants.ALOAD_0); // put "this" back on the stack for (int i = 0, len = stateTypes.length; i < len; i++) { stateTempVar.appendConvertableArrayLoad( returnConversionCode, fact, i, world.resolve(BcelWorld.fromBcel(stateTypes[i]))); } } else { returnConversionCode = Utility.createConversion( getFactory(), BcelWorld.makeBcelType(munger.getSignature().getReturnType()), callbackMethod.getReturnType()); if (!isFallsThrough()) { returnConversionCode.append( InstructionFactory.createReturn(callbackMethod.getReturnType())); } } InstructionList advice = new InstructionList(); advice.append(munger.getAdviceArgSetup(this, null, closureInstantiation)); // advice.append(closureInstantiation); advice.append(munger.getNonTestAdviceInstructions(this)); advice.append(returnConversionCode); if (!hasDynamicTest) { range.append(advice); } else { InstructionList callback = makeCallToCallback(callbackMethod); InstructionList postCallback = new InstructionList(); if (terminatesWithReturn()) { callback.append( InstructionFactory.createReturn(callbackMethod.getReturnType())); } else { advice.append( InstructionFactory.createBranchInstruction( Constants.GOTO, postCallback.append(InstructionConstants.NOP))); } range.append( munger.getTestInstructions( this, advice.getStart(), callback.getStart(), advice.getStart())); range.append(advice); range.append(callback); range.append(postCallback); } } // exposed for testing InstructionList makeCallToCallback(LazyMethodGen callbackMethod) { InstructionFactory fact = getFactory(); InstructionList callback = new InstructionList(); if (thisVar != null) { callback.append(InstructionConstants.ALOAD_0); } if (targetVar != null && targetVar != thisVar) { callback.append(BcelRenderer.renderExpr(fact, world, targetVar)); } callback.append(BcelRenderer.renderExprs(fact, world, argVars)); // remember to render tjps if (thisJoinPointVar != null) { callback.append(BcelRenderer.renderExpr(fact, world, thisJoinPointVar)); } callback.append(Utility.createInvoke(fact, callbackMethod)); return callback; } /** side-effect-free */ private InstructionList makeClosureInstantiation(Member constructor, BcelVar holder) { // LazyMethodGen constructor) { InstructionFactory fact = getFactory(); BcelVar arrayVar = genTempVar(TypeX.OBJECTARRAY); //final Type objectArrayType = new ArrayType(Type.OBJECT, 1); final InstructionList il = new InstructionList(); int alen = getArgCount() + (thisVar == null ? 0 : 1) + ((targetVar != null && targetVar != thisVar) ? 1 : 0) + (thisJoinPointVar == null ? 0 : 1); il.append(Utility.createConstant(fact, alen)); il.append((Instruction)fact.createNewArray(Type.OBJECT, (short)1)); arrayVar.appendStore(il, fact); int stateIndex = 0; if (thisVar != null) { arrayVar.appendConvertableArrayStore(il, fact, stateIndex, thisVar); thisVar.setPositionInAroundState(stateIndex); stateIndex++; } if (targetVar != null && targetVar != thisVar) { arrayVar.appendConvertableArrayStore(il, fact, stateIndex, targetVar); targetVar.setPositionInAroundState(stateIndex); stateIndex++; } for (int i = 0, len = getArgCount(); i<len; i++) { arrayVar.appendConvertableArrayStore(il, fact, stateIndex, argVars[i]); argVars[i].setPositionInAroundState(stateIndex); stateIndex++; } if (thisJoinPointVar != null) { arrayVar.appendConvertableArrayStore(il, fact, stateIndex, thisJoinPointVar); thisJoinPointVar.setPositionInAroundState(stateIndex); stateIndex++; } il.append(fact.createNew(new ObjectType(constructor.getDeclaringType().getName()))); il.append(new DUP()); arrayVar.appendLoad(il, fact); il.append(Utility.createInvoke(fact, world, constructor)); if (getKind() == PreInitialization) { il.append(InstructionConstants.DUP); holder.appendStore(il, fact); } return il; } private IntMap makeProceedArgumentMap(BcelVar[] adviceArgs) { //System.err.println("coming in with " + Arrays.asList(adviceArgs)); IntMap ret = new IntMap(); for(int i = 0, len = adviceArgs.length; i < len; i++) { BcelVar v = (BcelVar) adviceArgs[i]; if (v == null) continue; // XXX we don't know why this is required int pos = v.getPositionInAroundState(); if (pos >= 0) { // need this test to avoid args bound via cflow ret.put(pos, i); } } //System.err.println("returning " + ret); return ret; } /** * * * @param callbackMethod the method we will call back to when our run method gets called. * * @param proceedMap A map from state position to proceed argument position. May be * non covering on state position. */ private LazyMethodGen makeClosureClassAndReturnConstructor( String closureClassName, LazyMethodGen callbackMethod, IntMap proceedMap) { String superClassName = "org.aspectj.runtime.internal.AroundClosure"; Type objectArrayType = new ArrayType(Type.OBJECT, 1); LazyClassGen closureClass = new LazyClassGen(closureClassName, superClassName, getEnclosingClass().getFileName(), Modifier.PUBLIC, new String[] {}); InstructionFactory fact = new InstructionFactory(closureClass.getConstantPoolGen()); // constructor LazyMethodGen constructor = new LazyMethodGen(Modifier.PUBLIC, Type.VOID, "<init>", new Type[] {objectArrayType}, new String[] {}, closureClass); InstructionList cbody = constructor.getBody(); cbody.append(InstructionFactory.createLoad(Type.OBJECT, 0)); cbody.append(InstructionFactory.createLoad(objectArrayType, 1)); cbody.append(fact.createInvoke(superClassName, "<init>", Type.VOID, new Type[] {objectArrayType}, Constants.INVOKESPECIAL)); cbody.append(InstructionFactory.createReturn(Type.VOID)); closureClass.addMethodGen(constructor); // method LazyMethodGen runMethod = new LazyMethodGen(Modifier.PUBLIC, Type.OBJECT, "run", new Type[] {objectArrayType}, new String[] {}, closureClass); InstructionList mbody = runMethod.getBody(); BcelVar proceedVar = new BcelVar(TypeX.OBJECTARRAY.resolve(world), 1); // int proceedVarIndex = 1; BcelVar stateVar = new BcelVar(TypeX.OBJECTARRAY.resolve(world), runMethod.allocateLocal(1)); // int stateVarIndex = runMethod.allocateLocal(1); mbody.append(InstructionFactory.createThis()); mbody.append(fact.createGetField(superClassName, "state", objectArrayType)); mbody.append(stateVar.createStore(fact)); // mbody.append(fact.createStore(objectArrayType, stateVarIndex)); Type[] stateTypes = callbackMethod.getArgumentTypes(); for (int i=0, len=stateTypes.length; i < len; i++) { Type stateType = stateTypes[i]; ResolvedTypeX stateTypeX = BcelWorld.fromBcel(stateType).resolve(world); if (proceedMap.hasKey(i)) { mbody.append( proceedVar.createConvertableArrayLoad(fact, proceedMap.get(i), stateTypeX)); } else { mbody.append( stateVar.createConvertableArrayLoad(fact, i, stateTypeX)); } } mbody.append(Utility.createInvoke(fact, callbackMethod)); if (getKind() == PreInitialization) { mbody.append(Utility.createSet( fact, AjcMemberMaker.aroundClosurePreInitializationField())); mbody.append(InstructionConstants.ACONST_NULL); } else { mbody.append( Utility.createConversion( fact, callbackMethod.getReturnType(), Type.OBJECT)); } mbody.append(InstructionFactory.createReturn(Type.OBJECT)); closureClass.addMethodGen(runMethod); // class getEnclosingClass().addGeneratedInner(closureClass); return constructor; } // ---- extraction methods public LazyMethodGen extractMethod(String newMethodName, int visibilityModifier, ShadowMunger munger) { LazyMethodGen.assertGoodBody(range.getBody(), newMethodName); if (!getKind().allowsExtraction()) throw new BCException(); LazyMethodGen freshMethod = createMethodGen(newMethodName,visibilityModifier); // System.err.println("******"); // System.err.println("ABOUT TO EXTRACT METHOD for" + this); // enclosingMethod.print(System.err); // System.err.println("INTO"); // freshMethod.print(System.err); // System.err.println("WITH REMAP"); // System.err.println(makeRemap()); range.extractInstructionsInto(freshMethod, makeRemap(), (getKind() != PreInitialization) && isFallsThrough()); if (getKind() == PreInitialization) { addPreInitializationReturnCode( freshMethod, getSuperConstructorParameterTypes()); } getEnclosingClass().addMethodGen(freshMethod,munger.getSourceLocation()); return freshMethod; } private void addPreInitializationReturnCode( LazyMethodGen extractedMethod, Type[] superConstructorTypes) { InstructionList body = extractedMethod.getBody(); final InstructionFactory fact = getFactory(); BcelVar arrayVar = new BcelVar( world.resolve(TypeX.OBJECTARRAY), extractedMethod.allocateLocal(1)); int len = superConstructorTypes.length; body.append(Utility.createConstant(fact, len)); body.append((Instruction)fact.createNewArray(Type.OBJECT, (short)1)); arrayVar.appendStore(body, fact); for (int i = len - 1; i >= 0; i++) { // convert thing on top of stack to object body.append( Utility.createConversion(fact, superConstructorTypes[i], Type.OBJECT)); // push object array arrayVar.appendLoad(body, fact); // swap body.append(InstructionConstants.SWAP); // do object array store. body.append(Utility.createConstant(fact, i)); body.append(InstructionConstants.SWAP); body.append(InstructionFactory.createArrayStore(Type.OBJECT)); } arrayVar.appendLoad(body, fact); body.append(InstructionConstants.ARETURN); } private Type[] getSuperConstructorParameterTypes() { // assert getKind() == PreInitialization InstructionHandle superCallHandle = getRange().getEnd().getNext(); InvokeInstruction superCallInstruction = (InvokeInstruction) superCallHandle.getInstruction(); return superCallInstruction.getArgumentTypes( getEnclosingClass().getConstantPoolGen()); } /** make a map from old frame location to new frame location. Any unkeyed frame * location picks out a copied local */ private IntMap makeRemap() { IntMap ret = new IntMap(5); int reti = 0; if (thisVar != null) { ret.put(0, reti++); // thisVar guaranteed to be 0 } if (targetVar != null && targetVar != thisVar) { ret.put(targetVar.getSlot(), reti++); } for (int i = 0, len = argVars.length; i < len; i++) { ret.put(argVars[i].getSlot(), reti); reti += argVars[i].getType().getSize(); } if (thisJoinPointVar != null) { ret.put(thisJoinPointVar.getSlot(), reti++); } // we not only need to put the arguments, we also need to remap their // aliases, which we so helpfully put into temps at the beginning of this join // point. if (! getKind().argsOnStack()) { int oldi = 0; int newi = 0; // if we're passing in a this and we're not argsOnStack we're always // passing in a target too if (arg0HoldsThis()) { ret.put(0, 0); oldi++; newi+=1; } //assert targetVar == thisVar for (int i = 0; i < getArgCount(); i++) { TypeX type = getArgType(i); ret.put(oldi, newi); oldi += type.getSize(); newi += type.getSize(); } } // System.err.println("making remap for : " + this); // if (targetVar != null) System.err.println("target slot : " + targetVar.getSlot()); // if (thisVar != null) System.err.println(" this slot : " + thisVar.getSlot()); // System.err.println(ret); return ret; } /** * The new method always static. * It may take some extra arguments: this, target. * If it's argsOnStack, then it must take both this/target * If it's argsOnFrame, it shares this and target. * ??? rewrite this to do less array munging, please */ private LazyMethodGen createMethodGen(String newMethodName, int visibilityModifier) { Type[] parameterTypes = BcelWorld.makeBcelTypes(getArgTypes()); int modifiers = Modifier.FINAL | visibilityModifier; // XXX some bug // if (! isExpressionKind() && getSignature().isStrict(world)) { // modifiers |= Modifier.STRICT; // } modifiers |= Modifier.STATIC; if (targetVar != null && targetVar != thisVar) { TypeX targetType = getTargetType(); ResolvedMember resolvedMember = getSignature().resolve(world); if (resolvedMember != null && Modifier.isProtected(resolvedMember.getModifiers()) && !samePackage(targetType.getPackageName(), getEnclosingType().getPackageName())) { if (!targetType.isAssignableFrom(getThisType(), world)) { throw new BCException("bad bytecode"); } targetType = getThisType(); } parameterTypes = addType(BcelWorld.makeBcelType(targetType), parameterTypes); } if (thisVar != null) { TypeX thisType = getThisType(); parameterTypes = addType(BcelWorld.makeBcelType(thisType), parameterTypes); } // We always want to pass down thisJoinPoint in case we have already woven // some advice in here. If we only have a single piece of around advice on a // join point, it is unnecessary to accept (and pass) tjp. if (thisJoinPointVar != null) { parameterTypes = addTypeToEnd(LazyClassGen.tjpType, parameterTypes); } TypeX returnType; if (getKind() == PreInitialization) { returnType = TypeX.OBJECTARRAY; } else { returnType = getReturnType(); } return new LazyMethodGen( modifiers, BcelWorld.makeBcelType(returnType), newMethodName, parameterTypes, new String[0], // XXX again, we need to look up methods! // TypeX.getNames(getSignature().getExceptions(world)), getEnclosingClass()); } private boolean samePackage(String p1, String p2) { if (p1 == null) return p2 == null; if (p2 == null) return false; return p1.equals(p2); } private Type[] addType(Type type, Type[] types) { int len = types.length; Type[] ret = new Type[len+1]; ret[0] = type; System.arraycopy(types, 0, ret, 1, len); return ret; } private Type[] addTypeToEnd(Type type, Type[] types) { int len = types.length; Type[] ret = new Type[len+1]; ret[len] = type; System.arraycopy(types, 0, ret, 0, len); return ret; } public BcelVar genTempVar(TypeX typeX) { return new BcelVar(typeX.resolve(world), genTempVarIndex(typeX.getSize())); } // public static final boolean CREATE_TEMP_NAMES = true; public BcelVar genTempVar(TypeX typeX, String localName) { BcelVar tv = genTempVar(typeX); // if (CREATE_TEMP_NAMES) { // for (InstructionHandle ih = range.getStart(); ih != range.getEnd(); ih = ih.getNext()) { // if (Range.isRangeHandle(ih)) continue; // ih.addTargeter(new LocalVariableTag(typeX, localName, tv.getSlot())); // } // } return tv; } // eh doesn't think we need to garbage collect these (64K is a big number...) private int genTempVarIndex(int size) { return enclosingMethod.allocateLocal(size); } public InstructionFactory getFactory() { return getEnclosingClass().getFactory(); } public ISourceLocation getSourceLocation() { int sourceLine = getSourceLine(); if (sourceLine == 0 || sourceLine == -1) { // Thread.currentThread().dumpStack(); // System.err.println(this + ": " + range); return getEnclosingClass().getType().getSourceLocation(); } else { return getEnclosingClass().getType().getSourceContext().makeSourceLocation(sourceLine); } } public Shadow getEnclosingShadow() { return enclosingShadow; } public LazyMethodGen getEnclosingMethod() { return enclosingMethod; } public boolean isFallsThrough() { return !terminatesWithReturn(); //fallsThrough; } }
57,666
Bug 57666 duplicate manifests cause resource-copying to gack
(Ah, the joy of build infrastructure...) Mostly self-explanatory trace, from a build Monday Apr 5, 2004 at 08:46:01 GMT: duplicate entry: META-INF/MANIFEST.MF duplicate entry: META-INF/MANIFEST.MF java.util.zip.ZipException: duplicate entry: META-INF/MANIFEST.MF at java.util.zip.ZipOutputStream.putNextEntry(ZipOutputStream.java:163) at java.util.jar.JarOutputStream.putNextEntry(JarOutputStream.java:90) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.writeResource(AjBuildManager.java:344) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.copyResourcesFromJarFile(AjBuildManager.java:288) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.copyResourcesToDestination(AjBuildManager.java:253) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.doBuild(AjBuildManager.java:195) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.batchBuild(AjBuildManager.java:94) at org.aspectj.ajdt.ajc.AjdtCommand.doCommand(AjdtCommand.java:102) at org.aspectj.ajdt.ajc.AjdtCommand.runCommand(AjdtCommand.java:53) at org.aspectj.tools.ajc.Main.run(Main.java:280) at org.aspectj.tools.ajc.Main.runMain(Main.java:217) at org.aspectj.tools.ajc.Main.main(Main.java:79)
resolved fixed
2b8fa31
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2004-08-02T15:47:02Z
2004-04-06T22:20:00Z
ajde/testsrc/org/aspectj/ajde/AjdeTests.java
/* ******************************************************************* * Copyright (c) 1999-2001 Xerox Corporation, * 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Common Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * Xerox/PARC initial implementation * ******************************************************************/ package org.aspectj.ajde; import junit.framework.*; public class AjdeTests extends TestCase { public static String TESTDATA_PATH = "../ajde/testdata"; public static Test suite() { TestSuite suite = new TestSuite(AjdeTests.class.getName()); //$JUnit-BEGIN$ suite.addTestSuite(BuildOptionsTest.class); suite.addTestSuite(BuildConfigurationTests.class); suite.addTestSuite(StructureModelRegressionTest.class); suite.addTestSuite(StructureModelTest.class); suite.addTestSuite(VersionTest.class); suite.addTestSuite(CompilerMessagesTest.class); suite.addTestSuite(AsmDeclarationsTest.class); suite.addTestSuite(AsmRelationshipsTest.class); suite.addTestSuite(InpathTestcase.class); suite.addTestSuite(ReweavableTestCase.class); suite.addTestSuite(ResourceCopyTestCase.class); suite.addTestSuite(ModelPerformanceTest.class); suite.addTestSuite(SavedModelConsistencyTest. class); suite.addTestSuite(BuildCancellingTest.class); suite.addTestSuite(JarManifestTest.class); //$JUnit-END$ return suite; } public AjdeTests(String name) { super(name); } }
57,666
Bug 57666 duplicate manifests cause resource-copying to gack
(Ah, the joy of build infrastructure...) Mostly self-explanatory trace, from a build Monday Apr 5, 2004 at 08:46:01 GMT: duplicate entry: META-INF/MANIFEST.MF duplicate entry: META-INF/MANIFEST.MF java.util.zip.ZipException: duplicate entry: META-INF/MANIFEST.MF at java.util.zip.ZipOutputStream.putNextEntry(ZipOutputStream.java:163) at java.util.jar.JarOutputStream.putNextEntry(JarOutputStream.java:90) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.writeResource(AjBuildManager.java:344) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.copyResourcesFromJarFile(AjBuildManager.java:288) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.copyResourcesToDestination(AjBuildManager.java:253) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.doBuild(AjBuildManager.java:195) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.batchBuild(AjBuildManager.java:94) at org.aspectj.ajdt.ajc.AjdtCommand.doCommand(AjdtCommand.java:102) at org.aspectj.ajdt.ajc.AjdtCommand.runCommand(AjdtCommand.java:53) at org.aspectj.tools.ajc.Main.run(Main.java:280) at org.aspectj.tools.ajc.Main.runMain(Main.java:217) at org.aspectj.tools.ajc.Main.main(Main.java:79)
resolved fixed
2b8fa31
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2004-08-02T15:47:02Z
2004-04-06T22:20:00Z
ajde/testsrc/org/aspectj/ajde/DuplicateManifestTest.java
57,666
Bug 57666 duplicate manifests cause resource-copying to gack
(Ah, the joy of build infrastructure...) Mostly self-explanatory trace, from a build Monday Apr 5, 2004 at 08:46:01 GMT: duplicate entry: META-INF/MANIFEST.MF duplicate entry: META-INF/MANIFEST.MF java.util.zip.ZipException: duplicate entry: META-INF/MANIFEST.MF at java.util.zip.ZipOutputStream.putNextEntry(ZipOutputStream.java:163) at java.util.jar.JarOutputStream.putNextEntry(JarOutputStream.java:90) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.writeResource(AjBuildManager.java:344) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.copyResourcesFromJarFile(AjBuildManager.java:288) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.copyResourcesToDestination(AjBuildManager.java:253) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.doBuild(AjBuildManager.java:195) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.batchBuild(AjBuildManager.java:94) at org.aspectj.ajdt.ajc.AjdtCommand.doCommand(AjdtCommand.java:102) at org.aspectj.ajdt.ajc.AjdtCommand.runCommand(AjdtCommand.java:53) at org.aspectj.tools.ajc.Main.run(Main.java:280) at org.aspectj.tools.ajc.Main.runMain(Main.java:217) at org.aspectj.tools.ajc.Main.main(Main.java:79)
resolved fixed
2b8fa31
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2004-08-02T15:47:02Z
2004-04-06T22:20:00Z
org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/core/builder/AjBuildManager.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Common Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * PARC initial implementation * ******************************************************************/ package org.aspectj.ajdt.internal.core.builder; import java.io.*; import java.util.*; import java.util.jar.*; import java.util.zip.ZipEntry; import org.aspectj.ajdt.internal.compiler.AjCompilerAdapter; import org.aspectj.ajdt.internal.compiler.IBinarySourceProvider; import org.aspectj.ajdt.internal.compiler.IIntermediateResultsRequestor; import org.aspectj.ajdt.internal.compiler.IOutputClassFileNameProvider; import org.aspectj.ajdt.internal.compiler.InterimCompilationResult; import org.aspectj.ajdt.internal.compiler.lookup.*; import org.aspectj.ajdt.internal.compiler.problem.AjProblemReporter; import org.aspectj.asm.*; //import org.aspectj.asm.internal.*; import org.aspectj.asm.internal.ProgramElement; import org.aspectj.bridge.*; import org.aspectj.util.FileUtil; import org.aspectj.weaver.World; import org.aspectj.weaver.bcel.*; import org.eclipse.core.runtime.OperationCanceledException; import org.eclipse.jdt.core.compiler.*; import org.eclipse.jdt.internal.compiler.*; import org.eclipse.jdt.internal.compiler.batch.*; import org.eclipse.jdt.internal.compiler.batch.FileSystem; import org.eclipse.jdt.internal.compiler.env.*; import org.eclipse.jdt.internal.compiler.impl.CompilerOptions; import org.eclipse.jdt.internal.compiler.parser.Parser; import org.eclipse.jdt.internal.compiler.problem.AbortCompilation; import org.eclipse.jdt.internal.compiler.problem.DefaultProblemFactory; //import org.eclipse.jdt.internal.compiler.util.HashtableOfObject; public class AjBuildManager implements IOutputClassFileNameProvider,IBinarySourceProvider,ICompilerAdapterFactory { private static final String CANT_WRITE_RESULT = "unable to write compilation result"; private static final String MANIFEST_NAME = "META-INF/MANIFEST.MF"; static final boolean COPY_INPATH_DIR_RESOURCES = false; static final boolean FAIL_IF_RUNTIME_NOT_FOUND = false; private static final FileFilter binarySourceFilter = new FileFilter() { public boolean accept(File f) { return f.getName().endsWith(".class"); }}; /** * This builder is static so that it can be subclassed and reset. However, note * that there is only one builder present, so if two extendsion reset it, only * the latter will get used. */ private static AsmHierarchyBuilder asmHierarchyBuilder = new AsmHierarchyBuilder(); private IProgressListener progressListener = null; private int compiledCount; private int sourceFileCount; private JarOutputStream zos; private boolean batchCompile = true; private INameEnvironment environment; private Map /* String -> List<UCF>*/ binarySourcesForTheNextCompile = new HashMap(); private IHierarchy structureModel; public AjBuildConfig buildConfig; AjState state = new AjState(this); BcelWeaver bcelWeaver; public BcelWorld bcelWorld; public CountingMessageHandler handler; public AjBuildManager(IMessageHandler holder) { super(); this.handler = CountingMessageHandler.makeCountingMessageHandler(holder); } /** @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; try { if (batch) { this.state = new AjState(this); } boolean canIncremental = state.prepareForNextBuild(buildConfig); if (!canIncremental && !batch) { // retry as batch? return doBuild(buildConfig, baseHandler, true); } this.handler = CountingMessageHandler.makeCountingMessageHandler(baseHandler); // XXX duplicate, no? remove? String check = checkRtJar(buildConfig); if (check != null) { if (FAIL_IF_RUNTIME_NOT_FOUND) { MessageUtil.error(handler, check); return false; } else { MessageUtil.warn(handler, check); } } // if (batch) { setBuildConfig(buildConfig); //} // if (batch) { // if (buildConfig.isEmacsSymMode() || buildConfig.isGenerateModelMode()) { setupModel(); // } // } if (batch) { initBcelWorld(handler); } if (handler.hasErrors()) { return false; } if (buildConfig.getOutputJar() != null) { if (!openOutputStream(buildConfig.getOutputJar())) return false; } if (batch) { // System.err.println("XXXX batch: " + buildConfig.getFiles()); if (buildConfig.isEmacsSymMode() || buildConfig.isGenerateModelMode()) { bcelWorld.setModel(AsmManager.getDefault().getHierarchy()); // in incremental build, only get updated model? } binarySourcesForTheNextCompile = state.getBinaryFilesToCompile(true); performCompilation(buildConfig.getFiles()); if (handler.hasErrors()) { return false; } } 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); boolean hereWeGoAgain = !(files.isEmpty() && binarySourcesForTheNextCompile.isEmpty()); for (int i = 0; (i < 5) && hereWeGoAgain; i++) { // System.err.println("XXXX inc: " + files); performCompilation(files); if (handler.hasErrors() || (progressListener!=null && progressListener.isCancelledRequested())) { return false; } binarySourcesForTheNextCompile = state.getBinaryFilesToCompile(false); files = state.getFilesToCompile(false); hereWeGoAgain = !(files.isEmpty() && binarySourcesForTheNextCompile.isEmpty()); } if (!files.isEmpty()) { return batchBuild(buildConfig, baseHandler); } } // XXX not in Mik's incremental if (buildConfig.isEmacsSymMode()) { new org.aspectj.ajdt.internal.core.builder.EmacsStructureModelManager().externalizeModel(); } // have to tell state we succeeded or next is not incremental state.successfulCompile(buildConfig); copyResourcesToDestination(); /*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(); } } finally { if (zos != null) { closeOutputStream(); } ret = !handler.hasErrors(); // bug 59895, don't release reference to handler as may be needed by a nested call //handler = null; } return ret; } private boolean openOutputStream(File outJar) { try { OutputStream os = FileUtil.makeOutputStream(buildConfig.getOutputJar()); zos = new JarOutputStream(os,bcelWeaver.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() { try { if (zos != null) zos.close(); zos = null; } catch (IOException ex) { IMessage message = new Message("Unable to write outjar " + buildConfig.getOutputJar().getPath() + "(" + ex.getMessage() + ")", new SourceLocation(buildConfig.getOutputJar(),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(); 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.resources.contains(filename)) { IMessage msg = new Message("duplicate resource: '" + filename + "'", IMessage.WARNING, null, new SourceLocation(srcLocation,0)); handler.handleMessage(msg); return; } if (zos != null) { ZipEntry newEntry = new ZipEntry(filename); //??? get compression scheme right zos.putNextEntry(newEntry); zos.write(content); zos.closeEntry(); } else { OutputStream fos = FileUtil.makeOutputStream(new File(buildConfig.getOutputDir(),filename)); fos.write(content); fos.close(); } state.resources.add(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 = bcelWeaver.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")) ) { return false; } else { return true; } } /** * Responsible for managing the ASM model between builds. Contains the policy for * maintaining the persistance of elements in the model. * * TODO: implement incremental policy. */ private void setupModel() { String rootLabel = "<root>"; IHierarchy model = AsmManager.getDefault().getHierarchy(); AsmManager.getDefault().getRelationshipMap().clear(); 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); } /** init only on initial batch compile? no file-specific options */ private void initBcelWorld(IMessageHandler handler) throws IOException { bcelWorld = new BcelWorld(buildConfig.getClasspath(), handler, null); bcelWorld.setXnoInline(buildConfig.isXnoInline()); bcelWorld.setXlazyTjp(buildConfig.isXlazyTjp()); bcelWeaver = new BcelWeaver(bcelWorld); state.binarySourceFiles = new HashMap(); for (Iterator i = buildConfig.getAspectpath().iterator(); i.hasNext();) { File f = (File) i.next(); bcelWeaver.addLibraryJarFile(f); } // String lintMode = buildConfig.getLintMode(); if (buildConfig.getLintMode().equals(AjBuildConfig.AJLINT_DEFAULT)) { bcelWorld.getLint().loadDefaultProperties(); } else { bcelWorld.getLint().setAll(buildConfig.getLintMode()); } if (buildConfig.getLintSpecFile() != null) { bcelWorld.getLint().setFromProperties(buildConfig.getLintSpecFile()); } //??? incremental issues for (Iterator i = buildConfig.getInJars().iterator(); i.hasNext(); ) { File inJar = (File)i.next(); List unwovenClasses = bcelWeaver.addJarFile(inJar, buildConfig.getOutputDir(),false); state.binarySourceFiles.put(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.binarySourceFiles.put(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.binarySourceFiles.put(binSrcs[j].getPath(),ucfl); } } } bcelWeaver.setReweavableMode(buildConfig.isXreweavable(),buildConfig.getXreweavableCompressClasses()); //check for org.aspectj.runtime.JoinPoint bcelWorld.resolve("org.aspectj.lang.JoinPoint"); } public World getWorld() { return bcelWorld; } void addAspectClassFilesToWeaver(List addedClassFiles) throws IOException { for (Iterator i = addedClassFiles.iterator(); i.hasNext(); ) { UnwovenClassFile classFile = (UnwovenClassFile) i.next(); bcelWeaver.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(); 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.classesFromName.isEmpty()) { environment = new StatefulNameEnvironment(environment, state.classesFromName); } org.eclipse.jdt.internal.compiler.Compiler.setCompilerAdapterFactory(this); org.eclipse.jdt.internal.compiler.Compiler compiler = new 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 environment.cleanup(); environment = null; } /* * Answer the component to which will be handed back compilation results from the compiler */ public IIntermediateResultsRequestor getInterimResultRequestor() { return new IIntermediateResultsRequestor() { int lineDelta = 0; 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())) { 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"; try { if (buildConfig.getOutputJar() == null) { writeDirectoryEntry(unitResult, classFile,filename); } else { writeZipEntry(classFile,filename); } } catch (IOException ex) { IMessage message = EclipseAdapterUtils.makeErrorMessage( new String(unitResult.fileName), CANT_WRITE_RESULT, ex); handler.handleMessage(message); } } } if (unitResult.hasProblems() || unitResult.hasTasks()) { IProblem[] problems = unitResult.getAllProblems(); for (int i=0; i < problems.length; i++) { IMessage message = EclipseAdapterUtils.makeMessage(unitResult.compilationUnit, problems[i]); handler.handleMessage(message); } } } private void writeDirectoryEntry( CompilationResult unitResult, ClassFile classFile, String filename) throws IOException { File destinationPath = buildConfig.getOutputDir(); 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(); } }; } protected boolean proceedOnError() { return true; //??? } // 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; handler.reset(); } String makeClasspathString() { if (buildConfig == null || buildConfig.getClasspath() == null) return ""; StringBuffer buf = new StringBuffer(); boolean first = true; for (Iterator it = buildConfig.getClasspath().iterator(); it.hasNext(); ) { if (first) { first = false; } else { buf.append(File.pathSeparator); } buf.append(it.next().toString()); } return buf.toString(); } /** * This will return null if aspectjrt.jar is present and has the correct version. * Otherwise it will return a string message indicating the problem. */ public String checkRtJar(AjBuildConfig buildConfig) { // omitting dev info if (Version.text.equals(Version.DEVELOPMENT)) { // in the development version we can't do this test usefully // MessageUtil.info(holder, "running development version of aspectj compiler"); return null; } if (buildConfig == null || buildConfig.getClasspath() == null) return "no classpath specified"; for (Iterator it = buildConfig.getClasspath().iterator(); it.hasNext(); ) { File p = new File( (String)it.next() ); if (p.isFile() && p.getName().equals("aspectjrt.jar")) { try { String version = null; Manifest manifest = new JarFile(p).getManifest(); if (manifest == null) { return "no manifest found in " + p.getAbsolutePath() + ", expected " + Version.text; } 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)) { return "bad version number found in " + p.getAbsolutePath() + " expected " + Version.text + " found " + version; } } catch (IOException ioe) { return "bad jar file found in " + p.getAbsolutePath() + " error: " + ioe; } return null; } else { // might want to catch other classpath errors } } return "couldn't find aspectjrt.jar on classpath, checked: " + makeClasspathString(); } 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.eclipse.jdt.internal.compiler.Compiler forCompiler) { // complete compiler config and return a suitable adapter... AjProblemReporter pr = new AjProblemReporter(DefaultErrorHandlingPolicies.proceedWithAllProblems(), forCompiler.options, getProblemFactory()); forCompiler.problemReporter = pr; AjLookupEnvironment le = new AjLookupEnvironment(forCompiler, forCompiler.options, pr, environment); EclipseFactory factory = new EclipseFactory(le,this); le.factory = factory; pr.factory = factory; forCompiler.lookupEnvironment = le; forCompiler.parser = new Parser( pr, forCompiler.options.parseLiteralExpressionsAsConstants); return new AjCompilerAdapter(forCompiler,batchCompile,bcelWorld,bcelWeaver, factory, getInterimResultRequestor(), progressListener, this, // IOutputFilenameProvider this, // IBinarySourceProvider state.binarySourceFiles, state.resultsFromFile.values(), buildConfig.isNoWeave()); } /* (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; } } // class AjBuildManager
57,666
Bug 57666 duplicate manifests cause resource-copying to gack
(Ah, the joy of build infrastructure...) Mostly self-explanatory trace, from a build Monday Apr 5, 2004 at 08:46:01 GMT: duplicate entry: META-INF/MANIFEST.MF duplicate entry: META-INF/MANIFEST.MF java.util.zip.ZipException: duplicate entry: META-INF/MANIFEST.MF at java.util.zip.ZipOutputStream.putNextEntry(ZipOutputStream.java:163) at java.util.jar.JarOutputStream.putNextEntry(JarOutputStream.java:90) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.writeResource(AjBuildManager.java:344) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.copyResourcesFromJarFile(AjBuildManager.java:288) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.copyResourcesToDestination(AjBuildManager.java:253) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.doBuild(AjBuildManager.java:195) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.batchBuild(AjBuildManager.java:94) at org.aspectj.ajdt.ajc.AjdtCommand.doCommand(AjdtCommand.java:102) at org.aspectj.ajdt.ajc.AjdtCommand.runCommand(AjdtCommand.java:53) at org.aspectj.tools.ajc.Main.run(Main.java:280) at org.aspectj.tools.ajc.Main.runMain(Main.java:217) at org.aspectj.tools.ajc.Main.main(Main.java:79)
resolved fixed
2b8fa31
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2004-08-02T15:47:02Z
2004-04-06T22:20:00Z
org.aspectj.ajdt.core/testsrc/org/aspectj/ajdt/internal/compiler/batch/BcweaverJarMaker.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Common Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * PARC initial implementation * ******************************************************************/ package org.aspectj.ajdt.internal.compiler.batch; import java.io.File; import java.io.IOException; import java.util.*; import java.util.ArrayList; import org.aspectj.ajdt.ajc.AjdtAjcTests; public class BcweaverJarMaker { public BcweaverJarMaker() { super(); } public static void main(String[] args) throws IOException { makeJar0(); makeJar1(); makeJar1a(); makeJar2(); makeJarObviousNothing(); makeJarHardNothing(); makeTestJars(); makeURLWeavingClassLoaderJars(); } public static void makeJar0() throws IOException { List args = new ArrayList(); args.add("-outjar"); args.add("../weaver/testdata/tracing.jar"); args.add("-classpath"); args.add("../runtime/bin" + File.pathSeparator + System.getProperty("aspectjrt.path")); args.add(AjdtAjcTests.TESTDATA_PATH + "/src1/Trace.java"); args.add(AjdtAjcTests.TESTDATA_PATH + "/src1/MyTrace.java"); CommandTestCase.runCompiler(args, CommandTestCase.NO_ERRORS); } public static void makeJar1() throws IOException { List args = new ArrayList(); args.add("-outjar"); args.add("../weaver/testdata/megatrace.jar"); args.add("-classpath"); args.add("../runtime/bin" + File.pathSeparator + System.getProperty("aspectjrt.path")); args.add(AjdtAjcTests.TESTDATA_PATH + "/src1/trace/MegaTrace.java"); args.add(AjdtAjcTests.TESTDATA_PATH + "/src1/trace/ExecTrace.java"); CommandTestCase.runCompiler(args, CommandTestCase.NO_ERRORS); } public static void makeJarObviousNothing() throws IOException { List args = new ArrayList(); args.add("-outjar"); args.add("../weaver/testdata/megatrace0easy.jar"); args.add("-classpath"); args.add("../runtime/bin" + File.pathSeparator + System.getProperty("aspectjrt.path")); args.add(AjdtAjcTests.TESTDATA_PATH + "/src1/trace/MegaTrace.java"); args.add(AjdtAjcTests.TESTDATA_PATH + "/src1/trace/ObviousTraceNothing.java"); CommandTestCase.runCompiler(args, CommandTestCase.NO_ERRORS); } public static void makeJarHardNothing() throws IOException { List args = new ArrayList(); args.add("-outjar"); args.add("../weaver/testdata/megatrace0hard.jar"); args.add("-classpath"); args.add("../runtime/bin" + File.pathSeparator + System.getProperty("aspectjrt.path")); args.add(AjdtAjcTests.TESTDATA_PATH + "/src1/trace/MegaTrace.java"); args.add(AjdtAjcTests.TESTDATA_PATH + "/src1/trace/HardTraceNothing.java"); CommandTestCase.runCompiler(args, CommandTestCase.NO_ERRORS); } public static void makeJar1a() throws IOException { List args = new ArrayList(); args.add("-outjar"); args.add("../weaver/testdata/megatraceNoweave.jar"); args.add("-noweave"); args.add("-classpath"); args.add("../runtime/bin" + File.pathSeparator + System.getProperty("aspectjrt.path")); args.add(AjdtAjcTests.TESTDATA_PATH + "/src1/trace/MegaTrace.java"); args.add(AjdtAjcTests.TESTDATA_PATH + "/src1/trace/ExecTrace.java"); CommandTestCase.runCompiler(args, CommandTestCase.NO_ERRORS); } public static void makeJar2() throws IOException { List args = new ArrayList(); args.add("-outjar"); args.add("../weaver/testdata/dummyAspect.jar"); args.add("-classpath"); args.add("../runtime/bin" + File.pathSeparator + System.getProperty("aspectjrt.path")); args.add(AjdtAjcTests.TESTDATA_PATH + "/src1/DummyAspect.java"); CommandTestCase.runCompiler(args, CommandTestCase.NO_ERRORS); } public static void makeTestJars() throws IOException { List args = new ArrayList(); args.add("-classpath"); args.add("../lib/test/aspectjrt.jar;../lib/test/testing-client.jar" + File.pathSeparator + System.getProperty("aspectjrt.path")); args.add("-outjar"); args.add("../tests/new/options11/aspectlib1.jar"); args.add("../tests/new/options11/library1/*.java"); CommandTestCase.runCompiler(args, CommandTestCase.NO_ERRORS); args = new ArrayList(); args.add("-classpath"); args.add("../lib/test/aspectjrt.jar;../lib/test/testing-client.jar" + File.pathSeparator + System.getProperty("aspectjrt.path")); args.add("-outjar"); args.add("../tests/new/options11/aspectlib2.jar"); args.add("../tests/new/options11/library2/*.java"); CommandTestCase.runCompiler(args, CommandTestCase.NO_ERRORS); args = new ArrayList(); args.add("-classpath"); args.add("../lib/test/aspectjrt.jar;../lib/test/testing-client.jar" + File.pathSeparator + System.getProperty("aspectjrt.path")); args.add("-outjar"); args.add("../tests/new/options11/injar.jar"); args.add("../tests/new/options11/injar/*.java"); CommandTestCase.runCompiler(args, CommandTestCase.NO_ERRORS); args = new ArrayList(); args.add("-classpath"); args.add("../lib/test/aspectjrt.jar;../lib/test/testing-client.jar" + File.pathSeparator + System.getProperty("aspectjrt.path")); args.add("-outjar"); args.add("../tests/bugs/serialVersionUID/injar.jar"); args.add("../tests/bugs/serialVersionUID/Test.java"); args.add("../tests/bugs/serialVersionUID/Util.java"); CommandTestCase.runCompiler(args, CommandTestCase.NO_ERRORS); // For PR55341 args = new ArrayList(); args.add("-classpath"); args.add("../lib/test/aspectjrt.jar;../lib/test/testing-client.jar" + File.pathSeparator + System.getProperty("aspectjrt.path")); args.add("-outjar"); args.add("../tests/bugs/StringToString/helloworld.jar"); args.add("../tests/bugs/StringToString/HW.java"); CommandTestCase.runCompiler(args, CommandTestCase.NO_ERRORS); } public static void makeURLWeavingClassLoaderJars() throws IOException { List args = new ArrayList(); /* * Vanilla classes */ args.add("-classpath"); args.add("../lib/test/aspectjrt.jar;../lib/test/testing-client.jar" + File.pathSeparator + System.getProperty("aspectjrt.path")); args.add("-outjar"); args.add("../weaver/testdata/ltw-classes.jar"); args.add(AjdtAjcTests.TESTDATA_PATH + "/src1/LTWHelloWorld.java"); args.add(AjdtAjcTests.TESTDATA_PATH + "/src1/ltw/LTWPackageTest.java"); CommandTestCase.runCompiler(args, CommandTestCase.NO_ERRORS); /* * Woven classes */ args = new ArrayList(); args.add("-classpath"); args.add("../lib/test/aspectjrt.jar;../lib/test/testing-client.jar;../weaver/testdata/ltw-classes.jar" + File.pathSeparator + System.getProperty("aspectjrt.path")); args.add("-outjar"); args.add("../weaver/testdata/ltw-woven.jar"); args.add(AjdtAjcTests.TESTDATA_PATH + "/src1/LTWHelloWorld.java"); args.add(AjdtAjcTests.TESTDATA_PATH + "/src1/LTWAspect.aj"); CommandTestCase.runCompiler(args, CommandTestCase.NO_ERRORS); /* * Advice */ args = new ArrayList(); args.add("-classpath"); args.add("../lib/test/aspectjrt.jar;../lib/test/testing-client.jar;../weaver/testdata/ltw-classes.jar" + File.pathSeparator + System.getProperty("aspectjrt.path")); args.add("-outjar"); args.add("../weaver/testdata/ltw-aspects.jar"); args.add(AjdtAjcTests.TESTDATA_PATH + "/src1/LTWAspect.aj"); CommandTestCase.runCompiler(args, CommandTestCase.NO_ERRORS); /* * Declare warning advice */ args = new ArrayList(); args.add("-classpath"); args.add("../lib/test/aspectjrt.jar;../lib/test/testing-client.jar;../weaver/testdata/ltw-classes.jar" + File.pathSeparator + System.getProperty("aspectjrt.path")); args.add("-outjar"); args.add("../weaver/testdata/ltw-dwaspects.jar"); args.add(AjdtAjcTests.TESTDATA_PATH + "/src1/LTWDeclareWarning.aj"); CommandTestCase.runCompiler(args, CommandTestCase.NO_ERRORS); /* * Declare error advice */ args = new ArrayList(); args.add("-classpath"); args.add("../lib/test/aspectjrt.jar;../lib/test/testing-client.jar;../weaver/testdata/ltw-classes.jar" + File.pathSeparator + System.getProperty("aspectjrt.path")); args.add("-outjar"); args.add("../weaver/testdata/ltw-deaspects.jar"); args.add(AjdtAjcTests.TESTDATA_PATH + "/src1/LTWDeclareError.aj"); CommandTestCase.runCompiler(args, CommandTestCase.NO_ERRORS); /* * Around closure advice */ args = new ArrayList(); args.add("-classpath"); args.add("../lib/test/aspectjrt.jar;../lib/test/testing-client.jar;../weaver/testdata/ltw-classes.jar" + File.pathSeparator + System.getProperty("aspectjrt.path")); args.add("-outjar"); args.add("../weaver/testdata/ltw-acaspects.jar"); args.add(AjdtAjcTests.TESTDATA_PATH + "/src1/LTWAroundClosure.aj"); CommandTestCase.runCompiler(args, CommandTestCase.NO_ERRORS); /* * ITD */ args = new ArrayList(); args.add("-Xlint:ignore"); args.add("-classpath"); args.add("../lib/test/aspectjrt.jar;../lib/test/testing-client.jar;../weaver/testdata/ltw-classes.jar" + File.pathSeparator + System.getProperty("aspectjrt.path")); args.add("-outjar"); args.add("../weaver/testdata/ltw-itdaspects.jar"); args.add(AjdtAjcTests.TESTDATA_PATH + "/src1/LTWInterfaceITD.aj"); args.add(AjdtAjcTests.TESTDATA_PATH + "/src1/LTWFieldITD.aj"); args.add(AjdtAjcTests.TESTDATA_PATH + "/src1/LTWMethodITD.aj"); CommandTestCase.runCompiler(args, CommandTestCase.NO_ERRORS); /* * perXXX() */ args = new ArrayList(); args.add("-classpath"); args.add("../lib/test/aspectjrt.jar;../lib/test/testing-client.jar;../weaver/testdata/ltw-classes.jar" + File.pathSeparator + System.getProperty("aspectjrt.path")); args.add("-outjar"); args.add("../weaver/testdata/ltw-peraspects.jar"); args.add(AjdtAjcTests.TESTDATA_PATH + "/src1/LTWPerthis.aj"); CommandTestCase.runCompiler(args, CommandTestCase.NO_ERRORS); } }
57,666
Bug 57666 duplicate manifests cause resource-copying to gack
(Ah, the joy of build infrastructure...) Mostly self-explanatory trace, from a build Monday Apr 5, 2004 at 08:46:01 GMT: duplicate entry: META-INF/MANIFEST.MF duplicate entry: META-INF/MANIFEST.MF java.util.zip.ZipException: duplicate entry: META-INF/MANIFEST.MF at java.util.zip.ZipOutputStream.putNextEntry(ZipOutputStream.java:163) at java.util.jar.JarOutputStream.putNextEntry(JarOutputStream.java:90) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.writeResource(AjBuildManager.java:344) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.copyResourcesFromJarFile(AjBuildManager.java:288) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.copyResourcesToDestination(AjBuildManager.java:253) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.doBuild(AjBuildManager.java:195) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.batchBuild(AjBuildManager.java:94) at org.aspectj.ajdt.ajc.AjdtCommand.doCommand(AjdtCommand.java:102) at org.aspectj.ajdt.ajc.AjdtCommand.runCommand(AjdtCommand.java:53) at org.aspectj.tools.ajc.Main.run(Main.java:280) at org.aspectj.tools.ajc.Main.runMain(Main.java:217) at org.aspectj.tools.ajc.Main.main(Main.java:79)
resolved fixed
2b8fa31
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2004-08-02T15:47:02Z
2004-04-06T22:20:00Z
weaver/src/org/aspectj/weaver/bcel/BcelWeaver.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Common Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * PARC initial implementation * ******************************************************************/ package org.aspectj.weaver.bcel; import java.io.ByteArrayInputStream; 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.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Set; import java.util.jar.Attributes; import java.util.jar.Attributes.Name; import java.util.jar.JarInputStream; import java.util.jar.Manifest; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; import java.util.zip.ZipOutputStream; import org.apache.bcel.classfile.ClassParser; import org.apache.bcel.classfile.JavaClass; import org.aspectj.bridge.IMessage; import org.aspectj.bridge.IProgressListener; import org.aspectj.bridge.Message; import org.aspectj.bridge.SourceLocation; import org.aspectj.util.FileUtil; import org.aspectj.weaver.ConcreteTypeMunger; import org.aspectj.weaver.CrosscuttingMembersSet; import org.aspectj.weaver.IClassFileProvider; import org.aspectj.weaver.IWeaveRequestor; import org.aspectj.weaver.IWeaver; import org.aspectj.weaver.NewParentTypeMunger; import org.aspectj.weaver.ResolvedTypeMunger; import org.aspectj.weaver.ResolvedTypeX; import org.aspectj.weaver.ShadowMunger; import org.aspectj.weaver.TypeX; import org.aspectj.weaver.WeaverMessages; import org.aspectj.weaver.WeaverStateInfo; import org.aspectj.weaver.patterns.DeclareParents; import org.aspectj.weaver.patterns.FastMatchInfo; public class BcelWeaver implements IWeaver { private BcelWorld world; private CrosscuttingMembersSet xcutSet; private IProgressListener progressListener = null; private double progressMade; private double progressPerClassFile; private boolean inReweavableMode = false; public BcelWeaver(BcelWorld world) { super(); this.world = world; this.xcutSet = world.getCrosscuttingMembersSet(); } public BcelWeaver() { this(new BcelWorld()); } // ---- fields // private Map sourceJavaClasses = new HashMap(); /* String -> UnwovenClassFile */ private List addedClasses = new ArrayList(); /* List<UnovenClassFile> */ private List deletedTypenames = new ArrayList(); /* List<String> */ // private Map resources = new HashMap(); /* String -> UnwovenClassFile */ private Manifest manifest = null; private boolean needToReweaveWorld = false; private List shadowMungerList = null; // setup by prepareForWeave private List typeMungerList = null; // setup by prepareForWeave private List declareParentsList = null; // setup by prepareForWeave private ZipOutputStream zipOutputStream; // ---- // only called for testing public void setShadowMungers(List l) { shadowMungerList = l; } public void addLibraryAspect(String aspectName) { ResolvedTypeX type = world.resolve(aspectName); //System.out.println("type: " + type + " for " + aspectName); if (type.isAspect()) { xcutSet.addOrReplaceAspect(type); } else { throw new RuntimeException("unimplemented"); } } public void addLibraryJarFile(File inFile) throws IOException { ZipInputStream inStream = new ZipInputStream(new FileInputStream(inFile)); //??? buffered List addedAspects = new ArrayList(); while (true) { ZipEntry entry = inStream.getNextEntry(); if (entry == null) break; if (entry.isDirectory() || !entry.getName().endsWith(".class")) { continue; } ClassParser parser = new ClassParser(new ByteArrayInputStream(FileUtil.readAsByteArray(inStream)), entry.getName()); JavaClass jc = parser.parse(); inStream.closeEntry(); ResolvedTypeX type = world.addSourceObjectType(jc).getResolvedTypeX(); if (type.isAspect()) { addedAspects.add(type); } } inStream.close(); for (Iterator i = addedAspects.iterator(); i.hasNext();) { ResolvedTypeX aspectX = (ResolvedTypeX) i.next(); xcutSet.addOrReplaceAspect(aspectX); } } // // The ANT copy task should be used to copy resources across. // private final static boolean CopyResourcesFromInpathDirectoriesToOutput=false; private Set alreadyConfirmedReweavableState; /** * Add any .class files in the directory to the outdir. Anything other than .class files in * the directory (or its subdirectories) are considered resources and are also copied. * */ public List addDirectoryContents(File inFile,File outDir) throws IOException { List addedClassFiles = new ArrayList(); // Get a list of all files (i.e. everything that isnt a directory) File[] files = FileUtil.listFiles(inFile,new FileFilter() { public boolean accept(File f) { boolean accept = !f.isDirectory(); return accept; } }); // For each file, add it either as a real .class file or as a resource for (int i = 0; i < files.length; i++) { addedClassFiles.add(addClassFile(files[i],inFile,outDir)); } return addedClassFiles; } /** Adds all class files in the jar */ public List addJarFile(File inFile, File outDir, boolean canBeDirectory){ // System.err.println("? addJarFile(" + inFile + ", " + outDir + ")"); List addedClassFiles = new ArrayList(); needToReweaveWorld = true; JarInputStream inStream = null; try { // Is this a directory we are looking at? if (inFile.isDirectory() && canBeDirectory) { addedClassFiles.addAll(addDirectoryContents(inFile,outDir)); } else { inStream = new JarInputStream(new FileInputStream(inFile)); //??? buffered addManifest(inStream.getManifest()); while (true) { ZipEntry entry = inStream.getNextEntry(); if (entry == null) break; byte[] bytes = FileUtil.readAsByteArray(inStream); String filename = entry.getName(); UnwovenClassFile classFile = new UnwovenClassFile(new File(outDir, filename).getAbsolutePath(), bytes); if (filename.endsWith(".class")) { this.addClassFile(classFile); addedClassFiles.add(classFile); } // else if (!entry.isDirectory()) { // // /* bug-44190 Copy meta-data */ // addResource(filename,classFile); // } inStream.closeEntry(); } inStream.close(); } } catch (FileNotFoundException ex) { IMessage message = new Message( "Could not find input jar file " + inFile.getPath() + ", ignoring", new SourceLocation(inFile,0), false); world.getMessageHandler().handleMessage(message); } catch (IOException ex) { IMessage message = new Message( "Could not read input jar file " + inFile.getPath() + "(" + ex.getMessage() + ")", new SourceLocation(inFile,0), true); world.getMessageHandler().handleMessage(message); } finally { if (inStream != null) { try {inStream.close();} catch (IOException ex) { IMessage message = new Message( "Could not close input jar file " + inFile.getPath() + "(" + ex.getMessage() + ")", new SourceLocation(inFile,0), true); world.getMessageHandler().handleMessage(message); } } } return addedClassFiles; } // public void addResource(String name, File inPath, File outDir) throws IOException { // // /* Eliminate CVS files. Relative paths use "/" */ // if (!name.startsWith("CVS/") && (-1 == name.indexOf("/CVS/")) && !name.endsWith("/CVS")) { //// System.err.println("? addResource('" + name + "')"); //// BufferedInputStream inStream = new BufferedInputStream(new FileInputStream(inPath)); //// byte[] bytes = new byte[(int)inPath.length()]; //// inStream.read(bytes); //// inStream.close(); // byte[] bytes = FileUtil.readAsByteArray(inPath); // UnwovenClassFile resourceFile = new UnwovenClassFile(new File(outDir, name).getAbsolutePath(), bytes); // addResource(name,resourceFile); // } // } public boolean needToReweaveWorld() { return needToReweaveWorld; } /** Should be addOrReplace */ public void addClassFile(UnwovenClassFile classFile) { addedClasses.add(classFile); // if (null != sourceJavaClasses.put(classFile.getClassName(), classFile)) { //// throw new RuntimeException(classFile.getClassName()); // } world.addSourceObjectType(classFile.getJavaClass()); } public UnwovenClassFile addClassFile(File classFile, File inPathDir, File outDir) throws IOException { FileInputStream fis = new FileInputStream(classFile); byte[] bytes = FileUtil.readAsByteArray(fis); // String relativePath = files[i].getPath(); // ASSERT: files[i].getAbsolutePath().startsWith(inFile.getAbsolutePath() // or we are in trouble... String filename = classFile.getAbsolutePath().substring( inPathDir.getAbsolutePath().length()+1); UnwovenClassFile ucf = new UnwovenClassFile(new File(outDir,filename).getAbsolutePath(),bytes); if (filename.endsWith(".class")) { // System.err.println("BCELWeaver: processing class from input directory "+classFile); this.addClassFile(ucf); } fis.close(); return ucf; } public void deleteClassFile(String typename) { deletedTypenames.add(typename); // sourceJavaClasses.remove(typename); world.deleteSourceObjectType(TypeX.forName(typename)); } // public void addResource (String name, UnwovenClassFile resourceFile) { // /* bug-44190 Change error to warning and copy first resource */ // if (!resources.containsKey(name)) { // resources.put(name, resourceFile); // } // else { // world.showMessage(IMessage.WARNING, "duplicate resource: '" + name + "'", // null, null); // } // } // ---- weave preparation public void prepareForWeave() { needToReweaveWorld = false; // update mungers for (Iterator i = addedClasses.iterator(); i.hasNext(); ) { UnwovenClassFile jc = (UnwovenClassFile)i.next(); String name = jc.getClassName(); ResolvedTypeX type = world.resolve(name); //System.err.println("added: " + type + " aspect? " + type.isAspect()); if (type.isAspect()) { needToReweaveWorld |= xcutSet.addOrReplaceAspect(type); } } for (Iterator i = deletedTypenames.iterator(); i.hasNext(); ) { String name = (String)i.next(); if (xcutSet.deleteAspect(TypeX.forName(name))) needToReweaveWorld = true; } shadowMungerList = xcutSet.getShadowMungers(); typeMungerList = xcutSet.getTypeMungers(); declareParentsList = xcutSet.getDeclareParents(); //XXX this gets us a stable (but completely meaningless) order Collections.sort( shadowMungerList, new Comparator() { public int compare(Object o1, Object o2) { return o1.toString().compareTo(o2.toString()); } }); } // public void dumpUnwoven(File file) throws IOException { // BufferedOutputStream os = FileUtil.makeOutputStream(file); // this.zipOutputStream = new ZipOutputStream(os); // dumpUnwoven(); // /* BUG 40943*/ // dumpResourcesToOutJar(); // zipOutputStream.close(); //this flushes and closes the acutal file // } // // // public void dumpUnwoven() throws IOException { // Collection filesToDump = new HashSet(sourceJavaClasses.values()); // for (Iterator i = filesToDump.iterator(); i.hasNext(); ) { // UnwovenClassFile classFile = (UnwovenClassFile)i.next(); // dumpUnchanged(classFile); // } // } // public void dumpResourcesToOutPath() throws IOException { //// System.err.println("? dumpResourcesToOutPath() resources=" + resources.keySet()); // Iterator i = resources.keySet().iterator(); // while (i.hasNext()) { // UnwovenClassFile res = (UnwovenClassFile)resources.get(i.next()); // dumpUnchanged(res); // } // //resources = new HashMap(); // } // /* BUG #40943 */ // public void dumpResourcesToOutJar() throws IOException { //// System.err.println("? dumpResourcesToOutJar() resources=" + resources.keySet()); // Iterator i = resources.keySet().iterator(); // while (i.hasNext()) { // String name = (String)i.next(); // UnwovenClassFile res = (UnwovenClassFile)resources.get(name); // writeZipEntry(name,res.getBytes()); // } // resources = new HashMap(); // } // // // halfway house for when the jar is managed outside of the weaver, but the resources // // to be copied are known in the weaver. // public void dumpResourcesToOutJar(ZipOutputStream zos) throws IOException { // this.zipOutputStream = zos; // dumpResourcesToOutJar(); // } public void addManifest (Manifest newManifest) { if (manifest == null) { manifest = newManifest; } } private static final String WEAVER_MANIFEST_VERSION = "1.0"; private static final Attributes.Name CREATED_BY = new Name("Created-By"); private static final String WEAVER_CREATED_BY = "AspectJ Compiler"; public Manifest getManifest (boolean shouldCreate) { if (manifest == null && shouldCreate) { manifest = new Manifest(); Attributes attributes = manifest.getMainAttributes(); attributes.put(Name.MANIFEST_VERSION,WEAVER_MANIFEST_VERSION); attributes.put(CREATED_BY,WEAVER_CREATED_BY); } return manifest; } // ---- weaving // Used by some test cases only... public Collection weave(File file) throws IOException { OutputStream os = FileUtil.makeOutputStream(file); this.zipOutputStream = new ZipOutputStream(os); prepareForWeave(); Collection c = weave( new IClassFileProvider() { public Iterator getClassFileIterator() { return addedClasses.iterator(); } public IWeaveRequestor getRequestor() { return new IWeaveRequestor() { public void acceptResult(UnwovenClassFile result) { try { writeZipEntry(result.filename, result.bytes); } catch(IOException ex) {} } public void processingReweavableState() {} public void addingTypeMungers() {} public void weavingAspects() {} public void weavingClasses() {} public void weaveCompleted() {} }; } }); // /* BUG 40943*/ // dumpResourcesToOutJar(); zipOutputStream.close(); //this flushes and closes the acutal file return c; } // public Collection weave() throws IOException { // prepareForWeave(); // Collection filesToWeave; // // if (needToReweaveWorld) { // filesToWeave = sourceJavaClasses.values(); // } else { // filesToWeave = addedClasses; // } // // Collection wovenClassNames = new ArrayList(); // world.showMessage(IMessage.INFO, "might need to weave " + filesToWeave + // "(world=" + needToReweaveWorld + ")", null, null); // // // //System.err.println("typeMungers: " + typeMungerList); // // prepareToProcessReweavableState(); // // clear all state from files we'll be reweaving // for (Iterator i = filesToWeave.iterator(); i.hasNext(); ) { // UnwovenClassFile classFile = (UnwovenClassFile)i.next(); // String className = classFile.getClassName(); // BcelObjectType classType = getClassType(className); // processReweavableStateIfPresent(className, classType); // } // // // // //XXX this isn't quite the right place for this... // for (Iterator i = filesToWeave.iterator(); i.hasNext(); ) { // UnwovenClassFile classFile = (UnwovenClassFile)i.next(); // String className = classFile.getClassName(); // addTypeMungers(className); // } // // // first weave into aspects // for (Iterator i = filesToWeave.iterator(); i.hasNext(); ) { // UnwovenClassFile classFile = (UnwovenClassFile)i.next(); // String className = classFile.getClassName(); // BcelObjectType classType = BcelWorld.getBcelObjectType(world.resolve(className)); // if (classType.isAspect()) { // weave(classFile, classType); // wovenClassNames.add(className); // } // } // // // then weave into non-aspects // for (Iterator i = filesToWeave.iterator(); i.hasNext(); ) { // UnwovenClassFile classFile = (UnwovenClassFile)i.next(); // String className = classFile.getClassName(); // BcelObjectType classType = BcelWorld.getBcelObjectType(world.resolve(className)); // if (! classType.isAspect()) { // weave(classFile, classType); // wovenClassNames.add(className); // } // } // // if (zipOutputStream != null && !needToReweaveWorld) { // Collection filesToDump = new HashSet(sourceJavaClasses.values()); // filesToDump.removeAll(filesToWeave); // for (Iterator i = filesToDump.iterator(); i.hasNext(); ) { // UnwovenClassFile classFile = (UnwovenClassFile)i.next(); // dumpUnchanged(classFile); // } // } // // addedClasses = new ArrayList(); // deletedTypenames = new ArrayList(); // // return wovenClassNames; // } // variation of "weave" that sources class files from an external source. public Collection weave(IClassFileProvider input) throws IOException { Collection wovenClassNames = new ArrayList(); IWeaveRequestor requestor = input.getRequestor(); requestor.processingReweavableState(); prepareToProcessReweavableState(); // clear all state from files we'll be reweaving for (Iterator i = input.getClassFileIterator(); i.hasNext(); ) { UnwovenClassFile classFile = (UnwovenClassFile)i.next(); String className = classFile.getClassName(); BcelObjectType classType = getClassType(className); processReweavableStateIfPresent(className, classType); } requestor.addingTypeMungers(); //XXX this isn't quite the right place for this... for (Iterator i = input.getClassFileIterator(); i.hasNext(); ) { UnwovenClassFile classFile = (UnwovenClassFile)i.next(); String className = classFile.getClassName(); addTypeMungers(className); } requestor.weavingAspects(); // first weave into aspects for (Iterator i = input.getClassFileIterator(); i.hasNext(); ) { UnwovenClassFile classFile = (UnwovenClassFile)i.next(); String className = classFile.getClassName(); BcelObjectType classType = BcelWorld.getBcelObjectType(world.resolve(className)); if (classType.isAspect()) { weaveAndNotify(classFile, classType,requestor); wovenClassNames.add(className); } } requestor.weavingClasses(); // then weave into non-aspects for (Iterator i = input.getClassFileIterator(); i.hasNext(); ) { UnwovenClassFile classFile = (UnwovenClassFile)i.next(); String className = classFile.getClassName(); BcelObjectType classType = BcelWorld.getBcelObjectType(world.resolve(className)); if (! classType.isAspect()) { weaveAndNotify(classFile, classType, requestor); wovenClassNames.add(className); } } addedClasses = new ArrayList(); deletedTypenames = new ArrayList(); requestor.weaveCompleted(); return wovenClassNames; } public void prepareToProcessReweavableState() { if (inReweavableMode) world.showMessage(IMessage.INFO, WeaverMessages.format(WeaverMessages.REWEAVABLE_MODE), null, null); alreadyConfirmedReweavableState = new HashSet(); } public void processReweavableStateIfPresent(String className, BcelObjectType classType) { // If the class is marked reweavable, check any aspects around when it was built are in this world WeaverStateInfo wsi = classType.getWeaverState(); if (wsi!=null && wsi.isReweavable()) { // Check all necessary types are around! world.showMessage(IMessage.INFO, WeaverMessages.format(WeaverMessages.PROCESSING_REWEAVABLE,className,classType.getSourceLocation().getSourceFile()), null,null); Set aspectsPreviouslyInWorld = wsi.getAspectsAffectingType(); if (aspectsPreviouslyInWorld!=null) { for (Iterator iter = aspectsPreviouslyInWorld.iterator(); iter.hasNext();) { String requiredTypeName = (String) iter.next(); if (!alreadyConfirmedReweavableState.contains(requiredTypeName)) { ResolvedTypeX rtx = world.resolve(TypeX.forName(requiredTypeName),true); boolean exists = rtx!=ResolvedTypeX.MISSING; if (!exists) { world.showMessage(IMessage.ERROR, WeaverMessages.format(WeaverMessages.MISSING_REWEAVABLE_TYPE,requiredTypeName,className), classType.getSourceLocation(), null); } else { if (!world.getMessageHandler().isIgnoring(IMessage.INFO)) world.showMessage(IMessage.INFO, WeaverMessages.format(WeaverMessages.VERIFIED_REWEAVABLE_TYPE,requiredTypeName,rtx.getSourceLocation().getSourceFile()), null,null); alreadyConfirmedReweavableState.add(requiredTypeName); } } } } classType.setJavaClass(Utility.makeJavaClass(classType.getJavaClass().getFileName(), wsi.getUnwovenClassFileData())); } else { classType.resetState(); } } private void weaveAndNotify(UnwovenClassFile classFile, BcelObjectType classType, IWeaveRequestor requestor) throws IOException { LazyClassGen clazz = weaveWithoutDump(classFile,classType); classType.finishedWith(); //clazz is null if the classfile was unchanged by weaving... if (clazz != null) { UnwovenClassFile[] newClasses = getClassFilesFor(clazz); for (int i = 0; i < newClasses.length; i++) { requestor.acceptResult(newClasses[i]); } } else { requestor.acceptResult(classFile); } } // helper method public BcelObjectType getClassType(String forClass) { return BcelWorld.getBcelObjectType(world.resolve(forClass)); } public void addTypeMungers(String typeName) { weave(world.resolve(typeName)); } public UnwovenClassFile[] getClassFilesFor(LazyClassGen clazz) { List childClasses = clazz.getChildClasses(world); UnwovenClassFile[] ret = new UnwovenClassFile[1 + childClasses.size()]; ret[0] = new UnwovenClassFile(clazz.getFileName(),clazz.getJavaClass(world).getBytes()); int index = 1; for (Iterator iter = childClasses.iterator(); iter.hasNext();) { UnwovenClassFile.ChildClass element = (UnwovenClassFile.ChildClass) iter.next(); UnwovenClassFile childClass = new UnwovenClassFile(clazz.getFileName() + "$" + element.name, element.bytes); ret[index++] = childClass; } return ret; } public void weave(ResolvedTypeX onType) { onType.clearInterTypeMungers(); // need to do any declare parents before the matching below for (Iterator i = declareParentsList.iterator(); i.hasNext(); ) { DeclareParents p = (DeclareParents)i.next(); List newParents = p.findMatchingNewParents(onType); if (!newParents.isEmpty()) { BcelObjectType classType = BcelWorld.getBcelObjectType(onType); //System.err.println("need to do declare parents for: " + onType); for (Iterator j = newParents.iterator(); j.hasNext(); ) { ResolvedTypeX newParent = (ResolvedTypeX)j.next(); if (newParent.isClass()) { world.showMessage(IMessage.ERROR, WeaverMessages.format(WeaverMessages.DECP_BINARY_LIMITATION,onType.getName()), p.getSourceLocation(), null); continue; } classType.addParent(newParent); ResolvedTypeMunger newParentMunger = new NewParentTypeMunger(newParent); onType.addInterTypeMunger(new BcelTypeMunger(newParentMunger, xcutSet.findAspectDeclaringParents(p))); } } } for (Iterator i = typeMungerList.iterator(); i.hasNext(); ) { ConcreteTypeMunger m = (ConcreteTypeMunger)i.next(); if (m.matches(onType)) { onType.addInterTypeMunger(m); } } } // exposed for ClassLoader dynamic weaving public LazyClassGen weaveWithoutDump(UnwovenClassFile classFile, BcelObjectType classType) throws IOException { return weave(classFile, classType, false); } // non-private for testing LazyClassGen weave(UnwovenClassFile classFile, BcelObjectType classType) throws IOException { LazyClassGen ret = weave(classFile, classType, true); if (progressListener != null) { progressMade += progressPerClassFile; progressListener.setProgress(progressMade); progressListener.setText("woven: " + classFile.getFilename()); } return ret; } private LazyClassGen weave(UnwovenClassFile classFile, BcelObjectType classType, boolean dump) throws IOException { if (classType.isSynthetic()) { if (dump) dumpUnchanged(classFile); return null; } // JavaClass javaClass = classType.getJavaClass(); List shadowMungers = fastMatch(shadowMungerList, classType.getResolvedTypeX()); List typeMungers = classType.getResolvedTypeX().getInterTypeMungers(); classType.getResolvedTypeX().checkInterTypeMungers(); LazyClassGen clazz = null; if (shadowMungers.size() > 0 || typeMungers.size() > 0 || classType.isAspect()) { clazz = classType.getLazyClassGen(); //System.err.println("got lazy gen: " + clazz + ", " + clazz.getWeaverState()); try { boolean isChanged = BcelClassWeaver.weave(world, clazz, shadowMungers, typeMungers); if (isChanged) { if (dump) dump(classFile, clazz); return clazz; } } catch (RuntimeException re) { System.err.println("trouble in: "); //XXXclazz.print(System.err); throw re; } catch (Error re) { System.err.println("trouble in: "); clazz.print(System.err); throw re; } } // this is very odd return behavior trying to keep everyone happy if (dump) { dumpUnchanged(classFile); return clazz; } else { return null; } } // ---- writing private void dumpUnchanged(UnwovenClassFile classFile) throws IOException { if (zipOutputStream != null) { writeZipEntry(getEntryName(classFile.getJavaClass().getClassName()), classFile.getBytes()); } else { classFile.writeUnchangedBytes(); } } private String getEntryName(String className) { //XXX what does bcel's getClassName do for inner names return className.replace('.', '/') + ".class"; } private void dump(UnwovenClassFile classFile, LazyClassGen clazz) throws IOException { if (zipOutputStream != null) { String mainClassName = classFile.getJavaClass().getClassName(); writeZipEntry(getEntryName(mainClassName), clazz.getJavaClass(world).getBytes()); if (!clazz.getChildClasses(world).isEmpty()) { for (Iterator i = clazz.getChildClasses(world).iterator(); i.hasNext();) { UnwovenClassFile.ChildClass c = (UnwovenClassFile.ChildClass) i.next(); writeZipEntry(getEntryName(mainClassName + "$" + c.name), c.bytes); } } } else { classFile.writeWovenBytes( clazz.getJavaClass(world).getBytes(), clazz.getChildClasses(world) ); } } private void writeZipEntry(String name, byte[] bytes) throws IOException { ZipEntry newEntry = new ZipEntry(name); //??? get compression scheme right zipOutputStream.putNextEntry(newEntry); zipOutputStream.write(bytes); zipOutputStream.closeEntry(); } private List fastMatch(List list, ResolvedTypeX type) { if (list == null) return Collections.EMPTY_LIST; // here we do the coarsest grained fast match with no kind constraints // this will remove all obvious non-matches and see if we need to do any weaving FastMatchInfo info = new FastMatchInfo(type, null); List result = new ArrayList(); Iterator iter = list.iterator(); while (iter.hasNext()) { ShadowMunger munger = (ShadowMunger)iter.next(); if (munger.getPointcut().fastMatch(info).maybeTrue()) { result.add(munger); } } return result; } public void setProgressListener(IProgressListener listener, double previousProgress, double progressPerClassFile) { progressListener = listener; this.progressMade = previousProgress; this.progressPerClassFile = progressPerClassFile; } public void setReweavableMode(boolean mode,boolean compress) { inReweavableMode = mode; WeaverStateInfo.setReweavableModeDefaults(mode,compress); BcelClassWeaver.setReweavableMode(mode,compress); } public boolean isReweavable() { return inReweavableMode; } }
60,015
Bug 60015 NPE, Incorrect XLint:unmatchedSuperTypeInCall warning
(This is an incomplete bug report -- sorry no time not to further isolate.) Running AJDT 1.1.6, I get dozens of these warnings: ---------- Warning does not match because declaring type is java.lang.Object, if match desired use target(st.ata.mc.exim.DatastoreReader) [Xlint:unmatchedSuperTypeInCall] Blah.aj project/src/package/dir line 22 ---------- for something like this code: ---------- import pack.Interface; ... pointcut dsrCall() : call(* Interface.*(..)); // WARNING HERE ... ---------- Each warning points to the pointcut (not the join point shadow). NPE running from the command-line with the latest tree (will attach).
resolved fixed
ef7885f
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2004-08-03T14:53:38Z
2004-04-26T20:06:40Z
tests/bugs/IncorrectXlintOnInterface.java
60,015
Bug 60015 NPE, Incorrect XLint:unmatchedSuperTypeInCall warning
(This is an incomplete bug report -- sorry no time not to further isolate.) Running AJDT 1.1.6, I get dozens of these warnings: ---------- Warning does not match because declaring type is java.lang.Object, if match desired use target(st.ata.mc.exim.DatastoreReader) [Xlint:unmatchedSuperTypeInCall] Blah.aj project/src/package/dir line 22 ---------- for something like this code: ---------- import pack.Interface; ... pointcut dsrCall() : call(* Interface.*(..)); // WARNING HERE ... ---------- Each warning points to the pointcut (not the join point shadow). NPE running from the command-line with the latest tree (will attach).
resolved fixed
ef7885f
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2004-08-03T14:53:38Z
2004-04-26T20:06:40Z
weaver/src/org/aspectj/weaver/patterns/KindedPointcut.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Common Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * PARC initial implementation * ******************************************************************/ package org.aspectj.weaver.patterns; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.aspectj.bridge.ISourceLocation; import org.aspectj.lang.JoinPoint; import org.aspectj.util.FuzzyBoolean; import org.aspectj.weaver.Checker; import org.aspectj.weaver.ISourceContext; import org.aspectj.weaver.IntMap; import org.aspectj.weaver.Member; import org.aspectj.weaver.ResolvedTypeX; import org.aspectj.weaver.Shadow; import org.aspectj.weaver.ShadowMunger; import org.aspectj.weaver.TypeX; import org.aspectj.weaver.World; import org.aspectj.weaver.ast.Literal; import org.aspectj.weaver.ast.Test; public class KindedPointcut extends Pointcut { Shadow.Kind kind; SignaturePattern signature; private ShadowMunger munger = null; // only set after concretization public KindedPointcut( Shadow.Kind kind, SignaturePattern signature) { this.kind = kind; this.signature = signature; } public KindedPointcut( Shadow.Kind kind, SignaturePattern signature, ShadowMunger munger) { this(kind, signature); this.munger = munger; } public FuzzyBoolean fastMatch(FastMatchInfo info) { if (info.getKind() != null) { if (info.getKind() != kind) return FuzzyBoolean.NO; } return FuzzyBoolean.MAYBE; } public FuzzyBoolean match(Shadow shadow) { if (shadow.getKind() != kind) return FuzzyBoolean.NO; if (!signature.matches(shadow.getSignature(), shadow.getIWorld())){ if(kind == Shadow.MethodCall) { warnOnConfusingSig(shadow); } return FuzzyBoolean.NO; } return FuzzyBoolean.YES; } public FuzzyBoolean match(JoinPoint.StaticPart jpsp) { if (jpsp.getKind().equals(kind.getName())) { if (signature.matches(jpsp)) { return FuzzyBoolean.YES; } } return FuzzyBoolean.NO; } private void warnOnConfusingSig(Shadow shadow) { // no warnings for declare error/warning if (munger instanceof Checker) return; World world = shadow.getIWorld(); // warning never needed if the declaring type is any TypeX exactDeclaringType = signature.getDeclaringType().getExactType(); ResolvedTypeX shadowDeclaringType = shadow.getSignature().getDeclaringType().resolve(world); if (signature.getDeclaringType().isStar() || exactDeclaringType== ResolvedTypeX.MISSING) return; // warning not needed if match type couldn't ever be the declaring type if (!shadowDeclaringType.isAssignableFrom(exactDeclaringType)) { return; } // if the method in the declaring type is *not* visible to the // exact declaring type then warning not needed. int shadowModifiers = shadow.getSignature().getModifiers(world); if (!ResolvedTypeX .isVisible( shadowModifiers, shadowDeclaringType, exactDeclaringType.resolve(world))) { return; } SignaturePattern nonConfusingPattern = new SignaturePattern( signature.getKind(), signature.getModifiers(), signature.getReturnType(), TypePattern.ANY, signature.getName(), signature.getParameterTypes(), signature.getThrowsPattern()); if (nonConfusingPattern .matches(shadow.getSignature(), shadow.getIWorld())) { shadow.getIWorld().getLint().unmatchedSuperTypeInCall.signal( new String[] { shadow.getSignature().getDeclaringType().toString(), signature.getDeclaringType().toString() }, this.getSourceLocation(), new ISourceLocation[] {shadow.getSourceLocation()} ); } } public boolean equals(Object other) { if (!(other instanceof KindedPointcut)) return false; KindedPointcut o = (KindedPointcut)other; return o.kind == this.kind && o.signature.equals(this.signature); } public int hashCode() { int result = 17; result = 37*result + kind.hashCode(); result = 37*result + signature.hashCode(); return result; } public String toString() { StringBuffer buf = new StringBuffer(); buf.append(kind.getSimpleName()); buf.append("("); buf.append(signature.toString()); buf.append(")"); return buf.toString(); } public void postRead(ResolvedTypeX enclosingType) { signature.postRead(enclosingType); } public void write(DataOutputStream s) throws IOException { s.writeByte(Pointcut.KINDED); kind.write(s); signature.write(s); writeLocation(s); } public static Pointcut read(DataInputStream s, ISourceContext context) throws IOException { Shadow.Kind kind = Shadow.Kind.read(s); SignaturePattern sig = SignaturePattern.read(s, context); KindedPointcut ret = new KindedPointcut(kind, sig); ret.readLocation(context, s); return ret; } // XXX note: there is no namebinding in any kinded pointcut. // still might want to do something for better error messages // We want to do something here to make sure we don't sidestep the parameter // list in capturing type identifiers. public void resolveBindings(IScope scope, Bindings bindings) { if (kind == Shadow.Initialization) { // scope.getMessageHandler().handleMessage( // MessageUtil.error( // "initialization unimplemented in 1.1beta1", // this.getSourceLocation())); } signature = signature.resolveBindings(scope, bindings); if (kind == Shadow.ConstructorExecution) { // Bug fix 60936 if (signature.getDeclaringType() != null) { World world = scope.getWorld(); TypeX exactType = signature.getDeclaringType().getExactType(); if (signature.getKind() == Member.CONSTRUCTOR && !exactType.equals(ResolvedTypeX.MISSING) && exactType.isInterface(world) && !signature.getDeclaringType().isIncludeSubtypes()) { world.getLint().noInterfaceCtorJoinpoint.signal(exactType.toString(), getSourceLocation()); } } } } public void resolveBindingsFromRTTI() { signature = signature.resolveBindingsFromRTTI(); } public Test findResidue(Shadow shadow, ExposedState state) { return match(shadow).alwaysTrue() ? Literal.TRUE : Literal.FALSE; } public Pointcut concretize1(ResolvedTypeX inAspect, IntMap bindings) { Pointcut ret = new KindedPointcut(kind, signature, bindings.getEnclosingAdvice()); ret.copyLocationFrom(this); return ret; } public Shadow.Kind getKind() { return kind; } }
42,573
Bug 42573 .lst file entries not resolved relative to list file: {boot}classpath, extdirs,
My -classpath entry in a config/.lst file was resolved relative to the working directory rather than to the config/.lst file. BuildArgParser.java looks like this would also be true for bootclasspath and extdirs, but not for injars, aspectpath, or sourceroots.
resolved fixed
648c0f4
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2004-08-05T17:31:56Z
2003-09-05T00:00:00Z
org.aspectj.ajdt.core/src/org/aspectj/ajdt/ajc/BuildArgParser.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Common Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * PARC initial implementation * ******************************************************************/ package org.aspectj.ajdt.ajc; import java.io.*; import java.util.*; import org.aspectj.ajdt.internal.core.builder.*; import org.aspectj.bridge.*; import org.aspectj.util.*; import org.eclipse.jdt.core.compiler.InvalidInputException; import org.eclipse.jdt.internal.compiler.batch.Main; import org.eclipse.jdt.internal.compiler.impl.CompilerOptions; public class BuildArgParser extends Main { private static final String BUNDLE_NAME = "org.aspectj.ajdt.ajc.messages"; private static boolean LOADED_BUNDLE = false; static { bundle = ResourceBundle.getBundle(BUNDLE_NAME); if (!LOADED_BUNDLE) { LOADED_BUNDLE = true; } } /** to initialize super's PrintWriter but refer to underlying StringWriter */ private static class StringPrintWriter extends PrintWriter { public final StringWriter stringWriter; StringPrintWriter(StringWriter sw) { super(sw); this.stringWriter = sw; } } /** @return multi-line String usage for the compiler */ public static String getUsage() { return Main.bind("misc.usage"); } public static String getXOptionUsage() { return Main.bind("xoption.usage"); } /** * StringWriter sink for some errors. * This only captures errors not handled by any IMessageHandler parameter * and only when no PrintWriter is set in the constructor. * XXX This relies on (Sun's) implementation of StringWriter, * which returns the actual (not copy) internal StringBuffer. */ private final StringBuffer errorSink; private IMessageHandler handler; /** * Overrides super's bundle. */ public BuildArgParser(PrintWriter writer, IMessageHandler handler) { super(writer, writer, false); if (writer instanceof StringPrintWriter) { errorSink = ((StringPrintWriter) writer).stringWriter.getBuffer(); } else { errorSink = null; } this.handler = handler; } /** Set up to capture messages using getOtherMessages(boolean) */ public BuildArgParser(IMessageHandler handler) { this(new StringPrintWriter(new StringWriter()),handler); } /** * Generate build configuration for the input args, * passing to handler any error messages. * @param args the String[] arguments for the build configuration * @return AjBuildConfig per args, * which will be invalid unless there are no handler errors. */ public AjBuildConfig genBuildConfig(String[] args) { AjBuildConfig config = new AjBuildConfig(); populateBuildConfig(config, args, true, null); return config; } /** * Generate build configuration for the input args, * passing to handler any error messages. * @param args the String[] arguments for the build configuration * @param setClasspath determines if the classpath should be parsed and set on the build configuration * @param configFile can be null * @return AjBuildConfig per args, * which will be invalid unless there are no handler errors. */ public AjBuildConfig populateBuildConfig(AjBuildConfig buildConfig, String[] args, boolean setClasspath, File configFile) { buildConfig.setConfigFile(configFile); try { // sets filenames to be non-null in order to make sure that file paramters are ignored super.filenames = new String[] { "" }; AjcConfigParser parser = new AjcConfigParser(buildConfig, handler); parser.parseCommandLine(args); boolean swi = buildConfig.getShowWeavingInformation(); // Now jump through firey hoops to turn them on/off if (handler instanceof CountingMessageHandler) { IMessageHandler delegate = ((CountingMessageHandler)handler).delegate; // Without dontIgnore() on the IMessageHandler interface, we have to do this *blurgh* if (delegate instanceof MessageHandler) { if (swi) ((MessageHandler)delegate).dontIgnore(IMessage.WEAVEINFO); else ((MessageHandler)delegate).ignore(IMessage.WEAVEINFO); } } boolean incrementalMode = buildConfig.isIncrementalMode() || buildConfig.isIncrementalFileMode(); List fileList = new ArrayList(); List files = parser.getFiles(); if (!LangUtil.isEmpty(files)) { if (incrementalMode) { MessageUtil.error(handler, "incremental mode only handles source files using -sourceroots"); } else { fileList.addAll(files); } } List javaArgList = new ArrayList(); // disable all special eclipse warnings by default - why??? //??? might want to instead override getDefaultOptions() javaArgList.add("-warn:none"); // these next four lines are some nonsense to fool the eclipse batch compiler // without these it will go searching for reasonable values from properties //TODO fix org.eclipse.jdt.internal.compiler.batch.Main so this hack isn't needed javaArgList.add("-classpath"); javaArgList.add(System.getProperty("user.dir")); javaArgList.add("-bootclasspath"); javaArgList.add(System.getProperty("user.dir")); javaArgList.addAll(parser.getUnparsedArgs()); super.configure((String[])javaArgList.toArray(new String[javaArgList.size()])); if (!proceed) { buildConfig.doNotProceed(); return buildConfig; } if (buildConfig.getSourceRoots() != null) { for (Iterator i = buildConfig.getSourceRoots().iterator(); i.hasNext(); ) { fileList.addAll(collectSourceRootFiles((File)i.next())); } } buildConfig.setFiles(fileList); if (destinationPath != null) { // XXX ?? unparsed but set? buildConfig.setOutputDir(new File(destinationPath)); } if (setClasspath) { buildConfig.setClasspath(getClasspath(parser)); } if (incrementalMode && (0 == buildConfig.getSourceRoots().size())) { MessageUtil.error(handler, "specify a source root when in incremental mode"); } setDebugOptions(); buildConfig.getOptions().set(options); } catch (InvalidInputException iie) { ISourceLocation location = null; if (buildConfig.getConfigFile() != null) { location = new SourceLocation(buildConfig.getConfigFile(), 0); } IMessage m = new Message(iie.getMessage(), IMessage.ERROR, null, location); handler.handleMessage(m); } return buildConfig; } // from super... public void printVersion() { System.err.println("AspectJ Compiler " + Version.text + " built on " + Version.time_text); //$NON-NLS-1$ System.err.flush(); } public void printUsage() { System.out.println(bind("misc.usage")); //$NON-NLS-1$ System.out.flush(); } /** * Get messages not dumped to handler or any PrintWriter. * @param flush if true, empty errors * @return null if none, String otherwise * @see BuildArgParser() */ public String getOtherMessages(boolean flush) { if (null == errorSink) { return null; } String result = errorSink.toString().trim(); if (0 == result.length()) { result = null; } if (flush) { errorSink.setLength(0); } return result; } private void setDebugOptions() { options.put( CompilerOptions.OPTION_LocalVariableAttribute, CompilerOptions.GENERATE); options.put( CompilerOptions.OPTION_LineNumberAttribute, CompilerOptions.GENERATE); options.put( CompilerOptions.OPTION_SourceFileAttribute, CompilerOptions.GENERATE); } private Collection collectSourceRootFiles(File dir) { return Arrays.asList(FileUtil.listFiles(dir, FileUtil.aspectjSourceFileFilter)); } /** * If the classpath is not set, we use the environment's java.class.path, but remove * the aspectjtools.jar entry from that list in order to prevent wierd bootstrap issues * (refer to bug#39959). */ public List getClasspath(AjcConfigParser parser) { List ret = new ArrayList(); if (parser.bootclasspath == null) { addClasspath(System.getProperty("sun.boot.class.path", ""), ret); } else { addClasspath(parser.bootclasspath, ret); } String extdirs = parser.extdirs; if (extdirs == null) { extdirs = System.getProperty("java.ext.dirs", ""); } addExtDirs(extdirs, ret); if (parser.classpath == null) { addClasspath(System.getProperty("java.class.path", ""), ret); List fixedList = new ArrayList(); for (Iterator it = ret.iterator(); it.hasNext(); ) { String entry = (String)it.next(); if (!entry.endsWith("aspectjtools.jar")) { fixedList.add(entry); } } ret = fixedList; } else { addClasspath(parser.classpath, ret); } //??? eclipse seems to put outdir on the classpath //??? we're brave and believe we don't need it return ret; } private void addExtDirs(String extdirs, List classpathCollector) { StringTokenizer tokenizer = new StringTokenizer(extdirs, File.pathSeparator); while (tokenizer.hasMoreTokens()) { // classpathCollector.add(tokenizer.nextToken()); File dirFile = new File((String)tokenizer.nextToken()); if (dirFile.canRead() && dirFile.isDirectory()) { File[] files = dirFile.listFiles(FileUtil.ZIP_FILTER); for (int i = 0; i < files.length; i++) { classpathCollector.add(files[i].getAbsolutePath()); } } else { // XXX alert on invalid -extdirs entries } } } private void addClasspath(String classpath, List classpathCollector) { StringTokenizer tokenizer = new StringTokenizer(classpath, File.pathSeparator); while (tokenizer.hasMoreTokens()) { classpathCollector.add(tokenizer.nextToken()); } } private class AjcConfigParser extends ConfigParser { private String bootclasspath = null; private String classpath = null; private String extdirs = null; private List unparsedArgs = new ArrayList(); private AjBuildConfig buildConfig; private IMessageHandler handler; public AjcConfigParser(AjBuildConfig buildConfig, IMessageHandler handler) { this.buildConfig = buildConfig; this.handler = handler; } public List getUnparsedArgs() { return unparsedArgs; } /** * Extract AspectJ-specific options (except for argfiles). * Caller should warn when sourceroots is empty but in * incremental mode. * Signals warnings or errors through handler set in constructor. */ public void parseOption(String arg, LinkedList args) { // XXX use ListIterator.remove() int nextArgIndex = args.indexOf(arg)+1; // XXX assumes unique // trim arg? if (LangUtil.isEmpty(arg)) { showWarning("empty arg found"); } else if (arg.equals("-inpath")) {; if (args.size() > nextArgIndex) { // buildConfig.getAjOptions().put(AjCompilerOptions.OPTION_Inpath, CompilerOptions.PRESERVE); List inPath = buildConfig.getInpath(); StringTokenizer st = new StringTokenizer( ((ConfigParser.Arg)args.get(nextArgIndex)).getValue(), File.pathSeparator); while (st.hasMoreTokens()) { String filename = st.nextToken(); File file = makeFile(filename); if (file.exists() && FileUtil.hasZipSuffix(filename)) { inPath.add(file); } else { if (file.isDirectory()) { inPath.add(file); } else showError("bad inpath component: " + filename); } } buildConfig.setInPath(inPath); args.remove(args.get(nextArgIndex)); } } else if (arg.equals("-injars")) {; if (args.size() > nextArgIndex) { // buildConfig.getAjOptions().put(AjCompilerOptions.OPTION_InJARs, CompilerOptions.PRESERVE); StringTokenizer st = new StringTokenizer( ((ConfigParser.Arg)args.get(nextArgIndex)).getValue(), File.pathSeparator); while (st.hasMoreTokens()) { String filename = st.nextToken(); File jarFile = makeFile(filename); if (jarFile.exists() && FileUtil.hasZipSuffix(filename)) { buildConfig.getInJars().add(jarFile); } else { File dirFile = makeFile(filename); if (dirFile.isDirectory()) { buildConfig.getInJars().add(dirFile); } else showError("bad injar: " + filename); } } args.remove(args.get(nextArgIndex)); } } else if (arg.equals("-aspectpath")) {; if (args.size() > nextArgIndex) { StringTokenizer st = new StringTokenizer( ((ConfigParser.Arg)args.get(nextArgIndex)).getValue(), File.pathSeparator); while (st.hasMoreTokens()) { String filename = st.nextToken(); File jarFile = makeFile(filename); if (jarFile.exists() && FileUtil.hasZipSuffix(filename)) { buildConfig.getAspectpath().add(jarFile); } else { showError("bad aspectpath: " + filename); } } args.remove(args.get(nextArgIndex)); } } else if (arg.equals("-sourceroots")) { if (args.size() > nextArgIndex) { List sourceRoots = new ArrayList(); StringTokenizer st = new StringTokenizer( ((ConfigParser.Arg)args.get(nextArgIndex)).getValue(), File.pathSeparator); while (st.hasMoreTokens()) { File f = makeFile(st.nextToken()); if (f.isDirectory() && f.canRead()) { sourceRoots.add(f); } else { showError("bad sourceroot: " + f); } } if (0 < sourceRoots.size()) { buildConfig.setSourceRoots(sourceRoots); } args.remove(args.get(nextArgIndex)); } else { showError("-sourceroots requires list of directories"); } } else if (arg.equals("-outjar")) { if (args.size() > nextArgIndex) { // buildConfig.getAjOptions().put(AjCompilerOptions.OPTION_OutJAR, CompilerOptions.GENERATE); File jarFile = makeFile(((ConfigParser.Arg)args.get(nextArgIndex)).getValue()); if (FileUtil.hasZipSuffix(jarFile)) { try { if (!jarFile.exists()) { jarFile.createNewFile(); } buildConfig.setOutputJar(jarFile); } catch (IOException ioe) { showError("unable to create outjar file: " + jarFile); } } else { showError("invalid -outjar file: " + jarFile); } args.remove(args.get(nextArgIndex)); } else { showError("-outjar requires jar path argument"); } } else if (arg.equals("-incremental")) { buildConfig.setIncrementalMode(true); } else if (arg.equals("-XincrementalFile")) { if (args.size() > nextArgIndex) { File file = makeFile(((ConfigParser.Arg)args.get(nextArgIndex)).getValue()); buildConfig.setIncrementalFile(file); if (!file.canRead()) { showError("bad -XincrementalFile : " + file); // if not created before recompile test, stop after first compile } args.remove(args.get(nextArgIndex)); } else { showError("-XincrementalFile requires file argument"); } } else if (arg.equals("-emacssym")) { buildConfig.setEmacsSymMode(true); buildConfig.setGenerateModelMode(true); } else if (arg.equals("-XjavadocsInModel")) { buildConfig.setGenerateModelMode(true); buildConfig.setGenerateJavadocsInModelMode(true); } else if (arg.equals("-noweave") || arg.equals( "-XnoWeave")) { buildConfig.setNoWeave(true); } else if (arg.equals("-XserializableAspects")) { buildConfig.setXserializableAspects(true); } else if (arg.equals("-XlazyTjp")) { buildConfig.setXlazyTjp(true); } else if (arg.startsWith("-Xreweavable")) { buildConfig.setXreweavable(true); if (arg.endsWith(":compress")) { buildConfig.setXreweavableCompressClasses(true); } } else if (arg.equals("-XnoInline")) { buildConfig.setXnoInline(true); } else if (arg.startsWith("-showWeaveInfo")) { buildConfig.setShowWeavingInformation(true); } else if (arg.equals("-Xlintfile")) { if (args.size() > nextArgIndex) { File lintSpecFile = makeFile(((ConfigParser.Arg)args.get(nextArgIndex)).getValue()); // XXX relax restriction on props file suffix? if (lintSpecFile.canRead() && lintSpecFile.getName().endsWith(".properties")) { buildConfig.setLintSpecFile(lintSpecFile); } else { showError("bad -Xlintfile file: " + lintSpecFile); buildConfig.setLintSpecFile(null); } args.remove(args.get(nextArgIndex)); } else { showError("-Xlintfile requires .properties file argument"); } } else if (arg.equals("-Xlint")) { // buildConfig.getAjOptions().put( // AjCompilerOptions.OPTION_Xlint, // CompilerOptions.GENERATE); buildConfig.setLintMode(AjBuildConfig.AJLINT_DEFAULT); } else if (arg.startsWith("-Xlint:")) { if (7 < arg.length()) { buildConfig.setLintMode(arg.substring(7)); } else { showError("invalid lint option " + arg); } } else if (arg.equals("-bootclasspath")) { if (args.size() > nextArgIndex) { bootclasspath = ((ConfigParser.Arg)args.get(nextArgIndex)).getValue(); args.remove(args.get(nextArgIndex)); } else { showError("-bootclasspath requires classpath entries"); } } else if (arg.equals("-classpath")) { if (args.size() > nextArgIndex) { classpath = ((ConfigParser.Arg)args.get(nextArgIndex)).getValue(); args.remove(args.get(nextArgIndex)); } else { showError("-classpath requires classpath entries"); } } else if (arg.equals("-extdirs")) { if (args.size() > nextArgIndex) { extdirs = ((ConfigParser.Arg)args.get(nextArgIndex)).getValue(); args.remove(args.get(nextArgIndex)); } else { showError("-extdirs requires list of external directories"); } // error on directory unless -d, -{boot}classpath, or -extdirs } else if (arg.equals("-d")) { dirLookahead(arg, args, nextArgIndex); // } else if (arg.equals("-classpath")) { // dirLookahead(arg, args, nextArgIndex); // } else if (arg.equals("-bootclasspath")) { // dirLookahead(arg, args, nextArgIndex); // } else if (arg.equals("-extdirs")) { // dirLookahead(arg, args, nextArgIndex); } else if (new File(arg).isDirectory()) { showError("dir arg not permitted: " + arg); } else { // argfile, @file parsed by superclass // no eclipse options parsed: // -d args, -help (handled), // -classpath, -target, -1.3, -1.4, -source [1.3|1.4] // -nowarn, -warn:[...], -deprecation, -noImportError, // -proceedOnError, -g:[...], -preserveAllLocals, // -referenceInfo, -encoding, -verbose, -log, -time // -noExit, -repeat unparsedArgs.add(arg); } } protected void dirLookahead(String arg, LinkedList argList, int nextArgIndex) { unparsedArgs.add(arg); ConfigParser.Arg next = (ConfigParser.Arg) argList.get(nextArgIndex); String value = next.getValue(); if (!LangUtil.isEmpty(value)) { if (new File(value).isDirectory()) { unparsedArgs.add(value); argList.remove(next); return; } } } public void showError(String message) { ISourceLocation location = null; if (buildConfig.getConfigFile() != null) { location = new SourceLocation(buildConfig.getConfigFile(), 0); } IMessage errorMessage = new Message(CONFIG_MSG + message, IMessage.ERROR, null, location); handler.handleMessage(errorMessage); // MessageUtil.error(handler, CONFIG_MSG + message); } protected void showWarning(String message) { ISourceLocation location = null; if (buildConfig.getConfigFile() != null) { location = new SourceLocation(buildConfig.getConfigFile(), 0); } IMessage errorMessage = new Message(CONFIG_MSG + message, IMessage.WARNING, null, location); handler.handleMessage(errorMessage); // MessageUtil.warn(handler, message); } protected File makeFile(File dir, String name) { name = name.replace('/', File.separatorChar); File ret = new File(name); if (dir == null || ret.isAbsolute()) return ret; try { dir = dir.getCanonicalFile(); } catch (IOException ioe) { } return new File(dir, name); } } }
42,573
Bug 42573 .lst file entries not resolved relative to list file: {boot}classpath, extdirs,
My -classpath entry in a config/.lst file was resolved relative to the working directory rather than to the config/.lst file. BuildArgParser.java looks like this would also be true for bootclasspath and extdirs, but not for injars, aspectpath, or sourceroots.
resolved fixed
648c0f4
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2004-08-05T17:31:56Z
2003-09-05T00:00:00Z
org.aspectj.ajdt.core/testsrc/org/aspectj/ajdt/ajc/BuildArgParserTestCase.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Common Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * PARC initial implementation * ******************************************************************/ package org.aspectj.ajdt.ajc; import java.io.*; import java.util.*; import junit.framework.TestCase; import org.aspectj.ajdt.internal.core.builder.*; import org.aspectj.bridge.CountingMessageHandler; import org.aspectj.bridge.IMessage; import org.aspectj.bridge.IMessageHandler; import org.aspectj.bridge.MessageWriter; import org.aspectj.testing.util.TestUtil; import org.eclipse.jdt.core.compiler.InvalidInputException; import org.eclipse.jdt.internal.compiler.impl.CompilerOptions; /** * Some black-box test is happening here. */ public class BuildArgParserTestCase extends TestCase { private static final String TEST_DIR = AjdtAjcTests.TESTDATA_PATH + File.separator + "ajc" + File.separator; private MessageWriter messageWriter = new MessageWriter(new PrintWriter(System.out), false); public BuildArgParserTestCase(String name) { super(name); } private AjBuildConfig genBuildConfig(String[] args, IMessageHandler handler) { return new BuildArgParser(handler).genBuildConfig(args); } public void testDefaultClasspathAndTargetCombo() throws InvalidInputException { String ENTRY = "1.jar" + File.pathSeparator + "2.jar"; final String classpath = System.getProperty("java.class.path"); try { System.setProperty("java.class.path", ENTRY); // see finally below BuildArgParser parser = new BuildArgParser(messageWriter); AjBuildConfig config = parser.genBuildConfig(new String[] { }); /*String err = */parser.getOtherMessages(true); //!!!assertTrue(err, null == err); assertTrue( config.getClasspath().toString(), config.getClasspath().contains("1.jar")); assertTrue( config.getClasspath().toString(), config.getClasspath().contains("2.jar")); config = genBuildConfig(new String[] { "-1.3" }, messageWriter); // these errors are deffered to the compiler now //err = parser.getOtherMessages(true); //!!!assertTrue(err, null == err); assertTrue( config.getClasspath().toString(), config.getClasspath().contains("1.jar")); assertTrue( config.getClasspath().toString(), config.getClasspath().contains("2.jar")); parser = new BuildArgParser(messageWriter); config = parser.genBuildConfig(new String[] { "-1.3" }); /*err = */parser.getOtherMessages(true); //!!!assertTrue(err, null == err); assertTrue( config.getClasspath().toString(), config.getClasspath().contains("1.jar")); assertTrue( config.getClasspath().toString(), config.getClasspath().contains("2.jar")); config = genBuildConfig(new String[] { "-classpath", ENTRY, "-1.4" }, messageWriter); // these errors are deffered to the compiler now //err = parser.getOtherMessages(true); //assertTrue("expected errors for missing jars", null != err); assertTrue( config.getClasspath().toString(), config.getClasspath().contains("1.jar")); assertTrue( config.getClasspath().toString(), config.getClasspath().contains("2.jar")); } finally { // do finally to avoid messing up classpath for other tests System.setProperty("java.class.path", classpath); String setPath = System.getProperty("java.class.path"); String m = "other tests will fail - classpath not reset"; assertEquals(m, classpath, setPath); } } public void testAjOptions() throws InvalidInputException { AjBuildConfig config = genBuildConfig(new String[] { "-Xlint" }, messageWriter); assertTrue( "default options", config.getLintMode().equals(AjBuildConfig.AJLINT_DEFAULT)); } public void testAspectpath() throws InvalidInputException { final String SOURCE_JAR = AjdtAjcTests.TESTDATA_PATH + "/testclasses.jar"; final String SOURCE_JARS = AjdtAjcTests.TESTDATA_PATH + "/testclasses.jar" + File.pathSeparator + "../weaver/testdata/tracing.jar" + File.pathSeparator + "../weaver/testdata/dummyAspect.jar"; AjBuildConfig config = genBuildConfig(new String[] { "-aspectpath", SOURCE_JAR }, messageWriter); assertTrue(((File)config.getAspectpath().get(0)).getName(), ((File)config.getAspectpath().get(0)).getName().equals("testclasses.jar")); config = genBuildConfig(new String[] { "-aspectpath", SOURCE_JARS }, messageWriter); assertTrue("size", + config.getAspectpath().size() == 3); } public void testInJars() throws InvalidInputException { final String SOURCE_JAR = AjdtAjcTests.TESTDATA_PATH + "/testclasses.jar"; final String SOURCE_JARS = AjdtAjcTests.TESTDATA_PATH + "/testclasses.jar" + File.pathSeparator + "../weaver/testdata/tracing.jar" + File.pathSeparator + "../weaver/testdata/dummyAspect.jar"; AjBuildConfig config = genBuildConfig(new String[] { "-injars", SOURCE_JAR }, messageWriter); //XXX don't let this remain in both places in beta1 // assertTrue( // "" + config.getAjOptions().get(AjCompilerOptions.OPTION_InJARs), // config.getAjOptions().get(AjCompilerOptions.OPTION_InJARs).equals(CompilerOptions.PRESERVE)); assertTrue(((File)config.getInJars().get(0)).getName(), ((File)config.getInJars().get(0)).getName().equals("testclasses.jar")); config = genBuildConfig(new String[] { "-injars", SOURCE_JARS }, messageWriter); assertTrue("size", + config.getInJars().size() == 3); } public void testBadInJars() throws InvalidInputException { final String SOURCE_JARS = AjdtAjcTests.TESTDATA_PATH + "/testclasses.jar" + File.pathSeparator + "b.far" + File.pathSeparator + "c.jar"; AjBuildConfig config = genBuildConfig(new String[] { "-injars", SOURCE_JARS }, messageWriter); assertTrue("size: " + config.getInJars().size(), config.getInJars().size() == 1); } public void testBadPathToSourceFiles() { CountingMessageHandler countingHandler = new CountingMessageHandler(messageWriter); /*AjBuildConfig config = */genBuildConfig(new String[]{ "inventedDir/doesntexist/*.java"},countingHandler); assertTrue("Expected an error for the invalid path.",countingHandler.numMessages(IMessage.ERROR,false)==1); } public void testMultipleSourceRoots() throws InvalidInputException, IOException { final String SRCROOT_1 = AjdtAjcTests.TESTDATA_PATH + "/src1/p1"; final String SRCROOT_2 = AjdtAjcTests.TESTDATA_PATH + "/ajc"; AjBuildConfig config = genBuildConfig(new String[] { "-sourceroots", SRCROOT_1 + File.pathSeparator + SRCROOT_2 }, messageWriter); assertEquals(getCanonicalPath(new File(SRCROOT_1)), ((File)config.getSourceRoots().get(0)).getAbsolutePath()); Collection expectedFiles = Arrays.asList(new File[] { new File(SRCROOT_1+File.separator+"A.java").getCanonicalFile(), new File(SRCROOT_1+File.separator+"Foo.java").getCanonicalFile(), new File(SRCROOT_2+File.separator+"A.java").getCanonicalFile(), new File(SRCROOT_2+File.separator+"B.java").getCanonicalFile(), new File(SRCROOT_2+File.separator+"X.aj").getCanonicalFile(), new File(SRCROOT_2+File.separator+"Y.aj").getCanonicalFile(), new File(SRCROOT_2+File.separator+"pkg"+File.separator+"Hello.java").getCanonicalFile(), }); //System.out.println(config.getFiles()); TestUtil.assertSetEquals(expectedFiles, config.getFiles()); } /** * @param file * @return String */ private String getCanonicalPath(File file) { String ret = ""; try { ret = file.getCanonicalPath(); } catch (IOException ioEx) { fail("Unable to canonicalize " + file + " : " + ioEx); } return ret; } public void testSourceRootDir() throws InvalidInputException, IOException { final String SRCROOT = AjdtAjcTests.TESTDATA_PATH + "/ajc"; AjBuildConfig config = genBuildConfig(new String[] { "-sourceroots", SRCROOT }, messageWriter); assertEquals(getCanonicalPath(new File(SRCROOT)), ((File)config.getSourceRoots().get(0)).getAbsolutePath()); Collection expectedFiles = Arrays.asList(new File[] { new File(SRCROOT+File.separator+"A.java").getCanonicalFile(), new File(SRCROOT+File.separator+"B.java").getCanonicalFile(), new File(SRCROOT+File.separator+"X.aj").getCanonicalFile(), new File(SRCROOT+File.separator+"Y.aj").getCanonicalFile(), new File(SRCROOT+File.separator+"pkg"+File.separator+"Hello.java").getCanonicalFile(), }); //System.out.println(config.getFiles()); TestUtil.assertSetEquals(expectedFiles, config.getFiles()); } public void testBadSourceRootDir() throws InvalidInputException { AjBuildConfig config = genBuildConfig(new String[] { "-sourceroots", AjdtAjcTests.TESTDATA_PATH + "/mumbleDoesNotExist" + File.pathSeparator + AjdtAjcTests.TESTDATA_PATH + "/ajc" }, messageWriter); assertTrue(config.getSourceRoots().toString(), config.getSourceRoots().size() == 1); config = genBuildConfig(new String[] { "-sourceroots" }, messageWriter); assertTrue("" + config.getSourceRoots(), config.getSourceRoots().size() == 0); } //??? we've decided not to make this an error public void testSourceRootDirWithFiles() throws InvalidInputException, IOException { final String SRCROOT = AjdtAjcTests.TESTDATA_PATH + "/ajc/pkg"; AjBuildConfig config = genBuildConfig(new String[] { "-sourceroots", SRCROOT, AjdtAjcTests.TESTDATA_PATH + "/src1/A.java"}, messageWriter); assertEquals(getCanonicalPath(new File(SRCROOT)), ((File)config.getSourceRoots().get(0)).getAbsolutePath()); Collection expectedFiles = Arrays.asList(new File[] { new File(SRCROOT+File.separator+"Hello.java").getCanonicalFile(), new File(AjdtAjcTests.TESTDATA_PATH +File.separator+"src1"+File.separator+"A.java").getCanonicalFile(), }); TestUtil.assertSetEquals(expectedFiles, config.getFiles()); } public void testExtDirs() throws InvalidInputException { final String DIR = AjdtAjcTests.TESTDATA_PATH; AjBuildConfig config = genBuildConfig(new String[] { "-extdirs", DIR }, messageWriter); assertTrue(config.getClasspath().toString(), config.getClasspath().contains( new File(DIR + File.separator + "testclasses.jar").getAbsolutePath() )); } public void testBootclasspath() throws InvalidInputException { final String PATH = "mumble/rt.jar"; AjBuildConfig config = genBuildConfig(new String[] { "-bootclasspath", PATH }, messageWriter); assertTrue(config.getClasspath().toString(), config.getClasspath().get(0).equals(PATH)); config = genBuildConfig(new String[] { }, messageWriter); assertTrue(config.getClasspath().toString(), !config.getClasspath().get(0).equals(PATH)); } public void testOutputJar() throws InvalidInputException { final String OUT_JAR = AjdtAjcTests.TESTDATA_PATH + "/testclasses.jar"; AjBuildConfig config = genBuildConfig(new String[] { "-outjar", OUT_JAR }, messageWriter); //XXX don't let this remain in both places in beta1 // assertTrue( // "will generate: " + config.getAjOptions().get(AjCompilerOptions.OPTION_OutJAR), // config.getAjOptions().get(AjCompilerOptions.OPTION_OutJAR).equals(CompilerOptions.GENERATE)); assertEquals( getCanonicalPath(new File(OUT_JAR)),config.getOutputJar().getAbsolutePath()); File nonExistingJar = new File(AjdtAjcTests.TESTDATA_PATH + "/mumbleDoesNotExist.jar"); config = genBuildConfig(new String[] { "-outjar", nonExistingJar.getAbsolutePath() }, messageWriter); assertEquals( getCanonicalPath(nonExistingJar), config.getOutputJar().getAbsolutePath()); nonExistingJar.delete(); } //XXX shouldn't need -1.4 to get this to pass public void testCombinedOptions() throws InvalidInputException { AjBuildConfig config = genBuildConfig(new String[] { "-Xlint:error", "-target", "1.4"}, messageWriter); assertTrue( "target set", config.getOptions().targetJDK == CompilerOptions.JDK1_4); assertTrue( "Xlint option set", config.getLintMode().equals(AjBuildConfig.AJLINT_ERROR)); } public void testOutputDirectorySetting() throws InvalidInputException { AjBuildConfig config = genBuildConfig(new String[] { "-d", TEST_DIR }, messageWriter); assertTrue( new File(config.getOutputDir().getPath()).getAbsolutePath() + " ?= " + new File(TEST_DIR).getAbsolutePath(), config.getOutputDir().getAbsolutePath().equals((new File(TEST_DIR)).getAbsolutePath())); } public void testClasspathSetting() throws InvalidInputException { String ENTRY = "1.jar" + File.pathSeparator + "2.jar"; AjBuildConfig config = genBuildConfig(new String[] { "-classpath", ENTRY }, messageWriter); assertTrue( config.getClasspath().toString(), config.getClasspath().contains("1.jar")); assertTrue( config.getClasspath().toString(), config.getClasspath().contains("2.jar")); } public void testArgInConfigFile() throws InvalidInputException { String FILE_PATH = "@" + TEST_DIR + "configWithArgs.lst"; String OUT_PATH = "bin"; AjBuildConfig config = genBuildConfig(new String[] { FILE_PATH }, messageWriter); assertNotNull(config); File outputDir = config.getOutputDir(); assertNotNull(outputDir); assertEquals(outputDir.getPath(), OUT_PATH); } public void testNonExistentConfigFile() throws IOException { String FILE_PATH = "@" + TEST_DIR + "../bug-40257/d1/test.lst"; AjBuildConfig config = genBuildConfig(new String[] { FILE_PATH }, messageWriter); String a = new File(TEST_DIR + "../bug-40257/d1/A.java").getCanonicalPath(); String b = new File(TEST_DIR + "../bug-40257/d1/d2/B.java").getCanonicalPath(); String c = new File(TEST_DIR + "../bug-40257/d3/C.java").getCanonicalPath(); List pathList = new ArrayList(); for (Iterator it = config.getFiles().iterator(); it.hasNext(); ) { pathList.add(((File)it.next()).getCanonicalPath()); } assertTrue(pathList.contains(a)); assertTrue(pathList.contains(b)); assertTrue(pathList.contains(c)); } public void testXlint() throws InvalidInputException { // AjdtCommand command = new AjdtCommand(); AjBuildConfig config = genBuildConfig(new String[] {"-Xlint"}, messageWriter); assertTrue("", config.getLintMode().equals(AjBuildConfig.AJLINT_DEFAULT)); config = genBuildConfig(new String[] {"-Xlint:warn"}, messageWriter); assertTrue("", config.getLintMode().equals(AjBuildConfig.AJLINT_WARN)); config = genBuildConfig(new String[] {"-Xlint:error"}, messageWriter); assertTrue("", config.getLintMode().equals(AjBuildConfig.AJLINT_ERROR)); config = genBuildConfig(new String[] {"-Xlint:ignore"}, messageWriter); assertTrue("", config.getLintMode().equals(AjBuildConfig.AJLINT_IGNORE)); } public void testXlintfile() throws InvalidInputException { String lintFile = AjdtAjcTests.TESTDATA_PATH + "/lintspec.properties"; // String badLintFile = "lint.props"; AjBuildConfig config = genBuildConfig(new String[] {"-Xlintfile", lintFile}, messageWriter); assertTrue(new File(lintFile).exists()); assertEquals(getCanonicalPath(new File(lintFile)),config.getLintSpecFile().getAbsolutePath()); } public void testOptions() throws InvalidInputException { // AjdtCommand command = new AjdtCommand(); String TARGET = "1.4"; AjBuildConfig config = genBuildConfig(new String[] {"-target", TARGET, "-source", TARGET}, messageWriter); assertTrue( "target set", config.getOptions().targetJDK == CompilerOptions.JDK1_4); assertTrue( "source set", config.getOptions().sourceLevel == CompilerOptions.JDK1_4); } public void testLstFileExpansion() throws IOException, FileNotFoundException, InvalidInputException { String FILE_PATH = TEST_DIR + "config.lst"; String SOURCE_PATH_1 = "A.java"; String SOURCE_PATH_2 = "B.java"; // File f = new File(FILE_PATH); AjBuildConfig config = genBuildConfig(new String[] { "@" + FILE_PATH }, messageWriter); List resultList = config.getFiles(); assertTrue("correct number of files", resultList.size() == 2); assertTrue(resultList.toString() + new File(TEST_DIR + SOURCE_PATH_1).getCanonicalFile(), resultList.contains(new File(TEST_DIR + SOURCE_PATH_1).getCanonicalFile())); assertTrue(resultList.toString() + SOURCE_PATH_2, resultList.contains(new File(TEST_DIR + SOURCE_PATH_2).getCanonicalFile())); } //??? do we need to remove this limitation // public void testArgInConfigFileAndRelativizingPathParam() throws InvalidInputException { // String FILE_PATH = "@" + TEST_DIR + "configWithArgs.lst"; // String OUT_PATH = TEST_DIR + "bin"; // AjBuildConfig config = genBuildConfig(new String[] { FILE_PATH }); // // assertTrue( // config.getOutputDir().getPath() + " ?= " + OUT_PATH, // config.getOutputDir().getAbsolutePath().equals((new File(OUT_PATH)).getAbsolutePath())); // } public void testAjFileInclusion() throws InvalidInputException { genBuildConfig(new String[] { TEST_DIR + "X.aj", TEST_DIR + "Y.aj"}, messageWriter); } protected void setUp() throws Exception { super.setUp(); } protected void tearDown() throws Exception { super.tearDown(); } }
42,573
Bug 42573 .lst file entries not resolved relative to list file: {boot}classpath, extdirs,
My -classpath entry in a config/.lst file was resolved relative to the working directory rather than to the config/.lst file. BuildArgParser.java looks like this would also be true for bootclasspath and extdirs, but not for injars, aspectpath, or sourceroots.
resolved fixed
648c0f4
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2004-08-05T17:31:56Z
2003-09-05T00:00:00Z
util/src/org/aspectj/util/ConfigParser.java
/* ******************************************************************* * Copyright (c) 1999-2001 Xerox Corporation, * 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Common Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * Xerox/PARC initial implementation * ******************************************************************/ package org.aspectj.util; import java.util.*; import java.io.*; public class ConfigParser { Location location; protected List files = new LinkedList(); private boolean fileParsed = false; protected static String CONFIG_MSG = "build config error: "; public List getFiles() { return files; } public void parseCommandLine(String[] argsArray) throws ParseException { location = new CommandLineLocation(); LinkedList args = new LinkedList(); for (int i = 0; i < argsArray.length; i++) { args.add(new Arg(argsArray[i], location)); } parseArgs(args); } public void parseConfigFile(File configFile) throws ParseException { if (fileParsed == true) { throw new ParseException(CONFIG_MSG + "The file has already been parsed.", null); } else { parseConfigFileHelper(configFile); } } /** * @throws ParseException if the config file has already been prased. */ private void parseConfigFileHelper(File configFile) { if (!configFile.exists()) { showError("file does not exist: " + configFile.getPath()); return; } LinkedList args = new LinkedList(); int lineNum = 0; try { BufferedReader stream = new BufferedReader(new FileReader(configFile)); String line = null; while ( (line = stream.readLine()) != null) { lineNum += 1; line = stripWhitespaceAndComments(line); if (line.length() == 0) continue; args.add(new Arg(line, new SourceLocation(configFile, lineNum))); } } catch (IOException e) { location = new SourceLocation(configFile, lineNum); showError("error reading config file: " + e.toString()); } parseArgs(args); fileParsed = true; } File getCurrentDir() { return location.getDirectory(); } String stripSingleLineComment(String s, String commentString) { int commentStart = s.indexOf(commentString); if (commentStart == -1) return s; else return s.substring(0, commentStart); } String stripWhitespaceAndComments(String s) { s = stripSingleLineComment(s, "//"); s = stripSingleLineComment(s, "#"); s = s.trim(); if (s.startsWith("\"") && s.endsWith("\"")) { s = s.substring(1, s.length()-1); } return s; } /** ??? We would like to call a showNonFatalError method here * to show all errors in config files before aborting the compilation */ protected void addFile(File sourceFile) { if (!sourceFile.isFile()) { showError("source file does not exist: " + sourceFile.getPath()); } files.add(sourceFile); } void addFileOrPattern(File sourceFile) { if (sourceFile.getName().equals("*.java")) { addFiles(sourceFile.getParentFile(), new FileFilter() { public boolean accept(File f) { return f != null && f.getName().endsWith(".java"); }}); } else if (sourceFile.getName().equals("*.aj")) { addFiles(sourceFile.getParentFile(), new FileFilter() { public boolean accept(File f) { return f != null && f.getName().endsWith(".aj"); }}); } else { addFile(sourceFile); } } void addFiles(File dir, FileFilter filter) { if (dir == null) dir = new File(System.getProperty("user.dir")); if (!dir.isDirectory()) { showError("can't find " + dir.getPath()); } else { File[] files = dir.listFiles(filter); if (files.length == 0) { showWarning("no matching files found in: " + dir); } for (int i = 0; i < files.length; i++) { addFile(files[i]); } } } protected void parseOption(String arg, LinkedList args) { showWarning("unrecognized option: " + arg); } protected void showWarning(String message) { if (location != null) { message += " at " + location.toString(); } System.err.println(CONFIG_MSG + message); } protected void showError(String message) { throw new ParseException(CONFIG_MSG + message, location); } void parseArgs(LinkedList args) { while (args.size() > 0) parseOneArg(args); } protected Arg removeArg(LinkedList args) { if (args.size() == 0) { showError("value missing"); return null; } else { return (Arg)args.removeFirst(); } } protected String removeStringArg(LinkedList args) { Arg arg = removeArg(args); if (arg == null) return null; return arg.getValue(); } boolean isSourceFileName(String s) { if (s.endsWith(".java")) return true; if (s.endsWith(".aj")) return true; if (s.endsWith(".ajava")) { showWarning(".ajava is deprecated, replace with .aj or .java: " + s); return true; } return false; } void parseOneArg(LinkedList args) { Arg arg = removeArg(args); String v = arg.getValue(); location = arg.getLocation(); if (v.startsWith("@")) { parseImportedConfigFile(v.substring(1)); } else if (v.equals("-argfile")) { parseConfigFileHelper(makeFile(removeArg(args).getValue())); } else if (isSourceFileName(v)) { addFileOrPattern(makeFile(v)); } else { parseOption(arg.getValue(), args); } } protected void parseImportedConfigFile(String relativeFilePath) { parseConfigFileHelper(makeFile(relativeFilePath)); } public File makeFile(String name) { return makeFile(getCurrentDir(), name); } private File makeFile(File dir, String name) { name = name.replace('/', File.separatorChar); File ret = new File(name); if (dir != null && !ret.isAbsolute()) { ret = new File(dir, name); } try { ret = ret.getCanonicalFile(); } catch (IOException ioEx) { // proceed without canonicalization // so nothing to do here } return ret; } protected static class Arg { private Location location; private String value; public Arg(String value, Location location) { this.value = value; this.location = location; } public void setValue(String value) { this.value = value; } public void setLocation(Location location) { this.location = location; } public String getValue() { return value; } public Location getLocation() { return location; } } static abstract class Location { public abstract File getFile(); public abstract File getDirectory(); public abstract int getLine(); public abstract String toString(); } static class SourceLocation extends Location { private int line; private File file; public SourceLocation(File file, int line) { this.line = line; this.file = file; } public File getFile() { return file; } public File getDirectory() { return file.getParentFile(); } public int getLine() { return line; } public String toString() { return file.getPath()+":"+line; } } static class CommandLineLocation extends Location { public File getFile() { return new File(System.getProperty("user.dir")); } public File getDirectory() { return new File(System.getProperty("user.dir")); } public int getLine() { return -1; } public String toString() { return "command-line"; } } public static class ParseException extends RuntimeException { private Location location; public ParseException(String message, Location location) { super(message); this.location = location; } public int getLine() { if (location == null) return -1; return location.getLine(); } public File getFile() { if (location == null) return null; return location.getFile(); } } }
44,191
Bug 44191 Need better error message for "can't find type"
I have experienced situations where IAJC outputs a message like this at the end of compilation. [iajc] can't find type org.xxx.SomeTest In my case this was one time highly confusing since I did not expect the class in question to be referred anywhere in the project (I have to date still not located the reference). For such cases, it would be extremely nice if the error message would display WHY it need the class (i.e. the name of the refering class(es) or aspect(es) possibly with a reasonable cutoff as there is seldom need to list all referals). So I would like a message like this: [iajc] can't find type org.xxx.SomeTest referred by org.yyy.SomeClass,org.yy.SomeOtherClass ...
resolved fixed
061395c
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2004-08-06T15:04:45Z
2003-10-04T23:26:40Z
org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/compiler/ast/AspectDeclaration.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Common Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * PARC initial implementation * ******************************************************************/ package org.aspectj.ajdt.internal.compiler.ast; import java.lang.reflect.Modifier; import java.util.*; import org.aspectj.ajdt.internal.compiler.lookup.*; import org.aspectj.weaver.*; import org.aspectj.weaver.patterns.*; import org.eclipse.jdt.internal.compiler.ClassFile; import org.eclipse.jdt.internal.compiler.CompilationResult; //import org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration; import org.eclipse.jdt.internal.compiler.ast.Clinit; import org.eclipse.jdt.internal.compiler.ast.MethodDeclaration; //import org.eclipse.jdt.internal.compiler.ast.ConstructorDeclaration; import org.eclipse.jdt.internal.compiler.ast.TypeDeclaration; import org.eclipse.jdt.internal.compiler.codegen.CodeStream; import org.eclipse.jdt.internal.compiler.codegen.Label; import org.eclipse.jdt.internal.compiler.lookup.*; //import org.eclipse.jdt.internal.compiler.parser.Parser; // (we used to...) making all aspects member types avoids a nasty hierarchy pain // switched from MemberTypeDeclaration to TypeDeclaration public class AspectDeclaration extends TypeDeclaration { //public IAjDeclaration[] ajDeclarations; private AjAttribute.Aspect aspectAttribute; public PerClause perClause; public ResolvedMember aspectOfMethod; public ResolvedMember hasAspectMethod; public Map accessForInline = new HashMap(); public Map superAccessForInline = new HashMap(); public boolean isPrivileged; public EclipseSourceType concreteName; public ResolvedTypeX.Name typeX; public EclipseFactory factory; //??? should use this consistently public int adviceCounter = 1; // Used as a part of the generated name for advice methods // for better error messages in 1.0 to 1.1 transition public TypePattern dominatesPattern; public AspectDeclaration(CompilationResult compilationResult) { super(compilationResult); //perClause = new PerSingleton(); } public boolean isAbstract() { return (modifiers & AccAbstract) != 0; } public void resolve() { if (binding == null) { ignoreFurtherInvestigation = true; return; } super.resolve(); } public void checkSpec(ClassScope scope) { if (ignoreFurtherInvestigation) return; if (dominatesPattern != null) { scope.problemReporter().signalError( dominatesPattern.getStart(), dominatesPattern.getEnd(), "dominates has changed for 1.1, use 'declare precedence: " + new String(this.name) + ", " + dominatesPattern.toString() + ";' " + "in the body of the aspect instead"); } if (!isAbstract()) { MethodBinding[] methods = binding.methods(); for (int i=0, len = methods.length; i < len; i++) { MethodBinding m = methods[i]; if (m.isConstructor()) { // this make all constructors in aspects invisible and thus uncallable //XXX this only works for aspects that come from source methods[i] = new MethodBinding(m, binding) { public boolean canBeSeenBy( InvocationSite invocationSite, Scope scope) { return false; } }; if (m.parameters != null && m.parameters.length != 0) { scope.problemReporter().signalError(m.sourceStart(), m.sourceEnd(), "only zero-argument constructors allowed in concrete aspect"); } } } } if (this.enclosingType != null) { if (!Modifier.isStatic(modifiers)) { scope.problemReporter().signalError(sourceStart, sourceEnd, "inner aspects must be static"); ignoreFurtherInvestigation = true; return; } } EclipseFactory world = EclipseFactory.fromScopeLookupEnvironment(scope); ResolvedTypeX myType = typeX; //if (myType == null) System.err.println("bad myType for: " + this); ResolvedTypeX superType = myType.getSuperclass(); // can't be Serializable/Cloneable unless -XserializableAspects if (!world.isXSerializableAspects()) { if (world.getWorld().resolve(TypeX.SERIALIZABLE).isAssignableFrom(myType)) { scope.problemReporter().signalError(sourceStart, sourceEnd, "aspects may not implement Serializable"); ignoreFurtherInvestigation = true; return; } if (world.getWorld().resolve(TypeX.CLONEABLE).isAssignableFrom(myType)) { scope.problemReporter().signalError(sourceStart, sourceEnd, "aspects may not implement Cloneable"); ignoreFurtherInvestigation = true; return; } } if (superType.isAspect()) { if (!superType.isAbstract()) { scope.problemReporter().signalError(sourceStart, sourceEnd, "can not extend a concrete aspect"); ignoreFurtherInvestigation = true; return; } } } private FieldBinding initFailureField= null; public void generateCode(ClassFile enclosingClassFile) { if (ignoreFurtherInvestigation) { if (binding == null) return; ClassFile.createProblemType( this, scope.referenceCompilationUnit().compilationResult); return; } // make me and my binding public this.modifiers = AstUtil.makePublic(this.modifiers); this.binding.modifiers = AstUtil.makePublic(this.binding.modifiers); if (!isAbstract()) { initFailureField = factory.makeFieldBinding(AjcMemberMaker.initFailureCauseField(typeX)); binding.addField(initFailureField); if (perClause == null) { // we've already produced an error for this } else if (perClause.getKind() == PerClause.SINGLETON) { binding.addField(factory.makeFieldBinding(AjcMemberMaker.perSingletonField( typeX))); methods[0] = new AspectClinit((Clinit)methods[0], compilationResult, false, true, initFailureField); } else if (perClause.getKind() == PerClause.PERCFLOW) { binding.addField( factory.makeFieldBinding( AjcMemberMaker.perCflowField( typeX))); methods[0] = new AspectClinit((Clinit)methods[0], compilationResult, true, false, null); } else if (perClause.getKind() == PerClause.PEROBJECT) { // binding.addField( // world.makeFieldBinding( // AjcMemberMaker.perCflowField( // typeX))); } else { throw new RuntimeException("unimplemented"); } } if (EclipseFactory.DEBUG) System.out.println(toString()); super.generateCode(enclosingClassFile); } public boolean needClassInitMethod() { return true; } protected void generateAttributes(ClassFile classFile) { if (!isAbstract()) generatePerSupportMembers(classFile); generateInlineAccessMembers(classFile); classFile.extraAttributes.add( new EclipseAttributeAdapter(new AjAttribute.Aspect(perClause))); if (binding.privilegedHandler != null) { ResolvedMember[] members = ((PrivilegedHandler)binding.privilegedHandler).getMembers(); classFile.extraAttributes.add( new EclipseAttributeAdapter(new AjAttribute.PrivilegedAttribute(members))); } //XXX need to get this attribute on anyone with a pointcut for good errors classFile.extraAttributes.add( new EclipseAttributeAdapter(new AjAttribute.SourceContextAttribute( new String(compilationResult().getFileName()), compilationResult().lineSeparatorPositions))); super.generateAttributes(classFile); } private void generateInlineAccessMembers(ClassFile classFile) { for (Iterator i = superAccessForInline.values().iterator(); i.hasNext(); ) { AccessForInlineVisitor.SuperAccessMethodPair pair = (AccessForInlineVisitor.SuperAccessMethodPair)i.next(); generateSuperAccessMethod(classFile, pair.accessMethod, pair.originalMethod); } for (Iterator i = accessForInline.entrySet().iterator(); i.hasNext(); ) { Map.Entry e = (Map.Entry)i.next(); generateInlineAccessMethod(classFile, (Binding)e.getValue(), (ResolvedMember)e.getKey()); } } private void generatePerSupportMembers(ClassFile classFile) { if (isAbstract()) return; //XXX otherwise we need to have this (error handling?) if (aspectOfMethod == null) return; if (perClause == null) { System.err.println("has null perClause: " + this); return; } EclipseFactory world = EclipseFactory.fromScopeLookupEnvironment(this.scope); if (perClause.getKind() == PerClause.SINGLETON) { generatePerSingletonAspectOfMethod(classFile); generatePerSingletonHasAspectMethod(classFile); generatePerSingletonAjcClinitMethod(classFile); } else if (perClause.getKind() == PerClause.PERCFLOW) { generatePerCflowAspectOfMethod(classFile); generatePerCflowHasAspectMethod(classFile); generatePerCflowPushMethod(classFile); generatePerCflowAjcClinitMethod(classFile); } else if (perClause.getKind() == PerClause.PEROBJECT) { TypeBinding interfaceType = generatePerObjectInterface(classFile); world.addTypeBinding(interfaceType); generatePerObjectAspectOfMethod(classFile, interfaceType); generatePerObjectHasAspectMethod(classFile, interfaceType); generatePerObjectBindMethod(classFile, interfaceType); } else { throw new RuntimeException("unimplemented"); } } private static interface BodyGenerator { public void generate(CodeStream codeStream); } private void generateMethod(ClassFile classFile, ResolvedMember member, BodyGenerator gen) { final EclipseFactory world = EclipseFactory.fromScopeLookupEnvironment(this.scope); generateMethod(classFile, world.makeMethodBinding(member), gen); } private void generateMethod(ClassFile classFile, MethodBinding methodBinding, BodyGenerator gen) { // EclipseFactory world = EclipseFactory.fromScopeLookupEnvironment(this.scope); classFile.generateMethodInfoHeader(methodBinding); int methodAttributeOffset = classFile.contentsOffset; int attributeNumber = classFile.generateMethodInfoAttribute(methodBinding, AstUtil.getAjSyntheticAttribute()); int codeAttributeOffset = classFile.contentsOffset; classFile.generateCodeAttributeHeader(); CodeStream codeStream = classFile.codeStream; // Use reset() rather than init() // XXX We need a scope to keep reset happy, initializerScope is *not* the right one, but it works ! // codeStream.init(classFile); // codeStream.initializeMaxLocals(methodBinding); MethodDeclaration md = AstUtil.makeMethodDeclaration(methodBinding); md.scope = initializerScope; codeStream.reset(md,classFile); // body starts here gen.generate(codeStream); // body ends here classFile.completeCodeAttribute(codeAttributeOffset); attributeNumber++; classFile.completeMethodInfo(methodAttributeOffset, attributeNumber); } private void generatePerCflowAspectOfMethod( ClassFile classFile) { final EclipseFactory world = EclipseFactory.fromScopeLookupEnvironment(this.scope); generateMethod(classFile, aspectOfMethod, new BodyGenerator() { public void generate(CodeStream codeStream) { // body starts here codeStream.getstatic( world.makeFieldBinding( AjcMemberMaker.perCflowField( typeX))); codeStream.invokevirtual(world.makeMethodBindingForCall( AjcMemberMaker.cflowStackPeekInstance())); codeStream.checkcast(binding); codeStream.areturn(); // body ends here }}); } private void generatePerCflowHasAspectMethod(ClassFile classFile) { final EclipseFactory world = EclipseFactory.fromScopeLookupEnvironment(this.scope); generateMethod(classFile, hasAspectMethod, new BodyGenerator() { public void generate(CodeStream codeStream) { // body starts here codeStream.getstatic( world.makeFieldBinding( AjcMemberMaker.perCflowField( typeX))); codeStream.invokevirtual(world.makeMethodBindingForCall( AjcMemberMaker.cflowStackIsValid())); codeStream.ireturn(); // body ends here }}); } private void generatePerCflowPushMethod( ClassFile classFile) { final EclipseFactory world = EclipseFactory.fromScopeLookupEnvironment(this.scope); generateMethod(classFile, world.makeMethodBinding(AjcMemberMaker.perCflowPush( EclipseFactory.fromBinding(binding))), new BodyGenerator() { public void generate(CodeStream codeStream) { // body starts here codeStream.getstatic( world.makeFieldBinding( AjcMemberMaker.perCflowField( typeX))); codeStream.new_(binding); codeStream.dup(); codeStream.invokespecial( new MethodBinding(0, "<init>".toCharArray(), BaseTypes.VoidBinding, new TypeBinding[0], new ReferenceBinding[0], binding)); codeStream.invokevirtual(world.makeMethodBindingForCall( AjcMemberMaker.cflowStackPushInstance())); codeStream.return_(); // body ends here }}); } private void generatePerCflowAjcClinitMethod( ClassFile classFile) { final EclipseFactory world = EclipseFactory.fromScopeLookupEnvironment(this.scope); generateMethod(classFile, world.makeMethodBinding(AjcMemberMaker.ajcPreClinitMethod( EclipseFactory.fromBinding(binding))), new BodyGenerator() { public void generate(CodeStream codeStream) { // body starts here codeStream.new_(world.makeTypeBinding(AjcMemberMaker.CFLOW_STACK_TYPE)); codeStream.dup(); codeStream.invokespecial(world.makeMethodBindingForCall(AjcMemberMaker.cflowStackInit())); codeStream.putstatic( world.makeFieldBinding( AjcMemberMaker.perCflowField( typeX))); codeStream.return_(); // body ends here }}); } private TypeBinding generatePerObjectInterface( ClassFile classFile) { final EclipseFactory world = EclipseFactory.fromScopeLookupEnvironment(this.scope); TypeX interfaceTypeX = AjcMemberMaker.perObjectInterfaceType(typeX); HelperInterfaceBinding interfaceType = new HelperInterfaceBinding(this.binding, interfaceTypeX); world.addTypeBinding(interfaceType); interfaceType.addMethod(world, AjcMemberMaker.perObjectInterfaceGet(typeX)); interfaceType.addMethod(world, AjcMemberMaker.perObjectInterfaceSet(typeX)); interfaceType.generateClass(compilationResult, classFile); return interfaceType; } private void generatePerObjectAspectOfMethod( ClassFile classFile, final TypeBinding interfaceType) { final EclipseFactory world = EclipseFactory.fromScopeLookupEnvironment(this.scope); generateMethod(classFile, aspectOfMethod, new BodyGenerator() { public void generate(CodeStream codeStream) { // body starts here Label wrongType = new Label(codeStream); Label popWrongType = new Label(codeStream); codeStream.aload_0(); codeStream.instance_of(interfaceType); codeStream.ifeq(wrongType); codeStream.aload_0(); codeStream.checkcast(interfaceType); codeStream.invokeinterface(world.makeMethodBindingForCall( AjcMemberMaker.perObjectInterfaceGet(typeX))); codeStream.dup(); codeStream.ifnull(popWrongType); codeStream.areturn(); popWrongType.place(); codeStream.pop(); wrongType.place(); codeStream.new_(world.makeTypeBinding(AjcMemberMaker.NO_ASPECT_BOUND_EXCEPTION)); codeStream.dup(); codeStream.invokespecial(world.makeMethodBindingForCall( AjcMemberMaker.noAspectBoundExceptionInit() )); codeStream.athrow(); // body ends here }}); } private void generatePerObjectHasAspectMethod(ClassFile classFile, final TypeBinding interfaceType) { final EclipseFactory world = EclipseFactory.fromScopeLookupEnvironment(this.scope); generateMethod(classFile, hasAspectMethod, new BodyGenerator() { public void generate(CodeStream codeStream) { // body starts here Label wrongType = new Label(codeStream); codeStream.aload_0(); codeStream.instance_of(interfaceType); codeStream.ifeq(wrongType); codeStream.aload_0(); codeStream.checkcast(interfaceType); codeStream.invokeinterface(world.makeMethodBindingForCall( AjcMemberMaker.perObjectInterfaceGet(typeX))); codeStream.ifnull(wrongType); codeStream.iconst_1(); codeStream.ireturn(); wrongType.place(); codeStream.iconst_0(); codeStream.ireturn(); // body ends here }}); } private void generatePerObjectBindMethod( ClassFile classFile, final TypeBinding interfaceType) { final EclipseFactory world = EclipseFactory.fromScopeLookupEnvironment(this.scope); generateMethod(classFile, AjcMemberMaker.perObjectBind(EclipseFactory.fromBinding(binding)), new BodyGenerator() { public void generate(CodeStream codeStream) { // body starts here Label wrongType = new Label(codeStream); codeStream.aload_0(); codeStream.instance_of(interfaceType); codeStream.ifeq(wrongType); //XXX this case might call for screaming codeStream.aload_0(); codeStream.checkcast(interfaceType); codeStream.invokeinterface(world.makeMethodBindingForCall( AjcMemberMaker.perObjectInterfaceGet(typeX))); //XXX should do a check for null here and throw a NoAspectBound codeStream.ifnonnull(wrongType); codeStream.aload_0(); codeStream.checkcast(interfaceType); codeStream.new_(binding); codeStream.dup(); codeStream.invokespecial( new MethodBinding(0, "<init>".toCharArray(), BaseTypes.VoidBinding, new TypeBinding[0], new ReferenceBinding[0], binding)); codeStream.invokeinterface(world.makeMethodBindingForCall( AjcMemberMaker.perObjectInterfaceSet(typeX))); wrongType.place(); codeStream.return_(); // body ends here }}); } private void generatePerSingletonAspectOfMethod(ClassFile classFile) { final EclipseFactory world = EclipseFactory.fromScopeLookupEnvironment(this.scope); generateMethod(classFile, aspectOfMethod, new BodyGenerator() { public void generate(CodeStream codeStream) { // Old style aspectOf() method which confused decompilers // // body starts here // codeStream.getstatic(world.makeFieldBinding(AjcMemberMaker.perSingletonField( // typeX))); // Label isNull = new Label(codeStream); // codeStream.dup(); // codeStream.ifnull(isNull); // codeStream.areturn(); // isNull.place(); // // codeStream.incrStackSize(+1); // the dup trick above confuses the stack counter // codeStream.new_(world.makeTypeBinding(AjcMemberMaker.NO_ASPECT_BOUND_EXCEPTION)); // codeStream.dup(); // codeStream.ldc(typeX.getNameAsIdentifier()); // codeStream.getstatic(initFailureField); // codeStream.invokespecial(world.makeMethodBindingForCall( // AjcMemberMaker.noAspectBoundExceptionInitWithCause() // )); // codeStream.athrow(); // // body ends here // The stuff below generates code that looks like this: /* * if (ajc$perSingletonInstance == null) * throw new NoAspectBoundException("A", ajc$initFailureCause); * else * return ajc$perSingletonInstance; */ // body starts here (see end of each line for what it is doing!) FieldBinding fb = world.makeFieldBinding(AjcMemberMaker.perSingletonField(typeX)); codeStream.getstatic(fb); // GETSTATIC Label isNonNull = new Label(codeStream); codeStream.ifnonnull(isNonNull); // IFNONNULL codeStream.new_(world.makeTypeBinding(AjcMemberMaker.NO_ASPECT_BOUND_EXCEPTION)); // NEW codeStream.dup(); // DUP codeStream.ldc(typeX.getNameAsIdentifier()); // LDC codeStream.getstatic(initFailureField); // GETSTATIC codeStream.invokespecial(world.makeMethodBindingForCall( AjcMemberMaker.noAspectBoundExceptionInitWithCause())); // INVOKESPECIAL codeStream.athrow(); // ATHROW isNonNull.place(); codeStream.getstatic(fb); // GETSTATIC codeStream.areturn(); // ARETURN // body ends here }}); } private void generatePerSingletonHasAspectMethod(ClassFile classFile) { final EclipseFactory world = EclipseFactory.fromScopeLookupEnvironment(this.scope); generateMethod(classFile, hasAspectMethod, new BodyGenerator() { public void generate(CodeStream codeStream) { // body starts here codeStream.getstatic(world.makeFieldBinding(AjcMemberMaker.perSingletonField( typeX))); Label isNull = new Label(codeStream); codeStream.ifnull(isNull); codeStream.iconst_1(); codeStream.ireturn(); isNull.place(); codeStream.iconst_0(); codeStream.ireturn(); // body ends here }}); } private void generatePerSingletonAjcClinitMethod( ClassFile classFile) { final EclipseFactory world = EclipseFactory.fromScopeLookupEnvironment(this.scope); generateMethod(classFile, world.makeMethodBinding(AjcMemberMaker.ajcPostClinitMethod( EclipseFactory.fromBinding(binding))), new BodyGenerator() { public void generate(CodeStream codeStream) { // body starts here codeStream.new_(binding); codeStream.dup(); codeStream.invokespecial( new MethodBinding(0, "<init>".toCharArray(), BaseTypes.VoidBinding, new TypeBinding[0], new ReferenceBinding[0], binding)); codeStream.putstatic( world.makeFieldBinding( AjcMemberMaker.perSingletonField( typeX))); codeStream.return_(); // body ends here }}); } private void generateSuperAccessMethod(ClassFile classFile, final MethodBinding accessMethod, final ResolvedMember method) { generateMethod(classFile, accessMethod, new BodyGenerator() { public void generate(CodeStream codeStream) { // body starts here codeStream.aload_0(); AstUtil.generateParameterLoads(accessMethod.parameters, codeStream); codeStream.invokespecial( factory.makeMethodBinding(method)); AstUtil.generateReturn(accessMethod.returnType, codeStream); // body ends here }}); } private void generateInlineAccessMethod(ClassFile classFile, final Binding binding, final ResolvedMember member) { if (binding instanceof InlineAccessFieldBinding) { generateInlineAccessors(classFile, (InlineAccessFieldBinding)binding, member); } else { generateInlineAccessMethod(classFile, (MethodBinding)binding, member); } } private void generateInlineAccessors(ClassFile classFile, final InlineAccessFieldBinding accessField, final ResolvedMember field) { final FieldBinding fieldBinding = factory.makeFieldBinding(field); generateMethod(classFile, accessField.reader, new BodyGenerator() { public void generate(CodeStream codeStream) { // body starts here if (field.isStatic()) { codeStream.getstatic(fieldBinding); } else { codeStream.aload_0(); codeStream.getfield(fieldBinding); } AstUtil.generateReturn(accessField.reader.returnType, codeStream); // body ends here }}); generateMethod(classFile, accessField.writer, new BodyGenerator() { public void generate(CodeStream codeStream) { // body starts here if (field.isStatic()) { codeStream.load(fieldBinding.type, 0); codeStream.putstatic(fieldBinding); } else { codeStream.aload_0(); codeStream.load(fieldBinding.type, 1); codeStream.putfield(fieldBinding); } codeStream.return_(); // body ends here }}); } private void generateInlineAccessMethod(ClassFile classFile, final MethodBinding accessMethod, final ResolvedMember method) { generateMethod(classFile, accessMethod, new BodyGenerator() { public void generate(CodeStream codeStream) { // body starts here AstUtil.generateParameterLoads(accessMethod.parameters, codeStream); if (method.isStatic()) { codeStream.invokestatic(factory.makeMethodBinding(method)); } else { codeStream.invokevirtual(factory.makeMethodBinding(method)); } AstUtil.generateReturn(accessMethod.returnType, codeStream); // body ends here }}); } private PerClause.Kind lookupPerClauseKind(ReferenceBinding binding) { PerClause perClause; if (binding instanceof BinaryTypeBinding) { ResolvedTypeX superTypeX = factory.fromEclipse(binding); perClause = superTypeX.getPerClause(); } else if (binding instanceof SourceTypeBinding ) { SourceTypeBinding sourceSc = (SourceTypeBinding)binding; if (sourceSc.scope.referenceContext instanceof AspectDeclaration) { perClause = ((AspectDeclaration)sourceSc.scope.referenceContext).perClause; } else { return null; } } else { //XXX need to handle this too return null; } if (perClause == null) { return lookupPerClauseKind(binding.superclass()); } else { return perClause.getKind(); } } private void buildPerClause(ClassScope scope) { EclipseFactory world = EclipseFactory.fromScopeLookupEnvironment(scope); if (perClause == null) { PerClause.Kind kind = lookupPerClauseKind(binding.superclass); if (kind == null) { perClause = new PerSingleton(); } else { perClause = new PerFromSuper(kind); } } aspectAttribute = new AjAttribute.Aspect(perClause); if (ignoreFurtherInvestigation) return; //??? if (!isAbstract()) { if (perClause.getKind() == PerClause.SINGLETON) { aspectOfMethod = AjcMemberMaker.perSingletonAspectOfMethod(typeX); hasAspectMethod = AjcMemberMaker.perSingletonHasAspectMethod(typeX); } else if (perClause.getKind() == PerClause.PERCFLOW) { aspectOfMethod = AjcMemberMaker.perCflowAspectOfMethod(typeX); hasAspectMethod = AjcMemberMaker.perCflowHasAspectMethod(typeX); } else if (perClause.getKind() == PerClause.PEROBJECT) { aspectOfMethod = AjcMemberMaker.perObjectAspectOfMethod(typeX); hasAspectMethod = AjcMemberMaker.perObjectHasAspectMethod(typeX); } else { throw new RuntimeException("bad per clause: " + perClause); } binding.addMethod(world.makeMethodBinding(aspectOfMethod)); binding.addMethod(world.makeMethodBinding(hasAspectMethod)); } resolvePerClause(); //XXX might be too soon for some error checking } private PerClause resolvePerClause() { EclipseScope iscope = new EclipseScope(new FormalBinding[0], scope); perClause.resolve(iscope); return perClause; } public void buildInterTypeAndPerClause(ClassScope classScope) { factory = EclipseFactory.fromScopeLookupEnvironment(scope); if (isPrivileged) { binding.privilegedHandler = new PrivilegedHandler(this); } checkSpec(classScope); if (ignoreFurtherInvestigation) return; buildPerClause(scope); if (methods != null) { for (int i = 0; i < methods.length; i++) { if (methods[i] instanceof InterTypeDeclaration) { EclipseTypeMunger m = ((InterTypeDeclaration)methods[i]).build(classScope); if (m != null) concreteName.typeMungers.add(m); } else if (methods[i] instanceof DeclareDeclaration) { Declare d = ((DeclareDeclaration)methods[i]).build(classScope); if (d != null) concreteName.declares.add(d); } } } concreteName.getDeclaredPointcuts(); } // public String toString(int tab) { // return tabString(tab) + toStringHeader() + toStringBody(tab); // } // // public String toStringBody(int tab) { // // String s = " {"; //$NON-NLS-1$ // // // if (memberTypes != null) { // for (int i = 0; i < memberTypes.length; i++) { // if (memberTypes[i] != null) { // s += "\n" + memberTypes[i].toString(tab + 1); //$NON-NLS-1$ // } // } // } // if (fields != null) { // for (int fieldI = 0; fieldI < fields.length; fieldI++) { // if (fields[fieldI] != null) { // s += "\n" + fields[fieldI].toString(tab + 1); //$NON-NLS-1$ // if (fields[fieldI].isField()) // s += ";"; //$NON-NLS-1$ // } // } // } // if (methods != null) { // for (int i = 0; i < methods.length; i++) { // if (methods[i] != null) { // s += "\n" + methods[i].toString(tab + 1); //$NON-NLS-1$ // } // } // } // s += "\n" + tabString(tab) + "}"; //$NON-NLS-2$ //$NON-NLS-1$ // return s; // } public StringBuffer printHeader(int indent, StringBuffer output) { printModifiers(this.modifiers, output); output.append("aspect " ); output.append(name); if (superclass != null) { output.append(" extends "); //$NON-NLS-1$ superclass.print(0, output); } if (superInterfaces != null && superInterfaces.length > 0) { output.append(isInterface() ? " extends " : " implements ");//$NON-NLS-2$ //$NON-NLS-1$ for (int i = 0; i < superInterfaces.length; i++) { if (i > 0) output.append( ", "); //$NON-NLS-1$ superInterfaces[i].print(0, output); } } return output; //XXX we should append the per-clause } }
44,191
Bug 44191 Need better error message for "can't find type"
I have experienced situations where IAJC outputs a message like this at the end of compilation. [iajc] can't find type org.xxx.SomeTest In my case this was one time highly confusing since I did not expect the class in question to be referred anywhere in the project (I have to date still not located the reference). For such cases, it would be extremely nice if the error message would display WHY it need the class (i.e. the name of the refering class(es) or aspect(es) possibly with a reasonable cutoff as there is seldom need to list all referals). So I would like a message like this: [iajc] can't find type org.xxx.SomeTest referred by org.yyy.SomeClass,org.yy.SomeOtherClass ...
resolved fixed
061395c
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2004-08-06T15:04:45Z
2003-10-04T23: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 Common Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * PARC initial implementation * ******************************************************************/ package org.aspectj.ajdt.internal.compiler.lookup; import java.util.*; import org.aspectj.ajdt.internal.compiler.ast.*; import org.aspectj.ajdt.internal.core.builder.EclipseSourceContext; import org.aspectj.bridge.IMessage; //import org.aspectj.bridge.ISourceLocation; import org.aspectj.weaver.*; import org.aspectj.weaver.patterns.PerClause; import org.aspectj.weaver.patterns.PerSingleton; import org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration; import org.eclipse.jdt.internal.compiler.ast.TypeDeclaration; import org.eclipse.jdt.internal.compiler.lookup.*; /** * Supports viewing eclipse TypeDeclarations/SourceTypeBindings as a ResolvedTypeX * * @author Jim Hugunin */ public class EclipseSourceType extends ResolvedTypeX.ConcreteName { 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; protected EclipseFactory eclipseWorld() { return factory; } public EclipseSourceType(ResolvedTypeX.Name resolvedTypeX, EclipseFactory factory, SourceTypeBinding binding, TypeDeclaration declaration) { super(resolvedTypeX, true); this.factory = factory; this.binding = binding; this.declaration = declaration; resolvedTypeX.setSourceContext(new EclipseSourceContext(declaration.compilationResult)); resolvedTypeX.setStartPos(declaration.sourceStart); resolvedTypeX.setEndPos(declaration.sourceEnd); } public boolean isAspect() { return declaration instanceof AspectDeclaration; } public WeaverStateInfo getWeaverState() { return null; } public ResolvedTypeX getSuperclass() { if (binding.isInterface()) return getResolvedTypeX().getWorld().resolve(TypeX.OBJECT); //XXX what about java.lang.Object return eclipseWorld().fromEclipse(binding.superclass()); } public ResolvedTypeX[] 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(); declaredPointcuts.add(df); } else if (amd instanceof InterTypeDeclaration) { // these are handled in a separate pass continue; } else if (amd instanceof DeclareDeclaration) { // 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.binding == null || !amd.binding.isValidBinding()) continue; declaredMethods.add(EclipseFactory.makeResolvedMember(amd.binding)); } } } FieldBinding[] fields = binding.fields(); for (int i=0, len=fields.length; i < len; i++) { FieldBinding f = fields[i]; declaredFields.add(EclipseFactory.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()]); } public ResolvedMember[] getDeclaredFields() { if (declaredFields == null) fillDeclaredMembers(); return declaredFields; } 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(); } 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 return new PerSingleton(); } protected Collection getDeclares() { return declares; } protected Collection getPrivilegedAccesses() { return Collections.EMPTY_LIST; } protected Collection getTypeMungers() { return typeMungers; } public boolean doesNotExposeShadowMungers() { return true; } }
44,191
Bug 44191 Need better error message for "can't find type"
I have experienced situations where IAJC outputs a message like this at the end of compilation. [iajc] can't find type org.xxx.SomeTest In my case this was one time highly confusing since I did not expect the class in question to be referred anywhere in the project (I have to date still not located the reference). For such cases, it would be extremely nice if the error message would display WHY it need the class (i.e. the name of the refering class(es) or aspect(es) possibly with a reasonable cutoff as there is seldom need to list all referals). So I would like a message like this: [iajc] can't find type org.xxx.SomeTest referred by org.yyy.SomeClass,org.yy.SomeOtherClass ...
resolved fixed
061395c
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2004-08-06T15:04:45Z
2003-10-04T23:26:40Z
weaver/src/org/aspectj/weaver/ResolvedTypeX.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Common Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * PARC initial implementation * ******************************************************************/ package org.aspectj.weaver; import java.lang.reflect.Modifier; 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.bridge.IMessage; import org.aspectj.bridge.ISourceLocation; import org.aspectj.bridge.Message; import org.aspectj.bridge.MessageUtil; import org.aspectj.weaver.patterns.Declare; import org.aspectj.weaver.patterns.PerClause; public abstract class ResolvedTypeX extends TypeX { protected World world; ResolvedTypeX(String signature, World world) { super(signature); this.world = world; } // ---- things that don't require a world /** returns Iterator&lt;ResolvedTypeX&gt; */ public final Iterator getDirectSupertypes() { Iterator ifacesIterator = Iterators.array(getDeclaredInterfaces()); ResolvedTypeX superclass = getSuperclass(); if (superclass == null) { return ifacesIterator; } else { return Iterators.snoc(ifacesIterator, superclass); } } public abstract ResolvedMember[] getDeclaredFields(); public abstract ResolvedMember[] getDeclaredMethods(); public abstract ResolvedTypeX[] getDeclaredInterfaces(); public abstract ResolvedMember[] getDeclaredPointcuts(); public abstract ResolvedTypeX getSuperclass(); public abstract int getModifiers(); public abstract boolean needsNoConversionFrom(TypeX other); public abstract boolean isCoerceableFrom(TypeX other); public abstract boolean isAssignableFrom(TypeX other); // ---- things that would require a world if I weren't resolved public final Iterator getDirectSupertypes(World world) { return getDirectSupertypes(); } public final ResolvedMember[] getDeclaredFields(World world) { return getDeclaredFields(); } public final ResolvedMember[] getDeclaredMethods(World world) { return getDeclaredMethods(); } public final TypeX[] getDeclaredInterfaces(World world) { return getDeclaredInterfaces(); } public final ResolvedMember[] getDeclaredPointcuts(World world) { return getDeclaredPointcuts(); } public final int getModifiers(World world) { return getModifiers(); } public final TypeX getSuperclass(World world) { return getSuperclass(); } // conversions public final boolean isAssignableFrom(TypeX other, World world) { return isAssignableFrom(other); } public final boolean isCoerceableFrom(TypeX other, World world) { return isCoerceableFrom(other); } public boolean needsNoConversionFrom(TypeX other, World world) { return needsNoConversionFrom(other); } public final boolean isConvertableFrom(TypeX other) { if (this.equals(OBJECT) || other.equals(OBJECT)) return true; return this.isCoerceableFrom(other); } // utilities public ResolvedTypeX getResolvedComponentType() { return null; } public ResolvedTypeX resolve(World world) { return this; } public World getWorld() { return world; } // ---- things from object public final boolean equals(Object other) { if (other instanceof ResolvedTypeX) { return this == other; } else { return super.equals(other); } } // ---- difficult things /** * returns an iterator through all of the fields of this type, in order * for checking from JVM spec 2ed 5.4.3.2. This means that the order is * * <ul><li> fields from current class </li> * <li> recur into direct superinterfaces </li> * <li> recur into superclass </li> * </ul> * * We keep a hashSet of interfaces that we've visited so we don't spiral * out into 2^n land. */ public Iterator getFields() { final Iterators.Filter dupFilter = Iterators.dupFilter(); Iterators.Getter typeGetter = new Iterators.Getter() { public Iterator get(Object o) { return dupFilter.filter( ((ResolvedTypeX)o).getDirectSupertypes()); } }; Iterators.Getter fieldGetter = new Iterators.Getter() { public Iterator get(Object o) { return Iterators.array(((ResolvedTypeX)o).getDeclaredFields()); } }; return Iterators.mapOver( Iterators.recur(this, typeGetter), fieldGetter); } /** * returns an iterator through all of the methods of this type, in order * for checking from JVM spec 2ed 5.4.3.3. This means that the order is * * <ul><li> methods from current class </li> * <li> recur into superclass, all the way up, not touching interfaces </li> * <li> recur into all superinterfaces, in some unspecified order </li> * </ul> * * We keep a hashSet of interfaces that we've visited so we don't spiral * out into 2^n land. */ public Iterator getMethods() { final Iterators.Filter dupFilter = Iterators.dupFilter(); Iterators.Getter ifaceGetter = new Iterators.Getter() { public Iterator get(Object o) { return dupFilter.filter( Iterators.array(((ResolvedTypeX)o).getDeclaredInterfaces()) ); } }; Iterators.Getter methodGetter = new Iterators.Getter() { public Iterator get(Object o) { return Iterators.array(((ResolvedTypeX)o).getDeclaredMethods()); } }; return Iterators.mapOver( Iterators.append( new Iterator() { ResolvedTypeX curr = ResolvedTypeX.this; public boolean hasNext() { return curr != null; } public Object next() { ResolvedTypeX ret = curr; curr = curr.getSuperclass(); return ret; } public void remove() { throw new UnsupportedOperationException(); } }, Iterators.recur(this, ifaceGetter)), methodGetter); } /** * described in JVM spec 2ed 5.4.3.2 */ public ResolvedMember lookupField(Member m) { return lookupMember(m, getFields()); } /** * described in JVM spec 2ed 5.4.3.3 */ public ResolvedMember lookupMethod(Member m) { return lookupMember(m, getMethods()); } /** return null if not found */ private ResolvedMember lookupMember(Member m, Iterator i) { while (i.hasNext()) { ResolvedMember f = (ResolvedMember) i.next(); if (matches(f, m)) return f; } return null; //ResolvedMember.Missing; //throw new BCException("can't find " + m); } /** return null if not found */ private ResolvedMember lookupMember(Member m, ResolvedMember[] a) { for (int i = 0; i < a.length; i++) { ResolvedMember f = a[i]; if (matches(f, m)) return f; } return null; } public static boolean matches(Member m1, Member m2) { if (m1 == null) return m2 == null; if (m2 == null) return false; return m1.getName().equals(m2.getName()) && m1.getSignature().equals(m2.getSignature()); } public static boolean conflictingSignature(Member m1, Member m2) { if (m1 == null || m2 == null) return false; if (!m1.getName().equals(m2.getName())) { return false; } if (m1.getKind() != m2.getKind()) { return false; } if (m1.getKind() == Member.FIELD) { return m1.getDeclaringType().equals(m2.getDeclaringType()); } else if (m1.getKind() == Member.POINTCUT) { return true; } TypeX[] p1 = m1.getParameterTypes(); TypeX[] p2 = m2.getParameterTypes(); int n = p1.length; if (n != p2.length) return false; for (int i=0; i < n; i++) { if (!p1[i].equals(p2[i])) return false; } return true; } /** * returns an iterator through all of the pointcuts of this type, in order * for checking from JVM spec 2ed 5.4.3.2 (as for fields). This means that the order is * * <ul><li> pointcuts from current class </li> * <li> recur into direct superinterfaces </li> * <li> recur into superclass </li> * </ul> * * We keep a hashSet of interfaces that we've visited so we don't spiral * out into 2^n land. */ public Iterator getPointcuts() { final Iterators.Filter dupFilter = Iterators.dupFilter(); // same order as fields Iterators.Getter typeGetter = new Iterators.Getter() { public Iterator get(Object o) { return dupFilter.filter( ((ResolvedTypeX)o).getDirectSupertypes()); } }; Iterators.Getter pointcutGetter = new Iterators.Getter() { public Iterator get(Object o) { //System.err.println("getting for " + o); return Iterators.array(((ResolvedTypeX)o).getDeclaredPointcuts()); } }; return Iterators.mapOver( Iterators.recur(this, typeGetter), pointcutGetter); } public ResolvedPointcutDefinition findPointcut(String name) { //System.err.println("looking for pointcuts " + this); for (Iterator i = getPointcuts(); i.hasNext(); ) { ResolvedPointcutDefinition f = (ResolvedPointcutDefinition) i.next(); //System.err.println(f); if (name.equals(f.getName())) { return f; } } return null; // should we throw an exception here? } // all about collecting CrosscuttingMembers //??? collecting data-structure, shouldn't really be a field public CrosscuttingMembers crosscuttingMembers; public CrosscuttingMembers collectCrosscuttingMembers() { crosscuttingMembers = new CrosscuttingMembers(this); crosscuttingMembers.setPerClause(getPerClause()); crosscuttingMembers.addShadowMungers(collectShadowMungers()); crosscuttingMembers.addTypeMungers(getTypeMungers()); crosscuttingMembers.addDeclares(collectDeclares(!this.doesNotExposeShadowMungers())); crosscuttingMembers.addPrivilegedAccesses(getPrivilegedAccesses()); //System.err.println("collected cc members: " + this + ", " + collectDeclares()); return crosscuttingMembers; } public final Collection collectDeclares(boolean includeAdviceLike) { if (! this.isAspect() ) return Collections.EMPTY_LIST; ArrayList ret = new ArrayList(); //if (this.isAbstract()) { for (Iterator i = getDeclares().iterator(); i.hasNext();) { Declare dec = (Declare) i.next(); if (!dec.isAdviceLike()) ret.add(dec); } if (!includeAdviceLike) return ret; if (!this.isAbstract()) { //ret.addAll(getDeclares()); final Iterators.Filter dupFilter = Iterators.dupFilter(); Iterators.Getter typeGetter = new Iterators.Getter() { public Iterator get(Object o) { return dupFilter.filter( ((ResolvedTypeX)o).getDirectSupertypes()); } }; Iterator typeIterator = Iterators.recur(this, typeGetter); while (typeIterator.hasNext()) { ResolvedTypeX ty = (ResolvedTypeX) typeIterator.next(); //System.out.println("super: " + ty + ", " + ); for (Iterator i = ty.getDeclares().iterator(); i.hasNext();) { Declare dec = (Declare) i.next(); if (dec.isAdviceLike()) ret.add(dec); } } } return ret; } private final Collection collectShadowMungers() { if (! this.isAspect() || this.isAbstract() || this.doesNotExposeShadowMungers()) return Collections.EMPTY_LIST; ArrayList acc = new ArrayList(); final Iterators.Filter dupFilter = Iterators.dupFilter(); Iterators.Getter typeGetter = new Iterators.Getter() { public Iterator get(Object o) { return dupFilter.filter( ((ResolvedTypeX)o).getDirectSupertypes()); } }; Iterator typeIterator = Iterators.recur(this, typeGetter); while (typeIterator.hasNext()) { ResolvedTypeX ty = (ResolvedTypeX) typeIterator.next(); acc.addAll(ty.getDeclaredShadowMungers()); } return acc; } protected boolean doesNotExposeShadowMungers() { return false; } public PerClause getPerClause() { return null; } protected Collection getDeclares() { return Collections.EMPTY_LIST; } protected Collection getTypeMungers() { return Collections.EMPTY_LIST; } protected Collection getPrivilegedAccesses() { return Collections.EMPTY_LIST; } // ---- useful things public final boolean isInterface() { return Modifier.isInterface(getModifiers()); } public final boolean isAbstract() { return Modifier.isAbstract(getModifiers()); } public boolean isClass() { return false; } public boolean isAspect() { return false; } public boolean isSynthetic() { return signature.indexOf("$ajc") != -1; } public final boolean isFinal() { return Modifier.isFinal(getModifiers()); } public Collection getDeclaredAdvice() { List l = new ArrayList(); ResolvedMember[] methods = getDeclaredMethods(); for (int i=0, len = methods.length; i < len; i++) { ShadowMunger munger = methods[i].getAssociatedShadowMunger(); if (munger != null) l.add(munger); } return l; } private List shadowMungers = new ArrayList(0); public Collection getDeclaredShadowMungers() { Collection c = getDeclaredAdvice(); c.addAll(shadowMungers); return c; } public void addShadowMunger(ShadowMunger munger) { shadowMungers.add(munger); } // ---- only for testing! public ResolvedMember[] getDeclaredJavaFields() { return filterInJavaVisible(getDeclaredFields()); } public ResolvedMember[] getDeclaredJavaMethods() { return filterInJavaVisible(getDeclaredMethods()); } public ShadowMunger[] getDeclaredShadowMungersArray() { List l = (List) getDeclaredShadowMungers(); return (ShadowMunger[]) l.toArray(new ShadowMunger[l.size()]); } private ResolvedMember[] filterInJavaVisible(ResolvedMember[] ms) { List l = new ArrayList(); for (int i=0, len = ms.length; i < len; i++) { if (! ms[i].isAjSynthetic() && ms[i].getAssociatedShadowMunger() == null) { l.add(ms[i]); } } return (ResolvedMember[]) l.toArray(new ResolvedMember[l.size()]); } public abstract ISourceContext getSourceContext(); // ---- fields public static final ResolvedTypeX[] NONE = new ResolvedTypeX[0]; public static final Primitive BYTE = new Primitive("B", 1, 0); public static final Primitive CHAR = new Primitive("C", 1, 1); public static final Primitive DOUBLE = new Primitive("D", 2, 2); public static final Primitive FLOAT = new Primitive("F", 1, 3); public static final Primitive INT = new Primitive("I", 1, 4); public static final Primitive LONG = new Primitive("J", 2, 5); public static final Primitive SHORT = new Primitive("S", 1, 6); public static final Primitive VOID = new Primitive("V", 0, 8); public static final Primitive BOOLEAN = new Primitive("Z", 1, 7); public static final Missing MISSING = new Missing(); // ---- types public static class Name extends ResolvedTypeX { private ConcreteName delegate = null; private ISourceContext sourceContext = null; private int startPos = 0; private int endPos = 0; //??? should set delegate before any use public Name(String signature, World world) { super(signature, world); } public final boolean isClass() { return delegate.isClass(); } public boolean isAspect() { return delegate.isAspect(); } public final boolean needsNoConversionFrom(TypeX o) { return isAssignableFrom(o); } public final boolean isAssignableFrom(TypeX o) { if (o.isPrimitive()) return false; ResolvedTypeX other = o.resolve(world); return isAssignableFrom(other); } public final boolean isCoerceableFrom(TypeX o) { ResolvedTypeX other = o.resolve(world); if (this.isAssignableFrom(other) || other.isAssignableFrom(this)) { return true; } 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 = ((Name)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 boolean isAssignableFrom(ResolvedTypeX other) { if (this == other) return true; for(Iterator i = other.getDirectSupertypes(); i.hasNext(); ) { if (this.isAssignableFrom((ResolvedTypeX) i.next())) return true; } return false; } public ISourceContext getSourceContext() { return sourceContext; } public ISourceLocation getSourceLocation() { if (sourceContext == null) return null; return sourceContext.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() { return delegate.getDeclaredFields(); } public ResolvedTypeX[] getDeclaredInterfaces() { return delegate.getDeclaredInterfaces(); } public ResolvedMember[] getDeclaredMethods() { return delegate.getDeclaredMethods(); } public ResolvedMember[] getDeclaredPointcuts() { return delegate.getDeclaredPointcuts(); } public PerClause getPerClause() { return delegate.getPerClause(); } protected Collection getDeclares() { return delegate.getDeclares(); } protected Collection getTypeMungers() { return delegate.getTypeMungers(); } protected Collection getPrivilegedAccesses() { return delegate.getPrivilegedAccesses(); } public int getModifiers() { return delegate.getModifiers(); } public ResolvedTypeX getSuperclass() { return delegate.getSuperclass(); } public ConcreteName getDelegate() { return delegate; } public void setDelegate(ConcreteName delegate) { this.delegate = delegate; } public int getEndPos() { return endPos; } public int getStartPos() { return startPos; } public void setEndPos(int endPos) { this.endPos = endPos; } public void setSourceContext(ISourceContext sourceContext) { this.sourceContext = sourceContext; } public void setStartPos(int startPos) { this.startPos = startPos; } public boolean doesNotExposeShadowMungers() { return delegate.doesNotExposeShadowMungers(); } } public static abstract class ConcreteName { //protected ISourceContext sourceContext; protected boolean exposedToWeaver; protected ResolvedTypeX.Name resolvedTypeX; public ConcreteName(ResolvedTypeX.Name resolvedTypeX, boolean exposedToWeaver) { //???super(signature, world); this.resolvedTypeX = resolvedTypeX; this.exposedToWeaver = exposedToWeaver; } public final boolean isClass() { return !isAspect() && !isInterface(); } public abstract boolean isAspect(); public abstract boolean isInterface(); public abstract ResolvedMember[] getDeclaredFields(); public abstract ResolvedTypeX[] getDeclaredInterfaces(); public abstract ResolvedMember[] getDeclaredMethods(); public abstract ResolvedMember[] getDeclaredPointcuts(); public abstract PerClause getPerClause(); protected abstract Collection getDeclares() ; protected abstract Collection getTypeMungers(); protected abstract Collection getPrivilegedAccesses(); public abstract int getModifiers(); public abstract ResolvedTypeX getSuperclass(); // public abstract ISourceLocation getSourceLocation(); public abstract WeaverStateInfo getWeaverState(); // public ISourceContext getSourceContext() { // return sourceContext; // } /** * Designed to be overriden by EclipseType to disable collection of shadow mungers * during pre-weave compilation phase */ public boolean doesNotExposeShadowMungers() { return false; } public boolean isExposedToWeaver() { return exposedToWeaver; } public ResolvedTypeX.Name getResolvedTypeX() { return resolvedTypeX; } } static class Array extends ResolvedTypeX { ResolvedTypeX componentType; Array(String s, World world, ResolvedTypeX componentType) { super(s, world); this.componentType = componentType; } public final ResolvedMember[] getDeclaredFields() { return ResolvedMember.NONE; } public final ResolvedMember[] getDeclaredMethods() { // ??? should this return clone? Probably not... return ResolvedMember.NONE; } public final ResolvedTypeX[] getDeclaredInterfaces() { return new ResolvedTypeX[] { world.resolve(CLONEABLE), world.resolve(SERIALIZABLE) }; } public final ResolvedMember[] getDeclaredPointcuts() { return ResolvedMember.NONE; } public final ResolvedTypeX getSuperclass() { return world.resolve(OBJECT); } public final boolean isAssignableFrom(TypeX o) { if (! o.isArray()) return false; if (o.getComponentType().isPrimitive()) { return o.equals(this); } else { return getComponentType().isAssignableFrom(o.getComponentType(), world); } } public final boolean isCoerceableFrom(TypeX o) { if (o.equals(TypeX.OBJECT) || o.equals(TypeX.SERIALIZABLE) || o.equals(TypeX.CLONEABLE)) { return true; } if (! o.isArray()) return false; if (o.getComponentType().isPrimitive()) { return o.equals(this); } else { return getComponentType().isCoerceableFrom(o.getComponentType(), world); } } public final boolean needsNoConversionFrom(TypeX o) { return isAssignableFrom(o); } public final int getModifiers() { int mask = Modifier.PUBLIC | Modifier.PRIVATE | Modifier.PROTECTED; return (componentType.getModifiers() & mask) | Modifier.FINAL; } public TypeX getComponentType() { return componentType; } public ResolvedTypeX getResolvedComponentType() { return componentType; } public ISourceContext getSourceContext() { return getResolvedComponentType().getSourceContext(); } } static class Primitive extends ResolvedTypeX { private int size; private int index; Primitive(String signature, int size, int index) { super(signature, null); this.size = size; this.index = index; } public final int getSize() { return size; } public final int getModifiers() { return Modifier.PUBLIC | Modifier.FINAL; } public final boolean isPrimitive() { return true; } public final boolean isAssignableFrom(TypeX other) { if (! other.isPrimitive()) return false; return assignTable[((Primitive)other).index][index]; } public final boolean isCoerceableFrom(TypeX other) { if (this == other) return true; if (! other.isPrimitive()) return false; if (index > 6 || ((Primitive)other).index > 6) return false; return true; } public final boolean needsNoConversionFrom(TypeX other) { if (! other.isPrimitive()) return false; return noConvertTable[((Primitive)other).index][index]; } private static final boolean[][] assignTable = {// to: B C D F I J S V Z from { true , true , true , true , true , true , true , false, false }, // B { false, true , true , true , true , true , false, false, false }, // C { false, false, true , false, false, false, false, false, false }, // D { false, false, true , true , false, false, false, false, false }, // F { false, false, true , true , true , true , false, false, false }, // I { false, false, true , true , false, true , false, false, false }, // J { false, false, true , true , true , true , true , false, false }, // S { false, false, false, false, false, false, false, true , false }, // V { false, false, false, false, false, false, false, false, true }, // Z }; private static final boolean[][] noConvertTable = {// to: B C D F I J S V Z from { true , true , false, false, true , false, true , false, false }, // B { false, true , false, false, true , false, false, false, false }, // C { false, false, true , false, false, false, false, false, false }, // D { false, false, false, true , false, false, false, false, false }, // F { false, false, false, false, true , false, false, false, false }, // I { false, false, false, false, false, true , false, false, false }, // J { false, false, false, false, true , false, true , false, false }, // S { false, false, false, false, false, false, false, true , false }, // V { false, false, false, false, false, false, false, false, true }, // Z }; // ---- public final ResolvedMember[] getDeclaredFields() { return ResolvedMember.NONE; } public final ResolvedMember[] getDeclaredMethods() { return ResolvedMember.NONE; } public final ResolvedTypeX[] getDeclaredInterfaces() { return ResolvedTypeX.NONE; } public final ResolvedMember[] getDeclaredPointcuts() { return ResolvedMember.NONE; } public final ResolvedTypeX getSuperclass() { return null; } public ISourceContext getSourceContext() { return null; } } static class Missing extends ResolvedTypeX { Missing() { super(MISSING_NAME, null); } // public final String toString() { // return "<missing>"; // } public final String getName() { return MISSING_NAME; } public final ResolvedMember[] getDeclaredFields() { return ResolvedMember.NONE; } public final ResolvedMember[] getDeclaredMethods() { return ResolvedMember.NONE; } public final ResolvedTypeX[] getDeclaredInterfaces() { return ResolvedTypeX.NONE; } public final ResolvedMember[] getDeclaredPointcuts() { return ResolvedMember.NONE; } public final ResolvedTypeX getSuperclass() { return null; } public final int getModifiers() { return 0; } public final boolean isAssignableFrom(TypeX other) { return false; } public final boolean isCoerceableFrom(TypeX other) { return false; } public boolean needsNoConversionFrom(TypeX other) { return false; } public ISourceContext getSourceContext() { return null; } } /** return null if not found */ public ResolvedMember lookupMemberNoSupers(Member member) { ResolvedMember ret; if (member.getKind() == Member.FIELD) { ret = lookupMember(member, getDeclaredFields()); } else { // assert member.getKind() == Member.METHOD || member.getKind() == Member.CONSTRUCTOR ret = lookupMember(member, getDeclaredMethods()); } if (ret == null && interTypeMungers != null) { for (Iterator i = interTypeMungers.iterator(); i.hasNext();) { ConcreteTypeMunger tm = (ConcreteTypeMunger) i.next(); if (matches(tm.getSignature(), member)) { return tm.getSignature(); } } } return ret; } protected List interTypeMungers = new ArrayList(0); public List getInterTypeMungers() { return interTypeMungers; } /** * ??? This method is O(N*M) where N = number of methods and M is number of * inter-type declarations in my super */ public List getInterTypeMungersIncludingSupers() { ArrayList ret = new ArrayList(); collectInterTypeMungers(ret); return ret; } private void collectInterTypeMungers(List collector) { for (Iterator iter = getDirectSupertypes(); iter.hasNext();) { ResolvedTypeX superType = (ResolvedTypeX) iter.next(); superType.collectInterTypeMungers(collector); } outer: for (Iterator iter1 = collector.iterator(); iter1.hasNext(); ) { ConcreteTypeMunger superMunger = (ConcreteTypeMunger) iter1.next(); if ( superMunger.getSignature() == null) continue; if ( !superMunger.getSignature().isAbstract()) continue; for (Iterator iter = getInterTypeMungers().iterator(); iter.hasNext();) { ConcreteTypeMunger myMunger = (ConcreteTypeMunger) iter.next(); if (conflictingSignature(myMunger.getSignature(), superMunger.getSignature())) { iter1.remove(); continue outer; } } if (!superMunger.getSignature().isPublic()) continue; for (Iterator iter = getMethods(); iter.hasNext(); ) { ResolvedMember method = (ResolvedMember)iter.next(); if (conflictingSignature(method, superMunger.getSignature())) { iter1.remove(); continue outer; } } } collector.addAll(getInterTypeMungers()); } /** * Check that we don't have any abstract type mungers unless this * type is abstract. */ public void checkInterTypeMungers() { if (isAbstract()) return; for (Iterator iter = getInterTypeMungersIncludingSupers().iterator(); iter.hasNext();) { ConcreteTypeMunger element = (ConcreteTypeMunger) iter.next(); if (element.getSignature() != null && element.getSignature().isAbstract()) { ISourceLocation xtraLocation = element.getSourceLocation(); if (xtraLocation == null) { // Until intertype mungers remember where they came from, the source location // for the element is null when binary weaving. In these cases uses the // source location for the aspect containing the ITD xtraLocation = element.getAspectType().getSourceLocation(); } world.getMessageHandler().handleMessage( new Message("must implement abstract inter-type declaration: " + element.getSignature(), "", IMessage.ERROR, getSourceLocation(), null, new ISourceLocation[] { xtraLocation })); } } } /** * Returns a ResolvedTypeX object representing the declaring type of this type, or * null if this type does not represent a non-package-level-type. * * <strong>Warning</strong>: This is guaranteed to work for all member types. * For anonymous/local types, the only guarantee is given in JLS 13.1, where * it guarantees that if you call getDeclaringType() repeatedly, you will eventually * get the top-level class, but it does not say anything about classes in between. * * @return the declaring TypeX object, or null. */ public ResolvedTypeX getDeclaringType() { if (isArray()) return null; String name = getName(); int lastDollar = name.lastIndexOf('$'); while (lastDollar != -1) { ResolvedTypeX ret = world.resolve(TypeX.forName(name.substring(0, lastDollar)), true); if (ret != ResolvedTypeX.MISSING) return ret; lastDollar = name.lastIndexOf('$', lastDollar-1); } return null; } public static boolean isVisible(int modifiers, ResolvedTypeX targetType, ResolvedTypeX fromType) { //System.err.println("mod: " + modifiers + ", " + targetType + " and " + fromType); if (Modifier.isPublic(modifiers)) { return true; } else if (Modifier.isPrivate(modifiers)) { return targetType.getOutermostType().equals(fromType.getOutermostType()); } else if (Modifier.isProtected(modifiers)) { return samePackage(targetType, fromType) || targetType.isAssignableFrom(fromType); } else { // package-visible return samePackage(targetType, fromType); } } private static boolean samePackage( ResolvedTypeX targetType, ResolvedTypeX fromType) { String p1 = targetType.getPackageName(); String p2 = fromType.getPackageName(); if (p1 == null) return p2 == null; if (p2 == null) return false; return p1.equals(p2); } public void addInterTypeMunger(ConcreteTypeMunger munger) { ResolvedMember sig = munger.getSignature(); if (sig == null || munger.getMunger() == null || munger.getMunger().getKind() == ResolvedTypeMunger.PrivilegedAccess) { interTypeMungers.add(munger); return; } //System.err.println("add: " + munger + " to " + this.getClassName() + " with " + interTypeMungers); if (sig.getKind() == Member.METHOD) { if (!compareToExistingMembers(munger, getMethods())) return; if (this.isInterface()) { if (!compareToExistingMembers(munger, Arrays.asList(world.resolve(OBJECT).getDeclaredMethods()).iterator())) return; } } else if (sig.getKind() == Member.FIELD) { if (!compareToExistingMembers(munger, Arrays.asList(getDeclaredFields()).iterator())) return; } else { if (!compareToExistingMembers(munger, Arrays.asList(getDeclaredMethods()).iterator())) return; } // now compare to existingMungers for (Iterator i = interTypeMungers.iterator(); i.hasNext(); ) { ConcreteTypeMunger existingMunger = (ConcreteTypeMunger)i.next(); if (conflictingSignature(existingMunger.getSignature(), munger.getSignature())) { //System.err.println("match " + munger + " with " + existingMunger); if (isVisible(munger.getSignature().getModifiers(), munger.getAspectType(), existingMunger.getAspectType())) { //System.err.println(" is visible"); int c = compareMemberPrecedence(sig, existingMunger.getSignature()); if (c == 0) { c = getWorld().comparePrecedence(munger.getAspectType(), existingMunger.getAspectType()); } //System.err.println(" compare: " + c); if (c < 0) { // the existing munger dominates the new munger checkLegalOverride(munger.getSignature(), existingMunger.getSignature()); return; } else if (c > 0) { // the new munger dominates the existing one checkLegalOverride(existingMunger.getSignature(), munger.getSignature()); i.remove(); break; } else { interTypeConflictError(munger, existingMunger); interTypeConflictError(existingMunger, munger); return; } } } } //System.err.println("adding: " + munger + " to " + this); interTypeMungers.add(munger); } //??? returning too soon private boolean compareToExistingMembers(ConcreteTypeMunger munger, Iterator existingMembers) { ResolvedMember sig = munger.getSignature(); while (existingMembers.hasNext()) { ResolvedMember existingMember = (ResolvedMember)existingMembers.next(); //System.err.println("Comparing munger: "+sig+" with member "+existingMember); if (conflictingSignature(existingMember, munger.getSignature())) { //System.err.println("conflict: existingMember=" + existingMember + " typeMunger=" + munger); //System.err.println(munger.getSourceLocation() + ", " + munger.getSignature() + ", " + munger.getSignature().getSourceLocation()); if (isVisible(existingMember.getModifiers(), this, munger.getAspectType())) { int c = compareMemberPrecedence(sig, existingMember); //System.err.println(" c: " + c); if (c < 0) { // existingMember dominates munger checkLegalOverride(munger.getSignature(), existingMember); return false; } else if (c > 0) { // munger dominates existingMember checkLegalOverride(existingMember, munger.getSignature()); //interTypeMungers.add(munger); //??? might need list of these overridden abstracts continue; } else { //XXX dual errors possible if (this instanceof BcelObjectType) return false; //XXX ignores separate comp getWorld().getMessageHandler().handleMessage( MessageUtil.error(WeaverMessages.format(WeaverMessages.ITD_MEMBER_CONFLICT,munger.getAspectType().getName(), existingMember), munger.getSourceLocation()) ); } } else { //interTypeMungers.add(munger); } //return; } } return true; } public boolean checkLegalOverride(ResolvedMember parent, ResolvedMember child) { //System.err.println("check: " + child.getDeclaringType() + " overrides " + parent.getDeclaringType()); if (!parent.getReturnType().equals(child.getReturnType())) { world.showMessage(IMessage.ERROR, WeaverMessages.format(WeaverMessages.ITD_RETURN_TYPE_MISMATCH,parent,child), child.getSourceLocation(), parent.getSourceLocation()); return false; } if (parent.getKind() == Member.POINTCUT) { TypeX[] pTypes = parent.getParameterTypes(); TypeX[] cTypes = child.getParameterTypes(); if (!Arrays.equals(pTypes, cTypes)) { world.showMessage(IMessage.ERROR, WeaverMessages.format(WeaverMessages.ITD_PARAM_TYPE_MISMATCH,parent,child), child.getSourceLocation(), parent.getSourceLocation()); return false; } } //System.err.println("check: " + child.getModifiers() + " more visible " + parent.getModifiers()); if (isMoreVisible(parent.getModifiers(), child.getModifiers())) { world.showMessage(IMessage.ERROR, WeaverMessages.format(WeaverMessages.ITD_VISIBILITY_REDUCTION,parent,child), child.getSourceLocation(), parent.getSourceLocation()); return false; } // check declared exceptions ResolvedTypeX[] childExceptions = world.resolve(child.getExceptions()); ResolvedTypeX[] parentExceptions = world.resolve(parent.getExceptions()); ResolvedTypeX runtimeException = world.resolve("java.lang.RuntimeException"); ResolvedTypeX error = world.resolve("java.lang.Error"); outer: for (int i=0, leni = childExceptions.length; i < leni; i++) { //System.err.println("checking: " + childExceptions[i]); if (runtimeException.isAssignableFrom(childExceptions[i])) continue; if (error.isAssignableFrom(childExceptions[i])) continue; for (int j = 0, lenj = parentExceptions.length; j < lenj; j++) { if (parentExceptions[j].isAssignableFrom(childExceptions[i])) continue outer; } world.showMessage(IMessage.ERROR, WeaverMessages.format(WeaverMessages.ITD_DOESNT_THROW,childExceptions[i].getName()), child.getSourceLocation(), null); return false; } if (parent.isStatic() && !child.isStatic()) { world.showMessage(IMessage.ERROR, WeaverMessages.format(WeaverMessages.ITD_OVERRIDDEN_STATIC,child,parent), child.getSourceLocation(),null); } else if (child.isStatic() && !parent.isStatic()) { world.showMessage(IMessage.ERROR, WeaverMessages.format(WeaverMessages.ITD_OVERIDDING_STATIC,child,parent), child.getSourceLocation(),null); } return true; } private int compareMemberPrecedence(ResolvedMember m1, ResolvedMember m2) { //if (!m1.getReturnType().equals(m2.getReturnType())) return 0; if (Modifier.isAbstract(m1.getModifiers())) return -1; if (Modifier.isAbstract(m2.getModifiers())) return +1; if (m1.getDeclaringType().equals(m2.getDeclaringType())) return 0; ResolvedTypeX t1 = m1.getDeclaringType().resolve(world); ResolvedTypeX t2 = m2.getDeclaringType().resolve(world); if (t1.isAssignableFrom(t2)) { return -1; } if (t2.isAssignableFrom(t1)) { return +1; } return 0; } public static boolean isMoreVisible(int m1, int m2) { if (Modifier.isPrivate(m1)) return false; if (isPackage(m1)) return Modifier.isPrivate(m2); if (Modifier.isProtected(m1)) return /* private package */ (Modifier.isPrivate(m2) || isPackage(m2)); if (Modifier.isPublic(m1)) return /* private package protected */ ! Modifier.isPublic(m2); throw new RuntimeException("bad modifier: " + m1); } private static boolean isPackage(int i) { return (0 == (i & (Modifier.PUBLIC | Modifier.PRIVATE | Modifier.PROTECTED))); } private void interTypeConflictError( ConcreteTypeMunger m1, ConcreteTypeMunger m2) { //XXX this works only if we ignore separate compilation issues //XXX dual errors possible if (this instanceof BcelObjectType) return; //System.err.println("conflict at " + m2.getSourceLocation()); getWorld().showMessage(IMessage.ERROR, WeaverMessages.format(WeaverMessages.ITD_CONFLICT,m1.getAspectType().getName(), m2.getSignature(),m2.getAspectType().getName()), m2.getSourceLocation(), getSourceLocation()); } public ResolvedMember lookupSyntheticMember(Member member) { //??? horribly inefficient //for (Iterator i = //System.err.println("lookup " + member + " in " + interTypeMungers); for (Iterator i = interTypeMungers.iterator(); i.hasNext(); ) { ConcreteTypeMunger m = (ConcreteTypeMunger)i.next(); ResolvedMember ret = m.getMatchingSyntheticMember(member); if (ret != null) { //System.err.println(" found: " + ret); return ret; } } return null; } public void clearInterTypeMungers() { interTypeMungers = new ArrayList(); } public boolean isTopmostImplementor(ResolvedTypeX interfaceType) { if (isInterface()) return false; if (!interfaceType.isAssignableFrom(this)) return false; // check that I'm truly the topmost implementor if (interfaceType.isAssignableFrom(this.getSuperclass())) { return false; } return true; } public List getExposedPointcuts() { List ret = new ArrayList(); if (getSuperclass() != null) ret.addAll(getSuperclass().getExposedPointcuts()); for (Iterator i = Arrays.asList(getDeclaredInterfaces()).iterator(); i.hasNext(); ) { ResolvedTypeX t = (ResolvedTypeX)i.next(); addPointcutsResolvingConflicts(ret, Arrays.asList(t.getDeclaredPointcuts()), false); } addPointcutsResolvingConflicts(ret, Arrays.asList(getDeclaredPointcuts()), true); for (Iterator i = ret.iterator(); i.hasNext(); ) { ResolvedPointcutDefinition inherited = (ResolvedPointcutDefinition)i.next(); // System.err.println("looking at: " + inherited + " in " + this); // System.err.println(" " + inherited.isAbstract() + " in " + this.isAbstract()); if (inherited.isAbstract()) { if (!this.isAbstract()) { getWorld().showMessage(IMessage.ERROR, WeaverMessages.format(WeaverMessages.POINCUT_NOT_CONCRETE,inherited,this.getName()), inherited.getSourceLocation(), this.getSourceLocation()); } } } return ret; } private void addPointcutsResolvingConflicts(List acc, List added, boolean isOverriding) { for (Iterator i = added.iterator(); i.hasNext();) { ResolvedPointcutDefinition toAdd = (ResolvedPointcutDefinition) i.next(); //System.err.println("adding: " + toAdd); for (Iterator j = acc.iterator(); j.hasNext();) { ResolvedPointcutDefinition existing = (ResolvedPointcutDefinition) j.next(); if (existing == toAdd) continue; if (!isVisible(existing.getModifiers(), existing.getDeclaringType().resolve(getWorld()), this)) { continue; } if (conflictingSignature(existing, toAdd)) { if (isOverriding) { checkLegalOverride(existing, toAdd); j.remove(); } else { getWorld().showMessage( IMessage.ERROR, WeaverMessages.format(WeaverMessages.CONFLICTING_INHERITED_POINTCUTS,this.getName() + toAdd.getSignature()), existing.getSourceLocation(), toAdd.getSourceLocation()); j.remove(); } } } acc.add(toAdd); } } public ISourceLocation getSourceLocation() { return null; } public boolean isExposedToWeaver() { return false; } public WeaverStateInfo getWeaverState() { return null; } }
44,191
Bug 44191 Need better error message for "can't find type"
I have experienced situations where IAJC outputs a message like this at the end of compilation. [iajc] can't find type org.xxx.SomeTest In my case this was one time highly confusing since I did not expect the class in question to be referred anywhere in the project (I have to date still not located the reference). For such cases, it would be extremely nice if the error message would display WHY it need the class (i.e. the name of the refering class(es) or aspect(es) possibly with a reasonable cutoff as there is seldom need to list all referals). So I would like a message like this: [iajc] can't find type org.xxx.SomeTest referred by org.yyy.SomeClass,org.yy.SomeOtherClass ...
resolved fixed
061395c
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2004-08-06T15:04:45Z
2003-10-04T23:26:40Z
weaver/src/org/aspectj/weaver/bcel/BcelAdvice.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Common Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * PARC initial implementation * ******************************************************************/ package org.aspectj.weaver.bcel; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import org.apache.bcel.generic.InstructionFactory; import org.apache.bcel.generic.InstructionHandle; import org.apache.bcel.generic.InstructionList; import org.aspectj.weaver.Advice; import org.aspectj.weaver.AdviceKind; import org.aspectj.weaver.AjAttribute; import org.aspectj.weaver.BCException; import org.aspectj.weaver.ISourceContext; import org.aspectj.weaver.Member; import org.aspectj.weaver.ResolvedMember; import org.aspectj.weaver.ResolvedTypeX; import org.aspectj.weaver.Shadow; import org.aspectj.weaver.TypeX; 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.Pointcut; /** * Advice implemented for bcel. * * @author Erik Hilsdale * @author Jim Hugunin */ public class BcelAdvice extends Advice { private Test pointcutTest; private ExposedState exposedState; public BcelAdvice( AjAttribute.AdviceAttribute attribute, Pointcut pointcut, Member signature, ResolvedTypeX 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, ResolvedTypeX 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 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 } pointcutTest = getPointcut().findResidue(shadow, exposedState); // 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) { ((BcelShadow)shadow).requireThisJoinPoint(pointcutTest != Literal.TRUE && getKind() != AdviceKind.Around); ((BcelShadow)shadow).getEnclosingClass().warnOnAddedStaticInitializer(shadow,getSourceLocation()); } if ((getExtraParameterFlags() & ThisEnclosingJoinPointStaticPart) != 0) { ((BcelShadow)shadow).getThisEnclosingJoinPointStaticPartVar(); ((BcelShadow)shadow).getEnclosingClass().warnOnAddedStaticInitializer(shadow,getSourceLocation()); } } private boolean canInline(Shadow s) { if (attribute.isProceedInInners()) return false; //XXX this guard seems to only be needed for bad test cases if (concreteAspect == null || concreteAspect == ResolvedTypeX.MISSING) 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) { BcelShadow shadow = (BcelShadow) s; if (getKind() == AdviceKind.Before) { shadow.weaveBefore(this); } else if (getKind() == AdviceKind.AfterReturning) { shadow.weaveAfterReturning(this); } else if (getKind() == AdviceKind.AfterThrowing) { TypeX catchType = hasExtraParameter() ? getExtraParameterType() : TypeX.THROWABLE; shadow.weaveAfterThrowing(this, catchType); } else if (getKind() == AdviceKind.After) { shadow.weaveAfter(this); } else if (getKind() == AdviceKind.Around) { 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 { throw new BCException("unimplemented kind: " + getKind()); } } // ---- implementations private Collection collectCheckedExceptions(TypeX[] excs) { if (excs == null || excs.length == 0) return Collections.EMPTY_LIST; Collection ret = new ArrayList(); World world = concreteAspect.getWorld(); ResolvedTypeX runtimeException = world.resolve(TypeX.RUNTIME_EXCEPTION); ResolvedTypeX error = world.resolve(TypeX.ERROR); for (int i=0, len=excs.length; i < len; i++) { ResolvedTypeX t = world.resolve(excs[i]); 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; } // only call me after prepare has been called public boolean hasDynamicTests() { // if (hasExtraParameter() && getKind() == AdviceKind.AfterReturning) { // TypeX extraParameterType = getExtraParameterType(); // if (! extraParameterType.equals(TypeX.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) { TypeX extraParameterType = getExtraParameterType(); if (! extraParameterType.equals(TypeX.OBJECT) && ! extraParameterType.isPrimitive()) { il.append( BcelRenderer.renderTest( fact, world, Test.makeInstanceof( extraArgVar, getExtraParameterType().resolve(world)), null, ifNoAdvice, null)); } } il.append(getAdviceArgSetup(shadow, extraArgVar, null)); il.append(getNonTestAdviceInstructions(shadow)); InstructionHandle ifYesAdvice = il.getStart(); il.insert(getTestInstructions(shadow, ifYesAdvice, ifNoAdvice, ifYesAdvice)); return il; } public InstructionList getAdviceArgSetup( BcelShadow shadow, BcelVar extraVar, InstructionList closureInstantiation) { InstructionFactory fact = shadow.getFactory(); BcelWorld world = shadow.getWorld(); InstructionList il = new InstructionList(); // if (targetAspectField != null) { // il.append(fact.createFieldAccess( // targetAspectField.getDeclaringType().getName(), // targetAspectField.getName(), // BcelWorld.makeBcelType(targetAspectField.getType()), // Constants.GETSTATIC)); // } // //System.err.println("BcelAdvice: " + exposedState); if (exposedState.getAspectInstance() != null) { il.append( BcelRenderer.renderExpr(fact, world, exposedState.getAspectInstance())); } for (int i = 0, len = exposedState.size(); i < len; i++) { BcelVar v = (BcelVar) exposedState.get(i); if (v == null) continue; TypeX desiredTy = getSignature().getParameterTypes()[i]; v.appendLoadAndConvert(il, fact, desiredTy.resolve(world)); } 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(), getSignature())); } 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().compareByDominates( concreteAspect, o.concreteAspect); if (ret != 0) return ret; ResolvedTypeX declaringAspect = getDeclaringAspect().resolve(world); ResolvedTypeX 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() { //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; } }
44,191
Bug 44191 Need better error message for "can't find type"
I have experienced situations where IAJC outputs a message like this at the end of compilation. [iajc] can't find type org.xxx.SomeTest In my case this was one time highly confusing since I did not expect the class in question to be referred anywhere in the project (I have to date still not located the reference). For such cases, it would be extremely nice if the error message would display WHY it need the class (i.e. the name of the refering class(es) or aspect(es) possibly with a reasonable cutoff as there is seldom need to list all referals). So I would like a message like this: [iajc] can't find type org.xxx.SomeTest referred by org.yyy.SomeClass,org.yy.SomeOtherClass ...
resolved fixed
061395c
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2004-08-06T15:04:45Z
2003-10-04T23:26:40Z
weaver/src/org/aspectj/weaver/bcel/BcelShadow.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Common Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * PARC initial implementation * ******************************************************************/ package org.aspectj.weaver.bcel; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.apache.bcel.Constants; import org.apache.bcel.classfile.Field; import org.apache.bcel.generic.ACONST_NULL; import org.apache.bcel.generic.ArrayType; import org.apache.bcel.generic.BranchInstruction; import org.apache.bcel.generic.ConstantPoolGen; import org.apache.bcel.generic.DUP; import org.apache.bcel.generic.DUP_X1; import org.apache.bcel.generic.FieldInstruction; import org.apache.bcel.generic.INVOKESPECIAL; import org.apache.bcel.generic.INVOKESTATIC; import org.apache.bcel.generic.Instruction; import org.apache.bcel.generic.InstructionConstants; import org.apache.bcel.generic.InstructionFactory; import org.apache.bcel.generic.InstructionHandle; import org.apache.bcel.generic.InstructionList; import org.apache.bcel.generic.InstructionTargeter; import org.apache.bcel.generic.InvokeInstruction; import org.apache.bcel.generic.NEW; import org.apache.bcel.generic.ObjectType; import org.apache.bcel.generic.ReturnInstruction; import org.apache.bcel.generic.SWAP; import org.apache.bcel.generic.StoreInstruction; import org.apache.bcel.generic.TargetLostException; import org.apache.bcel.generic.Type; import org.aspectj.bridge.ISourceLocation; import org.aspectj.weaver.Advice; import org.aspectj.weaver.AdviceKind; import org.aspectj.weaver.AjcMemberMaker; import org.aspectj.weaver.BCException; import org.aspectj.weaver.IntMap; import org.aspectj.weaver.Member; import org.aspectj.weaver.NameMangler; import org.aspectj.weaver.ResolvedMember; import org.aspectj.weaver.ResolvedTypeX; import org.aspectj.weaver.Shadow; import org.aspectj.weaver.ShadowMunger; import org.aspectj.weaver.TypeX; import org.aspectj.weaver.World; import org.aspectj.weaver.ast.Var; /* * Some fun implementation stuff: * * * expressionKind advice is non-execution advice * * may have a target. * * if the body is extracted, it will be extracted into * a static method. The first argument to the static * method is the target * * advice may expose a this object, but that's the advice's * consideration, not ours. This object will NOT be cached in another * local, but will always come from frame zero. * * * non-expressionKind advice is execution advice * * may have a this. * * target is same as this, and is exposed that way to advice * (i.e., target will not be cached, will always come from frame zero) * * if the body is extracted, it will be extracted into a method * with same static/dynamic modifier as enclosing method. If non-static, * target of callback call will be this. * * * because of these two facts, the setup of the actual arguments (including * possible target) callback method is the same for both kinds of advice: * push the targetVar, if it exists (it will not exist for advice on static * things), then push all the argVars. * * Protected things: * * * the above is sufficient for non-expressionKind advice for protected things, * since the target will always be this. * * * For expressionKind things, we have to modify the signature of the callback * method slightly. For non-static expressionKind things, we modify * the first argument of the callback method NOT to be the type specified * by the method/field signature (the owner), but rather we type it to * the currentlyEnclosing type. We are guaranteed this will be fine, * since the verifier verifies that the target is a subtype of the currently * enclosingType. * * Worries: * * * ConstructorCalls will be weirder than all of these, since they * supposedly don't have a target (according to AspectJ), but they clearly * do have a target of sorts, just one that needs to be pushed on the stack, * dupped, and not touched otherwise until the constructor runs. * * @author Jim Hugunin * @author Erik Hilsdale * */ public class BcelShadow extends Shadow { private ShadowRange range; private final BcelWorld world; private final LazyMethodGen enclosingMethod; private boolean fallsThrough; //XXX not used anymore // ---- initialization /** * This generates an unassociated shadow, rooted in a particular method but not rooted * to any particular point in the code. It should be given to a rooted ShadowRange * in the {@link ShadowRange#associateWithShadow(BcelShadow)} method. */ public BcelShadow( BcelWorld world, Kind kind, Member signature, LazyMethodGen enclosingMethod, BcelShadow enclosingShadow) { super(kind, signature, enclosingShadow); this.world = world; this.enclosingMethod = enclosingMethod; fallsThrough = kind.argsOnStack(); } // ---- copies all state, including Shadow's mungers... public BcelShadow copyInto(LazyMethodGen recipient, BcelShadow enclosing) { BcelShadow s = new BcelShadow(world, getKind(), getSignature(), recipient, enclosing); List src = mungers; List dest = s.mungers; for (Iterator i = src.iterator(); i.hasNext(); ) { dest.add(i.next()); } return s; } // ---- overridden behaviour public World getIWorld() { return world; } private void deleteNewAndDup() { final ConstantPoolGen cpg = getEnclosingClass().getConstantPoolGen(); int depth = 1; InstructionHandle ih = range.getStart(); while (true) { Instruction inst = ih.getInstruction(); if (inst instanceof INVOKESPECIAL && ((INVOKESPECIAL) inst).getName(cpg).equals("<init>")) { depth++; } else if (inst instanceof NEW) { depth--; if (depth == 0) break; } ih = ih.getPrev(); } // now IH points to the NEW. We're followed by the DUP, and that is followed // by the actual instruciton we care about. InstructionHandle newHandle = ih; InstructionHandle endHandle = newHandle.getNext(); InstructionHandle nextHandle; if (endHandle.getInstruction() instanceof DUP) { nextHandle = endHandle.getNext(); retargetFrom(newHandle, nextHandle); retargetFrom(endHandle, nextHandle); } else if (endHandle.getInstruction() instanceof DUP_X1) { InstructionHandle dupHandle = endHandle; endHandle = endHandle.getNext(); nextHandle = endHandle.getNext(); if (endHandle.getInstruction() instanceof SWAP) {} else { // XXX see next XXX comment throw new RuntimeException("Unhandled kind of new " + endHandle); } retargetFrom(newHandle, nextHandle); retargetFrom(dupHandle, nextHandle); retargetFrom(endHandle, nextHandle); } else { endHandle = newHandle; nextHandle = endHandle.getNext(); retargetFrom(newHandle, nextHandle); // add a POP here... we found a NEW w/o a dup or anything else, so // we must be in statement context. getRange().insert(InstructionConstants.POP, Range.OutsideAfter); } // assert (dupHandle.getInstruction() instanceof DUP); try { range.getBody().delete(newHandle, endHandle); } catch (TargetLostException e) { throw new BCException("shouldn't happen"); } } private void retargetFrom(InstructionHandle old, InstructionHandle fresh) { InstructionTargeter[] sources = old.getTargeters(); if (sources != null) { for (int i = sources.length - 1; i >= 0; i--) { sources[i].updateTarget(old, fresh); } } } protected void prepareForMungers() { // if we're a constructor call, we need to remove the new:dup or the new:dup_x1:swap, // and store all our // arguments on the frame. // ??? This is a bit of a hack (for the Java langauge). We do this because // we sometime add code "outsideBefore" when dealing with weaving join points. We only // do this for exposing state that is on the stack. It turns out to just work for // everything except for constructor calls and exception handlers. If we were to clean // this up, every ShadowRange would have three instructionHandle points, the start of // the arg-setup code, the start of the running code, and the end of the running code. if (getKind() == ConstructorCall) { deleteNewAndDup(); initializeArgVars(); } else if (getKind() == ExceptionHandler) { ShadowRange range = getRange(); InstructionList body = range.getBody(); InstructionHandle start = range.getStart(); InstructionHandle freshIh = body.insert(start, InstructionConstants.NOP); InstructionTargeter[] targeters = start.getTargeters(); for (int i = 0; i < targeters.length; i++) { InstructionTargeter t = targeters[i]; if (t instanceof ExceptionRange) { ExceptionRange er = (ExceptionRange) t; er.updateTarget(start, freshIh, body); } } } // now we ask each munger to request our state isThisJoinPointLazy = world.isXlazyTjp(); for (Iterator iter = mungers.iterator(); iter.hasNext();) { ShadowMunger munger = (ShadowMunger) iter.next(); munger.specializeOn(this); } initializeThisJoinPoint(); // If we are an expression kind, we require our target/arguments on the stack // before we do our actual thing. However, they may have been removed // from the stack as the shadowMungers have requested state. // if any of our shadowMungers requested either the arguments or target, // the munger will have added code // to pop the target/arguments into temporary variables, represented by // targetVar and argVars. In such a case, we must make sure to re-push the // values. // If we are nonExpressionKind, we don't expect arguments on the stack // so this is moot. If our argVars happen to be null, then we know that // no ShadowMunger has squirrelled away our arguments, so they're still // on the stack. InstructionFactory fact = getFactory(); if (getKind().argsOnStack() && argVars != null) { range.insert( BcelRenderer.renderExprs(fact, world, argVars), Range.InsideBefore); if (targetVar != null) { range.insert( BcelRenderer.renderExpr(fact, world, targetVar), Range.InsideBefore); } if (getKind() == ConstructorCall) { range.insert((Instruction) InstructionFactory.createDup(1), Range.InsideBefore); range.insert( fact.createNew( (ObjectType) BcelWorld.makeBcelType( getSignature().getDeclaringType())), Range.InsideBefore); } } } // ---- getters public ShadowRange getRange() { return range; } public void setRange(ShadowRange range) { this.range = range; } public int getSourceLine() { if (range == null) { if (getEnclosingMethod().hasBody()) { return Utility.getSourceLine(getEnclosingMethod().getBody().getStart()); } else { return 0; } } int ret = Utility.getSourceLine(range.getStart()); if (ret < 0) return 0; return ret; } // overrides public TypeX getEnclosingType() { return getEnclosingClass().getType(); } public LazyClassGen getEnclosingClass() { return enclosingMethod.getEnclosingClass(); } public BcelWorld getWorld() { return world; } // ---- factory methods public static BcelShadow makeConstructorExecution( BcelWorld world, LazyMethodGen enclosingMethod, InstructionHandle justBeforeStart) { final InstructionList body = enclosingMethod.getBody(); BcelShadow s = new BcelShadow( world, ConstructorExecution, world.makeMethodSignature(enclosingMethod), enclosingMethod, null); ShadowRange r = new ShadowRange(body); r.associateWithShadow(s); r.associateWithTargets( Range.genStart(body, justBeforeStart.getNext()), Range.genEnd(body)); return s; } public static BcelShadow makeStaticInitialization( BcelWorld world, LazyMethodGen enclosingMethod) { InstructionList body = enclosingMethod.getBody(); // move the start past ajc$preClinit InstructionHandle clinitStart = body.getStart(); if (clinitStart.getInstruction() instanceof InvokeInstruction) { InvokeInstruction ii = (InvokeInstruction)clinitStart.getInstruction(); if (ii .getName(enclosingMethod.getEnclosingClass().getConstantPoolGen()) .equals(NameMangler.AJC_PRE_CLINIT_NAME)) { clinitStart = clinitStart.getNext(); } } InstructionHandle clinitEnd = body.getEnd(); //XXX should move the end before the postClinit, but the return is then tricky... // if (clinitEnd.getInstruction() instanceof InvokeInstruction) { // InvokeInstruction ii = (InvokeInstruction)clinitEnd.getInstruction(); // if (ii.getName(enclosingMethod.getEnclosingClass().getConstantPoolGen()).equals(NameMangler.AJC_POST_CLINIT_NAME)) { // clinitEnd = clinitEnd.getPrev(); // } // } BcelShadow s = new BcelShadow( world, StaticInitialization, world.makeMethodSignature(enclosingMethod), enclosingMethod, null); ShadowRange r = new ShadowRange(body); r.associateWithShadow(s); r.associateWithTargets( Range.genStart(body, clinitStart), Range.genEnd(body, clinitEnd)); return s; } /** Make the shadow for an exception handler. Currently makes an empty shadow that * only allows before advice to be woven into it. */ public static BcelShadow makeExceptionHandler( BcelWorld world, ExceptionRange exceptionRange, LazyMethodGen enclosingMethod, InstructionHandle startOfHandler, BcelShadow enclosingShadow) { InstructionList body = enclosingMethod.getBody(); TypeX catchType = exceptionRange.getCatchType(); TypeX inType = enclosingMethod.getEnclosingClass().getType(); ResolvedMember sig = Member.makeExceptionHandlerSignature(inType, catchType); sig.parameterNames = new String[] {findHandlerParamName(startOfHandler)}; BcelShadow s = new BcelShadow( world, ExceptionHandler, sig, enclosingMethod, enclosingShadow); ShadowRange r = new ShadowRange(body); r.associateWithShadow(s); InstructionHandle start = Range.genStart(body, startOfHandler); InstructionHandle end = Range.genEnd(body, start); r.associateWithTargets(start, end); exceptionRange.updateTarget(startOfHandler, start, body); return s; } private static String findHandlerParamName(InstructionHandle startOfHandler) { if (startOfHandler.getInstruction() instanceof StoreInstruction && startOfHandler.getNext() != null) { int slot = ((StoreInstruction)startOfHandler.getInstruction()).getIndex(); //System.out.println("got store: " + startOfHandler.getInstruction() + ", " + index); InstructionTargeter[] targeters = startOfHandler.getNext().getTargeters(); if (targeters!=null) { for (int i=targeters.length-1; i >= 0; i--) { if (targeters[i] instanceof LocalVariableTag) { LocalVariableTag t = (LocalVariableTag)targeters[i]; if (t.getSlot() == slot) { return t.getName(); } //System.out.println("tag: " + targeters[i]); } } } } return "<missing>"; } /** create an init join point associated w/ an interface in the body of a constructor */ public static BcelShadow makeIfaceInitialization( BcelWorld world, LazyMethodGen constructor, Member interfaceConstructorSignature) { InstructionList body = constructor.getBody(); // TypeX inType = constructor.getEnclosingClass().getType(); BcelShadow s = new BcelShadow( world, Initialization, interfaceConstructorSignature, constructor, null); s.fallsThrough = true; // ShadowRange r = new ShadowRange(body); // r.associateWithShadow(s); // InstructionHandle start = Range.genStart(body, handle); // InstructionHandle end = Range.genEnd(body, handle); // // r.associateWithTargets(start, end); return s; } public void initIfaceInitializer(InstructionHandle end) { final InstructionList body = enclosingMethod.getBody(); ShadowRange r = new ShadowRange(body); r.associateWithShadow(this); InstructionHandle nop = body.insert(end, InstructionConstants.NOP); r.associateWithTargets( Range.genStart(body, nop), Range.genEnd(body, nop)); } // public static BcelShadow makeIfaceConstructorExecution( // BcelWorld world, // LazyMethodGen constructor, // InstructionHandle next, // Member interfaceConstructorSignature) // { // // final InstructionFactory fact = constructor.getEnclosingClass().getFactory(); // InstructionList body = constructor.getBody(); // // TypeX inType = constructor.getEnclosingClass().getType(); // BcelShadow s = // new BcelShadow( // world, // ConstructorExecution, // interfaceConstructorSignature, // constructor, // null); // s.fallsThrough = true; // ShadowRange r = new ShadowRange(body); // r.associateWithShadow(s); // // ??? this may or may not work // InstructionHandle start = Range.genStart(body, next); // //InstructionHandle end = Range.genEnd(body, body.append(start, fact.NOP)); // InstructionHandle end = Range.genStart(body, next); // //body.append(start, fact.NOP); // // r.associateWithTargets(start, end); // return s; // } /** Create an initialization join point associated with a constructor, but not * with any body of code yet. If this is actually matched, it's range will be set * when we inline self constructors. * * @param constructor The constructor starting this initialization. */ public static BcelShadow makeUnfinishedInitialization( BcelWorld world, LazyMethodGen constructor) { return new BcelShadow( world, Initialization, world.makeMethodSignature(constructor), constructor, null); } public static BcelShadow makeUnfinishedPreinitialization( BcelWorld world, LazyMethodGen constructor) { BcelShadow ret = new BcelShadow( world, PreInitialization, world.makeMethodSignature(constructor), constructor, null); ret.fallsThrough = true; return ret; } public static BcelShadow makeMethodExecution( BcelWorld world, LazyMethodGen enclosingMethod, boolean lazyInit) { if (!lazyInit) return makeMethodExecution(world, enclosingMethod); BcelShadow s = new BcelShadow( world, MethodExecution, enclosingMethod.getMemberView(), enclosingMethod, null); return s; } public void init() { if (range != null) return; final InstructionList body = enclosingMethod.getBody(); ShadowRange r = new ShadowRange(body); r.associateWithShadow(this); r.associateWithTargets( Range.genStart(body), Range.genEnd(body)); } public static BcelShadow makeMethodExecution( BcelWorld world, LazyMethodGen enclosingMethod) { return makeShadowForMethod(world, enclosingMethod, MethodExecution, enclosingMethod.getMemberView()); //world.makeMethodSignature(enclosingMethod)); } public static BcelShadow makeShadowForMethod(BcelWorld world, LazyMethodGen enclosingMethod, Shadow.Kind kind, Member sig) { final InstructionList body = enclosingMethod.getBody(); BcelShadow s = new BcelShadow( world, kind, sig, enclosingMethod, null); ShadowRange r = new ShadowRange(body); r.associateWithShadow(s); r.associateWithTargets( Range.genStart(body), Range.genEnd(body)); return s; } public static BcelShadow makeAdviceExecution( BcelWorld world, LazyMethodGen enclosingMethod) { final InstructionList body = enclosingMethod.getBody(); BcelShadow s = new BcelShadow( world, AdviceExecution, world.makeMethodSignature(enclosingMethod, Member.ADVICE), enclosingMethod, null); ShadowRange r = new ShadowRange(body); r.associateWithShadow(s); r.associateWithTargets(Range.genStart(body), Range.genEnd(body)); return s; } // constructor call shadows are <em>initially</em> just around the // call to the constructor. If ANY advice gets put on it, we move // the NEW instruction inside the join point, which involves putting // all the arguments in temps. public static BcelShadow makeConstructorCall( BcelWorld world, LazyMethodGen enclosingMethod, InstructionHandle callHandle, BcelShadow enclosingShadow) { final InstructionList body = enclosingMethod.getBody(); Member sig = BcelWorld.makeMethodSignature( enclosingMethod.getEnclosingClass(), (InvokeInstruction) callHandle.getInstruction()); BcelShadow s = new BcelShadow( world, ConstructorCall, sig, enclosingMethod, enclosingShadow); ShadowRange r = new ShadowRange(body); r.associateWithShadow(s); r.associateWithTargets( Range.genStart(body, callHandle), Range.genEnd(body, callHandle)); retargetAllBranches(callHandle, r.getStart()); return s; } public static BcelShadow makeMethodCall( BcelWorld world, LazyMethodGen enclosingMethod, InstructionHandle callHandle, BcelShadow enclosingShadow) { final InstructionList body = enclosingMethod.getBody(); BcelShadow s = new BcelShadow( world, MethodCall, BcelWorld.makeMethodSignature( enclosingMethod.getEnclosingClass(), (InvokeInstruction) callHandle.getInstruction()), enclosingMethod, enclosingShadow); ShadowRange r = new ShadowRange(body); r.associateWithShadow(s); r.associateWithTargets( Range.genStart(body, callHandle), Range.genEnd(body, callHandle)); retargetAllBranches(callHandle, r.getStart()); return s; } public static BcelShadow makeShadowForMethodCall( BcelWorld world, LazyMethodGen enclosingMethod, InstructionHandle callHandle, BcelShadow enclosingShadow, Kind kind, ResolvedMember sig) { final InstructionList body = enclosingMethod.getBody(); BcelShadow s = new BcelShadow( world, kind, sig, enclosingMethod, enclosingShadow); ShadowRange r = new ShadowRange(body); r.associateWithShadow(s); r.associateWithTargets( Range.genStart(body, callHandle), Range.genEnd(body, callHandle)); retargetAllBranches(callHandle, r.getStart()); return s; } public static BcelShadow makeFieldGet( BcelWorld world, LazyMethodGen enclosingMethod, InstructionHandle getHandle, BcelShadow enclosingShadow) { final InstructionList body = enclosingMethod.getBody(); BcelShadow s = new BcelShadow( world, FieldGet, BcelWorld.makeFieldSignature( enclosingMethod.getEnclosingClass(), (FieldInstruction) getHandle.getInstruction()), enclosingMethod, enclosingShadow); ShadowRange r = new ShadowRange(body); r.associateWithShadow(s); r.associateWithTargets( Range.genStart(body, getHandle), Range.genEnd(body, getHandle)); retargetAllBranches(getHandle, r.getStart()); return s; } public static BcelShadow makeFieldSet( BcelWorld world, LazyMethodGen enclosingMethod, InstructionHandle setHandle, BcelShadow enclosingShadow) { final InstructionList body = enclosingMethod.getBody(); BcelShadow s = new BcelShadow( world, FieldSet, BcelWorld.makeFieldSignature( enclosingMethod.getEnclosingClass(), (FieldInstruction) setHandle.getInstruction()), enclosingMethod, enclosingShadow); ShadowRange r = new ShadowRange(body); r.associateWithShadow(s); r.associateWithTargets( Range.genStart(body, setHandle), Range.genEnd(body, setHandle)); retargetAllBranches(setHandle, r.getStart()); return s; } public static void retargetAllBranches(InstructionHandle from, InstructionHandle to) { InstructionTargeter[] sources = from.getTargeters(); if (sources != null) { for (int i = sources.length - 1; i >= 0; i--) { InstructionTargeter source = sources[i]; if (source instanceof BranchInstruction) { source.updateTarget(from, to); } } } } // // ---- type access methods // private ObjectType getTargetBcelType() { // return (ObjectType) BcelWorld.makeBcelType(getTargetType()); // } // private Type getArgBcelType(int arg) { // return BcelWorld.makeBcelType(getArgType(arg)); // } // ---- kinding /** * If the end of my range has no real instructions following then * my context needs a return at the end. */ public boolean terminatesWithReturn() { return getRange().getRealNext() == null; } /** * Is arg0 occupied with the value of this */ public boolean arg0HoldsThis() { if (getKind().isEnclosingKind()) { return !getSignature().isStatic(); } else if (enclosingShadow == null) { //XXX this is mostly right // this doesn't do the right thing for calls in the pre part of introduced constructors. return !enclosingMethod.isStatic(); } else { return ((BcelShadow)enclosingShadow).arg0HoldsThis(); } } // ---- argument getting methods private BcelVar thisVar = null; private BcelVar targetVar = null; private BcelVar[] argVars = null; public Var getThisVar() { if (!hasThis()) { throw new IllegalStateException("no this"); } initializeThisVar(); return thisVar; } public Var getTargetVar() { if (!hasTarget()) { throw new IllegalStateException("no target"); } initializeTargetVar(); return targetVar; } public Var getArgVar(int i) { initializeArgVars(); return argVars[i]; } // reflective thisJoinPoint support private BcelVar thisJoinPointVar = null; private boolean isThisJoinPointLazy; private int lazyTjpConsumers = 0; private BcelVar thisJoinPointStaticPartVar = null; // private BcelVar thisEnclosingJoinPointStaticPartVar = null; public final Var getThisJoinPointStaticPartVar() { return getThisJoinPointStaticPartBcelVar(); } public final Var getThisEnclosingJoinPointStaticPartVar() { return getThisEnclosingJoinPointStaticPartBcelVar(); } public void requireThisJoinPoint(boolean hasGuardTest) { if (!hasGuardTest) { isThisJoinPointLazy = false; } else { lazyTjpConsumers++; } if (thisJoinPointVar == null) { thisJoinPointVar = genTempVar(TypeX.forName("org.aspectj.lang.JoinPoint")); } } public Var getThisJoinPointVar() { requireThisJoinPoint(false); return thisJoinPointVar; } void initializeThisJoinPoint() { if (thisJoinPointVar == null) return; if (isThisJoinPointLazy) { isThisJoinPointLazy = checkLazyTjp(); } if (isThisJoinPointLazy) { createThisJoinPoint(); // make sure any state needed is initialized, but throw the instructions out if (lazyTjpConsumers == 1) return; // special case only one lazyTjpUser InstructionFactory fact = getFactory(); InstructionList il = new InstructionList(); il.append(InstructionConstants.ACONST_NULL); il.append(thisJoinPointVar.createStore(fact)); range.insert(il, Range.OutsideBefore); } else { InstructionFactory fact = getFactory(); InstructionList il = createThisJoinPoint(); il.append(thisJoinPointVar.createStore(fact)); range.insert(il, Range.OutsideBefore); } } private boolean checkLazyTjp() { // check for around advice for (Iterator i = mungers.iterator(); i.hasNext();) { ShadowMunger munger = (ShadowMunger) i.next(); if (munger instanceof Advice) { if ( ((Advice)munger).getKind() == AdviceKind.Around) { world.getLint().canNotImplementLazyTjp.signal( new String[] {toString()}, getSourceLocation(), new ISourceLocation[] { munger.getSourceLocation() } ); return false; } } } return true; } InstructionList loadThisJoinPoint() { InstructionFactory fact = getFactory(); InstructionList il = new InstructionList(); if (isThisJoinPointLazy) { il.append(createThisJoinPoint()); if (lazyTjpConsumers > 1) { il.append(thisJoinPointVar.createStore(fact)); InstructionHandle end = il.append(thisJoinPointVar.createLoad(fact)); il.insert(InstructionFactory.createBranchInstruction(Constants.IFNONNULL, end)); il.insert(thisJoinPointVar.createLoad(fact)); } } else { thisJoinPointVar.appendLoad(il, fact); } return il; } InstructionList createThisJoinPoint() { InstructionFactory fact = getFactory(); InstructionList il = new InstructionList(); BcelVar staticPart = getThisJoinPointStaticPartBcelVar(); staticPart.appendLoad(il, fact); if (hasThis()) { ((BcelVar)getThisVar()).appendLoad(il, fact); } else { il.append(new ACONST_NULL()); } if (hasTarget()) { ((BcelVar)getTargetVar()).appendLoad(il, fact); } else { il.append(new ACONST_NULL()); } switch(getArgCount()) { case 0: il.append(fact.createInvoke("org.aspectj.runtime.reflect.Factory", "makeJP", LazyClassGen.tjpType, new Type[] { LazyClassGen.staticTjpType, Type.OBJECT, Type.OBJECT}, Constants.INVOKESTATIC)); break; case 1: ((BcelVar)getArgVar(0)).appendLoadAndConvert(il, fact, world.resolve(ResolvedTypeX.OBJECT)); il.append(fact.createInvoke("org.aspectj.runtime.reflect.Factory", "makeJP", LazyClassGen.tjpType, new Type[] { LazyClassGen.staticTjpType, Type.OBJECT, Type.OBJECT, Type.OBJECT}, Constants.INVOKESTATIC)); break; case 2: ((BcelVar)getArgVar(0)).appendLoadAndConvert(il, fact, world.resolve(ResolvedTypeX.OBJECT)); ((BcelVar)getArgVar(1)).appendLoadAndConvert(il, fact, world.resolve(ResolvedTypeX.OBJECT)); il.append(fact.createInvoke("org.aspectj.runtime.reflect.Factory", "makeJP", LazyClassGen.tjpType, new Type[] { LazyClassGen.staticTjpType, Type.OBJECT, Type.OBJECT, Type.OBJECT, Type.OBJECT}, Constants.INVOKESTATIC)); break; default: il.append(makeArgsObjectArray()); il.append(fact.createInvoke("org.aspectj.runtime.reflect.Factory", "makeJP", LazyClassGen.tjpType, new Type[] { LazyClassGen.staticTjpType, Type.OBJECT, Type.OBJECT, new ArrayType(Type.OBJECT, 1)}, Constants.INVOKESTATIC)); break; } return il; } public BcelVar getThisJoinPointStaticPartBcelVar() { if (thisJoinPointStaticPartVar == null) { Field field = getEnclosingClass().getTjpField(this); thisJoinPointStaticPartVar = new BcelFieldRef( world.resolve(TypeX.forName("org.aspectj.lang.JoinPoint$StaticPart")), getEnclosingClass().getClassName(), field.getName()); // getEnclosingClass().warnOnAddedStaticInitializer(this,munger.getSourceLocation()); } return thisJoinPointStaticPartVar; } public BcelVar getThisEnclosingJoinPointStaticPartBcelVar() { if (enclosingShadow == null) { // the enclosing of an execution is itself return getThisJoinPointStaticPartBcelVar(); } else { return ((BcelShadow)enclosingShadow).getThisJoinPointStaticPartBcelVar(); } } //??? need to better understand all the enclosing variants public Member getEnclosingCodeSignature() { if (getKind().isEnclosingKind()) { return getSignature(); } else if (getKind() == Shadow.PreInitialization) { // PreInit doesn't enclose code but its signature // is correctly the signature of the ctor. return getSignature(); } else if (enclosingShadow == null) { return getEnclosingMethod().getMemberView(); } else { return enclosingShadow.getSignature(); } } private InstructionList makeArgsObjectArray() { InstructionFactory fact = getFactory(); BcelVar arrayVar = genTempVar(TypeX.OBJECTARRAY); final InstructionList il = new InstructionList(); int alen = getArgCount() ; il.append(Utility.createConstant(fact, alen)); il.append((Instruction)fact.createNewArray(Type.OBJECT, (short)1)); arrayVar.appendStore(il, fact); int stateIndex = 0; for (int i = 0, len = getArgCount(); i<len; i++) { arrayVar.appendConvertableArrayStore(il, fact, stateIndex, (BcelVar)getArgVar(i)); stateIndex++; } arrayVar.appendLoad(il, fact); return il; } // ---- initializing var tables /* initializing this is doesn't do anything, because this * is protected from side-effects, so we don't need to copy its location */ private void initializeThisVar() { if (thisVar != null) return; thisVar = new BcelVar(getThisType().resolve(world), 0); thisVar.setPositionInAroundState(0); } public void initializeTargetVar() { InstructionFactory fact = getFactory(); if (targetVar != null) return; if (getKind().isTargetSameAsThis()) { if (hasThis()) initializeThisVar(); targetVar = thisVar; } else { initializeArgVars(); // gotta pop off the args before we find the target TypeX type = getTargetType(); targetVar = genTempVar(type, "ajc$target"); range.insert(targetVar.createStore(fact), Range.OutsideBefore); targetVar.setPositionInAroundState(hasThis() ? 1 : 0); } } public void initializeArgVars() { if (argVars != null) return; InstructionFactory fact = getFactory(); int len = getArgCount(); argVars = new BcelVar[len]; int positionOffset = (hasTarget() ? 1 : 0) + ((hasThis() && !getKind().isTargetSameAsThis()) ? 1 : 0); if (getKind().argsOnStack()) { // we move backwards because we're popping off the stack for (int i = len - 1; i >= 0; i--) { TypeX type = getArgType(i); BcelVar tmp = genTempVar(type, "ajc$arg" + i); range.insert(tmp.createStore(getFactory()), Range.OutsideBefore); int position = i; position += positionOffset; tmp.setPositionInAroundState(position); argVars[i] = tmp; } } else { int index = 0; if (arg0HoldsThis()) index++; for (int i = 0; i < len; i++) { TypeX type = getArgType(i); BcelVar tmp = genTempVar(type, "ajc$arg" + i); range.insert(tmp.createCopyFrom(fact, index), Range.OutsideBefore); argVars[i] = tmp; int position = i; position += positionOffset; // System.out.println("set position: " + tmp + ", " + position + " in " + this); // System.out.println(" hasThis: " + hasThis() + ", hasTarget: " + hasTarget()); tmp.setPositionInAroundState(position); index += type.getSize(); } } } public void initializeForAroundClosure() { initializeArgVars(); if (hasTarget()) initializeTargetVar(); if (hasThis()) initializeThisVar(); // System.out.println("initialized: " + this + " thisVar = " + thisVar); } // ---- weave methods void weaveBefore(BcelAdvice munger) { range.insert( munger.getAdviceInstructions(this, null, range.getRealStart()), Range.InsideBefore); } public void weaveAfter(BcelAdvice munger) { weaveAfterThrowing(munger, TypeX.THROWABLE); weaveAfterReturning(munger); } /** * We guarantee that the return value is on the top of the stack when * munger.getAdviceInstructions() will be run * (Unless we have a void return type in which case there's nothing) */ public void weaveAfterReturning(BcelAdvice munger) { // InstructionFactory fact = getFactory(); List returns = new ArrayList(); Instruction ret = null; for (InstructionHandle ih = range.getStart(); ih != range.getEnd(); ih = ih.getNext()) { if (ih.getInstruction() instanceof ReturnInstruction) { returns.add(ih); ret = Utility.copyInstruction(ih.getInstruction()); } } InstructionList retList; InstructionHandle afterAdvice; if (ret != null) { retList = new InstructionList(ret); afterAdvice = retList.getStart(); } else /* if (munger.hasDynamicTests()) */ { retList = new InstructionList(InstructionConstants.NOP); afterAdvice = retList.getStart(); // } else { // retList = new InstructionList(); // afterAdvice = null; } InstructionList advice = new InstructionList(); BcelVar tempVar = null; if (munger.hasExtraParameter()) { TypeX tempVarType = getReturnType(); if (tempVarType.equals(ResolvedTypeX.VOID)) { tempVar = genTempVar(TypeX.OBJECT); advice.append(InstructionConstants.ACONST_NULL); tempVar.appendStore(advice, getFactory()); } else { tempVar = genTempVar(tempVarType); advice.append(InstructionFactory.createDup(tempVarType.getSize())); tempVar.appendStore(advice, getFactory()); } } advice.append(munger.getAdviceInstructions(this, tempVar, afterAdvice)); if (ret != null) { InstructionHandle gotoTarget = advice.getStart(); for (Iterator i = returns.iterator(); i.hasNext();) { InstructionHandle ih = (InstructionHandle) i.next(); Utility.replaceInstruction( ih, InstructionFactory.createBranchInstruction( Constants.GOTO, gotoTarget), enclosingMethod); } range.append(advice); range.append(retList); } else { range.append(advice); range.append(retList); } } public void weaveAfterThrowing(BcelAdvice munger, TypeX catchType) { // a good optimization would be not to generate anything here // if the shadow is GUARANTEED empty (i.e., there's NOTHING, not even // a shadow, inside me). if (getRange().getStart().getNext() == getRange().getEnd()) return; InstructionFactory fact = getFactory(); InstructionList handler = new InstructionList(); BcelVar exceptionVar = genTempVar(catchType); exceptionVar.appendStore(handler, fact); InstructionList endHandler = new InstructionList( exceptionVar.createLoad(fact)); handler.append(munger.getAdviceInstructions(this, exceptionVar, endHandler.getStart())); handler.append(endHandler); handler.append(InstructionConstants.ATHROW); InstructionHandle handlerStart = handler.getStart(); if (isFallsThrough()) { InstructionHandle jumpTarget = handler.append(InstructionConstants.NOP); handler.insert(InstructionFactory.createBranchInstruction(Constants.GOTO, jumpTarget)); } InstructionHandle protectedEnd = handler.getStart(); range.insert(handler, Range.InsideAfter); enclosingMethod.addExceptionHandler(range.getStart().getNext(), protectedEnd.getPrev(), handlerStart, (ObjectType)BcelWorld.makeBcelType(catchType), //???Type.THROWABLE, // high priority if our args are on the stack getKind().hasHighPriorityExceptions()); } //??? this shares a lot of code with the above weaveAfterThrowing //??? would be nice to abstract that to say things only once public void weaveSoftener(BcelAdvice munger, TypeX catchType) { // a good optimization would be not to generate anything here // if the shadow is GUARANTEED empty (i.e., there's NOTHING, not even // a shadow, inside me). if (getRange().getStart().getNext() == getRange().getEnd()) return; InstructionFactory fact = getFactory(); InstructionList handler = new InstructionList(); BcelVar exceptionVar = genTempVar(catchType); exceptionVar.appendStore(handler, fact); // ENH 42743 suggests that we don't soften runtime exceptions. // To implement that, would need to add instructions into the handler // stream here to test if exceptionVar is an instanceof RuntimeException, // and if it is, just re-throw it without softening. // (Not yet implemented obviously). handler.append(fact.createNew(NameMangler.SOFT_EXCEPTION_TYPE)); handler.append(InstructionFactory.createDup(1)); handler.append(exceptionVar.createLoad(fact)); handler.append(fact.createInvoke(NameMangler.SOFT_EXCEPTION_TYPE, "<init>", Type.VOID, new Type[] { Type.THROWABLE }, Constants.INVOKESPECIAL)); //??? special handler.append(InstructionConstants.ATHROW); InstructionHandle handlerStart = handler.getStart(); if (isFallsThrough()) { InstructionHandle jumpTarget = range.getEnd();//handler.append(fact.NOP); handler.insert(InstructionFactory.createBranchInstruction(Constants.GOTO, jumpTarget)); } InstructionHandle protectedEnd = handler.getStart(); range.insert(handler, Range.InsideAfter); enclosingMethod.addExceptionHandler(range.getStart().getNext(), protectedEnd.getPrev(), handlerStart, (ObjectType)BcelWorld.makeBcelType(catchType), // high priority if our args are on the stack getKind().hasHighPriorityExceptions()); } public void weavePerObjectEntry(final BcelAdvice munger, final BcelVar onVar) { final InstructionFactory fact = getFactory(); InstructionList entryInstructions = new InstructionList(); InstructionList entrySuccessInstructions = new InstructionList(); onVar.appendLoad(entrySuccessInstructions, fact); entrySuccessInstructions.append( Utility.createInvoke(fact, world, AjcMemberMaker.perObjectBind(munger.getConcreteAspect()))); InstructionList testInstructions = munger.getTestInstructions(this, entrySuccessInstructions.getStart(), range.getRealStart(), entrySuccessInstructions.getStart()); entryInstructions.append(testInstructions); entryInstructions.append(entrySuccessInstructions); range.insert(entryInstructions, Range.InsideBefore); } public void weaveCflowEntry(final BcelAdvice munger, final Member cflowStackField) { final boolean isPer = munger.getKind() == AdviceKind.PerCflowBelowEntry || munger.getKind() == AdviceKind.PerCflowEntry; final Type objectArrayType = new ArrayType(Type.OBJECT, 1); final InstructionFactory fact = getFactory(); final BcelVar testResult = genTempVar(ResolvedTypeX.BOOLEAN); InstructionList entryInstructions = new InstructionList(); { InstructionList entrySuccessInstructions = new InstructionList(); if (munger.hasDynamicTests()) { entryInstructions.append(Utility.createConstant(fact, 0)); testResult.appendStore(entryInstructions, fact); entrySuccessInstructions.append(Utility.createConstant(fact, 1)); testResult.appendStore(entrySuccessInstructions, fact); } if (isPer) { entrySuccessInstructions.append( fact.createInvoke(munger.getConcreteAspect().getName(), NameMangler.PERCFLOW_PUSH_METHOD, Type.VOID, new Type[] { }, Constants.INVOKESTATIC)); } else { BcelVar[] cflowStateVars = munger.getExposedStateAsBcelVars(); BcelVar arrayVar = genTempVar(TypeX.OBJECTARRAY); int alen = cflowStateVars.length; entrySuccessInstructions.append(Utility.createConstant(fact, alen)); entrySuccessInstructions.append( (Instruction) fact.createNewArray(Type.OBJECT, (short) 1)); arrayVar.appendStore(entrySuccessInstructions, fact); for (int i = 0; i < alen; i++) { arrayVar.appendConvertableArrayStore( entrySuccessInstructions, fact, i, cflowStateVars[i]); } entrySuccessInstructions.append( Utility.createGet(fact, cflowStackField)); arrayVar.appendLoad(entrySuccessInstructions, fact); entrySuccessInstructions.append( fact.createInvoke(NameMangler.CFLOW_STACK_TYPE, "push", Type.VOID, new Type[] { objectArrayType }, Constants.INVOKEVIRTUAL)); } InstructionList testInstructions = munger.getTestInstructions(this, entrySuccessInstructions.getStart(), range.getRealStart(), entrySuccessInstructions.getStart()); entryInstructions.append(testInstructions); entryInstructions.append(entrySuccessInstructions); } // this is the same for both per and non-per weaveAfter(new BcelAdvice(null, null, null, 0, 0, 0, null, null) { public InstructionList getAdviceInstructions( BcelShadow s, BcelVar extraArgVar, InstructionHandle ifNoAdvice) { InstructionList exitInstructions = new InstructionList(); if (munger.hasDynamicTests()) { testResult.appendLoad(exitInstructions, fact); exitInstructions.append( InstructionFactory.createBranchInstruction( Constants.IFEQ, ifNoAdvice)); } exitInstructions.append(Utility.createGet(fact, cflowStackField)); exitInstructions .append( fact .createInvoke( NameMangler.CFLOW_STACK_TYPE, "pop", Type.VOID, new Type[] { }, Constants.INVOKEVIRTUAL)); return exitInstructions; } }); range.insert(entryInstructions, Range.InsideBefore); } public void weaveAroundInline( BcelAdvice munger, boolean hasDynamicTest) { /* Implementation notes: * * AroundInline still extracts the instructions of the original shadow into * an extracted method. This allows inlining of even that advice that doesn't * call proceed or calls proceed more than once. * * It extracts the instructions of the original shadow into a method. * * Then it extracts the instructions of the advice into a new method defined on * this enclosing class. This new method can then be specialized as below. * * Then it searches in the instructions of the advice for any call to the * proceed method. * * At such a call, there is stuff on the stack representing the arguments to * proceed. Pop these into the frame. * * Now build the stack for the call to the extracted method, taking values * either from the join point state or from the new frame locs from proceed. * Now call the extracted method. The right return value should be on the * stack, so no cast is necessary. * * If only one call to proceed is made, we can re-inline the original shadow. * We are not doing that presently. * * If the body of the advice can be determined to not alter the stack, or if * this shadow doesn't care about the stack, i.e. method-execution, then the * new method for the advice can also be re-lined. We are not doing that * presently. */ // !!! THIS BLOCK OF CODE SHOULD BE IN A METHOD CALLED weaveAround(...); Member mungerSig = munger.getSignature(); ResolvedTypeX declaringType = world.resolve(mungerSig.getDeclaringType()); //??? might want some checks here to give better errors BcelObjectType ot = BcelWorld.getBcelObjectType(declaringType); LazyMethodGen adviceMethod = ot.getLazyClassGen().getLazyMethodGen(mungerSig); if (!adviceMethod.getCanInline()) { weaveAroundClosure(munger, hasDynamicTest); return; } // We can't inline around methods if they have around advice on them, this // is because the weaving will extract the body and hence the proceed call. //??? should consider optimizations to recognize simple cases that don't require body extraction enclosingMethod.setCanInline(false); // start by exposing various useful things into the frame final InstructionFactory fact = getFactory(); // now generate the aroundBody method LazyMethodGen extractedMethod = extractMethod( NameMangler.aroundCallbackMethodName( getSignature(), getEnclosingClass()), Modifier.PRIVATE, munger); // now extract the advice into its own method String adviceMethodName = NameMangler.aroundCallbackMethodName( getSignature(), getEnclosingClass()) + "$advice"; List argVarList = new ArrayList(); List proceedVarList = new ArrayList(); int extraParamOffset = 0; // Create the extra parameters that are needed for passing to proceed // This code is very similar to that found in makeCallToCallback and should // be rationalized in the future if (thisVar != null) { argVarList.add(thisVar); proceedVarList.add(new BcelVar(thisVar.getType(), extraParamOffset)); extraParamOffset += thisVar.getType().getSize(); } if (targetVar != null && targetVar != thisVar) { argVarList.add(targetVar); proceedVarList.add(new BcelVar(targetVar.getType(), extraParamOffset)); extraParamOffset += targetVar.getType().getSize(); } for (int i = 0, len = getArgCount(); i < len; i++) { argVarList.add(argVars[i]); proceedVarList.add(new BcelVar(argVars[i].getType(), extraParamOffset)); extraParamOffset += argVars[i].getType().getSize(); } if (thisJoinPointVar != null) { argVarList.add(thisJoinPointVar); proceedVarList.add(new BcelVar(thisJoinPointVar.getType(), extraParamOffset)); extraParamOffset += thisJoinPointVar.getType().getSize(); } Type[] adviceParameterTypes = adviceMethod.getArgumentTypes(); Type[] extractedMethodParameterTypes = extractedMethod.getArgumentTypes(); Type[] parameterTypes = new Type[extractedMethodParameterTypes.length + adviceParameterTypes.length + 1]; int parameterIndex = 0; System.arraycopy( extractedMethodParameterTypes, 0, parameterTypes, parameterIndex, extractedMethodParameterTypes.length); parameterIndex += extractedMethodParameterTypes.length; parameterTypes[parameterIndex++] = BcelWorld.makeBcelType(adviceMethod.getEnclosingClass().getType()); System.arraycopy( adviceParameterTypes, 0, parameterTypes, parameterIndex, adviceParameterTypes.length); LazyMethodGen localAdviceMethod = new LazyMethodGen( Modifier.PRIVATE | Modifier.FINAL | Modifier.STATIC, adviceMethod.getReturnType(), adviceMethodName, parameterTypes, new String[0], getEnclosingClass()); String donorFileName = adviceMethod.getEnclosingClass().getInternalFileName(); String recipientFileName = getEnclosingClass().getInternalFileName(); // System.err.println("donor " + donorFileName); // System.err.println("recip " + recipientFileName); if (! donorFileName.equals(recipientFileName)) { localAdviceMethod.fromFilename = donorFileName; getEnclosingClass().addInlinedSourceFileInfo( donorFileName, adviceMethod.highestLineNumber); } getEnclosingClass().addMethodGen(localAdviceMethod); // create a map that will move all slots in advice method forward by extraParamOffset // in order to make room for the new proceed-required arguments that are added at // the beginning of the parameter list int nVars = adviceMethod.getMaxLocals() + extraParamOffset; IntMap varMap = IntMap.idMap(nVars); for (int i=extraParamOffset; i < nVars; i++) { varMap.put(i-extraParamOffset, i); } localAdviceMethod.getBody().insert( BcelClassWeaver.genInlineInstructions(adviceMethod, localAdviceMethod, varMap, fact, true)); localAdviceMethod.setMaxLocals(nVars); //System.err.println(localAdviceMethod); // the shadow is now empty. First, create a correct call // to the around advice. This includes both the call (which may involve // value conversion of the advice arguments) and the return // (which may involve value conversion of the return value). Right now // we push a null for the unused closure. It's sad, but there it is. InstructionList advice = new InstructionList(); // InstructionHandle adviceMethodInvocation; { for (Iterator i = argVarList.iterator(); i.hasNext(); ) { BcelVar var = (BcelVar)i.next(); var.appendLoad(advice, fact); } // ??? we don't actually need to push NULL for the closure if we take care advice.append( munger.getAdviceArgSetup( this, null, new InstructionList(InstructionConstants.ACONST_NULL))); // adviceMethodInvocation = advice.append( Utility.createInvoke(fact, localAdviceMethod)); //(fact, getWorld(), munger.getSignature())); advice.append( Utility.createConversion( getFactory(), BcelWorld.makeBcelType(munger.getSignature().getReturnType()), extractedMethod.getReturnType())); if (! isFallsThrough()) { advice.append(InstructionFactory.createReturn(extractedMethod.getReturnType())); } } // now, situate the call inside the possible dynamic tests, // and actually add the whole mess to the shadow if (! hasDynamicTest) { range.append(advice); } else { InstructionList afterThingie = new InstructionList(InstructionConstants.NOP); InstructionList callback = makeCallToCallback(extractedMethod); if (terminatesWithReturn()) { callback.append( InstructionFactory.createReturn(extractedMethod.getReturnType())); } else { //InstructionHandle endNop = range.insert(fact.NOP, Range.InsideAfter); advice.append( InstructionFactory.createBranchInstruction( Constants.GOTO, afterThingie.getStart())); } range.append( munger.getTestInstructions( this, advice.getStart(), callback.getStart(), advice.getStart())); range.append(advice); range.append(callback); range.append(afterThingie); } // now search through the advice, looking for a call to PROCEED. // Then we replace the call to proceed with some argument setup, and a // call to the extracted method. String proceedName = NameMangler.proceedMethodName(munger.getSignature().getName()); InstructionHandle curr = localAdviceMethod.getBody().getStart(); InstructionHandle end = localAdviceMethod.getBody().getEnd(); ConstantPoolGen cpg = localAdviceMethod.getEnclosingClass().getConstantPoolGen(); while (curr != end) { InstructionHandle next = curr.getNext(); Instruction inst = curr.getInstruction(); if ((inst instanceof INVOKESTATIC) && proceedName.equals(((INVOKESTATIC) inst).getMethodName(cpg))) { localAdviceMethod.getBody().append( curr, getRedoneProceedCall( fact, extractedMethod, munger, localAdviceMethod, proceedVarList)); Utility.deleteInstruction(curr, localAdviceMethod); } curr = next; } // and that's it. } private InstructionList getRedoneProceedCall( InstructionFactory fact, LazyMethodGen callbackMethod, BcelAdvice munger, LazyMethodGen localAdviceMethod, List argVarList) { InstructionList ret = new InstructionList(); // we have on stack all the arguments for the ADVICE call. // we have in frame somewhere all the arguments for the non-advice call. BcelVar[] adviceVars = munger.getExposedStateAsBcelVars(); IntMap proceedMap = makeProceedArgumentMap(adviceVars); // System.out.println(proceedMap + " for " + this); // System.out.println(argVarList); ResolvedTypeX[] proceedParamTypes = world.resolve(munger.getSignature().getParameterTypes()); // remove this*JoinPoint* as arguments to proceed if (munger.getBaseParameterCount()+1 < proceedParamTypes.length) { int len = munger.getBaseParameterCount()+1; ResolvedTypeX[] newTypes = new ResolvedTypeX[len]; System.arraycopy(proceedParamTypes, 0, newTypes, 0, len); proceedParamTypes = newTypes; } //System.out.println("stateTypes: " + Arrays.asList(stateTypes)); BcelVar[] proceedVars = Utility.pushAndReturnArrayOfVars(proceedParamTypes, ret, fact, localAdviceMethod); Type[] stateTypes = callbackMethod.getArgumentTypes(); // System.out.println("stateTypes: " + Arrays.asList(stateTypes)); for (int i=0, len=stateTypes.length; i < len; i++) { Type stateType = stateTypes[i]; ResolvedTypeX stateTypeX = BcelWorld.fromBcel(stateType).resolve(world); if (proceedMap.hasKey(i)) { //throw new RuntimeException("unimplemented"); proceedVars[proceedMap.get(i)].appendLoadAndConvert(ret, fact, stateTypeX); } else { ((BcelVar) argVarList.get(i)).appendLoad(ret, fact); } } ret.append(Utility.createInvoke(fact, callbackMethod)); ret.append(Utility.createConversion(fact, callbackMethod.getReturnType(), BcelWorld.makeBcelType(munger.getSignature().getReturnType()))); return ret; } public void weaveAroundClosure( BcelAdvice munger, boolean hasDynamicTest) { InstructionFactory fact = getFactory(); enclosingMethod.setCanInline(false); // MOVE OUT ALL THE INSTRUCTIONS IN MY SHADOW INTO ANOTHER METHOD! LazyMethodGen callbackMethod = extractMethod( NameMangler.aroundCallbackMethodName( getSignature(), getEnclosingClass()), 0, munger); BcelVar[] adviceVars = munger.getExposedStateAsBcelVars(); String closureClassName = NameMangler.makeClosureClassName( getEnclosingClass().getType(), getEnclosingClass().getNewGeneratedNameTag()); Member constructorSig = new Member(Member.CONSTRUCTOR, TypeX.forName(closureClassName), 0, "<init>", "([Ljava/lang/Object;)V"); BcelVar closureHolder = null; // This is not being used currently since getKind() == preinitializaiton // cannot happen in around advice if (getKind() == PreInitialization) { closureHolder = genTempVar(AjcMemberMaker.AROUND_CLOSURE_TYPE); } InstructionList closureInstantiation = makeClosureInstantiation(constructorSig, closureHolder); /*LazyMethodGen constructor = */ makeClosureClassAndReturnConstructor( closureClassName, callbackMethod, makeProceedArgumentMap(adviceVars) ); InstructionList returnConversionCode; if (getKind() == PreInitialization) { returnConversionCode = new InstructionList(); BcelVar stateTempVar = genTempVar(TypeX.OBJECTARRAY); closureHolder.appendLoad(returnConversionCode, fact); returnConversionCode.append( Utility.createInvoke( fact, world, AjcMemberMaker.aroundClosurePreInitializationGetter())); stateTempVar.appendStore(returnConversionCode, fact); Type[] stateTypes = getSuperConstructorParameterTypes(); returnConversionCode.append(InstructionConstants.ALOAD_0); // put "this" back on the stack for (int i = 0, len = stateTypes.length; i < len; i++) { stateTempVar.appendConvertableArrayLoad( returnConversionCode, fact, i, world.resolve(BcelWorld.fromBcel(stateTypes[i]))); } } else { returnConversionCode = Utility.createConversion( getFactory(), BcelWorld.makeBcelType(munger.getSignature().getReturnType()), callbackMethod.getReturnType()); if (!isFallsThrough()) { returnConversionCode.append( InstructionFactory.createReturn(callbackMethod.getReturnType())); } } InstructionList advice = new InstructionList(); advice.append(munger.getAdviceArgSetup(this, null, closureInstantiation)); // advice.append(closureInstantiation); advice.append(munger.getNonTestAdviceInstructions(this)); advice.append(returnConversionCode); if (!hasDynamicTest) { range.append(advice); } else { InstructionList callback = makeCallToCallback(callbackMethod); InstructionList postCallback = new InstructionList(); if (terminatesWithReturn()) { callback.append( InstructionFactory.createReturn(callbackMethod.getReturnType())); } else { advice.append( InstructionFactory.createBranchInstruction( Constants.GOTO, postCallback.append(InstructionConstants.NOP))); } range.append( munger.getTestInstructions( this, advice.getStart(), callback.getStart(), advice.getStart())); range.append(advice); range.append(callback); range.append(postCallback); } } // exposed for testing InstructionList makeCallToCallback(LazyMethodGen callbackMethod) { InstructionFactory fact = getFactory(); InstructionList callback = new InstructionList(); if (thisVar != null) { callback.append(InstructionConstants.ALOAD_0); } if (targetVar != null && targetVar != thisVar) { callback.append(BcelRenderer.renderExpr(fact, world, targetVar)); } callback.append(BcelRenderer.renderExprs(fact, world, argVars)); // remember to render tjps if (thisJoinPointVar != null) { callback.append(BcelRenderer.renderExpr(fact, world, thisJoinPointVar)); } callback.append(Utility.createInvoke(fact, callbackMethod)); return callback; } /** side-effect-free */ private InstructionList makeClosureInstantiation(Member constructor, BcelVar holder) { // LazyMethodGen constructor) { InstructionFactory fact = getFactory(); BcelVar arrayVar = genTempVar(TypeX.OBJECTARRAY); //final Type objectArrayType = new ArrayType(Type.OBJECT, 1); final InstructionList il = new InstructionList(); int alen = getArgCount() + (thisVar == null ? 0 : 1) + ((targetVar != null && targetVar != thisVar) ? 1 : 0) + (thisJoinPointVar == null ? 0 : 1); il.append(Utility.createConstant(fact, alen)); il.append((Instruction)fact.createNewArray(Type.OBJECT, (short)1)); arrayVar.appendStore(il, fact); int stateIndex = 0; if (thisVar != null) { arrayVar.appendConvertableArrayStore(il, fact, stateIndex, thisVar); thisVar.setPositionInAroundState(stateIndex); stateIndex++; } if (targetVar != null && targetVar != thisVar) { arrayVar.appendConvertableArrayStore(il, fact, stateIndex, targetVar); targetVar.setPositionInAroundState(stateIndex); stateIndex++; } for (int i = 0, len = getArgCount(); i<len; i++) { arrayVar.appendConvertableArrayStore(il, fact, stateIndex, argVars[i]); argVars[i].setPositionInAroundState(stateIndex); stateIndex++; } if (thisJoinPointVar != null) { arrayVar.appendConvertableArrayStore(il, fact, stateIndex, thisJoinPointVar); thisJoinPointVar.setPositionInAroundState(stateIndex); stateIndex++; } il.append(fact.createNew(new ObjectType(constructor.getDeclaringType().getName()))); il.append(new DUP()); arrayVar.appendLoad(il, fact); il.append(Utility.createInvoke(fact, world, constructor)); if (getKind() == PreInitialization) { il.append(InstructionConstants.DUP); holder.appendStore(il, fact); } return il; } private IntMap makeProceedArgumentMap(BcelVar[] adviceArgs) { //System.err.println("coming in with " + Arrays.asList(adviceArgs)); IntMap ret = new IntMap(); for(int i = 0, len = adviceArgs.length; i < len; i++) { BcelVar v = (BcelVar) adviceArgs[i]; if (v == null) continue; // XXX we don't know why this is required int pos = v.getPositionInAroundState(); if (pos >= 0) { // need this test to avoid args bound via cflow ret.put(pos, i); } } //System.err.println("returning " + ret); return ret; } /** * * * @param callbackMethod the method we will call back to when our run method gets called. * * @param proceedMap A map from state position to proceed argument position. May be * non covering on state position. */ private LazyMethodGen makeClosureClassAndReturnConstructor( String closureClassName, LazyMethodGen callbackMethod, IntMap proceedMap) { String superClassName = "org.aspectj.runtime.internal.AroundClosure"; Type objectArrayType = new ArrayType(Type.OBJECT, 1); LazyClassGen closureClass = new LazyClassGen(closureClassName, superClassName, getEnclosingClass().getFileName(), Modifier.PUBLIC, new String[] {}); InstructionFactory fact = new InstructionFactory(closureClass.getConstantPoolGen()); // constructor LazyMethodGen constructor = new LazyMethodGen(Modifier.PUBLIC, Type.VOID, "<init>", new Type[] {objectArrayType}, new String[] {}, closureClass); InstructionList cbody = constructor.getBody(); cbody.append(InstructionFactory.createLoad(Type.OBJECT, 0)); cbody.append(InstructionFactory.createLoad(objectArrayType, 1)); cbody.append(fact.createInvoke(superClassName, "<init>", Type.VOID, new Type[] {objectArrayType}, Constants.INVOKESPECIAL)); cbody.append(InstructionFactory.createReturn(Type.VOID)); closureClass.addMethodGen(constructor); // method LazyMethodGen runMethod = new LazyMethodGen(Modifier.PUBLIC, Type.OBJECT, "run", new Type[] {objectArrayType}, new String[] {}, closureClass); InstructionList mbody = runMethod.getBody(); BcelVar proceedVar = new BcelVar(TypeX.OBJECTARRAY.resolve(world), 1); // int proceedVarIndex = 1; BcelVar stateVar = new BcelVar(TypeX.OBJECTARRAY.resolve(world), runMethod.allocateLocal(1)); // int stateVarIndex = runMethod.allocateLocal(1); mbody.append(InstructionFactory.createThis()); mbody.append(fact.createGetField(superClassName, "state", objectArrayType)); mbody.append(stateVar.createStore(fact)); // mbody.append(fact.createStore(objectArrayType, stateVarIndex)); Type[] stateTypes = callbackMethod.getArgumentTypes(); for (int i=0, len=stateTypes.length; i < len; i++) { Type stateType = stateTypes[i]; ResolvedTypeX stateTypeX = BcelWorld.fromBcel(stateType).resolve(world); if (proceedMap.hasKey(i)) { mbody.append( proceedVar.createConvertableArrayLoad(fact, proceedMap.get(i), stateTypeX)); } else { mbody.append( stateVar.createConvertableArrayLoad(fact, i, stateTypeX)); } } mbody.append(Utility.createInvoke(fact, callbackMethod)); if (getKind() == PreInitialization) { mbody.append(Utility.createSet( fact, AjcMemberMaker.aroundClosurePreInitializationField())); mbody.append(InstructionConstants.ACONST_NULL); } else { mbody.append( Utility.createConversion( fact, callbackMethod.getReturnType(), Type.OBJECT)); } mbody.append(InstructionFactory.createReturn(Type.OBJECT)); closureClass.addMethodGen(runMethod); // class getEnclosingClass().addGeneratedInner(closureClass); return constructor; } // ---- extraction methods public LazyMethodGen extractMethod(String newMethodName, int visibilityModifier, ShadowMunger munger) { LazyMethodGen.assertGoodBody(range.getBody(), newMethodName); if (!getKind().allowsExtraction()) throw new BCException(); LazyMethodGen freshMethod = createMethodGen(newMethodName,visibilityModifier); // System.err.println("******"); // System.err.println("ABOUT TO EXTRACT METHOD for" + this); // enclosingMethod.print(System.err); // System.err.println("INTO"); // freshMethod.print(System.err); // System.err.println("WITH REMAP"); // System.err.println(makeRemap()); range.extractInstructionsInto(freshMethod, makeRemap(), (getKind() != PreInitialization) && isFallsThrough()); if (getKind() == PreInitialization) { addPreInitializationReturnCode( freshMethod, getSuperConstructorParameterTypes()); } getEnclosingClass().addMethodGen(freshMethod,munger.getSourceLocation()); return freshMethod; } private void addPreInitializationReturnCode( LazyMethodGen extractedMethod, Type[] superConstructorTypes) { InstructionList body = extractedMethod.getBody(); final InstructionFactory fact = getFactory(); BcelVar arrayVar = new BcelVar( world.resolve(TypeX.OBJECTARRAY), extractedMethod.allocateLocal(1)); int len = superConstructorTypes.length; body.append(Utility.createConstant(fact, len)); body.append((Instruction)fact.createNewArray(Type.OBJECT, (short)1)); arrayVar.appendStore(body, fact); for (int i = len - 1; i >= 0; i++) { // convert thing on top of stack to object body.append( Utility.createConversion(fact, superConstructorTypes[i], Type.OBJECT)); // push object array arrayVar.appendLoad(body, fact); // swap body.append(InstructionConstants.SWAP); // do object array store. body.append(Utility.createConstant(fact, i)); body.append(InstructionConstants.SWAP); body.append(InstructionFactory.createArrayStore(Type.OBJECT)); } arrayVar.appendLoad(body, fact); body.append(InstructionConstants.ARETURN); } private Type[] getSuperConstructorParameterTypes() { // assert getKind() == PreInitialization InstructionHandle superCallHandle = getRange().getEnd().getNext(); InvokeInstruction superCallInstruction = (InvokeInstruction) superCallHandle.getInstruction(); return superCallInstruction.getArgumentTypes( getEnclosingClass().getConstantPoolGen()); } /** make a map from old frame location to new frame location. Any unkeyed frame * location picks out a copied local */ private IntMap makeRemap() { IntMap ret = new IntMap(5); int reti = 0; if (thisVar != null) { ret.put(0, reti++); // thisVar guaranteed to be 0 } if (targetVar != null && targetVar != thisVar) { ret.put(targetVar.getSlot(), reti++); } for (int i = 0, len = argVars.length; i < len; i++) { ret.put(argVars[i].getSlot(), reti); reti += argVars[i].getType().getSize(); } if (thisJoinPointVar != null) { ret.put(thisJoinPointVar.getSlot(), reti++); } // we not only need to put the arguments, we also need to remap their // aliases, which we so helpfully put into temps at the beginning of this join // point. if (! getKind().argsOnStack()) { int oldi = 0; int newi = 0; // if we're passing in a this and we're not argsOnStack we're always // passing in a target too if (arg0HoldsThis()) { ret.put(0, 0); oldi++; newi+=1; } //assert targetVar == thisVar for (int i = 0; i < getArgCount(); i++) { TypeX type = getArgType(i); ret.put(oldi, newi); oldi += type.getSize(); newi += type.getSize(); } } // System.err.println("making remap for : " + this); // if (targetVar != null) System.err.println("target slot : " + targetVar.getSlot()); // if (thisVar != null) System.err.println(" this slot : " + thisVar.getSlot()); // System.err.println(ret); return ret; } /** * The new method always static. * It may take some extra arguments: this, target. * If it's argsOnStack, then it must take both this/target * If it's argsOnFrame, it shares this and target. * ??? rewrite this to do less array munging, please */ private LazyMethodGen createMethodGen(String newMethodName, int visibilityModifier) { Type[] parameterTypes = BcelWorld.makeBcelTypes(getArgTypes()); int modifiers = Modifier.FINAL | visibilityModifier; // XXX some bug // if (! isExpressionKind() && getSignature().isStrict(world)) { // modifiers |= Modifier.STRICT; // } modifiers |= Modifier.STATIC; if (targetVar != null && targetVar != thisVar) { TypeX targetType = getTargetType(); ResolvedMember resolvedMember = getSignature().resolve(world); if (resolvedMember != null && Modifier.isProtected(resolvedMember.getModifiers()) && !samePackage(targetType.getPackageName(), getEnclosingType().getPackageName())) { if (!targetType.isAssignableFrom(getThisType(), world)) { throw new BCException("bad bytecode"); } targetType = getThisType(); } parameterTypes = addType(BcelWorld.makeBcelType(targetType), parameterTypes); } if (thisVar != null) { TypeX thisType = getThisType(); parameterTypes = addType(BcelWorld.makeBcelType(thisType), parameterTypes); } // We always want to pass down thisJoinPoint in case we have already woven // some advice in here. If we only have a single piece of around advice on a // join point, it is unnecessary to accept (and pass) tjp. if (thisJoinPointVar != null) { parameterTypes = addTypeToEnd(LazyClassGen.tjpType, parameterTypes); } TypeX returnType; if (getKind() == PreInitialization) { returnType = TypeX.OBJECTARRAY; } else { returnType = getReturnType(); } return new LazyMethodGen( modifiers, BcelWorld.makeBcelType(returnType), newMethodName, parameterTypes, new String[0], // XXX again, we need to look up methods! // TypeX.getNames(getSignature().getExceptions(world)), getEnclosingClass()); } private boolean samePackage(String p1, String p2) { if (p1 == null) return p2 == null; if (p2 == null) return false; return p1.equals(p2); } private Type[] addType(Type type, Type[] types) { int len = types.length; Type[] ret = new Type[len+1]; ret[0] = type; System.arraycopy(types, 0, ret, 1, len); return ret; } private Type[] addTypeToEnd(Type type, Type[] types) { int len = types.length; Type[] ret = new Type[len+1]; ret[len] = type; System.arraycopy(types, 0, ret, 0, len); return ret; } public BcelVar genTempVar(TypeX typeX) { return new BcelVar(typeX.resolve(world), genTempVarIndex(typeX.getSize())); } // public static final boolean CREATE_TEMP_NAMES = true; public BcelVar genTempVar(TypeX typeX, String localName) { BcelVar tv = genTempVar(typeX); // if (CREATE_TEMP_NAMES) { // for (InstructionHandle ih = range.getStart(); ih != range.getEnd(); ih = ih.getNext()) { // if (Range.isRangeHandle(ih)) continue; // ih.addTargeter(new LocalVariableTag(typeX, localName, tv.getSlot())); // } // } return tv; } // eh doesn't think we need to garbage collect these (64K is a big number...) private int genTempVarIndex(int size) { return enclosingMethod.allocateLocal(size); } public InstructionFactory getFactory() { return getEnclosingClass().getFactory(); } public ISourceLocation getSourceLocation() { int sourceLine = getSourceLine(); if (sourceLine == 0 || sourceLine == -1) { // Thread.currentThread().dumpStack(); // System.err.println(this + ": " + range); return getEnclosingClass().getType().getSourceLocation(); } else { return getEnclosingClass().getType().getSourceContext().makeSourceLocation(sourceLine); } } public Shadow getEnclosingShadow() { return enclosingShadow; } public LazyMethodGen getEnclosingMethod() { return enclosingMethod; } public boolean isFallsThrough() { return !terminatesWithReturn(); //fallsThrough; } }