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
73,334
Bug 73334 Avoid clashes in the org.eclipse namespace by renaming our duplicates.
We have recently renamed our 'copy' of BCEL to use a different package prefix so that our version never clashes with another version that might be around on a users system. This enhancement is to do the same thing for our 'copy' of the org.eclipse.jdt code (in the shadows project). As part of packaging the shadows project to create the 'jdtcore' jar files (bin and src) we will rename the packages from: org.eclipse.jdt.*** to org.aspectj.org.eclipse.jdt.** This has a really nice side effect that we can make our version of the compiler accessible in the IDE. It should now be possible for AJDT to work more closely with it and get features like eager parsing to work. Care will be taken that we don't accidentally make the merge process a nightmare.
resolved fixed
b133299
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2004-09-06T15:40:02Z
2004-09-06T17:00:00Z
org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/core/builder/AjState.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.File; import java.io.FileFilter; import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import org.aspectj.ajdt.internal.compiler.InterimCompilationResult; import org.aspectj.bridge.IMessage; import org.aspectj.bridge.Message; import org.aspectj.bridge.SourceLocation; import org.aspectj.util.FileUtil; import org.aspectj.weaver.bcel.UnwovenClassFile; import org.eclipse.jdt.internal.compiler.CompilationResult; import org.eclipse.jdt.internal.compiler.classfmt.ClassFileReader; import org.eclipse.jdt.internal.compiler.classfmt.ClassFormatException; import org.eclipse.jdt.internal.core.builder.ReferenceCollection; import org.eclipse.jdt.internal.core.builder.StringSet; /** * Holds state needed for incremental compilation */ public class AjState { AjBuildManager buildManager; long lastSuccessfulBuildTime = -1; long currentBuildTime = -1; AjBuildConfig buildConfig; AjBuildConfig newBuildConfig; // Map/*<File, List<UnwovenClassFile>*/ classesFromFile = new HashMap(); Map/*<File, CompilationResult*/ resultsFromFile = new HashMap(); Map/*<File, ReferenceCollection>*/ references = new HashMap(); Map/*File, List<UnwovenClassFile>*/ binarySourceFiles = new HashMap(); Map/*<String, UnwovenClassFile>*/ classesFromName = new HashMap(); List/*File*/ compiledSourceFiles = new ArrayList(); List/*String*/ resources = new ArrayList(); ArrayList/*<String>*/ qualifiedStrings; ArrayList/*<String>*/ simpleStrings; Set addedFiles; Set deletedFiles; Set /*BinarySourceFile*/addedBinaryFiles; Set /*BinarySourceFile*/deletedBinaryFiles; List addedClassFiles; public AjState(AjBuildManager buildManager) { this.buildManager = buildManager; } void successfulCompile(AjBuildConfig config) { buildConfig = config; lastSuccessfulBuildTime = currentBuildTime; } /** * Returns false if a batch build is needed. */ boolean prepareForNextBuild(AjBuildConfig newBuildConfig) { currentBuildTime = System.currentTimeMillis(); addedClassFiles = new ArrayList(); if (lastSuccessfulBuildTime == -1 || buildConfig == null) { return false; } // we don't support incremental with an outjar yet if (newBuildConfig.getOutputJar() != null) return false; // we can't do an incremental build if one of our paths // has changed, or a jar on a path has been modified if (pathChange(buildConfig,newBuildConfig)) { // last time we built, .class files and resource files from jars on the // inpath will have been copied to the output directory. // these all need to be deleted in preparation for the clean build that is // coming - otherwise a file that has been deleted from an inpath jar // since the last build will not be deleted from the output directory. removeAllResultsOfLastBuild(); return false; } simpleStrings = new ArrayList(); qualifiedStrings = new ArrayList(); Set oldFiles = new HashSet(buildConfig.getFiles()); Set newFiles = new HashSet(newBuildConfig.getFiles()); addedFiles = new HashSet(newFiles); addedFiles.removeAll(oldFiles); deletedFiles = new HashSet(oldFiles); deletedFiles.removeAll(newFiles); Set oldBinaryFiles = new HashSet(buildConfig.getBinaryFiles()); Set newBinaryFiles = new HashSet(newBuildConfig.getBinaryFiles()); addedBinaryFiles = new HashSet(newBinaryFiles); addedBinaryFiles.removeAll(oldBinaryFiles); deletedBinaryFiles = new HashSet(oldBinaryFiles); deletedBinaryFiles.removeAll(newBinaryFiles); this.newBuildConfig = newBuildConfig; return true; } private Collection getModifiedFiles() { return getModifiedFiles(lastSuccessfulBuildTime); } Collection getModifiedFiles(long lastBuildTime) { List ret = new ArrayList(); //not our job to account for new and deleted files for (Iterator i = buildConfig.getFiles().iterator(); i.hasNext(); ) { File file = (File)i.next(); if (!file.exists()) continue; long modTime = file.lastModified(); //System.out.println("check: " + file + " mod " + modTime + " build " + lastBuildTime); // need to add 1000 since lastModTime is only accurate to a second on some (all?) platforms if (modTime + 1000 >= lastBuildTime) { ret.add(file); } } return ret; } private Collection getModifiedBinaryFiles() { return getModifiedBinaryFiles(lastSuccessfulBuildTime); } Collection getModifiedBinaryFiles(long lastBuildTime) { List ret = new ArrayList(); //not our job to account for new and deleted files for (Iterator i = buildConfig.getBinaryFiles().iterator(); i.hasNext(); ) { AjBuildConfig.BinarySourceFile bsfile = (AjBuildConfig.BinarySourceFile)i.next(); File file = bsfile.binSrc; if (!file.exists()) continue; long modTime = file.lastModified(); //System.out.println("check: " + file + " mod " + modTime + " build " + lastBuildTime); // need to add 1000 since lastModTime is only accurate to a second on some (all?) platforms if (modTime + 1000 >= lastBuildTime) { ret.add(bsfile); } } return ret; } private boolean pathChange(AjBuildConfig oldConfig, AjBuildConfig newConfig) { boolean changed = false; List oldClasspath = oldConfig.getClasspath(); List newClasspath = newConfig.getClasspath(); if (changed(oldClasspath,newClasspath)) return true; List oldAspectpath = oldConfig.getAspectpath(); List newAspectpath = newConfig.getAspectpath(); if (changed(oldAspectpath,newAspectpath)) return true; List oldInJars = oldConfig.getInJars(); List newInJars = newConfig.getInJars(); if (changed(oldInJars,newInJars)) return true; List oldInPath = oldConfig.getInpath(); List newInPath = newConfig.getInpath(); if (changed(oldInPath, newInPath)) return true; return changed; } private boolean changed(List oldPath, List newPath) { if (oldPath == null) oldPath = new ArrayList(); if (newPath == null) newPath = new ArrayList(); if (oldPath.size() != newPath.size()) { return true; } for (int i = 0; i < oldPath.size(); i++) { if (!oldPath.get(i).equals(newPath.get(i))) { return true; } Object o = oldPath.get(i); // String on classpath, File on other paths File f = null; if (o instanceof String) { f = new File((String)o); } else { f = (File) o; } if (f.exists() && !f.isDirectory() && (f.lastModified() >= lastSuccessfulBuildTime)) { return true; } } return false; } public List getFilesToCompile(boolean firstPass) { List thisTime = new ArrayList(); if (firstPass) { compiledSourceFiles = new ArrayList(); Collection modifiedFiles = getModifiedFiles(); //System.out.println("modified: " + modifiedFiles); thisTime.addAll(modifiedFiles); //??? eclipse IncrementalImageBuilder appears to do this // for (Iterator i = modifiedFiles.iterator(); i.hasNext();) { // File file = (File) i.next(); // addDependentsOf(file); // } thisTime.addAll(addedFiles); deleteClassFiles(); deleteResources(); addAffectedSourceFiles(thisTime,thisTime); } else { addAffectedSourceFiles(thisTime,compiledSourceFiles); } compiledSourceFiles = thisTime; return thisTime; } public Map /* String -> List<ucf> */ getBinaryFilesToCompile(boolean firstTime) { if (lastSuccessfulBuildTime == -1 || buildConfig == null) { return binarySourceFiles; } // else incremental... Map toWeave = new HashMap(); if (firstTime) { List addedOrModified = new ArrayList(); addedOrModified.addAll(addedBinaryFiles); addedOrModified.addAll(getModifiedBinaryFiles()); for (Iterator iter = addedOrModified.iterator(); iter.hasNext();) { AjBuildConfig.BinarySourceFile bsf = (AjBuildConfig.BinarySourceFile) iter.next(); UnwovenClassFile ucf = createUnwovenClassFile(bsf); if (ucf == null) continue; List ucfs = new ArrayList(); ucfs.add(ucf); addDependentsOf(ucf.getClassName()); binarySourceFiles.put(bsf.binSrc.getPath(),ucfs); toWeave.put(bsf.binSrc.getPath(),ucfs); } deleteBinaryClassFiles(); } else { // return empty set... we've already done our bit. } return toWeave; } /** * Called when a path change is about to trigger a full build, but * we haven't cleaned up from the last incremental build... */ private void removeAllResultsOfLastBuild() { // remove all binarySourceFiles, and all classesFromName... for (Iterator iter = binarySourceFiles.values().iterator(); iter.hasNext();) { List ucfs = (List) iter.next(); for (Iterator iterator = ucfs.iterator(); iterator.hasNext();) { UnwovenClassFile ucf = (UnwovenClassFile) iterator.next(); try { ucf.deleteRealFile(); } catch (IOException ex) { /* we did our best here */ } } } for (Iterator iterator = classesFromName.values().iterator(); iterator.hasNext();) { UnwovenClassFile ucf = (UnwovenClassFile) iterator.next(); try { ucf.deleteRealFile(); } catch (IOException ex) { /* we did our best here */ } } for (Iterator iter = resources.iterator(); iter.hasNext();) { String resource = (String) iter.next(); new File(buildConfig.getOutputDir(),resource).delete(); } } private void deleteClassFiles() { for (Iterator i = deletedFiles.iterator(); i.hasNext(); ) { File deletedFile = (File)i.next(); //System.out.println("deleting: " + deletedFile); addDependentsOf(deletedFile); InterimCompilationResult intRes = (InterimCompilationResult) resultsFromFile.get(deletedFile); resultsFromFile.remove(deletedFile); //System.out.println("deleting: " + unwovenClassFiles); if (intRes == null) continue; for (int j=0; j<intRes.unwovenClassFiles().length; j++ ) { deleteClassFile(intRes.unwovenClassFiles()[j]); } } } private void deleteBinaryClassFiles() { // range of bsf is ucfs, domain is files (.class and jars) in inpath/jars for (Iterator iter = deletedBinaryFiles.iterator(); iter.hasNext();) { AjBuildConfig.BinarySourceFile deletedFile = (AjBuildConfig.BinarySourceFile) iter.next(); List ucfs = (List) binarySourceFiles.get(deletedFile.binSrc.getPath()); binarySourceFiles.remove(deletedFile.binSrc.getPath()); deleteClassFile((UnwovenClassFile)ucfs.get(0)); } } private void deleteResources() { List oldResources = new ArrayList(); oldResources.addAll(resources); // note - this deliberately ignores resources in jars as we don't yet handle jar changes // with incremental compilation for (Iterator i = buildConfig.getInpath().iterator(); i.hasNext(); ) { File inPathElement = (File)i.next(); if (inPathElement.isDirectory() && AjBuildManager.COPY_INPATH_DIR_RESOURCES) { deleteResourcesFromDirectory(inPathElement,oldResources); } } if (buildConfig.getSourcePathResources() != null) { for (Iterator i = buildConfig.getSourcePathResources().keySet().iterator(); i.hasNext(); ) { String resource = (String)i.next(); maybeDeleteResource(resource, oldResources); } } // oldResources need to be deleted... for (Iterator iter = oldResources.iterator(); iter.hasNext();) { String victim = (String) iter.next(); File f = new File(buildConfig.getOutputDir(),victim); if (f.exists()) { f.delete(); } resources.remove(victim); } } private void maybeDeleteResource(String resName, List oldResources) { if (resources.contains(resName)) { oldResources.remove(resName); File source = new File(buildConfig.getOutputDir(),resName); if ((source != null) && (source.exists()) && (source.lastModified() >= lastSuccessfulBuildTime)) { resources.remove(resName); // will ensure it is re-copied } } } private void deleteResourcesFromDirectory(File dir, List oldResources) { 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); maybeDeleteResource(filename, oldResources); } } private void deleteClassFile(UnwovenClassFile classFile) { classesFromName.remove(classFile.getClassName()); buildManager.bcelWeaver.deleteClassFile(classFile.getClassName()); try { classFile.deleteRealFile(); } catch (IOException e) { //!!! might be okay to ignore } } private UnwovenClassFile createUnwovenClassFile(AjBuildConfig.BinarySourceFile bsf) { UnwovenClassFile ucf = null; try { ucf = buildManager.bcelWeaver.addClassFile(bsf.binSrc, bsf.fromInPathDirectory, buildConfig.getOutputDir()); } catch(IOException ex) { IMessage msg = new Message("can't read class file " + bsf.binSrc.getPath(), new SourceLocation(bsf.binSrc,0),false); buildManager.handler.handleMessage(msg); } return ucf; } public void noteResult(InterimCompilationResult result) { File sourceFile = new File(result.fileName()); CompilationResult cr = result.result(); if (result != null) { references.put(sourceFile, new ReferenceCollection(cr.qualifiedReferences, cr.simpleNameReferences)); } InterimCompilationResult previous = (InterimCompilationResult) resultsFromFile.get(sourceFile); UnwovenClassFile[] unwovenClassFiles = result.unwovenClassFiles(); for (int i = 0; i < unwovenClassFiles.length; i++) { UnwovenClassFile lastTimeRound = removeFromPreviousIfPresent(unwovenClassFiles[i],previous); recordClassFile(unwovenClassFiles[i],lastTimeRound); classesFromName.put(unwovenClassFiles[i].getClassName(),unwovenClassFiles[i]); } if (previous != null) { for (int i = 0; i < previous.unwovenClassFiles().length; i++) { if (previous.unwovenClassFiles()[i] != null) { deleteClassFile(previous.unwovenClassFiles()[i]); } } } resultsFromFile.put(sourceFile, result); } private UnwovenClassFile removeFromPreviousIfPresent(UnwovenClassFile cf, InterimCompilationResult previous) { if (previous == null) return null; UnwovenClassFile[] unwovenClassFiles = previous.unwovenClassFiles(); for (int i = 0; i < unwovenClassFiles.length; i++) { UnwovenClassFile candidate = unwovenClassFiles[i]; if ((candidate != null) && candidate.getFilename().equals(cf.getFilename())) { unwovenClassFiles[i] = null; return candidate; } } return null; } private void recordClassFile(UnwovenClassFile thisTime, UnwovenClassFile lastTime) { if (simpleStrings == null) return; // batch build if (lastTime == null) { addDependentsOf(thisTime.getClassName()); return; } byte[] newBytes = thisTime.getBytes(); byte[] oldBytes = lastTime.getBytes(); boolean bytesEqual = (newBytes.length == oldBytes.length); for (int i = 0; (i < oldBytes.length) && bytesEqual; i++) { if (newBytes[i] != oldBytes[i]) bytesEqual = false; } if (!bytesEqual) { try { ClassFileReader reader = new ClassFileReader(oldBytes, lastTime.getFilename().toCharArray()); // ignore local types since they're only visible inside a single method if (!(reader.isLocal() || reader.isAnonymous()) && reader.hasStructuralChanges(newBytes)) { addDependentsOf(lastTime.getClassName()); } } catch (ClassFormatException e) { addDependentsOf(lastTime.getClassName()); } } } // public void noteClassesFromFile(CompilationResult result, String sourceFileName, List unwovenClassFiles) { // File sourceFile = new File(sourceFileName); // // if (result != null) { // references.put(sourceFile, new ReferenceCollection(result.qualifiedReferences, result.simpleNameReferences)); // } // // List previous = (List)classesFromFile.get(sourceFile); // List newClassFiles = new ArrayList(); // for (Iterator i = unwovenClassFiles.iterator(); i.hasNext();) { // UnwovenClassFile cf = (UnwovenClassFile) i.next(); // cf = writeClassFile(cf, findAndRemoveClassFile(cf.getClassName(), previous)); // newClassFiles.add(cf); // classesFromName.put(cf.getClassName(), cf); // } // // if (previous != null && !previous.isEmpty()) { // for (Iterator i = previous.iterator(); i.hasNext();) { // UnwovenClassFile cf = (UnwovenClassFile) i.next(); // deleteClassFile(cf); // } // } // // classesFromFile.put(sourceFile, newClassFiles); // resultsFromFile.put(sourceFile, result); // } // // private UnwovenClassFile findAndRemoveClassFile(String name, List previous) { // if (previous == null) return null; // for (Iterator i = previous.iterator(); i.hasNext();) { // UnwovenClassFile cf = (UnwovenClassFile) i.next(); // if (cf.getClassName().equals(name)) { // i.remove(); // return cf; // } // } // return null; // } // // private UnwovenClassFile writeClassFile(UnwovenClassFile cf, UnwovenClassFile previous) { // if (simpleStrings == null) { // batch build // addedClassFiles.add(cf); // return cf; // } // // try { // if (previous == null) { // addedClassFiles.add(cf); // addDependentsOf(cf.getClassName()); // return cf; // } // // byte[] oldBytes = previous.getBytes(); // byte[] newBytes = cf.getBytes(); // //if (this.compileLoop > 1) { // only optimize files which were recompiled during the dependent pass, see 33990 // notEqual : if (newBytes.length == oldBytes.length) { // for (int i = newBytes.length; --i >= 0;) { // if (newBytes[i] != oldBytes[i]) break notEqual; // } // //addedClassFiles.add(previous); //!!! performance wasting // buildManager.bcelWorld.addSourceObjectType(previous.getJavaClass()); // return previous; // bytes are identical so skip them // } // //} // ClassFileReader reader = new ClassFileReader(oldBytes, previous.getFilename().toCharArray()); // // ignore local types since they're only visible inside a single method // if (!(reader.isLocal() || reader.isAnonymous()) && reader.hasStructuralChanges(newBytes)) { // addDependentsOf(cf.getClassName()); // } // } catch (ClassFormatException e) { // addDependentsOf(cf.getClassName()); // } // addedClassFiles.add(cf); // return cf; // } private static StringSet makeStringSet(List strings) { StringSet ret = new StringSet(strings.size()); for (Iterator iter = strings.iterator(); iter.hasNext();) { String element = (String) iter.next(); ret.add(element); } return ret; } protected void addAffectedSourceFiles(List addTo, List lastTimeSources) { if (qualifiedStrings.isEmpty() && simpleStrings.isEmpty()) return; // the qualifiedStrings are of the form 'p1/p2' & the simpleStrings are just 'X' char[][][] qualifiedNames = ReferenceCollection.internQualifiedNames(makeStringSet(qualifiedStrings)); // if a well known qualified name was found then we can skip over these if (qualifiedNames.length < qualifiedStrings.size()) qualifiedNames = null; char[][] simpleNames = ReferenceCollection.internSimpleNames(makeStringSet(simpleStrings)); // if a well known name was found then we can skip over these if (simpleNames.length < simpleStrings.size()) simpleNames = null; //System.err.println("simple: " + simpleStrings); //System.err.println("qualif: " + qualifiedStrings); for (Iterator i = references.entrySet().iterator(); i.hasNext();) { Map.Entry entry = (Map.Entry) i.next(); ReferenceCollection refs = (ReferenceCollection)entry.getValue(); if (refs != null && refs.includes(qualifiedNames, simpleNames)) { File file = (File)entry.getKey(); if (file.exists()) { if (!lastTimeSources.contains(file)) { //??? O(n**2) addTo.add(file); } } } } qualifiedStrings.clear(); simpleStrings.clear(); } protected void addDependentsOf(String qualifiedTypeName) { int lastDot = qualifiedTypeName.lastIndexOf('.'); String typeName; if (lastDot != -1) { String packageName = qualifiedTypeName.substring(0,lastDot).replace('.', '/'); if (!qualifiedStrings.contains(packageName)) { //??? O(n**2) qualifiedStrings.add(packageName); } typeName = qualifiedTypeName.substring(lastDot+1); } else { qualifiedStrings.add(""); typeName = qualifiedTypeName; } int memberIndex = typeName.indexOf('$'); if (memberIndex > 0) typeName = typeName.substring(0, memberIndex); if (!simpleStrings.contains(typeName)) { //??? O(n**2) simpleStrings.add(typeName); } //System.err.println("adding: " + qualifiedTypeName); } protected void addDependentsOf(File sourceFile) { InterimCompilationResult intRes = (InterimCompilationResult)resultsFromFile.get(sourceFile); if (intRes == null) return; for (int i = 0; i < intRes.unwovenClassFiles().length; i++) { addDependentsOf(intRes.unwovenClassFiles()[i].getClassName()); } } }
73,334
Bug 73334 Avoid clashes in the org.eclipse namespace by renaming our duplicates.
We have recently renamed our 'copy' of BCEL to use a different package prefix so that our version never clashes with another version that might be around on a users system. This enhancement is to do the same thing for our 'copy' of the org.eclipse.jdt code (in the shadows project). As part of packaging the shadows project to create the 'jdtcore' jar files (bin and src) we will rename the packages from: org.eclipse.jdt.*** to org.aspectj.org.eclipse.jdt.** This has a really nice side effect that we can make our version of the compiler accessible in the IDE. It should now be possible for AJDT to work more closely with it and get features like eager parsing to work. Care will be taken that we don't accidentally make the merge process a nightmare.
resolved fixed
b133299
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2004-09-06T15:40:02Z
2004-09-06T17:00:00Z
org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/core/builder/AsmElementFormatter.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Common Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * PARC initial implementation * ******************************************************************/ package org.aspectj.ajdt.internal.core.builder; import java.util.ArrayList; import java.util.List; import org.aspectj.ajdt.internal.compiler.ast.AdviceDeclaration; import org.aspectj.ajdt.internal.compiler.ast.DeclareDeclaration; import org.aspectj.ajdt.internal.compiler.ast.InterTypeConstructorDeclaration; import org.aspectj.ajdt.internal.compiler.ast.InterTypeDeclaration; import org.aspectj.ajdt.internal.compiler.ast.InterTypeFieldDeclaration; import org.aspectj.ajdt.internal.compiler.ast.InterTypeMethodDeclaration; import org.aspectj.ajdt.internal.compiler.ast.PointcutDeclaration; import org.aspectj.ajdt.internal.compiler.lookup.AjLookupEnvironment; import org.aspectj.asm.IProgramElement; import org.aspectj.weaver.AdviceKind; import org.aspectj.weaver.ResolvedTypeX; import org.aspectj.weaver.TypeX; import org.aspectj.weaver.patterns.AndPointcut; import org.aspectj.weaver.patterns.DeclareErrorOrWarning; import org.aspectj.weaver.patterns.DeclareParents; import org.aspectj.weaver.patterns.DeclarePrecedence; import org.aspectj.weaver.patterns.DeclareSoft; import org.aspectj.weaver.patterns.OrPointcut; import org.aspectj.weaver.patterns.ReferencePointcut; import org.aspectj.weaver.patterns.TypePattern; import org.aspectj.weaver.patterns.TypePatternList; import org.eclipse.jdt.internal.compiler.ast.Argument; import org.eclipse.jdt.internal.compiler.ast.MethodDeclaration; /** * @author Mik Kersten */ public class AsmElementFormatter { public static final String DECLARE_PRECEDENCE = "precedence"; public static final String DECLARE_SOFT = "soft"; public static final String DECLARE_PARENTS = "parents"; public static final String DECLARE_WARNING = "warning"; public static final String DECLARE_ERROR = "error"; public static final String DECLARE_UNKNONWN = "<unknown declare>"; public static final String POINTCUT_ABSTRACT = "<abstract pointcut>"; public static final String POINTCUT_ANONYMOUS = "<anonymous pointcut>"; public static final int MAX_MESSAGE_LENGTH = 18; public static final String DEC_LABEL = "declare"; public void genLabelAndKind(MethodDeclaration methodDeclaration, IProgramElement node) { if (methodDeclaration instanceof AdviceDeclaration) { AdviceDeclaration ad = (AdviceDeclaration)methodDeclaration; node.setKind(IProgramElement.Kind.ADVICE); if (ad.kind == AdviceKind.Around) { node.setCorrespondingType(ad.returnType.toString()); //returnTypeToString(0)); } String details = ""; if (ad.pointcutDesignator != null) { if (ad.pointcutDesignator.getPointcut() instanceof ReferencePointcut) { ReferencePointcut rp = (ReferencePointcut)ad.pointcutDesignator.getPointcut(); details += rp.name + ".."; } else if (ad.pointcutDesignator.getPointcut() instanceof AndPointcut) { AndPointcut ap = (AndPointcut)ad.pointcutDesignator.getPointcut(); if (ap.getLeft() instanceof ReferencePointcut) { details += ap.getLeft().toString() + ".."; } else { details += POINTCUT_ANONYMOUS + ".."; } } else if (ad.pointcutDesignator.getPointcut() instanceof OrPointcut) { OrPointcut op = (OrPointcut)ad.pointcutDesignator.getPointcut(); if (op.getLeft() instanceof ReferencePointcut) { details += op.getLeft().toString() + ".."; } else { details += POINTCUT_ANONYMOUS + ".."; } } else { details += POINTCUT_ANONYMOUS; } } else { details += POINTCUT_ABSTRACT; } node.setName(ad.kind.toString()); node.setDetails(details); setParameters(methodDeclaration, node); } else if (methodDeclaration instanceof PointcutDeclaration) { // PointcutDeclaration pd = (PointcutDeclaration)methodDeclaration; node.setKind(IProgramElement.Kind.POINTCUT); node.setName(translatePointcutName(new String(methodDeclaration.selector))); setParameters(methodDeclaration, node); } else if (methodDeclaration instanceof DeclareDeclaration) { DeclareDeclaration declare = (DeclareDeclaration)methodDeclaration; String name = DEC_LABEL + " "; if (declare.declareDecl instanceof DeclareErrorOrWarning) { DeclareErrorOrWarning deow = (DeclareErrorOrWarning)declare.declareDecl; if (deow.isError()) { node.setKind( IProgramElement.Kind.DECLARE_ERROR); name += DECLARE_ERROR; } else { node.setKind( IProgramElement.Kind.DECLARE_WARNING); name += DECLARE_WARNING; } node.setName(name) ; node.setDetails("\"" + genDeclareMessage(deow.getMessage()) + "\""); } else if (declare.declareDecl instanceof DeclareParents) { node.setKind( IProgramElement.Kind.DECLARE_PARENTS); DeclareParents dp = (DeclareParents)declare.declareDecl; node.setName(name + DECLARE_PARENTS); String kindOfDP = null; StringBuffer details = new StringBuffer(""); TypePattern[] newParents = dp.getParents().getTypePatterns(); for (int i = 0; i < newParents.length; i++) { TypePattern tp = newParents[i]; TypeX tx = tp.getExactType(); if (kindOfDP == null) { kindOfDP = "implements "; try { ResolvedTypeX rtx = tx.resolve(((AjLookupEnvironment)declare.scope.environment()).factory.getWorld()); if (!rtx.isInterface()) kindOfDP = "extends "; } catch (Throwable t) { // What can go wrong???? who knows! } } String typename= tp.toString(); if (typename.lastIndexOf(".")!=-1) { typename=typename.substring(typename.lastIndexOf(".")+1); } details.append(typename); if ((i+1)<newParents.length) details.append(","); } node.setDetails(kindOfDP+details.toString()); } else if (declare.declareDecl instanceof DeclareSoft) { node.setKind( IProgramElement.Kind.DECLARE_SOFT); DeclareSoft ds = (DeclareSoft)declare.declareDecl; node.setName(name + DECLARE_SOFT); node.setDetails(genTypePatternLabel(ds.getException())); } else if (declare.declareDecl instanceof DeclarePrecedence) { node.setKind( IProgramElement.Kind.DECLARE_PRECEDENCE); DeclarePrecedence ds = (DeclarePrecedence)declare.declareDecl; node.setName(name + DECLARE_PRECEDENCE); node.setDetails(genPrecedenceListLabel(ds.getPatterns())); } else { node.setKind(IProgramElement.Kind.ERROR); node.setName(DECLARE_UNKNONWN); } } else if (methodDeclaration instanceof InterTypeDeclaration) { InterTypeDeclaration itd = (InterTypeDeclaration)methodDeclaration; String name = itd.onType.toString() + "." + new String(itd.getDeclaredSelector()); if (methodDeclaration instanceof InterTypeFieldDeclaration) { node.setKind(IProgramElement.Kind.INTER_TYPE_FIELD); node.setName(name); } else if (methodDeclaration instanceof InterTypeMethodDeclaration) { node.setKind(IProgramElement.Kind.INTER_TYPE_METHOD); node.setName(name); } else if (methodDeclaration instanceof InterTypeConstructorDeclaration) { node.setKind(IProgramElement.Kind.INTER_TYPE_CONSTRUCTOR); // StringBuffer argumentsSignature = new StringBuffer("fubar"); // argumentsSignature.append("("); // if (methodDeclaration.arguments!=null && methodDeclaration.arguments.length>1) { // // for (int i = 1;i<methodDeclaration.arguments.length;i++) { // argumentsSignature.append(methodDeclaration.arguments[i]); // if (i+1<methodDeclaration.arguments.length) argumentsSignature.append(","); // } // } // argumentsSignature.append(")"); // InterTypeConstructorDeclaration itcd = (InterTypeConstructorDeclaration)methodDeclaration; node.setName(itd.onType.toString() + "." + itd.onType.toString()/*+argumentsSignature.toString()*/); } else { node.setKind(IProgramElement.Kind.ERROR); node.setName(name); } node.setCorrespondingType(itd.returnType.toString()); if (node.getKind() != IProgramElement.Kind.INTER_TYPE_FIELD) { setParameters(methodDeclaration, node); } } else { if (methodDeclaration.isConstructor()) { node.setKind(IProgramElement.Kind.CONSTRUCTOR); } else { node.setKind(IProgramElement.Kind.METHOD); } String label = new String(methodDeclaration.selector); node.setName(label); setParameters(methodDeclaration, node); } } private String genPrecedenceListLabel(TypePatternList list) { String tpList = ""; for (int i = 0; i < list.size(); i++) { tpList += genTypePatternLabel(list.get(i)); if (i < list.size()-1) tpList += ", "; } return tpList; } // private String genArguments(MethodDeclaration md) { // String args = ""; // Argument[] argArray = md.arguments; // if (argArray == null) return args; // for (int i = 0; i < argArray.length; i++) { // String argName = new String(argArray[i].name); // String argType = argArray[i].type.toString(); // if (acceptArgument(argName, argType)) { // args += argType + ", "; // } // } // int lastSepIndex = args.lastIndexOf(','); // if (lastSepIndex != -1 && args.endsWith(", ")) args = args.substring(0, lastSepIndex); // return args; // } private void setParameters(MethodDeclaration md, IProgramElement pe) { Argument[] argArray = md.arguments; List names = new ArrayList(); List types = new ArrayList(); pe.setParameterNames(names); pe.setParameterTypes(types); if (argArray == null) return; for (int i = 0; i < argArray.length; i++) { String argName = new String(argArray[i].name); String argType = argArray[i].type.toString(); if (acceptArgument(argName, argType)) { names.add(argName); types.add(argType); } } } // TODO: fix this way of determing ajc-added arguments, make subtype of Argument with extra info private boolean acceptArgument(String name, String type) { return !name.startsWith("ajc$this_") && !type.equals("org.aspectj.lang.JoinPoint.StaticPart") && !type.equals("org.aspectj.lang.JoinPoint") && !type.equals("org.aspectj.runtime.internal.AroundClosure"); } public String genTypePatternLabel(TypePattern tp) { final String TYPE_PATTERN_LITERAL = "<type pattern>"; String label; TypeX typeX = tp.getExactType(); if (typeX != ResolvedTypeX.MISSING) { label = typeX.getName(); if (tp.isIncludeSubtypes()) label += "+"; } else { label = TYPE_PATTERN_LITERAL; } return label; } public String genDeclareMessage(String message) { int length = message.length(); if (length < MAX_MESSAGE_LENGTH) { return message; } else { return message.substring(0, MAX_MESSAGE_LENGTH-1) + ".."; } } // // TODO: // private String translateAdviceName(String label) { // if (label.indexOf("before") != -1) return "before"; // if (label.indexOf("returning") != -1) return "after returning"; // if (label.indexOf("after") != -1) return "after"; // if (label.indexOf("around") != -1) return "around"; // else return "<advice>"; // } // // !!! move or replace // private String translateDeclareName(String name) { // int colonIndex = name.indexOf(":"); // if (colonIndex != -1) { // return name.substring(0, colonIndex); // } else { // return name; // } // } // !!! move or replace // private String translateInterTypeDecName(String name) { // int index = name.lastIndexOf('$'); // if (index != -1) { // return name.substring(index+1); // } else { // return name; // } // } // !!! move or replace private String translatePointcutName(String name) { int index = name.indexOf("$$")+2; int endIndex = name.lastIndexOf('$'); if (index != -1 && endIndex != -1) { return name.substring(index, endIndex); } else { return name; } } }
73,334
Bug 73334 Avoid clashes in the org.eclipse namespace by renaming our duplicates.
We have recently renamed our 'copy' of BCEL to use a different package prefix so that our version never clashes with another version that might be around on a users system. This enhancement is to do the same thing for our 'copy' of the org.eclipse.jdt code (in the shadows project). As part of packaging the shadows project to create the 'jdtcore' jar files (bin and src) we will rename the packages from: org.eclipse.jdt.*** to org.aspectj.org.eclipse.jdt.** This has a really nice side effect that we can make our version of the compiler accessible in the IDE. It should now be possible for AJDT to work more closely with it and get features like eager parsing to work. Care will be taken that we don't accidentally make the merge process a nightmare.
resolved fixed
b133299
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2004-09-06T15:40:02Z
2004-09-06T17:00:00Z
org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/core/builder/AsmHierarchyBuilder.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Common Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * PARC initial implementation * ******************************************************************/ package org.aspectj.ajdt.internal.core.builder; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Iterator; import java.util.ListIterator; import java.util.Stack; import org.aspectj.ajdt.internal.compiler.ast.AspectDeclaration; import org.aspectj.ajdt.internal.compiler.ast.InterTypeDeclaration; import org.aspectj.ajdt.internal.compiler.lookup.EclipseFactory; import org.aspectj.asm.IHierarchy; import org.aspectj.asm.IProgramElement; import org.aspectj.asm.internal.ProgramElement; import org.aspectj.bridge.ISourceLocation; import org.aspectj.bridge.SourceLocation; import org.aspectj.util.LangUtil; import org.aspectj.weaver.Member; import org.aspectj.weaver.ResolvedMember; import org.eclipse.jdt.internal.compiler.ASTVisitor; import org.eclipse.jdt.internal.compiler.CompilationResult; import org.eclipse.jdt.internal.compiler.ast.ASTNode; import org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration; import org.eclipse.jdt.internal.compiler.ast.AbstractVariableDeclaration; import org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration; import org.eclipse.jdt.internal.compiler.ast.ConstructorDeclaration; import org.eclipse.jdt.internal.compiler.ast.ExtendedStringLiteral; import org.eclipse.jdt.internal.compiler.ast.FieldDeclaration; import org.eclipse.jdt.internal.compiler.ast.ImportReference; import org.eclipse.jdt.internal.compiler.ast.Initializer; import org.eclipse.jdt.internal.compiler.ast.MethodDeclaration; import org.eclipse.jdt.internal.compiler.ast.QualifiedAllocationExpression; import org.eclipse.jdt.internal.compiler.ast.TypeDeclaration; import org.eclipse.jdt.internal.compiler.lookup.BlockScope; import org.eclipse.jdt.internal.compiler.lookup.ClassScope; import org.eclipse.jdt.internal.compiler.lookup.CompilationUnitScope; import org.eclipse.jdt.internal.compiler.lookup.MethodScope; import org.eclipse.jdt.internal.compiler.problem.ProblemHandler; /** * At each iteration of <CODE>processCompilationUnit</CODE> the declarations for a * particular compilation unit are added to the hierarchy passed as a a parameter. * * Clients who extend this class need to ensure that they do not override any of the existing * behavior. If they do, the structure model will not be built properly and tools such as IDE * structure views and ajdoc will fail. * * @author Mik Kersten */ public class AsmHierarchyBuilder extends ASTVisitor { // public static void build( // CompilationUnitDeclaration unit, // IHierarchy structureModel, AjBuildConfig buildConfig) { // LangUtil.throwIaxIfNull(unit, "unit"); // new AsmHierarchyBuilder(unit., ).; // } protected AsmElementFormatter formatter = new AsmElementFormatter(); /** * Reset for every compilation unit. */ protected AjBuildConfig buildConfig; /** * Reset for every compilation unit. */ protected Stack stack; /** * Reset for every compilation unit. */ private CompilationResult currCompilationResult; /** * * @param cuDeclaration * @param buildConfig * @param structureModel hiearchy to add this unit's declarations to */ public void buildStructureForCompilationUnit(CompilationUnitDeclaration cuDeclaration, IHierarchy structureModel, AjBuildConfig buildConfig) { currCompilationResult = cuDeclaration.compilationResult(); LangUtil.throwIaxIfNull(currCompilationResult, "result"); stack = new Stack(); this.buildConfig = buildConfig; internalBuild(cuDeclaration, structureModel); // throw new RuntimeException("not implemented"); } private void internalBuild(CompilationUnitDeclaration unit, IHierarchy structureModel) { LangUtil.throwIaxIfNull(structureModel, "structureModel"); if (!currCompilationResult.equals(unit.compilationResult())) { throw new IllegalArgumentException("invalid unit: " + unit); } // ---- summary // add unit to package (or root if no package), // first removing any duplicate (XXX? removes children if 3 classes in same file?) // push the node on the stack // and traverse // -- create node to add final File file = new File(new String(unit.getFileName())); final IProgramElement cuNode; { // AMC - use the source start and end from the compilation unit decl int startLine = getStartLine(unit); int endLine = getEndLine(unit); ISourceLocation sourceLocation = new SourceLocation(file, startLine, endLine); cuNode = new ProgramElement( new String(file.getName()), IProgramElement.Kind.FILE_JAVA, sourceLocation, 0, "", new ArrayList()); } cuNode.addChild(new ProgramElement( "import declarations", IProgramElement.Kind.IMPORT_REFERENCE, null, 0, "", new ArrayList())); final IProgramElement addToNode = genAddToNode(unit, structureModel); // -- remove duplicates before adding (XXX use them instead?) if (addToNode!=null && addToNode.getChildren()!=null) { for (ListIterator itt = addToNode.getChildren().listIterator(); itt.hasNext(); ) { IProgramElement child = (IProgramElement)itt.next(); ISourceLocation childLoc = child.getSourceLocation(); if (null == childLoc) { // XXX ok, packages have null source locations // signal others? } else if (childLoc.getSourceFile().equals(file)) { itt.remove(); } } } // -- add and traverse addToNode.addChild(cuNode); stack.push(cuNode); unit.traverse(this, unit.scope); // -- update file map (XXX do this before traversal?) try { structureModel.addToFileMap(file.getCanonicalPath(), cuNode); } catch (IOException e) { System.err.println("IOException " + e.getMessage() + " creating path for " + file ); // XXX signal IOException when canonicalizing file path } } /** * Get/create the node (package or root) to add to. */ private IProgramElement genAddToNode( CompilationUnitDeclaration unit, IHierarchy structureModel) { final IProgramElement addToNode; { ImportReference currentPackage = unit.currentPackage; if (null == currentPackage) { addToNode = structureModel.getRoot(); } else { String pkgName; { StringBuffer nameBuffer = new StringBuffer(); final char[][] importName = currentPackage.getImportName(); final int last = importName.length-1; for (int i = 0; i < importName.length; i++) { nameBuffer.append(new String(importName[i])); if (i < last) { nameBuffer.append('.'); } } pkgName = nameBuffer.toString(); } IProgramElement pkgNode = null; if (structureModel!=null && structureModel.getRoot()!=null && structureModel.getRoot().getChildren()!=null) { for (Iterator it = structureModel.getRoot().getChildren().iterator(); it.hasNext(); ) { IProgramElement currNode = (IProgramElement)it.next(); if (pkgName.equals(currNode.getName())) { pkgNode = currNode; break; } } } if (pkgNode == null) { // note packages themselves have no source location pkgNode = new ProgramElement( pkgName, IProgramElement.Kind.PACKAGE, new ArrayList() ); structureModel.getRoot().addChild(pkgNode); } addToNode = pkgNode; } } return addToNode; } public boolean visit(TypeDeclaration typeDeclaration, CompilationUnitScope scope) { String name = new String(typeDeclaration.name); IProgramElement.Kind kind = IProgramElement.Kind.CLASS; if (typeDeclaration instanceof AspectDeclaration) kind = IProgramElement.Kind.ASPECT; else if (typeDeclaration.isInterface()) kind = IProgramElement.Kind.INTERFACE; IProgramElement peNode = new ProgramElement( name, kind, makeLocation(typeDeclaration), typeDeclaration.modifiers, "", new ArrayList()); peNode.setSourceSignature(genSourceSignature(typeDeclaration)); peNode.setFormalComment(generateJavadocComment(typeDeclaration)); ((IProgramElement)stack.peek()).addChild(peNode); stack.push(peNode); return true; } public void endVisit(TypeDeclaration typeDeclaration, CompilationUnitScope scope) { stack.pop(); } // ??? share impl with visit(TypeDeclaration, ..) ? public boolean visit(TypeDeclaration memberTypeDeclaration, ClassScope scope) { String name = new String(memberTypeDeclaration.name); //System.err.println("member type with name: " + name); IProgramElement.Kind kind = IProgramElement.Kind.CLASS; if (memberTypeDeclaration instanceof AspectDeclaration) kind = IProgramElement.Kind.ASPECT; else if (memberTypeDeclaration.isInterface()) kind = IProgramElement.Kind.INTERFACE; IProgramElement peNode = new ProgramElement( name, kind, makeLocation(memberTypeDeclaration), memberTypeDeclaration.modifiers, "", new ArrayList()); peNode.setSourceSignature(genSourceSignature(memberTypeDeclaration)); peNode.setFormalComment(generateJavadocComment(memberTypeDeclaration)); ((IProgramElement)stack.peek()).addChild(peNode); stack.push(peNode); return true; } public void endVisit(TypeDeclaration memberTypeDeclaration, ClassScope scope) { stack.pop(); } public boolean visit(TypeDeclaration memberTypeDeclaration, BlockScope scope) { // String name = new String(memberTypeDeclaration.name); String fullName = "<undefined>"; if (memberTypeDeclaration.allocation != null && memberTypeDeclaration.allocation.type != null) { // Create a name something like 'new Runnable() {..}' fullName = "new "+memberTypeDeclaration.allocation.type.toString()+"() {..}"; } else if (memberTypeDeclaration.binding != null && memberTypeDeclaration.binding.constantPoolName() != null) { // If we couldn't find a nice name like 'new Runnable() {..}' then use the number after the $ fullName = new String(memberTypeDeclaration.binding.constantPoolName()); int dollar = fullName.indexOf('$'); fullName = fullName.substring(dollar+1); } IProgramElement.Kind kind = IProgramElement.Kind.CLASS; if (memberTypeDeclaration.isInterface()) kind = IProgramElement.Kind.INTERFACE; IProgramElement peNode = new ProgramElement( fullName, kind, makeLocation(memberTypeDeclaration), memberTypeDeclaration.modifiers, "", new ArrayList()); peNode.setSourceSignature(genSourceSignature(memberTypeDeclaration)); peNode.setFormalComment(generateJavadocComment(memberTypeDeclaration)); ((IProgramElement)stack.peek()).addChild(peNode); stack.push(peNode); return true; } public void endVisit(TypeDeclaration memberTypeDeclaration, BlockScope scope) { stack.pop(); } private String genSourceSignature(TypeDeclaration typeDeclaration) { StringBuffer output = new StringBuffer(); typeDeclaration.printHeader(0, output); return output.toString(); } private IProgramElement findEnclosingClass(Stack stack) { for (int i = stack.size()-1; i >= 0; i--) { IProgramElement pe = (IProgramElement)stack.get(i); if (pe.getKind() == IProgramElement.Kind.CLASS) { return pe; } } return (IProgramElement)stack.peek(); } public boolean visit(MethodDeclaration methodDeclaration, ClassScope scope) { IProgramElement peNode = null; // For intertype decls, use the modifiers from the original signature, not the generated method if (methodDeclaration instanceof InterTypeDeclaration) { InterTypeDeclaration itd = (InterTypeDeclaration) methodDeclaration; ResolvedMember sig = itd.getSignature(); peNode = new ProgramElement( "", IProgramElement.Kind.ERROR, makeLocation(methodDeclaration), (sig!=null?sig.getModifiers():0), "", new ArrayList()); } else { peNode = new ProgramElement( "", IProgramElement.Kind.ERROR, makeLocation(methodDeclaration), methodDeclaration.modifiers, "", new ArrayList()); } formatter.genLabelAndKind(methodDeclaration, peNode); genBytecodeInfo(methodDeclaration, peNode); if (methodDeclaration.returnType!=null) { peNode.setCorrespondingType(methodDeclaration.returnType.toString()); } else { peNode.setCorrespondingType(null); } peNode.setSourceSignature(genSourceSignature(methodDeclaration)); peNode.setFormalComment(generateJavadocComment(methodDeclaration)); // TODO: add return type test if (peNode.getKind().equals(IProgramElement.Kind.METHOD)) { if (peNode.toLabelString().equals("main(String[])") && peNode.getModifiers().contains(IProgramElement.Modifiers.STATIC) && peNode.getAccessibility().equals(IProgramElement.Accessibility.PUBLIC)) { ((IProgramElement)stack.peek()).setRunnable(true); } } stack.push(peNode); return true; } private String genSourceSignature(MethodDeclaration methodDeclaration) { StringBuffer output = new StringBuffer(); ASTNode.printModifiers(methodDeclaration.modifiers, output); methodDeclaration.printReturnType(0, output).append(methodDeclaration.selector).append('('); if (methodDeclaration.arguments != null) { for (int i = 0; i < methodDeclaration.arguments.length; i++) { if (i > 0) output.append(", "); //$NON-NLS-1$ methodDeclaration.arguments[i].print(0, output); } } output.append(')'); if (methodDeclaration.thrownExceptions != null) { output.append(" throws "); //$NON-NLS-1$ for (int i = 0; i < methodDeclaration.thrownExceptions.length; i++) { if (i > 0) output.append(", "); //$NON-NLS-1$ methodDeclaration.thrownExceptions[i].print(0, output); } } return output.toString(); } private void genBytecodeInfo(MethodDeclaration methodDeclaration, IProgramElement peNode) { if (methodDeclaration.binding != null) { String memberName = ""; String memberBytecodeSignature = ""; try { Member member = EclipseFactory.makeResolvedMember(methodDeclaration.binding); memberName = member.getName(); memberBytecodeSignature = member.getSignature(); } catch (NullPointerException npe) { memberName = "<undefined>"; } peNode.setBytecodeName(memberName); peNode.setBytecodeSignature(memberBytecodeSignature); } ((IProgramElement)stack.peek()).addChild(peNode); } public void endVisit(MethodDeclaration methodDeclaration, ClassScope scope) { stack.pop(); } public boolean visit(ImportReference importRef, CompilationUnitScope scope) { int dotIndex = importRef.toString().lastIndexOf('.'); String currPackageImport = ""; if (dotIndex != -1) { currPackageImport = importRef.toString().substring(0, dotIndex); } if (!((ProgramElement)stack.peek()).getPackageName().equals(currPackageImport)) { IProgramElement peNode = new ProgramElement( new String(importRef.toString()), IProgramElement.Kind.IMPORT_REFERENCE, makeLocation(importRef), 0, "", new ArrayList()); ProgramElement imports = (ProgramElement)((ProgramElement)stack.peek()).getChildren().get(0); imports.addChild(0, peNode); stack.push(peNode); } return true; } public void endVisit(ImportReference importRef, CompilationUnitScope scope) { int dotIndex = importRef.toString().lastIndexOf('.'); String currPackageImport = ""; if (dotIndex != -1) { currPackageImport = importRef.toString().substring(0, dotIndex); } if (!((ProgramElement)stack.peek()).getPackageName().equals(currPackageImport)) { stack.pop(); } } public boolean visit(FieldDeclaration fieldDeclaration, MethodScope scope) { IProgramElement peNode = new ProgramElement( new String(fieldDeclaration.name), IProgramElement.Kind.FIELD, makeLocation(fieldDeclaration), fieldDeclaration.modifiers, "", new ArrayList()); peNode.setCorrespondingType(fieldDeclaration.type.toString()); peNode.setSourceSignature(genSourceSignature(fieldDeclaration)); peNode.setFormalComment(generateJavadocComment(fieldDeclaration)); ((IProgramElement)stack.peek()).addChild(peNode); stack.push(peNode); return true; } public void endVisit(FieldDeclaration fieldDeclaration, MethodScope scope) { stack.pop(); } /** * Checks if comments should be added to the model before generating. */ private String generateJavadocComment(ASTNode astNode) { if (buildConfig != null && !buildConfig.isGenerateJavadocsInModelMode()) return null; StringBuffer sb = new StringBuffer(); // !!! specify length? boolean completed = false; int startIndex = -1; if (astNode instanceof MethodDeclaration) { startIndex = ((MethodDeclaration)astNode).declarationSourceStart; } else if (astNode instanceof FieldDeclaration) { startIndex = ((FieldDeclaration)astNode).declarationSourceStart; } else if (astNode instanceof TypeDeclaration) { startIndex = ((TypeDeclaration)astNode).declarationSourceStart; } if (startIndex == -1) { return null; } else if (currCompilationResult.compilationUnit.getContents()[startIndex] == '/' // look for /** && currCompilationResult.compilationUnit.getContents()[startIndex+1] == '*' && currCompilationResult.compilationUnit.getContents()[startIndex+2] == '*') { for (int i = startIndex; i < astNode.sourceStart && !completed; i++) { char curr = currCompilationResult.compilationUnit.getContents()[i]; if (curr == '/' && sb.length() > 2 && sb.charAt(sb.length()-1) == '*') completed = true; // found */ sb.append(currCompilationResult.compilationUnit.getContents()[i]); } // System.err.println(">> " + sb.toString()); return sb.toString(); } else { return null; } } /** * Doesn't print qualified allocation expressions. */ private String genSourceSignature(FieldDeclaration fieldDeclaration) { StringBuffer output = new StringBuffer(); FieldDeclaration.printModifiers(fieldDeclaration.modifiers, output); fieldDeclaration.type.print(0, output).append(' ').append(fieldDeclaration.name); if (fieldDeclaration.initialization != null && !(fieldDeclaration.initialization instanceof QualifiedAllocationExpression)) { output.append(" = "); //$NON-NLS-1$ if (fieldDeclaration.initialization instanceof ExtendedStringLiteral) { output.append("\"<extended string literal>\""); } else { fieldDeclaration.initialization.printExpression(0, output); } } output.append(';'); return output.toString(); } // public boolean visit(ImportReference importRef, CompilationUnitScope scope) { // ProgramElementNode peNode = new ProgramElementNode( // new String(importRef.toString()), // ProgramElementNode.Kind., // makeLocation(importRef), // 0, // "", // new ArrayList()); // ((IProgramElement)stack.peek()).addChild(0, peNode); // stack.push(peNode); // return true; // } // public void endVisit(ImportReference importRef,CompilationUnitScope scope) { // stack.pop(); // } public boolean visit(ConstructorDeclaration constructorDeclaration, ClassScope scope) { if (constructorDeclaration.isDefaultConstructor) { stack.push(null); // a little wierd but does the job return true; } StringBuffer argumentsSignature = new StringBuffer(); argumentsSignature.append("("); if (constructorDeclaration.arguments!=null) { for (int i = 0;i<constructorDeclaration.arguments.length;i++) { argumentsSignature.append(constructorDeclaration.arguments[i]); if (i+1<constructorDeclaration.arguments.length) argumentsSignature.append(","); } } argumentsSignature.append(")"); IProgramElement peNode = new ProgramElement( new String(constructorDeclaration.selector)+argumentsSignature, IProgramElement.Kind.CONSTRUCTOR, makeLocation(constructorDeclaration), constructorDeclaration.modifiers, "", new ArrayList()); peNode.setModifiers(constructorDeclaration.modifiers); peNode.setSourceSignature(genSourceSignature(constructorDeclaration)); // Fix to enable us to anchor things from ctor nodes if (constructorDeclaration.binding != null) { String memberName = ""; String memberBytecodeSignature = ""; try { Member member = EclipseFactory.makeResolvedMember(constructorDeclaration.binding); memberName = member.getName(); memberBytecodeSignature = member.getSignature(); } catch (NullPointerException npe) { memberName = "<undefined>"; } peNode.setBytecodeName(memberName); peNode.setBytecodeSignature(memberBytecodeSignature); } ((IProgramElement)stack.peek()).addChild(peNode); stack.push(peNode); return true; } public void endVisit(ConstructorDeclaration constructorDeclaration, ClassScope scope) { stack.pop(); } private String genSourceSignature(ConstructorDeclaration constructorDeclaration) { StringBuffer output = new StringBuffer(); ASTNode.printModifiers(constructorDeclaration.modifiers, output); output.append(constructorDeclaration.selector).append('('); if (constructorDeclaration.arguments != null) { for (int i = 0; i < constructorDeclaration.arguments.length; i++) { if (i > 0) output.append(", "); //$NON-NLS-1$ constructorDeclaration.arguments[i].print(0, output); } } output.append(')'); if (constructorDeclaration.thrownExceptions != null) { output.append(" throws "); //$NON-NLS-1$ for (int i = 0; i < constructorDeclaration.thrownExceptions.length; i++) { if (i > 0) output.append(", "); //$NON-NLS-1$ constructorDeclaration.thrownExceptions[i].print(0, output); } } return output.toString(); } // public boolean visit(Clinit clinit, ClassScope scope) { // ProgramElementNode peNode = new ProgramElementNode( // "<clinit>", // ProgramElementNode.Kind.INITIALIZER, // makeLocation(clinit), // clinit.modifiers, // "", // new ArrayList()); // ((IProgramElement)stack.peek()).addChild(peNode); // stack.push(peNode); // return false; // } // public void endVisit(Clinit clinit, ClassScope scope) { // stack.pop(); // } /** This method works-around an odd traverse implementation on Initializer */ private Initializer inInitializer = null; public boolean visit(Initializer initializer, MethodScope scope) { if (initializer == inInitializer) return false; inInitializer = initializer; IProgramElement peNode = new ProgramElement( "...", IProgramElement.Kind.INITIALIZER, makeLocation(initializer), initializer.modifiers, "", new ArrayList()); ((IProgramElement)stack.peek()).addChild(peNode); stack.push(peNode); initializer.block.traverse(this, scope); stack.pop(); return false; } // ??? handle non-existant files private ISourceLocation makeLocation(ASTNode node) { String fileName = ""; if (currCompilationResult.getFileName() != null) { fileName = new String(currCompilationResult.getFileName()); } // AMC - different strategies based on node kind int startLine = getStartLine(node); int endLine = getEndLine(node); ISourceLocation loc = null; if ( startLine <= endLine ) { // found a valid end line for this node... loc = new SourceLocation(new File(fileName), startLine, endLine); } else { loc = new SourceLocation(new File(fileName), startLine); } return loc; } // AMC - overloaded set of methods to get start and end lines for // various ASTNode types. They have no common ancestor in the // hierarchy!! private int getStartLine( ASTNode n){ // if ( n instanceof AbstractVariableDeclaration ) return getStartLine( (AbstractVariableDeclaration)n); // if ( n instanceof AbstractMethodDeclaration ) return getStartLine( (AbstractMethodDeclaration)n); // if ( n instanceof TypeDeclaration ) return getStartLine( (TypeDeclaration)n); return ProblemHandler.searchLineNumber( currCompilationResult.lineSeparatorPositions, n.sourceStart); } // AMC - overloaded set of methods to get start and end lines for // various ASTNode types. They have no common ancestor in the // hierarchy!! private int getEndLine( ASTNode n){ if ( n instanceof AbstractVariableDeclaration ) return getEndLine( (AbstractVariableDeclaration)n); if ( n instanceof AbstractMethodDeclaration ) return getEndLine( (AbstractMethodDeclaration)n); if ( n instanceof TypeDeclaration ) return getEndLine( (TypeDeclaration)n); return ProblemHandler.searchLineNumber( currCompilationResult.lineSeparatorPositions, n.sourceEnd); } // AMC - overloaded set of methods to get start and end lines for // various ASTNode types. They have no common ancestor in the // hierarchy!! // private int getStartLine( AbstractVariableDeclaration avd ) { // return ProblemHandler.searchLineNumber( // currCompilationResult.lineSeparatorPositions, // avd.declarationSourceStart); // } // AMC - overloaded set of methods to get start and end lines for // various ASTNode types. They have no common ancestor in the // hierarchy!! private int getEndLine( AbstractVariableDeclaration avd ){ return ProblemHandler.searchLineNumber( currCompilationResult.lineSeparatorPositions, avd.declarationSourceEnd); } // AMC - overloaded set of methods to get start and end lines for // various ASTNode types. They have no common ancestor in the // hierarchy!! // private int getStartLine( AbstractMethodDeclaration amd ){ // return ProblemHandler.searchLineNumber( // currCompilationResult.lineSeparatorPositions, // amd.declarationSourceStart); // } // AMC - overloaded set of methods to get start and end lines for // various ASTNode types. They have no common ancestor in the // hierarchy!! private int getEndLine( AbstractMethodDeclaration amd) { return ProblemHandler.searchLineNumber( currCompilationResult.lineSeparatorPositions, amd.declarationSourceEnd); } // AMC - overloaded set of methods to get start and end lines for // various ASTNode types. They have no common ancestor in the // hierarchy!! // private int getStartLine( TypeDeclaration td ){ // return ProblemHandler.searchLineNumber( // currCompilationResult.lineSeparatorPositions, // td.declarationSourceStart); // } // AMC - overloaded set of methods to get start and end lines for // various ASTNode types. They have no common ancestor in the // hierarchy!! private int getEndLine( TypeDeclaration td){ return ProblemHandler.searchLineNumber( currCompilationResult.lineSeparatorPositions, td.declarationSourceEnd); } }
73,334
Bug 73334 Avoid clashes in the org.eclipse namespace by renaming our duplicates.
We have recently renamed our 'copy' of BCEL to use a different package prefix so that our version never clashes with another version that might be around on a users system. This enhancement is to do the same thing for our 'copy' of the org.eclipse.jdt code (in the shadows project). As part of packaging the shadows project to create the 'jdtcore' jar files (bin and src) we will rename the packages from: org.eclipse.jdt.*** to org.aspectj.org.eclipse.jdt.** This has a really nice side effect that we can make our version of the compiler accessible in the IDE. It should now be possible for AJDT to work more closely with it and get features like eager parsing to work. Care will be taken that we don't accidentally make the merge process a nightmare.
resolved fixed
b133299
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2004-09-06T15:40:02Z
2004-09-06T17:00:00Z
org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/core/builder/AspectJBuilder.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.core.builder; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.Locale; import java.util.Map; import java.util.Properties; import org.aspectj.ajdt.core.AspectJCore; 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.AjLookupEnvironment; import org.aspectj.ajdt.internal.compiler.lookup.EclipseFactory; import org.aspectj.ajdt.internal.compiler.problem.AjProblemReporter; import org.aspectj.bridge.AbortException; import org.aspectj.bridge.IMessage; import org.aspectj.bridge.IMessageHandler; import org.aspectj.bridge.IMessage.Kind; import org.aspectj.weaver.Lint; import org.aspectj.weaver.bcel.BcelWeaver; import org.aspectj.weaver.bcel.BcelWorld; import org.eclipse.core.resources.IMarker; import org.eclipse.core.resources.IProject; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.Path; import org.eclipse.jdt.core.IJavaModelMarker; import org.eclipse.jdt.core.JavaCore; import org.eclipse.jdt.core.JavaModelException; import org.eclipse.jdt.internal.compiler.CompilationResult; import org.eclipse.jdt.internal.compiler.Compiler; import org.eclipse.jdt.internal.compiler.DefaultErrorHandlingPolicies; import org.eclipse.jdt.internal.compiler.ICompilerAdapter; import org.eclipse.jdt.internal.compiler.ICompilerAdapterFactory; import org.eclipse.jdt.internal.compiler.problem.DefaultProblemFactory; import org.eclipse.jdt.internal.core.builder.BatchImageBuilder; import org.eclipse.jdt.internal.core.builder.BuildNotifier; import org.eclipse.jdt.internal.core.builder.IncrementalImageBuilder; import org.eclipse.jdt.internal.core.builder.JavaBuilder; /** * @author colyer * * This is the builder class used by AJDT, and that the org.eclipse.ajdt.core * plugin references. */ public class AspectJBuilder extends JavaBuilder implements ICompilerAdapterFactory { // One builder instance per project (important) private BcelWeaver myWeaver = null; private BcelWorld myBcelWorld = null; private EclipseClassPathManager cpManager = null; private UnwovenResultCollector unwovenResultCollector = null; private OutputFileNameProvider fileNameProvider = null; private boolean isBatchBuild = false; /* (non-Javadoc) * @see org.eclipse.core.internal.events.InternalBuilder#build(int, java.util.Map, org.eclipse.core.runtime.IProgressMonitor) */ protected IProject[] build(int kind, Map ignored, IProgressMonitor monitor) throws CoreException { // super method always causes construction of a new XXXImageBuilder, which // causes construction of a new Compiler, so we will be detected as the // adapter. Compiler.setCompilerAdapterFactory(this); return super.build(kind, ignored, monitor); } protected BatchImageBuilder getBatchImageBuilder() { isBatchBuild = true; return new AjBatchImageBuilder(this); } protected IncrementalImageBuilder getIncrementalImageBuilder() { isBatchBuild = false; return new AjIncrementalImageBuilder(this); } /* (non-Javadoc) * @see org.eclipse.jdt.internal.compiler.ICompilerAdapterFactory#getAdapter(org.eclipse.jdt.internal.compiler.Compiler) */ public ICompilerAdapter getAdapter(Compiler forCompiler) { Map javaOptions = forCompiler.options.getMap(); // TODO get aspectj options from project and add into map before... AjCompilerOptions ajOptions = new AjCompilerOptions(javaOptions); forCompiler.options = ajOptions; if (isBatchBuild || myBcelWorld == null || myWeaver == null) { initWorldAndWeaver(ajOptions); } else { // update the nameEnvironment each time we compile... cpManager.setNameEnvironment(nameEnvironment); } // * an eclipse factory -- create from AjLookupEnvironment, need to hide AjBuildManager field AjProblemReporter pr = new AjProblemReporter(DefaultErrorHandlingPolicies.proceedWithAllProblems(), forCompiler.options, new DefaultProblemFactory(Locale.getDefault())); forCompiler.problemReporter = pr; AjLookupEnvironment le = new AjLookupEnvironment(forCompiler, forCompiler.options, pr,nameEnvironment); EclipseFactory eFactory = new EclipseFactory(le,myBcelWorld,ajOptions.xSerializableAspects); le.factory = eFactory; forCompiler.lookupEnvironment = le; AjBuildNotifier ajNotifier = (AjBuildNotifier) notifier; if (fileNameProvider == null ) fileNameProvider = new OutputFileNameProvider(getProject()); // * the set of binary source entries for this compile -- from analyzing deltas, or everything if batch // * the full set of binary source entries for the project -- from IAspectJProject // TODO deal with inpath, injars here... IBinarySourceProvider bsProvider = new NullBinarySourceProvider(); Map fullBinarySourceEntries = new HashMap(); // * the intermediate result set from the last batch compile if (isBatchBuild) { unwovenResultCollector = new UnwovenResultCollector(); } Collection resultSetForFullWeave = unwovenResultCollector.getIntermediateResults(); return new AjCompilerAdapter(forCompiler,isBatchBuild,myBcelWorld, myWeaver,eFactory,unwovenResultCollector,ajNotifier,fileNameProvider,bsProvider, fullBinarySourceEntries,resultSetForFullWeave, ajOptions.noWeave); } /* (non-Javadoc) * @see org.eclipse.jdt.internal.core.builder.JavaBuilder#createBuildNotifier(org.eclipse.core.runtime.IProgressMonitor, org.eclipse.core.resources.IProject) */ protected BuildNotifier createBuildNotifier(IProgressMonitor monitor, IProject currentProject) { return new AjBuildNotifier(monitor, currentProject); } private void initWorldAndWeaver(AjCompilerOptions options) { cpManager = new EclipseClassPathManager(nameEnvironment); myBcelWorld = new BcelWorld(cpManager,new UnhandledMessageHandler(getProject()),null /*(xrefHandler)*/); myBcelWorld.setXnoInline(options.xNoInline); myBcelWorld.setXlazyTjp(options.xLazyThisJoinPoint); setLintProperties(myBcelWorld,options); myWeaver = new BcelWeaver(myBcelWorld); myWeaver.setReweavableMode(options.xReweavable,options.xReweavableCompress); // TODO deal with injars, inpath, and aspectpath here... } private void setLintProperties(BcelWorld world, AjCompilerOptions options) { Properties p = new Properties(); Lint lintSettings = world.getLint(); Map map = options.getMap(); p.put(lintSettings.invalidAbsoluteTypeName.getName(),map.get(AjCompilerOptions.OPTION_ReportInvalidAbsoluteTypeName)); p.put(lintSettings.invalidWildcardTypeName.getName(),map.get(AjCompilerOptions.OPTION_ReportInvalidWildcardTypeName)); p.put(lintSettings.unresolvableMember.getName(),map.get(AjCompilerOptions.OPTION_ReportUnresolvableMember)); p.put(lintSettings.typeNotExposedToWeaver.getName(),map.get(AjCompilerOptions.OPTION_ReportTypeNotExposedToWeaver)); p.put(lintSettings.shadowNotInStructure.getName(),map.get(AjCompilerOptions.OPTION_ReportShadowNotInStructure)); p.put(lintSettings.unmatchedSuperTypeInCall.getName(),map.get(AjCompilerOptions.OPTION_ReportUnmatchedSuperTypeInCall)); p.put(lintSettings.canNotImplementLazyTjp.getName(),map.get(AjCompilerOptions.OPTION_ReportCannotImplementLazyTJP)); p.put(lintSettings.needsSerialVersionUIDField.getName(),map.get(AjCompilerOptions.OPTION_ReportNeedSerialVersionUIDField)); p.put(lintSettings.serialVersionUIDBroken.getName(),map.get(AjCompilerOptions.OPTION_ReportIncompatibleSerialVersion)); lintSettings.setFromProperties(p); } private static class UnwovenResultCollector implements IIntermediateResultsRequestor { private Collection results = new ArrayList(); /* (non-Javadoc) * @see org.aspectj.ajdt.internal.compiler.IIntermediateResultsRequestor#acceptResult(org.aspectj.ajdt.internal.compiler.InterimCompilationResult) */ public void acceptResult(InterimCompilationResult intRes) { results.add(intRes); } public Collection getIntermediateResults() { return results; } } // this class will only get messages that the weaver adapter couldn't tie into // an originating resource in the project - make them messages on the project // itself. private static class UnhandledMessageHandler implements IMessageHandler { private IProject project; public UnhandledMessageHandler(IProject p) { this.project = p; } /* (non-Javadoc) * @see org.aspectj.bridge.IMessageHandler#handleMessage(org.aspectj.bridge.IMessage) */ public boolean handleMessage(IMessage message) throws AbortException { try { IMarker marker = project.createMarker(IJavaModelMarker.JAVA_MODEL_PROBLEM_MARKER); marker.setAttribute(IMarker.MESSAGE, message.getMessage()); marker.setAttribute(IMarker.SEVERITY, message.isError() ? IMarker.SEVERITY_ERROR : IMarker.SEVERITY_WARNING); } catch (CoreException e) { AspectJCore.getPlugin().getLog().log(e.getStatus()); } return true; } /* (non-Javadoc) * @see org.aspectj.bridge.IMessageHandler#isIgnoring(org.aspectj.bridge.IMessage.Kind) */ public boolean isIgnoring(Kind kind) { if (kind == IMessage.DEBUG || kind == IMessage.INFO) return true; return false; } } private static class OutputFileNameProvider implements IOutputClassFileNameProvider { private IPath outputLocation; public OutputFileNameProvider(IProject p) { try { outputLocation = JavaCore.create(p).getOutputLocation(); } catch (JavaModelException e) { outputLocation = new Path("."); AspectJCore.getPlugin().getLog().log(e.getStatus()); } } /* (non-Javadoc) * @see org.aspectj.ajdt.internal.compiler.IOutputClassFileNameProvider#getOutputClassFileName(char[], org.eclipse.jdt.internal.compiler.CompilationResult) */ public String getOutputClassFileName(char[] eclipseClassFileName, CompilationResult result) { // In the AJDT implementation, the name provided here will be ignored, we write the results // out in xxxImageBuilder.acceptResult() instead. // simply return the default output directory for the project. String filename = new String(eclipseClassFileName); IPath out = outputLocation.append(filename); out.addFileExtension(".class"); return out.toOSString(); } } // default impl class until the implementation is extended to cope with inpath, injars private static class NullBinarySourceProvider implements IBinarySourceProvider { /* (non-Javadoc) * @see org.aspectj.ajdt.internal.compiler.IBinarySourceProvider#getBinarySourcesForThisWeave() */ public Map getBinarySourcesForThisWeave() { return new HashMap(); } } }
73,334
Bug 73334 Avoid clashes in the org.eclipse namespace by renaming our duplicates.
We have recently renamed our 'copy' of BCEL to use a different package prefix so that our version never clashes with another version that might be around on a users system. This enhancement is to do the same thing for our 'copy' of the org.eclipse.jdt code (in the shadows project). As part of packaging the shadows project to create the 'jdtcore' jar files (bin and src) we will rename the packages from: org.eclipse.jdt.*** to org.aspectj.org.eclipse.jdt.** This has a really nice side effect that we can make our version of the compiler accessible in the IDE. It should now be possible for AJDT to work more closely with it and get features like eager parsing to work. Care will be taken that we don't accidentally make the merge process a nightmare.
resolved fixed
b133299
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2004-09-06T15:40:02Z
2004-09-06T17:00:00Z
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)) || compilationUnit==null) //return Util.bind("problem.noSourceInformation"); //$NON-NLS-1$ return "(no source information available)"; final char SPACE = '\u0020'; final char MARK = '^'; final char TAB = '\t'; char[] source = compilationUnit.getContents(); //the next code tries to underline the token..... //it assumes (for a good display) that token source does not //contain any \r \n. This is false on statements ! //(the code still works but the display is not optimal !) //compute the how-much-char we are displaying around the inaccurate token int begin = startPosition >= source.length ? source.length - 1 : startPosition; int relativeStart = 0; int end = endPosition >= source.length ? source.length - 1 : endPosition; int relativeEnd = 0; label : for (relativeStart = 0;; relativeStart++) { if (begin == 0) break label; if ((source[begin - 1] == '\n') || (source[begin - 1] == '\r')) break label; begin--; } label : for (relativeEnd = 0;; relativeEnd++) { if ((end + 1) >= source.length) break label; if ((source[end + 1] == '\r') || (source[end + 1] == '\n')) { break label; } end++; } //extract the message form the source char[] extract = new char[end - begin + 1]; System.arraycopy(source, begin, extract, 0, extract.length); char c; //remove all SPACE and TAB that begin the error message... int trimLeftIndex = 0; while (((c = extract[trimLeftIndex++]) == TAB) || (c == SPACE)) { }; System.arraycopy( extract, trimLeftIndex - 1, extract = new char[extract.length - trimLeftIndex + 1], 0, extract.length); relativeStart -= trimLeftIndex; //buffer spaces and tabs in order to reach the error position int pos = 0; char[] underneath = new char[extract.length]; // can't be bigger for (int i = 0; i <= relativeStart; i++) { if (extract[i] == TAB) { underneath[pos++] = TAB; } else { underneath[pos++] = SPACE; } } //mark the error position for (int i = startPosition + trimLeftIndex; // AMC if we took stuff off the start, take it into account! i <= (endPosition >= source.length ? source.length - 1 : endPosition); i++) underneath[pos++] = MARK; //resize underneathto remove 'null' chars System.arraycopy(underneath, 0, underneath = new char[pos], 0, pos); return new String(extract) + "\n" + new String(underneath); //$NON-NLS-2$ //$NON-NLS-1$ } /** * Extract source location file, start and end lines, and context. * Column is not extracted correctly. * @return ISourceLocation with correct file and lines but not column. */ public static ISourceLocation makeSourceLocation(ICompilationUnit unit, IProblem problem) { int line = problem.getSourceLineNumber(); File file = new File(new String(problem.getOriginatingFileName())); String context = makeLocationContext(unit, problem); // XXX 0 column is wrong but recoverable from makeLocationContext return new SourceLocation(file, line, line, 0, context); } /** * Extract message text and source location, including context. */ public static IMessage makeMessage(ICompilationUnit unit, IProblem problem) { ISourceLocation sourceLocation = makeSourceLocation(unit, problem); IProblem[] seeAlso = problem.seeAlso(); ISourceLocation[] seeAlsoLocations = new ISourceLocation[seeAlso.length]; for (int i = 0; i < seeAlso.length; i++) { seeAlsoLocations[i] = new SourceLocation(new File(new String(seeAlso[i].getOriginatingFileName())), seeAlso[i].getSourceLineNumber()); } // We transform messages from AJ types to eclipse IProblems // and back to AJ types. During their time as eclipse problems, // we remember whether the message originated from a declare // in the extraDetails. String extraDetails = problem.getSupplementaryMessageInfo(); boolean declared = false; if (extraDetails!=null && extraDetails.endsWith("[deow=true]")) { declared = true; extraDetails = extraDetails.substring(0,extraDetails.length()-"[deow=true]".length()); } IMessage msg = new Message(problem.getMessage(), extraDetails, problem.isError() ? IMessage.ERROR : IMessage.WARNING, sourceLocation, null, seeAlsoLocations, declared, problem.getID(), problem.getSourceStart(),problem.getSourceEnd()); return msg; } public static IMessage makeErrorMessage(ICompilationUnit unit, String text, Exception ex) { ISourceLocation loc = new SourceLocation(new File(new String(unit.getFileName())), 0,0,0,""); IMessage msg = new Message(text,IMessage.ERROR,ex,loc); return msg; } public static IMessage makeErrorMessage(String srcFile, String text, Exception ex) { ISourceLocation loc = new SourceLocation(new File(srcFile), 0,0,0,""); IMessage msg = new Message(text,IMessage.ERROR,ex,loc); return msg; } private EclipseAdapterUtils() { } }
73,334
Bug 73334 Avoid clashes in the org.eclipse namespace by renaming our duplicates.
We have recently renamed our 'copy' of BCEL to use a different package prefix so that our version never clashes with another version that might be around on a users system. This enhancement is to do the same thing for our 'copy' of the org.eclipse.jdt code (in the shadows project). As part of packaging the shadows project to create the 'jdtcore' jar files (bin and src) we will rename the packages from: org.eclipse.jdt.*** to org.aspectj.org.eclipse.jdt.** This has a really nice side effect that we can make our version of the compiler accessible in the IDE. It should now be possible for AJDT to work more closely with it and get features like eager parsing to work. Care will be taken that we don't accidentally make the merge process a nightmare.
resolved fixed
b133299
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2004-09-06T15:40:02Z
2004-09-06T17:00:00Z
org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/core/builder/EclipseClassPathManager.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.core.builder; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.util.List; import org.aspectj.bridge.IMessageHandler; import org.aspectj.weaver.TypeX; import org.aspectj.weaver.bcel.ClassPathManager; import org.eclipse.jdt.core.compiler.CharOperation; import org.eclipse.jdt.internal.compiler.classfmt.ClassFileReader; import org.eclipse.jdt.internal.compiler.env.IBinaryType; import org.eclipse.jdt.internal.compiler.env.INameEnvironment; import org.eclipse.jdt.internal.compiler.env.NameEnvironmentAnswer; /** * @author colyer * * Provide a type lookup environment for the weaver, without having to convert * the various eclipse paths into their external form. */ public class EclipseClassPathManager extends ClassPathManager { private INameEnvironment nameEnv; public EclipseClassPathManager(INameEnvironment env) { this.nameEnv = env; } // class path manager will be used by weaver across multiple compiles, // whereas a name environment may be constructed per-compile. public void setNameEnvironment(INameEnvironment env) { this.nameEnv = env; } /* (non-Javadoc) * @see org.aspectj.weaver.bcel.ClassPathManager#addPath(java.lang.String, org.aspectj.bridge.IMessageHandler) */ public void addPath(String name, IMessageHandler handler) { throw new UnsupportedOperationException("Can't add paths to an *Eclipse*ClassPathManager."); } /* (non-Javadoc) * @see org.aspectj.weaver.bcel.ClassPathManager#find(org.aspectj.weaver.TypeX) */ public ClassFile find(TypeX type) { ClassFile cf = null; String name = type.getName(); if (name.endsWith(".class")) { name = name.substring(0,name.length() - ".class".length()); } char[][] cname = CharOperation.splitOn('.',name.toCharArray()); NameEnvironmentAnswer answer = nameEnv.findType(cname); if (answer == null || !answer.isBinaryType()) { return null; } else { IBinaryType binType = answer.getBinaryType(); // XXX - but better than the alternative hacks if (binType instanceof ClassFileReader) { ClassFileReader cfr = (ClassFileReader) binType; cf = new ClassFileReaderBackedClassFile(cfr); } else { throw new IllegalArgumentException( "I'm only geared up to handle ClassFileReaders, and you gave me a " + binType.getClass().getName()); } return cf; } } /* (non-Javadoc) * @see org.aspectj.weaver.bcel.ClassPathManager#getAllClassFiles() */ public List getAllClassFiles() { throw new UnsupportedOperationException("I don't implement getAllClassFiles()"); //return Collections.EMPTY_LIST; } /* (non-Javadoc) * @see java.lang.Object#toString() */ public String toString() { StringBuffer buf = new StringBuffer("EclipseClassPathManager: "); buf.append(nameEnv.toString()); return buf.toString(); } private class ClassFileReaderBackedClassFile extends ClassPathManager.ClassFile { private ClassFileReader source; public ClassFileReaderBackedClassFile(ClassFileReader cfr) { source = cfr; } /* (non-Javadoc) * @see org.aspectj.weaver.bcel.ClassPathManager.ClassFile#getInputStream() */ public InputStream getInputStream() throws IOException { return new ByteArrayInputStream(source.getReferenceBytes()); } /* (non-Javadoc) * @see org.aspectj.weaver.bcel.ClassPathManager.ClassFile#getPath() */ public String getPath() { return new String(source.getFileName()); } } }
73,334
Bug 73334 Avoid clashes in the org.eclipse namespace by renaming our duplicates.
We have recently renamed our 'copy' of BCEL to use a different package prefix so that our version never clashes with another version that might be around on a users system. This enhancement is to do the same thing for our 'copy' of the org.eclipse.jdt code (in the shadows project). As part of packaging the shadows project to create the 'jdtcore' jar files (bin and src) we will rename the packages from: org.eclipse.jdt.*** to org.aspectj.org.eclipse.jdt.** This has a really nice side effect that we can make our version of the compiler accessible in the IDE. It should now be possible for AJDT to work more closely with it and get features like eager parsing to work. Care will be taken that we don't accidentally make the merge process a nightmare.
resolved fixed
b133299
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2004-09-06T15:40:02Z
2004-09-06T17:00:00Z
org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/core/builder/EclipseSourceContext.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.File; import org.aspectj.ajdt.internal.compiler.lookup.EclipseSourceLocation; import org.aspectj.bridge.ISourceLocation; import org.aspectj.bridge.SourceLocation; import org.aspectj.weaver.IHasPosition; import org.aspectj.weaver.ISourceContext; import org.eclipse.jdt.internal.compiler.CompilationResult; public class EclipseSourceContext implements ISourceContext { CompilationResult result; public EclipseSourceContext(CompilationResult result) { this.result = result; } private File getSourceFile() { return new File(new String(result.fileName)); } public ISourceLocation makeSourceLocation(IHasPosition position) { return new EclipseSourceLocation(result, position.getStart(), position.getEnd()); } public ISourceLocation makeSourceLocation(int line) { return new SourceLocation(getSourceFile(), line); } }
73,334
Bug 73334 Avoid clashes in the org.eclipse namespace by renaming our duplicates.
We have recently renamed our 'copy' of BCEL to use a different package prefix so that our version never clashes with another version that might be around on a users system. This enhancement is to do the same thing for our 'copy' of the org.eclipse.jdt code (in the shadows project). As part of packaging the shadows project to create the 'jdtcore' jar files (bin and src) we will rename the packages from: org.eclipse.jdt.*** to org.aspectj.org.eclipse.jdt.** This has a really nice side effect that we can make our version of the compiler accessible in the IDE. It should now be possible for AJDT to work more closely with it and get features like eager parsing to work. Care will be taken that we don't accidentally make the merge process a nightmare.
resolved fixed
b133299
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2004-09-06T15:40:02Z
2004-09-06T17:00:00Z
org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/core/builder/StatefulNameEnvironment.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.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.Map; import java.util.Set; import org.aspectj.weaver.bcel.UnwovenClassFile; import org.eclipse.jdt.core.compiler.CharOperation; import org.eclipse.jdt.internal.compiler.classfmt.ClassFileReader; import org.eclipse.jdt.internal.compiler.classfmt.ClassFormatException; import org.eclipse.jdt.internal.compiler.env.INameEnvironment; import org.eclipse.jdt.internal.compiler.env.NameEnvironmentAnswer; public class StatefulNameEnvironment implements INameEnvironment { Map classesFromName; Set packageNames; INameEnvironment baseEnvironment; public StatefulNameEnvironment(INameEnvironment baseEnvironment, Map classesFromName) { this.classesFromName = classesFromName; this.baseEnvironment = baseEnvironment; packageNames = new HashSet(); for (Iterator i = classesFromName.keySet().iterator(); i.hasNext(); ) { String className = (String)i.next(); addAllPackageNames(className); } // System.err.println(packageNames); } private void addAllPackageNames(String className) { int dot = className.indexOf('.'); while (dot != -1) { packageNames.add(className.substring(0, dot)); dot = className.indexOf('.', dot+1); } } public void cleanup() { baseEnvironment.cleanup(); } private NameEnvironmentAnswer findType(String name) { UnwovenClassFile cf = (UnwovenClassFile)classesFromName.get(name); //System.err.println("find: " + name + " found: " + cf); if (cf == null) return null; try { //System.out.println("from cache: " + name); return new NameEnvironmentAnswer(new ClassFileReader(cf.getBytes(), cf.getFilename().toCharArray())); } catch (ClassFormatException e) { return null; //!!! seems to match FileSystem behavior } } public NameEnvironmentAnswer findType( char[] typeName, char[][] packageName) { NameEnvironmentAnswer ret = findType(new String(CharOperation.concatWith(packageName, typeName, '.'))); if (ret != null) return ret; return baseEnvironment.findType(typeName, packageName); } public NameEnvironmentAnswer findType(char[][] compoundName) { NameEnvironmentAnswer ret = findType(new String(CharOperation.concatWith(compoundName, '.'))); if (ret != null) return ret; return baseEnvironment.findType(compoundName); } public boolean isPackage(char[][] parentPackageName, char[] packageName) { if (baseEnvironment.isPackage(parentPackageName, packageName)) return true; String fullPackageName = new String(CharOperation.concatWith(parentPackageName, packageName, '.')); return packageNames.contains(fullPackageName); } }
73,334
Bug 73334 Avoid clashes in the org.eclipse namespace by renaming our duplicates.
We have recently renamed our 'copy' of BCEL to use a different package prefix so that our version never clashes with another version that might be around on a users system. This enhancement is to do the same thing for our 'copy' of the org.eclipse.jdt code (in the shadows project). As part of packaging the shadows project to create the 'jdtcore' jar files (bin and src) we will rename the packages from: org.eclipse.jdt.*** to org.aspectj.org.eclipse.jdt.** This has a really nice side effect that we can make our version of the compiler accessible in the IDE. It should now be possible for AJDT to work more closely with it and get features like eager parsing to work. Care will be taken that we don't accidentally make the merge process a nightmare.
resolved fixed
b133299
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2004-09-06T15:40:02Z
2004-09-06T17:00:00Z
org.aspectj.ajdt.core/testsrc/WeaveTests.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: * Noel Markham, Matthew Webster initial implementation * ******************************************************************/ import java.io.BufferedOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; /** * @author Noel Markham */ public class WeaveTests { private static final String OUTPUT_PACKAGE = "out"; private static final int WEAVE_FAST = 1; private static final int WEAVE_MED = 2; private static final int WEAVE_SLOW = 3; public static final String EXECUTION_SLOW = "execution(void *(..))"; public static final String EXECUTION_MED = "args(" + OUTPUT_PACKAGE + ".C0) && execution(void m0(..))"; public static final String EXECUTION_FAST = "within(" + OUTPUT_PACKAGE + ".C0) && execution(void m0(..))"; public static final String GET_SLOW = "get(int *)"; public static final String GET_MED = "target(" + OUTPUT_PACKAGE + ".C0) && get(int i0)"; public static final String GET_FAST = "get(int " + OUTPUT_PACKAGE + ".C0.i0)"; // Defaults, can be changed with command-line args private static int NUMCLASSES = 5; private static int ITERATIONS = 3; private static int METHODLINES = 20; private static int NUMMETHODS = 100; private static boolean INCLUDE_TEST_CLASSES = false; private static boolean TEST_GET = true; private static boolean TEST_EXECUTION = true; private static boolean ALL_POINTCUT_TESTS = true; private static boolean TEST_ONE = false; private static boolean TEST_ONE_SEARCH_ALL = false; private static boolean TEST_ALL = false; private static boolean ECHO = false; public static long[] compileTimes = new long[ITERATIONS]; public static long[] executionSlowTimes = new long[ITERATIONS]; public static long[] executionMedTimes = new long[ITERATIONS]; public static long[] executionFastTimes = new long[ITERATIONS]; public static long[] getSlowTimes = new long[ITERATIONS]; public static long[] getMedTimes = new long[ITERATIONS]; public static long[] getFastTimes = new long[ITERATIONS]; private static final String NL = System.getProperty("line.separator", "\n"); private static final File outputDir = new File(System.getProperty("user.dir") + File.separatorChar + OUTPUT_PACKAGE); static { outputDir.mkdirs(); } public static void main(String[] args) throws IOException { //if (args.length > 0) parseArgs(args); parseArgs(args); if(ECHO) System.out.println("Weave-time Test"); if(ECHO) System.out.println("---------------"); if(ECHO) System.out.println("Number of classes: " + NUMCLASSES); if(ECHO) System.out.println("Number of methods: " + NUMMETHODS); if(ECHO) System.out.println("Number of method lines: " + METHODLINES); if(ECHO) System.out.println("Number of test iterations: " + ITERATIONS); if(ECHO) if(INCLUDE_TEST_CLASSES) System.out.println("Including advice test classes"); if(ECHO) if(TEST_GET && !TEST_EXECUTION) System.out.println("Weaving only get advice"); if(ECHO) if(TEST_EXECUTION && !TEST_GET) System.out.println("Weaving only execution advice"); if(ECHO) { if(!ALL_POINTCUT_TESTS) { if(TEST_ONE) System.out.println("Weaving one poinctcut"); if(TEST_ONE_SEARCH_ALL) System.out.println("Weaving one pointcut, searching all"); if(TEST_ALL) System.out.println("Weaving all"); } } if(ECHO) System.out.println(); createClasses(); compileClasses(); boolean warm = false; if (TEST_EXECUTION) { String advice = "execution"; createAspects(advice); //Warm up the weaver weaveAllAspects(advice, WEAVE_FAST); warm = true; weaveAspects(advice); } if (TEST_GET) { String advice = "get"; createAspects(advice); if(!warm) weaveAllAspects(advice, WEAVE_FAST); weaveAspects(advice); } } private static void parseArgs(String[] args) { if(args == null || args.length <= 0) return; int i = 0; boolean error = false; while(i < args.length) { String arg = args[i++]; try { if(arg.equals("-c")) { // Number of classes if(i < args.length) NUMCLASSES = Integer.parseInt(args[i++]); else error = true; } else if(arg.equals("-m")) { // Number of methods if(i < args.length) NUMMETHODS = Integer.parseInt(args[i++]); else error = true; } else if(arg.equals("-l")) { // Number of method lines if(i < args.length) METHODLINES = Integer.parseInt(args[i++]); else error = true; } else if(arg.equals("-i")) { // Number of iterations if(i < args.length) ITERATIONS = Integer.parseInt(args[i++]); else error = true; } else if(arg.equals("-include-tests")) { if(i < args.length) { arg = args[i++]; if(arg.equalsIgnoreCase("y")) INCLUDE_TEST_CLASSES = true; else if(arg.equalsIgnoreCase("n")) INCLUDE_TEST_CLASSES = false; else error = true; } } else if(arg.equals("-advice")) { String advice = args[i++]; if(advice.equals("get")){ TEST_GET = true; TEST_EXECUTION = false; } else if(advice.equals("execution")){ TEST_EXECUTION = true; TEST_GET = false; } else error = true; } else if(arg.equals("-pointcut")) { ALL_POINTCUT_TESTS = false; String advice = args[i++]; if(advice.equals("fast")) TEST_ONE = true; else if(advice.equals("meduim")) TEST_ONE_SEARCH_ALL = true; else if(advice.equals("slow")) TEST_ALL = true; else error = true; } else if(arg.equals("-echo")) { ECHO = true; } else if (arg.equals("-help")) { usage(); } else error = true; } catch (NumberFormatException e) { usage(); } if(error) usage(); compileTimes = new long[ITERATIONS]; executionSlowTimes = new long[ITERATIONS]; executionMedTimes = new long[ITERATIONS]; executionFastTimes = new long[ITERATIONS]; getSlowTimes = new long[ITERATIONS]; getMedTimes = new long[ITERATIONS]; getFastTimes = new long[ITERATIONS]; } } private static void usage() { System.err.println("Usage:"); System.err.println("\tjava WeaveTests [-c num_of_classes] [-m num_of_methods] " + "[-l num_of_method_lines] [-i num_of_iterations]" + "\n\t\t[-include-tests y|n] [-advice get|execution] [-pointcut fast|medium|slow] [-echo] [-help]"); System.exit(-1); } /** * Will create a number of classes of the following form: * * public class C0 { * * int i0; * ... * int iN; * * void m0(C0 arg) { * i0++; * ... * iN++; * } * ... * void mN(C0 arg) { * ... * } * */ public static void createClasses() throws IOException { if(ECHO) System.out.println("Creating classes"); for(int classcounter = 0; classcounter < NUMCLASSES; classcounter++) { StringBuffer classfile = new StringBuffer(1000); classfile.append("// Auto-generated" + NL); classfile.append("package " + OUTPUT_PACKAGE + ";" + NL + NL); classfile.append("public class C" + classcounter + " {" + NL + NL); for(int intdeclaration = 0; intdeclaration < METHODLINES; intdeclaration++) { classfile.append("\tint i" + intdeclaration + ";" + NL); } classfile.append("\tint getter;" + NL); classfile.append(NL); for(int methodcounter = 0; methodcounter < NUMMETHODS; methodcounter++) { classfile.append("\tvoid m" + methodcounter + "(C" + classcounter + " arg) {" + NL); for(int methodbody = 0; methodbody < METHODLINES; methodbody++) { classfile.append("\t\ti" + methodbody + "++;" + NL); } classfile.append("\t}" + NL + NL); } classfile.append("}" + NL); try { File f = new File(outputDir, ("C" + classcounter + ".java")); FileOutputStream fos = new FileOutputStream(f); BufferedOutputStream bos = new BufferedOutputStream(fos); bos.write(new String(classfile).getBytes()); bos.close(); fos.close(); } catch (IOException e) { e.printStackTrace(); System.exit(-1); } } if (INCLUDE_TEST_CLASSES) { StringBuffer testFiles = new StringBuffer(1000); try { testFiles.append("// Auto generated" + NL); testFiles.append("package " + OUTPUT_PACKAGE + ";" + NL + NL); testFiles.append("public class TestGet {" + NL + NL); testFiles.append( "\tpublic static void main(String args[]) {" + NL); testFiles.append("\t\tC0 tester = new C0();" + NL); testFiles.append("\t\tint i = tester.i0;" + NL); testFiles.append("\t}" + NL); testFiles.append("}" + NL); File f = new File(outputDir, "TestGet.java"); FileOutputStream fos = new FileOutputStream(f); BufferedOutputStream bos = new BufferedOutputStream(fos); bos.write(new String(testFiles).getBytes()); bos.close(); fos.close(); } catch (IOException e) { e.printStackTrace(); System.exit(-1); } testFiles = new StringBuffer(1000); try { testFiles.append("// Auto generated" + NL); testFiles.append("package " + OUTPUT_PACKAGE + ";" + NL + NL); testFiles.append("public class TestExecution {" + NL + NL); testFiles.append( "\tpublic static void main(String args[]) {" + NL); testFiles.append("\t\tC0 tester = new C0();" + NL); testFiles.append("\t\ttester.m0(tester);" + NL); testFiles.append("\t}" + NL); testFiles.append("}" + NL); File f = new File(outputDir, "TestExecution.java"); FileOutputStream fos = new FileOutputStream(f); BufferedOutputStream bos = new BufferedOutputStream(fos); bos.write(new String(testFiles).getBytes()); bos.close(); fos.close(); } catch (IOException e) { e.printStackTrace(); System.exit(-1); } } StringBuffer buildList = new StringBuffer(100); for(int i = 0; i < NUMCLASSES; i++) buildList.append("C" + i + ".java" + NL); if (INCLUDE_TEST_CLASSES) { buildList.append("TestGet.java" + NL); buildList.append("TestExecution.java" + NL); } try { File f = new File(outputDir, "build.lst"); FileOutputStream fos = new FileOutputStream(f); BufferedOutputStream bos = new BufferedOutputStream(fos); bos.write(new String(buildList).getBytes()); bos.close(); fos.close(); } catch (IOException e) { e.printStackTrace(); System.exit(-1); } } /** * @param adviceType Either "get" or "execution" depending on which test. * * Will create an aspect such as the following: * * public aspect GetAdviceWeaveOne { * * before() : get(int output.C0.getter) { * System.out.println("In the aspect"); * } * } */ public static void createAspects(String adviceType) { adviceType = adviceType.toLowerCase(); if((!adviceType.equals("get")) && (!adviceType.equals("execution"))) { System.err.println("Only get and execution advice is supported"); System.exit(-1); } if(ECHO) System.out.println("Creating aspects"); if(ALL_POINTCUT_TESTS || TEST_ONE) createAllAspects(adviceType, WEAVE_FAST); if(ALL_POINTCUT_TESTS || TEST_ONE_SEARCH_ALL) createAllAspects(adviceType, WEAVE_MED); if(ALL_POINTCUT_TESTS || TEST_ALL) createAllAspects(adviceType, WEAVE_SLOW); } private static void createAllAspects(String adviceType, int pointcut) { StringBuffer aspectFile = new StringBuffer(1000); // Capitalises the first char in the adviceType String, and then adds "Advice" to it. String adviceName = (char)(adviceType.charAt(0) - 32) + adviceType.substring(1) + "Advice"; switch(pointcut) { case WEAVE_FAST: adviceName += "WeaveFast"; break; case WEAVE_MED: adviceName += "WeaveMedium"; break; case WEAVE_SLOW: adviceName += "WeaveSlow"; break; } aspectFile.append("// Auto-generated" + NL + NL); aspectFile.append("public aspect " + adviceName + " {" + NL + NL); aspectFile.append("\tbefore() : "); if(adviceType.equals("execution")) { switch(pointcut) { case WEAVE_FAST: aspectFile.append(EXECUTION_FAST); break; case WEAVE_MED: aspectFile.append(EXECUTION_MED); break; case WEAVE_SLOW: aspectFile.append(EXECUTION_SLOW); break; } } else { switch(pointcut) { case WEAVE_FAST: aspectFile.append(GET_FAST); break; case WEAVE_MED: aspectFile.append(GET_MED); break; case WEAVE_SLOW: aspectFile.append(GET_SLOW); break; } } aspectFile.append(" {" + NL); aspectFile.append("\t\tSystem.out.println(\"In the aspect\");" + NL); aspectFile.append("\t}" + NL); aspectFile.append("}" + NL); // Create the file try { File f = new File(outputDir, (adviceName + ".aj")); FileOutputStream fos = new FileOutputStream(f); BufferedOutputStream bos = new BufferedOutputStream(fos); bos.write(new String(aspectFile).getBytes()); bos.close(); fos.close(); } catch (IOException e) { e.printStackTrace(); System.exit(-1); } } public static void compileClasses() throws IOException { if(ECHO) System.out.print("Compiling: "); long average = 0; for (int i = 0; i < ITERATIONS; i++) { long time = performCompile(); compileTimes[i] = time; average += time; } if(ECHO) System.out.println((average / ITERATIONS) + " millis"); } private static long performCompile() throws IOException { String ajcargs = "-noExit -outjar " + OUTPUT_PACKAGE + File.separatorChar + "classes.jar " + "-argfile " + OUTPUT_PACKAGE + File.separatorChar + "build.lst"; // split method creates a String array delimited on a space String[] parsedArgs = RunWeaveTests.split(ajcargs); long start = System.currentTimeMillis(); org.aspectj.tools.ajc.Main.main(parsedArgs); long stop = System.currentTimeMillis(); return stop - start; } public static void weaveAspects(String adviceType) throws IOException { adviceType = adviceType.toLowerCase(); if((!adviceType.equals("get")) && (!adviceType.equals("execution"))) { System.err.println("Only get and execution advice is supported"); System.exit(-1); } long average = 0; if(ECHO) System.out.println((char)(adviceType.charAt(0) - 32) + adviceType.substring(1)); if (ALL_POINTCUT_TESTS || TEST_ONE) { if(ECHO) System.out.print("Weave Fast:"); for (int i = 0; i < ITERATIONS; i++) { long time = weaveAllAspects(adviceType, WEAVE_FAST); if(adviceType.equals("execution")) executionFastTimes[i] = time; else getFastTimes[i] = time; average += time; if(ECHO) System.out.print("."); } if(ECHO) System.out.println(" " + (average / ITERATIONS) + " millis"); } average = 0; if (ALL_POINTCUT_TESTS || TEST_ONE_SEARCH_ALL) { if(ECHO) System.out.print("Weave Medium:"); for (int i = 0; i < ITERATIONS; i++) { long time = weaveAllAspects(adviceType, WEAVE_MED); if(adviceType.equals("execution")) executionMedTimes[i] = time; else getMedTimes[i] = time; average += time; if(ECHO) System.out.print("."); } if(ECHO) System.out.println(" " + (average / ITERATIONS) + " millis"); } average = 0; if (ALL_POINTCUT_TESTS || TEST_ALL) { if(ECHO) System.out.print("Weave Slow:"); for (int i = 0; i < ITERATIONS; i++) { long time = weaveAllAspects(adviceType, WEAVE_SLOW); if(adviceType.equals("execution")) executionSlowTimes[i] = time; else getSlowTimes[i] = time; average += time; if(ECHO) System.out.print("."); } if(ECHO) System.out.println(" " + (average / ITERATIONS) + " millis"); } if(ECHO) System.out.println(); } private static long weaveAllAspects(String adviceType, int pointcut) throws IOException { // Capitalises the first char in the adviceType String, to keep to Java naming convention String adviceName = (char)(adviceType.charAt(0) - 32) + adviceType.substring(1) + "Advice"; switch(pointcut) { case WEAVE_FAST: adviceName += "WeaveFast"; break; case WEAVE_MED: adviceName += "WeaveMedium"; break; case WEAVE_SLOW: adviceName += "WeaveSlow"; break; } String ajcargs = "-noExit -injars " + OUTPUT_PACKAGE + File.separatorChar + "classes.jar " + "-outjar " + OUTPUT_PACKAGE + File.separatorChar + adviceName + ".jar " + OUTPUT_PACKAGE + File.separatorChar + adviceName + ".aj"; String[] parsedArgs = RunWeaveTests.split(ajcargs); long start = System.currentTimeMillis(); org.aspectj.tools.ajc.Main.main(parsedArgs); long stop = System.currentTimeMillis(); return stop - start; } }
73,334
Bug 73334 Avoid clashes in the org.eclipse namespace by renaming our duplicates.
We have recently renamed our 'copy' of BCEL to use a different package prefix so that our version never clashes with another version that might be around on a users system. This enhancement is to do the same thing for our 'copy' of the org.eclipse.jdt code (in the shadows project). As part of packaging the shadows project to create the 'jdtcore' jar files (bin and src) we will rename the packages from: org.eclipse.jdt.*** to org.aspectj.org.eclipse.jdt.** This has a really nice side effect that we can make our version of the compiler accessible in the IDE. It should now be possible for AJDT to work more closely with it and get features like eager parsing to work. Care will be taken that we don't accidentally make the merge process a nightmare.
resolved fixed
b133299
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2004-09-06T15:40:02Z
2004-09-06T17:00:00Z
org.aspectj.ajdt.core/testsrc/org/aspectj/ajdt/ajc/AjdtCommandTestCase.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.AjBuildConfig; import org.aspectj.bridge.*; import org.aspectj.util.*; import org.eclipse.jdt.core.compiler.InvalidInputException; import java.io.*; import java.util.*; import junit.framework.TestCase; /** * Some black-box test is happening here. */ public class AjdtCommandTestCase extends TestCase { private ArrayList tempFiles = new ArrayList(); private StreamPrintWriter outputWriter = new StreamPrintWriter(new PrintWriter(System.out)); // private AjdtCommand command = new AjdtCommand(); private MessageWriter messageWriter = new MessageWriter(outputWriter, false); private CountingMessageHandler counter = new CountingMessageHandler(messageWriter); public AjdtCommandTestCase(String name) { super(name); // command.buildArgParser.out = outputWriter; } private static boolean delete(File file) { if ((null == file) || !file.exists()) { return true; } else if (!file.canWrite()) { return false; } if (file.isDirectory()) { FileUtil.deleteContents(file); } return file.delete(); } public void testIncrementalHandler() throws IOException { // verify that AjdtCommand respects handler parm // in runCommand and repeatCommand final String sig = getClass().getName() + ".testIncrementalHandler"; boolean runTest = false; try { runTest = null != System.getProperty(sig); } catch (Throwable t) { } if (!runTest) { System.out.println("warning: to run " + sig + "(), set system property " + sig); return; } // setup initial compile File testBase = new File("testdata/ajdtCommand"); assertTrue(testBase.isDirectory()); assertTrue(testBase.canWrite()); File genBase = new File(testBase, "genBase"); tempFiles.add(genBase); if (genBase.exists()) { FileUtil.deleteContents(genBase); } else { genBase.mkdirs(); } assertTrue(genBase.canWrite()); File classesDir = new File(testBase, "classes"); tempFiles.add(classesDir); assertTrue(classesDir.mkdirs()); File mainSrc= new File(testBase, "Main-1.java"); File main = new File(genBase, "Main.java"); FileUtil.copyFile(mainSrc, main); assertTrue(main.canRead()); long initialSize = main.length(); // do initial compile String[] args = new String[] { "-d", classesDir.getPath(), "-classpath", "../lib/test/aspectjrt.jar", main.getPath() }; AjdtCommand command = new AjdtCommand(); IMessageHolder holder = new MessageHandler(); boolean result = command.runCommand(args, holder); assertTrue(result); assertTrue(!holder.hasAnyMessage(IMessage.WARNING, true)); int initialMessages = holder.numMessages(null, true); // do repeat compile, introducing an error mainSrc= new File(testBase, "Main-2.java"); FileUtil.copyFile(mainSrc, main); assertTrue(main.canRead()); long nextSize = main.length(); assertTrue(nextSize > initialSize); IMessageHolder newHolder = new MessageHandler(); result = command.repeatCommand(newHolder); // verify failed, no effect on first holder, error in second assertFalse(result); assertEquals(1, newHolder.numMessages(IMessage.ERROR, false)); assertEquals(initialMessages, holder.numMessages(null, true)); } public void testIncrementalOption() throws InvalidInputException { AjdtCommand.genBuildConfig( new String[] { "-incremental" }, counter); assertTrue( "didn't specify source root", outputWriter.getContents().indexOf("specify a source root") != -1); outputWriter.flushBuffer(); AjdtCommand.genBuildConfig( new String[] { "-incremental", "-sourceroots", AjdtAjcTests.TESTDATA_PATH + "/src1" }, counter); assertTrue( outputWriter.getContents(), outputWriter.getContents().equals("")); outputWriter.flushBuffer(); AjdtCommand.genBuildConfig( new String[] { "-incremental", "testdata/src1/Hello.java" }, counter); assertTrue( "specified a file", outputWriter.getContents().indexOf("incremental mode only handles source files using -sourceroots") != -1); ; } public void testBadOptionAndUsagePrinting() throws InvalidInputException { try { AjdtCommand.genBuildConfig( new String[] { "-mubleBadOption" }, counter); } catch (AbortException ae) { } // usage printed by caller to genBuildConfig now... assertTrue( outputWriter.getContents() + " contains? " + "Usage", outputWriter.getContents().indexOf("-mubleBadOption") != -1); } public void testHelpUsagePrinting() { String[] args = new String[] { "-help" }; PrintStream saveOut = System.out; ByteArrayOutputStream byteArrayOut = new ByteArrayOutputStream(); PrintStream newOut = new PrintStream(byteArrayOut); System.setOut(newOut); try { try { AjdtCommand.genBuildConfig( args, counter); } catch (AbortException ae) { } } finally { System.setOut(saveOut); } String text = byteArrayOut.toString(); assertTrue( text + " contains? " + "Usage", text.indexOf("Usage") != -1); } public void testVersionOutput() throws InvalidInputException { String[] args = new String[] { "-version" }; PrintStream saveOut = System.err; ByteArrayOutputStream byteArrayOut = new ByteArrayOutputStream(); PrintStream newOut = new PrintStream(byteArrayOut); System.setErr(newOut); try { try { AjdtCommand.genBuildConfig( args, counter); } catch (AbortException ae) { } } finally { System.setErr(saveOut); } String text = byteArrayOut.toString(); assertTrue( "version output", text.indexOf("AspectJ Compiler") != -1); } public void testNonExistingLstFile() { AjdtCommand.genBuildConfig( new String[] { "@mumbleDoesNotExist" }, counter); assertTrue( outputWriter.getContents(), outputWriter.getContents().indexOf("file does not exist") != -1); } protected void setUp() throws Exception { super.setUp(); } protected void tearDown() throws Exception { super.tearDown(); outputWriter.flushBuffer(); for (ListIterator iter = tempFiles.listIterator(); iter.hasNext();) { File file = (File) iter.next(); if (delete(file)) { iter.remove(); } } } }
73,334
Bug 73334 Avoid clashes in the org.eclipse namespace by renaming our duplicates.
We have recently renamed our 'copy' of BCEL to use a different package prefix so that our version never clashes with another version that might be around on a users system. This enhancement is to do the same thing for our 'copy' of the org.eclipse.jdt code (in the shadows project). As part of packaging the shadows project to create the 'jdtcore' jar files (bin and src) we will rename the packages from: org.eclipse.jdt.*** to org.aspectj.org.eclipse.jdt.** This has a really nice side effect that we can make our version of the compiler accessible in the IDE. It should now be possible for AJDT to work more closely with it and get features like eager parsing to work. Care will be taken that we don't accidentally make the merge process a nightmare.
resolved fixed
b133299
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2004-09-06T15:40:02Z
2004-09-06T17: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 Exception { 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); List cp = config.getClasspath(); boolean jar1Found = false; boolean jar2Found = false; for (Iterator iter = cp.iterator(); iter.hasNext();) { String element = (String) iter.next(); if (element.indexOf("1.jar") != -1) jar1Found = true; if (element.indexOf("2.jar") != -1) jar2Found = true; } assertTrue( config.getClasspath().toString(), jar1Found); assertTrue( config.getClasspath().toString(), jar2Found); } 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 testPathResolutionFromConfigArgs() { String FILE_PATH = "@" + TEST_DIR + "configWithClasspathExtdirsBootCPArgs.lst"; AjBuildConfig config = genBuildConfig(new String[] { FILE_PATH }, messageWriter); List classpath = config.getFullClasspath(); // should have three entries, resolved relative to location of .lst file assertEquals("Three entries in classpath",3,classpath.size()); Iterator cpIter = classpath.iterator(); try { assertEquals("Should be relative to TESTDIR",new File(TEST_DIR+File.separator+"xyz").getCanonicalPath(),cpIter.next()); assertEquals("Should be relative to TESTDIR",new File(TEST_DIR+File.separator+"myextdir" + File.separator + "dummy.jar").getCanonicalPath(),cpIter.next()); assertEquals("Should be relative to TESTDIR",new File(TEST_DIR+File.separator+"abc.jar").getCanonicalPath(),cpIter.next()); List files = config.getFiles(); assertEquals("Two source files",2,files.size()); Iterator fIter = files.iterator(); assertEquals("Should be relative to TESTDIR",new File(TEST_DIR+File.separator+"Abc.java").getCanonicalFile(),fIter.next()); assertEquals("Should be relative to TESTDIR",new File(TEST_DIR+File.separator+"xyz"+File.separator+"Def.aj").getCanonicalFile(),fIter.next()); } catch (IOException ex) { fail("Test case failure attempting to create canonical path: " + ex); } } 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 Exception { 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").getCanonicalPath() )); } public void testBootclasspath() throws InvalidInputException { final String PATH = "mumble" + File.separator + "rt.jar"; AjBuildConfig config = genBuildConfig(new String[] { "-bootclasspath", PATH }, messageWriter); assertTrue("Should find '" + PATH + "' contained in the first entry of '" + config.getBootclasspath().toString(), ((String)config.getBootclasspath().get(0)).indexOf(PATH) != -1); config = genBuildConfig(new String[] { }, messageWriter); assertTrue(config.getBootclasspath().toString(), !config.getBootclasspath().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); List cp = config.getClasspath(); boolean jar1Found = false; boolean jar2Found = false; for (Iterator iter = cp.iterator(); iter.hasNext();) { String element = (String) iter.next(); if (element.indexOf("1.jar") != -1) jar1Found = true; if (element.indexOf("2.jar") != -1) jar2Found = true; } assertTrue( config.getClasspath().toString(), jar1Found); assertTrue( config.getClasspath().toString(), jar2Found); } 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(); } }
73,334
Bug 73334 Avoid clashes in the org.eclipse namespace by renaming our duplicates.
We have recently renamed our 'copy' of BCEL to use a different package prefix so that our version never clashes with another version that might be around on a users system. This enhancement is to do the same thing for our 'copy' of the org.eclipse.jdt code (in the shadows project). As part of packaging the shadows project to create the 'jdtcore' jar files (bin and src) we will rename the packages from: org.eclipse.jdt.*** to org.aspectj.org.eclipse.jdt.** This has a really nice side effect that we can make our version of the compiler accessible in the IDE. It should now be possible for AJDT to work more closely with it and get features like eager parsing to work. Care will be taken that we don't accidentally make the merge process a nightmare.
resolved fixed
b133299
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2004-09-06T15:40:02Z
2004-09-06T17:00:00Z
org.aspectj.ajdt.core/testsrc/org/aspectj/ajdt/internal/core/builder/AjCompilerOptionsTest.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.core.builder; import java.util.HashMap; import java.util.Map; import org.eclipse.jdt.internal.compiler.impl.CompilerOptions; import junit.framework.TestCase; /** * @author colyer * * TODO To change the template for this generated type comment go to * Window - Preferences - Java - Code Generation - Code and Comments */ public class AjCompilerOptionsTest extends TestCase { private AjCompilerOptions options; /* * @see TestCase#setUp() */ protected void setUp() throws Exception { super.setUp(); options = new AjCompilerOptions(); } public void testDefaultValues() { assertFalse(options.noWeave); assertFalse(options.xSerializableAspects); assertFalse(options.xLazyThisJoinPoint); assertFalse(options.xNoInline); assertFalse(options.xReweavable); assertFalse(options.xReweavableCompress); assertFalse(options.generateModel); assertFalse(options.generateJavaDocsInModel); assertFalse(options.generateEmacsSymFiles); Map map = options.getMap(); assertEquals(CompilerOptions.WARNING,map.get(AjCompilerOptions.OPTION_ReportInvalidAbsoluteTypeName)); assertEquals(CompilerOptions.IGNORE,map.get(AjCompilerOptions.OPTION_ReportInvalidWildcardTypeName)); assertEquals(CompilerOptions.WARNING,map.get(AjCompilerOptions.OPTION_ReportUnresolvableMember)); assertEquals(CompilerOptions.WARNING,map.get(AjCompilerOptions.OPTION_ReportTypeNotExposedToWeaver)); assertEquals(CompilerOptions.IGNORE,map.get(AjCompilerOptions.OPTION_ReportShadowNotInStructure)); assertEquals(CompilerOptions.WARNING,map.get(AjCompilerOptions.OPTION_ReportUnmatchedSuperTypeInCall)); assertEquals(CompilerOptions.WARNING,map.get(AjCompilerOptions.OPTION_ReportCannotImplementLazyTJP)); assertEquals(CompilerOptions.IGNORE,map.get(AjCompilerOptions.OPTION_ReportNeedSerialVersionUIDField)); assertEquals(CompilerOptions.IGNORE,map.get(AjCompilerOptions.OPTION_ReportIncompatibleSerialVersion)); } public void testDirectSet() { options.noWeave = true; options.xSerializableAspects = true; options.xLazyThisJoinPoint = true; options.xNoInline = true; options.xReweavable = true; options.xReweavableCompress = true; options.generateModel = true; options.generateJavaDocsInModel = true; options.generateEmacsSymFiles = true; Map map = options.getMap(); assertEquals(CompilerOptions.ENABLED,map.get(AjCompilerOptions.OPTION_NoWeave)); assertEquals(CompilerOptions.ENABLED,map.get(AjCompilerOptions.OPTION_XSerializableAspects)); assertEquals(CompilerOptions.ENABLED,map.get(AjCompilerOptions.OPTION_XLazyThisJoinPoint)); assertEquals(CompilerOptions.ENABLED,map.get(AjCompilerOptions.OPTION_XNoInline)); assertEquals(CompilerOptions.ENABLED,map.get(AjCompilerOptions.OPTION_XReweavable)); assertEquals(CompilerOptions.ENABLED,map.get(AjCompilerOptions.OPTION_XReweavableCompress)); assertEquals(CompilerOptions.ENABLED,map.get(AjCompilerOptions.OPTION_GenerateModel)); assertEquals(CompilerOptions.ENABLED,map.get(AjCompilerOptions.OPTION_GenerateJavaDocsInModel)); assertEquals(CompilerOptions.ENABLED,map.get(AjCompilerOptions.OPTION_Emacssym)); } public void testMapSet() { Map map = new HashMap(); map.put(AjCompilerOptions.OPTION_ReportInvalidAbsoluteTypeName,CompilerOptions.ERROR); map.put(AjCompilerOptions.OPTION_ReportInvalidWildcardTypeName,CompilerOptions.ERROR); map.put(AjCompilerOptions.OPTION_ReportUnresolvableMember,CompilerOptions.IGNORE); map.put(AjCompilerOptions.OPTION_ReportTypeNotExposedToWeaver,CompilerOptions.ERROR); map.put(AjCompilerOptions.OPTION_ReportShadowNotInStructure,CompilerOptions.WARNING); map.put(AjCompilerOptions.OPTION_ReportUnmatchedSuperTypeInCall,CompilerOptions.ERROR); map.put(AjCompilerOptions.OPTION_ReportCannotImplementLazyTJP,CompilerOptions.ERROR); map.put(AjCompilerOptions.OPTION_ReportNeedSerialVersionUIDField,CompilerOptions.WARNING); map.put(AjCompilerOptions.OPTION_ReportIncompatibleSerialVersion,CompilerOptions.ERROR); map.put(AjCompilerOptions.OPTION_NoWeave,CompilerOptions.ENABLED); map.put(AjCompilerOptions.OPTION_XSerializableAspects,CompilerOptions.ENABLED); map.put(AjCompilerOptions.OPTION_XLazyThisJoinPoint,CompilerOptions.ENABLED); map.put(AjCompilerOptions.OPTION_XNoInline,CompilerOptions.ENABLED); map.put(AjCompilerOptions.OPTION_XReweavable,CompilerOptions.ENABLED); map.put(AjCompilerOptions.OPTION_XReweavableCompress,CompilerOptions.ENABLED); map.put(AjCompilerOptions.OPTION_GenerateModel,CompilerOptions.ENABLED); map.put(AjCompilerOptions.OPTION_GenerateJavaDocsInModel,CompilerOptions.ENABLED); map.put(AjCompilerOptions.OPTION_Emacssym,CompilerOptions.ENABLED); options.set(map); assertTrue(options.noWeave); assertTrue(options.xSerializableAspects); assertTrue(options.xLazyThisJoinPoint); assertTrue(options.xNoInline); assertTrue(options.xReweavable); assertTrue(options.xReweavableCompress); assertTrue(options.generateModel); assertTrue(options.generateJavaDocsInModel); assertTrue(options.generateEmacsSymFiles); Map newMap = options.getMap(); assertEquals(CompilerOptions.ERROR,newMap.get(AjCompilerOptions.OPTION_ReportInvalidAbsoluteTypeName)); assertEquals(CompilerOptions.ERROR,newMap.get(AjCompilerOptions.OPTION_ReportInvalidWildcardTypeName)); assertEquals(CompilerOptions.IGNORE,newMap.get(AjCompilerOptions.OPTION_ReportUnresolvableMember)); assertEquals(CompilerOptions.ERROR,newMap.get(AjCompilerOptions.OPTION_ReportTypeNotExposedToWeaver)); assertEquals(CompilerOptions.WARNING,newMap.get(AjCompilerOptions.OPTION_ReportShadowNotInStructure)); assertEquals(CompilerOptions.ERROR,newMap.get(AjCompilerOptions.OPTION_ReportUnmatchedSuperTypeInCall)); assertEquals(CompilerOptions.ERROR,newMap.get(AjCompilerOptions.OPTION_ReportCannotImplementLazyTJP)); assertEquals(CompilerOptions.WARNING,newMap.get(AjCompilerOptions.OPTION_ReportNeedSerialVersionUIDField)); assertEquals(CompilerOptions.ERROR,newMap.get(AjCompilerOptions.OPTION_ReportIncompatibleSerialVersion)); } /* * Class to test for String toString() */ public void testToString() { String s = options.toString(); assertTrue("Should have info on AspectJ options",s.indexOf("AspectJ Specific Options:") > 0); } }
73,334
Bug 73334 Avoid clashes in the org.eclipse namespace by renaming our duplicates.
We have recently renamed our 'copy' of BCEL to use a different package prefix so that our version never clashes with another version that might be around on a users system. This enhancement is to do the same thing for our 'copy' of the org.eclipse.jdt code (in the shadows project). As part of packaging the shadows project to create the 'jdtcore' jar files (bin and src) we will rename the packages from: org.eclipse.jdt.*** to org.aspectj.org.eclipse.jdt.** This has a really nice side effect that we can make our version of the compiler accessible in the IDE. It should now be possible for AJDT to work more closely with it and get features like eager parsing to work. Care will be taken that we don't accidentally make the merge process a nightmare.
resolved fixed
b133299
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2004-09-06T15:40:02Z
2004-09-06T17:00:00Z
org.aspectj.ajdt.core/testsrc/org/aspectj/ajdt/internal/core/builder/AsmBuilderTest.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 junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import org.eclipse.jdt.internal.compiler.CompilationResult; import org.eclipse.jdt.internal.compiler.ast.TypeDeclaration; import org.eclipse.jdt.internal.compiler.env.ICompilationUnit; import org.eclipse.jdt.internal.compiler.lookup.BlockScope; public class AsmBuilderTest extends TestCase { private AsmHierarchyBuilder builder = new AsmHierarchyBuilder(); public static Test suite() { TestSuite suite = new TestSuite(AsmBuilderTest.class.getName()); //$JUnit-BEGIN$ suite.addTestSuite(AsmBuilderTest.class); //$JUnit-END$ return suite; } /** * Test for bug#39626 */ public void testNullHandlingOfVisit() { ICompilationUnit cu = new ICompilationUnit() { public char[] getContents() { return null; } public char[] getMainTypeName() { return null; } public char[][] getPackageName() { return null; } public char[] getFileName() { return null; } }; TypeDeclaration local = new TypeDeclaration(new CompilationResult(cu, 0, 0, 0)); local.name = new char[2]; BlockScope scope = null; try { // builder.internalBuild(new CompilationResult(cu, 0, 0, 0), null); builder.visit(local, scope); } catch (Exception e) { assertTrue(e instanceof NullPointerException); } // XXX put back? // catch (Exception e) { // assertTrue(e instanceof EmptyStackException); // } } }
73,433
Bug 73433 AspectJ does not correctly support -cp
Discovered by Andy Brodie. -cp is a shorthand for -classpath supported by the JDT compiler. AspectJ does not correctly support -cp option. Look at this example: C:\aspectj1.2>ajc -inpath injar.jar -outjar outjar.jar -cp lib\aspectjrt.jar [error] can't find type org.aspectj.lang.JoinPoint 1 error C:\aspectj1.2>ajc -inpath injar.jar -outjar outjar.jar -classpath lib\aspectjrt.jar This is due to the arg parser in AspectJ only recognizing -classpath. It doesn't fail when it encounters -cp, it just ignores it and passes it down to JDT for processing. The fix is to recognize -cp too.
resolved fixed
8e4d898
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2004-09-08T10:14:44Z
2004-09-08T10:40: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.aspectj.weaver.Dump; import org.aspectj.weaver.WeaverMessages; import org.aspectj.org.eclipse.jdt.core.compiler.InvalidInputException; import org.aspectj.org.eclipse.jdt.internal.compiler.batch.Main; import org.aspectj.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) { Dump.saveCommandLine(args); 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)); buildConfig.setBootclasspath(getBootclasspath(parser)); } if (incrementalMode && (0 == buildConfig.getSourceRoots().size())) { MessageUtil.error(handler, "specify a source root when in incremental mode"); } /* * Ensure we don't overwrite injars, inpath or aspectpath with outjar * bug-71339 */ File outjar = buildConfig.getOutputJar(); if (outjar != null) { /* Search injars */ for (Iterator i = buildConfig.getInJars().iterator(); i.hasNext(); ) { File injar = (File)i.next(); if (injar.equals(outjar)) { String message = WeaverMessages.format(WeaverMessages.OUTJAR_IN_INPUT_PATH); MessageUtil.error(handler,message); } } /* Search inpath */ for (Iterator i = buildConfig.getInpath().iterator(); i.hasNext(); ) { File inPathElement = (File)i.next(); if (!inPathElement.isDirectory() && inPathElement.equals(outjar)) { String message = WeaverMessages.format(WeaverMessages.OUTJAR_IN_INPUT_PATH); MessageUtil.error(handler,message); } } /* Search aspectpath */ for (Iterator i = buildConfig.getAspectpath().iterator(); i.hasNext(); ) { File pathElement = (File)i.next(); if (!pathElement.isDirectory() && pathElement.equals(outjar)) { String message = WeaverMessages.format(WeaverMessages.OUTJAR_IN_INPUT_PATH); MessageUtil.error(handler,message); } } } 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)); } public List getBootclasspath(AjcConfigParser parser) { List ret = new ArrayList(); if (parser.bootclasspath == null) { addClasspath(System.getProperty("sun.boot.class.path", ""), ret); } else { addClasspath(parser.bootclasspath, ret); } return ret; } /** * 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) { String bcpArg = ((ConfigParser.Arg)args.get(nextArgIndex)).getValue(); StringBuffer bcp = new StringBuffer(); StringTokenizer strTok = new StringTokenizer(bcpArg,File.pathSeparator); while (strTok.hasMoreTokens()) { bcp.append(makeFile(strTok.nextToken())); if (strTok.hasMoreTokens()) { bcp.append(File.pathSeparator); } } bootclasspath = bcp.toString(); args.remove(args.get(nextArgIndex)); } else { showError("-bootclasspath requires classpath entries"); } } else if (arg.equals("-classpath")) { if (args.size() > nextArgIndex) { String cpArg = ((ConfigParser.Arg)args.get(nextArgIndex)).getValue(); StringBuffer cp = new StringBuffer(); StringTokenizer strTok = new StringTokenizer(cpArg,File.pathSeparator); while (strTok.hasMoreTokens()) { cp.append(makeFile(strTok.nextToken())); if (strTok.hasMoreTokens()) { cp.append(File.pathSeparator); } } classpath = cp.toString(); args.remove(args.get(nextArgIndex)); } else { showError("-classpath requires classpath entries"); } } else if (arg.equals("-extdirs")) { if (args.size() > nextArgIndex) { String extdirsArg = ((ConfigParser.Arg)args.get(nextArgIndex)).getValue(); StringBuffer ed = new StringBuffer(); StringTokenizer strTok = new StringTokenizer(extdirsArg,File.pathSeparator); while (strTok.hasMoreTokens()) { ed.append(makeFile(strTok.nextToken())); if (strTok.hasMoreTokens()) { ed.append(File.pathSeparator); } } extdirs = ed.toString(); 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); } } }
72,157
Bug 72157 declare soft can cause programs with invalid exception behaviour to be generated
Compiling the program below results in the constructor for the class SCE2 throwing Exception, which it is not declared to throw either in the source code or in the generated bytecode. If the 'declare soft' statement is removed, then the super() call in the SCE2 constructor is correctly reported as throwing an undeclared exception; it seems that the 'declare soft' statement turns off the exception checking of the super() call despite there being no join point which covers this call that would actually soften the exception. I'm using 'DEVELOPMENT built on Monday Aug 16, 2004 at 13:50:47 GMT'. public class SuperConsExc { public SuperConsExc() throws Exception { throw new Exception(); } public static void main(String[] args) { new SCE2(); } } class SCE2 extends SuperConsExc { public SCE2() { super(); } } aspect SCEAspect { declare soft: Exception: within(SCE2); }
resolved fixed
eca1429
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2004-09-08T12:04:49Z
2004-08-18T11:53:20Z
org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/compiler/problem/AjProblemReporter.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the 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.problem; import java.lang.reflect.Modifier; import java.util.Iterator; import org.aspectj.ajdt.internal.compiler.ast.AdviceDeclaration; import org.aspectj.ajdt.internal.compiler.ast.PointcutDeclaration; import org.aspectj.ajdt.internal.compiler.ast.Proceed; import org.aspectj.ajdt.internal.compiler.lookup.EclipseFactory; import org.aspectj.util.FuzzyBoolean; import org.aspectj.weaver.AjcMemberMaker; import org.aspectj.weaver.ConcreteTypeMunger; import org.aspectj.weaver.ResolvedMember; import org.aspectj.weaver.ResolvedTypeX; import org.aspectj.weaver.Shadow; import org.aspectj.weaver.patterns.DeclareSoft; import org.aspectj.org.eclipse.jdt.internal.compiler.CompilationResult; import org.aspectj.org.eclipse.jdt.internal.compiler.IErrorHandlingPolicy; import org.aspectj.org.eclipse.jdt.internal.compiler.IProblemFactory; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.ASTNode; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.Argument; import org.aspectj.org.eclipse.jdt.internal.compiler.impl.CompilerOptions; import org.aspectj.org.eclipse.jdt.internal.compiler.impl.ReferenceContext; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.MethodBinding; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.MethodScope; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.ReferenceBinding; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.SourceTypeBinding; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.TypeBinding; import org.aspectj.org.eclipse.jdt.internal.compiler.problem.ProblemReporter; import org.aspectj.org.eclipse.jdt.core.compiler.CharOperation; import org.aspectj.org.eclipse.jdt.core.compiler.IProblem; /** * Extends problem reporter to support compiler-side implementation of declare soft. * Also overrides error reporting for the need to implement abstract methods to * account for inter-type declarations and pointcut declarations. This second * job might be better done directly in the SourceTypeBinding/ClassScope classes. * * @author Jim Hugunin */ public class AjProblemReporter extends ProblemReporter { private static final boolean DUMP_STACK = false; public EclipseFactory factory; public AjProblemReporter( IErrorHandlingPolicy policy, CompilerOptions options, IProblemFactory problemFactory) { super(policy, options, problemFactory); } public void unhandledException( TypeBinding exceptionType, ASTNode location) { if (!factory.getWorld().getDeclareSoft().isEmpty()) { Shadow callSite = factory.makeShadow(location, referenceContext); Shadow enclosingExec = factory.makeShadow(referenceContext); // System.err.println("about to show error for unhandled exception: " + new String(exceptionType.sourceName()) + // " at " + location + " in " + referenceContext); for (Iterator i = factory.getWorld().getDeclareSoft().iterator(); i.hasNext(); ) { DeclareSoft d = (DeclareSoft)i.next(); // We need the exceptionType to match the type in the declare soft statement // This means it must either be the same type or a subtype ResolvedTypeX throwException = factory.fromEclipse((ReferenceBinding)exceptionType); FuzzyBoolean isExceptionTypeOrSubtype = d.getException().matchesInstanceof(throwException); if (!isExceptionTypeOrSubtype.alwaysTrue() ) continue; if (callSite != null) { FuzzyBoolean match = d.getPointcut().match(callSite); if (match.alwaysTrue()) { //System.err.println("matched callSite: " + callSite + " with " + d); return; } else if (!match.alwaysFalse()) { //!!! need this check to happen much sooner //throw new RuntimeException("unimplemented, shouldn't have fuzzy match here"); } } if (enclosingExec != null) { FuzzyBoolean match = d.getPointcut().match(enclosingExec); if (match.alwaysTrue()) { //System.err.println("matched enclosingExec: " + enclosingExec + " with " + d); return; } else if (!match.alwaysFalse()) { //!!! need this check to happen much sooner //throw new RuntimeException("unimplemented, shouldn't have fuzzy match here"); } } } } //??? is this always correct if (location instanceof Proceed) { return; } super.unhandledException(exceptionType, location); } private boolean isPointcutDeclaration(MethodBinding binding) { return CharOperation.prefixEquals(PointcutDeclaration.mangledPrefix, binding.selector); } public void abstractMethodCannotBeOverridden( SourceTypeBinding type, MethodBinding concreteMethod) { if (isPointcutDeclaration(concreteMethod)) { return; } super.abstractMethodCannotBeOverridden(type, concreteMethod); } public void abstractMethodMustBeImplemented( SourceTypeBinding type, MethodBinding abstractMethod) { // if this is a PointcutDeclaration then there is no error if (isPointcutDeclaration(abstractMethod)) { return; } if (CharOperation.prefixEquals("ajc$interField".toCharArray(), abstractMethod.selector)) { //??? think through how this could go wrong return; } // if we implemented this method by an inter-type declaration, then there is no error //??? be sure this is always right ResolvedTypeX onTypeX = factory.fromEclipse(type); //abstractMethod.declaringClass); for (Iterator i = onTypeX.getInterTypeMungersIncludingSupers().iterator(); i.hasNext(); ) { ConcreteTypeMunger m = (ConcreteTypeMunger)i.next(); ResolvedMember sig = m.getSignature(); if (!Modifier.isAbstract(sig.getModifiers())) { if (ResolvedTypeX .matches( AjcMemberMaker.interMethod( sig, m.getAspectType(), sig.getDeclaringType().isInterface( factory.getWorld())), EclipseFactory.makeResolvedMember(abstractMethod))) { return; } } } super.abstractMethodMustBeImplemented(type, abstractMethod); } public void handle( int problemId, String[] problemArguments, String[] messageArguments, int severity, int problemStartPosition, int problemEndPosition, ReferenceContext referenceContext, CompilationResult unitResult) { if (severity != Ignore && DUMP_STACK) { Thread.dumpStack(); } super.handle( problemId, problemArguments, messageArguments, severity, problemStartPosition, problemEndPosition, referenceContext, unitResult); } // PR71076 public void javadocMissingParamTag(Argument arg, int modifiers) { boolean reportIt = true; if (arg.binding!=null && (arg.binding.declaringScope instanceof MethodScope) ) { MethodScope ms = (MethodScope) arg.binding.declaringScope; if (ms.referenceContext!=null && (ms.referenceContext instanceof AdviceDeclaration)) { AdviceDeclaration adviceDecl = (AdviceDeclaration)ms.referenceContext; if (arg.name!=null) { if (adviceDecl.selector.length>4 && adviceDecl.selector[0] == 'a' && adviceDecl.selector[1] == 'j' && adviceDecl.selector[2] == 'c' && adviceDecl.selector[3] == '$') { String stringArgName = new String(arg.name); if (stringArgName.equals("thisJoinPoint")) reportIt = false; if (stringArgName.equals("thisJoinPointStaticPart")) reportIt = false; if (stringArgName.equals("thisEnclosingJoinPointStaticPart")) reportIt = false; if (arg.type.toString().indexOf("AroundClosure")!=-1) reportIt = false; } } } } if (arg.name!=null && new String(arg.name).startsWith("ajc$")) reportIt = false; if (reportIt) super.javadocMissingParamTag(arg, modifiers); } public void abstractMethodInAbstractClass(SourceTypeBinding type, AbstractMethodDeclaration methodDecl) { String abstractMethodName = new String(methodDecl.selector); if (abstractMethodName.startsWith("ajc$pointcut")) { // This will already have been reported, see: PointcutDeclaration.postParse() return; } String[] arguments = new String[] {new String(type.sourceName()), abstractMethodName}; super.handle( IProblem.AbstractMethodInAbstractClass, arguments, arguments, methodDecl.sourceStart, methodDecl.sourceEnd,this.referenceContext, this.referenceContext == null ? null : this.referenceContext.compilationResult()); } }
72,157
Bug 72157 declare soft can cause programs with invalid exception behaviour to be generated
Compiling the program below results in the constructor for the class SCE2 throwing Exception, which it is not declared to throw either in the source code or in the generated bytecode. If the 'declare soft' statement is removed, then the super() call in the SCE2 constructor is correctly reported as throwing an undeclared exception; it seems that the 'declare soft' statement turns off the exception checking of the super() call despite there being no join point which covers this call that would actually soften the exception. I'm using 'DEVELOPMENT built on Monday Aug 16, 2004 at 13:50:47 GMT'. public class SuperConsExc { public SuperConsExc() throws Exception { throw new Exception(); } public static void main(String[] args) { new SCE2(); } } class SCE2 extends SuperConsExc { public SCE2() { super(); } } aspect SCEAspect { declare soft: Exception: within(SCE2); }
resolved fixed
eca1429
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2004-09-08T12:04:49Z
2004-08-18T11:53:20Z
tests/bugs/ConvertToUnchecked.java
import org.aspectj.testing.Tester; /** Bugzilla Bug 34925 compiler crash on yesterday's rc1 build */ import java.io.*; public aspect ConvertToUnchecked { public static void main(String[] args) { try { Foo foo = new Foo("hello"); Tester.check(false, "shouldn't get here"); } catch (PersistenceException pe) { } } // convert IOExceptions in Foo to PersistenceException pointcut module() : within(Foo); after() throwing (IOException e) : module() { throw new PersistenceException(e); } declare soft: (IOException): module(); } class PersistenceException extends RuntimeException { Throwable cause; public PersistenceException(Throwable cause) { this.cause = cause; } } class Root { Root(String s) throws IOException { } } class Foo extends Root { Foo(String s) { super(s); } static { if (false) { getFile(); throw new IOException("bar"); } } { if (false) throw new IOException("bar"); } File f = getFile(); static File getFile() throws IOException { throw new IOException("bad"); } public void m() { throw new IOException("hi"); } }
72,157
Bug 72157 declare soft can cause programs with invalid exception behaviour to be generated
Compiling the program below results in the constructor for the class SCE2 throwing Exception, which it is not declared to throw either in the source code or in the generated bytecode. If the 'declare soft' statement is removed, then the super() call in the SCE2 constructor is correctly reported as throwing an undeclared exception; it seems that the 'declare soft' statement turns off the exception checking of the super() call despite there being no join point which covers this call that would actually soften the exception. I'm using 'DEVELOPMENT built on Monday Aug 16, 2004 at 13:50:47 GMT'. public class SuperConsExc { public SuperConsExc() throws Exception { throw new Exception(); } public static void main(String[] args) { new SCE2(); } } class SCE2 extends SuperConsExc { public SCE2() { super(); } } aspect SCEAspect { declare soft: Exception: within(SCE2); }
resolved fixed
eca1429
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2004-09-08T12:04:49Z
2004-08-18T11:53:20Z
tests/bugs/PR72157.java
72,157
Bug 72157 declare soft can cause programs with invalid exception behaviour to be generated
Compiling the program below results in the constructor for the class SCE2 throwing Exception, which it is not declared to throw either in the source code or in the generated bytecode. If the 'declare soft' statement is removed, then the super() call in the SCE2 constructor is correctly reported as throwing an undeclared exception; it seems that the 'declare soft' statement turns off the exception checking of the super() call despite there being no join point which covers this call that would actually soften the exception. I'm using 'DEVELOPMENT built on Monday Aug 16, 2004 at 13:50:47 GMT'. public class SuperConsExc { public SuperConsExc() throws Exception { throw new Exception(); } public static void main(String[] args) { new SCE2(); } } class SCE2 extends SuperConsExc { public SCE2() { super(); } } aspect SCEAspect { declare soft: Exception: within(SCE2); }
resolved fixed
eca1429
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2004-09-08T12:04:49Z
2004-08-18T11:53:20Z
tests/src/org/aspectj/systemtest/ajc121/Ajc121Tests.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 * * ******************************************************************/ package org.aspectj.systemtest.ajc121; import java.io.File; import java.util.Iterator; import java.util.List; import junit.framework.Test; import org.aspectj.bridge.WeaveMessage; import org.aspectj.testing.XMLBasedAjcTestCase; public class Ajc121Tests extends org.aspectj.testing.XMLBasedAjcTestCase { public static Test suite() { return XMLBasedAjcTestCase.loadSuite(Ajc121Tests.class); } protected File getSpecFile() { return new File("../tests/src/org/aspectj/systemtest/ajc121/ajc121.xml"); } public void test001(){ runTest("false ambiguous binding error (introduced in 1.2rc2)"); } public void test002(){ runTest("An if() pointcut inside a perthis() clauses an ABORT - null pointer exception in ajc"); } public void test003(){ runTest("An if() pointcut inside a perthis() clauses an ABORT - null pointer exception in ajc"); } public void test004(){ runTest("An if() pointcut inside a perthis() clauses an ABORT - null pointer exception in ajc"); } public void test005(){ runTest("compiler aborts with 'conflicting dominates orders' with circular declare precedences"); } public void test006(){ runTest("'can't bind type' message has $ for . in type name for declare soft"); } public void test007(){ runTest("Hiding of Instance Methods by static methods"); } public void test008(){ runTest("if(false) optimisation"); } public void test009(){ runTest("if(true) optimisation"); } public void test010(){ runTest("java.lang.NullPointerException in WeaverMessageHandler class"); } public void test011(){ runTest("ClassCastException at BcelRenderer.java:169"); } public void test012(){ runTest("Front-end bug, shouldn't allow patterns of the form foo.., should be foo..*"); } public void test013() { runTest("Nullpointer-Exception when defining a withincode() pointcut"); } public void test014() { runTest("NPE, Incorrect XLint:unmatchedSuperTypeInCall warning"); } public void test015_invalidXlint() { // keywords: "laurie hendren" runTest("invalid warning indicating no match when a match really occurs"); } public void test016_ByteConversionInstructions() { runTest("RuntimeException thrown: Could not find instruction: org.apache.bcel.generic.B2I"); String output = getLastRunResult().getStdErr(); assertTrue("Expected to find [b2] in this output but didn't:"+output,output.indexOf("[b2]")!=-1); assertTrue("Expected to find [b127] in this output but didn't:"+output,output.indexOf("[b127]")!=-1); assertTrue("Expected to find [b0] in this output but didn't:"+output,output.indexOf("[b0]")!=-1); assertTrue("Expected to find [c65] in this output but didn't:"+output,output.indexOf("[c65]")!=-1); assertTrue("Expected to find [c66] in this output but didn't:"+output,output.indexOf("[c66]")!=-1); assertTrue("Expected to find [c67] in this output but didn't:"+output,output.indexOf("[c67]")!=-1); assertTrue("Expected to find [s1] in this output but didn't:"+output,output.indexOf("[s1]")!=-1); assertTrue("Expected to find [s32767] in this output but didn't:"+output,output.indexOf("[s32767]")!=-1); assertTrue("Expected to find [b0] in this output but didn't:"+output,output.indexOf("[b0]")!=-1); } public void test017_PrivateMethodCallsInAroundAdvice() { runTest("Cannot advise private method call in around advice"); System.err.println(getLastRunResult().getStdErr()); } public void test018_PrivateFieldSetsInAroundAdvice() { runTest("Cannot advise private field sets in around advice"); System.err.println(getLastRunResult().getStdErr()); } public void test019_PrivateFieldGetsInAroundAdvice() { runTest("Cannot advise private field gets in around advice"); System.err.println(getLastRunResult().getStdErr()); } // test takes over 5 minutes to run, so not included in normal suite run // public void test020_branchTargetOffsetTooLargeForShort() { // runTest("Branch target offset too large for short"); // } // public void test021_BcelFailureWithVeryLargeClasses() { // runTest("Weaver fails in BCEL for large classes"); // } // // public void test022_BcelFailureWithVeryLargeClasses_Binary() { // runTest("Weaver fails in BCEL for large classes (binary)"); // } public void test023_proceedInAround1() { runTest("proceed used as method name in around advice (1)"); } public void test024_proceedInAround2() { runTest("proceed used as method name in around advice (2)"); } public void test025_proceedInAround3() { runTest("proceed used as method name in around advice (3)"); } public void test026_bindingThisAndTargetToTheSameFormal() { runTest("ajc crashes when compiling the following program (binding this() and target())"); } public void test027_itdsOnInnerClassesAsStatic() { runTest("ITDs on inner classes should be static context"); } public void test028_itdsAndInitializers() { runTest("resolution of IT field inits"); } public void test029_falseInvalidAbsoluteTypeName() { runTest("Valid but inaccessible type names should not be flagged by XLint:invalidAbsoluteTypeName"); } public void test030_privateITDinitialisersBeingMatched() { runTest("intertype initialisers should match field set pointcuts"); } public void test031_privateITDinitialisersBeingMatched_OxfordTest() { runTest("intertype initialisers should match field set pointcuts (oxford testcase)"); //System.err.println(">"+getLastRunResult().getStdErr()); String exp = ":set field set(int C.n):set field set(int C.m):get field get(int C.n):set field set(int C.n)"; assertTrue("Expected output '"+exp+"' but got "+getLastRunResult().getStdErr(), getLastRunResult().getStdErr().equals(exp)); } public void test032_stringConcatForDEOW() { runTest("Compile time declarations (warning and error) do not accept string concatenation (with +)"); } public void test033_stringConcatForDEOWErrorCase() { runTest("Compile time declarations (warning and error) do not accept string concatenation (with +) (2)"); } public void test034_scopeForITDS_pr61768() { runTest("scope for inter-type methods"); } public void test035_innerAspectCallsPrivateMethod_pr71372() { runTest("NoSuchMethodError calling private method from around advice in inner aspect"); String s = getLastRunResult().getStdErr(); assertTrue("Expected ':before:around' but got "+s, s.equals(":before:around")); } public void test036_innerAspectCallsPrivateMethod_pr71372_2() { runTest("NoSuchMethodError calling private method from around advice in inner aspect (2)"); String s = getLastRunResult().getStdErr(); assertTrue("Expected ':before:around' but got "+s, s.equals(":before:around")); } public void test037_innerAspectCallsPrivateMethod_pr71372_3() { runTest("NoSuchMethodError calling private method from around advice in inner aspect (3)"); String s = getLastRunResult().getStdErr(); assertTrue("Expected ':before:around' but got "+s, s.equals(":before:around")); } public void test038_innerAspectCallsPrivateMethod_pr71372_4() { runTest("NoSuchMethodError calling private method from around advice in inner aspect (4)"); String s = getLastRunResult().getStdErr(); assertTrue("Expected ':before:around' but got "+s, s.equals(":before:around")); } public void test039_privilegedAspectAccessingPrivateMethods_pr67579() { runTest("NPE on privileged aspect error"); } public void test040_privilegedAspectAccessingPrivateMethods_pr67579_2() { runTest("NPE on privileged aspect error (2)"); } public void test041_ITDaccessingPrivateMethod_pr67578() { runTest("Privileged Aspect Access Problem Across Packages"); } public void test042_ITDaccessingPrivateMethod_pr67578_2() { runTest("Privileged Aspect Access Problem Across Packages (2)"); } public void test043_pr62642_ExceptionInInitializerError() { runTest("proper handling of ExceptionInIntializer inside clinit in presence of after throwing advice"); String s = getLastRunResult().getStdErr(); assertTrue("Output should contain java.lang.ExceptionInInitializerError but is '"+s+"'", s.indexOf("java.lang.ExceptionInInitializerError")!=-1); // No getCause on 1.3 JVMs // assertTrue("Output should contain 'CAUSE=org.aspectj.lang.NoAspectBoundException' but is '"+s+"'", // s.indexOf("CAUSE=org.aspectj.lang.NoAspectBoundException")!=-1); } public void test044_ITDnameClashes() { runTest("ITD name clashes with private members"); } public void test045_ITDprotectedVisibility() { runTest("Inconsistency in scoping of protected members in ITDs"); } public void test045_wrongLineForExecutionJoinPoint() { runTest("wrong line for method execution join point"); } public void test046_interfaceITD_pr70794_1() { runTest("The introduction on interface causes the interface implementation class error (1)"); } public void test047_interfaceITD_pr70794_2() { runTest("The introduction on interface causes the interface implementation class error (2)"); } public void test048_interfaceITD_pr70794_3() { runTest("The introduction on interface causes the interface implementation class error (3)"); } public void test049_interfaceITD_pr70794_4() { runTest("The introduction on interface causes the interface implementation class error (4)"); } public void test050_typePatternMatchingWithArrays() { runTest("declare warning warns at wrong points"); } public void test051_arrayCloningInJava5() { runTest("AJC possible bug with static nested classes"); List l = ajc.getLastCompilationResult().getInfoMessages(); assertTrue("Should at least have had one weaving message",l!=null && l.size()>0); boolean gotWeaveMessage = false; for (Iterator msg = l.iterator(); msg.hasNext();) { Object element = (Object) msg.next(); if (element instanceof WeaveMessage) { WeaveMessage wm = (WeaveMessage)element; if (wm.getMessage().indexOf("advised by around advice from")!=-1) gotWeaveMessage = true; } } assertTrue("Expected a weaving message but only found "+l,gotWeaveMessage); } public void test052_bogusMessage1() { runTest("Bogus error message: The abstract method ajc$pointcut$$tracingScope$a2 in type Tracing can only be defined by an abstract class (1)"); } public void test053_bogusMessage2() { runTest("Bogus error message: The abstract method ajc$pointcut$$tracingScope$a2 in type Tracing can only be defined by an abstract class (2)"); } public void test054_cnfe() { runTest("passing null to array arguments confuzes static join point signature. (1)"); } public void test055_cnfe() { runTest("passing null to array arguments confuzes static join point signature. (2)"); } public void test056_arrayCloning() { runTest("around advice throws java.lang.VerifyError at runtime"); } }
74,238
Bug 74238 Applet which uses cflow pointcut gets AccessControlException
When I used cflow pointcut for my applet, I couldn't launch the Applet. java.lang.ExceptionInInitializerError at SandAspect.ajc$preClinit(SandAspect.aj) at SandAspect.<clinit>(SandAspect.aj) at SandApplet.init(SandApplet.java) at sun.applet.AppletPanel.run(AppletPanel.java:353) at java.lang.Thread.run(Thread.java:534) Caused by: java.security.AccessControlException: access denied (java.util.Proper tyPermission aspectj.runtime.cflowstack.usethreadlocal read) at java.security.AccessControlContext.checkPermission(AccessControlConte xt.java:269) at java.security.AccessController.checkPermission(AccessController.java: 401) at java.lang.SecurityManager.checkPermission(SecurityManager.java:524) at java.lang.SecurityManager.checkPropertyAccess(SecurityManager.java:12 76) at java.lang.System.getProperty(System.java:612) at org.aspectj.runtime.internal.CFlowStack.selectFactoryForVMVersion(CFl owStack.java:124) at org.aspectj.runtime.internal.CFlowStack.<clinit>(CFlowStack.java:59) ... 5 more It because CFlowStack uses System.getProperty method with no try..catch block. Applet doesn't have permission to read system property: "aspectj.runtime.cflowstack.usethreadlocal". workaround: modify CFlowStack.java(1.5) line 123,124 like this ----- private static String getSystemPropertyWithNoSecurityException( String aPropertyName, String aDefaultValue){ try{ return System.getProperty(aPropertyName, aDefaultValue); } catch(java.lang.SecurityException e){ return aDefaultValue; } } private static void selectFactoryForVMVersion() { String override = getSystemPropertyWithNoSecurityException( "aspectj.runtime.cflowstack.usethreadlocal" , "unspecified" ); ----- I think defining getSystemPropertyWithNoSecurityException(or more simple name :-)) method in some utility class and using it where you call System.getProperty are better way.
resolved fixed
6e155a6
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2004-10-14T08:12:09Z
2004-09-19T10:33:20Z
ajde/testdata/SecurityManagerTest/src/HelloWorld.java
74,238
Bug 74238 Applet which uses cflow pointcut gets AccessControlException
When I used cflow pointcut for my applet, I couldn't launch the Applet. java.lang.ExceptionInInitializerError at SandAspect.ajc$preClinit(SandAspect.aj) at SandAspect.<clinit>(SandAspect.aj) at SandApplet.init(SandApplet.java) at sun.applet.AppletPanel.run(AppletPanel.java:353) at java.lang.Thread.run(Thread.java:534) Caused by: java.security.AccessControlException: access denied (java.util.Proper tyPermission aspectj.runtime.cflowstack.usethreadlocal read) at java.security.AccessControlContext.checkPermission(AccessControlConte xt.java:269) at java.security.AccessController.checkPermission(AccessController.java: 401) at java.lang.SecurityManager.checkPermission(SecurityManager.java:524) at java.lang.SecurityManager.checkPropertyAccess(SecurityManager.java:12 76) at java.lang.System.getProperty(System.java:612) at org.aspectj.runtime.internal.CFlowStack.selectFactoryForVMVersion(CFl owStack.java:124) at org.aspectj.runtime.internal.CFlowStack.<clinit>(CFlowStack.java:59) ... 5 more It because CFlowStack uses System.getProperty method with no try..catch block. Applet doesn't have permission to read system property: "aspectj.runtime.cflowstack.usethreadlocal". workaround: modify CFlowStack.java(1.5) line 123,124 like this ----- private static String getSystemPropertyWithNoSecurityException( String aPropertyName, String aDefaultValue){ try{ return System.getProperty(aPropertyName, aDefaultValue); } catch(java.lang.SecurityException e){ return aDefaultValue; } } private static void selectFactoryForVMVersion() { String override = getSystemPropertyWithNoSecurityException( "aspectj.runtime.cflowstack.usethreadlocal" , "unspecified" ); ----- I think defining getSystemPropertyWithNoSecurityException(or more simple name :-)) method in some utility class and using it where you call System.getProperty are better way.
resolved fixed
6e155a6
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2004-10-14T08:12:09Z
2004-09-19T10:33:20Z
runtime/src/org/aspectj/runtime/internal/CFlowCounter.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: * Andy Clement initial implementation * ******************************************************************/ package org.aspectj.runtime.internal; import org.aspectj.runtime.internal.cflowstack.ThreadCounter; import org.aspectj.runtime.internal.cflowstack.ThreadStackFactory; import org.aspectj.runtime.internal.cflowstack.ThreadStackFactoryImpl; import org.aspectj.runtime.internal.cflowstack.ThreadStackFactoryImpl11; public class CFlowCounter { private static ThreadStackFactory tsFactory; private ThreadCounter flowHeightHandler; static { selectFactoryForVMVersion(); } public CFlowCounter() { flowHeightHandler = tsFactory.getNewThreadCounter(); } public void inc() { flowHeightHandler.inc(); } public void dec() { flowHeightHandler.dec(); } public boolean isValid() { return flowHeightHandler.isNotZero(); } private static ThreadStackFactory getThreadLocalStackFactory() { return new ThreadStackFactoryImpl(); } private static ThreadStackFactory getThreadLocalStackFactoryFor11() { return new ThreadStackFactoryImpl11(); } private static void selectFactoryForVMVersion() { String override = System.getProperty("aspectj.runtime.cflowstack.usethreadlocal","unspecified"); boolean useThreadLocalImplementation = false; if (override.equals("unspecified")) { String v = System.getProperty("java.class.version","0.0"); // Java 1.2 is version 46.0 and above useThreadLocalImplementation = (v.compareTo("46.0") >= 0); } else { useThreadLocalImplementation = override.equals("yes") || override.equals("true"); } // System.err.println("Trying to use thread local implementation? "+useThreadLocalImplementation); if (useThreadLocalImplementation) { tsFactory = getThreadLocalStackFactory(); } else { tsFactory = getThreadLocalStackFactoryFor11(); } } // For debug ... public static String getThreadStackFactoryClassName() { return tsFactory.getClass().getName(); } }
74,238
Bug 74238 Applet which uses cflow pointcut gets AccessControlException
When I used cflow pointcut for my applet, I couldn't launch the Applet. java.lang.ExceptionInInitializerError at SandAspect.ajc$preClinit(SandAspect.aj) at SandAspect.<clinit>(SandAspect.aj) at SandApplet.init(SandApplet.java) at sun.applet.AppletPanel.run(AppletPanel.java:353) at java.lang.Thread.run(Thread.java:534) Caused by: java.security.AccessControlException: access denied (java.util.Proper tyPermission aspectj.runtime.cflowstack.usethreadlocal read) at java.security.AccessControlContext.checkPermission(AccessControlConte xt.java:269) at java.security.AccessController.checkPermission(AccessController.java: 401) at java.lang.SecurityManager.checkPermission(SecurityManager.java:524) at java.lang.SecurityManager.checkPropertyAccess(SecurityManager.java:12 76) at java.lang.System.getProperty(System.java:612) at org.aspectj.runtime.internal.CFlowStack.selectFactoryForVMVersion(CFl owStack.java:124) at org.aspectj.runtime.internal.CFlowStack.<clinit>(CFlowStack.java:59) ... 5 more It because CFlowStack uses System.getProperty method with no try..catch block. Applet doesn't have permission to read system property: "aspectj.runtime.cflowstack.usethreadlocal". workaround: modify CFlowStack.java(1.5) line 123,124 like this ----- private static String getSystemPropertyWithNoSecurityException( String aPropertyName, String aDefaultValue){ try{ return System.getProperty(aPropertyName, aDefaultValue); } catch(java.lang.SecurityException e){ return aDefaultValue; } } private static void selectFactoryForVMVersion() { String override = getSystemPropertyWithNoSecurityException( "aspectj.runtime.cflowstack.usethreadlocal" , "unspecified" ); ----- I think defining getSystemPropertyWithNoSecurityException(or more simple name :-)) method in some utility class and using it where you call System.getProperty are better way.
resolved fixed
6e155a6
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2004-10-14T08:12:09Z
2004-09-19T10:33:20Z
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 java.util.Stack; import org.aspectj.lang.NoAspectBoundException; import org.aspectj.runtime.CFlow; import org.aspectj.runtime.internal.cflowstack.ThreadStack; import org.aspectj.runtime.internal.cflowstack.ThreadStackFactory; import org.aspectj.runtime.internal.cflowstack.ThreadStackFactoryImpl; import org.aspectj.runtime.internal.cflowstack.ThreadStackFactoryImpl11; /* * How we benefit from ThreadLocal when it is available at runtime: * * When the CFlowStack class is loaded, we run its static initializer. This checks the JVM * version number and loads an appropriate implementation of the ThreadStackFactory. * There are two possible implementations depending on whether this is a 1.1 or 1.2+ JVM. * Rather than doing a Class.forName for ThreadLocal and catching a ClassNotFoundEx in order * to determine the JVM version, we look at the java class version which I believe can help * us identify the Java level. * * In the 1.1 JVM case we use a factory implementation that does not use ThreadLocal storage. * In the 1.2+ JVM case we use a factory implementation that does use ThreadLocal storage. * * Once we have the factory set, whenever someone builds a CFlowStack object, we ask the * factory for a new stack proxy - this is an object that can return us the right stack * that we should use on a particular thread. The reason we create the proxy in the ctor and * not lazily in the getThreadStack() method is because it means the getThreadStack() method in * this class does not have to be synchronized. * * When any of the methods in CFlowStack need to operate on the stack (peek/pop/etc), they * all delegate to getThreadStack() which asks the proxy for the right stack. Depending on the * factory loaded to build the proxy, the call to proxy.getThreadStack() will return a threadlocal * based stack or it will call the original implementation of getThreadStack() which manages * a Hashtable of threads->stacks. * */ public class CFlowStack { private static ThreadStackFactory tsFactory; private ThreadStack stackProxy; static { selectFactoryForVMVersion(); } public CFlowStack() { stackProxy = tsFactory.getNewThreadStack(); } private Stack getThreadStack() { return stackProxy.getThreadStack(); } //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(); } private static ThreadStackFactory getThreadLocalStackFactory() { return new ThreadStackFactoryImpl(); } private static ThreadStackFactory getThreadLocalStackFactoryFor11() { return new ThreadStackFactoryImpl11(); } private static void selectFactoryForVMVersion() { String override = System.getProperty("aspectj.runtime.cflowstack.usethreadlocal","unspecified"); boolean useThreadLocalImplementation = false; if (override.equals("unspecified")) { String v = System.getProperty("java.class.version","0.0"); // Java 1.2 is version 46.0 and above useThreadLocalImplementation = (v.compareTo("46.0") >= 0); } else { useThreadLocalImplementation = override.equals("yes") || override.equals("true"); } // System.err.println("Trying to use thread local implementation? "+useThreadLocalImplementation); if (useThreadLocalImplementation) { tsFactory = getThreadLocalStackFactory(); } else { tsFactory = getThreadLocalStackFactoryFor11(); } } // For debug ... public static String getThreadStackFactoryClassName() { return tsFactory.getClass().getName(); } }
75,568
Bug 75568 ajc changes classfile timestamps even if compilation fails (regression)
It appears that ajc 1.2 updates a classfile timestamps even if the compilation fails. This breaks the integration with the Ant build system. E.g. using the ant "javac" task with the Ajc11CompilerAdapter interface, the compilation may fail on the first attempt and succeed on the second attempt, - because ajc has touched the timestamp and Ant hence decides that nothing needs to be recompiled. This did not happen in ajc 1.1. To reproduce: 1. In the examples/observer folder, run a build: ajc -sourceroots . 2. Edit the "Demo.java" class and insert the line "DONT COMPILE" 3. Run the compilation again. The compiler displays the correct error message but the Demo.class file has been updated with the compile-time timestamp.
resolved fixed
0a77939
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2004-10-14T12:51:18Z
2004-10-04T14: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.aspectj.weaver.Dump; import org.aspectj.weaver.WeaverMessages; import org.aspectj.org.eclipse.jdt.core.compiler.InvalidInputException; import org.aspectj.org.eclipse.jdt.internal.compiler.batch.Main; import org.aspectj.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) { Dump.saveCommandLine(args); 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)); buildConfig.setBootclasspath(getBootclasspath(parser)); } if (incrementalMode && (0 == buildConfig.getSourceRoots().size())) { MessageUtil.error(handler, "specify a source root when in incremental mode"); } /* * Ensure we don't overwrite injars, inpath or aspectpath with outjar * bug-71339 */ File outjar = buildConfig.getOutputJar(); if (outjar != null) { /* Search injars */ for (Iterator i = buildConfig.getInJars().iterator(); i.hasNext(); ) { File injar = (File)i.next(); if (injar.equals(outjar)) { String message = WeaverMessages.format(WeaverMessages.OUTJAR_IN_INPUT_PATH); MessageUtil.error(handler,message); } } /* Search inpath */ for (Iterator i = buildConfig.getInpath().iterator(); i.hasNext(); ) { File inPathElement = (File)i.next(); if (!inPathElement.isDirectory() && inPathElement.equals(outjar)) { String message = WeaverMessages.format(WeaverMessages.OUTJAR_IN_INPUT_PATH); MessageUtil.error(handler,message); } } /* Search aspectpath */ for (Iterator i = buildConfig.getAspectpath().iterator(); i.hasNext(); ) { File pathElement = (File)i.next(); if (!pathElement.isDirectory() && pathElement.equals(outjar)) { String message = WeaverMessages.format(WeaverMessages.OUTJAR_IN_INPUT_PATH); MessageUtil.error(handler,message); } } } 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)); } public List getBootclasspath(AjcConfigParser parser) { List ret = new ArrayList(); if (parser.bootclasspath == null) { addClasspath(System.getProperty("sun.boot.class.path", ""), ret); } else { addClasspath(parser.bootclasspath, ret); } return ret; } /** * 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) { String bcpArg = ((ConfigParser.Arg)args.get(nextArgIndex)).getValue(); StringBuffer bcp = new StringBuffer(); StringTokenizer strTok = new StringTokenizer(bcpArg,File.pathSeparator); while (strTok.hasMoreTokens()) { bcp.append(makeFile(strTok.nextToken())); if (strTok.hasMoreTokens()) { bcp.append(File.pathSeparator); } } bootclasspath = bcp.toString(); args.remove(args.get(nextArgIndex)); } else { showError("-bootclasspath requires classpath entries"); } } else if (arg.equals("-classpath") || arg.equals("-cp")) { if (args.size() > nextArgIndex) { String cpArg = ((ConfigParser.Arg)args.get(nextArgIndex)).getValue(); StringBuffer cp = new StringBuffer(); StringTokenizer strTok = new StringTokenizer(cpArg,File.pathSeparator); while (strTok.hasMoreTokens()) { cp.append(makeFile(strTok.nextToken())); if (strTok.hasMoreTokens()) { cp.append(File.pathSeparator); } } classpath = cp.toString(); args.remove(args.get(nextArgIndex)); } else { showError("-classpath requires classpath entries"); } } else if (arg.equals("-extdirs")) { if (args.size() > nextArgIndex) { String extdirsArg = ((ConfigParser.Arg)args.get(nextArgIndex)).getValue(); StringBuffer ed = new StringBuffer(); StringTokenizer strTok = new StringTokenizer(extdirsArg,File.pathSeparator); while (strTok.hasMoreTokens()) { ed.append(makeFile(strTok.nextToken())); if (strTok.hasMoreTokens()) { ed.append(File.pathSeparator); } } extdirs = ed.toString(); 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); } } }
75,568
Bug 75568 ajc changes classfile timestamps even if compilation fails (regression)
It appears that ajc 1.2 updates a classfile timestamps even if the compilation fails. This breaks the integration with the Ant build system. E.g. using the ant "javac" task with the Ajc11CompilerAdapter interface, the compilation may fail on the first attempt and succeed on the second attempt, - because ajc has touched the timestamp and Ant hence decides that nothing needs to be recompiled. This did not happen in ajc 1.1. To reproduce: 1. In the examples/observer folder, run a build: ajc -sourceroots . 2. Edit the "Demo.java" class and insert the line "DONT COMPILE" 3. Run the compilation again. The compiler displays the correct error message but the Demo.class file has been updated with the compile-time timestamp.
resolved fixed
0a77939
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2004-10-14T12:51:18Z
2004-10-04T14:26:40Z
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.aspectj.weaver.patterns.CflowPointcut; import org.aspectj.org.eclipse.jdt.internal.compiler.CompilationResult; import org.aspectj.org.eclipse.jdt.internal.compiler.Compiler; import org.aspectj.org.eclipse.jdt.internal.compiler.ICompilerAdapter; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration; import org.aspectj.org.eclipse.jdt.internal.compiler.env.ICompilationUnit; import org.aspectj.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; } catch (RuntimeException rEx) { if (rEx instanceof AbortCompilation) throw rEx; // Don't wrap AbortCompilation exceptions! // This will be unwrapped in Compiler.handleInternalException() and the nested // RuntimeException thrown back to the original caller - which is AspectJ // which will then then log it as a compiler problem. throw new AbortCompilation(true,rEx); } } 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); // XXX - see bugs 57432,58679 - final parameter on next call should be "compiler.options.maxProblemsPerUnit" CompilationResult result = new CompilationResult(sourceFileName.toCharArray(),0,0,Integer.MAX_VALUE); 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)); // } try { weaver.weave(new WeaverAdapter(this,weaverMessageHandler,progressListener)); } finally { // ???: is this the right point for this? After weaving has finished clear the caches. CflowPointcut.clearCaches(); } } 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); } } } }
75,568
Bug 75568 ajc changes classfile timestamps even if compilation fails (regression)
It appears that ajc 1.2 updates a classfile timestamps even if the compilation fails. This breaks the integration with the Ant build system. E.g. using the ant "javac" task with the Ajc11CompilerAdapter interface, the compilation may fail on the first attempt and succeed on the second attempt, - because ajc has touched the timestamp and Ant hence decides that nothing needs to be recompiled. This did not happen in ajc 1.1. To reproduce: 1. In the examples/observer folder, run a build: ajc -sourceroots . 2. Edit the "Demo.java" class and insert the line "DONT COMPILE" 3. Run the compilation again. The compiler displays the correct error message but the Demo.class file has been updated with the compile-time timestamp.
resolved fixed
0a77939
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2004-10-14T12:51:18Z
2004-10-04T14:26:40Z
org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/core/builder/AjBuildConfig.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Common Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * PARC initial implementation * Adrian Colyer added constructor to populate javaOptions with * default settings - 01.20.2003 * Bugzilla #29768, 29769 * ******************************************************************/ package org.aspectj.ajdt.internal.core.builder; import java.io.File; import java.io.FileFilter; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import org.aspectj.util.FileUtil; /** * All configuration information needed to run the AspectJ compiler. * Compiler options (as opposed to path information) are held in an AjCompilerOptions instance */ public class AjBuildConfig { private boolean shouldProceed = true; public static final String AJLINT_IGNORE = "ignore"; public static final String AJLINT_WARN = "warn"; public static final String AJLINT_ERROR = "error"; public static final String AJLINT_DEFAULT = "default"; private File outputDir; private File outputJar; private List/*File*/ sourceRoots = new ArrayList(); private List/*File*/ files = new ArrayList(); private List /*File*/ binaryFiles = new ArrayList(); // .class files in indirs... private List/*File*/ inJars = new ArrayList(); private List/*File*/ inPath = new ArrayList(); private Map/*String->File*/ sourcePathResources = new HashMap(); private List/*File*/ aspectpath = new ArrayList(); private List/*String*/ classpath = new ArrayList(); private List/*String*/ bootclasspath = new ArrayList(); private File configFile; private String lintMode = AJLINT_DEFAULT; private File lintSpecFile = null; private AjCompilerOptions options; /** if true, then global values override local when joining */ private boolean override = true; // incremental variants handled by the compiler client, but parsed here private boolean incrementalMode; private File incrementalFile; public static class BinarySourceFile { public BinarySourceFile(File dir, File src) { this.fromInPathDirectory = dir; this.binSrc = src; } public File fromInPathDirectory; public File binSrc; public boolean equals(Object obj) { if ((obj instanceof BinarySourceFile) && (obj != null)) { BinarySourceFile other = (BinarySourceFile)obj; return(binSrc.equals(other.binSrc)); } return false; } public int hashCode() { return binSrc != null ? binSrc.hashCode() : 0; } } /** * Intialises the javaOptions Map to hold the default * JDT Compiler settings. Added by AMC 01.20.2003 in reponse * to bug #29768 and enh. 29769. * The settings here are duplicated from those set in * org.eclipse.jdt.internal.compiler.batch.Main, but I've elected to * copy them rather than refactor the JDT class since this keeps * integration with future JDT releases easier (?). */ public AjBuildConfig( ) { options = new AjCompilerOptions(); } /** * returned files includes <ul> * <li>files explicitly listed on command-line</li> * <li>files listed by reference in argument list files</li> * <li>files contained in sourceRootDir if that exists</li> * </ul> * * @return all source files that should be compiled. */ public List/*File*/ getFiles() { return files; } /** * returned files includes all .class files found in * a directory on the inpath, but does not include * .class files contained within jars. */ public List/*BinarySourceFile*/ getBinaryFiles() { return binaryFiles; } public File getOutputDir() { return outputDir; } public void setFiles(List files) { this.files = files; } public void setOutputDir(File outputDir) { this.outputDir = outputDir; } public AjCompilerOptions getOptions() { return options; } /** * This does not include -bootclasspath but includes -extdirs and -classpath */ public List getClasspath() { // XXX setters don't respect javadoc contract... return classpath; } public void setClasspath(List classpath) { this.classpath = classpath; } public List getBootclasspath() { return bootclasspath; } public void setBootclasspath(List bootclasspath) { this.bootclasspath = bootclasspath; } public File getOutputJar() { return outputJar; } public List/*File*/ getInpath() { // Elements of the list are either archives (jars/zips) or directories return inPath; } public List/*File*/ getInJars() { return inJars; } public Map getSourcePathResources() { return sourcePathResources; } public void setOutputJar(File outputJar) { this.outputJar = outputJar; } public void setInJars(List sourceJars) { this.inJars = sourceJars; } public void setInPath(List dirsOrJars) { inPath = dirsOrJars; // remember all the class files in directories on the inpath binaryFiles = new ArrayList(); FileFilter filter = new FileFilter() { public boolean accept(File pathname) { return pathname.getPath().endsWith(".class"); }}; for (Iterator iter = dirsOrJars.iterator(); iter.hasNext();) { File inpathElement = (File) iter.next(); if (inpathElement.isDirectory()) { File[] files = FileUtil.listFiles(inpathElement, filter); for (int i = 0; i < files.length; i++) { binaryFiles.add(new BinarySourceFile(inpathElement,files[i])); } } } } public List getSourceRoots() { return sourceRoots; } public void setSourceRoots(List sourceRootDir) { this.sourceRoots = sourceRootDir; } public File getConfigFile() { return configFile; } public void setConfigFile(File configFile) { this.configFile = configFile; } public void setIncrementalMode(boolean incrementalMode) { this.incrementalMode = incrementalMode; } public boolean isIncrementalMode() { return incrementalMode; } public void setIncrementalFile(File incrementalFile) { this.incrementalFile = incrementalFile; } public boolean isIncrementalFileMode() { return (null != incrementalFile); } /** * @return List (String) classpath of bootclasspath, injars, inpath, aspectpath * entries, specified classpath (extdirs, and classpath), and output dir or jar */ public List getFullClasspath() { List full = new ArrayList(); full.addAll(getBootclasspath()); // XXX Is it OK that boot classpath overrides inpath/injars/aspectpath? for (Iterator i = inJars.iterator(); i.hasNext(); ) { full.add(((File)i.next()).getAbsolutePath()); } for (Iterator i = inPath.iterator();i.hasNext();) { full.add(((File)i.next()).getAbsolutePath()); } for (Iterator i = aspectpath.iterator(); i.hasNext(); ) { full.add(((File)i.next()).getAbsolutePath()); } full.addAll(getClasspath()); // if (null != outputDir) { // full.add(outputDir.getAbsolutePath()); // } else if (null != outputJar) { // full.add(outputJar.getAbsolutePath()); // } return full; } public File getLintSpecFile() { return lintSpecFile; } public void setLintSpecFile(File lintSpecFile) { this.lintSpecFile = lintSpecFile; } public List getAspectpath() { return aspectpath; } public void setAspectpath(List aspectpath) { this.aspectpath = aspectpath; } /** @return true if any config file, sourceroots, sourcefiles, injars or inpath */ public boolean hasSources() { return ((null != configFile) || (0 < sourceRoots.size()) || (0 < files.size()) || (0 < inJars.size()) || (0 < inPath.size()) ); } // /** @return null if no errors, String errors otherwise */ // public String configErrors() { // StringBuffer result = new StringBuffer(); // // ok, permit both. sigh. //// if ((null != outputDir) && (null != outputJar)) { //// result.append("specified both outputDir and outputJar"); //// } // // incremental => only sourceroots // // // return (0 == result.length() ? null : result.toString()); // } /** * Install global values into local config * unless values conflict: * <ul> * <li>Collections are unioned</li> * <li>values takes local value unless default and global set</li> * <li>this only sets one of outputDir and outputJar as needed</li> * <ul> * This also configures super if javaOptions change. * @param global the AjBuildConfig to read globals from */ public void installGlobals(AjBuildConfig global) { // XXX relies on default values // don't join the options - they already have defaults taken care of. // Map optionsMap = options.getMap(); // join(optionsMap,global.getOptions().getMap()); // options.set(optionsMap); join(aspectpath, global.aspectpath); join(classpath, global.classpath); if (null == configFile) { configFile = global.configFile; // XXX correct? } if (!isEmacsSymMode() && global.isEmacsSymMode()) { setEmacsSymMode(true); } join(files, global.files); if (!isGenerateModelMode() && global.isGenerateModelMode()) { setGenerateModelMode(true); } if (null == incrementalFile) { incrementalFile = global.incrementalFile; } if (!incrementalMode && global.incrementalMode) { incrementalMode = true; } join(inJars, global.inJars); join(inPath, global.inPath); if ((null == lintMode) || (AJLINT_DEFAULT.equals(lintMode))) { setLintMode(global.lintMode); } if (null == lintSpecFile) { lintSpecFile = global.lintSpecFile; } if (!isNoWeave() && global.isNoWeave()) { setNoWeave(true); } if ((null == outputDir) && (null == outputJar)) { if (null != global.outputDir) { outputDir = global.outputDir; } if (null != global.outputJar) { outputJar = global.outputJar; } } join(sourceRoots, global.sourceRoots); if (!isXnoInline() && global.isXnoInline()) { setXnoInline(true); } if (!isXserializableAspects() && global.isXserializableAspects()) { setXserializableAspects(true); } if (!isXlazyTjp() && global.isXlazyTjp()) { setXlazyTjp(true); } if (!isXreweavable() && global.isXreweavable()) { setXreweavable(true); } if (!getXreweavableCompressClasses() && global.getXreweavableCompressClasses()) { setXreweavableCompressClasses(true); } } void join(Collection local, Collection global) { for (Iterator iter = global.iterator(); iter.hasNext();) { Object next = iter.next(); if (!local.contains(next)) { local.add(next); } } } void join(Map local, Map global) { for (Iterator iter = global.keySet().iterator(); iter.hasNext();) { Object key = iter.next(); if (override || (null == local.get(key))) { // Object value = global.get(key); if (null != value) { local.put(key, value); } } } } public void setSourcePathResources(Map map) { sourcePathResources = map; } /** * used to indicate whether to proceed after parsing config */ public boolean shouldProceed() { return shouldProceed; } public void doNotProceed() { shouldProceed = false; } public String getLintMode() { return lintMode; } // options... public void setLintMode(String lintMode) { this.lintMode = lintMode; String lintValue = null; if (AJLINT_IGNORE.equals(lintMode)) { lintValue = AjCompilerOptions.IGNORE; } else if (AJLINT_WARN.equals(lintMode)) { lintValue = AjCompilerOptions.WARNING; } else if (AJLINT_ERROR.equals(lintMode)) { lintValue = AjCompilerOptions.ERROR; } if (lintValue != null) { Map lintOptions = new HashMap(); lintOptions.put(AjCompilerOptions.OPTION_ReportInvalidAbsoluteTypeName,lintValue); lintOptions.put(AjCompilerOptions.OPTION_ReportInvalidWildcardTypeName,lintValue); lintOptions.put(AjCompilerOptions.OPTION_ReportUnresolvableMember,lintValue); lintOptions.put(AjCompilerOptions.OPTION_ReportTypeNotExposedToWeaver,lintValue); lintOptions.put(AjCompilerOptions.OPTION_ReportShadowNotInStructure,lintValue); lintOptions.put(AjCompilerOptions.OPTION_ReportUnmatchedSuperTypeInCall,lintValue); lintOptions.put(AjCompilerOptions.OPTION_ReportCannotImplementLazyTJP,lintValue); lintOptions.put(AjCompilerOptions.OPTION_ReportNeedSerialVersionUIDField,lintValue); lintOptions.put(AjCompilerOptions.OPTION_ReportIncompatibleSerialVersion,lintValue); options.set(lintOptions); } } public boolean isNoWeave() { return options.noWeave; } public void setNoWeave(boolean noWeave) { options.noWeave = noWeave; } public boolean isXserializableAspects() { return options.xSerializableAspects; } public void setXserializableAspects(boolean xserializableAspects) { options.xSerializableAspects = xserializableAspects; } public boolean isXnoInline() { return options.xNoInline; } public void setXnoInline(boolean xnoInline) { options.xNoInline = xnoInline; } public boolean isXlazyTjp() { return options.xLazyThisJoinPoint; } public void setXlazyTjp(boolean b) { options.xLazyThisJoinPoint = b; } public void setXreweavable(boolean b) { options.xReweavable = b; } public boolean isXreweavable() { return options.xReweavable; } public void setXreweavableCompressClasses(boolean b) { options.xReweavableCompress = b; } public boolean getXreweavableCompressClasses() { return options.xReweavableCompress; } public boolean isGenerateJavadocsInModelMode() { return options.generateJavaDocsInModel; } public void setGenerateJavadocsInModelMode( boolean generateJavadocsInModelMode) { options.generateJavaDocsInModel = generateJavadocsInModelMode; } public boolean isEmacsSymMode() { return options.generateEmacsSymFiles; } public void setEmacsSymMode(boolean emacsSymMode) { options.generateEmacsSymFiles = emacsSymMode; } public boolean isGenerateModelMode() { return options.generateModel; } public void setGenerateModelMode(boolean structureModelMode) { options.generateModel = structureModelMode; } public void setShowWeavingInformation(boolean b) { options.showWeavingInformation = true; } public boolean getShowWeavingInformation() { return options.showWeavingInformation; } }
75,568
Bug 75568 ajc changes classfile timestamps even if compilation fails (regression)
It appears that ajc 1.2 updates a classfile timestamps even if the compilation fails. This breaks the integration with the Ant build system. E.g. using the ant "javac" task with the Ajc11CompilerAdapter interface, the compilation may fail on the first attempt and succeed on the second attempt, - because ajc has touched the timestamp and Ant hence decides that nothing needs to be recompiled. This did not happen in ajc 1.1. To reproduce: 1. In the examples/observer folder, run a build: ajc -sourceroots . 2. Edit the "Demo.java" class and insert the line "DONT COMPILE" 3. Run the compilation again. The compiler displays the correct error message but the Demo.class file has been updated with the compile-time timestamp.
resolved fixed
0a77939
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2004-10-14T12:51:18Z
2004-10-04T14:26:40Z
org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/core/builder/AjBuildManager.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the 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.Dump; import org.aspectj.weaver.World; import org.aspectj.weaver.bcel.*; import org.eclipse.core.runtime.OperationCanceledException; import org.aspectj.org.eclipse.jdt.core.compiler.*; import org.aspectj.org.eclipse.jdt.internal.compiler.*; import org.aspectj.org.eclipse.jdt.internal.compiler.batch.*; import org.aspectj.org.eclipse.jdt.internal.compiler.batch.FileSystem; import org.aspectj.org.eclipse.jdt.internal.compiler.env.*; import org.aspectj.org.eclipse.jdt.internal.compiler.impl.CompilerOptions; import org.aspectj.org.eclipse.jdt.internal.compiler.parser.Parser; import org.aspectj.org.eclipse.jdt.internal.compiler.problem.AbortCompilation; import org.aspectj.org.eclipse.jdt.internal.compiler.problem.DefaultProblemFactory; //import org.aspectj.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 || !AsmManager.attemptIncrementalModelRepairs) { // if (buildConfig.isEmacsSymMode() || buildConfig.isGenerateModelMode()) { setupModel(buildConfig); // } } 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; } if (AsmManager.isReporting()) AsmManager.getDefault().reportModelInfo("After a batch build"); } else { // done already? // if (buildConfig.isEmacsSymMode() || buildConfig.isGenerateModelMode()) { // bcelWorld.setModel(StructureModelManager.INSTANCE.getStructureModel()); // } // System.err.println("XXXX start inc "); binarySourcesForTheNextCompile = state.getBinaryFilesToCompile(true); List files = state.getFilesToCompile(true); if (buildConfig.isEmacsSymMode() || buildConfig.isGenerateModelMode()) if (AsmManager.attemptIncrementalModelRepairs) AsmManager.getDefault().processDelta(files,state.addedFiles,state.deletedFiles); 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()); // TODO Andy - Needs some thought here... // I think here we might want to pass empty addedFiles/deletedFiles as they were // dealt with on the first call to processDelta - we are going through this loop // again because in compiling something we found something else we needed to // rebuild. But what case causes this? if (hereWeGoAgain) if (buildConfig.isEmacsSymMode() || buildConfig.isGenerateModelMode()) if (AsmManager.attemptIncrementalModelRepairs) AsmManager.getDefault().processDelta(files,state.addedFiles,state.deletedFiles); } if (!files.isEmpty()) { return batchBuild(buildConfig, baseHandler); } else { if (AsmManager.isReporting()) AsmManager.getDefault().reportModelInfo("After an incremental build"); } } // XXX not in Mik's incremental if (buildConfig.isEmacsSymMode()) { new org.aspectj.ajdt.internal.core.builder.EmacsStructureModelManager().externalizeModel(); } // 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(buildConfig.getOutputJar()); } 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(File outJar) { try { if (zos != null) zos.close(); zos = null; /* Ensure we don't write an incomplete JAR bug-71339 */ if (handler.hasErrors()) { outJar.delete(); } } catch (IOException ex) { IMessage message = new Message("Unable to write outjar " + outJar.getPath() + "(" + ex.getMessage() + ")", new SourceLocation(outJar,0), true); handler.handleMessage(message); } } private void copyResourcesToDestination() throws IOException { // resources that we need to copy are contained in the injars and inpath only for (Iterator i = buildConfig.getInJars().iterator(); i.hasNext(); ) { File inJar = (File)i.next(); copyResourcesFromJarFile(inJar); } for (Iterator i = buildConfig.getInpath().iterator(); i.hasNext(); ) { File inPathElement = (File)i.next(); if (inPathElement.isDirectory()) { copyResourcesFromDirectory(inPathElement); } else { copyResourcesFromJarFile(inPathElement); } } if (buildConfig.getSourcePathResources() != null) { for (Iterator i = buildConfig.getSourcePathResources().keySet().iterator(); i.hasNext(); ) { String resource = (String)i.next(); File from = (File)buildConfig.getSourcePathResources().get(resource); copyResourcesFromFile(from,resource,from); } } writeManifest(); } private void copyResourcesFromJarFile(File jarFile) throws IOException { JarInputStream inStream = null; try { inStream = new JarInputStream(new FileInputStream(jarFile)); while (true) { ZipEntry entry = inStream.getNextEntry(); if (entry == null) break; String filename = entry.getName(); // System.out.println("? copyResourcesFromJarFile() filename='" + filename +"'"); if (!entry.isDirectory() && acceptResource(filename)) { byte[] bytes = FileUtil.readAsByteArray(inStream); writeResource(filename,bytes,jarFile); } inStream.closeEntry(); } } finally { if (inStream != null) inStream.close(); } } private void copyResourcesFromDirectory(File dir) throws IOException { if (!COPY_INPATH_DIR_RESOURCES) return; // Get a list of all files (i.e. everything that isnt a directory) File[] files = FileUtil.listFiles(dir,new FileFilter() { public boolean accept(File f) { boolean accept = !(f.isDirectory() || f.getName().endsWith(".class")) ; return accept; } }); // For each file, add it either as a real .class file or as a resource for (int i = 0; i < files.length; i++) { // ASSERT: files[i].getAbsolutePath().startsWith(inFile.getAbsolutePath() // or we are in trouble... String filename = files[i].getAbsolutePath().substring( dir.getAbsolutePath().length()+1); copyResourcesFromFile(files[i],filename,dir); } } private void copyResourcesFromFile(File f,String filename,File src) throws IOException { if (!acceptResource(filename)) return; FileInputStream fis = null; try { fis = new FileInputStream(f); byte[] bytes = FileUtil.readAsByteArray(fis); // String relativePath = files[i].getPath(); writeResource(filename,bytes,src); } finally { if (fis != null) fis.close(); } } private void writeResource(String filename, byte[] content, File srcLocation) throws IOException { if (state.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")) || (resourceName.toUpperCase().equals(MANIFEST_NAME)) ) { return false; } else { return true; } } // public static void dumprels() { // IRelationshipMap irm = AsmManager.getDefault().getRelationshipMap(); // int ctr = 1; // Set entries = irm.getEntries(); // for (Iterator iter = entries.iterator(); iter.hasNext();) { // String hid = (String) iter.next(); // List rels = irm.get(hid); // for (Iterator iterator = rels.iterator(); iterator.hasNext();) { // IRelationship ir = (IRelationship) iterator.next(); // List targets = ir.getTargets(); // for (Iterator iterator2 = targets.iterator(); // iterator2.hasNext(); // ) { // String thid = (String) iterator2.next(); // System.err.println("Hid:"+(ctr++)+":(targets="+targets.size()+") "+hid+" ("+ir.getName()+") "+thid); // } // } // } // } /** * Responsible for managing the ASM model between builds. Contains the policy for * maintaining the persistance of elements in the model. * * TODO: implement incremental policy. */ private void setupModel(AjBuildConfig config) { IHierarchy model = AsmManager.getDefault().getHierarchy(); String rootLabel = "<root>"; 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); } // // private void dumplist(List l) { // System.err.println("---- "+l.size()); // for (int i =0 ;i<l.size();i++) System.err.println(i+"\t "+l.get(i)); // } // private void accumulateFileNodes(IProgramElement ipe,List store) { // if (ipe.getKind()==IProgramElement.Kind.FILE_JAVA || // ipe.getKind()==IProgramElement.Kind.FILE_ASPECTJ) { // if (!ipe.getName().equals("<root>")) { // store.add(ipe); // return; // } // } // for (Iterator i = ipe.getChildren().iterator();i.hasNext();) { // accumulateFileNodes((IProgramElement)i.next(),store); // } // } /** init only on initial batch compile? no file-specific options */ private void initBcelWorld(IMessageHandler handler) throws IOException { List cp = buildConfig.getBootclasspath(); cp.addAll(buildConfig.getClasspath()); bcelWorld = new BcelWorld(cp, 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(); Dump.saveFullClasspath(cps); String[] classpaths = new String[cps.size()]; for (int i=0; i < cps.size(); i++) { classpaths[i] = (String)cps.get(i); } //System.out.println("compiling"); environment = getLibraryAccess(classpaths, filenames); if (!state.classesFromName.isEmpty()) { environment = new StatefulNameEnvironment(environment, state.classesFromName); } org.aspectj.org.eclipse.jdt.internal.compiler.Compiler.setCompilerAdapterFactory(this); org.aspectj.org.eclipse.jdt.internal.compiler.Compiler compiler = new org.aspectj.org.eclipse.jdt.internal.compiler.Compiler(environment, DefaultErrorHandlingPolicies.proceedWithAllProblems(), buildConfig.getOptions().getMap(), getBatchRequestor(), getProblemFactory()); CompilerOptions options = compiler.options; options.produceReferenceInfo = true; //TODO turn off when not needed try { compiler.compile(getCompilationUnits(filenames, encodings)); } catch (OperationCanceledException oce) { handler.handleMessage(new Message("build cancelled:"+oce.getMessage(),IMessage.WARNING,null,null)); } // cleanup 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(AjBuildConfig buildConfig) { if (buildConfig == null || buildConfig.getFullClasspath() == null) return ""; StringBuffer buf = new StringBuffer(); boolean first = true; for (Iterator it = buildConfig.getFullClasspath().iterator(); it.hasNext(); ) { if (first) { first = false; } else { buf.append(File.pathSeparator); } buf.append(it.next().toString()); } return buf.toString(); } /** * This will return null if aspectjrt.jar is present and has the correct version. * Otherwise it will return a string message indicating the problem. */ 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.getFullClasspath() == null) return "no classpath specified"; for (Iterator it = buildConfig.getFullClasspath().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(buildConfig); } public String toString() { StringBuffer buf = new StringBuffer(); buf.append("AjBuildManager("); buf.append(")"); return buf.toString(); } public void setStructureModel(IHierarchy structureModel) { this.structureModel = structureModel; } /** * Returns null if there is no structure model */ public IHierarchy getStructureModel() { return structureModel; } public IProgressListener getProgressListener() { return progressListener; } public void setProgressListener(IProgressListener progressListener) { this.progressListener = progressListener; } /* (non-Javadoc) * @see org.aspectj.ajdt.internal.compiler.AjCompiler.IOutputClassFileNameProvider#getOutputClassFileName(char[]) */ public String getOutputClassFileName(char[] eclipseClassFileName, CompilationResult result) { String filename = new String(eclipseClassFileName); filename = filename.replace('/', File.separatorChar) + ".class"; File destinationPath = buildConfig.getOutputDir(); String outFile; if (destinationPath == null) { outFile = new File(filename).getName(); outFile = new File(extractDestinationPathFromSourceFile(result), outFile).getPath(); } else { outFile = new File(destinationPath, filename).getPath(); } return outFile; } /* (non-Javadoc) * @see org.eclipse.jdt.internal.compiler.ICompilerAdapterFactory#getAdapter(org.eclipse.jdt.internal.compiler.Compiler) */ public ICompilerAdapter getAdapter(org.aspectj.org.eclipse.jdt.internal.compiler.Compiler forCompiler) { // complete compiler config and return a suitable adapter... 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; } public AjState getState() { return state; } } // class AjBuildManager
75,568
Bug 75568 ajc changes classfile timestamps even if compilation fails (regression)
It appears that ajc 1.2 updates a classfile timestamps even if the compilation fails. This breaks the integration with the Ant build system. E.g. using the ant "javac" task with the Ajc11CompilerAdapter interface, the compilation may fail on the first attempt and succeed on the second attempt, - because ajc has touched the timestamp and Ant hence decides that nothing needs to be recompiled. This did not happen in ajc 1.1. To reproduce: 1. In the examples/observer folder, run a build: ajc -sourceroots . 2. Edit the "Demo.java" class and insert the line "DONT COMPILE" 3. Run the compilation again. The compiler displays the correct error message but the Demo.class file has been updated with the compile-time timestamp.
resolved fixed
0a77939
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2004-10-14T12:51:18Z
2004-10-04T14:26:40Z
org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/core/builder/AjCompilerOptions.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.util.Map; import org.aspectj.org.eclipse.jdt.internal.compiler.impl.CompilerOptions; /** * Compiler options used by Eclipse integration (AJDT) */ public class AjCompilerOptions extends CompilerOptions { // AspectJ Lint options public static final String OPTION_ReportInvalidAbsoluteTypeName = "org.aspectj.ajdt.core.compiler.lint.InvalidAbsoluteTypeName"; public static final String OPTION_ReportInvalidWildcardTypeName = "org.aspectj.ajdt.core.compiler.lint.WildcardTypeName"; public static final String OPTION_ReportUnresolvableMember = "org.aspectj.ajdt.core.compiler.lint.UnresolvableMember"; public static final String OPTION_ReportTypeNotExposedToWeaver = "org.aspectj.ajdt.core.compiler.lint.TypeNotExposedToWeaver"; public static final String OPTION_ReportShadowNotInStructure = "org.aspectj.ajdt.core.compiler.lint.ShadowNotInStructure"; public static final String OPTION_ReportUnmatchedSuperTypeInCall = "org.aspectj.ajdt.core.compiler.list.UnmatchedSuperTypeInCall"; public static final String OPTION_ReportCannotImplementLazyTJP = "org.aspectj.ajdt.core.compiler.lint.CannotImplementLazyTJP"; public static final String OPTION_ReportNeedSerialVersionUIDField = "org.aspectj.ajdt.core.compiler.lint.NeedSerialVersionUIDField"; public static final String OPTION_ReportIncompatibleSerialVersion = "org.aspectj.ajdt.core.compiler.lint.BrokeSerialVersionCompatibility"; // General AspectJ Compiler options (excludes paths etc, these are handled separately) public static final String OPTION_NoWeave = "org.aspectj.ajdt.core.compiler.weaver.NoWeave"; public static final String OPTION_XSerializableAspects = "org.aspectj.ajdt.core.compiler.weaver.XSerializableAspects"; public static final String OPTION_XLazyThisJoinPoint = "org.aspectj.ajdt.core.compiler.weaver.XLazyThisJoinPoint"; public static final String OPTION_XNoInline = "org.aspectj.ajdt.core.compiler.weaver.XNoInline"; public static final String OPTION_XReweavable = "org.aspectj.ajdt.core.compiler.weaver.XReweavable"; public static final String OPTION_XReweavableCompress = "org.aspectj.ajdt.core.compiler.weaver.XReweavableCompress"; // these next three not exposed by IDEs public static final String OPTION_GenerateModel = "org.aspectj.ajdt.core.compiler.model.GenerateModel"; public static final String OPTION_GenerateJavaDocsInModel = "org.aspectj.ajdt.core.compiler.model.GenerateJavaDocsInModel"; public static final String OPTION_Emacssym = "org.aspectj.ajdt.core.compiler.model.Emacssym"; // constants for irritant levels public static final long InvalidAbsoluteTypeName = 0x20000000000L; public static final long InvalidWildCardTypeName = 0x40000000000L; public static final long UnresolvableMember = 0x80000000000L; public static final long TypeNotExposedToWeaver = 0x100000000000L; public static final long ShadowNotInStructure = 0x200000000000L; public static final long UnmatchedSuperTypeInCall = 0x400000000000L; public static final long CannotImplementLazyTJP = 0x800000000000L; public static final long NeedSerialVersionUIDField = 0x1000000000000L; public static final long IncompatibleSerialVersion = 0x2000000000000L; public boolean noWeave = false; public boolean xSerializableAspects = false; public boolean xLazyThisJoinPoint = false; public boolean xNoInline = false; public boolean xReweavable = false; public boolean xReweavableCompress = false; public boolean showWeavingInformation = false; // these next three not exposed by IDEs public boolean generateModel = false; public boolean generateJavaDocsInModel = false; public boolean generateEmacsSymFiles = false; /** * Initializing the compiler options with defaults */ public AjCompilerOptions(){ super(); setAspectJWarningDefaults(); } /** * Initializing the compiler options with external settings * @param settings */ public AjCompilerOptions(Map settings){ setAspectJWarningDefaults(); if (settings == null) return; set(settings); } /* (non-Javadoc) * @see org.eclipse.jdt.internal.compiler.impl.CompilerOptions#getMap() */ public Map getMap() { Map map = super.getMap(); // now add AspectJ additional options map.put(OPTION_ReportInvalidAbsoluteTypeName,getSeverityString(InvalidAbsoluteTypeName)); map.put(OPTION_ReportInvalidWildcardTypeName,getSeverityString(InvalidWildCardTypeName)); map.put(OPTION_ReportUnresolvableMember,getSeverityString(UnresolvableMember)); map.put(OPTION_ReportTypeNotExposedToWeaver,getSeverityString(TypeNotExposedToWeaver)); map.put(OPTION_ReportShadowNotInStructure,getSeverityString(ShadowNotInStructure)); map.put(OPTION_ReportUnmatchedSuperTypeInCall,getSeverityString(UnmatchedSuperTypeInCall)); map.put(OPTION_ReportCannotImplementLazyTJP,getSeverityString(CannotImplementLazyTJP)); map.put(OPTION_ReportNeedSerialVersionUIDField,getSeverityString(NeedSerialVersionUIDField)); map.put(OPTION_ReportIncompatibleSerialVersion,getSeverityString(IncompatibleSerialVersion)); map.put(OPTION_NoWeave, this.noWeave ? ENABLED : DISABLED); map.put(OPTION_XSerializableAspects,this.xSerializableAspects ? ENABLED : DISABLED); map.put(OPTION_XLazyThisJoinPoint,this.xLazyThisJoinPoint ? ENABLED : DISABLED); map.put(OPTION_XNoInline,this.xNoInline ? ENABLED : DISABLED); map.put(OPTION_XReweavable,this.xReweavable ? ENABLED : DISABLED); map.put(OPTION_XReweavableCompress,this.xReweavableCompress ? ENABLED : DISABLED); map.put(OPTION_GenerateModel,this.generateModel ? ENABLED : DISABLED); map.put(OPTION_GenerateJavaDocsInModel,this.generateJavaDocsInModel ? ENABLED : DISABLED); map.put(OPTION_Emacssym,this.generateEmacsSymFiles ? ENABLED : DISABLED); return map; } /* (non-Javadoc) * @see org.eclipse.jdt.internal.compiler.impl.CompilerOptions#set(java.util.Map) */ public void set(Map optionsMap) { super.set(optionsMap); Object optionValue; if ((optionValue = optionsMap.get(OPTION_ReportInvalidAbsoluteTypeName)) != null) updateSeverity(InvalidAbsoluteTypeName, optionValue); if ((optionValue = optionsMap.get(OPTION_ReportInvalidWildcardTypeName)) != null) updateSeverity(InvalidWildCardTypeName, optionValue); if ((optionValue = optionsMap.get(OPTION_ReportUnresolvableMember)) != null) updateSeverity(UnresolvableMember, optionValue); if ((optionValue = optionsMap.get(OPTION_ReportTypeNotExposedToWeaver)) != null) updateSeverity(TypeNotExposedToWeaver, optionValue); if ((optionValue = optionsMap.get(OPTION_ReportShadowNotInStructure)) != null) updateSeverity(ShadowNotInStructure, optionValue); if ((optionValue = optionsMap.get(OPTION_ReportUnmatchedSuperTypeInCall)) != null) updateSeverity(UnmatchedSuperTypeInCall, optionValue); if ((optionValue = optionsMap.get(OPTION_ReportCannotImplementLazyTJP)) != null) updateSeverity(CannotImplementLazyTJP, optionValue); if ((optionValue = optionsMap.get(OPTION_ReportNeedSerialVersionUIDField)) != null) updateSeverity(NeedSerialVersionUIDField, optionValue); if ((optionValue = optionsMap.get(OPTION_ReportIncompatibleSerialVersion)) != null) updateSeverity(IncompatibleSerialVersion, optionValue); if ((optionValue = optionsMap.get(OPTION_NoWeave)) != null) { if (ENABLED.equals(optionValue)) { this.noWeave = true; } else if (DISABLED.equals(optionValue)) { this.noWeave = false; } } if ((optionValue = optionsMap.get(OPTION_XSerializableAspects)) != null) { if (ENABLED.equals(optionValue)) { this.xSerializableAspects = true; } else if (DISABLED.equals(optionValue)) { this.xSerializableAspects = false; } } if ((optionValue = optionsMap.get(OPTION_XLazyThisJoinPoint)) != null) { if (ENABLED.equals(optionValue)) { this.xLazyThisJoinPoint = true; } else if (DISABLED.equals(optionValue)) { this.xLazyThisJoinPoint = false; } } if ((optionValue = optionsMap.get(OPTION_XNoInline)) != null) { if (ENABLED.equals(optionValue)) { this.xNoInline = true; } else if (DISABLED.equals(optionValue)) { this.xNoInline = false; } } if ((optionValue = optionsMap.get(OPTION_XReweavable)) != null) { if (ENABLED.equals(optionValue)) { this.xReweavable = true; } else if (DISABLED.equals(optionValue)) { this.xReweavable = false; } } if ((optionValue = optionsMap.get(OPTION_XReweavableCompress)) != null) { if (ENABLED.equals(optionValue)) { this.xReweavableCompress = true; } else if (DISABLED.equals(optionValue)) { this.xReweavableCompress = false; } } if ((optionValue = optionsMap.get(OPTION_GenerateModel)) != null) { if (ENABLED.equals(optionValue)) { this.generateModel = true; } else if (DISABLED.equals(optionValue)) { this.generateModel = false; } } if ((optionValue = optionsMap.get(OPTION_GenerateJavaDocsInModel)) != null) { if (ENABLED.equals(optionValue)) { this.generateJavaDocsInModel = true; } else if (DISABLED.equals(optionValue)) { this.generateJavaDocsInModel = false; } } if ((optionValue = optionsMap.get(OPTION_Emacssym)) != null) { if (ENABLED.equals(optionValue)) { this.generateEmacsSymFiles = true; } else if (DISABLED.equals(optionValue)) { this.generateEmacsSymFiles = false; } } } /** * Add these warnings to the default set... */ private void setAspectJWarningDefaults() { super.warningThreshold = super.warningThreshold | InvalidAbsoluteTypeName | UnresolvableMember | TypeNotExposedToWeaver | UnmatchedSuperTypeInCall | CannotImplementLazyTJP; } /* (non-Javadoc) * @see java.lang.Object#toString() */ public String toString() { StringBuffer buf = new StringBuffer( super.toString() ); // now add AspectJ additional options buf.append("\n\tAspectJ Specific Options:"); buf.append("\n\t- no weave: ").append(this.noWeave ? ENABLED : DISABLED); //$NON-NLS-1$ buf.append("\n\t- no inline (X option): ").append(this.xNoInline ? ENABLED : DISABLED); //$NON-NLS-1$ buf.append("\n\t- generate serializable aspects (X option): ").append(this.xSerializableAspects ? ENABLED : DISABLED); //$NON-NLS-1$ buf.append("\n\t- lazy thisJoinPoint (X option): ").append(this.xLazyThisJoinPoint ? ENABLED : DISABLED); //$NON-NLS-1$ buf.append("\n\t- generate reweavable class files (X option): ").append(this.xReweavable ? ENABLED : DISABLED); //$NON-NLS-1$ buf.append("\n\t- compress reweavable class files (X option): ").append(this.xReweavableCompress ? ENABLED : DISABLED); //$NON-NLS-1$ buf.append("\n\t- generate AJDE model: ").append(this.generateModel ? ENABLED : DISABLED); //$NON-NLS-1$ buf.append("\n\t- generate Javadocs in AJDE model: ").append(this.generateJavaDocsInModel ? ENABLED : DISABLED); //$NON-NLS-1$ buf.append("\n\t- generate Emacs symbol files: ").append(this.generateEmacsSymFiles ? ENABLED : DISABLED); //$NON-NLS-1$ buf.append("\n\t- invalid absolute type name (XLint): ").append(getSeverityString(InvalidAbsoluteTypeName)); //$NON-NLS-1$ buf.append("\n\t- invalid wildcard type name (XLint): ").append(getSeverityString(InvalidWildCardTypeName)); //$NON-NLS-1$ buf.append("\n\t- unresolvable member (XLint): ").append(getSeverityString(UnresolvableMember)); //$NON-NLS-1$ buf.append("\n\t- type not exposed to weaver (XLint): ").append(getSeverityString(TypeNotExposedToWeaver)); //$NON-NLS-1$ buf.append("\n\t- shadow not in structure (XLint): ").append(getSeverityString(ShadowNotInStructure)); //$NON-NLS-1$ buf.append("\n\t- unmatched super type in call (XLint): ").append(getSeverityString(UnmatchedSuperTypeInCall)); //$NON-NLS-1$ buf.append("\n\t- cannot implement lazy thisJoinPoint (XLint): ").append(getSeverityString(CannotImplementLazyTJP)); //$NON-NLS-1$ buf.append("\n\t- need serialVersionUID field (XLint): ").append(getSeverityString(NeedSerialVersionUIDField)); //$NON-NLS-1$ buf.append("\n\t- incompatible serial version (XLint): ").append(getSeverityString(IncompatibleSerialVersion)); //$NON-NLS-1$ return buf.toString(); } }
75,568
Bug 75568 ajc changes classfile timestamps even if compilation fails (regression)
It appears that ajc 1.2 updates a classfile timestamps even if the compilation fails. This breaks the integration with the Ant build system. E.g. using the ant "javac" task with the Ajc11CompilerAdapter interface, the compilation may fail on the first attempt and succeed on the second attempt, - because ajc has touched the timestamp and Ant hence decides that nothing needs to be recompiled. This did not happen in ajc 1.1. To reproduce: 1. In the examples/observer folder, run a build: ajc -sourceroots . 2. Edit the "Demo.java" class and insert the line "DONT COMPILE" 3. Run the compilation again. The compiler displays the correct error message but the Demo.class file has been updated with the compile-time timestamp.
resolved fixed
0a77939
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2004-10-14T12:51:18Z
2004-10-04T14:26:40Z
org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/core/builder/AspectJBuilder.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.core.builder; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.Locale; import java.util.Map; import java.util.Properties; import org.aspectj.ajdt.core.AspectJCore; 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.AjLookupEnvironment; import org.aspectj.ajdt.internal.compiler.lookup.EclipseFactory; import org.aspectj.ajdt.internal.compiler.problem.AjProblemReporter; import org.aspectj.bridge.AbortException; import org.aspectj.bridge.IMessage; import org.aspectj.bridge.IMessageHandler; import org.aspectj.bridge.IMessage.Kind; import org.aspectj.weaver.Lint; import org.aspectj.weaver.bcel.BcelWeaver; import org.aspectj.weaver.bcel.BcelWorld; import org.eclipse.core.resources.IMarker; import org.eclipse.core.resources.IProject; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.Path; import org.aspectj.org.eclipse.jdt.core.IJavaModelMarker; import org.aspectj.org.eclipse.jdt.core.JavaCore; import org.aspectj.org.eclipse.jdt.core.JavaModelException; import org.aspectj.org.eclipse.jdt.internal.compiler.CompilationResult; import org.aspectj.org.eclipse.jdt.internal.compiler.Compiler; import org.aspectj.org.eclipse.jdt.internal.compiler.DefaultErrorHandlingPolicies; import org.aspectj.org.eclipse.jdt.internal.compiler.ICompilerAdapter; import org.aspectj.org.eclipse.jdt.internal.compiler.ICompilerAdapterFactory; import org.aspectj.org.eclipse.jdt.internal.compiler.problem.DefaultProblemFactory; import org.aspectj.org.eclipse.jdt.internal.core.builder.BatchImageBuilder; import org.aspectj.org.eclipse.jdt.internal.core.builder.BuildNotifier; import org.aspectj.org.eclipse.jdt.internal.core.builder.IncrementalImageBuilder; import org.aspectj.org.eclipse.jdt.internal.core.builder.JavaBuilder; /** * @author colyer * * This is the builder class used by AJDT, and that the org.eclipse.ajdt.core * plugin references. */ public class AspectJBuilder extends JavaBuilder implements ICompilerAdapterFactory { // One builder instance per project (important) private BcelWeaver myWeaver = null; private BcelWorld myBcelWorld = null; private EclipseClassPathManager cpManager = null; private UnwovenResultCollector unwovenResultCollector = null; private OutputFileNameProvider fileNameProvider = null; private boolean isBatchBuild = false; /* (non-Javadoc) * @see org.eclipse.core.internal.events.InternalBuilder#build(int, java.util.Map, org.eclipse.core.runtime.IProgressMonitor) */ protected IProject[] build(int kind, Map ignored, IProgressMonitor monitor) throws CoreException { // super method always causes construction of a new XXXImageBuilder, which // causes construction of a new Compiler, so we will be detected as the // adapter. Compiler.setCompilerAdapterFactory(this); return super.build(kind, ignored, monitor); } protected BatchImageBuilder getBatchImageBuilder() { isBatchBuild = true; return new AjBatchImageBuilder(this); } protected IncrementalImageBuilder getIncrementalImageBuilder() { isBatchBuild = false; return new AjIncrementalImageBuilder(this); } /* (non-Javadoc) * @see org.eclipse.jdt.internal.compiler.ICompilerAdapterFactory#getAdapter(org.eclipse.jdt.internal.compiler.Compiler) */ public ICompilerAdapter getAdapter(Compiler forCompiler) { Map javaOptions = forCompiler.options.getMap(); // TODO get aspectj options from project and add into map before... AjCompilerOptions ajOptions = new AjCompilerOptions(javaOptions); forCompiler.options = ajOptions; if (isBatchBuild || myBcelWorld == null || myWeaver == null) { initWorldAndWeaver(ajOptions); } else { // update the nameEnvironment each time we compile... cpManager.setNameEnvironment(nameEnvironment); } // * an eclipse factory -- create from AjLookupEnvironment, need to hide AjBuildManager field AjProblemReporter pr = new AjProblemReporter(DefaultErrorHandlingPolicies.proceedWithAllProblems(), forCompiler.options, new DefaultProblemFactory(Locale.getDefault())); forCompiler.problemReporter = pr; AjLookupEnvironment le = new AjLookupEnvironment(forCompiler, forCompiler.options, pr,nameEnvironment); EclipseFactory eFactory = new EclipseFactory(le,myBcelWorld,ajOptions.xSerializableAspects); le.factory = eFactory; forCompiler.lookupEnvironment = le; AjBuildNotifier ajNotifier = (AjBuildNotifier) notifier; if (fileNameProvider == null ) fileNameProvider = new OutputFileNameProvider(getProject()); // * the set of binary source entries for this compile -- from analyzing deltas, or everything if batch // * the full set of binary source entries for the project -- from IAspectJProject // TODO deal with inpath, injars here... IBinarySourceProvider bsProvider = new NullBinarySourceProvider(); Map fullBinarySourceEntries = new HashMap(); // * the intermediate result set from the last batch compile if (isBatchBuild) { unwovenResultCollector = new UnwovenResultCollector(); } Collection resultSetForFullWeave = unwovenResultCollector.getIntermediateResults(); return new AjCompilerAdapter(forCompiler,isBatchBuild,myBcelWorld, myWeaver,eFactory,unwovenResultCollector,ajNotifier,fileNameProvider,bsProvider, fullBinarySourceEntries,resultSetForFullWeave, ajOptions.noWeave); } /* (non-Javadoc) * @see org.eclipse.jdt.internal.core.builder.JavaBuilder#createBuildNotifier(org.eclipse.core.runtime.IProgressMonitor, org.eclipse.core.resources.IProject) */ protected BuildNotifier createBuildNotifier(IProgressMonitor monitor, IProject currentProject) { return new AjBuildNotifier(monitor, currentProject); } private void initWorldAndWeaver(AjCompilerOptions options) { cpManager = new EclipseClassPathManager(nameEnvironment); myBcelWorld = new BcelWorld(cpManager,new UnhandledMessageHandler(getProject()),null /*(xrefHandler)*/); myBcelWorld.setXnoInline(options.xNoInline); myBcelWorld.setXlazyTjp(options.xLazyThisJoinPoint); setLintProperties(myBcelWorld,options); myWeaver = new BcelWeaver(myBcelWorld); myWeaver.setReweavableMode(options.xReweavable,options.xReweavableCompress); // TODO deal with injars, inpath, and aspectpath here... } private void setLintProperties(BcelWorld world, AjCompilerOptions options) { Properties p = new Properties(); Lint lintSettings = world.getLint(); Map map = options.getMap(); p.put(lintSettings.invalidAbsoluteTypeName.getName(),map.get(AjCompilerOptions.OPTION_ReportInvalidAbsoluteTypeName)); p.put(lintSettings.invalidWildcardTypeName.getName(),map.get(AjCompilerOptions.OPTION_ReportInvalidWildcardTypeName)); p.put(lintSettings.unresolvableMember.getName(),map.get(AjCompilerOptions.OPTION_ReportUnresolvableMember)); p.put(lintSettings.typeNotExposedToWeaver.getName(),map.get(AjCompilerOptions.OPTION_ReportTypeNotExposedToWeaver)); p.put(lintSettings.shadowNotInStructure.getName(),map.get(AjCompilerOptions.OPTION_ReportShadowNotInStructure)); p.put(lintSettings.unmatchedSuperTypeInCall.getName(),map.get(AjCompilerOptions.OPTION_ReportUnmatchedSuperTypeInCall)); p.put(lintSettings.canNotImplementLazyTjp.getName(),map.get(AjCompilerOptions.OPTION_ReportCannotImplementLazyTJP)); p.put(lintSettings.needsSerialVersionUIDField.getName(),map.get(AjCompilerOptions.OPTION_ReportNeedSerialVersionUIDField)); p.put(lintSettings.serialVersionUIDBroken.getName(),map.get(AjCompilerOptions.OPTION_ReportIncompatibleSerialVersion)); lintSettings.setFromProperties(p); } private static class UnwovenResultCollector implements IIntermediateResultsRequestor { private Collection results = new ArrayList(); /* (non-Javadoc) * @see org.aspectj.ajdt.internal.compiler.IIntermediateResultsRequestor#acceptResult(org.aspectj.ajdt.internal.compiler.InterimCompilationResult) */ public void acceptResult(InterimCompilationResult intRes) { results.add(intRes); } public Collection getIntermediateResults() { return results; } } // this class will only get messages that the weaver adapter couldn't tie into // an originating resource in the project - make them messages on the project // itself. private static class UnhandledMessageHandler implements IMessageHandler { private IProject project; public UnhandledMessageHandler(IProject p) { this.project = p; } /* (non-Javadoc) * @see org.aspectj.bridge.IMessageHandler#handleMessage(org.aspectj.bridge.IMessage) */ public boolean handleMessage(IMessage message) throws AbortException { try { IMarker marker = project.createMarker(IJavaModelMarker.JAVA_MODEL_PROBLEM_MARKER); marker.setAttribute(IMarker.MESSAGE, message.getMessage()); marker.setAttribute(IMarker.SEVERITY, message.isError() ? IMarker.SEVERITY_ERROR : IMarker.SEVERITY_WARNING); } catch (CoreException e) { AspectJCore.getPlugin().getLog().log(e.getStatus()); } return true; } /* (non-Javadoc) * @see org.aspectj.bridge.IMessageHandler#isIgnoring(org.aspectj.bridge.IMessage.Kind) */ public boolean isIgnoring(Kind kind) { if (kind == IMessage.DEBUG || kind == IMessage.INFO) return true; return false; } } private static class OutputFileNameProvider implements IOutputClassFileNameProvider { private IPath outputLocation; public OutputFileNameProvider(IProject p) { try { outputLocation = JavaCore.create(p).getOutputLocation(); } catch (JavaModelException e) { outputLocation = new Path("."); AspectJCore.getPlugin().getLog().log(e.getStatus()); } } /* (non-Javadoc) * @see org.aspectj.ajdt.internal.compiler.IOutputClassFileNameProvider#getOutputClassFileName(char[], org.eclipse.jdt.internal.compiler.CompilationResult) */ public String getOutputClassFileName(char[] eclipseClassFileName, CompilationResult result) { // In the AJDT implementation, the name provided here will be ignored, we write the results // out in xxxImageBuilder.acceptResult() instead. // simply return the default output directory for the project. String filename = new String(eclipseClassFileName); IPath out = outputLocation.append(filename); out.addFileExtension(".class"); return out.toOSString(); } } // default impl class until the implementation is extended to cope with inpath, injars private static class NullBinarySourceProvider implements IBinarySourceProvider { /* (non-Javadoc) * @see org.aspectj.ajdt.internal.compiler.IBinarySourceProvider#getBinarySourcesForThisWeave() */ public Map getBinarySourcesForThisWeave() { return new HashMap(); } } }
75,568
Bug 75568 ajc changes classfile timestamps even if compilation fails (regression)
It appears that ajc 1.2 updates a classfile timestamps even if the compilation fails. This breaks the integration with the Ant build system. E.g. using the ant "javac" task with the Ajc11CompilerAdapter interface, the compilation may fail on the first attempt and succeed on the second attempt, - because ajc has touched the timestamp and Ant hence decides that nothing needs to be recompiled. This did not happen in ajc 1.1. To reproduce: 1. In the examples/observer folder, run a build: ajc -sourceroots . 2. Edit the "Demo.java" class and insert the line "DONT COMPILE" 3. Run the compilation again. The compiler displays the correct error message but the Demo.class file has been updated with the compile-time timestamp.
resolved fixed
0a77939
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2004-10-14T12:51:18Z
2004-10-04T14:26:40Z
org.aspectj.ajdt.core/testdata/src1/C1.java
75,568
Bug 75568 ajc changes classfile timestamps even if compilation fails (regression)
It appears that ajc 1.2 updates a classfile timestamps even if the compilation fails. This breaks the integration with the Ant build system. E.g. using the ant "javac" task with the Ajc11CompilerAdapter interface, the compilation may fail on the first attempt and succeed on the second attempt, - because ajc has touched the timestamp and Ant hence decides that nothing needs to be recompiled. This did not happen in ajc 1.1. To reproduce: 1. In the examples/observer folder, run a build: ajc -sourceroots . 2. Edit the "Demo.java" class and insert the line "DONT COMPILE" 3. Run the compilation again. The compiler displays the correct error message but the Demo.class file has been updated with the compile-time timestamp.
resolved fixed
0a77939
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2004-10-14T12:51:18Z
2004-10-04T14:26:40Z
org.aspectj.ajdt.core/testdata/src1/C2.java
75,568
Bug 75568 ajc changes classfile timestamps even if compilation fails (regression)
It appears that ajc 1.2 updates a classfile timestamps even if the compilation fails. This breaks the integration with the Ant build system. E.g. using the ant "javac" task with the Ajc11CompilerAdapter interface, the compilation may fail on the first attempt and succeed on the second attempt, - because ajc has touched the timestamp and Ant hence decides that nothing needs to be recompiled. This did not happen in ajc 1.1. To reproduce: 1. In the examples/observer folder, run a build: ajc -sourceroots . 2. Edit the "Demo.java" class and insert the line "DONT COMPILE" 3. Run the compilation again. The compiler displays the correct error message but the Demo.class file has been updated with the compile-time timestamp.
resolved fixed
0a77939
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2004-10-14T12:51:18Z
2004-10-04T14:26:40Z
org.aspectj.ajdt.core/testsrc/org/aspectj/ajdt/internal/compiler/batch/AjdtBatchTests.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.compiler.batch; import junit.framework.*; public class AjdtBatchTests extends TestCase { public static Test suite() { TestSuite suite = new TestSuite(AjdtBatchTests.class.getName()); // Abstract superclass //suite.addTestSuite(CommandTestCase.class); //$JUnit-BEGIN$ suite.addTestSuite(BasicCommandTestCase.class); suite.addTestSuite(BinaryFormsTestCase.class); suite.addTestSuite(CompileAndRunTestCase.class); suite.addTestSuite(PerformanceTestCase.class); suite.addTestSuite(ImageTestCase.class); suite.addTestSuite(MultipleCompileTestCase.class); suite.addTestSuite(JavadocTest.class); suite.addTestSuite(PartiallyExposedHierarchyTestCase.class); suite.addTestSuite(CompilerDumpTestCase.class); // XXX suite.addTestSuite(VerifyWeaveTestCase.class); //suite.addTestSuite(WorkingCommandTestCase.class); //$JUnit-END$ return suite; } public AjdtBatchTests(String name) { super(name); } }
75,568
Bug 75568 ajc changes classfile timestamps even if compilation fails (regression)
It appears that ajc 1.2 updates a classfile timestamps even if the compilation fails. This breaks the integration with the Ant build system. E.g. using the ant "javac" task with the Ajc11CompilerAdapter interface, the compilation may fail on the first attempt and succeed on the second attempt, - because ajc has touched the timestamp and Ant hence decides that nothing needs to be recompiled. This did not happen in ajc 1.1. To reproduce: 1. In the examples/observer folder, run a build: ajc -sourceroots . 2. Edit the "Demo.java" class and insert the line "DONT COMPILE" 3. Run the compilation again. The compiler displays the correct error message but the Demo.class file has been updated with the compile-time timestamp.
resolved fixed
0a77939
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2004-10-14T12:51:18Z
2004-10-04T14:26:40Z
org.aspectj.ajdt.core/testsrc/org/aspectj/ajdt/internal/compiler/batch/ProceedOnErrorTestCase.java
76,096
Bug 76096 Anonymous classes unaware of introductions into abstract classes (error can't find type $Local$)
null
resolved fixed
6beb43f
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2004-10-19T10:37:31Z
2004-10-12T16:53:20Z
org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/compiler/problem/AjProblemReporter.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the 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.problem; import java.lang.reflect.Modifier; import java.util.Iterator; import org.aspectj.ajdt.internal.compiler.ast.AdviceDeclaration; import org.aspectj.ajdt.internal.compiler.ast.PointcutDeclaration; import org.aspectj.ajdt.internal.compiler.ast.Proceed; import org.aspectj.ajdt.internal.compiler.lookup.EclipseFactory; import org.aspectj.util.FuzzyBoolean; import org.aspectj.weaver.AjcMemberMaker; import org.aspectj.weaver.ConcreteTypeMunger; import org.aspectj.weaver.ResolvedMember; import org.aspectj.weaver.ResolvedTypeX; import org.aspectj.weaver.Shadow; import org.aspectj.weaver.patterns.DeclareSoft; import org.aspectj.org.eclipse.jdt.internal.compiler.CompilationResult; import org.aspectj.org.eclipse.jdt.internal.compiler.IErrorHandlingPolicy; import org.aspectj.org.eclipse.jdt.internal.compiler.IProblemFactory; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.ASTNode; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.Argument; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.ExplicitConstructorCall; import org.aspectj.org.eclipse.jdt.internal.compiler.impl.CompilerOptions; import org.aspectj.org.eclipse.jdt.internal.compiler.impl.ReferenceContext; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.MethodBinding; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.MethodScope; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.ReferenceBinding; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.SourceTypeBinding; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.TypeBinding; import org.aspectj.org.eclipse.jdt.internal.compiler.problem.ProblemReporter; import org.aspectj.org.eclipse.jdt.core.compiler.CharOperation; import org.aspectj.org.eclipse.jdt.core.compiler.IProblem; /** * Extends problem reporter to support compiler-side implementation of declare soft. * Also overrides error reporting for the need to implement abstract methods to * account for inter-type declarations and pointcut declarations. This second * job might be better done directly in the SourceTypeBinding/ClassScope classes. * * @author Jim Hugunin */ public class AjProblemReporter extends ProblemReporter { private static final boolean DUMP_STACK = false; public EclipseFactory factory; public AjProblemReporter( IErrorHandlingPolicy policy, CompilerOptions options, IProblemFactory problemFactory) { super(policy, options, problemFactory); } public void unhandledException( TypeBinding exceptionType, ASTNode location) { if (!factory.getWorld().getDeclareSoft().isEmpty()) { Shadow callSite = factory.makeShadow(location, referenceContext); Shadow enclosingExec = factory.makeShadow(referenceContext); // PR 72157 - calls to super / this within a constructor are not part of the cons join point. if ((callSite == null) && (enclosingExec.getKind() == Shadow.ConstructorExecution) && (location instanceof ExplicitConstructorCall)) { super.unhandledException(exceptionType, location); return; } // System.err.println("about to show error for unhandled exception: " + new String(exceptionType.sourceName()) + // " at " + location + " in " + referenceContext); for (Iterator i = factory.getWorld().getDeclareSoft().iterator(); i.hasNext(); ) { DeclareSoft d = (DeclareSoft)i.next(); // We need the exceptionType to match the type in the declare soft statement // This means it must either be the same type or a subtype ResolvedTypeX throwException = factory.fromEclipse((ReferenceBinding)exceptionType); FuzzyBoolean isExceptionTypeOrSubtype = d.getException().matchesInstanceof(throwException); if (!isExceptionTypeOrSubtype.alwaysTrue() ) continue; if (callSite != null) { FuzzyBoolean match = d.getPointcut().match(callSite); if (match.alwaysTrue()) { //System.err.println("matched callSite: " + callSite + " with " + d); return; } else if (!match.alwaysFalse()) { //!!! need this check to happen much sooner //throw new RuntimeException("unimplemented, shouldn't have fuzzy match here"); } } if (enclosingExec != null) { FuzzyBoolean match = d.getPointcut().match(enclosingExec); if (match.alwaysTrue()) { //System.err.println("matched enclosingExec: " + enclosingExec + " with " + d); return; } else if (!match.alwaysFalse()) { //!!! need this check to happen much sooner //throw new RuntimeException("unimplemented, shouldn't have fuzzy match here"); } } } } //??? is this always correct if (location instanceof Proceed) { return; } super.unhandledException(exceptionType, location); } private boolean isPointcutDeclaration(MethodBinding binding) { return CharOperation.prefixEquals(PointcutDeclaration.mangledPrefix, binding.selector); } public void abstractMethodCannotBeOverridden( SourceTypeBinding type, MethodBinding concreteMethod) { if (isPointcutDeclaration(concreteMethod)) { return; } super.abstractMethodCannotBeOverridden(type, concreteMethod); } public void abstractMethodMustBeImplemented( SourceTypeBinding type, MethodBinding abstractMethod) { // if this is a PointcutDeclaration then there is no error if (isPointcutDeclaration(abstractMethod)) { return; } if (CharOperation.prefixEquals("ajc$interField".toCharArray(), abstractMethod.selector)) { //??? think through how this could go wrong return; } // if we implemented this method by an inter-type declaration, then there is no error //??? be sure this is always right ResolvedTypeX onTypeX = factory.fromEclipse(type); //abstractMethod.declaringClass); for (Iterator i = onTypeX.getInterTypeMungersIncludingSupers().iterator(); i.hasNext(); ) { ConcreteTypeMunger m = (ConcreteTypeMunger)i.next(); ResolvedMember sig = m.getSignature(); if (!Modifier.isAbstract(sig.getModifiers())) { if (ResolvedTypeX .matches( AjcMemberMaker.interMethod( sig, m.getAspectType(), sig.getDeclaringType().isInterface( factory.getWorld())), EclipseFactory.makeResolvedMember(abstractMethod))) { return; } } } super.abstractMethodMustBeImplemented(type, abstractMethod); } public void handle( int problemId, String[] problemArguments, String[] messageArguments, int severity, int problemStartPosition, int problemEndPosition, ReferenceContext referenceContext, CompilationResult unitResult) { if (severity != Ignore && DUMP_STACK) { Thread.dumpStack(); } super.handle( problemId, problemArguments, messageArguments, severity, problemStartPosition, problemEndPosition, referenceContext, unitResult); } // PR71076 public void javadocMissingParamTag(Argument arg, int modifiers) { boolean reportIt = true; if (arg.binding!=null && (arg.binding.declaringScope instanceof MethodScope) ) { MethodScope ms = (MethodScope) arg.binding.declaringScope; if (ms.referenceContext!=null && (ms.referenceContext instanceof AdviceDeclaration)) { AdviceDeclaration adviceDecl = (AdviceDeclaration)ms.referenceContext; if (arg.name!=null) { if (adviceDecl.selector.length>4 && adviceDecl.selector[0] == 'a' && adviceDecl.selector[1] == 'j' && adviceDecl.selector[2] == 'c' && adviceDecl.selector[3] == '$') { String stringArgName = new String(arg.name); if (stringArgName.equals("thisJoinPoint")) reportIt = false; if (stringArgName.equals("thisJoinPointStaticPart")) reportIt = false; if (stringArgName.equals("thisEnclosingJoinPointStaticPart")) reportIt = false; if (arg.type.toString().indexOf("AroundClosure")!=-1) reportIt = false; } } } } if (arg.name!=null && new String(arg.name).startsWith("ajc$")) reportIt = false; if (reportIt) super.javadocMissingParamTag(arg, modifiers); } public void abstractMethodInAbstractClass(SourceTypeBinding type, AbstractMethodDeclaration methodDecl) { String abstractMethodName = new String(methodDecl.selector); if (abstractMethodName.startsWith("ajc$pointcut")) { // This will already have been reported, see: PointcutDeclaration.postParse() return; } String[] arguments = new String[] {new String(type.sourceName()), abstractMethodName}; super.handle( IProblem.AbstractMethodInAbstractClass, arguments, arguments, methodDecl.sourceStart, methodDecl.sourceEnd,this.referenceContext, this.referenceContext == null ? null : this.referenceContext.compilationResult()); } }
76,096
Bug 76096 Anonymous classes unaware of introductions into abstract classes (error can't find type $Local$)
null
resolved fixed
6beb43f
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2004-10-19T10:37:31Z
2004-10-12T16:53:20Z
tests/bugs/pr76096/ConcreteClassA.java
76,096
Bug 76096 Anonymous classes unaware of introductions into abstract classes (error can't find type $Local$)
null
resolved fixed
6beb43f
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2004-10-19T10:37:31Z
2004-10-12T16:53:20Z
tests/src/org/aspectj/systemtest/ajc121/Ajc121Tests.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 * * ******************************************************************/ package org.aspectj.systemtest.ajc121; import java.io.File; import java.util.Iterator; import java.util.List; import junit.framework.Test; import org.aspectj.bridge.WeaveMessage; import org.aspectj.testing.XMLBasedAjcTestCase; public class Ajc121Tests extends org.aspectj.testing.XMLBasedAjcTestCase { public static Test suite() { return XMLBasedAjcTestCase.loadSuite(Ajc121Tests.class); } protected File getSpecFile() { return new File("../tests/src/org/aspectj/systemtest/ajc121/ajc121.xml"); } public void test001(){ runTest("false ambiguous binding error (introduced in 1.2rc2)"); } public void test002(){ runTest("An if() pointcut inside a perthis() clauses an ABORT - null pointer exception in ajc"); } public void test003(){ runTest("An if() pointcut inside a perthis() clauses an ABORT - null pointer exception in ajc"); } public void test004(){ runTest("An if() pointcut inside a perthis() clauses an ABORT - null pointer exception in ajc"); } public void test005(){ runTest("compiler aborts with 'conflicting dominates orders' with circular declare precedences"); } public void test006(){ runTest("'can't bind type' message has $ for . in type name for declare soft"); } public void test007(){ runTest("Hiding of Instance Methods by static methods"); } public void test008(){ runTest("if(false) optimisation"); } public void test009(){ runTest("if(true) optimisation"); } public void test010(){ runTest("java.lang.NullPointerException in WeaverMessageHandler class"); } public void test011(){ runTest("ClassCastException at BcelRenderer.java:169"); } public void test012(){ runTest("Front-end bug, shouldn't allow patterns of the form foo.., should be foo..*"); } public void test013() { runTest("Nullpointer-Exception when defining a withincode() pointcut"); } public void test014() { runTest("NPE, Incorrect XLint:unmatchedSuperTypeInCall warning"); } public void test015_invalidXlint() { // keywords: "laurie hendren" runTest("invalid warning indicating no match when a match really occurs"); } public void test016_ByteConversionInstructions() { runTest("RuntimeException thrown: Could not find instruction: org.apache.bcel.generic.B2I"); String output = getLastRunResult().getStdErr(); assertTrue("Expected to find [b2] in this output but didn't:"+output,output.indexOf("[b2]")!=-1); assertTrue("Expected to find [b127] in this output but didn't:"+output,output.indexOf("[b127]")!=-1); assertTrue("Expected to find [b0] in this output but didn't:"+output,output.indexOf("[b0]")!=-1); assertTrue("Expected to find [c65] in this output but didn't:"+output,output.indexOf("[c65]")!=-1); assertTrue("Expected to find [c66] in this output but didn't:"+output,output.indexOf("[c66]")!=-1); assertTrue("Expected to find [c67] in this output but didn't:"+output,output.indexOf("[c67]")!=-1); assertTrue("Expected to find [s1] in this output but didn't:"+output,output.indexOf("[s1]")!=-1); assertTrue("Expected to find [s32767] in this output but didn't:"+output,output.indexOf("[s32767]")!=-1); assertTrue("Expected to find [b0] in this output but didn't:"+output,output.indexOf("[b0]")!=-1); } public void test017_PrivateMethodCallsInAroundAdvice() { runTest("Cannot advise private method call in around advice"); System.err.println(getLastRunResult().getStdErr()); } public void test018_PrivateFieldSetsInAroundAdvice() { runTest("Cannot advise private field sets in around advice"); System.err.println(getLastRunResult().getStdErr()); } public void test019_PrivateFieldGetsInAroundAdvice() { runTest("Cannot advise private field gets in around advice"); System.err.println(getLastRunResult().getStdErr()); } // test takes over 5 minutes to run, so not included in normal suite run // public void test020_branchTargetOffsetTooLargeForShort() { // runTest("Branch target offset too large for short"); // } // public void test021_BcelFailureWithVeryLargeClasses() { // runTest("Weaver fails in BCEL for large classes"); // } // // public void test022_BcelFailureWithVeryLargeClasses_Binary() { // runTest("Weaver fails in BCEL for large classes (binary)"); // } public void test023_proceedInAround1() { runTest("proceed used as method name in around advice (1)"); } public void test024_proceedInAround2() { runTest("proceed used as method name in around advice (2)"); } public void test025_proceedInAround3() { runTest("proceed used as method name in around advice (3)"); } public void test026_bindingThisAndTargetToTheSameFormal() { runTest("ajc crashes when compiling the following program (binding this() and target())"); } public void test027_itdsOnInnerClassesAsStatic() { runTest("ITDs on inner classes should be static context"); } public void test028_itdsAndInitializers() { runTest("resolution of IT field inits"); } public void test029_falseInvalidAbsoluteTypeName() { runTest("Valid but inaccessible type names should not be flagged by XLint:invalidAbsoluteTypeName"); } public void test030_privateITDinitialisersBeingMatched() { runTest("intertype initialisers should match field set pointcuts"); } public void test031_privateITDinitialisersBeingMatched_OxfordTest() { runTest("intertype initialisers should match field set pointcuts (oxford testcase)"); //System.err.println(">"+getLastRunResult().getStdErr()); String exp = ":set field set(int C.n):set field set(int C.m):get field get(int C.n):set field set(int C.n)"; assertTrue("Expected output '"+exp+"' but got "+getLastRunResult().getStdErr(), getLastRunResult().getStdErr().equals(exp)); } public void test032_stringConcatForDEOW() { runTest("Compile time declarations (warning and error) do not accept string concatenation (with +)"); } public void test033_stringConcatForDEOWErrorCase() { runTest("Compile time declarations (warning and error) do not accept string concatenation (with +) (2)"); } public void test034_scopeForITDS_pr61768() { runTest("scope for inter-type methods"); } public void test035_innerAspectCallsPrivateMethod_pr71372() { runTest("NoSuchMethodError calling private method from around advice in inner aspect"); String s = getLastRunResult().getStdErr(); assertTrue("Expected ':before:around' but got "+s, s.equals(":before:around")); } public void test036_innerAspectCallsPrivateMethod_pr71372_2() { runTest("NoSuchMethodError calling private method from around advice in inner aspect (2)"); String s = getLastRunResult().getStdErr(); assertTrue("Expected ':before:around' but got "+s, s.equals(":before:around")); } public void test037_innerAspectCallsPrivateMethod_pr71372_3() { runTest("NoSuchMethodError calling private method from around advice in inner aspect (3)"); String s = getLastRunResult().getStdErr(); assertTrue("Expected ':before:around' but got "+s, s.equals(":before:around")); } public void test038_innerAspectCallsPrivateMethod_pr71372_4() { runTest("NoSuchMethodError calling private method from around advice in inner aspect (4)"); String s = getLastRunResult().getStdErr(); assertTrue("Expected ':before:around' but got "+s, s.equals(":before:around")); } public void test039_privilegedAspectAccessingPrivateMethods_pr67579() { runTest("NPE on privileged aspect error"); } public void test040_privilegedAspectAccessingPrivateMethods_pr67579_2() { runTest("NPE on privileged aspect error (2)"); } public void test041_ITDaccessingPrivateMethod_pr67578() { runTest("Privileged Aspect Access Problem Across Packages"); } public void test042_ITDaccessingPrivateMethod_pr67578_2() { runTest("Privileged Aspect Access Problem Across Packages (2)"); } public void test043_pr62642_ExceptionInInitializerError() { runTest("proper handling of ExceptionInIntializer inside clinit in presence of after throwing advice"); String s = getLastRunResult().getStdErr(); assertTrue("Output should contain java.lang.ExceptionInInitializerError but is '"+s+"'", s.indexOf("java.lang.ExceptionInInitializerError")!=-1); // No getCause on 1.3 JVMs // assertTrue("Output should contain 'CAUSE=org.aspectj.lang.NoAspectBoundException' but is '"+s+"'", // s.indexOf("CAUSE=org.aspectj.lang.NoAspectBoundException")!=-1); } public void test044_ITDnameClashes() { runTest("ITD name clashes with private members"); } public void test045_ITDprotectedVisibility() { runTest("Inconsistency in scoping of protected members in ITDs"); } public void test045_wrongLineForExecutionJoinPoint() { runTest("wrong line for method execution join point"); } public void test046_interfaceITD_pr70794_1() { runTest("The introduction on interface causes the interface implementation class error (1)"); } public void test047_interfaceITD_pr70794_2() { runTest("The introduction on interface causes the interface implementation class error (2)"); } public void test048_interfaceITD_pr70794_3() { runTest("The introduction on interface causes the interface implementation class error (3)"); } public void test049_interfaceITD_pr70794_4() { runTest("The introduction on interface causes the interface implementation class error (4)"); } public void test050_typePatternMatchingWithArrays() { runTest("declare warning warns at wrong points"); } public void test051_arrayCloningInJava5() { runTest("AJC possible bug with static nested classes"); List l = ajc.getLastCompilationResult().getInfoMessages(); assertTrue("Should at least have had one weaving message",l!=null && l.size()>0); boolean gotWeaveMessage = false; for (Iterator msg = l.iterator(); msg.hasNext();) { Object element = (Object) msg.next(); if (element instanceof WeaveMessage) { WeaveMessage wm = (WeaveMessage)element; if (wm.getMessage().indexOf("advised by around advice from")!=-1) gotWeaveMessage = true; } } assertTrue("Expected a weaving message but only found "+l,gotWeaveMessage); } public void test052_bogusMessage1() { runTest("Bogus error message: The abstract method ajc$pointcut$$tracingScope$a2 in type Tracing can only be defined by an abstract class (1)"); } public void test053_bogusMessage2() { runTest("Bogus error message: The abstract method ajc$pointcut$$tracingScope$a2 in type Tracing can only be defined by an abstract class (2)"); } public void test054_cnfe() { runTest("passing null to array arguments confuzes static join point signature. (1)"); } public void test055_cnfe() { runTest("passing null to array arguments confuzes static join point signature. (2)"); } public void test056_arrayCloning() { runTest("around advice throws java.lang.VerifyError at runtime"); } public void test057_decSoftWithSuper() { runTest("declare soft can cause programs with invalid exception behaviour to be generated"); } public void test058_npeOnTJPerror() { runTest("NPE on thisJoinPoint mistake"); } public void test059_cflowOptimization_counters() { runTest("Optimization of cflow - counters (1)"); } public void test060_cflowOptimization_counters() { runTest("Optimization of cflow - shared counters (2)"); } public void test061_cflowOptimization_counters() { runTest("Optimization of cflow - shared stacks (3)"); } public void test062_cflowOptimization_counters() { runTest("Optimization of cflow - counters (4)"); } public void test063_cflowOptimization_countersWithAbstractPcuts() { runTest("Optimization of cflow - counters with abstract pointcuts (5)"); } }
74,952
Bug 74952 before,after !(cflow(within(Trace*))) prints nothing
Reference: "cflow(within(C)) vs (within(C)||cflowbelow(within(C)) in aspectj-users mailing list. The aspect TraceClass below doesn't print any message when the pointcut is defined to "!cflow(within(Trace*))". The other defintion "!(within(Trace*) || cflowbelow(within(Trace*)))" works fine. Wes Isberg in his reply explained that cflow should never be used alone but he thought "there is a bug or two in here" class SomeClass { static public void main (String [] args) { } } // SomeClass aspect TraceClass { // members static private int level = 0; static private void offset() { int i; for (i = 0; i < level; ++i) { System.out.print(" "); } } // offset pointcut pc() : !cflow(within(Trace*)) // !(within(Trace*) || cflowbelow(within(Trace*))) ; before () : pc() { offset(); System.out.println("-> " + thisJoinPoint); ++level; } after () : pc() { --level; offset(); System.out.println("<- " + thisJoinPoint); } } // TraceClass In order to try to figure out what is happening within TraceClass, I added a second aspect, TraceTrace, just to trace TraceClass. aspect TraceTrace { // members static private int level = 0; static private void offset() { int i; for (i = 0; i < level; ++i) { System.out.print(" "); } } // offset pointcut pc() : within(TraceClass); before () : pc() { offset(); System.out.println("=> " + thisJoinPoint); ++level; } after () : pc() { --level; offset(); System.out.println("<= " + thisJoinPoint); } } // TraceTrace Here is what TraceTrace prints when TraceClass uses "!cflow(within(Trace*))" => staticinitialization(TraceClass.<clinit>) => set(int TraceClass.level) <= set(int TraceClass.level) => preinitialization(TraceClass()) => initialization(TraceClass()) => execution(TraceClass()) <= execution(TraceClass()) <= initialization(TraceClass()) <= staticinitialization(TraceClass.<clinit>) The after advice is not executed for preinitialization.
resolved fixed
a303a09
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2004-10-21T12:55:49Z
2004-09-24T15:33:20Z
tests/bugs/WhatsGoingOn.java
74,952
Bug 74952 before,after !(cflow(within(Trace*))) prints nothing
Reference: "cflow(within(C)) vs (within(C)||cflowbelow(within(C)) in aspectj-users mailing list. The aspect TraceClass below doesn't print any message when the pointcut is defined to "!cflow(within(Trace*))". The other defintion "!(within(Trace*) || cflowbelow(within(Trace*)))" works fine. Wes Isberg in his reply explained that cflow should never be used alone but he thought "there is a bug or two in here" class SomeClass { static public void main (String [] args) { } } // SomeClass aspect TraceClass { // members static private int level = 0; static private void offset() { int i; for (i = 0; i < level; ++i) { System.out.print(" "); } } // offset pointcut pc() : !cflow(within(Trace*)) // !(within(Trace*) || cflowbelow(within(Trace*))) ; before () : pc() { offset(); System.out.println("-> " + thisJoinPoint); ++level; } after () : pc() { --level; offset(); System.out.println("<- " + thisJoinPoint); } } // TraceClass In order to try to figure out what is happening within TraceClass, I added a second aspect, TraceTrace, just to trace TraceClass. aspect TraceTrace { // members static private int level = 0; static private void offset() { int i; for (i = 0; i < level; ++i) { System.out.print(" "); } } // offset pointcut pc() : within(TraceClass); before () : pc() { offset(); System.out.println("=> " + thisJoinPoint); ++level; } after () : pc() { --level; offset(); System.out.println("<= " + thisJoinPoint); } } // TraceTrace Here is what TraceTrace prints when TraceClass uses "!cflow(within(Trace*))" => staticinitialization(TraceClass.<clinit>) => set(int TraceClass.level) <= set(int TraceClass.level) => preinitialization(TraceClass()) => initialization(TraceClass()) => execution(TraceClass()) <= execution(TraceClass()) <= initialization(TraceClass()) <= staticinitialization(TraceClass.<clinit>) The after advice is not executed for preinitialization.
resolved fixed
a303a09
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2004-10-21T12:55:49Z
2004-09-24T15:33:20Z
tests/src/org/aspectj/systemtest/ajc121/Ajc121Tests.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 * * ******************************************************************/ package org.aspectj.systemtest.ajc121; import java.io.File; import java.util.Iterator; import java.util.List; import junit.framework.Test; import org.aspectj.bridge.WeaveMessage; import org.aspectj.testing.XMLBasedAjcTestCase; public class Ajc121Tests extends org.aspectj.testing.XMLBasedAjcTestCase { public static Test suite() { return XMLBasedAjcTestCase.loadSuite(Ajc121Tests.class); } protected File getSpecFile() { return new File("../tests/src/org/aspectj/systemtest/ajc121/ajc121.xml"); } public void test001(){ runTest("false ambiguous binding error (introduced in 1.2rc2)"); } public void test002(){ runTest("An if() pointcut inside a perthis() clauses an ABORT - null pointer exception in ajc"); } public void test003(){ runTest("An if() pointcut inside a perthis() clauses an ABORT - null pointer exception in ajc"); } public void test004(){ runTest("An if() pointcut inside a perthis() clauses an ABORT - null pointer exception in ajc"); } public void test005(){ runTest("compiler aborts with 'conflicting dominates orders' with circular declare precedences"); } public void test006(){ runTest("'can't bind type' message has $ for . in type name for declare soft"); } public void test007(){ runTest("Hiding of Instance Methods by static methods"); } public void test008(){ runTest("if(false) optimisation"); } public void test009(){ runTest("if(true) optimisation"); } public void test010(){ runTest("java.lang.NullPointerException in WeaverMessageHandler class"); } public void test011(){ runTest("ClassCastException at BcelRenderer.java:169"); } public void test012(){ runTest("Front-end bug, shouldn't allow patterns of the form foo.., should be foo..*"); } public void test013() { runTest("Nullpointer-Exception when defining a withincode() pointcut"); } public void test014() { runTest("NPE, Incorrect XLint:unmatchedSuperTypeInCall warning"); } public void test015_invalidXlint() { // keywords: "laurie hendren" runTest("invalid warning indicating no match when a match really occurs"); } public void test016_ByteConversionInstructions() { runTest("RuntimeException thrown: Could not find instruction: org.apache.bcel.generic.B2I"); String output = getLastRunResult().getStdErr(); assertTrue("Expected to find [b2] in this output but didn't:"+output,output.indexOf("[b2]")!=-1); assertTrue("Expected to find [b127] in this output but didn't:"+output,output.indexOf("[b127]")!=-1); assertTrue("Expected to find [b0] in this output but didn't:"+output,output.indexOf("[b0]")!=-1); assertTrue("Expected to find [c65] in this output but didn't:"+output,output.indexOf("[c65]")!=-1); assertTrue("Expected to find [c66] in this output but didn't:"+output,output.indexOf("[c66]")!=-1); assertTrue("Expected to find [c67] in this output but didn't:"+output,output.indexOf("[c67]")!=-1); assertTrue("Expected to find [s1] in this output but didn't:"+output,output.indexOf("[s1]")!=-1); assertTrue("Expected to find [s32767] in this output but didn't:"+output,output.indexOf("[s32767]")!=-1); assertTrue("Expected to find [b0] in this output but didn't:"+output,output.indexOf("[b0]")!=-1); } public void test017_PrivateMethodCallsInAroundAdvice() { runTest("Cannot advise private method call in around advice"); System.err.println(getLastRunResult().getStdErr()); } public void test018_PrivateFieldSetsInAroundAdvice() { runTest("Cannot advise private field sets in around advice"); System.err.println(getLastRunResult().getStdErr()); } public void test019_PrivateFieldGetsInAroundAdvice() { runTest("Cannot advise private field gets in around advice"); System.err.println(getLastRunResult().getStdErr()); } // test takes over 5 minutes to run, so not included in normal suite run // public void test020_branchTargetOffsetTooLargeForShort() { // runTest("Branch target offset too large for short"); // } // public void test021_BcelFailureWithVeryLargeClasses() { // runTest("Weaver fails in BCEL for large classes"); // } // // public void test022_BcelFailureWithVeryLargeClasses_Binary() { // runTest("Weaver fails in BCEL for large classes (binary)"); // } public void test023_proceedInAround1() { runTest("proceed used as method name in around advice (1)"); } public void test024_proceedInAround2() { runTest("proceed used as method name in around advice (2)"); } public void test025_proceedInAround3() { runTest("proceed used as method name in around advice (3)"); } public void test026_bindingThisAndTargetToTheSameFormal() { runTest("ajc crashes when compiling the following program (binding this() and target())"); } public void test027_itdsOnInnerClassesAsStatic() { runTest("ITDs on inner classes should be static context"); } public void test028_itdsAndInitializers() { runTest("resolution of IT field inits"); } public void test029_falseInvalidAbsoluteTypeName() { runTest("Valid but inaccessible type names should not be flagged by XLint:invalidAbsoluteTypeName"); } public void test030_privateITDinitialisersBeingMatched() { runTest("intertype initialisers should match field set pointcuts"); } public void test031_privateITDinitialisersBeingMatched_OxfordTest() { runTest("intertype initialisers should match field set pointcuts (oxford testcase)"); //System.err.println(">"+getLastRunResult().getStdErr()); String exp = ":set field set(int C.n):set field set(int C.m):get field get(int C.n):set field set(int C.n)"; assertTrue("Expected output '"+exp+"' but got "+getLastRunResult().getStdErr(), getLastRunResult().getStdErr().equals(exp)); } public void test032_stringConcatForDEOW() { runTest("Compile time declarations (warning and error) do not accept string concatenation (with +)"); } public void test033_stringConcatForDEOWErrorCase() { runTest("Compile time declarations (warning and error) do not accept string concatenation (with +) (2)"); } public void test034_scopeForITDS_pr61768() { runTest("scope for inter-type methods"); } public void test035_innerAspectCallsPrivateMethod_pr71372() { runTest("NoSuchMethodError calling private method from around advice in inner aspect"); String s = getLastRunResult().getStdErr(); assertTrue("Expected ':before:around' but got "+s, s.equals(":before:around")); } public void test036_innerAspectCallsPrivateMethod_pr71372_2() { runTest("NoSuchMethodError calling private method from around advice in inner aspect (2)"); String s = getLastRunResult().getStdErr(); assertTrue("Expected ':before:around' but got "+s, s.equals(":before:around")); } public void test037_innerAspectCallsPrivateMethod_pr71372_3() { runTest("NoSuchMethodError calling private method from around advice in inner aspect (3)"); String s = getLastRunResult().getStdErr(); assertTrue("Expected ':before:around' but got "+s, s.equals(":before:around")); } public void test038_innerAspectCallsPrivateMethod_pr71372_4() { runTest("NoSuchMethodError calling private method from around advice in inner aspect (4)"); String s = getLastRunResult().getStdErr(); assertTrue("Expected ':before:around' but got "+s, s.equals(":before:around")); } public void test039_privilegedAspectAccessingPrivateMethods_pr67579() { runTest("NPE on privileged aspect error"); } public void test040_privilegedAspectAccessingPrivateMethods_pr67579_2() { runTest("NPE on privileged aspect error (2)"); } public void test041_ITDaccessingPrivateMethod_pr67578() { runTest("Privileged Aspect Access Problem Across Packages"); } public void test042_ITDaccessingPrivateMethod_pr67578_2() { runTest("Privileged Aspect Access Problem Across Packages (2)"); } public void test043_pr62642_ExceptionInInitializerError() { runTest("proper handling of ExceptionInIntializer inside clinit in presence of after throwing advice"); String s = getLastRunResult().getStdErr(); assertTrue("Output should contain java.lang.ExceptionInInitializerError but is '"+s+"'", s.indexOf("java.lang.ExceptionInInitializerError")!=-1); // No getCause on 1.3 JVMs // assertTrue("Output should contain 'CAUSE=org.aspectj.lang.NoAspectBoundException' but is '"+s+"'", // s.indexOf("CAUSE=org.aspectj.lang.NoAspectBoundException")!=-1); } public void test044_ITDnameClashes() { runTest("ITD name clashes with private members"); } public void test045_ITDprotectedVisibility() { runTest("Inconsistency in scoping of protected members in ITDs"); } public void test045_wrongLineForExecutionJoinPoint() { runTest("wrong line for method execution join point"); } public void test046_interfaceITD_pr70794_1() { runTest("The introduction on interface causes the interface implementation class error (1)"); } public void test047_interfaceITD_pr70794_2() { runTest("The introduction on interface causes the interface implementation class error (2)"); } public void test048_interfaceITD_pr70794_3() { runTest("The introduction on interface causes the interface implementation class error (3)"); } public void test049_interfaceITD_pr70794_4() { runTest("The introduction on interface causes the interface implementation class error (4)"); } public void test050_typePatternMatchingWithArrays() { runTest("declare warning warns at wrong points"); } public void test051_arrayCloningInJava5() { runTest("AJC possible bug with static nested classes"); List l = ajc.getLastCompilationResult().getInfoMessages(); assertTrue("Should at least have had one weaving message",l!=null && l.size()>0); boolean gotWeaveMessage = false; for (Iterator msg = l.iterator(); msg.hasNext();) { Object element = (Object) msg.next(); if (element instanceof WeaveMessage) { WeaveMessage wm = (WeaveMessage)element; if (wm.getMessage().indexOf("advised by around advice from")!=-1) gotWeaveMessage = true; } } assertTrue("Expected a weaving message but only found "+l,gotWeaveMessage); } public void test052_bogusMessage1() { runTest("Bogus error message: The abstract method ajc$pointcut$$tracingScope$a2 in type Tracing can only be defined by an abstract class (1)"); } public void test053_bogusMessage2() { runTest("Bogus error message: The abstract method ajc$pointcut$$tracingScope$a2 in type Tracing can only be defined by an abstract class (2)"); } public void test054_cnfe() { runTest("passing null to array arguments confuzes static join point signature. (1)"); } public void test055_cnfe() { runTest("passing null to array arguments confuzes static join point signature. (2)"); } public void test056_arrayCloning() { runTest("around advice throws java.lang.VerifyError at runtime"); } public void test057_decSoftWithSuper() { runTest("declare soft can cause programs with invalid exception behaviour to be generated"); } public void test058_npeOnTJPerror() { runTest("NPE on thisJoinPoint mistake"); } public void test059_cflowOptimization_counters() { runTest("Optimization of cflow - counters (1)"); } public void test060_cflowOptimization_counters() { runTest("Optimization of cflow - shared counters (2)"); } public void test061_cflowOptimization_counters() { runTest("Optimization of cflow - shared stacks (3)"); } public void test062_cflowOptimization_counters() { runTest("Optimization of cflow - counters (4)"); } public void test063_cflowOptimization_countersWithAbstractPcuts() { runTest("Optimization of cflow - counters with abstract pointcuts (5)"); } public void test064() { runTest("Anonymous classes unaware of introductions into abstract classes"); } }
74,952
Bug 74952 before,after !(cflow(within(Trace*))) prints nothing
Reference: "cflow(within(C)) vs (within(C)||cflowbelow(within(C)) in aspectj-users mailing list. The aspect TraceClass below doesn't print any message when the pointcut is defined to "!cflow(within(Trace*))". The other defintion "!(within(Trace*) || cflowbelow(within(Trace*)))" works fine. Wes Isberg in his reply explained that cflow should never be used alone but he thought "there is a bug or two in here" class SomeClass { static public void main (String [] args) { } } // SomeClass aspect TraceClass { // members static private int level = 0; static private void offset() { int i; for (i = 0; i < level; ++i) { System.out.print(" "); } } // offset pointcut pc() : !cflow(within(Trace*)) // !(within(Trace*) || cflowbelow(within(Trace*))) ; before () : pc() { offset(); System.out.println("-> " + thisJoinPoint); ++level; } after () : pc() { --level; offset(); System.out.println("<- " + thisJoinPoint); } } // TraceClass In order to try to figure out what is happening within TraceClass, I added a second aspect, TraceTrace, just to trace TraceClass. aspect TraceTrace { // members static private int level = 0; static private void offset() { int i; for (i = 0; i < level; ++i) { System.out.print(" "); } } // offset pointcut pc() : within(TraceClass); before () : pc() { offset(); System.out.println("=> " + thisJoinPoint); ++level; } after () : pc() { --level; offset(); System.out.println("<= " + thisJoinPoint); } } // TraceTrace Here is what TraceTrace prints when TraceClass uses "!cflow(within(Trace*))" => staticinitialization(TraceClass.<clinit>) => set(int TraceClass.level) <= set(int TraceClass.level) => preinitialization(TraceClass()) => initialization(TraceClass()) => execution(TraceClass()) <= execution(TraceClass()) <= initialization(TraceClass()) <= staticinitialization(TraceClass.<clinit>) The after advice is not executed for preinitialization.
resolved fixed
a303a09
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2004-10-21T12:55:49Z
2004-09-24T15:33:20Z
weaver/src/org/aspectj/weaver/bcel/BcelShadow.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Common Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * PARC initial implementation * ******************************************************************/ package org.aspectj.weaver.bcel; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.aspectj.apache.bcel.Constants; import org.aspectj.apache.bcel.classfile.Field; import org.aspectj.apache.bcel.generic.ACONST_NULL; import org.aspectj.apache.bcel.generic.ANEWARRAY; import org.aspectj.apache.bcel.generic.ArrayType; import org.aspectj.apache.bcel.generic.BranchInstruction; import org.aspectj.apache.bcel.generic.ConstantPoolGen; import org.aspectj.apache.bcel.generic.DUP; import org.aspectj.apache.bcel.generic.DUP_X1; import org.aspectj.apache.bcel.generic.FieldInstruction; import org.aspectj.apache.bcel.generic.INVOKESPECIAL; import org.aspectj.apache.bcel.generic.INVOKESTATIC; import org.aspectj.apache.bcel.generic.Instruction; import org.aspectj.apache.bcel.generic.InstructionConstants; import org.aspectj.apache.bcel.generic.InstructionFactory; import org.aspectj.apache.bcel.generic.InstructionHandle; import org.aspectj.apache.bcel.generic.InstructionList; import org.aspectj.apache.bcel.generic.InstructionTargeter; import org.aspectj.apache.bcel.generic.InvokeInstruction; import org.aspectj.apache.bcel.generic.LoadInstruction; import org.aspectj.apache.bcel.generic.MULTIANEWARRAY; import org.aspectj.apache.bcel.generic.NEW; import org.aspectj.apache.bcel.generic.ObjectType; import org.aspectj.apache.bcel.generic.ReturnInstruction; import org.aspectj.apache.bcel.generic.SWAP; import org.aspectj.apache.bcel.generic.StoreInstruction; import org.aspectj.apache.bcel.generic.TargetLostException; import org.aspectj.apache.bcel.generic.Type; import org.aspectj.bridge.IMessage; import org.aspectj.bridge.ISourceLocation; import org.aspectj.bridge.Message; 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.WeaverMessages; import org.aspectj.weaver.World; import org.aspectj.weaver.ast.Var; /* * Some fun implementation stuff: * * * expressionKind advice is non-execution advice * * may have a target. * * if the body is extracted, it will be extracted into * a static method. The first argument to the static * method is the target * * advice may expose a this object, but that's the advice's * consideration, not ours. This object will NOT be cached in another * local, but will always come from frame zero. * * * non-expressionKind advice is execution advice * * may have a this. * * target is same as this, and is exposed that way to advice * (i.e., target will not be cached, will always come from frame zero) * * if the body is extracted, it will be extracted into a method * with same static/dynamic modifier as enclosing method. If non-static, * target of callback call will be this. * * * because of these two facts, the setup of the actual arguments (including * possible target) callback method is the same for both kinds of advice: * push the targetVar, if it exists (it will not exist for advice on static * things), then push all the argVars. * * Protected things: * * * the above is sufficient for non-expressionKind advice for protected things, * since the target will always be this. * * * For expressionKind things, we have to modify the signature of the callback * method slightly. For non-static expressionKind things, we modify * the first argument of the callback method NOT to be the type specified * by the method/field signature (the owner), but rather we type it to * the currentlyEnclosing type. We are guaranteed this will be fine, * since the verifier verifies that the target is a subtype of the currently * enclosingType. * * Worries: * * * ConstructorCalls will be weirder than all of these, since they * supposedly don't have a target (according to AspectJ), but they clearly * do have a target of sorts, just one that needs to be pushed on the stack, * dupped, and not touched otherwise until the constructor runs. * * @author Jim Hugunin * @author Erik Hilsdale * */ public class BcelShadow extends Shadow { private ShadowRange range; private final BcelWorld world; private final LazyMethodGen enclosingMethod; private boolean fallsThrough; //XXX not used anymore // ---- 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(); // Create a store instruction to put the value from the top of the // stack into a local variable slot. This is a trimmed version of // what is in initializeArgVars() (since there is only one argument // at a handler jp and only before advice is supported) (pr46298) argVars = new BcelVar[1]; int positionOffset = (hasTarget() ? 1 : 0) + ((hasThis() && !getKind().isTargetSameAsThis()) ? 1 : 0); TypeX tx = getArgType(0); argVars[0] = genTempVar(tx, "ajc$arg0"); InstructionHandle insertedInstruction = range.insert(argVars[0].createStore(getFactory()), Range.OutsideBefore); // Now the exception range starts just after our new instruction. // The next bit of code changes the exception range to point at // the store instruction InstructionTargeter[] targeters = start.getTargeters(); for (int i = 0; i < targeters.length; i++) { InstructionTargeter t = targeters[i]; if (t instanceof ExceptionRange) { ExceptionRange er = (ExceptionRange) t; er.updateTarget(start, insertedInstruction, body); } } } // now we ask each munger to request our state isThisJoinPointLazy = 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) { // Special case first (pr46298). If we are an exception handler and the instruction // just after the shadow is a POP then we should remove the pop. The code // above which generated the store instruction has already cleared the stack. // We also don't generate any code for the arguments in this case as it would be // an incorrect aload. if (getKind() == ExceptionHandler && range.getEnd().getNext().getInstruction().equals(InstructionConstants.POP)) { // easier than deleting it ... range.getEnd().getNext().setInstruction(InstructionConstants.NOP); } else { range.insert( BcelRenderer.renderExprs(fact, world, argVars), Range.InsideBefore); if (targetVar != null) { range.insert( BcelRenderer.renderExpr(fact, world, targetVar), Range.InsideBefore); } if (getKind() == ConstructorCall) { range.insert((Instruction) InstructionFactory.createDup(1), Range.InsideBefore); range.insert( fact.createNew( (ObjectType) BcelWorld.makeBcelType( getSignature().getDeclaringType())), Range.InsideBefore); } } } } // ---- getters public ShadowRange getRange() { return range; } public void setRange(ShadowRange range) { this.range = range; } public int getSourceLine() { // if the kind of join point for which we are a shadow represents // a method or constructor execution, then the best source line is // the one from the enclosingMethod declarationLineNumber if available. Kind kind = getKind(); if ( (kind == MethodExecution) || (kind == ConstructorExecution) || (kind == AdviceExecution) || (kind == StaticInitialization) || (kind == PreInitialization) || (kind == Initialization)) { if (getEnclosingMethod().hasDeclaredLineNumberInfo()) { return getEnclosingMethod().getDeclarationLineNumber(); } } if (range == null) { if (getEnclosingMethod().hasBody()) { return Utility.getSourceLine(getEnclosingMethod().getBody().getStart()); } else { return 0; } } int ret = Utility.getSourceLine(range.getStart()); if (ret < 0) return 0; return ret; } // overrides public 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.getCoreType(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.getCoreType(ResolvedTypeX.OBJECT)); ((BcelVar)getArgVar(1)).appendLoadAndConvert(il, fact, world.getCoreType(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.getCoreType(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(); type = ensureTargetTypeIsCorrect(type); targetVar = genTempVar(type, "ajc$target"); range.insert(targetVar.createStore(fact), Range.OutsideBefore); targetVar.setPositionInAroundState(hasThis() ? 1 : 0); } } /* PR 72528 * This method double checks the target type under certain conditions. The Java 1.4 * compilers seem to take calls to clone methods on array types and create bytecode that * looks like clone is being called on Object. If we advise a clone call with around * advice we extract the call into a helper method which we can then refer to. Because the * type in the bytecode for the call to clone is Object we create a helper method with * an Object parameter - this is not correct as we have lost the fact that the actual * type is an array type. If we don't do the check below we will create code that fails * java verification. This method checks for the peculiar set of conditions and if they * are true, it has a sneak peek at the code before the call to see what is on the stack. */ public TypeX ensureTargetTypeIsCorrect(TypeX tx) { if (tx.equals(ResolvedTypeX.OBJECT) && getKind() == MethodCall && getSignature().getReturnType().equals(ResolvedTypeX.OBJECT) && getSignature().getArity()==0 && getSignature().getName().charAt(0) == 'c' && getSignature().getName().equals("clone")) { // Lets go back through the code from the start of the shadow InstructionHandle searchPtr = range.getStart().getPrev(); while (Range.isRangeHandle(searchPtr) || searchPtr.getInstruction() instanceof StoreInstruction) { // ignore this instruction - it doesnt give us the info we want searchPtr = searchPtr.getPrev(); } // A load instruction may tell us the real type of what the clone() call is on if (searchPtr.getInstruction() instanceof LoadInstruction) { LoadInstruction li = (LoadInstruction)searchPtr.getInstruction(); li.getIndex(); LocalVariableTag lvt = LazyMethodGen.getLocalVariableTag(searchPtr,li.getIndex()); return lvt.getType(); } // A field access instruction may tell us the real type of what the clone() call is on if (searchPtr.getInstruction() instanceof FieldInstruction) { FieldInstruction si = (FieldInstruction)searchPtr.getInstruction(); Type t = si.getFieldType(getEnclosingClass().getConstantPoolGen()); return BcelWorld.fromBcel(t); } // A new array instruction obviously tells us it is an array type ! if (searchPtr.getInstruction() instanceof ANEWARRAY) { //ANEWARRAY ana = (ANEWARRAY)searchPoint.getInstruction(); //Type t = ana.getType(getEnclosingClass().getConstantPoolGen()); // Just use a standard java.lang.object array - that will work fine return BcelWorld.fromBcel(new ArrayType(Type.OBJECT,1)); } // A multi new array instruction obviously tells us it is an array type ! if (searchPtr.getInstruction() instanceof MULTIANEWARRAY) { MULTIANEWARRAY ana = (MULTIANEWARRAY)searchPtr.getInstruction(); // Type t = ana.getType(getEnclosingClass().getConstantPoolGen()); // t = new ArrayType(t,ana.getDimensions()); // Just use a standard java.lang.object array - that will work fine return BcelWorld.fromBcel(new ArrayType(Type.OBJECT,ana.getDimensions())); } throw new BCException("Can't determine real target of clone() when processing instruction "+ searchPtr.getInstruction()); } return tx; } public void initializeArgVars() { if (argVars != null) return; InstructionFactory fact = getFactory(); int len = getArgCount(); argVars = new BcelVar[len]; int positionOffset = (hasTarget() ? 1 : 0) + ((hasThis() && !getKind().isTargetSameAsThis()) ? 1 : 0); if (getKind().argsOnStack()) { // we move backwards because we're popping off the stack for (int i = len - 1; i >= 0; i--) { 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); // pr62642 // I will now jump through some firey BCEL hoops to generate a trivial bit of code: // if (exc instanceof ExceptionInInitializerError) // throw (ExceptionInInitializerError)exc; if (this.getEnclosingMethod().getName().equals("<clinit>")) { ResolvedTypeX eiieType = world.resolve("java.lang.ExceptionInInitializerError"); ObjectType eiieBcelType = (ObjectType)BcelWorld.makeBcelType(eiieType); InstructionList ih = new InstructionList(InstructionConstants.NOP); handler.append(exceptionVar.createLoad(fact)); handler.append(fact.createInstanceOf(eiieBcelType)); BranchInstruction bi = InstructionFactory.createBranchInstruction(Constants.IFEQ,ih.getStart()); handler.append(bi); handler.append(exceptionVar.createLoad(fact)); handler.append(fact.createCheckCast(eiieBcelType)); handler.append(InstructionConstants.ATHROW); handler.append(ih); } InstructionList endHandler = new InstructionList( exceptionVar.createLoad(fact)); handler.append(munger.getAdviceInstructions(this, exceptionVar, endHandler.getStart())); handler.append(endHandler); handler.append(InstructionConstants.ATHROW); InstructionHandle handlerStart = handler.getStart(); if (isFallsThrough()) { InstructionHandle jumpTarget = handler.append(InstructionConstants.NOP); handler.insert(InstructionFactory.createBranchInstruction(Constants.GOTO, jumpTarget)); } InstructionHandle protectedEnd = handler.getStart(); range.insert(handler, Range.InsideAfter); enclosingMethod.addExceptionHandler(range.getStart().getNext(), protectedEnd.getPrev(), handlerStart, (ObjectType)BcelWorld.makeBcelType(catchType), //???Type.THROWABLE, // high priority if our args are on the stack getKind().hasHighPriorityExceptions()); } //??? this shares a lot of code with the above weaveAfterThrowing //??? would be nice to abstract that to say things only once public void weaveSoftener(BcelAdvice munger, 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 cflowField) { final boolean isPer = munger.getKind() == AdviceKind.PerCflowBelowEntry || munger.getKind() == AdviceKind.PerCflowEntry; final Type objectArrayType = new ArrayType(Type.OBJECT, 1); final InstructionFactory fact = getFactory(); final BcelVar testResult = genTempVar(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(); if (cflowStateVars.length == 0) { // This should be getting managed by a counter - lets make sure. if (!cflowField.getType().getName().endsWith("CFlowCounter")) throw new RuntimeException("Oncorrectly attempting counter operation on stacked cflow"); entrySuccessInstructions.append( Utility.createGet(fact, cflowField)); //arrayVar.appendLoad(entrySuccessInstructions, fact); entrySuccessInstructions.append(fact.createInvoke(NameMangler.CFLOW_COUNTER_TYPE,"inc",Type.VOID,new Type[] { },Constants.INVOKEVIRTUAL)); } else { BcelVar arrayVar = genTempVar(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, cflowField)); arrayVar.appendLoad(entrySuccessInstructions, fact); entrySuccessInstructions.append( fact.createInvoke(NameMangler.CFLOW_STACK_TYPE, "push", Type.VOID, new Type[] { objectArrayType }, Constants.INVOKEVIRTUAL)); } } InstructionList testInstructions = munger.getTestInstructions(this, entrySuccessInstructions.getStart(), range.getRealStart(), entrySuccessInstructions.getStart()); entryInstructions.append(testInstructions); entryInstructions.append(entrySuccessInstructions); } // this is the same for both per and non-per weaveAfter(new BcelAdvice(null, null, null, 0, 0, 0, null, null) { public InstructionList getAdviceInstructions( BcelShadow s, BcelVar extraArgVar, InstructionHandle ifNoAdvice) { InstructionList exitInstructions = new InstructionList(); if (munger.hasDynamicTests()) { testResult.appendLoad(exitInstructions, fact); exitInstructions.append( InstructionFactory.createBranchInstruction( Constants.IFEQ, ifNoAdvice)); } exitInstructions.append(Utility.createGet(fact, cflowField)); if (munger.getKind() != AdviceKind.PerCflowEntry && munger.getKind() != AdviceKind.PerCflowBelowEntry && munger.getExposedStateAsBcelVars().length==0) { exitInstructions .append( fact .createInvoke( NameMangler.CFLOW_COUNTER_TYPE, "dec", Type.VOID, new Type[] { }, Constants.INVOKEVIRTUAL)); } else { exitInstructions .append( fact .createInvoke( NameMangler.CFLOW_STACK_TYPE, "pop", Type.VOID, new Type[] { }, Constants.INVOKEVIRTUAL)); } return exitInstructions; } }); range.insert(entryInstructions, Range.InsideBefore); } public void weaveAroundInline( BcelAdvice munger, boolean hasDynamicTest) { /* Implementation notes: * * AroundInline still extracts the instructions of the original shadow into * an extracted method. This allows inlining of even that advice that doesn't * call proceed or calls proceed more than once. * * It extracts the instructions of the original shadow into a method. * * Then it extracts the instructions of the advice into a new method defined on * this enclosing class. This new method can then be specialized as below. * * Then it searches in the instructions of the advice for any call to the * proceed method. * * At such a call, there is stuff on the stack representing the arguments to * proceed. Pop these into the frame. * * Now build the stack for the call to the extracted method, taking values * either from the join point state or from the new frame locs from proceed. * Now call the extracted method. The right return value should be on the * stack, so no cast is necessary. * * If only one call to proceed is made, we can re-inline the original shadow. * We are not doing that presently. * * If the body of the advice can be determined to not alter the stack, or if * this shadow doesn't care about the stack, i.e. method-execution, then the * new method for the advice can also be re-lined. We are not doing that * presently. */ // !!! THIS BLOCK OF CODE SHOULD BE IN A METHOD CALLED weaveAround(...); Member mungerSig = munger.getSignature(); ResolvedTypeX declaringType = world.resolve(mungerSig.getDeclaringType(),true); if (declaringType == ResolvedTypeX.MISSING) { IMessage msg = new Message( WeaverMessages.format(WeaverMessages.CANT_FIND_TYPE_DURING_AROUND_WEAVE,declaringType.getClassName()), "",IMessage.ERROR,getSourceLocation(),null, new ISourceLocation[]{ munger.getSourceLocation()}); world.getMessageHandler().handleMessage(msg); } //??? might want some checks here to give better errors BcelObjectType ot = BcelWorld.getBcelObjectType(declaringType); 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++) { TypeX bcelTX = BcelWorld.fromBcel(stateTypes[i]); ResolvedTypeX stateRTX = world.resolve(bcelTX,true); if (stateRTX == ResolvedTypeX.MISSING) { IMessage msg = new Message( WeaverMessages.format(WeaverMessages.CANT_FIND_TYPE_DURING_AROUND_WEAVE_PREINIT,bcelTX.getClassName()), "",IMessage.ERROR,getSourceLocation(),null, new ISourceLocation[]{ munger.getSourceLocation()}); world.getMessageHandler().handleMessage(msg); } stateTempVar.appendConvertableArrayLoad( returnConversionCode, fact, i, stateRTX); } } else { returnConversionCode = Utility.createConversion( getFactory(), BcelWorld.makeBcelType(munger.getSignature().getReturnType()), callbackMethod.getReturnType()); if (!isFallsThrough()) { returnConversionCode.append( InstructionFactory.createReturn(callbackMethod.getReturnType())); } } 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.getCoreType(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(); targetType = ensureTargetTypeIsCorrect(targetType); ResolvedMember resolvedMember = getSignature().resolve(world); if (resolvedMember != null && Modifier.isProtected(resolvedMember.getModifiers()) && !samePackage(targetType.getPackageName(), getEnclosingType().getPackageName()) && !resolvedMember.getName().equals("clone")) { 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; } }
73,895
Bug 73895 unnecessary cast causing problems
class: org.aspectj.weaver.ResolvedTypeX$Name method: isCoerceableFrom(..) I am having trouble with the line: ResolvedMember[] b = ((Name)other).getDeclaredMethods(); //??? is this cast always safe As the comment suggests this cast is NOT always safe. In my case the cast is not safe because I have some additional implementations for ResolvedTypeX (some optimizations). Solution: just remove the cast since the method "getDeclaredMethods" is already defined abstract in the type of "other" (ResolvedTypeX). So the cast seems to be obsolete anyway.
resolved fixed
8a64fa2
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2004-10-21T13:40:23Z
2004-09-14T16: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... // If it ever does, here is the code: // ResolvedMember cloneMethod = // new ResolvedMember(Member.METHOD,this,Modifier.PUBLIC,TypeX.OBJECT,"clone",new TypeX[]{}); // return new ResolvedMember[]{cloneMethod}; return ResolvedMember.NONE; } public final ResolvedTypeX[] getDeclaredInterfaces() { return new ResolvedTypeX[] { world.getCoreType(CLONEABLE), world.getCoreType(SERIALIZABLE) }; } public final ResolvedMember[] getDeclaredPointcuts() { return ResolvedMember.NONE; } public final ResolvedTypeX getSuperclass() { return world.getCoreType(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: * 1) That we don't have any abstract type mungers unless this type is abstract. * 2) That an abstract ITDM on an interface is declared public. (Compiler limitation) (PR70794) */ public void checkInterTypeMungers() { if (isAbstract()) return; boolean itdProblem = false; for (Iterator iter = getInterTypeMungersIncludingSupers().iterator(); iter.hasNext();) { ConcreteTypeMunger munger = (ConcreteTypeMunger) iter.next(); itdProblem = checkAbstractDeclaration(munger) || itdProblem; // Rule 2 } if (itdProblem) return; // If the rules above are broken, return right now for (Iterator iter = getInterTypeMungersIncludingSupers().iterator(); iter.hasNext();) { ConcreteTypeMunger munger = (ConcreteTypeMunger) iter.next(); if (munger.getSignature() != null && munger.getSignature().isAbstract()) { // Rule 1 world.getMessageHandler().handleMessage( new Message("must implement abstract inter-type declaration: " + munger.getSignature(), "", IMessage.ERROR, getSourceLocation(), null, new ISourceLocation[] { getMungerLocation(munger) })); } } } /** * See PR70794. This method checks that if an abstract inter-type method declaration is made on * an interface then it must also be public. * This is a compiler limitation that could be made to work in the future (if someone * provides a worthwhile usecase) * * @return indicates if the munger failed the check */ private boolean checkAbstractDeclaration(ConcreteTypeMunger munger) { if (munger.getMunger()!=null && (munger.getMunger() instanceof NewMethodTypeMunger)) { ResolvedMember itdMember = munger.getSignature(); ResolvedTypeX onType = itdMember.getDeclaringType().resolve(world); if (onType.isInterface() && itdMember.isAbstract() && !itdMember.isPublic()) { world.getMessageHandler().handleMessage( new Message(WeaverMessages.format(WeaverMessages.ITD_ABSTRACT_MUST_BE_PUBLIC_ON_INTERFACE,munger.getSignature(),onType),"", Message.ERROR,getSourceLocation(),null, new ISourceLocation[]{getMungerLocation(munger)}) ); return true; } } return false; } /** * Get a source location for the munger. * Until intertype mungers remember where they came from, the source location * for the munger itself is null. In these cases use the * source location for the aspect containing the ITD. * */ private ISourceLocation getMungerLocation(ConcreteTypeMunger munger) { ISourceLocation sloc = munger.getSourceLocation(); if (sloc == null) { sloc = munger.getAspectType().getSourceLocation(); } return sloc; } /** * Returns a 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.getCoreType(OBJECT).getDeclaredMethods()).iterator())) return; } } else if (sig.getKind() == Member.FIELD) { if (!compareToExistingMembers(munger, Arrays.asList(getDeclaredFields()).iterator())) return; } else { if (!compareToExistingMembers(munger, Arrays.asList(getDeclaredMethods()).iterator())) return; } // now compare to existingMungers for (Iterator i = interTypeMungers.iterator(); i.hasNext(); ) { ConcreteTypeMunger existingMunger = (ConcreteTypeMunger)i.next(); if (conflictingSignature(existingMunger.getSignature(), munger.getSignature())) { //System.err.println("match " + munger + " with " + existingMunger); if (isVisible(munger.getSignature().getModifiers(), munger.getAspectType(), existingMunger.getAspectType())) { //System.err.println(" is visible"); int c = compareMemberPrecedence(sig, existingMunger.getSignature()); if (c == 0) { c = getWorld().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 if (isDuplicateMemberWithinTargetType(existingMember,this,sig)) { getWorld().getMessageHandler().handleMessage( MessageUtil.error(WeaverMessages.format(WeaverMessages.ITD_MEMBER_CONFLICT,munger.getAspectType().getName(), existingMember), munger.getSourceLocation()) );; } //return; } } return true; } // we know that the member signature matches, but that the member in the target type is not visible to the aspect. // this may still be disallowed if it would result in two members within the same declaring type with the same // signature AND more than one of them is concrete AND they are both visible within the target type. private boolean isDuplicateMemberWithinTargetType(ResolvedMember existingMember, ResolvedTypeX targetType,ResolvedMember itdMember) { if ( (existingMember.isAbstract() || itdMember.isAbstract())) return false; TypeX declaringType = existingMember.getDeclaringType(); if (!targetType.equals(declaringType)) return false; // now have to test that itdMember is visible from targetType if (itdMember.isPrivate()) return false; if (itdMember.isPublic()) return true; // must be in same package to be visible then... if (!targetType.getPackageName().equals(itdMember.getDeclaringType().getPackageName())) return false; // trying to put two members with the same signature into the exact same type..., and both visible in that type. return true; } 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 ResolvedTypeX getTopmostImplementor(ResolvedTypeX interfaceType) { if (isInterface()) return null; if (!interfaceType.isAssignableFrom(this)) return null; // Check if my super class is an implementor? ResolvedTypeX higherType = this.getSuperclass().getTopmostImplementor(interfaceType); if (higherType!=null) return higherType; return this; } private ResolvedTypeX findHigher(ResolvedTypeX other) { if (this == other) return this; for(Iterator i = other.getDirectSupertypes(); i.hasNext(); ) { ResolvedTypeX rtx = (ResolvedTypeX)i.next(); boolean b = this.isAssignableFrom(rtx); if (b) return rtx; } return null; } public List getExposedPointcuts() { List ret = new ArrayList(); if (getSuperclass() != null) ret.addAll(getSuperclass().getExposedPointcuts()); for (Iterator i = Arrays.asList(getDeclaredInterfaces()).iterator(); i.hasNext(); ) { 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; } }
76,798
Bug 76798 Add versions to woven class files - enabling better backwards compatibility.
We don't currently include a version in the class files that come out of the weaver. This can cause problems. For example, if we add a new attribute to a class file in a future version of AspectJ, then that attribute will cause older versions of AspectJ to blow up if they encounter it. If we include a version in the class file we can rev the version number when we add attributes (or change the class file form in another way), and by checking that version number in the weaver we can better determine whether we should fail if we encounter a new attribute (or other change), or if it is safe to continue processing. I will add a new WeaverVersion attribute that includes 2 shorts. Major and Minor. Encountering a major version in a class file that is greater than the version a particular weaver is designed to understand will cause compilation to fail. Encountering a minor version in a class file that is greater than the minor version a particular weaver is designed to understand will not cause compilation to fail - we will assume it is safe to continue.
resolved fixed
6aa7516
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2004-10-22T10:53:11Z
2004-10-22T10:13:20Z
weaver/src/org/aspectj/weaver/AjAttribute.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the 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.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.aspectj.util.FileUtil; import org.aspectj.weaver.patterns.Declare; import org.aspectj.weaver.patterns.PerClause; import org.aspectj.weaver.patterns.Pointcut; /** * These attributes are written to and read from .class files (see the JVM spec). * * <p>Each member or type can have a number of AjAttributes. Each * such attribute is in 1-1 correspondence with an Unknown bcel attribute. * Creating one of these does NOTHING to the underlying thing, so if you really * want to add an attribute to a particular thing, well, you'd better actually do that. * * @author Erik Hilsdale * @author Jim Hugunin */ public abstract class AjAttribute { public static final String AttributePrefix = "org.aspectj.weaver"; protected abstract void write(DataOutputStream s) throws IOException; public abstract String getNameString(); public char[] getNameChars() { return getNameString().toCharArray(); } /** * Just writes the contents */ public byte[] getBytes() { try { ByteArrayOutputStream b0 = new ByteArrayOutputStream(); DataOutputStream s0 = new DataOutputStream(b0); write(s0); return b0.toByteArray(); } catch (IOException e) { // shouldn't happen with ByteArrayOutputStreams throw new RuntimeException("sanity check"); } } /** * Writes the full attribute, i.e. name_index, length, and contents */ public byte[] getAllBytes(short nameIndex) { try { byte[] bytes = getBytes(); ByteArrayOutputStream b0 = new ByteArrayOutputStream(); DataOutputStream s0 = new DataOutputStream(b0); s0.writeShort(nameIndex); s0.writeInt(bytes.length); s0.write(bytes); return b0.toByteArray(); } catch (IOException e) { // shouldn't happen with ByteArrayOutputStreams throw new RuntimeException("sanity check"); } } public static AjAttribute read(String name, byte[] bytes, ISourceContext context) { try { if (bytes == null) bytes = new byte[0]; DataInputStream s = new DataInputStream(new ByteArrayInputStream(bytes)); if (name.equals(Aspect.AttributeName)) { return new Aspect(PerClause.readPerClause(s, context)); } else if (name.equals(MethodDeclarationLineNumberAttribute.AttributeName)) { return MethodDeclarationLineNumberAttribute.read(s); } else if (name.equals(WeaverState.AttributeName)) { return new WeaverState(WeaverStateInfo.read(s, context)); } else if (name.equals(AdviceAttribute.AttributeName)) { return AdviceAttribute.read(s, context); } else if (name.equals(PointcutDeclarationAttribute.AttributeName)) { return new PointcutDeclarationAttribute(ResolvedPointcutDefinition.read(s, context)); } else if (name.equals(TypeMunger.AttributeName)) { return new TypeMunger(ResolvedTypeMunger.read(s, context)); } else if (name.equals(AjSynthetic.AttributeName)) { return new AjSynthetic(); } else if (name.equals(DeclareAttribute.AttributeName)) { return new DeclareAttribute(Declare.read(s, context)); } else if (name.equals(PrivilegedAttribute.AttributeName)) { return PrivilegedAttribute.read(s, context); } else if (name.equals(SourceContextAttribute.AttributeName)) { return SourceContextAttribute.read(s); } else if (name.equals(EffectiveSignatureAttribute.AttributeName)) { return EffectiveSignatureAttribute.read(s, context); } else { throw new BCException("unknown attribute" + name); } } catch (IOException e) { throw new BCException("malformed " + name + " attribute " + e); } } //---- /** Synthetic members should have NO advice put on them or on their contents. * This attribute is currently unused as we consider all members starting * with NameMangler.PREFIX to automatically be synthetic. As we use this we might * find that we want multiple * kinds of synthetic. In particular, if we want to treat the call to a synthetic getter * (say, of an introduced field) as a field reference itself, then a method might want * a particular kind of AjSynthetic attribute that also includes a signature of what * it stands for. */ public static class AjSynthetic extends AjAttribute { public static final String AttributeName = "org.aspectj.weaver.AjSynthetic"; public String getNameString() { return AttributeName; } // private ResolvedTypeMunger munger; public AjSynthetic() {} public void write(DataOutputStream s) throws IOException {} } public static class TypeMunger extends AjAttribute { public static final String AttributeName = "org.aspectj.weaver.TypeMunger"; public String getNameString() { return AttributeName; } private ResolvedTypeMunger munger; public TypeMunger(ResolvedTypeMunger munger) { this.munger = munger; } public void write(DataOutputStream s) throws IOException { munger.write(s); } public ConcreteTypeMunger reify(World world, ResolvedTypeX aspectType) { return world.concreteTypeMunger(munger, aspectType); } } public static class WeaverState extends AjAttribute { public static final String AttributeName = "org.aspectj.weaver.WeaverState"; public String getNameString() { return AttributeName; } private WeaverStateInfo kind; public WeaverState(WeaverStateInfo kind) { this.kind = kind; } public void write(DataOutputStream s) throws IOException { kind.write(s); } public WeaverStateInfo reify() { return kind; } } public static class SourceContextAttribute extends AjAttribute { public static final String AttributeName = "org.aspectj.weaver.SourceContext"; public String getNameString() { return AttributeName; } private String sourceFileName; private int[] lineBreaks; public SourceContextAttribute(String sourceFileName, int[] lineBreaks) { this.sourceFileName = sourceFileName; this.lineBreaks = lineBreaks; } public void write(DataOutputStream s) throws IOException { s.writeUTF(sourceFileName); FileUtil.writeIntArray(lineBreaks, s); } public static SourceContextAttribute read(DataInputStream s) throws IOException { return new SourceContextAttribute(s.readUTF(), FileUtil.readIntArray(s)); } public int[] getLineBreaks() { return lineBreaks; } public String getSourceFileName() { return sourceFileName; } } public static class MethodDeclarationLineNumberAttribute extends AjAttribute { public static final String AttributeName = "org.aspectj.weaver.MethodDeclarationLineNumber"; public String getNameString() { return AttributeName; } private int lineNumber; public MethodDeclarationLineNumberAttribute(int line) { this.lineNumber = line; } public int getLineNumber() { return lineNumber; } public void write(DataOutputStream s) throws IOException { s.writeInt(lineNumber); } public static MethodDeclarationLineNumberAttribute read(DataInputStream s) throws IOException { return new MethodDeclarationLineNumberAttribute(s.readInt()); } public String toString() { return AttributeName + ": " + lineNumber; } } public static class PointcutDeclarationAttribute extends AjAttribute { public static final String AttributeName = "org.aspectj.weaver.PointcutDeclaration"; public String getNameString() { return AttributeName; } private ResolvedPointcutDefinition pointcutDef; public PointcutDeclarationAttribute(ResolvedPointcutDefinition pointcutDef) { this.pointcutDef = pointcutDef; } public void write(DataOutputStream s) throws IOException { pointcutDef.write(s); } public ResolvedPointcutDefinition reify() { return pointcutDef; } } public static class DeclareAttribute extends AjAttribute { public static final String AttributeName = "org.aspectj.weaver.Declare"; public String getNameString() { return AttributeName; } private Declare declare; public DeclareAttribute(Declare declare) { this.declare = declare; } public void write(DataOutputStream s) throws IOException { declare.write(s); } public Declare getDeclare() { return declare; } } public static class AdviceAttribute extends AjAttribute { public static final String AttributeName = "org.aspectj.weaver.Advice"; public String getNameString() { return AttributeName; } private AdviceKind kind; private Pointcut pointcut; private int extraParameterFlags; private int start; private int end; private ISourceContext sourceContext; // these are only used by around advice private boolean proceedInInners; private ResolvedMember[] proceedCallSignatures; // size == # of proceed calls in body private boolean[] formalsUnchangedToProceed; // size == formals.size private TypeX[] declaredExceptions; /** * @param lexicalPosition must be greater than the lexicalPosition * of any advice declared before this one in an aspect, otherwise, * it can be any value. */ public AdviceAttribute(AdviceKind kind, Pointcut pointcut, int extraArgumentFlags, int start, int end, ISourceContext sourceContext) { this.kind = kind; this.pointcut = pointcut; this.extraParameterFlags = extraArgumentFlags; this.start = start; this.end = end; this.sourceContext = sourceContext; //XXX put this back when testing works better (or fails better) //if (kind == AdviceKind.Around) throw new IllegalArgumentException("not for around"); } public AdviceAttribute(AdviceKind kind, Pointcut pointcut, int extraArgumentFlags, int start, int end, ISourceContext sourceContext, boolean proceedInInners, ResolvedMember[] proceedCallSignatures, boolean[] formalsUnchangedToProceed, TypeX[] declaredExceptions) { this.kind = kind; this.pointcut = pointcut; this.extraParameterFlags = extraArgumentFlags; this.start = start; this.end = end; this.sourceContext = sourceContext; if (kind != AdviceKind.Around) throw new IllegalArgumentException("only for around"); this.proceedInInners = proceedInInners; this.proceedCallSignatures = proceedCallSignatures; this.formalsUnchangedToProceed = formalsUnchangedToProceed; this.declaredExceptions = declaredExceptions; } public static AdviceAttribute read(DataInputStream s, ISourceContext context) throws IOException { AdviceKind kind = AdviceKind.read(s); if (kind == AdviceKind.Around) { return new AdviceAttribute( kind, Pointcut.read(s, context), s.readByte(), s.readInt(), s.readInt(), context, s.readBoolean(), ResolvedMember.readResolvedMemberArray(s, context), FileUtil.readBooleanArray(s), TypeX.readArray(s)); } else { return new AdviceAttribute( kind, Pointcut.read(s, context), s.readByte(), s.readInt(), s.readInt(), context); } } public void write(DataOutputStream s) throws IOException { kind.write(s); pointcut.write(s); s.writeByte(extraParameterFlags); s.writeInt(start); s.writeInt(end); if (kind == AdviceKind.Around) { s.writeBoolean(proceedInInners); ResolvedMember.writeArray(proceedCallSignatures, s); FileUtil.writeBooleanArray(formalsUnchangedToProceed, s); TypeX.writeArray(declaredExceptions, s); } } public Advice reify(Member signature, World world) { return world.concreteAdvice(this, pointcut, signature); } public String toString() { return "AdviceAttribute(" + kind + ", " + pointcut + ", " + extraParameterFlags + ", " + start+")"; } public int getExtraParameterFlags() { return extraParameterFlags; } public AdviceKind getKind() { return kind; } public Pointcut getPointcut() { return pointcut; } public TypeX[] getDeclaredExceptions() { return declaredExceptions; } public boolean[] getFormalsUnchangedToProceed() { return formalsUnchangedToProceed; } public ResolvedMember[] getProceedCallSignatures() { return proceedCallSignatures; } public boolean isProceedInInners() { return proceedInInners; } public int getEnd() { return end; } public ISourceContext getSourceContext() { return sourceContext; } public int getStart() { return start; } } public static class Aspect extends AjAttribute { public static final String AttributeName = "org.aspectj.weaver.Aspect"; public String getNameString() { return AttributeName; } private PerClause perClause; public Aspect(PerClause perClause) { this.perClause = perClause; } public PerClause reify(ResolvedTypeX inAspect) { //XXXperClause.concretize(inAspect); return perClause; } public void write(DataOutputStream s) throws IOException { perClause.write(s); } } public static class PrivilegedAttribute extends AjAttribute { public static final String AttributeName = "org.aspectj.weaver.Privileged"; public String getNameString() { return AttributeName; } private ResolvedMember[] accessedMembers; public PrivilegedAttribute(ResolvedMember[] accessedMembers) { this.accessedMembers = accessedMembers; } public void write(DataOutputStream s) throws IOException { ResolvedMember.writeArray(accessedMembers, s); } public ResolvedMember[] getAccessedMembers() { return accessedMembers; } public static PrivilegedAttribute read(DataInputStream s, ISourceContext context) throws IOException { return new PrivilegedAttribute(ResolvedMember.readResolvedMemberArray(s, context)); } } public static class EffectiveSignatureAttribute extends AjAttribute { public static final String AttributeName = "org.aspectj.weaver.EffectiveSignature"; public String getNameString() { return AttributeName; } private ResolvedMember effectiveSignature; private Shadow.Kind shadowKind; private boolean weaveBody; public EffectiveSignatureAttribute(ResolvedMember effectiveSignature, Shadow.Kind shadowKind, boolean weaveBody) { this.effectiveSignature = effectiveSignature; this.shadowKind = shadowKind; this.weaveBody = weaveBody; } public void write(DataOutputStream s) throws IOException { effectiveSignature.write(s); shadowKind.write(s); s.writeBoolean(weaveBody); } public static EffectiveSignatureAttribute read(DataInputStream s, ISourceContext context) throws IOException { return new EffectiveSignatureAttribute( ResolvedMember.readResolvedMember(s, context), Shadow.Kind.read(s), s.readBoolean()); } public ResolvedMember getEffectiveSignature() { return effectiveSignature; } public String toString() { return "EffectiveSignatureAttribute(" + effectiveSignature + ", " + shadowKind + ")"; } public Shadow.Kind getShadowKind() { return shadowKind; } public boolean isWeaveBody() { return weaveBody; } } }
76,798
Bug 76798 Add versions to woven class files - enabling better backwards compatibility.
We don't currently include a version in the class files that come out of the weaver. This can cause problems. For example, if we add a new attribute to a class file in a future version of AspectJ, then that attribute will cause older versions of AspectJ to blow up if they encounter it. If we include a version in the class file we can rev the version number when we add attributes (or change the class file form in another way), and by checking that version number in the weaver we can better determine whether we should fail if we encounter a new attribute (or other change), or if it is safe to continue processing. I will add a new WeaverVersion attribute that includes 2 shorts. Major and Minor. Encountering a major version in a class file that is greater than the version a particular weaver is designed to understand will cause compilation to fail. Encountering a minor version in a class file that is greater than the minor version a particular weaver is designed to understand will not cause compilation to fail - we will assume it is safe to continue.
resolved fixed
6aa7516
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2004-10-22T10:53:11Z
2004-10-22T10:13:20Z
weaver/src/org/aspectj/weaver/bcel/BcelAttributes.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.List; import org.aspectj.apache.bcel.classfile.Attribute; import org.aspectj.apache.bcel.classfile.Unknown; import org.aspectj.apache.bcel.generic.ConstantPoolGen; import org.aspectj.weaver.AjAttribute; import org.aspectj.weaver.ISourceContext; // this is a class o' static methods for reading attributes. It's pretty much a bridge from // bcel to AjAttribute. class BcelAttributes { public static List readAjAttributes(Attribute[] as, ISourceContext context) { List l = new ArrayList(); for (int i = as.length - 1; i >= 0; i--) { Attribute a = as[i]; if (a instanceof Unknown) { Unknown u = (Unknown) a; String name = u.getName(); if (name.startsWith(AjAttribute.AttributePrefix)) { l.add(AjAttribute.read(name, u.getBytes(), context)); } } } return l; } public static Attribute bcelAttribute(AjAttribute a, ConstantPoolGen pool) { int nameIndex = pool.addUtf8(a.getNameString()); byte[] bytes = a.getBytes(); int length = bytes.length; return new Unknown(nameIndex, length, bytes, pool.getConstantPool()); } }
76,798
Bug 76798 Add versions to woven class files - enabling better backwards compatibility.
We don't currently include a version in the class files that come out of the weaver. This can cause problems. For example, if we add a new attribute to a class file in a future version of AspectJ, then that attribute will cause older versions of AspectJ to blow up if they encounter it. If we include a version in the class file we can rev the version number when we add attributes (or change the class file form in another way), and by checking that version number in the weaver we can better determine whether we should fail if we encounter a new attribute (or other change), or if it is safe to continue processing. I will add a new WeaverVersion attribute that includes 2 shorts. Major and Minor. Encountering a major version in a class file that is greater than the version a particular weaver is designed to understand will cause compilation to fail. Encountering a minor version in a class file that is greater than the minor version a particular weaver is designed to understand will not cause compilation to fail - we will assume it is safe to continue.
resolved fixed
6aa7516
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2004-10-22T10:53:11Z
2004-10-22T10:13:20Z
weaver/src/org/aspectj/weaver/bcel/BcelField.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Common Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * PARC initial implementation * ******************************************************************/ package org.aspectj.weaver.bcel; import java.util.Iterator; import java.util.List; import org.aspectj.apache.bcel.classfile.Attribute; import org.aspectj.apache.bcel.classfile.Field; import org.aspectj.apache.bcel.classfile.Synthetic; import org.aspectj.weaver.AjAttribute; import org.aspectj.weaver.BCException; import org.aspectj.weaver.ResolvedMember; import org.aspectj.weaver.TypeX; import org.aspectj.weaver.World; final class BcelField extends ResolvedMember { private Field field; private boolean isAjSynthetic; private boolean isSynthetic = false; BcelField(BcelObjectType declaringType, Field field) { super( FIELD, declaringType.getResolvedTypeX(), field.getAccessFlags(), field.getName(), field.getSignature()); this.field = field; unpackAttributes(declaringType.getResolvedTypeX().getWorld()); checkedExceptions = TypeX.NONE; } // ---- private void unpackAttributes(World world) { Attribute[] attrs = field.getAttributes(); List as = BcelAttributes.readAjAttributes(attrs, getSourceContext(world)); for (Iterator iter = as.iterator(); iter.hasNext();) { AjAttribute a = (AjAttribute) iter.next(); if (a instanceof AjAttribute.AjSynthetic) { isAjSynthetic = true; } else { throw new BCException("weird field attribute " + a); } } isAjSynthetic = false; for (int i = attrs.length - 1; i >= 0; i--) { if (attrs[i] instanceof Synthetic) isSynthetic = true; } } public boolean isAjSynthetic() { return isAjSynthetic; // || getName().startsWith(NameMangler.PREFIX); } public boolean isSynthetic() { return isSynthetic; } }
76,798
Bug 76798 Add versions to woven class files - enabling better backwards compatibility.
We don't currently include a version in the class files that come out of the weaver. This can cause problems. For example, if we add a new attribute to a class file in a future version of AspectJ, then that attribute will cause older versions of AspectJ to blow up if they encounter it. If we include a version in the class file we can rev the version number when we add attributes (or change the class file form in another way), and by checking that version number in the weaver we can better determine whether we should fail if we encounter a new attribute (or other change), or if it is safe to continue processing. I will add a new WeaverVersion attribute that includes 2 shorts. Major and Minor. Encountering a major version in a class file that is greater than the version a particular weaver is designed to understand will cause compilation to fail. Encountering a minor version in a class file that is greater than the minor version a particular weaver is designed to understand will not cause compilation to fail - we will assume it is safe to continue.
resolved fixed
6aa7516
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2004-10-22T10:53:11Z
2004-10-22T10:13:20Z
weaver/src/org/aspectj/weaver/bcel/BcelMethod.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Common Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * PARC initial implementation * ******************************************************************/ package org.aspectj.weaver.bcel; import java.lang.reflect.Modifier; import java.util.Iterator; import java.util.List; import org.aspectj.apache.bcel.classfile.ExceptionTable; import org.aspectj.apache.bcel.classfile.LocalVariable; import org.aspectj.apache.bcel.classfile.LocalVariableTable; import org.aspectj.apache.bcel.classfile.Method; import org.aspectj.weaver.AjAttribute; import org.aspectj.weaver.BCException; import org.aspectj.weaver.ResolvedMember; import org.aspectj.weaver.ShadowMunger; import org.aspectj.weaver.TypeX; import org.aspectj.weaver.World; final class BcelMethod extends ResolvedMember { private Method method; private boolean isAjSynthetic; private ShadowMunger associatedShadowMunger; private AjAttribute.EffectiveSignatureAttribute effectiveSignature; private AjAttribute.MethodDeclarationLineNumberAttribute declarationLineNumber; BcelMethod(BcelObjectType declaringType, Method method) { super( method.getName().equals("<init>") ? CONSTRUCTOR : (method.getName().equals("<clinit>") ? STATIC_INITIALIZATION : METHOD), declaringType.getResolvedTypeX(), declaringType.isInterface() ? method.getAccessFlags() | Modifier.INTERFACE : method.getAccessFlags(), method.getName(), method.getSignature()); this.method = method; unpackAjAttributes(declaringType.getResolvedTypeX().getWorld()); unpackJavaAttributes(); } // ---- private void unpackJavaAttributes() { ExceptionTable exnTable = method.getExceptionTable(); checkedExceptions = (exnTable == null) ? TypeX.NONE : TypeX.forNames(exnTable.getExceptionNames()); LocalVariableTable varTable = method.getLocalVariableTable(); int len = getArity(); if (varTable == null) { this.parameterNames = Utility.makeArgNames(len); } else { TypeX[] paramTypes = getParameterTypes(); String[] paramNames = new String[len]; int index = isStatic() ? 0 : 1; for (int i = 0; i < len; i++) { LocalVariable lv = varTable.getLocalVariable(index); if (lv == null) { paramNames[i] = "arg" + i; } else { paramNames[i] = lv.getName(); } index += paramTypes[i].getSize(); } this.parameterNames = paramNames; } } private void unpackAjAttributes(World world) { List as = BcelAttributes.readAjAttributes(method.getAttributes(), getSourceContext(world)); //System.out.println("unpack: " + this + ", " + as); for (Iterator iter = as.iterator(); iter.hasNext();) { AjAttribute a = (AjAttribute) iter.next(); if (a instanceof AjAttribute.MethodDeclarationLineNumberAttribute) { declarationLineNumber = (AjAttribute.MethodDeclarationLineNumberAttribute)a; } else if (a instanceof AjAttribute.AdviceAttribute) { associatedShadowMunger = ((AjAttribute.AdviceAttribute)a).reify(this, world); return; } else if (a instanceof AjAttribute.AjSynthetic) { isAjSynthetic = true; } else if (a instanceof AjAttribute.EffectiveSignatureAttribute) { //System.out.println("found effective: " + this); effectiveSignature = (AjAttribute.EffectiveSignatureAttribute)a; } else { throw new BCException("weird method attribute " + a); } } associatedShadowMunger = null; } public boolean isAjSynthetic() { return isAjSynthetic; // || getName().startsWith(NameMangler.PREFIX); } //FIXME needs an isSynthetic method public ShadowMunger getAssociatedShadowMunger() { return associatedShadowMunger; } public AjAttribute.EffectiveSignatureAttribute getEffectiveSignature() { return effectiveSignature; } public boolean hasDeclarationLineNumberInfo() { return declarationLineNumber != null; } public int getDeclarationLineNumber() { if (declarationLineNumber != null) { return declarationLineNumber.getLineNumber(); } else { return -1; } } public Kind getKind() { if (associatedShadowMunger != null) { return ADVICE; } else { return super.getKind(); } } }
76,798
Bug 76798 Add versions to woven class files - enabling better backwards compatibility.
We don't currently include a version in the class files that come out of the weaver. This can cause problems. For example, if we add a new attribute to a class file in a future version of AspectJ, then that attribute will cause older versions of AspectJ to blow up if they encounter it. If we include a version in the class file we can rev the version number when we add attributes (or change the class file form in another way), and by checking that version number in the weaver we can better determine whether we should fail if we encounter a new attribute (or other change), or if it is safe to continue processing. I will add a new WeaverVersion attribute that includes 2 shorts. Major and Minor. Encountering a major version in a class file that is greater than the version a particular weaver is designed to understand will cause compilation to fail. Encountering a minor version in a class file that is greater than the minor version a particular weaver is designed to understand will not cause compilation to fail - we will assume it is safe to continue.
resolved fixed
6aa7516
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2004-10-22T10:53:11Z
2004-10-22T10:13:20Z
weaver/src/org/aspectj/weaver/bcel/BcelObjectType.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Common Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * PARC initial implementation * ******************************************************************/ package org.aspectj.weaver.bcel; import java.io.PrintStream; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Iterator; import java.util.List; import org.aspectj.apache.bcel.classfile.Field; import org.aspectj.apache.bcel.classfile.JavaClass; import org.aspectj.apache.bcel.classfile.Method; import org.aspectj.bridge.ISourceLocation; import org.aspectj.weaver.AjAttribute; import org.aspectj.weaver.BCException; import org.aspectj.weaver.ResolvedMember; import org.aspectj.weaver.ResolvedPointcutDefinition; import org.aspectj.weaver.ResolvedTypeX; import org.aspectj.weaver.TypeX; import org.aspectj.weaver.WeaverStateInfo; import org.aspectj.weaver.patterns.PerClause; // ??? exposed for testing public class BcelObjectType extends ResolvedTypeX.ConcreteName { private JavaClass javaClass; private boolean isObject = false; // set upon construction private LazyClassGen lazyClassGen = null; // set lazily if it's an aspect // lazy, for no particular reason I can discern private ResolvedTypeX[] interfaces = null; private ResolvedTypeX superClass = null; private ResolvedMember[] fields = null; private ResolvedMember[] methods = null; // strangely non-lazy private ResolvedPointcutDefinition[] pointcuts = null; private PerClause perClause = null; private WeaverStateInfo weaverState = null; private List typeMungers = Collections.EMPTY_LIST; private List declares = Collections.EMPTY_LIST; private ResolvedMember[] privilegedAccess = null; public Collection getTypeMungers() { return typeMungers; } public Collection getDeclares() { return declares; } public Collection getPrivilegedAccesses() { if (privilegedAccess == null) return Collections.EMPTY_LIST; return Arrays.asList(privilegedAccess); } // IMPORTANT! THIS DOESN'T do real work on the java class, just stores it away. BcelObjectType(ResolvedTypeX.Name resolvedTypeX, JavaClass javaClass, boolean exposedToWeaver) { super(resolvedTypeX, exposedToWeaver); this.javaClass = javaClass; if (resolvedTypeX.getSourceContext() == null) { resolvedTypeX.setSourceContext(new BcelSourceContext(this)); } // this should only ever be java.lang.Object which is // the only class in Java-1.4 with no superclasses isObject = (javaClass.getSuperclassNameIndex() == 0); unpackAspectAttributes(); } // repeat initialization public void setJavaClass(JavaClass newclass) { this.javaClass = newclass; resetState(); } public int getModifiers() { return javaClass.getAccessFlags(); } public ResolvedTypeX getSuperclass() { if (isObject) return null; if (superClass == null) { superClass = getResolvedTypeX().getWorld().resolve(TypeX.forName(javaClass.getSuperclassName())); } return superClass; } public ResolvedTypeX[] getDeclaredInterfaces() { if (interfaces == null) { String[] ifaceNames = javaClass.getInterfaceNames(); interfaces = new ResolvedTypeX[ifaceNames.length]; for (int i = 0, len = ifaceNames.length; i < len; i++) { interfaces[i] = getResolvedTypeX().getWorld().resolve(TypeX.forName(ifaceNames[i])); } } return interfaces; } public ResolvedMember[] getDeclaredMethods() { if (methods == null) { Method[] ms = javaClass.getMethods(); ResolvedMember[] ret = new ResolvedMember[ms.length]; for (int i = ms.length - 1; i >= 0; i--) { ret[i] = new BcelMethod(this, ms[i]); } methods = ret; } return methods; } public ResolvedMember[] getDeclaredFields() { if (fields == null) { Field[] fs = javaClass.getFields(); ResolvedMember[] ret = new ResolvedMember[fs.length]; for (int i = 0, len = fs.length; i < len; i++) { ret[i] = new BcelField(this, fs[i]); } fields = ret; } return fields; } // ---- // fun based on the aj attributes public ResolvedMember[] getDeclaredPointcuts() { return pointcuts; } //??? method only used for testing public void addPointcutDefinition(ResolvedPointcutDefinition d) { int len = pointcuts.length; ResolvedPointcutDefinition[] ret = new ResolvedPointcutDefinition[len+1]; System.arraycopy(pointcuts, 0, ret, 0, len); ret[len] = d; pointcuts = ret; } public boolean isAspect() { return perClause != null; } private void unpackAspectAttributes() { List pointcuts = new ArrayList(); typeMungers = new ArrayList(); declares = new ArrayList(); List l = BcelAttributes.readAjAttributes(javaClass.getAttributes(), getResolvedTypeX().getSourceContext()); for (Iterator iter = l.iterator(); iter.hasNext();) { AjAttribute a = (AjAttribute) iter.next(); //System.err.println("unpacking: " + this + " and " + a); if (a instanceof AjAttribute.Aspect) { perClause = ((AjAttribute.Aspect)a).reify(this.getResolvedTypeX()); } else if (a instanceof AjAttribute.PointcutDeclarationAttribute) { pointcuts.add(((AjAttribute.PointcutDeclarationAttribute)a).reify()); } else if (a instanceof AjAttribute.WeaverState) { weaverState = ((AjAttribute.WeaverState)a).reify(); } else if (a instanceof AjAttribute.TypeMunger) { typeMungers.add(((AjAttribute.TypeMunger)a).reify(getResolvedTypeX().getWorld(), getResolvedTypeX())); } else if (a instanceof AjAttribute.DeclareAttribute) { declares.add(((AjAttribute.DeclareAttribute)a).getDeclare()); } else if (a instanceof AjAttribute.PrivilegedAttribute) { privilegedAccess = ((AjAttribute.PrivilegedAttribute)a).getAccessedMembers(); } else if (a instanceof AjAttribute.SourceContextAttribute) { if (getResolvedTypeX().getSourceContext() instanceof BcelSourceContext) { ((BcelSourceContext)getResolvedTypeX().getSourceContext()).addAttributeInfo((AjAttribute.SourceContextAttribute)a); } } else { throw new BCException("bad attribute " + a); } } this.pointcuts = (ResolvedPointcutDefinition[]) pointcuts.toArray(new ResolvedPointcutDefinition[pointcuts.size()]); // this.typeMungers = (BcelTypeMunger[]) // typeMungers.toArray(new BcelTypeMunger[typeMungers.size()]); // this.declares = (Declare[]) // declares.toArray(new Declare[declares.size()]); } public PerClause getPerClause() { return perClause; } JavaClass getJavaClass() { return javaClass; } public void resetState() { this.interfaces = null; this.superClass = null; this.fields = null; this.methods = null; this.pointcuts = null; this.perClause = null; this.weaverState = null; this.lazyClassGen = null; isObject = (javaClass.getSuperclassNameIndex() == 0); unpackAspectAttributes(); } public void finishedWith() { // memory usage experiments.... // this.interfaces = null; // this.superClass = null; // this.fields = null; // this.methods = null; // this.pointcuts = null; // this.perClause = null; // this.weaverState = null; // this.lazyClassGen = null; // this next line frees up memory, but need to understand incremental implications // before leaving it in. // getResolvedTypeX().setSourceContext(null); } public WeaverStateInfo getWeaverState() { return weaverState; } void setWeaverState(WeaverStateInfo weaverState) { this.weaverState = weaverState; } public void printWackyStuff(PrintStream out) { if (typeMungers.size() > 0) { out.println(" TypeMungers: " + typeMungers); } if (declares.size() > 0) { out.println(" declares: " + declares); } } /** * Return the lazyClassGen associated with this type. For aspect types, this * value will be cached, since it is used to inline advice. For non-aspect * types, this lazyClassGen is always newly constructed. */ public LazyClassGen getLazyClassGen() { LazyClassGen ret = lazyClassGen; if (ret == null) { //System.err.println("creating lazy class gen for: " + this); ret = new LazyClassGen(this); //ret.print(System.err); //System.err.println("made LCG from : " + this.getJavaClass().getSuperclassName() ); if (isAspect()) { lazyClassGen = ret; } } return ret; } public boolean isInterface() { return javaClass.isInterface(); } public boolean isSynthetic() { return getResolvedTypeX().isSynthetic(); } public ISourceLocation getSourceLocation() { return getResolvedTypeX().getSourceContext().makeSourceLocation(0); //FIXME, we can do better than this } public void addParent(ResolvedTypeX newParent) { if (newParent.isClass()) { superClass = newParent; } else { ResolvedTypeX[] oldInterfaceNames = getDeclaredInterfaces(); int len = oldInterfaceNames.length; ResolvedTypeX[] newInterfaceNames = new ResolvedTypeX[len+1]; System.arraycopy(oldInterfaceNames, 0, newInterfaceNames, 0, len); newInterfaceNames[len] = newParent; interfaces = newInterfaceNames; } //System.err.println("javaClass: " + Arrays.asList(javaClass.getInterfaceNames()) + " super " + javaClass.getSuperclassName()); //if (lazyClassGen != null) lazyClassGen.print(); } }
76,798
Bug 76798 Add versions to woven class files - enabling better backwards compatibility.
We don't currently include a version in the class files that come out of the weaver. This can cause problems. For example, if we add a new attribute to a class file in a future version of AspectJ, then that attribute will cause older versions of AspectJ to blow up if they encounter it. If we include a version in the class file we can rev the version number when we add attributes (or change the class file form in another way), and by checking that version number in the weaver we can better determine whether we should fail if we encounter a new attribute (or other change), or if it is safe to continue processing. I will add a new WeaverVersion attribute that includes 2 shorts. Major and Minor. Encountering a major version in a class file that is greater than the version a particular weaver is designed to understand will cause compilation to fail. Encountering a minor version in a class file that is greater than the minor version a particular weaver is designed to understand will not cause compilation to fail - we will assume it is safe to continue.
resolved fixed
6aa7516
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2004-10-22T10:53:11Z
2004-10-22T10:13:20Z
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.aspectj.apache.bcel.Constants; import org.aspectj.apache.bcel.classfile.Attribute; import org.aspectj.apache.bcel.classfile.ConstantUtf8; import org.aspectj.apache.bcel.classfile.Field; import org.aspectj.apache.bcel.classfile.JavaClass; import org.aspectj.apache.bcel.classfile.Method; import org.aspectj.apache.bcel.classfile.Unknown; import org.aspectj.apache.bcel.generic.ClassGen; import org.aspectj.apache.bcel.generic.ConstantPoolGen; import org.aspectj.apache.bcel.generic.FieldGen; import org.aspectj.apache.bcel.generic.InstructionConstants; import org.aspectj.apache.bcel.generic.InstructionFactory; import org.aspectj.apache.bcel.generic.InstructionHandle; import org.aspectj.apache.bcel.generic.InstructionList; import org.aspectj.apache.bcel.generic.ObjectType; import org.aspectj.apache.bcel.generic.PUSH; import org.aspectj.apache.bcel.generic.RETURN; import org.aspectj.apache.bcel.generic.Type; import org.aspectj.bridge.IMessage; import org.aspectj.bridge.ISourceLocation; import org.aspectj.bridge.SourceLocation; 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.WeaverMessages; 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 (getConstantPoolGen().getSize() > Short.MAX_VALUE) { // PR 59208 // we've generated a class that is just toooooooooo big (you've been generating programs // again haven't you? come on, admit it, no-one writes classes this big by hand). // create an empty myGen so that we can give back a return value that doesn't upset the // rest of the process. myGen = new ClassGen(myGen.getClassName(), myGen.getSuperclassName(), myGen.getFileName(), myGen.getAccessFlags(), myGen.getInterfaceNames()); // raise an error against this compilation unit. getWorld().showMessage( IMessage.ERROR, WeaverMessages.format(WeaverMessages.CLASS_TOO_BIG, this.getClassName()), new SourceLocation(new File(myGen.getFileName()),0), null ); return; } 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, WeaverMessages.format(WeaverMessages.OVERWRITE_JSR45,getFileName()), 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.aspectj.apache.bcel.classfile.Utility.accessToString(myGen.getAccessFlags(), true); if (s != "") s += " "; s += org.aspectj.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.aspectj.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; // XXX - Do we ever inline before or after advice? If we do, then we // better include them in the check below. (or just change it to // shadow.getEnclosingMethod().getCanInline()) // If the enclosing method is around advice, we could inline the join point // that has led to this shadow. If we do that then the TJP we are creating // here must be PUBLIC so it is visible to the type in which the // advice is inlined. (PR71377) LazyMethodGen encMethod = shadow.getEnclosingMethod(); boolean shadowIsInAroundAdvice = false; if (encMethod!=null && encMethod.getName().startsWith(NameMangler.PREFIX+"around")) { shadowIsInAroundAdvice = true; } if (getType().isInterface() || shadowIsInAroundAdvice) { 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())); } }
76,798
Bug 76798 Add versions to woven class files - enabling better backwards compatibility.
We don't currently include a version in the class files that come out of the weaver. This can cause problems. For example, if we add a new attribute to a class file in a future version of AspectJ, then that attribute will cause older versions of AspectJ to blow up if they encounter it. If we include a version in the class file we can rev the version number when we add attributes (or change the class file form in another way), and by checking that version number in the weaver we can better determine whether we should fail if we encounter a new attribute (or other change), or if it is safe to continue processing. I will add a new WeaverVersion attribute that includes 2 shorts. Major and Minor. Encountering a major version in a class file that is greater than the version a particular weaver is designed to understand will cause compilation to fail. Encountering a minor version in a class file that is greater than the minor version a particular weaver is designed to understand will not cause compilation to fail - we will assume it is safe to continue.
resolved fixed
6aa7516
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2004-10-22T10:53:11Z
2004-10-22T10:13:20Z
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.aspectj.apache.bcel.Constants; import org.aspectj.apache.bcel.classfile.Attribute; import org.aspectj.apache.bcel.classfile.ConstantPool; import org.aspectj.apache.bcel.classfile.Method; import org.aspectj.apache.bcel.classfile.Synthetic; import org.aspectj.apache.bcel.generic.BranchHandle; import org.aspectj.apache.bcel.generic.BranchInstruction; import org.aspectj.apache.bcel.generic.CPInstruction; import org.aspectj.apache.bcel.generic.ClassGenException; import org.aspectj.apache.bcel.generic.CodeExceptionGen; import org.aspectj.apache.bcel.generic.ConstantPoolGen; import org.aspectj.apache.bcel.generic.Instruction; import org.aspectj.apache.bcel.generic.InstructionHandle; import org.aspectj.apache.bcel.generic.InstructionList; import org.aspectj.apache.bcel.generic.InstructionTargeter; import org.aspectj.apache.bcel.generic.LineNumberGen; import org.aspectj.apache.bcel.generic.LocalVariableGen; import org.aspectj.apache.bcel.generic.LocalVariableInstruction; import org.aspectj.apache.bcel.generic.MethodGen; import org.aspectj.apache.bcel.generic.ObjectType; import org.aspectj.apache.bcel.generic.Select; import org.aspectj.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; import org.aspectj.weaver.WeaverMessages; /** * 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(); } public boolean hasDeclaredLineNumberInfo() { return (memberView != null && memberView.hasDeclarationLineNumberInfo()); } public int getDeclarationLineNumber() { if (hasDeclaredLineNumberInfo()) { return memberView.getDeclarationLineNumber(); } else { return -1; } } 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, WeaverMessages.format(WeaverMessages.PROBLEM_GENERATING_METHOD, this.getClassName(), this.getName(), e.getMessage()), this.getMemberView() == null ? null : this.getMemberView().getSourceLocation(), null); // throw e; PR 70201.... let the normal problem reporting infrastructure deal with this rather than crashing. body = null; MethodGen gen = pack(); return gen.getMethod(); } } public void markAsChanged() { initialize(); savedMethod = null; } // ============================= public String toString() { return toLongString(); } public String toShortString() { String access = org.aspectj.apache.bcel.classfile.Utility.accessToString(getAccessFlags()); StringBuffer buf = new StringBuffer(); if (!access.equals("")) { buf.append(access); buf.append(" "); } buf.append( org.aspectj.apache.bcel.classfile.Utility.signatureToString( getReturnType().getSignature(), true)); buf.append(" "); buf.append(getName()); buf.append("("); { int len = argumentTypes.length; if (len > 0) { buf.append( org.aspectj.apache.bcel.classfile.Utility.signatureToString( argumentTypes[0].getSignature(), true)); for (int i = 1; i < argumentTypes.length; i++) { buf.append(", "); buf.append( org.aspectj.apache.bcel.classfile.Utility.signatureToString( argumentTypes[i].getSignature(), true)); } } } buf.append(")"); { int len = declaredExceptions != null ? declaredExceptions.length : 0; if (len > 0) { buf.append(" throws "); buf.append(declaredExceptions[0]); for (int i = 1; i < declaredExceptions.length; i++) { buf.append(", "); buf.append(declaredExceptions[i]); } } } return buf.toString(); } public String toLongString() { 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; } }
77,799
Bug 77799 NullPointerException in StructureSearchManager
Calling Ajde.getDefault().getStructureSearchManager().findMatches(...) for an AspectJ project that has not been built results in a NullPointerException in StructureSearchManager.findMatchesHelper(...) (line 58) Simple patch is attached.
resolved fixed
aab9c2c
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2004-11-04T15:44:51Z
2004-11-04T06:33:20Z
ajde/src/org/aspectj/ajde/ui/StructureSearchManager.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.ui; import java.util.*; import org.aspectj.ajde.Ajde; import org.aspectj.asm.*; //import org.aspectj.asm.internal.*; /** * @author Mik Kersten */ public class StructureSearchManager { /** * @param pattern case-sensitive substring of node name * * @return null if a corresponding node was not found */ public List findMatches( String pattern, IProgramElement.Kind kind) { List matches = new ArrayList(); IHierarchy model = Ajde.getDefault().getStructureModelManager().getHierarchy(); if (model.equals(IHierarchy.NO_STRUCTURE)) { return null; } else { return findMatchesHelper((IProgramElement)model.getRoot(), pattern, kind, matches); } } private List findMatchesHelper( IProgramElement node, String pattern, IProgramElement.Kind kind, List matches) { if (node != null && node.getName().indexOf(pattern) != -1) { if (kind == null || node.getKind().equals(kind)) { matches.add(node); } } if (node.getChildren() != null) { for (Iterator it = node.getChildren().iterator(); it.hasNext(); ) { IProgramElement nextNode = (IProgramElement)it.next(); if (nextNode instanceof IProgramElement) { findMatchesHelper( (IProgramElement)nextNode, pattern, kind, matches); } } } return matches; } }
77,163
Bug 77163 Load time weaver default verbose setting
The default setting for the load time weaver is (as of 1.2.1rc1) to produce weaving messages rather than ignore them. I think the default should be changed to ignore them. Also, I cannot override the default setting with -Daj.weaver.versose="False". This is the implied syntax from docs/examples/build.xml. If this has changed then build.xml should be updated. Otherwise, the weaver should be fixed to use it!
resolved fixed
edd6539
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2004-11-05T11:00:41Z
2004-10-27T23:33:20Z
weaver/src/org/aspectj/weaver/tools/WeavingAdaptor.java
/* ******************************************************************* * Copyright (c) 2004 IBM Corporation * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Common Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * Matthew Webster, Adrian Colyer, * Martin Lippert initial implementation * ******************************************************************/ package org.aspectj.weaver.tools; import java.io.File; import java.io.IOException; import java.net.URL; import java.net.URLClassLoader; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.StringTokenizer; import org.aspectj.bridge.AbortException; import org.aspectj.bridge.IMessage; import org.aspectj.bridge.IMessageHandler; 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.BcelWeaver; import org.aspectj.weaver.bcel.BcelWorld; import org.aspectj.weaver.bcel.UnwovenClassFile; /** * This adaptor allows the AspectJ compiler to be embedded in an existing * system to facilitate load-time weaving. It provides an interface for a * weaving class loader to provide a classpath to be woven by a set of * aspects. A callback is supplied to allow a class loader to define classes * generated by the compiler during the weaving process. * <p> * A weaving class loader should create a <code>WeavingAdaptor</code> before * any classes are defined, typically during construction. The set of aspects * passed to the adaptor is fixed for the lifetime of the adaptor although the * classpath can be augmented. A system property can be set to allow verbose * weaving messages to be written to the console. * */ public class WeavingAdaptor { /** * System property used to turn on verbose weaving messages */ public static final String WEAVING_ADAPTOR_VERBOSE = "aj.weaving.verbose"; 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())) { System.err.println(message.getSourceLocation()+": "+message.getKind()+" "+message.getMessage()); if (message.getKind() == IMessage.ERROR) throw new AbortException(message); } return true; } public boolean isIgnoring(Kind kind) { if (verbose) return false; else 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() {} }; } } }
77,163
Bug 77163 Load time weaver default verbose setting
The default setting for the load time weaver is (as of 1.2.1rc1) to produce weaving messages rather than ignore them. I think the default should be changed to ignore them. Also, I cannot override the default setting with -Daj.weaver.versose="False". This is the implied syntax from docs/examples/build.xml. If this has changed then build.xml should be updated. Otherwise, the weaver should be fixed to use it!
resolved fixed
edd6539
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2004-11-05T11:00:41Z
2004-10-27T23:33: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 DW_ADVICE_ASPECTS = BcweaverTests.TESTDATA_PATH + "/ltw-dwaspects.jar"; private final static String DE_ADVICE_ASPECTS = BcweaverTests.TESTDATA_PATH + "/ltw-deaspects.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 testWeaveDeclareWarningAdvice () { System.setProperty(WeavingURLClassLoader.WEAVING_ASPECT_PATH,DW_ADVICE_ASPECTS); System.setProperty(WeavingURLClassLoader.WEAVING_CLASS_PATH,DW_ADVICE_ASPECTS + File.pathSeparator + 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 testWeaveDeclareErrorAdvice () { System.setProperty(WeavingURLClassLoader.WEAVING_ASPECT_PATH,DE_ADVICE_ASPECTS); System.setProperty(WeavingURLClassLoader.WEAVING_CLASS_PATH,DE_ADVICE_ASPECTS + File.pathSeparator + CLASSES_JAR); WeavingURLClassLoader loader = new WeavingURLClassLoader(getClass().getClassLoader()); try { Class clazz = loader.loadClass("LTWHelloWorld"); invokeMain(clazz,new String[] {} ); fail("Expecting org.aspectj.bridge.AbortException"); } catch (Exception ex) { assertTrue("Expecting org.aspectj.bridge.AbortException caught " + ex,(ex instanceof AbortException)); } } 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()); } } }
80,249
Bug 80249 Order of types passed to compiler determines weaving behavior
Currently, the order in which you specify types when passing them to the compiler can affect how they are woven: For example, if we have class A and class B extends A - Also, an aspect that 'declare parents: A+ implements Serializable' then depending on whether we see A first, we may or may not make B serializable. The fix is that when we weave a type, we first weave its supertype then its superinterfaces (if they were also passed to the compiler). The problematic construct is declare parents - so we only process the types in a special order if there are declare parents around. Also, because we can't currently do decp when binary weaving, the order processing logic is only being put into the source weaving pipeline.
resolved fixed
9052d5d
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2004-12-06T10:38:07Z
2004-12-06T10: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.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import org.aspectj.ajdt.internal.compiler.ast.AspectDeclaration; import org.aspectj.ajdt.internal.compiler.ast.PointcutDeclaration; import org.aspectj.bridge.IMessage; import org.aspectj.bridge.WeaveMessage; import org.aspectj.weaver.AsmRelationshipProvider; import org.aspectj.weaver.ConcreteTypeMunger; import org.aspectj.weaver.ResolvedTypeMunger; import org.aspectj.weaver.ResolvedTypeX; import org.aspectj.weaver.TypeX; import org.aspectj.weaver.WeaverStateInfo; import org.aspectj.weaver.World; import org.aspectj.weaver.bcel.LazyClassGen; import org.aspectj.weaver.patterns.DeclareParents; import org.aspectj.org.eclipse.jdt.core.compiler.CharOperation; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.TypeDeclaration; import org.aspectj.org.eclipse.jdt.internal.compiler.env.IBinaryType; import org.aspectj.org.eclipse.jdt.internal.compiler.env.INameEnvironment; import org.aspectj.org.eclipse.jdt.internal.compiler.impl.CompilerOptions; import org.aspectj.org.eclipse.jdt.internal.compiler.impl.ITypeRequestor; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.BinaryTypeBinding; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.ClassScope; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.CompilationUnitScope; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.LookupEnvironment; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.PackageBinding; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.ReferenceBinding; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.SourceTypeBinding; import org.aspectj.org.eclipse.jdt.internal.compiler.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); //TODO: Andy Should be done at weave time. // Unfortunately we can't do it at weave time unless the type mungers remember where // they came from. Thats why we do it here during complation because at this time // they do know their source location. I've put a flag in ResolvedTypeMunger that // records whether type mungers are currently set to remember their source location. // The flag is currently set to false, it should be set to true when we do the // work to version all AspectJ attributes. // (When done at weave time, it is done by invoking addRelationship() on // AsmRelationshipProvider (see BCELTypeMunger) if (!ResolvedTypeMunger.persistSourceLocation) // Do it up front if we bloody have to AsmInterTypeRelationshipProvider.getDefault().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); } AsmRelationshipProvider.getDefault().addDeclareParentsRelationship(declareParents.getSourceLocation(),factory.fromEclipse(sourceType), newParents); addParent(sourceType, parent); } } } private void reportDeclareParentsMessage(WeaveMessage.WeaveMessageKind wmk,SourceTypeBinding sourceType,ResolvedTypeX parent) { if (!factory.getWorld().getMessageHandler().isIgnoring(IMessage.WEAVEINFO)) { String filename = new String(sourceType.getFileName()); int takefrom = filename.lastIndexOf('/'); if (takefrom == -1 ) takefrom = filename.lastIndexOf('\\'); filename = filename.substring(takefrom+1); factory.getWorld().getMessageHandler().handleMessage( WeaveMessage.constructWeavingMessage(wmk, new String[]{CharOperation.toString(sourceType.compoundName), filename, parent.getClassName(), getShortname(parent.getSourceLocation().getSourceFile().getPath())})); } } private String getShortname(String path) { int takefrom = path.lastIndexOf('/'); if (takefrom == -1) { takefrom = path.lastIndexOf('\\'); } return path.substring(takefrom+1); } private void addParent(SourceTypeBinding sourceType, ResolvedTypeX parent) { ReferenceBinding parentBinding = (ReferenceBinding)factory.makeTypeBinding(parent); if (parentBinding.isClass()) { sourceType.superclass = parentBinding; // TAG: WeavingMessage DECLARE PARENTS: EXTENDS // Compiler restriction: Can't do EXTENDS at weave time // So, only see this message if doing a source compilation reportDeclareParentsMessage(WeaveMessage.WEAVEMESSAGE_DECLAREPARENTSEXTENDS,sourceType,parent); } else { ReferenceBinding[] oldI = sourceType.superInterfaces; ReferenceBinding[] newI; if (oldI == null) { newI = new ReferenceBinding[1]; newI[0] = parentBinding; } else { int n = oldI.length; newI = new ReferenceBinding[n+1]; System.arraycopy(oldI, 0, newI, 0, n); newI[n] = parentBinding; } sourceType.superInterfaces = newI; warnOnAddedInterface(factory.fromEclipse(sourceType),parent); // TAG: WeavingMessage DECLARE PARENTS: IMPLEMENTS // This message will come out of BcelTypeMunger.munge if doing a binary weave reportDeclareParentsMessage(WeaveMessage.WEAVEMESSAGE_DECLAREPARENTSIMPLEMENTS,sourceType,parent); } } public void warnOnAddedInterface (ResolvedTypeX type, ResolvedTypeX parent) { World world = factory.getWorld(); ResolvedTypeX serializable = world.getCoreType(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 inBinaryTypeCreationAndWeaving = false; boolean processingTheQueue = false; public BinaryTypeBinding createBinaryTypeFrom( IBinaryType binaryType, PackageBinding packageBinding, boolean needFieldsAndMethods) { if (inBinaryTypeCreationAndWeaving) { BinaryTypeBinding ret = super.createBinaryTypeFrom( binaryType, packageBinding, needFieldsAndMethods); pendingTypesToFinish.add(ret); return ret; } inBinaryTypeCreationAndWeaving = true; try { BinaryTypeBinding ret = super.createBinaryTypeFrom( binaryType, packageBinding, needFieldsAndMethods); weaveInterTypeDeclarations(ret); return ret; } finally { inBinaryTypeCreationAndWeaving = false; // Start processing the list... if (pendingTypesToFinish.size()>0) { processingTheQueue = true; while (!pendingTypesToFinish.isEmpty()) { BinaryTypeBinding nextVictim = (BinaryTypeBinding)pendingTypesToFinish.remove(0); // During this call we may recurse into this method and add // more entries to the pendingTypesToFinish list. weaveInterTypeDeclarations(nextVictim); } processingTheQueue = false; } } } }
80,249
Bug 80249 Order of types passed to compiler determines weaving behavior
Currently, the order in which you specify types when passing them to the compiler can affect how they are woven: For example, if we have class A and class B extends A - Also, an aspect that 'declare parents: A+ implements Serializable' then depending on whether we see A first, we may or may not make B serializable. The fix is that when we weave a type, we first weave its supertype then its superinterfaces (if they were also passed to the compiler). The problematic construct is declare parents - so we only process the types in a special order if there are declare parents around. Also, because we can't currently do decp when binary weaving, the order processing logic is only being put into the source weaving pipeline.
resolved fixed
9052d5d
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2004-12-06T10:38:07Z
2004-12-06T10:46:40Z
tests/decp/A.java
80,249
Bug 80249 Order of types passed to compiler determines weaving behavior
Currently, the order in which you specify types when passing them to the compiler can affect how they are woven: For example, if we have class A and class B extends A - Also, an aspect that 'declare parents: A+ implements Serializable' then depending on whether we see A first, we may or may not make B serializable. The fix is that when we weave a type, we first weave its supertype then its superinterfaces (if they were also passed to the compiler). The problematic construct is declare parents - so we only process the types in a special order if there are declare parents around. Also, because we can't currently do decp when binary weaving, the order processing logic is only being put into the source weaving pipeline.
resolved fixed
9052d5d
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2004-12-06T10:38:07Z
2004-12-06T10:46:40Z
tests/decp/AspectX.java
80,249
Bug 80249 Order of types passed to compiler determines weaving behavior
Currently, the order in which you specify types when passing them to the compiler can affect how they are woven: For example, if we have class A and class B extends A - Also, an aspect that 'declare parents: A+ implements Serializable' then depending on whether we see A first, we may or may not make B serializable. The fix is that when we weave a type, we first weave its supertype then its superinterfaces (if they were also passed to the compiler). The problematic construct is declare parents - so we only process the types in a special order if there are declare parents around. Also, because we can't currently do decp when binary weaving, the order processing logic is only being put into the source weaving pipeline.
resolved fixed
9052d5d
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2004-12-06T10:38:07Z
2004-12-06T10:46:40Z
tests/decp/B.java
80,249
Bug 80249 Order of types passed to compiler determines weaving behavior
Currently, the order in which you specify types when passing them to the compiler can affect how they are woven: For example, if we have class A and class B extends A - Also, an aspect that 'declare parents: A+ implements Serializable' then depending on whether we see A first, we may or may not make B serializable. The fix is that when we weave a type, we first weave its supertype then its superinterfaces (if they were also passed to the compiler). The problematic construct is declare parents - so we only process the types in a special order if there are declare parents around. Also, because we can't currently do decp when binary weaving, the order processing logic is only being put into the source weaving pipeline.
resolved fixed
9052d5d
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2004-12-06T10:38:07Z
2004-12-06T10:46:40Z
tests/src/org/aspectj/systemtest/ajc150/Ajc150Tests.java
/******************************************************************************* * Copyright (c) 2004 IBM * All rights reserved. This program and the accompanying materials * are made available under the terms of the Common Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * Andy Clement - initial API and implementation *******************************************************************************/ package org.aspectj.systemtest.ajc150; import java.io.File; import junit.framework.Test; import org.aspectj.testing.XMLBasedAjcTestCase; public class Ajc150Tests extends org.aspectj.testing.XMLBasedAjcTestCase { public static Test suite() { return XMLBasedAjcTestCase.loadSuite(Ajc150Tests.class); } protected File getSpecFile() { return new File("../tests/src/org/aspectj/systemtest/ajc150/ajc150.xml"); } public void test() { // placeholder for the first test... } }
80,916
Bug 80916 In some cases the structure model doesn't contain the "matches declare" relationship
With a project containing one class and one aspect: public class HelloClass { public static void main(String[] args) { new HelloClass().sayHello(); } public void sayHello() { System.out.println("Hello"); } } public aspect A1 { pointcut test() : get(* System.out); declare warning : test() && !within(A1) : "test warning"; pointcut anotherTest() : execution(void HelloClass.sayHello(..)); after() returning : anotherTest() { System.out.println("returning...."); } } The following is returned from the structure model: asmRelMap entry: HelloClass.sayHello(), relationship: advised by, target: A1.afterReturning(): anotherTest.. asmRelMap entry: A1.afterReturning(): anotherTest.., relationship: uses pointcut, target: A1.anotherTest() asmRelMap entry: A1.afterReturning(): anotherTest.., relationship: advises, target: HelloClass.sayHello() asmRelMap entry: HelloClass.sayHello(), relationship: advised by, target: A1.afterReturning(): anotherTest.. asmRelMap entry: A1.anotherTest(), relationship: pointcut used by, target: A1.afterReturning(): anotherTest.. asmRelMap entry: A1.declare warning: "test warning", relationship: matched by, target: HelloClass.sayHello() In other words, the model is saying that there are two entries the same: asmRelMap entry: HelloClass.sayHello(), relationship: advised by, target: A1.afterReturning(): anotherTest.. whereas one of these should be the "matches declare" relationship relating to the declare warning. Changing the aspect to be: public aspect A1 { pointcut test() : get(* System.out); declare warning : test() && !within(A1) : "test warning"; pointcut anotherTest() : execution(void HelloClass.sayHello(..)); after() returning : anotherTest() { System.out.println("returning...."); } after() returning : test() { System.out.println("returning again!"); } } means that the IRelationshipMap does now contain the "matches declare" relationship. This is all with AspectJ 5 M1.
resolved fixed
427c0d3
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2004-12-20T14:44:07Z
2004-12-14T10:26:40Z
weaver/src/org/aspectj/weaver/AsmRelationshipProvider.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.*; import java.util.ArrayList; import java.util.Iterator; import org.aspectj.asm.AsmManager; import org.aspectj.asm.IHierarchy; import org.aspectj.asm.IProgramElement; import org.aspectj.asm.IRelationship; import org.aspectj.asm.IRelationshipMap; import org.aspectj.asm.internal.ProgramElement; import org.aspectj.bridge.ISourceLocation; import org.aspectj.bridge.SourceLocation; import org.aspectj.weaver.bcel.BcelAdvice; public class AsmRelationshipProvider { protected static AsmRelationshipProvider INSTANCE = new AsmRelationshipProvider(); public static final String ADVISES = "advises"; public static final String ADVISED_BY = "advised by"; public static final String DECLARES_ON = "declares on"; public static final String DECLAREDY_BY = "declared by"; public static final String MATCHED_BY = "matched by"; public static final String MATCHES_DECLARE = "matches declare"; public static final String INTER_TYPE_DECLARES = "declared on"; public static final String INTER_TYPE_DECLARED_BY = "aspect declarations"; public void checkerMunger(IHierarchy model, Shadow shadow, Checker checker) { if (shadow.getSourceLocation() == null || checker.getSourceLocation() == null) return; String sourceHandle = ProgramElement.createHandleIdentifier( checker.getSourceLocation().getSourceFile(), checker.getSourceLocation().getLine(), checker.getSourceLocation().getColumn(), checker.getSourceLocation().getOffset()); String targetHandle = ProgramElement.createHandleIdentifier( shadow.getSourceLocation().getSourceFile(), shadow.getSourceLocation().getLine(), shadow.getSourceLocation().getColumn(), shadow.getSourceLocation().getOffset()); IRelationshipMap mapper = AsmManager.getDefault().getRelationshipMap(); if (sourceHandle != null && targetHandle != null) { IRelationship foreward = mapper.get(sourceHandle, IRelationship.Kind.DECLARE, MATCHED_BY,false,true); foreward.addTarget(targetHandle); // foreward.getTargets().add(targetHandle); IRelationship back = mapper.get(targetHandle, IRelationship.Kind.DECLARE, MATCHES_DECLARE,false,true); if (back != null && back.getTargets() != null) { back.addTarget(sourceHandle); //back.getTargets().add(sourceHandle); } } } // For ITDs public void addRelationship( ResolvedTypeX onType, ResolvedTypeMunger munger, ResolvedTypeX originatingAspect) { String sourceHandle = ""; if (munger.getSourceLocation()!=null) { sourceHandle = ProgramElement.createHandleIdentifier( munger.getSourceLocation().getSourceFile(), munger.getSourceLocation().getLine(), munger.getSourceLocation().getColumn(), munger.getSourceLocation().getOffset()); } else { sourceHandle = ProgramElement.createHandleIdentifier( originatingAspect.getSourceLocation().getSourceFile(), originatingAspect.getSourceLocation().getLine(), originatingAspect.getSourceLocation().getColumn(), originatingAspect.getSourceLocation().getOffset()); } if (originatingAspect.getSourceLocation() != null) { String targetHandle = ProgramElement.createHandleIdentifier( onType.getSourceLocation().getSourceFile(), onType.getSourceLocation().getLine(), onType.getSourceLocation().getColumn(), onType.getSourceLocation().getOffset()); IRelationshipMap mapper = AsmManager.getDefault().getRelationshipMap(); if (sourceHandle != null && targetHandle != null) { IRelationship foreward = mapper.get(sourceHandle, IRelationship.Kind.DECLARE_INTER_TYPE, INTER_TYPE_DECLARES,false,true); foreward.addTarget(targetHandle); // foreward.getTargets().add(targetHandle); IRelationship back = mapper.get(targetHandle, IRelationship.Kind.DECLARE_INTER_TYPE, INTER_TYPE_DECLARED_BY,false,true); back.addTarget(sourceHandle); // back.getTargets().add(sourceHandle); } } } public void addDeclareParentsRelationship(ISourceLocation decp,ResolvedTypeX targetType, List newParents) { String sourceHandle = ProgramElement.createHandleIdentifier(decp.getSourceFile(),decp.getLine(),decp.getColumn(),decp.getOffset()); IProgramElement ipe = AsmManager.getDefault().getHierarchy().findElementForHandle(sourceHandle); String targetHandle = ProgramElement.createHandleIdentifier( targetType.getSourceLocation().getSourceFile(), targetType.getSourceLocation().getLine(), targetType.getSourceLocation().getColumn(), targetType.getSourceLocation().getOffset()); IRelationshipMap mapper = AsmManager.getDefault().getRelationshipMap(); if (sourceHandle != null && targetHandle != null) { IRelationship foreward = mapper.get(sourceHandle, IRelationship.Kind.DECLARE_INTER_TYPE, INTER_TYPE_DECLARES,false,true); foreward.addTarget(targetHandle); IRelationship back = mapper.get(targetHandle, IRelationship.Kind.DECLARE_INTER_TYPE, INTER_TYPE_DECLARED_BY,false,true); back.addTarget(sourceHandle); } } public void adviceMunger(IHierarchy model, Shadow shadow, ShadowMunger munger) { if (munger instanceof Advice) { Advice advice = (Advice)munger; if (advice.getKind().isPerEntry() || advice.getKind().isCflow()) { // TODO: might want to show these in the future return; } IRelationshipMap mapper = AsmManager.getDefault().getRelationshipMap(); IProgramElement targetNode = getNode(AsmManager.getDefault().getHierarchy(), shadow); boolean runtimeTest = ((BcelAdvice)munger).hasDynamicTests(); // Work out extra info to inform interested UIs ! IProgramElement.ExtraInformation ai = new IProgramElement.ExtraInformation(); String adviceHandle = advice.getHandle(); // What kind of advice is it? // TODO: Prob a better way to do this but I just want to // get it into CVS !!! AdviceKind ak = ((Advice)munger).getKind(); ai.setExtraAdviceInformation(ak.getName()); IProgramElement adviceElement = AsmManager.getDefault().getHierarchy().findElementForHandle(adviceHandle); adviceElement.setExtraInfo(ai); if (adviceHandle != null && targetNode != null) { if (targetNode != null) { String targetHandle = targetNode.getHandleIdentifier(); IRelationship foreward = mapper.get(adviceHandle, IRelationship.Kind.ADVICE, ADVISES,runtimeTest,true); if (foreward != null) foreward.addTarget(targetHandle);//foreward.getTargets().add(targetHandle); IRelationship back = mapper.get(targetHandle, IRelationship.Kind.ADVICE, ADVISED_BY,runtimeTest,true); if (back != null) back.addTarget(adviceHandle);//back.getTargets().add(adviceHandle); } } } } protected IProgramElement getNode(IHierarchy model, Shadow shadow) { Member enclosingMember = shadow.getEnclosingCodeSignature(); IProgramElement enclosingNode = lookupMember(model, enclosingMember); if (enclosingNode == null) { Lint.Kind err = shadow.getIWorld().getLint().shadowNotInStructure; if (err.isEnabled()) { err.signal(shadow.toString(), shadow.getSourceLocation()); } return null; } Member shadowSig = shadow.getSignature(); if (!shadowSig.equals(enclosingMember)) { IProgramElement bodyNode = findOrCreateCodeNode(enclosingNode, shadowSig, shadow); return bodyNode; } else { return enclosingNode; } } private boolean sourceLinesMatch(ISourceLocation loc1,ISourceLocation loc2) { if (loc1.getLine()!=loc2.getLine()) return false; return true; } private IProgramElement findOrCreateCodeNode(IProgramElement enclosingNode, Member shadowSig, Shadow shadow) { for (Iterator it = enclosingNode.getChildren().iterator(); it.hasNext(); ) { IProgramElement node = (IProgramElement)it.next(); if (shadowSig.getName().equals(node.getBytecodeName()) && shadowSig.getSignature().equals(node.getBytecodeSignature()) && sourceLinesMatch(node.getSourceLocation(),shadow.getSourceLocation())) { return node; } } ISourceLocation sl = shadow.getSourceLocation(); // XXX why not use shadow file? new SourceLocation(sl.getSourceFile(), sl.getLine()), SourceLocation peLoc = new SourceLocation(enclosingNode.getSourceLocation().getSourceFile(),sl.getLine()); peLoc.setOffset(sl.getOffset()); IProgramElement peNode = new ProgramElement( shadow.toString(), IProgramElement.Kind.CODE, peLoc, 0, "", new ArrayList()); peNode.setBytecodeName(shadowSig.getName()); peNode.setBytecodeSignature(shadowSig.getSignature()); enclosingNode.addChild(peNode); return peNode; } protected IProgramElement lookupMember(IHierarchy model, Member member) { TypeX declaringType = member.getDeclaringType(); IProgramElement classNode = model.findElementForType(declaringType.getPackageName(), declaringType.getClassName()); return findMemberInClass(classNode, member); } protected IProgramElement findMemberInClass( IProgramElement classNode, Member member) { if (classNode == null) return null; // XXX remove this check for (Iterator it = classNode.getChildren().iterator(); it.hasNext(); ) { IProgramElement node = (IProgramElement)it.next(); if (member.getName().equals(node.getBytecodeName()) && member.getSignature().equals(node.getBytecodeSignature())) { return node; } } // if we can't find the member, we'll just put it in the class return classNode; } // private static IProgramElement.Kind genShadowKind(Shadow shadow) { // IProgramElement.Kind shadowKind; // if (shadow.getKind() == Shadow.MethodCall // || shadow.getKind() == Shadow.ConstructorCall // || shadow.getKind() == Shadow.FieldGet // || shadow.getKind() == Shadow.FieldSet // || shadow.getKind() == Shadow.ExceptionHandler) { // return IProgramElement.Kind.CODE; // // } else if (shadow.getKind() == Shadow.MethodExecution) { // return IProgramElement.Kind.METHOD; // // } else if (shadow.getKind() == Shadow.ConstructorExecution) { // return IProgramElement.Kind.CONSTRUCTOR; // // } else if (shadow.getKind() == Shadow.PreInitialization // || shadow.getKind() == Shadow.Initialization) { // return IProgramElement.Kind.CLASS; // // } else if (shadow.getKind() == Shadow.AdviceExecution) { // return IProgramElement.Kind.ADVICE; // // } else { // return IProgramElement.Kind.ERROR; // } // } public static AsmRelationshipProvider getDefault() { return INSTANCE; } /** * Reset the instance of this class, intended for extensibility. * This enables a subclass to become used as the default instance. */ public static void setDefault(AsmRelationshipProvider instance) { INSTANCE = instance; } }
82,062
Bug 82062 WeaveMessage should provide more information
It would be wonderful if the WeaveMessage object would provide two additional things: - the affected class name - the aspect name I could use this to determine which aspect is woven into which class during load-time weaving (need this for dependency management).
resolved fixed
9897659
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-01-04T13:15:57Z
2005-01-01T20:06:40Z
bridge/src/org/aspectj/bridge/WeaveMessage.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: * Andy Clement IBM initial implementation 30-May-2004 * ******************************************************************/ package org.aspectj.bridge; public class WeaveMessage extends Message { // Kinds of weaving message we can produce public static WeaveMessageKind WEAVEMESSAGE_DECLAREPARENTSIMPLEMENTS = new WeaveMessageKind(1,"Extending interface set for type '%1' (%2) to include '%3' (%4)"); public static WeaveMessageKind WEAVEMESSAGE_ITD = new WeaveMessageKind(2,"Type '%1' (%2) has intertyped %3 from '%4' (%5)"); // %6 is information like "[with runtime test]" public static WeaveMessageKind WEAVEMESSAGE_ADVISES = new WeaveMessageKind(3,"Type '%1' (%2) advised by %3 advice from '%4' (%5)%6"); public static WeaveMessageKind WEAVEMESSAGE_DECLAREPARENTSEXTENDS = new WeaveMessageKind(4,"Setting superclass of type '%1' (%2) to '%3' (%4)"); public static WeaveMessageKind WEAVEMESSAGE_SOFTENS = new WeaveMessageKind(5,"Softening exceptions in type '%1' (%2) as defined by aspect '%3' (%4)"); // private ctor - use the static factory method private WeaveMessage(String message) { super(message, IMessage.WEAVEINFO, null, null); } /** * Static helper method for constructing weaving messages. * @param kind what kind of message (e.g. declare parents) * @param inserts inserts for the message (inserts are marked %n in the message) * @param affectedtypename the type which is being advised/declaredUpon * @param aspectname the aspect that defined the advice or declares * @return new weaving message */ public static WeaveMessage constructWeavingMessage( WeaveMessageKind kind, String[] inserts) { StringBuffer str = new StringBuffer(kind.getMessage()); int pos = -1; while ((pos=new String(str).indexOf("%"))!=-1) { int n = Character.getNumericValue(str.charAt(pos+1)); str.replace(pos,pos+2,inserts[n-1]); } return new WeaveMessage(str.toString()); } public static class WeaveMessageKind { private int id; private String message; public WeaveMessageKind(int id,String message) { this.id = id; this.message = message; } public String getMessage() { return message; } } }
82,062
Bug 82062 WeaveMessage should provide more information
It would be wonderful if the WeaveMessage object would provide two additional things: - the affected class name - the aspect name I could use this to determine which aspect is woven into which class during load-time weaving (need this for dependency management).
resolved fixed
9897659
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-01-04T13:15:57Z
2005-01-01T20:06:40Z
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.bridge.ISourceLocation; 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,IHasSourceLocation loc) { Advice ret = world.concreteAdvice(AdviceKind.Softener, entry, null, 0, loc); 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, WeaverMessages.format(WeaverMessages.ONLY_BEFORE_ON_HANDLER), 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, WeaverMessages.format(WeaverMessages.AROUND_ON_PREINIT), getSourceLocation(), shadow.getSourceLocation()); return false; } else if (shadow.getKind() == Shadow.Initialization) { world.showMessage(IMessage.ERROR, WeaverMessages.format(WeaverMessages.AROUND_ON_INIT), getSourceLocation(), shadow.getSourceLocation()); return false; } else if (shadow.getKind() == Shadow.StaticInitialization && shadow.getEnclosingType().isInterface(world)) { world.showMessage(IMessage.ERROR, WeaverMessages.format(WeaverMessages.AROUND_ON_INTERFACE_STATICINIT,shadow.getEnclosingType().getName()), 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, WeaverMessages.format(WeaverMessages.NON_VOID_RETURN,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, WeaverMessages.format(WeaverMessages.INCOMPATIBLE_RETURN_TYPE,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 String[] getBaseParameterNames(World world) { String[] allNames = getSignature().getParameterNames(world); int extras = getExtraParameterCount(); if (extras == 0) return allNames; String[] result = new String[getBaseParameterCount()]; for (int i = 0; i < result.length; i++) { result[i] = allNames[i]; } return result; } 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) { Pointcut oldP = p; p = new AndPointcut(clause, p); p.copyLocationFrom(oldP); 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; } }
82,062
Bug 82062 WeaveMessage should provide more information
It would be wonderful if the WeaveMessage object would provide two additional things: - the affected class name - the aspect name I could use this to determine which aspect is woven into which class during load-time weaving (need this for dependency management).
resolved fixed
9897659
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-01-04T13:15:57Z
2005-01-01T20:06:40Z
weaver/src/org/aspectj/weaver/Shadow.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Common Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * PARC initial implementation * ******************************************************************/ package org.aspectj.weaver; import java.io.DataInputStream; import java.io.IOException; import java.util.ArrayList; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Set; 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; import org.aspectj.weaver.bcel.BcelAdvice; /* * The superclass of anything representing a the shadow of a join point. A shadow represents * some bit of code, and encompasses both entry and exit from that code. All shadows have a kind * and a signature. */ public abstract class Shadow { // every Shadow has a unique id, doesn't matter if it wraps... private static int nextShadowID = 100; // easier to spot than zero. private final Kind kind; private final Member signature; protected final Shadow enclosingShadow; protected List mungers = new ArrayList(1); public int shadowId = nextShadowID++; // every time we build a shadow, it gets a new id // ---- protected Shadow(Kind kind, Member signature, Shadow enclosingShadow) { this.kind = kind; this.signature = signature; this.enclosingShadow = enclosingShadow; } // ---- public abstract World getIWorld(); public List /*ShadowMunger*/ getMungers() { return mungers; } /** * could this(*) pcd ever match */ public final boolean hasThis() { if (getKind().neverHasThis()) { return false; } else if (getKind().isEnclosingKind()) { return !getSignature().isStatic(); } else if (enclosingShadow == null) { return false; } else { return enclosingShadow.hasThis(); } } /** * the type of the this object here * * @throws IllegalStateException if there is no this here */ public final 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(); // annotation variables public abstract Var getKindedAnnotationVar(TypeX forAnnotationType); public abstract Var getWithinAnnotationVar(TypeX forAnnotationType); public abstract Var getWithinCodeAnnotationVar(TypeX forAnnotationType); public abstract Var getThisAnnotationVar(TypeX forAnnotationType); public abstract Var getTargetAnnotationVar(TypeX forAnnotationType); public abstract Var getArgAnnotationVar(int i, TypeX forAnnotationType); public abstract Member getEnclosingCodeSignature(); /** returns the kind of shadow this is, representing what happens under this shadow */ public Kind getKind() { return kind; } /** returns the signature of the thing under this shadow */ public Member getSignature() { return signature; } 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, }; public static final Set ALL_SHADOW_KINDS = new HashSet(); static { for (int i = 0; i < SHADOW_KINDS.length; i++) { ALL_SHADOW_KINDS.add(SHADOW_KINDS[i]); } } /** 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, WeaverMessages.format(WeaverMessages.CANT_THROW_CHECKED,resolvedTypeX,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( WeaverMessages.format(WeaverMessages.CIRCULAR_DEPENDENCY,this), m.getSourceLocation())); } } mungers = sorted; } /** Prepare the shadow for implementation. After this is done, the shadow * should be in such a position that each munger simply needs to be implemented. */ protected void prepareForMungers() { throw new RuntimeException("Generic shadows cannot be prepared"); } /* * Ensure we report a nice source location - particular in the case * where the source info is missing (binary weave). */ private String beautifyLocation(ISourceLocation isl) { StringBuffer nice = new StringBuffer(); if (isl==null || isl.getSourceFile()==null || isl.getSourceFile().getName().indexOf("no debug info available")!=-1) { nice.append("no debug info available"); } else { // can't use File.getName() as this fails when a Linux box encounters a path created on Windows and vice-versa int takeFrom = isl.getSourceFile().getPath().lastIndexOf('/'); if (takeFrom == -1) { takeFrom = isl.getSourceFile().getPath().lastIndexOf('\\'); } nice.append(isl.getSourceFile().getPath().substring(takeFrom +1)); if (isl.getLine()!=0) nice.append(":").append(isl.getLine()); } return nice.toString(); } /* * Report a message about the advice weave that has occurred. Some messing about * to make it pretty ! This code is just asking for an NPE to occur ... */ private void reportWeavingMessage(ShadowMunger munger) { Advice advice = (Advice)munger; AdviceKind aKind = advice.getKind(); // Only report on interesting advice kinds ... if (aKind == null || advice.getConcreteAspect()==null) { // We suspect someone is programmatically driving the weaver // (e.g. IdWeaveTestCase in the weaver testcases) return; } if (!( aKind.equals(AdviceKind.Before) || aKind.equals(AdviceKind.After) || aKind.equals(AdviceKind.AfterReturning) || aKind.equals(AdviceKind.AfterThrowing) || aKind.equals(AdviceKind.Around) || aKind.equals(AdviceKind.Softener))) return; String description = advice.getKind().toString(); String advisedType = this.getEnclosingType().getName(); String advisingType= advice.getConcreteAspect().getName(); Message msg = null; if (advice.getKind().equals(AdviceKind.Softener)) { msg = WeaveMessage.constructWeavingMessage( WeaveMessage.WEAVEMESSAGE_SOFTENS, new String[]{advisedType,beautifyLocation(getSourceLocation()), advisingType,beautifyLocation(munger.getSourceLocation())}); } else { boolean runtimeTest = ((BcelAdvice)advice).hasDynamicTests(); msg = WeaveMessage.constructWeavingMessage(WeaveMessage.WEAVEMESSAGE_ADVISES, new String[]{ advisedType, beautifyLocation(getSourceLocation()), description, advisingType,beautifyLocation(munger.getSourceLocation()), (runtimeTest?" [with runtime test]":"")}); // Boolean.toString(runtimeTest)}); } getIWorld().getMessageHandler().handleMessage(msg); } public IRelationship.Kind determineRelKind(ShadowMunger munger) { AdviceKind ak = ((Advice)munger).getKind(); if (ak.getKey()==AdviceKind.Before.getKey()) return IRelationship.Kind.ADVICE_BEFORE; else if (ak.getKey()==AdviceKind.After.getKey()) return IRelationship.Kind.ADVICE_AFTER; else if (ak.getKey()==AdviceKind.AfterThrowing.getKey()) return IRelationship.Kind.ADVICE_AFTERTHROWING; else if (ak.getKey()==AdviceKind.AfterReturning.getKey()) return IRelationship.Kind.ADVICE_AFTERRETURNING; else if (ak.getKey()==AdviceKind.Around.getKey()) return IRelationship.Kind.ADVICE_AROUND; else if (ak.getKey()==AdviceKind.CflowEntry.getKey() || ak.getKey()==AdviceKind.CflowBelowEntry.getKey() || ak.getKey()==AdviceKind.InterInitializer.getKey() || ak.getKey()==AdviceKind.PerCflowEntry.getKey() || ak.getKey()==AdviceKind.PerCflowBelowEntry.getKey() || ak.getKey()==AdviceKind.PerThisEntry.getKey() || ak.getKey()==AdviceKind.PerTargetEntry.getKey() || ak.getKey()==AdviceKind.Softener.getKey()) { System.err.println("Dont want a message about this: "+ak); return null; } throw new RuntimeException("Shadow.determineRelKind: What the hell is it? "+ak); } /** Actually implement the (non-empty) mungers associated with this shadow */ private void implementMungers() { World world = getIWorld(); for (Iterator iter = mungers.iterator(); iter.hasNext();) { ShadowMunger munger = (ShadowMunger) iter.next(); munger.implementOn(this); if (world.xrefHandler != null) { world.xrefHandler.addCrossReference( munger.getSourceLocation(), // What is being applied this.getSourceLocation(), // Where is it being applied determineRelKind(munger), // What kind of advice? ((BcelAdvice)munger).hasDynamicTests() // Is a runtime test being stuffed in the code? ); } // TAG: WeavingMessage if (!getIWorld().getMessageHandler().isIgnoring(IMessage.WEAVEINFO)) { reportWeavingMessage(munger); } if (world.getModel() != null) { //System.err.println("munger: " + munger + " on " + this); AsmRelationshipProvider.getDefault().adviceMunger(world.getModel(), this, munger); } } } public String makeReflectiveFactoryString() { return null; //XXX } public abstract ISourceLocation getSourceLocation(); // ---- utility public String toString() { return getKind() + "(" + getSignature() + ")"; // + getSourceLines(); } }
82,062
Bug 82062 WeaveMessage should provide more information
It would be wonderful if the WeaveMessage object would provide two additional things: - the affected class name - the aspect name I could use this to determine which aspect is woven into which class during load-time weaving (need this for dependency management).
resolved fixed
9897659
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-01-04T13:15:57Z
2005-01-01T20:06:40Z
weaver/src/org/aspectj/weaver/bcel/BcelTypeMunger.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the 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.Iterator; import java.util.Set; import org.aspectj.apache.bcel.Constants; import org.aspectj.apache.bcel.generic.FieldGen; import org.aspectj.apache.bcel.generic.InstructionConstants; import org.aspectj.apache.bcel.generic.InstructionFactory; import org.aspectj.apache.bcel.generic.InstructionList; import org.aspectj.apache.bcel.generic.Type; import org.aspectj.bridge.IMessage; import org.aspectj.bridge.ISourceLocation; import org.aspectj.bridge.MessageUtil; import org.aspectj.bridge.WeaveMessage; import org.aspectj.weaver.AjcMemberMaker; import org.aspectj.weaver.AsmRelationshipProvider; import org.aspectj.weaver.ConcreteTypeMunger; import org.aspectj.weaver.Member; import org.aspectj.weaver.NameMangler; import org.aspectj.weaver.NewConstructorTypeMunger; import org.aspectj.weaver.NewFieldTypeMunger; import org.aspectj.weaver.NewMethodTypeMunger; import org.aspectj.weaver.NewParentTypeMunger; import org.aspectj.weaver.PerObjectInterfaceTypeMunger; import org.aspectj.weaver.PrivilegedAccessMunger; import org.aspectj.weaver.ResolvedMember; import org.aspectj.weaver.ResolvedTypeMunger; import org.aspectj.weaver.ResolvedTypeX; import org.aspectj.weaver.TypeX; import org.aspectj.weaver.WeaverMessages; import org.aspectj.weaver.WeaverStateInfo; import org.aspectj.weaver.patterns.Pointcut; //XXX addLazyMethodGen is probably bad everywhere public class BcelTypeMunger extends ConcreteTypeMunger { public BcelTypeMunger(ResolvedTypeMunger munger, ResolvedTypeX aspectType) { super(munger, aspectType); } public String toString() { return "(BcelTypeMunger " + getMunger() + ")"; } public boolean munge(BcelClassWeaver weaver) { boolean changed = false; boolean worthReporting = true; if (munger.getKind() == ResolvedTypeMunger.Field) { changed = mungeNewField(weaver, (NewFieldTypeMunger)munger); } else if (munger.getKind() == ResolvedTypeMunger.Method) { changed = mungeNewMethod(weaver, (NewMethodTypeMunger)munger); } else if (munger.getKind() == ResolvedTypeMunger.PerObjectInterface) { changed = mungePerObjectInterface(weaver, (PerObjectInterfaceTypeMunger)munger); worthReporting = false; } else if (munger.getKind() == ResolvedTypeMunger.PrivilegedAccess) { changed = mungePrivilegedAccess(weaver, (PrivilegedAccessMunger)munger); worthReporting = false; } else if (munger.getKind() == ResolvedTypeMunger.Constructor) { changed = mungeNewConstructor(weaver, (NewConstructorTypeMunger)munger); } else if (munger.getKind() == ResolvedTypeMunger.Parent) { changed = mungeNewParent(weaver, (NewParentTypeMunger)munger); } else { throw new RuntimeException("unimplemented"); } if (changed && munger.changesPublicSignature()) { WeaverStateInfo info = weaver.getLazyClassGen().getOrCreateWeaverStateInfo(); info.addConcreteMunger(this); } // Whilst type mungers aren't persisting their source locations, we add this relationship during // compilation time (see other reference to ResolvedTypeMunger.persist) if (ResolvedTypeMunger.persistSourceLocation) { if (changed) { if (munger.getKind().equals(ResolvedTypeMunger.Parent)) { AsmRelationshipProvider.getDefault().addRelationship(weaver.getLazyClassGen().getType(), munger,getAspectType()); } else { AsmRelationshipProvider.getDefault().addRelationship(weaver.getLazyClassGen().getType(), munger,getAspectType()); } } } // TAG: WeavingMessage if (changed && worthReporting && munger!=null && !weaver.getWorld().getMessageHandler().isIgnoring(IMessage.WEAVEINFO)) { String tName = weaver.getLazyClassGen().getType().getSourceLocation().getSourceFile().getName(); if (tName.indexOf("no debug info available")!=-1) tName = "no debug info available"; else tName = getShortname(weaver.getLazyClassGen().getType().getSourceLocation().getSourceFile().getPath()); String fName = getShortname(getAspectType().getSourceLocation().getSourceFile().getPath()); if (munger.getKind().equals(ResolvedTypeMunger.Parent)) { // This message will come out of AjLookupEnvironment.addParent if doing a source // compilation. NewParentTypeMunger parentTM = (NewParentTypeMunger)munger; if (parentTM.getNewParent().isInterface()) { weaver.getWorld().getMessageHandler().handleMessage(WeaveMessage.constructWeavingMessage(WeaveMessage.WEAVEMESSAGE_DECLAREPARENTSIMPLEMENTS, new String[]{weaver.getLazyClassGen().getType().getName(), tName,parentTM.getNewParent().getName(),fName})); } else { System.err.println("BANG, you need to fix this. BcelTypeMunger"); } } else { weaver.getWorld().getMessageHandler().handleMessage(WeaveMessage.constructWeavingMessage(WeaveMessage.WEAVEMESSAGE_ITD, new String[]{weaver.getLazyClassGen().getType().getName(), tName,munger.getKind().toString().toLowerCase(), getAspectType().getName(), fName+":'"+munger.getSignature()+"'"})); // ??? If only type mungers knew their originating line numbers ... } } return changed; } private String getShortname(String path) { int takefrom = path.lastIndexOf('/'); if (takefrom == -1) { takefrom = path.lastIndexOf('\\'); } return path.substring(takefrom+1); } private boolean mungeNewParent(BcelClassWeaver weaver, NewParentTypeMunger munger) { LazyClassGen gen = weaver.getLazyClassGen(); ResolvedTypeX newParent = munger.getNewParent(); if (newParent.isClass()) { //gen.setSuperClass(newParent); } else { gen.addInterface(newParent,getSourceLocation()); } return true; } private boolean mungePrivilegedAccess( BcelClassWeaver weaver, PrivilegedAccessMunger munger) { LazyClassGen gen = weaver.getLazyClassGen(); ResolvedMember member = munger.getMember(); ResolvedTypeX onType = weaver.getWorld().resolve(member.getDeclaringType(),munger.getSourceLocation()); //System.out.println("munging: " + gen + " with " + member); if (onType.equals(gen.getType())) { if (member.getKind() == Member.FIELD) { //System.out.println("matched: " + gen); addFieldGetter(gen, member, AjcMemberMaker.privilegedAccessMethodForFieldGet(aspectType, member)); addFieldSetter(gen, member, AjcMemberMaker.privilegedAccessMethodForFieldSet(aspectType, member)); return true; } else if (member.getKind() == Member.METHOD) { addMethodDispatch(gen, member, AjcMemberMaker.privilegedAccessMethodForMethod(aspectType, member)); return true; } else if (member.getKind() == Member.CONSTRUCTOR) { for (Iterator i = gen.getMethodGens().iterator(); i.hasNext(); ) { LazyMethodGen m = (LazyMethodGen)i.next(); if (m.getMemberView() != null && m.getMemberView().getKind() == Member.CONSTRUCTOR) { // m.getMemberView().equals(member)) { m.forcePublic(); //return true; } } return true; //throw new BCException("no match for " + member + " in " + gen); } else if (member.getKind() == Member.STATIC_INITIALIZATION) { gen.forcePublic(); return true; } else { throw new RuntimeException("unimplemented"); } } return false; } private void addFieldGetter( LazyClassGen gen, ResolvedMember field, ResolvedMember accessMethod) { LazyMethodGen mg = makeMethodGen(gen, accessMethod); InstructionList il = new InstructionList(); InstructionFactory fact = gen.getFactory(); if (field.isStatic()) { il.append(fact.createFieldAccess( gen.getClassName(), field.getName(), BcelWorld.makeBcelType(field.getType()), Constants.GETSTATIC)); } else { il.append(InstructionConstants.ALOAD_0); il.append(fact.createFieldAccess( gen.getClassName(), field.getName(), BcelWorld.makeBcelType(field.getType()), Constants.GETFIELD)); } il.append(InstructionFactory.createReturn(BcelWorld.makeBcelType(field.getType()))); mg.getBody().insert(il); gen.addMethodGen(mg,getSignature().getSourceLocation()); } private void addFieldSetter( LazyClassGen gen, ResolvedMember field, ResolvedMember accessMethod) { LazyMethodGen mg = makeMethodGen(gen, accessMethod); InstructionList il = new InstructionList(); InstructionFactory fact = gen.getFactory(); Type fieldType = BcelWorld.makeBcelType(field.getType()); if (field.isStatic()) { il.append(InstructionFactory.createLoad(fieldType, 0)); il.append(fact.createFieldAccess( gen.getClassName(), field.getName(), fieldType, Constants.PUTSTATIC)); } else { il.append(InstructionConstants.ALOAD_0); il.append(InstructionFactory.createLoad(fieldType, 1)); il.append(fact.createFieldAccess( gen.getClassName(), field.getName(), fieldType, Constants.PUTFIELD)); } il.append(InstructionFactory.createReturn(Type.VOID)); mg.getBody().insert(il); gen.addMethodGen(mg,getSignature().getSourceLocation()); } private void addMethodDispatch( LazyClassGen gen, ResolvedMember method, ResolvedMember accessMethod) { LazyMethodGen mg = makeMethodGen(gen, accessMethod); InstructionList il = new InstructionList(); InstructionFactory fact = gen.getFactory(); //Type fieldType = BcelWorld.makeBcelType(field.getType()); Type[] paramTypes = BcelWorld.makeBcelTypes(method.getParameterTypes()); int pos = 0; if (!method.isStatic()) { il.append(InstructionConstants.ALOAD_0); pos++; } for (int i = 0, len = paramTypes.length; i < len; i++) { Type paramType = paramTypes[i]; il.append(InstructionFactory.createLoad(paramType, pos)); pos+=paramType.getSize(); } il.append(Utility.createInvoke(fact, (BcelWorld)aspectType.getWorld(), method)); il.append(InstructionFactory.createReturn(BcelWorld.makeBcelType(method.getReturnType()))); mg.getBody().insert(il); gen.addMethodGen(mg); } private LazyMethodGen makeMethodGen(LazyClassGen gen, ResolvedMember member) { LazyMethodGen ret = new LazyMethodGen( member.getModifiers(), BcelWorld.makeBcelType(member.getReturnType()), member.getName(), BcelWorld.makeBcelTypes(member.getParameterTypes()), TypeX.getNames(member.getExceptions()), gen); // 43972 : Static crosscutting makes interfaces unusable for javac // ret.makeSynthetic(); return ret; } private FieldGen makeFieldGen(LazyClassGen gen, ResolvedMember member) { return new FieldGen( member.getModifiers(), BcelWorld.makeBcelType(member.getReturnType()), member.getName(), gen.getConstantPoolGen()); } private boolean mungePerObjectInterface( BcelClassWeaver weaver, PerObjectInterfaceTypeMunger munger) { LazyClassGen gen = weaver.getLazyClassGen(); if (couldMatch(gen.getBcelObjectType(), munger.getTestPointcut())) { FieldGen fg = makeFieldGen(gen, AjcMemberMaker.perObjectField(gen.getType(), aspectType)); gen.addField(fg.getField(),getSourceLocation()); Type fieldType = BcelWorld.makeBcelType(aspectType); LazyMethodGen mg = new LazyMethodGen( Modifier.PUBLIC, fieldType, NameMangler.perObjectInterfaceGet(aspectType), new Type[0], new String[0], gen); InstructionList il = new InstructionList(); InstructionFactory fact = gen.getFactory(); il.append(InstructionConstants.ALOAD_0); il.append(fact.createFieldAccess( gen.getClassName(), fg.getName(), fieldType, Constants.GETFIELD)); il.append(InstructionFactory.createReturn(fieldType)); mg.getBody().insert(il); gen.addMethodGen(mg); LazyMethodGen mg1 = new LazyMethodGen( Modifier.PUBLIC, Type.VOID, NameMangler.perObjectInterfaceSet(aspectType), new Type[]{fieldType,}, new String[0], gen); InstructionList il1 = new InstructionList(); il1.append(InstructionConstants.ALOAD_0); il1.append(InstructionFactory.createLoad(fieldType, 1)); il1.append(fact.createFieldAccess( gen.getClassName(), fg.getName(), fieldType, Constants.PUTFIELD)); il1.append(InstructionFactory.createReturn(Type.VOID)); mg1.getBody().insert(il1); gen.addMethodGen(mg1); gen.addInterface(munger.getInterfaceType(),getSourceLocation()); return true; } else { return false; } } private boolean couldMatch( BcelObjectType bcelObjectType, Pointcut pointcut) { return !bcelObjectType.isInterface(); } private boolean mungeNewMethod(BcelClassWeaver weaver, NewMethodTypeMunger munger) { ResolvedMember signature = munger.getSignature(); ResolvedMember dispatchMethod = munger.getDispatchMethod(aspectType); LazyClassGen gen = weaver.getLazyClassGen(); ResolvedTypeX onType = weaver.getWorld().resolve(signature.getDeclaringType(),munger.getSourceLocation()); boolean onInterface = onType.isInterface(); if (onType.isAnnotation(weaver.getWorld())) { signalError(WeaverMessages.ITDM_ON_ANNOTATION_NOT_ALLOWED,weaver,onType); return false; } if (onType.isEnum(weaver.getWorld())) { signalError(WeaverMessages.ITDM_ON_ENUM_NOT_ALLOWED,weaver,onType); return false; } if (onType.equals(gen.getType())) { ResolvedMember introMethod = AjcMemberMaker.interMethod(signature, aspectType, onInterface); LazyMethodGen mg = makeMethodGen(gen, introMethod); if (!onInterface && !Modifier.isAbstract(introMethod.getModifiers())) { InstructionList body = mg.getBody(); InstructionFactory fact = gen.getFactory(); int pos = 0; if (!signature.isStatic()) { body.append(InstructionFactory.createThis()); pos++; } Type[] paramTypes = BcelWorld.makeBcelTypes(introMethod.getParameterTypes()); for (int i = 0, len = paramTypes.length; i < len; i++) { Type paramType = paramTypes[i]; body.append(InstructionFactory.createLoad(paramType, pos)); pos+=paramType.getSize(); } body.append(Utility.createInvoke(fact, weaver.getWorld(), dispatchMethod)); body.append( InstructionFactory.createReturn( BcelWorld.makeBcelType(introMethod.getReturnType()))); } else { //??? this is okay //if (!(mg.getBody() == null)) throw new RuntimeException("bas"); } // XXX make sure to check that we set exceptions properly on this guy. weaver.addLazyMethodGen(mg); weaver.getLazyClassGen().warnOnAddedMethod(mg.getMethod(),getSignature().getSourceLocation()); addNeededSuperCallMethods(weaver, onType, munger.getSuperMethodsCalled()); return true; } else if (onInterface && !Modifier.isAbstract(signature.getModifiers())) { // This means the 'gen' should be the top most implementor // - if it is *not* then something went wrong after we worked // out that it was the top most implementor (see pr49657) if (!gen.getType().isTopmostImplementor(onType)) { ResolvedTypeX rtx = gen.getType().getTopmostImplementor(onType); if (!rtx.isExposedToWeaver()) { ISourceLocation sLoc = munger.getSourceLocation(); weaver.getWorld().getMessageHandler().handleMessage(MessageUtil.error( WeaverMessages.format(WeaverMessages.ITD_NON_EXPOSED_IMPLEMENTOR,rtx,getAspectType().getName()), (sLoc==null?getAspectType().getSourceLocation():sLoc))); } else { // XXX what does this state mean? // We have incorrectly identified what is the top most implementor and its not because // a type wasn't exposed to the weaver } return false; } else { ResolvedMember introMethod = AjcMemberMaker.interMethod(signature, aspectType, false); LazyMethodGen mg = makeMethodGen(gen, introMethod); Type[] paramTypes = BcelWorld.makeBcelTypes(introMethod.getParameterTypes()); Type returnType = BcelWorld.makeBcelType(introMethod.getReturnType()); InstructionList body = mg.getBody(); InstructionFactory fact = gen.getFactory(); int pos = 0; if (!introMethod.isStatic()) { body.append(InstructionFactory.createThis()); pos++; } for (int i = 0, len = paramTypes.length; i < len; i++) { Type paramType = paramTypes[i]; body.append(InstructionFactory.createLoad(paramType, pos)); pos+=paramType.getSize(); } body.append(Utility.createInvoke(fact, weaver.getWorld(), dispatchMethod)); body.append(InstructionFactory.createReturn(returnType)); mg.definingType = onType; weaver.addOrReplaceLazyMethodGen(mg); addNeededSuperCallMethods(weaver, onType, munger.getSuperMethodsCalled()); return true; } } else { return false; } } private void addNeededSuperCallMethods( BcelClassWeaver weaver, ResolvedTypeX onType, Set neededSuperCalls) { LazyClassGen gen = weaver.getLazyClassGen(); for (Iterator iter = neededSuperCalls.iterator(); iter.hasNext();) { ResolvedMember superMethod = (ResolvedMember) iter.next(); if (weaver.addDispatchTarget(superMethod)) { //System.err.println("super type: " + superMethod.getDeclaringType() + ", " + gen.getType()); boolean isSuper = !superMethod.getDeclaringType().equals(gen.getType()); String dispatchName; if (isSuper) dispatchName = NameMangler.superDispatchMethod(onType, superMethod.getName()); else dispatchName = NameMangler.protectedDispatchMethod( onType, superMethod.getName()); LazyMethodGen dispatcher = makeDispatcher( gen, dispatchName, superMethod, weaver.getWorld(), isSuper); weaver.addLazyMethodGen(dispatcher); } } } private void signalError(String msgid,BcelClassWeaver weaver,TypeX onType) { IMessage msg = MessageUtil.error( WeaverMessages.format(msgid,onType.getName()),getSourceLocation()); weaver.getWorld().getMessageHandler().handleMessage(msg); } private boolean mungeNewConstructor( BcelClassWeaver weaver, NewConstructorTypeMunger newConstructorTypeMunger) { final LazyClassGen currentClass = weaver.getLazyClassGen(); final InstructionFactory fact = currentClass.getFactory(); ResolvedMember newConstructorMember = newConstructorTypeMunger.getSyntheticConstructor(); TypeX onType = newConstructorMember.getDeclaringType(); if (onType.isAnnotation(weaver.getWorld())) { signalError(WeaverMessages.ITDC_ON_ANNOTATION_NOT_ALLOWED,weaver,onType); return false; } if (onType.isEnum(weaver.getWorld())) { signalError(WeaverMessages.ITDC_ON_ENUM_NOT_ALLOWED,weaver,onType); return false; } if (! onType.equals(currentClass.getType())) return false; ResolvedMember explicitConstructor = newConstructorTypeMunger.getExplicitConstructor(); //int declaredParameterCount = newConstructorTypeMunger.getDeclaredParameterCount(); LazyMethodGen freshConstructor = makeMethodGen(currentClass, newConstructorMember); currentClass.addMethodGen(freshConstructor); //weaver.addLazyMethodGen(freshConstructor); InstructionList body = freshConstructor.getBody(); // add to body: push arts for call to pre, from actual args starting at 1 (skipping this), going to // declared argcount + 1 TypeX[] declaredParams = newConstructorTypeMunger.getSignature().getParameterTypes(); Type[] paramTypes = freshConstructor.getArgumentTypes(); int frameIndex = 1; for (int i = 0, len = declaredParams.length; i < len; i++) { body.append(InstructionFactory.createLoad(paramTypes[i], frameIndex)); frameIndex += paramTypes[i].getSize(); } // do call to pre Member preMethod = AjcMemberMaker.preIntroducedConstructor(aspectType, onType, declaredParams); body.append(Utility.createInvoke(fact, null, preMethod)); // create a local, and store return pre stuff into it. int arraySlot = freshConstructor.allocateLocal(1); body.append(InstructionFactory.createStore(Type.OBJECT, arraySlot)); // put this on the stack body.append(InstructionConstants.ALOAD_0); // unpack pre args onto stack TypeX[] superParamTypes = explicitConstructor.getParameterTypes(); for (int i = 0, len = superParamTypes.length; i < len; i++) { body.append(InstructionFactory.createLoad(Type.OBJECT, arraySlot)); body.append(Utility.createConstant(fact, i)); body.append(InstructionFactory.createArrayLoad(Type.OBJECT)); body.append( Utility.createConversion( fact, Type.OBJECT, BcelWorld.makeBcelType(superParamTypes[i]))); } // call super/this body.append(Utility.createInvoke(fact, null, explicitConstructor)); // put this back on the stack body.append(InstructionConstants.ALOAD_0); // unpack params onto stack Member postMethod = AjcMemberMaker.postIntroducedConstructor(aspectType, onType, declaredParams); TypeX[] postParamTypes = postMethod.getParameterTypes(); for (int i = 1, len = postParamTypes.length; i < len; i++) { body.append(InstructionFactory.createLoad(Type.OBJECT, arraySlot)); body.append(Utility.createConstant(fact, superParamTypes.length + i-1)); body.append(InstructionFactory.createArrayLoad(Type.OBJECT)); body.append( Utility.createConversion( fact, Type.OBJECT, BcelWorld.makeBcelType(postParamTypes[i]))); } // call post body.append(Utility.createInvoke(fact, null, postMethod)); // don't forget to return!! body.append(InstructionConstants.RETURN); return true; } private static LazyMethodGen makeDispatcher( LazyClassGen onGen, String dispatchName, ResolvedMember superMethod, BcelWorld world, boolean isSuper) { Type[] paramTypes = BcelWorld.makeBcelTypes(superMethod.getParameterTypes()); Type returnType = BcelWorld.makeBcelType(superMethod.getReturnType()); int modifiers = Modifier.PUBLIC; if (onGen.isInterface()) modifiers |= Modifier.ABSTRACT; LazyMethodGen mg = new LazyMethodGen( modifiers, returnType, dispatchName, paramTypes, TypeX.getNames(superMethod.getExceptions()), onGen); InstructionList body = mg.getBody(); if (onGen.isInterface()) return mg; // assert (!superMethod.isStatic()) InstructionFactory fact = onGen.getFactory(); int pos = 0; body.append(InstructionFactory.createThis()); pos++; for (int i = 0, len = paramTypes.length; i < len; i++) { Type paramType = paramTypes[i]; body.append(InstructionFactory.createLoad(paramType, pos)); pos+=paramType.getSize(); } if (isSuper) { body.append(Utility.createSuperInvoke(fact, world, superMethod)); } else { body.append(Utility.createInvoke(fact, world, superMethod)); } body.append(InstructionFactory.createReturn(returnType)); return mg; } private boolean mungeNewField(BcelClassWeaver weaver, NewFieldTypeMunger munger) { /*ResolvedMember initMethod = */munger.getInitMethod(aspectType); LazyClassGen gen = weaver.getLazyClassGen(); ResolvedMember field = munger.getSignature(); ResolvedTypeX onType = weaver.getWorld().resolve(field.getDeclaringType(),munger.getSourceLocation()); boolean onInterface = onType.isInterface(); if (onType.isAnnotation(weaver.getWorld())) { signalError(WeaverMessages.ITDF_ON_ANNOTATION_NOT_ALLOWED,weaver,onType); return false; } if (onType.isEnum(weaver.getWorld())) { signalError(WeaverMessages.ITDF_ON_ENUM_NOT_ALLOWED,weaver,onType); return false; } if (onType.equals(gen.getType())) { if (onInterface) { LazyMethodGen mg = makeMethodGen(gen, AjcMemberMaker.interFieldInterfaceGetter(field, onType, aspectType)); gen.addMethodGen(mg); LazyMethodGen mg1 = makeMethodGen(gen, AjcMemberMaker.interFieldInterfaceSetter(field, onType, aspectType)); gen.addMethodGen(mg1); } else { weaver.addInitializer(this); FieldGen fg = makeFieldGen(gen, AjcMemberMaker.interFieldClassField(field, aspectType)); gen.addField(fg.getField(),getSourceLocation()); } return true; } else if (onInterface && gen.getType().isTopmostImplementor(onType)) { // wew know that we can't be static since we don't allow statics on interfaces if (field.isStatic()) throw new RuntimeException("unimplemented"); weaver.addInitializer(this); //System.err.println("impl body on " + gen.getType() + " for " + munger); Type fieldType = BcelWorld.makeBcelType(field.getType()); FieldGen fg = makeFieldGen(gen, AjcMemberMaker.interFieldInterfaceField(field, onType, aspectType)); gen.addField(fg.getField(),getSourceLocation()); //this uses a shadow munger to add init method to constructors //weaver.getShadowMungers().add(makeInitCallShadowMunger(initMethod)); LazyMethodGen mg = makeMethodGen(gen, AjcMemberMaker.interFieldInterfaceGetter(field, gen.getType(), aspectType)); InstructionList il = new InstructionList(); InstructionFactory fact = gen.getFactory(); if (field.isStatic()) { il.append(fact.createFieldAccess( gen.getClassName(), fg.getName(), fieldType, Constants.GETSTATIC)); } else { il.append(InstructionConstants.ALOAD_0); il.append(fact.createFieldAccess( gen.getClassName(), fg.getName(), fieldType, Constants.GETFIELD)); } il.append(InstructionFactory.createReturn(fieldType)); mg.getBody().insert(il); gen.addMethodGen(mg); LazyMethodGen mg1 = makeMethodGen(gen, AjcMemberMaker.interFieldInterfaceSetter(field, gen.getType(), aspectType)); InstructionList il1 = new InstructionList(); if (field.isStatic()) { il1.append(InstructionFactory.createLoad(fieldType, 0)); il1.append(fact.createFieldAccess( gen.getClassName(), fg.getName(), fieldType, Constants.PUTSTATIC)); } else { il1.append(InstructionConstants.ALOAD_0); il1.append(InstructionFactory.createLoad(fieldType, 1)); il1.append(fact.createFieldAccess( gen.getClassName(), fg.getName(), fieldType, Constants.PUTFIELD)); } il1.append(InstructionFactory.createReturn(Type.VOID)); mg1.getBody().insert(il1); gen.addMethodGen(mg1); return true; } else { return false; } } }
82,062
Bug 82062 WeaveMessage should provide more information
It would be wonderful if the WeaveMessage object would provide two additional things: - the affected class name - the aspect name I could use this to determine which aspect is woven into which class during load-time weaving (need this for dependency management).
resolved fixed
9897659
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-01-04T13:15:57Z
2005-01-01T20:06:40Z
weaver/src/org/aspectj/weaver/bcel/BcelWorld.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the 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.IOException; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.List; import java.util.StringTokenizer; import org.aspectj.apache.bcel.classfile.ClassParser; import org.aspectj.apache.bcel.classfile.JavaClass; import org.aspectj.apache.bcel.classfile.Method; import org.aspectj.apache.bcel.generic.ConstantPoolGen; import org.aspectj.apache.bcel.generic.FieldInstruction; import org.aspectj.apache.bcel.generic.GETSTATIC; import org.aspectj.apache.bcel.generic.INVOKEINTERFACE; import org.aspectj.apache.bcel.generic.INVOKESPECIAL; import org.aspectj.apache.bcel.generic.INVOKESTATIC; import org.aspectj.apache.bcel.generic.InvokeInstruction; import org.aspectj.apache.bcel.generic.PUTSTATIC; import org.aspectj.apache.bcel.generic.Type; import org.aspectj.apache.bcel.util.ClassPath; import org.aspectj.apache.bcel.util.Repository; import org.aspectj.bridge.IMessageHandler; import org.aspectj.weaver.Advice; import org.aspectj.weaver.AdviceKind; import org.aspectj.weaver.AjAttribute; import org.aspectj.weaver.ConcreteTypeMunger; import org.aspectj.weaver.ICrossReferenceHandler; import org.aspectj.weaver.Member; import org.aspectj.weaver.ResolvedMember; import org.aspectj.weaver.ResolvedTypeMunger; import org.aspectj.weaver.ResolvedTypeX; import org.aspectj.weaver.TypeX; import org.aspectj.weaver.World; import org.aspectj.weaver.patterns.FormalBinding; import org.aspectj.weaver.patterns.Pointcut; import org.aspectj.weaver.patterns.SimpleScope; public class BcelWorld extends World implements Repository { private ClassPathManager classPath; //private ClassPathManager aspectPath = null; // private List aspectPathEntries; // ---- constructors public BcelWorld() { this(""); } public BcelWorld(String cp) { this(makeDefaultClasspath(cp), IMessageHandler.THROW, null); } private static List makeDefaultClasspath(String cp) { List classPath = new ArrayList(); classPath.addAll(getPathEntries(cp)); classPath.addAll(getPathEntries(ClassPath.getClassPath())); //System.err.println("classpath: " + classPath); return classPath; } private static List getPathEntries(String s) { List ret = new ArrayList(); StringTokenizer tok = new StringTokenizer(s, File.pathSeparator); while(tok.hasMoreTokens()) ret.add(tok.nextToken()); return ret; } public BcelWorld(List classPath, IMessageHandler handler, ICrossReferenceHandler xrefHandler) { //this.aspectPath = new ClassPathManager(aspectPath, handler); this.classPath = new ClassPathManager(classPath, handler); setMessageHandler(handler); setXRefHandler(xrefHandler); // Tell BCEL to use us for resolving any classes org.aspectj.apache.bcel.Repository.setRepository(this); } public BcelWorld(ClassPathManager cpm, IMessageHandler handler, ICrossReferenceHandler xrefHandler) { this.classPath = cpm; setMessageHandler(handler); setXRefHandler(xrefHandler); // Tell BCEL to use us for resolving any classes org.aspectj.apache.bcel.Repository.setRepository(this); } public void addPath (String name) { classPath.addPath(name, this.getMessageHandler()); } /** * Parse a string into advice. * * <blockquote><pre> * Kind ( Id , ... ) : Pointcut -> MethodSignature * </pre></blockquote> */ public Advice shadowMunger(String str, int extraFlag) { str = str.trim(); int start = 0; int i = str.indexOf('('); AdviceKind kind = AdviceKind.stringToKind(str.substring(start, i)); start = ++i; i = str.indexOf(')', i); String[] ids = parseIds(str.substring(start, i).trim()); //start = ++i; i = str.indexOf(':', i); start = ++i; i = str.indexOf("->", i); Pointcut pointcut = Pointcut.fromString(str.substring(start, i).trim()); Member m = Member.methodFromString(str.substring(i+2, str.length()).trim()); // now, we resolve TypeX[] types = m.getParameterTypes(); FormalBinding[] bindings = new FormalBinding[ids.length]; for (int j = 0, len = ids.length; j < len; j++) { bindings[j] = new FormalBinding(types[j], ids[j], j, 0, 0, "fromString"); } Pointcut p = pointcut.resolve(new SimpleScope(this, bindings)); return new BcelAdvice(kind, p, m, extraFlag, 0, 0, null, null); } private String[] parseIds(String str) { if (str.length() == 0) return ZERO_STRINGS; List l = new ArrayList(); int start = 0; while (true) { int i = str.indexOf(',', start); if (i == -1) { l.add(str.substring(start).trim()); break; } l.add(str.substring(start, i).trim()); start = i+1; } return (String[]) l.toArray(new String[l.size()]); } // ---- various interactions with bcel public static Type makeBcelType(TypeX type) { return Type.getType(type.getSignature()); } static Type[] makeBcelTypes(TypeX[] types) { Type[] ret = new Type[types.length]; for (int i = 0, len = types.length; i < len; i++) { ret[i] = makeBcelType(types[i]); } return ret; } public static TypeX fromBcel(Type t) { return TypeX.forSignature(t.getSignature()); } static TypeX[] fromBcel(Type[] ts) { TypeX[] ret = new TypeX[ts.length]; for (int i = 0, len = ts.length; i < len; i++) { ret[i] = fromBcel(ts[i]); } return ret; } public ResolvedTypeX resolve(Type t) { return resolve(fromBcel(t)); } protected ResolvedTypeX.ConcreteName resolveObjectType(ResolvedTypeX.Name ty) { String name = ty.getName(); JavaClass jc = null; //UnwovenClassFile classFile = (UnwovenClassFile)sourceJavaClasses.get(name); //if (classFile != null) jc = classFile.getJavaClass(); // if (jc == null) { // jc = lookupJavaClass(aspectPath, name); // } if (jc == null) { jc = lookupJavaClass(classPath, name); } if (jc == null) { return null; } else { return makeBcelObjectType(ty, jc, false); } } private BcelObjectType makeBcelObjectType(ResolvedTypeX.Name resolvedTypeX, JavaClass jc, boolean exposedToWeaver) { BcelObjectType ret = new BcelObjectType(resolvedTypeX, jc, exposedToWeaver); resolvedTypeX.setDelegate(ret); return ret; } private JavaClass lookupJavaClass(ClassPathManager classPath, String name) { if (classPath == null) return null; try { ClassPathManager.ClassFile file = classPath.find(TypeX.forName(name)); if (file == null) return null; ClassParser parser = new ClassParser(file.getInputStream(), file.getPath()); JavaClass jc = parser.parse(); file.close(); return jc; } catch (IOException ioe) { return null; } } public BcelObjectType addSourceObjectType(JavaClass jc) { String signature = TypeX.forName(jc.getClassName()).getSignature(); ResolvedTypeX.Name nameTypeX = (ResolvedTypeX.Name)typeMap.get(signature); if (nameTypeX == null) { nameTypeX = new ResolvedTypeX.Name(signature, this); } BcelObjectType ret = makeBcelObjectType(nameTypeX, jc, true); nameTypeX.setDelegate(ret); typeMap.put(signature, nameTypeX); return ret; } void deleteSourceObjectType(TypeX ty) { typeMap.remove(ty.getSignature()); } public static Member makeFieldSignature(LazyClassGen cg, FieldInstruction fi) { ConstantPoolGen cpg = cg.getConstantPoolGen(); return Member.field( fi.getClassName(cpg), (fi instanceof GETSTATIC || fi instanceof PUTSTATIC) ? Modifier.STATIC : 0, fi.getName(cpg), fi.getSignature(cpg)); } public static Member makeFieldSetSignature(LazyClassGen cg, FieldInstruction fi) { ConstantPoolGen cpg = cg.getConstantPoolGen(); return Member.field( fi.getClassName(cpg), (fi instanceof GETSTATIC || fi instanceof PUTSTATIC) ? Modifier.STATIC : 0, fi.getName(cpg), "(" + fi.getSignature(cpg) + ")" +fi.getSignature(cpg)); } public Member makeMethodSignature(LazyMethodGen mg) { return makeMethodSignature(mg, null); } public Member makeMethodSignature(LazyMethodGen mg, Member.Kind kind) { ResolvedMember ret = mg.getMemberView(); if (ret == null) { int mods = mg.getAccessFlags(); if (mg.getEnclosingClass().isInterface()) { mods |= Modifier.INTERFACE; } if (kind == null) { if (mg.getName().equals("<init>")) { kind = Member.CONSTRUCTOR; } else if (mg.getName().equals("<clinit>")) { kind = Member.STATIC_INITIALIZATION; } else { kind = Member.METHOD; } } return new ResolvedMember(kind, TypeX.forName(mg.getClassName()), mods, fromBcel(mg.getReturnType()), mg.getName(), fromBcel(mg.getArgumentTypes()) ); } else { return ret; } } public static Member makeMethodSignature(LazyClassGen cg, InvokeInstruction ii) { ConstantPoolGen cpg = cg.getConstantPoolGen(); String declaring = ii.getClassName(cpg); String name = ii.getName(cpg); String signature = ii.getSignature(cpg); int modifier = (ii instanceof INVOKEINTERFACE) ? Modifier.INTERFACE : (ii instanceof INVOKESTATIC) ? Modifier.STATIC : (ii instanceof INVOKESPECIAL && ! name.equals("<init>")) ? Modifier.PRIVATE : 0; return Member.method(TypeX.forName(declaring), modifier, name, signature); } public static Member makeMungerMethodSignature(JavaClass javaClass, Method method) { int mods = 0; if (method.isStatic()) mods = Modifier.STATIC; else if (javaClass.isInterface()) mods = Modifier.INTERFACE; else if (method.isPrivate()) mods = Modifier.PRIVATE; return Member.method( TypeX.forName(javaClass.getClassName()), mods, method.getName(), method.getSignature()); } private static final String[] ZERO_STRINGS = new String[0]; public String toString() { StringBuffer buf = new StringBuffer(); buf.append("BcelWorld("); //buf.append(shadowMungerMap); buf.append(")"); return buf.toString(); } public Advice concreteAdvice( AjAttribute.AdviceAttribute attribute, Pointcut pointcut, Member signature) { //System.err.println("concrete advice: " + signature + " context " + sourceContext); return new BcelAdvice(attribute, pointcut, signature, null); } public ConcreteTypeMunger concreteTypeMunger( ResolvedTypeMunger munger, ResolvedTypeX aspectType) { return new BcelTypeMunger(munger, aspectType); } public ConcreteTypeMunger makeCflowStackFieldAdder(ResolvedMember cflowField) { return new BcelCflowStackFieldAdder(cflowField); } public ConcreteTypeMunger makeCflowCounterFieldAdder(ResolvedMember cflowField) { return new BcelCflowCounterFieldAdder(cflowField); } public static BcelObjectType getBcelObjectType(ResolvedTypeX concreteAspect) { //XXX need error checking return (BcelObjectType) ((ResolvedTypeX.Name)concreteAspect).getDelegate(); } public void tidyUp() { // At end of compile, close any open files so deletion of those archives is possible classPath.closeArchives(); } /// The repository interface methods public JavaClass findClass(String className) { return lookupJavaClass(classPath,className); } public JavaClass loadClass(String className) throws ClassNotFoundException { return lookupJavaClass(classPath,className); } public void storeClass(JavaClass clazz) { throw new RuntimeException("Not implemented"); } public void removeClass(JavaClass clazz) { throw new RuntimeException("Not implemented"); } public JavaClass loadClass(Class clazz) throws ClassNotFoundException { throw new RuntimeException("Not implemented"); } public void clear() { throw new RuntimeException("Not implemented"); } }
81,863
Bug 81863 Annotation matching using within() PCD doesn't appear to be working.
null
resolved fixed
8a8930f
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-01-05T15:15:28Z
2004-12-23T16:40:00Z
tests/java5/annotations/within/PlainWithin.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 *******************************************************************************/ /** * @author colyer * * TODO To change the template for this generated type comment go to * Window - Preferences - Java - Code Generation - Code and Comments */ @MyClassRetententionAnnotation public class PlainWithin { public void foo() {} } class NotAnnotated { public void foo() {} } @interface MyAnnotation {}
81,863
Bug 81863 Annotation matching using within() PCD doesn't appear to be working.
null
resolved fixed
8a8930f
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-01-05T15:15:28Z
2004-12-23T16:40:00Z
tests/src/org/aspectj/systemtest/ajc150/AnnotationPointcutsTests.java
/******************************************************************************* * Copyright (c) 2004 IBM * All rights reserved. This program and the accompanying materials * are made available under the terms of the Common Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * Andy Clement - initial API and implementation *******************************************************************************/ package org.aspectj.systemtest.ajc150; import java.io.File; import java.util.ArrayList; import java.util.List; import org.aspectj.tools.ajc.CompilationResult; /** * Tests the use of Annotations in pointcuts */ public class AnnotationPointcutsTests extends TestUtils { protected void setUp() throws Exception { super.setUp(); baseDir = new File("../tests/java5/annotations"); } // before(): call(@SimpleAnnotation * *(..)) { } public void test001_usingAnnotationsInPointcuts() { CompilationResult cR = binaryWeave("testcode.jar","AnnotationAspect02.aj",0,0); System.err.println(cR.getStandardError()); System.err.println(cR.getErrorMessages()); System.err.println(cR.getInfoMessages()); verifyWeavingMessagesOutput(cR,new String[]{ "weaveinfo Type 'AnnotatedType' (AnnotatedType.java:3) advised by before advice from 'AnnotationAspect02' (AnnotationAspect02.aj:4)", "weaveinfo Type 'AnnotatedType' (AnnotatedType.java:3) advised by before advice from 'AnnotationAspect02' (AnnotationAspect02.aj:2)", "weaveinfo Type 'AnnotatedType' (AnnotatedType.java:4) advised by before advice from 'AnnotationAspect02' (AnnotationAspect02.aj:4)"}); } public void test002_AtAnnotationMatching() { CompilationResult cR = binaryWeave("testcode.jar","AnnotationAspect03.aj",0,1); List expectedWarnings = new ArrayList(); expectedWarnings.add(new Message("@annotation matched here")); // L 8 assertMessages(cR, new MessageSpec(expectedWarnings, new ArrayList())); } // TODO extra tests // 1) @within (matches, does not match, matches inherited annotation) // 2) @withincode (matches, does not match) // 3) @annotation on the different join point kinds, matches with inherited annotation }
81,863
Bug 81863 Annotation matching using within() PCD doesn't appear to be working.
null
resolved fixed
8a8930f
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-01-05T15:15:28Z
2004-12-23T16:40:00Z
tests/src/org/aspectj/systemtest/ajc150/AnnotationRuntimeTests.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.systemtest.ajc150; import java.io.File; import java.util.ArrayList; import java.util.List; import org.aspectj.tools.ajc.CompilationResult; /** * Tests for @this, @target, @args */ public class AnnotationRuntimeTests extends TestUtils { protected void setUp() throws Exception { super.setUp(); baseDir = new File("../tests/java5/annotations/thisOrtarget"); } public void test001_NoBinding() { CompilationResult cR = binaryWeave("TestingAnnotations.jar","BindingLimitation.aj",1,0); List errors = cR.getErrorMessages(); assertTrue("Binding not supported",errors.get(0).toString().startsWith("error Binding not supported")); } public void test002_MustHaveRuntimeRetention() { CompilationResult cR = binaryWeave("TestingAnnotations.jar","NotRuntimeRetention.aj",2,0); List errors = new ArrayList(); errors.add(new Message(7,"Annotation type MyClassRetentionAnnotation does not have runtime retention")); errors.add(new Message(13,"Annotation type MyClassRetentionAnnotation does not have runtime retention")); MessageSpec messageSpec = new MessageSpec(new ArrayList(), errors); assertMessages(cR, messageSpec); } public void test003_InheritableOrNot() { CompilationResult cR = binaryWeave("TestingAnnotations.jar","ThisOrTargetTests.aj",0,0); } public void test004_CantUseinDecEoW() { CompilationResult cR = binaryWeave("TestingAnnotations.jar","DeclareEoW.java",4,0); List errors = new ArrayList(); errors.add(new Message(3,"this() pointcut designator cannot be used in declare statement")); errors.add(new Message(5,"target() pointcut designator cannot be used in declare statement")); MessageSpec messageSpec = new MessageSpec(new ArrayList(), errors); assertMessages(cR, messageSpec); } // TODO extra tests // run the result of test003 and validate matches (needs 1.5 runtime) // test inheritable annotation not present on type [should generate runtime test] public void test005_ArgsSuite() { baseDir = new File("../tests/java5/annotations/args"); CompilationResult cR = binaryWeave("TestingArgsAnnotations.jar","AtArgsAspect.java",0,0); // TODO need to RUN the result of these tests... System.out.println(cR); } public void test006_CantUseinDecEoW() { baseDir = new File("../tests/java5/annotations/args"); CompilationResult cR = binaryWeave("TestingArgsAnnotations.jar","DeclareEoW.java",2,0); List errors = new ArrayList(); errors.add(new Message(3,"args() pointcut designator cannot be used in declare statement")); MessageSpec messageSpec = new MessageSpec(new ArrayList(), errors); assertMessages(cR, messageSpec); } public void test007_Within_Code() { baseDir = new File("../tests/java5/annotations/within_code"); CompilationResult cR = binaryWeave("TestingAnnotations.jar","WithinAndWithinCodeTests.java",0,5); List warnings = new ArrayList(); warnings.add(new Message(32,"@within match on non-inherited annotation")); warnings.add(new Message(39,"@within match on non-inherited annotation")); warnings.add(new Message(39,"@within match on inheritable annotation")); warnings.add(new Message(43,"@within match on inheritable annotation")); warnings.add(new Message(32,"@withincode match")); MessageSpec mSpec = new MessageSpec(warnings,new ArrayList()); assertMessages(cR,mSpec); } }
81,863
Bug 81863 Annotation matching using within() PCD doesn't appear to be working.
null
resolved fixed
8a8930f
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-01-05T15:15:28Z
2004-12-23T16:40:00Z
weaver/src/org/aspectj/weaver/patterns/AnnotationTypePattern.java
/* ******************************************************************* * Copyright (c) 2004 IBM Corporation. * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Common Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/cpl-v10.html * * ******************************************************************/ package org.aspectj.weaver.patterns; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.aspectj.util.FuzzyBoolean; import org.aspectj.weaver.AnnotatedElement; import org.aspectj.weaver.BCException; import org.aspectj.weaver.ISourceContext; import org.aspectj.weaver.IntMap; import org.aspectj.weaver.World; public abstract class AnnotationTypePattern extends PatternNode { public static final AnnotationTypePattern ANY = new AnyAnnotationTypePattern(); public static final AnnotationTypePattern ELLIPSIS = new EllipsisAnnotationTypePattern(); /** * TODO: write, read, equals & hashcode both in annotation hierarachy and * in altered TypePattern hierarchy */ protected AnnotationTypePattern() { super(); } public abstract FuzzyBoolean matches(AnnotatedElement annotated); public FuzzyBoolean fastMatches(AnnotatedElement annotated) { return FuzzyBoolean.MAYBE; } public AnnotationTypePattern remapAdviceFormals(IntMap bindings) { return this; } public abstract void resolve(World world); /** * This can modify in place, or return a new TypePattern if the type changes. */ public AnnotationTypePattern resolveBindings(IScope scope, Bindings bindings, boolean allowBinding) { return this; } public static final byte EXACT = 1; public static final byte BINDING = 2; public static final byte NOT = 3; public static final byte OR = 4; public static final byte AND = 5; public static final byte ELLIPSIS_KEY = 6; public static final byte ANY_KEY = 7; public static final byte WILD = 8; public static AnnotationTypePattern read(DataInputStream s, ISourceContext context) throws IOException { byte key = s.readByte(); switch(key) { case EXACT: return ExactAnnotationTypePattern.read(s, context); case BINDING: return BindingAnnotationTypePattern.read(s, context); case NOT: return NotAnnotationTypePattern.read(s, context); case OR: return OrAnnotationTypePattern.read(s, context); case AND: return AndAnnotationTypePattern.read(s, context); case WILD: return WildAnnotationTypePattern.read(s,context); case ELLIPSIS_KEY: return ELLIPSIS; case ANY_KEY: return ANY; } throw new BCException("unknown TypePattern kind: " + key); } } class AnyAnnotationTypePattern extends AnnotationTypePattern { public FuzzyBoolean matches(AnnotatedElement annotated) { return FuzzyBoolean.YES; } public void write(DataOutputStream s) throws IOException { s.writeByte(AnnotationTypePattern.ANY_KEY); } public void resolve(World world) { } public String toString() { return "@ANY"; } } class EllipsisAnnotationTypePattern extends AnnotationTypePattern { public FuzzyBoolean matches(AnnotatedElement annotated) { return FuzzyBoolean.NO; } public void write(DataOutputStream s) throws IOException { s.writeByte(AnnotationTypePattern.ELLIPSIS_KEY); } public void resolve(World world) { } public String toString() { return ".."; } }
81,863
Bug 81863 Annotation matching using within() PCD doesn't appear to be working.
null
resolved fixed
8a8930f
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-01-05T15:15:28Z
2004-12-23T16:40:00Z
weaver/src/org/aspectj/weaver/patterns/ExactAnnotationTypePattern.java
/* ******************************************************************* * Copyright (c) 2004 IBM Corporation. * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Common Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/cpl-v10.html * * ******************************************************************/ 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.bridge.MessageUtil; import org.aspectj.util.FuzzyBoolean; import org.aspectj.weaver.AnnotatedElement; import org.aspectj.weaver.BCException; import org.aspectj.weaver.ISourceContext; import org.aspectj.weaver.ResolvedTypeX; import org.aspectj.weaver.TypeX; import org.aspectj.weaver.WeaverMessages; import org.aspectj.weaver.World; /** * Matches an annotation of a given type */ public class ExactAnnotationTypePattern extends AnnotationTypePattern { protected TypeX annotationType; protected String formalName; protected boolean resolved = false; private boolean bindingPattern = false; /** * */ public ExactAnnotationTypePattern(TypeX annotationType) { this.annotationType = annotationType; this.resolved = (annotationType instanceof ResolvedTypeX); } public ExactAnnotationTypePattern(String formalName) { this.formalName = formalName; this.resolved = false; this.bindingPattern = true; // will be turned into BindingAnnotationTypePattern during resolution } public FuzzyBoolean fastMatches(AnnotatedElement annotated) { if (annotated.hasAnnotation(annotationType)) { return FuzzyBoolean.YES; } else { // could be inherited, but we don't know that until we are // resolved, and we're not yet... return FuzzyBoolean.MAYBE; } } public FuzzyBoolean matches(AnnotatedElement annotated) { boolean checkSupers = false; if (annotationType.hasAnnotation(TypeX.AT_INHERITED)) { if (annotated instanceof ResolvedTypeX) { checkSupers = true; } } if (annotated.hasAnnotation(annotationType)) { return FuzzyBoolean.YES; } else if (checkSupers) { ResolvedTypeX toMatchAgainst = ((ResolvedTypeX) annotated).getSuperclass(); while (toMatchAgainst != null) { if (toMatchAgainst.hasAnnotation(annotationType)) return FuzzyBoolean.YES; toMatchAgainst = toMatchAgainst.getSuperclass(); } } return FuzzyBoolean.NO; } public void resolve(World world) { annotationType = annotationType.resolve(world); } /* (non-Javadoc) * @see org.aspectj.weaver.patterns.AnnotationTypePattern#resolveBindings(org.aspectj.weaver.patterns.IScope, org.aspectj.weaver.patterns.Bindings, boolean) */ public AnnotationTypePattern resolveBindings(IScope scope, Bindings bindings, boolean allowBinding) { if (resolved) return this; resolved = true; if (formalName != null) { FormalBinding formalBinding = scope.lookupFormal(formalName); if (formalBinding != null) { if (bindings == null) { scope.message(IMessage.ERROR, this, "negation doesn't allow binding"); return this; } if (!allowBinding) { scope.message(IMessage.ERROR, this, "name binding only allowed in @pcds, args, this, and target"); return this; } verifyIsAnnotationType(formalBinding.getType(),scope); BindingAnnotationTypePattern binding = new BindingAnnotationTypePattern(formalBinding); binding.copyLocationFrom(this); bindings.register(binding, scope); binding.resolveBinding(scope.getWorld()); return binding; } else { scope.message(IMessage.ERROR,this,"unbound formal " + formalName); return this; } } else { annotationType = annotationType.resolve(scope.getWorld()); verifyIsAnnotationType(annotationType,scope); return this; } } /** * @param scope */ private void verifyIsAnnotationType(TypeX type,IScope scope) { if (!type.isAnnotation(scope.getWorld())) { IMessage m = MessageUtil.error( WeaverMessages.format(WeaverMessages.REFERENCE_TO_NON_ANNOTATION_TYPE,type.getName()), getSourceLocation()); scope.getWorld().getMessageHandler().handleMessage(m); resolved = false; } } private static byte VERSION = 1; // rev if serialisation form changes /* (non-Javadoc) * @see org.aspectj.weaver.patterns.PatternNode#write(java.io.DataOutputStream) */ public void write(DataOutputStream s) throws IOException { s.writeByte(AnnotationTypePattern.EXACT); s.writeByte(VERSION); s.writeBoolean(bindingPattern); if (bindingPattern) { s.writeUTF(formalName); } else { annotationType.write(s); } writeLocation(s); } public static AnnotationTypePattern read(DataInputStream s,ISourceContext context) throws IOException { AnnotationTypePattern ret; byte version = s.readByte(); if (version > VERSION) { throw new BCException("ExactAnnotationTypePattern was written by a newer version of AspectJ"); } boolean isBindingPattern = s.readBoolean(); if (isBindingPattern) { ret = new ExactAnnotationTypePattern(s.readUTF()); } else { ret = new ExactAnnotationTypePattern(TypeX.read(s)); } ret.readLocation(context,s); return ret; } /* (non-Javadoc) * @see java.lang.Object#equals(java.lang.Object) */ public boolean equals(Object obj) { if (!(obj instanceof ExactAnnotationTypePattern)) return false; ExactAnnotationTypePattern other = (ExactAnnotationTypePattern) obj; return (other.annotationType.equals(annotationType)); } /* (non-Javadoc) * @see java.lang.Object#hashCode() */ public int hashCode() { return annotationType.hashCode(); } public String toString() { if (!resolved && formalName != null) return formalName; String ret = "@" + annotationType.toString(); if (formalName != null) ret = ret + " " + formalName; return ret; } }
81,863
Bug 81863 Annotation matching using within() PCD doesn't appear to be working.
null
resolved fixed
8a8930f
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-01-05T15:15:28Z
2004-12-23T16:40:00Z
weaver/src/org/aspectj/weaver/patterns/ExactTypePattern.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the 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.HashMap; import java.util.Map; import org.aspectj.util.FuzzyBoolean; import org.aspectj.weaver.BCException; import org.aspectj.weaver.ISourceContext; import org.aspectj.weaver.ResolvedTypeX; import org.aspectj.weaver.TypeX; public class ExactTypePattern extends TypePattern { protected TypeX type; public static final Map primitiveTypesMap; public static final Map boxedPrimitivesMap; private static final Map boxedTypesMap; static { primitiveTypesMap = new HashMap(); primitiveTypesMap.put("int",int.class); primitiveTypesMap.put("short",short.class); primitiveTypesMap.put("long",long.class); primitiveTypesMap.put("byte",byte.class); primitiveTypesMap.put("char",char.class); primitiveTypesMap.put("float",float.class); primitiveTypesMap.put("double",double.class); boxedPrimitivesMap = new HashMap(); boxedPrimitivesMap.put("java.lang.Integer",Integer.class); boxedPrimitivesMap.put("java.lang.Short",Short.class); boxedPrimitivesMap.put("java.lang.Long",Long.class); boxedPrimitivesMap.put("java.lang.Byte",Byte.class); boxedPrimitivesMap.put("java.lang.Character",Character.class); boxedPrimitivesMap.put("java.lang.Float",Float.class); boxedPrimitivesMap.put("java.lang.Double",Double.class); boxedTypesMap = new HashMap(); boxedTypesMap.put("int",Integer.class); boxedTypesMap.put("short",Short.class); boxedTypesMap.put("long",Long.class); boxedTypesMap.put("byte",Byte.class); boxedTypesMap.put("char",Character.class); boxedTypesMap.put("float",Float.class); boxedTypesMap.put("double",Double.class); } public ExactTypePattern(TypeX type, boolean includeSubtypes,boolean isVarArgs) { super(includeSubtypes,isVarArgs); this.type = type; } /* (non-Javadoc) * @see org.aspectj.weaver.patterns.TypePattern#couldEverMatchSameTypesAs(org.aspectj.weaver.patterns.TypePattern) */ protected boolean couldEverMatchSameTypesAs(TypePattern other) { if (super.couldEverMatchSameTypesAs(other)) return true; // false is necessary but not sufficient TypeX otherType = other.getExactType(); if (otherType != ResolvedTypeX.MISSING) { return type.equals(otherType); } if (other instanceof WildTypePattern) { WildTypePattern owtp = (WildTypePattern) other; String yourSimpleNamePrefix = owtp.namePatterns[0].maybeGetSimpleName(); if (yourSimpleNamePrefix != null) { return (type.getName().startsWith(yourSimpleNamePrefix)); } } return true; } protected boolean matchesExactly(ResolvedTypeX matchType) { return this.type.equals(matchType); } public TypeX getType() { return type; } public FuzzyBoolean matchesInstanceof(ResolvedTypeX matchType) { // in our world, Object is assignable from anything if (type.equals(ResolvedTypeX.OBJECT)) return FuzzyBoolean.YES; if (type.isAssignableFrom(matchType, matchType.getWorld())) { return FuzzyBoolean.YES; } // fix for PR 64262 - shouldn't try to coerce primitives if (type.isPrimitive()) { return FuzzyBoolean.NO; } else { return matchType.isCoerceableFrom(type) ? FuzzyBoolean.MAYBE : FuzzyBoolean.NO; } } public boolean matchesExactly(Class matchType) { try { Class toMatchAgainst = getClassFor(type.getName()); return matchType == toMatchAgainst; } catch (ClassNotFoundException cnfEx) { return false; } } public FuzzyBoolean matchesInstanceof(Class matchType) { if (matchType.equals(Object.class)) return FuzzyBoolean.YES; try { String typeName = type.getName(); Class toMatchAgainst = getClassFor(typeName); FuzzyBoolean ret = FuzzyBoolean.fromBoolean(toMatchAgainst.isAssignableFrom(matchType)); if (ret == FuzzyBoolean.NO) { if (boxedTypesMap.containsKey(typeName)) { // try again with 'boxed' alternative toMatchAgainst = (Class) boxedTypesMap.get(typeName); ret = FuzzyBoolean.fromBoolean(toMatchAgainst.isAssignableFrom(matchType)); } } return ret; } catch (ClassNotFoundException cnfEx) { return FuzzyBoolean.NO; } } /** * Return YES if any subtype of the static type would match, * MAYBE if some subtypes could match * NO if there could never be a match * @param staticType * @return */ public FuzzyBoolean willMatchDynamically(Class staticType) { if (matchesExactly(staticType)) return FuzzyBoolean.YES; if (matchesInstanceof(staticType) == FuzzyBoolean.YES) return FuzzyBoolean.YES; try { String typeName = type.getName(); Class toMatchAgainst = getClassFor(typeName); if (toMatchAgainst.isInterface()) return FuzzyBoolean.MAYBE; if (staticType.isAssignableFrom(toMatchAgainst)) return FuzzyBoolean.MAYBE; return FuzzyBoolean.NO; } catch (ClassNotFoundException cnfEx) { return FuzzyBoolean.NO; } } private Class getClassFor(String typeName) throws ClassNotFoundException { Class ret = null; ret = (Class) primitiveTypesMap.get(typeName); if (ret == null) ret = Class.forName(typeName); return ret; } public boolean equals(Object other) { if (!(other instanceof ExactTypePattern)) return false; ExactTypePattern o = (ExactTypePattern)other; if (includeSubtypes != o.includeSubtypes) return false; if (isVarArgs != o.isVarArgs) return false; return (o.type.equals(this.type) && o.annotationPattern.equals(this.annotationPattern)); } public int hashCode() { int result = 17; result = 37*result + type.hashCode(); result = 37*result + annotationPattern.hashCode(); return result; } private static final byte EXACT_VERSION = 1; // rev if changed public void write(DataOutputStream out) throws IOException { out.writeByte(TypePattern.EXACT); out.writeByte(EXACT_VERSION); type.write(out); out.writeBoolean(includeSubtypes); out.writeBoolean(isVarArgs); annotationPattern.write(out); writeLocation(out); } public static TypePattern read(DataInputStream s, ISourceContext context) throws IOException { byte version = s.readByte(); if (version > EXACT_VERSION) throw new BCException("ExactTypePattern was written by a more recent version of AspectJ"); TypePattern ret = new ExactTypePattern(TypeX.read(s), s.readBoolean(), s.readBoolean()); ret.setAnnotationTypePattern(AnnotationTypePattern.read(s,context)); ret.readLocation(context, s); return ret; } public String toString() { StringBuffer buff = new StringBuffer(); if (annotationPattern != AnnotationTypePattern.ANY) { buff.append('('); buff.append(annotationPattern.toString()); buff.append(' '); } buff.append(type.toString()); if (includeSubtypes) buff.append('+'); // Note, there will be a rogue [] in the pattern here in the case of varargs ... if (isVarArgs) buff.append("..."); if (annotationPattern != AnnotationTypePattern.ANY) { buff.append(')'); } return buff.toString(); } public TypePattern resolveBindings(IScope scope, Bindings bindings, boolean allowBinding, boolean requireExactType) { throw new BCException("trying to re-resolve"); } public TypePattern resolveBindingsFromRTTI(boolean allowBinding, boolean requireExactType) { throw new IllegalStateException("trying to re-resolve"); } }
81,863
Bug 81863 Annotation matching using within() PCD doesn't appear to be working.
null
resolved fixed
8a8930f
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-01-05T15:15:28Z
2004-12-23T16:40:00Z
weaver/src/org/aspectj/weaver/patterns/HandlerPointcut.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the 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.Member; import java.util.HashSet; import java.util.Set; 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.ast.Literal; import org.aspectj.weaver.ast.Test; import org.aspectj.weaver.internal.tools.PointcutExpressionImpl; /** * This is a kind of KindedPointcut. This belongs either in * a hierarchy with it or in a new place to share code * with other potential future statement-level pointcuts like * synchronized and throws */ public class HandlerPointcut extends Pointcut { TypePattern exceptionType; private static final Set MATCH_KINDS = new HashSet(); static { MATCH_KINDS.add(Shadow.ExceptionHandler); } public HandlerPointcut(TypePattern exceptionType) { this.exceptionType = exceptionType; this.pointcutKind = HANDLER; } public Set couldMatchKinds() { return MATCH_KINDS; } public FuzzyBoolean fastMatch(FastMatchInfo type) { //??? should be able to do better by finding all referenced types in type return FuzzyBoolean.MAYBE; } protected FuzzyBoolean matchInternal(Shadow shadow) { if (shadow.getKind() != Shadow.ExceptionHandler) return FuzzyBoolean.NO; // we know we have exactly one parameter since we're checking an exception handler return exceptionType.matches( shadow.getSignature().getParameterTypes()[0].resolve(shadow.getIWorld()), TypePattern.STATIC); } public FuzzyBoolean match(JoinPoint jp, JoinPoint.StaticPart jpsp) { if (!jp.getKind().equals(JoinPoint.EXCEPTION_HANDLER)) return FuzzyBoolean.NO; if (jp.getArgs().length > 0) { Object caughtException = jp.getArgs()[0]; return exceptionType.matches(caughtException,TypePattern.STATIC); } else { return FuzzyBoolean.NO; } } /* (non-Javadoc) * @see org.aspectj.weaver.patterns.Pointcut#matchesDynamically(java.lang.Object, java.lang.Object, java.lang.Object[]) */ public boolean matchesDynamically(Object thisObject, Object targetObject, Object[] args) { if (args.length > 0) { return (exceptionType.matches(args[0],TypePattern.STATIC) == FuzzyBoolean.YES); } else return false; } /* (non-Javadoc) * @see org.aspectj.weaver.patterns.Pointcut#matchesStatically(java.lang.String, java.lang.reflect.Member, java.lang.Class, java.lang.Class, java.lang.reflect.Member) */ public FuzzyBoolean matchesStatically(String joinpointKind, Member member, Class thisClass, Class targetClass, Member withinCode) { if (!(member instanceof PointcutExpressionImpl.Handler)) { return FuzzyBoolean.NO; } else { Class exceptionClass = ((PointcutExpressionImpl.Handler)member).getHandledExceptionType(); return exceptionType.matches(exceptionClass,TypePattern.STATIC); } } public boolean equals(Object other) { if (!(other instanceof HandlerPointcut)) return false; HandlerPointcut o = (HandlerPointcut)other; return o.exceptionType.equals(this.exceptionType); } public int hashCode() { int result = 17; result = 37*result + exceptionType.hashCode(); return result; } public String toString() { StringBuffer buf = new StringBuffer(); buf.append("handler("); buf.append(exceptionType.toString()); buf.append(")"); return buf.toString(); } public void write(DataOutputStream s) throws IOException { s.writeByte(Pointcut.HANDLER); exceptionType.write(s); writeLocation(s); } public static Pointcut read(DataInputStream s, ISourceContext context) throws IOException { HandlerPointcut ret = new HandlerPointcut(TypePattern.read(s, context)); ret.readLocation(context, s); return ret; } // XXX note: there is no namebinding in any kinded pointcut. // still might want to do something for better error messages // We want to do something here to make sure we don't sidestep the parameter // list in capturing type identifiers. public void resolveBindings(IScope scope, Bindings bindings) { exceptionType = exceptionType.resolveBindings(scope, bindings, false, false); //XXX add error if exact binding and not an exception } public void resolveBindingsFromRTTI() { exceptionType = exceptionType.resolveBindingsFromRTTI(false,false); } protected Test findResidueInternal(Shadow shadow, ExposedState state) { return match(shadow).alwaysTrue() ? Literal.TRUE : Literal.FALSE; } public Pointcut concretize1(ResolvedTypeX inAspect, IntMap bindings) { Pointcut ret = new HandlerPointcut(exceptionType); ret.copyLocationFrom(this); return ret; } }
81,863
Bug 81863 Annotation matching using within() PCD doesn't appear to be working.
null
resolved fixed
8a8930f
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-01-05T15:15:28Z
2004-12-23T16: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; import org.aspectj.weaver.WeaverMessages; /** * On creation, type pattern only contains WildTypePattern nodes, not BindingType or ExactType. * * <p>Then we call resolveBindings() during compilation * During concretization of enclosing pointcuts, we call remapAdviceFormals * * @author Erik Hilsdale * @author Jim Hugunin */ public abstract class TypePattern extends PatternNode { public static class MatchKind { private String name; public MatchKind(String name) { this.name = name; } public String toString() { return name; } } public static final MatchKind STATIC = new MatchKind("STATIC"); public static final MatchKind DYNAMIC = new MatchKind("DYNAMIC"); public static final TypePattern ELLIPSIS = new EllipsisTypePattern(); public static final TypePattern ANY = new AnyTypePattern(); public static final TypePattern NO = new NoTypePattern(); protected boolean includeSubtypes; protected boolean isVarArgs = false; protected AnnotationTypePattern annotationPattern = AnnotationTypePattern.ANY; protected TypePattern(boolean includeSubtypes,boolean isVarArgs) { this.includeSubtypes = includeSubtypes; this.isVarArgs = isVarArgs; } protected TypePattern(boolean includeSubtypes) { this(includeSubtypes,false); } public void setAnnotationTypePattern(AnnotationTypePattern annPatt) { this.annotationPattern = annPatt; } // answer conservatively... protected boolean couldEverMatchSameTypesAs(TypePattern other) { if (this.includeSubtypes || other.includeSubtypes) return true; if (this.annotationPattern != AnnotationTypePattern.ANY) return true; if (other.annotationPattern != AnnotationTypePattern.ANY) return true; return false; } //XXX non-final for Not, && and || public boolean matchesStatically(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) { FuzzyBoolean typeMatch = null; //??? This is part of gracefully handling missing references if (type == ResolvedTypeX.MISSING) return FuzzyBoolean.NO; if (kind == STATIC) { typeMatch = FuzzyBoolean.fromBoolean(matchesStatically(type)); return typeMatch.and(annotationPattern.matches(type)); } else if (kind == DYNAMIC) { //System.err.println("matching: " + this + " with " + type); typeMatch = matchesInstanceof(type); //System.err.println(" got: " + ret); return typeMatch.and(annotationPattern.matches(type)); } 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( WeaverMessages.format(WeaverMessages.EXACT_TYPE_PATTERN_REQD), getSourceLocation())); return NO; } // public boolean assertExactType(IMessageHandler m) { // if (this instanceof ExactTypePattern) return true; // // //XXX should try harder to avoid multiple errors for one problem // m.handleMessage(MessageUtil.error("exact type pattern required", getSourceLocation())); // return false; // } /** * This can modify in place, or return a new TypePattern if the type changes. */ public TypePattern resolveBindings(IScope scope, Bindings bindings, boolean allowBinding, boolean requireExactType) { annotationPattern = annotationPattern.resolveBindings(scope,bindings,allowBinding); return this; } public 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,false); } /* (non-Javadoc) * @see org.aspectj.weaver.patterns.TypePattern#couldEverMatchSameTypesAs(org.aspectj.weaver.patterns.TypePattern) */ protected boolean couldEverMatchSameTypesAs(TypePattern other) { return true; } /** * @see org.aspectj.weaver.patterns.TypePattern#matchesExactly(IType) */ protected boolean matchesExactly(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 ".."; } /* (non-Javadoc) * @see java.lang.Object#equals(java.lang.Object) */ public boolean equals(Object obj) { return (obj instanceof EllipsisTypePattern); } /* (non-Javadoc) * @see java.lang.Object#hashCode() */ public int hashCode() { return 17 * 37; } } class AnyTypePattern extends TypePattern { /** * Constructor for EllipsisTypePattern. * @param includeSubtypes */ public AnyTypePattern() { super(false,false); } /* (non-Javadoc) * @see org.aspectj.weaver.patterns.TypePattern#couldEverMatchSameTypesAs(org.aspectj.weaver.patterns.TypePattern) */ protected boolean couldEverMatchSameTypesAs(TypePattern other) { return true; } /** * @see org.aspectj.weaver.patterns.TypePattern#matchesExactly(IType) */ protected boolean matchesExactly(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 "*"; } public boolean equals(Object obj) { return (obj instanceof AnyTypePattern); } public int hashCode() { return 37; } } class NoTypePattern extends TypePattern { public NoTypePattern() { super(false,false); } /* (non-Javadoc) * @see org.aspectj.weaver.patterns.TypePattern#couldEverMatchSameTypesAs(org.aspectj.weaver.patterns.TypePattern) */ protected boolean couldEverMatchSameTypesAs(TypePattern other) { return false; } /** * @see org.aspectj.weaver.patterns.TypePattern#matchesExactly(IType) */ protected boolean matchesExactly(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>"; } /* (non-Javadoc) * @see java.lang.Object#equals(java.lang.Object) */ public boolean equals(Object obj) { return (obj instanceof NoTypePattern); } /* (non-Javadoc) * @see java.lang.Object#hashCode() */ public int hashCode() { return 17 * 37 * 37; } }
81,863
Bug 81863 Annotation matching using within() PCD doesn't appear to be working.
null
resolved fixed
8a8930f
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-01-05T15:15:28Z
2004-12-23T16: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.BCException; import org.aspectj.weaver.ISourceContext; import org.aspectj.weaver.ResolvedTypeX; import org.aspectj.weaver.TypeX; import org.aspectj.weaver.WeaverMessages; //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, boolean isVarArgs) { super(includeSubtypes,isVarArgs); this.namePatterns = namePatterns; this.dim = dim; ellipsisCount = 0; for (int i=0; i<namePatterns.length; i++) { if (namePatterns[i] == NamePattern.ELLIPSIS) ellipsisCount++; } setLocation(namePatterns[0].getSourceContext(), namePatterns[0].getStart(), namePatterns[namePatterns.length-1].getEnd()); } public WildTypePattern(List names, boolean includeSubtypes, int dim) { this((NamePattern[])names.toArray(new NamePattern[names.size()]), includeSubtypes, dim,false); } public WildTypePattern(List names, boolean includeSubtypes, int dim, int endPos) { this(names, includeSubtypes, dim); this.end = endPos; } public WildTypePattern(List names, boolean includeSubtypes, int dim, int endPos, boolean isVarArg) { this(names, includeSubtypes, dim); this.end = endPos; this.isVarArgs = isVarArg; } /* (non-Javadoc) * @see org.aspectj.weaver.patterns.TypePattern#couldEverMatchSameTypesAs(org.aspectj.weaver.patterns.TypePattern) */ protected boolean couldEverMatchSameTypesAs(TypePattern other) { if (super.couldEverMatchSameTypesAs(other)) return true; // false is necessary but not sufficient TypeX otherType = other.getExactType(); if (otherType != ResolvedTypeX.MISSING) { if (namePatterns.length > 0) { if (!namePatterns[0].matches(otherType.getName())) return false; } } if (other instanceof WildTypePattern) { WildTypePattern owtp = (WildTypePattern) other; String mySimpleName = namePatterns[0].maybeGetSimpleName(); String yourSimpleName = owtp.namePatterns[0].maybeGetSimpleName(); if (mySimpleName != null && yourSimpleName != null) { return (mySimpleName.startsWith(yourSimpleName) || yourSimpleName.startsWith(mySimpleName)); } } return true; } //XXX inefficient implementation 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); } /** * Used in conjunction with checks on 'isStar()' to tell you if this pattern represents '*' or '*[]' which are * different ! */ public int getDimensions() { return dim; } /** * @param targetTypeName * @return */ private boolean matchesExactlyByName(String targetTypeName) { //XXX hack if (knownMatches == null && importedPrefixes == null) { return innerMatchesExactly(targetTypeName); } if (isStar()) { // we match if the dimensions match int numDimensionsInTargetType = 0; if (dim > 0) { int index; while((index = targetTypeName.indexOf('[')) != -1) { numDimensionsInTargetType++; targetTypeName = targetTypeName.substring(index+1); } if (numDimensionsInTargetType == dim) { return true; } else { return false; } } } // if our pattern is length 1, then known matches are exact matches // if it's longer than that, then known matches are prefixes of a sort if (namePatterns.length == 1) { 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() && (annotationPattern == AnnotationTypePattern.ANY)) { if (dim == 0) { // pr72531 return TypePattern.ANY; //??? loses source location } } annotationPattern = annotationPattern.resolveBindings(scope,bindings,allowBinding); String simpleName = maybeGetSimpleName(); if (simpleName != null) { FormalBinding formalBinding = scope.lookupFormal(simpleName); if (formalBinding != null) { if (bindings == null) { scope.message(IMessage.ERROR, this, "negation doesn't allow binding"); return this; } if (!allowBinding) { scope.message(IMessage.ERROR, this, "name binding only allowed in target, this, and args pcds"); return this; } BindingTypePattern binding = new BindingTypePattern(formalBinding,isVarArgs); binding.copyLocationFrom(this); bindings.register(binding, scope); return binding; } } String cleanName = maybeGetCleanName(); String originalName = cleanName; // if we discover it is 'MISSING' when searching via the scope, this next local var will // tell us if it is really missing or if it does exist in the world and we just can't // see it from the current scope. ResolvedTypeX resolvedTypeInTheWorld = null; if (cleanName != null) { TypeX type; //System.out.println("resolve: " + cleanName); //??? this loop has too many inefficiencies to count resolvedTypeInTheWorld = scope.getWorld().resolve(TypeX.forName(cleanName),true); 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 (resolvedTypeInTheWorld == ResolvedTypeX.MISSING) resolvedTypeInTheWorld = scope.getWorld().resolve(TypeX.forName(cleanName),true); } if (type == ResolvedTypeX.MISSING) { if (requireExactType) { if (!allowBinding) { scope.getWorld().getMessageHandler().handleMessage( MessageUtil.error(WeaverMessages.format(WeaverMessages.CANT_BIND_TYPE,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()) { // Only put the lint warning out if we can't find it in the world if (resolvedTypeInTheWorld == ResolvedTypeX.MISSING) scope.getWorld().getLint().invalidAbsoluteTypeName.signal(originalName, getSourceLocation()); } } else { if (dim != 0) type = TypeX.makeArray(type, dim); TypePattern ret = new ExactTypePattern(type, includeSubtypes,isVarArgs); ret.copyLocationFrom(this); return ret; } } else { if (requireExactType) { scope.getWorld().getMessageHandler().handleMessage( MessageUtil.error(WeaverMessages.format(WeaverMessages.WILDCARD_NOT_ALLOWED), 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,isVarArgs); 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(); if (annotationPattern != AnnotationTypePattern.ANY) { buf.append('('); buf.append(annotationPattern.toString()); buf.append(' '); } for (int i=0, len=namePatterns.length; i < len; i++) { NamePattern name = namePatterns[i]; if (name == null) { buf.append("."); } else { if (i > 0) buf.append("."); buf.append(name.toString()); } } if (includeSubtypes) buf.append('+'); if (annotationPattern != AnnotationTypePattern.ANY) { buf.append(')'); } return buf.toString(); } public boolean equals(Object other) { if (!(other instanceof WildTypePattern)) return false; WildTypePattern o = (WildTypePattern)other; int len = o.namePatterns.length; if (len != this.namePatterns.length) return false; if (this.includeSubtypes != o.includeSubtypes) return false; if (this.dim != o.dim) return false; if (this.isVarArgs != o.isVarArgs) return false; for (int i=0; i < len; i++) { if (!o.namePatterns[i].equals(this.namePatterns[i])) return false; } return (o.annotationPattern.equals(this.annotationPattern)); } public int hashCode() { int result = 17; for (int i = 0, len = namePatterns.length; i < len; i++) { result = 37*result + namePatterns[i].hashCode(); } result = 37*result + annotationPattern.hashCode(); return result; } public FuzzyBoolean matchesInstanceof(Class type) { return FuzzyBoolean.NO; } public boolean matchesExactly(Class type) { return matchesExactlyByName(type.getName()); } private static final byte VERSION = 1; // rev on change /** * @see org.aspectj.weaver.patterns.PatternNode#write(DataOutputStream) */ public void write(DataOutputStream s) throws IOException { s.writeByte(TypePattern.WILD); s.writeByte(VERSION); s.writeShort(namePatterns.length); for (int i = 0; i < namePatterns.length; i++) { namePatterns[i].write(s); } s.writeBoolean(includeSubtypes); s.writeInt(dim); s.writeBoolean(isVarArgs); //??? storing this information with every type pattern is wasteful of .class // file size. Storing it on enclosing types would be more efficient FileUtil.writeStringArray(knownMatches, s); FileUtil.writeStringArray(importedPrefixes, s); writeLocation(s); annotationPattern.write(s); } public static TypePattern read(DataInputStream s, ISourceContext context) throws IOException { byte version = s.readByte(); if (version > VERSION) { throw new BCException("WildTypePattern was written by a more recent version of AspectJ, cannot read"); } int len = s.readShort(); NamePattern[] namePatterns = new NamePattern[len]; for (int i=0; i < len; i++) { namePatterns[i] = NamePattern.read(s); } boolean includeSubtypes = s.readBoolean(); int dim = s.readInt(); boolean varArg = s.readBoolean(); WildTypePattern ret = new WildTypePattern(namePatterns, includeSubtypes, dim,varArg); ret.knownMatches = FileUtil.readStringArray(s); ret.importedPrefixes = FileUtil.readStringArray(s); ret.readLocation(context, s); ret.setAnnotationTypePattern(AnnotationTypePattern.read(s,context)); return ret; } }
81,863
Bug 81863 Annotation matching using within() PCD doesn't appear to be working.
null
resolved fixed
8a8930f
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-01-05T15:15:28Z
2004-12-23T16:40:00Z
weaver/src/org/aspectj/weaver/patterns/WithinPointcut.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Common Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * PARC initial implementation * ******************************************************************/ package org.aspectj.weaver.patterns; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.lang.reflect.Member; import java.util.Set; import org.aspectj.bridge.IMessage; import org.aspectj.bridge.ISourceLocation; import org.aspectj.bridge.Message; 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.WeaverMessages; import org.aspectj.weaver.ast.Literal; import org.aspectj.weaver.ast.Test; public class WithinPointcut extends Pointcut { TypePattern typePattern; public WithinPointcut(TypePattern type) { this.typePattern = type; this.pointcutKind = WITHIN; } private FuzzyBoolean isWithinType(ResolvedTypeX type) { while (type != null) { if (typePattern.matchesStatically(type)) { return FuzzyBoolean.YES; } type = type.getDeclaringType(); } return FuzzyBoolean.NO; } public Set couldMatchKinds() { return Shadow.ALL_SHADOW_KINDS; } public FuzzyBoolean fastMatch(FastMatchInfo info) { return isWithinType(info.getType()); } protected FuzzyBoolean matchInternal(Shadow shadow) { ResolvedTypeX enclosingType = shadow.getIWorld().resolve(shadow.getEnclosingType(),true); if (enclosingType == ResolvedTypeX.MISSING) { IMessage msg = new Message( WeaverMessages.format(WeaverMessages.CANT_FIND_TYPE_WITHINPCD, shadow.getEnclosingType().getName()), shadow.getSourceLocation(),true,new ISourceLocation[]{getSourceLocation()}); shadow.getIWorld().getMessageHandler().handleMessage(msg); } return isWithinType(enclosingType); } public FuzzyBoolean match(JoinPoint jp, JoinPoint.StaticPart encJp) { return isWithinType(encJp.getSignature().getDeclaringType()); } /* (non-Javadoc) * @see org.aspectj.weaver.patterns.Pointcut#matchesDynamically(java.lang.Object, java.lang.Object, java.lang.Object[]) */ public boolean matchesDynamically(Object thisObject, Object targetObject, Object[] args) { return true; } /* (non-Javadoc) * @see org.aspectj.weaver.patterns.Pointcut#matchesStatically(java.lang.String, java.lang.reflect.Member, java.lang.Class, java.lang.Class, java.lang.reflect.Member) */ public FuzzyBoolean matchesStatically( String joinpointKind, Member member, Class thisClass, Class targetClass, Member withinCode) { if ((member != null) && !(joinpointKind.equals(Shadow.ConstructorCall.getName()) || joinpointKind.equals(Shadow.MethodCall.getName()) || joinpointKind.equals(Shadow.FieldGet.getName()) || joinpointKind.equals(Shadow.FieldSet.getName())) ) { return isWithinType(member.getDeclaringClass()); } else { return isWithinType(thisClass); } } private FuzzyBoolean isWithinType(Class type) { while (type != null) { if (typePattern.matchesStatically(type)) { return FuzzyBoolean.YES; } type = type.getDeclaringClass(); } return FuzzyBoolean.NO; } public void write(DataOutputStream s) throws IOException { s.writeByte(Pointcut.WITHIN); typePattern.write(s); writeLocation(s); } public static Pointcut read(DataInputStream s, ISourceContext context) throws IOException { TypePattern type = TypePattern.read(s, context); WithinPointcut ret = new WithinPointcut(type); ret.readLocation(context, s); return ret; } public void resolveBindings(IScope scope, Bindings bindings) { typePattern = typePattern.resolveBindings(scope, bindings, false, false); } public void resolveBindingsFromRTTI() { typePattern = typePattern.resolveBindingsFromRTTI(false,false); } public void postRead(ResolvedTypeX enclosingType) { typePattern.postRead(enclosingType); } public boolean couldEverMatchSameJoinPointsAs(WithinPointcut other) { return typePattern.couldEverMatchSameTypesAs(other.typePattern); } public boolean equals(Object other) { if (!(other instanceof WithinPointcut)) return false; WithinPointcut o = (WithinPointcut)other; return o.typePattern.equals(this.typePattern); } public int hashCode() { int result = 43; result = 37*result + typePattern.hashCode(); return result; } public String toString() { return "within(" + typePattern + ")"; } protected Test findResidueInternal(Shadow shadow, ExposedState state) { return match(shadow).alwaysTrue() ? Literal.TRUE : Literal.FALSE; } public Pointcut concretize1(ResolvedTypeX inAspect, IntMap bindings) { Pointcut ret = new WithinPointcut(typePattern); ret.copyLocationFrom(this); return ret; } }
82,134
Bug 82134 AspectJ 5 M2 should implement backwards compatibility for binary aspect form
null
resolved fixed
797b6a6
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-01-07T14:14:45Z
2005-01-04T14:46:40Z
tests/src/org/aspectj/systemtest/ajc150/AllTestsJava5_binaryWeaving.java
/******************************************************************************* * Copyright (c) 2004 IBM * All rights reserved. This program and the accompanying materials * are made available under the terms of the Common Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * Andy Clement - initial API and implementation *******************************************************************************/ package org.aspectj.systemtest.ajc150; import junit.framework.Test; import junit.framework.TestSuite; /** * @author colyer * * TODO To change the template for this generated type comment go to * Window - Preferences - Java - Code Style - Code Templates */ public class AllTestsJava5_binaryWeaving { public static Test suite() { TestSuite suite = new TestSuite("Java5 - binary weaving"); //$JUnit-BEGIN$ suite.addTest(Ajc150Tests.suite()); suite.addTest(AccBridgeMethods.suite()); suite.addTestSuite(CovarianceTests.class); suite.addTestSuite(Enums.class); suite.addTestSuite(Annotations.class); suite.addTestSuite(AnnotationPointcutsTests.class); suite.addTestSuite(VarargsTests.class); suite.addTestSuite(AnnotationRuntimeTests.class); //$JUnit-END$ return suite; } }
82,134
Bug 82134 AspectJ 5 M2 should implement backwards compatibility for binary aspect form
null
resolved fixed
797b6a6
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-01-07T14:14:45Z
2005-01-04T14:46:40Z
tests/src/org/aspectj/systemtest/ajc150/MigrationTests.java
82,134
Bug 82134 AspectJ 5 M2 should implement backwards compatibility for binary aspect form
null
resolved fixed
797b6a6
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-01-07T14:14:45Z
2005-01-04T14:46:40Z
weaver/src/org/aspectj/weaver/AdviceKind.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 org.aspectj.util.TypeSafeEnum; /** * The 5 kinds of advice in AspectJ. * * @author Erik Hilsdale * @author Jim Hugunin */ public class AdviceKind extends TypeSafeEnum { private int precedence; private boolean isAfter; private boolean isCflow; public AdviceKind(String name, int key, int precedence, boolean isAfter, boolean isCflow) { super(name, key); this.precedence = precedence; this.isAfter = isAfter; this.isCflow = isCflow; } public static AdviceKind read(DataInputStream s) throws IOException { int key = s.readByte(); switch(key) { case 1: return Before; case 2: return After; case 3: return AfterThrowing; case 4: return AfterReturning; case 5: return Around; case 6: return CflowEntry; case 7: return CflowBelowEntry; case 8: return InterInitializer; case 9: return PerCflowEntry; case 10: return PerCflowBelowEntry; case 11: return PerThisEntry; case 12: return PerTargetEntry; case 13: return Softener; } throw new RuntimeException("unimplemented kind: " + key); } public static final AdviceKind Before = new AdviceKind("before", 1, 0, false, false); public static final AdviceKind After = new AdviceKind("after", 2, 0, true, false); public static final AdviceKind AfterThrowing = new AdviceKind("afterThrowing", 3, 0, true, false); public static final AdviceKind AfterReturning = new AdviceKind("afterReturning", 4, 0, true, false); public static final AdviceKind Around = new AdviceKind("around", 5, 0, false, false); // these kinds can't be declared, but are used by the weaver public static final AdviceKind CflowEntry = new AdviceKind("cflowEntry", 6, 1, false, true); public static final AdviceKind CflowBelowEntry = new AdviceKind("cflowBelowEntry", 7, -1, false, true); //XXX resolve precednece with the below public static final AdviceKind InterInitializer = new AdviceKind("interInitializer", 8, -2, false, false); public static final AdviceKind PerCflowEntry = new AdviceKind("perCflowEntry", 9, 1, false, true); public static final AdviceKind PerCflowBelowEntry = new AdviceKind("perCflowBelowEntry", 10, -1, false, true); public static final AdviceKind PerThisEntry = new AdviceKind("perThisEntry", 11, 1, false, false); public static final AdviceKind PerTargetEntry = new AdviceKind("perTargetEntry", 12, 1, false, false); public static final AdviceKind Softener = new AdviceKind("softener", 13, 1, false, false); public static AdviceKind stringToKind(String s) { if (s.equals(Before.getName())) return Before; if (s.equals(After.getName())) return After; if (s.equals(AfterThrowing.getName())) return AfterThrowing; if (s.equals(AfterReturning.getName())) return AfterReturning; if (s.equals(Around.getName())) return Around; throw new IllegalArgumentException("unknown kind: " + "\"" + s + "\""); } public boolean isAfter() { return this.isAfter; } public boolean isCflow() { return this.isCflow; } public int getPrecedence() { return precedence; } public boolean isPerEntry() { return this == PerCflowEntry || this == PerCflowBelowEntry || this == PerThisEntry || this == PerTargetEntry; } public boolean isPerObjectEntry() { return this == PerThisEntry || this == PerTargetEntry; } }
82,134
Bug 82134 AspectJ 5 M2 should implement backwards compatibility for binary aspect form
null
resolved fixed
797b6a6
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-01-07T14:14:45Z
2005-01-04T14:46:40Z
weaver/src/org/aspectj/weaver/AjAttribute.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the 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.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.aspectj.bridge.IMessageHandler; import org.aspectj.bridge.MessageUtil; import org.aspectj.util.FileUtil; import org.aspectj.weaver.patterns.Declare; import org.aspectj.weaver.patterns.PerClause; import org.aspectj.weaver.patterns.Pointcut; /** * These attributes are written to and read from .class files (see the JVM spec). * * <p>Each member or type can have a number of AjAttributes. Each * such attribute is in 1-1 correspondence with an Unknown bcel attribute. * Creating one of these does NOTHING to the underlying thing, so if you really * want to add an attribute to a particular thing, well, you'd better actually do that. * * @author Erik Hilsdale * @author Jim Hugunin */ public abstract class AjAttribute { public static final String AttributePrefix = "org.aspectj.weaver"; protected abstract void write(DataOutputStream s) throws IOException; public abstract String getNameString(); public char[] getNameChars() { return getNameString().toCharArray(); } /** * Just writes the contents */ public byte[] getBytes() { try { ByteArrayOutputStream b0 = new ByteArrayOutputStream(); DataOutputStream s0 = new DataOutputStream(b0); write(s0); return b0.toByteArray(); } catch (IOException e) { // shouldn't happen with ByteArrayOutputStreams throw new RuntimeException("sanity check"); } } /** * Writes the full attribute, i.e. name_index, length, and contents */ public byte[] getAllBytes(short nameIndex) { try { byte[] bytes = getBytes(); ByteArrayOutputStream b0 = new ByteArrayOutputStream(); DataOutputStream s0 = new DataOutputStream(b0); s0.writeShort(nameIndex); s0.writeInt(bytes.length); s0.write(bytes); return b0.toByteArray(); } catch (IOException e) { // shouldn't happen with ByteArrayOutputStreams throw new RuntimeException("sanity check"); } } public static AjAttribute read(String name, byte[] bytes, ISourceContext context,IMessageHandler msgHandler) { try { if (bytes == null) bytes = new byte[0]; DataInputStream s = new DataInputStream(new ByteArrayInputStream(bytes)); if (name.equals(Aspect.AttributeName)) { return new Aspect(PerClause.readPerClause(s, context)); } else if (name.equals(MethodDeclarationLineNumberAttribute.AttributeName)) { return MethodDeclarationLineNumberAttribute.read(s); } else if (name.equals(WeaverState.AttributeName)) { return new WeaverState(WeaverStateInfo.read(s, context)); } else if (name.equals(WeaverVersionInfo.AttributeName)) { return WeaverVersionInfo.read(s); } else if (name.equals(AdviceAttribute.AttributeName)) { return AdviceAttribute.read(s, context); } else if (name.equals(PointcutDeclarationAttribute.AttributeName)) { return new PointcutDeclarationAttribute(ResolvedPointcutDefinition.read(s, context)); } else if (name.equals(TypeMunger.AttributeName)) { return new TypeMunger(ResolvedTypeMunger.read(s, context)); } else if (name.equals(AjSynthetic.AttributeName)) { return new AjSynthetic(); } else if (name.equals(DeclareAttribute.AttributeName)) { return new DeclareAttribute(Declare.read(s, context)); } else if (name.equals(PrivilegedAttribute.AttributeName)) { return PrivilegedAttribute.read(s, context); } else if (name.equals(SourceContextAttribute.AttributeName)) { return SourceContextAttribute.read(s); } else if (name.equals(EffectiveSignatureAttribute.AttributeName)) { return EffectiveSignatureAttribute.read(s, context); } else { // We have to tell the user about this... if (msgHandler == null) throw new BCException("unknown attribute" + name); msgHandler.handleMessage(MessageUtil.warn("unknown attribute encountered "+name)); return null; } } catch (IOException e) { throw new BCException("malformed " + name + " attribute " + e); } } //---- /** Synthetic members should have NO advice put on them or on their contents. * This attribute is currently unused as we consider all members starting * with NameMangler.PREFIX to automatically be synthetic. As we use this we might * find that we want multiple * kinds of synthetic. In particular, if we want to treat the call to a synthetic getter * (say, of an introduced field) as a field reference itself, then a method might want * a particular kind of AjSynthetic attribute that also includes a signature of what * it stands for. */ public static class AjSynthetic extends AjAttribute { public static final String AttributeName = "org.aspectj.weaver.AjSynthetic"; public String getNameString() { return AttributeName; } // private ResolvedTypeMunger munger; public AjSynthetic() {} public void write(DataOutputStream s) throws IOException {} } public static class TypeMunger extends AjAttribute { public static final String AttributeName = "org.aspectj.weaver.TypeMunger"; public String getNameString() { return AttributeName; } private ResolvedTypeMunger munger; public TypeMunger(ResolvedTypeMunger munger) { this.munger = munger; } public void write(DataOutputStream s) throws IOException { munger.write(s); } public ConcreteTypeMunger reify(World world, ResolvedTypeX aspectType) { return world.concreteTypeMunger(munger, aspectType); } } public static class WeaverState extends AjAttribute { public static final String AttributeName = "org.aspectj.weaver.WeaverState"; public String getNameString() { return AttributeName; } private WeaverStateInfo kind; public WeaverState(WeaverStateInfo kind) { this.kind = kind; } public void write(DataOutputStream s) throws IOException { kind.write(s); } public WeaverStateInfo reify() { return kind; } } public static class WeaverVersionInfo extends AjAttribute { public static final String AttributeName = "org.aspectj.weaver.WeaverVersion"; // If you change the format of an AspectJ class file, you have two options: // - changing the minor version means you have not added anything that prevents // previous versions of the weaver from operating (e.g. MethodDeclarationLineNumber attribute) // - changing the major version means you have added something that prevents previous // versions of the weaver from operating correctly. // // The user will get a warning for any org.aspectj.weaver attributes the weaver does // not recognize. // These are the weaver major/minor numbers for AspectJ 1.2.1 private static short WEAVER_VERSION_MAJOR_AJ121 = 1; private static short WEAVER_VERSION_MINOR_AJ121 = 0; // These are the weaver major/minor versions for *this* weaver private static short CURRENT_VERSION_MAJOR = WEAVER_VERSION_MAJOR_AJ121; private static short CURRENT_VERSION_MINOR = WEAVER_VERSION_MINOR_AJ121; // These are the versions read in from a particular class file. private short major_version; private short minor_version; public String getNameString() { return AttributeName; } // Default ctor uses the current version numbers public WeaverVersionInfo() { this.major_version = CURRENT_VERSION_MAJOR; this.minor_version = CURRENT_VERSION_MINOR; } public WeaverVersionInfo(short major,short minor) { major_version = major; minor_version = minor; } public void write(DataOutputStream s) throws IOException { s.writeShort(CURRENT_VERSION_MAJOR); s.writeShort(CURRENT_VERSION_MINOR); } public static WeaverVersionInfo read(DataInputStream s) throws IOException { short major = s.readShort(); short minor = s.readShort(); return new WeaverVersionInfo(major,minor); } public short getMajorVersion() { return major_version; } public short getMinorVersion() { return minor_version; } public static short getCurrentWeaverMajorVersion() { return CURRENT_VERSION_MAJOR; } public static short getCurrentWeaverMinorVersion() { return CURRENT_VERSION_MINOR; } public String toString() { return major_version+"."+minor_version; } public static String toCurrentVersionString() { return CURRENT_VERSION_MAJOR+"."+CURRENT_VERSION_MINOR; } } public static class SourceContextAttribute extends AjAttribute { public static final String AttributeName = "org.aspectj.weaver.SourceContext"; public String getNameString() { return AttributeName; } private String sourceFileName; private int[] lineBreaks; public SourceContextAttribute(String sourceFileName, int[] lineBreaks) { this.sourceFileName = sourceFileName; this.lineBreaks = lineBreaks; } public void write(DataOutputStream s) throws IOException { s.writeUTF(sourceFileName); FileUtil.writeIntArray(lineBreaks, s); } public static SourceContextAttribute read(DataInputStream s) throws IOException { return new SourceContextAttribute(s.readUTF(), FileUtil.readIntArray(s)); } public int[] getLineBreaks() { return lineBreaks; } public String getSourceFileName() { return sourceFileName; } } public static class MethodDeclarationLineNumberAttribute extends AjAttribute { public static final String AttributeName = "org.aspectj.weaver.MethodDeclarationLineNumber"; public String getNameString() { return AttributeName; } private int lineNumber; public MethodDeclarationLineNumberAttribute(int line) { this.lineNumber = line; } public int getLineNumber() { return lineNumber; } public void write(DataOutputStream s) throws IOException { s.writeInt(lineNumber); } public static MethodDeclarationLineNumberAttribute read(DataInputStream s) throws IOException { return new MethodDeclarationLineNumberAttribute(s.readInt()); } public String toString() { return AttributeName + ": " + lineNumber; } } public static class PointcutDeclarationAttribute extends AjAttribute { public static final String AttributeName = "org.aspectj.weaver.PointcutDeclaration"; public String getNameString() { return AttributeName; } private ResolvedPointcutDefinition pointcutDef; public PointcutDeclarationAttribute(ResolvedPointcutDefinition pointcutDef) { this.pointcutDef = pointcutDef; } public void write(DataOutputStream s) throws IOException { pointcutDef.write(s); } public ResolvedPointcutDefinition reify() { return pointcutDef; } } public static class DeclareAttribute extends AjAttribute { public static final String AttributeName = "org.aspectj.weaver.Declare"; public String getNameString() { return AttributeName; } private Declare declare; public DeclareAttribute(Declare declare) { this.declare = declare; } public void write(DataOutputStream s) throws IOException { declare.write(s); } public Declare getDeclare() { return declare; } } public static class AdviceAttribute extends AjAttribute { public static final String AttributeName = "org.aspectj.weaver.Advice"; public String getNameString() { return AttributeName; } private AdviceKind kind; private Pointcut pointcut; private int extraParameterFlags; private int start; private int end; private ISourceContext sourceContext; // these are only used by around advice private boolean proceedInInners; private ResolvedMember[] proceedCallSignatures; // size == # of proceed calls in body private boolean[] formalsUnchangedToProceed; // size == formals.size private TypeX[] declaredExceptions; /** * @param lexicalPosition must be greater than the lexicalPosition * of any advice declared before this one in an aspect, otherwise, * it can be any value. */ public AdviceAttribute(AdviceKind kind, Pointcut pointcut, int extraArgumentFlags, int start, int end, ISourceContext sourceContext) { this.kind = kind; this.pointcut = pointcut; this.extraParameterFlags = extraArgumentFlags; this.start = start; this.end = end; this.sourceContext = sourceContext; //XXX put this back when testing works better (or fails better) //if (kind == AdviceKind.Around) throw new IllegalArgumentException("not for around"); } public AdviceAttribute(AdviceKind kind, Pointcut pointcut, int extraArgumentFlags, int start, int end, ISourceContext sourceContext, boolean proceedInInners, ResolvedMember[] proceedCallSignatures, boolean[] formalsUnchangedToProceed, TypeX[] declaredExceptions) { this.kind = kind; this.pointcut = pointcut; this.extraParameterFlags = extraArgumentFlags; this.start = start; this.end = end; this.sourceContext = sourceContext; if (kind != AdviceKind.Around) throw new IllegalArgumentException("only for around"); this.proceedInInners = proceedInInners; this.proceedCallSignatures = proceedCallSignatures; this.formalsUnchangedToProceed = formalsUnchangedToProceed; this.declaredExceptions = declaredExceptions; } public static AdviceAttribute read(DataInputStream s, ISourceContext context) throws IOException { AdviceKind kind = AdviceKind.read(s); if (kind == AdviceKind.Around) { return new AdviceAttribute( kind, Pointcut.read(s, context), s.readByte(), s.readInt(), s.readInt(), context, s.readBoolean(), ResolvedMember.readResolvedMemberArray(s, context), FileUtil.readBooleanArray(s), TypeX.readArray(s)); } else { return new AdviceAttribute( kind, Pointcut.read(s, context), s.readByte(), s.readInt(), s.readInt(), context); } } public void write(DataOutputStream s) throws IOException { kind.write(s); pointcut.write(s); s.writeByte(extraParameterFlags); s.writeInt(start); s.writeInt(end); if (kind == AdviceKind.Around) { s.writeBoolean(proceedInInners); ResolvedMember.writeArray(proceedCallSignatures, s); FileUtil.writeBooleanArray(formalsUnchangedToProceed, s); TypeX.writeArray(declaredExceptions, s); } } public Advice reify(Member signature, World world) { return world.concreteAdvice(this, pointcut, signature); } public String toString() { return "AdviceAttribute(" + kind + ", " + pointcut + ", " + extraParameterFlags + ", " + start+")"; } public int getExtraParameterFlags() { return extraParameterFlags; } public AdviceKind getKind() { return kind; } public Pointcut getPointcut() { return pointcut; } public TypeX[] getDeclaredExceptions() { return declaredExceptions; } public boolean[] getFormalsUnchangedToProceed() { return formalsUnchangedToProceed; } public ResolvedMember[] getProceedCallSignatures() { return proceedCallSignatures; } public boolean isProceedInInners() { return proceedInInners; } public int getEnd() { return end; } public ISourceContext getSourceContext() { return sourceContext; } public int getStart() { return start; } } public static class Aspect extends AjAttribute { public static final String AttributeName = "org.aspectj.weaver.Aspect"; public String getNameString() { return AttributeName; } private PerClause perClause; public Aspect(PerClause perClause) { this.perClause = perClause; } public PerClause reify(ResolvedTypeX inAspect) { //XXXperClause.concretize(inAspect); return perClause; } public void write(DataOutputStream s) throws IOException { perClause.write(s); } } public static class PrivilegedAttribute extends AjAttribute { public static final String AttributeName = "org.aspectj.weaver.Privileged"; public String getNameString() { return AttributeName; } private ResolvedMember[] accessedMembers; public PrivilegedAttribute(ResolvedMember[] accessedMembers) { this.accessedMembers = accessedMembers; } public void write(DataOutputStream s) throws IOException { ResolvedMember.writeArray(accessedMembers, s); } public ResolvedMember[] getAccessedMembers() { return accessedMembers; } public static PrivilegedAttribute read(DataInputStream s, ISourceContext context) throws IOException { return new PrivilegedAttribute(ResolvedMember.readResolvedMemberArray(s, context)); } } public static class EffectiveSignatureAttribute extends AjAttribute { public static final String AttributeName = "org.aspectj.weaver.EffectiveSignature"; public String getNameString() { return AttributeName; } private ResolvedMember effectiveSignature; private Shadow.Kind shadowKind; private boolean weaveBody; public EffectiveSignatureAttribute(ResolvedMember effectiveSignature, Shadow.Kind shadowKind, boolean weaveBody) { this.effectiveSignature = effectiveSignature; this.shadowKind = shadowKind; this.weaveBody = weaveBody; } public void write(DataOutputStream s) throws IOException { effectiveSignature.write(s); shadowKind.write(s); s.writeBoolean(weaveBody); } public static EffectiveSignatureAttribute read(DataInputStream s, ISourceContext context) throws IOException { return new EffectiveSignatureAttribute( ResolvedMember.readResolvedMember(s, context), Shadow.Kind.read(s), s.readBoolean()); } public ResolvedMember getEffectiveSignature() { return effectiveSignature; } public String toString() { return "EffectiveSignatureAttribute(" + effectiveSignature + ", " + shadowKind + ")"; } public Shadow.Kind getShadowKind() { return shadowKind; } public boolean isWeaveBody() { return weaveBody; } } }
82,134
Bug 82134 AspectJ 5 M2 should implement backwards compatibility for binary aspect form
null
resolved fixed
797b6a6
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-01-07T14:14:45Z
2005-01-04T14:46:40Z
weaver/src/org/aspectj/weaver/ResolvedPointcutDefinition.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the 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 org.aspectj.weaver.patterns.Pointcut; public class ResolvedPointcutDefinition extends ResolvedMember { private Pointcut pointcut; public ResolvedPointcutDefinition( TypeX declaringType, int modifiers, String name, TypeX[] parameterTypes, Pointcut pointcut) { super( POINTCUT, declaringType, modifiers, ResolvedTypeX.VOID, name, parameterTypes); this.pointcut = pointcut; //XXXpointcut.assertState(Pointcut.RESOLVED); checkedExceptions = TypeX.NONE; } // ---- public void write(DataOutputStream s) throws IOException { getDeclaringType().write(s); s.writeInt(getModifiers()); s.writeUTF(getName()); TypeX.writeArray(getParameterTypes(), s); pointcut.write(s); } public static ResolvedPointcutDefinition read(DataInputStream s, ISourceContext context) throws IOException { return new ResolvedPointcutDefinition( TypeX.read(s), s.readInt(), s.readUTF(), TypeX.readArray(s), Pointcut.read(s, context)); } public String toString() { StringBuffer buf = new StringBuffer(); buf.append("pointcut "); buf.append(getDeclaringType().getName()); buf.append("."); buf.append(getName()); buf.append("("); for (int i=0; i < getParameterTypes().length; i++) { if (i > 0) buf.append(", "); buf.append(getParameterTypes()[i].toString()); } buf.append(")"); //buf.append(pointcut); return buf.toString(); } public Pointcut getPointcut() { return pointcut; } public boolean isAjSynthetic() { return true; } // for testing public static final ResolvedPointcutDefinition DUMMY = new ResolvedPointcutDefinition(TypeX.OBJECT, 0, "missing", TypeX.NONE, Pointcut.makeMatchesNothing(Pointcut.RESOLVED)); public void setPointcut(Pointcut pointcut) { this.pointcut = pointcut; } }
82,134
Bug 82134 AspectJ 5 M2 should implement backwards compatibility for binary aspect form
null
resolved fixed
797b6a6
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-01-07T14:14:45Z
2005-01-04T14:46:40Z
weaver/src/org/aspectj/weaver/VersionedDataInputStream.java
82,134
Bug 82134 AspectJ 5 M2 should implement backwards compatibility for binary aspect form
null
resolved fixed
797b6a6
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-01-07T14:14:45Z
2005-01-04T14:46:40Z
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, WeaverMessages.format(WeaverMessages.ASPECT_NEEDED,entry.aspectType,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(); } } } }
82,134
Bug 82134 AspectJ 5 M2 should implement backwards compatibility for binary aspect form
null
resolved fixed
797b6a6
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-01-07T14:14:45Z
2005-01-04T14:46:40Z
weaver/src/org/aspectj/weaver/bcel/BcelAttributes.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.List; import org.aspectj.apache.bcel.classfile.Attribute; import org.aspectj.apache.bcel.classfile.Unknown; import org.aspectj.apache.bcel.generic.ConstantPoolGen; import org.aspectj.bridge.IMessageHandler; import org.aspectj.weaver.AjAttribute; import org.aspectj.weaver.ISourceContext; // this is a class o' static methods for reading attributes. It's pretty much a bridge from // bcel to AjAttribute. class BcelAttributes { public static List readAjAttributes(Attribute[] as, ISourceContext context,IMessageHandler msgHandler) { List l = new ArrayList(); for (int i = as.length - 1; i >= 0; i--) { Attribute a = as[i]; if (a instanceof Unknown) { Unknown u = (Unknown) a; String name = u.getName(); if (name.startsWith(AjAttribute.AttributePrefix)) { AjAttribute attr = AjAttribute.read(name, u.getBytes(), context,msgHandler); if (attr!=null) l.add(attr); } } } return l; } public static Attribute bcelAttribute(AjAttribute a, ConstantPoolGen pool) { int nameIndex = pool.addUtf8(a.getNameString()); byte[] bytes = a.getBytes(); int length = bytes.length; return new Unknown(nameIndex, length, bytes, pool.getConstantPool()); } }
82,134
Bug 82134 AspectJ 5 M2 should implement backwards compatibility for binary aspect form
null
resolved fixed
797b6a6
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-01-07T14:14:45Z
2005-01-04T14:46:40Z
weaver/src/org/aspectj/weaver/bcel/BcelField.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Common Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * PARC initial implementation * ******************************************************************/ package org.aspectj.weaver.bcel; import java.util.Iterator; import java.util.List; import org.aspectj.apache.bcel.classfile.Attribute; import org.aspectj.apache.bcel.classfile.Field; import org.aspectj.apache.bcel.classfile.Synthetic; import org.aspectj.apache.bcel.classfile.annotation.Annotation; import org.aspectj.weaver.AjAttribute; import org.aspectj.weaver.BCException; import org.aspectj.weaver.ResolvedMember; import org.aspectj.weaver.ResolvedTypeX; import org.aspectj.weaver.TypeX; import org.aspectj.weaver.World; final class BcelField extends ResolvedMember { private Field field; private boolean isAjSynthetic; private boolean isSynthetic = false; private ResolvedTypeX[] resolvedAnnotations; private World world; BcelField(BcelObjectType declaringType, Field field) { super( FIELD, declaringType.getResolvedTypeX(), field.getAccessFlags(), field.getName(), field.getSignature()); this.field = field; this.world = declaringType.getResolvedTypeX().getWorld(); unpackAttributes(world); checkedExceptions = TypeX.NONE; } // ---- private void unpackAttributes(World world) { Attribute[] attrs = field.getAttributes(); List as = BcelAttributes.readAjAttributes(attrs, getSourceContext(world),world.getMessageHandler()); for (Iterator iter = as.iterator(); iter.hasNext();) { AjAttribute a = (AjAttribute) iter.next(); if (a instanceof AjAttribute.AjSynthetic) { isAjSynthetic = true; } else { throw new BCException("weird field attribute " + a); } } isAjSynthetic = false; for (int i = attrs.length - 1; i >= 0; i--) { if (attrs[i] instanceof Synthetic) isSynthetic = true; } } public boolean isAjSynthetic() { return isAjSynthetic; // || getName().startsWith(NameMangler.PREFIX); } public boolean isSynthetic() { return isSynthetic; } public boolean hasAnnotation(TypeX ofType) { Annotation[] anns = field.getAnnotations(); for (int i = 0; i < anns.length; i++) { Annotation annotation = anns[i]; if (annotation.getTypeName().equals(ofType.getName())) return true; } return false; } public ResolvedTypeX[] getAnnotationTypes() { if (resolvedAnnotations == null) { Annotation[] annotations = field.getAnnotations(); resolvedAnnotations = new ResolvedTypeX[annotations.length]; for (int i = 0; i < annotations.length; i++) { Annotation annotation = annotations[i]; ResolvedTypeX rtx = world.resolve(TypeX.forName(annotation.getTypeName())); resolvedAnnotations[i] = rtx; } } return resolvedAnnotations; } }
82,134
Bug 82134 AspectJ 5 M2 should implement backwards compatibility for binary aspect form
null
resolved fixed
797b6a6
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-01-07T14:14:45Z
2005-01-04T14:46:40Z
weaver/src/org/aspectj/weaver/bcel/BcelMethod.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Common Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * PARC initial implementation * ******************************************************************/ package org.aspectj.weaver.bcel; import java.lang.reflect.Modifier; import java.util.Iterator; import java.util.List; import org.aspectj.apache.bcel.classfile.ExceptionTable; import org.aspectj.apache.bcel.classfile.LocalVariable; import org.aspectj.apache.bcel.classfile.LocalVariableTable; import org.aspectj.apache.bcel.classfile.Method; import org.aspectj.apache.bcel.classfile.annotation.Annotation; import org.aspectj.bridge.ISourceLocation; import org.aspectj.bridge.SourceLocation; import org.aspectj.weaver.AjAttribute; import org.aspectj.weaver.BCException; import org.aspectj.weaver.ISourceContext; import org.aspectj.weaver.ResolvedMember; import org.aspectj.weaver.ResolvedTypeX; import org.aspectj.weaver.ShadowMunger; import org.aspectj.weaver.TypeX; import org.aspectj.weaver.World; final class BcelMethod extends ResolvedMember { private Method method; private boolean isAjSynthetic; private ShadowMunger associatedShadowMunger; private AjAttribute.EffectiveSignatureAttribute effectiveSignature; private AjAttribute.MethodDeclarationLineNumberAttribute declarationLineNumber; private ResolvedTypeX[] resolvedAnnotations; private World world; BcelMethod(BcelObjectType declaringType, Method method) { super( method.getName().equals("<init>") ? CONSTRUCTOR : (method.getName().equals("<clinit>") ? STATIC_INITIALIZATION : METHOD), declaringType.getResolvedTypeX(), declaringType.isInterface() ? method.getAccessFlags() | Modifier.INTERFACE : method.getAccessFlags(), method.getName(), method.getSignature()); this.method = method; this.sourceContext = declaringType.getResolvedTypeX().getSourceContext(); this.world = declaringType.getResolvedTypeX().getWorld(); unpackAjAttributes(world); unpackJavaAttributes(); } // ---- private void unpackJavaAttributes() { ExceptionTable exnTable = method.getExceptionTable(); checkedExceptions = (exnTable == null) ? TypeX.NONE : TypeX.forNames(exnTable.getExceptionNames()); LocalVariableTable varTable = method.getLocalVariableTable(); int len = getArity(); if (varTable == null) { this.parameterNames = Utility.makeArgNames(len); } else { TypeX[] paramTypes = getParameterTypes(); String[] paramNames = new String[len]; int index = isStatic() ? 0 : 1; for (int i = 0; i < len; i++) { LocalVariable lv = varTable.getLocalVariable(index); if (lv == null) { paramNames[i] = "arg" + i; } else { paramNames[i] = lv.getName(); } index += paramTypes[i].getSize(); } this.parameterNames = paramNames; } } private void unpackAjAttributes(World world) { List as = BcelAttributes.readAjAttributes(method.getAttributes(), getSourceContext(world),world.getMessageHandler()); //System.out.println("unpack: " + this + ", " + as); for (Iterator iter = as.iterator(); iter.hasNext();) { AjAttribute a = (AjAttribute) iter.next(); if (a instanceof AjAttribute.MethodDeclarationLineNumberAttribute) { declarationLineNumber = (AjAttribute.MethodDeclarationLineNumberAttribute)a; } else if (a instanceof AjAttribute.AdviceAttribute) { associatedShadowMunger = ((AjAttribute.AdviceAttribute)a).reify(this, world); return; } else if (a instanceof AjAttribute.AjSynthetic) { isAjSynthetic = true; } else if (a instanceof AjAttribute.EffectiveSignatureAttribute) { //System.out.println("found effective: " + this); effectiveSignature = (AjAttribute.EffectiveSignatureAttribute)a; } else { throw new BCException("weird method attribute " + a); } } associatedShadowMunger = null; } public boolean isAjSynthetic() { return isAjSynthetic; // || getName().startsWith(NameMangler.PREFIX); } //FIXME needs an isSynthetic method public ShadowMunger getAssociatedShadowMunger() { return associatedShadowMunger; } public AjAttribute.EffectiveSignatureAttribute getEffectiveSignature() { return effectiveSignature; } public boolean hasDeclarationLineNumberInfo() { return declarationLineNumber != null; } public int getDeclarationLineNumber() { if (declarationLineNumber != null) { return declarationLineNumber.getLineNumber(); } else { return -1; } } public ISourceLocation getSourceLocation() { ISourceLocation ret = super.getSourceLocation(); if ((ret == null || ret.getLine()==0) && hasDeclarationLineNumberInfo()) { // lets see if we can do better ISourceContext isc = getSourceContext(); if (isc !=null) ret = isc.makeSourceLocation(getDeclarationLineNumber()); else ret = new SourceLocation(null,getDeclarationLineNumber()); } return ret; } public Kind getKind() { if (associatedShadowMunger != null) { return ADVICE; } else { return super.getKind(); } } public boolean hasAnnotation(TypeX ofType) { Annotation[] anns = method.getAnnotations(); for (int i = 0; i < anns.length; i++) { Annotation annotation = anns[i]; if (annotation.getTypeName().equals(ofType.getName())) return true; } return false; } public ResolvedTypeX[] getAnnotationTypes() { if (resolvedAnnotations == null) { Annotation[] annotations = method.getAnnotations(); resolvedAnnotations = new ResolvedTypeX[annotations.length]; for (int i = 0; i < annotations.length; i++) { Annotation annotation = annotations[i]; ResolvedTypeX rtx = world.resolve(TypeX.forName(annotation.getTypeName())); resolvedAnnotations[i] = rtx; } } return resolvedAnnotations; } }
82,134
Bug 82134 AspectJ 5 M2 should implement backwards compatibility for binary aspect form
null
resolved fixed
797b6a6
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-01-07T14:14:45Z
2005-01-04T14:46:40Z
weaver/src/org/aspectj/weaver/bcel/BcelObjectType.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Common Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * PARC initial implementation * ******************************************************************/ package org.aspectj.weaver.bcel; import java.io.PrintStream; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Iterator; import java.util.List; import org.aspectj.apache.bcel.classfile.Field; import org.aspectj.apache.bcel.classfile.JavaClass; import org.aspectj.apache.bcel.classfile.Method; import org.aspectj.apache.bcel.classfile.annotation.Annotation; import org.aspectj.apache.bcel.classfile.annotation.ElementNameValuePair; import org.aspectj.apache.bcel.classfile.annotation.ElementValue; import org.aspectj.bridge.ISourceLocation; import org.aspectj.weaver.AjAttribute; import org.aspectj.weaver.BCException; import org.aspectj.weaver.ResolvedMember; import org.aspectj.weaver.ResolvedPointcutDefinition; import org.aspectj.weaver.ResolvedTypeX; import org.aspectj.weaver.TypeX; import org.aspectj.weaver.WeaverStateInfo; import org.aspectj.weaver.AjAttribute.WeaverVersionInfo; import org.aspectj.weaver.patterns.PerClause; // ??? exposed for testing public class BcelObjectType extends ResolvedTypeX.ConcreteName { private JavaClass javaClass; private boolean isObject = false; // set upon construction private LazyClassGen lazyClassGen = null; // set lazily if it's an aspect // lazy, for no particular reason I can discern private ResolvedTypeX[] interfaces = null; private ResolvedTypeX superClass = null; private ResolvedMember[] fields = null; private ResolvedMember[] methods = null; private ResolvedTypeX[] resolvedAnnotations = null; // strangely non-lazy private ResolvedPointcutDefinition[] pointcuts = null; private PerClause perClause = null; private WeaverStateInfo weaverState = null; private AjAttribute.WeaverVersionInfo wvInfo = null; private List typeMungers = Collections.EMPTY_LIST; private List declares = Collections.EMPTY_LIST; private ResolvedMember[] privilegedAccess = null; public Collection getTypeMungers() { return typeMungers; } public Collection getDeclares() { return declares; } public Collection getPrivilegedAccesses() { if (privilegedAccess == null) return Collections.EMPTY_LIST; return Arrays.asList(privilegedAccess); } // IMPORTANT! THIS DOESN'T do real work on the java class, just stores it away. BcelObjectType(ResolvedTypeX.Name resolvedTypeX, JavaClass javaClass, boolean exposedToWeaver) { super(resolvedTypeX, exposedToWeaver); this.javaClass = javaClass; if (resolvedTypeX.getSourceContext() == null) { resolvedTypeX.setSourceContext(new BcelSourceContext(this)); } // this should only ever be java.lang.Object which is // the only class in Java-1.4 with no superclasses isObject = (javaClass.getSuperclassNameIndex() == 0); unpackAspectAttributes(); } // repeat initialization public void setJavaClass(JavaClass newclass) { this.javaClass = newclass; resetState(); } public int getModifiers() { return javaClass.getAccessFlags(); } public ResolvedTypeX getSuperclass() { if (isObject) return null; if (superClass == null) { superClass = getResolvedTypeX().getWorld().resolve(TypeX.forName(javaClass.getSuperclassName())); } return superClass; } public ResolvedTypeX[] getDeclaredInterfaces() { if (interfaces == null) { String[] ifaceNames = javaClass.getInterfaceNames(); interfaces = new ResolvedTypeX[ifaceNames.length]; for (int i = 0, len = ifaceNames.length; i < len; i++) { interfaces[i] = getResolvedTypeX().getWorld().resolve(TypeX.forName(ifaceNames[i])); } } return interfaces; } public ResolvedMember[] getDeclaredMethods() { if (methods == null) { Method[] ms = javaClass.getMethods(); ResolvedMember[] ret = new ResolvedMember[ms.length]; for (int i = ms.length - 1; i >= 0; i--) { ret[i] = new BcelMethod(this, ms[i]); } methods = ret; } return methods; } public ResolvedMember[] getDeclaredFields() { if (fields == null) { Field[] fs = javaClass.getFields(); ResolvedMember[] ret = new ResolvedMember[fs.length]; for (int i = 0, len = fs.length; i < len; i++) { ret[i] = new BcelField(this, fs[i]); } fields = ret; } return fields; } // ---- // fun based on the aj attributes public ResolvedMember[] getDeclaredPointcuts() { return pointcuts; } //??? method only used for testing public void addPointcutDefinition(ResolvedPointcutDefinition d) { int len = pointcuts.length; ResolvedPointcutDefinition[] ret = new ResolvedPointcutDefinition[len+1]; System.arraycopy(pointcuts, 0, ret, 0, len); ret[len] = d; pointcuts = ret; } public boolean isAspect() { return perClause != null; } private void unpackAspectAttributes() { List pointcuts = new ArrayList(); typeMungers = new ArrayList(); declares = new ArrayList(); List l = BcelAttributes.readAjAttributes(javaClass.getAttributes(), getResolvedTypeX().getSourceContext(),getResolvedTypeX().getWorld().getMessageHandler()); for (Iterator iter = l.iterator(); iter.hasNext();) { AjAttribute a = (AjAttribute) iter.next(); //System.err.println("unpacking: " + this + " and " + a); if (a instanceof AjAttribute.Aspect) { perClause = ((AjAttribute.Aspect)a).reify(this.getResolvedTypeX()); } else if (a instanceof AjAttribute.PointcutDeclarationAttribute) { pointcuts.add(((AjAttribute.PointcutDeclarationAttribute)a).reify()); } else if (a instanceof AjAttribute.WeaverState) { weaverState = ((AjAttribute.WeaverState)a).reify(); } else if (a instanceof AjAttribute.TypeMunger) { typeMungers.add(((AjAttribute.TypeMunger)a).reify(getResolvedTypeX().getWorld(), getResolvedTypeX())); } else if (a instanceof AjAttribute.DeclareAttribute) { declares.add(((AjAttribute.DeclareAttribute)a).getDeclare()); } else if (a instanceof AjAttribute.PrivilegedAttribute) { privilegedAccess = ((AjAttribute.PrivilegedAttribute)a).getAccessedMembers(); } else if (a instanceof AjAttribute.SourceContextAttribute) { if (getResolvedTypeX().getSourceContext() instanceof BcelSourceContext) { ((BcelSourceContext)getResolvedTypeX().getSourceContext()).addAttributeInfo((AjAttribute.SourceContextAttribute)a); } } else if (a instanceof AjAttribute.WeaverVersionInfo) { wvInfo = (AjAttribute.WeaverVersionInfo)a; if (wvInfo.getMajorVersion() > WeaverVersionInfo.getCurrentWeaverMajorVersion()) { // The class file containing this attribute was created by a version of AspectJ that // added some behavior that 'this' version of AspectJ doesn't understand. And the // class file contains changes that mean 'this' version of AspectJ cannot continue. throw new BCException("Unable to continue, this version of AspectJ supports classes built with weaver version "+ WeaverVersionInfo.toCurrentVersionString()+" but the class "+ javaClass.getClassName()+" is version "+wvInfo.toString()); } } else { throw new BCException("bad attribute " + a); } } this.pointcuts = (ResolvedPointcutDefinition[]) pointcuts.toArray(new ResolvedPointcutDefinition[pointcuts.size()]); // this.typeMungers = (BcelTypeMunger[]) // typeMungers.toArray(new BcelTypeMunger[typeMungers.size()]); // this.declares = (Declare[]) // declares.toArray(new Declare[declares.size()]); } public PerClause getPerClause() { return perClause; } JavaClass getJavaClass() { return javaClass; } public void resetState() { this.interfaces = null; this.superClass = null; this.fields = null; this.methods = null; this.pointcuts = null; this.perClause = null; this.weaverState = null; this.lazyClassGen = null; isObject = (javaClass.getSuperclassNameIndex() == 0); unpackAspectAttributes(); } public void finishedWith() { // memory usage experiments.... // this.interfaces = null; // this.superClass = null; // this.fields = null; // this.methods = null; // this.pointcuts = null; // this.perClause = null; // this.weaverState = null; // this.lazyClassGen = null; // this next line frees up memory, but need to understand incremental implications // before leaving it in. // getResolvedTypeX().setSourceContext(null); } public WeaverStateInfo getWeaverState() { return weaverState; } void setWeaverState(WeaverStateInfo weaverState) { this.weaverState = weaverState; } public void printWackyStuff(PrintStream out) { if (typeMungers.size() > 0) { out.println(" TypeMungers: " + typeMungers); } if (declares.size() > 0) { out.println(" declares: " + declares); } } /** * Return the lazyClassGen associated with this type. For aspect types, this * value will be cached, since it is used to inline advice. For non-aspect * types, this lazyClassGen is always newly constructed. */ public LazyClassGen getLazyClassGen() { LazyClassGen ret = lazyClassGen; if (ret == null) { //System.err.println("creating lazy class gen for: " + this); ret = new LazyClassGen(this); //ret.print(System.err); //System.err.println("made LCG from : " + this.getJavaClass().getSuperclassName() ); if (isAspect()) { lazyClassGen = ret; } } return ret; } public boolean isInterface() { return javaClass.isInterface(); } public boolean isEnum() { return javaClass.isEnum(); } public boolean isAnnotation() { return javaClass.isAnnotation(); } public boolean isAnnotationWithRuntimeRetention() { if (!isAnnotation()) { return false; } else { Annotation[] annotationsOnThisType = javaClass.getAnnotations(); for (int i = 0; i < annotationsOnThisType.length; i++) { Annotation a = annotationsOnThisType[i]; if (a.getTypeName().equals(TypeX.AT_RETENTION.getName())) { List values = a.getValues(); boolean isRuntime = false; for (Iterator it = values.iterator(); it.hasNext();) { ElementNameValuePair element = (ElementNameValuePair) it.next(); ElementValue v = element.getValue(); isRuntime = v.stringifyValue().equals("RUNTIME"); } return isRuntime; } } } return false; } public boolean isSynthetic() { return getResolvedTypeX().isSynthetic(); } public ISourceLocation getSourceLocation() { return getResolvedTypeX().getSourceContext().makeSourceLocation(0); //FIXME, we can do better than this } public AjAttribute.WeaverVersionInfo getWeaverVersionAttribute() { return wvInfo; } public void addParent(ResolvedTypeX newParent) { if (newParent.isClass()) { superClass = newParent; } else { ResolvedTypeX[] oldInterfaceNames = getDeclaredInterfaces(); int len = oldInterfaceNames.length; ResolvedTypeX[] newInterfaceNames = new ResolvedTypeX[len+1]; System.arraycopy(oldInterfaceNames, 0, newInterfaceNames, 0, len); newInterfaceNames[len] = newParent; interfaces = newInterfaceNames; } //System.err.println("javaClass: " + Arrays.asList(javaClass.getInterfaceNames()) + " super " + javaClass.getSuperclassName()); //if (lazyClassGen != null) lazyClassGen.print(); } public boolean hasAnnotation(TypeX ofType) { Annotation[] annotationsOnThisType = javaClass.getAnnotations(); for (int i = 0; i < annotationsOnThisType.length; i++) { Annotation a = annotationsOnThisType[i]; if (a.getTypeName().equals(ofType.getName())) return true; } return false; } public ResolvedTypeX[] getAnnotationTypes() { if (resolvedAnnotations == null) { Annotation annotations[] = javaClass.getAnnotations(); resolvedAnnotations = new ResolvedTypeX[annotations.length]; for (int i = 0; i < annotations.length; i++) { Annotation annotation = annotations[i]; ResolvedTypeX rtx = getResolvedTypeX().getWorld().resolve(TypeX.forName(annotation.getTypeName())); resolvedAnnotations[i] = rtx; } } return resolvedAnnotations; } }
82,134
Bug 82134 AspectJ 5 M2 should implement backwards compatibility for binary aspect form
null
resolved fixed
797b6a6
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-01-07T14:14:45Z
2005-01-04T14:46:40Z
weaver/src/org/aspectj/weaver/bcel/LazyMethodGen.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the 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.aspectj.apache.bcel.Constants; import org.aspectj.apache.bcel.classfile.Attribute; import org.aspectj.apache.bcel.classfile.ConstantPool; import org.aspectj.apache.bcel.classfile.Method; import org.aspectj.apache.bcel.classfile.Synthetic; import org.aspectj.apache.bcel.generic.BranchHandle; import org.aspectj.apache.bcel.generic.BranchInstruction; import org.aspectj.apache.bcel.generic.CPInstruction; import org.aspectj.apache.bcel.generic.ClassGenException; import org.aspectj.apache.bcel.generic.CodeExceptionGen; import org.aspectj.apache.bcel.generic.ConstantPoolGen; import org.aspectj.apache.bcel.generic.Instruction; import org.aspectj.apache.bcel.generic.InstructionHandle; import org.aspectj.apache.bcel.generic.InstructionList; import org.aspectj.apache.bcel.generic.InstructionTargeter; import org.aspectj.apache.bcel.generic.LineNumberGen; import org.aspectj.apache.bcel.generic.LocalVariableGen; import org.aspectj.apache.bcel.generic.LocalVariableInstruction; import org.aspectj.apache.bcel.generic.MethodGen; import org.aspectj.apache.bcel.generic.ObjectType; import org.aspectj.apache.bcel.generic.Select; import org.aspectj.apache.bcel.generic.Type; import org.aspectj.bridge.IMessage; import org.aspectj.bridge.ISourceLocation; import org.aspectj.weaver.AjAttribute; import org.aspectj.weaver.BCException; import org.aspectj.weaver.ISourceContext; import org.aspectj.weaver.Member; import org.aspectj.weaver.ResolvedTypeX; import org.aspectj.weaver.WeaverMessages; /** * 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; List /*Test*/ matchedShadowTests; // 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(); } public boolean hasDeclaredLineNumberInfo() { return (memberView != null && memberView.hasDeclarationLineNumberInfo()); } public int getDeclarationLineNumber() { if (hasDeclaredLineNumberInfo()) { return memberView.getDeclarationLineNumber(); } else { return -1; } } 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, WeaverMessages.format(WeaverMessages.PROBLEM_GENERATING_METHOD, this.getClassName(), this.getName(), e.getMessage()), this.getMemberView() == null ? null : this.getMemberView().getSourceLocation(), null); // throw e; PR 70201.... let the normal problem reporting infrastructure deal with this rather than crashing. body = null; MethodGen gen = pack(); return gen.getMethod(); } } public void markAsChanged() { initialize(); savedMethod = null; } // ============================= public String toString() { return toLongString(); } public String toShortString() { String access = org.aspectj.apache.bcel.classfile.Utility.accessToString(getAccessFlags()); StringBuffer buf = new StringBuffer(); if (!access.equals("")) { buf.append(access); buf.append(" "); } buf.append( org.aspectj.apache.bcel.classfile.Utility.signatureToString( getReturnType().getSignature(), true)); buf.append(" "); buf.append(getName()); buf.append("("); { int len = argumentTypes.length; if (len > 0) { buf.append( org.aspectj.apache.bcel.classfile.Utility.signatureToString( argumentTypes[0].getSignature(), true)); for (int i = 1; i < argumentTypes.length; i++) { buf.append(", "); buf.append( org.aspectj.apache.bcel.classfile.Utility.signatureToString( argumentTypes[i].getSignature(), true)); } } } buf.append(")"); { int len = declaredExceptions != null ? declaredExceptions.length : 0; if (len > 0) { buf.append(" throws "); buf.append(declaredExceptions[0]); for (int i = 1; i < declaredExceptions.length; i++) { buf.append(", "); buf.append(declaredExceptions[i]); } } } return buf.toString(); } public String toLongString() { 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,null); 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 boolean isBridgeMethod() { return (getAccessFlags() & Constants.ACC_BRIDGE) != 0; } public void addExceptionHandler( InstructionHandle start, InstructionHandle end, InstructionHandle handlerStart, ObjectType catchType, boolean highPriority) { InstructionHandle start1 = Range.genStart(body, start); InstructionHandle end1 = Range.genEnd(body, end); ExceptionRange er = new ExceptionRange(body, 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()); } public boolean isProtected() { return Modifier.isProtected(getAccessFlags()); } public boolean isDefault() { return !(isProtected() || isPrivate() || isPublic()); } public boolean isPublic() { return Modifier.isPublic(getAccessFlags()); } // ---- /** A good body is a body with the following properties: * * <ul> * <li> For each branch instruction S in body, target T of S is in body. * <li> For each branch instruction S in body, target T of S has S as a targeter. * <li> For each instruction T in body, for each branch instruction S that is a * targeter of T, S is in body. * <li> For each non-range-handle instruction T in body, for each instruction S * that is a targeter of T, S is * either a branch instruction, an exception range or a tag * <li> For each range-handle instruction T in body, there is exactly one targeter S * that is a range. * <li> For each range-handle instruction T in body, the range R targeting T is in body. * <li> For each instruction T in body, for each exception range R targeting T, R is * in body. * <li> For each exception range R in body, let T := R.handler. T is in body, and R is one * of T's targeters * <li> All ranges are properly nested: For all ranges Q and R, if Q.start preceeds * R.start, then R.end preceeds Q.end. * </ul> * * Where the shorthand "R is in body" means "R.start is in body, R.end is in body, and * any InstructionHandle stored in a field of R (such as an exception handle) is in body". */ public void assertGoodBody() { if (true) return; // only enable for debugging, 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 ISourceLocation getSourceLocation() { if (memberView!=null) return memberView.getSourceLocation(); return null; } 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 String getParameterSignature() { if (memberView!=null) return memberView.getParameterSignature(); return Member.typesToSignature(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; } }
82,134
Bug 82134 AspectJ 5 M2 should implement backwards compatibility for binary aspect form
null
resolved fixed
797b6a6
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-01-07T14:14:45Z
2005-01-04T14:46:40Z
weaver/src/org/aspectj/weaver/patterns/AndAnnotationTypePattern.java
/* ******************************************************************* * Copyright (c) 2004 IBM Corporation. * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Common Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/cpl-v10.html * * ******************************************************************/ package org.aspectj.weaver.patterns; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.aspectj.util.FuzzyBoolean; import org.aspectj.weaver.AnnotatedElement; import org.aspectj.weaver.ISourceContext; import org.aspectj.weaver.World; /** * @author colyer * * TODO To change the template for this generated type comment go to * Window - Preferences - Java - Code Style - Code Templates */ public class AndAnnotationTypePattern extends AnnotationTypePattern { private AnnotationTypePattern left; private AnnotationTypePattern right; public AndAnnotationTypePattern(AnnotationTypePattern left, AnnotationTypePattern right) { this.left = left; this.right = right; setLocation(left.getSourceContext(), left.getStart(), right.getEnd()); } public FuzzyBoolean matches(AnnotatedElement annotated) { return left.matches(annotated).and(right.matches(annotated)); } public void resolve(World world) { left.resolve(world); right.resolve(world); } /* (non-Javadoc) * @see org.aspectj.weaver.patterns.AnnotationTypePattern#resolveBindings(org.aspectj.weaver.patterns.IScope, org.aspectj.weaver.patterns.Bindings, boolean) */ public AnnotationTypePattern resolveBindings(IScope scope, Bindings bindings, boolean allowBinding) { left = left.resolveBindings(scope,bindings,allowBinding); right =right.resolveBindings(scope,bindings,allowBinding); return this; } public static AnnotationTypePattern read(DataInputStream s, ISourceContext context) throws IOException { AnnotationTypePattern p = new AndAnnotationTypePattern( AnnotationTypePattern.read(s,context), AnnotationTypePattern.read(s,context)); p.readLocation(context,s); return p; } public void write(DataOutputStream s) throws IOException { s.writeByte(AnnotationTypePattern.AND); left.write(s); right.write(s); writeLocation(s); } public boolean equals(Object obj) { if (!(obj instanceof AndAnnotationTypePattern)) return false; AndAnnotationTypePattern other = (AndAnnotationTypePattern) obj; return (left.equals(other.left) && right.equals(other.right)); } public int hashCode() { int result = 17; result = result*37 + left.hashCode(); result = result*37 + right.hashCode(); return result; } public String toString() { return left.toString() + " " + right.toString(); } public AnnotationTypePattern getLeft() { return left; } public AnnotationTypePattern getRight() { return right; } }
82,134
Bug 82134 AspectJ 5 M2 should implement backwards compatibility for binary aspect form
null
resolved fixed
797b6a6
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-01-07T14:14:45Z
2005-01-04T14:46:40Z
weaver/src/org/aspectj/weaver/patterns/AndPointcut.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the 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.Member; import java.util.HashSet; import java.util.Set; 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.ast.Test; public class AndPointcut extends Pointcut { Pointcut left, right; // exposed for testing private Set couldMatchKinds; public AndPointcut(Pointcut left, Pointcut right) { super(); this.left = left; this.right = right; this.pointcutKind = AND; setLocation(left.getSourceContext(), left.getStart(), right.getEnd()); couldMatchKinds = new HashSet(); couldMatchKinds.addAll(left.couldMatchKinds()); couldMatchKinds.retainAll(right.couldMatchKinds()); } public Set couldMatchKinds() { return couldMatchKinds; } public FuzzyBoolean fastMatch(FastMatchInfo type) { return left.fastMatch(type).and(right.fastMatch(type)); } protected FuzzyBoolean matchInternal(Shadow shadow) { FuzzyBoolean leftMatch = left.match(shadow); if (leftMatch.alwaysFalse()) return leftMatch; return leftMatch.and(right.match(shadow)); } public FuzzyBoolean match(JoinPoint jp, JoinPoint.StaticPart encJP) { return left.match(jp,encJP).and(right.match(jp,encJP)); } public FuzzyBoolean match(JoinPoint.StaticPart jpsp) { return left.match(jpsp).and(right.match(jpsp)); } /* (non-Javadoc) * @see org.aspectj.weaver.tools.PointcutExpression#matchesDynamically(java.lang.Object, java.lang.Object, java.lang.Object[]) */ public boolean matchesDynamically(Object thisObject, Object targetObject, Object[] args) { return left.matchesDynamically(thisObject,targetObject,args) && right.matchesDynamically(thisObject,targetObject,args); } /* (non-Javadoc) * @see org.aspectj.weaver.patterns.Pointcut#matchesStatically(java.lang.String, java.lang.reflect.Member, java.lang.Class, java.lang.Class, java.lang.reflect.Member) */ public FuzzyBoolean matchesStatically( String joinpointKind, Member member, Class thisClass, Class targetClass, Member withinCode) { return left.matchesStatically(joinpointKind,member,thisClass,targetClass,withinCode) .and( right.matchesStatically(joinpointKind,member,thisClass,targetClass,withinCode)); } public String toString() { return "(" + left.toString() + " && " + right.toString() + ")"; } public boolean equals(Object other) { if (!(other instanceof AndPointcut)) return false; AndPointcut o = (AndPointcut)other; return o.left.equals(left) && o.right.equals(right); } public int hashCode() { int result = 19; result = 37*result + left.hashCode(); result = 37*result + right.hashCode(); return result; } public void resolveBindings(IScope scope, Bindings bindings) { left.resolveBindings(scope, bindings); right.resolveBindings(scope, bindings); } public void resolveBindingsFromRTTI() { left.resolveBindingsFromRTTI(); right.resolveBindingsFromRTTI(); } public void write(DataOutputStream s) throws IOException { s.writeByte(Pointcut.AND); left.write(s); right.write(s); writeLocation(s); } public static Pointcut read(DataInputStream s, ISourceContext context) throws IOException { AndPointcut ret = new AndPointcut(Pointcut.read(s, context), Pointcut.read(s, context)); ret.readLocation(context, s); return ret; } protected Test findResidueInternal(Shadow shadow, ExposedState state) { return Test.makeAnd(left.findResidue(shadow, state), right.findResidue(shadow, state)); } public Pointcut concretize1(ResolvedTypeX inAspect, IntMap bindings) { AndPointcut ret = new AndPointcut(left.concretize(inAspect, bindings), right.concretize(inAspect, bindings)); ret.copyLocationFrom(this); return ret; } public Pointcut getLeft() { return left; } public Pointcut getRight() { return right; } }
82,134
Bug 82134 AspectJ 5 M2 should implement backwards compatibility for binary aspect form
null
resolved fixed
797b6a6
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-01-07T14:14:45Z
2005-01-04T14:46:40Z
weaver/src/org/aspectj/weaver/patterns/AndTypePattern.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the 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.util.FuzzyBoolean; import org.aspectj.weaver.ISourceContext; import org.aspectj.weaver.ResolvedTypeX; /** * left && right * * <p>any binding to formals is explicitly forbidden for any composite by the language * * @author Erik Hilsdale * @author Jim Hugunin */ public class AndTypePattern extends TypePattern { private TypePattern left, right; public AndTypePattern(TypePattern left, TypePattern right) { super(false,false); //?? we override all methods that care about includeSubtypes this.left = left; this.right = right; setLocation(left.getSourceContext(), left.getStart(), right.getEnd()); } protected boolean couldEverMatchSameTypesAs(TypePattern other) { return true; // don't dive into ands yet.... } public FuzzyBoolean matchesInstanceof(ResolvedTypeX type) { return left.matchesInstanceof(type).and(right.matchesInstanceof(type)); } protected boolean matchesExactly(ResolvedTypeX type) { //??? if these had side-effects, this sort-circuit could be a mistake return left.matchesExactly(type) && right.matchesExactly(type); } public boolean matchesStatically(Class type) { return left.matchesStatically(type) && right.matchesStatically(type); } public FuzzyBoolean matchesInstanceof(Class type) { return left.matchesInstanceof(type).and(right.matchesInstanceof(type)); } protected boolean matchesExactly(Class type) { //??? if these had side-effects, this sort-circuit could be a mistake return left.matchesExactly(type) && right.matchesExactly(type); } public boolean matchesStatically(ResolvedTypeX type) { return left.matchesStatically(type) && right.matchesStatically(type); } public void write(DataOutputStream s) throws IOException { s.writeByte(TypePattern.AND); left.write(s); right.write(s); writeLocation(s); } public static TypePattern read(DataInputStream s, ISourceContext context) throws IOException { TypePattern ret = new AndTypePattern(TypePattern.read(s, context), TypePattern.read(s, context)); ret.readLocation(context, s); return ret; } public TypePattern resolveBindings( IScope scope, Bindings bindings, boolean allowBinding, boolean requireExactType) { if (requireExactType) return notExactType(scope); left = left.resolveBindings(scope, bindings, false, false); right = right.resolveBindings(scope, bindings, false, false); return this; } public TypePattern resolveBindingsFromRTTI(boolean allowBinding, boolean requireExactType) { if (requireExactType) return TypePattern.NO; left = left.resolveBindingsFromRTTI(allowBinding,requireExactType); right = right.resolveBindingsFromRTTI(allowBinding,requireExactType); return this; } public String toString() { StringBuffer buff = new StringBuffer(); if (annotationPattern != AnnotationTypePattern.ANY) { buff.append('('); buff.append(annotationPattern.toString()); buff.append(' '); } buff.append('('); buff.append(left.toString()); buff.append(" && "); buff.append(right.toString()); buff.append(')'); if (annotationPattern != AnnotationTypePattern.ANY) { buff.append(')'); } return buff.toString(); } public boolean equals(Object obj) { if (! (obj instanceof AndTypePattern)) return false; AndTypePattern atp = (AndTypePattern) obj; return left.equals(atp.left) && right.equals(atp.right); } /* (non-Javadoc) * @see java.lang.Object#hashCode() */ public int hashCode() { int ret = 17; ret = ret + 37 * left.hashCode(); ret = ret + 37 * right.hashCode(); return ret; } }
82,134
Bug 82134 AspectJ 5 M2 should implement backwards compatibility for binary aspect form
null
resolved fixed
797b6a6
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-01-07T14:14:45Z
2005-01-04T14:46:40Z
weaver/src/org/aspectj/weaver/patterns/AnnotationPatternList.java
/* ******************************************************************* * Copyright (c) 2004 IBM Corporation. * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Common Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/cpl-v10.html * * ******************************************************************/ package org.aspectj.weaver.patterns; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.util.List; import org.aspectj.util.FuzzyBoolean; import org.aspectj.weaver.ISourceContext; import org.aspectj.weaver.IntMap; import org.aspectj.weaver.ResolvedTypeX; import org.aspectj.weaver.World; /** * @author colyer * * TODO To change the template for this generated type comment go to * Window - Preferences - Java - Code Style - Code Templates */ public class AnnotationPatternList extends PatternNode { private AnnotationTypePattern[] typePatterns; int ellipsisCount = 0; public static final AnnotationPatternList EMPTY = new AnnotationPatternList(new AnnotationTypePattern[] {}); public static final AnnotationPatternList ANY = new AnnotationPatternList(new AnnotationTypePattern[] {AnnotationTypePattern.ELLIPSIS}); public AnnotationPatternList() { typePatterns = new AnnotationTypePattern[0]; ellipsisCount = 0; } public AnnotationPatternList(AnnotationTypePattern[] arguments) { this.typePatterns = arguments; for (int i=0; i<arguments.length; i++) { if (arguments[i] == AnnotationTypePattern.ELLIPSIS) ellipsisCount++; } } public AnnotationPatternList(List l) { this((AnnotationTypePattern[]) l.toArray(new AnnotationTypePattern[l.size()])); } protected AnnotationTypePattern[] getAnnotationPatterns() { return typePatterns; } public void resolve(World inWorld) { for (int i = 0; i < typePatterns.length; i++) { typePatterns[i].resolve(inWorld); } } public FuzzyBoolean matches(ResolvedTypeX[] someArgs) { // do some quick length tests first int numArgsMatchedByEllipsis = (someArgs.length + ellipsisCount) - typePatterns.length; if (numArgsMatchedByEllipsis < 0) return FuzzyBoolean.NO; if ((numArgsMatchedByEllipsis > 0) && (ellipsisCount == 0)) { return FuzzyBoolean.NO; } // now work through the args and the patterns, skipping at ellipsis FuzzyBoolean ret = FuzzyBoolean.YES; int argsIndex = 0; for (int i = 0; i < typePatterns.length; i++) { if (typePatterns[i] == AnnotationTypePattern.ELLIPSIS) { // match ellipsisMatchCount args argsIndex += numArgsMatchedByEllipsis; } else if (typePatterns[i] == AnnotationTypePattern.ANY) { argsIndex++; } else { // match the argument type at argsIndex with the ExactAnnotationTypePattern // we know it is exact because nothing else is allowed in args ExactAnnotationTypePattern ap = (ExactAnnotationTypePattern)typePatterns[i]; FuzzyBoolean matches = ap.matches(someArgs[argsIndex]); if (matches == FuzzyBoolean.NO) { return FuzzyBoolean.MAYBE; // could still match at runtime } else { argsIndex++; ret = ret.and(matches); } } } return ret; } public int size() { return typePatterns.length; } public AnnotationTypePattern get(int index) { return typePatterns[index]; } public AnnotationPatternList resolveBindings(IScope scope, Bindings bindings, boolean allowBinding) { for (int i=0; i<typePatterns.length; i++) { AnnotationTypePattern p = typePatterns[i]; if (p != null) { typePatterns[i] = typePatterns[i].resolveBindings(scope, bindings, allowBinding); } } return this; } public AnnotationPatternList resolveReferences(IntMap bindings) { int len = typePatterns.length; AnnotationTypePattern[] ret = new AnnotationTypePattern[len]; for (int i=0; i < len; i++) { ret[i] = typePatterns[i].remapAdviceFormals(bindings); } return new AnnotationPatternList(ret); } public String toString() { StringBuffer buf = new StringBuffer(); buf.append("("); for (int i=0, len=typePatterns.length; i < len; i++) { AnnotationTypePattern type = typePatterns[i]; if (i > 0) buf.append(", "); if (type == AnnotationTypePattern.ELLIPSIS) { buf.append(".."); } else { buf.append(type.toString()); } } buf.append(")"); return buf.toString(); } public boolean equals(Object other) { if (!(other instanceof AnnotationPatternList)) return false; AnnotationPatternList o = (AnnotationPatternList)other; int len = o.typePatterns.length; if (len != this.typePatterns.length) return false; for (int i=0; i<len; i++) { if (!this.typePatterns[i].equals(o.typePatterns[i])) return false; } return true; } public int hashCode() { int result = 41; for (int i = 0, len = typePatterns.length; i < len; i++) { result = 37*result + typePatterns[i].hashCode(); } return result; } public static AnnotationPatternList read(DataInputStream s, ISourceContext context) throws IOException { short len = s.readShort(); AnnotationTypePattern[] arguments = new AnnotationTypePattern[len]; for (int i=0; i<len; i++) { arguments[i] = AnnotationTypePattern.read(s, context); } AnnotationPatternList ret = new AnnotationPatternList(arguments); ret.readLocation(context, s); return ret; } public void write(DataOutputStream s) throws IOException { s.writeShort(typePatterns.length); for (int i=0; i<typePatterns.length; i++) { typePatterns[i].write(s); } writeLocation(s); } }
82,134
Bug 82134 AspectJ 5 M2 should implement backwards compatibility for binary aspect form
null
resolved fixed
797b6a6
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-01-07T14:14:45Z
2005-01-04T14:46:40Z
weaver/src/org/aspectj/weaver/patterns/AnnotationPointcut.java
/* ******************************************************************* * Copyright (c) 2004 IBM Corporation. * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Common Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/cpl-v10.html * * ******************************************************************/ 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 java.util.Set; import org.aspectj.util.FuzzyBoolean; import org.aspectj.weaver.AnnotatedElement; import org.aspectj.weaver.ISourceContext; import org.aspectj.weaver.IntMap; import org.aspectj.weaver.Member; import org.aspectj.weaver.NameMangler; import org.aspectj.weaver.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.ast.Literal; import org.aspectj.weaver.ast.Test; import org.aspectj.weaver.ast.Var; /** * @annotation(@Foo) or @annotation(foo) * * Matches any join point where the subject of the join point has an * annotation matching the annotationTypePattern: * * Join Point Kind Subject * ================================ * method call the target method * method execution the method * constructor call the constructor * constructor execution the constructor * get the target field * set the target field * adviceexecution the advice * initialization the constructor * preinitialization the constructor * staticinitialization the type being initialized * handler the declared type of the handled exception */ public class AnnotationPointcut extends NameBindingPointcut { private ExactAnnotationTypePattern annotationTypePattern; private ShadowMunger munger = null; // only set after concretization public AnnotationPointcut(ExactAnnotationTypePattern type) { super(); this.annotationTypePattern = type; this.pointcutKind = Pointcut.ANNOTATION; } public AnnotationPointcut(ExactAnnotationTypePattern type, ShadowMunger munger) { this(type); this.munger = munger; } public Set couldMatchKinds() { return Shadow.ALL_SHADOW_KINDS; } /* (non-Javadoc) * @see org.aspectj.weaver.patterns.Pointcut#fastMatch(org.aspectj.weaver.patterns.FastMatchInfo) */ public FuzzyBoolean fastMatch(FastMatchInfo info) { if (info.getKind() == Shadow.StaticInitialization) { return annotationTypePattern.fastMatches(info.getType()); } else { return FuzzyBoolean.MAYBE; } } /* (non-Javadoc) * @see org.aspectj.weaver.patterns.Pointcut#match(org.aspectj.weaver.Shadow) */ protected FuzzyBoolean matchInternal(Shadow shadow) { AnnotatedElement toMatchAgainst = null; Member member = shadow.getSignature(); ResolvedMember rMember = member.resolve(shadow.getIWorld()); if (rMember == null) { if (member.getName().startsWith(NameMangler.PREFIX)) { return FuzzyBoolean.NO; } shadow.getIWorld().getLint().unresolvableMember.signal(member.toString(), getSourceLocation()); return FuzzyBoolean.NO; } Shadow.Kind kind = shadow.getKind(); if (kind == Shadow.StaticInitialization) { toMatchAgainst = rMember.getType(); } else if ( (kind == Shadow.ExceptionHandler)) { toMatchAgainst = TypeX.forName(rMember.getSignature()).resolve(shadow.getIWorld()); } else { toMatchAgainst = rMember; } annotationTypePattern.resolve(shadow.getIWorld()); return annotationTypePattern.matches(toMatchAgainst); } /* (non-Javadoc) * @see org.aspectj.weaver.patterns.Pointcut#resolveBindings(org.aspectj.weaver.patterns.IScope, org.aspectj.weaver.patterns.Bindings) */ protected void resolveBindings(IScope scope, Bindings bindings) { annotationTypePattern = (ExactAnnotationTypePattern) annotationTypePattern.resolveBindings(scope,bindings,true); // must be either a Var, or an annotation type pattern } /* (non-Javadoc) * @see org.aspectj.weaver.patterns.Pointcut#resolveBindingsFromRTTI() */ protected void resolveBindingsFromRTTI() { // TODO Auto-generated method stub } /* (non-Javadoc) * @see org.aspectj.weaver.patterns.Pointcut#concretize1(org.aspectj.weaver.ResolvedTypeX, org.aspectj.weaver.IntMap) */ protected Pointcut concretize1(ResolvedTypeX inAspect, IntMap bindings) { ExactAnnotationTypePattern newType = (ExactAnnotationTypePattern) annotationTypePattern.remapAdviceFormals(bindings); Pointcut ret = new AnnotationPointcut(newType, bindings.getEnclosingAdvice()); ret.copyLocationFrom(this); return ret; } /* (non-Javadoc) * @see org.aspectj.weaver.patterns.Pointcut#findResidue(org.aspectj.weaver.Shadow, org.aspectj.weaver.patterns.ExposedState) */ protected Test findResidueInternal(Shadow shadow, ExposedState state) { if (annotationTypePattern instanceof BindingAnnotationTypePattern) { BindingAnnotationTypePattern btp = (BindingAnnotationTypePattern)annotationTypePattern; TypeX annotationType = btp.annotationType; Var var = shadow.getKindedAnnotationVar(annotationType); if (var == null) return Literal.FALSE; // Check if we have already bound something to this formal if ((state.get(btp.getFormalIndex())!=null) &&(lastMatchedShadowId == shadow.shadowId)) { // ISourceLocation pcdSloc = getSourceLocation(); // ISourceLocation shadowSloc = shadow.getSourceLocation(); // Message errorMessage = new Message( // "Cannot use @pointcut to match at this location and bind a formal to type '"+var.getType()+ // "' - the formal is already bound to type '"+state.get(btp.getFormalIndex()).getType()+"'"+ // ". The secondary source location points to the problematic binding.", // shadowSloc,true,new ISourceLocation[]{pcdSloc}); // shadow.getIWorld().getMessageHandler().handleMessage(errorMessage); state.setErroneousVar(btp.getFormalIndex()); } state.set(btp.getFormalIndex(),var); } return Literal.TRUE; } /* (non-Javadoc) * @see org.aspectj.weaver.patterns.NameBindingPointcut#getBindingAnnotationTypePatterns() */ public List getBindingAnnotationTypePatterns() { if (annotationTypePattern instanceof BindingAnnotationTypePattern) { List l = new ArrayList(); l.add(annotationTypePattern); return l; } else return Collections.EMPTY_LIST; } /* (non-Javadoc) * @see org.aspectj.weaver.patterns.NameBindingPointcut#getBindingTypePatterns() */ public List getBindingTypePatterns() { return Collections.EMPTY_LIST; } /* (non-Javadoc) * @see org.aspectj.weaver.patterns.PatternNode#write(java.io.DataOutputStream) */ public void write(DataOutputStream s) throws IOException { s.writeByte(Pointcut.ANNOTATION); annotationTypePattern.write(s); writeLocation(s); } public static Pointcut read(DataInputStream s, ISourceContext context) throws IOException { AnnotationTypePattern type = AnnotationTypePattern.read(s, context); AnnotationPointcut ret = new AnnotationPointcut((ExactAnnotationTypePattern)type); ret.readLocation(context, s); return ret; } public boolean equals(Object other) { if (!(other instanceof AnnotationPointcut)) return false; AnnotationPointcut o = (AnnotationPointcut)other; return o.annotationTypePattern.equals(this.annotationTypePattern); } public int hashCode() { int result = 17; result = 37*result + annotationTypePattern.hashCode(); return result; } public String toString() { StringBuffer buf = new StringBuffer(); buf.append("@annotation("); buf.append(annotationTypePattern.toString()); buf.append(")"); return buf.toString(); } }
82,134
Bug 82134 AspectJ 5 M2 should implement backwards compatibility for binary aspect form
null
resolved fixed
797b6a6
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-01-07T14:14:45Z
2005-01-04T14:46:40Z
weaver/src/org/aspectj/weaver/patterns/AnnotationTypePattern.java
/* ******************************************************************* * Copyright (c) 2004 IBM Corporation. * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Common Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/cpl-v10.html * * ******************************************************************/ package org.aspectj.weaver.patterns; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.aspectj.util.FuzzyBoolean; import org.aspectj.weaver.AnnotatedElement; import org.aspectj.weaver.BCException; import org.aspectj.weaver.ISourceContext; import org.aspectj.weaver.IntMap; import org.aspectj.weaver.World; public abstract class AnnotationTypePattern extends PatternNode { public static final AnnotationTypePattern ANY = new AnyAnnotationTypePattern(); public static final AnnotationTypePattern ELLIPSIS = new EllipsisAnnotationTypePattern(); /** * TODO: write, read, equals & hashcode both in annotation hierarachy and * in altered TypePattern hierarchy */ protected AnnotationTypePattern() { super(); } public abstract FuzzyBoolean matches(AnnotatedElement annotated); public FuzzyBoolean fastMatches(AnnotatedElement annotated) { return FuzzyBoolean.MAYBE; } public AnnotationTypePattern remapAdviceFormals(IntMap bindings) { return this; } public abstract void resolve(World world); /** * This can modify in place, or return a new TypePattern if the type changes. */ public AnnotationTypePattern resolveBindings(IScope scope, Bindings bindings, boolean allowBinding) { return this; } public static final byte EXACT = 1; public static final byte BINDING = 2; public static final byte NOT = 3; public static final byte OR = 4; public static final byte AND = 5; public static final byte ELLIPSIS_KEY = 6; public static final byte ANY_KEY = 7; public static final byte WILD = 8; public static AnnotationTypePattern read(DataInputStream s, ISourceContext context) throws IOException { byte key = s.readByte(); switch(key) { case EXACT: return ExactAnnotationTypePattern.read(s, context); case BINDING: return BindingAnnotationTypePattern.read(s, context); case NOT: return NotAnnotationTypePattern.read(s, context); case OR: return OrAnnotationTypePattern.read(s, context); case AND: return AndAnnotationTypePattern.read(s, context); case WILD: return WildAnnotationTypePattern.read(s,context); case ELLIPSIS_KEY: return ELLIPSIS; case ANY_KEY: return ANY; } throw new BCException("unknown TypePattern kind: " + key); } } class AnyAnnotationTypePattern extends AnnotationTypePattern { public FuzzyBoolean fastMatches(AnnotatedElement annotated) { return FuzzyBoolean.YES; } public FuzzyBoolean matches(AnnotatedElement annotated) { return FuzzyBoolean.YES; } public void write(DataOutputStream s) throws IOException { s.writeByte(AnnotationTypePattern.ANY_KEY); } public void resolve(World world) { } public String toString() { return "@ANY"; } } class EllipsisAnnotationTypePattern extends AnnotationTypePattern { public FuzzyBoolean matches(AnnotatedElement annotated) { return FuzzyBoolean.NO; } public void write(DataOutputStream s) throws IOException { s.writeByte(AnnotationTypePattern.ELLIPSIS_KEY); } public void resolve(World world) { } public String toString() { return ".."; } }
82,134
Bug 82134 AspectJ 5 M2 should implement backwards compatibility for binary aspect form
null
resolved fixed
797b6a6
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-01-07T14:14:45Z
2005-01-04T14:46:40Z
weaver/src/org/aspectj/weaver/patterns/ArgsAnnotationPointcut.java
/* ******************************************************************* * Copyright (c) 2004 IBM Corporation. * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Common Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/cpl-v10.html * * ******************************************************************/ 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 java.util.Set; import org.aspectj.bridge.IMessage; import org.aspectj.bridge.ISourceLocation; import org.aspectj.bridge.Message; 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.WeaverMessages; import org.aspectj.weaver.ast.Literal; import org.aspectj.weaver.ast.Test; /** * @author colyer * * TODO To change the template for this generated type comment go to * Window - Preferences - Java - Code Style - Code Templates */ public class ArgsAnnotationPointcut extends NameBindingPointcut { private AnnotationPatternList arguments; /** * */ public ArgsAnnotationPointcut(AnnotationPatternList arguments) { super(); this.arguments = arguments; } public Set couldMatchKinds() { return Shadow.ALL_SHADOW_KINDS; // empty args() matches jps with no args } /* (non-Javadoc) * @see org.aspectj.weaver.patterns.Pointcut#fastMatch(org.aspectj.weaver.patterns.FastMatchInfo) */ public FuzzyBoolean fastMatch(FastMatchInfo info) { return FuzzyBoolean.MAYBE; } /* (non-Javadoc) * @see org.aspectj.weaver.patterns.Pointcut#match(org.aspectj.weaver.Shadow) */ protected FuzzyBoolean matchInternal(Shadow shadow) { arguments.resolve(shadow.getIWorld()); FuzzyBoolean ret = arguments.matches(shadow.getIWorld().resolve(shadow.getArgTypes())); return ret; } /* (non-Javadoc) * @see org.aspectj.weaver.patterns.Pointcut#resolveBindings(org.aspectj.weaver.patterns.IScope, org.aspectj.weaver.patterns.Bindings) */ protected void resolveBindings(IScope scope, Bindings bindings) { arguments.resolveBindings(scope, bindings, true); if (arguments.ellipsisCount > 1) { scope.message(IMessage.ERROR, this, "uses more than one .. in args (compiler limitation)"); } } /* (non-Javadoc) * @see org.aspectj.weaver.patterns.Pointcut#resolveBindingsFromRTTI() */ protected void resolveBindingsFromRTTI() { // TODO Auto-generated method stub } /* (non-Javadoc) * @see org.aspectj.weaver.patterns.Pointcut#concretize1(org.aspectj.weaver.ResolvedTypeX, org.aspectj.weaver.IntMap) */ protected Pointcut concretize1(ResolvedTypeX inAspect, IntMap bindings) { if (isDeclare(bindings.getEnclosingAdvice())) { // Enforce rule about which designators are supported in declare inAspect.getWorld().showMessage(IMessage.ERROR, WeaverMessages.format(WeaverMessages.ARGS_IN_DECLARE), bindings.getEnclosingAdvice().getSourceLocation(), null); return Pointcut.makeMatchesNothing(Pointcut.CONCRETE); } AnnotationPatternList list = arguments.resolveReferences(bindings); Pointcut ret = new ArgsAnnotationPointcut(list); ret.copyLocationFrom(this); return ret; } /* (non-Javadoc) * @see org.aspectj.weaver.patterns.Pointcut#findResidue(org.aspectj.weaver.Shadow, org.aspectj.weaver.patterns.ExposedState) */ protected Test findResidueInternal(Shadow shadow, ExposedState state) { int len = shadow.getArgCount(); // do some quick length tests first int numArgsMatchedByEllipsis = (len + arguments.ellipsisCount) - arguments.size(); if (numArgsMatchedByEllipsis < 0) return Literal.FALSE; // should never happen if ((numArgsMatchedByEllipsis > 0) && (arguments.ellipsisCount == 0)) { return Literal.FALSE; // should never happen } // now work through the args and the patterns, skipping at ellipsis Test ret = Literal.TRUE; int argsIndex = 0; for (int i = 0; i < arguments.size(); i++) { if (arguments.get(i) == AnnotationTypePattern.ELLIPSIS) { // match ellipsisMatchCount args argsIndex += numArgsMatchedByEllipsis; } else if (arguments.get(i) == AnnotationTypePattern.ANY) { argsIndex++; } else { // match the argument type at argsIndex with the ExactAnnotationTypePattern // we know it is exact because nothing else is allowed in args ExactAnnotationTypePattern ap = (ExactAnnotationTypePattern)arguments.get(i); TypeX argType = shadow.getArgType(argsIndex); ResolvedTypeX rArgType = argType.resolve(shadow.getIWorld()); if (rArgType == ResolvedTypeX.MISSING) { IMessage msg = new Message( WeaverMessages.format(WeaverMessages.CANT_FIND_TYPE_ARG_TYPE,argType.getName()), "",IMessage.ERROR,shadow.getSourceLocation(),null,new ISourceLocation[]{getSourceLocation()}); } if (ap.matches(rArgType).alwaysTrue()) { argsIndex++; continue; } else { // we need a test... // TODO: binding ResolvedTypeX rAnnType = ap.annotationType.resolve(shadow.getIWorld()); ret = Test.makeAnd(ret,Test.makeHasAnnotation(shadow.getArgVar(argsIndex),rAnnType)); argsIndex++; } } } return ret; } /* (non-Javadoc) * @see org.aspectj.weaver.patterns.NameBindingPointcut#getBindingAnnotationTypePatterns() */ public List getBindingAnnotationTypePatterns() { List l = new ArrayList(); AnnotationTypePattern[] pats = arguments.getAnnotationPatterns(); for (int i = 0; i < pats.length; i++) { if (pats[i] instanceof BindingAnnotationTypePattern) { l.add(pats[i]); } } return l; } /* (non-Javadoc) * @see org.aspectj.weaver.patterns.NameBindingPointcut#getBindingTypePatterns() */ public List getBindingTypePatterns() { return Collections.EMPTY_LIST; } /* (non-Javadoc) * @see org.aspectj.weaver.patterns.PatternNode#write(java.io.DataOutputStream) */ public void write(DataOutputStream s) throws IOException { s.writeByte(Pointcut.ATARGS); arguments.write(s); writeLocation(s); } public static Pointcut read(DataInputStream s, ISourceContext context) throws IOException { AnnotationPatternList annotationPatternList = AnnotationPatternList.read(s,context); ArgsAnnotationPointcut ret = new ArgsAnnotationPointcut(annotationPatternList); ret.readLocation(context, s); return ret; } /* (non-Javadoc) * @see java.lang.Object#equals(java.lang.Object) */ public boolean equals(Object obj) { if (!(obj instanceof ArgsAnnotationPointcut)) return false; ArgsAnnotationPointcut other = (ArgsAnnotationPointcut) obj; return other.arguments.equals(arguments); } /* (non-Javadoc) * @see java.lang.Object#hashCode() */ public int hashCode() { return 17 + 37*arguments.hashCode(); } /* (non-Javadoc) * @see java.lang.Object#toString() */ public String toString() { StringBuffer buf = new StringBuffer("@args"); buf.append(arguments.toString()); return buf.toString(); } }
82,134
Bug 82134 AspectJ 5 M2 should implement backwards compatibility for binary aspect form
null
resolved fixed
797b6a6
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-01-07T14:14:45Z
2005-01-04T14:46:40Z
weaver/src/org/aspectj/weaver/patterns/ArgsPointcut.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the 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.Constructor; import java.lang.reflect.Field; import java.lang.reflect.Member; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.Set; 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.WeaverMessages; import org.aspectj.weaver.ast.Literal; import org.aspectj.weaver.ast.Test; import org.aspectj.weaver.internal.tools.PointcutExpressionImpl; /** * args(arguments) * * @author Erik Hilsdale * @author Jim Hugunin */ public class ArgsPointcut extends NameBindingPointcut { TypePatternList arguments; public ArgsPointcut(TypePatternList arguments) { this.arguments = arguments; this.pointcutKind = ARGS; } public Set couldMatchKinds() { return Shadow.ALL_SHADOW_KINDS; // empty args() matches jps with no args } public FuzzyBoolean fastMatch(FastMatchInfo type) { return FuzzyBoolean.MAYBE; } protected FuzzyBoolean matchInternal(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(); ret = checkSignatureMatch(pTypes); } return ret; } /** * @param ret * @param pTypes * @return */ private FuzzyBoolean checkSignatureMatch(Class[] pTypes) { 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) { return FuzzyBoolean.NO; } } } return FuzzyBoolean.YES; } /* (non-Javadoc) * @see org.aspectj.weaver.patterns.Pointcut#matchesDynamically(java.lang.Object, java.lang.Object, java.lang.Object[]) */ public boolean matchesDynamically(Object thisObject, Object targetObject, Object[] args) { return (arguments.matches(args,TypePattern.DYNAMIC) == FuzzyBoolean.YES); } /* (non-Javadoc) * @see org.aspectj.weaver.patterns.Pointcut#matchesStatically(java.lang.String, java.lang.reflect.Member, java.lang.Class, java.lang.Class, java.lang.reflect.Member) */ public FuzzyBoolean matchesStatically(String joinpointKind, Member member, Class thisClass, Class targetClass, Member withinCode) { Class[] paramTypes = new Class[0]; if (member instanceof Method) { paramTypes = ((Method)member).getParameterTypes(); } else if (member instanceof Constructor) { paramTypes = ((Constructor)member).getParameterTypes(); } else if (member instanceof PointcutExpressionImpl.Handler){ paramTypes = new Class[] {((PointcutExpressionImpl.Handler)member).getHandledExceptionType()}; } else if (member instanceof Field) { if (joinpointKind.equals(Shadow.FieldGet.getName())) return FuzzyBoolean.NO; // no args here paramTypes = new Class[] {((Field)member).getType()}; } else { return FuzzyBoolean.NO; } return arguments.matchesArgsPatternSubset(paramTypes); } 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; } /* (non-Javadoc) * @see org.aspectj.weaver.patterns.NameBindingPointcut#getBindingAnnotationTypePatterns() */ public List getBindingAnnotationTypePatterns() { return Collections.EMPTY_LIST; } /* (non-Javadoc) * @see org.aspectj.weaver.patterns.NameBindingPointcut#getBindingTypePatterns() */ public List getBindingTypePatterns() { List l = new ArrayList(); TypePattern[] pats = arguments.getTypePatterns(); for (int i = 0; i < pats.length; i++) { if (pats[i] instanceof BindingTypePattern) { l.add(pats[i]); } } return l; } public void write(DataOutputStream s) throws IOException { s.writeByte(Pointcut.ARGS); arguments.write(s); writeLocation(s); } public static Pointcut read(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, WeaverMessages.format(WeaverMessages.ARGS_IN_DECLARE), bindings.getEnclosingAdvice().getSourceLocation(), null); return Pointcut.makeMatchesNothing(Pointcut.CONCRETE); } TypePatternList args = arguments.resolveReferences(bindings); if (inAspect.crosscuttingMembers != null) { inAspect.crosscuttingMembers.exposeTypes(args.getExactTypes()); } Pointcut ret = new ArgsPointcut(args); ret.copyLocationFrom(this); return ret; } private Test findResidueNoEllipsis(Shadow shadow, ExposedState state, TypePattern[] patterns) { 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)) { ResolvedTypeX argRTX = shadow.getIWorld().resolve(argType,true); if (argRTX == ResolvedTypeX.MISSING) { IMessage msg = new Message( WeaverMessages.format(WeaverMessages.CANT_FIND_TYPE_ARG_TYPE,argType.getName()), "",IMessage.ERROR,shadow.getSourceLocation(),null,new ISourceLocation[]{getSourceLocation()}); } if (type.matchesInstanceof(argRTX).alwaysTrue()) { continue; } } else { BindingTypePattern btp = (BindingTypePattern)type; // Check if we have already bound something to this formal if ((state.get(btp.getFormalIndex())!=null) &&(lastMatchedShadowId != shadow.shadowId)) { // ISourceLocation isl = getSourceLocation(); // Message errorMessage = new Message( // "Ambiguous binding of type "+type.getExactType().toString()+ // " using args(..) at this line - formal is already bound"+ // ". See secondary source location for location of args(..)", // shadow.getSourceLocation(),true,new ISourceLocation[]{getSourceLocation()}); // shadow.getIWorld().getMessageHandler().handleMessage(errorMessage); state.setErroneousVar(btp.getFormalIndex()); } } ret = Test.makeAnd(ret, exposeStateForVar(shadow.getArgVar(i), type, state,shadow.getIWorld())); } return ret; } protected Test findResidueInternal(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() + ""; } }
82,134
Bug 82134 AspectJ 5 M2 should implement backwards compatibility for binary aspect form
null
resolved fixed
797b6a6
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-01-07T14:14:45Z
2005-01-04T14:46:40Z
weaver/src/org/aspectj/weaver/patterns/BindingAnnotationTypePattern.java
/* ******************************************************************* * Copyright (c) 2004 IBM Corporation. * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Common Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/cpl-v10.html * * ******************************************************************/ 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.bridge.MessageUtil; import org.aspectj.weaver.BCException; import org.aspectj.weaver.ISourceContext; import org.aspectj.weaver.IntMap; import org.aspectj.weaver.TypeX; import org.aspectj.weaver.WeaverMessages; import org.aspectj.weaver.World; public class BindingAnnotationTypePattern extends ExactAnnotationTypePattern implements BindingPattern { private int formalIndex; /** * @param annotationType */ public BindingAnnotationTypePattern(TypeX annotationType, int index) { super(annotationType); this.formalIndex = index; } public BindingAnnotationTypePattern(FormalBinding binding) { this(binding.getType(),binding.getIndex()); } public void resolveBinding(World world) { // For 1.5.0 M1 IMessage lim = MessageUtil.error("Binding not supported in @pcds (1.5.0 M1 limitation): " + getSourceLocation()); world.getMessageHandler().handleMessage(lim); // End of 1.5.0 M1 if (resolved) return; resolved = true; annotationType = annotationType.resolve(world); if (!annotationType.isAnnotation(world)) { IMessage m = MessageUtil.error( WeaverMessages.format(WeaverMessages.REFERENCE_TO_NON_ANNOTATION_TYPE,annotationType.getName()), getSourceLocation()); world.getMessageHandler().handleMessage(m); resolved = false; } if (!annotationType.hasAnnotation(TypeX.AT_RETENTION)) { // default is class visibility IMessage m = MessageUtil.error( WeaverMessages.format(WeaverMessages.BINDING_NON_RUNTIME_RETENTION_ANNOTATION,annotationType.getName()), getSourceLocation()); world.getMessageHandler().handleMessage(m); resolved = false; } else { // TO DO... get the retention policy annotation, and check the value is // RetentionPolicy.RUNTIME; } } public int getFormalIndex() { return formalIndex; } public boolean equals(Object obj) { if (!(obj instanceof BindingAnnotationTypePattern)) return false; BindingAnnotationTypePattern btp = (BindingAnnotationTypePattern) obj; return (super.equals(btp) && (btp.formalIndex == formalIndex)); } public int hashCode() { return super.hashCode()*37 + formalIndex; } public AnnotationTypePattern remapAdviceFormals(IntMap bindings) { if (!bindings.hasKey(formalIndex)) { return new ExactAnnotationTypePattern(annotationType); } else { int newFormalIndex = bindings.get(formalIndex); return new BindingAnnotationTypePattern(annotationType, newFormalIndex); } } private static final byte VERSION = 1; // rev if serialised form changed /* (non-Javadoc) * @see org.aspectj.weaver.patterns.ExactAnnotationTypePattern#write(java.io.DataOutputStream) */ public void write(DataOutputStream s) throws IOException { s.writeByte(AnnotationTypePattern.BINDING); s.writeByte(VERSION); annotationType.write(s); s.writeShort((short)formalIndex); writeLocation(s); } public static AnnotationTypePattern read(DataInputStream s, ISourceContext context) throws IOException { byte version = s.readByte(); if (version > VERSION) { throw new BCException("BindingAnnotationTypePattern was written by a more recent version of AspectJ"); } AnnotationTypePattern ret = new BindingAnnotationTypePattern(TypeX.read(s),s.readShort()); ret.readLocation(context,s); return ret; } }
82,134
Bug 82134 AspectJ 5 M2 should implement backwards compatibility for binary aspect form
null
resolved fixed
797b6a6
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-01-07T14:14:45Z
2005-01-04T14:46:40Z
weaver/src/org/aspectj/weaver/patterns/BindingTypePattern.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the 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.weaver.ISourceContext; import org.aspectj.weaver.IntMap; import org.aspectj.weaver.TypeX; public class BindingTypePattern extends ExactTypePattern implements BindingPattern { private int formalIndex; public BindingTypePattern(TypeX type, int index,boolean isVarArgs) { super(type, false,isVarArgs); this.formalIndex = index; } public BindingTypePattern(FormalBinding binding, boolean isVarArgs) { this(binding.getType(), binding.getIndex(),isVarArgs); } public int getFormalIndex() { return formalIndex; } public boolean equals(Object other) { if (!(other instanceof BindingTypePattern)) return false; BindingTypePattern o = (BindingTypePattern)other; if (includeSubtypes != o.includeSubtypes) return false; if (isVarArgs != o.isVarArgs) return false; return o.type.equals(this.type) && o.formalIndex == this.formalIndex; } public int hashCode() { int result = 17; result = 37*result + type.hashCode(); result = 37*result + formalIndex; return result; } public void write(DataOutputStream out) throws IOException { out.writeByte(TypePattern.BINDING); type.write(out); out.writeShort((short)formalIndex); out.writeBoolean(isVarArgs); writeLocation(out); } public static TypePattern read(DataInputStream s, ISourceContext context) throws IOException { TypePattern ret = new BindingTypePattern(TypeX.read(s), s.readShort(), s.readBoolean()); ret.readLocation(context, s); return ret; } public TypePattern remapAdviceFormals(IntMap bindings) { if (!bindings.hasKey(formalIndex)) { return new ExactTypePattern(type, false, isVarArgs); } else { int newFormalIndex = bindings.get(formalIndex); return new BindingTypePattern(type, newFormalIndex, isVarArgs); } } public String toString() { //Thread.currentThread().dumpStack(); return "BindingTypePattern(" + super.toString() + ", " + formalIndex + ")"; } }
82,134
Bug 82134 AspectJ 5 M2 should implement backwards compatibility for binary aspect form
null
resolved fixed
797b6a6
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-01-07T14:14:45Z
2005-01-04T14:46:40Z
weaver/src/org/aspectj/weaver/patterns/CflowPointcut.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the 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.Hashtable; import java.util.List; import java.util.Set; 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.WeaverMessages; import org.aspectj.weaver.World; import org.aspectj.weaver.ast.Test; public class CflowPointcut extends Pointcut { private Pointcut entry; // The pointcut inside the cflow() that represents the 'entry' point private boolean isBelow;// Is this cflowbelow? private int[] freeVars; private static Hashtable cflowFields = new Hashtable(); private static Hashtable cflowBelowFields = new Hashtable(); /** * Used to indicate that we're in the context of a cflow when concretizing if's * * Will be removed or replaced with something better when we handle this * as a non-error */ public static final ResolvedPointcutDefinition CFLOW_MARKER = new ResolvedPointcutDefinition(null, 0, null, TypeX.NONE, Pointcut.makeMatchesNothing(Pointcut.RESOLVED)); public CflowPointcut(Pointcut entry, boolean isBelow, int[] freeVars) { // System.err.println("Building cflow pointcut "+entry.toString()); this.entry = entry; this.isBelow = isBelow; this.freeVars = freeVars; this.pointcutKind = CFLOW; } public Set couldMatchKinds() { return Shadow.ALL_SHADOW_KINDS; } public FuzzyBoolean fastMatch(FastMatchInfo type) { return FuzzyBoolean.MAYBE; } protected FuzzyBoolean matchInternal(Shadow shadow) { //??? this is not maximally efficient return FuzzyBoolean.MAYBE; } /* (non-Javadoc) * @see org.aspectj.weaver.patterns.Pointcut#matchesDynamically(java.lang.Object, java.lang.Object, java.lang.Object[]) */ public boolean matchesDynamically(Object thisObject, Object targetObject, Object[] args) { throw new UnsupportedOperationException("cflow pointcut matching not supported by this operation"); } /* (non-Javadoc) * @see org.aspectj.weaver.patterns.Pointcut#matchesStatically(java.lang.String, java.lang.reflect.Member, java.lang.Class, java.lang.Class, java.lang.reflect.Member) */ public FuzzyBoolean matchesStatically( String joinpointKind, java.lang.reflect.Member member, Class thisClass, Class targetClass, java.lang.reflect.Member withinCode) { throw new UnsupportedOperationException("cflow pointcut matching not supported by this operation"); } 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 + ")"; } protected Test findResidueInternal(Shadow shadow, ExposedState state) { throw new RuntimeException("unimplemented"); } public Pointcut concretize1(ResolvedTypeX inAspect, IntMap bindings) { // Enforce rule about which designators are supported in declare if (isDeclare(bindings.getEnclosingAdvice())) { inAspect.getWorld().showMessage(IMessage.ERROR, WeaverMessages.format(WeaverMessages.CFLOW_IN_DECLARE,isBelow?"below":""), bindings.getEnclosingAdvice().getSourceLocation(), null); return Pointcut.makeMatchesNothing(Pointcut.CONCRETE); } //make this remap from formal positions to arrayIndices IntMap entryBindings = new IntMap(); 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); // This block concretizes the pointcut within the cflow pointcut try { concreteEntry = entry.concretize(inAspect, entryBindings); } finally { entryBindings.popEnclosingDefinitition(); } List innerCflowEntries = new ArrayList(xcut.getCflowEntries()); innerCflowEntries.removeAll(previousCflowEntries); Object field = getCflowfield(concreteEntry); // Four routes of interest through this code (did I hear someone say refactor??) // 1) no state in the cflow - we can use a counter *and* we have seen this pointcut // before - so use the same counter as before. // 2) no state in the cflow - we can use a counter, but this is the first time // we have seen this pointcut, so build the infrastructure. // 3) state in the cflow - we need to use a stack *and* we have seen this pointcut // before - so share the stack. // 4) state in the cflow - we need to use a stack, but this is the first time // we have seen this pointcut, so build the infrastructure. if (freeVars.length == 0) { // No state, so don't use a stack, use a counter. ResolvedMember localCflowField = null; // Check if we have already got a counter for this cflow pointcut if (field != null) { localCflowField = (ResolvedMember)field; // Use the one we already have } else { // Create a counter field in the aspect localCflowField = new ResolvedMember(Member.FIELD,concreteAspect,Modifier.STATIC | Modifier.PUBLIC | Modifier.FINAL, NameMangler.cflowCounter(xcut),TypeX.forName(NameMangler.CFLOW_COUNTER_TYPE).getSignature()); // Create type munger to add field to the aspect concreteAspect.crosscuttingMembers.addTypeMunger(world.makeCflowCounterFieldAdder(localCflowField)); // Create shadow munger to push stuff onto the stack concreteAspect.crosscuttingMembers.addConcreteShadowMunger( Advice.makeCflowEntry(world,concreteEntry,isBelow,localCflowField,freeVars.length,innerCflowEntries,inAspect)); putCflowfield(concreteEntry,localCflowField); // Remember it } Pointcut ret = new ConcreteCflowPointcut(localCflowField, null,true); ret.copyLocationFrom(this); return ret; } else { List slots = new ArrayList(); for (int i=0, len=freeVars.length; i < len; i++) { int freeVar = freeVars[i]; // we don't need to keep state that isn't actually exposed to advice //??? this means that we will store some state that we won't actually use, optimize this later if (!bindings.hasKey(freeVar)) continue; int formalIndex = bindings.get(freeVar); ResolvedTypeX formalType = bindings.getAdviceSignature().getParameterTypes()[formalIndex].resolve(world); ConcreteCflowPointcut.Slot slot = new ConcreteCflowPointcut.Slot(formalIndex, formalType, i); slots.add(slot); } ResolvedMember localCflowField = null; if (field != null) { localCflowField = (ResolvedMember)field; } else { localCflowField = 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, localCflowField, freeVars.length, innerCflowEntries,inAspect)); concreteAspect.crosscuttingMembers.addTypeMunger( world.makeCflowStackFieldAdder(localCflowField)); putCflowfield(concreteEntry,localCflowField); } Pointcut ret = new ConcreteCflowPointcut(localCflowField, slots,false); ret.copyLocationFrom(this); return ret; } } public static void clearCaches() { cflowFields.clear(); cflowBelowFields.clear(); } private Object getCflowfield(Pointcut pcutkey) { if (isBelow) { return cflowBelowFields.get(pcutkey); } else { return cflowFields.get(pcutkey); } } private void putCflowfield(Pointcut pcutkey,Object o) { if (isBelow) { cflowBelowFields.put(pcutkey,o); } else { cflowFields.put(pcutkey,o); } } }
82,134
Bug 82134 AspectJ 5 M2 should implement backwards compatibility for binary aspect form
null
resolved fixed
797b6a6
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-01-07T14:14:45Z
2005-01-04T14:46:40Z
weaver/src/org/aspectj/weaver/patterns/Declare.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the 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.IOException; import org.aspectj.weaver.ISourceContext; public abstract class Declare extends PatternNode { public static final byte ERROR_OR_WARNING = 1; public static final byte PARENTS = 2; public static final byte SOFT = 3; public static final byte DOMINATES = 4; public static Declare read(DataInputStream s, ISourceContext context) throws IOException { byte kind = s.readByte(); switch (kind) { case ERROR_OR_WARNING: return DeclareErrorOrWarning.read(s, context); case DOMINATES: return DeclarePrecedence.read(s, context); case PARENTS: return DeclareParents.read(s, context); case SOFT: return DeclareSoft.read(s, context); default: throw new RuntimeException("unimplemented"); } } /** * Returns this declare mutated */ public abstract void resolve(IScope scope); /** * Indicates if this declare should be treated like advice. If true, the * declare will have no effect in an abstract aspect. It will be inherited by * any concrete aspects and will have an effect for each concrete aspect it * is ultimately inherited by. */ public abstract boolean isAdviceLike(); }
82,134
Bug 82134 AspectJ 5 M2 should implement backwards compatibility for binary aspect form
null
resolved fixed
797b6a6
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-01-07T14:14:45Z
2005-01-04T14:46:40Z
weaver/src/org/aspectj/weaver/patterns/DeclareErrorOrWarning.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the 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.weaver.ISourceContext; public class DeclareErrorOrWarning extends Declare { private boolean isError; private Pointcut pointcut; private String message; public DeclareErrorOrWarning(boolean isError, Pointcut pointcut, String message) { this.isError = isError; this.pointcut = pointcut; this.message = message; } public String toString() { StringBuffer buf = new StringBuffer(); buf.append("declare "); if (isError) buf.append("error: "); else buf.append("warning: "); buf.append(pointcut); buf.append(": "); buf.append("\""); buf.append(message); buf.append("\";"); return buf.toString(); } public boolean equals(Object other) { if (!(other instanceof DeclareErrorOrWarning)) return false; DeclareErrorOrWarning o = (DeclareErrorOrWarning)other; return (o.isError == isError) && o.pointcut.equals(pointcut) && o.message.equals(message); } public int hashCode() { int result = isError ? 19 : 23; result = 37*result + pointcut.hashCode(); result = 37*result + message.hashCode(); return result; } public void write(DataOutputStream s) throws IOException { s.writeByte(Declare.ERROR_OR_WARNING); s.writeBoolean(isError); pointcut.write(s); s.writeUTF(message); writeLocation(s); } public static Declare read(DataInputStream s, ISourceContext context) throws IOException { Declare ret = new DeclareErrorOrWarning( s.readBoolean(), Pointcut.read(s, context), s.readUTF() ); ret.readLocation(context, s); return ret; } public boolean isError() { return isError; } public String getMessage() { return message; } public Pointcut getPointcut() { return pointcut; } public void resolve(IScope scope) { pointcut = pointcut.resolve(scope); } public boolean isAdviceLike() { return true; } }
82,134
Bug 82134 AspectJ 5 M2 should implement backwards compatibility for binary aspect form
null
resolved fixed
797b6a6
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-01-07T14:14:45Z
2005-01-04T14:46:40Z
weaver/src/org/aspectj/weaver/patterns/DeclareParents.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the 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.WeaverMessages; import org.aspectj.weaver.World; public class DeclareParents extends Declare { private TypePattern child; private TypePatternList parents; private boolean isWildChild = false; public DeclareParents(TypePattern child, List parents) { this(child, new TypePatternList(parents)); } private DeclareParents(TypePattern child, TypePatternList parents) { this.child = child; this.parents = parents; if (child instanceof WildTypePattern) isWildChild = true; } 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 boolean parentsIncludeInterface(World w) { for (int i = 0; i < parents.size(); i++) { if (parents.get(i).getExactType().isInterface(w)) return true; } return false; } public boolean parentsIncludeClass(World w) { for (int i = 0; i < parents.size(); i++) { if (parents.get(i).getExactType().isClass(w)) return true; } return false; } public void resolve(IScope scope) { child = child.resolveBindings(scope, Bindings.NONE, false, false); parents = parents.resolveBindings(scope, Bindings.NONE, false, true); // Could assert this ... // for (int i=0; i < parents.size(); i++) { // parents.get(i).assertExactType(scope.getMessageHandler()); // } } public TypePatternList getParents() { return parents; } public TypePattern getChild() { return child; } public boolean isAdviceLike() { return false; } private ResolvedTypeX maybeGetNewParent(ResolvedTypeX targetType, TypePattern typePattern, World world,boolean reportErrors) { if (typePattern == TypePattern.NO) return null; // already had an error here TypeX iType = typePattern.getExactType(); ResolvedTypeX parentType = iType.resolve(world); if (targetType.equals(world.getCoreType(TypeX.OBJECT))) { world.showMessage(IMessage.ERROR, WeaverMessages.format(WeaverMessages.DECP_OBJECT), this.getSourceLocation(), null); return null; } if (parentType.isAssignableFrom(targetType)) return null; // already a parent // Enum types that are targetted for decp through a wild type pattern get linted if (reportErrors && isWildChild && targetType.isEnum()) { world.getLint().enumAsTargetForDecpIgnored.signal(targetType.toString(),getSourceLocation()); } // Annotation types that are targetted for decp through a wild type pattern get linted if (reportErrors && isWildChild && targetType.isAnnotation()) { world.getLint().annotationAsTargetForDecpIgnored.signal(targetType.toString(),getSourceLocation()); } // 1. Can't use decp to make an enum/annotation type implement an interface if (targetType.isEnum() && parentType.isInterface()) { if (reportErrors && !isWildChild) { world.showMessage(IMessage.ERROR, WeaverMessages.format(WeaverMessages.CANT_DECP_ON_ENUM_TO_IMPL_INTERFACE,targetType),getSourceLocation(),null); } return null; } if (targetType.isAnnotation() && parentType.isInterface()) { if (reportErrors && !isWildChild) { world.showMessage(IMessage.ERROR,WeaverMessages.format(WeaverMessages.CANT_DECP_ON_ANNOTATION_TO_IMPL_INTERFACE,targetType),getSourceLocation(),null); } return null; } // 2. Can't use decp to change supertype of an enum/annotation if (targetType.isEnum() && parentType.isClass()) { if (reportErrors && !isWildChild) { world.showMessage(IMessage.ERROR,WeaverMessages.format(WeaverMessages.CANT_DECP_ON_ENUM_TO_EXTEND_CLASS,targetType),getSourceLocation(),null); } return null; } if (targetType.isAnnotation() && parentType.isClass()) { if (reportErrors && !isWildChild) { world.showMessage(IMessage.ERROR,WeaverMessages.format(WeaverMessages.CANT_DECP_ON_ANNOTATION_TO_EXTEND_CLASS,targetType),getSourceLocation(),null); } return null; } // 3. Can't use decp to declare java.lang.Enum/java.lang.annotation.Annotation as the parent of a type if (parentType.getSignature().equals(TypeX.ENUM.getSignature())) { if (reportErrors && !isWildChild) { world.showMessage(IMessage.ERROR, WeaverMessages.format(WeaverMessages.CANT_DECP_TO_MAKE_ENUM_SUPERTYPE,targetType),getSourceLocation(),null); } return null; } if (parentType.getSignature().equals(TypeX.ANNOTATION.getSignature())) { if (reportErrors && !isWildChild) { world.showMessage(IMessage.ERROR, WeaverMessages.format(WeaverMessages.CANT_DECP_TO_MAKE_ANNOTATION_SUPERTYPE,targetType),getSourceLocation(),null); } return null; } if (parentType.isAssignableFrom(targetType)) return null; // already a parent if (targetType.isAssignableFrom(parentType)) { world.showMessage(IMessage.ERROR, WeaverMessages.format(WeaverMessages.CANT_EXTEND_SELF,targetType.getName()), this.getSourceLocation(), null ); return null; } if (parentType.isClass()) { if (targetType.isInterface()) { world.showMessage(IMessage.ERROR, WeaverMessages.format(WeaverMessages.INTERFACE_CANT_EXTEND_CLASS), this.getSourceLocation(), null ); return null; // how to handle xcutting errors??? } if (!targetType.getSuperclass().isAssignableFrom(parentType)) { world.showMessage(IMessage.ERROR, WeaverMessages.format(WeaverMessages.DECP_HIERARCHY_ERROR, iType.getName(), targetType.getSuperclass().getName()), this.getSourceLocation(), null ); return null; } else { return parentType; } } else { return parentType; } } public List/*<ResolvedTypeX>*/ findMatchingNewParents(ResolvedTypeX onType,boolean reportErrors) { 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(),reportErrors); if (t != null) ret.add(t); } return ret; } }
82,134
Bug 82134 AspectJ 5 M2 should implement backwards compatibility for binary aspect form
null
resolved fixed
797b6a6
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-01-07T14:14:45Z
2005-01-04T14:46:40Z
weaver/src/org/aspectj/weaver/patterns/DeclarePrecedence.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the 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; import org.aspectj.weaver.WeaverMessages; public class DeclarePrecedence extends Declare { private TypePatternList patterns; public DeclarePrecedence(List patterns) { this(new TypePatternList(patterns)); } private DeclarePrecedence(TypePatternList patterns) { this.patterns = patterns; } public 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, WeaverMessages.format(WeaverMessages.TWO_STARS_IN_PRECEDENCE), 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, WeaverMessages.format(WeaverMessages.CLASSES_IN_PRECEDENCE,exactType.getName()), pi.getSourceLocation(),null); } for (int j=0; j < patterns.size(); j++) { if (j == i) continue; TypePattern pj = patterns.get(j); if (pj.isStar()) continue; if (pj.matchesStatically(exactType)) { scope.getWorld().showMessage(IMessage.ERROR, WeaverMessages.format(WeaverMessages.TWO_PATTERN_MATCHES_IN_PRECEDENCE,exactType.getName()), pi.getSourceLocation(), pj.getSourceLocation()); } } } } public TypePatternList getPatterns() { return patterns; } private int matchingIndex(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, WeaverMessages.format(WeaverMessages.MULTIPLE_MATCHES_IN_PRECEDENCE,a,patterns.get(knownMatch),p), patterns.get(knownMatch).getSourceLocation(), p.getSourceLocation()); return -1; } else { knownMatch = i; } } } if (knownMatch == -1) return starMatch; else return knownMatch; } public int compare(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; } }
82,134
Bug 82134 AspectJ 5 M2 should implement backwards compatibility for binary aspect form
null
resolved fixed
797b6a6
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-01-07T14:14:45Z
2005-01-04T14:46:40Z
weaver/src/org/aspectj/weaver/patterns/DeclareSoft.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the 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; import org.aspectj.weaver.WeaverMessages; public class DeclareSoft extends Declare { private TypePattern exception; private Pointcut pointcut; public DeclareSoft(TypePattern exception, Pointcut pointcut) { this.exception = exception; this.pointcut = pointcut; } public 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().getCoreType(TypeX.THROWABLE).isAssignableFrom(excType)) { scope.getWorld().showMessage(IMessage.ERROR, WeaverMessages.format(WeaverMessages.NOT_THROWABLE,excType.getName()), exception.getSourceLocation(), null); pointcut = Pointcut.makeMatchesNothing(Pointcut.RESOLVED); return; } } pointcut = pointcut.resolve(scope); } public boolean isAdviceLike() { return true; } }
82,134
Bug 82134 AspectJ 5 M2 should implement backwards compatibility for binary aspect form
null
resolved fixed
797b6a6
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-01-07T14:14:45Z
2005-01-04T14:46:40Z
weaver/src/org/aspectj/weaver/patterns/ExactAnnotationTypePattern.java
/* ******************************************************************* * Copyright (c) 2004 IBM Corporation. * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Common Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/cpl-v10.html * * ******************************************************************/ 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.bridge.MessageUtil; import org.aspectj.util.FuzzyBoolean; import org.aspectj.weaver.AnnotatedElement; import org.aspectj.weaver.BCException; import org.aspectj.weaver.ISourceContext; import org.aspectj.weaver.ResolvedTypeX; import org.aspectj.weaver.TypeX; import org.aspectj.weaver.WeaverMessages; import org.aspectj.weaver.World; /** * Matches an annotation of a given type */ public class ExactAnnotationTypePattern extends AnnotationTypePattern { protected TypeX annotationType; protected String formalName; protected boolean resolved = false; private boolean bindingPattern = false; /** * */ public ExactAnnotationTypePattern(TypeX annotationType) { this.annotationType = annotationType; this.resolved = (annotationType instanceof ResolvedTypeX); } public ExactAnnotationTypePattern(String formalName) { this.formalName = formalName; this.resolved = false; this.bindingPattern = true; // will be turned into BindingAnnotationTypePattern during resolution } public FuzzyBoolean fastMatches(AnnotatedElement annotated) { if (annotated.hasAnnotation(annotationType)) { return FuzzyBoolean.YES; } else { // could be inherited, but we don't know that until we are // resolved, and we're not yet... return FuzzyBoolean.MAYBE; } } public FuzzyBoolean matches(AnnotatedElement annotated) { boolean checkSupers = false; if (annotationType.hasAnnotation(TypeX.AT_INHERITED)) { if (annotated instanceof ResolvedTypeX) { checkSupers = true; } } if (annotated.hasAnnotation(annotationType)) { return FuzzyBoolean.YES; } else if (checkSupers) { ResolvedTypeX toMatchAgainst = ((ResolvedTypeX) annotated).getSuperclass(); while (toMatchAgainst != null) { if (toMatchAgainst.hasAnnotation(annotationType)) return FuzzyBoolean.YES; toMatchAgainst = toMatchAgainst.getSuperclass(); } } return FuzzyBoolean.NO; } public void resolve(World world) { if (!resolved) annotationType = annotationType.resolve(world); resolved = true; } /* (non-Javadoc) * @see org.aspectj.weaver.patterns.AnnotationTypePattern#resolveBindings(org.aspectj.weaver.patterns.IScope, org.aspectj.weaver.patterns.Bindings, boolean) */ public AnnotationTypePattern resolveBindings(IScope scope, Bindings bindings, boolean allowBinding) { if (resolved) return this; resolved = true; if (formalName != null) { FormalBinding formalBinding = scope.lookupFormal(formalName); if (formalBinding != null) { if (bindings == null) { scope.message(IMessage.ERROR, this, "negation doesn't allow binding"); return this; } if (!allowBinding) { scope.message(IMessage.ERROR, this, "name binding only allowed in @pcds, args, this, and target"); return this; } verifyIsAnnotationType(formalBinding.getType(),scope); BindingAnnotationTypePattern binding = new BindingAnnotationTypePattern(formalBinding); binding.copyLocationFrom(this); bindings.register(binding, scope); binding.resolveBinding(scope.getWorld()); return binding; } else { scope.message(IMessage.ERROR,this,"unbound formal " + formalName); return this; } } else { annotationType = annotationType.resolve(scope.getWorld()); verifyIsAnnotationType(annotationType,scope); return this; } } /** * @param scope */ private void verifyIsAnnotationType(TypeX type,IScope scope) { if (!type.isAnnotation(scope.getWorld())) { IMessage m = MessageUtil.error( WeaverMessages.format(WeaverMessages.REFERENCE_TO_NON_ANNOTATION_TYPE,type.getName()), getSourceLocation()); scope.getWorld().getMessageHandler().handleMessage(m); resolved = false; } } private static byte VERSION = 1; // rev if serialisation form changes /* (non-Javadoc) * @see org.aspectj.weaver.patterns.PatternNode#write(java.io.DataOutputStream) */ public void write(DataOutputStream s) throws IOException { s.writeByte(AnnotationTypePattern.EXACT); s.writeByte(VERSION); s.writeBoolean(bindingPattern); if (bindingPattern) { s.writeUTF(formalName); } else { annotationType.write(s); } writeLocation(s); } public static AnnotationTypePattern read(DataInputStream s,ISourceContext context) throws IOException { AnnotationTypePattern ret; byte version = s.readByte(); if (version > VERSION) { throw new BCException("ExactAnnotationTypePattern was written by a newer version of AspectJ"); } boolean isBindingPattern = s.readBoolean(); if (isBindingPattern) { ret = new ExactAnnotationTypePattern(s.readUTF()); } else { ret = new ExactAnnotationTypePattern(TypeX.read(s)); } ret.readLocation(context,s); return ret; } /* (non-Javadoc) * @see java.lang.Object#equals(java.lang.Object) */ public boolean equals(Object obj) { if (!(obj instanceof ExactAnnotationTypePattern)) return false; ExactAnnotationTypePattern other = (ExactAnnotationTypePattern) obj; return (other.annotationType.equals(annotationType)); } /* (non-Javadoc) * @see java.lang.Object#hashCode() */ public int hashCode() { return annotationType.hashCode(); } public String toString() { if (!resolved && formalName != null) return formalName; String ret = "@" + annotationType.toString(); if (formalName != null) ret = ret + " " + formalName; return ret; } }
82,134
Bug 82134 AspectJ 5 M2 should implement backwards compatibility for binary aspect form
null
resolved fixed
797b6a6
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-01-07T14:14:45Z
2005-01-04T14:46:40Z
weaver/src/org/aspectj/weaver/patterns/ExactTypePattern.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the 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.HashMap; import java.util.Map; import org.aspectj.util.FuzzyBoolean; import org.aspectj.weaver.BCException; import org.aspectj.weaver.ISourceContext; import org.aspectj.weaver.ResolvedTypeX; import org.aspectj.weaver.TypeX; public class ExactTypePattern extends TypePattern { protected TypeX type; public static final Map primitiveTypesMap; public static final Map boxedPrimitivesMap; private static final Map boxedTypesMap; static { primitiveTypesMap = new HashMap(); primitiveTypesMap.put("int",int.class); primitiveTypesMap.put("short",short.class); primitiveTypesMap.put("long",long.class); primitiveTypesMap.put("byte",byte.class); primitiveTypesMap.put("char",char.class); primitiveTypesMap.put("float",float.class); primitiveTypesMap.put("double",double.class); boxedPrimitivesMap = new HashMap(); boxedPrimitivesMap.put("java.lang.Integer",Integer.class); boxedPrimitivesMap.put("java.lang.Short",Short.class); boxedPrimitivesMap.put("java.lang.Long",Long.class); boxedPrimitivesMap.put("java.lang.Byte",Byte.class); boxedPrimitivesMap.put("java.lang.Character",Character.class); boxedPrimitivesMap.put("java.lang.Float",Float.class); boxedPrimitivesMap.put("java.lang.Double",Double.class); boxedTypesMap = new HashMap(); boxedTypesMap.put("int",Integer.class); boxedTypesMap.put("short",Short.class); boxedTypesMap.put("long",Long.class); boxedTypesMap.put("byte",Byte.class); boxedTypesMap.put("char",Character.class); boxedTypesMap.put("float",Float.class); boxedTypesMap.put("double",Double.class); } public ExactTypePattern(TypeX type, boolean includeSubtypes,boolean isVarArgs) { super(includeSubtypes,isVarArgs); this.type = type; } /* (non-Javadoc) * @see org.aspectj.weaver.patterns.TypePattern#couldEverMatchSameTypesAs(org.aspectj.weaver.patterns.TypePattern) */ protected boolean couldEverMatchSameTypesAs(TypePattern other) { if (super.couldEverMatchSameTypesAs(other)) return true; // false is necessary but not sufficient TypeX otherType = other.getExactType(); if (otherType != ResolvedTypeX.MISSING) { return type.equals(otherType); } if (other instanceof WildTypePattern) { WildTypePattern owtp = (WildTypePattern) other; String yourSimpleNamePrefix = owtp.namePatterns[0].maybeGetSimpleName(); if (yourSimpleNamePrefix != null) { return (type.getName().startsWith(yourSimpleNamePrefix)); } } return true; } protected boolean matchesExactly(ResolvedTypeX matchType) { boolean typeMatch = this.type.equals(matchType); boolean annMatch = this.annotationPattern.matches(matchType).alwaysTrue(); return (typeMatch && annMatch); } public TypeX getType() { return type; } public FuzzyBoolean matchesInstanceof(ResolvedTypeX matchType) { // in our world, Object is assignable from anything if (type.equals(ResolvedTypeX.OBJECT)) return FuzzyBoolean.YES.and(annotationPattern.matches(matchType)); if (type.isAssignableFrom(matchType, matchType.getWorld())) { return FuzzyBoolean.YES.and(annotationPattern.matches(matchType)); } // fix for PR 64262 - shouldn't try to coerce primitives if (type.isPrimitive()) { return FuzzyBoolean.NO; } else { return matchType.isCoerceableFrom(type) ? FuzzyBoolean.MAYBE : FuzzyBoolean.NO; } } public boolean matchesExactly(Class matchType) { try { Class toMatchAgainst = getClassFor(type.getName()); return matchType == toMatchAgainst; } catch (ClassNotFoundException cnfEx) { return false; } } public FuzzyBoolean matchesInstanceof(Class matchType) { if (matchType.equals(Object.class)) return FuzzyBoolean.YES; try { String typeName = type.getName(); Class toMatchAgainst = getClassFor(typeName); FuzzyBoolean ret = FuzzyBoolean.fromBoolean(toMatchAgainst.isAssignableFrom(matchType)); if (ret == FuzzyBoolean.NO) { if (boxedTypesMap.containsKey(typeName)) { // try again with 'boxed' alternative toMatchAgainst = (Class) boxedTypesMap.get(typeName); ret = FuzzyBoolean.fromBoolean(toMatchAgainst.isAssignableFrom(matchType)); } } return ret; } catch (ClassNotFoundException cnfEx) { return FuzzyBoolean.NO; } } /** * Return YES if any subtype of the static type would match, * MAYBE if some subtypes could match * NO if there could never be a match * @param staticType * @return */ public FuzzyBoolean willMatchDynamically(Class staticType) { if (matchesExactly(staticType)) return FuzzyBoolean.YES; if (matchesInstanceof(staticType) == FuzzyBoolean.YES) return FuzzyBoolean.YES; try { String typeName = type.getName(); Class toMatchAgainst = getClassFor(typeName); if (toMatchAgainst.isInterface()) return FuzzyBoolean.MAYBE; if (staticType.isAssignableFrom(toMatchAgainst)) return FuzzyBoolean.MAYBE; return FuzzyBoolean.NO; } catch (ClassNotFoundException cnfEx) { return FuzzyBoolean.NO; } } private Class getClassFor(String typeName) throws ClassNotFoundException { Class ret = null; ret = (Class) primitiveTypesMap.get(typeName); if (ret == null) ret = Class.forName(typeName); return ret; } public boolean equals(Object other) { if (!(other instanceof ExactTypePattern)) return false; ExactTypePattern o = (ExactTypePattern)other; if (includeSubtypes != o.includeSubtypes) return false; if (isVarArgs != o.isVarArgs) return false; return (o.type.equals(this.type) && o.annotationPattern.equals(this.annotationPattern)); } public int hashCode() { int result = 17; result = 37*result + type.hashCode(); result = 37*result + annotationPattern.hashCode(); return result; } private static final byte EXACT_VERSION = 1; // rev if changed public void write(DataOutputStream out) throws IOException { out.writeByte(TypePattern.EXACT); out.writeByte(EXACT_VERSION); type.write(out); out.writeBoolean(includeSubtypes); out.writeBoolean(isVarArgs); annotationPattern.write(out); writeLocation(out); } public static TypePattern read(DataInputStream s, ISourceContext context) throws IOException { byte version = s.readByte(); if (version > EXACT_VERSION) throw new BCException("ExactTypePattern was written by a more recent version of AspectJ"); TypePattern ret = new ExactTypePattern(TypeX.read(s), s.readBoolean(), s.readBoolean()); ret.setAnnotationTypePattern(AnnotationTypePattern.read(s,context)); ret.readLocation(context, s); return ret; } public String toString() { StringBuffer buff = new StringBuffer(); if (annotationPattern != AnnotationTypePattern.ANY) { buff.append('('); buff.append(annotationPattern.toString()); buff.append(' '); } buff.append(type.toString()); if (includeSubtypes) buff.append('+'); // Note, there will be a rogue [] in the pattern here in the case of varargs ... if (isVarArgs) buff.append("..."); if (annotationPattern != AnnotationTypePattern.ANY) { buff.append(')'); } return buff.toString(); } public TypePattern resolveBindings(IScope scope, Bindings bindings, boolean allowBinding, boolean requireExactType) { throw new BCException("trying to re-resolve"); } public TypePattern resolveBindingsFromRTTI(boolean allowBinding, boolean requireExactType) { throw new IllegalStateException("trying to re-resolve"); } }
82,134
Bug 82134 AspectJ 5 M2 should implement backwards compatibility for binary aspect form
null
resolved fixed
797b6a6
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-01-07T14:14:45Z
2005-01-04T14:46:40Z
weaver/src/org/aspectj/weaver/patterns/HandlerPointcut.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the 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.Member; import java.util.HashSet; import java.util.Set; 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.ast.Literal; import org.aspectj.weaver.ast.Test; import org.aspectj.weaver.internal.tools.PointcutExpressionImpl; /** * This is a kind of KindedPointcut. This belongs either in * a hierarchy with it or in a new place to share code * with other potential future statement-level pointcuts like * synchronized and throws */ public class HandlerPointcut extends Pointcut { TypePattern exceptionType; private static final Set MATCH_KINDS = new HashSet(); static { MATCH_KINDS.add(Shadow.ExceptionHandler); } public HandlerPointcut(TypePattern exceptionType) { this.exceptionType = exceptionType; this.pointcutKind = HANDLER; } public Set couldMatchKinds() { return MATCH_KINDS; } public FuzzyBoolean fastMatch(FastMatchInfo type) { //??? should be able to do better by finding all referenced types in type return FuzzyBoolean.MAYBE; } protected FuzzyBoolean matchInternal(Shadow shadow) { if (shadow.getKind() != Shadow.ExceptionHandler) return FuzzyBoolean.NO; exceptionType.resolve(shadow.getIWorld()); // we know we have exactly one parameter since we're checking an exception handler return exceptionType.matches( shadow.getSignature().getParameterTypes()[0].resolve(shadow.getIWorld()), TypePattern.STATIC); } public FuzzyBoolean match(JoinPoint jp, JoinPoint.StaticPart jpsp) { if (!jp.getKind().equals(JoinPoint.EXCEPTION_HANDLER)) return FuzzyBoolean.NO; if (jp.getArgs().length > 0) { Object caughtException = jp.getArgs()[0]; return exceptionType.matches(caughtException,TypePattern.STATIC); } else { return FuzzyBoolean.NO; } } /* (non-Javadoc) * @see org.aspectj.weaver.patterns.Pointcut#matchesDynamically(java.lang.Object, java.lang.Object, java.lang.Object[]) */ public boolean matchesDynamically(Object thisObject, Object targetObject, Object[] args) { if (args.length > 0) { return (exceptionType.matches(args[0],TypePattern.STATIC) == FuzzyBoolean.YES); } else return false; } /* (non-Javadoc) * @see org.aspectj.weaver.patterns.Pointcut#matchesStatically(java.lang.String, java.lang.reflect.Member, java.lang.Class, java.lang.Class, java.lang.reflect.Member) */ public FuzzyBoolean matchesStatically(String joinpointKind, Member member, Class thisClass, Class targetClass, Member withinCode) { if (!(member instanceof PointcutExpressionImpl.Handler)) { return FuzzyBoolean.NO; } else { Class exceptionClass = ((PointcutExpressionImpl.Handler)member).getHandledExceptionType(); return exceptionType.matches(exceptionClass,TypePattern.STATIC); } } public boolean equals(Object other) { if (!(other instanceof HandlerPointcut)) return false; HandlerPointcut o = (HandlerPointcut)other; return o.exceptionType.equals(this.exceptionType); } public int hashCode() { int result = 17; result = 37*result + exceptionType.hashCode(); return result; } public String toString() { StringBuffer buf = new StringBuffer(); buf.append("handler("); buf.append(exceptionType.toString()); buf.append(")"); return buf.toString(); } public void write(DataOutputStream s) throws IOException { s.writeByte(Pointcut.HANDLER); exceptionType.write(s); writeLocation(s); } public static Pointcut read(DataInputStream s, ISourceContext context) throws IOException { HandlerPointcut ret = new HandlerPointcut(TypePattern.read(s, context)); ret.readLocation(context, s); return ret; } // XXX note: there is no namebinding in any kinded pointcut. // still might want to do something for better error messages // We want to do something here to make sure we don't sidestep the parameter // list in capturing type identifiers. public void resolveBindings(IScope scope, Bindings bindings) { exceptionType = exceptionType.resolveBindings(scope, bindings, false, false); //XXX add error if exact binding and not an exception } public void resolveBindingsFromRTTI() { exceptionType = exceptionType.resolveBindingsFromRTTI(false,false); } protected Test findResidueInternal(Shadow shadow, ExposedState state) { return match(shadow).alwaysTrue() ? Literal.TRUE : Literal.FALSE; } public Pointcut concretize1(ResolvedTypeX inAspect, IntMap bindings) { Pointcut ret = new HandlerPointcut(exceptionType); ret.copyLocationFrom(this); return ret; } }